From 6e9f5dd407489291ed377edfec1ed1f22f8318ce Mon Sep 17 00:00:00 2001 From: "DAL\\Administrator" <3452720699@qq.com> Date: Tue, 15 Sep 2026 15:36:32 +0800 Subject: [PATCH 1/4] fix(sync): skip isolated metadata failures and prepare v1.0.3 --- CHANGELOG.md | 12 + README.md | 10 +- .../e2e/desktop-production-boundary.spec.mjs | 74 ++++ apps/desktop/e2e/desktop-sync-switch.spec.mjs | 4 +- apps/desktop/package.json | 2 +- apps/desktop/src/main/diagnostics-export.ts | 17 +- apps/desktop/src/main/index.ts | 3 +- .../desktop/src/main/operation-log-service.ts | 22 +- .../desktop/src/shared/operation-log-types.ts | 6 +- .../src/shared/operation-log-validation.ts | 7 +- apps/desktop/src/shared/runtime-protocol.ts | 6 +- .../desktop/tests/metadata-error-log.test.mjs | 30 ++ apps/desktop/tests/provider-skip-log.test.mjs | 44 ++ .../CodexProviderSync.App.csproj | 6 +- .../CodexProviderSync.Application.csproj | 6 +- .../CodexProviderSync.Automation.csproj | 6 +- .../CodexProviderSync.Core.csproj | 6 +- .../CodexProviderSync.GuiE2E.csproj | 6 +- .../CodexProviderSync.Mac.csproj | 6 +- docs/README_CLI_ZH.md | 8 + docs/README_DESKTOP_EN.md | 8 + docs/README_DESKTOP_ZH.md | 10 +- docs/README_EN.md | 8 + docs/README_JA.md | 6 + docs/README_KO.md | 6 + docs/README_WEB_UI_ZH.md | 8 + docs/WINDOWS_ELECTRON_RELEASE_ZH.md | 8 +- docs/WORKING_PRINCIPLE_ZH.md | 6 +- ...-history-and-provider-preparation-facts.md | 4 + ...0043-status-provider-relevant-revisions.md | 4 + docs/adr/0044-large-session-metadata.md | 25 ++ docs/adr/0045-isolated-provider-data-skips.md | 39 ++ .../architecture/NODE_CORE_ARCHITECTURE_ZH.md | 6 +- .../architecture/contracts/CLI_CONTRACT_ZH.md | 4 + .../contracts/CORE_EXTERNAL_BEHAVIOR_ZH.md | 4 + docs/architecture/contracts/ERROR_CODES_ZH.md | 4 + docs/migration/BEHAVIOR_FIXTURES_ZH.md | 8 + docs/release-notes/v1.0.3-zh.md | 49 +++ package-lock.json | 6 +- package.json | 4 +- .../operation-logs/OperationLogsPage.tsx | 6 +- .../operations/OperationResultDialog.tsx | 10 +- .../src/features/operations/PlanReview.tsx | 2 + .../src/features/operations/SkipDetails.tsx | 22 + .../src/features/overview/OverviewPage.tsx | 3 + packages/app-ui/src/i18n.ts | 10 + packages/app-ui/src/types.ts | 6 +- .../app-ui/tests/metadata-errors.vitest.tsx | 19 + .../app-ui/tests/partial-feedback.vitest.tsx | 13 + packages/app-ui/tests/skip-details.vitest.tsx | 18 + packages/contracts/dist/errors.d.ts | 2 +- packages/contracts/dist/errors.js | 6 +- packages/contracts/dist/index.d.ts | 1 + packages/contracts/dist/index.js | 1 + packages/contracts/dist/protocol.js | 6 + packages/contracts/dist/skip-summary.d.ts | 24 ++ packages/contracts/dist/skip-summary.js | 32 ++ packages/contracts/src/errors.ts | 6 +- packages/contracts/src/index.ts | 1 + packages/contracts/src/protocol.ts | 6 + packages/contracts/src/skip-summary.ts | 47 ++ .../core/src/application/operation-result.js | 1 + .../src/application/ordinary-write-runtime.js | 3 + packages/core/src/application/plan-context.js | 8 +- .../core/src/application/provider-sync.js | 178 ++++++-- packages/core/src/application/status.js | 1 + .../core/src/application/watch-runtime.js | 3 +- packages/core/src/index.js | 10 +- .../src/infrastructure/node-core-ports.js | 5 + src/backup.js | 26 +- src/cli-json.js | 13 +- src/cli.js | 10 + src/constants.js | 2 + src/core-error.js | 2 + src/operation-revision.js | 94 +++- src/provider-skips.js | 121 ++++++ src/session-files.js | 400 +++++++++++++----- src/sqlite-state.js | 66 ++- src/web-core-adapter.js | 1 + src/windows-provider-bytes.cs | 10 +- test/cli-json.test.js | 11 + test/large-session-metadata.test.js | 212 ++++++++++ test/plan-apply.test.js | 36 +- test/provider-header-validation.test.js | 227 ++++++++++ test/provider-preparation-facts.test.js | 22 +- test/provider-skip-associations.test.js | 42 ++ test/provider-skip-data.test.js | 190 +++++++++ test/provider-sync-lite.test.js | 2 +- test/status-coordination.test.js | 16 +- test/sync-service.test.js | 11 +- test/windows-provider-bytes.ps1 | 27 +- test/windows-rewrite-worker.test.js | 2 +- web/dist/assets/index-B_v6pRZ5.css | 2 - web/dist/assets/index-Bp6DrQQ2.js | 143 ------- web/dist/assets/index-CmcveSDP.css | 2 + web/dist/assets/index-D-VUimW_.js | 143 +++++++ web/dist/index.html | 4 +- 97 files changed, 2348 insertions(+), 437 deletions(-) create mode 100644 apps/desktop/tests/metadata-error-log.test.mjs create mode 100644 apps/desktop/tests/provider-skip-log.test.mjs create mode 100644 docs/adr/0044-large-session-metadata.md create mode 100644 docs/adr/0045-isolated-provider-data-skips.md create mode 100644 docs/release-notes/v1.0.3-zh.md create mode 100644 packages/app-ui/src/features/operations/SkipDetails.tsx create mode 100644 packages/app-ui/tests/metadata-errors.vitest.tsx create mode 100644 packages/app-ui/tests/skip-details.vitest.tsx create mode 100644 packages/contracts/dist/skip-summary.d.ts create mode 100644 packages/contracts/dist/skip-summary.js create mode 100644 packages/contracts/src/skip-summary.ts create mode 100644 src/provider-skips.js create mode 100644 test/large-session-metadata.test.js create mode 100644 test/provider-header-validation.test.js create mode 100644 test/provider-skip-associations.test.js create mode 100644 test/provider-skip-data.test.js delete mode 100644 web/dist/assets/index-B_v6pRZ5.css delete mode 100644 web/dist/assets/index-Bp6DrQQ2.js create mode 100644 web/dist/assets/index-CmcveSDP.css create mode 100644 web/dist/assets/index-D-VUimW_.js diff --git a/CHANGELOG.md b/CHANGELOG.md index c12670b..31eedc1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ 本文件记录面向用户和集成方的重要变化。完整的发布叙事、升级说明和下载入口见对应版本的中文发布说明;实现证据和测试门禁见技术发布说明。 +## [Unreleased] + +## [1.0.3] - 2026-09-15 + +- 修复非法 UTF-8 被静默替换、数组 payload 误报同步成功、深层 JSON 导致整次准备中止:现在逐文件跳过并保留关联索引,日志显示具体原因。 + +- Node Sync/Switch/Watch 逐条跳过问题会话并保留关联或不确定 SQLite 行,正常数据继续;预览冻结候选与排除集合,写后收窄恢复范围。 +- 部分完成显示成功、跳过及未确认数量,最多 200 条本机路径/原因明细;诊断导出单独脱敏。全部历史跳过时仍可切换配置。 + +- Node Core(Electron、CLI、Web)支持最高 128 MiB 的会话首行元数据;分块读取与原地资格检查可处理长指令,避免重复复制和正则栈溢出。 +- 首行超限或无效分别提示实际原因,不再误报“会话发生变化”并建议无效重试。保持正文不变和备份保护,Legacy .NET 不受此次修改影响。 + ## [1.0.2] - 2026-09-11 - 修复 Windows 安装版点击“检查更新”立即失败的问题:正确加载更新器的 CommonJS 导出。 diff --git a/README.md b/README.md index 920934f..41ea00a 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,9 @@
+非法 UTF-8、数组 payload 或超出首行处理能力的数据会跳过并显示具体原因,关联索引保留;请处理后重新预览。不会自动转码或增加固定嵌套层数限制。 + +问题会话会被跳过,其关联索引保留原样;正常会话继续同步/切换。有跳过会显示“部分完成”,在预览、结果和操作日志可查看原因及本机完整路径(最多 200 项)。处理问题后重新预览即可纳入;全部历史跳过时,切换仍会备份并更新配置。数据库/目录/备份等全局故障仍停止,已写入时保留备份。诊断导出移除路径和索引标识。 + # codex-provider-sync ### 切换 Provider 后,帮助 Codex 旧会话重新可用 @@ -41,7 +45,7 @@ [下载最新正式版:安装版 / 便携 ZIP、版本说明与校验](https://github.com/Dailin521/codex-provider-sync/releases/latest) -未签名。安装版支持下载后确认安装更新;便携版须手动完整解压。1.0.2 修复安装版检查更新立即失败的问题,受影响的 1.0.1 用户需手动安装 1.0.2 一次,详见[升级说明](docs/release-notes/v1.0.2-zh.md)。旧 .NET 版不能通过旧更新按钮迁移。 +未签名。安装版支持下载后确认安装更新;便携版须手动完整解压。1.0.3 支持大首行并跳过问题会话,让正常数据继续同步;1.0.1 用户需手动安装新版一次,详见[升级说明](docs/release-notes/v1.0.3-zh.md)。旧 .NET 版不能通过旧更新按钮迁移。 macOS/Linux Electron 包尚未发布;CLI / Web 的 npm 版本独立发布。 @@ -166,3 +170,7 @@ npm run desktop:build 感谢 [@tangquanwei](https://github.com/tangquanwei) 贡献本地 Web UI、聊天记录浏览和多语言文档基础,并通过 [PR #80](https://github.com/Dailin521/codex-provider-sync/pull/80) 带入 v0.5.0;感谢所有参与贡献和问题调查的朋友。 [贡献者](CONTRIBUTORS.md) · [GitHub Contributors](https://github.com/Dailin521/codex-provider-sync/graphs/contributors) · [LINUX DO 社区](https://linux.do/) · [MIT License](LICENSE) + +### 大首行会话 + +Node 版本(Electron、CLI、Web)支持最高 128 MiB 的会话首行元数据(UTF-8 字节,不含换行);超限或格式无效的数据会跳过并记录原因,正常部分继续同步。此限制不是整个聊天记录的大小限制。 diff --git a/apps/desktop/e2e/desktop-production-boundary.spec.mjs b/apps/desktop/e2e/desktop-production-boundary.spec.mjs index e6d7ff2..3af88fa 100644 --- a/apps/desktop/e2e/desktop-production-boundary.spec.mjs +++ b/apps/desktop/e2e/desktop-production-boundary.spec.mjs @@ -1,3 +1,4 @@ +import { DatabaseSync } from "node:sqlite"; import { createRequire } from "node:module"; import { spawn } from "node:child_process"; import fs from "node:fs/promises"; @@ -784,3 +785,76 @@ test("production or unpacked desktop completes real Sync and Restore through Uti if (closeError) throw closeError; } }); + + +for (const mixed of [false, true]) test(mixed ? "production desktop syncs healthy mixed data and restores" : "production desktop syncs and restores large session metadata", async () => { + test.setTimeout(PRODUCTION_SMOKE_TIMEOUT_MS); + const fixture = await createDesktopSyncSwitchFixture(); + const source = await fs.readFile(fixture.rolloutPath, "utf8"); + const newline = source.indexOf("\n"); + const metadata = JSON.parse(source.slice(0, newline)); + metadata.payload.instructions = "x".repeat(8 * 1024 * 1024); + await fs.writeFile(fixture.rolloutPath, JSON.stringify(metadata) + source.slice(newline)); + const badPath = path.join(path.dirname(fixture.rolloutPath), "rollout-bad.jsonl"); + const badHeaders = new Map(); + if (mixed) { + await fs.writeFile(badPath, "invalid metadata\n"); + badHeaders.set(path.join(path.dirname(badPath), "rollout-utf8.jsonl"), Buffer.concat([ + Buffer.from('{"type":"session_meta","payload":{"extra":"'), Buffer.from([255]), Buffer.from('"}}\n') + ])); + badHeaders.set(path.join(path.dirname(badPath), "rollout-array.jsonl"), Buffer.from('{"type":"session_meta","payload":[]}\n')); + badHeaders.set(path.join(path.dirname(badPath), "rollout-complex.jsonl"), Buffer.from( + // Newer Electron V8 can serialize deep JSON iteratively. Equal-byte + // Providers also exercise semantic comparison's independent capacity. + '{"type":"session_meta","payload":{"id":"bad-row","model_provider":"custom","extra":' + + '['.repeat(20000) + '0' + ']'.repeat(20000) + '}}\n')); + for (const [file, content] of badHeaders) await fs.writeFile(file, content); + const db = new DatabaseSync(fixture.stateDbPath); + try { db.prepare("INSERT INTO threads(id, model_provider) VALUES ('bad-row', 'legacy-provider')").run(); } finally { db.close(); } + } + await claimDailyUpdateCheck(fixture.userData); + const baseline = await fixture.snapshotTargets(); + let app; + try { + app = await launchProductionDesktop({ + args: [...(packagedExecutable ? [] : [path.join(desktopRoot, "out", "main", "index.js")]), `--user-data-dir=${fixture.userData}`, "--lang=en-US"], + env: { ...process.env, CODEX_HOME: fixture.codexHome, CPS_DESKTOP_E2E: "1", CPS_DESKTOP_WINDOW_DISPLAY: "hidden", ELECTRON_ENABLE_SECURITY_WARNINGS: "true" } + }); + const page = await app.firstWindow(); + await waitForProductionReady(page); + await page.getByRole("button", { name: "Sync now" }).click(); + const result = page.getByRole("dialog", { name: "Operation result" }); + await expect(result.getByRole("heading", { name: mixed ? "Partially completed" : "Completed", exact: true })).toBeVisible({ timeout: PRODUCTION_OPERATION_TIMEOUT_MS }); + if (mixed) { + await expect(result.getByText("Skipped data", { exact: true })).toBeVisible(); + await result.getByText("Show local details", { exact: true }).click(); + await expect(result.getByText(badPath, { exact: true })).toBeVisible(); + expect(await fs.readFile(badPath, "utf8")).toBe("invalid metadata\n"); + for (const [file, content] of badHeaders) { + await expect(result.getByText(file, { exact: true })).toBeVisible(); + expect(await fs.readFile(file)).toEqual(content); + } + await expect(result.getByText("First-line metadata is not valid UTF-8", { exact: false }).first()).toBeVisible(); + await expect(result.getByText("Metadata exceeds the processing capacity", { exact: false }).first()).toBeVisible(); + const db = new DatabaseSync(fixture.stateDbPath, { readOnly: true }); + try { expect(db.prepare("SELECT model_provider FROM threads WHERE id='bad-row'").get().model_provider).toBe("legacy-provider"); } finally { db.close(); } + } + await result.getByRole("button", { name: "Close", exact: true }).last().click(); + const synced = await fixture.inspect(); + expect(synced.rollout.model_provider).toBe("openai"); + expect(synced.sqlite.provider).toBe("openai"); + expect(synced.backupIds).toHaveLength(1); + await page.getByRole("button", { name: "Backups / Restore" }).click(); + await page.getByRole("button", { name: new RegExp(synced.backupIds[0]) }).click(); + await page.getByRole("button", { name: "Preview restore" }).click(); + const confirmation = page.getByRole("dialog", { name: "Confirm restore" }); + await expect(confirmation).toBeVisible(); + await confirmation.getByRole("button", { name: "Confirm restore" }).click(); + await expect(confirmation).toBeHidden({ timeout: PRODUCTION_OPERATION_TIMEOUT_MS }); + await expect(result.getByRole("heading", { name: "Completed", exact: true })).toBeVisible({ timeout: PRODUCTION_OPERATION_TIMEOUT_MS }); + expect((await fixture.snapshotTargets()).hash).toBe(baseline.hash); + for (const [file, content] of badHeaders) expect(await fs.readFile(file)).toEqual(content); + } finally { + try { await app?.close(); } finally { await fixture.close(); } + } +}); diff --git a/apps/desktop/e2e/desktop-sync-switch.spec.mjs b/apps/desktop/e2e/desktop-sync-switch.spec.mjs index 350423f..71e24fb 100644 --- a/apps/desktop/e2e/desktop-sync-switch.spec.mjs +++ b/apps/desktop/e2e/desktop-sync-switch.spec.mjs @@ -548,8 +548,8 @@ test("Electron reports a locked rollout as partial without rewriting the locked const state = await fixture.inspect(); expect(await fs.readFile(fixture.rolloutPath)).toEqual(rolloutBefore); expect(state.rollout.model_provider).toBe("legacy-provider"); - expect(state.sqlite.provider).toBe("openai"); - expect(state.backupIds).toHaveLength(1); + expect(state.sqlite.provider).toBe("legacy-provider"); + expect(state.backupIds).toHaveLength(0); } finally { try { await releaseChild(lockProcess); diff --git a/apps/desktop/package.json b/apps/desktop/package.json index c0dc0cc..90f1321 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@codex-provider-sync/desktop", - "version": "1.0.2", + "version": "1.0.3", "description": "Desktop app for synchronizing Codex Provider metadata and local session history.", "homepage": "https://github.com/Dailin521/codex-provider-sync#readme", "author": "Dailin521", diff --git a/apps/desktop/src/main/diagnostics-export.ts b/apps/desktop/src/main/diagnostics-export.ts index 207da40..6d99387 100644 --- a/apps/desktop/src/main/diagnostics-export.ts +++ b/apps/desktop/src/main/diagnostics-export.ts @@ -3,10 +3,12 @@ import fs from "node:fs/promises"; import path from "node:path"; import { - assertCoreMethodOutput, + assertCoreMethodOutput, redactSkipSummary, type DiagnosticsSnapshot } from "@codex-provider-sync/contracts"; +import { validateOperationLogEntry } from "../shared/operation-log-validation.js"; + import { DESKTOP_BUILD_ID, DESKTOP_CORE_VERSION @@ -220,7 +222,7 @@ export class DesktopDiagnosticsExporter { }), { name: "recent-redacted-logs/operations.jsonl", - data: Buffer.from(`${this.#recentLogs()}\n`, "utf8") + data: Buffer.from(`${redactOperationLogs(this.#recentLogs())}\n`, "utf8") }, { name: "recent-redacted-logs/README.txt", @@ -288,3 +290,14 @@ export class DesktopDiagnosticsExporter { } } } + +/** Export only validated local records, with session identities removed. */ +export function redactOperationLogs(jsonl: string): string { + return jsonl.split("\n").filter(Boolean).slice(0, 200).flatMap(line => { + try { + const entry = validateOperationLogEntry(JSON.parse(line)); + if (entry.skipSummary) entry.skipSummary = redactSkipSummary(entry.skipSummary); + return [JSON.stringify(entry)]; + } catch { return []; } + }).join("\n"); +} diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts index 4764e66..8adbd10 100644 --- a/apps/desktop/src/main/index.ts +++ b/apps/desktop/src/main/index.ts @@ -201,6 +201,7 @@ if (!app.requestSingleInstanceLock()) { status: activity.outcome === "partial" ? "partial" : activity.outcome === "failed" ? "failed" : "completed", outcome: activity.outcome, backupId: activity.backupId, + skipSummary: activity.skipSummary, fileUpdateTiming: activity.fileUpdateTiming, failedStage: activity.failedStage, failureCode: activity.failureCode, @@ -220,7 +221,7 @@ if (!app.requestSingleInstanceLock()) { const diagnosticsExporter = new DesktopDiagnosticsExporter({ appVersion: app.getVersion(), isPackaged: app.isPackaged, - recentLogs: () => operationLogs.recentJsonLines() + recentLogs: () => operationLogs.recentRedactedJsonLines() }); const updateReminders = new UpdateReminderStore(app.getPath("userData")); updates = new DesktopUpdateController({ diff --git a/apps/desktop/src/main/operation-log-service.ts b/apps/desktop/src/main/operation-log-service.ts index 525f3d8..cea3b47 100644 --- a/apps/desktop/src/main/operation-log-service.ts +++ b/apps/desktop/src/main/operation-log-service.ts @@ -7,7 +7,7 @@ import { CORE_ERROR_CODES, OPERATION_FAILURE_STAGES, SAFE_CAUSE_CODES, - publicFileUpdateTiming, + publicFileUpdateTiming, publicSkipSummary, redactSkipSummary, type CoreResponseEnvelope, type ProgressEvent } from "@codex-provider-sync/contracts"; @@ -34,10 +34,10 @@ const FAILURE_CODES = new Set([ "SQLITE_READONLY", "SQLITE_FULL" ]); -const PARTIAL_REASONS = new Set(["locked-session", "rollout-changed", "mutation-failed"]); +const PARTIAL_REASONS = new Set(["locked-session", "rollout-changed", "mutation-failed", "skipped-data"]); const ERROR_REASONS = new Set(["profile", "config", "storage", "rollout", "state-db", "backup", "provider-not-configured"]); const COUNT_FIELDS = new Set([ - "changedSessionFiles", "inPlaceSessionFiles", "rewrittenSessionFiles", "sqliteRowsUpdated", + "unconfirmedSessionFiles", "changedSessionFiles", "inPlaceSessionFiles", "rewrittenSessionFiles", "sqliteRowsUpdated", "sqliteProviderRowsUpdated", "sqliteModelRowsUpdated", "sqliteUserEventRowsUpdated", "sqliteCwdRowsUpdated", "skippedLockedRolloutFiles", "skippedChangedRolloutFiles", "updatedWorkspaceRoots", "savedWorkspaceRootCount", "resolvedOperationCount", "deletedCount", "remainingCount", "freedBytes" @@ -60,6 +60,7 @@ interface BeginInput { interface PreparedSummary { target?: { provider?: unknown; model?: unknown; modelMode?: unknown; previousProvider?: unknown; previousRootModel?: unknown }; impact?: { + skipSummary?: unknown; rolloutFilesToChange?: unknown; sqliteRowsToChange?: unknown; lockedRolloutFiles?: unknown; @@ -229,6 +230,8 @@ export class OperationLogService { const plannedCounts = previewCounts(summary); if (targetProvider) entry.targetProvider = targetProvider; if (plannedCounts) entry.previewCounts = plannedCounts; + const skipped = publicSkipSummary(summary?.impact?.skipSummary); + if (skipped) entry.skipSummary = skipped; const plannedSwitch = switchPlan(summary); if (plannedSwitch) entry.switchPlan = plannedSwitch; entry.status = "awaiting-confirmation"; @@ -328,6 +331,7 @@ export class OperationLogService { outcome, backupId: safeText(backup?.backupId, 180), counts: { ...resultCounts(result), ...resultCounts(details) }, + skipSummary: details.skipSummary, fileUpdateTiming: details.fileUpdateTiming, failedStage: typeof details.failedStage === "string" ? details.failedStage : undefined, failureCode: typeof details.failureCode === "string" ? details.failureCode : undefined, @@ -351,13 +355,15 @@ export class OperationLogService { }); } - async finish(id: string, fields: { status: OperationLogStatus; outcome?: string; errorCode?: string; errorReason?: string; backupId?: string; profileId?: string; counts?: Record; fileUpdateTiming?: unknown; warnings?: unknown[]; failedStage?: string; failureCode?: string; partialReason?: string; retryRecommended?: boolean }): Promise { + async finish(id: string, fields: { status: OperationLogStatus; outcome?: string; errorCode?: string; errorReason?: string; backupId?: string; profileId?: string; counts?: Record; skipSummary?: unknown; fileUpdateTiming?: unknown; warnings?: unknown[]; failedStage?: string; failureCode?: string; partialReason?: string; retryRecommended?: boolean }): Promise { const entry = this.#require(id); this.#pause(entry); for (const running of entry.stages.filter((stage) => stage.status === "running")) { this.#completeStage(entry, running.stage, running.stage === fields.failedStage || (fields.status !== "completed" && fields.status !== "partial") ? "failed" : "completed"); } entry.status = fields.status; + const skipped = publicSkipSummary(fields.skipSummary); + if (skipped) entry.skipSummary = skipped; const fileUpdateTiming = publicFileUpdateTiming(fields.fileUpdateTiming); if (fileUpdateTiming) entry.fileUpdateTiming = fileUpdateTiming; if (safeText(fields.profileId, 80)) entry.profileId = safeText(fields.profileId, 80); @@ -400,6 +406,14 @@ export class OperationLogService { return entry ? clone(entry) : null; } + recentRedactedJsonLines(limit = 200): string { + return this.recentJsonLines(limit).split("\n").filter(Boolean).map(line => { + const entry = JSON.parse(line); + if (entry.skipSummary) entry.skipSummary = redactSkipSummary(entry.skipSummary); + return JSON.stringify(entry); + }).join("\n"); + } + recentJsonLines(limit = 200): string { return [...this.#entries.values()].sort((left, right) => Date.parse(right.startedAt) - Date.parse(left.startedAt)).slice(0, limit).map((entry) => JSON.stringify(entry)).join("\n"); } diff --git a/apps/desktop/src/shared/operation-log-types.ts b/apps/desktop/src/shared/operation-log-types.ts index f8a457f..a86b439 100644 --- a/apps/desktop/src/shared/operation-log-types.ts +++ b/apps/desktop/src/shared/operation-log-types.ts @@ -1,4 +1,4 @@ -import type { FileUpdateTiming } from "@codex-provider-sync/contracts"; +import type { SkipSummary, FileUpdateTiming } from "@codex-provider-sync/contracts"; export type OperationLogStatus = | "running" @@ -37,7 +37,7 @@ export interface OperationLogEntry { errorReason?: "profile" | "config" | "storage" | "rollout" | "state-db" | "backup" | "provider-not-configured"; failedStage?: string; failureCode?: string; - partialReason?: "locked-session" | "rollout-changed" | "mutation-failed"; + partialReason?: "locked-session" | "rollout-changed" | "mutation-failed" | "skipped-data"; retryRecommended?: boolean; requestIds: string[]; planId?: string; @@ -60,7 +60,7 @@ export interface OperationLogEntry { modelMode: "provider-default" | "keep-root-model" | "explicit"; }; counts: Record; - fileUpdateTiming?: FileUpdateTiming; + skipSummary?: SkipSummary; fileUpdateTiming?: FileUpdateTiming; warnings: string[]; stages: OperationLogStage[]; } diff --git a/apps/desktop/src/shared/operation-log-validation.ts b/apps/desktop/src/shared/operation-log-validation.ts index 5c82eba..5b27847 100644 --- a/apps/desktop/src/shared/operation-log-validation.ts +++ b/apps/desktop/src/shared/operation-log-validation.ts @@ -1,5 +1,5 @@ import type { OperationLogEntry, OperationLogStage, OperationLogStatus } from "./operation-log-types.js"; -import { isFileUpdateTiming } from "@codex-provider-sync/contracts"; +import { isSkipSummary, isFileUpdateTiming } from "@codex-provider-sync/contracts"; export const operationLogStatuses = new Set(["running", "awaiting-confirmation", "completed", "partial", "failed", "cancelled", "dismissed", "interrupted"]); // A new DTO field must also be consciously admitted at the transport boundary. @@ -9,7 +9,7 @@ const entryFields = { status: true, outcome: true, errorCode: true, failedStage: true, failureCode: true, partialReason: true, retryRecommended: true, requestIds: true, planId: true, operationId: true, backupId: true, targetProvider: true, previewCounts: true, - errorReason: true, switchPlan: true, fileUpdateTiming: true, counts: true, warnings: true, stages: true + errorReason: true, switchPlan: true, skipSummary: true, fileUpdateTiming: true, counts: true, warnings: true, stages: true } satisfies Record; const stageFields = { stage: true, status: true, startedAt: true, completedAt: true, durationMs: true, progress: true, count: true } satisfies Record; const record = (value: unknown): value is Record => value !== null && typeof value === "object" && !Array.isArray(value); @@ -38,6 +38,7 @@ export function validateOperationLogEntry(value: unknown): OperationLogEntry { if ((value.targetProvider !== undefined && (typeof value.targetProvider !== "string" || !/^[A-Za-z0-9._-]{1,128}$/.test(value.targetProvider))) || (value.errorReason !== undefined && !["profile", "config", "storage", "rollout", "state-db", "backup", "provider-not-configured"].includes(String(value.errorReason)))) return fail(); const planned = value.previewCounts; + if (value.skipSummary !== undefined && !isSkipSummary(value.skipSummary)) return fail(); if (value.fileUpdateTiming !== undefined && !isFileUpdateTiming(value.fileUpdateTiming)) return fail(); if (planned !== undefined && (!record(planned) @@ -54,7 +55,7 @@ export function validateOperationLogEntry(value: unknown): OperationLogEntry { if ((value.completedAt !== undefined && !date(value.completedAt)) || (value.wallDurationMs !== undefined && !number(value.wallDurationMs)) || (value.retryRecommended !== undefined && typeof value.retryRecommended !== "boolean") - || (value.partialReason !== undefined && !["locked-session", "rollout-changed", "mutation-failed"].includes(String(value.partialReason)))) return fail(); + || (value.partialReason !== undefined && !["locked-session", "rollout-changed", "mutation-failed", "skipped-data"].includes(String(value.partialReason)))) return fail(); for (const stage of value.stages) { if (!record(stage) || Object.keys(stage).some((key) => !Object.hasOwn(stageFields, key)) || !text(stage.stage, 120) || !["running", "completed", "failed"].includes(String(stage.status)) || !date(stage.startedAt) diff --git a/apps/desktop/src/shared/runtime-protocol.ts b/apps/desktop/src/shared/runtime-protocol.ts index 4c4e274..5495ebc 100644 --- a/apps/desktop/src/shared/runtime-protocol.ts +++ b/apps/desktop/src/shared/runtime-protocol.ts @@ -3,6 +3,8 @@ import { assertCoreRequestProgressEnvelope, assertCoreRequestEnvelope, assertCoreResponseEnvelope, + isSkipSummary, + type SkipSummary, isFileUpdateTiming, type FileUpdateTiming, type CoreMethodName, @@ -87,6 +89,7 @@ export interface RuntimeWatchActivity { changedSessionFiles?: number; sqliteRowsUpdated?: number; skippedLockedRolloutFiles?: number; + skipSummary?: SkipSummary; fileUpdateTiming?: FileUpdateTiming; } @@ -281,7 +284,8 @@ export function assertRuntimeWatchActivityFrame(value: unknown): asserts value i || !isRecord(value.activity)) throw new TypeError("Invalid desktop Watch activity frame."); assertGeneration(value.generation); const activity = value.activity; - const allowed = ["schemaVersion", "event", "activityId", "watchId", "profileId", "profileRevision", "backupId", "failedStage", "failureCode", "partialReason", "retryRecommended", "startedAt", "finishedAt", "reason", "outcome", "errorCode", "changedSessionFiles", "sqliteRowsUpdated", "skippedLockedRolloutFiles", "fileUpdateTiming"]; + const allowed = ["schemaVersion", "event", "activityId", "watchId", "profileId", "profileRevision", "backupId", "failedStage", "failureCode", "partialReason", "retryRecommended", "startedAt", "finishedAt", "reason", "outcome", "errorCode", "changedSessionFiles", "sqliteRowsUpdated", "skippedLockedRolloutFiles", "fileUpdateTiming", "skipSummary"]; + if (activity.skipSummary !== undefined && (activity.event !== "finished" || !isSkipSummary(activity.skipSummary))) throw new Error("Invalid skip summary."); if (activity.fileUpdateTiming !== undefined && (activity.event !== "finished" || !isFileUpdateTiming(activity.fileUpdateTiming))) throw new Error("Invalid file update timing."); if (Object.keys(activity).some((key) => !allowed.includes(key)) || activity.schemaVersion !== 1 || (activity.event !== "started" && activity.event !== "finished") diff --git a/apps/desktop/tests/metadata-error-log.test.mjs b/apps/desktop/tests/metadata-error-log.test.mjs new file mode 100644 index 0000000..1821f53 --- /dev/null +++ b/apps/desktop/tests/metadata-error-log.test.mjs @@ -0,0 +1,30 @@ +import assert from "node:assert/strict"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { OperationLogService } from "../dist/main/operation-log-service.js"; +import { createPublicCoreErrorDto } from "../../../packages/contracts/dist/index.js"; + +test("metadata error classification and failure stage survive log restart and export", async t => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "metadata-error-log-")); + t.after(() => fs.rm(root, { recursive: true, force: true })); + const logs = new OperationLogService({ directory: root }); + await logs.initialize(); + const ids = []; + for (const code of ["ROLLOUT_METADATA_TOO_LARGE", "ROLLOUT_METADATA_INVALID"]) { + const id = await logs.begin({ operation: "sync" }); + ids.push([id, code]); + await logs.finishFromResponse(id, { protocolVersion: 1, requestId: "prepare", ok: false, + error: createPublicCoreErrorDto(code, { details: { failureStage: "prepare_rollouts", path: "PRIVATE_PATH", body: "PRIVATE_BODY" } }) + }); + } + const restarted = new OperationLogService({ directory: root }); + await restarted.initialize(); + for (const [id, code] of ids) { + assert.equal(restarted.get(id).errorCode, code); + assert.equal(restarted.get(id).failedStage, "prepare_rollouts"); + assert.equal(restarted.get(id).status, "failed"); + } + assert.doesNotMatch(restarted.recentJsonLines(), /PRIVATE_PATH|PRIVATE_BODY/); +}); diff --git a/apps/desktop/tests/provider-skip-log.test.mjs b/apps/desktop/tests/provider-skip-log.test.mjs new file mode 100644 index 0000000..1b49efe --- /dev/null +++ b/apps/desktop/tests/provider-skip-log.test.mjs @@ -0,0 +1,44 @@ +import assert from "node:assert/strict"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { OperationLogService } from "../dist/main/operation-log-service.js"; +import { redactOperationLogs } from "../dist/main/diagnostics-export.js"; +import { validateOperationLogEntry } from "../dist/shared/operation-log-validation.js"; +import { isSkipSummary, publicSkipSummary } from "../../../packages/contracts/dist/index.js"; + +test("local skip details survive restart; diagnostic export removes paths and row identities", async t => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "skip-logs-")); + t.after(() => fs.rm(root, { recursive: true, force: true })); + const logs = new OperationLogService({ directory: root }); + await logs.initialize(); + const skipSummary = { total: 205, rolloutFiles: 204, sqliteRows: 1, unconfirmed: 1, omitted: 5, retryRecommended: false, items: [ + { kind: "sqlite", id: "private-row-identity", reason: "association-unknown", stage: "plan", retryable: false }, + ...Array.from({ length: 199 }, (_, n) => ({ kind: "rollout", path: `D:\\private-user\\sessions\\file-${n}.jsonl`, reason: n === 0 ? "metadata-invalid-utf8" : n === 1 ? "metadata-too-complex" : "metadata-invalid", stage: "scan", retryable: false })) + ] }; + assert.ok(isSkipSummary(skipSummary)); + assert.equal(publicSkipSummary({ ...skipSummary, body: "must not leak" }), undefined); + assert.equal(publicSkipSummary({ ...skipSummary, items: [...skipSummary.items, skipSummary.items[0]] }), undefined); + assert.equal(publicSkipSummary({ ...skipSummary, items: [{ ...skipSummary.items[0], error: "raw" }] }), undefined); + const id = await logs.begin({ operation: "sync" }); + await logs.prepared(id, "plan", { impact: { skipSummary, rolloutFilesToChange: 1, sqliteRowsToChange: 1, lockedRolloutFiles: 0 } }); + assert.deepEqual(logs.get(id).skipSummary, skipSummary); + await logs.finish(id, { status: "partial", outcome: "partial", partialReason: "skipped-data", skipSummary, counts: { changedSessionFiles: 1 } }); + const restarted = new OperationLogService({ directory: root }); + await restarted.initialize(); + const entry = validateOperationLogEntry(restarted.get(id)); + assert.deepEqual(entry.skipSummary, skipSummary); + assert.equal(entry.partialReason, "skipped-data"); + assert.match(restarted.recentJsonLines(), /private-user/); + for (const exported of [restarted.recentRedactedJsonLines(), redactOperationLogs(restarted.recentJsonLines())]) { + assert.doesNotMatch(exported, /private-user|private-row-identity|file-0/); + const parsed = JSON.parse(exported); + assert.equal(parsed.skipSummary.total, 205); + assert.equal(parsed.skipSummary.omitted, 5); + assert.equal(parsed.skipSummary.items[0].reason, "association-unknown"); + assert.equal(parsed.skipSummary.items[1].reason, "metadata-invalid-utf8"); + assert.equal(parsed.skipSummary.items[2].reason, "metadata-too-complex"); + } + assert.equal(redactOperationLogs('{"body":"private"}\nnot-json'), ""); +}); diff --git a/desktop/CodexProviderSync.App/CodexProviderSync.App.csproj b/desktop/CodexProviderSync.App/CodexProviderSync.App.csproj index 40c99a9..bed227e 100644 --- a/desktop/CodexProviderSync.App/CodexProviderSync.App.csproj +++ b/desktop/CodexProviderSync.App/CodexProviderSync.App.csproj @@ -24,9 +24,9 @@ CodexProviderSync Codex Provider Sync Dailin521 - 1.0.2 - 1.0.2.0 - 1.0.2.0 + 1.0.3 + 1.0.3.0 + 1.0.3.0 diff --git a/desktop/CodexProviderSync.Application/CodexProviderSync.Application.csproj b/desktop/CodexProviderSync.Application/CodexProviderSync.Application.csproj index 080ba96..b1d1c7d 100644 --- a/desktop/CodexProviderSync.Application/CodexProviderSync.Application.csproj +++ b/desktop/CodexProviderSync.Application/CodexProviderSync.Application.csproj @@ -5,9 +5,9 @@ enable enable false - 1.0.2 - 1.0.2.0 - 1.0.2.0 + 1.0.3 + 1.0.3.0 + 1.0.3.0 diff --git a/desktop/CodexProviderSync.Automation/CodexProviderSync.Automation.csproj b/desktop/CodexProviderSync.Automation/CodexProviderSync.Automation.csproj index ce38c97..6331e52 100644 --- a/desktop/CodexProviderSync.Automation/CodexProviderSync.Automation.csproj +++ b/desktop/CodexProviderSync.Automation/CodexProviderSync.Automation.csproj @@ -7,9 +7,9 @@ enable CodexProviderSync.Automation CodexProviderSync.Automation - 1.0.2 - 1.0.2.0 - 1.0.2.0 + 1.0.3 + 1.0.3.0 + 1.0.3.0 diff --git a/desktop/CodexProviderSync.Core/CodexProviderSync.Core.csproj b/desktop/CodexProviderSync.Core/CodexProviderSync.Core.csproj index 02de990..57e5d15 100644 --- a/desktop/CodexProviderSync.Core/CodexProviderSync.Core.csproj +++ b/desktop/CodexProviderSync.Core/CodexProviderSync.Core.csproj @@ -4,9 +4,9 @@ net10.0 enable enable - 1.0.2 - 1.0.2.0 - 1.0.2.0 + 1.0.3 + 1.0.3.0 + 1.0.3.0 diff --git a/desktop/CodexProviderSync.GuiE2E/CodexProviderSync.GuiE2E.csproj b/desktop/CodexProviderSync.GuiE2E/CodexProviderSync.GuiE2E.csproj index 0f9c7a5..923ce17 100644 --- a/desktop/CodexProviderSync.GuiE2E/CodexProviderSync.GuiE2E.csproj +++ b/desktop/CodexProviderSync.GuiE2E/CodexProviderSync.GuiE2E.csproj @@ -7,9 +7,9 @@ enable true CodexProviderSync.GuiE2E - 1.0.2 - 1.0.2.0 - 1.0.2.0 + 1.0.3 + 1.0.3.0 + 1.0.3.0 diff --git a/desktop/CodexProviderSync.Mac/CodexProviderSync.Mac.csproj b/desktop/CodexProviderSync.Mac/CodexProviderSync.Mac.csproj index a6df15b..4c07772 100644 --- a/desktop/CodexProviderSync.Mac/CodexProviderSync.Mac.csproj +++ b/desktop/CodexProviderSync.Mac/CodexProviderSync.Mac.csproj @@ -17,9 +17,9 @@ CodexProviderSync Codex Provider Sync Dailin521 - 1.0.2 - 1.0.2.0 - 1.0.2.0 + 1.0.3 + 1.0.3.0 + 1.0.3.0 true diff --git a/docs/README_CLI_ZH.md b/docs/README_CLI_ZH.md index 87f16f4..883b0d4 100644 --- a/docs/README_CLI_ZH.md +++ b/docs/README_CLI_ZH.md @@ -1,5 +1,9 @@ # CLI 使用指南 +非法 UTF-8、数组 payload 或超出首行处理能力的数据会跳过并显示具体原因,关联索引保留;请处理后重新预览。不会自动转码或增加固定嵌套层数限制。 + +问题会话会被跳过,其关联索引保留原样;正常会话继续同步/切换。有跳过会显示“部分完成”,在预览、结果和操作日志可查看原因及本机完整路径(最多 200 项)。处理问题后重新预览即可纳入;全部历史跳过时,切换仍会备份并更新配置。数据库/目录/备份等全局故障仍停止,已写入时保留备份。诊断导出移除路径和索引标识。 + 适用于 V1 Node Core。CLI、Web 和 Electron 使用同一套同步业务;CLI 不启动 Electron,也不依赖桌面安装。npm 安装得到的是已发布版本,仓库 V1 的新增能力以本页和实际安装版本的 `codex-provider help` 为准。 ## 安装与检查 @@ -158,3 +162,7 @@ Status 发现已确认失效的锁时只作提示、不删除文件,后续正 普通写入不会自动全量回滚。当前 CLI 的 Sync/Switch/Repair/Restore 没有提供受控取消入口;请等待终态结果,不要用 Ctrl+C 或强制结束进程代替恢复流程。JSON 的 130 是已取消结果的映射,不保证终端中断会输出该对象。Watch 和 Web 单独处理 Ctrl+C/SIGTERM,按其清理流程停止。 [返回首页](../README.md) · [工作原理](WORKING_PRINCIPLE_ZH.md) · [精确 CLI 合同](architecture/contracts/CLI_CONTRACT_ZH.md) + +### 大首行会话 + +Node CLI 支持最高 128 MiB UTF-8 字节的会话首行元数据(不含换行)。超限或无效分别以 metadata-too-large / metadata-invalid 原因跳过,正常部分继续;JSON 部分完成退出 3。处理原因后重新预览同步。 diff --git a/docs/README_DESKTOP_EN.md b/docs/README_DESKTOP_EN.md index 9e99c74..949dd49 100644 --- a/docs/README_DESKTOP_EN.md +++ b/docs/README_DESKTOP_EN.md @@ -1,5 +1,9 @@ # Codex Provider Sync Desktop +Invalid UTF-8, array payloads, and metadata exceeding processing capacity are skipped with specific reasons; associated index rows stay unchanged. Resolve the data issue and preview again. No automatic transcoding or fixed nesting limit is introduced. + +Node Sync/Switch/Watch skip isolated invalid, oversized, unreadable or changed sessions and preserve their associated index rows. Healthy data continues; partial results show counts and up to 200 local details. A new preview can include repaired data. Switch can still back up and change configuration when all history is skipped. Global storage/database/backup failures stop the operation. Diagnostic exports remove local paths and row identifiers. + V1 Electron is the primary desktop interface for aligning Provider metadata in local Codex session files and the chat index, helping reuse sessions affected by Provider mismatches after switching. Sync does not guarantee cross-provider decryption or continuation. Build targets are Windows, macOS, and Linux; available downloads depend on actual Release assets. Local builds do not imply public release, signing, or an enabled update channel. ## First use @@ -162,3 +166,7 @@ npm run desktop:test:e2e ``` [Home](../README.md) · [CLI guide (Chinese)](README_CLI_ZH.md) · [Current Core architecture](architecture/NODE_CORE_ARCHITECTURE_ZH.md) + +### Large session metadata + +Electron supports first-line metadata up to 128 MiB, excluding line endings. Oversized or invalid headers are skipped with distinct reasons while healthy sessions continue; resolve the cause and prepare again to include them. diff --git a/docs/README_DESKTOP_ZH.md b/docs/README_DESKTOP_ZH.md index d5115a3..9d57fd6 100644 --- a/docs/README_DESKTOP_ZH.md +++ b/docs/README_DESKTOP_ZH.md @@ -1,5 +1,9 @@ # Codex Provider Sync 桌面版 +非法 UTF-8、数组 payload 或超出首行处理能力的数据会跳过并显示具体原因,关联索引保留;请处理后重新预览。不会自动转码或增加固定嵌套层数限制。 + +问题会话会被跳过,其关联索引保留原样;正常会话继续同步/切换。有跳过会显示“部分完成”,在预览、结果和操作日志可查看原因及本机完整路径(最多 200 项)。处理问题后重新预览即可纳入;全部历史跳过时,切换仍会备份并更新配置。数据库/目录/备份等全局故障仍停止,已写入时保留备份。诊断导出移除路径和索引标识。 + V1 Electron 是面向用户的主桌面界面,用于在切换 Provider 后对齐本地会话文件和聊天索引,帮助因 Provider 信息不一致而无法正常使用的旧会话重新可用。同步不保证跨 Provider 解密或继续。构建目标为 Windows、macOS 和 Linux;可下载平台以实际 Release 资产为准。本地构建不代表已经公开发布、签名或启用更新通道。 ## 第一次使用 @@ -155,7 +159,7 @@ Watch 需在“设置”主动开启;当前状态按存储配置显示。指 - 便携版/本地打包版打开官方下载页。退出后解压完整新版到新目录,不要只替换一个 EXE。 - 已启用正式更新通道的安装版可按需下载,再确认重启安装;写操作、自动同步或未完成恢复会阻止安装。 - 设置更新区和新版弹窗可选“不再提醒此版本”;重启后保留,下个新版仍提醒。仍可手动检查/更新,也可在设置中恢复该版本提醒。 -- 1.0.2 修复安装版检查更新立即失败的问题。受影响的 1.0.1 安装版无法自行检查到修复,请从官方下载页手动安装 1.0.2 一次,详见[升级说明](release-notes/v1.0.2-zh.md)。线上跨版本下载安装仍待独立验收。 +- 1.0.3 支持大首行及问题会话跳过。受影响的 1.0.1 安装版无法正常检查更新,请从官方下载页手动安装新版一次,详见[升级说明](release-notes/v1.0.3-zh.md)。线上跨版本下载安装仍待独立验收。 - **旧 Windows .NET 的单 EXE 自更新不能直接升级到 Electron。** 首次迁移需安装/解压完整新版;不把 NSIS 安装器冒充旧 EXE,不承诺已经完成线上跨版本升级验证。 - 更新程序不替换 Codex 数据。下载安装方式、签名与更新通道以实际发布说明为准。 @@ -178,3 +182,7 @@ npm run desktop:test:e2e ``` [返回首页](../README.md) · [CLI 指南](README_CLI_ZH.md) · [当前核心架构](architecture/NODE_CORE_ARCHITECTURE_ZH.md) + +### 大首行会话 + +Node Electron 桌面支持最高 128 MiB 的会话首行元数据;超限或格式无效的数据会跳过,记录原因并继续处理正常部分。请处理首行问题后再同步,反复关闭 Codex 并重试不能解决固定的格式问题。聊天正文总大小不受这个首行上限限制。 diff --git a/docs/README_EN.md b/docs/README_EN.md index c7be91e..e8a1d6b 100644 --- a/docs/README_EN.md +++ b/docs/README_EN.md @@ -1,5 +1,9 @@
+Invalid UTF-8, array payloads, and metadata exceeding processing capacity are skipped with specific reasons; associated index rows stay unchanged. Resolve the data issue and preview again. No automatic transcoding or fixed nesting limit is introduced. + +Node Sync/Switch/Watch skip isolated invalid, oversized, unreadable or changed sessions and preserve their associated index rows. Healthy data continues; partial results show counts and up to 200 local details. A new preview can include repaired data. Switch can still back up and change configuration when all history is skipped. Global storage/database/backup failures stop the operation. Diagnostic exports remove local paths and row identifiers. + # codex-provider-sync ### Help reuse existing Codex sessions after switching providers @@ -84,3 +88,7 @@ CLI, Web and Electron share Node Core; installing the CLI does not install Elect Thanks to [@tangquanwei](https://github.com/tangquanwei) for the Local Web UI, history browsing and multilingual documentation foundation, brought into v0.5.0 through [PR #80](https://github.com/Dailin521/codex-provider-sync/pull/80), and to everyone contributing code, documentation and issue investigation. [Contributors](../CONTRIBUTORS.md) · [GitHub Contributors](https://github.com/Dailin521/codex-provider-sync/graphs/contributors) · [LINUX DO community](https://linux.do/) · [MIT License](../LICENSE) + +### Large session metadata + +Node Electron, CLI and Web support first-line metadata up to 128 MiB of UTF-8 content, excluding line endings. Oversized or invalid headers are skipped with distinct reasons while healthy sessions continue; resolve the cause and prepare again to include them. This is not a limit on the entire conversation file. diff --git a/docs/README_JA.md b/docs/README_JA.md index 315ba03..cb562da 100644 --- a/docs/README_JA.md +++ b/docs/README_JA.md @@ -1,5 +1,7 @@
+Node の Sync/Switch/Watch は、形式不正・上限超過・読み取り不可・変更済みのセッションを個別にスキップし、関連する索引行を保持します。正常なデータの処理は続行し、部分完了の件数と最大 200 件のローカル詳細を表示します。修正したデータは新しいプレビューで取り込めます。履歴をすべてスキップしても、Switch はバックアップと設定変更を実行します。ストレージ・データベース・バックアップ全体の障害は処理を停止します。診断エクスポートからはローカルパスと行識別子を除去します。 + # codex-provider-sync ### Provider 切り替え後に Codex の既存セッションを再利用するためのツール @@ -190,3 +192,7 @@ dotnet test desktop/CodexProviderSync.Core.Tests/CodexProviderSync.Core.Tests.cs ## License MIT + +### 大きなセッションメタデータ + +Node 版の Electron・CLI・Web は、改行を除く UTF-8 で最大 128 MiB の先頭行メタデータに対応します。上限超過や形式不正のデータは理由を記録してスキップし、正常なセッションの同期を続行します。原因を解消した後、新しいプレビューで再同期してください。会話ファイル全体のサイズ制限ではありません。 diff --git a/docs/README_KO.md b/docs/README_KO.md index 8e74c70..99e7cc5 100644 --- a/docs/README_KO.md +++ b/docs/README_KO.md @@ -1,5 +1,7 @@
+Node Sync/Switch/Watch는 형식 오류, 크기 초과, 읽기 불가 또는 변경된 세션을 개별적으로 건너뛰고 관련 인덱스 행을 유지합니다. 정상 데이터 처리는 계속하며 부분 완료 건수와 최대 200개의 로컬 상세 정보를 표시합니다. 수정한 데이터는 새 미리보기에서 포함할 수 있습니다. 모든 기록을 건너뛰어도 Switch는 백업과 설정 변경을 수행합니다. 저장소·데이터베이스·백업 전체의 오류가 발생하면 중단합니다. 진단 내보내기에서는 로컬 경로와 행 식별자를 제거합니다. + # codex-provider-sync ### Provider 전환 후 기존 Codex 세션을 다시 사용할 수 있도록 돕습니다 @@ -190,3 +192,7 @@ dotnet test desktop/CodexProviderSync.Core.Tests/CodexProviderSync.Core.Tests.cs ## License MIT + +### 큰 세션 메타데이터 + +Node 기반 Electron, CLI, Web은 줄바꿈을 제외한 UTF-8 기준 최대 128 MiB의 첫 줄 메타데이터를 지원합니다. 크기 초과나 잘못된 형식의 데이터는 원인을 기록하고 건너뛰며, 정상 세션의 동기화는 계속합니다. 원인을 해결한 후 새 미리보기로 다시 동기화하세요. 대화 파일 전체의 크기 제한은 아닙니다. diff --git a/docs/README_WEB_UI_ZH.md b/docs/README_WEB_UI_ZH.md index c421c79..03fa322 100644 --- a/docs/README_WEB_UI_ZH.md +++ b/docs/README_WEB_UI_ZH.md @@ -1,5 +1,9 @@ # Web 版使用说明 +非法 UTF-8、数组 payload 或超出首行处理能力的数据会跳过并显示具体原因,关联索引保留;请处理后重新预览。不会自动转码或增加固定嵌套层数限制。 + +问题会话会被跳过,其关联索引保留原样;正常会话继续同步/切换。有跳过会显示“部分完成”,在预览、结果和操作日志可查看原因及本机完整路径(最多 200 项)。处理问题后重新预览即可纳入;全部历史跳过时,切换仍会备份并更新配置。数据库/目录/备份等全局故障仍停止,已写入时保留备份。诊断导出移除路径和索引标识。 + Web 版是 CLI 提供的本地浏览器界面,复用与桌面版相同的 Node 同步核心。它只在本机运行,不需要把 Codex 数据上传到远程服务;不提供桌面端的操作日志、原生目录选择器和应用更新。 本页说明 V1 界面。npm 安装得到的是已发布版本,未发布的 V1 功能需要对应本地构建;下载和版本状态以实际发布说明为准。 @@ -106,3 +110,7 @@ codex-provider web --no-open 普通 Sync/Switch/Repair 写入后失败不自动全量回滚;查看结果和备份后选择重试或手动恢复。状态待刷新不等于工具正在写入,不要通过删除锁文件解决。 [返回首页](../README.md) · [CLI 指南](README_CLI_ZH.md) · [工作原理](WORKING_PRINCIPLE_ZH.md) + +### 大首行会话 + +Local Web 与 Electron 共用 Node Core,支持最高 128 MiB 的会话首行元数据。超限或格式无效的数据会跳过并记录原因,正常部分继续同步。该上限不限制整个聊天记录的大小。 diff --git a/docs/WINDOWS_ELECTRON_RELEASE_ZH.md b/docs/WINDOWS_ELECTRON_RELEASE_ZH.md index 1306d7d..fb54d55 100644 --- a/docs/WINDOWS_ELECTRON_RELEASE_ZH.md +++ b/docs/WINDOWS_ELECTRON_RELEASE_ZH.md @@ -41,7 +41,7 @@ main push 始终完整执行全部原有任务和 C10,最终 SHA 的发布门 应用内更新的显式渠道为 `stable-updater`,仅 Windows x64 严格 `1.0.x`;仍默认 RC。此渠道增加 `latest.yml` 与安装器 `.exe.blockmap`,两者必须来自同次构建并通过 metadata/大小/SHA512、blockmap、包内 GitHub 配置和 SHA256 清单审核。下载和安装均需用户确认,便携版仍手动。固定依赖对有 publisherName 的包继续校验签名;无发布者的未签名包不能冒充已签名更新。 -不得移动已有 tag 或覆盖既有 Release;当前 1.0.2 使用新标签和新 Release,见第 6 节。历史 1.0.1 的单次覆盖例外已经结束。真实安装版跨版本下载/重启、数据保持、失败重试与安装门禁需独立记录,首批更新能力上线仍须在公告明确线上跨版本尚未验收,不以单元测试替代。 +不得移动已有 tag 或覆盖既有 Release;后续版本使用新标签和新 Release,当前版本见第 6 节。历史 1.0.1 的单次覆盖例外已经结束。真实安装版跨版本下载/重启、数据保持、失败重试与安装门禁需独立记录,首批更新能力上线仍须在公告明确线上跨版本尚未验收,不以单元测试替代。 - 核心回归、架构/Provider I/O 门禁、完整跨平台 CI、根包 Node 16 安装兼容通过。 - 生产依赖无 moderate/high/critical,完整依赖树无 high/critical;其他告警如实列明。 @@ -76,11 +76,11 @@ main push 始终完整执行全部原有任务和 C10,最终 SHA 的发布门 正式版公告先通过 `node scripts/read-release-metadata.js --tag v1.0.x`,然后按该版本的明确授权执行 `gh release edit v1.0.x --draft=false --prerelease=false --latest=true --notes-file docs/release-notes/v1.0.x-zh.md`。公开后再次检查 `/releases/latest`、tag SHA、对应渠道的全部下载资产与哈希。RC 只公开 prerelease,不使用正式版命令,也不设 latest。 -## 6. 当前 1.0.2 发布与历史例外 +## 6. 当前 1.0.3 发布与历史例外 -维护者已明确选择发布 **1.0.2**,修复更新器模块加载失败。本次遵循第 1~5 节:最终 main SHA 的 CI 通过后创建新的 `v1.0.2` 标签,以 `stable-updater` 准备并验收 10 项附件,再创建/公开对应的新 Release。不得移动 `v1.0.1` 标签、覆盖其附件或撤下原 Release。 +维护者已于 2026-09-15 授权提交、合并并发布新的 Windows 包。本次版本为 **1.0.3**,交付 128 MiB 首行、问题会话逐文件跳过和首行校验修复。遵循第 1~5 节:最终 main SHA 的 CI 通过后创建新的 `v1.0.3` 标签,以 `stable-updater` 准备并验收 10 项附件,再公开对应的新 Release。不得移动旧标签或覆盖既有 Release。 -受影响的 1.0.1 安装版无法正常检查更新,公告必须要求手动安装 1.0.2 一次,并如实列明未签名、线上跨版本下载安装尚未验收;不发布 npm、Legacy 或其他平台包。 +继续保留安装版显式下载/重启确认和便携版手动更新。公告列明未签名、线上跨版本下载安装尚未独立验收;不发布 npm、Legacy 或其他平台包。此前 1.0.2 修复更新器加载,1.0.1 用户仍需手动安装新版。 历史记录:2026-09-11 曾按单次明确授权重新发布 1.0.1,原标签 SHA 为 `30c276a585344fa3f4f8fee4066565c97981d038`,原 Release ID 为 `386924117`;原文件与哈希先备份再替换。该例外已经结束,仅保留审计来源,不再是当前操作指令,也不授权任何后续覆盖。 diff --git a/docs/WORKING_PRINCIPLE_ZH.md b/docs/WORKING_PRINCIPLE_ZH.md index 7e12c82..e8fd9dd 100644 --- a/docs/WORKING_PRINCIPLE_ZH.md +++ b/docs/WORKING_PRINCIPLE_ZH.md @@ -1,5 +1,9 @@ # codex-provider-sync 工作原理与落盘机制 +非法 UTF-8、数组 payload 或超出首行处理能力的数据会跳过并显示具体原因,关联索引保留;请处理后重新预览。不会自动转码或增加固定嵌套层数限制。 + +问题会话会被跳过,其关联索引保留原样;正常会话继续同步/切换。有跳过会显示“部分完成”,在预览、结果和操作日志可查看原因及本机完整路径(最多 200 项)。处理问题后重新预览即可纳入;全部历史跳过时,切换仍会备份并更新配置。数据库/目录/备份等全局故障仍停止,已写入时保留备份。诊断导出移除路径和索引标识。 + > 适用于当前 V1 Node Core(CLI / Web / Electron)。Legacy .NET 的历史行为不作为新实现规范。 > 用户安装见 [README](../README.md);开发约束、模块映射及测试入口以 [Node Core 当前架构](architecture/NODE_CORE_ARCHITECTURE_ZH.md) 为准,本文只解释原理。 @@ -76,7 +80,7 @@ Switch 的 config → 可写 rollout → Repair 的 global state → SQLite 提 正文必须逐字节相同;首行可能重新序列化,文件身份允许变化,结果计入 `rewrittenSessionFiles`。用户无需把所有 Provider ID 改成固定长度。 -**计划为原地写后发生失败/锁定/漂移,不得静默降级成整文件重写来绕过校验。** 无效或超过 1 MiB 的 Sync 首行也不会通过扫描正文查找下一条 metadata 来兜底。 +**计划为原地写后发生失败/锁定/漂移,不得静默降级成整文件重写来绕过校验。** 无效或超过 128 MiB UTF-8 内容字节(不含 LF/CRLF)的 Sync 首行也不会通过扫描正文查找下一条 metadata 来兜底。 ### “只读首行”的准确含义 diff --git a/docs/adr/0037-switch-history-and-provider-preparation-facts.md b/docs/adr/0037-switch-history-and-provider-preparation-facts.md index 4e9fe01..ab682d9 100644 --- a/docs/adr/0037-switch-history-and-provider-preparation-facts.md +++ b/docs/adr/0037-switch-history-and-provider-preparation-facts.md @@ -1,5 +1,9 @@ # ADR-0037:切换历史、单轮预览首行事实与时间戳保留 +> 后续修订:[ADR-0045](0045-isolated-provider-data-skips.md) 取代 Provider 单条问题全局拒绝及集合漂移整体失效规则,保留其余边界。 + +> 后续修订:首行上限及错误分类以 [ADR-0044](0044-large-session-metadata.md) 为准;下文 1 MiB 记录原决策。 + - 状态:Accepted - 日期:2026-09-08 - 范围:V1 Provider Prepare、Desktop 日志/最近使用;不改普通写算法、Restore 或 Legacy diff --git a/docs/adr/0043-status-provider-relevant-revisions.md b/docs/adr/0043-status-provider-relevant-revisions.md index 9d29363..3e4b527 100644 --- a/docs/adr/0043-status-provider-relevant-revisions.md +++ b/docs/adr/0043-status-provider-relevant-revisions.md @@ -1,5 +1,9 @@ # ADR-0043:状态读取只校验相关数据变化 +> 后续修订:[ADR-0045](0045-isolated-provider-data-skips.md) 取代 Provider 单条问题全局拒绝及集合漂移整体失效规则,保留其余边界。 + +> 后续修订:首行上限及错误分类以 [ADR-0044](0044-large-session-metadata.md) 为准;下文 1 MiB 记录原决策。 + - Status: Accepted - Date: 2026-09-11 - Scope: 普通轻量 Status;独立于 ADR-0042 更新功能。Core 写入算法不变。 diff --git a/docs/adr/0044-large-session-metadata.md b/docs/adr/0044-large-session-metadata.md new file mode 100644 index 0000000..e0f2f0f --- /dev/null +++ b/docs/adr/0044-large-session-metadata.md @@ -0,0 +1,25 @@ +# ADR-0044:大首行兼容与元数据错误分类 + +> 后续修订:[ADR-0045](0045-isolated-provider-data-skips.md) 取代 Provider 单条问题全局拒绝及集合漂移整体失效规则,保留其余边界。 + +- 状态:Accepted +- 日期:2026-09-15 + +## 背景 + +Issue #102 报告关闭 Codex 后仍在准备阶段立即提示会话变化。隔离复现证明首行超限和格式无效都会被错误归类为 ROLLOUT_CHANGED;尚未确认该用户现场原因。用户选择以 128 MiB 为候选支持上限,并要求验证实际读写,而非仅修改提示。 + +## 决策 + +1. Node Status、Provider Prepare/revision/Sync/Switch 支持至多 134217728 字节的首行 UTF-8 内容,不含 LF/CRLF。无末尾换行时全部内容即首行。保持 64 KiB 分块及最多一个块的尾部预读;边界只需两字节判定 CRLF,不扫描正文寻找替代 metadata。Repair 保留独立 1 MiB 上限,Diagnostics/History 保持原有边界。Legacy .NET 不在此次范围。 +2. JS 与 Windows 首行读取只扫描新块,避免每块复制/扫描已收集前缀;Windows 写前校验受原首行长度约束,漂移继续跳过。原地资格使用线性 JSON 字符串 token 遍历,保留转义/重复键、字节等长、语义及身份校验。原地 worker 不传无用的新首行。变长替换后的首行也必须在上限内,否则 Prepare 在任何业务写入前拒绝;等长原地路径按实际保留的原首行长度校验。保持 PIO-2~PIO-6、锁、备份、时间戳和正文 byte preservation。 +3. 新增 ROLLOUT_METADATA_TOO_LARGE(超出支持上限)、ROLLOUT_METADATA_INVALID(不能解析为既有定义的 session_meta),severity=error、retryable=false、recoveryRequired=false。不可自动重试不表示用户处理原因后不能再次执行。真实漂移继续使用原错误/partial 规则;Prepare 拒绝仍为零业务写入、无备份。 +4. Contracts、CLI JSON、Web、Electron 与操作日志使用相同安全错误。Web 返回 422;CLI JSON 保持 schemaVersion=1 和一般失败退出码。不新增公开参数、路径字段或原始异常文本。保留固定 failureStage,中英文说明实际原因。Status 超限仍报告不完整,不能伪造健康或忙碌。 +5. 128 MiB 是单文件读取上限,不是整个操作的内存预算;计划仍可包含多个待改文件。不得宣称任意规模 Home 都有固定内存开销。测试记录近上限的耗时与进程峰值;本 ADR 不构成正式安装包、其他平台或用户现场验收。 + +## 验证 + +- test/large-session-metadata.test.js:默认 8 MiB 有效首行,Status、原地 Sync、变长 Switch、各自 Restore、SQLite 字段及正文 hash;虚拟 128 MiB LF/CRLF/EOF 边界与超一字节,读取/合并字节计数;真实无效/超限 PrepareSync/PrepareSwitch 零写入、HTTP 422 和安全 DTO。 +- CPS_LARGE_HEADER_MIB=128 配合 --test-name-pattern="large valid metadata" 运行真实近上限流程并输出父进程 peak RSS;只使用临时合成 Home。 +- provider-preparation-facts、status-coordination、in-place-transaction、windows-rewrite-worker 等原门禁继续保持;修改的预期以本 ADR 的新分类及上限为依据。 +- 生产 Electron 大首行 Sync→Restore 检查、architecture:check、npm test;CI 跨平台及实际安装验收仍独立。 diff --git a/docs/adr/0045-isolated-provider-data-skips.md b/docs/adr/0045-isolated-provider-data-skips.md new file mode 100644 index 0000000..3efb1c8 --- /dev/null +++ b/docs/adr/0045-isolated-provider-data-skips.md @@ -0,0 +1,39 @@ +# ADR-0045:隔离问题会话,继续正常 Provider 同步 + +- 状态:Accepted +- 日期:2026-09-15 +- 范围:共享 Node Core 的 Sync、Switch、Watch 及 Electron、Web、CLI;不回移 Legacy .NET。 + +## 决策 + +单个会话的无效首行、128 MiB 输入/输出超限、不可读/占用、消失或变化,作为逐文件跳过事实。写入失败只有在底层明确证明源文件未受损时才可继续。配置/Profile/存储位置、目录完整枚举、路径边界、数据库身份/schema/损坏/忙碌、备份失败、磁盘写满和未知写入结果仍停止;已发生写入则返回部分完成并保留备份。 + +Provider 计划保存内部文件身份、首行校验、SQLite 行原 Provider 和排除集合。预览排除项在本次执行始终排除,修好后需新预览;正常候选逐个复核,新增文件和行留待下一次。Repair/Restore 的严格计划校验不变。Status 保留不完整标记,允许预览健康部分,不能将未知数据计为对齐。读取中发生单条变化时仍只允许一次受限重读;新一轮完整且稳定的事实可以成为有效快照,持续漂移仍不完整。 + +SQLite 通过有效 metadata 的 ID 或经规范化和边界验证的 `rollout_path` 建立关联。不猜文件名,不扫描正文找 ID。跳过文件的关联行不更新;冲突及未知归属保留。有无法关联的坏文件时,仅更新正向确认健康的索引;无歧义时继续支持 SQLite-only。预览与 SQL 使用同一选择集合,空集合零更新。事务内逐行比较原 Provider,变化/消失的行跳过,数据库级故障停止。 + +备份先于业务写入,仅包含可写候选。写后复用 sessions manifest 的恢复范围,排除明确未写入的文件,保留写入成功和结果不确定的文件。范围落盘失败需提示,不能声称已排除。旧备份和崩溃时未记录结果的备份保守恢复;SQLite Restore 仍是整库快照。普通同步不引入 journal。 + +有跳过即部分完成。全部历史跳过且无其他写目标时 Sync 不创建备份;Switch 仍备份并切换配置,明确报告历史成功 0 条。成功文件和索引计数分开;跳过摘要含未确认数量。 + +## 接口和日志 + +### 首行编码、结构和处理容量 + +Provider Status/Prepare 严格解码首行 UTF-8;非法字节作为 `metadata-invalid-utf8` 跳过,不能以替换字符静默修改非 Provider 数据。有效 U+FFFD、跨分块多字节字符继续支持;BOM 保留并按现有格式规则拒绝。`payload` 必须为非 null、非数组对象,数组归为 `metadata-invalid`;缺失 Provider 和合法扩展字段仍兼容。 + +不设置固定 JSON 嵌套层数上限。仅在准备变更的 JSON 序列化和原地资格语义比较边界,将 RangeError 处理容量失败归为 `metadata-too-complex`,其他异常继续抛出。无需改写的有效深层首行仍可进入 Status 的已观察 Provider 分布,Status 候选数量不保证实际可写;已识别跳过项不能报告对齐。成功解析出的有效 ID 可用于保护关联索引,非法解码内容不能用于猜 ID。 + +上述固定数据问题 `retryable=false`,提示处理后重新预览。严格校验通过私有 Provider 标记接入,Repair/Restore/History 共享读取默认行为不变。Node 和 Windows worker 写前发现合法首行变成非法编码时返回 `SKIP_CHANGED`,确认源文件未写,沿用关联行排除和恢复范围收窄;不得绕过原地写失败改用替换。 + +沿用公开 schemaVersion/protocolVersion 与 Apply planId 输入。预览 impact、结果和本机操作日志新增 `skipSummary`:`total/rolloutFiles/sqliteRows/unconfirmed/omitted/retryRecommended/items`。每项仅含文件或索引类别、固定 reason、stage、retryable,以及本机文件完整路径或安全索引标识。相同对象只计一次,最多 200 条明细,展示总数和省略数。 + +原因白名单:`metadata-invalid/metadata-invalid-utf8/metadata-too-complex/metadata-too-large/locked/unreadable/missing/changed/write-not-applied/association-unknown/association-conflict/row-changed/row-missing/deferred`。阶段:`scan/plan/revalidate/write/sqlite`。保留锁定和变化计数字段;其他跳过使用 `partialReason=skipped-data`。永久格式/超限问题提示处理后新预览;占用/变化才提示稍后同步。 + +诊断导出独立移除路径和索引标识,不直接复制本机日志。不记录正文、原始异常或凭据。CLI JSON 部分完成退出 3;Human 继续既有退出约定。 + +## 替代范围与验证 + +替代 ADR-0037/0043 的 Provider 全量 revision 失效规则及 ADR-0044 的单条 metadata 错误全局拒绝规则;保留 128 MiB、PIO-1~PIO-6、时间戳、备份优先及完整枚举安全校验。旧 ADR 中相冲突描述为历史行为。 + +证据:`test/provider-skip-data.test.js`、计划漂移/首行/原地及 Windows worker 回归、Contracts 和本机日志重启/导出/UI 测试;生产 Electron 混合数据 Sync→Restore。执行 `npm run architecture:check` 和 `npm test`。本地验证不代表跨平台 CI、真实安装或发布完成。 diff --git a/docs/architecture/NODE_CORE_ARCHITECTURE_ZH.md b/docs/architecture/NODE_CORE_ARCHITECTURE_ZH.md index 26f03be..b611e5f 100644 --- a/docs/architecture/NODE_CORE_ARCHITECTURE_ZH.md +++ b/docs/architecture/NODE_CORE_ARCHITECTURE_ZH.md @@ -1,5 +1,9 @@ # Node Core 当前架构与开发约束 +Provider 首行新增严格 UTF-8 和对象 payload 校验;处理容量失败仅在序列化/语义比较边界逐文件跳过,不设固定嵌套上限。默认共享 Repair/Restore 读取规则不变。 + +当前 Provider 跳过合同见 [ADR-0045](../adr/0045-isolated-provider-data-skips.md):内部逐文件/逐行计划绑定、关联索引排除、已知未写恢复范围及有界本机日志。`test/provider-skip-data.test.js` 覆盖混合数据、未知归属、冻结排除、删除及全部跳过。全局故障和 Repair/Restore 仍严格;不完整状态不能宣称对齐。 + > 状态:Accepted,适用于 V1 当前代码;最近校对:2026-09-08(已纳入 ADR-0038)。 > 本文是 Node Core 日常开发入口,不是发布证明。Electron 总体路线仍见 [vNext 架构基线](../VNEXT_ELECTRON_NODE_ARCHITECTURE_ZH.md),阶段及发布状态只记在[执行索引](../migration/VNEXT_MIGRATION_EXECUTION_INDEX_ZH.md)。 @@ -68,7 +72,7 @@ Windows 写目标占用探测的私有协议位于 `src/windows-lock-probe.js` ### PIO-1:只改 Provider -Sync 目标始终取 `config.toml` 根级 `model_provider`,缺失时为 `openai`。公共输入不接受 `provider/model/fast/syncMode`。正常扫描经 `collectProviderChanges`,只解析第一行 `session_meta`(上限 1 MiB);不得为模型、cwd、用户事件、加密字段、会话序号或历史显示索引扫描正文。 +Sync 目标始终取 `config.toml` 根级 `model_provider`,缺失时为 `openai`。公共输入不接受 `provider/model/fast/syncMode`。正常扫描经 `collectProviderChanges`,只解析第一行 `session_meta`(上限 128 MiB UTF-8 内容字节,不含 LF/CRLF;见 [ADR-0044](../adr/0044-large-session-metadata.md));不得为模型、cwd、用户事件、加密字段、会话序号或历史显示索引扫描正文。 这里“只读首行”指**业务扫描边界**:底层按 64 KiB 分块,可能在包含换行的块中预读少量尾部。按 [ADR-0037](../adr/0037-switch-history-and-provider-preparation-facts.md),Sync/Switch Prepare 的分布、revision 和 change descriptor 复用同一次首行事实,短期记录不进入计划 ledger/公开输入/持久缓存。Apply 锁内复核、实际目标重扫和落盘前仍重新读取。不能声称整个 Sync 只读一次或只读取 Provider 的几个字节。备份/哈希及变长复制有各自 I/O,但不能借此恢复正文业务扫描。 diff --git a/docs/architecture/contracts/CLI_CONTRACT_ZH.md b/docs/architecture/contracts/CLI_CONTRACT_ZH.md index cd14b21..16ab9cb 100644 --- a/docs/architecture/contracts/CLI_CONTRACT_ZH.md +++ b/docs/architecture/contracts/CLI_CONTRACT_ZH.md @@ -1,5 +1,9 @@ # CLI 命令兼容合同 +首行校验补充:非法 UTF-8 使用 `metadata-invalid-utf8`,数组 payload 使用 `metadata-invalid`,序列化或原地资格语义比较的明确容量失败使用 `metadata-too-complex`;三者均逐文件跳过、保留关联索引,固定数据问题不建议稍后重试。不新增固定嵌套层数限制,其他异常仍中止。合法 U+FFFD 支持及 BOM 拒绝规则不变;写前非法编码变化按已变化且未写入处理。 + +ADR-0045 当前增量:Provider Sync/Switch/Watch 将单条首行无效、128 MiB 输入/输出超限、占用/不可读、消失/变化及明确未损坏源文件的写入失败列为跳过,正常候选继续;对应 SQLite 行及不确定关联保持原样。计划排除集合冻结,新增数据留待下次;全局安全、目录枚举、配置/存储、数据库和备份故障仍停止。部分完成新增有界 `skipSummary`(最多 200 项本机完整路径/安全行标识、原因/阶段/可重试性及总数/省略/未确认数);诊断导出单独移除路径和标识。全部跳过的 Sync 无备份,Switch 仍备份并切换配置。JSON 部分完成退出 3,Human 保持既有行为;协议结构版本不变。保留 128 MiB 与 PIO,Repair/Restore 边界不变。详见 [ADR-0045](../../adr/0045-isolated-provider-data-skips.md)。 + ADR-0041 增量:Status/Diagnostics JSON 可选 `staleLockDetected:boolean` 表示发现已证明失效的 Home 锁,不表示已删除锁;检查保持只读。正常写命令重新验证后回收失效锁。未知 owner 仍为 `LOCK_UNVERIFIABLE`,写命令 JSON 退出码仍为 5。 > 状态:Accepted(Phase 0 Human 兼容基线;ADR-0016 C2/C3 增量已实现) diff --git a/docs/architecture/contracts/CORE_EXTERNAL_BEHAVIOR_ZH.md b/docs/architecture/contracts/CORE_EXTERNAL_BEHAVIOR_ZH.md index 13f4d52..4f2ad54 100644 --- a/docs/architecture/contracts/CORE_EXTERNAL_BEHAVIOR_ZH.md +++ b/docs/architecture/contracts/CORE_EXTERNAL_BEHAVIOR_ZH.md @@ -1,5 +1,9 @@ # Node Core 外部行为兼容合同 +首行校验补充:非法 UTF-8 使用 `metadata-invalid-utf8`,数组 payload 使用 `metadata-invalid`,序列化或原地资格语义比较的明确容量失败使用 `metadata-too-complex`;三者均逐文件跳过、保留关联索引,固定数据问题不建议稍后重试。不新增固定嵌套层数限制,其他异常仍中止。合法 U+FFFD 支持及 BOM 拒绝规则不变;写前非法编码变化按已变化且未写入处理。 + +ADR-0045 当前增量:Provider Sync/Switch/Watch 将单条首行无效、128 MiB 输入/输出超限、占用/不可读、消失/变化及明确未损坏源文件的写入失败列为跳过,正常候选继续;对应 SQLite 行及不确定关联保持原样。计划排除集合冻结,新增数据留待下次;全局安全、目录枚举、配置/存储、数据库和备份故障仍停止。部分完成新增有界 `skipSummary`(最多 200 项本机完整路径/安全行标识、原因/阶段/可重试性及总数/省略/未确认数);诊断导出单独移除路径和标识。全部跳过的 Sync 无备份,Switch 仍备份并切换配置。JSON 部分完成退出 3,Human 保持既有行为;协议结构版本不变。保留 128 MiB 与 PIO,Repair/Restore 边界不变。详见 [ADR-0045](../../adr/0045-isolated-provider-data-skips.md)。 + ## 2026-09-11:轻量状态相关性(ADR-0043) 普通 Status 使用内部 `status` revision:正文追加、非 Provider SQLite 列及 WAL/SHM 变化不导致失效;仍校验首行、文件身份/链接数/集合/最小大小、threads schema/ID/Provider/archived 和配置路径。Provider 状态不再整读/哈希数据库文件。真实漂移最多重试一次,实际锁与 pending Restore 继续优先阻断。超限/非法首行仍不完整、不可读数据库仍不可读,WSL 不执行 SQL。完整 Diagnostics、显式 full Status、Plan/Apply、Repair/Restore 与 PIO 不变。见 [ADR-0043](../../adr/0043-status-provider-relevant-revisions.md)。 diff --git a/docs/architecture/contracts/ERROR_CODES_ZH.md b/docs/architecture/contracts/ERROR_CODES_ZH.md index 3b5fd79..88b0fc1 100644 --- a/docs/architecture/contracts/ERROR_CODES_ZH.md +++ b/docs/architecture/contracts/ERROR_CODES_ZH.md @@ -1,5 +1,9 @@ # vNext Error Code 合同 +首行校验补充:非法 UTF-8 使用 `metadata-invalid-utf8`,数组 payload 使用 `metadata-invalid`,序列化或原地资格语义比较的明确容量失败使用 `metadata-too-complex`;三者均逐文件跳过、保留关联索引,固定数据问题不建议稍后重试。不新增固定嵌套层数限制,其他异常仍中止。合法 U+FFFD 支持及 BOM 拒绝规则不变;写前非法编码变化按已变化且未写入处理。 + +ADR-0045 当前增量:Provider Sync/Switch/Watch 将单条首行无效、128 MiB 输入/输出超限、占用/不可读、消失/变化及明确未损坏源文件的写入失败列为跳过,正常候选继续;对应 SQLite 行及不确定关联保持原样。计划排除集合冻结,新增数据留待下次;全局安全、目录枚举、配置/存储、数据库和备份故障仍停止。部分完成新增有界 `skipSummary`(最多 200 项本机完整路径/安全行标识、原因/阶段/可重试性及总数/省略/未确认数);诊断导出单独移除路径和标识。全部跳过的 Sync 无备份,Switch 仍备份并切换配置。JSON 部分完成退出 3,Human 保持既有行为;协议结构版本不变。保留 128 MiB 与 PIO,Repair/Restore 边界不变。详见 [ADR-0045](../../adr/0045-isolated-provider-data-skips.md)。 + ADR-0041 修订:全部 owner 已证明失效时,内部锁观察返回 `stale`,不再把该情形当作 `LOCK_UNVERIFIABLE`;Status 不创建虚假的进行中操作。任何未知、变动或不可验证 owner 仍按原码阻止写入,未新增错误码。 > **状态:Accepted(阶段 0 合同;ADR-0016 C2/C3 轻量写增量已实施)** diff --git a/docs/migration/BEHAVIOR_FIXTURES_ZH.md b/docs/migration/BEHAVIOR_FIXTURES_ZH.md index 2b80a51..b8e6437 100644 --- a/docs/migration/BEHAVIOR_FIXTURES_ZH.md +++ b/docs/migration/BEHAVIOR_FIXTURES_ZH.md @@ -1,5 +1,13 @@ # vNext 行为兼容 Fixture 清单 +`test/provider-header-validation.test.js` 覆盖非法 UTF-8、数组 payload、序列化及语义比较容量失败、有效替换字符和跨块编码、BOM、普通/归档混合数据、冻结排除、写前变化、关联索引保留及恢复范围。日志/UI/生产 Electron 混合数据验收覆盖新增原因码,继续执行 128 MiB 和 PIO 门禁。 + +当前 Provider 跳过合同见 [ADR-0045](../adr/0045-isolated-provider-data-skips.md):内部逐文件/逐行计划绑定、关联索引排除、已知未写恢复范围及有界本机日志。`test/provider-skip-data.test.js` 覆盖混合数据、未知归属、冻结排除、删除及全部跳过。全局故障和 Repair/Restore 仍严格;不完整状态不能宣称对齐。 + +## ADR-0044:大首行与明确错误 + +`test/large-session-metadata.test.js` 覆盖 8 MiB 完整 Status→Sync/Switch→Restore、原地/变长正文不变、128 MiB LF/CRLF/EOF 读取边界与线性合并、超限/无效 Prepare 零写入及安全错误。`CPS_LARGE_HEADER_MIB=128` 可显式运行完整近上限读写。`provider-preparation-facts.test.js`、`status-coordination.test.js` 保留无效/超限拒绝及 Status 不完整检查。生产 Electron smoke 使用 8 MiB 首行验证大首行同步与恢复。 + ## ADR-0039 增补:普通文档 PR 的 CI 分流 `test/ci-docs.test.js` 验证整个 PR 比较(早期代码改动不可被后续文档提交掩盖)、重命名两侧、白名单/未知/空差异、main 始终完整、分类失败、精确任务清单、非预期失败/取消/跳过拒绝,以及 C10 业务结果保真。链接夹具覆盖删除公告入链、括号路径/标题、非渲染示例、百分号及 HTML 目标。`test/release-packaging-contract.test.js` 继续验证四目标和稳定 gate;不以纯文档跳过结果生成或替代正式发布证据。 diff --git a/docs/release-notes/v1.0.3-zh.md b/docs/release-notes/v1.0.3-zh.md new file mode 100644 index 0000000..605e73e --- /dev/null +++ b/docs/release-notes/v1.0.3-zh.md @@ -0,0 +1,49 @@ + + +# v1.0.3:问题会话跳过与大首行同步修复 + +修复一条异常会话导致整次同步或切换中止的问题。支持最高 128 MiB 的会话首行元数据;首行无效、超限、无法读取或占用时,跳过该文件并显示实际原因,让正常会话继续处理。 + +## 本版变化 + +- 普通和归档会话均逐文件处理,跳过文件的关联 SQLite 索引保留原样;无法确认归属的索引保守保留。 +- 修复非法 UTF-8 被静默替换、数组 payload 误报成功,以及首行序列化或语义比较超出处理能力导致整次中止的问题。不设固定 JSON 嵌套层数限制。 +- 修复首行恰好达到大小上限且使用 CRLF 换行时的误判。等字节长度 Provider 继续原地更新,其他合法首行使用流式复制并保留正文。 +- 有跳过时显示“部分完成”,分别统计成功、跳过及未确认数量;本机明细最多展示 200 项路径和原因,诊断导出单独脱敏。 +- 全部历史跳过且没有其他写目标时,同步不创建无用备份;切换仍备份并更新配置,明确显示历史成功 0 条。预览中排除的数据修好后,需重新预览才能纳入。 + +## 📦 下载 + +- 安装版:`CodexProviderSync-1.0.3-windows-x64-setup.exe`。 +- 便携版:`CodexProviderSync-1.0.3-windows-x64-portable.zip`,完整解压后运行 `Codex Provider Sync.exe`。 +- [官方 Release](https://github.com/Dailin521/codex-provider-sync/releases/tag/v1.0.3) 提供 SHA-256、SBOM 和容器验收文件。 + +本版未签名,Windows 可能显示 SmartScreen 提示,请核对官方来源和 SHA-256。本次仅发布 Windows x64 Electron;不发布 npm、macOS/Linux 或 Legacy 安装包。 + +## ⬆️ 升级说明 + +1.0.2 安装版可检查更新,由用户确认下载及重启安装,也可手动安装。1.0.1 的更新检查故障需要手动升级。便携版仍手动下载并完整解压;旧 .NET 单 EXE 更新器不能直接迁移至 Electron。 + +保留现有 Codex 数据、配置和备份,无需删除数据库或锁文件。同步后查看跳过明细:格式或编码问题需处理后重新预览,占用或变化可在会话结束后再同步。 + +## 🛡 安全保障 + +不读取 `auth.json` 或凭据;Provider 同步不解析聊天正文,不修改 `updated_at` 或 `encrypted_content`。实际写入先备份,默认保留 2 份受管备份,可手动回滚。 + +目录无法完整枚举、路径安全、配置或存储变化、数据库、备份、磁盘写满和写入结果不确定仍会停止操作;已有写入时保留备份并报告部分完成。只有明确未写入的文件才从恢复范围排除,SQLite 恢复仍采用整库快照。 + +## ⚠️ 重要说明 + +跳过不代表问题文件已被修复,也不代表全部历史已对齐。超过 128 MiB、BOM/UTF-16 等不支持的首行仍需先处理。元数据对齐不能保证跨 Provider 的会话继续或 compact,也不能解决原账号加密内容的解密限制。 + +Windows 的 WSL UNC SQLite 路径仍仅限诊断,应在对应 WSL 环境内操作。 + +## 🔍 验证结果 + +本地验证覆盖混合问题数据、关联索引保留、预览冻结、写前变化、备份恢复范围、日志重启及导出脱敏;近 128 MiB 真文件完成 Status、原地同步、流式切换和恢复回归。生产 Electron 覆盖大首行及混合数据 Sync → Restore。 + +发布门禁要求最终源码跨平台 CI、Node 16 根包兼容,以及实际安装版/便携版容器启动、SQLite、隔离数据同步恢复、正常退出和适用的卸载验收全部通过。实际源码 SHA、产物哈希及容器结果见 Release 审核附件。 + +公开更新源检查不等于线上跨版本下载、重启升级和数据保持验收,后者尚未完成独立验证。未新增签名、真实 WSL 或其他平台人工验收。 + +[使用说明](../README_DESKTOP_ZH.md) · [更新日志](../../CHANGELOG.md) diff --git a/package-lock.json b/package-lock.json index 2ddfae7..4e33e2c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@dailin521/codex-provider-sync", - "version": "1.0.2", + "version": "1.0.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@dailin521/codex-provider-sync", - "version": "1.0.2", + "version": "1.0.3", "license": "MIT", "workspaces": [ "apps/*", @@ -35,7 +35,7 @@ }, "apps/desktop": { "name": "@codex-provider-sync/desktop", - "version": "1.0.2", + "version": "1.0.3", "dependencies": { "better-sqlite3": "13.0.3", "electron-updater": "6.8.9" diff --git a/package.json b/package.json index a383252..f53558c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@dailin521/codex-provider-sync", - "version": "1.0.2", + "version": "1.0.3", "description": "Synchronize Codex session provider metadata across rollout files and SQLite state.", "type": "module", "workspaces": [ @@ -46,7 +46,7 @@ "workspaces:build": "tsc -b tsconfig.workspaces.json && tsc -p packages/core/tsconfig.json", "workspaces:test": "npm run test --workspaces --if-present", "workspaces:check": "npm run workspaces:build && npm run workspaces:test && node scripts/verify-workspace-boundaries.js", - "core:test:provider-io": "node --test test/provider-sync-lite.test.js test/provider-preparation-facts.test.js test/in-place-transaction.test.js test/windows-rewrite-worker.test.js", + "core:test:provider-io": "node --test test/provider-sync-lite.test.js test/provider-preparation-facts.test.js test/provider-header-validation.test.js test/large-session-metadata.test.js test/in-place-transaction.test.js test/windows-rewrite-worker.test.js", "architecture:check": "npm run workspaces:check && npm run core:test:provider-io", "package:smoke": "node scripts/smoke-root-tarball.js", "package:smoke:lifecycle": "node scripts/smoke-root-tarball.js --install-lifecycle", diff --git a/packages/app-ui/src/features/operation-logs/OperationLogsPage.tsx b/packages/app-ui/src/features/operation-logs/OperationLogsPage.tsx index 809dfbd..79af31e 100644 --- a/packages/app-ui/src/features/operation-logs/OperationLogsPage.tsx +++ b/packages/app-ui/src/features/operation-logs/OperationLogsPage.tsx @@ -1,3 +1,4 @@ +import { SkipDetails } from "../operations/SkipDetails.js"; import { useQuery } from "@tanstack/react-query"; import { ArrowLeft, RefreshCw } from "lucide-react"; import { useEffect, useLayoutEffect, useRef, useState } from "react"; @@ -15,7 +16,7 @@ const PAGE_SIZE = 50; const OPERATIONS = ["sync", "switch", "repair", "restore", "pruneBackups", "diagnostics", "watch", "update", "profile", "runtime"] as const; const STATUSES: OperationLogStatus[] = ["running", "awaiting-confirmation", "completed", "partial", "failed", "cancelled", "dismissed", "interrupted"]; const KNOWN_COUNTS = new Set([ - "changedSessionFiles", "inPlaceSessionFiles", "rewrittenSessionFiles", "sqliteRowsUpdated", + "unconfirmedSessionFiles", "changedSessionFiles", "inPlaceSessionFiles", "rewrittenSessionFiles", "sqliteRowsUpdated", "sqliteProviderRowsUpdated", "sqliteModelRowsUpdated", "sqliteUserEventRowsUpdated", "sqliteCwdRowsUpdated", "skippedLockedRolloutFiles", "skippedChangedRolloutFiles", "updatedWorkspaceRoots", "savedWorkspaceRootCount", "resolvedOperationCount" @@ -152,7 +153,8 @@ export function OperationLogsPage({ host, profileId, profileRevision, openBackup {hasManyRewrittenSessions(selected.operation, selected.counts) ? : null} {["sync", "switch", "watch"].includes(selected.operation) ? : null} {selected.failedStage || selected.failureCode || selected.partialReason ?
{selected.failedStage ?
{t("operationResult.fields.failedStage")}
{operationStageLabel(selected.failedStage, t)}
: null}{selected.failureCode ?
{t("operationResult.fields.failureCode")}
{operationFailureLabel(selected.failureCode, t)}
: null}{selected.partialReason ?
{t("operationResult.fields.partialReason")}
{t(`operationResult.partialReasons.${selected.partialReason}`, { defaultValue: t("global.partial") })}
: null}
: null} - {selected.retryRecommended ?

{t(selected.partialReason === "locked-session" ? "operationResult.retryAfterSession" : "operationResult.retryFreshPlan")}

: null} + + {!selected.skipSummary && selected.retryRecommended ?

{t(selected.partialReason === "locked-session" ? "operationResult.retryAfterSession" : "operationResult.retryFreshPlan")}

: null} {(selected.backupId || selected.retryRecommended) && (openBackupRestore || reviewOperation) ? selected.profileId === profileId && selected.profileRevision !== undefined && selected.profileRevision === profileRevision ?
{selected.retryRecommended && reviewOperation && ["sync", "switch", "repair", "watch"].includes(selected.operation) ? : null}{selected.backupId && openBackupRestore ? : null}
:

{t("logs.profileMismatch")}

: null} {previewCounts.length ?

{t("logs.previewCounts")}

{previewCounts.map(([name, value]) =>
{t(`logs.previewCountLabels.${name}`)}
{value}
)}
: null} {selected.switchPlan ?

{t("logs.switchPlan")}

{t("logs.providerChange")}
{selected.switchPlan.previousProvider} → {selected.switchPlan.targetProvider}
{t("logs.rootModelChange")}
{selected.switchPlan.previousRootModel ?? t("logs.notSet")} → {selected.switchPlan.targetRootModel ?? t("logs.notSet")}
{t("logs.modelMode")}
{t(`plan.modelModes.${selected.switchPlan.modelMode}`)}
{selected.status === "partial" ?

{t("logs.switchPlanPartial")}

: null}
: selected.operation === "switch" ?

{t("logs.switchPlanUnavailable")}

: null} diff --git a/packages/app-ui/src/features/operations/OperationResultDialog.tsx b/packages/app-ui/src/features/operations/OperationResultDialog.tsx index 2696bab..12efe4b 100644 --- a/packages/app-ui/src/features/operations/OperationResultDialog.tsx +++ b/packages/app-ui/src/features/operations/OperationResultDialog.tsx @@ -1,3 +1,5 @@ +import { SkipDetails } from "./SkipDetails.js"; +import { publicSkipSummary } from "@codex-provider-sync/contracts"; import type { OperationOutcome, OperationResult } from "@codex-provider-sync/contracts"; import { Fragment } from "react"; import { useTranslation } from "react-i18next"; @@ -37,6 +39,7 @@ function publicResultEntries(value: OperationResult["result"]): Array<[string, s "partialReason", "failedStage", "failureCode" ]); const numbers = new Set([ + "unconfirmedSessionFiles", "changedSessionFiles", "sqliteRowsUpdated", "sqliteProviderRowsUpdated", @@ -122,7 +125,8 @@ export function OperationResultDialog({ result, postWriteStatus, close, closeDis const entries = result ? publicResultEntries(result.result) : []; const skipped = result ? skippedRollouts(result.result) : []; const skippedChanged = result ? skippedChangedRollouts(result.result) : []; - const skippedCount = skipped.length + skippedChanged.length; + const summary = publicSkipSummary(result?.result && typeof result.result === "object" && !Array.isArray(result.result) ? result.result.skipSummary : undefined); + const skippedCount = summary ? 0 : skipped.length + skippedChanged.length; const partialReason = result?.result && typeof result.result === "object" && !Array.isArray(result.result) @@ -161,8 +165,10 @@ export function OperationResultDialog({ result, postWriteStatus, close, closeDis : null} {hasManyRewrittenSessions(result.operation, result.result) ? : null} {result.warnings.length ?

{t("common.warnings")}

    {result.warnings.map((warning, index) =>
  • {displayWarningText(warning, t)}
  • )}
: null} + + {result.operation === "switch" && result.result && typeof result.result === "object" && !Array.isArray(result.result) && result.result.configUpdated === true ?

{t("skips.configSwitched", { count: result.result.changedSessionFiles ?? 0 })}

: null} {skippedCount ?

{t("operationResult.skippedCount", { count: skippedCount })}

: null} - {retryRecommended ?

{t(partialReason === "locked-session" ? "operationResult.retryAfterSession" : "operationResult.retryFreshPlan")}

: null} + {retryRecommended && (partialReason === "mutation-failed" || !summary || (!summary.total && !summary.unconfirmed)) ?

{t(partialReason === "locked-session" ? "operationResult.retryAfterSession" : "operationResult.retryFreshPlan")}

: null} {retryRecommended && reviewOperation ? : null} {resultVerification ?

{t("operationResult.verification.title")}

{t(`operationResult.verification.status.${resultVerification.status}`)}

{resultVerification.status === "remaining" ?
{t("operationResult.verification.remainingRolloutFiles")}
{resultVerification.remainingRolloutFiles}
{t("operationResult.verification.remainingSqliteRows")}
{resultVerification.remainingSqliteRows}
{t("operationResult.verification.remainingWorkspaceRoots")}
{resultVerification.remainingWorkspaceRoots}
{t("operationResult.verification.skippedSessions")}
{resultVerification.skippedSessions}
: null}
: null} {entries.length ?

{t("operationResult.changeCountersHint")}

: null} diff --git a/packages/app-ui/src/features/operations/PlanReview.tsx b/packages/app-ui/src/features/operations/PlanReview.tsx index 9b2a29c..8207f2c 100644 --- a/packages/app-ui/src/features/operations/PlanReview.tsx +++ b/packages/app-ui/src/features/operations/PlanReview.tsx @@ -1,3 +1,4 @@ +import { SkipDetails } from "./SkipDetails.js"; import type { PlanSummary, ProgressEvent } from "@codex-provider-sync/contracts"; import { Fragment, useEffect, useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; @@ -164,6 +165,7 @@ export function PlanReview({ {cancelling ?

{t("plan.cancelPending")}

: null} : plan ? (
+

{t("plan.target")}

{modelTransition ? : null}{targetRows.map(([key, label]) => )}
diff --git a/packages/app-ui/src/features/operations/SkipDetails.tsx b/packages/app-ui/src/features/operations/SkipDetails.tsx new file mode 100644 index 0000000..6bf8cc7 --- /dev/null +++ b/packages/app-ui/src/features/operations/SkipDetails.tsx @@ -0,0 +1,22 @@ +import { publicSkipSummary } from "@codex-provider-sync/contracts"; +import { useTranslation } from "react-i18next"; + +export function SkipDetails({ value }: { value: unknown }) { + const { t } = useTranslation(); + const summary = publicSkipSummary(value); + if (!summary || (!summary.total && !summary.unconfirmed)) return null; + return
+

{t("skips.title")}

+

{t("skips.counts", { total: summary.total, files: summary.rolloutFiles, rows: summary.sqliteRows, unknown: summary.unconfirmed })}

+

{t(summary.retryRecommended ? "skips.retry" : "skips.fix")}

+
{t("skips.details")} +
    + {summary.items.map((item, index) =>
  • + {item.path ?? item.id ?? t("skips.unidentified")} + {t(`skips.reasons.${item.reason}`)} · {t(`skips.stages.${item.stage}`)} +
  • )} +
+
+

{t("skips.shown", { shown: summary.items.length, omitted: summary.omitted, total: summary.total })}

+
; +} diff --git a/packages/app-ui/src/features/overview/OverviewPage.tsx b/packages/app-ui/src/features/overview/OverviewPage.tsx index e93f309..4ac1fda 100644 --- a/packages/app-ui/src/features/overview/OverviewPage.tsx +++ b/packages/app-ui/src/features/overview/OverviewPage.tsx @@ -1,3 +1,4 @@ +import { SkipDetails } from "../operations/SkipDetails.js"; import type { StatusSnapshot } from "@codex-provider-sync/contracts"; import { AlertTriangle, CheckCircle2, RefreshCw } from "lucide-react"; import { Fragment } from "react"; @@ -92,6 +93,8 @@ export function OverviewPage({ status, loading, refresh, profileName, profileKey
{sessionUsageKnown ? status.sessionActivity?.count : t("overview.usageUnknown")}
+ {hasSnapshot && !status.rolloutScanComplete ?

{t("skips.incomplete")}

: null} + {loading && hasSnapshot ?

{t("ux.previousSnapshot")}

: null} {hasSnapshot ?
diff --git a/packages/app-ui/src/i18n.ts b/packages/app-ui/src/i18n.ts index e5d23c9..232113c 100644 --- a/packages/app-ui/src/i18n.ts +++ b/packages/app-ui/src/i18n.ts @@ -715,6 +715,7 @@ export const resources = { cancelling: "Cancelling…", cancelPending: "Cancellation will take effect at the next safe point." }, + skips: {"title":"Skipped data","counts":"Skipped {{total}} items: {{files}} files, {{rows}} index rows; {{unknown}} unconfirmed.","details":"Show local details","unidentified":"Unidentified index row","shown":"Showing {{shown}} of {{total}}; {{omitted}} omitted.","retry":"Some files are in use or have changed. Retry those with a fresh preview; fix other listed issues first.","fix":"Resolve the listed issues, then create a fresh preview to include these items.","configSwitched":"Configuration switched; history files updated: {{count}}.","incomplete":"Some session data could not be verified. You can preview and synchronize the healthy portion.","reasons":{"metadata-invalid":"Invalid first-line metadata","metadata-invalid-utf8":"First-line metadata is not valid UTF-8","metadata-too-complex":"Metadata exceeds the processing capacity","metadata-too-large":"Metadata exceeds the 128 MiB input/output limit","locked":"File is in use","unreadable":"File cannot be read","missing":"File disappeared","changed":"File changed","write-not-applied":"Write failed; source confirmed unchanged","association-unknown":"Cannot confirm session association","association-conflict":"Session associations conflict","row-changed":"Index Provider changed","row-missing":"Index row disappeared","deferred":"New item deferred to the next preview"},"stages":{"scan":"Scan","plan":"Preview","revalidate":"Recheck","write":"Write","sqlite":"Index update"}}, operationResult: { title: "Operation result", operationId: "Operation ID", @@ -737,12 +738,14 @@ export const resources = { skippedSessions: "Skipped chat records" }, partialReasons: { + "skipped-data": "Some session data was skipped", "locked-session": "A chat is still in use", "rollout-changed": "A chat changed during the operation", "mutation-failed": "The operation stopped after some changes were saved" }, resolveBeforeClose: "Resolve the pending recovery before closing this result.", fields: { + unconfirmedSessionFiles: "Files with unconfirmed write outcome", inPlaceSessionFiles: "In-place rollout updates", rewrittenSessionFiles: "Fully rewritten rollouts", targetProvider: "Target Provider", @@ -819,6 +822,8 @@ export const resources = { SQLITE_UNREADABLE: "The local chat index could not be read. Run diagnostics or restore a backup.", ROLLOUT_LOCKED: "Some chats are in use. Close the active Codex sessions and try again.", ROLLOUT_CHANGED: "Some chats changed during the operation. Review and try again.", + ROLLOUT_METADATA_TOO_LARGE: "Session metadata must stay within 128 MiB before and after syncing. Resolve the oversized header before syncing again.", + ROLLOUT_METADATA_INVALID: "The first rollout record is not valid session metadata. Resolve the invalid header before syncing again.", PENDING_TRANSACTION: "A previous restore must be completed before continuing.", BACKUP_FAILED: "A backup could not be created, so no changes were made.", SYNC_FAILED_ROLLED_BACK: "The sync did not finish. The previous data was restored.", @@ -1559,6 +1564,7 @@ export const resources = { cancelling: "正在取消…", cancelPending: "取消将在下一个安全点生效。" }, + skips: {"title":"已跳过的问题数据","counts":"跳过 {{total}} 项:文件 {{files}} 个、索引 {{rows}} 条;未确认 {{unknown}} 项。","details":"查看本机明细","unidentified":"无法安全标识的索引行","shown":"共 {{total}} 项,展示 {{shown}} 项,省略 {{omitted}} 项。","retry":"部分文件正在使用或已变化,可稍后重新预览同步;其他问题请按明细处理后再试。","fix":"请先处理明细中的问题,再重新预览,将修好的数据纳入同步。","configSwitched":"配置已切换,历史成功 {{count}} 条。","incomplete":"存在无法确认的问题数据。可以继续预览并同步正常部分。","reasons":{"metadata-invalid":"首行元数据格式无效","metadata-invalid-utf8":"首行元数据不是有效的 UTF-8 编码","metadata-too-complex":"首行元数据超出处理能力","metadata-too-large":"首行元数据在同步前或同步后超过 128 MiB","locked":"文件正在使用","unreadable":"文件无法读取","missing":"文件已消失","changed":"文件已变化","write-not-applied":"写入失败,已确认源文件未受损","association-unknown":"无法确认会话归属","association-conflict":"会话关联冲突","row-changed":"索引 Provider 已变化","row-missing":"索引行已消失","deferred":"新数据留待下一次预览"},"stages":{"scan":"扫描","plan":"预览","revalidate":"执行前复核","write":"写入","sqlite":"索引更新"}}, operationResult: { title: "操作结果", operationId: "操作 ID", @@ -1581,12 +1587,14 @@ export const resources = { skippedSessions: "跳过的会话记录" }, partialReasons: { + "skipped-data": "部分会话数据已跳过", "locked-session": "有聊天仍在使用", "rollout-changed": "操作期间聊天记录发生变化", "mutation-failed": "部分更改保存后操作中断" }, resolveBeforeClose: "请先完成待处理的恢复,再关闭此结果。", fields: { + unconfirmedSessionFiles: "写入结果未确认的文件", inPlaceSessionFiles: "原地更新的 rollout", rewrittenSessionFiles: "完整重写的 rollout", targetProvider: "目标 Provider", @@ -1663,6 +1671,8 @@ export const resources = { SQLITE_UNREADABLE: "无法读取本地聊天索引,请运行诊断或从备份恢复。", ROLLOUT_LOCKED: "部分会话正在使用中,请关闭相关 Codex 会话后重试。", ROLLOUT_CHANGED: "部分会话在操作期间发生变化,请重新检查后重试。", + ROLLOUT_METADATA_TOO_LARGE: "会话首行元数据必须在同步前后均不超过 128 MiB,请处理超限问题后再同步。", + ROLLOUT_METADATA_INVALID: "会话首行不是有效的会话元数据,请处理格式问题后再同步。", PENDING_TRANSACTION: "上一次恢复需要先完成,才能继续操作。", BACKUP_FAILED: "无法创建备份,因此没有修改任何数据。", SYNC_FAILED_ROLLED_BACK: "同步未能完成,原有数据已经恢复。", diff --git a/packages/app-ui/src/types.ts b/packages/app-ui/src/types.ts index 22708e6..649623c 100644 --- a/packages/app-ui/src/types.ts +++ b/packages/app-ui/src/types.ts @@ -1,4 +1,4 @@ -import type { FileUpdateTiming, WatchSnapshot } from "@codex-provider-sync/contracts"; +import type { SkipSummary, FileUpdateTiming, WatchSnapshot } from "@codex-provider-sync/contracts"; import type { CoreClient } from "@codex-provider-sync/core-client"; import type { SupportedLocale, ThemeMode } from "@codex-provider-sync/design-system"; @@ -29,8 +29,8 @@ export type HostDirectorySelection = export type OperationLogStatus = "running" | "awaiting-confirmation" | "completed" | "partial" | "failed" | "cancelled" | "dismissed" | "interrupted"; export interface OperationLogStage { stage: string; status: "running" | "completed" | "failed"; startedAt: string; completedAt?: string; durationMs?: number; progress?: number; count?: number; } -export interface OperationLogEntry { fileUpdateTiming?: FileUpdateTiming; } -export interface OperationLogEntry { schemaVersion: 1; id: string; operation: string; profileId?: string; profileRevision?: string; startedAt: string; completedAt?: string; activeDurationMs: number; wallDurationMs?: number; status: OperationLogStatus; outcome?: string; errorCode?: string; errorReason?: "profile" | "config" | "storage" | "rollout" | "state-db" | "backup" | "provider-not-configured"; failedStage?: string; failureCode?: string; partialReason?: "locked-session" | "rollout-changed" | "mutation-failed"; retryRecommended?: boolean; requestIds: string[]; planId?: string; operationId?: string; backupId?: string; targetProvider?: string; previewCounts?: { rolloutFilesToChange: number; sqliteRowsToChange: number; lockedRolloutFiles: number; }; switchPlan?: { previousProvider: string; targetProvider: string; previousRootModel: string | null; targetRootModel: string | null; modelMode: "provider-default" | "keep-root-model" | "explicit"; }; counts: Record; warnings: string[]; stages: OperationLogStage[]; } +export interface OperationLogEntry { skipSummary?: SkipSummary; fileUpdateTiming?: FileUpdateTiming; } +export interface OperationLogEntry { schemaVersion: 1; id: string; operation: string; profileId?: string; profileRevision?: string; startedAt: string; completedAt?: string; activeDurationMs: number; wallDurationMs?: number; status: OperationLogStatus; outcome?: string; errorCode?: string; errorReason?: "profile" | "config" | "storage" | "rollout" | "state-db" | "backup" | "provider-not-configured"; failedStage?: string; failureCode?: string; partialReason?: "locked-session" | "rollout-changed" | "mutation-failed" | "skipped-data"; retryRecommended?: boolean; requestIds: string[]; planId?: string; operationId?: string; backupId?: string; targetProvider?: string; previewCounts?: { rolloutFilesToChange: number; sqliteRowsToChange: number; lockedRolloutFiles: number; }; switchPlan?: { previousProvider: string; targetProvider: string; previousRootModel: string | null; targetRootModel: string | null; modelMode: "provider-default" | "keep-root-model" | "explicit"; }; counts: Record; warnings: string[]; stages: OperationLogStage[]; } export interface OperationLogPage { schemaVersion: 1; page: number; pageSize: number; total: number; hasNextPage: boolean; entries: OperationLogEntry[]; } export interface HostClient { diff --git a/packages/app-ui/tests/metadata-errors.vitest.tsx b/packages/app-ui/tests/metadata-errors.vitest.tsx new file mode 100644 index 0000000..ddad49b --- /dev/null +++ b/packages/app-ui/tests/metadata-errors.vitest.tsx @@ -0,0 +1,19 @@ +import { CoreClientError } from "@codex-provider-sync/core-client"; +import { createPublicCoreErrorDto } from "@codex-provider-sync/contracts"; +import { describe, expect, it } from "vitest"; +import { createAppI18n } from "../src/i18n.js"; +import { safeErrorText } from "../src/shared/presentation.js"; + +describe("metadata failures", () => { + it.each(["en", "zh-CN"] as const)("shows distinct actionable errors in %s through CoreClient", async locale => { + const i18n = await createAppI18n(locale); + const texts = (["ROLLOUT_METADATA_TOO_LARGE", "ROLLOUT_METADATA_INVALID", "ROLLOUT_CHANGED"] as const).map(code => { + const dto = createPublicCoreErrorDto(code); + return safeErrorText(new CoreClientError(dto), i18n.t.bind(i18n)); + }); + expect(new Set(texts).size).toBe(3); + expect(texts[0]).toContain("128 MiB"); + expect(texts[1]).toMatch(/元数据|session metadata/); + expect(texts.every(text => text !== i18n.t("errors.fallback"))).toBe(true); + }); +}); diff --git a/packages/app-ui/tests/partial-feedback.vitest.tsx b/packages/app-ui/tests/partial-feedback.vitest.tsx index d6135df..dab71c6 100644 --- a/packages/app-ui/tests/partial-feedback.vitest.tsx +++ b/packages/app-ui/tests/partial-feedback.vitest.tsx @@ -18,6 +18,19 @@ const entry: OperationLogEntry = { }; describe("Partial operation feedback", () => { + it.each([0, 1])("keeps mutation failure retry guidance with %i fixed data skips", async count => { + const i18n = await createAppI18n("en"); + const skipSummary = { total: count, rolloutFiles: count, sqliteRows: 0, unconfirmed: 0, omitted: 0, retryRecommended: false, + items: count ? [{ kind: "rollout", path: "/fixture/bad.jsonl", reason: "metadata-invalid", stage: "scan", retryable: false }] : [] }; + render( {}} restoreFocus={() => {}} result={{ + schemaVersion: 1, operationId: "failed-switch", operation: "switch", outcome: "partial", backup: { backupId: "backup" }, warnings: [], + result: { partialReason: "mutation-failed", retryRecommended: true, skipSummary } + }} />); + expect(screen.getByText(i18n.t("operationResult.retryFreshPlan"))).toBeVisible(); + if (count) expect(screen.getByText(i18n.t("skips.fix"))).toBeVisible(); + else expect(screen.queryByRole("region", { name: i18n.t("skips.title") })).not.toBeInTheDocument(); + }); + it.each([ { profileRevision: "r1", logRevision: "r1" }, { profileRevision: "changed", logRevision: "r1" }, diff --git a/packages/app-ui/tests/skip-details.vitest.tsx b/packages/app-ui/tests/skip-details.vitest.tsx new file mode 100644 index 0000000..948091d --- /dev/null +++ b/packages/app-ui/tests/skip-details.vitest.tsx @@ -0,0 +1,18 @@ +import { render, screen, cleanup } from "@testing-library/react"; +import { I18nextProvider } from "react-i18next"; +import { afterEach, expect, it } from "vitest"; +import { createAppI18n } from "../src/i18n.js"; +import { SkipDetails } from "../src/features/operations/SkipDetails.js"; +afterEach(cleanup); +it.each(["en", "zh-CN"] as const)("shows bounded actionable local skip details in %s", async locale => { + const i18n = await createAppI18n(locale); + const summary = { total: 201, rolloutFiles: 201, sqliteRows: 0, unconfirmed: 0, omitted: 1, retryRecommended: false, + items: Array.from({ length: 200 }, (_, n) => ({ kind: "rollout", path: `D:/fixture/file-${n}.jsonl`, reason: n === 0 ? "metadata-invalid-utf8" : n === 1 ? "metadata-too-complex" : "metadata-invalid", stage: "scan", retryable: false })) }; + render(); + expect(screen.getByText("D:/fixture/file-199.jsonl")).toBeInTheDocument(); + expect(screen.getByText(i18n.t("skips.reasons.metadata-invalid-utf8"), { exact: false })).toBeInTheDocument(); + expect(screen.getByText(i18n.t("skips.reasons.metadata-too-complex"), { exact: false })).toBeInTheDocument(); + expect(screen.getByText(i18n.t("skips.fix"))).toBeInTheDocument(); + expect(screen.queryByText(i18n.t("skips.retry"))).toBeNull(); + expect(screen.getByText(i18n.t("skips.shown", { shown: 200, total: 201, omitted: 1 }))).toBeInTheDocument(); +}); diff --git a/packages/contracts/dist/errors.d.ts b/packages/contracts/dist/errors.d.ts index 8c1056d..46da2f1 100644 --- a/packages/contracts/dist/errors.d.ts +++ b/packages/contracts/dist/errors.d.ts @@ -1,5 +1,5 @@ import type { JsonObject } from "./json.js"; -export declare const CORE_ERROR_CODES: readonly ["INVALID_INPUT", "PROFILE_CHANGED", "STORAGE_CHANGED", "PLAN_STALE", "PLAN_EXPIRED", "STALE_STATE", "CODEX_HOME_NOT_FOUND", "STATE_DB_NOT_FOUND", "SQLITE_UNSUPPORTED_PATH", "SQLITE_BUSY", "SQLITE_UNREADABLE", "ROLLOUT_LOCKED", "ROLLOUT_CHANGED", "PENDING_TRANSACTION", "BACKUP_FAILED", "SYNC_FAILED_ROLLED_BACK", "RECOVERY_REQUIRED", "RESTORE_VALIDATION_FAILED", "PERMISSION_DENIED", "OPERATION_BUSY", "LOCK_UNVERIFIABLE", "OPERATION_CANCELLED", "CORE_RUNTIME_CRASHED", "PROTOCOL_VERSION_MISMATCH", "INTERNAL_ERROR"]; +export declare const CORE_ERROR_CODES: readonly ["INVALID_INPUT", "PROFILE_CHANGED", "STORAGE_CHANGED", "PLAN_STALE", "PLAN_EXPIRED", "STALE_STATE", "CODEX_HOME_NOT_FOUND", "STATE_DB_NOT_FOUND", "SQLITE_UNSUPPORTED_PATH", "SQLITE_BUSY", "SQLITE_UNREADABLE", "ROLLOUT_LOCKED", "ROLLOUT_CHANGED", "ROLLOUT_METADATA_TOO_LARGE", "ROLLOUT_METADATA_INVALID", "PENDING_TRANSACTION", "BACKUP_FAILED", "SYNC_FAILED_ROLLED_BACK", "RECOVERY_REQUIRED", "RESTORE_VALIDATION_FAILED", "PERMISSION_DENIED", "OPERATION_BUSY", "LOCK_UNVERIFIABLE", "OPERATION_CANCELLED", "CORE_RUNTIME_CRASHED", "PROTOCOL_VERSION_MISMATCH", "INTERNAL_ERROR"]; export type CoreErrorCode = typeof CORE_ERROR_CODES[number]; export type CoreErrorSeverity = "info" | "warning" | "error" | "fatal"; /** diff --git a/packages/contracts/dist/errors.js b/packages/contracts/dist/errors.js index 6be10e6..aa5463c 100644 --- a/packages/contracts/dist/errors.js +++ b/packages/contracts/dist/errors.js @@ -12,6 +12,8 @@ export const CORE_ERROR_CODES = [ "SQLITE_UNREADABLE", "ROLLOUT_LOCKED", "ROLLOUT_CHANGED", + "ROLLOUT_METADATA_TOO_LARGE", + "ROLLOUT_METADATA_INVALID", "PENDING_TRANSACTION", "BACKUP_FAILED", "SYNC_FAILED_ROLLED_BACK", @@ -82,6 +84,8 @@ export const PUBLIC_CORE_ERROR_MESSAGES = Object.freeze({ SQLITE_UNREADABLE: "The state database is unreadable or malformed.", ROLLOUT_LOCKED: "One or more rollout files are locked.", ROLLOUT_CHANGED: "One or more rollout files changed during the operation.", + ROLLOUT_METADATA_TOO_LARGE: "Session metadata must stay within 128 MiB before and after syncing. Resolve the oversized header before syncing again.", + ROLLOUT_METADATA_INVALID: "The first rollout record is not valid session metadata. Resolve the invalid header before syncing again.", PENDING_TRANSACTION: "An unfinished transaction must be resolved before another write.", BACKUP_FAILED: "The required backup could not be completed.", SYNC_FAILED_ROLLED_BACK: "The operation failed and its changes were rolled back.", @@ -216,7 +220,7 @@ export function createPublicCoreErrorDto(code, options = {}) { code, message: PUBLIC_CORE_ERROR_MESSAGES[code], severity: publicSeverity(code), - retryable: true, + retryable: code !== "ROLLOUT_METADATA_TOO_LARGE" && code !== "ROLLOUT_METADATA_INVALID", recoveryRequired: RECOVERY_CODES.has(code), ...(operationId ? { operationId } : {}), ...(details ? { details } : {}) diff --git a/packages/contracts/dist/index.d.ts b/packages/contracts/dist/index.d.ts index 2b4123e..5ad72a0 100644 --- a/packages/contracts/dist/index.d.ts +++ b/packages/contracts/dist/index.d.ts @@ -1,5 +1,6 @@ export * from "./dto.js"; export * from "./errors.js"; export * from "./file-update-timing.js"; +export * from "./skip-summary.js"; export * from "./json.js"; export * from "./protocol.js"; diff --git a/packages/contracts/dist/index.js b/packages/contracts/dist/index.js index 2b4123e..5ad72a0 100644 --- a/packages/contracts/dist/index.js +++ b/packages/contracts/dist/index.js @@ -1,5 +1,6 @@ export * from "./dto.js"; export * from "./errors.js"; export * from "./file-update-timing.js"; +export * from "./skip-summary.js"; export * from "./json.js"; export * from "./protocol.js"; diff --git a/packages/contracts/dist/protocol.js b/packages/contracts/dist/protocol.js index 55576a7..165bc32 100644 --- a/packages/contracts/dist/protocol.js +++ b/packages/contracts/dist/protocol.js @@ -1,5 +1,6 @@ import { CORE_METHODS, CORE_PROTOCOL_VERSION } from "./dto.js"; import { CORE_ERROR_CODES, isCanonicalPublicCoreErrorDto } from "./errors.js"; +import { isSkipSummary } from "./skip-summary.js"; import { isFileUpdateTiming } from "./file-update-timing.js"; const METHOD_SET = new Set(CORE_METHODS); const ERROR_CODE_SET = new Set(CORE_ERROR_CODES); @@ -528,6 +529,7 @@ export function assertCoreMethodOutput(method, value) { || !isNonEmptyString(profile.id) || !isNonEmptyString(profile.revision) || !isNonEmptyString(status.currentProvider) + || (status.skipSummary !== undefined && !isSkipSummary(status.skipSummary)) || (status.sessionActivity !== undefined && !isSessionActivity(status.sessionActivity)) || (usage !== undefined && (!isRecord(usage) || Object.keys(usage).sort().join(",") !== "count,state" @@ -608,6 +610,7 @@ export function assertCoreMethodOutput(method, value) { || !isJsonValue(plan.target) || !isRecord(plan.impact) || !isJsonValue(plan.impact) + || (plan.impact.skipSummary !== undefined && !isSkipSummary(plan.impact.skipSummary)) || (plan.impact.sessionActivity !== undefined && !isSessionActivity(plan.impact.sessionActivity)) || !Array.isArray(plan.warnings) || plan.warnings.some((entry) => typeof entry !== "string") @@ -648,6 +651,9 @@ export function assertCoreMethodOutput(method, value) { if (!("result" in result) || !isJsonValue(result.result)) { throw new ContractValidationError("INVALID_INPUT", "OperationResult result is required."); } + if (isRecord(result.result) && result.result.skipSummary !== undefined && !isSkipSummary(result.result.skipSummary)) { + throw new ContractValidationError("INVALID_INPUT", "Invalid skip summary."); + } if (isRecord(result.result) && result.result.fileUpdateTiming !== undefined && !isFileUpdateTiming(result.result.fileUpdateTiming)) { throw new ContractValidationError("INVALID_INPUT", "Invalid file update timing."); } diff --git a/packages/contracts/dist/skip-summary.d.ts b/packages/contracts/dist/skip-summary.d.ts new file mode 100644 index 0000000..b9b5362 --- /dev/null +++ b/packages/contracts/dist/skip-summary.d.ts @@ -0,0 +1,24 @@ +/** Local operation detail. Diagnostic exports must use redactSkipSummary. */ +export declare const SKIP_REASONS: readonly ["metadata-invalid", "metadata-invalid-utf8", "metadata-too-complex", "metadata-too-large", "locked", "unreadable", "missing", "changed", "write-not-applied", "association-unknown", "association-conflict", "row-changed", "row-missing", "deferred"]; +export declare const SKIP_STAGES: readonly ["scan", "plan", "revalidate", "write", "sqlite"]; +export interface SkipItem { + kind: "rollout" | "sqlite"; + path?: string; + id?: string; + reason: typeof SKIP_REASONS[number]; + stage: typeof SKIP_STAGES[number]; + retryable: boolean; +} +export interface SkipSummary { + total: number; + rolloutFiles: number; + sqliteRows: number; + unconfirmed: number; + omitted: number; + retryRecommended: boolean; + items: SkipItem[]; +} +export declare function isSkipSummary(value: unknown): value is SkipSummary; +export declare function publicSkipSummary(value: unknown): SkipSummary | undefined; +/** Preserve counts/reasons while removing every local file path and row ID. */ +export declare function redactSkipSummary(value: unknown): SkipSummary | undefined; diff --git a/packages/contracts/dist/skip-summary.js b/packages/contracts/dist/skip-summary.js new file mode 100644 index 0000000..6c21fde --- /dev/null +++ b/packages/contracts/dist/skip-summary.js @@ -0,0 +1,32 @@ +/** Local operation detail. Diagnostic exports must use redactSkipSummary. */ +export const SKIP_REASONS = ["metadata-invalid", "metadata-invalid-utf8", "metadata-too-complex", "metadata-too-large", "locked", "unreadable", "missing", "changed", "write-not-applied", "association-unknown", "association-conflict", "row-changed", "row-missing", "deferred"]; +export const SKIP_STAGES = ["scan", "plan", "revalidate", "write", "sqlite"]; +const record = (value) => !!value && typeof value === "object" && !Array.isArray(value); +const count = (value) => Number.isSafeInteger(value) && Number(value) >= 0; +const fields = new Set(["total", "rolloutFiles", "sqliteRows", "unconfirmed", "omitted", "retryRecommended", "items"]); +const itemFields = new Set(["kind", "path", "id", "reason", "stage", "retryable"]); +export function isSkipSummary(value) { + if (!record(value) || Object.keys(value).some(key => !fields.has(key)) + || !["total", "rolloutFiles", "sqliteRows", "unconfirmed", "omitted"].every(key => count(value[key])) + || typeof value.retryRecommended !== "boolean" || !Array.isArray(value.items) || value.items.length > 200 + || Number(value.total) !== Number(value.rolloutFiles) + Number(value.sqliteRows) + || Number(value.total) !== value.items.length + Number(value.omitted)) + return false; + if (new TextEncoder().encode(JSON.stringify(value)).length > 1024 * 1024) + return false; + return value.items.every(item => record(item) && Object.keys(item).every(key => itemFields.has(key)) + && ["rollout", "sqlite"].includes(String(item.kind)) + && SKIP_REASONS.includes(item.reason) + && SKIP_STAGES.includes(item.stage) + && typeof item.retryable === "boolean" + && (item.path === undefined || (item.kind === "rollout" && typeof item.path === "string" && item.path.length > 0 && item.path.length <= 32768 && !/[\u0000-\u001f]/.test(item.path))) + && (item.id === undefined || (item.kind === "sqlite" && typeof item.id === "string" && /^[A-Za-z0-9_.:-]{1,128}$/.test(item.id)))); +} +export function publicSkipSummary(value) { + return isSkipSummary(value) ? { ...value, items: value.items.map(item => ({ ...item })) } : undefined; +} +/** Preserve counts/reasons while removing every local file path and row ID. */ +export function redactSkipSummary(value) { + const summary = publicSkipSummary(value); + return summary ? { ...summary, items: summary.items.map(({ kind, reason, stage, retryable }) => ({ kind, reason, stage, retryable })) } : undefined; +} diff --git a/packages/contracts/src/errors.ts b/packages/contracts/src/errors.ts index ea7a79d..3ae62c3 100644 --- a/packages/contracts/src/errors.ts +++ b/packages/contracts/src/errors.ts @@ -14,6 +14,8 @@ export const CORE_ERROR_CODES = [ "SQLITE_UNREADABLE", "ROLLOUT_LOCKED", "ROLLOUT_CHANGED", + "ROLLOUT_METADATA_TOO_LARGE", + "ROLLOUT_METADATA_INVALID", "PENDING_TRANSACTION", "BACKUP_FAILED", "SYNC_FAILED_ROLLED_BACK", @@ -100,6 +102,8 @@ export const PUBLIC_CORE_ERROR_MESSAGES: Readonly> SQLITE_UNREADABLE: "The state database is unreadable or malformed.", ROLLOUT_LOCKED: "One or more rollout files are locked.", ROLLOUT_CHANGED: "One or more rollout files changed during the operation.", + ROLLOUT_METADATA_TOO_LARGE: "Session metadata must stay within 128 MiB before and after syncing. Resolve the oversized header before syncing again.", + ROLLOUT_METADATA_INVALID: "The first rollout record is not valid session metadata. Resolve the invalid header before syncing again.", PENDING_TRANSACTION: "An unfinished transaction must be resolved before another write.", BACKUP_FAILED: "The required backup could not be completed.", SYNC_FAILED_ROLLED_BACK: "The operation failed and its changes were rolled back.", @@ -233,7 +237,7 @@ export function createPublicCoreErrorDto( code, message: PUBLIC_CORE_ERROR_MESSAGES[code], severity: publicSeverity(code), - retryable: true, + retryable: code !== "ROLLOUT_METADATA_TOO_LARGE" && code !== "ROLLOUT_METADATA_INVALID", recoveryRequired: RECOVERY_CODES.has(code), ...(operationId ? { operationId } : {}), ...(details ? { details } : {}) diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 2b4123e..5ad72a0 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -1,5 +1,6 @@ export * from "./dto.js"; export * from "./errors.js"; export * from "./file-update-timing.js"; +export * from "./skip-summary.js"; export * from "./json.js"; export * from "./protocol.js"; diff --git a/packages/contracts/src/protocol.ts b/packages/contracts/src/protocol.ts index 60ed173..4f3b207 100644 --- a/packages/contracts/src/protocol.ts +++ b/packages/contracts/src/protocol.ts @@ -14,6 +14,7 @@ import { type CoreErrorDto, type CoreErrorSeverity } from "./errors.js"; +import { isSkipSummary } from "./skip-summary.js"; import { isFileUpdateTiming } from "./file-update-timing.js"; export interface CoreRequestEnvelope { @@ -647,6 +648,7 @@ export function assertCoreMethodOutput( || !isNonEmptyString(profile.id) || !isNonEmptyString(profile.revision) || !isNonEmptyString(status.currentProvider) + || (status.skipSummary !== undefined && !isSkipSummary(status.skipSummary)) || (status.sessionActivity !== undefined && !isSessionActivity(status.sessionActivity)) || (usage !== undefined && (!isRecord(usage) || Object.keys(usage).sort().join(",") !== "count,state" @@ -727,6 +729,7 @@ export function assertCoreMethodOutput( || !isJsonValue(plan.target) || !isRecord(plan.impact) || !isJsonValue(plan.impact) + || (plan.impact.skipSummary !== undefined && !isSkipSummary(plan.impact.skipSummary)) || (plan.impact.sessionActivity !== undefined && !isSessionActivity(plan.impact.sessionActivity)) || !Array.isArray(plan.warnings) || plan.warnings.some((entry) => typeof entry !== "string") @@ -767,6 +770,9 @@ export function assertCoreMethodOutput( if (!("result" in result) || !isJsonValue(result.result)) { throw new ContractValidationError("INVALID_INPUT", "OperationResult result is required."); } + if (isRecord(result.result) && result.result.skipSummary !== undefined && !isSkipSummary(result.result.skipSummary)) { + throw new ContractValidationError("INVALID_INPUT", "Invalid skip summary."); + } if (isRecord(result.result) && result.result.fileUpdateTiming !== undefined && !isFileUpdateTiming(result.result.fileUpdateTiming)) { throw new ContractValidationError("INVALID_INPUT", "Invalid file update timing."); } diff --git a/packages/contracts/src/skip-summary.ts b/packages/contracts/src/skip-summary.ts new file mode 100644 index 0000000..298b215 --- /dev/null +++ b/packages/contracts/src/skip-summary.ts @@ -0,0 +1,47 @@ +/** Local operation detail. Diagnostic exports must use redactSkipSummary. */ +export const SKIP_REASONS = ["metadata-invalid", "metadata-invalid-utf8", "metadata-too-complex", "metadata-too-large", "locked", "unreadable", "missing", "changed", "write-not-applied", "association-unknown", "association-conflict", "row-changed", "row-missing", "deferred"] as const; +export const SKIP_STAGES = ["scan", "plan", "revalidate", "write", "sqlite"] as const; +export interface SkipItem { + kind: "rollout" | "sqlite"; + path?: string; + id?: string; + reason: typeof SKIP_REASONS[number]; + stage: typeof SKIP_STAGES[number]; + retryable: boolean; +} +export interface SkipSummary { + total: number; + rolloutFiles: number; + sqliteRows: number; + unconfirmed: number; + omitted: number; + retryRecommended: boolean; + items: SkipItem[]; +} +const record = (value: unknown): value is Record => !!value && typeof value === "object" && !Array.isArray(value); +const count = (value: unknown) => Number.isSafeInteger(value) && Number(value) >= 0; +const fields = new Set(["total", "rolloutFiles", "sqliteRows", "unconfirmed", "omitted", "retryRecommended", "items"]); +const itemFields = new Set(["kind", "path", "id", "reason", "stage", "retryable"]); +export function isSkipSummary(value: unknown): value is SkipSummary { + if (!record(value) || Object.keys(value).some(key => !fields.has(key)) + || !["total", "rolloutFiles", "sqliteRows", "unconfirmed", "omitted"].every(key => count(value[key])) + || typeof value.retryRecommended !== "boolean" || !Array.isArray(value.items) || value.items.length > 200 + || Number(value.total) !== Number(value.rolloutFiles) + Number(value.sqliteRows) + || Number(value.total) !== value.items.length + Number(value.omitted)) return false; + if (new TextEncoder().encode(JSON.stringify(value)).length > 1024 * 1024) return false; + return value.items.every(item => record(item) && Object.keys(item).every(key => itemFields.has(key)) + && ["rollout", "sqlite"].includes(String(item.kind)) + && SKIP_REASONS.includes(item.reason as SkipItem["reason"]) + && SKIP_STAGES.includes(item.stage as SkipItem["stage"]) + && typeof item.retryable === "boolean" + && (item.path === undefined || (item.kind === "rollout" && typeof item.path === "string" && item.path.length > 0 && item.path.length <= 32768 && !/[\u0000-\u001f]/.test(item.path))) + && (item.id === undefined || (item.kind === "sqlite" && typeof item.id === "string" && /^[A-Za-z0-9_.:-]{1,128}$/.test(item.id)))); +} +export function publicSkipSummary(value: unknown): SkipSummary | undefined { + return isSkipSummary(value) ? { ...value, items: value.items.map(item => ({ ...item })) } : undefined; +} +/** Preserve counts/reasons while removing every local file path and row ID. */ +export function redactSkipSummary(value: unknown): SkipSummary | undefined { + const summary = publicSkipSummary(value); + return summary ? { ...summary, items: summary.items.map(({ kind, reason, stage, retryable }) => ({ kind, reason, stage, retryable })) } : undefined; +} diff --git a/packages/core/src/application/operation-result.js b/packages/core/src/application/operation-result.js index 75db533..31c352d 100644 --- a/packages/core/src/application/operation-result.js +++ b/packages/core/src/application/operation-result.js @@ -7,6 +7,7 @@ export function operationWarnings(result) { result?.partialWarning, result?.autoPruneWarning, result?.backupInventoryWarning, + result?.backupScopeWarning, result?.modelSync?.warning, ...(Array.isArray(result?.restoreWarnings) ? result.restoreWarnings : []) ].filter((warning) => typeof warning === "string" && warning.trim()); diff --git a/packages/core/src/application/ordinary-write-runtime.js b/packages/core/src/application/ordinary-write-runtime.js index 884c9a6..6277140 100644 --- a/packages/core/src/application/ordinary-write-runtime.js +++ b/packages/core/src/application/ordinary-write-runtime.js @@ -139,6 +139,7 @@ export async function executeOrdinaryWrite({ platform, faultInjector, signal, + expectedPlanState, emitProgress: (event) => emitProgress(onProgress, event), markMutation() { state.mutationStarted = true; @@ -205,11 +206,13 @@ export async function executeOrdinaryWrite({ } } } catch (error) { + await program.finalize?.({ context, state, error }); if (!state.mutationStarted) throw error; await tryRefreshBackupInventory(state.backupDir); return await program.toResult({ context, state, outcome: "partial", error }); } + await program.finalize?.({ context, state, error: null }); try { await undoBackup.refreshInventory(state.backupDir, { faultInjector }); } catch { diff --git a/packages/core/src/application/plan-context.js b/packages/core/src/application/plan-context.js index e826563..37e211b 100644 --- a/packages/core/src/application/plan-context.js +++ b/packages/core/src/application/plan-context.js @@ -58,8 +58,9 @@ export async function verifyExpectedPlanState({ backupDir, rolloutRevisionMode: expectedPlanState.rolloutRevisionMode ?? "content", minimumRolloutSizes: expectedPlanState.revisions.providerRolloutSizes, + providerScoped: Boolean(expectedPlanState.providerScope), platform - }); + }, expectedPlanState.providerScope ? { revision: expectedPlanState.revisions.rolloutRevision } : null); const reason = revisionMismatch(expectedPlanState.revisions, actual); if (reason) { throw new CoreError("STALE_STATE", "Protected state changed after the operation was prepared.", { @@ -112,7 +113,7 @@ export async function preparePlanContext(options, operation, { backupDir = null, // Actual write targets are still probed separately by the use case. includeSessionActivity: operation === "sync" || operation === "switch", platform: options.platform - }, providerFacts ? { ...providerFacts.scan, incompletePaths: [] } : null)); + }, providerFacts ? providerFacts.scan : null)); const rolloutRevisionMode = (operation === "sync" || operation === "switch" ? "provider" : options.rolloutRevisionMode) ?? (options.rolloutScanMode === "full" ? "content" : "metadata"); const revisions = await withFailureStage("prepare_revisions", () => captureOperationRevisions({ @@ -122,9 +123,10 @@ export async function preparePlanContext(options, operation, { backupDir = null, storage, backupDir, rolloutRevisionMode, + providerScoped: Boolean(providerFacts), platform: options.platform }, providerFacts?.rollout)); operationCoordinator.cacheStatus(codexHome, status, options.platform); return { codexHome, sqliteHome, configText, storage, profile, revisions, status, rolloutRevisionMode, - providerScan: providerFacts?.scan }; + providerScan: providerFacts?.scan, providerFiles: providerFacts?.rollout.fileBindings }; } diff --git a/packages/core/src/application/provider-sync.js b/packages/core/src/application/provider-sync.js index 6a59fd8..d7a433b 100644 --- a/packages/core/src/application/provider-sync.js +++ b/packages/core/src/application/provider-sync.js @@ -7,21 +7,21 @@ import { withFailureStage, isConfiguredSqliteHome, missingConfiguredStateDbError, - codexStorage + codexStorage, + summarizeSkips, rolloutSkip, uniqueSkips, selectProviderRows, updateSessionBackupManifest } from "../infrastructure/node-core-ports.js"; import { executeOrdinaryWrite } from "./ordinary-write-runtime.js"; import { preparePlanContext } from "./plan-context.js"; -import { sqliteProviderRowsToChange } from "./provider-counts.js"; import { inspectSessionUsage } from "./session-usage.js"; import { operationRuntime, sqliteTransaction } from "./runtime-context.js"; const { applySessionChanges, - collectProviderChanges, + collectProviderPreparationFacts, summarizeProviderCounts } = codexStorage.sessions; const { readCurrentProviderFromConfigText, configDeclaresProvider } = codexStorage.config; -const { assertSqliteWritable, readSqliteProviderCounts } = codexStorage.stateDb; +const { assertSqliteWritable, readSqliteProviderCounts, readSqliteProviderRevisionState } = codexStorage.stateDb; function assertConfiguredProvider(configText, provider) { if (!configDeclaresProvider(configText, provider)) { @@ -47,25 +47,31 @@ function sortedUnique(paths) { } function providerResult({ context, state, current, targetProvider, scan, initiallySkipped, outcome, error }) { - const applyResult = state.outputs.rollout ?? { + const applyResult = state.outputs.rollout ?? state.data.rolloutResult ?? { appliedChanges: 0, inPlaceChanges: 0, skippedLockedPaths: [], skippedChangedPaths: [] }; - const sqliteResult = state.outputs.sqlite ?? emptySqliteMutationResult(Boolean(context.storage.stateDbLocation)); + const sqliteResult = state.outputs.sqlite ?? state.data.sqliteResult ?? emptySqliteMutationResult(Boolean(context.storage.stateDbLocation)); const skippedLockedRolloutFiles = sortedUnique([ ...initiallySkipped, ...(applyResult.skippedLockedPaths ?? []) ]); - const skippedChangedRolloutFiles = sortedUnique(applyResult.skippedChangedPaths ?? []); - const partialFromSessions = skippedLockedRolloutFiles.length > 0 || skippedChangedRolloutFiles.length > 0; + const skippedChangedRolloutFiles = sortedUnique([...(scan.skippedItems ?? []).filter(item => ["changed", "missing"].includes(item.reason)).map(item => item.path), ...(applyResult.skippedChangedPaths ?? [])]); + const skipSummary = summarizeSkips([...(scan.skippedItems ?? []), + ...initiallySkipped.map(filePath => rolloutSkip(filePath, "locked", "revalidate")), + ...(state.data.skippedItems ?? []), ...(sqliteResult.skippedItems ?? [])], (state.data.unconfirmed ?? 0) + (state.data.sqliteUnconfirmed ?? 0)); + const partialFromSessions = skipSummary.total > 0; const partialFailure = outcome === "partial"; return { codexHome: context.codexHome, sqliteHome: context.storage.sqliteHome, sqliteHomeSource: context.storage.sqliteHomeSource, targetProvider, + configUpdated: state.outputs.config?.updated === true || state.data.configUpdated === true, + skipSummary, + unconfirmedSessionFiles: state.data.unconfirmed ?? 0, previousProvider: current.provider, backupDir: state.backupDir, backupDurationMs: state.backupDurationMs, @@ -83,8 +89,8 @@ function providerResult({ context, state, current, targetProvider, scan, initial partial: partialFromSessions, partialReason: skippedLockedRolloutFiles.length > 0 ? "locked-session" - : (skippedChangedRolloutFiles.length > 0 ? "rollout-changed" : null), - retryRecommended: partialFromSessions + : (skippedChangedRolloutFiles.length > 0 ? "rollout-changed" : (partialFromSessions ? "skipped-data" : null)), + retryRecommended: skipSummary.retryRecommended }), changedSessionFiles: applyResult.appliedChanges ?? 0, inPlaceSessionFiles: applyResult.inPlaceChanges ?? 0, @@ -97,6 +103,7 @@ function providerResult({ context, state, current, targetProvider, scan, initial rolloutCountsBefore: summarizeProviderCounts(scan.providerCounts), autoPruneResult: state.autoPruneResult, backupInventoryWarning: state.backupInventoryWarning, + backupScopeWarning: state.data.backupScopeWarning ?? null, autoPruneWarning: state.autoPruneWarning }; } @@ -119,7 +126,10 @@ export async function buildProviderWriteProgram(context, settings = {}) { assertConfiguredProvider(context.configText, targetProvider); context.emitProgress({ stage: "scan_rollout_files", status: "start" }); - const scan = await withFailureStage("scan_rollout_files", () => collectProviderChanges(context.codexHome, targetProvider, { skipLockedReads: true })); + const facts = await withFailureStage("scan_rollout_files", () => collectProviderPreparationFacts(context.codexHome, targetProvider, { + expectedFiles: context.expectedPlanState?.providerScope?.files ?? null + })); + const scan = facts.scan; context.emitProgress({ stage: "check_locked_rollout_files", status: "start" }); const { writableChanges, lockedPaths: initiallySkipped } = await withFailureStage("check_locked_rollout_files", () => inspectSessionUsage(scan)); context.emitProgress({ @@ -138,7 +148,34 @@ export async function buildProviderWriteProgram(context, settings = {}) { const sqliteCounts = context.storage.stateDbLocation ? await withFailureStage("preflight_sqlite", () => readSqliteProviderCounts(context.storage)) : null; - const sqliteRowsToWrite = sqliteProviderRowsToChange(sqliteCounts, targetProvider); + const sqliteState = context.expectedPlanState?.providerScope?.sqliteState + ?? (context.storage.stateDbLocation ? await readSqliteProviderRevisionState(context.storage.stateDbLocation.path) : { rows: [] }); + const selection = selectProviderRows(context.codexHome, scan, sqliteState, targetProvider, + initiallySkipped.map(filePath => rolloutSkip(filePath, "locked", "revalidate"))); + if (context.expectedPlanState?.providerScope?.eligibleRowIds) { + const eligible = new Set(context.expectedPlanState.providerScope.eligibleRowIds); + selection.rows = selection.rows.filter(row => eligible.has(String(row.id))); + } + const expectedRowIds = new Set(sqliteState.rows.map(row => String(row.id))); + if (context.expectedPlanState?.providerScope && context.storage.stateDbLocation) { + const currentState = await readSqliteProviderRevisionState(context.storage.stateDbLocation.path); + if (currentState.schema !== sqliteState.schema || JSON.stringify(currentState.identity) !== JSON.stringify(sqliteState.identity)) { + throw new CoreError("STALE_STATE", "The thread index changed before backup.", { details: { reason: "state-db" } }); + } + for (const row of currentState.rows) if (!expectedRowIds.has(String(row.id)) && row.model_provider !== targetProvider) { + selection.skippedItems.push({ kind: "sqlite", id: String(row.id), reason: "deferred", stage: "revalidate", retryable: true }); + } + } + const sqliteRowsToWrite = selection.rows.length; + selection.skippedItems.push(...(context.expectedPlanState?.providerScope?.excludedRows ?? [])); + const initialSkips = uniqueSkips([...(scan.skippedItems ?? []), + ...initiallySkipped.map(filePath => rolloutSkip(filePath, "locked", "revalidate")), ...selection.skippedItems]); + const initialSummary = summarizeSkips(initialSkips); + const definitelyUnwritten = new Set(writableChanges.map(change => change.path)); + const attemptedPaths = new Set(); + const appliedPaths = new Set(); + const writeSkips = []; + const partialRollout = { appliedChanges: 0, inPlaceChanges: 0, appliedPaths: [], skippedPaths: [], skippedLockedPaths: [], skippedChangedPaths: [] }; const targetKinds = { config: Boolean(configStep), rollout: writableChanges.length > 0, @@ -168,15 +205,18 @@ export async function buildProviderWriteProgram(context, settings = {}) { previousProvider: current.provider, backupDir: null, backupDurationMs: 0, - noop: initiallySkipped.length === 0, - partial: initiallySkipped.length > 0, - partialReason: initiallySkipped.length > 0 ? "locked-session" : null, - retryRecommended: initiallySkipped.length > 0, + noop: initialSummary.total === 0, + partial: initialSummary.total > 0, + partialReason: initialSummary.total > 0 ? "skipped-data" : null, + retryRecommended: initialSummary.retryRecommended, + skipSummary: initialSummary, + configUpdated: false, + unconfirmedSessionFiles: 0, changedSessionFiles: 0, inPlaceSessionFiles: 0, rewrittenSessionFiles: 0, skippedLockedRolloutFiles: initiallySkipped, - skippedChangedRolloutFiles: [], + skippedChangedRolloutFiles: (scan.skippedItems ?? []).filter(item => ["changed", "missing"].includes(item.reason)).map(item => item.path), sqliteRowsUpdated: 0, sqliteProviderRowsUpdated: 0, sqlitePresent: Boolean(context.storage.stateDbLocation), @@ -191,9 +231,10 @@ export async function buildProviderWriteProgram(context, settings = {}) { stage: "update_config", start: configStep.start, complete: configStep.complete, - run: async ({ context: writeContext }) => { + run: async ({ context: writeContext, state }) => { await configStep.run({ context: writeContext }); writeContext.markMutation(); + state.data.configUpdated = true; await writeContext.faultInjector?.({ point: "after_config_mutation_before_applied", path: writeContext.configPath @@ -212,20 +253,46 @@ export async function buildProviderWriteProgram(context, settings = {}) { appliedChanges: result.appliedChanges, skippedChanges: result.skippedPaths.length }), - run: ({ context: writeContext, state }) => applySessionChanges(writableChanges, { - onTiming: (timing) => { state.data.fileUpdateTiming = timing; }, - onBeforeApply: (change) => writeContext.faultInjector?.({ point: "before_rollout_apply", path: change.path }), - onMutation: (change, mutation) => { - writeContext.markMutation(); - return writeContext.faultInjector?.({ - point: "after_rollout_mutation_before_applied", - path: change.path, - mutation + run: async ({ context: writeContext, state }) => { + state.data.rolloutResult = partialRollout; + state.data.skippedItems = [...selection.skippedItems, ...writeSkips]; + try { + return await applySessionChanges(writableChanges, { + onTiming: timing => { state.data.fileUpdateTiming = timing; }, + onBeforeApply: async change => { + await writeContext.faultInjector?.({ point: "before_rollout_apply", path: change.path }); + attemptedPaths.add(change.path); + definitelyUnwritten.delete(change.path); + }, + onMutation: async (change, mutation) => { + appliedPaths.add(change.path); + partialRollout.appliedPaths.push(change.path); + partialRollout.appliedChanges += 1; + if (mutation.result === "APPLIED_IN_PLACE") partialRollout.inPlaceChanges += 1; + writeContext.markMutation(); + await writeContext.faultInjector?.({ point: "after_rollout_mutation_before_applied", path: change.path, mutation }); + }, + onUnwritten: change => { definitelyUnwritten.add(change.path); }, + onApplied: change => writeContext.faultInjector?.({ point: "after_rollout_apply", path: change.path }), + onSkipped: async (change, result) => { + definitelyUnwritten.add(change.path); + const reason = result === "SKIP_BUSY" ? "locked" : result === "SKIP_MISSING" ? "missing" + : result === "SKIP_UNREADABLE" ? "unreadable" : result === "SKIP_NOT_APPLIED" ? "write-not-applied" : "changed"; + const skip = rolloutSkip(change.path, reason, "write", change.threadId); + writeSkips.push(skip); + state.data.skippedItems.push(skip); + partialRollout.skippedPaths.push(change.path); + if (reason === "locked") partialRollout.skippedLockedPaths.push(change.path); + if (reason === "changed" || reason === "missing") partialRollout.skippedChangedPaths.push(change.path); + await writeContext.faultInjector?.({ point: "after_rollout_skip", path: change.path, reason: result }); + } }); - }, - onApplied: (change) => writeContext.faultInjector?.({ point: "after_rollout_apply", path: change.path }), - onSkipped: (change, reason) => writeContext.faultInjector?.({ point: "after_rollout_skip", path: change.path, reason }) - }) + } catch (error) { + state.data.unconfirmed = [...attemptedPaths].filter(filePath => !appliedPaths.has(filePath) && !definitelyUnwritten.has(filePath)).length; + if (state.data.unconfirmed > 0) writeContext.markMutation(); + throw error; + } + } } } : {}), @@ -234,14 +301,27 @@ export async function buildProviderWriteProgram(context, settings = {}) { sqlite: { stage: "update_sqlite", complete: (result) => ({ updatedRows: result.updatedRows }), - run: async ({ context: writeContext }) => { + run: async ({ context: writeContext, state }) => { + const finalSelection = selectProviderRows(context.codexHome, scan, sqliteState, targetProvider, + [...initiallySkipped.map(filePath => rolloutSkip(filePath, "locked", "revalidate")), ...writeSkips]); + const eligible = new Set(selection.rows.map(row => String(row.id))); + finalSelection.rows = finalSelection.rows.filter(row => eligible.has(String(row.id))); + state.data.skippedItems = uniqueSkips([...(state.data.skippedItems ?? []), ...selection.skippedItems, ...finalSelection.skippedItems]); const result = await sqliteTransaction.updateProvider(writeContext.storage, targetProvider, { busyTimeoutMs: writeContext.sqliteBusyTimeoutMs, - onCommitAttempt: () => writeContext.markMutation(), - afterCommit: () => writeContext.faultInjector?.({ - point: "after_sqlite_commit_before_ack", - path: writeContext.storage.stateDbLocation?.path ?? null - }) + plannedRows: finalSelection.rows, + expectedSchema: sqliteState.schema, + expectedIdentity: sqliteState.identity, + expectedRowIds: [...expectedRowIds], + onCommitAttempt: result => { + state.data.sqliteUnconfirmed = result.updatedRows; + if (result.updatedRows > 0) writeContext.markMutation(); + }, + afterCommit: async result => { + state.data.sqliteUnconfirmed = 0; + state.data.sqliteResult = result; + await writeContext.faultInjector?.({ point: "after_sqlite_commit_before_ack", path: writeContext.storage.stateDbLocation?.path ?? null }); + } }); await writeContext.faultInjector?.({ point: "after_sqlite_commit", @@ -253,6 +333,15 @@ export async function buildProviderWriteProgram(context, settings = {}) { } : {}) }, + finalize: async ({ state }) => { + state.data.skippedItems = uniqueSkips([...(state.data.skippedItems ?? []), ...selection.skippedItems]); + if (!state.backupDir || writableChanges.length === 0) return; + try { + await updateSessionBackupManifest(state.backupDir, writableChanges.filter(change => !definitelyUnwritten.has(change.path))); + } catch { + state.data.backupScopeWarning = "Backup restore scope could not be narrowed; conservative restore coverage remains."; + } + }, toResult: ({ state, outcome, error }) => providerResult({ context, state, @@ -305,7 +394,16 @@ export async function prepareProviderPlan(operation, options, switchIntent = nul } if (switchIntent?.modelSync.warning) warnings.push(switchIntent.modelSync.warning); - const sqliteRowsToChange = sqliteProviderRowsToChange(context.status.sqliteCounts, targetProvider); + const sqliteState = context.storage.stateDbLocation + ? await readSqliteProviderRevisionState(context.storage.stateDbLocation.path) : { rows: [] }; + const selection = selectProviderRows(context.codexHome, scan, sqliteState, targetProvider, + lockedPaths.map(filePath => rolloutSkip(filePath, "locked", "plan"))); + const skipSummary = summarizeSkips([...(scan.skippedItems ?? []), + ...lockedPaths.map(filePath => rolloutSkip(filePath, "locked", "plan")), ...selection.skippedItems]); + const sqliteRowsToChange = selection.rows.length; + const lockedSet = new Set(lockedPaths); + const providerFiles = context.providerFiles.map(file => lockedSet.has(file.path) + ? { ...file, skip: file.skip ?? rolloutSkip(file.path, "locked", "plan", file.id) } : file); const summary = { profile: { id: context.profile.id, revision: context.profile.revision }, storageRevision: context.revisions.storageRevision, @@ -325,6 +423,7 @@ export async function prepareProviderPlan(operation, options, switchIntent = nul }, impact: { rolloutFilesToChange: writableChanges.length, + skipSummary, sqliteRowsToChange, lockedRolloutFiles: lockedCount, sessionActivity: context.status.sessionActivity, @@ -366,7 +465,8 @@ export async function prepareProviderPlan(operation, options, switchIntent = nul profile: context.profile, profileResolver: options.profileResolver, revisions: context.revisions, - rolloutRevisionMode: context.rolloutRevisionMode + rolloutRevisionMode: context.rolloutRevisionMode, + providerScope: { files: providerFiles, sqliteState, eligibleRowIds: selection.rows.map(row => String(row.id)), excludedRows: selection.skippedItems } }, statusOptions: { codexHome: context.codexHome, diff --git a/packages/core/src/application/status.js b/packages/core/src/application/status.js index 1fff6a0..ef9e86d 100644 --- a/packages/core/src/application/status.js +++ b/packages/core/src/application/status.js @@ -202,6 +202,7 @@ export async function scanStatus({ pendingRecovery: pendingTransactions.some((transaction) => transaction.operationKind === "restore"), operationInProgress: null, rolloutScanComplete: lockedPaths.length === 0 && incompletePaths.length === 0, + ...(rolloutScan.skipSummary ? { skipSummary: rolloutScan.skipSummary } : {}), pendingTransactions: pendingTransactions.map((transaction) => ({ operationId: transaction.operationId ?? null, operationKind: transaction.operationKind ?? "sync", diff --git a/packages/core/src/application/watch-runtime.js b/packages/core/src/application/watch-runtime.js index 081bebc..82f5ac5 100644 --- a/packages/core/src/application/watch-runtime.js +++ b/packages/core/src/application/watch-runtime.js @@ -303,13 +303,14 @@ export async function runWatch({ ...(typeof result.failureCode === "string" ? { failureCode: result.failureCode } : {}), ...(typeof result.partialReason === "string" ? { partialReason: result.partialReason } : {}), ...(typeof result.retryRecommended === "boolean" ? { retryRecommended: result.retryRecommended } : {}), + ...(result.skipSummary ? { skipSummary: result.skipSummary } : {}), changedSessionFiles: Number(result.changedSessionFiles) || 0, ...(publicFileUpdateTiming(result.fileUpdateTiming) ? { fileUpdateTiming: publicFileUpdateTiming(result.fileUpdateTiming) } : {}), sqliteRowsUpdated: Number(result.sqliteRowsUpdated) || 0, skippedLockedRolloutFiles: Number(result.skippedLockedRolloutFiles?.length) || 0, finishedAt: new Date().toISOString() }); - log(`[${new Date().toISOString()}] Sync complete: provider=${result.targetProvider}, rollout_files=${result.changedSessionFiles}, sqlite_rows=${result.sqliteRowsUpdated}${result.skippedLockedRolloutFiles?.length ? `, skipped_locked=${result.skippedLockedRolloutFiles.length}` : ""}`); + log(`[${new Date().toISOString()}] Sync ${result.partial ? "partial" : "complete"}: provider=${result.targetProvider}, rollout_files=${result.changedSessionFiles}, sqlite_rows=${result.sqliteRowsUpdated}${result.skipSummary?.total ? `, skipped=${result.skipSummary.total}, unconfirmed=${result.skipSummary.unconfirmed}${result.retryRecommended ? ", retry after activity settles" : ", fix reported data before retrying"}` : ""}`); // A successful sync resets the consecutive-failure counter // so a transient error followed by recovery does not // poison subsequent invocations. diff --git a/packages/core/src/index.js b/packages/core/src/index.js index 651dd36..8579267 100644 --- a/packages/core/src/index.js +++ b/packages/core/src/index.js @@ -4,7 +4,7 @@ // application/ and storage adapters live in infrastructure/. import { createHash } from "node:crypto"; import path from "node:path"; -import { publicFileUpdateTiming } from "../../contracts/dist/index.js"; +import { publicFileUpdateTiming, publicSkipSummary } from "../../contracts/dist/index.js"; import { createCoreApplication } from "./application/core-application.js"; import { toPublicProgress } from "./progress.js"; @@ -34,6 +34,7 @@ import { CoreError, publicHistoryIntegrity } from "./infrastructure/node-core-po * changedSessionFiles?: number, * sqliteRowsUpdated?: number, * skippedLockedRolloutFiles?: number + * skipSummary?: import("../../contracts/dist/index.js").SkipSummary, * fileUpdateTiming?: import("../../contracts/dist/index.js").FileUpdateTiming * }} WatchActivityEvent */ /** @typedef {{schemaVersion: 1, watchId: string, status: "stopped", startedAt: string, stoppedAt: string, stopReason: string, includeStateDb: boolean, once: boolean}} WatchStoppedSnapshot */ @@ -353,6 +354,7 @@ function publicStatus(value, includeLocalDisplayPaths = false) { ...(value.staleLockDetected === true ? { staleLockDetected: true } : {}), rolloutScanComplete: value.rolloutScanComplete === true && locked.length === 0, lockedRolloutFiles: locked, + ...(publicSkipSummary(value.skipSummary) ? { skipSummary: publicSkipSummary(value.skipSummary) } : {}), currentProviderImplicit: value.currentProviderImplicit === true, configuredProviders: Array.isArray(value.configuredProviders) ? value.configuredProviders.filter((entry) => typeof entry === "string") @@ -409,6 +411,7 @@ function publicPlan(value) { } /** @type {Record} */ const publicImpact = {}; + if (publicSkipSummary(impact.skipSummary)) publicImpact.skipSummary = publicSkipSummary(impact.skipSummary); if (isRecord(impact.sessionActivity)) publicImpact.sessionActivity = publicSessionActivity(impact.sessionActivity); for (const [key, candidate] of Object.entries(impact)) { if (typeof candidate === "boolean" || (Number.isSafeInteger(candidate) && Number(candidate) >= 0)) { @@ -464,6 +467,8 @@ function publicOperationResult(value) { const source = isRecord(value.result) ? value.result : {}; /** @type {Record} */ const result = {}; + const skipSummary = publicSkipSummary(source.skipSummary); + if (skipSummary) result.skipSummary = skipSummary; const fileUpdateTiming = publicFileUpdateTiming(source.fileUpdateTiming); if (fileUpdateTiming) result.fileUpdateTiming = fileUpdateTiming; for (const key of [ @@ -486,7 +491,7 @@ function publicOperationResult(value) { if (typeof source.commitAcknowledgementRecovered === "boolean") { result.commitAcknowledgementRecovered = source.commitAcknowledgementRecovered; } - for (const key of ["noop", "retryRecommended"]) { + for (const key of ["noop", "retryRecommended", "configUpdated"]) { if (typeof source[key] === "boolean") result[key] = source[key]; } if (Array.isArray(source.resolvedOperationIds)) { @@ -495,6 +500,7 @@ function publicOperationResult(value) { } for (const key of [ "backupDurationMs", + "unconfirmedSessionFiles", "changedSessionFiles", "inPlaceSessionFiles", "rewrittenSessionFiles", diff --git a/packages/core/src/infrastructure/node-core-ports.js b/packages/core/src/infrastructure/node-core-ports.js index 9192a1e..f12edce 100644 --- a/packages/core/src/infrastructure/node-core-ports.js +++ b/packages/core/src/infrastructure/node-core-ports.js @@ -12,6 +12,7 @@ import { defaultBackupRoot } from "../../../../src/constants.js"; import { CoreError } from "../../../../src/core-error.js"; +export { summarizeSkips, rolloutSkip, uniqueSkips, selectProviderRows, providerPathKey } from "../../../../src/provider-skips.js"; export { annotateFailureStage, withFailureStage } from "../../../../src/core-error.js"; import { configDeclaresProvider, @@ -32,6 +33,7 @@ import { listBackups, pruneBackups as pruneManagedBackups, refreshBackupInventory, + updateSessionBackupManifest, resolveRestoreStateDbTargetPath, restoreBackup } from "../../../../src/backup.js"; @@ -68,6 +70,7 @@ import { assertSqliteWritable, detectStateDb, readSqliteProviderCounts, + readSqliteProviderRevisionState, readSqliteRepairStats, updateSqliteProvider } from "../../../../src/sqlite-state.js"; @@ -138,6 +141,7 @@ export const codexStorage = createCodexStorage({ assertSqliteWritable, detectStateDb, readSqliteProviderCounts, + readSqliteProviderRevisionState, readSqliteRepairStats, updateSqliteProvider }, @@ -163,6 +167,7 @@ export { listBackups, pruneManagedBackups, refreshBackupInventory, + updateSessionBackupManifest, resolveRestoreStateDbTargetPath, restoreBackup, acquireLock, diff --git a/src/backup.js b/src/backup.js index 21e8363..c69cbf0 100644 --- a/src/backup.js +++ b/src/backup.js @@ -223,7 +223,10 @@ async function assertNoLinkedPathSegments(root, target) { } } -async function validateSessionManifestEntries(entries, codexHome) { +async function validateSessionManifestEntries(entries, codexHome, physicalEntries = null) { + if (!Array.isArray(entries)) throw new Error("Backup session manifest has invalid entries."); + const physical = physicalEntries ? new Set(physicalEntries.map(entry => pathComparisonKey(entry.path))) : null; + const lexicalSeen = new Set(); const roots = ["sessions", "archived_sessions"].map((name) => path.resolve(codexHome, name)); const canonicalRoots = (await Promise.all(roots.map(async (root) => { try { @@ -249,6 +252,19 @@ async function validateSessionManifestEntries(entries, codexHome) { if (!rawRoot) { throw new Error(`Backup session target is outside the allowed rollout roots: ${entry.path}`); } + const lexicalKey = pathComparisonKey(target); + if (lexicalSeen.has(lexicalKey)) throw new Error("Backup session manifest contains a duplicate rollout target."); + lexicalSeen.add(lexicalKey); + if (entry.mutation) { + if (entry.modelOnlyChange) throw new Error("Provider byte mutation cannot describe a model-only change."); + validateProviderMutationDescriptor(entry.mutation, entry.path, entry.originalFirstLine, entry.originalSeparator); + } + if (physical && !physical.has(lexicalKey)) { + // Excluded entries retain syntax/boundary validation, but need not still + // exist: they were positively acknowledged as never written. + if (!roots.some(root => pathIsWithin(root, target))) throw new Error("Excluded rollout target is outside the backup Home."); + continue; + } await assertNoLinkedPathSegments(rawRoot, target); const [canonicalRawRoot, canonicalTarget] = await Promise.all([ fs.realpath(rawRoot), @@ -771,7 +787,9 @@ export async function getBackupRecoveryCoverage(backupDir, storageOrCodexHome) { if (!Array.isArray(sessionManifest.files)) { throw new Error(`Session backup manifest has an invalid files collection: ${sessionManifestPath}`); } - await validateSessionManifestEntries(sessionManifest.files, codexHome); + const selectedEntries = await selectSessionRestoreEntries(backupDir, sessionManifest); + await validateSessionManifestEntries(sessionManifest.files, codexHome, selectedEntries); + sessionManifest = { ...sessionManifest, files: selectedEntries }; } let globalState = false; @@ -854,7 +872,8 @@ export async function restoreBackup(backupDir, storageOrCodexHome, options = {}) || !await storagePathsEqualPhysical(sessionManifest.codexHome, codexHome)) { throw new Error(`Session backup was created for ${sessionManifest.codexHome}, not ${codexHome}.`); } - const validatedEntries = await validateSessionManifestEntries(sessionManifest.files ?? [], codexHome); + const selectedEntries = await selectSessionRestoreEntries(backupDir, sessionManifest); + const validatedEntries = await validateSessionManifestEntries(sessionManifest.files ?? [], codexHome, selectedEntries); if (sessionTargetPaths) { const selected = new Set(sessionTargetPaths.map(pathComparisonKey)); for (const selectedPath of sessionTargetPaths) { @@ -866,7 +885,6 @@ export async function restoreBackup(backupDir, storageOrCodexHome, options = {}) ) .map(({ entry }) => entry); } else { - const selectedEntries = await selectSessionRestoreEntries(backupDir, sessionManifest); const selected = new Set(selectedEntries.map((entry) => pathComparisonKey(entry.path))); sessionRestoreEntries = validatedEntries .filter(({ originalPath }) => selected.has(pathComparisonKey(originalPath))) diff --git a/src/cli-json.js b/src/cli-json.js index c094abb..815e210 100644 --- a/src/cli-json.js +++ b/src/cli-json.js @@ -2,7 +2,7 @@ import path from "node:path"; import { OPERATION_FAILURE_STAGES, SAFE_CAUSE_CODES, - publicFileUpdateTiming + publicFileUpdateTiming, publicSkipSummary } from "../packages/contracts/dist/index.js"; import { publicHistoryIntegrity } from "./history-integrity-dto.js"; @@ -79,6 +79,8 @@ const CLI_ERROR_MESSAGES = Object.freeze({ SQLITE_UNREADABLE: "The state database is unreadable or malformed.", ROLLOUT_LOCKED: "One or more rollout files are locked.", ROLLOUT_CHANGED: "One or more rollout files changed during the operation.", + ROLLOUT_METADATA_TOO_LARGE: "Session metadata must stay within 128 MiB before and after syncing. Resolve the oversized header before syncing again.", + ROLLOUT_METADATA_INVALID: "The first rollout record is not valid session metadata. Resolve the invalid header before syncing again.", PENDING_TRANSACTION: "An unfinished transaction must be resolved before another write.", BACKUP_FAILED: "The required backup could not be completed.", SYNC_FAILED_ROLLED_BACK: "The operation failed and its changes were rolled back.", @@ -244,6 +246,9 @@ function sanitizeModelSync(value) { function sanitizeSyncResult(value) { const result = {}; + put(result, "unconfirmedSessionFiles", safeNumber(value.unconfirmedSessionFiles, { integer: true, minimum: 0 })); + put(result, "skipSummary", publicSkipSummary(value.skipSummary)); + put(result, "configUpdated", typeof value.configUpdated === "boolean" ? value.configUpdated : undefined); put(result, "fileUpdateTiming", publicFileUpdateTiming(value.fileUpdateTiming)); for (const key of ["codexHome", "sqliteHome", "backupDir"]) { put(result, key, safeString(value[key], 32768)); @@ -266,7 +271,7 @@ function sanitizeSyncResult(value) { put(result, "sqlitePresent", safeBoolean(value.sqlitePresent)); put(result, "partial", safeBoolean(value.partial)); putNullable(result, "partialReason", value.partialReason, (entry) => ( - ["locked-session", "rollout-changed", "mutation-failed", "verification-remaining", "verification-unavailable"].includes(entry) ? entry : undefined + ["locked-session", "rollout-changed", "mutation-failed", "skipped-data", "verification-remaining", "verification-unavailable"].includes(entry) ? entry : undefined )); putNullable(result, "failedStage", value.failedStage, (entry) => ( PARTIAL_FAILURE_STAGES.has(entry) ? entry : undefined @@ -279,6 +284,7 @@ function sanitizeSyncResult(value) { put(result, "skippedChangedRolloutFiles", sanitizeFileNameArray(value.skippedChangedRolloutFiles)); put(result, "rolloutCountsBefore", sanitizeDistribution(value.rolloutCountsBefore)); putNullable(result, "autoPruneResult", value.autoPruneResult, sanitizePruneResult); + if (value.backupScopeWarning) result.backupScopeWarning = "Backup restore scope could not be narrowed; exclusions are not confirmed."; if (value.autoPruneWarning) result.autoPruneWarning = WARNING_MESSAGES.autoPruneWarning; else if (value.autoPruneWarning === null) result.autoPruneWarning = null; put(result, "modelSync", sanitizeModelSync(value.modelSync)); @@ -321,6 +327,7 @@ function sanitizeRepairResult(value) { function sanitizeStatusResult(value) { const result = {}; + put(result, "skipSummary", publicSkipSummary(value.skipSummary)); put(result, "schemaVersion", safeNumber(value.schemaVersion, { integer: true, minimum: 1 })); put(result, "snapshotAt", safeString(value.snapshotAt, 64)); put(result, "storageRevision", safeString(value.storageRevision, 256)); @@ -690,7 +697,7 @@ export function normalizeCliErrorDto(dto) { code, message, severity: canonicalErrorSeverity(code), - retryable: true, + retryable: code !== "ROLLOUT_METADATA_TOO_LARGE" && code !== "ROLLOUT_METADATA_INVALID", recoveryRequired: RECOVERY_CODES.has(code), ...(operationId ? { operationId } : {}), ...(details ? { details } : {}) diff --git a/src/cli.js b/src/cli.js index cbe662d..fa5f58b 100755 --- a/src/cli.js +++ b/src/cli.js @@ -1,5 +1,6 @@ #!/usr/bin/env node +import { publicSkipSummary } from "../packages/contracts/dist/index.js"; import fs from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; @@ -283,6 +284,14 @@ function summarizeSync(result, label) { lines.push(`Skipped changed rollout files: ${result.skippedChangedRolloutFiles.length}`); lines.push(`Changed file(s): ${preview}${extraCount > 0 ? ` (+${extraCount} more)` : ""}`); } + const skipped = publicSkipSummary(result.skipSummary); + if (skipped?.total) { + lines.push(`Partial: skipped ${skipped.total} (${skipped.rolloutFiles} files, ${skipped.sqliteRows} rows); unconfirmed ${skipped.unconfirmed}.`); + for (const item of skipped.items) lines.push(`[${item.kind}/${item.stage}/${item.reason}] ${item.path ?? item.id ?? "unidentified"}`); + lines.push(`Showing ${skipped.items.length} of ${skipped.total}; omitted ${skipped.omitted}.`); + if (!skipped.retryRecommended) lines.push("Resolve the listed issues, then prepare again."); + } + if (result.configUpdated) lines.push(`Configuration switched; history files updated: ${result.changedSessionFiles}.`); if (result.retryRecommended) { lines.push(result.partialReason === "locked-session" ? "Retry recommendation: after the active session ends, prepare a fresh operation and retry to converge." @@ -296,6 +305,7 @@ function summarizeSync(result, label) { `Backup cleanup: deleted ${result.autoPruneResult.deletedCount}, remaining ${result.autoPruneResult.remainingCount}, freed ${formatBytes(result.autoPruneResult.freedBytes)}` ); } + if (result.backupScopeWarning) lines.push("Backup warning: restore exclusions could not be confirmed; conservative coverage may remain."); if (result.autoPruneWarning) { lines.push(`Backup cleanup warning: ${result.autoPruneWarning}`); } diff --git a/src/constants.js b/src/constants.js index 84b7f6d..04bdda8 100644 --- a/src/constants.js +++ b/src/constants.js @@ -1,6 +1,8 @@ import os from "node:os"; import path from "node:path"; +export const PROVIDER_SESSION_META_MAX_BYTES = 128 * 1024 * 1024; + export const DEFAULT_PROVIDER = "openai"; export const DEFAULT_LOCK_NAME = "provider-sync.lock"; export const BACKUP_NAMESPACE = "provider-sync"; diff --git a/src/core-error.js b/src/core-error.js index 6dc4c98..963194e 100644 --- a/src/core-error.js +++ b/src/core-error.js @@ -49,6 +49,8 @@ const ERROR_DEFINITIONS = Object.freeze({ SQLITE_BUSY: { severity: "warning", retryable: true, recoveryRequired: false }, SQLITE_UNREADABLE: { severity: "error", retryable: true, recoveryRequired: false }, ROLLOUT_LOCKED: { severity: "warning", retryable: true, recoveryRequired: false }, + ROLLOUT_METADATA_TOO_LARGE: { severity: "error", retryable: false, recoveryRequired: false }, + ROLLOUT_METADATA_INVALID: { severity: "error", retryable: false, recoveryRequired: false }, ROLLOUT_CHANGED: { severity: "warning", retryable: true, recoveryRequired: false }, PENDING_TRANSACTION: { severity: "error", retryable: true, recoveryRequired: true }, BACKUP_FAILED: { severity: "error", retryable: true, recoveryRequired: false }, diff --git a/src/operation-revision.js b/src/operation-revision.js index 6fe05ae..2b87591 100644 --- a/src/operation-revision.js +++ b/src/operation-revision.js @@ -3,6 +3,7 @@ import fs from "node:fs/promises"; import path from "node:path"; import { CoreError } from "./core-error.js"; +import { fileReadSkipReason, rolloutSkip, providerPathKey } from "./provider-skips.js"; import { collectProviderChanges, readProviderRevisionHeader } from "./session-files.js"; import { readSqliteProviderRevisionState } from "./sqlite-state.js"; @@ -64,7 +65,7 @@ async function physicalFileIdentity(filePath, fsImpl, reason) { stats = await fsImpl.lstat(filePath, { bigint: true }); } catch (error) { if (error?.code !== "ENOENT") throw error; - throw new CoreError("STALE_STATE", "A revision target disappeared.", { details: { reason } }); + throw error; } if (!stats.isFile() || stats.isSymbolicLink() || stats.ino === 0n) { throw new CoreError("STALE_STATE", "The revision file identity cannot be verified.", { details: { reason } }); @@ -86,7 +87,7 @@ async function physicalFileIdentity(filePath, fsImpl, reason) { async function captureProviderHeader(filePath, fsImpl, minimumSize, onProviderHeader, allowIncomplete = false) { const before = await physicalFileIdentity(filePath, fsImpl, "rollout"); if (minimumSize !== undefined && BigInt(before.size) < BigInt(minimumSize)) { - throw new CoreError("STALE_STATE", "A planned rollout was truncated.", { details: { reason: "rollout" } }); + throw new CoreError("STALE_STATE", "A planned rollout was truncated.", { details: { reason: "rollout", fileChanged: true } }); } let header; let record; @@ -97,13 +98,14 @@ async function captureProviderHeader(filePath, fsImpl, minimumSize, onProviderHe if (allowIncomplete && error?.name === "RolloutMetadataLimitError") header = { incomplete: true }; else { if (!LOCKED_FILE_CODES.has(error?.code)) throw error; - header = { locked: true, causeCode: error.code }; + const reason = fileReadSkipReason(error); + header = { locked: reason === "locked", skipReason: reason, causeCode: error.code }; } } const after = await physicalFileIdentity(filePath, fsImpl, "rollout"); if (stableStringify(before.identity) !== stableStringify(after.identity) || BigInt(after.size) < BigInt(before.size)) { - throw new CoreError("STALE_STATE", "A planned rollout was replaced or truncated.", { details: { reason: "rollout" } }); + throw new CoreError("STALE_STATE", "A planned rollout was replaced or truncated.", { details: { reason: "rollout", fileChanged: true } }); } onProviderHeader?.(filePath, { record, beforeSnapshot: before.snapshot, afterSnapshot: after.snapshot, @@ -185,12 +187,18 @@ async function captureStableMetadata(filePath, fsImpl, { allowLocked = false } = }); } -async function listRolloutFiles(rootDir, fsImpl) { +async function listRolloutFiles(rootDir, fsImpl, optionalRoot = true) { + try { + const info = await fsImpl.lstat(rootDir); + if (info.isSymbolicLink() || !info.isDirectory()) throw new CoreError("STALE_STATE", "A rollout directory is unsafe.", { details: { reason: "rollout" } }); + } catch (error) { + if (optionalRoot && error?.code === "ENOENT") return []; + throw error; + } let entries; try { entries = await fsImpl.readdir(rootDir, { withFileTypes: true }); } catch (error) { - if (error?.code === "ENOENT") return []; throw error; } entries.sort((left, right) => left.name.localeCompare(right.name)); @@ -198,7 +206,7 @@ async function listRolloutFiles(rootDir, fsImpl) { for (const entry of entries) { const fullPath = path.join(rootDir, entry.name); if (entry.isDirectory()) { - files.push(...await listRolloutFiles(fullPath, fsImpl)); + files.push(...await listRolloutFiles(fullPath, fsImpl, false)); } else if (entry.isFile() && entry.name.startsWith("rollout-") && entry.name.endsWith(".jsonl")) { files.push(fullPath); } else if (entry.isSymbolicLink()) { @@ -210,33 +218,69 @@ async function listRolloutFiles(rootDir, fsImpl) { return files; } -export async function captureRolloutRevision(codexHome, { fsImpl = fs, mode = "content", minimumSizes = {} } = {}, onProviderHeader = undefined) { +export async function captureRolloutRevision(codexHome, { fsImpl = fs, mode = "content", minimumSizes = {}, expectedFiles = null } = {}, onProviderHeader = undefined) { if (!["content", "metadata", "provider", "status"].includes(mode)) { throw new CoreError("INVALID_INPUT", "Unsupported rollout revision mode."); } const manifest = []; const lockedRolloutFiles = []; const observedSizes = {}; + const fileBindings = []; + const seen = new Set(); + const expected = expectedFiles ? new Map(expectedFiles.map(file => [providerPathKey(file.path), file])) : null; for (const scope of SESSION_SCOPES) { const scopeRoot = path.join(codexHome, scope); - for (const filePath of await listRolloutFiles(scopeRoot, fsImpl)) { + const rootPreviouslyPresent = expectedFiles?.some(file => path.relative(codexHome, file.path).split(path.sep)[0] === scope); + for (const filePath of await listRolloutFiles(scopeRoot, fsImpl, !rootPreviouslyPresent)) { const relativePath = path.relative(codexHome, filePath).split(path.sep).join("/"); - const revision = mode === "provider" || mode === "status" - ? await captureProviderHeader(filePath, fsImpl, minimumSizes[relativePath], onProviderHeader, mode === "status") - : mode === "metadata" - ? await captureStableMetadata(filePath, fsImpl, { allowLocked: true }) - : await captureStableFile(filePath, fsImpl, { allowLocked: true }); + const key = providerPathKey(filePath); + seen.add(key); + const prior = expected?.get(key); + let record; + let revision; + if (expected && (!prior || prior.skip)) { + const skip = prior?.skip ?? rolloutSkip(filePath, "deferred", "revalidate"); + revision = { skipped: skip.reason }; + record = { skip }; + } else { + try { + revision = mode === "provider" || mode === "status" + ? await captureProviderHeader(filePath, fsImpl, minimumSizes[relativePath], (_, value) => { record = value; }) + : mode === "metadata" + ? await captureStableMetadata(filePath, fsImpl, { allowLocked: true }) + : await captureStableFile(filePath, fsImpl, { allowLocked: true }); + if (revision.skipReason) record = { skip: rolloutSkip(filePath, revision.skipReason, expected ? "revalidate" : "scan", prior?.id) }; + if (prior && (prior.headerHash !== revision.headerHash || prior.realPath !== revision.realPath + || prior.ino !== revision.ino || prior.dev !== revision.dev || prior.nlink !== revision.nlink + || BigInt(revision.observedSize ?? 0) < BigInt(prior.observedSize ?? 0))) { + record = { skip: rolloutSkip(filePath, "changed", "revalidate", prior.id) }; + } + } catch (error) { + const reason = ["provider", "status"].includes(mode) ? fileReadSkipReason(error) : null; + if (!reason) throw error; + record = { skip: rolloutSkip(filePath, reason, expected ? "revalidate" : "scan", prior?.id) }; + revision = { skipped: reason }; + } + } + onProviderHeader?.(filePath, record); + fileBindings.push({ path: filePath, ...revision, ...(record?.skip ? { skip: record.skip } : {}) }); const { observedSize, ...binding } = revision; if (observedSize !== undefined) observedSizes[relativePath] = observedSize; manifest.push({ path: relativePath, ...binding }); if (revision.locked) lockedRolloutFiles.push(relativePath); } } + if (expected) for (const [key, prior] of expected) if (!seen.has(key)) { + const skip = prior.skip ?? rolloutSkip(prior.path, "missing", "revalidate", prior.id); + onProviderHeader?.(prior.path, { skip }); + fileBindings.push({ ...prior, skip }); + } manifest.sort((left, right) => left.path.localeCompare(right.path)); return { revision: sha256Revision(stableStringify(manifest)), fileCount: manifest.length, - rolloutScanComplete: lockedRolloutFiles.length === 0, + fileBindings, + rolloutScanComplete: lockedRolloutFiles.length === 0 && !fileBindings.some(file => file.skip), lockedRolloutFiles, ...(["provider", "status"].includes(mode) ? { observedSizes } : {}) }; @@ -245,16 +289,22 @@ export async function captureRolloutRevision(codexHome, { fsImpl = fs, mode = "c // Keep the revision reader/manifest authoritative. Its private callback lends // first-line facts to the existing Provider-only collector during this call. // No body read, persistent cache, new manifest algorithm or Apply descriptor. -export async function collectProviderPreparationFacts(codexHome, targetProvider, { fsImpl = fs } = {}) { +export async function collectProviderPreparationFacts(codexHome, targetProvider, { fsImpl = fs, expectedFiles = null } = {}) { const records = new Map(); try { - const rollout = await captureRolloutRevision(codexHome, { fsImpl, mode: "provider" }, + const rollout = await captureRolloutRevision(codexHome, { fsImpl, mode: "provider", expectedFiles }, (filePath, record) => records.set(filePath, record)); const scan = await collectProviderChanges(codexHome, targetProvider, { skipLockedReads: true }, records); + const skips = new Map(scan.skippedItems.map(item => [providerPathKey(item.path), item])); + const files = new Map(scan.files.map(file => [providerPathKey(file.path), file])); + rollout.fileBindings = rollout.fileBindings.map(binding => ({ ...binding, + id: files.get(providerPathKey(binding.path))?.id ?? binding.id ?? null, + ...(skips.has(providerPathKey(binding.path)) ? { skip: skips.get(providerPathKey(binding.path)) } : {}) })); + rollout.rolloutScanComplete = scan.skippedItems.length === 0; return { rollout, scan }; } catch (error) { if (error?.name === "RolloutMetadataLimitError") { - throw new CoreError("ROLLOUT_CHANGED", "Provider sync requires a session metadata header no larger than 1 MiB.", { cause: error }); + throw new CoreError("ROLLOUT_METADATA_TOO_LARGE", "Session metadata exceeds the 128 MiB supported limit.", { cause: error }); } throw error; } finally { @@ -262,7 +312,7 @@ export async function collectProviderPreparationFacts(codexHome, targetProvider, } } -export async function captureStateDbRevision(storage, { fsImpl = fs, platform = process.platform, mode = "content" } = {}) { +export async function captureStateDbRevision(storage, { fsImpl = fs, platform = process.platform, mode = "content", schemaOnly = false } = {}) { const stateDbPath = storage.stateDbLocation?.path ?? null; if (!stateDbPath) { return sha256Revision(stableStringify({ stateDb: null })); @@ -274,7 +324,8 @@ export async function captureStateDbRevision(storage, { fsImpl = fs, platform = // Unsupported WSL remains diagnostic-only; do not open its SQLite database. if (mode === "status" && storage.sqliteAccess?.supported === false) state = { unsupported: true }; else { - try { state = await readSqliteProviderRevisionState(stateDbPath, { includeArchived: mode === "status" }); } + try { state = await readSqliteProviderRevisionState(stateDbPath, { includeArchived: mode === "status" }); + if (schemaOnly) state = { schema: state.schema, key: state.key }; } catch (error) { // Preserve Status's unreadable index presentation, never fabricate healthy counts. if (mode !== "status" || error?.code !== "SQLITE_UNREADABLE") throw error; @@ -366,13 +417,14 @@ export async function captureOperationRevisions({ backupDir = null, rolloutRevisionMode = "content", minimumRolloutSizes = {}, + providerScoped = false, platform = process.platform, fsImpl = fs }, preparedRollout = null) { const configRevision = captureConfigRevision(configText); const [rollout, stateDbRevision, backupRevision] = await Promise.all([ preparedRollout ?? captureRolloutRevision(codexHome, { fsImpl, mode: rolloutRevisionMode, minimumSizes: minimumRolloutSizes }), - captureStateDbRevision(storage, { fsImpl, platform, mode: ["provider", "status"].includes(rolloutRevisionMode) ? rolloutRevisionMode : "content" }), + captureStateDbRevision(storage, { fsImpl, platform, schemaOnly: providerScoped, mode: ["provider", "status"].includes(rolloutRevisionMode) ? rolloutRevisionMode : "content" }), backupDir ? captureBackupRevision(backupDir, { fsImpl }) : Promise.resolve(null) ]); return { diff --git a/src/provider-skips.js b/src/provider-skips.js new file mode 100644 index 0000000..9bad47f --- /dev/null +++ b/src/provider-skips.js @@ -0,0 +1,121 @@ +import path from "node:path"; + +export function rolloutSkip(filePath, reason, stage = "scan", id = null) { + return { kind: "rollout", path: filePath, ...(id ? { id } : {}), reason, stage, + retryable: ["locked", "missing", "changed", "deferred", "write-not-applied"].includes(reason) }; +} + +export function fileReadSkipReason(error) { + if (error?.name === "RolloutMetadataEncodingError") return "metadata-invalid-utf8"; + if (error?.name === "RolloutMetadataLimitError") return "metadata-too-large"; + const code = error?.code === "ROLLOUT_FILE_BUSY" ? error?.cause?.code : error?.code; + if (["EBUSY", "ETXTBSY"].includes(code) || error?.code === "ROLLOUT_FILE_BUSY") return "locked"; + if (["EACCES", "EPERM"].includes(code)) return "unreadable"; + if (code === "ENOENT") return "missing"; + if (error?.details?.fileChanged === true) return "changed"; + return null; +} + +export function providerPathKey(value) { + const normalized = path.resolve(value); + return process.platform === "win32" ? normalized.toLowerCase() : normalized; +} + +export function uniqueSkips(items) { + const unique = new Map(); + for (const item of items ?? []) { + const key = `${item.kind}:${item.kind === "rollout" ? providerPathKey(item.path) : String(item.id)}`; + if (!unique.has(key)) unique.set(key, item); + } + return [...unique.values()]; +} + +export function summarizeSkips(items, unconfirmed = 0) { + const all = uniqueSkips(items); + const details = []; + let detailBytes = 1024; + for (const item of all) { + const detail = { kind: item.kind, reason: item.reason, stage: item.stage, retryable: item.retryable, + ...(item.kind === "rollout" && typeof item.path === "string" && item.path.length <= 32768 && !/[\u0000-\u001f]/.test(item.path) ? { path: item.path } : {}), + ...(item.kind === "sqlite" && /^[A-Za-z0-9_.:-]{1,128}$/.test(item.id) ? { id: item.id } : {}) }; + const bytes = Buffer.byteLength(JSON.stringify(detail), "utf8") + 1; + if (details.length >= 200 || detailBytes + bytes > 1024 * 1024) break; + details.push(detail); detailBytes += bytes; + } + return { total: all.length, rolloutFiles: all.filter(item => item.kind === "rollout").length, + sqliteRows: all.filter(item => item.kind === "sqlite").length, + unconfirmed: unconfirmed + all.filter(item => ["association-unknown", "association-conflict"].includes(item.reason)).length, + omitted: all.length - details.length, retryRecommended: all.some(item => item.retryable), items: details }; +} + +// Resolve only paths within a known rollout tree. No filename-based identity inference. +function rowRolloutPath(home, value) { + if (typeof value !== "string" || !value || value.includes("\0")) return null; + const absolute = path.resolve(home, value); + const relative = path.relative(home, absolute).split(path.sep); + if (!["sessions", "archived_sessions"].includes(relative[0]) || relative.includes("..")) return null; + return providerPathKey(absolute); +} + +export function selectProviderRows(home, scan, state, targetProvider, additionalSkips = []) { + const skipped = uniqueSkips([...(scan.skippedItems ?? []), ...additionalSkips]); + const skippedPaths = new Set(skipped.filter(item => item.kind === "rollout").map(item => providerPathKey(item.path))); + const files = scan.files ?? []; + const byId = new Map(); + const byPath = new Map(files.map(file => [providerPathKey(file.path), file])); + for (const file of files) if (file.id) { + const matches = byId.get(file.id) ?? []; + matches.push(file); byId.set(file.id, matches); + } + for (const item of skipped) if (item.kind === "rollout" && !byPath.has(providerPathKey(item.path))) { + const file = { path: item.path, id: item.id ?? null }; + byPath.set(providerPathKey(item.path), file); + if (file.id) { const matches = byId.get(file.id) ?? []; matches.push(file); byId.set(file.id, matches); } + } + const rowMatches = new Map(); + const ownersByPath = new Map(); + const associatedBadPaths = new Set(); + const rows = state?.rows ?? []; + for (const row of rows) { + const idMatches = state.key === "rowid" ? [] : (byId.get(String(row.id)) ?? []); + const pathKey = rowRolloutPath(home, row.rollout_path); + const pathMatch = pathKey ? byPath.get(pathKey) : null; + const matches = [...new Map([...idMatches, ...(pathMatch ? [pathMatch] : [])].map(file => [providerPathKey(file.path), file])).values()]; + const conflict = matches.length > 1 || (pathMatch?.id && String(row.id) !== pathMatch.id && state.key !== "rowid"); + rowMatches.set(row, { matches, conflict }); + for (const match of matches) { + const key = providerPathKey(match.path); + const owners = ownersByPath.get(key) ?? []; + owners.push(row); ownersByPath.set(key, owners); + } + } + for (const row of rows) { + const relation = rowMatches.get(row); + if (relation.matches.some(file => ownersByPath.get(providerPathKey(file.path)).length > 1)) relation.conflict = true; + if (!relation.conflict) for (const file of relation.matches) { + const key = providerPathKey(file.path); + if (skippedPaths.has(key)) associatedBadPaths.add(key); + } + } + // A trustworthy ID absent from the index still proves which row would own + // the file. Do not manufacture that certainty for corrupt/no-ID headers. + for (const key of skippedPaths) { + const file = byPath.get(key); + if (file?.id && byId.get(file.id)?.length === 1 && !ownersByPath.has(key)) associatedBadPaths.add(key); + } + const unknown = [...skippedPaths].some(key => !associatedBadPaths.has(key)); + const selected = []; + const rowSkips = []; + for (const row of rows) { + if (row.model_provider === targetProvider) continue; + const { matches, conflict } = rowMatches.get(row); + let reason = conflict ? "association-conflict" : null; + const skippedMatch = matches.find(file => skippedPaths.has(providerPathKey(file.path))); + const fileSkip = skippedMatch ? skipped.find(item => item.kind === "rollout" && providerPathKey(item.path) === providerPathKey(skippedMatch.path)) : null; + if (!reason && fileSkip) reason = fileSkip.reason; + if (!reason && unknown && matches.length === 0) reason = "association-unknown"; + if (reason) rowSkips.push({ kind: "sqlite", id: String(row.id), reason, stage: "plan", retryable: !conflict && fileSkip?.retryable === true }); + else selected.push({ ...row, paths: matches.map(file => file.path) }); + } + return { rows: selected, skippedItems: rowSkips }; +} diff --git a/src/session-files.js b/src/session-files.js index 32656e0..0dfeb62 100644 --- a/src/session-files.js +++ b/src/session-files.js @@ -7,19 +7,37 @@ import path from "node:path"; import readline from "node:readline"; import { isDeepStrictEqual, promisify } from "node:util"; -import { SESSION_DIRS } from "./constants.js"; +import { SESSION_DIRS, PROVIDER_SESSION_META_MAX_BYTES } from "./constants.js"; import { syncDirectory } from "./atomic-file.js"; import { CoreError } from "./core-error.js"; +import { fileReadSkipReason, rolloutSkip, summarizeSkips } from "./provider-skips.js"; import { WINDOWS_LOCK_PROBE_SCRIPT, parseWindowsLockProbeResult } from "./windows-lock-probe.js"; const execFileAsync = promisify(execFile); const ROLLOUT_SCAN_CHUNK_BYTES = 1024 * 1024; -const STATUS_SESSION_META_MAX_BYTES = 1024 * 1024; -const PROVIDER_SESSION_META_MAX_BYTES = 1024 * 1024; +const STATUS_SESSION_META_MAX_BYTES = PROVIDER_SESSION_META_MAX_BYTES; +const REPAIR_SESSION_META_MAX_BYTES = 1024 * 1024; + +class RolloutMetadataEncodingError extends Error { + constructor() { + super("Rollout session metadata is not valid UTF-8."); + this.name = "RolloutMetadataEncodingError"; + } +} + +const providerMetadataDecoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); +function decodeFirstLine(bytes, strictMetadata) { + if (!strictMetadata) return bytes.toString("utf8"); + try { return providerMetadataDecoder.decode(bytes); } + catch (error) { + if (error?.code === "ERR_ENCODING_INVALID_ENCODED_DATA") throw new RolloutMetadataEncodingError(); + throw error; + } +} class RolloutMetadataLimitError extends Error { constructor() { - super("Rollout session metadata exceeds the read-only Status limit."); + super("Rollout session metadata exceeds the bounded header limit."); this.name = "RolloutMetadataLimitError"; } } @@ -153,42 +171,47 @@ async function listJsonlFiles(rootDir) { return files; } -async function readFirstLineRecord(filePath, { maxBytes = Number.POSITIVE_INFINITY, fsImpl = fsp, wrapBusyErrors = true } = {}) { +async function readFirstLineRecord(filePath, { maxBytes = Number.POSITIVE_INFINITY, fsImpl = fsp, wrapBusyErrors = true, strictMetadata = false } = {}) { let handle; try { handle = await fsImpl.open(filePath, "r"); let position = 0; - let collected = Buffer.alloc(0); + let length = 0; + const chunks = []; + const bounded = Number.isSafeInteger(maxBytes) && maxBytes >= 0; while (true) { - const bounded = Number.isSafeInteger(maxBytes) && maxBytes >= 0; - const remaining = bounded ? (maxBytes + 1) - position : 64 * 1024; - const chunkLength = bounded ? Math.min(64 * 1024, remaining) : 64 * 1024; + // Two lookahead bytes allow a boundary-sized header followed by CRLF. + const remaining = bounded ? maxBytes + 2 - position : 64 * 1024; + const chunkLength = Math.min(64 * 1024, remaining); if (chunkLength <= 0) throw new RolloutMetadataLimitError(); const chunk = Buffer.alloc(chunkLength); const { bytesRead } = await handle.read(chunk, 0, chunk.length, position); - if (bytesRead === 0) { - break; - } - position += bytesRead; - collected = Buffer.concat([collected, chunk.subarray(0, bytesRead)]); - const newlineIndex = collected.indexOf(0x0a); + if (bytesRead === 0) break; + const bytes = chunk.subarray(0, bytesRead); + const newlineIndex = bytes.indexOf(0x0a); if (newlineIndex !== -1) { - if (bounded && newlineIndex > maxBytes) throw new RolloutMetadataLimitError(); - const crlf = newlineIndex > 0 && collected[newlineIndex - 1] === 0x0d; - const lineBuffer = crlf ? collected.subarray(0, newlineIndex - 1) : collected.subarray(0, newlineIndex); + const preceding = newlineIndex > 0 ? bytes[newlineIndex - 1] : chunks.at(-1)?.at(-1); + const crlf = preceding === 0x0d; + const lineLength = length + newlineIndex - (crlf ? 1 : 0); + if (bounded && lineLength > maxBytes) throw new RolloutMetadataLimitError(); + chunks.push(bytes.subarray(0, newlineIndex)); + const collected = Buffer.concat(chunks, length + newlineIndex); return { - firstLine: lineBuffer.toString("utf8"), + firstLine: decodeFirstLine(collected.subarray(0, lineLength), strictMetadata), separator: crlf ? "\r\n" : "\n", - offset: newlineIndex + 1 + offset: position + newlineIndex + 1 }; } - if (bounded && collected.length > maxBytes) throw new RolloutMetadataLimitError(); + chunks.push(bytes); + length += bytesRead; + position += bytesRead; + if (bounded && length > maxBytes + && !(length === maxBytes + 1 && bytes[bytesRead - 1] === 0x0d)) { + throw new RolloutMetadataLimitError(); + } } - return { - firstLine: collected.toString("utf8"), - separator: "", - offset: collected.length - }; + if (bounded && length > maxBytes) throw new RolloutMetadataLimitError(); + return { firstLine: decodeFirstLine(Buffer.concat(chunks, length), strictMetadata), separator: "", offset: length }; } catch (error) { throw wrapBusyErrors ? wrapRolloutFileBusyError(error, filePath, "read") : error; } finally { @@ -196,13 +219,14 @@ async function readFirstLineRecord(filePath, { maxBytes = Number.POSITIVE_INFINI } } -function parseSessionMetaRecord(firstLine) { +function parseSessionMetaRecord(firstLine, strictMetadata = false) { if (!firstLine) { return null; } try { const parsed = JSON.parse(firstLine); - if (parsed?.type !== "session_meta" || typeof parsed?.payload !== "object" || parsed.payload === null) { + if (parsed?.type !== "session_meta" || typeof parsed?.payload !== "object" || parsed.payload === null + || (strictMetadata && (Array.isArray(parsed) || Array.isArray(parsed.payload)))) { return null; } return parsed; @@ -405,7 +429,10 @@ function isValidWindowsRewriteResult(result) { return result === "APPLIED" || result === "APPLIED_IN_PLACE" || result === "SKIP_BUSY" - || result === "SKIP_CHANGED"; + || result === "SKIP_CHANGED" + || result === "SKIP_MISSING" + || result === "SKIP_UNREADABLE" + || result === "SKIP_NOT_APPLIED"; } async function restoreOriginalMtime(filePath, mtimeMs) { @@ -446,20 +473,39 @@ function getInPlaceProviderMutation(change) { return null; } - // Tokenize strings first: a regex on raw field text can match inside a JSON - // string or miss an escaped duplicate key. Only one literal provider key and - // one payload key anywhere in the header are eligible. - const keys = [...change.originalFirstLine.matchAll(/"(?:[^"\\]|\\.)*"/g)] - .filter((token) => /^\s*:/.test(change.originalFirstLine.slice(token.index + token[0].length))); - const named = (name) => keys.filter((key) => JSON.parse(key[0]) === name); - const fields = named("model_provider"); - if (fields.length !== 1 || named("payload").length !== 1 - || !fields[0][0].startsWith('"model_provider"')) { - return null; - } - const field = fields[0]; - const valueOffset = field.index + field[0].length - + change.originalFirstLine.slice(field.index + field[0].length).match(/^\s*:\s*/)[0].length; + // Walk JSON string tokens once. A repeated-alternative regexp can exhaust + // V8's stack on a large, otherwise valid instruction string. + const text = change.originalFirstLine; + let payloadCount = 0; + let providerCount = 0; + let valueOffset = -1; + for (let index = 0; index < text.length; index += 1) { + if (text.charCodeAt(index) !== 34) continue; + const start = index; + index += 1; + for (; index < text.length; index += 1) { + const code = text.charCodeAt(index); + if (code === 92) { index += 1; continue; } + if (code === 34) break; + } + if (index >= text.length) return null; + const end = index + 1; + let after = end; + while (after < text.length && /\s/.test(text[after])) after += 1; + if (text[after] !== ":") continue; + // Even a fully Unicode-escaped model_provider key fits in this bound. + if (end - start > 2 + 6 * "model_provider".length) continue; + const literal = text.slice(start, end); + const name = JSON.parse(literal); + if (name === "payload") payloadCount += 1; + if (name !== "model_provider") continue; + providerCount += 1; + if (literal !== '"model_provider"') return null; + after += 1; + while (after < text.length && /\s/.test(text[after])) after += 1; + valueOffset = after; + } + if (providerCount !== 1 || payloadCount !== 1) return null; if (!change.originalFirstLine.startsWith(originalLiteral, valueOffset)) { return null; } @@ -675,10 +721,11 @@ async function tryRewriteProviderInPlace(change, options = {}) { mutation, change.path, change.originalFirstLine, change.originalSeparator); const writeImpl = options.inPlaceWrite ?? defaultInPlaceWrite; let handle; + let mutationAttempted = false; try { const pathStat = await fsp.lstat(change.path); if (pathStat.isSymbolicLink() || !pathStat.isFile()) { - return "SKIP_CHANGED"; + throw new CoreError("STALE_STATE", "An unsafe rollout target cannot be written.", { details: { reason: "rollout" } }); } handle = await fsp.open(change.path, "r+"); const identity = await handle.stat({ bigint: true }); @@ -701,11 +748,14 @@ async function tryRewriteProviderInPlace(change, options = {}) { try { await assertInPlaceIdentity(handle, change.path, mutation); if (!snapshotMatches(change, await getFileSnapshot(change.path))) return "SKIP_CHANGED"; - } catch { - return "SKIP_CHANGED"; + } catch (error) { + const reason = fileReadSkipReason(error); + if (reason) return reason === "missing" ? "SKIP_MISSING" : reason === "unreadable" ? "SKIP_UNREADABLE" : "SKIP_BUSY"; + throw error; } try { + mutationAttempted = true; await writeBytesFully(handle, replacementBytes, mutation.byteOffset, writeImpl); await finishInPlaceWrite(handle, change, replacementBytes, options); } catch (error) { @@ -719,10 +769,17 @@ async function tryRewriteProviderInPlace(change, options = {}) { failure.code = "IN_PLACE_RESTORE_FAILED"; throw failure; } - throw error; + error.sourceUnchanged = true; + if (error?.code === "ENOSPC" || error?.code === "EDQUOT") throw error; + return "SKIP_NOT_APPLIED"; } return "APPLIED_IN_PLACE"; } catch (error) { + if (!mutationAttempted) { + const reason = fileReadSkipReason(error); + if (reason) return reason === "missing" ? "SKIP_MISSING" : reason === "unreadable" ? "SKIP_UNREADABLE" : "SKIP_BUSY"; + error.sourceUnchanged = true; + } throw wrapRolloutFileBusyError(error, change.path, "rewrite provider bytes in place"); } finally { await handle?.close(); @@ -802,32 +859,48 @@ ${WINDOWS_PROVIDER_BYTES_SOURCE} return $null } - function Read-FirstLineRecord([System.IO.FileStream]$stream) { + function Has-VerifiedSourceUnchanged($exception) { + for ($depth = 0; $null -ne $exception -and $depth -lt 8; $depth++) { + if ($exception.Data["providerSyncSourceUnchanged"] -eq $true) { return $true } + $exception = $exception.InnerException + } + return $false + } + + function Read-FirstLineRecord([System.IO.FileStream]$stream, [long]$maxBytes = [long]::MaxValue, [bool]$strictMetadata = $false) { + $decoder = [System.Text.UTF8Encoding]::new($false, $strictMetadata) $stream.Seek(0, [System.IO.SeekOrigin]::Begin) | Out-Null $buffer = New-Object byte[] (64 * 1024) $collected = New-Object System.IO.MemoryStream try { while ($true) { - $bytesRead = $stream.Read($buffer, 0, $buffer.Length) - if ($bytesRead -le 0) { - break + $readLength = $buffer.Length + if ($maxBytes -ne [long]::MaxValue) { + $readLength = [int][Math]::Min($readLength, $maxBytes + 2 - $collected.Length) + if ($readLength -le 0) { return $null } } - - $collected.Write($buffer, 0, $bytesRead) - $bytes = $collected.ToArray() - $newlineIndex = [Array]::IndexOf($bytes, [byte]10) + $bytesRead = $stream.Read($buffer, 0, $readLength) + if ($bytesRead -le 0) { break } + $newlineIndex = [Array]::IndexOf($buffer, [byte]10, 0, $bytesRead) if ($newlineIndex -ge 0) { - $crlf = $newlineIndex -gt 0 -and $bytes[$newlineIndex - 1] -eq [byte]13 - $lineLength = if ($crlf) { $newlineIndex - 1 } else { $newlineIndex } + $collected.Write($buffer, 0, $newlineIndex) + $bytes = $collected.GetBuffer() + $count = [int]$collected.Length + $crlf = $count -gt 0 -and $bytes[$count - 1] -eq [byte]13 + $lineLength = if ($crlf) { $count - 1 } else { $count } + if ($lineLength -gt $maxBytes) { return $null } return @{ - firstLine = [System.Text.Encoding]::UTF8.GetString($bytes, 0, $lineLength) - offset = $newlineIndex + 1 + firstLine = $decoder.GetString($bytes, 0, $lineLength) + offset = $count + 1 } } + $collected.Write($buffer, 0, $bytesRead) + if ($collected.Length -gt $maxBytes -and + -not ($collected.Length -eq $maxBytes + 1 -and $buffer[$bytesRead - 1] -eq [byte]13)) { return $null } } - + if ($collected.Length -gt $maxBytes) { return $null } return @{ - firstLine = [System.Text.Encoding]::UTF8.GetString($collected.ToArray()) + firstLine = $decoder.GetString($collected.GetBuffer(), 0, [int]$collected.Length) offset = [int]$collected.Length } } finally { @@ -835,6 +908,16 @@ ${WINDOWS_PROVIDER_BYTES_SOURCE} } } + function Safe-OpenSkip($exception) { + $cause = $exception + while ($null -ne $cause.InnerException) { $cause = $cause.InnerException } + $code = $cause.HResult -band 65535 + if ($code -eq 2 -or $code -eq 3) { return "SKIP_MISSING" } + if ($code -eq 5) { return "SKIP_UNREADABLE" } + if ($code -eq 32 -or $code -eq 33) { return "SKIP_BUSY" } + return $null + } + function Invoke-RewriteChange($change) { $path = [string]$change.path $tmpPath = "$path.provider-sync.$PID.$([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()).tmp" @@ -842,26 +925,28 @@ ${WINDOWS_PROVIDER_BYTES_SOURCE} $encoding = [System.Text.UTF8Encoding]::new($false) $source = $null $writer = $null + $sourceMayHaveChanged = $false $timing = New-RewriteTiming $total = [System.Diagnostics.Stopwatch]::StartNew() try { try { $sourceOpen = [System.Diagnostics.Stopwatch]::StartNew() + if (([System.IO.File]::GetAttributes($path) -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) { throw "Unsafe rollout link." } $source = [System.IO.File]::Open($path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) $timing.sourceOpenMs += $sourceOpen.Elapsed.TotalMilliseconds } catch { $timing.sourceOpenMs += $sourceOpen.Elapsed.TotalMilliseconds - if (Test-Path -LiteralPath $path) { - return Complete-RewriteChange "SKIP_BUSY" $timing $total - } - return Complete-RewriteChange "SKIP_CHANGED" $timing $total + $skip = Safe-OpenSkip $_.Exception + if ($null -ne $skip) { return Complete-RewriteChange $skip $timing $total } + throw } if ($null -ne $change.inPlaceMutation) { $m = $change.inPlaceMutation $header = $encoding.GetBytes([string]$change.originalFirstLine + [string]$change.originalSeparator) try { + $sourceMayHaveChanged = $true $native = [ProviderByteFile]::ApplyWithTiming($source, $header, [Convert]::FromBase64String([string]$m.originalBase64), [Convert]::FromBase64String([string]$m.replacementBase64), @@ -881,9 +966,17 @@ ${WINDOWS_PROVIDER_BYTES_SOURCE} } $readHeader = [System.Diagnostics.Stopwatch]::StartNew() - try { $record = Read-FirstLineRecord $source } + try { $record = Read-FirstLineRecord $source ($encoding.GetByteCount([string]$change.originalFirstLine)) ([bool]$change.strictProviderMetadata) } + catch { + $cause = $_.Exception + while ($null -ne $cause.InnerException) { $cause = $cause.InnerException } + if ([bool]$change.strictProviderMetadata -and $cause -is [System.Text.DecoderFallbackException]) { + return Complete-RewriteChange "SKIP_CHANGED" $timing $total + } + throw + } finally { $timing.readHeaderMs += $readHeader.Elapsed.TotalMilliseconds } - if ($record.firstLine -ne [string]$change.originalFirstLine -or $record.offset -ne [int]$change.originalOffset) { + if ($null -eq $record -or $record.firstLine -cne [string]$change.originalFirstLine -or $record.offset -ne [int]$change.originalOffset) { return Complete-RewriteChange "SKIP_CHANGED" $timing $total } @@ -928,20 +1021,23 @@ ${WINDOWS_PROVIDER_BYTES_SOURCE} $source = $null try { $replace = [System.Diagnostics.Stopwatch]::StartNew() + $sourceMayHaveChanged = $true [System.IO.File]::Replace($tmpPath, $path, $replaceBackupPath, $true) $timing.replaceMs += $replace.Elapsed.TotalMilliseconds } catch { $timing.replaceMs += $replace.Elapsed.TotalMilliseconds - if (Test-Path -LiteralPath $path) { - return Complete-RewriteChange "SKIP_BUSY" $timing $total - } - return Complete-RewriteChange "SKIP_CHANGED" $timing $total + throw } return Complete-RewriteChange "APPLIED" $timing $total } catch { + if (-not $sourceMayHaveChanged) { + $skip = Safe-OpenSkip $_.Exception + if ($null -ne $skip) { return Complete-RewriteChange $skip $timing $total } + } $timing.workerMs = [Math]::Max(0.0, $total.Elapsed.TotalMilliseconds) $_.Exception.Data["providerSyncTiming"] = $timing + $_.Exception.Data["providerSyncSourceUnchanged"] = ((-not $sourceMayHaveChanged) -or (Has-VerifiedSourceUnchanged $_.Exception)) throw } finally { if ($writer) { @@ -1005,6 +1101,7 @@ ${WINDOWS_PROVIDER_BYTES_SOURCE} id = $errorId path = $errorPath message = $_.Exception.Message + sourceUnchanged = ($_.Exception.Data["providerSyncSourceUnchanged"] -eq $true) timing = $failureTiming }) exit 1 @@ -1156,6 +1253,7 @@ export async function createWindowsExclusiveRewriteWorker(options = {}) { try { await writeWorkerRequest(child.stdin, { ...change, + ...(change.inPlaceMutation ? { updatedFirstLine: undefined } : {}), protocolVersion: WINDOWS_REWRITE_PROTOCOL_VERSION, type: "rewrite", id, @@ -1168,6 +1266,12 @@ export async function createWindowsExclusiveRewriteWorker(options = {}) { if (response?.type === "result" || response?.type === "error") { lastTiming = timing ? { timing, complete: response.type === "result" } : null; } + if (response?.protocolVersion === WINDOWS_REWRITE_PROTOCOL_VERSION && response?.type === "error" + && response?.id === id && response?.path === change.path && response.sourceUnchanged === true) { + const failure = new Error("Windows rewrite worker failed before source mutation."); + failure.sourceUnchanged = true; + throw failure; + } if (response?.protocolVersion !== WINDOWS_REWRITE_PROTOCOL_VERSION || response?.type !== "result" || response?.id !== id @@ -1180,17 +1284,11 @@ export async function createWindowsExclusiveRewriteWorker(options = {}) { } catch (error) { child.stdin.destroy(); child.kill(); - throw wrapRolloutFileBusyError( - new Error( - formatWindowsRewriteWorkerError( - `Windows rewrite worker failed for ${change.path}: ${stdinError?.message ?? error.message}`, - stderr - ), - { cause: error } - ), - change.path, - "rewrite" - ); + const failure = wrapRolloutFileBusyError(new Error( + formatWindowsRewriteWorkerError(`Windows rewrite worker failed for ${change.path}: ${stdinError?.message ?? error.message}`, stderr), + { cause: error }), change.path, "rewrite"); + if (error.sourceUnchanged === true) failure.sourceUnchanged = true; + throw failure; } finally { inFlight = false; } @@ -1326,17 +1424,38 @@ async function tryRewriteCollectedFirstLine(change, options = {}) { return tryRewriteProviderInPlace(change, options); } - const beforeSnapshot = await getFileSnapshot(change.path); + let beforeSnapshot; + try { + const info = await fsp.lstat(change.path); + if (info.isSymbolicLink() || !info.isFile()) throw new CoreError("STALE_STATE", "An unsafe rollout target cannot be written.", { details: { reason: "rollout" } }); + beforeSnapshot = await getFileSnapshot(change.path); + } + catch (error) { + const reason = fileReadSkipReason(error); + if (reason) return reason === "missing" ? "SKIP_MISSING" : reason === "unreadable" ? "SKIP_UNREADABLE" : "SKIP_BUSY"; + error.sourceUnchanged = true; + throw error; + } if (!snapshotMatches(change, beforeSnapshot)) { return "SKIP_CHANGED"; } - const current = await readFirstLineRecord(change.path); + let current; + try { + current = await readFirstLineRecord(change.path, { maxBytes: Buffer.byteLength(change.originalFirstLine, "utf8"), strictMetadata: change.strictProviderMetadata === true }); + } catch (error) { + if (error instanceof RolloutMetadataLimitError || error instanceof RolloutMetadataEncodingError) return "SKIP_CHANGED"; + const reason = fileReadSkipReason(error); + if (reason) return reason === "missing" ? "SKIP_MISSING" : reason === "unreadable" ? "SKIP_UNREADABLE" : "SKIP_BUSY"; + error.sourceUnchanged = true; + throw error; + } if (current.firstLine !== change.originalFirstLine || current.offset !== change.originalOffset) { return "SKIP_CHANGED"; } const tmpPath = `${change.path}.provider-sync.${process.pid}.${Date.now()}.tmp`; + let replaceAttempted = false; const writer = fs.createWriteStream(tmpPath, { encoding: "utf8" }); try { @@ -1369,11 +1488,18 @@ async function tryRewriteCollectedFirstLine(change, options = {}) { await fsp.chmod(tmpPath, beforeSnapshot.mode); await syncStagedFile(tmpPath); + replaceAttempted = true; await fsp.rename(tmpPath, change.path); await syncDirectory(path.dirname(change.path)); return "APPLIED"; } catch (error) { - await fsp.rm(tmpPath, { force: true }); + writer.destroy(); + await fsp.rm(tmpPath, { force: true }).catch(() => {}); + if (!replaceAttempted) { + const reason = fileReadSkipReason(error); + if (reason) return reason === "missing" ? "SKIP_MISSING" : reason === "unreadable" ? "SKIP_UNREADABLE" : "SKIP_BUSY"; + error.sourceUnchanged = true; + } throw wrapRolloutFileBusyError(error, change.path, "rewrite"); } } @@ -1552,6 +1678,7 @@ export async function collectStatusRolloutMetadata(codexHome, options = {}) { const { skipLockedReads = false } = options; const lockedPaths = []; const incompletePaths = []; + const skippedItems = []; const providerChangeCandidates = []; const providerCounts = { sessions: new Map(), @@ -1562,15 +1689,23 @@ export async function collectStatusRolloutMetadata(codexHome, options = {}) { const rootDir = path.join(codexHome, dirName); try { await fsp.access(rootDir); - } catch { + } catch (error) { + if (error?.code !== "ENOENT") throw error; continue; } const rolloutPaths = await listJsonlFiles(rootDir); for (const rolloutPath of rolloutPaths) { let record; try { - record = await readFirstLineRecord(rolloutPath, { maxBytes: STATUS_SESSION_META_MAX_BYTES }); + record = await readFirstLineRecord(rolloutPath, { maxBytes: STATUS_SESSION_META_MAX_BYTES, strictMetadata: true }); } catch (error) { + const reason = fileReadSkipReason(error); + if (reason) { + skippedItems.push(rolloutSkip(rolloutPath, reason)); + incompletePaths.push(rolloutPath); + if (reason === "locked") lockedPaths.push(rolloutPath); + continue; + } if (error instanceof RolloutMetadataLimitError) { incompletePaths.push(rolloutPath); continue; @@ -1581,8 +1716,9 @@ export async function collectStatusRolloutMetadata(codexHome, options = {}) { } throw error; } - const parsed = parseSessionMetaRecord(record.firstLine); + const parsed = parseSessionMetaRecord(record.firstLine, true); if (!parsed) { + skippedItems.push(rolloutSkip(rolloutPath, "metadata-invalid")); incompletePaths.push(rolloutPath); continue; } @@ -1597,7 +1733,7 @@ export async function collectStatusRolloutMetadata(codexHome, options = {}) { } } - return { incompletePaths, lockedPaths, providerCounts, providerChangeCandidates }; + return { skippedItems, skipSummary: summarizeSkips(skippedItems), incompletePaths, lockedPaths, providerCounts, providerChangeCandidates }; } export async function collectSessionChanges(codexHome, targetProvider, options = {}, preparationRecords = null) { @@ -1620,6 +1756,12 @@ export async function collectSessionChanges(codexHome, targetProvider, options = ); } const summaries = []; + const skippedItems = []; + const files = []; + const skip = (filePath, reason, id = null, stage = "scan") => { + skippedItems.push(rolloutSkip(filePath, reason, stage, id)); + if (reason === "locked") lockedPaths.push(filePath); + }; const lockedPaths = []; const providerCounts = { sessions: new Map(), @@ -1635,7 +1777,8 @@ export async function collectSessionChanges(codexHome, targetProvider, options = if (!preparationRecords) { try { await fsp.access(rootDir); - } catch { + } catch (error) { + if (error?.code !== "ENOENT") throw error; continue; } } @@ -1646,8 +1789,14 @@ export async function collectSessionChanges(codexHome, targetProvider, options = ? trackScanFiles(rolloutPaths, { ...options, stage: `scan_${dirName}` }) : rolloutPaths; for (const rolloutPath of trackedPaths) { const prepared = preparationRecords?.get(rolloutPath); + if (prepared?.skip) { + skippedItems.push(prepared.skip); + files.push({ path: rolloutPath, id: prepared.skip.id ?? null }); + if (prepared.skip.reason === "locked") lockedPaths.push(rolloutPath); + continue; + } if (prepared?.locked) { - lockedPaths.push(rolloutPath); + skip(rolloutPath, "locked"); continue; } let record; @@ -1655,33 +1804,35 @@ export async function collectSessionChanges(codexHome, targetProvider, options = try { scanStart = prepared?.beforeSnapshot ?? await getFileSnapshot(rolloutPath); record = prepared?.record ?? await readFirstLineRecord(rolloutPath, { - maxBytes: maxSessionMetaBytes + maxBytes: maxSessionMetaBytes, strictMetadata: rejectInvalidMetadata }); } catch (error) { + if (rejectInvalidMetadata && fileReadSkipReason(error)) { + skip(rolloutPath, fileReadSkipReason(error)); + continue; + } if (skipLockedReads && isRolloutFileBusyError(error)) { lockedPaths.push(rolloutPath); continue; } if (rejectInvalidMetadata && error instanceof RolloutMetadataLimitError) { throw new CoreError( - "ROLLOUT_CHANGED", - `Provider sync requires a session metadata header no larger than 1 MiB: ${rolloutPath}`, + "ROLLOUT_METADATA_TOO_LARGE", + "Session metadata exceeds the 128 MiB supported limit.", { cause: error } ); } throw error; } - const parsed = parseSessionMetaRecord(record.firstLine); + const parsed = parseSessionMetaRecord(record.firstLine, rejectInvalidMetadata); if (!parsed) { if (rejectInvalidMetadata) { - throw new CoreError( - "ROLLOUT_CHANGED", - `Provider sync cannot validate session metadata: ${rolloutPath}` - ); + skip(rolloutPath, "metadata-invalid"); } continue; } const currentProvider = parsed.payload.model_provider ?? "(missing)"; + files.push({ path: rolloutPath, id: typeof parsed.payload.id === "string" && parsed.payload.id ? parsed.payload.id : null, provider: currentProvider }); if (typeof parsed.payload.id === "string" && parsed.payload.id) nativeSessionIds.add(parsed.payload.id); // Selected repair work is addressed by Codex's native session id, never // by a rollout filename/path. Files without that identity stay out. @@ -1709,6 +1860,10 @@ export async function collectSessionChanges(codexHome, targetProvider, options = userEventThreadIds.add(parsed.payload.id); } } catch (error) { + if (rejectInvalidMetadata && fileReadSkipReason(error)) { + skip(rolloutPath, fileReadSkipReason(error)); + continue; + } if (skipLockedReads && isRolloutFileBusyError(error)) { lockedPaths.push(rolloutPath); continue; @@ -1735,7 +1890,8 @@ export async function collectSessionChanges(codexHome, targetProvider, options = const snapshot = prepared?.afterSnapshot ?? await getFileSnapshot(rolloutPath); if (snapshot.size !== scanStart.size || snapshot.mtimeMs !== scanStart.mtimeMs || snapshot.dev !== scanStart.dev || snapshot.ino !== scanStart.ino) { - lockedPaths.push(rolloutPath); + if (rejectInvalidMetadata) skip(rolloutPath, "changed", parsed.payload.id); + else lockedPaths.push(rolloutPath); continue; } if (providerChanged) { @@ -1759,15 +1915,33 @@ export async function collectSessionChanges(codexHome, targetProvider, options = originalTurnContextModels: modelSnapshot.originalTurnContextModels, modelRewriteRequired: modelChanged, modelOnlyChange: !providerChanged && modelChanged, - updatedFirstLine: providerChanged ? JSON.stringify(parsed) : record.firstLine + strictProviderMetadata: rejectInvalidMetadata, + updatedFirstLine: record.firstLine }; - change.inPlaceMutation = getInPlaceProviderMutation(change); + // Only these pure JSON operations may turn a capacity failure into a + // data skip. I/O, snapshots and writes remain outside this boundary. + try { + if (providerChanged) change.updatedFirstLine = JSON.stringify(parsed); + change.inPlaceMutation = getInPlaceProviderMutation(change); + } catch (error) { + if (!rejectInvalidMetadata || !(error instanceof RangeError)) throw error; + skip(rolloutPath, "metadata-too-complex", parsed.payload.id); + const count = providerCounts[dirName].get(currentProvider) - 1; + if (count) providerCounts[dirName].set(currentProvider, count); + else providerCounts[dirName].delete(currentProvider); + continue; + } + if (rejectInvalidMetadata && !change.inPlaceMutation + && Buffer.byteLength(change.updatedFirstLine, "utf8") > maxSessionMetaBytes) { + skip(rolloutPath, "metadata-too-large", parsed.payload.id); + continue; + } summaries.push(change); } } } - return { changes: summaries, lockedPaths, providerCounts, encryptedContentCounts, userEventThreadIds, threadCwdById, nativeSessionIds }; + return { changes: summaries, files, skippedItems, skipSummary: summarizeSkips(skippedItems), incompletePaths: skippedItems.map(item => item.path), lockedPaths, providerCounts, encryptedContentCounts, userEventThreadIds, threadCwdById, nativeSessionIds }; } const WINDOWS_FIRST_LINE_TIMING_FIELDS = [ @@ -1839,7 +2013,7 @@ function addWindowsRewriteTiming(target, source) { // header reader; never open a body stream or expose this through the Facade. export async function readProviderRevisionHeader(filePath, { fsImpl = fsp } = {}) { return readFirstLineRecord(filePath, { - maxBytes: PROVIDER_SESSION_META_MAX_BYTES, fsImpl, wrapBusyErrors: false + maxBytes: PROVIDER_SESSION_META_MAX_BYTES, fsImpl, wrapBusyErrors: false, strictMetadata: true }); } @@ -1870,7 +2044,7 @@ export async function collectRepairChanges(codexHome, targets, options = {}) { sessionIds: options.sessionIds, onProgress: options.onProgress, signal: options.signal, - maxSessionMetaBytes: PROVIDER_SESSION_META_MAX_BYTES, + maxSessionMetaBytes: REPAIR_SESSION_META_MAX_BYTES, rejectInvalidMetadata: false }); } @@ -1951,6 +2125,7 @@ export async function applySessionChanges(changes, options = {}) { onMutation, onApplied, onSkipped, + onUnwritten, onTiming, windowsRewriteWorkerFactory = createWindowsExclusiveRewriteWorker, inPlaceWrite, @@ -2000,7 +2175,8 @@ export async function applySessionChanges(changes, options = {}) { const requestStart = timingNow(); let result; try { - result = await worker.rewrite(change, { requireOriginalMatch: true }); + try { result = await worker.rewrite(change, { requireOriginalMatch: true }); } + catch (error) { if (error.sourceUnchanged === true) await onUnwritten?.(change); throw error; } } finally { timing.requestRoundTripMs += elapsedTimingMs(requestStart); let observedTiming = null; @@ -2038,7 +2214,7 @@ export async function applySessionChanges(changes, options = {}) { timing.skippedFiles += 1; skippedPaths.push(change.path); if (result === "SKIP_BUSY") skippedLockedPaths.push(change.path); - else skippedChangedPaths.push(change.path); + else if (result === "SKIP_CHANGED" || result === "SKIP_MISSING") skippedChangedPaths.push(change.path); await onSkipped?.(change, result); } } @@ -2072,11 +2248,9 @@ export async function applySessionChanges(changes, options = {}) { } else { for (const change of firstLineChanges) { await onBeforeApply?.(change); - const result = await tryRewriteCollectedFirstLine(change, { - inPlaceWrite, - inPlaceRestoreWrite, - inPlaceSync - }); + let result; + try { result = await tryRewriteCollectedFirstLine(change, { inPlaceWrite, inPlaceRestoreWrite, inPlaceSync }); } + catch (error) { if (error.sourceUnchanged === true) await onUnwritten?.(change); throw error; } if (result === "APPLIED" || result === "APPLIED_IN_PLACE") { appliedChanges += 1; inPlaceChanges += result === "APPLIED_IN_PLACE" ? 1 : 0; @@ -2095,7 +2269,7 @@ export async function applySessionChanges(changes, options = {}) { } else { skippedPaths.push(change.path); if (result === "SKIP_BUSY") skippedLockedPaths.push(change.path); - else skippedChangedPaths.push(change.path); + else if (result === "SKIP_CHANGED" || result === "SKIP_MISSING") skippedChangedPaths.push(change.path); await onSkipped?.(change, result); } } diff --git a/src/sqlite-state.js b/src/sqlite-state.js index 80e0707..97c2dd6 100644 --- a/src/sqlite-state.js +++ b/src/sqlite-state.js @@ -356,9 +356,28 @@ export async function readSqliteProviderCounts(storageOrLocation) { // A Provider plan depends on row identity / Provider, not message previews, // activity timestamps, or the physical WAL/SHM representation. One read // transaction binds the schema and rows to the same SQLite snapshot. +async function sqlitePhysicalIdentity(dbPath) { + const stats = await fs.lstat(dbPath, { bigint: true }); + if (!stats.isFile() || stats.isSymbolicLink() || stats.ino === 0n) { + throw new CoreError("STALE_STATE", "The thread index identity cannot be verified.", { details: { reason: "state-db" } }); + } + const realPath = await fs.realpath(dbPath); + return { dev: String(stats.dev), ino: String(stats.ino), nlink: String(stats.nlink), + realPath: process.platform === "win32" ? realPath.toLowerCase() : realPath }; +} + +async function assertSqlitePhysicalIdentity(dbPath, expected) { + if (!expected) return; + const actual = await sqlitePhysicalIdentity(dbPath); + if (Object.keys(expected).some(key => expected[key] !== actual[key])) { + throw new CoreError("STALE_STATE", "The thread index was replaced before its transaction.", { details: { reason: "state-db" } }); + } +} + export async function readSqliteProviderRevisionState(dbPath, { includeArchived = false } = {}) { let db; try { + const identity = await sqlitePhysicalIdentity(dbPath); db = await openDatabase(dbPath, { readOnly: true }); db.exec("BEGIN"); const schema = db.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'threads'").get()?.sql; @@ -367,9 +386,11 @@ export async function readSqliteProviderRevisionState(dbPath, { includeArchived } const key = tableHasColumn(db, "threads", "id") ? "id" : "rowid"; const archived = includeArchived && tableHasColumn(db, "threads", "archived") ? ", archived" : ""; - const rows = db.prepare(`SELECT ${key} AS id, model_provider${archived} FROM threads ORDER BY ${key}`).all(); + const rolloutPath = tableHasColumn(db, "threads", "rollout_path") ? ", rollout_path" : ""; + const rows = db.prepare(`SELECT ${key} AS id, model_provider${archived}${rolloutPath} FROM threads ORDER BY ${key}`).all(); db.exec("COMMIT"); - return { schema, rows }; + await assertSqlitePhysicalIdentity(dbPath, identity); + return { schema, key, rows, identity }; } catch (error) { if (isSqliteBusyError(error)) throw wrapSqliteBusyError(error, "read Provider revision"); if (error instanceof CoreError) throw error; @@ -635,6 +656,7 @@ export async function updateSqliteProvider(storageOrLocation, targetProvider, af const targetModel = options.targetModel ?? null; const dbPath = await existingStateDbPath(storageOrLocation); + if (!dbPath && options.expectedIdentity) throw new CoreError("STALE_STATE", "The planned thread index disappeared.", { details: { reason: "state-db" } }); if (!dbPath) { if (afterUpdate) { await afterUpdate({ @@ -659,11 +681,13 @@ export async function updateSqliteProvider(storageOrLocation, targetProvider, af let db; let transactionOpen = false; try { + await assertSqlitePhysicalIdentity(dbPath, options.expectedIdentity); db = await openDatabase(dbPath); setBusyTimeout(db, options.busyTimeoutMs); configureSqliteWriteDurability(db); db.exec("BEGIN IMMEDIATE"); transactionOpen = true; + await assertSqlitePhysicalIdentity(dbPath, options.expectedIdentity); // When a target model is provided, align every thread's `model` column // with it alongside `model_provider`. This is what makes the bottom-right // of the Codex UI show the active model for old sessions, instead of the @@ -675,11 +699,38 @@ export async function updateSqliteProvider(storageOrLocation, targetProvider, af // Keep the update shape and counters identical to .NET: provider and // optional model are independent writes, and a row changed in both // columns contributes two to updatedRows. - const providerResult = db.prepare(` - UPDATE threads - SET model_provider = ? - WHERE COALESCE(model_provider, '') <> ? - `).run(targetProvider, targetProvider); + const skippedItems = []; + let providerResult; + if (Array.isArray(options.plannedRows)) { + const key = tableHasColumn(db, "threads", "id") ? "id" : "rowid"; + const schema = db.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'threads'").get()?.sql; + if (options.expectedSchema && schema !== options.expectedSchema) throw new CoreError("STALE_STATE", "The thread index schema changed.", { details: { reason: "state-db" } }); + const hasPath = tableHasColumn(db, "threads", "rollout_path"); + const read = db.prepare(`SELECT model_provider${hasPath ? ", rollout_path" : ""} FROM threads WHERE ${key} = ?`); + const update = db.prepare(`UPDATE threads SET model_provider = ? WHERE ${key} = ? AND model_provider IS ?${hasPath ? " AND rollout_path IS ?" : ""}`); + let changes = 0; + for (const row of options.plannedRows) { + const current = read.get(row.id); + if (!current || current.model_provider !== row.model_provider || (hasPath && current.rollout_path !== row.rollout_path)) { + skippedItems.push({ kind: "sqlite", id: String(row.id), reason: current ? "row-changed" : "row-missing", stage: "sqlite", retryable: true }); + continue; + } + changes += update.run(targetProvider, row.id, row.model_provider, ...(hasPath ? [row.rollout_path] : [])).changes ?? 0; + } + if (Array.isArray(options.expectedRowIds)) { + const expected = new Set(options.expectedRowIds); + for (const row of db.prepare(`SELECT ${key} AS id FROM threads WHERE COALESCE(model_provider, '') <> ?`).all(targetProvider)) { + if (!expected.has(String(row.id))) skippedItems.push({ kind: "sqlite", id: String(row.id), reason: "deferred", stage: "sqlite", retryable: true }); + } + } + providerResult = { changes }; + } else { + providerResult = db.prepare(` + UPDATE threads + SET model_provider = ? + WHERE COALESCE(model_provider, '') <> ? + `).run(targetProvider, targetProvider); + } let modelUpdatedRows = 0; if (wantsModel) { modelUpdatedRows = db.prepare(` @@ -718,6 +769,7 @@ export async function updateSqliteProvider(storageOrLocation, targetProvider, af const result = { updatedRows, providerRowsUpdated: providerUpdatedRows, + skippedItems, modelRowsUpdated: modelUpdatedRows, userEventRowsUpdated: userEventUpdatedRows, cwdRowsUpdated: cwdUpdatedRows, diff --git a/src/web-core-adapter.js b/src/web-core-adapter.js index 9e67e4e..52ac614 100644 --- a/src/web-core-adapter.js +++ b/src/web-core-adapter.js @@ -38,6 +38,7 @@ function safeString(value) { } function httpStatusForCode(code) { + if (code === "ROLLOUT_METADATA_TOO_LARGE" || code === "ROLLOUT_METADATA_INVALID") return 422; if (code === "INVALID_INPUT" || code === "PROTOCOL_VERSION_MISMATCH") return 400; if (code === "CODEX_HOME_NOT_FOUND" || code === "STATE_DB_NOT_FOUND") return 404; if (code === "PERMISSION_DENIED") return 403; diff --git a/src/windows-provider-bytes.cs b/src/windows-provider-bytes.cs index b4d6bee..911e2e0 100644 --- a/src/windows-provider-bytes.cs +++ b/src/windows-provider-bytes.cs @@ -176,7 +176,15 @@ public static ApplyResult ApplyWithTiming(FileStream stream, byte[] header, byte { throw new AggregateException("Provider write and immediate recovery failed.", failure, recovery); } - throw; + // The original header and identity were verified after restoration. + // Disk exhaustion remains an operation-level stop even after recovery. + int code = failure.HResult & 65535; + if (code == 39 || code == 112) + { + failure.Data["providerSyncSourceUnchanged"] = true; + throw; + } + return Complete("SKIP_NOT_APPLIED", timing, total); } return Complete("APPLIED_IN_PLACE", timing, total); } diff --git a/test/cli-json.test.js b/test/cli-json.test.js index 586f7dd..3423ea1 100644 --- a/test/cli-json.test.js +++ b/test/cli-json.test.js @@ -21,6 +21,17 @@ const ENVELOPE_KEYS = [ "error" ]; +test("CLI JSON retains new metadata skip reasons with partial exit 3 and no raw exception", () => { + const skipSummary = { total: 2, rolloutFiles: 2, sqliteRows: 0, unconfirmed: 0, omitted: 0, retryRecommended: false, + items: ["metadata-invalid-utf8", "metadata-too-complex"].map(reason => ({ kind: "rollout", path: `/fixture/${reason}.jsonl`, reason, stage: "scan", retryable: false })) }; + const envelope = createCliSuccessEnvelope("sync", { partial: true, partialReason: "skipped-data", retryRecommended: false, + skipSummary, rawException: "RangeError private source text" }); + assert.equal(cliJsonExitCode(envelope), 3); + assert.deepEqual(envelope.result.skipSummary, skipSummary); + assert.equal(envelope.result.retryRecommended, false); + assert.doesNotMatch(JSON.stringify(envelope), /RangeError|private source/); +}); + function dto(code, overrides = {}) { return { code, diff --git a/test/large-session-metadata.test.js b/test/large-session-metadata.test.js new file mode 100644 index 0000000..65c1ea7 --- /dev/null +++ b/test/large-session-metadata.test.js @@ -0,0 +1,212 @@ +import assert from "node:assert/strict"; +import fs from "node:fs/promises"; +import fsSync from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { createHash } from "node:crypto"; +import test, { afterEach } from "node:test"; + +const cleanups = []; +afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); }); +import { PROVIDER_SESSION_META_MAX_BYTES } from "../src/constants.js"; +import { readProviderRevisionHeader } from "../src/session-files.js"; +import { applySwitch, prepareSync, prepareSwitch, runSync, runSwitch, runRestore, getStatus } from "../src/service.js"; +import { openDatabase } from "../src/sqlite.js"; +import { CoreError } from "../src/core-error.js"; +import { createPublicCoreErrorDto, isCanonicalPublicCoreErrorDto } from "../packages/contracts/dist/index.js"; +import { normalizeCliErrorDto } from "../src/cli-json.js"; +import { dispatchWebCoreRequest } from "../src/web-core-adapter.js"; + +delete process.env.CODEX_SQLITE_HOME; +const MiB = 1024 * 1024; + +async function fixture(t) { + const base = process.platform === "win32" ? "D:/Temp" : os.tmpdir(); + await fs.mkdir(base, { recursive: true }); + const home = await fs.mkdtemp(path.join(base, "large-session-metadata-")); + cleanups.push(() => fs.rm(home, { recursive: true, force: true })); + await fs.mkdir(path.join(home, "sessions")); + await fs.mkdir(path.join(home, "sqlite")); + await fs.writeFile(path.join(home, "config.toml"), 'model_provider="openai"\n[model_providers.provider_long]\nmodel="fixture"\n'); + const file = path.join(home, "sessions", "rollout-fixture.jsonl"); + const dbPath = path.join(home, "sqlite", "state_5.sqlite"); + const db = await openDatabase(dbPath); + db.exec("CREATE TABLE threads (id TEXT PRIMARY KEY, model_provider TEXT, archived INTEGER DEFAULT 0, updated_at INTEGER DEFAULT 123); INSERT INTO threads (id,model_provider) VALUES ('fixture','custom');"); + db.close(); + return { home, file, dbPath }; +} + +async function digest(file, start = 0) { + const hash = createHash("sha256"); + for await (const chunk of fsSync.createReadStream(file, { start })) hash.update(chunk); + return hash.digest("hex"); +} + +async function writeHeader(file, bytes, separator = "\r\n") { + const prefix = '{"type":"session_meta","payload":{"id":"fixture","model_provider":"custom","instructions":"'; + const suffix = '中文"}}'; + const handle = await fs.open(file, "w"); + try { + await handle.write(prefix); + let remaining = bytes - Buffer.byteLength(prefix + suffix); + const chunk = Buffer.alloc(64 * 1024, 120); + while (remaining > 0) { + const size = Math.min(remaining, chunk.length); + await handle.write(chunk.subarray(0, size)); + remaining -= size; + } + await handle.write(suffix + separator); + for (let i = 0; i < 32; i++) await handle.write(Buffer.alloc(MiB, 121)); + } finally { await handle.close(); } +} + +test("large valid metadata: Status, in-place Sync, streaming Switch and Restore preserve data", async t => { + const value = await fixture(t); + const requestedSize = Number(process.env.CPS_LARGE_HEADER_MIB ?? 8) * MiB; + // Leave room for the longer Provider, so the successful write stays readable. + const size = Math.min(requestedSize, PROVIDER_SESSION_META_MAX_BYTES - 16); + assert.ok(size >= 8 * MiB && size <= PROVIDER_SESSION_META_MAX_BYTES); + await writeHeader(value.file, size); + const original = await digest(value.file); + const body = await digest(value.file, size + 2); + const before = await fs.stat(value.file); + const started = performance.now(); + const status = await getStatus({ codexHome: value.home, includeSessionActivity: false }); + assert.equal(status.rolloutScanComplete, true); + assert.equal(status.rolloutCounts.sessions.custom, 1); + const sync = await runSync({ codexHome: value.home }); + assert.equal(sync.partial, false); + assert.equal(sync.inPlaceSessionFiles, 1); + const synced = await fs.stat(value.file); + assert.equal(synced.ino, before.ino); + assert.equal(synced.size, before.size); + assert.ok(Math.abs(synced.mtimeMs - before.mtimeMs) < 1); + assert.equal(await digest(value.file, size + 2), body); + const db = await openDatabase(value.dbPath); + try { assert.deepEqual({ ...db.prepare("SELECT model_provider, updated_at FROM threads").get() }, { model_provider: "openai", updated_at: 123 }); } + finally { db.close(); } + await runRestore({ codexHome: value.home, backupDir: sync.backupDir }); + assert.equal(await digest(value.file), original); + const switched = await runSwitch({ codexHome: value.home, provider: "provider_long", keepRootModel: true }); + assert.equal(switched.partial, false); + assert.equal(switched.rewrittenSessionFiles, 1); + const afterSwitch = await getStatus({ codexHome: value.home, includeSessionActivity: false }); + assert.equal(afterSwitch.rolloutScanComplete, true); + await prepareSync({ codexHome: value.home }); + assert.equal(await digest(value.file, size + 2 + "provider_long".length - "openai".length), body); + await runRestore({ codexHome: value.home, backupDir: switched.backupDir }); + assert.equal(await digest(value.file), original); + t.diagnostic(JSON.stringify({ headerBytes: size, headerMiB: size / MiB, elapsedMs: Math.round(performance.now() - started), parentPeakRssKiB: process.resourceUsage().maxRSS })); +}); + +test("bounded reader accepts exact 128 MiB with LF, CRLF or EOF and rejects an extra byte", async () => { + // Virtual files avoid writing three 128 MiB fixtures; the actual reader still + // consumes every byte. Count only linear merge work, not elapsed-time guesses. + for (const separator of ["\n", "\r\n", ""]) { + let read = 0; + let closed = false; + let merged = 0; + const originalConcat = Buffer.concat; + const max = PROVIDER_SESSION_META_MAX_BYTES; + const fsImpl = { async open() { return { + async read(buffer, offset, length, position) { + const count = Math.max(0, Math.min(length, max + separator.length - position)); + buffer.fill(120, offset, offset + count); + for (let i = 0; i < separator.length; i++) { + if (max + i >= position && max + i < position + count) buffer[offset + max + i - position] = separator.charCodeAt(i); + } + read += count; + return { bytesRead: count }; + }, async close() { closed = true; } + }; } }; + Buffer.concat = function(chunks, length) { if (length >= max) merged += length; return originalConcat(chunks, length); }; + try { + const record = await readProviderRevisionHeader("virtual", { fsImpl }); + assert.equal(record.firstLine.length, max); + assert.equal(record.separator, separator); + assert.equal(record.offset, max + separator.length); + assert.equal(read, max + separator.length); + assert.ok(merged <= max + 1); + assert.equal(closed, true); + } finally { Buffer.concat = originalConcat; } + } + let read = 0; + const fsImpl = { async open() { return { + async read(buffer, offset, length) { buffer.fill(120); read += length; return { bytesRead: length }; }, + async close() {} + }; } }; + await assert.rejects(readProviderRevisionHeader("virtual", { fsImpl }), { name: "RolloutMetadataLimitError" }); + assert.ok(read <= PROVIDER_SESSION_META_MAX_BYTES + 2); +}); + +test("header reader handles split CRLF and UTF-8 without scanning the body", async () => { + for (const prefixLength of [65529, 65532]) { + const firstLine = "x".repeat(prefixLength) + "中文"; + const source = Buffer.concat([Buffer.from(firstLine + "\r\n"), Buffer.alloc(8 * MiB, 121)]); + let read = 0; + const fsImpl = { async open() { return { + async read(buffer, offset, length, position) { + const count = source.copy(buffer, offset, position, position + length); + read += count; + return { bytesRead: count }; + }, async close() {} + }; } }; + const record = await readProviderRevisionHeader("virtual", { fsImpl }); + assert.equal(record.firstLine, firstLine); + assert.equal(record.separator, "\r\n"); + assert.equal(record.offset, Buffer.byteLength(firstLine) + 2); + assert.equal(read, 128 * 1024); + } +}); + +test("invalid and oversized metadata are excluded from Prepare with safe reasons and zero writes", async t => { + const value = await fixture(t); + for (const code of ["ROLLOUT_METADATA_INVALID", "ROLLOUT_METADATA_TOO_LARGE"]) { + await fs.writeFile(value.file, "not-json\n"); + if (code.endsWith("TOO_LARGE")) { + await fs.writeFile(value.file, "x"); + await fs.truncate(value.file, PROVIDER_SESSION_META_MAX_BYTES + 1); + } + const before = await digest(value.file); + const config = await fs.readFile(path.join(value.home, "config.toml")); + const db = await digest(value.dbPath); + for (const prepare of [() => prepareSync({ codexHome: value.home }), () => prepareSwitch({ codexHome: value.home, provider: "provider_long" })]) { + const plan = await prepare(); + assert.equal(plan.impact.rolloutFilesToChange, 0); + assert.ok(plan.impact.skipSummary.items.some(item => item.reason === (code.endsWith("TOO_LARGE") ? "metadata-too-large" : "metadata-invalid"))); + } + assert.equal(await digest(value.file), before); + assert.equal(await digest(value.dbPath), db); + assert.deepEqual(await fs.readFile(path.join(value.home, "config.toml")), config); + await assert.rejects(fs.stat(path.join(value.home, "backups_state")), { code: "ENOENT" }); + const response = await dispatchWebCoreRequest({ async prepareSync() { throw new CoreError(code, "sensitive fixture text"); } }, { + protocolVersion: 1, requestId: "metadata-error", method: "prepareSync", payload: { profile: { profileId: "fixture" } } + }); + assert.equal(response.statusCode, 422); + assert.equal(response.envelope.error.code, code); + const raw = new CoreError(code, "sensitive fixture text", { details: { path: value.file, failureStage: "prepare_rollouts" } }).toDto(); + for (const dto of [createPublicCoreErrorDto(code, raw), normalizeCliErrorDto(raw)]) { + assert.equal(dto.code, code); + assert.equal(dto.retryable, false); + assert.equal(dto.severity, "error"); + assert.equal(dto.recoveryRequired, false); + assert.equal(isCanonicalPublicCoreErrorDto(dto), true); + assert.doesNotMatch(JSON.stringify(dto), /sensitive|rollout-fixture/); + } + } +}); + + +test("Switch skips an oversized output but still changes configuration", async t => { + const value = await fixture(t); + await writeHeader(value.file, PROVIDER_SESSION_META_MAX_BYTES); + const before = await digest(value.file); + const plan = await prepareSwitch({ codexHome: value.home, provider: "provider_long" }); + assert.equal(plan.impact.rolloutFilesToChange, 0); + const result = await applySwitch({ schemaVersion: 1, planId: plan.planId }); + assert.equal(result.outcome, "partial"); + assert.equal(result.result.configUpdated, true); + assert.equal(result.result.changedSessionFiles, 0); + assert.equal(await digest(value.file), before); + assert.match(await fs.readFile(path.join(value.home, "config.toml"), "utf8"), /model_provider = "provider_long"/); +}); diff --git a/test/plan-apply.test.js b/test/plan-apply.test.js index af2ea8e..49f71c2 100644 --- a/test/plan-apply.test.js +++ b/test/plan-apply.test.js @@ -297,7 +297,7 @@ test("applySync rejects config drift under the write locks before backup", async } }); -test("applySync rejects rollout header and State DB Provider drift before backup", async () => { +test("applySync skips individual rollout and Provider row drift", async () => { for (const drift of ["rollout", "state-db"]) { const value = await makeFixture(); try { @@ -312,12 +312,11 @@ test("applySync rejects rollout header and State DB Provider drift before backup db.close(); } } - await assert.rejects( - applySync({ schemaVersion: 1, planId: plan.planId }), - (error) => error?.code === "STALE_STATE" && error?.details?.reason === drift, - drift - ); - assert.equal(await backupCount(value.codexHome), 0, drift); + const result = await applySync({ schemaVersion: 1, planId: plan.planId }); + assert.equal(result.outcome, "partial", drift); + const db = await openDatabase(value.stateDbPath); + try { assert.equal(db.prepare("SELECT model_provider FROM threads WHERE id = 'thread-a'").get().model_provider, drift === "rollout" ? "custom" : "changed"); } finally { db.close(); } + assert.equal(await backupCount(value.codexHome), drift === "rollout" ? 0 : 1, drift); } finally { await fs.rm(value.root, { recursive: true, force: true }); } @@ -351,7 +350,7 @@ test("Sync and Switch allow body appends and non-Provider WAL updates between pr } }); -test("Provider plans still reject replacement, truncation, inventory and schema changes before backup", async (t) => { +test("Provider plans skip changed targets and defer new targets but reject schema drift", async (t) => { for (const drift of ["replace", "truncate", "new-rollout", "new-row", "schema"]) { const value = await makeFixture(); cleanups.push(() => fs.rm(value.root, { recursive: true, force: true })); @@ -371,8 +370,22 @@ test("Provider plans still reject replacement, truncation, inventory and schema db.exec(drift === "schema" ? "ALTER TABLE threads ADD COLUMN extra TEXT" : "INSERT INTO threads (id, model_provider) VALUES ('thread-b', 'custom')"); } finally { db.close(); } } - await assert.rejects(applySync({ schemaVersion: 1, planId: plan.planId }), (error) => error.code === "STALE_STATE", drift); - assert.equal(await backupCount(value.codexHome), 0, drift); + if (drift === "schema") { + await assert.rejects(applySync({ schemaVersion: 1, planId: plan.planId }), error => error.code === "STALE_STATE"); + assert.equal(await backupCount(value.codexHome), 0); + } else { + const result = await applySync({ schemaVersion: 1, planId: plan.planId }); + if (["replace", "truncate"].includes(drift)) { + assert.equal(result.outcome, "partial"); + assert.equal(result.result.changedSessionFiles, 0); + assert.equal(result.result.sqliteRowsUpdated, 0); + } else if (drift === "new-row") { + const db = await openDatabase(value.stateDbPath); + try { assert.equal(db.prepare("SELECT model_provider FROM threads WHERE id='thread-b'").get().model_provider, "custom"); } finally { db.close(); } + } else { + assert.match(await fs.readFile(path.join(path.dirname(value.rolloutPath), "rollout-new.jsonl"), "utf8"), /"custom"/); + } + } } }); @@ -521,7 +534,8 @@ test("different Codex Homes sharing one State DB rely on native SQLite transacti release(); const firstApplied = await firstApply; - assert.equal(firstApplied.outcome, "completed"); + assert.equal(firstApplied.outcome, "partial"); + assert.ok(firstApplied.result.skipSummary.items.some(item => item.reason === "row-changed")); } finally { release?.(); await fs.rm(value.root, { recursive: true, force: true }); diff --git a/test/provider-header-validation.test.js b/test/provider-header-validation.test.js new file mode 100644 index 0000000..3678ac5 --- /dev/null +++ b/test/provider-header-validation.test.js @@ -0,0 +1,227 @@ +import assert from "node:assert/strict"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { promisify } from "node:util"; +import { execFile } from "node:child_process"; +import test, { afterEach } from "node:test"; + +const cleanups = []; +afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); }); +import { collectProviderChanges, collectSessionChanges, readProviderRevisionHeader, applySessionChanges } from "../src/session-files.js"; +import { prepareSync, applySync, getStatus, prepareRestore, applyRestore, prepareSwitch, applySwitch } from "../src/service.js"; +import { openDatabase } from "../src/sqlite.js"; + +const header = (id, provider = "custom", extra = {}) => JSON.stringify({ type: "session_meta", payload: { id, model_provider: provider, ...extra } }); +const nested = (depth, id = "bad") => '{"type":"session_meta","payload":{"id":"' + id + '","model_provider":"custom","extra":' + '['.repeat(depth) + '0' + ']'.repeat(depth) + '}}'; +const invalidUtf8 = Buffer.concat([Buffer.from('{"type":"session_meta","payload":{"id":"bad","model_provider":"custom","extra":"'), Buffer.from([0xff]), Buffer.from('"}}')]); + +async function fixture(t, withPath = true) { + const base = process.platform === "win32" ? "D:/Temp/" : os.tmpdir(); + await fs.mkdir(base, { recursive: true }); + const home = await fs.mkdtemp(path.join(base, "provider-header-")); + cleanups.push(() => fs.rm(home, { recursive: true, force: true })); + await fs.mkdir(path.join(home, "sessions")); + await fs.mkdir(path.join(home, "archived_sessions")); + await fs.mkdir(path.join(home, "sqlite")); + await fs.writeFile(path.join(home, "config.toml"), 'model_provider="openai"\n[model_providers.custom]\nname="Custom"\n'); + const good = path.join(home, "sessions", "rollout-good.jsonl"); + const bad = path.join(home, "archived_sessions", "rollout-bad.jsonl"); + const originalGood = header("good") + '\r\n{"type":"event_msg","payload":{"message":"fixture body"}}\n'; + await fs.writeFile(good, originalGood); + await fs.writeFile(bad, header("bad")); + const dbPath = path.join(home, "sqlite", "state_5.sqlite"); + const db = await openDatabase(dbPath); + try { + db.exec(`CREATE TABLE threads(id TEXT PRIMARY KEY, model_provider TEXT, archived INTEGER DEFAULT 0, updated_at INTEGER DEFAULT 42${withPath ? ', rollout_path TEXT' : ''})`); + for (const [id, file] of [["good", good], ["bad", bad], ["sqlite-only", null]]) { + if (withPath) db.prepare("INSERT INTO threads(id, model_provider, rollout_path) VALUES (?, 'custom', ?)").run(id, file); + else db.prepare("INSERT INTO threads(id, model_provider) VALUES (?, 'custom')").run(id); + } + } finally { db.close(); } + return { home, good, bad, originalGood, async rows() { + const db = await openDatabase(dbPath); + try { return Object.fromEntries(db.prepare("SELECT id, model_provider FROM threads").all().map(row => [row.id, row.model_provider])); } + finally { db.close(); } + } }; +} +const apply = plan => applySync({ schemaVersion: 1, planId: plan.planId }); + +for (const [name, content, reason] of [ + ["invalid UTF-8", invalidUtf8, "metadata-invalid-utf8"], + ["array payload", Buffer.from('{"type":"session_meta","payload":[]}'), "metadata-invalid"], + ["serialization capacity", Buffer.from(nested(20000)), "metadata-too-complex"] +]) test(`${name}: skip file and index, sync healthy data, freeze exclusion, restore only written files`, async t => { + const f = await fixture(t); + await fs.writeFile(f.bad, content); + const plan = await prepareSync({ codexHome: f.home }); + assert.equal(plan.impact.rolloutFilesToChange, 1); + assert.equal(plan.impact.sqliteRowsToChange, 2); + assert.ok(plan.impact.skipSummary.items.some(item => item.kind === "rollout" && item.reason === reason)); + assert.equal(plan.impact.skipSummary.retryRecommended, false); + const result = await apply(plan); + assert.equal(result.outcome, "partial"); + assert.equal(result.result.changedSessionFiles, 1); + assert.deepEqual(await fs.readFile(f.bad), content); + assert.deepEqual(await f.rows(), { good: "openai", bad: "custom", "sqlite-only": "openai" }); + const repaired = header("bad") + '\n'; + const frozen = await prepareSync({ codexHome: f.home }); + await fs.writeFile(f.bad, repaired); + await apply(frozen); + assert.equal(await fs.readFile(f.bad, "utf8"), repaired); + const restore = await prepareRestore({ codexHome: f.home, backupId: result.backup.backupId }); + await applyRestore({ schemaVersion: 1, planId: restore.planId }); + assert.equal(await fs.readFile(f.bad, "utf8"), repaired); + assert.equal(await fs.readFile(f.good, "utf8"), f.originalGood); + const next = await prepareSync({ codexHome: f.home }); + assert.equal(next.impact.rolloutFilesToChange, 2); +}); + +test("strict decoding covers both returns, chunk boundaries, BOM and valid replacement characters", async t => { + const f = await fixture(t); + for (const separator of ["\n", "\r\n", ""]) { + for (const malformed of [invalidUtf8, Buffer.from([0xe4, 0xb8]), Buffer.from([0xc0, 0xaf])]) { + await fs.writeFile(f.bad, Buffer.concat([malformed, Buffer.from(separator)])); + await assert.rejects(readProviderRevisionHeader(f.bad), { name: "RolloutMetadataEncodingError" }); + } + // Place a multibyte code point across a 64 KiB read boundary. + const prefix = '{"type":"session_meta","payload":{"id":"bad","extra":"'; + const text = prefix + "x".repeat(65535 - Buffer.byteLength(prefix)) + '中文😀�"}}'; + await fs.writeFile(f.bad, text + separator); + const record = await readProviderRevisionHeader(f.bad); + assert.equal(record.firstLine, text); + assert.equal(record.offset, Buffer.byteLength(text + separator)); + const scan = await collectProviderChanges(f.home, "openai"); + assert.equal(scan.changes.length, 2); // A missing Provider remains supported. + assert.equal(scan.skippedItems.length, 0); + } + for (const bytes of [Buffer.concat([Buffer.from([239, 187, 191]), Buffer.from(header("bad"))]), Buffer.from(header("bad"), "utf16le")]) { + await fs.writeFile(f.bad, bytes); + const scan = await collectProviderChanges(f.home, "openai"); + assert.equal(scan.changes.length, 1); + assert.equal(scan.skippedItems[0].reason, "metadata-invalid"); + } +}); + +test("Provider shape checks do not change shared legacy collection defaults", async t => { + const f = await fixture(t); + for (const payload of [[], null, "text", 1, false]) { + await fs.writeFile(f.bad, JSON.stringify({ type: "session_meta", payload })); + const scan = await collectProviderChanges(f.home, "openai"); + assert.equal(scan.changes.length, 1); + assert.equal(scan.skippedItems[0].reason, "metadata-invalid"); + } + await fs.writeFile(f.bad, '{"type":"session_meta","payload":[]}'); + const legacy = await collectSessionChanges(f.home, "openai", { includeModels: false, includeEncryptedContent: false }); + assert.equal(legacy.changes.length, 2); + const status = await getStatus({ codexHome: f.home }); + assert.equal(status.rolloutScanComplete, false); + assert.ok(status.skipSummary.items.some(item => item.reason === "metadata-invalid")); +}); + +test("semantic comparison capacity is skipped independently of serialization; supported nesting works", async t => { + const f = await fixture(t, false); + // JIT optimization changes which operation exhausts its stack first. Isolate + // only this case without JIT, keeping the real error and business flow in the + // same process. No product depth limit or mocked comparison is introduced. + const script = ` + import assert from "node:assert/strict"; + import fs from "node:fs/promises"; + import { isDeepStrictEqual } from "node:util"; + import { prepareSync, applySync } from "./src/service.js"; + const [home, bad] = process.argv.slice(1); + const nested = ${nested.toString()}; + let deep; + for (let depth = 500; depth <= 6000; depth += 250) { + const text = nested(depth); + const parsed = JSON.parse(text); + try { JSON.stringify(parsed); } catch { break; } + try { isDeepStrictEqual(parsed, JSON.parse(text)); } + catch (error) { assert.ok(error instanceof RangeError); deep = text; break; } + } + assert.ok(deep, "must exercise real equality overflow separately from stringify"); + await fs.writeFile(bad, deep); + const plan = await prepareSync({ codexHome: home }); + assert.equal(plan.impact.rolloutFilesToChange, 1); + assert.ok(plan.impact.skipSummary.items.some(item => item.reason === "metadata-too-complex")); + const result = await applySync({ schemaVersion: 1, planId: plan.planId }); + assert.equal(result.outcome, "partial"); + `; + await promisify(execFile)(process.execPath, ["--jitless", "--input-type=module", "-e", script, f.home, f.bad], { + cwd: new URL("..", import.meta.url), timeout: 30000, windowsHide: true + }); + assert.deepEqual(await f.rows(), { good: "openai", bad: "custom", "sqlite-only": "openai" }); + await fs.writeFile(f.bad, nested(100)); + assert.equal((await collectProviderChanges(f.home, "openai")).changes.length, 1); +}); + +test("unknown JSON processing exceptions still abort preparation", async t => { + const f = await fixture(t); + const stringify = JSON.stringify; + const failure = new Error("injected unknown processing failure"); + JSON.stringify = function(value, ...args) { + if (value?.payload?.id === "bad" && value.payload.model_provider === "openai") throw failure; + return stringify(value, ...args); + }; + try { await assert.rejects(collectProviderChanges(f.home, "openai"), error => error === failure); } + finally { JSON.stringify = stringify; } + assert.equal(await fs.readFile(f.good, "utf8"), f.originalGood); +}); + +test("write preflight detects invalid bytes replacing valid U+FFFD, for both write strategies", async t => { + const f = await fixture(t); + for (const provider of ["custom", "old"]) for (const separator of ["\n", ""]) { + await fs.writeFile(f.bad, header("bad", provider, { extra: "�" }) + separator); + const scan = await collectProviderChanges(f.home, "openai"); + const change = scan.changes.find(item => item.path === f.bad); + const bytes = await fs.readFile(f.bad); + bytes[bytes.indexOf(Buffer.from("�"))] = 0xff; + await fs.writeFile(f.bad, bytes); + // Keep identity/size stable and bind the fresh timestamp so the decoder or + // in-place byte comparison, rather than a timestamp mismatch, rejects it. + const stat = await fs.stat(f.bad); + change.originalMtimeMs = stat.mtimeMs; + if (change.inPlaceMutation) change.inPlaceMutation.originalMtimeMs = stat.mtimeMs; + const result = await applySessionChanges([change]); + assert.deepEqual(result.skippedChangedPaths, [f.bad]); + assert.deepEqual(await fs.readFile(f.bad), bytes); + } +}); + +test("invalid encoding introduced after backup preserves index and is excluded from Restore", async t => { + const f = await fixture(t); + await fs.writeFile(f.bad, header("bad", "old", { extra: "�" }) + '\n'); + let changed; + const plan = await prepareSync({ codexHome: f.home, faultInjector: async ({ point, path: file }) => { + if (point !== "before_rollout_apply" || file !== f.bad) return; + changed = await fs.readFile(file); + changed[changed.indexOf(Buffer.from("�"))] = 0xff; + await fs.writeFile(file, changed); + } }); + const result = await apply(plan); + assert.equal(result.outcome, "partial"); + assert.equal(result.result.changedSessionFiles, 1); + assert.equal((await f.rows()).bad, "custom"); + const restore = await prepareRestore({ codexHome: f.home, backupId: result.backup.backupId }); + await applyRestore({ schemaVersion: 1, planId: restore.planId }); + assert.deepEqual(await fs.readFile(f.bad), changed); +}); + +test("all invalid headers give zero-write Sync and config-only Switch", async t => { + const f = await fixture(t, false); + await fs.writeFile(f.bad, invalidUtf8); + await fs.writeFile(f.good, '{"type":"session_meta","payload":[]}'); + const status = await getStatus({ codexHome: f.home }); + assert.equal(status.rolloutScanComplete, false); + assert.ok(status.skipSummary.items.some(item => item.reason === "metadata-invalid-utf8")); + const sync = await apply(await prepareSync({ codexHome: f.home })); + assert.equal(sync.outcome, "partial"); + assert.equal(sync.backup, null); + assert.equal(sync.result.changedSessionFiles, 0); + assert.equal(sync.result.sqliteRowsUpdated, 0); + const plan = await prepareSwitch({ codexHome: f.home, provider: "custom", keepRootModel: true }); + const switched = await applySwitch({ schemaVersion: 1, planId: plan.planId }); + assert.equal(switched.result.configUpdated, true); + assert.equal(switched.result.changedSessionFiles, 0); + assert.ok(switched.backup); +}); diff --git a/test/provider-preparation-facts.test.js b/test/provider-preparation-facts.test.js index 7730ec7..caeeedf 100644 --- a/test/provider-preparation-facts.test.js +++ b/test/provider-preparation-facts.test.js @@ -65,7 +65,7 @@ test("Provider facts reuse the exact revision and change algorithm with one boun assert.deepEqual(probe.counts(), { opens: 3, bytes: 3 * 64 * 1024 }); const facts = await collectProviderPreparationFacts(value.home, "openai"); assert.deepEqual(probe.counts(), { opens: 4, bytes: 4 * 64 * 1024 }); - assert.deepEqual(facts.rollout, revision); + assert.deepEqual(withoutInternalBindings(facts.rollout), withoutInternalBindings(revision)); assert.deepEqual(facts.scan, changes); assert.deepEqual(facts.scan.providerCounts, status.providerCounts); } finally { probe.restore(); } @@ -106,8 +106,9 @@ test("merged Prepare retains locked cause/revision and never turns locked facts } }; const old = await captureRolloutRevision(value.home, { mode: "provider", fsImpl }); const facts = await collectProviderPreparationFacts(value.home, "openai", { fsImpl }); - assert.deepEqual(facts.rollout, old); - assert.deepEqual(facts.scan.lockedPaths, [value.file]); + assert.deepEqual(withoutInternalBindings(facts.rollout), withoutInternalBindings(old)); + assert.deepEqual(facts.scan.lockedPaths, ["EACCES", "EPERM"].includes(code) ? [] : [value.file]); + assert.ok(facts.scan.skipSummary.items.some(item => item.reason === (["EACCES", "EPERM"].includes(code) ? "unreadable" : "locked"))); assert.equal(facts.scan.changes.length, 0); assert.equal(facts.rollout.rolloutScanComplete, false); } @@ -127,7 +128,7 @@ test("shared facts keep nested active and archived inventories separate and revi const expected = await collectProviderChanges(value.home, "openai", { skipLockedReads: true }); const expectedRevision = await captureRolloutRevision(value.home, { mode: "provider" }); const facts = await collectProviderPreparationFacts(value.home, "openai"); - assert.deepEqual(facts.rollout, expectedRevision); + assert.deepEqual(withoutInternalBindings(facts.rollout), withoutInternalBindings(expectedRevision)); assert.equal(facts.rollout.fileCount, 4); assert.deepEqual(facts.scan.providerCounts, expected.providerCounts); assert.deepEqual(facts.scan.changes.map(change => [change.path, change]).sort(), expected.changes.map(change => [change.path, change]).sort()); @@ -135,11 +136,13 @@ test("shared facts keep nested active and archived inventories separate and revi assert.equal(facts.scan.changes.filter(change => change.directory === "archived_sessions").length, 2); }); -test("merged Prepare rejects invalid, oversized and symlinked metadata without writing", async t => { +test("merged Prepare excludes invalid metadata but rejects symlinks", async t => { const value = await fixture(t); - for (const content of ["not-json\n", '{"type":"event_msg","payload":{}}\n', "x".repeat(1024 * 1024 + 1) + "\n"]) { + for (const content of ["not-json\n", '{"type":"event_msg","payload":{}}\n']) { await fs.writeFile(value.file, content); - await assert.rejects(collectProviderPreparationFacts(value.home, "openai"), error => error.code === "ROLLOUT_CHANGED"); + const facts = await collectProviderPreparationFacts(value.home, "openai"); + assert.equal(facts.scan.changes.length, 0); + assert.ok(facts.scan.skipSummary.total > 0); assert.equal(await fs.readFile(value.file, "utf8"), content); } await fs.writeFile(value.file, value.line + "\n"); @@ -166,6 +169,9 @@ test("a candidate appended during the shared header read remains skipped, never } }; const facts = await collectProviderPreparationFacts(value.home, "openai", { fsImpl }); assert.equal(facts.scan.changes.length, 0); - assert.deepEqual(facts.scan.lockedPaths, [value.file]); + assert.deepEqual(facts.scan.lockedPaths, []); + assert.ok(facts.scan.skipSummary.items.some(item => item.path === value.file && item.reason === "changed")); assert.equal(facts.rollout.observedSizes["sessions/rollout-fixture.jsonl"], String((await fs.stat(value.file)).size)); }); + +function withoutInternalBindings({ fileBindings, ...revision }) { return revision; } diff --git a/test/provider-skip-associations.test.js b/test/provider-skip-associations.test.js new file mode 100644 index 0000000..e8e9eb6 --- /dev/null +++ b/test/provider-skip-associations.test.js @@ -0,0 +1,42 @@ +import assert from "node:assert/strict"; +import path from "node:path"; +import test from "node:test"; +import { selectProviderRows, rolloutSkip, summarizeSkips } from "../src/provider-skips.js"; +import { isSkipSummary } from "../packages/contracts/dist/index.js"; +const home = path.resolve("D:/synthetic-associations"); +const good = path.join(home, "sessions", "rollout-good.jsonl"); +const bad = path.join(home, "sessions", "rollout-bad.jsonl"); +const row = (id, rollout_path) => ({ id, rollout_path, model_provider: "old" }); +test("duplicate ID and path associations are excluded without guessing from filenames", () => { + const scan = { files: [{ path: good, id: "same" }, { path: bad, id: "same" }], skippedItems: [] }; + const result = selectProviderRows(home, scan, { key: "id", rows: [row("same", good), row("other", null)] }, "openai"); + assert.deepEqual(result.rows.map(r => r.id), ["other"]); + assert.equal(result.skippedItems[0].reason, "association-conflict"); + const sharedPath = selectProviderRows(home, { files: [{ path: good, id: null }], skippedItems: [] }, { key: "id", rows: [row("one", good), row("two", good)] }, "openai"); + assert.equal(sharedPath.rows.length, 0); +}); +test("a skipped known ID without an index row does not block unrelated SQLite-only rows", () => { + const result = selectProviderRows(home, { files: [{ path: bad, id: "known" }], skippedItems: [rolloutSkip(bad, "metadata-too-large", "scan", "known")] }, + { key: "id", rows: [row("index-only", null)] }, "openai"); + assert.deepEqual(result.rows.map(r => r.id), ["index-only"]); +}); +test("unknown bad metadata restricts updates to positive healthy associations", () => { + const scan = { files: [{ path: good, id: "good" }, { path: bad, id: null }], skippedItems: [rolloutSkip(bad, "metadata-invalid")] }; + for (const unknownPath of [null, path.join(home, "..", "outside.jsonl"), "../../sessions/rollout-bad.jsonl"]) { + const result = selectProviderRows(home, scan, { key: "id", rows: [row("good", good), row("unknown", unknownPath)] }, "openai"); + assert.deepEqual(result.rows.map(r => r.id), ["good"]); + } +}); +test("skip summaries deduplicate and bound detail bytes without exposing internal identifiers", () => { + const items = Array.from({ length: 205 }, (_, n) => rolloutSkip(path.join(home, "sessions", `rollout-${n}.jsonl`), "changed", "revalidate", "unsafe/private-id")); + const summary = summarizeSkips([...items, ...items]); + assert.equal(summary.total, 205); + assert.equal(summary.omitted, 5); + assert.ok(isSkipSummary(summary)); + assert.doesNotMatch(JSON.stringify(summary), /unsafe\/private-id/); + const huge = summarizeSkips(Array.from({ length: 200 }, (_, n) => rolloutSkip(path.join(home, "sessions", `rollout-${n}-${"长".repeat(10000)}.jsonl`), "metadata-invalid"))); + assert.equal(huge.total, 200); + assert.ok(huge.omitted > 0); + assert.ok(isSkipSummary(huge)); + assert.ok(Buffer.byteLength(JSON.stringify(huge)) <= 1024 * 1024); +}); diff --git a/test/provider-skip-data.test.js b/test/provider-skip-data.test.js new file mode 100644 index 0000000..9a32233 --- /dev/null +++ b/test/provider-skip-data.test.js @@ -0,0 +1,190 @@ +import assert from "node:assert/strict"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import test, { afterEach } from "node:test"; + +const cleanups = []; +afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); }); +import { prepareSync, applySync, prepareSwitch, applySwitch, prepareRestore, applyRestore, getStatus } from "../src/service.js"; +import { openDatabase } from "../src/sqlite.js"; + +const line = id => JSON.stringify({ type: "session_meta", payload: { id, model_provider: "custom" } }) + '\n{"type":"event_msg","payload":{"message":"synthetic body"}}\n'; +async function fixture(t, withPath = true) { + const base = process.platform === "win32" ? "D:/Temp/" : os.tmpdir(); + await fs.mkdir(base, { recursive: true }); + const root = await fs.mkdtemp(path.join(base, "provider-skip-")); + cleanups.push(() => fs.rm(root, { recursive: true, force: true })); + const home = path.join(root, "home"), sessions = path.join(home, "sessions"), dbPath = path.join(home, "sqlite", "state_5.sqlite"); + await fs.mkdir(sessions, { recursive: true }); + await fs.mkdir(path.dirname(dbPath), { recursive: true }); + await fs.writeFile(path.join(home, "config.toml"), 'model_provider = "openai"\n[model_providers.custom]\nname = "Custom"\n'); + const good = path.join(sessions, "rollout-good.jsonl"), bad = path.join(sessions, "rollout-bad.jsonl"); + await fs.writeFile(good, line("good")); + await fs.writeFile(bad, "invalid metadata\n"); + const db = await openDatabase(dbPath); + try { + db.exec(`CREATE TABLE threads (id TEXT PRIMARY KEY, model_provider TEXT, archived INTEGER DEFAULT 0, updated_at INTEGER DEFAULT 42${withPath ? ", rollout_path TEXT" : ""})`); + for (const [id, file] of [["good", good], ["bad", bad], ["sqlite-only", null]]) { + if (withPath) db.prepare("INSERT INTO threads(id, model_provider, rollout_path) VALUES (?, 'custom', ?)").run(id, file); + else db.prepare("INSERT INTO threads(id, model_provider) VALUES (?, 'custom')").run(id); + } + } finally { db.close(); } + return { home, good, bad, dbPath, async rows() { + const db = await openDatabase(dbPath); + try { return Object.fromEntries(db.prepare("SELECT id, model_provider FROM threads").all().map(r => [r.id, r.model_provider])); } finally { db.close(); } + } }; +} +const apply = plan => applySync({ schemaVersion: 1, planId: plan.planId }); + +test("mixed metadata preserves a bad file and its index, updates healthy data, and restores only written files", async t => { + const f = await fixture(t); + const before = await fs.readFile(f.good, "utf8"); + const plan = await prepareSync({ codexHome: f.home }); + assert.equal(plan.impact.rolloutFilesToChange, 1); + assert.equal(plan.impact.sqliteRowsToChange, 2); + assert.ok(plan.impact.skipSummary.total >= 1); + const result = await apply(plan); + assert.equal(result.outcome, "partial"); + assert.equal(result.result.changedSessionFiles, 1); + assert.equal(result.result.sqliteRowsUpdated, 2); + assert.deepEqual(await f.rows(), { good: "openai", bad: "custom", "sqlite-only": "openai" }); + assert.equal(await fs.readFile(f.bad, "utf8"), "invalid metadata\n"); + const status = await getStatus({ codexHome: f.home }); + assert.equal(status.rolloutScanComplete, false); + // A later repair must not be undone by restoring a backup which excluded it. + await fs.writeFile(f.bad, line("bad")); + const restore = await prepareRestore({ codexHome: f.home, backupId: result.backup.backupId }); + await applyRestore({ schemaVersion: 1, planId: restore.planId }); + assert.equal(await fs.readFile(f.bad, "utf8"), line("bad")); + assert.equal(await fs.readFile(f.good, "utf8"), before); +}); + +test("unidentified bad metadata without path column preserves uncertain SQLite-only rows", async t => { + const f = await fixture(t, false); + const plan = await prepareSync({ codexHome: f.home }); + assert.equal(plan.impact.sqliteRowsToChange, 1); + const result = await apply(plan); + assert.equal(result.outcome, "partial"); + assert.deepEqual(await f.rows(), { good: "openai", bad: "custom", "sqlite-only": "custom" }); + assert.ok(result.result.skipSummary.unconfirmed > 0); +}); + +test("preview exclusions remain frozen after repair and new files are deferred", async t => { + const f = await fixture(t); + const plan = await prepareSync({ codexHome: f.home }); + await fs.writeFile(f.bad, line("bad")); + const added = path.join(path.dirname(f.good), "rollout-new.jsonl"); + await fs.writeFile(added, line("new")); + await apply(plan); + assert.equal(await fs.readFile(f.bad, "utf8"), line("bad")); + assert.equal(await fs.readFile(added, "utf8"), line("new")); + assert.equal((await f.rows()).bad, "custom"); + const next = await prepareSync({ codexHome: f.home }); + assert.equal(next.impact.rolloutFilesToChange, 2); + await apply(next); + assert.equal((await f.rows()).bad, "openai"); +}); + +test("deleted eligible file preserves its index while another eligible file continues", async t => { + const f = await fixture(t); + await fs.writeFile(f.bad, line("bad")); + const plan = await prepareSync({ codexHome: f.home }); + await fs.unlink(f.good); + const result = await apply(plan); + assert.equal(result.outcome, "partial"); + assert.equal(result.result.changedSessionFiles, 1); + assert.equal((await f.rows()).good, "custom"); + assert.equal((await f.rows()).bad, "openai"); +}); + +test("all excluded yields no Sync backup but Switch backs up and changes config", async t => { + const f = await fixture(t, false); + await fs.writeFile(f.good, "invalid too\n"); + const sync = await apply(await prepareSync({ codexHome: f.home })); + assert.equal(sync.outcome, "partial"); + assert.equal(sync.backup, null); + assert.equal(sync.result.sqliteRowsUpdated, 0); + const plan = await prepareSwitch({ codexHome: f.home, provider: "custom", keepRootModel: true }); + const switched = await applySwitch({ schemaVersion: 1, planId: plan.planId }); + assert.equal(switched.outcome, "partial"); + assert.ok(switched.backup); + assert.equal(switched.result.configUpdated, true); + assert.equal(switched.result.changedSessionFiles, 0); + assert.match(await fs.readFile(path.join(f.home, "config.toml"), "utf8"), /model_provider = "custom"/); +}); + +test("a row whose rollout_path changes after preview is preserved", async t => { + const f = await fixture(t); + const plan = await prepareSync({ codexHome: f.home }); + const db = await openDatabase(f.dbPath); + try { db.prepare("UPDATE threads SET rollout_path=? WHERE id='good'").run(f.bad); } finally { db.close(); } + const result = await apply(plan); + assert.equal(result.outcome, "partial"); + assert.equal((await f.rows()).good, "custom"); + assert.ok(result.result.skipSummary.items.some(item => item.kind === "sqlite" && item.id === "good")); +}); + +test("a file disappearing after backup is excluded from physical Restore validation", async t => { + const f = await fixture(t); + await fs.writeFile(f.bad, line("bad")); + const plan = await prepareSync({ codexHome: f.home, faultInjector: async ({ point, path: file }) => { + if (point === "before_rollout_apply" && file === f.good) await fs.unlink(f.good); + } }); + const result = await apply(plan); + assert.equal(result.outcome, "partial"); + assert.equal(result.result.changedSessionFiles, 1); + assert.equal((await f.rows()).good, "custom"); + const restore = await prepareRestore({ codexHome: f.home, backupId: result.backup.backupId }); + await applyRestore({ schemaVersion: 1, planId: restore.planId }); + await assert.rejects(fs.stat(f.good), { code: "ENOENT" }); + assert.equal(await fs.readFile(f.bad, "utf8"), line("bad")); +}); + +test("replacing the database after rollout mutation stops before writing the replacement", async t => { + const f = await fixture(t); + let swapped = false; + const plan = await prepareSync({ codexHome: f.home, faultInjector: async ({ point }) => { + if (point !== "after_rollout_apply" || swapped) return; + swapped = true; + await fs.rename(f.dbPath, f.dbPath + ".original"); + await fs.copyFile(f.dbPath + ".original", f.dbPath); + } }); + const result = await apply(plan); + assert.equal(swapped, true); + assert.equal(result.outcome, "partial"); + assert.equal(result.result.changedSessionFiles, 1); + assert.equal(result.result.sqliteRowsUpdated, 0); + assert.deepEqual(await f.rows(), { good: "custom", bad: "custom", "sqlite-only": "custom" }); +}); + +test("mixed invalid, oversized, unreadable and busy files leave healthy rollout and index writable", async t => { + const f = await fixture(t, false); + const large = path.join(path.dirname(f.good), "rollout-large.jsonl"); + const denied = path.join(path.dirname(f.good), "rollout-denied.jsonl"); + const busy = path.join(path.dirname(f.good), "rollout-busy.jsonl"); + await fs.writeFile(large, "x"); + await fs.truncate(large, 128 * 1024 * 1024 + 1); + await fs.writeFile(denied, line("denied")); + await fs.writeFile(busy, line("busy")); + const originalOpen = fs.open; + fs.open = async (file, ...args) => { + if (String(file) === denied || String(file) === busy) throw Object.assign(new Error("synthetic read failure"), { code: String(file) === denied ? "EACCES" : "EBUSY" }); + return originalOpen(file, ...args); + }; + try { + const plan = await prepareSync({ codexHome: f.home }); + assert.equal(plan.impact.rolloutFilesToChange, 1); + for (const reason of ["metadata-invalid", "metadata-too-large", "unreadable", "locked"]) { + assert.ok(plan.impact.skipSummary.items.some(item => item.reason === reason), reason); + } + const result = await apply(plan); + assert.equal(result.outcome, "partial"); + assert.equal(result.result.changedSessionFiles, 1); + assert.equal(result.result.sqliteRowsUpdated, 1); + assert.deepEqual(await f.rows(), { good: "openai", bad: "custom", "sqlite-only": "custom" }); + } finally { fs.open = originalOpen; } + assert.equal(await fs.readFile(denied, "utf8"), line("denied")); + assert.equal(await fs.readFile(busy, "utf8"), line("busy")); + assert.equal((await fs.stat(large)).size, 128 * 1024 * 1024 + 1); +}); diff --git a/test/provider-sync-lite.test.js b/test/provider-sync-lite.test.js index 326a116..c9db678 100644 --- a/test/provider-sync-lite.test.js +++ b/test/provider-sync-lite.test.js @@ -602,7 +602,7 @@ test("rollout changed during Apply is reported separately and a fresh retry conv await fs.readFile(value.file), Buffer.concat([beforeBytes, Buffer.from('{"type":"event_msg","payload":{"type":"assistant_message","message":"later"}}\n')]) ); - assert.equal((await row(value)).model_provider, "openai"); + assert.equal((await row(value)).model_provider, "prov_a"); const retryPlan = await prepareSync({ codexHome: value.home }); const retry = await applySync({ schemaVersion: 1, planId: retryPlan.planId }); diff --git a/test/status-coordination.test.js b/test/status-coordination.test.js index f5cb96d..5b0d364 100644 --- a/test/status-coordination.test.js +++ b/test/status-coordination.test.js @@ -616,9 +616,9 @@ test("HTTP Status stays usable during normal chatting", async (t) => { test("Status keeps oversized metadata incomplete rather than claiming a healthy empty scan", async () => { const fixture = await makeFixture(); try { - await fs.writeFile(fixture.rolloutPath, JSON.stringify({ type: "session_meta", payload: { - id: "status-thread", model_provider: "openai", title: "x".repeat(1024 * 1024) - } }) + "\n"); + // A sparse, unterminated header exceeds the limit without allocating its text. + await fs.writeFile(fixture.rolloutPath, "x"); + await fs.truncate(fixture.rolloutPath, 128 * 1024 * 1024 + 1); const status = await getStatus({ codexHome: fixture.codexHome, includeSessionActivity: false }); assert.equal(status.rolloutScanComplete, false); assert.equal(status.operationInProgress, null); @@ -627,12 +627,12 @@ test("Status keeps oversized metadata incomplete rather than claiming a healthy }); for (const change of ["replace", "truncate"]) { - test(`Status still refuses a ${change} during header inspection`, async t => { + test(`Status rechecks a ${change} once and accepts the fresh stable snapshot`, async t => { const fixture = await makeFixture(); try { const header = await fs.readFile(fixture.rolloutPath); await syntheticAppend(fixture); - afterHeaderRead(t, fixture, async count => { + const reads = afterHeaderRead(t, fixture, async count => { if (count !== 1) return; if (change === "truncate") await fs.truncate(fixture.rolloutPath, header.length); else { @@ -641,8 +641,10 @@ for (const change of ["replace", "truncate"]) { } }); const status = await getStatus({ codexHome: fixture.codexHome, includeSessionActivity: false }); - assert.equal(status.statusReadBlocked?.reason, "revision-unverifiable"); - assert.equal(status.rolloutScanComplete, false); + assert.equal(status.statusReadBlocked, undefined); + assert.equal(reads(), 5, "one bounded fresh scan verifies the replacement; no polling"); + assert.equal(status.rolloutScanComplete, true); + assert.deepEqual(status.rolloutCounts.sessions, { openai: 1 }); assert.equal(status.operationInProgress, null); } finally { methodMocks.restoreAll(); diff --git a/test/sync-service.test.js b/test/sync-service.test.js index 5dcd538..ad7673e 100644 --- a/test/sync-service.test.js +++ b/test/sync-service.test.js @@ -3393,7 +3393,7 @@ test("assertSqliteWritable defaults to a fail-fast SQLite busy policy", async () } }); -test("runSync skips locked rollout files and still updates sqlite", async () => { +test("runSync skips locked rollout files and preserves uncertain sqlite rows", async () => { if (process.platform !== "win32") { return; } @@ -3416,7 +3416,7 @@ test("runSync skips locked rollout files and still updates sqlite", async () => } assert.equal(result.changedSessionFiles, 0); - assert.equal(result.sqliteRowsUpdated, 1); + assert.equal(result.sqliteRowsUpdated, 0); assert.deepEqual(result.skippedLockedRolloutFiles, [sessionPath]); assert.deepEqual(result.skippedChangedRolloutFiles, []); assert.equal(result.retryRecommended, true); @@ -3429,7 +3429,7 @@ test("runSync skips locked rollout files and still updates sqlite", async () => const row = db .prepare("SELECT model_provider FROM threads WHERE id = ?") .get("thread-a"); - assert.equal(row.model_provider, "openai"); + assert.equal(row.model_provider, "apigather"); } finally { db.close(); } @@ -4393,9 +4393,10 @@ test("real cli sync JSON reports a locked rollout as partial", { assert.equal(envelope.ok, true); assert.equal(envelope.outcome, "partial"); assert.deepEqual(envelope.result.skippedLockedRolloutFiles, [path.basename(sessionPath)]); - assert.equal(envelope.result.sqliteRowsUpdated, 1); + assert.equal(envelope.result.sqliteRowsUpdated, 0); assert.match(result.stderr, /\[1\/6\] Scanning rollout files/); - assert.equal(await readProvider(codexHome, "thread-json-locked"), "openai"); + assert.equal(await readProvider(codexHome, "thread-json-locked"), "apigather"); + assert.ok(envelope.result.skipSummary.items.some(item => item.path === sessionPath)); }); test("syncDirectory only downgrades known unsupported flush errors on Windows", async () => { diff --git a/test/windows-provider-bytes.ps1 b/test/windows-provider-bytes.ps1 index 68a9bde..a69dfba 100644 --- a/test/windows-provider-bytes.ps1 +++ b/test/windows-provider-bytes.ps1 @@ -4,6 +4,7 @@ Add-Type -Path $Source Add-Type -TypeDefinition @' using System; using System.IO; +public sealed class SyntheticDiskFull : IOException { public SyntheticDiskFull() : base("Synthetic disk full") { HResult = unchecked((int)0x80070070); } } public sealed class FaultingProviderStream : FileStream { readonly string kind; int writes, syncs; @@ -12,9 +13,10 @@ public sealed class FaultingProviderStream : FileStream { : base(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None) { this.kind = kind; } public override void Write(byte[] buffer, int offset, int count) { wrote = true; - if (kind == "write" || kind == "restore") { + if (kind == "write" || kind == "restore" || kind == "diskfull") { if (++writes == 1) { base.Write(buffer, offset, Math.Min(3, count)); + if (kind == "diskfull") throw new SyntheticDiskFull(); throw new IOException("Injected partial write failure"); } if (kind == "restore") throw new IOException("Injected recovery failure"); @@ -106,7 +108,7 @@ try { if (-not $rejected) { throw "Truncated recovery was not rejected" } } finally { $s.Dispose() } Write-Output "PASS: native identity, exclusive handle, in-place write, mtime, partial recovery, idempotence, append, unknown-byte rejection" - foreach ($kind in @("write", "flush", "restore")) { + foreach ($kind in @("write", "flush", "restore", "diskfull")) { [IO.File]::WriteAllBytes($file, [byte[]]($header + $tail)) $s = [FaultingProviderStream]::new($file, $kind) try { @@ -117,9 +119,24 @@ try { $ino = [string](([uint64]$info.IndexHigh -shl 32) -bor [uint64]$info.IndexLow) $mtime = ([double]($info.WriteTime - 116444736000000000L)) / 10000 $failed = $false - try { [ProviderByteFile]::Apply($s, $header, $old, $new, $offset, $size, $mtime, $dev, $ino, $false) | Out-Null } - catch { $failed = $true } - if (-not $failed) { throw "Injected $kind failure was ignored" } + $sourceUnchanged = $false + $outcome = $null + try { $outcome = [ProviderByteFile]::Apply($s, $header, $old, $new, $offset, $size, $mtime, $dev, $ino, $false) } + catch { + $failed = $true + $errorCursor = $_.Exception + while ($errorCursor) { + if ($errorCursor.Data["providerSyncSourceUnchanged"] -eq $true) { $sourceUnchanged = $true } + $errorCursor = $errorCursor.InnerException + } + } + if ($kind -eq "diskfull") { + if (-not $failed -or -not $sourceUnchanged) { throw "Recovered disk full did not stop with unchanged-source proof" } + } elseif ($kind -eq "restore") { + if (-not $failed) { throw "Unknown recovery failure was ignored" } + } elseif ($failed -or $outcome -ne "SKIP_NOT_APPLIED") { + throw "Verified recovered $kind failure did not return SKIP_NOT_APPLIED" + } } finally { $s.Dispose() } $isOriginal = $utf8.GetString([IO.File]::ReadAllBytes($file)) -eq $utf8.GetString([byte[]]($header + $tail)) if (($kind -ne "restore") -and (-not $isOriginal)) { throw "Immediate recovery failed for $kind" } diff --git a/test/windows-rewrite-worker.test.js b/test/windows-rewrite-worker.test.js index 6324bcf..027c786 100644 --- a/test/windows-rewrite-worker.test.js +++ b/test/windows-rewrite-worker.test.js @@ -102,7 +102,7 @@ test("native Windows helper recovers short writes and flush failures", { }); test("Windows rewrite worker reuses one process and preserves the closed result set", async () => { - const expectedResults = ["APPLIED", "APPLIED_IN_PLACE", "SKIP_BUSY", "SKIP_CHANGED"]; + const expectedResults = ["APPLIED", "APPLIED_IN_PLACE", "SKIP_BUSY", "SKIP_CHANGED", "SKIP_MISSING", "SKIP_UNREADABLE", "SKIP_NOT_APPLIED"]; const fake = createFakeSpawn({ respond(request) { return { diff --git a/web/dist/assets/index-B_v6pRZ5.css b/web/dist/assets/index-B_v6pRZ5.css deleted file mode 100644 index 1341d0f..0000000 --- a/web/dist/assets/index-B_v6pRZ5.css +++ /dev/null @@ -1,2 +0,0 @@ -/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */ -@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-space-y-reverse:0;--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-outline-style:solid}::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-space-y-reverse:0;--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-outline-style:solid}}}@layer theme{:root,:host{--font-sans:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-lg:32rem;--container-2xl:42rem;--container-3xl:48rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75 / 1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--leading-tight:1.25;--leading-normal:1.5;--leading-relaxed:1.625;--radius-md:.375rem;--radius-lg:.5rem;--radius-xl:.75rem;--radius-2xl:1rem;--animate-spin:spin 1s linear infinite;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before{box-sizing:border-box;border:0 solid;margin:0;padding:0}::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.sticky{position:sticky}.inset-0{inset:0}.top-0{top:0}.top-1\/2{top:50%}.top-2{top:calc(var(--spacing) * 2)}.top-4{top:calc(var(--spacing) * 4)}.right-2{right:calc(var(--spacing) * 2)}.right-4{right:calc(var(--spacing) * 4)}.right-5{right:calc(var(--spacing) * 5)}.bottom-5{bottom:calc(var(--spacing) * 5)}.left-1\/2{left:50%}.z-30{z-index:30}.z-40{z-index:40}.z-50{z-index:50}.z-\[60\]{z-index:60}.z-\[70\]{z-index:70}.col-span-2{grid-column:span 2/span 2}.mx-auto{margin-inline:auto}.my-1{margin-block:var(--spacing)}.my-3{margin-block:calc(var(--spacing) * 3)}.my-4{margin-block:calc(var(--spacing) * 4)}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mt-1{margin-top:var(--spacing)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mt-5{margin-top:calc(var(--spacing) * 5)}.mt-\[var\(--space-1\)\]{margin-top:var(--space-1)}.mt-\[var\(--space-5\)\]{margin-top:var(--space-5)}.mt-\[var\(--space-6\)\]{margin-top:var(--space-6)}.mb-1{margin-bottom:var(--spacing)}.mb-1\.5{margin-bottom:calc(var(--spacing) * 1.5)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-5{margin-bottom:calc(var(--spacing) * 5)}.mb-\[var\(--space-6\)\]{margin-bottom:var(--space-6)}.ml-1{margin-left:var(--spacing)}.ml-2{margin-left:calc(var(--spacing) * 2)}.ml-auto{margin-left:auto}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline-flex{display:inline-flex}.table{display:table}.h-2{height:calc(var(--spacing) * 2)}.h-4{height:calc(var(--spacing) * 4)}.h-8{height:calc(var(--spacing) * 8)}.h-9{height:calc(var(--spacing) * 9)}.h-10{height:calc(var(--spacing) * 10)}.h-\[var\(--control-height\)\]{height:var(--control-height)}.h-dvh{height:100dvh}.h-full{height:100%}.max-h-72{max-height:calc(var(--spacing) * 72)}.max-h-80{max-height:calc(var(--spacing) * 80)}.max-h-\[30\%\]{max-height:30%}.max-h-\[40\%\]{max-height:40%}.max-h-\[45\%\]{max-height:45%}.max-h-\[90vh\]{max-height:90vh}.max-h-\[calc\(100dvh-16px\)\]{max-height:calc(100dvh - 16px)}.min-h-0{min-height:0}.min-h-8{min-height:calc(var(--spacing) * 8)}.min-h-9{min-height:calc(var(--spacing) * 9)}.min-h-10{min-height:calc(var(--spacing) * 10)}.min-h-11{min-height:calc(var(--spacing) * 11)}.min-h-16{min-height:calc(var(--spacing) * 16)}.min-h-\[var\(--control-height\)\]{min-height:var(--control-height)}.min-h-screen{min-height:100vh}.w-4{width:calc(var(--spacing) * 4)}.w-6{width:calc(var(--spacing) * 6)}.w-10{width:calc(var(--spacing) * 10)}.w-64{width:calc(var(--spacing) * 64)}.w-\[min\(92vw\,420px\)\]{width:min(92vw,420px)}.w-\[min\(92vw\,680px\)\]{width:min(92vw,680px)}.w-full{width:100%}.max-w-2xl{max-width:var(--container-2xl)}.max-w-3xl{max-width:var(--container-3xl)}.max-w-\[85\%\]{max-width:85%}.max-w-\[1600px\]{max-width:1600px}.max-w-\[calc\(100vw-16px\)\]{max-width:calc(100vw - 16px)}.max-w-\[min\(12rem\,70vw\)\]{max-width:min(12rem,70vw)}.max-w-full{max-width:100%}.max-w-lg{max-width:var(--container-lg)}.min-w-0{min-width:0}.flex-1{flex:1}.shrink-0{flex-shrink:0}.border-collapse{border-collapse:collapse}.-translate-x-1\/2{--tw-translate-x:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.-translate-y-1\/2{--tw-translate-y:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.resize{resize:both}.list-decimal{list-style-type:decimal}.list-disc{list-style-type:disc}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-\[minmax\(0\,1fr\)_auto\]{grid-template-columns:minmax(0,1fr) auto}.grid-rows-1{grid-template-rows:repeat(1,minmax(0,1fr))}.grid-rows-\[auto_minmax\(0\,1fr\)\]{grid-template-rows:auto minmax(0,1fr)}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.place-items-center{place-items:center}.content-start{align-content:flex-start}.items-baseline{align-items:baseline}.items-center{align-items:center}.items-end{align-items:flex-end}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.justify-items-start{justify-items:start}.gap-0{gap:0}.gap-1{gap:var(--spacing)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-5{gap:calc(var(--spacing) * 5)}.gap-6{gap:calc(var(--spacing) * 6)}.gap-\[var\(--space-1\)\]{gap:var(--space-1)}.gap-\[var\(--space-2\)\]{gap:var(--space-2)}.gap-\[var\(--space-3\)\]{gap:var(--space-3)}.gap-\[var\(--space-4\)\]{gap:var(--space-4)}:where(.space-y-0\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * .5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * .5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(var(--spacing) * var(--tw-space-y-reverse));margin-block-end:calc(var(--spacing) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px * var(--tw-divide-y-reverse));border-bottom-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-\[var\(--border\)\]>:not(:last-child)){border-color:var(--border)}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.overscroll-contain{overscroll-behavior:contain}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-\[var\(--radius-control\)\]{border-radius:var(--radius-control)}.rounded-\[var\(--radius-panel\)\]{border-radius:var(--radius-panel)}.rounded-full{border-radius:2147483647px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-none{border-radius:0}.rounded-xl{border-radius:var(--radius-xl)}.rounded-br-md{border-bottom-right-radius:var(--radius-md)}.border{border-style:var(--tw-border-style);border-width:1px}.border-0{border-style:var(--tw-border-style);border-width:0}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-l-4{border-left-style:var(--tw-border-style);border-left-width:4px}.border-\[var\(--accent\)\]{border-color:var(--accent)}.border-\[var\(--border\)\]{border-color:var(--border)}.border-\[var\(--danger\)\]{border-color:var(--danger)}.border-\[var\(--success\)\]{border-color:var(--success)}.border-\[var\(--warning\)\]{border-color:var(--warning)}.bg-\[color\:var\(--surface-raised\)\/\.96\]{background-color:var(--surface-raised)/.96}.bg-\[var\(--accent\)\]{background-color:var(--accent)}.bg-\[var\(--accent-soft\)\]{background-color:var(--accent-soft)}.bg-\[var\(--danger\)\]{background-color:var(--danger)}.bg-\[var\(--danger-soft\)\]{background-color:var(--danger-soft)}.bg-\[var\(--input\)\]{background-color:var(--input)}.bg-\[var\(--success-soft\)\]{background-color:var(--success-soft)}.bg-\[var\(--surface\)\]{background-color:var(--surface)}.bg-\[var\(--surface-hover\)\]{background-color:var(--surface-hover)}.bg-\[var\(--surface-raised\)\]{background-color:var(--surface-raised)}.bg-\[var\(--warning-soft\)\]{background-color:var(--warning-soft)}.bg-black\/50{background-color:#00000080}@supports (color:color-mix(in lab, red, red)){.bg-black\/50{background-color:color-mix(in oklab, var(--color-black) 50%, transparent)}}.p-0{padding:0}.p-1\.5{padding:calc(var(--spacing) * 1.5)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-5{padding:calc(var(--spacing) * 5)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.p-\[var\(--space-4\)\]{padding:var(--space-4)}.p-\[var\(--space-5\)\]{padding:var(--space-5)}.p-\[var\(--space-6\)\]{padding:var(--space-6)}.px-0{padding-inline:0}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-\[var\(--space-3\)\]{padding-inline:var(--space-3)}.px-\[var\(--space-4\)\]{padding-inline:var(--space-4)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:var(--spacing)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-\[var\(--space-1\)\]{padding-block:var(--space-1)}.pt-2{padding-top:calc(var(--spacing) * 2)}.pr-10{padding-right:calc(var(--spacing) * 10)}.pr-12{padding-right:calc(var(--spacing) * 12)}.pb-1{padding-bottom:var(--spacing)}.pb-3{padding-bottom:calc(var(--spacing) * 3)}.pl-4{padding-left:calc(var(--spacing) * 4)}.pl-5{padding-left:calc(var(--spacing) * 5)}.pl-6{padding-left:calc(var(--spacing) * 6)}.pl-7{padding-left:calc(var(--spacing) * 7)}.pl-8{padding-left:calc(var(--spacing) * 8)}.text-center{text-align:center}.text-left{text-align:left}.align-middle{vertical-align:middle}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.\[font-size\:var\(--text-2xl\)\]{font-size:var(--text-2xl)}.\[font-size\:var\(--text-sm\)\]{font-size:var(--text-sm)}.\[font-size\:var\(--text-xs\)\]{font-size:var(--text-xs)}.text-\[0\.9em\]{font-size:.9em}.text-\[10px\]{font-size:10px}.leading-5{--tw-leading:calc(var(--spacing) * 5);line-height:calc(var(--spacing) * 5)}.leading-6{--tw-leading:calc(var(--spacing) * 6);line-height:calc(var(--spacing) * 6)}.leading-7{--tw-leading:calc(var(--spacing) * 7);line-height:calc(var(--spacing) * 7)}.leading-\[var\(--leading-normal\)\]{--tw-leading:var(--leading-normal);line-height:var(--leading-normal)}.leading-\[var\(--leading-relaxed\)\]{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.leading-\[var\(--leading-tight\)\]{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.text-\[var\(--accent-strong\)\]{color:var(--accent-strong)}.text-\[var\(--danger\)\]{color:var(--danger)}.text-\[var\(--muted\)\]{color:var(--muted)}.text-\[var\(--success\)\]{color:var(--success)}.text-\[var\(--text\)\]{color:var(--text)}.text-\[var\(--warning\)\]{color:var(--warning)}.text-white{color:var(--color-white)}.tabular-nums{--tw-numeric-spacing:tabular-nums;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.underline{text-decoration-line:underline}.underline-offset-2{text-underline-offset:2px}.accent-\[var\(--accent\)\]{accent-color:var(--accent)}.accent-\[var\(--muted\)\]{accent-color:var(--muted)}.shadow-2xl{--tw-shadow:0 25px 50px -12px var(--tw-shadow-color,#00000040);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-none{--tw-shadow:0 0 #0000;box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-xl{--tw-shadow:0 20px 25px -5px var(--tw-shadow-color,#0000001a), 0 8px 10px -6px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.\[box-shadow\:var\(--shadow-panel\)\]{box-shadow:var(--shadow-panel)}.blur{--tw-blur:blur(8px);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.backdrop-blur{--tw-backdrop-blur:blur(8px);-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.backdrop-blur-\[2px\]{--tw-backdrop-blur:blur(2px);-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}.select-text{-webkit-user-select:text;user-select:text}.placeholder\:text-\[var\(--muted\)\]::placeholder{color:var(--muted)}.first\:mt-0:first-child{margin-top:0}.last\:mb-0:last-child{margin-bottom:0}.last\:border-0:last-child{border-style:var(--tw-border-style);border-width:0}@media (hover:hover){.hover\:bg-\[var\(--accent-strong\)\]:hover{background-color:var(--accent-strong)}.hover\:bg-\[var\(--surface-hover\)\]:hover{background-color:var(--surface-hover)}.hover\:text-\[var\(--text\)\]:hover{color:var(--text)}.hover\:brightness-95:hover{--tw-brightness:brightness(95%);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}}.focus\:not-sr-only:focus{clip-path:none;white-space:normal;width:auto;height:auto;margin:0;padding:0;position:static;overflow:visible}.focus\:fixed:focus{position:fixed}.focus\:top-4:focus{top:calc(var(--spacing) * 4)}.focus\:left-4:focus{left:calc(var(--spacing) * 4)}.focus\:z-\[70\]:focus{z-index:70}.focus\:rounded:focus{border-radius:.25rem}.focus\:bg-\[var\(--accent\)\]:focus{background-color:var(--accent)}.focus\:bg-\[var\(--accent-soft\)\]:focus{background-color:var(--accent-soft)}.focus\:px-4:focus{padding-inline:calc(var(--spacing) * 4)}.focus\:py-2:focus{padding-block:calc(var(--spacing) * 2)}.focus\:text-white:focus{color:var(--color-white)}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.focus-visible\:ring-2:focus-visible{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus-visible\:ring-\[var\(--focus\)\]:focus-visible{--tw-ring-color:var(--focus)}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.focus-visible\:ring-offset-\[var\(--surface\)\]:focus-visible{--tw-ring-offset-color:var(--surface)}.focus-visible\:outline:focus-visible{outline-style:var(--tw-outline-style);outline-width:1px}.focus-visible\:outline-2:focus-visible{outline-style:var(--tw-outline-style);outline-width:2px}.focus-visible\:outline-\[var\(--accent\)\]:focus-visible{outline-color:var(--accent)}.focus-visible\:outline-\[var\(--focus\)\]:focus-visible{outline-color:var(--focus)}.focus-visible\:outline-none:focus-visible{--tw-outline-style:none;outline-style:none}.focus-visible\:ring-inset:focus-visible{--tw-ring-inset:inset}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:opacity-40:disabled{opacity:.4}.disabled\:opacity-50:disabled{opacity:.5}.data-\[state\=closed\]\:animate-none[data-state=closed]{animation:none}@media (min-width:40rem){.sm\:grid{display:grid}.sm\:w-auto{width:auto}.sm\:shrink{flex-shrink:1}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.sm\:grid-cols-\[180px_1fr\]{grid-template-columns:180px 1fr}.sm\:justify-end{justify-content:flex-end}.sm\:overflow-visible{overflow:visible}.sm\:pb-0{padding-bottom:0}}@media (min-width:48rem){.md\:col-span-2{grid-column:span 2/span 2}.md\:min-h-\[calc\(100vh-4rem\)\]{min-height:calc(100vh - 4rem)}.md\:grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-\[240px_minmax\(0\,1fr\)\]{grid-template-columns:240px minmax(0,1fr)}.md\:grid-rows-1{grid-template-rows:repeat(1,minmax(0,1fr))}.md\:border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.md\:border-b-0{border-bottom-style:var(--tw-border-style);border-bottom-width:0}.md\:p-4{padding:calc(var(--spacing) * 4)}.md\:p-8{padding:calc(var(--spacing) * 8)}.md\:px-6{padding-inline:calc(var(--spacing) * 6)}}@media (min-width:64rem){.lg\:block{display:block}.lg\:flex{display:flex}.lg\:hidden{display:none}.lg\:inline{display:inline}.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.lg\:grid-cols-\[minmax\(240px\,0\.85fr\)_minmax\(0\,1\.4fr\)\]{grid-template-columns:minmax(240px,.85fr) minmax(0,1.4fr)}.lg\:grid-cols-\[minmax\(240px\,300px\)_minmax\(0\,1fr\)\]{grid-template-columns:minmax(240px,300px) minmax(0,1fr)}.lg\:border-r{border-right-style:var(--tw-border-style);border-right-width:1px}}@media (min-width:80rem){.xl\:col-span-4{grid-column:span 4/span 4}.xl\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.xl\:grid-cols-\[minmax\(0\,1fr\)_420px\]{grid-template-columns:minmax(0,1fr) 420px}.xl\:grid-cols-\[minmax\(0\,1fr\)_minmax\(320px\,440px\)\]{grid-template-columns:minmax(0,1fr) minmax(320px,440px)}}.\[\&\>div\]\:py-2>div{padding-block:calc(var(--spacing) * 2)}@media (min-width:40rem){.sm\:\[\&\>div\]\:grid-cols-\[140px_minmax\(0\,1fr\)\]>div{grid-template-columns:140px minmax(0,1fr)}}.\[\&\>select\]\:max-w-full>select{max-width:100%}@media (max-height:500px){.\[\@media\(max-height\:500px\)\]\:hidden{display:none}.\[\@media\(max-height\:500px\)\]\:min-h-0{min-height:0}.\[\@media\(max-height\:500px\)\]\:p-1{padding:var(--spacing)}.\[\@media\(max-height\:500px\)\]\:py-1{padding-block:var(--spacing)}}}:root,:root[data-theme=light]{--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light;--surface:#f6f7fb;--surface-raised:#fff;--surface-hover:#eef1f7;--input:#fff;--border:#dce1eb;--text:#172033;--muted:#657086;--accent:#4867e8;--accent-strong:#3452ce;--accent-soft:#e9edff;--focus:#315ee8;--success:#16734a;--success-soft:#e6f6ee;--warning:#9a5b00;--warning-soft:#fff3d8;--danger:#b42335;--danger-soft:#fdebed;--control-height:2.5rem;--radius-control:.5rem;--radius-panel:.75rem;--shadow-panel:0 1px 2px #17203314, 0 8px 24px #17203308;--font-sans:"Segoe UI Variable Text", "Segoe UI", Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, sans-serif;--text-xs:.75rem;--text-sm:.875rem;--text-base:1rem;--text-lg:1.125rem;--text-xl:1.25rem;--text-2xl:1.5rem;--leading-tight:1.25;--leading-normal:1.5;--leading-relaxed:1.625;--space-1:.25rem;--space-2:.5rem;--space-3:.75rem;--space-4:1rem;--space-5:1.25rem;--space-6:1.5rem;font-family:var(--font-sans)}:root[data-theme=dark]{--lightningcss-light: ;--lightningcss-dark:initial;color-scheme:dark;--surface:#11141b;--surface-raised:#181d27;--surface-hover:#242b38;--input:#111722;--border:#30394a;--text:#eef2f8;--muted:#a6b0c1;--accent:#7189ff;--accent-strong:#8fa1ff;--accent-soft:#222d58;--focus:#91a3ff;--success:#67d8a4;--success-soft:#17392d;--warning:#f2bb61;--warning-soft:#3d2e17;--danger:#ff8c99;--danger-soft:#461e26}@media (prefers-color-scheme:dark){:root[data-theme=system]{--lightningcss-light: ;--lightningcss-dark:initial;color-scheme:dark;--surface:#11141b;--surface-raised:#181d27;--surface-hover:#242b38;--input:#111722;--border:#30394a;--text:#eef2f8;--muted:#a6b0c1;--accent:#7189ff;--accent-strong:#8fa1ff;--accent-soft:#222d58;--focus:#91a3ff;--success:#67d8a4;--success-soft:#17392d;--warning:#f2bb61;--warning-soft:#3d2e17;--danger:#ff8c99;--danger-soft:#461e26}}@media (prefers-reduced-motion:reduce){*,:before,:after{scroll-behavior:auto!important;transition-duration:.001ms!important;animation-duration:.001ms!important;animation-iteration-count:1!important}}html{background:var(--surface);min-width:320px}body{background:var(--surface);min-width:320px;min-height:100vh;margin:0}button,input,select{font:inherit}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-ordinal{syntax:"*";inherits:false}@property --tw-slashed-zero{syntax:"*";inherits:false}@property --tw-numeric-figure{syntax:"*";inherits:false}@property --tw-numeric-spacing{syntax:"*";inherits:false}@property --tw-numeric-fraction{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@keyframes spin{to{transform:rotate(360deg)}} diff --git a/web/dist/assets/index-Bp6DrQQ2.js b/web/dist/assets/index-Bp6DrQQ2.js deleted file mode 100644 index 2eab718..0000000 --- a/web/dist/assets/index-Bp6DrQQ2.js +++ /dev/null @@ -1,143 +0,0 @@ -var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;li[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,o)=>(o=n==null?{}:e(i(n)),c(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var u=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),d=o(((e,t)=>{t.exports=u()})),f=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.iterator;function m(e){return typeof e!=`object`||!e?null:(e=p&&e[p]||e[`@@iterator`],typeof e==`function`?e:null)}var h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,_={};function v(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}v.prototype.isReactComponent={},v.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function y(){}y.prototype=v.prototype;function b(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}var x=b.prototype=new y;x.constructor=b,g(x,v.prototype),x.isPureReactComponent=!0;var S=Array.isArray;function C(){}var w={H:null,A:null,T:null,S:null},T=Object.prototype.hasOwnProperty;function E(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function D(e,t){return E(e.type,t,e.props)}function O(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function ee(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var k=/\/+/g;function A(e,t){return typeof e==`object`&&e&&e.key!=null?ee(``+e.key):t.toString(36)}function j(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(C,C):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function M(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,M(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+A(e,0):a,S(o)?(i=``,c!=null&&(i=c.replace(k,`$&/`)+`/`),M(o,r,i,``,function(e){return e})):o!=null&&(O(o)&&(o=D(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(k,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(S(e))for(var u=0;u{t.exports=f()})),m=l(p(),1),h=d(),g=m.createContext(void 0),_=e=>{let t=m.useContext(g);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},v=({client:e,children:t})=>(m.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,h.jsx)(g.Provider,{value:e,children:t})),y={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},b=new class{#e=y;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function x(e){setTimeout(e,0)}var S=typeof window>`u`||`Deno`in globalThis;function C(){}function w(e,t){return typeof e==`function`?e(t):e}function T(e){return typeof e==`number`&&e>=0&&e!==1/0}function E(e,t){return Math.max(e+(t||0)-Date.now(),0)}function D(e,t){return typeof e==`function`?e(t):e}function O(e,t){return typeof e==`function`?e(t):e}function ee(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==A(o,t.options))return!1}else if(!M(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function k(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(j(t.options.mutationKey)!==j(a))return!1}else if(!M(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function A(e,t){return(t?.queryKeyHashFn||j)(e)}function j(e){return JSON.stringify(e,(e,t)=>ne(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function M(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){for(let n=0;n500)return t;let r=te(e)&&te(t);if(!r&&!(ne(e)&&ne(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l{b.setTimeout(t,e)})}function I(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:P(e,t)}function L(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function ae(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var oe=Symbol();function se(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===oe?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ce(e,t){return typeof e==`function`?e(...t):!!e}function le(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var ue=(()=>{let e=()=>S;return{isServer(){return e()},setIsServer(t){e=t}}})(),de=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},fe=new class extends de{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},pe=x;function me(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=pe,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var he=me(),ge=new class extends de{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function _e(e){return Math.min(1e3*2**e,3e4)}function ve(e){return(e??`online`)!==`online`||ge.isOnline()}var ye=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function be(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(C);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new ye(t);h(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>fe.isFocused()&&(e.networkMode===`always`||ge.isOnline())&&e.canRun(),p=()=>ve(e.networkMode)&&e.canRun(),m=e=>{c()||(r?.(),i=`resolved`,a(e))},h=e=>{c()||(r?.(),i=`rejected`,o(e))},g=()=>new Promise(t=>{r=e=>{(c()||f())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),_=()=>{if(c())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(m).catch(r=>{if(c())return;let i=e.retry??(ue.isServer()?0:3),a=e.retryDelay??_e,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&nf()?void 0:g()).then(()=>{t?h(r):_()})})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:p,start:()=>(p()?_():g().then(_),s)}}var xe=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),T(this.gcTime)&&(this.#e=b.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(ue.isServer()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(b.clearTimeout(this.#e),this.#e=void 0)}};function Se(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{le(e,()=>t.signal,()=>n=!0)},u=se(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?ae:L;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?Ce:R,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:R(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(ct.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function R(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Ce(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function we(e,t){return t?R(e,t)!=null:!1}function Te(e,t){return!t||!e.getPreviousPageParam?!1:Ce(e,t)!=null}var Ee=class extends xe{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=ke(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=ke(this.options);e.data!==void 0&&(this.setState(Oe(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=I(this.state.data,e,this.options);return this.#l({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(C).catch(C):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>O(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===oe||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>D(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!E(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#s||this.#c()?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}#c(){return this.state.fetchStatus===`paused`&&this.state.status===`pending`}invalidate(){this.state.isInvalidated||this.#l({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=se(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?Se(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#l({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=be({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof ye&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#l({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#l({type:`pause`})},onContinue:()=>{this.#l({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await o.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof ye){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#l({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0),this.scheduleGc()}}#l(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...De(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...Oe(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),he.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function De(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ve(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function Oe(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function ke(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var Ae=class extends de{#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Me(this.#t,this.options)?this.#m():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ne(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ne(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#y(),this.#b(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof O(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#x(),this.#t.setOptions(this.options),t._defaulted&&!F(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&Pe(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||O(this.options.enabled,this.#t)!==O(t.enabled,this.#t)||D(this.options.staleTime,this.#t)!==D(t.staleTime,this.#t))&&this.#h();let i=this.#g();r&&(this.#t!==n||O(this.options.enabled,this.#t)!==O(t.enabled,this.#t)||i!==this.#f)&&this.#_(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return Ie(this,n)&&(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t),r=()=>{},i,a=new Promise(e=>{i=e,r=this.#e.getQueryCache().subscribe(i=>{i.type===`updated`&&i.query.queryHash===n.queryHash&&n.state.data!==void 0&&(r(),e(this.createResult(n,t)))})});return Promise.race([n.fetch().then(()=>{let e=this.createResult(n,t);return i?.(e),e}).finally(()=>{r()}),a])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#x();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(C)),t}#h(){this.#y();let e=D(this.options.staleTime,this.#t);if(ue.isServer()||this.#r.isStale||!T(e))return;let t=E(this.#r.dataUpdatedAt,e)+1;this.#u=b.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#g(){return(typeof this.options.refetchInterval==`function`?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#_(e){this.#b(),this.#f=e,!(ue.isServer()||O(this.options.enabled,this.#t)===!1||!T(this.#f)||this.#f===0)&&(this.#d=b.setInterval(()=>{(this.options.refetchIntervalInBackground||fe.isFocused())&&this.#m()},this.#f))}#v(){this.#h(),this.#_(this.#g())}#y(){this.#u!==void 0&&(b.clearTimeout(this.#u),this.#u=void 0)}#b(){this.#d!==void 0&&(b.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&Me(e,t),o=i&&Pe(e,n,t,r);(a||o)&&(l={...l,...De(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(m=`success`,d=I(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h){if(i&&d===a?.data&&t.select===this.#s)d=this.#c;else try{this.#s=t.select,d=t.select(d),d=I(i?.data,d,t),this.#c=d,this.#o=null}catch(e){this.#o=e}}else d===void 0&&(this.#o=null);this.#o&&(f=this.#o,d=this.#c,p=Date.now(),m=`error`,u=!1);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0;return{status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:y,isLoading:y,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:Fe(e,t),refetch:this.refetch,isEnabled:O(t.enabled,e)!==!1}}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#l=this.#t),!F(t,e)&&(this.#r=t,this.#S({listeners:(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#p.size)return!0;let r=new Set(n??this.#p);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})()}))}#x(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#v()}#S(e){he.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function je(e,t){return O(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||O(t.retryOnMount,e)!==!1)}function Me(e,t){return je(e,t)||e.state.data!==void 0&&Ne(e,t,t.refetchOnMount)}function Ne(e,t,n){if(O(t.enabled,e)!==!1&&D(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&Fe(e,t)}return!1}function Pe(e,t,n,r){return(e!==t||O(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&Fe(e,n)}function Fe(e,t){return O(t.enabled,e)!==!1&&e.isStaleByTime(D(t.staleTime,e))}function Ie(e,t){return!F(e.getCurrentResult(),t)}var Le=class extends Ae{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type=`infinite`,super.setOptions(e)}getOptimisticResult(e){return e._type=`infinite`,super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:`forward`}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:`backward`}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:a,isError:o,isRefetchError:s}=r,c=n.fetchMeta?.fetchMore?.direction,l=o&&c===`forward`,u=i&&c===`forward`,d=o&&c===`backward`,f=i&&c===`backward`;return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:we(t,n.data),hasPreviousPage:Te(t,n.data),isFetchNextPageError:l,isFetchingNextPage:u,isFetchPreviousPageError:d,isFetchingPreviousPage:f,isRefetchError:s&&!l&&!d,isRefetching:a&&!u&&!f}}},Re=class extends xe{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||ze(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??(this.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},r=this.#r=be({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),i=this.state.status===`pending`,a=!r.canStart();try{if(i)t();else{this.#i({type:`pending`,variables:e,isPaused:a}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:a})}let o=await r.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#i({type:`success`,data:o}),o}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#r===r&&(this.#r=void 0),this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),he.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function ze(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var Be=class extends de{#e;#t;#n;constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}build(e,t,n){let r=new Re({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=Ve(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=Ve(e);if(typeof t==`string`){let n=this.#t.get(t);if(n){if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=Ve(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}return!0}runNext(e){let t=Ve(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){he.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>k(t,e))}findAll(e={}){return this.getAll().filter(t=>k(e,t))}notify(e){he.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return he.batch(()=>Promise.all(e.map(e=>e.continue().catch(C))))}};function Ve(e){return e.options.scope?.id}var He=class extends de{#e;#t=void 0;#n;#r;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),F(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&j(t.mutationKey)!==j(this.options.mutationKey)?this.reset():this.#n?.state.status===`pending`&&this.#n.setOptions(this.options)}onSubscribe(){this.listeners.size===1&&this.#n&&(this.#n.addObserver(this),this.#i())}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#i(),this.#a()}mutate(e,t){return this.#r=t,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(e)}#i(){let e=this.#n?.state??ze();this.#t={...e,isPending:e.status===`pending`,isSuccess:e.status===`success`,isError:e.status===`error`,isIdle:e.status===`idle`,mutate:this.mutate,reset:this.reset}}#a(e){he.batch(()=>{if(this.#r&&this.hasListeners()){let t=this.#t.variables,n=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{this.#r.onSuccess?.(e.data,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(e.data,null,t,n,r)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{this.#r.onError?.(e.error,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(void 0,e.error,t,n,r)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},Ue=class extends de{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){let r=t.queryKey,i=t.queryHash??A(r,t),a=this.get(i);return a||(a=new Ee({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){he.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>ee(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>ee(e,t)):t}notify(e){he.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){he.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){he.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},We=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new Ue,this.#t=e.mutationCache||new Be,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=fe.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=ge.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(D(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=w(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return he.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;he.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return he.batch(()=>{let r=n.findAll(e),i=new Set(r);return r.forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,predicate:e=>i.has(e)},t)})}cancelQueries(e,t={}){let n={revert:!0,...t},r=he.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(C).catch(C)}invalidateQueries(e,t={}){return he.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=he.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(C)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(C)}async query(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t),r=n.isStaleByTime(D(t.staleTime,n))?await n.fetch(t):n.state.data,i=t.select;return i?i(r):r}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(D(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(C).catch(C)}infiniteQuery(e){return e._type=`infinite`,this.query(e)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(C).catch(C)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return ge.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(j(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{M(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(j(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{M(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=A(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===oe&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},Ge=m.createContext(!1),Ke=()=>m.useContext(Ge);Ge.Provider;function qe(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Je=m.createContext(qe()),Ye=()=>m.useContext(Je),Xe=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?ce(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},Ze=e=>{m.useEffect(()=>{e.clearReset()},[e])},Qe=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||ce(n,[e.error,r])),$e=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},et=(e,t)=>e?.suspense&&t.isPending,tt=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function nt(e,t,n){let r=Ke(),i=Ye(),a=_(n),o=a.defaultQueryOptions(e),s=a.getQueryCache().get(o.queryHash),c=e.subscribed!==!1;o._optimisticResults=r?`isRestoring`:c?`optimistic`:void 0,$e(o),Xe(o,i,s),Ze(i);let[l]=m.useState(()=>new t(a,o)),u=l.getOptimisticResult(o),d=!r&&c;if(m.useSyncExternalStore(m.useCallback(e=>{let t=d?l.subscribe(he.batchCalls(e)):C;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),m.useEffect(()=>{l.setOptions(o)},[o,l]),et(o,u))throw tt(o,l,i);if(Qe({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return o.notifyOnChangeProps?u:l.trackResult(u)}function rt(e,t){return nt(e,Ae,t)}function it(e,t){let n=_(t);return ot({filters:{...e,status:`pending`}},n).length}function at(e,t){return e.findAll(t.filters).map(e=>t.select?t.select(e):e.state)}function ot(e={},t){let n=_(t).getMutationCache(),r=m.useRef(e),i=m.useRef(null);return i.current===null&&(i.current=at(n,e)),m.useEffect(()=>{r.current=e}),m.useSyncExternalStore(m.useCallback(e=>n.subscribe(()=>{let t=P(i.current,at(n,r.current));i.current!==t&&(i.current=t,he.schedule(e))}),[n]),()=>i.current,()=>i.current)}function st(e,t){let n=_(t),[r]=m.useState(()=>new He(n,e));m.useEffect(()=>{r.setOptions(e)},[r,e]);let i=m.useSyncExternalStore(m.useCallback(e=>r.subscribe(he.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=m.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(C)},[r]);if(i.error&&ce(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}function ct(e,t){return nt(e,Le,t)}var z=e=>typeof e==`string`,lt=()=>{let e,t,n=new Promise((n,r)=>{e=n,t=r});return n.resolve=e,n.reject=t,n},ut=e=>e==null?``:String(e),dt=(e,t,n)=>{e.forEach(e=>{t[e]&&(n[e]=t[e])})},ft=/###/g,pt=e=>e&&e.includes(`###`)?e.replace(ft,`.`):e,mt=e=>!e||z(e),ht=(e,t,n)=>{let r=z(t)?t.split(`.`):t,i=0;for(;i{let{obj:r,k:i}=ht(e,t,Object);if(r!==void 0||t.length===1){r[i]=n;return}let a=t[t.length-1],o=t.slice(0,t.length-1),s=ht(e,o,Object);for(;s.obj===void 0&&o.length;)a=`${o[o.length-1]}.${a}`,o=o.slice(0,o.length-1),s=ht(e,o,Object),s?.obj&&s.obj[`${s.k}.${a}`]!==void 0&&(s.obj=void 0);s.obj[`${s.k}.${a}`]=n},_t=(e,t,n,r)=>{let{obj:i,k:a}=ht(e,t,Object);i[a]=i[a]||[],i[a].push(n)},vt=(e,t)=>{let{obj:n,k:r}=ht(e,t);if(n&&Object.prototype.hasOwnProperty.call(n,r))return n[r]},yt=(e,t,n)=>{let r=vt(e,n);return r===void 0?vt(t,n):r},bt=(e,t,n)=>{for(let r in t)r!==`__proto__`&&r!==`constructor`&&(Object.prototype.hasOwnProperty.call(e,r)?z(e[r])||e[r]instanceof String||z(t[r])||t[r]instanceof String?n&&(e[r]=t[r]):bt(e[r],t[r],n):e[r]=t[r]);return e},xt=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,`\\$&`),St={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`,"/":`/`},Ct=e=>z(e)?e.replace(/[&<>"'\/]/g,e=>St[e]):e,wt=class{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){let t=this.regExpMap.get(e);if(t!==void 0)return t;let n=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,n),this.regExpQueue.push(e),n}},Tt=[` `,`,`,`?`,`!`,`;`],Et=new wt(20),Dt=(e,t,n)=>{t||=``,n||=``;let r=Tt.filter(e=>!t.includes(e)&&!n.includes(e));if(r.length===0)return!0;let i=Et.getRegExp(`(${r.map(e=>e===`?`?`\\?`:e).join(`|`)})`),a=!i.test(e);if(!a){let t=e.indexOf(n);t>0&&!i.test(e.substring(0,t))&&(a=!0)}return a},Ot=(e,t,n=`.`)=>{if(!e)return;if(e[t])return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;let r=t.split(n),i=e;for(let e=0;ee?.replace(/_/g,`-`),At={type:`logger`,log(e){this.output(`log`,e)},warn(e){this.output(`warn`,e)},error(e){this.output(`error`,e)},output(e,t){console?.[e]?.apply?.(console,t)}},jt=new class e{constructor(e,t={}){this.init(e,t)}init(e,t={}){this.prefix=t.prefix||`i18next:`,this.logger=e||At,this.options=t,this.debug=t.debug}log(...e){return this.forward(e,`log`,``,!0)}warn(...e){return this.forward(e,`warn`,``,!0)}error(...e){return this.forward(e,`error`,``)}deprecate(...e){return this.forward(e,`warn`,`WARNING DEPRECATED: `,!0)}forward(e,t,n,r){return r&&!this.debug?null:(e=e.map(e=>z(e)?e.replace(/[\r\n\x00-\x1F\x7F]/g,` `):e),z(e[0])&&(e[0]=`${n}${this.prefix} ${e[0]}`),this.logger[t](e))}create(t){return new e(this.logger,{prefix:`${this.prefix}:${t}:`,...this.options})}clone(t){return t||=this.options,t.prefix=t.prefix||this.prefix,new e(this.logger,t)}},Mt=class{constructor(){this.observers={}}on(e,t){return e.split(` `).forEach(e=>{this.observers[e]||(this.observers[e]=new Map);let n=this.observers[e].get(t)||0;this.observers[e].set(t,n+1)}),this}off(e,t){if(this.observers[e]){if(!t){delete this.observers[e];return}this.observers[e].delete(t)}}once(e,t){let n=(...r)=>{t(...r),this.off(e,n)};return this.on(e,n),this}emit(e,...t){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([e,n])=>{for(let r=0;r{for(let i=0;i-1&&this.options.ns.splice(t,1)}getResource(e,t,n,r={}){let i=r.keySeparator===void 0?this.options.keySeparator:r.keySeparator,a=r.ignoreJSONStructure===void 0?this.options.ignoreJSONStructure:r.ignoreJSONStructure,o;e.includes(`.`)?o=e.split(`.`):(o=[e,t],n&&(Array.isArray(n)?o.push(...n):z(n)&&i?o.push(...n.split(i)):o.push(n)));let s=vt(this.data,o);return!s&&!t&&!n&&e.includes(`.`)&&(e=o[0],t=o[1],n=o.slice(2).join(`.`)),s||!a||!z(n)?s:Ot(this.data?.[e]?.[t],n,i)}addResource(e,t,n,r,i={silent:!1}){let a=i.keySeparator===void 0?this.options.keySeparator:i.keySeparator,o=[e,t];n&&(o=o.concat(a?n.split(a):n)),e.includes(`.`)&&(o=e.split(`.`),r=t,t=o[1]),this.addNamespaces(t),gt(this.data,o,r),i.silent||this.emit(`added`,e,t,n,r)}addResources(e,t,n,r={silent:!1}){for(let r in n)(z(n[r])||Array.isArray(n[r]))&&this.addResource(e,t,r,n[r],{silent:!0});r.silent||this.emit(`added`,e,t,n)}addResourceBundle(e,t,n,r,i,a={silent:!1,skipCopy:!1}){let o=[e,t];e.includes(`.`)&&(o=e.split(`.`),r=n,n=t,t=o[1]),this.addNamespaces(t);let s=vt(this.data,o)||{};a.skipCopy||(n=JSON.parse(JSON.stringify(n))),r?bt(s,n,i):s={...s,...n},gt(this.data,o,s),a.silent||this.emit(`added`,e,t,n)}removeResourceBundle(e,t){this.hasResourceBundle(e,t)&&delete this.data[e][t],this.removeNamespaces(t),this.emit(`removed`,e,t)}hasResourceBundle(e,t){return this.getResource(e,t)!==void 0}getResourceBundle(e,t){return t||=this.options.defaultNS,this.getResource(e,t)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){let t=this.getDataByLanguage(e);return!!(t&&Object.keys(t)||[]).find(e=>t[e]&&Object.keys(t[e]).length>0)}toJSON(){return this.data}},Pt={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,n,r,i){return e.forEach(e=>{t=this.processors[e]?.process(t,n,r,i)??t}),t}},Ft=Symbol(`i18next/PATH_KEY`);function It(){let e=[],t=Object.create(null),n;return t.get=(r,i)=>(n?.revoke?.(),i===Ft?e:(e.push(i),n=Proxy.revocable(r,t),n.proxy)),Proxy.revocable(Object.create(null),t).proxy}function Lt(e,t){let{[Ft]:n}=e(It()),r=t?.keySeparator??`.`,i=t?.nsSeparator??`:`,a=t?.enableSelector===`strict`;if(n.length>1&&i){let e=t?.ns,o=a?Array.isArray(e)?e:e?[e]:null:Array.isArray(e)?e:null;if(o&&(a?o:o.length>1?o.slice(1):[]).includes(n[0]))return`${n[0]}${i}${n.slice(1).join(r)}`}return n.join(r)}var Rt=e=>!z(e)&&typeof e!=`boolean`&&typeof e!=`number`,zt=class e extends Mt{constructor(e,t={}){super(),dt([`resourceStore`,`languageUtils`,`pluralResolver`,`interpolator`,`backendConnector`,`i18nFormat`,`utils`],e,this),this.options=t,this.options.keySeparator===void 0&&(this.options.keySeparator=`.`),this.logger=jt.create(`translator`),this.checkedLoadedFor={}}changeLanguage(e){e&&(this.language=e)}exists(e,t={interpolation:{}}){let n={...t};if(e==null)return!1;let r=this.resolve(e,n);if(r?.res===void 0)return!1;let i=Rt(r.res);return!(n.returnObjects===!1&&i)}extractFromKey(e,t){let n=t.nsSeparator===void 0?this.options.nsSeparator:t.nsSeparator;n===void 0&&(n=`:`);let r=t.keySeparator===void 0?this.options.keySeparator:t.keySeparator,i=t.ns||this.options.defaultNS||[],a=n&&e.includes(n),o=!this.options.userDefinedKeySeparator&&!t.keySeparator&&!this.options.userDefinedNsSeparator&&!t.nsSeparator&&!Dt(e,n,r);if(a&&!o){let t=e.match(this.interpolator.nestingRegexp);if(t&&t.length>0)return{key:e,namespaces:z(i)?[i]:i};let a=e.split(n);(n!==r||n===r&&this.options.ns.includes(a[0]))&&(i=a.shift()),e=a.join(r)}return{key:e,namespaces:z(i)?[i]:i}}translate(t,n,r){let i=typeof n==`object`?{...n}:n;if(typeof i!=`object`&&this.options.overloadTranslationOptionHandler&&(i=this.options.overloadTranslationOptionHandler(arguments)),typeof i==`object`&&(i={...i}),i||={},t==null)return``;typeof t==`function`&&(t=Lt(t,{...this.options,...i})),Array.isArray(t)||(t=[String(t)]),t=t.map(e=>typeof e==`function`?Lt(e,{...this.options,...i}):String(e));let a=i.returnDetails===void 0?this.options.returnDetails:i.returnDetails,o=i.keySeparator===void 0?this.options.keySeparator:i.keySeparator,{key:s,namespaces:c}=this.extractFromKey(t[t.length-1],i),l=c[c.length-1],u=i.nsSeparator===void 0?this.options.nsSeparator:i.nsSeparator;u===void 0&&(u=`:`);let d=i.lng||this.language,f=i.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(d?.toLowerCase()===`cimode`)return f?a?{res:`${l}${u}${s}`,usedKey:s,exactUsedKey:s,usedLng:d,usedNS:l,usedParams:this.getUsedParamsDetails(i)}:`${l}${u}${s}`:a?{res:s,usedKey:s,exactUsedKey:s,usedLng:d,usedNS:l,usedParams:this.getUsedParamsDetails(i)}:s;let p=this.resolve(t,i),m=p?.res,h=p?.usedKey||s,g=p?.exactUsedKey||s,_=[`[object Number]`,`[object Function]`,`[object RegExp]`],v=i.joinArrays===void 0?this.options.joinArrays:i.joinArrays,y=!this.i18nFormat||this.i18nFormat.handleAsObject,b=i.count!==void 0&&!z(i.count),x=e.hasDefaultValue(i),S=b?this.pluralResolver.getSuffix(d,i.count,i):``,C=i.ordinal&&b?this.pluralResolver.getSuffix(d,i.count,{ordinal:!1}):``,w=b&&!i.ordinal&&i.count===0,T=w&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${S}`]||i[`defaultValue${C}`]||i.defaultValue,E=m;y&&!m&&x&&(E=T);let D=Rt(E),O=Object.prototype.toString.apply(E);if(y&&E&&D&&!_.includes(O)&&!(z(v)&&Array.isArray(E))){if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn(`accessing an object - but returnObjects options is not enabled!`);let e=this.options.returnedObjectHandler?this.options.returnedObjectHandler(h,E,{...i,ns:c}):`key '${s} (${this.language})' returned an object instead of string.`;return a?(p.res=e,p.usedParams=this.getUsedParamsDetails(i),p):e}if(o){let e=Array.isArray(E),t=e?[]:{},n=e?g:h;for(let e in E)if(Object.prototype.hasOwnProperty.call(E,e)){let r=`${n}${o}${e}`;t[e]=x&&!m?this.translate(r,{...i,defaultValue:Rt(T)?T[e]:void 0,joinArrays:!1,ns:c}):this.translate(r,{...i,joinArrays:!1,ns:c}),t[e]===r&&(t[e]=E[e])}m=t}}else if(y&&z(v)&&Array.isArray(m))m=m.join(v),m&&=this.extendTranslation(m,t,i,r);else{let e=!1,n=!1;!this.isValidLookup(m)&&x&&(e=!0,m=T),this.isValidLookup(m)||(n=!0,m=s);let a=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&n?void 0:m,c=x&&T!==m&&this.options.updateMissing;if(n||e||c){if(this.logger.log(c?`updateKey`:`missingKey`,d,l,b&&!c?`${s}${this.pluralResolver.getSuffix(d,i.count,i)}`:s,c?T:m),o){let e=this.resolve(s,{...i,keySeparator:!1});e&&e.res&&this.logger.warn(`Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.`)}let e=[],t=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if(this.options.saveMissingTo===`fallback`&&t&&t[0])for(let n=0;n{let r=x&&n!==m?n:a;this.options.missingKeyHandler?this.options.missingKeyHandler(e,l,t,r,c,i):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(e,l,t,r,c,i),this.emit(`missingKey`,e,l,t,m)};this.options.saveMissing&&(this.options.saveMissingPlurals&&b?e.forEach(e=>{let t=this.pluralResolver.getSuffixes(e,i);w&&i[`defaultValue${this.options.pluralSeparator}zero`]&&!t.includes(`${this.options.pluralSeparator}zero`)&&t.push(`${this.options.pluralSeparator}zero`),t.forEach(t=>{n([e],s+t,i[`defaultValue${t}`]||T)})}):n(e,s,T))}m=this.extendTranslation(m,t,i,p,r),n&&m===s&&this.options.appendNamespaceToMissingKey&&(m=`${l}${u}${s}`),(n||e)&&this.options.parseMissingKeyHandler&&(m=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${l}${u}${s}`:s,e?m:void 0,i))}return a?(p.res=m,p.usedParams=this.getUsedParamsDetails(i),p):m}extendTranslation(e,t,n,r,i){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...n},n.lng||this.language||r.usedLng,r.usedNS,r.usedKey,{resolved:r});else if(!n.skipInterpolation){n.interpolation&&this.interpolator.init({...n,interpolation:{...this.options.interpolation,...n.interpolation}});let a=z(e)&&(n?.interpolation?.skipOnVariables===void 0?this.options.interpolation.skipOnVariables:n.interpolation.skipOnVariables),o;if(a){let t=e.match(this.interpolator.nestingRegexp);o=t&&t.length}let s=n.replace&&!z(n.replace)?n.replace:n;if(this.options.interpolation.defaultVariables&&(s={...this.options.interpolation.defaultVariables,...s}),e=this.interpolator.interpolate(e,s,n.lng||this.language||r.usedLng,n),a){let t=e.match(this.interpolator.nestingRegexp),r=t&&t.length;oi?.[0]===e[0]&&!n.context?(this.logger.warn(`It seems you are nesting recursively key: ${e[0]} in key: ${t[0]}`),null):this.translate(...e,t),n)),n.interpolation&&this.interpolator.reset()}let a=n.postProcess||this.options.postProcess,o=z(a)?[a]:a;return e!=null&&o?.length&&n.applyPostProcessor!==!1&&(e=Pt.handle(o,e,t,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...r,usedParams:this.getUsedParamsDetails(n)},...n}:n,this)),e}resolve(e,t={}){let n,r,i,a,o;return z(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(e=>typeof e==`function`?Lt(e,{...this.options,...t}):e)),e.forEach(e=>{if(this.isValidLookup(n))return;let s=this.extractFromKey(e,t),c=s.key;r=c;let l=s.namespaces;this.options.fallbackNS&&(l=l.concat(this.options.fallbackNS));let u=t.count!==void 0&&!z(t.count),d=u&&!t.ordinal&&t.count===0,f=t.context!==void 0&&(z(t.context)||typeof t.context==`number`)&&t.context!==``,p=t.lngs?t.lngs:this.languageUtils.toResolveHierarchy(t.lng||this.language,t.fallbackLng);l.forEach(e=>{this.isValidLookup(n)||(o=e,!this.checkedLoadedFor[`${p[0]}-${e}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(o)&&(this.checkedLoadedFor[`${p[0]}-${e}`]=!0,this.logger.warn(`key "${r}" for languages "${p.join(`, `)}" won't get resolved as namespace "${o}" was not yet loaded`,`This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!`)),p.forEach(r=>{if(this.isValidLookup(n))return;a=r;let o=[c];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(o,c,r,e,t);else{let e;u&&(e=this.pluralResolver.getSuffix(r,t.count,t));let n=`${this.options.pluralSeparator}zero`,i=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(u&&(t.ordinal&&e.startsWith(i)&&o.push(c+e.replace(i,this.options.pluralSeparator)),o.push(c+e),d&&o.push(c+n)),f){let r=`${c}${this.options.contextSeparator||`_`}${t.context}`;o.push(r),u&&(t.ordinal&&e.startsWith(i)&&o.push(r+e.replace(i,this.options.pluralSeparator)),o.push(r+e),d&&o.push(r+n))}}let s;for(;s=o.pop();)this.isValidLookup(n)||(i=s,n=this.getResource(r,e,s,t))}))})}),{res:n,usedKey:r,exactUsedKey:i,usedLng:a,usedNS:o}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e===``)}getResource(e,t,n,r={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,t,n,r):this.resourceStore.getResource(e,t,n,r)}getUsedParamsDetails(e={}){let t=[`defaultValue`,`ordinal`,`context`,`replace`,`lng`,`lngs`,`fallbackLng`,`ns`,`keySeparator`,`nsSeparator`,`returnObjects`,`returnDetails`,`joinArrays`,`postProcess`,`interpolation`],n=e.replace&&!z(e.replace),r=n?e.replace:e;if(n&&e.count!==void 0&&(r={...r,count:e.count}),this.options.interpolation.defaultVariables&&(r={...this.options.interpolation.defaultVariables,...r}),!n){r={...r};for(let e of t)delete r[e]}return r}static hasDefaultValue(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&t.startsWith(`defaultValue`)&&e[t]!==void 0)return!0;return!1}},Bt=class{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=jt.create(`languageUtils`),this.resolveHierarchyCache={}}clearCache(){this.resolveHierarchyCache={}}getScriptPartFromCode(e){if(e=kt(e),!e||!e.includes(`-`))return null;let t=e.split(`-`);return t.length===2||(t.pop(),t[t.length-1].toLowerCase()===`x`)?null:this.formatLanguageCode(t.join(`-`))}getLanguagePartFromCode(e){if(e=kt(e),!e||!e.includes(`-`))return e;let t=e.split(`-`);return this.formatLanguageCode(t[0])}formatLanguageCode(e){if(z(e)&&e.includes(`-`)){let t;try{t=Intl.getCanonicalLocales(e)[0]}catch{}return t&&this.options.lowerCaseLng&&(t=t.toLowerCase()),t||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load===`languageOnly`||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.includes(e)}getBestMatchFromCodes(e){if(!e)return null;let t;return e.forEach(e=>{if(t)return;let n=this.formatLanguageCode(e);(!this.options.supportedLngs||this.isSupportedCode(n))&&(t=n)}),!t&&this.options.supportedLngs&&e.forEach(e=>{if(t)return;let n=this.getScriptPartFromCode(e);if(this.isSupportedCode(n))return t=n;let r=this.getLanguagePartFromCode(e);if(this.isSupportedCode(r))return t=r;t=this.options.supportedLngs.find(e=>e===r?!0:!e.includes(`-`)&&!r.includes(`-`)?!1:!!(e.includes(`-`)&&!r.includes(`-`)&&e.slice(0,e.indexOf(`-`))===r||e.startsWith(r)&&r.length>1))}),t||=this.getFallbackCodes(this.options.fallbackLng)[0],t}getFallbackCodes(e,t){if(!e)return[];if(typeof e==`function`&&(e=e(t)),z(e)&&(e=[e]),Array.isArray(e))return e;if(!t)return e.default||[];let n=e[t];return n||=e[this.getScriptPartFromCode(t)],n||=e[this.formatLanguageCode(t)],n||=e[this.getLanguagePartFromCode(t)],n||=e.default,n||[]}toResolveHierarchy(e,t){let n=this.options.fallbackLng,r=Array.isArray(n)?n.join(`|`):n;r!==this._cachedFallbackLng&&(this.resolveHierarchyCache={},this._cachedFallbackLng=r);let i=t===void 0||t===!1||z(t),a=t===void 0&&typeof this.options.fallbackLng==`function`,o=z(e)&&i&&!a,s=null;if(o){let n;n=t===void 0?`undefined`:t===!1?`boolean:false`:`string:${t}`,s=`${e.length}:${e}|${n}`}if(s!==null){let e=this.resolveHierarchyCache[s];if(e!==void 0)return e.slice()}let c=this.getFallbackCodes((t===!1?[]:t)||this.options.fallbackLng||[],e),l=[],u=e=>{e&&(this.isSupportedCode(e)?l.push(e):this.logger.warn(`rejecting language code not found in supportedLngs: ${e}`))};return z(e)&&(e.includes(`-`)||e.includes(`_`))?(this.options.load!==`languageOnly`&&u(this.formatLanguageCode(e)),this.options.load!==`languageOnly`&&this.options.load!==`currentOnly`&&u(this.getScriptPartFromCode(e)),this.options.load!==`currentOnly`&&u(this.getLanguagePartFromCode(e))):z(e)&&u(this.formatLanguageCode(e)),c.forEach(e=>{l.includes(e)||u(this.formatLanguageCode(e))}),s===null?l:(this.resolveHierarchyCache[s]=l,l.slice())}},Vt={zero:0,one:1,two:2,few:3,many:4,other:5},Ht={select:e=>e===1?`one`:`other`,resolvedOptions:()=>({pluralCategories:[`one`,`other`]})},Ut=class{constructor(e,t={}){this.languageUtils=e,this.options=t,this.logger=jt.create(`pluralResolver`),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,t={}){let n=kt(e===`dev`?`en`:e),r=t.ordinal?`ordinal`:`cardinal`,i=JSON.stringify({cleanedCode:n,type:r});if(i in this.pluralRulesCache)return this.pluralRulesCache[i];let a;try{a=new Intl.PluralRules(n,{type:r})}catch{if(typeof Intl>`u`)return this.logger.error(`No Intl support, please use an Intl polyfill!`),Ht;if(!e.match(/-|_/))return Ht;let n=this.languageUtils.getLanguagePartFromCode(e);a=this.getRule(n,t)}return this.pluralRulesCache[i]=a,a}needsPlural(e,t={}){let n=this.getRule(e,t);return n||=this.getRule(`dev`,t),n?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,t,n={}){return this.getSuffixes(e,n).map(e=>`${t}${e}`)}getSuffixes(e,t={}){let n=this.getRule(e,t);return n||=this.getRule(`dev`,t),n?n.resolvedOptions().pluralCategories.sort((e,t)=>Vt[e]-Vt[t]).map(e=>`${this.options.prepend}${t.ordinal?`ordinal${this.options.prepend}`:``}${e}`):[]}getSuffix(e,t,n={}){let r=this.getRule(e,n);return r?`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:``}${r.select(t)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix(`dev`,t,n))}},Wt=(e,t,n,r=`.`,i=!0)=>{let a=yt(e,t,n);return!a&&i&&z(n)&&(a=Ot(e,n,r),a===void 0&&(a=Ot(t,n,r))),a},Gt=e=>e.replace(/\$/g,`$$$$`),Kt=class{constructor(e={}){this.logger=jt.create(`interpolator`),this.options=e,this.format=e?.interpolation?.format||(e=>e),this.init(e)}init(e={}){e.interpolation||={escapeValue:!0};let{escape:t,escapeValue:n,useRawValueToEscape:r,prefix:i,prefixEscaped:a,suffix:o,suffixEscaped:s,formatSeparator:c,unescapeSuffix:l,unescapePrefix:u,nestingPrefix:d,nestingPrefixEscaped:f,nestingSuffix:p,nestingSuffixEscaped:m,nestingOptionsSeparator:h,maxReplaces:g,alwaysFormat:_}=e.interpolation;this.escape=t===void 0?Ct:t,this.escapeValue=n===void 0||n,this.useRawValueToEscape=r!==void 0&&r,this.prefix=i?xt(i):a||`{{`,this.suffix=o?xt(o):s||`}}`,this.formatSeparator=c||`,`,this.unescapePrefix=l?``:u?xt(u):`-`,this.unescapeSuffix=this.unescapePrefix?``:l?xt(l):``,this.nestingPrefix=d?xt(d):f||xt(`$t(`),this.nestingSuffix=p?xt(p):m||xt(`)`),this.nestingOptionsSeparator=h||`,`,this.maxReplaces=g||1e3,this.alwaysFormat=_!==void 0&&_,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){let e=(e,t)=>e?.source===t?(e.lastIndex=0,e):new RegExp(t,`g`);this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,t,n,r){let i,a,o,s=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},c=e=>{if(!e.includes(this.formatSeparator)){let i=Wt(t,s,e,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(i,void 0,n,{...r,...t,interpolationkey:e}):i}let i=e.split(this.formatSeparator),a=i.shift().trim(),o=i.join(this.formatSeparator).trim();return this.format(Wt(t,s,a,this.options.keySeparator,this.options.ignoreJSONStructure),o,n,{...r,...t,interpolationkey:a})};this.resetRegExp(),!this.escapeValue&&typeof e==`string`&&/\$t\([^)]*\{[^}]*\{\{/.test(e)&&this.logger.warn(`nesting options string contains interpolated variables with escapeValue: false — if any of those values are attacker-controlled they can inject additional nesting options (e.g. redirect lng/ns). Sanitise untrusted input before passing it to t(), or keep escapeValue: true.`);let l=r?.missingInterpolationHandler||this.options.missingInterpolationHandler,u=r?.interpolation?.skipOnVariables===void 0?this.options.interpolation.skipOnVariables:r.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:e=>e},{regex:this.regexp,safeValue:e=>this.escapeValue?this.escape(e):e}].forEach(t=>{for(o=0;i=t.regex.exec(e);){let n=i[1].trim();if(a=c(n),a===void 0){if(typeof l==`function`){let t=l(e,i,r);a=z(t)?t:``}else if(r&&Object.prototype.hasOwnProperty.call(r,n))a=``;else if(u){a=i[0];continue}else this.logger.warn(`missed to pass in variable ${n} for interpolating ${e}`),a=``}else!z(a)&&!this.useRawValueToEscape&&(a=ut(a));let s=t.safeValue(a);if(e=e.replace(i[0],Gt(s)),u?(t.regex.lastIndex+=s.length,t.regex.lastIndex-=i[0].length):t.regex.lastIndex=0,o++,o>=this.maxReplaces)break}}),e}nest(e,t,n={}){let r,i,a,o=(e,t)=>{let n=this.nestingOptionsSeparator;if(!e.includes(n))return e;let r=e.split(RegExp(`${xt(n)}[ ]*{`)),i=`{${r[1]}`;e=r[0],i=this.interpolate(i,a);let o=i.match(/'/g),s=i.match(/"/g);((o?.length??0)%2==0&&!s||(s?.length??0)%2!=0)&&(i=i.replace(/'/g,`"`));try{a=JSON.parse(i),t&&(a={...t,...a})}catch(t){return this.logger.warn(`failed parsing options string in nesting for key ${e}`,t),`${e}${n}${i}`}return a.defaultValue&&a.defaultValue.includes(this.prefix)&&delete a.defaultValue,e};for(;r=this.nestingRegexp.exec(e);){let s=[];a={...n},a=a.replace&&!z(a.replace)?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;let c=/{.*}/s.test(r[1])?r[1].lastIndexOf(`}`)+1:r[1].indexOf(this.formatSeparator);if(c!==-1&&(s=r[1].slice(c).split(this.formatSeparator).map(e=>e.trim()).filter(Boolean),r[1]=r[1].slice(0,c)),i=t(o.call(this,r[1].trim(),a),a),i&&r[0]===e&&!z(i))return i;z(i)||(i=ut(i)),i||=(this.logger.warn(`missed to resolve ${r[1]} for nesting ${e}`),``),s.length&&(i=s.reduce((e,t)=>this.format(e,t,n.lng,{...n,interpolationkey:r[1].trim()}),i.trim())),e=e.replace(r[0],i),this.regexp.lastIndex=0}return e}},qt=e=>{let t=e.toLowerCase().trim(),n={};if(e.includes(`(`)){let r=e.split(`(`);t=r[0].toLowerCase().trim();let i=r[1].slice(0,-1);t===`currency`&&!i.includes(`:`)?n.currency||=i.trim():t===`relativetime`&&!i.includes(`:`)?n.range||=i.trim():i.split(`;`).forEach(e=>{if(e){let[t,...r]=e.split(`:`),i=r.join(`:`).trim().replace(/^'+|'+$/g,``),a=t.trim();n[a]||(n[a]=i),i===`false`&&(n[a]=!1),i===`true`&&(n[a]=!0),isNaN(i)||(n[a]=parseInt(i,10))}})}return{formatName:t,formatOptions:n}},Jt=e=>{let t={};return(n,r,i)=>{let a=i;i&&i.interpolationkey&&i.formatParams&&i.formatParams[i.interpolationkey]&&i[i.interpolationkey]&&(a={...a,[i.interpolationkey]:void 0});let o=r+JSON.stringify(a),s=t[o];return s||(s=e(kt(r),i),t[o]=s),s(n)}},Yt=e=>(t,n,r)=>e(kt(n),r)(t),Xt=class{constructor(e={}){this.logger=jt.create(`formatter`),this.options=e,this.init(e)}init(e,t={interpolation:{}}){this.formatSeparator=t.interpolation.formatSeparator||`,`;let n=t.cacheInBuiltFormats?Jt:Yt;this.formats={number:n((e,t)=>{let n=new Intl.NumberFormat(e,{...t});return e=>n.format(e)}),currency:n((e,t)=>{let n=new Intl.NumberFormat(e,{...t,style:`currency`});return e=>n.format(e)}),datetime:n((e,t)=>{let n=new Intl.DateTimeFormat(e,{...t});return e=>n.format(e)}),relativetime:n((e,t)=>{let n=new Intl.RelativeTimeFormat(e,{...t});return e=>n.format(e,t.range||`day`)}),list:n((e,t)=>{let n=new Intl.ListFormat(e,{...t});return e=>n.format(e)})}}add(e,t){this.formats[e.toLowerCase().trim()]=t}addCached(e,t){this.formats[e.toLowerCase().trim()]=Jt(t)}format(e,t,n,r={}){if(!t||e==null)return e;let i=t.split(this.formatSeparator),a=[];for(let e=0;e-1&&!t.includes(`)`)&&e+1{let{formatName:i,formatOptions:a}=qt(t);if(this.formats[i]){let t=e;try{let o=r?.formatParams?.[r.interpolationkey]||{},s=o.locale||o.lng||r.locale||r.lng||n;t=this.formats[i](e,s,{...a,...r,...o})}catch(e){this.logger.warn(e)}return t}return this.logger.warn(`there was no format function for ${i}`),e},e)}},Zt=(e,t)=>{e.pending[t]!==void 0&&(delete e.pending[t],e.pendingCount--)},Qt=class extends Mt{constructor(e,t,n,r={}){super(),this.backend=e,this.store=t,this.services=n,this.languageUtils=n.languageUtils,this.options=r,this.logger=jt.create(`backendConnector`),this.waitingReads=[],this.maxParallelReads=r.maxParallelReads||10,this.readingCalls=0,this.maxRetries=r.maxRetries>=0?r.maxRetries:5,this.retryTimeout=r.retryTimeout>=1?r.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(n,r.backend,r)}queueLoad(e,t,n,r){let i={},a={},o={},s={};return e.forEach(e=>{let r=!0;t.forEach(t=>{let o=`${e}|${t}`;!n.reload&&this.store.hasResourceBundle(e,t)?this.state[o]=2:this.state[o]<0||(this.state[o]===1?a[o]===void 0&&(a[o]=!0):(this.state[o]=1,r=!1,a[o]===void 0&&(a[o]=!0),i[o]===void 0&&(i[o]=!0),s[t]===void 0&&(s[t]=!0)))}),r||(o[e]=!0)}),(Object.keys(i).length||Object.keys(a).length)&&this.queue.push({pending:a,pendingCount:Object.keys(a).length,loaded:{},errors:[],callback:r}),{toLoad:Object.keys(i),pending:Object.keys(a),toLoadLanguages:Object.keys(o),toLoadNamespaces:Object.keys(s)}}loaded(e,t,n){let r=e.split(`|`),i=r[0],a=r[1];t&&this.emit(`failedLoading`,i,a,t),!t&&n&&this.store.addResourceBundle(i,a,n,void 0,void 0,{skipCopy:!0}),this.state[e]=t?-1:2,t&&n&&(this.state[e]=0);let o={};this.queue.forEach(n=>{_t(n.loaded,[i],a),Zt(n,e),t&&n.errors.push(t),n.pendingCount===0&&!n.done&&(Object.keys(n.loaded).forEach(e=>{o[e]||(o[e]={});let t=n.loaded[e];t.length&&t.forEach(t=>{o[e][t]===void 0&&(o[e][t]=!0)})}),n.done=!0,n.errors.length?n.callback(n.errors):n.callback())}),this.emit(`loaded`,o),this.queue=this.queue.filter(e=>!e.done)}read(e,t,n,r=0,i=this.retryTimeout,a){if(!e.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:t,fcName:n,tried:r,wait:i,callback:a});return}this.readingCalls++;let o=(o,s)=>{if(this.readingCalls--,this.waitingReads.length>0){let e=this.waitingReads.shift();this.read(e.lng,e.ns,e.fcName,e.tried,e.wait,e.callback)}if(o&&s&&r{this.read(e,t,n,r+1,i*2,a)},i);return}a(o,s)},s=this.backend[n].bind(this.backend);if(s.length===2){try{let n=s(e,t);n&&typeof n.then==`function`?n.then(e=>o(null,e)).catch(o):o(null,n)}catch(e){o(e)}return}return s(e,t,o)}prepareLoading(e,t,n={},r){if(!this.backend)return this.logger.warn(`No backend was added via i18next.use. Will not load resources.`),r&&r();z(e)&&(e=this.languageUtils.toResolveHierarchy(e)),z(t)&&(t=[t]);let i=this.queueLoad(e,t,n,r);if(!i.toLoad.length)return i.pending.length||r(),null;i.toLoad.forEach(e=>{this.loadOne(e)})}load(e,t,n){this.prepareLoading(e,t,{},n)}reload(e,t,n){this.prepareLoading(e,t,{reload:!0},n)}loadOne(e,t=``){let n=e.split(`|`),r=n[0],i=n[1];this.read(r,i,`read`,void 0,void 0,(n,a)=>{n&&this.logger.warn(`${t}loading namespace ${i} for language ${r} failed`,n),!n&&a&&this.logger.log(`${t}loaded namespace ${i} for language ${r}`,a),this.loaded(e,n,a)})}saveMissing(e,t,n,r,i,a={},o=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(t)){this.logger.warn(`did not save key "${n}" as the namespace "${t}" was not yet loaded`,`This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!`);return}if(n!=null&&n!==``){if(this.backend?.create){let s={...a,isUpdate:i},c=this.backend.create.bind(this.backend);if(c.length<6)try{let i;i=c.length===5?c(e,t,n,r,s):c(e,t,n,r),i&&typeof i.then==`function`?i.then(e=>o(null,e)).catch(o):o(null,i)}catch(e){o(e)}else c(e,t,n,r,o,s)}!e||!e[0]||this.store.addResource(e[0],t,n,r)}}},$t=()=>({debug:!1,initAsync:!0,ns:[`translation`],defaultNS:[`translation`],fallbackLng:[`dev`],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:`all`,preload:!1,keySeparator:`.`,nsSeparator:`:`,pluralSeparator:`_`,contextSeparator:`_`,enableSelector:!1,partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:`fallback`,saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:e=>{let t={};if(typeof e[1]==`object`&&(t=e[1]),z(e[1])&&(t.defaultValue=e[1]),z(e[2])&&(t.tDescription=e[2]),typeof e[2]==`object`||typeof e[3]==`object`){let n=e[3]||e[2];Object.keys(n).forEach(e=>{t[e]=n[e]})}return t},interpolation:{escapeValue:!0,prefix:`{{`,suffix:`}}`,formatSeparator:`,`,unescapePrefix:`-`,nestingPrefix:`$t(`,nestingSuffix:`)`,nestingOptionsSeparator:`,`,maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),en=e=>(z(e.ns)&&(e.ns=[e.ns]),z(e.fallbackLng)&&(e.fallbackLng=[e.fallbackLng]),z(e.fallbackNS)&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs&&!e.supportedLngs.includes(`cimode`)&&(e.supportedLngs=e.supportedLngs.concat([`cimode`])),e),tn=()=>{},nn=e=>{Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(t=>{typeof e[t]==`function`&&(e[t]=e[t].bind(e))})},rn=class e extends Mt{constructor(e={},t){if(super(),this.options=en(e),this.services={},this.logger=jt,this.modules={external:[]},nn(this),t&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,t),this;setTimeout(()=>{this.init(e,t)},0)}}init(e={},t){this.isInitializing=!0,typeof e==`function`&&(t=e,e={}),e.defaultNS==null&&e.ns&&(z(e.ns)?e.defaultNS=e.ns:e.ns.includes(`translation`)||(e.defaultNS=e.ns[0]));let n=$t();this.options={...n,...this.options,...en(e)},this.options.interpolation={...n.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!=`function`&&(this.options.overloadTranslationOptionHandler=n.overloadTranslationOptionHandler);let r=e=>e?typeof e==`function`?new e:e:null;if(!this.options.isClone){this.modules.logger?jt.init(r(this.modules.logger),this.options):jt.init(null,this.options);let e;e=this.modules.formatter?this.modules.formatter:Xt;let t=new Bt(this.options);this.store=new Nt(this.options.resources,this.options);let n=this.services;n.logger=jt,n.resourceStore=this.store,n.languageUtils=t,n.pluralResolver=new Ut(t,{prepend:this.options.pluralSeparator}),e&&(n.formatter=r(e),n.formatter.init&&n.formatter.init(n,this.options),this.options.interpolation.format=n.formatter.format.bind(n.formatter)),n.interpolator=new Kt(this.options),n.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},n.backendConnector=new Qt(r(this.modules.backend),n.resourceStore,n,this.options),n.backendConnector.on(`*`,(e,...t)=>{this.emit(e,...t)}),this.modules.languageDetector&&(n.languageDetector=r(this.modules.languageDetector),n.languageDetector.init&&n.languageDetector.init(n,this.options.detection,this.options)),this.modules.i18nFormat&&(n.i18nFormat=r(this.modules.i18nFormat),n.i18nFormat.init&&n.i18nFormat.init(this)),this.translator=new zt(this.services,this.options),this.translator.on(`*`,(e,...t)=>{this.emit(e,...t)}),this.modules.external.forEach(e=>{e.init&&e.init(this)})}if(this.format=this.options.interpolation.format,t||=tn,this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){let e=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);e.length>0&&e[0]!==`dev`&&(this.options.lng=e[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn(`init: no languageDetector is used and no lng is defined`),[`getResource`,`hasResourceBundle`,`getResourceBundle`,`getDataByLanguage`].forEach(e=>{this[e]=(...t)=>this.store[e](...t)}),[`addResource`,`addResources`,`addResourceBundle`,`removeResourceBundle`].forEach(e=>{this[e]=(...t)=>(this.store[e](...t),this)});let i=lt(),a=()=>{let e=(e,n)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn(`init: i18next is already initialized. You should call init just once!`),this.isInitialized=!0,this.options.isClone||this.logger.log(`initialized`,this.options),this.emit(`initialized`,this.options),i.resolve(n),t(e,n)};if((this.languages||this.isLanguageChangingTo)&&!this.isInitialized)return e(null,this.t.bind(this));this.changeLanguage(this.options.lng,e)};return this.options.resources||!this.options.initAsync?a():setTimeout(a,0),i}loadResources(e,t=tn){let n=t,r=z(e)?e:this.language;if(typeof e==`function`&&(n=e),!this.options.resources||this.options.partialBundledLanguages){if(r?.toLowerCase()===`cimode`&&(!this.options.preload||this.options.preload.length===0))return n();let e=[],t=t=>{t&&t!==`cimode`&&this.services.languageUtils.toResolveHierarchy(t).forEach(t=>{t!==`cimode`&&(e.includes(t)||e.push(t))})};r?t(r):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(e=>t(e)),this.options.preload?.forEach?.(e=>t(e)),this.services.backendConnector.load(e,this.options.ns,e=>{!e&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),n(e)})}else n(null)}reloadResources(e,t,n){let r=lt();return typeof e==`function`&&(n=e,e=void 0),typeof t==`function`&&(n=t,t=void 0),e||=this.languages,t||=this.options.ns,n||=tn,this.services.backendConnector.reload(e,t,e=>{r.resolve(),n(e)}),r}use(e){if(!e)throw Error(`You are passing an undefined module! Please check the object you are passing to i18next.use()`);if(!e.type)throw Error(`You are passing a wrong module! Please check the object you are passing to i18next.use()`);return e.type===`backend`&&(this.modules.backend=e),(e.type===`logger`||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type===`languageDetector`&&(this.modules.languageDetector=e),e.type===`i18nFormat`&&(this.modules.i18nFormat=e),e.type===`postProcessor`&&Pt.addPostProcessor(e),e.type===`formatter`&&(this.modules.formatter=e),e.type===`3rdParty`&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&![`cimode`,`dev`].includes(e)){for(let e=0;e{this.language=e,this.languages=this.services.languageUtils.toResolveHierarchy(e),this.resolvedLanguage=void 0,this.setResolvedLanguage(e)},i=(i,a)=>{a?this.isLanguageChangingTo===e&&(r(a),this.translator.changeLanguage(a),this.isLanguageChangingTo=void 0,this.emit(`languageChanged`,a),this.logger.log(`languageChanged`,a)):this.isLanguageChangingTo=void 0,n.resolve((...e)=>this.t(...e)),t&&t(i,(...e)=>this.t(...e))},a=t=>{!e&&!t&&this.services.languageDetector&&(t=[]);let n=z(t)?t:t&&t[0],a=this.store.hasLanguageSomeTranslations(n)?n:this.services.languageUtils.getBestMatchFromCodes(z(t)?[t]:t);a&&(this.language||r(a),this.translator.language||this.translator.changeLanguage(a),this.services.languageDetector?.cacheUserLanguage?.(a)),this.loadResources(a,e=>{i(e,a)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?a(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(a):this.services.languageDetector.detect(a):a(e),n}getFixedT(e,t,n,r){let i=r?.scopeNs,a=(e,t,...r)=>{let o;o=typeof t==`object`?{...t}:this.options.overloadTranslationOptionHandler([e,t].concat(r)),o.lng=o.lng||a.lng,o.lngs=o.lngs||a.lngs;let s=o.ns!==void 0&&o.ns!==null;o.ns=o.ns||a.ns,o.keyPrefix!==``&&(o.keyPrefix=o.keyPrefix||n||a.keyPrefix);let c={...this.options,...o};Array.isArray(i)&&!s&&(c.ns=i),typeof o.keyPrefix==`function`&&(o.keyPrefix=Lt(o.keyPrefix,c));let l=this.options.keySeparator||`.`,u;return o.keyPrefix&&Array.isArray(e)?u=e.map(e=>(typeof e==`function`&&(e=Lt(e,c)),`${o.keyPrefix}${l}${e}`)):(typeof e==`function`&&(e=Lt(e,c)),u=o.keyPrefix?`${o.keyPrefix}${l}${e}`:e),this.t(u,o)};return z(e)?a.lng=e:a.lngs=e,a.ns=t,a.keyPrefix=n,a}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,t={}){if(!this.isInitialized)return this.logger.warn(`hasLoadedNamespace: i18next was not initialized`,this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn(`hasLoadedNamespace: i18n.languages were undefined or empty`,this.languages),!1;let n=t.lng||this.resolvedLanguage||this.languages[0],r=this.options?this.options.fallbackLng:!1,i=this.languages[this.languages.length-1];if(n.toLowerCase()===`cimode`)return!0;let a=(e,t)=>{let n=this.services.backendConnector.state[`${e}|${t}`];return n===-1||n===0||n===2};if(t.precheck){let e=t.precheck(this,a);if(e!==void 0)return e}return!!(this.hasResourceBundle(n,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||a(n,e)&&(!r||a(i,e)))}loadNamespaces(e,t){let n=lt();return this.options.ns?(z(e)&&(e=[e]),e.forEach(e=>{this.options.ns.includes(e)||this.options.ns.push(e)}),this.loadResources(e=>{n.resolve(),t&&t(e)}),n):(t&&t(),Promise.resolve())}loadLanguages(e,t){let n=lt();z(e)&&(e=[e]);let r=this.options.preload||[],i=e.filter(e=>!r.includes(e)&&this.services.languageUtils.isSupportedCode(e));return i.length?(this.options.preload=r.concat(i),this.loadResources(e=>{n.resolve(),t&&t(e)}),n):(t&&t(),Promise.resolve())}dir(e){if(e||=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language),!e)return`rtl`;try{let t=new Intl.Locale(e);if(t&&t.getTextInfo){let e=t.getTextInfo();if(e&&e.direction)return e.direction}}catch{}let t=`ar.shu.sqr.ssh.xaa.yhd.yud.aao.abh.abv.acm.acq.acw.acx.acy.adf.ads.aeb.aec.afb.ajp.apc.apd.arb.arq.ars.ary.arz.auz.avl.ayh.ayl.ayn.ayp.bbz.pga.he.iw.ps.pbt.pbu.pst.prp.prd.ug.ur.ydd.yds.yih.ji.yi.hbo.men.xmn.fa.jpr.peo.pes.prs.dv.sam.ckb`.split(`.`),n=this.services?.languageUtils||new Bt($t());return e.toLowerCase().indexOf(`-latn`)>1?`ltr`:t.includes(n.getLanguagePartFromCode(e))||e.toLowerCase().indexOf(`-arab`)>1?`rtl`:`ltr`}static createInstance(t={},n){let r=new e(t,n);return r.createInstance=e.createInstance,r}cloneInstance(t={},n=tn){let r=t.forkResourceStore;r&&delete t.forkResourceStore;let i={...this.options,...t,isClone:!0},a=new e(i);if((t.debug!==void 0||t.prefix!==void 0)&&(a.logger=a.logger.clone(t)),[`store`,`services`,`language`].forEach(e=>{a[e]=this[e]}),a.services={...this.services},a.services.utils={hasLoadedNamespace:a.hasLoadedNamespace.bind(a)},r&&(a.store=new Nt(Object.keys(this.store.data).reduce((e,t)=>(e[t]={...this.store.data[t]},e[t]=Object.keys(e[t]).reduce((n,r)=>(n[r]={...e[t][r]},n),e[t]),e),{}),i),a.services.resourceStore=a.store),t.interpolation){let e={...$t().interpolation,...this.options.interpolation,...t.interpolation},n={...i,interpolation:e};a.services.interpolator=new Kt(n)}return a.translator=new zt(a.services,i),a.translator.on(`*`,(e,...t)=>{a.emit(e,...t)}),a.init(i,n),a.translator.options=i,a.translator.backendConnector.services.utils={hasLoadedNamespace:a.hasLoadedNamespace.bind(a)},a}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}.createInstance();rn.createInstance,rn.dir,rn.init,rn.loadResources,rn.reloadResources,rn.use,rn.changeLanguage,rn.getFixedT,rn.t,rn.exists,rn.setDefaultNamespace,rn.hasLoadedNamespace,rn.loadNamespaces,rn.loadLanguages;var an=(e,t,n,r)=>{let i=[n,{code:t,...r||{}}];if(e?.services?.logger?.forward)return e.services.logger.forward(i,`warn`,`react-i18next::`,!0);fn(i[0])&&(i[0]=`react-i18next:: ${i[0]}`),e?.services?.logger?.warn?e.services.logger.warn(...i):console?.warn&&console.warn(...i)},on={},sn=(e,t,n,r)=>{fn(n)&&on[n]||(fn(n)&&(on[n]=new Date),an(e,t,n,r))},cn=(e,t)=>()=>{if(e.isInitialized)t();else{let n=()=>{setTimeout(()=>{e.off(`initialized`,n)},0),t()};e.on(`initialized`,n)}},ln=(e,t,n)=>{e.loadNamespaces(t,cn(e,n))},un=(e,t,n,r)=>{if(fn(n)&&(n=[n]),e.options.preload&&e.options.preload.indexOf(t)>-1)return ln(e,n,r);n.forEach(t=>{e.options.ns.indexOf(t)<0&&e.options.ns.push(t)}),e.loadLanguages(t,cn(e,r))},dn=(e,t,n={})=>!t.languages||!t.languages.length?(sn(t,`NO_LANGUAGES`,`i18n.languages were undefined or empty`,{languages:t.languages}),!0):t.hasLoadedNamespace(e,{lng:n.lng,precheck:(t,r)=>{if(n.bindI18n&&n.bindI18n.indexOf(`languageChanging`)>-1&&t.services.backendConnector.backend&&t.isLanguageChangingTo&&!r(t.isLanguageChangingTo,e))return!1}}),fn=e=>typeof e==`string`,pn=e=>typeof e==`object`&&!!e,mn=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,hn={"&":`&`,"&":`&`,"<":`<`,"<":`<`,">":`>`,">":`>`,"'":`'`,"'":`'`,""":`"`,""":`"`," ":` `," ":` `,"©":`©`,"©":`©`,"®":`®`,"®":`®`,"…":`…`,"…":`…`,"/":`/`,"/":`/`},gn=e=>hn[e],_n={bindI18n:`languageChanged`,bindI18nStore:``,transEmptyNodeValue:``,transSupportBasicHtmlNodes:!0,transWrapTextNodes:``,transKeepBasicHtmlNodesFor:[`br`,`strong`,`i`,`p`],useSuspense:!0,unescape:e=>e.replace(mn,gn),transDefaultProps:void 0},vn=()=>_n,yn,bn=()=>yn,xn=(0,m.createContext)(),Sn=class{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach(e=>{this.usedNamespaces[e]||(this.usedNamespaces[e]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}},Cn=o((e=>{var t=p();function n(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var r=typeof Object.is==`function`?Object.is:n,i=t.useState,a=t.useEffect,o=t.useLayoutEffect,s=t.useDebugValue;function c(e,t){var n=t(),r=i({inst:{value:n,getSnapshot:t}}),c=r[0].inst,u=r[1];return o(function(){c.value=n,c.getSnapshot=t,l(c)&&u({inst:c})},[e,n,t]),a(function(){return l(c)&&u({inst:c}),e(function(){l(c)&&u({inst:c})})},[e]),s(n),n}function l(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!r(e,n)}catch{return!0}}function u(e,t){return t()}var d=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?u:c;e.useSyncExternalStore=t.useSyncExternalStore===void 0?d:t.useSyncExternalStore})),wn=o(((e,t)=>{t.exports=Cn()}))(),Tn={t:(e,t)=>{if(fn(t))return t;if(pn(t)&&fn(t.defaultValue))return t.defaultValue;if(typeof e==`function`)return``;if(Array.isArray(e)){let t=e[e.length-1];return typeof t==`function`?``:t}return e},ready:!1},En=()=>()=>{},Dn=(e,t={})=>{let{i18n:n}=t,{i18n:r,defaultNS:i}=(0,m.useContext)(xn)||{},a=n||r||bn();a&&!a.reportNamespaces&&(a.reportNamespaces=new Sn),a||sn(a,`NO_I18NEXT_INSTANCE`,`useTranslation: You will need to pass in an i18next instance by using initReactI18next or by passing it via props or context. In monorepo setups, make sure there is only one instance of react-i18next.`);let o=(0,m.useMemo)(()=>({...vn(),...a?.options?.react,...t}),[a,t]),{useSuspense:s,keyPrefix:c}=o,l=e||i||a?.options?.defaultNS,u=fn(l)?[l]:l||[`translation`],d=(0,m.useMemo)(()=>u,u);a?.reportNamespaces?.addUsedNamespaces?.(d);let f=(0,m.useRef)(0),p=(0,m.useCallback)(e=>{if(!a)return En;let{bindI18n:t,bindI18nStore:n}=o,r=()=>{f.current+=1,e()};return t&&a.on(t,r),n&&a.store.on(n,r),()=>{t&&t.split(` `).forEach(e=>a.off(e,r)),n&&n.split(` `).forEach(e=>a.store.off(e,r))}},[a,o]),h=(0,m.useRef)(),g=(0,m.useCallback)(()=>{if(!a)return Tn;let e=!!(a.isInitialized||a.initializedStoreOnce)&&d.every(e=>dn(e,a,o)),n=t.lng||a.language,r=f.current,i=h.current;if(i&&i.ready===e&&i.lng===n&&i.keyPrefix===c&&i.revision===r)return i;let s={t:a.getFixedT(n,o.nsMode===`fallback`?d:d[0],c,{scopeNs:d}),ready:e,lng:n,keyPrefix:c,revision:r};return h.current=s,s},[a,d,c,o,t.lng]),[_,v]=(0,m.useState)(0),{t:y,ready:b}=(0,wn.useSyncExternalStore)(p,g,g);(0,m.useEffect)(()=>{if(a&&!b&&!s){let e=()=>v(e=>e+1);t.lng?un(a,t.lng,d,e):ln(a,d,e)}},[a,t.lng,d,b,s,_]);let x=a||{},S=(0,m.useRef)(null),C=(0,m.useRef)(),w=e=>{let t=Object.getOwnPropertyDescriptors(e);t.__original&&delete t.__original;let n=Object.create(Object.getPrototypeOf(e),t);if(!Object.prototype.hasOwnProperty.call(n,`__original`))try{Object.defineProperty(n,"__original",{value:e,writable:!1,enumerable:!1,configurable:!1})}catch{}return n},T=(0,m.useMemo)(()=>{let e=x,t=e?.language,n=e;e&&(S.current&&S.current.__original===e&&C.current===t?n=S.current:(n=w(e),S.current=n,C.current=t));let r=!b&&!s?(...e)=>(sn(a,`USE_T_BEFORE_READY`,`useTranslation: t was called before ready. When using useSuspense: false, make sure to check the ready flag before using t.`),y(...e)):y,i=[r,n,b];return i.t=r,i.i18n=n,i.ready=b,i},[y,x,b,x.resolvedLanguage,x.language,x.languages]);if(a&&s&&!b){let e=!1;try{e=!1}catch{}throw e&&sn(a,`SUSPENDED_WHILE_LOADING`,`useTranslation: suspended while translations are loading (useSuspense is true by default). Add a boundary above this component, or set react.useSuspense: false in the i18next init options. https://react.i18next.com/latest/usetranslation-hook`),new Promise(e=>{let n=()=>e();t.lng?un(a,t.lng,d,n):ln(a,d,n)})}return T};function On({i18n:e,defaultNS:t,children:n}){let r=(0,m.useMemo)(()=>({i18n:e,defaultNS:t}),[e,t]);return(0,m.createElement)(xn.Provider,{value:r},n)}var kn=[`getStatus`,`prepareSync`,`applySync`,`prepareSwitch`,`applySwitch`,`prepareRepair`,`applyRepair`,`listBackups`,`prepareRestore`,`applyRestore`,`pruneBackups`,`listHistory`,`getHistorySession`,`startWatch`,`stopWatch`,`getWatchStatus`,`getDiagnostics`],An=[`INVALID_INPUT`,`PROFILE_CHANGED`,`STORAGE_CHANGED`,`PLAN_STALE`,`PLAN_EXPIRED`,`STALE_STATE`,`CODEX_HOME_NOT_FOUND`,`STATE_DB_NOT_FOUND`,`SQLITE_UNSUPPORTED_PATH`,`SQLITE_BUSY`,`SQLITE_UNREADABLE`,`ROLLOUT_LOCKED`,`ROLLOUT_CHANGED`,`PENDING_TRANSACTION`,`BACKUP_FAILED`,`SYNC_FAILED_ROLLED_BACK`,`RECOVERY_REQUIRED`,`RESTORE_VALIDATION_FAILED`,`PERMISSION_DENIED`,`OPERATION_BUSY`,`LOCK_UNVERIFIABLE`,`OPERATION_CANCELLED`,`CORE_RUNTIME_CRASHED`,`PROTOCOL_VERSION_MISMATCH`,`INTERNAL_ERROR`],jn=new Set([`prepare_config`,`prepare_storage`,`prepare_rollouts`,`prepare_status`,`prepare_revisions`,`prepare_usage`,`acquire_lock`,`read_config`,`resolve_storage`,`check_pending_restore`,`validate_plan`,`scan_rollout_files`,`check_locked_rollout_files`,`preflight_sqlite`,`create_backup`,`update_config`,`rewrite_rollout_files`,`update_sqlite`,`release_lock`]),Mn=new Set([`ENOENT`,`EACCES`,`EPERM`,`EIO`,`EBUSY`,`ENOSPC`,`EMFILE`,`ENFILE`,`ETIMEDOUT`,`SQLITE_BUSY`,`SQLITE_LOCKED`,`SQLITE_CORRUPT`,`SQLITE_NOTADB`,`ERR_SQLITE_ERROR`]),Nn=Object.freeze({INVALID_INPUT:`The command input is invalid.`,PROFILE_CHANGED:`The selected profile changed. Prepare the operation again.`,STORAGE_CHANGED:`The resolved storage changed. Prepare the operation again.`,PLAN_STALE:`The prepared operation is stale. Prepare it again.`,PLAN_EXPIRED:`The prepared operation expired. Prepare it again.`,STALE_STATE:`The protected state changed. Prepare the operation again.`,CODEX_HOME_NOT_FOUND:`The selected Codex Home was not found.`,STATE_DB_NOT_FOUND:`The selected state database was not found.`,SQLITE_UNSUPPORTED_PATH:`The selected SQLite path is not supported by this runtime.`,SQLITE_BUSY:`The state database is busy. Close Codex processes and retry.`,SQLITE_UNREADABLE:`The state database is unreadable or malformed.`,ROLLOUT_LOCKED:`One or more rollout files are locked.`,ROLLOUT_CHANGED:`One or more rollout files changed during the operation.`,PENDING_TRANSACTION:`An unfinished transaction must be resolved before another write.`,BACKUP_FAILED:`The required backup could not be completed.`,SYNC_FAILED_ROLLED_BACK:`The operation failed and its changes were rolled back.`,RECOVERY_REQUIRED:`The operation requires explicit recovery.`,RESTORE_VALIDATION_FAILED:`The selected backup or restore target failed validation.`,PERMISSION_DENIED:`The operation does not have permission to access a required resource.`,OPERATION_BUSY:`Another write operation is using the protected resource.`,LOCK_UNVERIFIABLE:`The lock owner or protected resource identity cannot be verified.`,OPERATION_CANCELLED:`The operation was cancelled.`,CORE_RUNTIME_CRASHED:`The Core runtime stopped unexpectedly.`,PROTOCOL_VERSION_MISMATCH:`The client and Core protocol versions are incompatible.`,INTERNAL_ERROR:`An internal error occurred.`}),Pn=new Set([`PROFILE_CHANGED`,`STORAGE_CHANGED`,`PLAN_STALE`,`PLAN_EXPIRED`,`STALE_STATE`,`SQLITE_BUSY`,`ROLLOUT_LOCKED`,`ROLLOUT_CHANGED`,`OPERATION_BUSY`]),Fn=new Set([`PENDING_TRANSACTION`,`RECOVERY_REQUIRED`]),In=new Set([`codex-home`,`state-db`]),Ln=new Set([`profile`,`config`,`storage`,`rollout`,`state-db`,`provider-not-configured`,`windows-wsl-unc`]),Rn=new Set([`cli`,`config`,`env`,`default`]),zn=new Set([`sync`,`switch`,`repair`,`restore`,`prune-backups`,`watch`]),Bn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Vn=new Set(An);function Hn(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Un(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null?e:null}function Wn(e,t){if(!e)return;let n=Object.getOwnPropertyDescriptor(e,t);return n&&`value`in n?n.value:void 0}function Gn(e){return e===`OPERATION_CANCELLED`?`info`:e===`CORE_RUNTIME_CRASHED`||e===`INTERNAL_ERROR`?`fatal`:Pn.has(e)?`warning`:`error`}function Kn(e){let t=Un(e);if(!t)return;let n={},r=Wn(t,`busyScope`),i=Wn(t,`lockScope`),a=Wn(t,`causeCode`),o=Wn(t,`reason`),s=Wn(t,`missing`),c=Wn(t,`sqliteHomeSource`),l=Wn(t,`operationKind`),u=Wn(t,`failureStage`);In.has(String(r))&&(n.busyScope=String(r)),In.has(String(i))&&(n.lockScope=String(i)),Mn.has(String(a))&&(n.causeCode=String(a)),jn.has(String(u))&&(n.failureStage=String(u)),Ln.has(String(o))&&(n.reason=String(o)),(s===`config.toml`||s===`state_5.sqlite`)&&(n.missing=s),Rn.has(String(c))&&(n.sqliteHomeSource=String(c));for(let e of[`sqlitePrimaryCode`,`sqliteExtendedCode`]){let r=Wn(t,e);Number.isInteger(r)&&Number(r)>=0&&Number(r)<=65535&&(n[e]=Number(r))}return zn.has(String(l))&&(n.operationKind=String(l)),Object.keys(n).length>0?n:void 0}function qn(e,t={}){Vn.has(e)||(e=`INTERNAL_ERROR`);let n=Kn(t.details),r=n?Object.fromEntries(Object.entries(n).filter(([e])=>e===`failureStage`||e===`causeCode`)):void 0;if(e===`INTERNAL_ERROR`)return{code:e,message:Nn[e],severity:`fatal`,retryable:!1,recoveryRequired:!1,...typeof t.operationId==`string`&&Bn.test(t.operationId)?{operationId:t.operationId}:{},...r&&Object.keys(r).length>0?{details:r}:{}};if(e===`OPERATION_BUSY`&&n?.busyScope===void 0||e===`LOCK_UNVERIFIABLE`&&n?.lockScope===void 0)return qn(`INTERNAL_ERROR`);let i=typeof t.operationId==`string`&&Bn.test(t.operationId)?t.operationId:void 0;return{code:e,message:Nn[e],severity:Gn(e),retryable:!0,recoveryRequired:Fn.has(e),...i?{operationId:i}:{},...n?{details:n}:{}}}function Jn(e){let t=Hn(e),n=Wn(t,`code`);return qn(typeof n==`string`&&Vn.has(n)?n:`INTERNAL_ERROR`,{operationId:Wn(t,`operationId`),details:Wn(t,`details`)})}function Yn(e){let t=Un(e);if(!t)return!1;let n=Wn(t,`code`);if(typeof n!=`string`||!Vn.has(n))return!1;let r=Jn(t),i=Object.keys(t).sort(),a=Object.keys(r).sort();if(i.length!==a.length||i.some((e,t)=>e!==a[t]))return!1;for(let e of a)if(e!==`details`&&Wn(t,e)!==r[e])return!1;let o=Un(Wn(t,`details`)),s=r.details;if(s===void 0)return o===null;if(!o)return!1;let c=Object.keys(o).sort(),l=Object.keys(s).sort();return c.length===l.length&&c.every((e,t)=>e===l[t]&&Wn(o,e)===s[e])}var Xn=[`attemptedFiles`,`measuredFiles`,`inPlaceFiles`,`rewrittenFiles`,`skippedFiles`],Zn=[`totalMs`,`workerStartupMs`,`workerCloseMs`,`requestRoundTripMs`,`workerMs`,`sourceOpenMs`,`readHeaderMs`,`tempCreateMs`,`copyTailMs`,`flushMs`,`replaceMs`,`cleanupMs`,`restoreMtimeMs`],Qn=new Set([`schemaVersion`,`scope`,...Xn,...Zn]);function $n(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return t.schemaVersion!==1||t.scope!==`windows-first-line`||Object.keys(t).some(e=>!Qn.has(e))||!Xn.every(e=>Number.isSafeInteger(t[e])&&Number(t[e])>=0)||!Zn.every(e=>typeof t[e]==`number`&&Number.isFinite(t[e])&&Number(t[e])>=0)?!1:Number(t.measuredFiles)<=Number(t.attemptedFiles)&&Number(t.inPlaceFiles)+Number(t.rewrittenFiles)+Number(t.skippedFiles)<=Number(t.attemptedFiles)}var er=new Set(kn);new Set(An);var tr=[`models`,`cwd`,`userEvent`,`workspaceRoots`],nr=new Set(tr);function B(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function V(e){return typeof e==`string`&&e.length>0}function rr(e,t){let n=new Set(t);return Object.keys(e).every(e=>n.has(e))}function ir(e){if(!B(e)||!rr(e,[`profileId`,`profileRevision`])||typeof e.profileId!=`string`||!/^[A-Za-z0-9._-]{1,80}$/.test(e.profileId)||e.profileRevision!==void 0&&(!V(e.profileRevision)||e.profileRevision.length>512))throw new H(`INVALID_INPUT`,`Invalid profile selector.`)}function ar(e,t){if(!B(e)||!rr(e,[`profile`,...t]))throw new H(`INVALID_INPUT`,`Invalid Core method input.`);ir(e.profile)}var H=class extends Error{code;constructor(e,t){super(t),this.name=`ContractValidationError`,this.code=e}};function or(e){if(e!==1)throw new H(`PROTOCOL_VERSION_MISMATCH`,`Unsupported Core protocol version: ${String(e)}.`)}function sr(e){if(!B(e)||Object.keys(e).sort().join(`,`)!==`planId,schemaVersion`||e.schemaVersion!==1||!V(e.planId))throw new H(`INVALID_INPUT`,`Apply accepts exactly { schemaVersion: 1, planId }.`)}function cr(e,t){switch(e){case`applySync`:case`applySwitch`:case`applyRepair`:case`applyRestore`:sr(t);return;case`getStatus`:case`listBackups`:case`getDiagnostics`:ar(t,[]);return;case`prepareSync`:if(ar(t,[`keepCount`]),t.keepCount!==void 0&&(!Number.isSafeInteger(t.keepCount)||Number(t.keepCount)<1))throw new H(`INVALID_INPUT`,`Invalid Sync retention count.`);return;case`prepareSwitch`:if(ar(t,[`provider`,`modelMode`,`model`,`keepCount`]),!V(t.provider)||![`provider-default`,`keep-root-model`,`explicit`].includes(String(t.modelMode))||t.modelMode===`explicit`&&!V(t.model)||t.modelMode!==`explicit`&&t.model!==void 0||t.keepCount!==void 0&&(!Number.isSafeInteger(t.keepCount)||Number(t.keepCount)<1))throw new H(`INVALID_INPUT`,`Invalid Switch Provider input.`);return;case`prepareRepair`:{ar(t,[`targets`,`keepCount`,`sessionIds`]);let e=Array.isArray(t.targets)?t.targets:[];if(e.length<1||e.length>tr.length||e.some(e=>typeof e!=`string`||!nr.has(e))||new Set(e).size!==e.length||t.sessionIds!==void 0&&(!Array.isArray(t.sessionIds)||t.sessionIds.length<1||t.sessionIds.length>100||t.sessionIds.some(e=>typeof e!=`string`||!/^[A-Za-z0-9_-]{1,128}$/.test(e))||new Set(t.sessionIds).size!==t.sessionIds.length||e.includes(`workspaceRoots`))||t.keepCount!==void 0&&(!Number.isSafeInteger(t.keepCount)||Number(t.keepCount)<1))throw new H(`INVALID_INPUT`,`Invalid Repair input.`);return}case`prepareRestore`:if(ar(t,[`backupId`,`restoreConfig`,`restoreDatabase`,`restoreSessions`,`allowSqliteHomeRelocation`,`relocationTargetProfileId`]),!V(t.backupId)||typeof t.restoreConfig!=`boolean`||typeof t.restoreDatabase!=`boolean`||typeof t.restoreSessions!=`boolean`||t.allowSqliteHomeRelocation!==void 0&&typeof t.allowSqliteHomeRelocation!=`boolean`||t.relocationTargetProfileId!==void 0&&(typeof t.relocationTargetProfileId!=`string`||!/^[A-Za-z0-9._-]{1,80}$/.test(t.relocationTargetProfileId))||t.allowSqliteHomeRelocation===!0&&(t.restoreConfig!==!1||t.relocationTargetProfileId===void 0)||t.relocationTargetProfileId!==void 0&&t.allowSqliteHomeRelocation!==!0)throw new H(`INVALID_INPUT`,`Invalid Restore input.`);return;case`pruneBackups`:if(ar(t,[`keepCount`]),!Number.isSafeInteger(t.keepCount)||Number(t.keepCount)<0)throw new H(`INVALID_INPUT`,`Invalid Prune retention count.`);return;case`listHistory`:if(ar(t,[`page`,`pageSize`,`query`,`project`,`provider`,`archived`,`searchScope`,`sessionKind`,`view`,`projectId`,`parentId`]),t.page!==void 0&&(!Number.isSafeInteger(t.page)||Number(t.page)<1)||t.pageSize!==void 0&&(!Number.isSafeInteger(t.pageSize)||Number(t.pageSize)<10||Number(t.pageSize)>100)||[`query`,`project`,`provider`,`projectId`,`parentId`].some(e=>t[e]!==void 0&&typeof t[e]!=`string`)||t.view!==void 0&&![`flat`,`projects`].includes(String(t.view))||t.projectId!==void 0&&!(/^[a-f0-9]{64}$/.test(String(t.projectId))||[`unassigned`,`orphans`].includes(String(t.projectId)))||t.parentId!==void 0&&(!V(t.parentId)||t.parentId.length>512)||t.searchScope!==void 0&&![`metadata`,`content`].includes(String(t.searchScope))||t.sessionKind!==void 0&&![`all`,`main`,`subagent`].includes(String(t.sessionKind))||t.archived!==void 0&&![`all`,`active`,`archived`].includes(String(t.archived)))throw new H(`INVALID_INPUT`,`Invalid History list input.`);return;case`getHistorySession`:if(ar(t,[`sessionId`,`messageLimit`,`metadataOnly`]),!V(t.sessionId)||t.metadataOnly!==void 0&&typeof t.metadataOnly!=`boolean`||t.messageLimit!==void 0&&(!Number.isSafeInteger(t.messageLimit)||Number(t.messageLimit)<1||Number(t.messageLimit)>200))throw new H(`INVALID_INPUT`,`Invalid History detail input.`);return;case`startWatch`:if(ar(t,[`includeStateDb`,`debounceMs`,`once`,`keepCount`]),t.includeStateDb!==void 0&&typeof t.includeStateDb!=`boolean`||t.once!==void 0&&typeof t.once!=`boolean`||t.debounceMs!==void 0&&(!Number.isSafeInteger(t.debounceMs)||Number(t.debounceMs)<0)||t.keepCount!==void 0&&(!Number.isSafeInteger(t.keepCount)||Number(t.keepCount)<1))throw new H(`INVALID_INPUT`,`Invalid Watch input.`);return;case`stopWatch`:if(!B(t)||!rr(t,[`watchId`])||!V(t.watchId))throw new H(`INVALID_INPUT`,`Invalid Watch reference.`);return;case`getWatchStatus`:if(!B(t)||!rr(t,[`profile`,`watchId`])||t.watchId!==void 0&&!V(t.watchId)||t.profile!==void 0&&t.watchId!==void 0)throw new H(`INVALID_INPUT`,`Invalid Watch status input.`);t.profile!==void 0&&ir(t.profile);return;default:throw new H(`INVALID_INPUT`,`Unknown Core method input.`)}}function lr(e){if(!Yn(e))throw new H(`INVALID_INPUT`,`Invalid public CoreErrorDto.`)}function ur(e){if(!B(e))throw new H(`INVALID_INPUT`,`Core request envelope must be an object.`);let t=new Set([`protocolVersion`,`requestId`,`operationId`,`method`,`payload`]);if(Object.keys(e).some(e=>!t.has(e)))throw new H(`INVALID_INPUT`,`Core request envelope has unknown fields.`);if(or(e.protocolVersion),!V(e.requestId)||!V(e.method)||!er.has(e.method)||!B(e.payload))throw new H(`INVALID_INPUT`,`Invalid Core request envelope.`);if(e.operationId!==void 0&&!V(e.operationId))throw new H(`INVALID_INPUT`,`Invalid Core request operationId.`);cr(e.method,e.payload)}function dr(e,t){if(!B(e))throw new H(`INVALID_INPUT`,`Core response envelope must be an object.`);let n=e.ok===!0?new Set([`protocolVersion`,`requestId`,`operationId`,`ok`,`result`]):new Set([`protocolVersion`,`requestId`,`operationId`,`ok`,`error`]);if(Object.keys(e).some(e=>!n.has(e)))throw new H(`INVALID_INPUT`,`Core response envelope has unknown fields.`);if(or(e.protocolVersion),!V(e.requestId)||t!==void 0&&e.requestId!==t||typeof e.ok!=`boolean`)throw new H(`INVALID_INPUT`,`Invalid Core response envelope.`);if(e.operationId!==void 0&&!V(e.operationId))throw new H(`INVALID_INPUT`,`Invalid Core response operationId.`);if(e.ok){if(!(`result`in e)||`error`in e)throw new H(`INVALID_INPUT`,`Invalid successful Core response.`)}else{if(!(`error`in e)||`result`in e)throw new H(`INVALID_INPUT`,`Invalid failed Core response.`);lr(e.error)}}function fr(e,t){if(!B(e)||e.schemaVersion!==1)throw new H(`INVALID_INPUT`,`Invalid ${t}.`);return e}function pr(e,t){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw new H(`INVALID_INPUT`,`Invalid ${t}.`)}function mr(e){return Number.isSafeInteger(e)&&Number(e)>=0}function hr(e){return e===null||typeof e==`string`}function gr(e,t=0){return t>16?!1:e===null||typeof e==`string`||typeof e==`boolean`?!0:typeof e==`number`?Number.isFinite(e):Array.isArray(e)?e.every(e=>gr(e,t+1)):B(e)?Object.values(e).every(e=>gr(e,t+1)):!1}function _r(e){return B(e)?Object.values(e).every(e=>B(e)&&Object.values(e).every(mr)):!1}var vr=new Set([`prepared`,`applying`,`applied`,`skipped`,`committing`,`committed-pending-ack`,`rollback-pending`,`rollingBack`,`recovery-required`,`recoveryRequired`,`unknown`]);function yr(e){return typeof e==`string`&&/^[A-Za-z0-9._()-]{1,200}$/.test(e)}function br(e){return typeof e==`string`&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}function xr(e){return!B(e)||Object.keys(e).length>512?!1:Object.entries(e).every(([e,t])=>yr(e)&&mr(t))}function Sr(e,t=!1){return!B(e)||!rr(e,t?[`sessions`,`archived_sessions`,`unreadable`]:[`sessions`,`archived_sessions`])||!(`sessions`in e)||!(`archived_sessions`in e)||!xr(e.sessions)||!xr(e.archived_sessions)?!1:!t||e.unreadable===void 0||e.unreadable===!0}function Cr(e){return B(e)&&Object.keys(e).sort().join(`,`)===`operationId,operationKind,preRestoreSnapshotId,sourceBackupId,state`&&(e.operationId===null||br(e.operationId))&&[`sync`,`switch`,`restore`].includes(String(e.operationKind))&&vr.has(String(e.state))&&(e.sourceBackupId===null||yr(e.sourceBackupId))&&(e.preRestoreSnapshotId===null||yr(e.preRestoreSnapshotId))}function wr(e){return e===null?!0:!B(e)||!rr(e,[`operationId`,`operation`,`actor`,`startedAt`,`busyScope`,`lockState`,`errorCode`])?!1:(e.operationId===void 0||br(e.operationId))&&(e.operation===void 0||[`sync`,`switch`,`repair`,`restore`,`prune`,`watch`,`unknown`].includes(String(e.operation)))&&(e.actor===void 0||[`manual`,`watch`,`external`].includes(String(e.actor)))&&(e.startedAt===void 0||V(e.startedAt)&&e.startedAt.length<=64)&&(e.busyScope===void 0||[`codex-home`,`state-db`].includes(String(e.busyScope)))&&(e.lockState===void 0||yr(e.lockState)&&e.lockState.length<=80)&&(e.errorCode===void 0||typeof e.errorCode==`string`&&/^[A-Z0-9_]{1,80}$/.test(e.errorCode))}function Tr(e){if(!B(e)||!rr(e,[`version`,`outcome`,`issuesTruncated`,`counts`,`skipped`,`displayIndex`,`issues`,`limits`]))return!1;let t=[[`counts`,[`filesDiscovered`,`filesScanned`,`recordsRead`,`sessionsWithId`,`jsonCorruptRecords`,`oversizedRecords`,`duplicateOrdinals`,`outOfOrderOrdinals`,`changedFiles`,`truncatedFiles`,`unsupportedFiles`]],[`skipped`,[`symlinkOrReparse`,`outOfRoot`,`notRegular`,`unreadable`,`scanLimit`]],[`limits`,[`maxFiles`,`maxRecordsPerFile`,`maxLineBytes`,`maxIssues`]]],n=[`json-corrupt`,`record-too-large`,`ordinal-duplicate-observed`,`ordinal-out-of-order-observed`,`record-limit-reached`,`changed-during-scan`,`unterminated-record`,`unsupported-format`,`invalid-utf8`,`unverified`];return e.version===1&&[`no-findings`,`findings`,`inconclusive`,`findings-and-inconclusive`].includes(String(e.outcome))&&typeof e.issuesTruncated==`boolean`&&t.every(([t,n])=>{let r=e[t];return B(r)&&rr(r,[...n])&&n.every(e=>mr(r[e]))})&&B(e.displayIndex)&&rr(e.displayIndex,[`status`,`reason`])&&e.displayIndex.status===`unsupported`&&e.displayIndex.reason===`no-known-display-index-schema`&&Array.isArray(e.issues)&&e.issues.length<=100&&e.issues.every(e=>B(e)&&rr(e,[`code`,`sessionId`,`scope`,`line`])&&n.includes(String(e.code))&&(e.sessionId===null||typeof e.sessionId==`string`&&/^[A-Za-z0-9_-]{1,128}$/.test(e.sessionId))&&[`sessions`,`archived_sessions`].includes(String(e.scope))&&(e.line===null||mr(e.line)&&Number(e.line)>0))}function Er(e){let t=fr(e,`DiagnosticsSnapshot`),n=B(t.runtime)?t.runtime:null,r=B(t.storage)?t.storage:null,i=B(t.provider)?t.provider:null,a=B(t.issues)?t.issues:null,o=B(t.safety)?t.safety:null;if(!(rr(t,[`schemaVersion`,`generatedAt`,`runtime`,`storage`,`provider`,`issues`,`safety`,`historyIntegrity`])&&(t.historyIntegrity===void 0||Tr(t.historyIntegrity))&&V(t.generatedAt)&&t.generatedAt.length<=64&&n!==null&&Object.keys(n).sort().join(`,`)===`arch,node,platform`&&[n.node,n.platform,n.arch].every(e=>typeof e==`string`&&/^[A-Za-z0-9._-]{1,80}$/.test(e))&&r!==null&&Object.keys(r).sort().join(`,`)===`sqliteHomeSource,sqliteSupported,stateDbFound`&&[`cli`,`config`,`env`,`default`,`unknown`].includes(String(r.sqliteHomeSource))&&typeof r.stateDbFound==`boolean`&&typeof r.sqliteSupported==`boolean`&&i!==null&&Object.keys(i).sort().join(`,`)===`configured,current,implicit,rolloutCounts,sqliteCounts`&&yr(i.current)&&typeof i.implicit==`boolean`&&Array.isArray(i.configured)&&i.configured.length<=256&&i.configured.every(yr)&&Sr(i.rolloutCounts)&&(i.sqliteCounts===null||Sr(i.sqliteCounts,!0))&&a!==null&&Object.keys(a).sort().join(`,`)===`cwdRowsNeedingRepair,encryptedContentFiles,rolloutModelFilesNeedingRepair,rootModelAvailable,sqliteModelRowsNeedingRepair,userEventRowsNeedingRepair,workspaceRootsNeedingRepair`&&typeof a.rootModelAvailable==`boolean`&&[a.rolloutModelFilesNeedingRepair,a.sqliteModelRowsNeedingRepair,a.cwdRowsNeedingRepair,a.userEventRowsNeedingRepair,a.workspaceRootsNeedingRepair,a.encryptedContentFiles].every(mr)&&o!==null&&rr(o,[`storageRevision`,`pendingRecovery`,`pendingTransactions`,`operationInProgress`,`rolloutScanComplete`,`lockedRolloutCount`,`projectThreadVisibilityAvailable`,...o.staleLockDetected===void 0?[]:[`staleLockDetected`]])&&(o.storageRevision===void 0||typeof o.storageRevision==`string`&&/^[A-Za-z0-9_-]{1,256}$/.test(o.storageRevision))&&typeof o.pendingRecovery==`boolean`&&Array.isArray(o.pendingTransactions)&&o.pendingTransactions.length<=256&&o.pendingTransactions.every(Cr)&&wr(o.operationInProgress)&&typeof o.rolloutScanComplete==`boolean`&&mr(o.lockedRolloutCount)&&typeof o.projectThreadVisibilityAvailable==`boolean`&&(o.staleLockDetected===void 0||typeof o.staleLockDetected==`boolean`)))throw new H(`INVALID_INPUT`,`Invalid DiagnosticsSnapshot.`)}function Dr(e){return B(e)?V(e.id)&&typeof e.title==`string`&&(e.project===void 0||e.project===null||B(e.project)&&Object.keys(e.project).every(e=>[`id`,`name`].includes(e))&&typeof e.project.id==`string`&&(/^[a-f0-9]{64}$/.test(e.project.id)||[`unassigned`,`orphans`].includes(e.project.id))&&V(e.project.name)&&e.project.name.length<=160&&!/[\x00-\x1f\x7f]/.test(e.project.name))&&(e.nativeSessionId===void 0||e.nativeSessionId===null||V(e.nativeSessionId)&&e.nativeSessionId.length<=512)&&(e.parentSessionId===void 0||e.parentSessionId===null||V(e.parentSessionId)&&e.parentSessionId.length<=512)&&(e.sessionKind===void 0||[`main`,`subagent`].includes(String(e.sessionKind)))&&(e.childCount===void 0||mr(e.childCount))&&(e.fileModifiedAt===void 0||V(e.fileModifiedAt))&&(e.subagentName===void 0||V(e.subagentName)&&e.subagentName.length<=160&&!/[\\/\x00-\x1f]/.test(e.subagentName))&&!(`cwd`in e)&&V(e.provider)&&typeof e.archived==`boolean`&&V(e.updatedAt)&&mr(e.messageCount)&&(e.messageCountKnown===void 0||typeof e.messageCountKnown==`boolean`)&&(e.model===void 0||hr(e.model))&&(e.createdAt===void 0||V(e.createdAt)):!1}function Or(e){let t=fr(e,`WatchSnapshot`);if(!V(t.watchId)||![`running`,`stopping`,`stopped`].includes(String(t.status))||!V(t.startedAt)||!hr(t.stoppedAt)||!hr(t.stopReason)||typeof t.includeStateDb!=`boolean`||typeof t.once!=`boolean`)throw new H(`INVALID_INPUT`,`Invalid WatchSnapshot.`)}function kr(e){return B(e)&&Object.keys(e).sort().join(`,`)===`count,state`&&(e.state===`checked`?mr(e.count):(e.state===`unavailable`||e.state===`unsupported`)&&e.count===null)}function Ar(e,t){switch(e){case`getStatus`:{let e=fr(t,`StatusSnapshot`),n=B(e.profile)?e.profile:null,r=e=>typeof e==`string`&&e.length>0&&e.length<=32768&&!e.includes(`\0`)&&/^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(e),i=e.displayPaths,a=e.syncSessionUsage;if(!V(e.snapshotAt)||!V(e.storageRevision)||!n||!V(n.id)||!V(n.revision)||!V(e.currentProvider)||e.sessionActivity!==void 0&&!kr(e.sessionActivity)||a!==void 0&&(!B(a)||Object.keys(a).sort().join(`,`)!==`count,state`||!(a.state===`checked`?mr(a.count):(a.state===`unavailable`||a.state===`unsupported`)&&a.count===null))||!_r(e.rolloutCounts)||e.modelCounts!==void 0&&!_r(e.modelCounts)||!(`sqliteCounts`in e)||!gr(e.sqliteCounts)||`codexHome`in e||`sqliteHome`in e||i!==void 0&&(!B(i)||Object.keys(i).sort().join(`,`)!==`codexHome,sqliteHome,stateDbPath`||!r(i.codexHome)||!r(i.sqliteHome)||!(i.stateDbPath===null||r(i.stateDbPath)))||!V(e.codexHomeSource)||!V(e.sqliteHomeSource)||!B(e.backupSummary)||!mr(e.backupSummary.count)||!mr(e.backupSummary.totalBytes)||typeof e.pendingRecovery!=`boolean`||e.staleLockDetected!==void 0&&typeof e.staleLockDetected!=`boolean`||!Array.isArray(e.pendingTransactions)||e.pendingTransactions.some(e=>!B(e)||!gr(e))||!(e.operationInProgress===null||B(e.operationInProgress)&&gr(e.operationInProgress))||typeof e.rolloutScanComplete!=`boolean`||!Array.isArray(e.lockedRolloutFiles)||e.lockedRolloutFiles.some(e=>typeof e!=`string`)||e.currentModel!==void 0&&!hr(e.currentModel))throw new H(`INVALID_INPUT`,`Invalid StatusSnapshot.`);return}case`prepareSync`:case`prepareSwitch`:case`prepareRepair`:case`prepareRestore`:{let n=fr(t,`PlanSummary`),r=e===`prepareSync`?`sync`:e===`prepareSwitch`?`switch`:e===`prepareRepair`?`repair`:`restore`;if(!rr(n,[`schemaVersion`,`planId`,`operation`,`createdAt`,`expiresAt`,`profile`,`storageRevision`,`configRevision`,`rolloutRevision`,`stateDbRevision`,`target`,`impact`,`warnings`,`requiresConfirmation`,...n.backupRevision===void 0?[]:[`backupRevision`]])||!V(n.planId)||n.operation!==r||!V(n.createdAt)||!V(n.expiresAt)||!B(n.profile)||!V(n.profile.id)||!V(n.profile.revision)||!V(n.storageRevision)||!V(n.configRevision)||!V(n.rolloutRevision)||!V(n.stateDbRevision)||n.backupRevision!==void 0&&!V(n.backupRevision)||!B(n.target)||!gr(n.target)||!B(n.impact)||!gr(n.impact)||n.impact.sessionActivity!==void 0&&!kr(n.impact.sessionActivity)||!Array.isArray(n.warnings)||n.warnings.some(e=>typeof e!=`string`)||typeof n.requiresConfirmation!=`boolean`)throw new H(`INVALID_INPUT`,`Invalid PlanSummary.`);return}case`applySync`:case`applySwitch`:case`applyRepair`:case`applyRestore`:{let n=fr(t,`OperationResult`),r=e===`applySync`?`sync`:e===`applySwitch`?`switch`:e===`applyRepair`?`repair`:`restore`;if(!rr(n,[`schemaVersion`,`operationId`,`operation`,`outcome`,`backup`,`warnings`,`result`])||!V(n.operationId)||n.operation!==r||![`completed`,`partial`,`failed_rolled_back`,`recovery_required`,`cancelled`,`stale`].includes(String(n.outcome))||!(n.backup===null||B(n.backup)&&V(n.backup.backupId)))throw new H(`INVALID_INPUT`,`Invalid OperationResult.`);if(pr(n.warnings,`OperationResult warnings`),!(`result`in n)||!gr(n.result))throw new H(`INVALID_INPUT`,`OperationResult result is required.`);if(B(n.result)&&n.result.fileUpdateTiming!==void 0&&!$n(n.result.fileUpdateTiming))throw new H(`INVALID_INPUT`,`Invalid file update timing.`);return}case`listBackups`:if(!B(t)||!Array.isArray(t.backups)||t.backups.some(e=>{let t=B(e)?e:null;return!t||!V(t.backupId)||!mr(t.sizeBytes)||!B(t.metadata)||!gr(t.metadata)||t.createdAt!==void 0&&!V(t.createdAt)}))throw new H(`INVALID_INPUT`,`Invalid BackupList.`);return;case`pruneBackups`:if(!B(t)||!mr(t.deletedCount)||!mr(t.remainingCount)||!mr(t.freedBytes))throw new H(`INVALID_INPUT`,`Invalid PruneBackupsResult.`);return;case`listHistory`:if(!B(t)||!Number.isSafeInteger(t.page)||Number(t.page)<1||!Number.isSafeInteger(t.pageSize)||Number(t.pageSize)<1||!mr(t.total)||typeof t.hasNextPage!=`boolean`||!Array.isArray(t.sessions)||t.sessions.some(e=>!Dr(e))||t.view!==void 0&&t.view!==`projects`||t.projects!==void 0&&(!Array.isArray(t.projects)||t.projects.some(e=>!B(e)||Object.keys(e).sort().join(`,`)!==`id,kind,name,total`||typeof e.id!=`string`||!(/^[a-f0-9]{64}$/.test(e.id)||[`unassigned`,`orphans`].includes(e.id))||!V(e.name)||e.name.length>160||![`workspace`,`directory`,`unassigned`,`orphans`].includes(String(e.kind))||!mr(e.total)))||t.projectId!==void 0&&t.projectId!==null&&typeof t.projectId!=`string`)throw new H(`INVALID_INPUT`,`Invalid HistoryPage.`);return;case`getHistorySession`:if(!B(t)||!Dr(t.session)||t.storage!==void 0&&(!B(t.storage)||Object.keys(t.storage).some(e=>![`cwd`,`rolloutPath`].includes(e))||typeof t.storage.cwd!=`string`||t.storage.cwd.length>32768||!V(t.storage.rolloutPath)||t.storage.rolloutPath.length>32768||/[\x00]/.test(t.storage.cwd+t.storage.rolloutPath))||!Array.isArray(t.messages)||t.messages.some(e=>{let t=B(e)?e:null;return!t||!V(t.role)||typeof t.text!=`string`||!mr(t.sequence)||t.timestamp!==void 0&&!V(t.timestamp)})||typeof t.truncated!=`boolean`||!mr(t.returnedMessageCount)||Number(t.returnedMessageCount)!==t.messages.length)throw new H(`INVALID_INPUT`,`Invalid HistorySessionDetail.`);return;case`startWatch`:case`stopWatch`:Or(t);return;case`getWatchStatus`:if(B(t)&&Array.isArray(t.watches)){fr(t,`WatchStatusList`),t.watches.forEach(Or);return}Or(t);return;case`getDiagnostics`:Er(t);return;default:throw new H(`INVALID_INPUT`,`Unknown Core method output.`)}}function jr(e){if(!B(e))throw new H(`INVALID_INPUT`,`Progress event must be an object.`);let t=new Set([`stage`,`status`,`progress`,`count`]);if(Object.keys(e).some(e=>!t.has(e))||!V(e.stage)||!V(e.status)||e.stage.length>80||e.status.length>40||e.progress!==void 0&&(typeof e.progress!=`number`||!Number.isFinite(e.progress)||e.progress<0||e.progress>1)||e.count!==void 0&&(!Number.isSafeInteger(e.count)||Number(e.count)<0))throw new H(`INVALID_INPUT`,`Invalid ProgressEvent.`)}function Mr(e,t,n){if(!B(e)||!rr(e,[`protocolVersion`,`requestId`,`operationId`,`event`,`operation`])||(or(e.protocolVersion),!V(e.requestId)||e.requestId.length>512||t!==void 0&&e.requestId!==t||!V(e.operationId)||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e.operationId)||n!==void 0&&e.operationId!==n||e.event!==`operation-started`||![`sync`,`switch`,`repair`,`restore`].includes(String(e.operation))))throw new H(`INVALID_INPUT`,`Invalid operation-started envelope.`)}function Nr(e,t,n){if(!B(e)||!rr(e,[`protocolVersion`,`requestId`,`operationId`,`event`,`progress`])||(or(e.protocolVersion),!V(e.requestId)||e.requestId.length>512||t!==void 0&&e.requestId!==t||!V(e.operationId)||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e.operationId)||n!==void 0&&e.operationId!==n||e.event!==`progress`))throw new H(`INVALID_INPUT`,`Invalid Core progress envelope.`);jr(e.progress)}function Pr(e,t){if(!B(e)||!rr(e,[`protocolVersion`,`requestId`,`event`,`progress`])||(or(e.protocolVersion),!V(e.requestId)||e.requestId.length>512||t!==void 0&&e.requestId!==t||e.event!==`request-progress`))throw new H(`INVALID_INPUT`,`Invalid Core request progress envelope.`);jr(e.progress)}function Fr(e,t,n){if(B(e)&&e.event===`operation-started`){Mr(e,t,n);return}Nr(e,t,n)}function Ir(e,t,n,r){let i={protocolVersion:1,requestId:n,...r?{operationId:r}:{},method:e,payload:t};return ur(i),i}function Lr(e,t,n){return lr(t),{protocolVersion:1,requestId:e.requestId,...n??t.operationId??e.operationId?{operationId:n??t.operationId??e.operationId}:{},ok:!1,error:t}}var Rr=class extends Error{dto;code;constructor(e){lr(e),super(e.message),this.name=`CoreClientError`,this.dto=e,this.code=e.code}};function zr(){return globalThis.crypto?.randomUUID?.()??`request-${Date.now()}-${Math.random().toString(16).slice(2)}`}var Br=class{#e;#t;constructor(e,{requestIdFactory:t=zr}={}){this.#e=e,this.#t=t}async#n(e,t,n={}){let r=n.requestId??this.#t(),i=Ir(e,t,r,n.operationId),a=await this.#e.request(i,{signal:n.signal,onOperationStarted:n.onOperationStarted,onProgress:n.onProgress,onRequestProgress:n.onRequestProgress});try{dr(a,r),a.ok&&Ar(e,a.result)}catch(e){throw e instanceof H?new Rr(qn(e.code===`PROTOCOL_VERSION_MISMATCH`?`PROTOCOL_VERSION_MISMATCH`:`INTERNAL_ERROR`)):e}if(!a.ok)throw new Rr(a.error);return a.result}getStatus(e,t){return this.#n(`getStatus`,e,t)}prepareSync(e,t){return this.#n(`prepareSync`,e,t)}applySync(e,t){return this.#n(`applySync`,e,t)}prepareSwitch(e,t){return this.#n(`prepareSwitch`,e,t)}applySwitch(e,t){return this.#n(`applySwitch`,e,t)}prepareRepair(e,t){return this.#n(`prepareRepair`,e,t)}applyRepair(e,t){return this.#n(`applyRepair`,e,t)}listBackups(e,t){return this.#n(`listBackups`,e,t)}prepareRestore(e,t){return this.#n(`prepareRestore`,e,t)}applyRestore(e,t){return this.#n(`applyRestore`,e,t)}pruneBackups(e,t){return this.#n(`pruneBackups`,e,t)}listHistory(e,t){return this.#n(`listHistory`,e,t)}getHistorySession(e,t){return this.#n(`getHistorySession`,e,t)}startWatch(e,t){return this.#n(`startWatch`,e,t)}stopWatch(e,t){return this.#n(`stopWatch`,e,t)}getWatchStatus(e,t){return this.#n(`getWatchStatus`,e,t)}getDiagnostics(e,t){return this.#n(`getDiagnostics`,e,t)}},Vr=Object.freeze([`getStatus`,`listBackups`,`listHistory`,`getHistorySession`,`getDiagnostics`]),Hr=Object.freeze([`prepareSync`,`applySync`,`prepareSwitch`,`applySwitch`,`prepareRepair`,`applyRepair`]),Ur=Object.freeze([`prepareRestore`,`applyRestore`]),Wr=Object.freeze([`pruneBackups`,`startWatch`,`stopWatch`,`getWatchStatus`]);Object.freeze([...Vr,...Hr,...Ur,...Wr]),new Set(Vr),new Set(Hr),new Set(Ur),new Set(Wr);function Gr(e){return e===`prepareRepair`||e===`getDiagnostics`}var Kr=`application/x-ndjson`;function qr(e,t){if(e)try{e(t)}catch{}}var Jr=class extends Error{status;constructor(e,t=null){super(e),this.name=`CoreTransportError`,this.status=t}},Yr=class{#e;#t;#n;#r;constructor({baseUrl:e,endpoint:t=`/api/core`,fetch:n=globalThis.fetch,headers:r={}}){if(typeof n!=`function`)throw TypeError(`HttpCoreTransport requires a Fetch implementation.`);this.#e=new URL(t,e),this.#t=new URL(`${t.replace(/\/$/,``)}/cancel`,e),this.#n=n,this.#r=Object.freeze({...r})}async request(e,t={}){let n=JSON.stringify(e);if(new TextEncoder().encode(n).byteLength>65536)throw new Jr(`Core request exceeds the 64 KiB transport limit.`);let r=e.method===`applySync`||e.method===`applySwitch`||e.method===`applyRepair`||e.method===`applyRestore`,i=Gr(e.method);if(t.signal?.aborted){if(r)return Lr(e,qn(`OPERATION_CANCELLED`));throw new DOMException(`The Core HTTP request was cancelled.`,`AbortError`)}let a,o=!1,s=()=>{o=!0,this.#n(this.#t,{method:`POST`,credentials:`same-origin`,redirect:`error`,headers:{"Content-Type":`application/json`,...this.#r},body:JSON.stringify({protocolVersion:e.protocolVersion,requestId:e.requestId,...a?{operationId:a}:{}})}).catch(()=>void 0)},c=r||i?s:void 0;c&&t.signal?.addEventListener(`abort`,c,{once:!0});let l;try{l=await this.#n(this.#e,{method:`POST`,credentials:`same-origin`,redirect:`error`,headers:{"Content-Type":`application/json`,Accept:Kr,...this.#r},body:n,signal:r||i?void 0:t.signal})}catch{throw c&&t.signal?.removeEventListener(`abort`,c),new Jr(`Core HTTP request failed.`)}if((l.headers.get(`content-type`)?.toLowerCase()??``).startsWith(Kr))try{let n=await this.#i(l,e,t,{get operationId(){return a},set operationId(e){a=e},get cancellationRequested(){return o},requestCancellation:s});if(!l.ok&&typeof n==`object`&&n&&!Array.isArray(n)&&`ok`in n&&n.ok===!0)throw new Jr(`Core HTTP request failed.`,l.status);return n}finally{c&&t.signal?.removeEventListener(`abort`,c)}let u;try{u=await l.json()}catch{throw c&&t.signal?.removeEventListener(`abort`,c),new Jr(`Core HTTP response was not valid JSON.`,l.status)}if(c&&t.signal?.removeEventListener(`abort`,c),!l.ok&&(typeof u!=`object`||!u||Array.isArray(u)||!(`ok`in u)||u.ok!==!1))throw new Jr(`Core HTTP request failed.`,l.status);return u}async#i(e,t,n,r){if(!e.body)throw new Jr(`Core HTTP stream has no body.`,e.status);let i=t.method===`applySync`||t.method===`applySwitch`||t.method===`applyRepair`||t.method===`applyRestore`,a=Gr(t.method),o=t.method===`applySync`?`sync`:t.method===`applySwitch`?`switch`:t.method===`applyRepair`?`repair`:t.method===`applyRestore`?`restore`:null,s=e.body.getReader(),c=new TextDecoder,l=``,u=0,d,f=s=>{if(!s.trim())return;if(d!==void 0)throw new Jr(`Core HTTP stream contained data after its terminal envelope.`,e.status);let c;try{c=JSON.parse(s)}catch{throw new Jr(`Core HTTP stream contained invalid JSON.`,e.status)}if(typeof c==`object`&&c&&!Array.isArray(c)&&`event`in c){if(c.event===`request-progress`){if(!a)throw new Jr(`Core HTTP stream contained request progress for an unsupported method.`,e.status);try{Pr(c,t.requestId)}catch{throw new Jr(`Core HTTP stream contained invalid request progress.`,e.status)}qr(n.onRequestProgress,c),r.cancellationRequested&&r.requestCancellation();return}if(!i)throw new Jr(`Core HTTP read stream contained an operation event.`,e.status);let s=`event`in c?c.event:void 0;if(r.operationId===void 0&&s!==`operation-started`)throw new Jr(`Core HTTP stream emitted progress before operation-started.`,e.status);if(r.operationId!==void 0&&s===`operation-started`)throw new Jr(`Core HTTP stream emitted multiple operation-started events.`,e.status);try{Fr(c,t.requestId,r.operationId)}catch{throw new Jr(`Core HTTP stream contained an invalid operation event.`,e.status)}let l=c;if(l.event===`operation-started`&&l.operation!==o)throw new Jr(`Core HTTP stream started the wrong operation.`,e.status);r.operationId=l.operationId,l.event===`operation-started`?qr(n.onOperationStarted,l):qr(n.onProgress,l),r.cancellationRequested&&r.requestCancellation();return}try{dr(c,t.requestId)}catch{throw new Jr(`Core HTTP stream contained an invalid terminal envelope.`,e.status)}let l=c,u=r.operationId;if(u!==void 0){if(l.operationId!==u||!l.ok&&l.error.operationId!==void 0&&l.error.operationId!==u)throw new Jr(`Core HTTP stream terminal operationId did not match its lifecycle.`,e.status)}else if(i&&l.operationId!==void 0)throw new Jr(`Core HTTP stream ended an unannounced operation.`,e.status);if(l.ok){try{Ar(t.method,l.result)}catch{throw new Jr(`Core HTTP stream contained an invalid terminal result.`,e.status)}if(i){if(u===void 0)throw new Jr(`Core HTTP apply stream ended without operation-started.`,e.status);if(l.result.operationId!==u)throw new Jr(`Core HTTP stream result operationId did not match its lifecycle.`,e.status)}}d=l};for(;;){let{value:t,done:n}=await s.read();if(n)break;if(u+=t.byteLength,u>16777216)throw await s.cancel(),new Jr(`Core HTTP stream exceeded its response limit.`,e.status);l+=c.decode(t,{stream:!0});let r;for(;(r=l.indexOf(` -`))>=0;)f(l.slice(0,r)),l=l.slice(r+1)}if(l+=c.decode(),f(l),d===void 0)throw new Jr(`Core HTTP stream ended without a terminal envelope.`,e.status);return d}},Xr=class extends Br{constructor(e){super(new Yr(e),{requestIdFactory:e.requestIdFactory})}},Zr=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim(),Qr=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),$r=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()),ei=e=>{let t=$r(e);return t.charAt(0).toUpperCase()+t.slice(1)},ti={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`},ni=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0;return!1},ri=(0,m.createContext)({}),ii=()=>(0,m.useContext)(ri),ai=(0,m.forwardRef)(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:i=``,children:a,iconNode:o,...s},c)=>{let{size:l=24,strokeWidth:u=2,absoluteStrokeWidth:d=!1,color:f=`currentColor`,className:p=``}=ii()??{},h=r??d?Number(n??u)*24/Number(t??l):n??u;return(0,m.createElement)(`svg`,{ref:c,...ti,width:t??l??ti.width,height:t??l??ti.height,stroke:e??f,strokeWidth:h,className:Zr(`lucide`,p,i),...!a&&!ni(s)&&{"aria-hidden":`true`},...s},[...o.map(([e,t])=>(0,m.createElement)(e,t)),...Array.isArray(a)?a:[a]])}),oi=(e,t)=>{let n=(0,m.forwardRef)(({className:n,...r},i)=>(0,m.createElement)(ai,{ref:i,iconNode:t,className:Zr(`lucide-${Qr(ei(e))}`,`lucide-${e}`,n),...r}));return n.displayName=ei(e),n},si=oi(`activity`,[[`path`,{d:`M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2`,key:`169zse`}]]),ci=oi(`archive-restore`,[[`rect`,{width:`20`,height:`5`,x:`2`,y:`3`,rx:`1`,key:`1wp1u1`}],[`path`,{d:`M4 8v11a2 2 0 0 0 2 2h2`,key:`tvwodi`}],[`path`,{d:`M20 8v11a2 2 0 0 1-2 2h-2`,key:`1gkqxj`}],[`path`,{d:`m9 15 3-3 3 3`,key:`1pd0qc`}],[`path`,{d:`M12 12v9`,key:`192myk`}]]),li=oi(`archive`,[[`rect`,{width:`20`,height:`5`,x:`2`,y:`3`,rx:`1`,key:`1wp1u1`}],[`path`,{d:`M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8`,key:`1s80jp`}],[`path`,{d:`M10 12h4`,key:`a56b0p`}]]),ui=oi(`arrow-left`,[[`path`,{d:`m12 19-7-7 7-7`,key:`1l729n`}],[`path`,{d:`M19 12H5`,key:`x3x0zl`}]]),di=oi(`check`,[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]),fi=oi(`chevron-down`,[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]),pi=oi(`chevron-right`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]),mi=oi(`circle-check`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),hi=oi(`copy`,[[`rect`,{width:`14`,height:`14`,x:`8`,y:`8`,rx:`2`,ry:`2`,key:`17jyea`}],[`path`,{d:`M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2`,key:`zix9uf`}]]),gi=oi(`database`,[[`ellipse`,{cx:`12`,cy:`5`,rx:`9`,ry:`3`,key:`msslwz`}],[`path`,{d:`M3 5V19A9 3 0 0 0 21 19V5`,key:`1wlel7`}],[`path`,{d:`M3 12A9 3 0 0 0 21 12`,key:`mv7ke4`}]]),_i=oi(`earth`,[[`path`,{d:`M21.54 15H17a2 2 0 0 0-2 2v4.54`,key:`1djwo0`}],[`path`,{d:`M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17`,key:`1tzkfa`}],[`path`,{d:`M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05`,key:`14pb5j`}],[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}]]),vi=oi(`file-clock`,[[`path`,{d:`M16 22h2a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v2.85`,key:`ryk6xj`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M8 14v2.2l1.6 1`,key:`6m4bie`}],[`circle`,{cx:`8`,cy:`16`,r:`6`,key:`10v15b`}]]),yi=oi(`folder-cog`,[[`path`,{d:`M10.3 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.98a2 2 0 0 1 1.69.9l.66 1.2A2 2 0 0 0 12 6h8a2 2 0 0 1 2 2v3.3`,key:`128dxu`}],[`path`,{d:`m14.305 19.53.923-.382`,key:`3m78fa`}],[`path`,{d:`m15.228 16.852-.923-.383`,key:`npixar`}],[`path`,{d:`m16.852 15.228-.383-.923`,key:`5xggr7`}],[`path`,{d:`m16.852 20.772-.383.924`,key:`dpfhf9`}],[`path`,{d:`m19.148 15.228.383-.923`,key:`1reyyz`}],[`path`,{d:`m19.53 21.696-.382-.924`,key:`1goivc`}],[`path`,{d:`m20.772 16.852.924-.383`,key:`htqkph`}],[`path`,{d:`m20.772 19.148.924.383`,key:`9w9pjp`}],[`circle`,{cx:`18`,cy:`18`,r:`3`,key:`1xkwt0`}]]),bi=oi(`folder-open`,[[`path`,{d:`m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2`,key:`usdka0`}]]),xi=oi(`folder`,[[`path`,{d:`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`,key:`1kt360`}]]),Si=oi(`gauge`,[[`path`,{d:`m12 14 4-4`,key:`9kzdfg`}],[`path`,{d:`M3.34 19a10 10 0 1 1 17.32 0`,key:`19p75a`}]]),Ci=oi(`git-branch`,[[`path`,{d:`M15 6a9 9 0 0 0-9 9V3`,key:`1cii5b`}],[`circle`,{cx:`18`,cy:`6`,r:`3`,key:`1h7g24`}],[`circle`,{cx:`6`,cy:`18`,r:`3`,key:`fqmcym`}]]),wi=oi(`info`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 16v-4`,key:`1dtifu`}],[`path`,{d:`M12 8h.01`,key:`e9boi3`}]]),Ti=oi(`languages`,[[`path`,{d:`m5 8 6 6`,key:`1wu5hv`}],[`path`,{d:`m4 14 6-6 2-3`,key:`1k1g8d`}],[`path`,{d:`M2 5h12`,key:`or177f`}],[`path`,{d:`M7 2h1`,key:`1t2jsx`}],[`path`,{d:`m22 22-5-10-5 10`,key:`don7ne`}],[`path`,{d:`M14 18h6`,key:`1m8k6r`}]]),Ei=oi(`message-square`,[[`path`,{d:`M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z`,key:`18887p`}]]),Di=oi(`moon`,[[`path`,{d:`M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401`,key:`kfwtm`}]]),Oi=oi(`play`,[[`path`,{d:`M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z`,key:`10ikf1`}]]),U=oi(`refresh-cw`,[[`path`,{d:`M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8`,key:`v9h5vc`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}],[`path`,{d:`M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16`,key:`3uifl3`}],[`path`,{d:`M8 16H3v5`,key:`1cv678`}]]),ki=oi(`rotate-ccw-clock`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}],[`path`,{d:`M12 7v5l4 2`,key:`1fdv2h`}]]),Ai=oi(`rotate-ccw`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}]]),ji=oi(`scroll-text`,[[`path`,{d:`M15 12h-5`,key:`r7krc0`}],[`path`,{d:`M15 8h-5`,key:`1khuty`}],[`path`,{d:`M19 17V5a2 2 0 0 0-2-2H4`,key:`zz82l3`}],[`path`,{d:`M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3`,key:`1ph1d7`}]]),Mi=oi(`search`,[[`path`,{d:`m21 21-4.34-4.34`,key:`14j7rj`}],[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}]]),Ni=oi(`settings`,[[`path`,{d:`M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915`,key:`1i5ecw`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),Pi=oi(`shield-alert`,[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`M12 8v4`,key:`1got3b`}],[`path`,{d:`M12 16h.01`,key:`1drbdi`}]]),Fi=oi(`sun`,[[`circle`,{cx:`12`,cy:`12`,r:`4`,key:`4exip2`}],[`path`,{d:`M12 2v2`,key:`tus03m`}],[`path`,{d:`M12 20v2`,key:`1lh1kg`}],[`path`,{d:`m4.93 4.93 1.41 1.41`,key:`149t6j`}],[`path`,{d:`m17.66 17.66 1.41 1.41`,key:`ptbguv`}],[`path`,{d:`M2 12h2`,key:`1t8f8n`}],[`path`,{d:`M20 12h2`,key:`1q8mjw`}],[`path`,{d:`m6.34 17.66-1.41 1.41`,key:`1m8zz5`}],[`path`,{d:`m19.07 4.93-1.41 1.41`,key:`1shlcs`}]]),Ii=oi(`terminal`,[[`path`,{d:`M12 19h8`,key:`baeox8`}],[`path`,{d:`m4 17 6-6-6-6`,key:`1yngyt`}]]),Li=oi(`triangle-alert`,[[`path`,{d:`m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3`,key:`wmoenq`}],[`path`,{d:`M12 9v4`,key:`juzpu7`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),Ri=oi(`workflow`,[[`rect`,{width:`8`,height:`8`,x:`3`,y:`3`,rx:`2`,key:`by2w9f`}],[`path`,{d:`M7 11v4a2 2 0 0 0 2 2h4`,key:`xkn7yn`}],[`rect`,{width:`8`,height:`8`,x:`13`,y:`13`,rx:`2`,key:`1cgmvn`}]]),zi=oi(`wrench`,[[`path`,{d:`M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z`,key:`1ngwbx`}]]),Bi=oi(`x`,[[`path`,{d:`M18 6 6 18`,key:`1bl5f8`}],[`path`,{d:`m6 6 12 12`,key:`d8bk6v`}]]),Vi=e=>e.type===`checkbox`,Hi=e=>e.type===`file`,Ui=e=>e instanceof Date,Wi=e=>e==null,Gi=e=>typeof e==`object`,Ki=e=>!Wi(e)&&!Array.isArray(e)&&Gi(e)&&!Ui(e),qi=e=>Ki(e)&&e.target?Vi(e.target)?e.target.checked:Hi(e.target)?e.target.files:e.target.value:e,Ji=(e,t)=>t.split(`.`).some((t,n,r)=>!isNaN(Number(t))&&e.has(r.slice(0,n).join(`.`))),Yi=typeof window<`u`&&window.HTMLElement!==void 0&&typeof document<`u`;function Xi(e){if(typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e);let t=typeof FileList<`u`&&e instanceof FileList;if(Yi&&(e instanceof Blob||t))return e;let n=Array.isArray(e);if(!n&&e.constructor!==Object)return e;let r=n?[]:Object.create(Object.getPrototypeOf(e));for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&(r[t]=Xi(e[t]));return r}var Zi={BLUR:`blur`,FOCUS_OUT:`focusout`,CHANGE:`change`,SUBMIT:`submit`,TRIGGER:`trigger`,VALID:`valid`},Qi={onBlur:`onBlur`,onChange:`onChange`,onSubmit:`onSubmit`,onTouched:`onTouched`,all:`all`},$i={max:`max`,min:`min`,maxLength:`maxLength`,minLength:`minLength`,pattern:`pattern`,required:`required`,validate:`validate`},ea=`root`,ta=[`__proto__`,`constructor`,`prototype`],na=/^\w*$/,ra=e=>na.test(e),ia=e=>e===void 0,aa=/[.[\]'"]/,oa=e=>e.split(aa).filter(Boolean),W=(e,t,n)=>{if(!t||!Ki(e))return n;let r=ra(t)?[t]:oa(t);if(r.some(e=>ta.includes(e)))return n;let i=r.reduce((e,t)=>Wi(e)?void 0:e[t],e);return ia(i)||i===e?ia(e[t])?n:e[t]:i},sa=e=>typeof e==`boolean`,ca=e=>typeof e==`function`,la=(e,t,n)=>{let r=-1,i=ra(t)?[t]:oa(t),a=i.length,o=a-1;for(;++r{let i={};for(let a in e)Object.defineProperty(i,a,{get:()=>{let i=a;return t._proxyFormState[i]!==Qi.all&&(t._proxyFormState[i]=!r||Qi.all),n&&(n[i]=!0),e[i]}});return i},fa=Yi?m.useLayoutEffect:m.useEffect,pa=e=>{let t=e.constructor&&e.constructor.prototype;return Ki(t)&&t.hasOwnProperty(`isPrototypeOf`)},ma=e=>Wi(e)||!Gi(e),ha=(e,t)=>t.length===0&&!Array.isArray(e)&&!pa(e);function ga(e,t,n=new WeakMap){if(e===t)return!0;if(ma(e)||ma(t))return Object.is(e,t);if(Ui(e)&&Ui(t))return Object.is(e.getTime(),t.getTime());let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;if(ha(e,r)||ha(t,i))return Object.is(e,t);if(!r.length&&Array.isArray(e)!==Array.isArray(t))return!1;let a=n.get(e);if(a&&a.has(t))return!0;if(a)a.add(t);else{let r=new WeakSet;r.add(t),n.set(e,r)}for(let i of r){let r=e[i];if(!(i in t))return!1;if(i!==`ref`){let e=t[i];if(Ui(r)&&Ui(e)||(Ki(r)||Array.isArray(r))&&(Ki(e)||Array.isArray(e))?!ga(r,e,n):!Object.is(r,e))return!1}}return!0}function _a(){let e=m.useRef(!1),t=m.useRef(void 0);return{resyncIfNeeded:m.useCallback((n,r,i)=>{if(n&&e.current){let e=r();ga(t.current,e)||i(e)}e.current=!0},[]),snapshot:m.useCallback((e,n)=>{e&&(t.current=Xi(n()))},[])}}var va=e=>typeof e==`string`,ya=(e,t,n,r,i)=>va(e)?(r&&t.watch.add(e),W(n,e,i)):Array.isArray(e)?e.map(e=>(r&&t.watch.add(e),W(n,e))):(r&&(t.watchAll=!0),n),ba=e=>({isOnSubmit:!e||e===Qi.onSubmit,isOnBlur:e===Qi.onBlur,isOnChange:e===Qi.onChange,isOnAll:e===Qi.all,isOnTouch:e===Qi.onTouched}),xa=(e,t,n)=>{if(n)return!1;if(t.watchAll||t.watch.has(e))return!0;for(let n of t.watch)if(e.startsWith(n)&&e.charAt(n.length)===`.`)return!0;return!1},Sa=(e,t,n,r)=>{for(let i of n||Object.keys(e)){if(i===`_f`)continue;let a=n?W(e,i):e[i];if(a){let{_f:e}=a;if(e){if(e.refs&&e.refs[0]&&t(e.refs[0],i)&&!r||e.ref&&t(e.ref,e.name)&&!r)return!0;if(Sa(a,t))break}else if((Ki(a)||Array.isArray(a))&&Sa(a,t))break}}},Ca=(e,t,n)=>{let r=W(e,n),i=Array.isArray(r)?r:[];return la(i,ea,t[n]),la(e,n,i),e},wa=e=>Ki(e)&&!Object.keys(e).length,Ta=e=>{if(!Yi)return!1;let t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Ea=e=>e.type===`radio`,Da=e=>e instanceof RegExp,Oa=(e,t,n,r,i)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:i||!0}}:{},ka={value:!1,isValid:!1},Aa={value:!0,isValid:!0},ja=e=>{if(!Array.isArray(e))return ka;if(e.length>1){let t=e.filter(e=>e&&e.checked&&!e.disabled).map(e=>e.value);return{value:t,isValid:!!t.length}}let t=e[0];return!t||!t.checked||t.disabled?ka:!t.attributes||!(`value`in t.attributes)||ia(t.value)||t.value===``?Aa:{value:t.value,isValid:!0}},Ma={isValid:!1,value:null},Na=e=>Array.isArray(e)?e.reduce((e,t)=>t&&t.checked&&!t.disabled?{isValid:!0,value:t.value}:e,Ma):Ma;function Pa(e,t,n=`validate`){if(va(e)||Array.isArray(e)&&e.every(va)||sa(e)&&!e)return{type:n,message:va(e)?e:``,ref:t}}var Fa=e=>Ki(e)&&!Da(e)?e:{value:e,message:``},Ia=async(e,t,n,r,i,a)=>{let{ref:o,refs:s,required:c,maxLength:l,minLength:u,min:d,max:f,pattern:p,validate:m,name:h,valueAsNumber:g,mount:_}=e._f,v=W(n,h);if(!_||t.has(h))return{};let y=s?s[0]:o,b=e=>{if(i&&y.reportValidity){let t=sa(e)?``:e||``;s?s.forEach(e=>e.setCustomValidity(t)):y.setCustomValidity(t),y.reportValidity()}},x={},S=Ea(o),C=Vi(o),w=S||C,T=(g||Hi(o))&&ia(o.value)&&ia(v)||Ta(o)&&o.value===``||v===``||Array.isArray(v)&&!v.length,E=Oa.bind(null,h,r,x),D=(e,t,n,r=$i.maxLength,i=$i.minLength)=>{let a=e?t:n;x[h]={type:e?r:i,message:a,ref:o,...E(e?r:i,a)}};if(a?!Array.isArray(v)||!v.length:c&&(!w&&(T||Wi(v))||sa(v)&&!v||C&&!ja(s).isValid||S&&!Na(s).isValid)){let{value:e,message:t}=va(c)?{value:!!c,message:c}:Fa(c);if(e&&(x[h]={type:$i.required,message:t,ref:y,...E($i.required,t)},!r))return b(t),x}if(!T&&(!Wi(d)||!Wi(f))){let e,t,n=Fa(f),i=Fa(d);if(!Wi(v)&&!Ui(v)&&!isNaN(v)){let r=o.valueAsNumber||v&&+v;Wi(n.value)||(e=r>n.value),Wi(i.value)||(t=rnew Date(new Date().toDateString()+` `+e),s=o.type==`time`,c=o.type==`week`;va(n.value)&&v&&(e=s?a(v)>a(n.value):c?v>n.value:r>new Date(n.value)),va(i.value)&&v&&(t=s?a(v)+e.value,i=!Wi(t.value)&&v.length<+t.value;if((n||i)&&(D(n,e.message,t.message),!r))return b(x[h].message),x}if(p&&!T&&va(v)){let{value:e,message:t}=Fa(p);if(Da(e)&&!v.match(e)&&(x[h]={type:$i.pattern,message:t,ref:o,...E($i.pattern,t)},!r))return b(t),x}if(m){if(ca(m)){let e=Pa(await m(v,n),y);if(e&&(x[h]={...e,...E($i.validate,e.message)},!r))return b(e.message),x}else if(Ki(m)){let e={};for(let t in m){if(!wa(e)&&!r)break;let i=Pa(await m[t](v,n),y,t);i&&(e={...i,...E(t,i.message)},b(i.message),r&&(x[h]=e))}if(!wa(e)&&(x[h]={ref:y,...e},!r))return x}}let O=x[h];return b(!O||O.message),x},La=e=>Array.isArray(e)?e:[e],Ra=e=>Array.isArray(e)?e.filter(Boolean):[];function za(e,t){let n=t.length-1,r=0;for(;rta.includes(String(e))))return e;let r=n.length===1?e:za(e,n),i=n.length-1,a=n[i];return r&&delete r[a],i!==0&&(Ki(r)&&wa(r)||Array.isArray(r)&&Ba(r))&&Va(e,n.slice(0,-1)),e}var Ha=m.createContext(null);Ha.displayName=`HookFormContext`;var Ua=()=>{let e=[];return{get observers(){return e},next:t=>{for(let n of e)n.next&&n.next(t)},subscribe:t=>(e.push(t),{unsubscribe:()=>{e=e.filter(e=>e!==t)}}),unsubscribe:()=>{e=[]}}};function Wa(e,t){let n={};for(let r in e)if(e.hasOwnProperty(r)){let i=e[r],a=t[r];if(i&&Ki(i)&&a){let e=Wa(i,a);Ki(e)&&(n[r]=e)}else e[r]&&(n[r]=a)}return n}var Ga=(e,t)=>e!==null&&Gi(e)&&Object.prototype.hasOwnProperty.call(e,t),Ka=(e,t)=>{if(!t)return!1;let n=e;for(let r of ra(t)?[t]:oa(t)){if(!Ga(n,r))return Ga(e,t);n=n[r]}return!0},qa=e=>e.type===`select-multiple`,Ja=e=>Ea(e)||Vi(e),Ya=e=>Ta(e)&&e.isConnected;function Xa(e){return Array.isArray(e)||Ki(e)}function Za(e,t,n=``,r=[]){for(let i in e){let a=n?`${n}.${i}`:i,o=e[i];Xa(o)&&Xa(W(t,a))?Za(o,t,a,r):r.push(a)}return r}var Qa=e=>{for(let t in e)if(ca(e[t]))return!0;return!1};function $a(e){return Array.isArray(e)||Ki(e)&&!Qa(e)}function eo(e){return!!(e&&`_f`in e)}function to(e){return Array.isArray(e)?!e.some(e=>!ia(e)):!Object.keys(e).length}function no(e,t){Array.isArray(e)?e[t]=void 0:delete e[t]}function ro(e,t={},n){for(let r in e){let i=e[r],a=n&&n[r];$a(i)&&(!Array.isArray(i)||!eo(a))?(t[r]=Array.isArray(i)?[]:{},ro(i,t[r],a),to(t[r])&&no(t,r)):ia(i)||(t[r]=!0)}return t}function io(e,t,n,r){n||=ro(t,{},r);for(let i in e){let a=e[i],o=r&&r[i];$a(a)&&(!Array.isArray(a)||!eo(o))?(ia(t)||ma(n[i])?n[i]=ro(a,Array.isArray(a)?[]:{},o):io(a,Wi(t)?{}:t[i],n[i],o),to(n[i])&&no(n,i)):ga(a,t[i])?no(n,i):n[i]=!0}return n}var ao=(e,t)=>{let n=t.split(`.`),r=[],i=n[0];for(let t=1;tia(e)?e:t?e===``?NaN:e&&+e:n&&va(e)?new Date(e):r?r(e):e;function oo(e){let t=e.ref;return Hi(t)?t.files:Ea(t)?Na(e.refs).value:qa(t)?[...t.selectedOptions].map(({value:e})=>e):Vi(t)?ja(e.refs).value:G(t.value,e)}var so=(e,t,n,r)=>{let i={};for(let n of e){let e=W(t,n);e&&la(i,n,e._f)}return{criteriaMode:n,names:[...e],fields:i,shouldUseNativeValidation:r}},co=e=>ia(e)?e:Da(e)?e.source:Ki(e)?Da(e.value)?e.value.source:e.value:e,lo=`AsyncFunction`,uo=e=>{if(!e||!e.validate)return!1;if(ca(e.validate))return e.validate.constructor.name===lo;if(Ki(e.validate)){for(let t in e.validate)if(e.validate[t].constructor.name===lo)return!0}return!1},fo=e=>e.mount&&(e.required||!ia(e.required)&&e.required!==!1||!ia(e.min)||!ia(e.max)||!ia(e.maxLength)||!ia(e.minLength)||e.pattern||e.validate);function po(e,t,n){let r=W(e,n);if(r||ra(n))return{error:r,name:n};let i=n.split(`.`);for(;i.length;){let r=i.join(`.`),a=W(t,r),o=W(e,r);if(a&&!Array.isArray(a)&&n!==r)return{name:n};if(o&&o.type)return{name:r,error:o};if(o&&o.root&&o.root.type)return{name:`${r}.root`,error:o.root};i.pop()}return{name:n}}var mo=(e,t,n,r)=>{n(e);let i=Object.keys(e).filter(e=>e!==`name`);return!i.length||r&&i.length>=Object.keys(t).length||i.find(e=>t[e]===(!r||Qi.all))},ho=(e,t,n)=>!e||!t||e===t||La(e).some(e=>e&&(n?e===t||e.startsWith(t+`.`):e.startsWith(t)||t.startsWith(e))),go=(e,t,n,r,i)=>i.isOnAll?!1:!n&&i.isOnTouch?!(t||e):(n?r.isOnBlur:i.isOnBlur)?!e:!(n?r.isOnChange:i.isOnChange)||e,_o=(e,t)=>{let n=W(e,t);!Ra(n).length&&!(n!=null&&n.root)&&Va(e,t)},vo={mode:Qi.onSubmit,reValidateMode:Qi.onChange,shouldFocusError:!0},yo=`form`,bo=(e,t)=>{for(let n in e)n in t||delete e[n];Object.assign(e,t)},xo={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function So(e={}){let t={...vo,...e},n={...Xi(xo),isLoading:ca(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1},r={},i=(Ki(t.defaultValues)||Ki(t.values))&&Xi(t.defaultValues||t.values)||{},a=t.shouldUnregister?{}:Xi(i),o={action:!1,actionArrayLengths:new Map,mount:!1,watch:!1,keepIsValid:!1},s={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set,registerName:new Set},c={},l={},u=0,d=ba(t.mode),f=ba(t.reValidateMode),p={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},m={...p},h={...m},g={array:Ua(),state:Ua()},_=0,v=t.criteriaMode===Qi.all,y=(e,t)=>n=>{clearTimeout(l[e]),l[e]=setTimeout(t,n)},b=async e=>{if(!o.keepIsValid&&!t.disabled&&(m.isValid||h.isValid||e)){let e=++_,i;t.resolver?(i=wa((await A()).errors),e===_&&x()):i=await N({fields:r,onlyCheckValid:!0,eventType:Zi.VALID}),e===_&&i!==n.isValid&&g.state.next({isValid:i})}},x=(e,r)=>{!t.disabled&&(m.isValidating||m.validatingFields||h.isValidating||h.validatingFields)&&((e||s.mount).forEach(e=>{e&&(r?la(n.validatingFields,e,r):Va(n.validatingFields,e))}),g.state.next({validatingFields:n.validatingFields,isValidating:!wa(n.validatingFields)}))},S=()=>{n.dirtyFields=io(i,a,void 0,r)},C=(e,i=[],s,c,l=!0,u=!0)=>{if(c&&s&&!t.disabled){o.action=!0;let t=W(r,e);if(o.actionArrayLengths.has(e)||o.actionArrayLengths.set(e,Array.isArray(t)?t.length:0),u&&Array.isArray(t)){let n=s(t,c.argA,c.argB);l&&la(r,e,n)}let a=W(n.errors,e);if(u&&Array.isArray(a)){let t=a.root,r=s(a,c.argA,c.argB)||a;t&&(r.root=t),l&&la(n.errors,e,r),_o(n.errors,e)}let d=W(n.touchedFields,e);if((m.touchedFields||h.touchedFields)&&u&&Array.isArray(d)){let t=s(d,c.argA,c.argB);l&&la(n.touchedFields,e,t)}(m.dirtyFields||h.dirtyFields)&&S(),g.state.next({name:e,isDirty:F(e,i),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else la(a,e,i)},w=(e,t)=>{la(n.errors,e,t),n.errors={...n.errors},g.state.next({errors:n.errors})},T=e=>{n.errors=e,g.state.next({errors:n.errors,isValid:!1})},E=e=>{let t=ra(e)?[e]:oa(e),n=a,r=i;for(let e=0;e{if(!o.actionArrayLengths.size)return!1;let t=ra(e)?[e]:oa(e),n=a,r=``,i=-1,s=0;for(let e=0;e=n.length)return i===-1?!1:e!==i||+a{let d=W(r,t);if(d){if(E(t)||D(t))return;let r=ia(W(a,t)),f=W(a,t,ia(l)?W(i,t):l);ia(f)||u&&u.defaultChecked||c?la(a,t,c?f:oo(d._f)):re(t,f),o.mount&&!o.action&&(b(),r&&n.isDirty&&(m.isDirty||h.isDirty)&&(F()||(n.isDirty=!1,g.state.next({...n}))),e.shouldUnregister&&r&&!ia(W(a,t))&&xa(t,s)&&(o.watch=!0))}},ee=(e,o,s,c,l)=>{let u=!1,d=!1,f={name:e};if(!t.disabled||c===!0){if(!s||c){let t=ga(W(i,e),o);(m.isDirty||h.isDirty)&&(d=n.isDirty,n.isDirty=f.isDirty=!t||F(),u=d!==f.isDirty),d=!!W(n.dirtyFields,e),t===n.isDirty?t?Va(n.dirtyFields,e):la(n.dirtyFields,e,!0):bo(n.dirtyFields,io(i,a,void 0,r)),f.dirtyFields=n.dirtyFields,u||=(m.dirtyFields||h.dirtyFields)&&d!==!t}if(s){let t=W(n.touchedFields,e);t||(la(n.touchedFields,e,s),f.touchedFields=n.touchedFields,u||=(m.touchedFields||h.touchedFields)&&t!==s)}u&&l&&g.state.next(f)}return u?f:{}},k=(e,r,i,a)=>{let o=W(n.errors,e),s=(m.isValid||h.isValid)&&sa(r)&&n.isValid!==r;if(t.delayError&&i?(c[e]=y(e,()=>w(e,i)),c[e](t.delayError)):(clearTimeout(l[e]),delete c[e],i?la(n.errors,e,i):Va(n.errors,e),n.errors={...n.errors}),(i?!ga(o,i):o)||!wa(a)||s){let t={...a,...s&&sa(r)?{isValid:r}:{},errors:n.errors,name:e};g.state.next(t)}},A=async e=>(x(e,!0),await t.resolver(a,t.context,so(e||s.mount,r,t.criteriaMode,t.shouldUseNativeValidation))),j=async e=>{let{errors:t}=await A(e);if(x(e),e){for(let r of e){let e=W(t,r);e?s.array.has(r)&&Ki(e)&&!Object.keys(e).some(e=>!Number.isNaN(Number(e)))?Ca(n.errors,{[r]:e},r):la(n.errors,r,e):Va(n.errors,r)}n.errors={...n.errors}}else n.errors=t;return t},M=async({name:t,eventType:r})=>{if(e.validate){let i=await e.validate({formValues:a,formState:n,name:t,eventType:r});if(Ki(i))for(let e in i){let t=i[e];t&&pe(`${yo}.${e}`,{message:va(t.message)?t.message:``,type:t.type||$i.validate})}else va(i)||!i?pe(yo,{message:i||``,type:$i.validate}):fe(yo);return i}return!0},N=async({fields:r,onlyCheckValid:i,name:o,eventType:c,context:l={valid:!0,runRootValidation:!1}})=>{if(e.validate&&(l.runRootValidation=!0,!await M({name:o,eventType:c})&&(l.valid=!1,i)))return l.valid;for(let o in r){let u=r[o];if(u){let{_f:r,...d}=u;if(r){let o=s.array.has(r.name),c=u._f&&uo(u._f),d=m.validatingFields||m.isValidating||h.validatingFields||h.isValidating;c&&d&&x([r.name],!0);let f=await Ia(u,s.disabled,a,v,t.shouldUseNativeValidation&&!i,o);if(c&&d&&x([r.name]),f[r.name]&&(l.valid=!1,i)||(!i&&(W(f,r.name)?o?Ca(n.errors,f,r.name):la(n.errors,r.name,f[r.name]):Va(n.errors,r.name)),e.shouldUseNativeValidation&&f[r.name]))break}!wa(d)&&await N({context:l,onlyCheckValid:i,fields:d,name:o,eventType:c})}}return l.valid},P=()=>{for(let e of s.unMount){let t=W(r,e);t&&(t._f.refs?t._f.refs.every(e=>!Ya(e)):!Ya(t._f.ref))&&_e(e)}s.unMount=new Set},F=(e,t)=>(e&&t&&la(a,e,t),!ga(o.mount?a:i,i)),te=(e,t,n)=>ya(e,s,{...o.mount?a:ia(t)||va(e)?i:t},n,t),ne=e=>Ra(W(o.mount?a:i,e,t.shouldUnregister?W(i,e,[]):[])),re=(e,t,n={},i=!1,o=!1,s=!1)=>{let c=W(r,e),l=t;if(c){let n=c._f;n&&(!n.disabled&&la(a,e,G(t,n)),l=Ta(n.ref)&&Wi(t)?``:t,qa(n.ref)?[...n.ref.options].forEach(e=>e.selected=l.includes(e.value)):n.refs?Vi(n.ref)?n.refs.forEach(e=>{(!e.defaultChecked||!e.disabled)&&(e.checked=Array.isArray(l)?!!l.find(t=>t===e.value):l===e.value||!!l)}):n.refs.forEach(e=>e.checked=e.value===l):Hi(n.ref)?n.ref.value=``:(n.ref.value=l,!n.ref.type&&!o&&!s&&g.state.next({name:e,values:i?a:Xi(a)})))}(n.shouldDirty||n.shouldTouch)&&ee(e,l,n.shouldTouch,n.shouldDirty,!o),n.shouldValidate&&ce(e,{delayError:n.delayError})},ie=(e,t,n,i=!1,o=!1,c=!1)=>{s.array.has(e)&&g.array.next({name:e,values:i?a:Xi(a)});for(let a in t){if(!t.hasOwnProperty(a))return;let l=t[a],u=e+`.`+a,d=W(r,u);(s.array.has(e)||Ki(l)||d&&!d._f)&&!Ui(l)?ie(u,l,n,i,o,c):re(u,l,n,i,o,c)}},I=(e,t,i,c,l=!1)=>{let u=W(r,e),d=s.array.has(e),f=c?t:Xi(t),p=ga(W(a,e),f);if(p||la(a,e,f),d)g.array.next({name:e,values:c?a:Xi(a)}),(m.isDirty||m.dirtyFields||h.isDirty||h.dirtyFields)&&i.shouldDirty&&(S(),l||g.state.next({name:e,dirtyFields:n.dirtyFields,isDirty:F(e,f)}));else{let t=Array.isArray(f)&&!f.length||wa(f),n=!p&&!l;!u||u._f||Wi(f)||t?re(e,f,i,c,l,n):ie(e,f,i,c,l,n)}if(!p&&!l){let t=xa(e,s),r=c?a:Xi(a);if(g.state.next({...t&&n,name:o.mount||t?e:void 0,values:r}),!d)for(let t of ao(s.array,e))g.state.next({name:t,values:r})}},L=(e,t,n={})=>I(e,t,n,!1),ae=(e,t={})=>{let r=ca(e)?e(a):e;if(!ga(a,r)){a={...a,...r};for(let e of s.mount)Ka(r,e)&&I(e,W(r,e),t,!0,!0);g.state.next({...n,name:void 0,type:void 0,...u?{values:a}:{}}),t.shouldValidate&&b()}},oe=async i=>{o.mount=!0;let l=i.target,p=l.name,_=!0,y=W(r,p),S=e=>{_=Number.isNaN(e)||Ui(e)&&isNaN(e.getTime())||ga(e,W(a,p,e))};if(y){let o,C,w=l.type?oo(y._f):qi(i),T=i.type===Zi.BLUR||i.type===Zi.FOCUS_OUT,E=!fo(y._f)&&!e.validate&&!t.resolver&&!W(n.errors,p)&&!y._f.deps,D=E||go(T,W(n.touchedFields,p),n.isSubmitted,f,d),O=xa(p,s,T);if(la(a,p,w),T){if(!l||!l.readOnly){y._f.onBlur&&y._f.onBlur(i);let e=c[p];e&&e(0)}}else y._f.onChange&&y._f.onChange(i);let j=ee(p,w,T),P=!wa(j)||O;if(!T&&g.state.next({name:p,type:i.type,...u?{values:Xi(a)}:{}}),D)return(!E||!n.isValid)&&(m.isValid||h.isValid)&&(t.mode===`onBlur`?T&&b():T||b()),P&&g.state.next({name:p,...O?{}:j});if(!t.resolver&&e.validate&&await M({name:p,eventType:i.type}),!T&&O&&g.state.next({...n}),t.resolver){let{errors:e}=await A([p]);if(x([p]),S(w),!_){!wa(j)&&g.state.next(j);return}let t=po(n.errors,r,p),i=po(e,r,t.name||p);o=i.error,p=i.name,C=wa(e)}else x([p],!0),o=(await Ia(y,s.disabled,a,v,t.shouldUseNativeValidation))[p],x([p]),S(w),_&&(o?C=!1:(m.isValid||h.isValid)&&(C=await N({fields:r,onlyCheckValid:!0,name:p,eventType:i.type})));_&&(y._f.deps&&(!Array.isArray(y._f.deps)||y._f.deps.length>0)&&ce(y._f.deps),k(p,C,o,j))}},se=(e,t)=>{if(W(n.errors,t)&&e.focus)return e.focus(),1},ce=async(e,i={})=>{let a,o,u=La(e);if(t.resolver){let t=await j(ia(e)?e:u);a=wa(t),o=e?!u.some(e=>W(t,e)):a}else e?(o=(await Promise.all(u.map(async e=>{let t=W(r,e);return await N({fields:t&&t._f?{[e]:t}:t,eventType:Zi.TRIGGER})}))).every(Boolean),!(!o&&!n.isValid)&&b()):o=a=await N({fields:r,name:e,eventType:Zi.TRIGGER});if(i.delayError&&t.delayError&&va(e)){let r=W(n.errors,e);r?(Va(n.errors,e),c[e]=y(e,()=>w(e,r)),c[e](t.delayError)):(clearTimeout(l[e]),delete c[e])}return g.state.next({...!va(e)||(m.isValid||h.isValid)&&a!==n.isValid?{}:{name:e},...t.resolver||!e?{isValid:a}:{},errors:n.errors}),i.shouldFocus&&!o&&Sa(r,se,e?u:s.mount),o},le=(e,t)=>{let r={...o.mount?a:i};return t&&(r=Wa(t.dirtyFields?n.dirtyFields:n.touchedFields,r)),ia(e)?r:va(e)?W(r,e):e.map(e=>W(r,e))},ue=e=>ia(e)?{...n.errors}:va(e)?W(n.errors,e):e.map(e=>W(n.errors,e)),de=(e,t)=>{let r=t||n,i=W(r.errors,e);return{invalid:!!i,isDirty:!!W(r.dirtyFields,e),error:i,isValidating:!!W(n.validatingFields,e),isTouched:!!W(r.touchedFields,e)}},fe=e=>{let t=e?La(e):void 0;t?.forEach(e=>Va(n.errors,e)),t?t.forEach(e=>{g.state.next({name:e,errors:n.errors})}):(n.errors={},g.state.next({errors:n.errors}))},pe=(e,t,i)=>{let a=(W(r,e,{_f:{}})._f||{}).ref,{ref:o,message:s,type:c,...l}=W(n.errors,e)||{};la(n.errors,e,{...l,...t,ref:a}),g.state.next({name:e,errors:n.errors,isValid:!1}),i&&i.shouldFocus&&a&&a.focus&&a.focus()},me=(e,t)=>{if(ca(e)){u++;let{unsubscribe:n}=g.state.subscribe({next:n=>`values`in n&&e(n.values||te(void 0,t),n)}),r=!1;return{unsubscribe:()=>{r||(r=!0,u--,n())}}}return te(e,t,!0)},he=e=>{let t=!!e.formState?.values;t&&u++;let{unsubscribe:r}=g.state.subscribe({next:t=>{if(ho(e.name,t.name,e.exact)&&mo(t,e.formState||m,Ee,e.reRenderRoot)){let r={...a};e.callback({values:r,...n,...t,defaultValues:i})}}});if(!t)return r;let o=!1;return()=>{o||(o=!0,u--,r())}},ge=e=>(o.mount=!0,h={...h,...e.formState},he({...e,formState:{...p,...e.formState}})),_e=(e,o={})=>{for(let c of e?La(e):s.mount)s.mount.delete(c),s.array.delete(c),o.keepValue||(Va(r,c),Va(a,c)),!o.keepError&&Va(n.errors,c),!o.keepDirty&&Va(n.dirtyFields,c),!o.keepTouched&&Va(n.touchedFields,c),!o.keepIsValidating&&Va(n.validatingFields,c),!t.shouldUnregister&&!o.keepDefaultValue&&Va(i,c);u&&g.state.next({values:Xi(a)}),g.state.next({...n,...o.keepDirty?{}:{isDirty:F()}}),!o.keepIsValid&&b()},ve=({disabled:e,name:t})=>{if(sa(e)&&o.mount||e||s.disabled.has(t)){let n=s.disabled.has(t)!==!!e;e?s.disabled.add(t):s.disabled.delete(t),n&&o.mount&&!o.action&&b()}},ye=(e,n={})=>{let a=W(r,e),c=sa(n.disabled)||sa(t.disabled),l=!s.registerName.has(e)&&a&&a._f&&!a._f.mount;return la(r,e,{...a||{},_f:{...a&&a._f?a._f:{ref:{name:e}},name:e,mount:!0,...n}}),s.mount.add(e),a&&!l?ve({disabled:sa(n.disabled)?n.disabled:t.disabled,name:e}):O(e,!0,n.value),{...c?{disabled:n.disabled||t.disabled}:{},...t.progressive?{required:!!n.required,min:co(n.min),max:co(n.max),minLength:co(n.minLength),maxLength:co(n.maxLength),pattern:co(n.pattern)}:{},name:e,onChange:oe,onBlur:oe,ref:c=>{if(c){s.registerName.add(e),ye(e,n),s.registerName.delete(e),a=W(r,e);let t=ia(c.value)&&c.querySelectorAll&&c.querySelectorAll(`input,select,textarea`)[0]||c,o=Ja(t),l=a._f.refs||[];if(o?l.find(e=>e===t):t===a._f.ref)return;let u={...a._f};o?(u.refs=[...l.filter(Ya),t,...Array.isArray(W(i,e))?[{}]:[]],u.ref={type:t.type,name:e}):(u.ref=t,delete u.refs),la(r,e,{_f:u}),O(e,!1,void 0,t)}else a=W(r,e,{}),a._f&&(a._f.mount=!1),(t.shouldUnregister||n.shouldUnregister)&&!(Ji(s.array,e)&&o.action)&&s.unMount.add(e)}}},be=()=>t.shouldFocusError&&!t.shouldUseNativeValidation&&Sa(r,se,s.mount),xe=e=>{sa(e)&&(g.state.next({disabled:e}),Sa(r,(t,n)=>{let i=W(r,n);i&&(t.disabled=i._f.disabled||e,Array.isArray(i._f.refs)&&i._f.refs.forEach(t=>{t.disabled=i._f.disabled||e}))},0,!1))},Se=(e,i)=>async o=>{let c,l;o&&(o.preventDefault&&o.preventDefault(),o.persist&&o.persist());let u=Xi(a);if(g.state.next({isSubmitting:!0}),t.resolver){let{errors:e,values:t}=await A();x(),n.errors=e,u=Xi(t)}else await N({fields:r,eventType:Zi.SUBMIT});if(s.disabled.size)for(let e of s.disabled)Va(u,e);if(Va(n.errors,ea),wa(n.errors)){g.state.next({errors:{}});try{c=await e(u,o)}catch(e){l=e}}else i&&await i({...n.errors},o),be(),setTimeout(be);if(g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:wa(n.errors)&&!l,submitCount:n.submitCount+1,errors:n.errors}),l)throw l;return c},R=(e,t={})=>{W(r,e)&&(ia(t.defaultValue)?L(e,Xi(W(i,e))):(L(e,t.defaultValue),la(i,e,Xi(t.defaultValue))),t.keepTouched||Va(n.touchedFields,e),t.keepDirty||(Va(n.dirtyFields,e),n.isDirty=t.defaultValue?F(e,Xi(W(i,e))):F()),t.keepError||(Va(n.errors,e),m.isValid&&b()),g.state.next({...n}))},Ce=(e,c={})=>{let l=e?Xi(e):i,u=Xi(l),d=wa(e),f=u,p=r;if(c.keepDefaultValues||(i=l),!c.keepValues){if(c.keepDirtyValues){let e=new Set([...s.mount,...Za(io(i,a,void 0,p),n.dirtyFields)]);for(let t of e){let e=W(n.dirtyFields,t),r=W(a,t),i=W(f,t);e&&!ia(r)?la(f,t,r):!e&&!ia(i)&&L(t,i)}}else{if(Yi&&ia(e))for(let e of s.mount){let t=W(r,e);if(t&&t._f){let e=Array.isArray(t._f.refs)?t._f.refs[0]:t._f.ref;if(Ta(e)){let t=e.closest(`form`);if(t){t.reset();break}}}}if(c.keepFieldsRef)for(let e of s.mount)L(e,W(f,e));else r={}}if(t.shouldUnregister){if(a=c.keepDefaultValues?Xi(i):{},c.keepFieldsRef)for(let e of s.mount)la(a,e,W(f,e))}else a=Xi(f);g.array.next({values:{...f}}),g.state.next({name:void 0,type:void 0,values:{...f}})}s={mount:c.keepDirtyValues?s.mount:new Set,unMount:new Set,array:new Set,registerName:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:``},o.mount=!m.isValid||!!c.keepIsValid||!!c.keepDirtyValues||!t.shouldUnregister&&!wa(f),o.watch=!!t.shouldUnregister,o.keepIsValid=!!c.keepIsValid,o.action=!1,o.actionArrayLengths.clear(),c.keepErrors||(n.errors={}),g.state.next({submitCount:c.keepSubmitCount?n.submitCount:0,isDirty:d?!1:c.keepDirty?n.isDirty:c.keepValues?F():!!(c.keepDefaultValues&&!ga(e,i)),isSubmitted:c.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:d?{}:c.keepDirtyValues?c.keepDefaultValues&&a?io(i,a,void 0,p):n.dirtyFields:c.keepDefaultValues&&e?io(i,e,void 0,p):c.keepDirty?n.dirtyFields:{},touchedFields:c.keepTouched?n.touchedFields:{},errors:c.keepErrors?n.errors:{},isSubmitSuccessful:c.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:i})},we=(e,n)=>Ce(ca(e)?e(a):e,{...t.resetOptions,...n}),Te=(e,t={})=>{let n=W(r,e),i=n&&n._f;if(i){let e=i.refs?i.refs[0]:i.ref;e.focus&&setTimeout(()=>{e.focus(),t.shouldSelect&&ca(e.select)&&e.select()})}},Ee=e=>{let{name:t,type:r,values:i,...a}=e;n={...n,...a}};g.state.subscribe({next:Ee});let De={control:{register:ye,unregister:_e,getFieldState:de,handleSubmit:Se,setError:pe,_subscribe:he,_runSchema:A,_updateIsValidating:x,_focusError:be,_getWatch:te,_getDirty:F,_setValid:b,_setFieldArray:C,_setDisabledField:ve,_setErrors:T,_getFieldArray:ne,_reset:Ce,_resetDefaultValues:()=>ca(t.defaultValues)&&t.defaultValues().then(e=>{we(e,t.resetOptions),g.state.next({isLoading:!1})}),_removeUnmounted:P,_disableForm:xe,_subjects:g,_proxyFormState:m,get _fields(){return r},get _formValues(){return a},get _state(){return o},set _state(e){o=e},get _defaultValues(){return i},get _names(){return s},set _names(e){s=e},get _formState(){return n},get _options(){return t},set _options(e){t={...t,...e},d=ba(t.mode),f=ba(t.reValidateMode)}},subscribe:ge,trigger:ce,register:ye,handleSubmit:Se,watch:me,setValue:L,setValues:ae,getValues:le,getErrors:ue,reset:we,resetField:R,resetDefaultValues:(e,t={})=>{if(i=Xi(e),!t.keepDirty){let e=io(i,a,void 0,r);n.dirtyFields=e,n.isDirty=!wa(e)}t.keepIsValid||b(),g.state.next({...n,defaultValues:i})},clearErrors:fe,unregister:_e,setError:pe,setFocus:Te,getFieldState:de};return{...De,formControl:De}}function Co(e={}){let t=m.useRef(void 0),n=m.useRef(void 0),r=m.useRef(e.formControl),[i,a]=m.useState(()=>({...Xi(xo),isLoading:ca(e.defaultValues),errors:e.errors||{},disabled:e.disabled||!1,defaultValues:ca(e.defaultValues)?void 0:e.defaultValues}));if(!t.current||e.formControl&&r.current!==e.formControl){if(r.current=e.formControl,e.formControl)t.current={...e.formControl,formState:i},e.defaultValues&&!ca(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{let{formControl:n,...r}=So(e);t.current={...r,formState:i}}}let o=t.current.control;o._options=e;let{resyncIfNeeded:s,snapshot:c}=_a();return fa(()=>{let e=()=>({...o._formState,defaultValues:o._defaultValues});s(!0,e,a);let t=o._subscribe({formState:o._proxyFormState,callback:()=>a({...o._formState,defaultValues:o._defaultValues}),reRenderRoot:!0});return a(e=>({...e,isReady:!0})),o._formState.isReady=!0,()=>{t(),c(!0,e)}},[o,s,c]),m.useEffect(()=>o._disableForm(e.disabled),[o,e.disabled]),m.useEffect(()=>{e.mode&&(o._options.mode=e.mode),e.reValidateMode&&(o._options.reValidateMode=e.reValidateMode)},[o,e.mode,e.reValidateMode]),m.useEffect(()=>{e.errors&&(o._setErrors(e.errors),o._focusError())},[o,e.errors]),m.useEffect(()=>{e.shouldUnregister&&o._subjects.state.next({values:o._getWatch()})},[o,e.shouldUnregister]),m.useEffect(()=>{if(o._proxyFormState.isDirty){let e=o._getDirty();e!==i.isDirty&&o._subjects.state.next({isDirty:e})}},[o,i.isDirty]),m.useEffect(()=>{e.values&&!ga(e.values,n.current)?(o._reset(e.values,{keepFieldsRef:!0,...o._options.resetOptions}),o._options.resetOptions?.keepIsValid||o._setValid(),n.current=e.values,a(e=>({...e}))):o._resetDefaultValues()},[o,e.values]),m.useEffect(()=>{o._state.mount||(o._setValid(),o._state.mount=!0),o._state.watch&&(o._state.watch=!1,o._subjects.state.next({...o._formState})),o._removeUnmounted()}),t.current.formState=m.useMemo(()=>da(i,o),[o,i]),t.current}var wo=(e,t,n)=>{if(e&&`reportValidity`in e){let r=W(n,t);e.setCustomValidity(r&&r.message||``),e.reportValidity()}},To=(e,t)=>{for(let n in t.fields){let r=t.fields[n];r&&r.ref&&`reportValidity`in r.ref?wo(r.ref,n,e):r&&r.refs&&r.refs.forEach(t=>wo(t,n,e))}},Eo=(e,t)=>{t.shouldUseNativeValidation&&To(e,t);let n={};for(let r in e){let i=W(t.fields,r),a=Object.assign(e[r]||{},{ref:i&&i.refs?i.refs[0]:i&&i.ref});if(Do(t.names||Object.keys(e),r)){let e=Object.assign({},W(n,r));la(e,`root`,a),la(n,r,e)}else la(n,r,a)}return n},Do=(e,t)=>{let n=Oo(t).replace(/[.*+?^${}()|\\]/g,`\\$&`);return e.some(e=>Oo(e).match(`^${n}\\.\\d+`))};function Oo(e){return e.replace(/\[(\d+)]/g,`.$1`).replace(/[[\]]/g,``)}function ko(){return ko=Object.assign?Object.assign.bind():function(e){for(var t=1;t0){var s=r.errors.reduce(function(e,t){return t.lengthn?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var Fo=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},Io=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Po=globalThis).__zod_globalConfig??(Po.__zod_globalConfig={});var Lo=globalThis.__zod_globalConfig;function Ro(e){return e&&Object.assign(Lo,e),Lo}function zo(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function Bo(e,t){return typeof t==`bigint`?t.toString():t}function Vo(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Ho(e){return e==null}function Uo(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Wo(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r){};function Qo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var $o=Vo(()=>{if(Lo.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function es(e){if(Qo(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return Qo(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function ts(e){return es(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var ns=new Set([`string`,`number`,`symbol`]);function rs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function is(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function q(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function as(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}var os={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function ss(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return is(e,Jo(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return qo(this,`shape`,e),e},checks:[]}))}function cs(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return is(e,Jo(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return qo(this,`shape`,r),r},checks:[]}))}function ls(e,t){if(!es(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return is(e,Jo(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return qo(this,`shape`,n),n}}))}function us(e,t){if(!es(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return is(e,Jo(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return qo(this,`shape`,n),n}}))}function ds(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return is(e,Jo(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return qo(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function fs(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return is(t,Jo(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return qo(this,`shape`,i),i},checks:[]}))}function ps(e,t,n){return is(t,Jo(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return qo(this,`shape`,i),i}}))}function ms(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function _s(e){return typeof e==`string`?e:e?.message}function vs(e,t,n){let r=e.message?e.message:_s(e.inst?._zod.def?.error?.(e))??_s(t?.error?.(e))??_s(n.customError?.(e))??_s(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function ys(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function bs(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}var xs=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Bo,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ss=K(`$ZodError`,xs),Cs=K(`$ZodError`,xs,{Parent:Error});function ws(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Ts(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new Fo;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>vs(e,a,Ro())));throw Zo(t,i?.callee),t}return o.value},Ds=e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>vs(e,a,Ro())));throw Zo(t,i?.callee),t}return o.value},Os=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Fo;return a.issues.length?{success:!1,error:new(e??Ss)(a.issues.map(e=>vs(e,i,Ro())))}:{success:!0,data:a.value}},ks=Os(Cs),As=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>vs(e,i,Ro())))}:{success:!0,data:a.value}},js=As(Cs),Ms=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Es(e)(t,n,i)},Ns=e=>(t,n,r)=>Es(e)(t,n,r),Ps=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ds(e)(t,n,i)},Fs=e=>async(t,n,r)=>Ds(e)(t,n,r),Is=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Os(e)(t,n,i)},Ls=e=>(t,n,r)=>Os(e)(t,n,r),Rs=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return As(e)(t,n,i)},zs=e=>async(t,n,r)=>As(e)(t,n,r),Bs=/^[cC][0-9a-z]{6,}$/,Vs=/^[0-9a-z]+$/,Hs=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Us=/^[0-9a-vA-V]{20}$/,Ws=/^[A-Za-z0-9]{27}$/,Gs=/^[a-zA-Z0-9_-]{21}$/,Ks=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,qs=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Js=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Ys=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Xs=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;function Zs(){return new RegExp(Xs,`u`)}var Qs=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,$s=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,ec=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,tc=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,nc=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,rc=/^[A-Za-z0-9_-]*$/,ic=/^https?$/,ac=/^\+[1-9]\d{6,14}$/,oc=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,sc=RegExp(`^${oc}$`);function cc(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function lc(e){return RegExp(`^${cc(e)}$`)}function uc(e){let t=cc({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${oc}T(?:${r})$`)}var dc=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},fc=/^-?\d+$/,pc=/^-?\d+(?:\.\d+)?$/,mc=/^(?:true|false)$/i,hc=/^[^A-Z]*$/,gc=/^[^a-z]*$/,_c=K(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),vc={number:`number`,bigint:`bigint`,object:`date`},yc=K(`$ZodCheckLessThan`,(e,t)=>{_c.init(e,t);let n=vc[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value{(t.inclusive?r.value<=t.value:r.value{_c.init(e,t);let n=vc[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),xc=K(`$ZodCheckMultipleOf`,(e,t)=>{_c.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):Wo(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Sc=K(`$ZodCheckNumberFormat`,(e,t)=>{_c.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=os[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=fc)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}sa&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Cc=K(`$ZodCheckMaxLength`,(e,t)=>{var n;_c.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Ho(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum{let r=n.value;if(r.length<=t.maximum)return;let i=ys(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),wc=K(`$ZodCheckMinLength`,(e,t)=>{var n;_c.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Ho(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=ys(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Tc=K(`$ZodCheckLengthEquals`,(e,t)=>{var n;_c.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Ho(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=ys(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Ec=K(`$ZodCheckStringFormat`,(e,t)=>{var n,r;_c.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Dc=K(`$ZodCheckRegex`,(e,t)=>{Ec.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Oc=K(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=hc,Ec.init(e,t)}),kc=K(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=gc,Ec.init(e,t)}),Ac=K(`$ZodCheckIncludes`,(e,t)=>{_c.init(e,t);let n=rs(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),jc=K(`$ZodCheckStartsWith`,(e,t)=>{_c.init(e,t);let n=RegExp(`^${rs(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Mc=K(`$ZodCheckEndsWith`,(e,t)=>{_c.init(e,t);let n=RegExp(`.*${rs(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Nc=K(`$ZodCheckOverwrite`,(e,t)=>{_c.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),Pc=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(` -`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(` -`))}},Fc={major:4,minor:4,patch:3},Ic=K(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Fc;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=ms(e),i;for(let a of t){if(a._zod.def.when){if(hs(e)||!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new Fo;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=ms(e,t))});else{if(e.issues.length===t)continue;r||=ms(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(ms(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new Fo;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new Fo;return o.then(e=>t(e,r,a))}return t(o,r,a)}}Ko(e,`~standard`,()=>({validate:t=>{try{let n=ks(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return js(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),Lc=K(`$ZodString`,(e,t)=>{Ic.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??dc(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),Rc=K(`$ZodStringFormat`,(e,t)=>{Ec.init(e,t),Lc.init(e,t)}),zc=K(`$ZodGUID`,(e,t)=>{t.pattern??=qs,Rc.init(e,t)}),Bc=K(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=Js(e)}else t.pattern??=Js();Rc.init(e,t)}),Vc=K(`$ZodEmail`,(e,t)=>{t.pattern??=Ys,Rc.init(e,t)}),Hc=K(`$ZodURL`,(e,t)=>{Rc.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===ic.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}let i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),n.value=t.normalize?i.href:r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Uc=K(`$ZodEmoji`,(e,t)=>{t.pattern??=Zs(),Rc.init(e,t)}),Wc=K(`$ZodNanoID`,(e,t)=>{t.pattern??=Gs,Rc.init(e,t)}),Gc=K(`$ZodCUID`,(e,t)=>{t.pattern??=Bs,Rc.init(e,t)}),Kc=K(`$ZodCUID2`,(e,t)=>{t.pattern??=Vs,Rc.init(e,t)}),qc=K(`$ZodULID`,(e,t)=>{t.pattern??=Hs,Rc.init(e,t)}),Jc=K(`$ZodXID`,(e,t)=>{t.pattern??=Us,Rc.init(e,t)}),Yc=K(`$ZodKSUID`,(e,t)=>{t.pattern??=Ws,Rc.init(e,t)}),Xc=K(`$ZodISODateTime`,(e,t)=>{t.pattern??=uc(t),Rc.init(e,t)}),Zc=K(`$ZodISODate`,(e,t)=>{t.pattern??=sc,Rc.init(e,t)}),Qc=K(`$ZodISOTime`,(e,t)=>{t.pattern??=lc(t),Rc.init(e,t)}),$c=K(`$ZodISODuration`,(e,t)=>{t.pattern??=Ks,Rc.init(e,t)}),el=K(`$ZodIPv4`,(e,t)=>{t.pattern??=Qs,Rc.init(e,t),e._zod.bag.format=`ipv4`}),tl=K(`$ZodIPv6`,(e,t)=>{t.pattern??=$s,Rc.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),nl=K(`$ZodCIDRv4`,(e,t)=>{t.pattern??=ec,Rc.init(e,t)}),rl=K(`$ZodCIDRv6`,(e,t)=>{t.pattern??=tc,Rc.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function il(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var al=K(`$ZodBase64`,(e,t)=>{t.pattern??=nc,Rc.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{il(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function ol(e){if(!rc.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return il(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var sl=K(`$ZodBase64URL`,(e,t)=>{t.pattern??=rc,Rc.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{ol(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),cl=K(`$ZodE164`,(e,t)=>{t.pattern??=ac,Rc.init(e,t)});function ll(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var ul=K(`$ZodJWT`,(e,t)=>{Rc.init(e,t),e._zod.check=n=>{ll(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),dl=K(`$ZodNumber`,(e,t)=>{Ic.init(e,t),e._zod.pattern=e._zod.bag.pattern??pc,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),fl=K(`$ZodNumberFormat`,(e,t)=>{Sc.init(e,t),dl.init(e,t)}),pl=K(`$ZodBoolean`,(e,t)=>{Ic.init(e,t),e._zod.pattern=mc,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),ml=K(`$ZodUnknown`,(e,t)=>{Ic.init(e,t),e._zod.parse=e=>e}),hl=K(`$ZodNever`,(e,t)=>{Ic.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function gl(e,t,n){e.issues.length&&t.issues.push(...gs(n,e.issues)),t.value[n]=e.value}var _l=K(`$ZodArray`,(e,t)=>{Ic.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;egl(t,n,e))):gl(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function vl(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...gs(n,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function yl(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=as(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function bl(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>vl(e,n,i,t,u,d))):vl(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}var xl=K(`$ZodObject`,(e,t)=>{if(Ic.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}let n=Vo(()=>yl(t));Ko(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=Qo,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>vl(n,t,e,s,r,i))):vl(a,t,e,s,r,i)}return i?bl(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),Sl=K(`$ZodObjectJIT`,(e,t)=>{xl.init(e,t);let n=e._zod.parse,r=Vo(()=>yl(t)),i=e=>{let t=new Pc([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=Yo(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=Yo(r),s=e[r],c=s?._zod?.optin===`optional`,l=s?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),c&&l?t.write(` - if (${n}.issues.length) { - if (${o} in input) { - payload.issues = payload.issues.concat(${n}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${o}, ...iss.path] : [${o}] - }))); - } - } - - if (${n}.value === undefined) { - if (${o} in input) { - newResult[${o}] = undefined; - } - } else { - newResult[${o}] = ${n}.value; - } - - `):c?t.write(` - if (${n}.issues.length) { - payload.issues = payload.issues.concat(${n}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${o}, ...iss.path] : [${o}] - }))); - } - - if (${n}.value === undefined) { - if (${o} in input) { - newResult[${o}] = undefined; - } - } else { - newResult[${o}] = ${n}.value; - } - - `):t.write(` - const ${n}_present = ${o} in input; - if (${n}.issues.length) { - payload.issues = payload.issues.concat(${n}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${o}, ...iss.path] : [${o}] - }))); - } - if (!${n}_present && !${n}.issues.length) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: undefined, - path: [${o}] - }); - } - - if (${n}_present) { - if (${n}.value === undefined) { - newResult[${o}] = undefined; - } else { - newResult[${o}] = ${n}.value; - } - } - - `)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=Qo,s=!Lo.jitless,c=s&&$o.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?bl([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function Cl(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!ms(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>vs(e,r,Ro())))}),t)}var wl=K(`$ZodUnion`,(e,t)=>{Ic.init(e,t),Ko(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),Ko(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),Ko(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),Ko(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>Uo(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Cl(t,r,e,i)):Cl(o,r,e,i)}}),Tl=K(`$ZodIntersection`,(e,t)=>{Ic.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>Dl(e,t,n)):Dl(e,i,a)}});function El(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(es(e)&&es(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=El(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;re.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),ms(e))return e;let o=El(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var Ol=K(`$ZodEnum`,(e,t)=>{Ic.init(e,t);let n=zo(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>ns.has(typeof e)).map(e=>typeof e==`string`?rs(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),kl=K(`$ZodLiteral`,(e,t)=>{if(Ic.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?rs(e):e?rs(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),Al=K(`$ZodTransform`,(e,t)=>{Ic.init(e,t),e._zod.optin=`optional`,e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Io(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n.fallback=!0,n));if(i instanceof Promise)throw new Fo;return n.value=i,n.fallback=!0,n}});function jl(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var Ml=K(`$ZodOptional`,(e,t)=>{Ic.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,Ko(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ko(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${Uo(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>jl(e,r)):jl(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),Nl=K(`$ZodExactOptional`,(e,t)=>{Ml.init(e,t),Ko(e._zod,`values`,()=>t.innerType._zod.values),Ko(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Pl=K(`$ZodNullable`,(e,t)=>{Ic.init(e,t),Ko(e._zod,`optin`,()=>t.innerType._zod.optin),Ko(e._zod,`optout`,()=>t.innerType._zod.optout),Ko(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${Uo(e.source)}|null)$`):void 0}),Ko(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Fl=K(`$ZodDefault`,(e,t)=>{Ic.init(e,t),e._zod.optin=`optional`,Ko(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Il(e,t)):Il(r,t)}});function Il(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Ll=K(`$ZodPrefault`,(e,t)=>{Ic.init(e,t),e._zod.optin=`optional`,Ko(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Rl=K(`$ZodNonOptional`,(e,t)=>{Ic.init(e,t),Ko(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>zl(t,e)):zl(i,e)}});function zl(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}var Bl=K(`$ZodCatch`,(e,t)=>{Ic.init(e,t),e._zod.optin=`optional`,Ko(e._zod,`optout`,()=>t.innerType._zod.optout),Ko(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>vs(e,n,Ro()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>vs(e,n,Ro()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),Vl=K(`$ZodPipe`,(e,t)=>{Ic.init(e,t),Ko(e._zod,`values`,()=>t.in._zod.values),Ko(e._zod,`optin`,()=>t.in._zod.optin),Ko(e._zod,`optout`,()=>t.out._zod.optout),Ko(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Hl(e,t.in,n)):Hl(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Hl(e,t.out,n)):Hl(r,t.out,n)}});function Hl(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var Ul=K(`$ZodReadonly`,(e,t)=>{Ic.init(e,t),Ko(e._zod,`propValues`,()=>t.innerType._zod.propValues),Ko(e._zod,`values`,()=>t.innerType._zod.values),Ko(e._zod,`optin`,()=>t.innerType?._zod?.optin),Ko(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Wl):Wl(r)}});function Wl(e){return e.value=Object.freeze(e.value),e}var Gl=K(`$ZodCustom`,(e,t)=>{_c.init(e,t),Ic.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Kl(t,n,r,e));Kl(i,n,r,e)}});function Kl(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(bs(e))}}var ql,Jl=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Yl(){return new Jl}(ql=globalThis).__zod_globalRegistry??(ql.__zod_globalRegistry=Yl());var Xl=globalThis.__zod_globalRegistry;function Zl(e,t){return new e({type:`string`,...q(t)})}function Ql(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...q(t)})}function $l(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...q(t)})}function eu(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...q(t)})}function tu(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...q(t)})}function nu(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...q(t)})}function ru(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...q(t)})}function iu(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...q(t)})}function au(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...q(t)})}function ou(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...q(t)})}function su(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...q(t)})}function cu(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...q(t)})}function lu(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...q(t)})}function uu(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...q(t)})}function du(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...q(t)})}function fu(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...q(t)})}function pu(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...q(t)})}function mu(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...q(t)})}function hu(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...q(t)})}function gu(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...q(t)})}function _u(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...q(t)})}function vu(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...q(t)})}function yu(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...q(t)})}function bu(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...q(t)})}function xu(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...q(t)})}function Su(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...q(t)})}function Cu(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...q(t)})}function wu(e,t){return new e({type:`number`,checks:[],...q(t)})}function Tu(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...q(t)})}function Eu(e,t){return new e({type:`boolean`,...q(t)})}function Du(e){return new e({type:`unknown`})}function Ou(e,t){return new e({type:`never`,...q(t)})}function ku(e,t){return new yc({check:`less_than`,...q(t),value:e,inclusive:!1})}function Au(e,t){return new yc({check:`less_than`,...q(t),value:e,inclusive:!0})}function ju(e,t){return new bc({check:`greater_than`,...q(t),value:e,inclusive:!1})}function Mu(e,t){return new bc({check:`greater_than`,...q(t),value:e,inclusive:!0})}function Nu(e,t){return new xc({check:`multiple_of`,...q(t),value:e})}function Pu(e,t){return new Cc({check:`max_length`,...q(t),maximum:e})}function Fu(e,t){return new wc({check:`min_length`,...q(t),minimum:e})}function Iu(e,t){return new Tc({check:`length_equals`,...q(t),length:e})}function Lu(e,t){return new Dc({check:`string_format`,format:`regex`,...q(t),pattern:e})}function Ru(e){return new Oc({check:`string_format`,format:`lowercase`,...q(e)})}function zu(e){return new kc({check:`string_format`,format:`uppercase`,...q(e)})}function Bu(e,t){return new Ac({check:`string_format`,format:`includes`,...q(t),includes:e})}function Vu(e,t){return new jc({check:`string_format`,format:`starts_with`,...q(t),prefix:e})}function Hu(e,t){return new Mc({check:`string_format`,format:`ends_with`,...q(t),suffix:e})}function Uu(e){return new Nc({check:`overwrite`,tx:e})}function Wu(e){return Uu(t=>t.normalize(e))}function Gu(){return Uu(e=>e.trim())}function Ku(){return Uu(e=>e.toLowerCase())}function qu(){return Uu(e=>e.toUpperCase())}function Ju(){return Uu(e=>Xo(e))}function Yu(e,t,n){return new e({type:`array`,element:t,...q(n)})}function Xu(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...q(n)})}function Zu(e,t){let n=Qu(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(bs(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(bs(r))}},e(t.value,t)),t);return n}function Qu(e,t){let n=new _c({check:`custom`,...q(t)});return n._zod.check=e,n}function $u(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Xl,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function ed(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,ed(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&rd(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function td(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/ - -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function nd(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:ad(t,`input`,e.processors),output:ad(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function rd(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return rd(r.element,n);if(r.type===`set`)return rd(r.valueType,n);if(r.type===`lazy`)return rd(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return rd(r.innerType,n);if(r.type===`intersection`)return rd(r.left,n)||rd(r.right,n);if(r.type===`record`||r.type===`map`)return rd(r.keyType,n)||rd(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:rd(r.in,n)||rd(r.out,n);if(r.type===`object`){for(let e in r.shape)if(rd(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(rd(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(rd(e,n))return!0;return!!(r.rest&&rd(r.rest,n))}return!1}var id=(e,t={})=>n=>{let r=$u({...n,processors:t});return ed(e,r),td(r,e),nd(r,e)},ad=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=$u({...i??{},target:a,io:t,processors:n});return ed(e,o),td(o,e),nd(o,e)},od={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},sd=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=od[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},cd=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},ld=(e,t,n,r)=>{n.type=`boolean`},ud=(e,t,n,r)=>{n.not={}},dd=(e,t,n,r)=>{let i=e._zod.def,a=zo(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},fd=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},pd=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},md=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},hd=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=ed(a.element,t,{...r,path:[...r.path,`items`]})},gd=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=ed(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=ed(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},_d=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>ed(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},vd=(e,t,n,r)=>{let i=e._zod.def,a=ed(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=ed(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},yd=(e,t,n,r)=>{let i=e._zod.def,a=ed(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},bd=(e,t,n,r)=>{let i=e._zod.def;ed(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},xd=(e,t,n,r)=>{let i=e._zod.def;ed(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Sd=(e,t,n,r)=>{let i=e._zod.def;ed(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},Cd=(e,t,n,r)=>{let i=e._zod.def;ed(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},wd=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;ed(o,t,r);let s=t.seen.get(e);s.ref=o},Td=(e,t,n,r)=>{let i=e._zod.def;ed(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Ed=(e,t,n,r)=>{let i=e._zod.def;ed(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Dd=K(`ZodISODateTime`,(e,t)=>{Xc.init(e,t),ef.init(e,t)});function Od(e){return bu(Dd,e)}var kd=K(`ZodISODate`,(e,t)=>{Zc.init(e,t),ef.init(e,t)});function Ad(e){return xu(kd,e)}var jd=K(`ZodISOTime`,(e,t)=>{Qc.init(e,t),ef.init(e,t)});function Md(e){return Su(jd,e)}var Nd=K(`ZodISODuration`,(e,t)=>{$c.init(e,t),ef.init(e,t)});function Pd(e){return Cu(Nd,e)}var Fd=K(`ZodError`,(e,t)=>{Ss.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>Ts(e,t)},flatten:{value:t=>ws(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Bo,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Bo,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),Id=Es(Fd),Ld=Ds(Fd),Rd=Os(Fd),zd=As(Fd),Bd=Ms(Fd),Vd=Ns(Fd),Hd=Ps(Fd),Ud=Fs(Fd),Wd=Is(Fd),Gd=Ls(Fd),Kd=Rs(Fd),qd=zs(Fd),Jd=new WeakMap;function Yd(e,t,n){let r=Object.getPrototypeOf(e),i=Jd.get(r);if(i||(i=new Set,Jd.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var Xd=K(`ZodType`,(e,t)=>(Ic.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:ad(e,`input`),output:ad(e,`output`)}}),e.toJSONSchema=id(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>Id(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Rd(e,t,n),e.parseAsync=async(t,n)=>Ld(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>zd(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Bd(e,t,n),e.decode=(t,n)=>Vd(e,t,n),e.encodeAsync=async(t,n)=>Hd(e,t,n),e.decodeAsync=async(t,n)=>Ud(e,t,n),e.safeEncode=(t,n)=>Wd(e,t,n),e.safeDecode=(t,n)=>Gd(e,t,n),e.safeEncodeAsync=async(t,n)=>Kd(e,t,n),e.safeDecodeAsync=async(t,n)=>qd(e,t,n),Yd(e,`ZodType`,{check(...e){let t=this.def;return this.clone(Jo(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return is(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(up(e,t))},superRefine(e,t){return this.check(dp(e,t))},overwrite(e){return this.check(Uu(e))},optional(){return Kf(this)},exactOptional(){return Jf(this)},nullable(){return Xf(this)},nullish(){return Kf(Xf(this))},nonoptional(e){return np(this,e)},array(){return Mf(this)},or(e){return If([this,e])},and(e){return Rf(this,e)},transform(e){return op(this,Wf(e))},default(e){return Qf(this,e)},prefault(e){return ep(this,e)},catch(e){return ip(this,e)},pipe(e){return op(this,e)},readonly(){return cp(this)},describe(e){let t=this.clone();return Xl.add(t,{description:e}),t},meta(...e){if(e.length===0)return Xl.get(this);let t=this.clone();return Xl.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return Xl.get(e)?.description},configurable:!0}),e)),Zd=K(`_ZodString`,(e,t)=>{Lc.init(e,t),Xd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sd(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Yd(e,`_ZodString`,{regex(...e){return this.check(Lu(...e))},includes(...e){return this.check(Bu(...e))},startsWith(...e){return this.check(Vu(...e))},endsWith(...e){return this.check(Hu(...e))},min(...e){return this.check(Fu(...e))},max(...e){return this.check(Pu(...e))},length(...e){return this.check(Iu(...e))},nonempty(...e){return this.check(Fu(1,...e))},lowercase(e){return this.check(Ru(e))},uppercase(e){return this.check(zu(e))},trim(){return this.check(Gu())},normalize(...e){return this.check(Wu(...e))},toLowerCase(){return this.check(Ku())},toUpperCase(){return this.check(qu())},slugify(){return this.check(Ju())}})}),Qd=K(`ZodString`,(e,t)=>{Lc.init(e,t),Zd.init(e,t),e.email=t=>e.check(Ql(tf,t)),e.url=t=>e.check(iu(af,t)),e.jwt=t=>e.check(yu(bf,t)),e.emoji=t=>e.check(au(of,t)),e.guid=t=>e.check($l(nf,t)),e.uuid=t=>e.check(eu(rf,t)),e.uuidv4=t=>e.check(tu(rf,t)),e.uuidv6=t=>e.check(nu(rf,t)),e.uuidv7=t=>e.check(ru(rf,t)),e.nanoid=t=>e.check(ou(sf,t)),e.guid=t=>e.check($l(nf,t)),e.cuid=t=>e.check(su(cf,t)),e.cuid2=t=>e.check(cu(lf,t)),e.ulid=t=>e.check(lu(uf,t)),e.base64=t=>e.check(gu(_f,t)),e.base64url=t=>e.check(_u(vf,t)),e.xid=t=>e.check(uu(df,t)),e.ksuid=t=>e.check(du(ff,t)),e.ipv4=t=>e.check(fu(pf,t)),e.ipv6=t=>e.check(pu(mf,t)),e.cidrv4=t=>e.check(mu(hf,t)),e.cidrv6=t=>e.check(hu(gf,t)),e.e164=t=>e.check(vu(yf,t)),e.datetime=t=>e.check(Od(t)),e.date=t=>e.check(Ad(t)),e.time=t=>e.check(Md(t)),e.duration=t=>e.check(Pd(t))});function $d(e){return Zl(Qd,e)}var ef=K(`ZodStringFormat`,(e,t)=>{Rc.init(e,t),Zd.init(e,t)}),tf=K(`ZodEmail`,(e,t)=>{Vc.init(e,t),ef.init(e,t)}),nf=K(`ZodGUID`,(e,t)=>{zc.init(e,t),ef.init(e,t)}),rf=K(`ZodUUID`,(e,t)=>{Bc.init(e,t),ef.init(e,t)}),af=K(`ZodURL`,(e,t)=>{Hc.init(e,t),ef.init(e,t)}),of=K(`ZodEmoji`,(e,t)=>{Uc.init(e,t),ef.init(e,t)}),sf=K(`ZodNanoID`,(e,t)=>{Wc.init(e,t),ef.init(e,t)}),cf=K(`ZodCUID`,(e,t)=>{Gc.init(e,t),ef.init(e,t)}),lf=K(`ZodCUID2`,(e,t)=>{Kc.init(e,t),ef.init(e,t)}),uf=K(`ZodULID`,(e,t)=>{qc.init(e,t),ef.init(e,t)}),df=K(`ZodXID`,(e,t)=>{Jc.init(e,t),ef.init(e,t)}),ff=K(`ZodKSUID`,(e,t)=>{Yc.init(e,t),ef.init(e,t)}),pf=K(`ZodIPv4`,(e,t)=>{el.init(e,t),ef.init(e,t)}),mf=K(`ZodIPv6`,(e,t)=>{tl.init(e,t),ef.init(e,t)}),hf=K(`ZodCIDRv4`,(e,t)=>{nl.init(e,t),ef.init(e,t)}),gf=K(`ZodCIDRv6`,(e,t)=>{rl.init(e,t),ef.init(e,t)}),_f=K(`ZodBase64`,(e,t)=>{al.init(e,t),ef.init(e,t)}),vf=K(`ZodBase64URL`,(e,t)=>{sl.init(e,t),ef.init(e,t)}),yf=K(`ZodE164`,(e,t)=>{cl.init(e,t),ef.init(e,t)}),bf=K(`ZodJWT`,(e,t)=>{ul.init(e,t),ef.init(e,t)}),xf=K(`ZodNumber`,(e,t)=>{dl.init(e,t),Xd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>cd(e,t,n,r),Yd(e,`ZodNumber`,{gt(e,t){return this.check(ju(e,t))},gte(e,t){return this.check(Mu(e,t))},min(e,t){return this.check(Mu(e,t))},lt(e,t){return this.check(ku(e,t))},lte(e,t){return this.check(Au(e,t))},max(e,t){return this.check(Au(e,t))},int(e){return this.check(wf(e))},safe(e){return this.check(wf(e))},positive(e){return this.check(ju(0,e))},nonnegative(e){return this.check(Mu(0,e))},negative(e){return this.check(ku(0,e))},nonpositive(e){return this.check(Au(0,e))},multipleOf(e,t){return this.check(Nu(e,t))},step(e,t){return this.check(Nu(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function Sf(e){return wu(xf,e)}var Cf=K(`ZodNumberFormat`,(e,t)=>{fl.init(e,t),xf.init(e,t)});function wf(e){return Tu(Cf,e)}var Tf=K(`ZodBoolean`,(e,t)=>{pl.init(e,t),Xd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ld(e,t,n,r)});function Ef(e){return Eu(Tf,e)}var Df=K(`ZodUnknown`,(e,t)=>{ml.init(e,t),Xd.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Of(){return Du(Df)}var kf=K(`ZodNever`,(e,t)=>{hl.init(e,t),Xd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ud(e,t,n,r)});function Af(e){return Ou(kf,e)}var jf=K(`ZodArray`,(e,t)=>{_l.init(e,t),Xd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hd(e,t,n,r),e.element=t.element,Yd(e,`ZodArray`,{min(e,t){return this.check(Fu(e,t))},nonempty(e){return this.check(Fu(1,e))},max(e,t){return this.check(Pu(e,t))},length(e,t){return this.check(Iu(e,t))},unwrap(){return this.element}})});function Mf(e,t){return Yu(jf,e,t)}var Nf=K(`ZodObject`,(e,t)=>{Sl.init(e,t),Xd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gd(e,t,n,r),Ko(e,`shape`,()=>t.shape),Yd(e,`ZodObject`,{keyof(){return Bf(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:Of()})},loose(){return this.clone({...this._zod.def,catchall:Of()})},strict(){return this.clone({...this._zod.def,catchall:Af()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return ls(this,e)},safeExtend(e){return us(this,e)},merge(e){return ds(this,e)},pick(e){return ss(this,e)},omit(e){return cs(this,e)},partial(...e){return fs(Gf,this,e[0])},required(...e){return ps(tp,this,e[0])}})});function Pf(e,t){return new Nf({type:`object`,shape:e??{},...q(t)})}var Ff=K(`ZodUnion`,(e,t)=>{wl.init(e,t),Xd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_d(e,t,n,r),e.options=t.options});function If(e,t){return new Ff({type:`union`,options:e,...q(t)})}var Lf=K(`ZodIntersection`,(e,t)=>{Tl.init(e,t),Xd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vd(e,t,n,r)});function Rf(e,t){return new Lf({type:`intersection`,left:e,right:t})}var zf=K(`ZodEnum`,(e,t)=>{Ol.init(e,t),Xd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>dd(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new zf({...t,checks:[],...q(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new zf({...t,checks:[],...q(r),entries:i})}});function Bf(e,t){return new zf({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...q(t)})}var Vf=K(`ZodLiteral`,(e,t)=>{kl.init(e,t),Xd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fd(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Hf(e,t){return new Vf({type:`literal`,values:Array.isArray(e)?e:[e],...q(t)})}var Uf=K(`ZodTransform`,(e,t)=>{Al.init(e,t),Xd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>md(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Io(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(bs(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(bs(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function Wf(e){return new Uf({type:`transform`,transform:e})}var Gf=K(`ZodOptional`,(e,t)=>{Ml.init(e,t),Xd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ed(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Kf(e){return new Gf({type:`optional`,innerType:e})}var qf=K(`ZodExactOptional`,(e,t)=>{Nl.init(e,t),Xd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ed(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Jf(e){return new qf({type:`optional`,innerType:e})}var Yf=K(`ZodNullable`,(e,t)=>{Pl.init(e,t),Xd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>yd(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Xf(e){return new Yf({type:`nullable`,innerType:e})}var Zf=K(`ZodDefault`,(e,t)=>{Fl.init(e,t),Xd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xd(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Qf(e,t){return new Zf({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ts(t)}})}var $f=K(`ZodPrefault`,(e,t)=>{Ll.init(e,t),Xd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Sd(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ep(e,t){return new $f({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ts(t)}})}var tp=K(`ZodNonOptional`,(e,t)=>{Rl.init(e,t),Xd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bd(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function np(e,t){return new tp({type:`nonoptional`,innerType:e,...q(t)})}var rp=K(`ZodCatch`,(e,t)=>{Bl.init(e,t),Xd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Cd(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function ip(e,t){return new rp({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var ap=K(`ZodPipe`,(e,t)=>{Vl.init(e,t),Xd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wd(e,t,n,r),e.in=t.in,e.out=t.out});function op(e,t){return new ap({type:`pipe`,in:e,out:t})}var sp=K(`ZodReadonly`,(e,t)=>{Ul.init(e,t),Xd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Td(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function cp(e){return new sp({type:`readonly`,innerType:e})}var lp=K(`ZodCustom`,(e,t)=>{Gl.init(e,t),Xd.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pd(e,t,n,r)});function up(e,t={}){return Xu(lp,e,t)}function dp(e,t){return Zu(e,t)}var fp=Sf().int().min(1).max(1e3),pp=Pf({}).strict(),mp=Pf({provider:$d().trim().min(1).max(200).regex(/^[A-Za-z0-9._-]+$/),modelMode:Bf([`provider-default`,`keep-root-model`,`explicit`]),model:$d().trim().max(500).optional()}).strict().superRefine((e,t)=>{e.modelMode===`explicit`&&!e.model&&t.addIssue({code:`custom`,path:[`model`],message:`model-required`}),e.modelMode!==`explicit`&&e.model&&t.addIssue({code:`custom`,path:[`model`],message:`model-not-accepted`})}),hp=Pf({models:Ef(),cwd:Ef(),userEvent:Ef(),workspaceRoots:Ef()}).strict().superRefine((e,t)=>{!e.models&&!e.cwd&&!e.userEvent&&!e.workspaceRoots&&t.addIssue({code:`custom`,path:[`models`],message:`repair-target-required`})}),gp=Pf({backupId:$d().trim().min(1).max(300),restoreConfig:Ef(),restoreDatabase:Ef(),restoreSessions:Ef(),allowSqliteHomeRelocation:Ef(),relocationTargetProfileId:$d().trim().max(80).optional()}).superRefine((e,t)=>{!e.restoreConfig&&!e.restoreDatabase&&!e.restoreSessions&&t.addIssue({code:`custom`,path:[`restoreSessions`],message:`restore-required`}),e.allowSqliteHomeRelocation&&(!e.relocationTargetProfileId||e.restoreConfig)&&t.addIssue({code:`custom`,path:[`relocationTargetProfileId`],message:`relocation-invalid`})}),_p=$d().trim().min(1).max(4096).refine(e=>/^(?:[A-Za-z]:[\\/]|\\\\|\/)/.test(e),`absolute-path-required`);Pf({profileId:$d().trim().min(1).max(80).regex(/^[A-Za-z0-9._-]+$/),name:$d().trim().min(1).max(120),codexHome:_p,sqliteHome:If([_p,Hf(``)]).optional()});var vp=Object.defineProperty,yp=(e,t)=>vp(e,`name`,{value:t,configurable:!0}),bp=!!(typeof window<`u`&&window.document&&window.document.createElement);function xp(e,t,{checkForDefaultPrevented:n=!0}={}){return yp(function(r){if(e?.(r),n===!1||!r||!r.defaultPrevented)return t?.(r)},`handleEvent`)}yp(xp,`composeEventHandlers`);function Sp(e){if(!bp)throw Error(`Cannot access window outside of the DOM`);return e?.ownerDocument?.defaultView??window}yp(Sp,`getOwnerWindow`);function Cp(e){if(!bp)throw Error(`Cannot access document outside of the DOM`);return e?.ownerDocument??document}yp(Cp,`getOwnerDocument`);function wp(e,t=!1){let{activeElement:n}=Cp(e);if(!n?.nodeName)return null;if(Tp(n)&&n.contentDocument)return wp(n.contentDocument.body,t);if(t){let e=n.getAttribute(`aria-activedescendant`);if(e){let t=Cp(n).getElementById(e);if(t)return t}}return n}yp(wp,`getActiveElement`);function Tp(e){return e.tagName===`IFRAME`}yp(Tp,`isFrame`);var Ep=Object.defineProperty,Dp=(e,t)=>Ep(e,`name`,{value:t,configurable:!0});function Op(e,t){if(typeof e==`function`)return e(t);e!=null&&(e.current=t)}Dp(Op,`setRef`);function kp(...e){return t=>{let n=!1,r=e.map(e=>{let r=Op(e,t);return!n&&typeof r==`function`&&(n=!0),r});if(n)return()=>{for(let t=0;tjp(e,`name`,{value:t,configurable:!0});function Np(e,t){let n=m.createContext(t);n.displayName=e+`Context`;let r=Mp(e=>{let{children:t,...r}=e,i=m.useMemo(()=>r,Object.values(r));return(0,h.jsx)(n.Provider,{value:i,children:t})},`Provider`);r.displayName=e+`Provider`;function i(r,i={}){let{optional:a=!1}=i,o=m.useContext(n);if(o)return o;if(t!==void 0)return t;if(!a)throw Error(`\`${r}\` must be used within \`${e}\``)}return Mp(i,`useContext`),[r,i]}Mp(Np,`createContext`);function Pp(e,t=[]){let n=[];function r(t,r){let i=m.createContext(r);i.displayName=t+`Context`;let a=n.length;n=[...n,r];let o=Mp(t=>{let{scope:n,children:r,...o}=t,s=n?.[e]?.[a]||i,c=m.useMemo(()=>o,Object.values(o));return(0,h.jsx)(s.Provider,{value:c,children:r})},`Provider`);o.displayName=t+`Provider`;function s(n,o,s={}){let{optional:c=!1}=s,l=o?.[e]?.[a]||i,u=m.useContext(l);if(u)return u;if(r!==void 0)return r;if(!c)throw Error(`\`${n}\` must be used within \`${t}\``)}return Mp(s,`useContext`),[o,s]}Mp(r,`createContext`);let i=Mp(()=>{let t=n.map(e=>m.createContext(e));return Mp(function(n){let r=n?.[e]||t;return m.useMemo(()=>({[`__scope${e}`]:{...n,[e]:r}}),[n,r])},`useScope`)},`createScope`);return i.scopeName=e,[r,Fp(i,...t)]}Mp(Pp,`createContextScope`);function Fp(...e){let t=e[0];if(e.length===1)return t;let n=Mp(()=>{let n=e.map(e=>({useScope:e(),scopeName:e.scopeName}));return Mp(function(e){let r=n.reduce((t,{useScope:n,scopeName:r})=>{let i=n(e)[`__scope${r}`];return{...t,...i}},{});return m.useMemo(()=>({[`__scope${t.scopeName}`]:r}),[r])},`useComposedScopes`)},`createScope`);return n.scopeName=t.scopeName,n}Mp(Fp,`composeContextScopes`);var Ip=globalThis?.document?m.useLayoutEffect:()=>{},Lp=Object.defineProperty,Rp=(e,t)=>Lp(e,`name`,{value:t,configurable:!0}),zp=m.useId||(()=>void 0),Bp=0;function Vp(e){let[t,n]=m.useState(zp());return Ip(()=>{e||n(e=>e??String(Bp++))},[e]),e||(t?`radix-${t}`:``)}Rp(Vp,`useId`);var Hp=Object.defineProperty,Up=(e,t)=>Hp(e,`name`,{value:t,configurable:!0}),Wp=m.useEffectEvent,Gp=m.useInsertionEffect;function Kp(e){if(typeof Wp==`function`)return Wp(e);let t=m.useRef(()=>{throw Error(`Cannot call an event handler while rendering.`)});return typeof Gp==`function`?Gp(()=>{t.current=e}):Ip(()=>{t.current=e}),m.useMemo(()=>((...e)=>t.current?.(...e)),[])}Up(Kp,`useEffectEvent`);var qp=Object.defineProperty,Jp=(e,t)=>qp(e,`name`,{value:t,configurable:!0}),Yp=m.useInsertionEffect||Ip;function Xp({prop:e,defaultProp:t,onChange:n=Jp(()=>{},`onChange`),caller:r}){let[i,a,o]=Zp({defaultProp:t,onChange:n}),s=e!==void 0;return[s?e:i,m.useCallback(t=>{if(s){let n=Qp(t)?t(e):t;n!==e&&o.current?.(n)}else a(t)},[s,e,a,o])]}Jp(Xp,`useControllableState`);function Zp({defaultProp:e,onChange:t}){let[n,r]=m.useState(e),i=m.useRef(n),a=m.useRef(t);return Yp(()=>{a.current=t},[t]),m.useEffect(()=>{i.current!==n&&(a.current?.(n),i.current=n)},[n,i]),[n,r,a]}Jp(Zp,`useUncontrolledState`);function Qp(e){return typeof e==`function`}Jp(Qp,`isFunction`);var $p=Symbol(`RADIX:SYNC_STATE`);function em(e,t,n,r){let{prop:i,defaultProp:a,onChange:o,caller:s}=t,c=i!==void 0,l=Kp(o),u=[{...n,state:a}];r&&u.push(r);let[d,f]=m.useReducer((t,n)=>{if(n.type===$p)return{...t,state:n.state};let r=e(t,n);return c&&!Object.is(r.state,t.state)&&l(r.state),r},...u),p=d.state,h=m.useRef(p);m.useEffect(()=>{h.current!==p&&(h.current=p,c||l(p))},[p,h,c]);let g=m.useMemo(()=>i===void 0?d:{...d,state:i},[d,i]);return m.useEffect(()=>{c&&!Object.is(i,d.state)&&f({type:$p,state:i})},[i,d.state,c]),[g,f]}Jp(em,`useControllableStateReducer`);var tm=o((e=>{var t=p();function n(e){var t=`https://react.dev/errors/`+e;if(1{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=tm()})),rm=l(nm(),1),im=Object.defineProperty,am=(e,t)=>im(e,`name`,{value:t,configurable:!0});function om(e){let t=m.forwardRef((t,n)=>{let{children:r,...i}=t,a=null,o=!1,s=[];hm(r)&&typeof ym==`function`&&(r=ym(r._payload)),m.Children.forEach(r,e=>{if(pm(e)){o=!0;let t=e,n=`child`in t.props?t.props.child:t.props.children;hm(n)&&typeof ym==`function`&&(n=ym(n._payload)),a=um(t,n),s.push(a?.props?.children)}else s.push(e)}),a?a=m.cloneElement(a,void 0,s):!o&&m.Children.count(r)===1&&m.isValidElement(r)&&(a=r);let c=a?fm(a):void 0,l=Ap(n,c);if(!a){if(r||r===0)throw Error(o?vm(e):_m(e));return r}let u=dm(i,a.props??{});return a.type!==m.Fragment&&(u.ref=n?l:c),m.cloneElement(a,u)});return t.displayName=`${e}.Slot`,t}am(om,`createSlot`);var sm=om(`Slot`),cm=Symbol.for(`radix.slottable`);function lm(e){let t=am(e=>`child`in e?e.children(e.child):e.children,`Slottable`);return t.displayName=`${e}.Slottable`,t.__radixId=cm,t}am(lm,`createSlottable`);var um=am((e,t)=>{if(`child`in e.props){let t=e.props.child;return m.isValidElement(t)?m.cloneElement(t,void 0,e.props.children(t.props.children)):null}return m.isValidElement(t)?t:null},`getSlottableElementFromSlottable`);function dm(e,t){let n={...t};for(let r in t){let i=e[r],a=t[r];/^on[A-Z]/.test(r)?i&&a?n[r]=(...e)=>{let t=a(...e);return i(...e),t}:i&&(n[r]=i):r===`style`?n[r]={...i,...a}:r===`className`&&(n[r]=[i,a].filter(Boolean).join(` `))}return{...e,...n}}am(dm,`mergeProps`);function fm(e){let t=Object.getOwnPropertyDescriptor(e.props,`ref`)?.get,n=t&&`isReactWarning`in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,`ref`)?.get,n=t&&`isReactWarning`in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}am(fm,`getElementRef`);function pm(e){return m.isValidElement(e)&&typeof e.type==`function`&&`__radixId`in e.type&&e.type.__radixId===cm}am(pm,`isSlottable`);var mm=Symbol.for(`react.lazy`);function hm(e){return typeof e==`object`&&!!e&&`$$typeof`in e&&e.$$typeof===mm&&`_payload`in e&&gm(e._payload)}am(hm,`isLazyComponent`);function gm(e){return typeof e==`object`&&!!e&&`then`in e}am(gm,`isPromiseLike`);var _m=am(e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,`createSlotError`),vm=am(e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,`createSlottableError`),ym=m.use,bm=Object.defineProperty,xm=(e,t)=>bm(e,`name`,{value:t,configurable:!0}),Sm=[`a`,`button`,`div`,`form`,`h2`,`h3`,`img`,`input`,`label`,`li`,`nav`,`ol`,`p`,`select`,`span`,`svg`,`ul`].reduce((e,t)=>{let n=om(`Primitive.${t}`),r=m.forwardRef((e,r)=>{let{asChild:i,...a}=e,o=i?n:t;return typeof window<`u`&&(window[Symbol.for(`radix-ui`)]=!0),(0,h.jsx)(o,{...a,ref:r})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function Cm(e,t){e&&rm.flushSync(()=>e.dispatchEvent(t))}xm(Cm,`dispatchDiscreteCustomEvent`);var wm=Object.defineProperty,Tm=(e,t)=>wm(e,`name`,{value:t,configurable:!0});function Em(e){let t=m.useRef(e);return m.useEffect(()=>{t.current=e}),m.useMemo(()=>((...e)=>t.current?.(...e)),[])}Tm(Em,`useCallbackRef`);var Dm=Object.defineProperty,Om=(e,t)=>Dm(e,`name`,{value:t,configurable:!0}),km=`dismissableLayer.update`,Am=`dismissableLayer.pointerDownOutside`,jm=`dismissableLayer.focusOutside`,Mm,Nm=m.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Pm=m.forwardRef(Om(function(e,t){let{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:a,onFocusOutside:o,onInteractOutside:s,onDismiss:c,...l}=e,u=m.useContext(Nm),[d,f]=m.useState(null),p=d?.ownerDocument??globalThis?.document,[,g]=m.useState({}),_=Ap(t,f),v=Array.from(u.layers),[y]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),b=y?v.indexOf(y):-1,x=d?v.indexOf(d):-1,S=u.layersWithOutsidePointerEventsDisabled.size>0,C=x>=b,w=m.useRef(!1),T=Rm(e=>{a?.(e),s?.(e),e.defaultPrevented||c?.()},{ownerDocument:p,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:w,dismissableSurfaces:u.dismissableSurfaces,shouldHandlePointerDownOutside:m.useCallback(e=>{if(!(e instanceof Node))return!1;let t=[...u.branches].some(t=>t.contains(e));return C&&!t},[u.branches,C])}),E=zm(e=>{if(r&&w.current)return;let t=e.target;[...u.branches].some(e=>e.contains(t))||(o?.(e),s?.(e),e.defaultPrevented||c?.())},p),D=d?x===v.length-1:!1,O=Em(e=>{e.key===`Escape`&&(i?.(e),!e.defaultPrevented&&c&&(e.preventDefault(),c()))});return m.useEffect(()=>{if(D)return p.addEventListener(`keydown`,O,{capture:!0}),()=>p.removeEventListener(`keydown`,O,{capture:!0})},[p,D,O]),m.useEffect(()=>{if(d)return n&&(u.layersWithOutsidePointerEventsDisabled.size===0&&(Mm=p.body.style.pointerEvents,p.body.style.pointerEvents=`none`),u.layersWithOutsidePointerEventsDisabled.add(d)),u.layers.add(d),Bm(),()=>{n&&(u.layersWithOutsidePointerEventsDisabled.delete(d),u.layersWithOutsidePointerEventsDisabled.size===0&&(p.body.style.pointerEvents=Mm))}},[d,p,n,u]),m.useEffect(()=>()=>{d&&(u.layers.delete(d),u.layersWithOutsidePointerEventsDisabled.delete(d),Bm())},[d,u]),m.useEffect(()=>{let e=Om(()=>g({}),`handleUpdate`);return document.addEventListener(km,e),()=>document.removeEventListener(km,e)},[]),(0,h.jsx)(Sm.div,{...l,ref:_,style:{pointerEvents:S?C?`auto`:`none`:void 0,...e.style},onFocusCapture:xp(e.onFocusCapture,E.onFocusCapture),onBlurCapture:xp(e.onBlurCapture,E.onBlurCapture),onPointerDownCapture:xp(e.onPointerDownCapture,T.onPointerDownCapture)})},`DismissableLayer`)),Fm=m.forwardRef(Om(function(e,t){let n=m.useContext(Nm),r=m.useRef(null),i=Ap(t,r);return m.useEffect(()=>{let e=r.current;if(e)return n.branches.add(e),()=>{n.branches.delete(e)}},[n.branches]),(0,h.jsx)(Sm.div,{...e,ref:i})},`DismissableLayerBranch`));function Im(){let e=m.useContext(Nm),[t,n]=m.useState(null);return m.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}Om(Im,`useDismissableLayerSurface`);var Lm=Om(()=>!0,`IS_TRUE`);function Rm(e,t){let{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:a,shouldHandlePointerDownOutside:o=Lm}=t,s=Em(e),c=m.useRef(!1),l=m.useRef(!1),u=m.useRef(new Map),d=m.useRef(()=>{});return m.useEffect(()=>{function e(){l.current=!1,i.current=!1,u.current.clear()}Om(e,`resetOutsideInteraction`);function t(){return Array.from(u.current.values()).some(Boolean)}Om(t,`isOutsideInteractionIntercepted`);function f(e){if(!l.current)return;let t=e.target;t instanceof Node&&[...a].some(e=>e.contains(t))||u.current.set(e.type,!0),e.type===`click`&&window.setTimeout(()=>{l.current&&d.current()},0)}Om(f,`handleInteractionCapture`);function p(e){l.current&&u.current.set(e.type,!1)}Om(p,`handleInteractionBubble`);let m=Om(a=>{if(a.target&&!c.current){let f=function(){n.removeEventListener(`click`,d.current);let r=t();e(),r||Vm(Am,s,p,{discrete:!0})};if(Om(f,`handleAndDispatchPointerDownOutsideEvent`),!o(a.target)){n.removeEventListener(`click`,d.current),e(),c.current=!1;return}let p={originalEvent:a};l.current=!0,i.current=r&&a.button===0,u.current.clear(),!r||a.button!==0?f():(n.removeEventListener(`click`,d.current),d.current=f,n.addEventListener(`click`,d.current,{once:!0}))}else n.removeEventListener(`click`,d.current),e();c.current=!1},`handlePointerDown`),h=[`pointerup`,`mousedown`,`mouseup`,`touchstart`,`touchend`,`click`];for(let e of h)n.addEventListener(e,f,!0),n.addEventListener(e,p);let g=window.setTimeout(()=>{n.addEventListener(`pointerdown`,m)},0);return()=>{window.clearTimeout(g),n.removeEventListener(`pointerdown`,m),n.removeEventListener(`click`,d.current);for(let e of h)n.removeEventListener(e,f,!0),n.removeEventListener(e,p)}},[n,s,r,i,a,o]),{onPointerDownCapture:Om(()=>c.current=!0,`onPointerDownCapture`)}}Om(Rm,`usePointerDownOutside`);function zm(e,t=globalThis?.document){let n=Em(e),r=m.useRef(!1);return m.useEffect(()=>{let e=Om(e=>{e.target&&!r.current&&Vm(jm,n,{originalEvent:e},{discrete:!1})},`handleFocus`);return t.addEventListener(`focusin`,e),()=>t.removeEventListener(`focusin`,e)},[t,n]),{onFocusCapture:Om(()=>r.current=!0,`onFocusCapture`),onBlurCapture:Om(()=>r.current=!1,`onBlurCapture`)}}Om(zm,`useFocusOutside`);function Bm(){let e=new CustomEvent(km);document.dispatchEvent(e)}Om(Bm,`dispatchUpdate`);function Vm(e,t,n,{discrete:r}){let i=n.originalEvent.target,a=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?Cm(i,a):i.dispatchEvent(a)}Om(Vm,`handleAndDispatchCustomEvent`);var Hm=Pm,Um=Fm,Wm=Object.defineProperty,Gm=(e,t)=>Wm(e,`name`,{value:t,configurable:!0}),Km=`focusScope.autoFocusOnMount`,qm=`focusScope.autoFocusOnUnmount`,Jm={bubbles:!1,cancelable:!0},Ym=m.forwardRef(Gm(function(e,t){let{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:a,...o}=e,[s,c]=m.useState(null),l=Em(i),u=Em(a),d=m.useRef(null),f=Ap(t,c),p=m.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;m.useEffect(()=>{if(r){let e=function(e){if(p.paused||!s)return;let t=e.target;s.contains(t)?d.current=t:nh(d.current,{select:!0})},t=function(e){if(p.paused||!s)return;let t=e.relatedTarget;t!==null&&(s.contains(t)||nh(d.current,{select:!0}))},n=function(e){if(document.activeElement===document.body)for(let t of e)t.removedNodes.length>0&&nh(s)};Gm(e,`handleFocusIn`),Gm(t,`handleFocusOut`),Gm(n,`handleMutations`),document.addEventListener(`focusin`,e),document.addEventListener(`focusout`,t);let r=new MutationObserver(n);return s&&r.observe(s,{childList:!0,subtree:!0}),()=>{document.removeEventListener(`focusin`,e),document.removeEventListener(`focusout`,t),r.disconnect()}}},[r,s,p.paused]),m.useEffect(()=>{if(s){rh.add(p);let e=document.activeElement;if(!s.contains(e)){let t=new CustomEvent(Km,Jm);s.addEventListener(Km,l),s.dispatchEvent(t),t.defaultPrevented||(Xm(oh(Qm(s)),{select:!0}),document.activeElement===e&&nh(s))}return()=>{s.removeEventListener(Km,l),setTimeout(()=>{let t=new CustomEvent(qm,Jm);s.addEventListener(qm,u),s.dispatchEvent(t),t.defaultPrevented||nh(e??document.body,{select:!0}),s.removeEventListener(qm,u),rh.remove(p)},0)}}},[s,l,u,p]);let g=m.useCallback(e=>{if(!n&&!r||p.paused)return;let t=e.key===`Tab`&&!e.altKey&&!e.ctrlKey&&!e.metaKey,i=document.activeElement;if(t&&i){let t=e.currentTarget,[r,a]=Zm(t);r&&a?!e.shiftKey&&i===a?(e.preventDefault(),n&&nh(r,{select:!0})):e.shiftKey&&i===r&&(e.preventDefault(),n&&nh(a,{select:!0})):i===t&&e.preventDefault()}},[n,r,p.paused]);return(0,h.jsx)(Sm.div,{tabIndex:-1,...o,ref:f,onKeyDown:g})},`FocusScope`));function Xm(e,{select:t=!1}={}){let n=document.activeElement;for(let r of e)if(nh(r,{select:t}),document.activeElement!==n)return}Gm(Xm,`focusFirst`);function Zm(e){let t=Qm(e);return[$m(t,e),$m(t.reverse(),e)]}Gm(Zm,`getTabbableEdges`);function Qm(e){let t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:Gm(e=>{let t=e.tagName===`INPUT`&&e.type===`hidden`;return e.disabled||e.hidden||t?NodeFilter.FILTER_SKIP:e.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},`acceptNode`)});for(;n.nextNode();)t.push(n.currentNode);return t}Gm(Qm,`getTabbableCandidates`);function $m(e,t){let n=typeof t.checkVisibility==`function`&&t.checkVisibility({checkVisibilityCSS:!0});for(let r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):eh(r,{upTo:t})))return r}Gm($m,`findVisible`);function eh(e,{upTo:t}){if(getComputedStyle(e).visibility===`hidden`)return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display===`none`)return!0;e=e.parentElement}return!1}Gm(eh,`isHidden`);function th(e){return e instanceof HTMLInputElement&&`select`in e}Gm(th,`isSelectableInput`);function nh(e,{select:t=!1}={}){if(e&&e.focus){let n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&th(e)&&t&&e.select()}}Gm(nh,`focus`);var rh=ih();function ih(){let e=[];return{add(t){let n=e[0];t!==n&&n?.pause(),e=ah(e,t),e.unshift(t)},remove(t){e=ah(e,t),e[0]?.resume()}}}Gm(ih,`createFocusScopesStack`);function ah(e,t){let n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}Gm(ah,`arrayRemove`);function oh(e){return e.filter(e=>e.tagName!==`A`)}Gm(oh,`removeLinks`);var sh=Object.defineProperty,ch=m.forwardRef(((e,t)=>sh(e,`name`,{value:t,configurable:!0}))(function(e,t){let{container:n,...r}=e,[i,a]=m.useState(!1);Ip(()=>a(!0),[]);let o=n||i&&globalThis?.document?.body;return o?rm.createPortal((0,h.jsx)(Sm.div,{...r,ref:t}),o):null},`Portal`)),lh=Object.defineProperty,uh=(e,t)=>lh(e,`name`,{value:t,configurable:!0});function dh(e,t){return m.useReducer((e,n)=>t[e][n]??e,e)}uh(dh,`useStateMachine`);var fh=uh(e=>{let{present:t,children:n}=e,r=ph(t),i=typeof n==`function`?n({present:r.isPresent}):m.Children.only(n),a=hh(r.ref,_h(i));return typeof n==`function`||r.isPresent?m.cloneElement(i,{ref:a}):null},`Presence`);function ph(e){let[t,n]=m.useState(),r=m.useRef(null),i=m.useRef(e),a=m.useRef(`none`),o=m.useRef(void 0),[s,c]=dh(e?`mounted`:`unmounted`,{mounted:{UNMOUNT:`unmounted`,ANIMATION_OUT:`unmountSuspended`},unmountSuspended:{MOUNT:`mounted`,ANIMATION_END:`unmounted`},unmounted:{MOUNT:`mounted`}});return m.useEffect(()=>{s===`mounted`?(a.current=o.current??gh(r.current),o.current=void 0):a.current=`none`},[s]),Ip(()=>{let t=r.current,n=i.current;if(n!==e){let r=a.current,s=gh(t);e?(o.current=s,c(`MOUNT`)):s===`none`||t?.display===`none`?c(`UNMOUNT`):c(n&&r!==s?`ANIMATION_OUT`:`UNMOUNT`),i.current=e}},[e,c]),Ip(()=>{if(t){let e,n=t.ownerDocument.defaultView??window,o=uh(a=>{let o=gh(r.current).includes(CSS.escape(a.animationName));if(a.target===t&&o&&(c(`ANIMATION_END`),!i.current)){let r=t.style.animationFillMode;t.style.animationFillMode=`forwards`,e=n.setTimeout(()=>{t.style.animationFillMode===`forwards`&&(t.style.animationFillMode=r)})}},`handleAnimationEnd`),s=uh(e=>{e.target===t&&(a.current=gh(r.current))},`handleAnimationStart`);return t.addEventListener(`animationstart`,s),t.addEventListener(`animationcancel`,o),t.addEventListener(`animationend`,o),()=>{n.clearTimeout(e),t.removeEventListener(`animationstart`,s),t.removeEventListener(`animationcancel`,o),t.removeEventListener(`animationend`,o)}}c(`ANIMATION_END`)},[t,c]),{isPresent:[`mounted`,`unmountSuspended`].includes(s),ref:m.useCallback(e=>{if(e){let t=getComputedStyle(e);r.current=t,o.current=gh(t)}else r.current=null;n(e)},[])}}uh(ph,`usePresence`);function mh(e,t){if(typeof e==`function`)return e(t);e!=null&&(e.current=t)}uh(mh,`setRef`);function hh(...e){let t=m.useRef(e);return t.current=e,m.useCallback(e=>{let n=t.current,r=!1,i=n.map(t=>{let n=mh(t,e);return!r&&typeof n==`function`&&(r=!0),n});if(r)return()=>{for(let e=0;evh(e,`name`,{value:t,configurable:!0}),bh=0,xh=null;function Sh(e){return Ch(),e.children}yh(Sh,`FocusGuards`);function Ch(){m.useEffect(()=>{xh||={start:wh(),end:wh()};let{start:e,end:t}=xh;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement(`afterbegin`,e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement(`beforeend`,t),bh++,()=>{bh===1&&(xh?.start.remove(),xh?.end.remove(),xh=null),bh=Math.max(0,bh-1)}},[])}yh(Ch,`useFocusGuards`);function wh(){let e=document.createElement(`span`);return e.setAttribute(`data-radix-focus-guard`,``),e.tabIndex=0,e.style.outline=`none`,e.style.opacity=`0`,e.style.position=`fixed`,e.style.pointerEvents=`none`,e}yh(wh,`createFocusGuard`);var Th=function(){return Th=Object.assign||function(e){for(var t,n=1,r=arguments.length;n`u`)return Qh;var t=eg(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},ng=Zh(),rg=`data-scroll-locked`,ig=function(e,t,n,r){var i=e.left,a=e.top,o=e.right,s=e.gap;return n===void 0&&(n=`margin`),` - .${Ah} { - overflow: hidden ${r}; - padding-right: ${s}px ${r}; - } - body[${rg}] { - overflow: hidden ${r}; - overscroll-behavior: contain; - ${[t&&`position: relative ${r};`,n===`margin`&&` - padding-left: ${i}px; - padding-top: ${a}px; - padding-right: ${o}px; - margin-left:0; - margin-top:0; - margin-right: ${s}px ${r}; - `,n===`padding`&&`padding-right: ${s}px ${r};`].filter(Boolean).join(``)} - } - - .${Oh} { - right: ${s}px ${r}; - } - - .${kh} { - margin-right: ${s}px ${r}; - } - - .${Oh} .${Oh} { - right: 0 ${r}; - } - - .${kh} .${kh} { - margin-right: 0 ${r}; - } - - body[${rg}] { - ${jh}: ${s}px; - } -`},ag=function(){var e=parseInt(document.body.getAttribute(`data-scroll-locked`)||`0`,10);return isFinite(e)?e:0},og=function(){m.useEffect(function(){return document.body.setAttribute(rg,(ag()+1).toString()),function(){var e=ag()-1;e<=0?document.body.removeAttribute(rg):document.body.setAttribute(rg,e.toString())}},[])},sg=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?`margin`:r;og();var a=m.useMemo(function(){return tg(i)},[i]);return m.createElement(ng,{styles:ig(a,!t,i,n?``:`!important`)})},cg=!1;if(typeof window<`u`)try{var lg=Object.defineProperty({},"passive",{get:function(){return cg=!0,!0}});window.addEventListener(`test`,lg,lg),window.removeEventListener(`test`,lg,lg)}catch{cg=!1}var ug=cg?{passive:!1}:!1,dg=function(e){return e.tagName===`TEXTAREA`},fg=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!==`hidden`&&!(n.overflowY===n.overflowX&&!dg(e)&&n[t]===`visible`)},pg=function(e){return fg(e,`overflowY`)},mg=function(e){return fg(e,`overflowX`)},hg=function(e,t){var n=t.ownerDocument,r=t;do{if(typeof ShadowRoot<`u`&&r instanceof ShadowRoot&&(r=r.host),vg(e,r)){var i=yg(e,r);if(i[1]>i[2])return!0}r=r.parentNode}while(r&&r!==n.body);return!1},gg=function(e){return[e.scrollTop,e.scrollHeight,e.clientHeight]},_g=function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]},vg=function(e,t){return e===`v`?pg(t):mg(t)},yg=function(e,t){return e===`v`?gg(t):_g(t)},bg=function(e,t){return e===`h`&&t===`rtl`?-1:1},xg=function(e,t,n,r,i){var a=bg(e,window.getComputedStyle(t).direction),o=a*r,s=n.target,c=t.contains(s),l=!1,u=o>0,d=0,f=0;do{if(!s)break;var p=yg(e,s),m=p[0],h=p[1]-p[2]-a*m;(m||h)&&vg(e,s)&&(d+=h,f+=m);var g=s.parentNode;s=g&&g.nodeType===Node.DOCUMENT_FRAGMENT_NODE?g.host:g}while(!c&&s!==document.body||c&&(t.contains(s)||t===s));return(u&&(i&&Math.abs(d)<1||!i&&o>d)||!u&&(i&&Math.abs(f)<1||!i&&-o>f))&&(l=!0),l},Sg=function(e){return`changedTouches`in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Cg=function(e){return[e.deltaX,e.deltaY]},wg=function(e){return e&&`current`in e?e.current:e},Tg=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Eg=function(e){return` - .block-interactivity-${e} {pointer-events: none;} - .allow-interactivity-${e} {pointer-events: all;} -`},Dg=0,Og=[];function kg(e){var t=m.useRef([]),n=m.useRef([0,0]),r=m.useRef(),i=m.useState(Dg++)[0],a=m.useState(Zh)[0],o=m.useRef(e);m.useEffect(function(){o.current=e},[e]),m.useEffect(function(){if(e.inert){document.body.classList.add(`block-interactivity-${i}`);var t=Dh([e.lockRef.current],(e.shards||[]).map(wg),!0).filter(Boolean);return t.forEach(function(e){return e.classList.add(`allow-interactivity-${i}`)}),function(){document.body.classList.remove(`block-interactivity-${i}`),t.forEach(function(e){return e.classList.remove(`allow-interactivity-${i}`)})}}},[e.inert,e.lockRef.current,e.shards]);var s=m.useCallback(function(e,t){if(`touches`in e&&e.touches.length===2||e.type===`wheel`&&e.ctrlKey)return!o.current.allowPinchZoom;var i=Sg(e),a=n.current,s=`deltaX`in e?e.deltaX:a[0]-i[0],c=`deltaY`in e?e.deltaY:a[1]-i[1],l,u=e.target,d=Math.abs(s)>Math.abs(c)?`h`:`v`;if(`touches`in e&&d===`h`&&u.type===`range`)return!1;var f=window.getSelection(),p=f&&f.anchorNode;if(p&&(p===u||p.contains(u)))return!1;var m=hg(d,u);if(!m)return!0;if(m?l=d:(l=d===`v`?`h`:`v`,m=hg(d,u)),!m)return!1;if(!r.current&&`changedTouches`in e&&(s||c)&&(r.current=l),!l)return!0;var h=r.current||l;return xg(h,t,e,h===`h`?s:c,!0)},[]),c=m.useCallback(function(e){var n=e;if(!(!Og.length||Og[Og.length-1]!==a)){var r=`deltaY`in n?Cg(n):Sg(n),i=t.current.filter(function(e){return e.name===n.type&&(e.target===n.target||n.target===e.shadowParent)&&Tg(e.delta,r)})[0];if(i&&i.should){n.cancelable&&n.preventDefault();return}if(!i){var c=(o.current.shards||[]).map(wg).filter(Boolean).filter(function(e){return e.contains(n.target)});(c.length>0?s(n,c[0]):!o.current.noIsolation)&&n.cancelable&&n.preventDefault()}}},[]),l=m.useCallback(function(e,n,r,i){var a={name:e,delta:n,target:r,should:i,shadowParent:Ag(r)};t.current.push(a),setTimeout(function(){t.current=t.current.filter(function(e){return e!==a})},1)},[]),u=m.useCallback(function(e){n.current=Sg(e),r.current=void 0},[]),d=m.useCallback(function(t){l(t.type,Cg(t),t.target,s(t,e.lockRef.current))},[]),f=m.useCallback(function(t){l(t.type,Sg(t),t.target,s(t,e.lockRef.current))},[]);m.useEffect(function(){return Og.push(a),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener(`wheel`,c,ug),document.addEventListener(`touchmove`,c,ug),document.addEventListener(`touchstart`,u,ug),function(){Og=Og.filter(function(e){return e!==a}),document.removeEventListener(`wheel`,c,ug),document.removeEventListener(`touchmove`,c,ug),document.removeEventListener(`touchstart`,u,ug)}},[]);var p=e.removeScrollBar,h=e.inert;return m.createElement(m.Fragment,null,h?m.createElement(a,{styles:Eg(i)}):null,p?m.createElement(sg,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Ag(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var jg=Vh(Hh,kg),Mg=m.forwardRef(function(e,t){return m.createElement(Wh,Th({},e,{ref:t,sideCar:jg}))});Mg.classNames=Wh.classNames;var Ng=function(e){return typeof document>`u`?null:(Array.isArray(e)?e[0]:e).ownerDocument.body},Pg=new WeakMap,Fg=new WeakMap,Ig={},Lg=0,Rg=function(e){return e&&(e.host||Rg(e.parentNode))},zg=function(e,t){return t.map(function(t){if(e.contains(t))return t;var n=Rg(t);return n&&e.contains(n)?n:(console.error(`aria-hidden`,t,`in not contained inside`,e,`. Doing nothing`),null)}).filter(function(e){return!!e})},Bg=function(e,t,n,r){var i=zg(t,Array.isArray(e)?e:[e]);Ig[n]||(Ig[n]=new WeakMap);var a=Ig[n],o=[],s=new Set,c=new Set(i),l=function(e){!e||s.has(e)||(s.add(e),l(e.parentNode))};i.forEach(l);var u=function(e){!e||c.has(e)||Array.prototype.forEach.call(e.children,function(e){if(s.has(e))u(e);else try{var t=e.getAttribute(r),i=t!==null&&t!==`false`,c=(Pg.get(e)||0)+1,l=(a.get(e)||0)+1;Pg.set(e,c),a.set(e,l),o.push(e),c===1&&i&&Fg.set(e,!0),l===1&&e.setAttribute(n,`true`),i||e.setAttribute(r,`true`)}catch(t){console.error(`aria-hidden: cannot operate on `,e,t)}})};return u(t),s.clear(),Lg++,function(){o.forEach(function(e){var t=Pg.get(e)-1,i=a.get(e)-1;Pg.set(e,t),a.set(e,i),t||(Fg.has(e)||e.removeAttribute(r),Fg.delete(e)),i||e.removeAttribute(n)}),Lg--,Lg||(Pg=new WeakMap,Pg=new WeakMap,Fg=new WeakMap,Ig={})}},Vg=function(e,t,n){n===void 0&&(n=`data-aria-hidden`);var r=Array.from(Array.isArray(e)?e:[e]),i=t||Ng(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll(`[aria-live], script`))),Bg(r,i,n,`aria-hidden`)):function(){return null}},Hg=Object.defineProperty,Ug=(e,t)=>Hg(e,`name`,{value:t,configurable:!0}),Wg=`Dialog`,[Gg,Kg]=Pp(Wg),[qg,Jg]=Gg(Wg),Yg=Ug(e=>{let{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:a,modal:o=!0}=e,s=m.useRef(null),c=m.useRef(null),[l,u]=Xp({prop:r,defaultProp:i??!1,onChange:a,caller:Wg}),[d,f]=m.useState(0),[p,g]=m.useState(0);return(0,h.jsx)(qg,{scope:t,triggerRef:s,contentRef:c,contentId:Vp(),titleId:Vp(),descriptionId:Vp(),titlePresent:d>0,descriptionPresent:p>0,setTitleCount:f,setDescriptionCount:g,open:l,onOpenChange:u,onOpenToggle:m.useCallback(()=>u(e=>!e),[u]),modal:o,children:n})},`Dialog`),Xg=`DialogPortal`,[Zg,Qg]=Gg(Xg,{forceMount:void 0}),$g=Ug(e=>{let{__scopeDialog:t,forceMount:n,children:r,container:i}=e,a=Jg(Xg,t);return(0,h.jsx)(Zg,{scope:t,forceMount:n,children:m.Children.map(r,e=>(0,h.jsx)(fh,{present:n||a.open,children:(0,h.jsx)(ch,{asChild:!0,container:i,children:e})}))})},`DialogPortal`),e_=`DialogOverlay`,t_=m.forwardRef(Ug(function(e,t){let n=Qg(e_,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,a=Jg(e_,e.__scopeDialog);return a.modal?(0,h.jsx)(fh,{present:r||a.open,children:(0,h.jsx)(r_,{...i,ref:t})}):null},`DialogOverlay`)),n_=om(`DialogOverlay.RemoveScroll`),r_=m.forwardRef(Ug(function(e,t){let{__scopeDialog:n,...r}=e,i=Jg(e_,n),a=Ap(t,Im());return(0,h.jsx)(Mg,{as:n_,allowPinchZoom:!0,shards:[i.contentRef],children:(0,h.jsx)(Sm.div,{"data-state":h_(i.open),...r,ref:a,style:{pointerEvents:`auto`,...r.style}})})},`DialogOverlayImpl`)),i_=`DialogContent`,a_=m.forwardRef(Ug(function(e,t){let n=Qg(i_,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,a=Jg(i_,e.__scopeDialog);return(0,h.jsx)(fh,{present:r||a.open,children:a.modal?(0,h.jsx)(o_,{...i,ref:t}):(0,h.jsx)(s_,{...i,ref:t})})},`DialogContent`)),o_=m.forwardRef(Ug(function(e,t){let n=Jg(i_,e.__scopeDialog),r=m.useRef(null),i=Ap(t,n.contentRef,r);return m.useEffect(()=>{let e=r.current;if(e)return Vg(e)},[]),(0,h.jsx)(c_,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,onCloseAutoFocus:xp(e.onCloseAutoFocus,e=>{e.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:xp(e.onPointerDownOutside,e=>{let t=e.detail.originalEvent,n=t.button===0&&t.ctrlKey===!0;(t.button===2||n)&&e.preventDefault()}),onFocusOutside:xp(e.onFocusOutside,e=>e.preventDefault())})},`DialogContentModal`)),s_=m.forwardRef(Ug(function(e,t){let n=Jg(i_,e.__scopeDialog),r=m.useRef(!1),i=m.useRef(!1);return(0,h.jsx)(c_,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:t=>{e.onCloseAutoFocus?.(t),t.defaultPrevented||(r.current||n.triggerRef.current?.focus(),t.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:t=>{e.onInteractOutside?.(t),t.defaultPrevented||(r.current=!0,t.detail.originalEvent.type===`pointerdown`&&(i.current=!0));let a=t.target;n.triggerRef.current?.contains(a)&&t.preventDefault(),t.detail.originalEvent.type===`focusin`&&i.current&&t.preventDefault()}})},`DialogContentNonModal`)),c_=m.forwardRef(Ug(function(e,t){let{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:a,...o}=e,s=Jg(i_,n);return Ch(),(0,h.jsx)(h.Fragment,{children:(0,h.jsx)(Ym,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:a,children:(0,h.jsx)(Pm,{role:`dialog`,id:s.contentId,"aria-describedby":s.descriptionPresent?s.descriptionId:void 0,"aria-labelledby":s.titlePresent?s.titleId:void 0,"data-state":h_(s.open),...o,ref:t,deferPointerDownOutside:!0,onDismiss:()=>s.onOpenChange(!1)})})})},`DialogContentImpl`)),l_=`DialogTitle`,u_=m.forwardRef(Ug(function(e,t){let{__scopeDialog:n,...r}=e,i=Jg(l_,n),{setTitleCount:a}=i;return Ip(()=>(a(e=>e+1),()=>a(e=>e-1)),[a]),(0,h.jsx)(Sm.h2,{id:i.titleId,...r,ref:t})},`DialogTitle`)),d_=`DialogDescription`,f_=m.forwardRef(Ug(function(e,t){let{__scopeDialog:n,...r}=e,i=Jg(d_,n),{setDescriptionCount:a}=i;return Ip(()=>(a(e=>e+1),()=>a(e=>e-1)),[a]),(0,h.jsx)(Sm.p,{id:i.descriptionId,...r,ref:t})},`DialogDescription`)),p_=`DialogClose`,m_=m.forwardRef(Ug(function(e,t){let{__scopeDialog:n,...r}=e,i=Jg(p_,n);return(0,h.jsx)(Sm.button,{type:`button`,...r,ref:t,onClick:xp(e.onClick,()=>i.onOpenChange(!1))})},`DialogClose`));function h_(e){return e?`open`:`closed`}Ug(h_,`getState`);var g_=Object.defineProperty,__=(e,t)=>g_(e,`name`,{value:t,configurable:!0});function v_(e){let t=e+`CollectionProvider`,[n,r]=Pp(t),[i,a]=n(t,{collectionRef:{current:null},itemMap:new Map}),o=__(e=>{let{scope:t,children:n}=e,r=m.useRef(null),a=m.useRef(new Map).current;return(0,h.jsx)(i,{scope:t,itemMap:a,collectionRef:r,children:n})},`CollectionProvider`);o.displayName=t;let s=e+`CollectionSlot`,c=om(s),l=m.forwardRef((e,t)=>{let{scope:n,children:r}=e,i=Ap(t,a(s,n).collectionRef);return(0,h.jsx)(c,{ref:i,children:r})});l.displayName=s;let u=e+`CollectionItemSlot`,d=`data-radix-collection-item`,f=om(u),p=m.forwardRef((e,t)=>{let{scope:n,children:r,...i}=e,o=m.useRef(null),s=Ap(t,o),c=a(u,n);return m.useEffect(()=>(c.itemMap.set(o,{ref:o,...i}),()=>void c.itemMap.delete(o))),(0,h.jsx)(f,{[d]:``,ref:s,children:r})});p.displayName=u;function g(t){let n=a(e+`CollectionConsumer`,t);return m.useCallback(()=>{let e=n.collectionRef.current;if(!e)return[];let t=Array.from(e.querySelectorAll(`[${d}]`));return Array.from(n.itemMap.values()).sort((e,n)=>t.indexOf(e.ref.current)-t.indexOf(n.ref.current))},[n.collectionRef,n.itemMap])}return __(g,`useCollection`),[{Provider:o,Slot:l,ItemSlot:p},g,r]}__(v_,`createCollection`);var y_=new WeakMap,b_=class e extends Map{static{__(this,`OrderedDict`)}#e;constructor(e){super(e),this.#e=[...super.keys()],y_.set(this,!0)}set(e,t){return y_.get(this)&&(this.has(e)?this.#e[this.#e.indexOf(e)]=e:this.#e.push(e)),super.set(e,t),this}insert(e,t,n){let r=this.has(t),i=this.#e.length,a=C_(e),o=a>=0?a:i+a,s=o<0||o>=i?-1:o;if(s===this.size||r&&s===this.size-1||s===-1)return this.set(t,n),this;let c=this.size+ +!r;a<0&&o++;let l=[...this.#e],u,d=!1;for(let e=o;e=this.size&&(r=this.size-1),this.at(r)}keyFrom(e,t){let n=this.indexOf(e);if(n===-1)return;let r=n+t;return r<0&&(r=0),r>=this.size&&(r=this.size-1),this.keyAt(r)}find(e,t){let n=0;for(let r of this){if(Reflect.apply(e,t,[r,n,this]))return r;n++}}findIndex(e,t){let n=0;for(let r of this){if(Reflect.apply(e,t,[r,n,this]))return n;n++}return-1}filter(t,n){let r=[],i=0;for(let e of this)Reflect.apply(t,n,[e,i,this])&&r.push(e),i++;return new e(r)}map(t,n){let r=[],i=0;for(let e of this)r.push([e[0],Reflect.apply(t,n,[e,i,this])]),i++;return new e(r)}reduce(...e){let[t,n]=e,r=0,i=n??this.at(0);for(let n of this)i=r===0&&e.length===1?n:Reflect.apply(t,this,[i,n,r,this]),r++;return i}reduceRight(...e){let[t,n]=e,r=n??this.at(-1);for(let n=this.size-1;n>=0;n--){let i=this.at(n);r=n===this.size-1&&e.length===1?i:Reflect.apply(t,this,[r,i,n,this])}return r}toSorted(t){let n=[...this.entries()].sort(t);return new e(n)}toReversed(){let t=new e;for(let e=this.size-1;e>=0;e--){let n=this.keyAt(e),r=this.get(n);t.set(n,r)}return t}toSpliced(...t){let n=[...this.entries()];return n.splice(...t),new e(n)}slice(t,n){let r=new e,i=this.size-1;if(t===void 0)return r;t<0&&(t+=this.size),n!==void 0&&n>0&&(i=n-1);for(let e=t;e<=i;e++){let t=this.keyAt(e),n=this.get(t);r.set(t,n)}return r}every(e,t){let n=0;for(let r of this){if(!Reflect.apply(e,t,[r,n,this]))return!1;n++}return!0}some(e,t){let n=0;for(let r of this){if(Reflect.apply(e,t,[r,n,this]))return!0;n++}return!1}};function x_(e,t){if(`at`in Array.prototype)return Array.prototype.at.call(e,t);let n=S_(e,t);return n===-1?void 0:e[n]}__(x_,`at`);function S_(e,t){let n=e.length,r=C_(t),i=r>=0?r:n+r;return i<0||i>=n?-1:i}__(S_,`toSafeIndex`);function C_(e){return e!==e||e===0?0:Math.trunc(e)}__(C_,`toSafeInteger`);function w_(e){let t=e+`CollectionProvider`,[n,r]=Pp(t),[i,a]=n(t,{collectionElement:null,collectionRef:{current:null},collectionRefObject:{current:null},itemMap:new b_,setItemMap:__(()=>void 0,`setItemMap`)}),o=__(({state:e,...t})=>e?(0,h.jsx)(c,{...t,state:e}):(0,h.jsx)(s,{...t}),`CollectionProvider`);o.displayName=t;let s=__(e=>{let t=_();return(0,h.jsx)(c,{...e,state:t})},`CollectionInit`);s.displayName=t+`Init`;let c=__(e=>{let{scope:t,children:n,state:r}=e,a=m.useRef(null),[o,s]=m.useState(null),c=Ap(a,s),[l,u]=r;return m.useEffect(()=>{if(!o)return;let e=O_(()=>{});return e.observe(o,{childList:!0,subtree:!0}),()=>{e.disconnect()}},[o]),(0,h.jsx)(i,{scope:t,itemMap:l,setItemMap:u,collectionRef:c,collectionRefObject:a,collectionElement:o,children:n})},`CollectionProviderImpl`);c.displayName=t+`Impl`;let l=e+`CollectionSlot`,u=om(l),d=m.forwardRef((e,t)=>{let{scope:n,children:r}=e,i=Ap(t,a(l,n).collectionRef);return(0,h.jsx)(u,{ref:i,children:r})});d.displayName=l;let f=e+`CollectionItemSlot`,p=om(f),g=m.forwardRef((e,t)=>{let{scope:n,children:r,...i}=e,o=m.useRef(null),[s,c]=m.useState(null),l=Ap(t,o,c),{setItemMap:u}=a(f,n),d=m.useRef(i);T_(d.current,i)||(d.current=i);let g=d.current;return m.useEffect(()=>{let e=g;return u(t=>s?t.has(s)?t.set(s,{...e,element:s}).toSorted(D_):(t.set(s,{...e,element:s}),t.toSorted(D_)):t),()=>{u(e=>!s||!e.has(s)?e:(e.delete(s),new b_(e)))}},[s,g,u]),(0,h.jsx)(p,{"data-radix-collection-item":``,ref:l,children:r})});g.displayName=f;function _(){return m.useState(new b_)}__(_,`useInitCollection`);function v(t){let{itemMap:n}=a(e+`CollectionConsumer`,t);return n}return __(v,`useCollection`),[{Provider:o,Slot:d,ItemSlot:g},{createCollectionScope:r,useCollection:v,useInitCollection:_}]}__(w_,`createCollection`);function T_(e,t){if(e===t)return!0;if(typeof e!=`object`||typeof t!=`object`||e==null||t==null)return!1;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||e[r]!==t[r])return!1;return!0}__(T_,`shallowEqual`);function E_(e,t){return!!(t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_PRECEDING)}__(E_,`isElementPreceding`);function D_(e,t){return!e[1].element||!t[1].element?0:E_(e[1].element,t[1].element)?-1:1}__(D_,`sortByDocumentPosition`);function O_(e){return new MutationObserver(t=>{for(let n of t)if(n.type===`childList`){e();return}})}__(O_,`getChildListObserver`);var k_=Object.defineProperty,A_=(e,t)=>k_(e,`name`,{value:t,configurable:!0}),j_=Object.freeze({position:`absolute`,border:0,width:1,height:1,padding:0,margin:-1,overflow:`hidden`,clip:`rect(0, 0, 0, 0)`,whiteSpace:`nowrap`,wordWrap:`normal`}),M_=m.forwardRef(A_(function(e,t){return(0,h.jsx)(Sm.span,{...e,ref:t,style:{...j_,...e.style}})},`VisuallyHidden`)),N_=Object.defineProperty,P_=(e,t)=>N_(e,`name`,{value:t,configurable:!0}),F_=`ToastProvider`,[I_,L_,R_]=v_(`Toast`),[z_,B_]=Pp(`Toast`,[R_]),[V_,H_]=z_(F_),U_=P_(e=>{let{__scopeToast:t,label:n=`Notification`,duration:r=5e3,swipeDirection:i=`right`,swipeThreshold:a=50,announcerContainer:o,children:s}=e,[c,l]=m.useState(null),[u,d]=m.useState(0),f=m.useRef(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${F_}\`. Expected non-empty \`string\`.`),(0,h.jsx)(I_.Provider,{scope:t,children:(0,h.jsx)(V_,{scope:t,label:n,duration:r,swipeDirection:i,swipeThreshold:a,toastCount:u,viewport:c,onViewportChange:l,onToastAdd:m.useCallback(()=>d(e=>e+1),[]),onToastRemove:m.useCallback(()=>d(e=>e-1),[]),isClosePausedRef:f,announcerContainer:o,children:s})})},`ToastProvider`),W_=`ToastViewport`,G_=[`F8`],K_=`toast.viewportPause`,q_=`toast.viewportResume`,J_=m.forwardRef(P_(function(e,t){let{__scopeToast:n,hotkey:r=G_,label:i=`Notifications ({hotkey})`,...a}=e,o=H_(W_,n),s=L_(n),c=m.useRef(null),l=m.useRef(null),u=m.useRef(null),d=m.useRef(null),f=Ap(t,d,o.onViewportChange),p=r.join(`+`).replace(/Key/g,``).replace(/Digit/g,``),g=o.toastCount>0;m.useEffect(()=>{let e=P_(e=>{r.length!==0&&r.every(t=>e[t]||e.code===t)&&d.current?.focus()},`handleKeyDown`);return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[r]),m.useEffect(()=>{let e=c.current,t=d.current;if(g&&e&&t){let n=P_(()=>{if(!o.isClosePausedRef.current){let e=new CustomEvent(K_);t.dispatchEvent(e),o.isClosePausedRef.current=!0}},`handlePause`),r=P_(()=>{if(o.isClosePausedRef.current){let e=new CustomEvent(q_);t.dispatchEvent(e),o.isClosePausedRef.current=!1}},`handleResume`),i=P_(t=>{e.contains(t.relatedTarget)||r()},`handleFocusOutResume`),a=P_(()=>{e.contains(document.activeElement)||r()},`handlePointerLeaveResume`);return e.addEventListener(`focusin`,n),e.addEventListener(`focusout`,i),e.addEventListener(`pointermove`,n),e.addEventListener(`pointerleave`,a),window.addEventListener(`blur`,n),window.addEventListener(`focus`,r),()=>{e.removeEventListener(`focusin`,n),e.removeEventListener(`focusout`,i),e.removeEventListener(`pointermove`,n),e.removeEventListener(`pointerleave`,a),window.removeEventListener(`blur`,n),window.removeEventListener(`focus`,r)}}},[g,o.isClosePausedRef]);let _=m.useCallback(({tabbingDirection:e})=>{let t=s().map(t=>{let n=t.ref.current,r=[n,...mv(n)];return e===`forwards`?r:r.reverse()});return(e===`forwards`?t.reverse():t).flat()},[s]);return m.useEffect(()=>{let e=d.current;if(e){let t=P_(t=>{let n=t.altKey||t.ctrlKey||t.metaKey;if(t.key===`Tab`&&!n){let n=document.activeElement,r=t.shiftKey;if(t.target===e&&r){l.current?.focus();return}let i=_({tabbingDirection:r?`backwards`:`forwards`}),a=i.findIndex(e=>e===n);hv(i.slice(a+1))?t.preventDefault():r?l.current?.focus():u.current?.focus()}},`handleKeyDown`);return e.addEventListener(`keydown`,t),()=>e.removeEventListener(`keydown`,t)}},[s,_]),(0,h.jsxs)(Um,{ref:c,role:`region`,"aria-label":i.replace(`{hotkey}`,p),tabIndex:-1,style:{pointerEvents:g?void 0:`none`},children:[g&&(0,h.jsx)(X_,{ref:l,onFocusFromOutsideViewport:()=>{hv(_({tabbingDirection:`forwards`}))}}),(0,h.jsx)(I_.Slot,{scope:n,children:(0,h.jsx)(Sm.ol,{tabIndex:-1,...a,ref:f})}),g&&(0,h.jsx)(X_,{ref:u,onFocusFromOutsideViewport:()=>{hv(_({tabbingDirection:`backwards`}))}})]})},`ToastViewport`)),Y_=`ToastFocusProxy`,X_=m.forwardRef(P_(function(e,t){let{__scopeToast:n,onFocusFromOutsideViewport:r,...i}=e,a=H_(Y_,n);return(0,h.jsx)(M_,{tabIndex:0,...i,ref:t,style:{position:`fixed`},onFocus:e=>{let t=e.relatedTarget;a.viewport?.contains(t)||r()}})},`ToastFocusProxy`)),Z_=`Toast`,Q_=`toast.swipeStart`,$_=`toast.swipeMove`,ev=`toast.swipeCancel`,tv=`toast.swipeEnd`,nv=m.forwardRef(P_(function(e,t){let{forceMount:n,open:r,defaultOpen:i,onOpenChange:a,...o}=e,[s,c]=Xp({prop:r,defaultProp:i??!0,onChange:a,caller:Z_});return(0,h.jsx)(fh,{present:n||s,children:(0,h.jsx)(av,{open:s,...o,ref:t,onClose:()=>c(!1),onPause:Em(e.onPause),onResume:Em(e.onResume),onSwipeStart:xp(e.onSwipeStart,e=>{e.currentTarget.setAttribute(`data-swipe`,`start`)}),onSwipeMove:xp(e.onSwipeMove,e=>{let{x:t,y:n}=e.detail.delta;e.currentTarget.setAttribute(`data-swipe`,`move`),e.currentTarget.style.setProperty(`--radix-toast-swipe-move-x`,`${t}px`),e.currentTarget.style.setProperty(`--radix-toast-swipe-move-y`,`${n}px`)}),onSwipeCancel:xp(e.onSwipeCancel,e=>{e.currentTarget.setAttribute(`data-swipe`,`cancel`),e.currentTarget.style.removeProperty(`--radix-toast-swipe-move-x`),e.currentTarget.style.removeProperty(`--radix-toast-swipe-move-y`),e.currentTarget.style.removeProperty(`--radix-toast-swipe-end-x`),e.currentTarget.style.removeProperty(`--radix-toast-swipe-end-y`)}),onSwipeEnd:xp(e.onSwipeEnd,e=>{let{x:t,y:n}=e.detail.delta;e.currentTarget.setAttribute(`data-swipe`,`end`),e.currentTarget.style.removeProperty(`--radix-toast-swipe-move-x`),e.currentTarget.style.removeProperty(`--radix-toast-swipe-move-y`),e.currentTarget.style.setProperty(`--radix-toast-swipe-end-x`,`${t}px`),e.currentTarget.style.setProperty(`--radix-toast-swipe-end-y`,`${n}px`),c(!1)})})})},`Toast`)),[rv,iv]=z_(Z_,{onClose(){}}),av=m.forwardRef(P_(function(e,t){let{__scopeToast:n,type:r=`foreground`,duration:i,open:a,onClose:o,onEscapeKeyDown:s,onPause:c,onResume:l,onSwipeStart:u,onSwipeMove:d,onSwipeCancel:f,onSwipeEnd:p,...g}=e,_=H_(Z_,n),v=L_(n),[y,b]=m.useState(null),x=Ap(t,b),S=m.useRef(null),C=m.useRef(null),w=i||_.duration,T=m.useRef(0),E=m.useRef(w),D=m.useRef(0),{onToastAdd:O,onToastRemove:ee}=_,k=Em(()=>{y?.contains(document.activeElement)&&_.viewport?.focus(),o()}),A=m.useCallback(e=>{!e||e===1/0||(window.clearTimeout(D.current),T.current=new Date().getTime(),D.current=window.setTimeout(k,e))},[k]);m.useEffect(()=>{let e=_.viewport;if(e){let t=P_(()=>{A(E.current),l?.()},`handleResume`),n=P_(()=>{let e=new Date().getTime()-T.current;E.current-=e,window.clearTimeout(D.current),c?.()},`handlePause`);return e.addEventListener(K_,n),e.addEventListener(q_,t),()=>{e.removeEventListener(K_,n),e.removeEventListener(q_,t)}}},[_.viewport,w,c,l,A]),m.useEffect(()=>{a&&!_.isClosePausedRef.current&&A(w)},[a,w,_.isClosePausedRef,A]),m.useEffect(()=>()=>{window.clearTimeout(D.current)},[]),m.useEffect(()=>(O(),()=>ee()),[O,ee]);let j=m.useMemo(()=>y?lv(y):null,[y]);return _.viewport?(0,h.jsxs)(h.Fragment,{children:[j&&(0,h.jsx)(ov,{__scopeToast:n,role:`status`,"aria-live":r===`foreground`?`assertive`:`polite`,children:j}),(0,h.jsx)(rv,{scope:n,onClose:k,children:rm.createPortal((0,h.jsx)(I_.ItemSlot,{scope:n,children:(0,h.jsx)(Hm,{asChild:!0,onEscapeKeyDown:xp(s,e=>{v().some(t=>t.ref.current?.contains(e.target))||k()}),children:(0,h.jsx)(Sm.li,{tabIndex:0,"data-state":a?`open`:`closed`,"data-swipe-direction":_.swipeDirection,...g,ref:x,style:{userSelect:`none`,touchAction:`none`,...e.style},onKeyDown:xp(e.onKeyDown,e=>{e.key===`Escape`&&(s?.(e.nativeEvent),e.nativeEvent.defaultPrevented||k())}),onPointerDown:xp(e.onPointerDown,e=>{e.button===0&&(S.current={x:e.clientX,y:e.clientY})}),onPointerMove:xp(e.onPointerMove,e=>{if(!S.current)return;let t=e.clientX-S.current.x,n=e.clientY-S.current.y,r=!!C.current,i=[`left`,`right`].includes(_.swipeDirection),a=[`left`,`up`].includes(_.swipeDirection)?Math.min:Math.max,o=i?a(0,t):0,s=i?0:a(0,n),c=e.pointerType===`touch`?10:2,l={x:o,y:s},f={originalEvent:e,delta:l};r?(C.current=l,uv($_,d,f,{discrete:!1})):dv(l,_.swipeDirection,c)?(C.current=l,uv(Q_,u,f,{discrete:!1}),e.target.setPointerCapture(e.pointerId)):(Math.abs(t)>c||Math.abs(n)>c)&&(S.current=null)}),onPointerUp:xp(e.onPointerUp,e=>{let t=C.current,n=e.target;if(n.hasPointerCapture(e.pointerId)&&n.releasePointerCapture(e.pointerId),C.current=null,S.current=null,t){let n=e.currentTarget,r={originalEvent:e,delta:t};dv(t,_.swipeDirection,_.swipeThreshold)?uv(tv,p,r,{discrete:!0}):uv(ev,f,r,{discrete:!0}),n.addEventListener(`click`,e=>e.preventDefault(),{once:!0})}})})})}),_.viewport)})]}):null},`ToastImpl`)),ov=P_(e=>{let{__scopeToast:t,children:n,...r}=e,i=H_(Z_,t),[a,o]=m.useState(!1),[s,c]=m.useState(!1);return fv(()=>o(!0)),m.useEffect(()=>{let e=window.setTimeout(()=>c(!0),1e3);return()=>window.clearTimeout(e)},[]),s?null:(0,h.jsx)(ch,{asChild:!0,container:i.announcerContainer||void 0,children:(0,h.jsx)(M_,{...r,children:a&&(0,h.jsxs)(h.Fragment,{children:[i.label,` `,n]})})})},`ToastAnnounce`),sv=m.forwardRef(P_(function(e,t){let{__scopeToast:n,...r}=e;return(0,h.jsx)(Sm.div,{...r,ref:t})},`ToastTitle`)),cv=m.forwardRef(P_(function(e,t){let{__scopeToast:n,...r}=e;return(0,h.jsx)(Sm.div,{...r,ref:t})},`ToastDescription`));function lv(e){let t=[];return Array.from(e.childNodes).forEach(e=>{if(e.nodeType===e.TEXT_NODE&&e.textContent&&t.push(e.textContent),pv(e)){let n=e.ariaHidden||e.hidden||e.style.display===`none`,r=e.dataset.radixToastAnnounceExclude===``;if(!n){if(r){let n=e.dataset.radixToastAnnounceAlt;n&&t.push(n)}else t.push(...lv(e))}}}),t}P_(lv,`getAnnounceTextContent`);function uv(e,t,n,{discrete:r}){let i=n.originalEvent.currentTarget,a=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?Cm(i,a):i.dispatchEvent(a)}P_(uv,`handleAndDispatchCustomEvent`);var dv=P_((e,t,n=0)=>{let r=Math.abs(e.x),i=Math.abs(e.y),a=r>i;return t===`left`||t===`right`?a&&r>n:!a&&i>n},`isDeltaInDirection`);function fv(e=()=>{}){let t=Em(e);Ip(()=>{let e=0,n=0;return e=window.requestAnimationFrame(()=>n=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(e),window.cancelAnimationFrame(n)}},[t])}P_(fv,`useNextFrame`);function pv(e){return e.nodeType===e.ELEMENT_NODE}P_(pv,`isHTMLElement`);function mv(e){let t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:P_(e=>{let t=e.tagName===`INPUT`&&e.type===`hidden`;return e.disabled||e.hidden||t?NodeFilter.FILTER_SKIP:e.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},`acceptNode`)});for(;n.nextNode();)t.push(n.currentNode);return t}P_(mv,`getTabbableCandidates`);function hv(e){let t=document.activeElement;return e.some(e=>e===t||(e.focus(),document.activeElement!==t))}P_(hv,`focusFirst`);var gv=U_,_v=J_,vv=nv,yv=sv,bv=cv;function xv(e){var t,n,r=``;if(typeof e==`string`||typeof e==`number`)r+=e;else if(typeof e==`object`){if(Array.isArray(e)){var i=e.length;for(t=0;ttypeof e==`boolean`?`${e}`:e===0?`0`:e,wv=Sv,Tv=(e,t)=>n=>{if(t?.variants==null)return wv(e,n?.class,n?.className);let{variants:r,defaultVariants:i}=t,a=Object.keys(r).map(e=>{let t=n?.[e],a=i?.[e];if(t===null)return null;let o=Cv(t)||Cv(a);return r[e][o]}),o=n&&Object.entries(n).reduce((e,t)=>{let[n,r]=t;return r===void 0||(e[n]=r),e},{});return wv(e,a,t?.compoundVariants?.reduce((e,t)=>{let{class:n,className:r,...a}=t;return Object.entries(a).every(e=>{let[t,n]=e;return Array.isArray(n)?n.includes({...i,...o}[t]):{...i,...o}[t]===n})?[...e,n,r]:e},[]),n?.class,n?.className)},Ev=(e,t)=>{let n=Array(e.length+t.length);for(let t=0;t({classGroupId:e,validator:t}),Ov=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),kv=`-`,Av=[],jv=`arbitrary..`,Mv=e=>{let t=Fv(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:e=>{if(e.startsWith(`[`)&&e.endsWith(`]`))return Pv(e);let n=e.split(kv);return Nv(n,+(n[0]===``&&n.length>1),t)},getConflictingClassGroupIds:(e,t)=>{if(t){let t=r[e],i=n[e];return t?i?Ev(i,t):t:i||Av}return n[e]||Av}}},Nv=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;let r=e[t],i=n.nextPart.get(r);if(i){let n=Nv(e,t+1,i);if(n)return n}let a=n.validators;if(a===null)return;let o=t===0?e.join(kv):e.slice(t).join(kv),s=a.length;for(let e=0;ee.slice(1,-1).indexOf(`:`)===-1?void 0:(()=>{let t=e.slice(1,-1),n=t.indexOf(`:`),r=t.slice(0,n);return r?jv+r:void 0})(),Fv=e=>{let{theme:t,classGroups:n}=e;return Iv(n,t)},Iv=(e,t)=>{let n=Ov();for(let r in e){let i=e[r];Lv(i,n,r,t)}return n},Lv=(e,t,n,r)=>{let i=e.length;for(let a=0;a{if(typeof e==`string`){zv(e,t,n);return}if(typeof e==`function`){Bv(e,t,n,r);return}Vv(e,t,n,r)},zv=(e,t,n)=>{let r=e===``?t:Hv(t,e);r.classGroupId=n},Bv=(e,t,n,r)=>{if(Uv(e)){Lv(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(Dv(n,e))},Vv=(e,t,n,r)=>{let i=Object.entries(e),a=i.length;for(let e=0;e{let n=e,r=t.split(kv),i=r.length;for(let e=0;e`isThemeGetter`in e&&e.isThemeGetter===!0,Wv=e=>{if(e<1)return{get:()=>void 0,set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null),i=(i,a)=>{n[i]=a,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(e){let t=n[e];if(t!==void 0)return t;if((t=r[e])!==void 0)return i(e,t),t},set(e,t){e in n?n[e]=t:i(e,t)}}},Gv=`!`,Kv=`:`,qv=[],Jv=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),Yv=e=>{let{prefix:t,experimentalParseClassName:n}=e,r=e=>{let t=[],n=0,r=0,i=0,a,o=e.length;for(let s=0;si?a-i:void 0;return Jv(t,l,c,u)};if(t){let e=t+Kv,n=r;r=t=>t.startsWith(e)?n(t.slice(e.length)):Jv(qv,!1,t,void 0,!0)}if(n){let e=r;r=t=>n({className:t,parseClassName:e})}return r},Xv=e=>{let t=new Map;return e.orderSensitiveModifiers.forEach((e,n)=>{t.set(e,1e6+n)}),e=>{let n=[],r=[];for(let i=0;i0&&(r.sort(),n.push(...r),r=[]),n.push(a)):r.push(a)}return r.length>0&&(r.sort(),n.push(...r)),n}},Zv=e=>({cache:Wv(e.cacheSize),parseClassName:Yv(e),sortModifiers:Xv(e),postfixLookupClassGroupIds:Qv(e),...Mv(e)}),Qv=e=>{let t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let e=0;e{let{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:a,postfixLookupClassGroupIds:o}=t,s=[],c=e.trim().split($v),l=``;for(let e=c.length-1;e>=0;--e){let t=c[e],{isExternal:u,modifiers:d,hasImportantModifier:f,baseClassName:p,maybePostfixModifierPosition:m}=n(t);if(u){l=t+(l.length>0?` `+l:l);continue}let h=!!m,g;if(h){g=r(p.substring(0,m));let e=g&&o[g]?r(p):void 0;e&&e!==g&&(g=e,h=!1)}else g=r(p);if(!g){if(!h){l=t+(l.length>0?` `+l:l);continue}if(g=r(p),!g){l=t+(l.length>0?` `+l:l);continue}h=!1}let _=d.length===0?``:d.length===1?d[0]:a(d).join(`:`),v=f?_+Gv:_,y=v+g;if(s.indexOf(y)>-1)continue;s.push(y);let b=i(g,h);for(let e=0;e0?` `+l:l)}return l},ty=(...e)=>{let t=0,n,r,i=``;for(;t{if(typeof e==`string`)return e;let t,n=``;for(let r=0;r{let n,r,i,a,o=o=>(n=Zv(t.reduce((e,t)=>t(e),e())),r=n.cache.get,i=n.cache.set,a=s,s(o)),s=e=>{let t=r(e);if(t)return t;let a=ey(e,n);return i(e,a),a};return a=o,(...e)=>a(ty(...e))},iy=[],ay=e=>{let t=t=>t[e]||iy;return t.isThemeGetter=!0,t},oy=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,sy=/^\((?:(\w[\w-]*):)?(.+)\)$/i,cy=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,ly=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,uy=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,dy=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,fy=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,py=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,my=e=>cy.test(e),hy=e=>!!e&&!Number.isNaN(Number(e)),gy=e=>!!e&&Number.isInteger(Number(e)),_y=e=>e.endsWith(`%`)&&hy(e.slice(0,-1)),vy=e=>ly.test(e),yy=()=>!0,by=e=>uy.test(e)&&!dy.test(e),xy=()=>!1,Sy=e=>fy.test(e),Cy=e=>py.test(e),wy=e=>!J(e)&&!Y(e),Ty=e=>e.startsWith(`@container`)&&(e[10]===`/`&&e[11]!==void 0||e[11]===`s`&&e[16]!==void 0&&e.startsWith(`-size/`,10)||e[11]===`n`&&e[18]!==void 0&&e.startsWith(`-normal/`,10)),Ey=e=>Vy(e,Gy,xy),J=e=>oy.test(e),Dy=e=>Vy(e,Ky,by),Oy=e=>Vy(e,qy,hy),ky=e=>Vy(e,Yy,yy),Ay=e=>Vy(e,Jy,xy),jy=e=>Vy(e,Uy,xy),My=e=>Vy(e,Wy,Cy),Ny=e=>Vy(e,Xy,Sy),Y=e=>sy.test(e),Py=e=>Hy(e,Ky),Fy=e=>Hy(e,Jy),Iy=e=>Hy(e,Uy),Ly=e=>Hy(e,Gy),Ry=e=>Hy(e,Wy),zy=e=>Hy(e,Xy,!0),By=e=>Hy(e,Yy,!0),Vy=(e,t,n)=>{let r=oy.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Hy=(e,t,n=!1)=>{let r=sy.exec(e);return r?r[1]?t(r[1]):n:!1},Uy=e=>e===`position`||e===`percentage`,Wy=e=>e===`image`||e===`url`,Gy=e=>e===`length`||e===`size`||e===`bg-size`,Ky=e=>e===`length`,qy=e=>e===`number`,Jy=e=>e===`family-name`,Yy=e=>e===`number`||e===`weight`,Xy=e=>e===`shadow`,Zy=ry(()=>{let e=ay(`color`),t=ay(`font`),n=ay(`text`),r=ay(`font-weight`),i=ay(`tracking`),a=ay(`leading`),o=ay(`breakpoint`),s=ay(`container`),c=ay(`spacing`),l=ay(`radius`),u=ay(`shadow`),d=ay(`inset-shadow`),f=ay(`text-shadow`),p=ay(`drop-shadow`),m=ay(`blur`),h=ay(`perspective`),g=ay(`aspect`),_=ay(`ease`),v=ay(`animate`),y=()=>[`auto`,`avoid`,`all`,`avoid-page`,`page`,`left`,`right`,`column`],b=()=>[`center`,`top`,`bottom`,`left`,`right`,`top-left`,`left-top`,`top-right`,`right-top`,`bottom-right`,`right-bottom`,`bottom-left`,`left-bottom`],x=()=>[...b(),Y,J],S=()=>[`auto`,`hidden`,`clip`,`visible`,`scroll`],C=()=>[`auto`,`contain`,`none`],w=()=>[Y,J,c],T=()=>[my,`full`,`auto`,...w()],E=()=>[gy,`none`,`subgrid`,Y,J],D=()=>[`auto`,{span:[`full`,gy,Y,J]},gy,Y,J],O=()=>[gy,`auto`,Y,J],ee=()=>[`auto`,`min`,`max`,`fr`,Y,J],k=()=>[`start`,`end`,`center`,`between`,`around`,`evenly`,`stretch`,`baseline`,`center-safe`,`end-safe`],A=()=>[`start`,`end`,`center`,`stretch`,`center-safe`,`end-safe`],j=()=>[`auto`,...w()],M=()=>[my,`auto`,`full`,`dvw`,`dvh`,`lvw`,`lvh`,`svw`,`svh`,`min`,`max`,`fit`,...w()],N=()=>[my,`screen`,`full`,`dvw`,`lvw`,`svw`,`min`,`max`,`fit`,...w()],P=()=>[my,`screen`,`full`,`lh`,`dvh`,`lvh`,`svh`,`min`,`max`,`fit`,...w()],F=()=>[e,Y,J],te=()=>[...b(),Iy,jy,{position:[Y,J]}],ne=()=>[`no-repeat`,{repeat:[``,`x`,`y`,`space`,`round`]}],re=()=>[`auto`,`cover`,`contain`,Ly,Ey,{size:[Y,J]}],ie=()=>[_y,Py,Dy],I=()=>[``,`none`,`full`,l,Y,J],L=()=>[``,hy,Py,Dy],ae=()=>[`solid`,`dashed`,`dotted`,`double`],oe=()=>[`normal`,`multiply`,`screen`,`overlay`,`darken`,`lighten`,`color-dodge`,`color-burn`,`hard-light`,`soft-light`,`difference`,`exclusion`,`hue`,`saturation`,`color`,`luminosity`],se=()=>[hy,_y,Iy,jy],ce=()=>[``,`none`,m,Y,J],le=()=>[`none`,hy,Y,J],ue=()=>[`none`,hy,Y,J],de=()=>[hy,Y,J],fe=()=>[my,`full`,...w()];return{cacheSize:500,theme:{animate:[`spin`,`ping`,`pulse`,`bounce`],aspect:[`video`],blur:[vy],breakpoint:[vy],color:[yy],container:[vy],"drop-shadow":[vy],ease:[`in`,`out`,`in-out`],font:[wy],"font-weight":[`thin`,`extralight`,`light`,`normal`,`medium`,`semibold`,`bold`,`extrabold`,`black`],"inset-shadow":[vy],leading:[`none`,`tight`,`snug`,`normal`,`relaxed`,`loose`],perspective:[`dramatic`,`near`,`normal`,`midrange`,`distant`,`none`],radius:[vy],shadow:[vy],spacing:[`px`,hy],text:[vy],"text-shadow":[vy],tracking:[`tighter`,`tight`,`normal`,`wide`,`wider`,`widest`]},classGroups:{aspect:[{aspect:[`auto`,`square`,my,J,Y,g]}],container:[`container`],"container-type":[{"@container":[``,`normal`,`size`,Y,J]}],"container-named":[Ty],columns:[{columns:[hy,J,Y,s]}],"break-after":[{"break-after":y()}],"break-before":[{"break-before":y()}],"break-inside":[{"break-inside":[`auto`,`avoid`,`avoid-page`,`avoid-column`]}],"box-decoration":[{"box-decoration":[`slice`,`clone`]}],box:[{box:[`border`,`content`]}],display:[`block`,`inline-block`,`inline`,`flex`,`inline-flex`,`table`,`inline-table`,`table-caption`,`table-cell`,`table-column`,`table-column-group`,`table-footer-group`,`table-header-group`,`table-row-group`,`table-row`,`flow-root`,`grid`,`inline-grid`,`contents`,`list-item`,`hidden`],sr:[`sr-only`,`not-sr-only`],float:[{float:[`right`,`left`,`none`,`start`,`end`]}],clear:[{clear:[`left`,`right`,`both`,`none`,`start`,`end`]}],isolation:[`isolate`,`isolation-auto`],"object-fit":[{object:[`contain`,`cover`,`fill`,`none`,`scale-down`]}],"object-position":[{object:x()}],overflow:[{overflow:S()}],"overflow-x":[{"overflow-x":S()}],"overflow-y":[{"overflow-y":S()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:[`static`,`fixed`,`absolute`,`relative`,`sticky`],inset:[{inset:T()}],"inset-x":[{"inset-x":T()}],"inset-y":[{"inset-y":T()}],start:[{"inset-s":T(),start:T()}],end:[{"inset-e":T(),end:T()}],"inset-bs":[{"inset-bs":T()}],"inset-be":[{"inset-be":T()}],top:[{top:T()}],right:[{right:T()}],bottom:[{bottom:T()}],left:[{left:T()}],visibility:[`visible`,`invisible`,`collapse`],z:[{z:[gy,`auto`,Y,J]}],basis:[{basis:[my,`full`,`auto`,s,...w()]}],"flex-direction":[{flex:[`row`,`row-reverse`,`col`,`col-reverse`]}],"flex-wrap":[{flex:[`nowrap`,`wrap`,`wrap-reverse`]}],flex:[{flex:[hy,my,`auto`,`initial`,`none`,J]}],grow:[{grow:[``,hy,Y,J]}],shrink:[{shrink:[``,hy,Y,J]}],order:[{order:[gy,`first`,`last`,`none`,Y,J]}],"grid-cols":[{"grid-cols":E()}],"col-start-end":[{col:D()}],"col-start":[{"col-start":O()}],"col-end":[{"col-end":O()}],"grid-rows":[{"grid-rows":E()}],"row-start-end":[{row:D()}],"row-start":[{"row-start":O()}],"row-end":[{"row-end":O()}],"grid-flow":[{"grid-flow":[`row`,`col`,`dense`,`row-dense`,`col-dense`]}],"auto-cols":[{"auto-cols":ee()}],"auto-rows":[{"auto-rows":ee()}],gap:[{gap:w()}],"gap-x":[{"gap-x":w()}],"gap-y":[{"gap-y":w()}],"justify-content":[{justify:[...k(),`normal`]}],"justify-items":[{"justify-items":[...A(),`normal`]}],"justify-self":[{"justify-self":[`auto`,...A()]}],"align-content":[{content:[`normal`,...k()]}],"align-items":[{items:[...A(),{baseline:[``,`last`]}]}],"align-self":[{self:[`auto`,...A(),{baseline:[``,`last`]}]}],"place-content":[{"place-content":k()}],"place-items":[{"place-items":[...A(),`baseline`]}],"place-self":[{"place-self":[`auto`,...A()]}],p:[{p:w()}],px:[{px:w()}],py:[{py:w()}],ps:[{ps:w()}],pe:[{pe:w()}],pbs:[{pbs:w()}],pbe:[{pbe:w()}],pt:[{pt:w()}],pr:[{pr:w()}],pb:[{pb:w()}],pl:[{pl:w()}],m:[{m:j()}],mx:[{mx:j()}],my:[{my:j()}],ms:[{ms:j()}],me:[{me:j()}],mbs:[{mbs:j()}],mbe:[{mbe:j()}],mt:[{mt:j()}],mr:[{mr:j()}],mb:[{mb:j()}],ml:[{ml:j()}],"space-x":[{"space-x":w()}],"space-x-reverse":[`space-x-reverse`],"space-y":[{"space-y":w()}],"space-y-reverse":[`space-y-reverse`],size:[{size:M()}],"inline-size":[{inline:[`auto`,...N()]}],"min-inline-size":[{"min-inline":[`auto`,...N()]}],"max-inline-size":[{"max-inline":[`none`,...N()]}],"block-size":[{block:[`auto`,...P()]}],"min-block-size":[{"min-block":[`auto`,...P()]}],"max-block-size":[{"max-block":[`none`,...P()]}],w:[{w:[s,`screen`,...M()]}],"min-w":[{"min-w":[s,`screen`,`none`,...M()]}],"max-w":[{"max-w":[s,`screen`,`none`,`prose`,{screen:[o]},...M()]}],h:[{h:[`screen`,`lh`,...M()]}],"min-h":[{"min-h":[`screen`,`lh`,`none`,...M()]}],"max-h":[{"max-h":[`screen`,`lh`,...M()]}],"font-size":[{text:[`base`,n,Py,Dy]}],"font-smoothing":[`antialiased`,`subpixel-antialiased`],"font-style":[`italic`,`not-italic`],"font-weight":[{font:[r,By,ky]}],"font-stretch":[{"font-stretch":[`ultra-condensed`,`extra-condensed`,`condensed`,`semi-condensed`,`normal`,`semi-expanded`,`expanded`,`extra-expanded`,`ultra-expanded`,_y,J]}],"font-family":[{font:[Fy,Ay,t]}],"font-features":[{"font-features":[J]}],"fvn-normal":[`normal-nums`],"fvn-ordinal":[`ordinal`],"fvn-slashed-zero":[`slashed-zero`],"fvn-figure":[`lining-nums`,`oldstyle-nums`],"fvn-spacing":[`proportional-nums`,`tabular-nums`],"fvn-fraction":[`diagonal-fractions`,`stacked-fractions`],tracking:[{tracking:[i,Y,J]}],"line-clamp":[{"line-clamp":[hy,`none`,Y,Oy]}],leading:[{leading:[a,...w()]}],"list-image":[{"list-image":[`none`,Y,J]}],"list-style-position":[{list:[`inside`,`outside`]}],"list-style-type":[{list:[`disc`,`decimal`,`none`,Y,J]}],"text-alignment":[{text:[`left`,`center`,`right`,`justify`,`start`,`end`]}],"placeholder-color":[{placeholder:F()}],"text-color":[{text:F()}],"text-decoration":[`underline`,`overline`,`line-through`,`no-underline`],"text-decoration-style":[{decoration:[...ae(),`wavy`]}],"text-decoration-thickness":[{decoration:[hy,`from-font`,`auto`,Y,Dy]}],"text-decoration-color":[{decoration:F()}],"underline-offset":[{"underline-offset":[hy,`auto`,Y,J]}],"text-transform":[`uppercase`,`lowercase`,`capitalize`,`normal-case`],"text-overflow":[`truncate`,`text-ellipsis`,`text-clip`],"text-wrap":[{text:[`wrap`,`nowrap`,`balance`,`pretty`]}],indent:[{indent:w()}],"tab-size":[{tab:[gy,Y,J]}],"vertical-align":[{align:[`baseline`,`top`,`middle`,`bottom`,`text-top`,`text-bottom`,`sub`,`super`,Y,J]}],whitespace:[{whitespace:[`normal`,`nowrap`,`pre`,`pre-line`,`pre-wrap`,`break-spaces`]}],break:[{break:[`normal`,`words`,`all`,`keep`]}],wrap:[{wrap:[`break-word`,`anywhere`,`normal`]}],hyphens:[{hyphens:[`none`,`manual`,`auto`]}],content:[{content:[`none`,Y,J]}],"bg-attachment":[{bg:[`fixed`,`local`,`scroll`]}],"bg-clip":[{"bg-clip":[`border`,`padding`,`content`,`text`]}],"bg-origin":[{"bg-origin":[`border`,`padding`,`content`]}],"bg-position":[{bg:te()}],"bg-repeat":[{bg:ne()}],"bg-size":[{bg:re()}],"bg-image":[{bg:[`none`,{linear:[{to:[`t`,`tr`,`r`,`br`,`b`,`bl`,`l`,`tl`]},gy,Y,J],radial:[``,Y,J],conic:[gy,Y,J]},Ry,My]}],"bg-color":[{bg:F()}],"gradient-from-pos":[{from:ie()}],"gradient-via-pos":[{via:ie()}],"gradient-to-pos":[{to:ie()}],"gradient-from":[{from:F()}],"gradient-via":[{via:F()}],"gradient-to":[{to:F()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:L()}],"border-w-x":[{"border-x":L()}],"border-w-y":[{"border-y":L()}],"border-w-s":[{"border-s":L()}],"border-w-e":[{"border-e":L()}],"border-w-bs":[{"border-bs":L()}],"border-w-be":[{"border-be":L()}],"border-w-t":[{"border-t":L()}],"border-w-r":[{"border-r":L()}],"border-w-b":[{"border-b":L()}],"border-w-l":[{"border-l":L()}],"divide-x":[{"divide-x":L()}],"divide-x-reverse":[`divide-x-reverse`],"divide-y":[{"divide-y":L()}],"divide-y-reverse":[`divide-y-reverse`],"border-style":[{border:[...ae(),`hidden`,`none`]}],"divide-style":[{divide:[...ae(),`hidden`,`none`]}],"border-color":[{border:F()}],"border-color-x":[{"border-x":F()}],"border-color-y":[{"border-y":F()}],"border-color-s":[{"border-s":F()}],"border-color-e":[{"border-e":F()}],"border-color-bs":[{"border-bs":F()}],"border-color-be":[{"border-be":F()}],"border-color-t":[{"border-t":F()}],"border-color-r":[{"border-r":F()}],"border-color-b":[{"border-b":F()}],"border-color-l":[{"border-l":F()}],"divide-color":[{divide:F()}],"outline-style":[{outline:[...ae(),`none`,`hidden`]}],"outline-offset":[{"outline-offset":[hy,Y,J]}],"outline-w":[{outline:[``,hy,Py,Dy]}],"outline-color":[{outline:F()}],shadow:[{shadow:[``,`none`,u,zy,Ny]}],"shadow-color":[{shadow:F()}],"inset-shadow":[{"inset-shadow":[`none`,d,zy,Ny]}],"inset-shadow-color":[{"inset-shadow":F()}],"ring-w":[{ring:L()}],"ring-w-inset":[`ring-inset`],"ring-color":[{ring:F()}],"ring-offset-w":[{"ring-offset":[hy,Dy]}],"ring-offset-color":[{"ring-offset":F()}],"inset-ring-w":[{"inset-ring":L()}],"inset-ring-color":[{"inset-ring":F()}],"text-shadow":[{"text-shadow":[`none`,f,zy,Ny]}],"text-shadow-color":[{"text-shadow":F()}],opacity:[{opacity:[hy,Y,J]}],"mix-blend":[{"mix-blend":[...oe(),`plus-darker`,`plus-lighter`]}],"bg-blend":[{"bg-blend":oe()}],"mask-clip":[{"mask-clip":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]},`mask-no-clip`],"mask-composite":[{mask:[`add`,`subtract`,`intersect`,`exclude`]}],"mask-image-linear-pos":[{"mask-linear":[hy]}],"mask-image-linear-from-pos":[{"mask-linear-from":se()}],"mask-image-linear-to-pos":[{"mask-linear-to":se()}],"mask-image-linear-from-color":[{"mask-linear-from":F()}],"mask-image-linear-to-color":[{"mask-linear-to":F()}],"mask-image-t-from-pos":[{"mask-t-from":se()}],"mask-image-t-to-pos":[{"mask-t-to":se()}],"mask-image-t-from-color":[{"mask-t-from":F()}],"mask-image-t-to-color":[{"mask-t-to":F()}],"mask-image-r-from-pos":[{"mask-r-from":se()}],"mask-image-r-to-pos":[{"mask-r-to":se()}],"mask-image-r-from-color":[{"mask-r-from":F()}],"mask-image-r-to-color":[{"mask-r-to":F()}],"mask-image-b-from-pos":[{"mask-b-from":se()}],"mask-image-b-to-pos":[{"mask-b-to":se()}],"mask-image-b-from-color":[{"mask-b-from":F()}],"mask-image-b-to-color":[{"mask-b-to":F()}],"mask-image-l-from-pos":[{"mask-l-from":se()}],"mask-image-l-to-pos":[{"mask-l-to":se()}],"mask-image-l-from-color":[{"mask-l-from":F()}],"mask-image-l-to-color":[{"mask-l-to":F()}],"mask-image-x-from-pos":[{"mask-x-from":se()}],"mask-image-x-to-pos":[{"mask-x-to":se()}],"mask-image-x-from-color":[{"mask-x-from":F()}],"mask-image-x-to-color":[{"mask-x-to":F()}],"mask-image-y-from-pos":[{"mask-y-from":se()}],"mask-image-y-to-pos":[{"mask-y-to":se()}],"mask-image-y-from-color":[{"mask-y-from":F()}],"mask-image-y-to-color":[{"mask-y-to":F()}],"mask-image-radial":[{"mask-radial":[Y,J]}],"mask-image-radial-from-pos":[{"mask-radial-from":se()}],"mask-image-radial-to-pos":[{"mask-radial-to":se()}],"mask-image-radial-from-color":[{"mask-radial-from":F()}],"mask-image-radial-to-color":[{"mask-radial-to":F()}],"mask-image-radial-shape":[{"mask-radial":[`circle`,`ellipse`]}],"mask-image-radial-size":[{"mask-radial":[{closest:[`side`,`corner`],farthest:[`side`,`corner`]}]}],"mask-image-radial-pos":[{"mask-radial-at":b()}],"mask-image-conic-pos":[{"mask-conic":[hy]}],"mask-image-conic-from-pos":[{"mask-conic-from":se()}],"mask-image-conic-to-pos":[{"mask-conic-to":se()}],"mask-image-conic-from-color":[{"mask-conic-from":F()}],"mask-image-conic-to-color":[{"mask-conic-to":F()}],"mask-mode":[{mask:[`alpha`,`luminance`,`match`]}],"mask-origin":[{"mask-origin":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]}],"mask-position":[{mask:te()}],"mask-repeat":[{mask:ne()}],"mask-size":[{mask:re()}],"mask-type":[{"mask-type":[`alpha`,`luminance`]}],"mask-image":[{mask:[`none`,Y,J]}],filter:[{filter:[``,`none`,Y,J]}],blur:[{blur:ce()}],brightness:[{brightness:[hy,Y,J]}],contrast:[{contrast:[hy,Y,J]}],"drop-shadow":[{"drop-shadow":[``,`none`,p,zy,Ny]}],"drop-shadow-color":[{"drop-shadow":F()}],grayscale:[{grayscale:[``,hy,Y,J]}],"hue-rotate":[{"hue-rotate":[hy,Y,J]}],invert:[{invert:[``,hy,Y,J]}],saturate:[{saturate:[hy,Y,J]}],sepia:[{sepia:[``,hy,Y,J]}],"backdrop-filter":[{"backdrop-filter":[``,`none`,Y,J]}],"backdrop-blur":[{"backdrop-blur":ce()}],"backdrop-brightness":[{"backdrop-brightness":[hy,Y,J]}],"backdrop-contrast":[{"backdrop-contrast":[hy,Y,J]}],"backdrop-grayscale":[{"backdrop-grayscale":[``,hy,Y,J]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[hy,Y,J]}],"backdrop-invert":[{"backdrop-invert":[``,hy,Y,J]}],"backdrop-opacity":[{"backdrop-opacity":[hy,Y,J]}],"backdrop-saturate":[{"backdrop-saturate":[hy,Y,J]}],"backdrop-sepia":[{"backdrop-sepia":[``,hy,Y,J]}],"border-collapse":[{border:[`collapse`,`separate`]}],"border-spacing":[{"border-spacing":w()}],"border-spacing-x":[{"border-spacing-x":w()}],"border-spacing-y":[{"border-spacing-y":w()}],"table-layout":[{table:[`auto`,`fixed`]}],caption:[{caption:[`top`,`bottom`]}],transition:[{transition:[``,`all`,`colors`,`opacity`,`shadow`,`transform`,`none`,Y,J]}],"transition-behavior":[{transition:[`normal`,`discrete`]}],duration:[{duration:[hy,`initial`,Y,J]}],ease:[{ease:[`linear`,`initial`,_,Y,J]}],delay:[{delay:[hy,Y,J]}],animate:[{animate:[`none`,v,Y,J]}],backface:[{backface:[`hidden`,`visible`]}],perspective:[{perspective:[h,Y,J]}],"perspective-origin":[{"perspective-origin":x()}],rotate:[{rotate:le()}],"rotate-x":[{"rotate-x":le()}],"rotate-y":[{"rotate-y":le()}],"rotate-z":[{"rotate-z":le()}],scale:[{scale:ue()}],"scale-x":[{"scale-x":ue()}],"scale-y":[{"scale-y":ue()}],"scale-z":[{"scale-z":ue()}],"scale-3d":[`scale-3d`],skew:[{skew:de()}],"skew-x":[{"skew-x":de()}],"skew-y":[{"skew-y":de()}],transform:[{transform:[Y,J,``,`none`,`gpu`,`cpu`]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:[`3d`,`flat`]}],translate:[{translate:fe()}],"translate-x":[{"translate-x":fe()}],"translate-y":[{"translate-y":fe()}],"translate-z":[{"translate-z":fe()}],"translate-none":[`translate-none`],zoom:[{zoom:[gy,Y,J]}],accent:[{accent:F()}],appearance:[{appearance:[`none`,`auto`]}],"caret-color":[{caret:F()}],"color-scheme":[{scheme:[`normal`,`dark`,`light`,`light-dark`,`only-dark`,`only-light`]}],cursor:[{cursor:[`auto`,`default`,`pointer`,`wait`,`text`,`move`,`help`,`not-allowed`,`none`,`context-menu`,`progress`,`cell`,`crosshair`,`vertical-text`,`alias`,`copy`,`no-drop`,`grab`,`grabbing`,`all-scroll`,`col-resize`,`row-resize`,`n-resize`,`e-resize`,`s-resize`,`w-resize`,`ne-resize`,`nw-resize`,`se-resize`,`sw-resize`,`ew-resize`,`ns-resize`,`nesw-resize`,`nwse-resize`,`zoom-in`,`zoom-out`,Y,J]}],"field-sizing":[{"field-sizing":[`fixed`,`content`]}],"pointer-events":[{"pointer-events":[`auto`,`none`]}],resize:[{resize:[`none`,``,`y`,`x`]}],"scroll-behavior":[{scroll:[`auto`,`smooth`]}],"scrollbar-thumb-color":[{"scrollbar-thumb":F()}],"scrollbar-track-color":[{"scrollbar-track":F()}],"scrollbar-gutter":[{"scrollbar-gutter":[`auto`,`stable`,`both`]}],"scrollbar-w":[{scrollbar:[`auto`,`thin`,`none`]}],"scroll-m":[{"scroll-m":w()}],"scroll-mx":[{"scroll-mx":w()}],"scroll-my":[{"scroll-my":w()}],"scroll-ms":[{"scroll-ms":w()}],"scroll-me":[{"scroll-me":w()}],"scroll-mbs":[{"scroll-mbs":w()}],"scroll-mbe":[{"scroll-mbe":w()}],"scroll-mt":[{"scroll-mt":w()}],"scroll-mr":[{"scroll-mr":w()}],"scroll-mb":[{"scroll-mb":w()}],"scroll-ml":[{"scroll-ml":w()}],"scroll-p":[{"scroll-p":w()}],"scroll-px":[{"scroll-px":w()}],"scroll-py":[{"scroll-py":w()}],"scroll-ps":[{"scroll-ps":w()}],"scroll-pe":[{"scroll-pe":w()}],"scroll-pbs":[{"scroll-pbs":w()}],"scroll-pbe":[{"scroll-pbe":w()}],"scroll-pt":[{"scroll-pt":w()}],"scroll-pr":[{"scroll-pr":w()}],"scroll-pb":[{"scroll-pb":w()}],"scroll-pl":[{"scroll-pl":w()}],"snap-align":[{snap:[`start`,`end`,`center`,`align-none`]}],"snap-stop":[{snap:[`normal`,`always`]}],"snap-type":[{snap:[`none`,`x`,`y`,`both`]}],"snap-strictness":[{snap:[`mandatory`,`proximity`]}],touch:[{touch:[`auto`,`none`,`manipulation`]}],"touch-x":[{"touch-pan":[`x`,`left`,`right`]}],"touch-y":[{"touch-pan":[`y`,`up`,`down`]}],"touch-pz":[`touch-pinch-zoom`],select:[{select:[`none`,`text`,`all`,`auto`]}],"will-change":[{"will-change":[`auto`,`scroll`,`contents`,`transform`,Y,J]}],fill:[{fill:[`none`,...F()]}],"stroke-w":[{stroke:[hy,Py,Dy,Oy]}],stroke:[{stroke:[`none`,...F()]}],"forced-color-adjust":[{"forced-color-adjust":[`auto`,`none`]}]},conflictingClassGroups:{"container-named":[`container-type`],overflow:[`overflow-x`,`overflow-y`],overscroll:[`overscroll-x`,`overscroll-y`],inset:[`inset-x`,`inset-y`,`inset-bs`,`inset-be`,`start`,`end`,`top`,`right`,`bottom`,`left`],"inset-x":[`right`,`left`],"inset-y":[`top`,`bottom`],flex:[`basis`,`grow`,`shrink`],gap:[`gap-x`,`gap-y`],p:[`px`,`py`,`ps`,`pe`,`pbs`,`pbe`,`pt`,`pr`,`pb`,`pl`],px:[`pr`,`pl`],py:[`pt`,`pb`],m:[`mx`,`my`,`ms`,`me`,`mbs`,`mbe`,`mt`,`mr`,`mb`,`ml`],mx:[`mr`,`ml`],my:[`mt`,`mb`],size:[`w`,`h`],"font-size":[`leading`],"fvn-normal":[`fvn-ordinal`,`fvn-slashed-zero`,`fvn-figure`,`fvn-spacing`,`fvn-fraction`],"fvn-ordinal":[`fvn-normal`],"fvn-slashed-zero":[`fvn-normal`],"fvn-figure":[`fvn-normal`],"fvn-spacing":[`fvn-normal`],"fvn-fraction":[`fvn-normal`],"line-clamp":[`display`,`overflow`],rounded:[`rounded-s`,`rounded-e`,`rounded-t`,`rounded-r`,`rounded-b`,`rounded-l`,`rounded-ss`,`rounded-se`,`rounded-ee`,`rounded-es`,`rounded-tl`,`rounded-tr`,`rounded-br`,`rounded-bl`],"rounded-s":[`rounded-ss`,`rounded-es`],"rounded-e":[`rounded-se`,`rounded-ee`],"rounded-t":[`rounded-tl`,`rounded-tr`],"rounded-r":[`rounded-tr`,`rounded-br`],"rounded-b":[`rounded-br`,`rounded-bl`],"rounded-l":[`rounded-tl`,`rounded-bl`],"border-spacing":[`border-spacing-x`,`border-spacing-y`],"border-w":[`border-w-x`,`border-w-y`,`border-w-s`,`border-w-e`,`border-w-bs`,`border-w-be`,`border-w-t`,`border-w-r`,`border-w-b`,`border-w-l`],"border-w-x":[`border-w-r`,`border-w-l`],"border-w-y":[`border-w-t`,`border-w-b`],"border-color":[`border-color-x`,`border-color-y`,`border-color-s`,`border-color-e`,`border-color-bs`,`border-color-be`,`border-color-t`,`border-color-r`,`border-color-b`,`border-color-l`],"border-color-x":[`border-color-r`,`border-color-l`],"border-color-y":[`border-color-t`,`border-color-b`],translate:[`translate-x`,`translate-y`,`translate-none`],"translate-none":[`translate`,`translate-x`,`translate-y`,`translate-z`],"scroll-m":[`scroll-mx`,`scroll-my`,`scroll-ms`,`scroll-me`,`scroll-mbs`,`scroll-mbe`,`scroll-mt`,`scroll-mr`,`scroll-mb`,`scroll-ml`],"scroll-mx":[`scroll-mr`,`scroll-ml`],"scroll-my":[`scroll-mt`,`scroll-mb`],"scroll-p":[`scroll-px`,`scroll-py`,`scroll-ps`,`scroll-pe`,`scroll-pbs`,`scroll-pbe`,`scroll-pt`,`scroll-pr`,`scroll-pb`,`scroll-pl`],"scroll-px":[`scroll-pr`,`scroll-pl`],"scroll-py":[`scroll-pt`,`scroll-pb`],touch:[`touch-x`,`touch-y`,`touch-pz`],"touch-x":[`touch`],"touch-y":[`touch`],"touch-pz":[`touch`]},conflictingClassGroupModifiers:{"font-size":[`leading`]},postfixLookupClassGroups:[`container-type`],orderSensitiveModifiers:[`*`,`**`,`after`,`backdrop`,`before`,`details-content`,`file`,`first-letter`,`first-line`,`marker`,`placeholder`,`selection`]}});function Qy(...e){return Zy(Sv(e))}var $y=Tv(`inline-flex min-h-[var(--control-height)] items-center justify-center gap-[var(--space-2)] rounded-[var(--radius-control)] px-[var(--space-4)] [font-size:var(--text-sm)] leading-[var(--leading-tight)] font-semibold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--surface)] disabled:pointer-events-none disabled:opacity-50`,{variants:{variant:{primary:`bg-[var(--accent)] text-white hover:bg-[var(--accent-strong)]`,secondary:`border border-[var(--border)] bg-[var(--surface-raised)] text-[var(--text)] hover:bg-[var(--surface-hover)]`,danger:`bg-[var(--danger)] text-white hover:brightness-95`,ghost:`text-[var(--muted)] hover:bg-[var(--surface-hover)] hover:text-[var(--text)]`},size:{default:`h-[var(--control-height)]`,compact:`h-9 min-h-9 px-[var(--space-3)]`,icon:`h-10 w-10 px-0`}},defaultVariants:{variant:`primary`,size:`default`}}),X=(0,m.forwardRef)(function({asChild:e=!1,className:t,variant:n,size:r,...i},a){return(0,h.jsx)(e?sm:`button`,{className:Qy($y({variant:n,size:r}),t),ref:a,...i})}),eb=(0,m.forwardRef)(function({className:e,...t},n){return(0,h.jsx)(`div`,{ref:n,className:Qy(`rounded-[var(--radius-panel)] border border-[var(--border)] bg-[var(--surface-raised)] p-[var(--space-5)] [box-shadow:var(--shadow-panel)]`,e),...t})}),tb=(0,m.forwardRef)(function({className:e,...t},n){return(0,h.jsx)(`input`,{ref:n,className:Qy(`min-h-[var(--control-height)] w-full rounded-[var(--radius-control)] border border-[var(--border)] bg-[var(--input)] px-[var(--space-3)] [font-size:var(--text-sm)] leading-[var(--leading-normal)] text-[var(--text)] outline-none placeholder:text-[var(--muted)] focus-visible:ring-2 focus-visible:ring-[var(--focus)]`,e),...t})});function nb({label:e,error:t,hint:n,children:r}){return(0,h.jsxs)(`label`,{className:`grid gap-[var(--space-1)] [font-size:var(--text-sm)] leading-[var(--leading-normal)] font-medium text-[var(--text)]`,children:[(0,h.jsx)(`span`,{children:e}),r,t?(0,h.jsx)(`span`,{className:`[font-size:var(--text-xs)] text-[var(--danger)]`,role:`alert`,children:t}):null,!t&&n?(0,h.jsx)(`span`,{className:`[font-size:var(--text-xs)] font-normal text-[var(--muted)]`,children:n}):null]})}function rb({tone:e=`neutral`,children:t}){return(0,h.jsx)(`span`,{className:Qy(`inline-flex items-center rounded-full px-[var(--space-3)] py-[var(--space-1)] [font-size:var(--text-xs)] leading-[var(--leading-tight)] font-semibold`,{neutral:`bg-[var(--surface-hover)] text-[var(--muted)]`,success:`bg-[var(--success-soft)] text-[var(--success)]`,warning:`bg-[var(--warning-soft)] text-[var(--warning)]`,danger:`bg-[var(--danger-soft)] text-[var(--danger)]`}[e]),children:t})}function ib({open:e,onOpenChange:t,restoreFocus:n,title:r,description:i,children:a,footer:o,closeLabel:s,closeDisabled:c=!1}){return(0,h.jsx)(Yg,{open:e,onOpenChange:t,children:(0,h.jsxs)($g,{children:[(0,h.jsx)(t_,{className:`fixed inset-0 z-40 bg-black/50 backdrop-blur-[2px] data-[state=closed]:animate-none`}),(0,h.jsxs)(a_,{className:`fixed left-1/2 top-1/2 z-50 max-h-[90vh] w-[min(92vw,680px)] -translate-x-1/2 -translate-y-1/2 overflow-auto rounded-[var(--radius-panel)] border border-[var(--border)] bg-[var(--surface-raised)] p-[var(--space-6)] text-[var(--text)] shadow-2xl focus:outline-none`,onCloseAutoFocus:e=>{n&&(e.preventDefault(),n())},children:[(0,h.jsxs)(`div`,{className:`pr-10`,children:[(0,h.jsx)(u_,{className:`text-xl font-bold`,children:r}),i?(0,h.jsx)(f_,{className:`mt-1 text-sm text-[var(--muted)]`,children:i}):null]}),(0,h.jsx)(m_,{asChild:!0,children:(0,h.jsx)(X,{"aria-label":s,className:`absolute right-4 top-4`,disabled:c,size:`icon`,type:`button`,variant:`ghost`,children:(0,h.jsx)(Bi,{size:18})})}),(0,h.jsx)(`div`,{className:`mt-[var(--space-5)]`,children:a}),o?(0,h.jsx)(`div`,{className:`mt-[var(--space-6)] flex flex-wrap justify-end gap-[var(--space-3)]`,children:o}):null]})]})})}var ab=(0,m.createContext)(null);function ob({children:e}){let{t}=Dn(),n=(0,m.useRef)(null),[r,i]=(0,m.useState)([]),a=(0,m.useCallback)(e=>{let t=Date.now()+Math.floor(Math.random()*1e3);i(n=>[...n,{...e,id:t}])},[]),o=(0,m.useMemo)(()=>({push:a}),[a]);return(0,h.jsx)(ab.Provider,{value:o,children:(0,h.jsxs)(gv,{duration:5e3,swipeDirection:`right`,children:[e,r.map(e=>(0,h.jsx)(vv,{className:Qy(`w-[min(92vw,420px)] rounded-xl border bg-[var(--surface-raised)] text-[var(--text)] shadow-xl`,e.tone===`danger`?`border-[var(--danger)]`:e.tone===`warning`?`border-[var(--warning)]`:`border-[var(--success)]`),onOpenChange:t=>{t||i(t=>t.filter(t=>t.id!==e.id))},children:(0,h.jsxs)(`button`,{type:`button`,"aria-label":t(`common.dismissNotification`,{title:e.title}),onClick:t=>{t.currentTarget.contains(document.activeElement)&&n.current?.focus(),i(t=>t.filter(t=>t.id!==e.id))},className:`relative grid min-h-11 w-full cursor-pointer gap-[var(--space-1)] rounded-xl p-[var(--space-4)] pr-12 text-left hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--surface)]`,children:[(0,h.jsx)(yv,{asChild:!0,children:(0,h.jsx)(`span`,{className:`font-semibold`,children:e.title})}),e.description?(0,h.jsx)(bv,{asChild:!0,children:(0,h.jsx)(`span`,{className:`[font-size:var(--text-sm)] leading-[var(--leading-normal)] text-[var(--muted)]`,children:e.description})}):null,(0,h.jsx)(Bi,{"aria-hidden":`true`,size:18,className:`absolute right-4 top-4 text-[var(--muted)]`})]})},e.id)),(0,h.jsx)(_v,{ref:n,className:`fixed bottom-5 right-5 z-[60] grid gap-[var(--space-3)] outline-none`})]})})}function sb(){let e=(0,m.useContext)(ab);if(!e)throw Error(`useToast must be used inside ToastProvider.`);return e}function cb(e){return{profileId:e.id,profileRevision:e.revision}}function lb(e){let t=[`B`,`KB`,`MB`,`GB`,`TB`],n=Number.isFinite(e)?e:0,r=0;for(;n>=1024&&r=10?1:2)} ${t[r]}`}function ub(e,t=`en`){if(!e)return`—`;let n=new Date(e);return Number.isNaN(n.valueOf())?`—`:new Intl.DateTimeFormat(t,{dateStyle:`medium`,timeStyle:`medium`}).format(n)}function db(e,t){let n=t(`errors.fallback`);return e instanceof Rr?e.code===`INVALID_INPUT`&&e.dto.details?.reason===`provider-not-configured`?t(`errors.providerNotConfigured`):t(`errors.${e.code}`,{defaultValue:n}):n}function fb(e,t){return e.id==="default"?t(`profiles.defaultName`):e.name}function pb(e,t){return e===`Backup inventory refresh failed.`?t(`warnings.backupInventory`):e===`Automatic backup cleanup failed.`?t(`warnings.backupCleanup`):e===`Some encrypted histories may require their original Provider or account for continuation.`?t(`warnings.encryptedHistory`):e===`One or more rollout files are locked and may be skipped.`?t(`warnings.lockedSessions`):e===`The selected Provider has no default model; the root model will remain unchanged.`?t(`warnings.missingDefaultModel`):e===`Project visibility diagnostics are unavailable; backup-first protection remains enabled.`?t(`warnings.projectVisibility`):e===`SQLite Home relocation is confirmed; config.toml will not be restored.`?t(`warnings.relocationConfig`):/^Restore skipped /.test(e)?t(`warnings.restoreSkipped`):t(e===`The operation made only part of the requested change. Retry it to converge, or restore the managed backup.`?`warnings.partial`:`warnings.additional`)}function mb({title:e,subtitle:t,action:n,headingRef:r,headingTabIndex:i}){return(0,h.jsxs)(`div`,{className:`mb-[var(--space-6)] flex flex-wrap items-start justify-between gap-[var(--space-4)]`,children:[(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`h1`,{className:`[font-size:var(--text-2xl)] leading-[var(--leading-tight)] font-bold tracking-tight text-[var(--text)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus)]`,ref:r,tabIndex:i,children:e}),(0,h.jsx)(`p`,{className:`mt-[var(--space-1)] max-w-3xl [font-size:var(--text-sm)] leading-[var(--leading-relaxed)] text-[var(--muted)]`,children:t})]}),n]})}function hb({label:e,value:t,mono:n=!1}){return(0,h.jsxs)(`div`,{className:`grid gap-1 border-b border-[var(--border)] py-3 last:border-0 sm:grid-cols-[180px_1fr]`,children:[(0,h.jsx)(`dt`,{className:`text-sm text-[var(--muted)]`,children:e}),(0,h.jsx)(`dd`,{className:Qy(`min-w-0 break-words text-sm font-medium text-[var(--text)]`,n&&`font-mono text-xs`),children:t})]})}function gb(e){let t=e?.metadata.capturedTargetKinds,n=!!e&&t===void 0,r=t&&typeof t==`object`&&!Array.isArray(t)?t:{};return{restoreConfig:n||r.config===!0||r.globalState===!0,restoreDatabase:n||r.sqlite===!0,restoreSessions:n||r.rollout===!0}}function _b({backup:e,selected:t,onSelect:n}){let r=(0,h.jsxs)(m.Fragment,{children:[(0,h.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,h.jsx)(`span`,{className:`font-mono text-xs font-semibold`,children:e.backupId}),(0,h.jsx)(rb,{children:lb(e.sizeBytes)})]}),e.createdAt?(0,h.jsx)(`div`,{className:`mt-2 text-xs text-[var(--muted)]`,children:ub(e.createdAt)}):null]}),i=Qy(`w-full rounded-lg border p-4 text-left`,t?`border-[var(--accent)] bg-[var(--accent-soft)]`:`border-[var(--border)]`);return n?(0,h.jsx)(`button`,{"aria-pressed":t,className:Qy(i,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus)] hover:bg-[var(--surface-hover)]`),onClick:n,type:`button`,children:r}):(0,h.jsx)(`div`,{className:i,children:r})}function vb({profile:e,profiles:t,backups:n,loading:r,refreshing:i=!1,error:a,refresh:o,disabled:s,canRestore:c,canPrune:l,initialBackupId:u,retentionCount:d=2,saveRetention:f,prepare:p,prune:g}){let{t:_}=Dn(),v=Co({resolver:No(gp),defaultValues:{backupId:``,restoreConfig:!1,restoreDatabase:!1,restoreSessions:!1,allowSqliteHomeRelocation:!1,relocationTargetProfileId:``}}),y=v.watch(`allowSqliteHomeRelocation`),b=v.watch(`restoreDatabase`),x=d,[S,C]=(0,m.useState)(String(d)),[w,T]=(0,m.useState)(!1),[E,D]=(0,m.useState)(null),O=/^\d+$/.test(S)?Number(S):NaN,ee=fp.safeParse(O).success,k=S!==String(d);(0,m.useEffect)(()=>{C(String(d))},[d]);let[A,j]=(0,m.useState)(null),M=(0,m.useRef)(null),N=(0,m.useRef)(null),P=JSON.stringify([e.id,e.revision,x,n.map(({backupId:e,createdAt:t,sizeBytes:n})=>[e,t,n]).sort((e,t)=>String(e[0]).localeCompare(String(t[0])))]),F=Number.isInteger(x)&&x>=0&&x<=1e3,te=e=>_(`ux.pruneEstimate`,{remove:Math.max(0,n.length-e),keep:Math.min(n.length,e)}),ne=(0,m.useRef)(null),re=v.watch(`backupId`),ie=n.find(e=>e.backupId===re),I=gb(ie),L=s||r||i||!!a;return(0,m.useEffect)(()=>{v.setValue(`restoreConfig`,I.restoreConfig&&!v.getValues(`allowSqliteHomeRelocation`)),v.setValue(`restoreDatabase`,I.restoreDatabase),v.setValue(`restoreSessions`,I.restoreSessions),v.clearErrors()},[v,re,I.restoreConfig,I.restoreDatabase,I.restoreSessions]),(0,m.useEffect)(()=>{y&&v.setValue(`restoreConfig`,!1),v.clearErrors(`relocationTargetProfileId`)},[v,y]),(0,m.useEffect)(()=>{b||v.setValue(`allowSqliteHomeRelocation`,!1)},[v,b]),(0,m.useEffect)(()=>{u&&v.setValue(`backupId`,u,{shouldValidate:!0})},[v,u]),(0,h.jsxs)(m.Fragment,{children:[(0,h.jsx)(mb,{title:_(`backups.title`),subtitle:_(`backups.subtitle`),action:o?(0,h.jsxs)(X,{disabled:r||i,onClick:o,type:`button`,variant:`secondary`,children:[(0,h.jsx)(U,{size:16}),_(`common.refresh`)]}):void 0}),l?(0,h.jsxs)(eb,{className:`mb-4`,children:[(0,h.jsx)(`h2`,{className:`font-semibold`,children:_(`backupPolicy.title`)}),(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:_(`backupPolicy.scope`)}),(0,h.jsx)(`p`,{className:`mt-2 text-sm`,children:_(`backupPolicy.current`,{count:x})}),f?(0,h.jsxs)(`form`,{className:`mt-3 flex flex-wrap items-end gap-3`,onSubmit:async e=>{if(e.preventDefault(),!(!ee||!k||L||w)){T(!0),D(null);try{D(await f(O))}catch{D(`failed`)}finally{T(!1)}}},children:[(0,h.jsx)(nb,{label:_(`backupPolicy.count`),error:ee?void 0:_(`validation.keep`),children:(0,h.jsx)(tb,{min:1,max:1e3,type:`number`,value:S,disabled:L||w,onChange:e=>{C(e.target.value),D(null)}})}),(0,h.jsx)(X,{type:`submit`,disabled:!k||!ee||L||w,children:_(w?`common.loading`:`backupPolicy.save`)})]}):null,(0,h.jsx)(`p`,{className:`mt-3 text-xs text-[var(--muted)]`,children:_(`backupPolicy.hint`)}),E?(0,h.jsx)(`p`,{className:`mt-2 text-sm`,role:E===`saved`?`status`:`alert`,children:_(`backupPolicy.${E}`)}):null]}):null,u&&!r&&!a&&!n.some(e=>e.backupId===u)?(0,h.jsx)(`p`,{className:`mb-4 text-sm text-[var(--warning)]`,role:`alert`,children:_(`backups.requestedMissing`)}):null,(0,h.jsxs)(`div`,{className:Qy(`grid gap-4`,(c||l)&&`xl:grid-cols-[minmax(0,1fr)_minmax(320px,440px)]`),children:[(0,h.jsxs)(eb,{children:[(0,h.jsx)(`div`,{className:`grid gap-3`,children:r?(0,h.jsx)(`span`,{className:`text-sm text-[var(--muted)]`,children:_(`common.loading`)}):a?(0,h.jsxs)(`div`,{className:`grid justify-items-start gap-3`,children:[(0,h.jsxs)(`p`,{className:`text-sm text-[var(--danger)]`,role:`alert`,children:[_(`backups.loadFailed`),` `,db(a,_)]}),o?(0,h.jsx)(X,{disabled:i,onClick:o,type:`button`,variant:`secondary`,children:_(`common.retry`)}):null]}):n.length===0?(0,h.jsx)(`span`,{className:`text-sm text-[var(--muted)]`,children:_(`backups.empty`)}):n.map(e=>(0,h.jsx)(_b,{backup:e,onSelect:c?()=>v.setValue(`backupId`,e.backupId,{shouldValidate:!0}):void 0,selected:c&&re===e.backupId},e.backupId))}),!c&&!l?(0,h.jsx)(`p`,{className:`mt-4 text-xs text-[var(--muted)]`,children:_(`backups.readOnly`)}):null]}),c||l?(0,h.jsxs)(`div`,{className:`grid content-start gap-4`,children:[c?(0,h.jsx)(eb,{children:(0,h.jsx)(`form`,{onSubmit:v.handleSubmit(e=>p(e,ne.current)),children:(0,h.jsxs)(`fieldset`,{className:`grid gap-4`,disabled:L||v.formState.isSubmitting||!ie,children:[(0,h.jsx)(`p`,{className:`text-xs text-[var(--muted)]`,children:_(ie?`backups.capturedHint`:`backups.selectBackup`)}),[`restoreConfig`,`restoreDatabase`,`restoreSessions`].map(e=>(0,h.jsxs)(`label`,{className:`flex items-center gap-3 text-sm`,children:[(0,h.jsx)(`input`,{className:`h-4 w-4 accent-[var(--accent)]`,type:`checkbox`,disabled:!I[e]||e===`restoreConfig`&&y,...v.register(e)}),_(`backups.${e}`)]},e)),(0,h.jsxs)(`label`,{className:`flex items-center gap-3 text-sm`,children:[(0,h.jsx)(`input`,{className:`h-4 w-4 accent-[var(--accent)]`,type:`checkbox`,disabled:!b,...v.register(`allowSqliteHomeRelocation`)}),_(`backups.relocation`)]}),y?(0,h.jsx)(nb,{error:v.formState.errors.relocationTargetProfileId?_(`backups.relocationTargetRequired`):void 0,label:_(`backups.targetProfile`),children:(0,h.jsxs)(`select`,{"aria-label":_(`backups.targetProfile`),"aria-invalid":!!v.formState.errors.relocationTargetProfileId,className:`min-h-10 rounded-lg border border-[var(--border)] bg-[var(--input)] px-3`,...v.register(`relocationTargetProfileId`),children:[(0,h.jsx)(`option`,{value:``,children:`—`}),t.filter(t=>t.id!==e.id&&(!!t.sqliteHome||t.sqliteHomeConfigured===!0)).map(e=>(0,h.jsx)(`option`,{value:e.id,children:fb(e,_)},e.id))]})}):null,y?(0,h.jsx)(`p`,{className:`text-xs text-[var(--muted)]`,children:_(`backups.relocationHint`)}):null,v.formState.errors.restoreSessions?(0,h.jsx)(`span`,{className:`text-xs text-[var(--danger)]`,role:`alert`,children:_(`validation.restore`)}):null,(0,h.jsxs)(X,{ref:ne,type:`submit`,children:[(0,h.jsx)(ci,{size:17}),_(`backups.prepare`)]})]})})}):null,l?(0,h.jsxs)(eb,{children:[(0,h.jsx)(`p`,{className:`text-sm font-medium`,children:_(`backupPolicy.current`,{count:x})}),!L&&F?(0,h.jsx)(`p`,{className:`mt-3 text-sm`,children:te(x)}):null,(0,h.jsx)(`p`,{className:`mt-2 text-xs text-[var(--muted)]`,children:_(`ux.pruneCaution`)}),(0,h.jsx)(X,{ref:M,className:`mt-4 w-full`,disabled:L||!F||k||w,onClick:e=>{N.current=e.currentTarget,j({keep:x,revision:P})},type:`button`,variant:`secondary`,children:_(`backups.prune`)}),(0,h.jsxs)(`details`,{className:`mt-3 text-sm`,children:[(0,h.jsx)(`summary`,{className:`cursor-pointer`,children:_(`common.advanced`)}),(0,h.jsx)(X,{className:`mt-3`,disabled:L||k||w,onClick:e=>{N.current=e.currentTarget,j({keep:0,revision:P})},type:`button`,variant:`danger`,children:_(`backupPolicy.clear`)})]})]}):null]}):null]}),(0,h.jsx)(ib,{open:!!A,onOpenChange:e=>{e||j(null)},closeLabel:_(`common.close`),title:_(`ux.pruneTitle`),description:_(`ux.pruneCaution`),restoreFocus:()=>(N.current??M.current)?.focus(),footer:(0,h.jsx)(X,{type:`button`,variant:`danger`,disabled:!l||L||!A||A.revision!==P,onClick:()=>{if(!l||!A||L||A.revision!==P)return;let e=A.keep;j(null),g(e)},children:_(`ux.pruneConfirm`)}),children:A?(0,h.jsxs)(`div`,{className:`mt-4 grid gap-3 text-sm`,children:[(0,h.jsx)(`p`,{children:te(A.keep)}),A.keep===0?(0,h.jsx)(`p`,{className:`text-[var(--danger)]`,children:_(`ux.pruneZero`)}):null,A.revision===P?null:(0,h.jsx)(`p`,{role:`alert`,children:_(`ux.pruneChanged`)})]}):null})]})}var yb=async e=>{await navigator.clipboard.writeText(e)},bb=(0,m.createContext)(yb);function xb(){return(0,m.useContext)(bb)}function Sb(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Cb(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e;if(t.version!==1||![`no-findings`,`findings`,`inconclusive`,`findings-and-inconclusive`].includes(String(t.outcome))||!t.counts||typeof t.counts!=`object`||Array.isArray(t.counts)||!t.skipped||typeof t.skipped!=`object`||Array.isArray(t.skipped)||!t.displayIndex||typeof t.displayIndex!=`object`||Array.isArray(t.displayIndex)||!Array.isArray(t.issues)||!t.limits||typeof t.limits!=`object`||Array.isArray(t.limits)||!Object.values(t.counts).every(Sb)||!Object.values(t.skipped).every(Sb)||!Object.values(t.limits).every(Sb))return null;let n=t.displayIndex;return n.status!==`unsupported`||n.reason!==`no-known-display-index-schema`||!t.issues.every(e=>e&&typeof e==`object`&&!Array.isArray(e)&&typeof e.code==`string`)?null:t}function wb({historyIntegrity:e}){let{t}=Dn(),n=xb(),[r,i]=(0,m.useState)(null),a=Cb(e);if(!a)return null;let o=a.issues.slice(0,20),s=a.issuesTruncated===!0||a.issues.length>o.length,c=a.outcome===`no-findings`?`success`:a.outcome===`findings`?`warning`:`neutral`;return(0,h.jsxs)(eb,{className:`mt-4 max-w-3xl`,children:[(0,h.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,h.jsx)(`h2`,{className:`font-semibold`,children:t(`diagnostics.historyIntegrity.title`)}),(0,h.jsx)(rb,{tone:c,children:t(`diagnostics.historyIntegrity.outcomes.${a.outcome}`)})]}),(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:t(`diagnostics.historyIntegrity.scope`)}),(0,h.jsx)(`p`,{className:`mt-2 rounded-[var(--radius-control)] border border-[var(--border)] bg-[var(--surface)] p-3 text-sm`,children:t(`diagnostics.historyIntegrity.displayIndexUnsupported`)}),(0,h.jsx)(`dl`,{className:`mt-3 grid gap-2 text-sm sm:grid-cols-2`,children:Object.entries(a.counts).map(([e,n])=>(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:t(`diagnostics.historyIntegrity.counts.${e}`,{defaultValue:e})}),(0,h.jsx)(`dd`,{children:n})]},e))}),Object.values(a.skipped).some(e=>e>0)?(0,h.jsx)(`p`,{className:`mt-3 text-sm text-[var(--warning)]`,children:t(`diagnostics.historyIntegrity.skipped`)}):null,o.length?(0,h.jsxs)(`div`,{className:`mt-3`,children:[(0,h.jsx)(`h3`,{className:`text-sm font-semibold`,children:t(`diagnostics.historyIntegrity.findings`)}),(0,h.jsx)(`ul`,{className:`mt-2 list-disc space-y-2 pl-5 text-sm`,children:o.map((e,a)=>(0,h.jsxs)(`li`,{children:[(0,h.jsx)(`span`,{children:t(`diagnostics.historyIntegrity.issueCodes.${e.code}`,{defaultValue:t(`diagnostics.historyIntegrity.manualReview`)})}),e.sessionId?(0,h.jsxs)(`span`,{className:`ml-1 text-[var(--muted)]`,children:[`· `,t(`diagnostics.historyIntegrity.session`,{sessionId:e.sessionId}),e.line?` · ${t(`diagnostics.historyIntegrity.line`,{line:e.line})}`:``]}):e.line?(0,h.jsxs)(`span`,{className:`ml-1 text-[var(--muted)]`,children:[`· `,t(`diagnostics.historyIntegrity.line`,{line:e.line})]}):null,e.sessionId?(0,h.jsx)(X,{"aria-label":t(`diagnostics.historyIntegrity.copySessionId`),className:`ml-2 align-middle`,onClick:()=>{n(e.sessionId).then(()=>i(e.sessionId))},size:`compact`,type:`button`,variant:`ghost`,children:r===e.sessionId?t(`diagnostics.historyIntegrity.copiedSessionId`):t(`diagnostics.historyIntegrity.copySessionId`)}):null]},`${a}-${e.code}`))}),s?(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:t(`diagnostics.historyIntegrity.moreFindings`)}):null]}):null,(0,h.jsxs)(`details`,{className:`mt-3 rounded-[var(--radius-control)] border border-[var(--border)] bg-[var(--surface)] p-3 text-sm`,children:[(0,h.jsx)(`summary`,{className:`cursor-pointer font-medium`,children:t(`diagnostics.technicalDetails`)}),(0,h.jsx)(`pre`,{className:`mt-3 max-h-72 overflow-auto whitespace-pre-wrap break-words text-xs leading-5 text-[var(--muted)]`,children:JSON.stringify(a,null,2)})]})]})}function Tb(e){let[t,n]=(0,m.useState)(null),r=(0,m.useRef)(null),i=(0,m.useRef)(e);i.current=e,(0,m.useEffect)(()=>(r.current=null,n(null),()=>{r.current=null}),[e]);let a=(0,m.useCallback)(()=>{let t={};return r.current=t,n({profileKey:e,startedAt:performance.now(),progress:null}),{onRequestProgress(a){r.current===t&&i.current===e&&n(e=>e&&{...e,progress:a.progress})},finish(){r.current===t&&(r.current=null,n(null))}}},[e]);return{state:t?.profileKey===e?t:null,start:a}}function Eb({state:e}){let{t}=Dn(),[n,r]=(0,m.useState)(()=>performance.now()),i=e?.startedAt;if((0,m.useEffect)(()=>{if(i===void 0)return;r(performance.now());let e=setInterval(()=>r(performance.now()),1e3);return()=>clearInterval(e)},[i]),!e)return null;let a=e.progress,o=a?.progress===void 0?void 0:Math.round(a.progress*100),s=Math.max(0,Math.floor((n-e.startedAt)/1e3)),c=`${Math.floor(s/60)}:${String(s%60).padStart(2,`0`)}`,l=t(`requestProgress.stages.${a?.stage??`waiting`}`,{defaultValue:t(`requestProgress.working`)});return(0,h.jsxs)(`div`,{className:`mt-3 space-y-2 rounded-lg border border-[var(--border)] bg-[var(--surface)] p-3 text-sm`,"data-testid":`request-progress`,children:[(0,h.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,h.jsx)(`span`,{role:`status`,children:l}),(0,h.jsx)(`span`,{className:`tabular-nums text-[var(--muted)]`,children:t(`requestProgress.elapsed`,{time:c})})]}),(0,h.jsx)(`progress`,{"aria-label":l,className:`block h-2 w-full accent-[var(--accent)]`,max:100,value:o}),(0,h.jsxs)(`div`,{className:`flex flex-wrap justify-between gap-2 text-xs text-[var(--muted)]`,children:[a?.count===void 0?(0,h.jsx)(`span`,{children:t(`requestProgress.working`)}):(0,h.jsx)(`span`,{children:t(`requestProgress.files`,{count:a.count})}),o===void 0?null:(0,h.jsx)(`span`,{children:t(`requestProgress.stagePercent`,{percent:o})})]})]})}var Db=[`cwd`,`userEvent`,`workspaceRoots`],Ob={models:!1,cwd:!1,userEvent:!1,workspaceRoots:!1};function kb({targets:e,disabled:t,adjustment:n=!1,prepare:r,progress:i}){let{t:a}=Dn(),o=(0,m.useId)(),s=(0,m.useRef)(null),c=Co({resolver:No(hp),defaultValues:{...Ob}}),l=t||c.formState.isSubmitting;return(0,h.jsxs)(`form`,{className:`mt-4 grid gap-4`,onSubmit:c.handleSubmit(async n=>{if(t)return;let i={...Ob};for(let t of e)i[t]=n[t];await r(i,s.current)}),children:[(0,h.jsx)(`div`,{className:`grid gap-3`,children:e.map(e=>(0,h.jsxs)(`label`,{className:`grid gap-2 rounded-lg border border-[var(--border)] bg-[var(--surface)] p-3`,children:[(0,h.jsxs)(`span`,{className:`flex min-h-8 items-center gap-3`,children:[(0,h.jsx)(`input`,{"aria-label":a(`diagnostics.repairTargets.${e}`),"aria-describedby":`${o}-${e}`,"data-repair-target":e,disabled:l,type:`checkbox`,...c.register(e)}),(0,h.jsx)(`span`,{className:`font-medium`,children:a(`diagnostics.repairTargets.${e}`)})]}),(0,h.jsx)(`span`,{className:`pl-7 text-sm text-[var(--muted)]`,id:`${o}-${e}`,children:a(`diagnostics.repairTargetHints.${e}`)})]},e))}),c.formState.errors.models?(0,h.jsx)(`p`,{className:`text-sm text-[var(--danger)]`,role:`alert`,children:a(`diagnostics.repairTargetRequired`)}):null,!n&&c.watch(`workspaceRoots`)?(0,h.jsx)(`p`,{className:`text-sm text-[var(--muted)]`,children:a(`diagnostics.workspaceRootsIncludesCwd`)}):null,(0,h.jsxs)(X,{disabled:l,ref:s,type:`submit`,children:[(0,h.jsx)(zi,{size:16}),a(n?`diagnostics.previewAdjustment`:`diagnostics.prepareRepair`)]}),c.formState.isSubmitting?(0,h.jsx)(Eb,{state:i}):null]})}function Ab({diagnostics:e,fresh:t,disabled:n,prepare:r,progress:i}){let{t:a}=Dn(),o=(0,m.useRef)(null),s=e?.safety,c=t&&!n&&s?.rolloutScanComplete===!0&&s.pendingRecovery===!1&&s.operationInProgress===null&&s.lockedRolloutCount===0&&e?.storage.stateDbFound===!0&&e.storage.sqliteSupported===!0&&e.provider.sqliteCounts!==null&&typeof e.provider.sqliteCounts==`object`,l={cwd:`cwdRowsNeedingRepair`,userEvent:`userEventRowsNeedingRepair`,workspaceRoots:`workspaceRootsNeedingRepair`},u=c?Db.flatMap(t=>{let n=e?.issues[l[t]];return typeof n==`number`&&Number.isSafeInteger(n)&&n>0?[{target:t,count:n}]:[]}):[];return(0,h.jsxs)(`div`,{className:`mt-4 grid max-w-3xl gap-4`,children:[u.length?(0,h.jsxs)(eb,{children:[(0,h.jsx)(`h2`,{className:`font-semibold`,children:a(`diagnostics.availableRepairs`)}),(0,h.jsx)(`ul`,{className:`mt-3 grid gap-3`,children:u.map(({target:e,count:t})=>(0,h.jsxs)(`li`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,h.jsx)(`span`,{className:`text-sm`,children:a(`diagnostics.findings.${e}`,{count:t})}),(0,h.jsx)(X,{"aria-label":a(`diagnostics.viewSpecificRepair`,{target:a(`diagnostics.repairTargets.${e}`)}),onClick:()=>{n||!o.current||(o.current.open=!0,o.current.querySelector(`input[data-repair-target="${e}"]`)?.focus())},type:`button`,variant:`secondary`,children:a(`diagnostics.viewRepair`)})]},e))})]}):null,(0,h.jsx)(eb,{children:(0,h.jsxs)(`details`,{ref:o,children:[(0,h.jsx)(`summary`,{className:`cursor-pointer font-semibold focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--accent)]`,children:a(`diagnostics.repairTitle`)}),(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:a(`diagnostics.repairHint`)}),(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:a(`diagnostics.repairScope`)}),(0,h.jsx)(kb,{progress:i,disabled:n,targets:Db,prepare:r})]})}),(0,h.jsx)(eb,{children:(0,h.jsxs)(`details`,{children:[(0,h.jsx)(`summary`,{className:`cursor-pointer font-semibold focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--accent)]`,children:a(`diagnostics.adjustmentTitle`)}),(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:a(`diagnostics.adjustmentHint`)}),(0,h.jsx)(kb,{progress:i,adjustment:!0,disabled:n,targets:[`models`],prepare:r})]})})]})}function jb({diagnostics:e,error:t,expired:n=!1,loading:r,exporting:i,canExport:a,canRepair:o,repairDisabled:s,refresh:c,exportBundle:l,prepareRepair:u,scanProgress:d,repairProgress:f}){let{t:p,i18n:g}=Dn(),_=e?[[`runtime`,e.runtime],[`storage`,e.storage],[`provider`,e.provider],[`issues`,e.issues],[`safety`,e.safety]]:[],v=e=>e==null||e===``?p(`common.none`):typeof e==`boolean`?(0,h.jsx)(rb,{tone:e?`success`:`neutral`,children:p(e?`common.yes`:`common.no`)}):typeof e==`string`||typeof e==`number`?String(e):Array.isArray(e)?p(`diagnostics.items`,{count:e.length}):typeof e==`object`?p(`diagnostics.fieldsAvailable`,{count:Object.keys(e).length}):p(`common.unknown`);return(0,h.jsxs)(m.Fragment,{children:[(0,h.jsx)(mb,{title:p(`diagnostics.title`),subtitle:p(`diagnostics.subtitle`)}),(0,h.jsxs)(eb,{className:`mb-4`,children:[(0,h.jsx)(`h2`,{className:`font-semibold`,children:p(`diagnostics.scanTitle`)}),(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:p(`diagnostics.scanHint`)}),(0,h.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-2`,children:[(0,h.jsxs)(X,{disabled:r,onClick:c,type:`button`,variant:`secondary`,children:[(0,h.jsx)(U,{size:16}),p(r?`common.loading`:t?`diagnostics.retryScan`:`diagnostics.runScan`)]}),a?(0,h.jsxs)(X,{disabled:i||r||!!t||!e,onClick:l,type:`button`,variant:`secondary`,children:[(0,h.jsx)(ci,{size:16}),p(i?`diagnostics.exporting`:`diagnostics.export`)]}):null]}),r?(0,h.jsx)(`p`,{className:`mt-3 text-sm text-[var(--muted)]`,role:`status`,children:p(`diagnostics.scanning`)}):t?(0,h.jsxs)(`div`,{className:`mt-3 rounded-lg border border-[var(--danger)] p-3 text-sm`,role:`alert`,children:[(0,h.jsx)(`p`,{className:`font-semibold`,children:p(`diagnostics.scanFailed`)}),(0,h.jsx)(`p`,{children:db(t,p)}),(0,h.jsx)(`p`,{children:p(`diagnostics.scanFailedHint`)})]}):e?null:(0,h.jsx)(`p`,{className:`mt-3 text-sm text-[var(--muted)]`,children:p(`diagnostics.notScanned`)}),r?(0,h.jsx)(Eb,{state:d}):null,e?(0,h.jsx)(`p`,{className:`mt-3 text-sm text-[var(--muted)]`,children:p(t||r?`diagnostics.previousResult`:n?`diagnostics.expiredResult`:`diagnostics.scanCompleted`,{time:ub(e.generatedAt,g.language)})}):null,e?.safety.rolloutScanComplete===!1&&!r&&!t?(0,h.jsx)(`p`,{className:`mt-3 text-sm text-[var(--warning)]`,role:`status`,children:p(`diagnostics.incompleteScan`)}):null]}),(0,h.jsx)(`div`,{className:`grid gap-4 lg:grid-cols-2`,children:_.map(([e,t])=>(0,h.jsxs)(eb,{children:[(0,h.jsx)(`h2`,{className:`mb-2 font-semibold`,children:p(`diagnostics.${e}`)}),e===`issues`?(0,h.jsxs)(`div`,{className:`mb-3 space-y-2 text-sm text-[var(--muted)]`,children:[(0,h.jsx)(`p`,{children:p(`diagnostics.issuesHint`)}),(0,h.jsx)(`p`,{children:p(`diagnostics.modelDifferenceHint`)}),(0,h.jsx)(`p`,{children:p(`diagnostics.workspaceCountHint`)}),(0,h.jsx)(`p`,{children:p(`diagnostics.encryptedHint`)})]}):null,(0,h.jsx)(`dl`,{children:Object.entries(t).map(([e,t])=>(0,h.jsx)(hb,{label:p(`diagnostics.fields.${e}`,{defaultValue:e}),value:v(t)},e))}),(0,h.jsxs)(`details`,{className:`mt-3 rounded-[var(--radius-control)] border border-[var(--border)] bg-[var(--surface)] p-3 text-sm`,children:[(0,h.jsx)(`summary`,{className:`cursor-pointer font-medium`,children:p(`diagnostics.technicalDetails`)}),(0,h.jsx)(`pre`,{className:`mt-3 max-h-72 overflow-auto whitespace-pre-wrap break-words text-xs leading-5 text-[var(--muted)]`,children:JSON.stringify(t,null,2)})]})]},e))}),e?(0,h.jsx)(wb,{historyIntegrity:e.historyIntegrity}):null,o?(0,h.jsx)(Ab,{progress:f,diagnostics:e,fresh:!!e&&!t&&!n&&!r,disabled:s,prepare:u}):null]})}function Mb(e,t){let n=t||{};return(e[e.length-1]===``?[...e,``]:e).join((n.padRight?` `:``)+`,`+(n.padLeft===!1?``:` `)).trim()}var Nb=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Pb=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Fb={};function Ib(e,t){return((t||Fb).jsx?Pb:Nb).test(e)}var Lb=/[ \t\n\f\r]/g;function Rb(e){return typeof e==`object`?e.type===`text`&&zb(e.value):zb(e)}function zb(e){return e.replace(Lb,``)===``}var Bb=class{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}};Bb.prototype.normal={},Bb.prototype.property={},Bb.prototype.space=void 0;function Vb(e,t){let n={},r={};for(let t of e)Object.assign(n,t.property),Object.assign(r,t.normal);return new Bb(n,r,t)}function Hb(e){return e.toLowerCase()}var Ub=class{constructor(e,t){this.attribute=t,this.property=e}};Ub.prototype.attribute=``,Ub.prototype.booleanish=!1,Ub.prototype.boolean=!1,Ub.prototype.commaOrSpaceSeparated=!1,Ub.prototype.commaSeparated=!1,Ub.prototype.defined=!1,Ub.prototype.mustUseProperty=!1,Ub.prototype.number=!1,Ub.prototype.overloadedBoolean=!1,Ub.prototype.property=``,Ub.prototype.spaceSeparated=!1,Ub.prototype.space=void 0;var Wb=s({boolean:()=>Z,booleanish:()=>Kb,commaOrSpaceSeparated:()=>Xb,commaSeparated:()=>Yb,number:()=>Q,overloadedBoolean:()=>qb,spaceSeparated:()=>Jb}),Gb=0,Z=Zb(),Kb=Zb(),qb=Zb(),Q=Zb(),Jb=Zb(),Yb=Zb(),Xb=Zb();function Zb(){return 2**++Gb}var Qb=Object.keys(Wb),$b=class extends Ub{constructor(e,t,n,r){let i=-1;if(super(e,t),ex(this,`space`,r),typeof n==`number`)for(;++i4&&n.slice(0,4)===`data`&&px.test(t)){if(t.charAt(4)===`-`){let e=t.slice(5).replace(fx,gx);r=`data`+e.charAt(0).toUpperCase()+e.slice(1)}else{let e=t.slice(4);if(!fx.test(e)){let n=e.replace(dx,hx);n.charAt(0)!==`-`&&(n=`-`+n),t=`data`+n}}i=$b}return new i(r,t)}function hx(e){return`-`+e.toLowerCase()}function gx(e){return e.charAt(1).toUpperCase()}var _x=Vb([nx,ax,sx,cx,lx],`html`),vx=Vb([nx,ox,sx,cx,lx],`svg`);function yx(e){return e.join(` `).trim()}var bx=o(((e,t)=>{var n=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,r=/\n/g,i=/^\s*/,a=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,o=/^:\s*/,s=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,l=/^\s+|\s+$/g;function u(e,t){if(typeof e!=`string`)throw TypeError(`First argument must be a string`);if(!e)return[];t||={};var l=1,u=1;function f(e){var t=e.match(r);t&&(l+=t.length);var n=e.lastIndexOf(` -`);u=~n?e.length-n:u+e.length}function p(){var e={line:l,column:u};return function(t){return t.position=new m(e),_(),t}}function m(e){this.start=e,this.end={line:l,column:u},this.source=t.source}m.prototype.content=e;function h(n){var r=Error(t.source+`:`+l+`:`+u+`: `+n);if(r.reason=n,r.filename=t.source,r.line=l,r.column=u,r.source=e,!t.silent)throw r}function g(t){var n=t.exec(e);if(n){var r=n[0];return f(r),e=e.slice(r.length),n}}function _(){g(i)}function v(e){var t;for(e||=[];t=y();)t!==!1&&e.push(t);return e}function y(){var t=p();if(e.charAt(0)==`/`&&e.charAt(1)==`*`){for(var n=2;e.charAt(n)!=``&&(e.charAt(n)!=`*`||e.charAt(n+1)!=`/`);)++n;if(n+=2,e.charAt(n-1)===``)return h(`End of comment missing`);var r=e.slice(2,n-2);return u+=2,f(r),e=e.slice(n),u+=2,t({type:`comment`,comment:r})}}function b(){var e=p(),t=g(a);if(t){if(y(),!g(o))return h(`property missing ':'`);var r=g(s),i=e({type:`declaration`,property:d(t[0].replace(n,``)),value:r?d(r[0].replace(n,``)):``});return g(c),i}}function x(){var e=[];v(e);for(var t;t=b();)t!==!1&&(e.push(t),v(e));return e}return _(),x()}function d(e){return e?e.replace(l,``):``}t.exports=u})),xx=o((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.default=r;var n=t(bx());function r(e,t){let r=null;if(!e||typeof e!=`string`)return r;let i=(0,n.default)(e),a=typeof t==`function`;return i.forEach(e=>{if(e.type!==`declaration`)return;let{property:n,value:i}=e;a?t(n,i,e):i&&(r||={},r[n]=i)}),r}})),Sx=o((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.camelCase=void 0;var t=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,r=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(e){return!e||r.test(e)||t.test(e)},s=function(e,t){return t.toUpperCase()},c=function(e,t){return`${t}-`};e.camelCase=function(e,t){return t===void 0&&(t={}),o(e)?e:(e=e.toLowerCase(),e=t.reactCompat?e.replace(a,c):e.replace(i,c),e.replace(n,s))}})),Cx=o(((e,t)=>{var n=(e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(xx()),r=Sx();function i(e,t){var i={};return!e||typeof e!=`string`||(0,n.default)(e,function(e,n){e&&n&&(i[(0,r.camelCase)(e,t)]=n)}),i}i.default=i,t.exports=i})),wx=Ex(`end`),Tx=Ex(`start`);function Ex(e){return t;function t(t){let n=t&&t.position&&t.position[e]||{};if(typeof n.line==`number`&&n.line>0&&typeof n.column==`number`&&n.column>0)return{line:n.line,column:n.column,offset:typeof n.offset==`number`&&n.offset>-1?n.offset:void 0}}}function Dx(e){let t=Tx(e),n=wx(e);if(t&&n)return{start:t,end:n}}function Ox(e){return!e||typeof e!=`object`?``:`position`in e||`type`in e?Ax(e.position):`start`in e||`end`in e?Ax(e):`line`in e||`column`in e?kx(e):``}function kx(e){return jx(e&&e.line)+`:`+jx(e&&e.column)}function Ax(e){return kx(e&&e.start)+`-`+kx(e&&e.end)}function jx(e){return e&&typeof e==`number`?e:1}var Mx=class extends Error{constructor(e,t,n){super(),typeof t==`string`&&(n=t,t=void 0);let r=``,i={},a=!1;if(t&&(i=`line`in t&&`column`in t||`start`in t&&`end`in t?{place:t}:`type`in t?{ancestors:[t],place:t.position}:{...t}),typeof e==`string`?r=e:!i.cause&&e&&(a=!0,r=e.message,i.cause=e),!i.ruleId&&!i.source&&typeof n==`string`){let e=n.indexOf(`:`);e===-1?i.ruleId=n:(i.source=n.slice(0,e),i.ruleId=n.slice(e+1))}if(!i.place&&i.ancestors&&i.ancestors){let e=i.ancestors[i.ancestors.length-1];e&&(i.place=e.position)}let o=i.place&&`start`in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file=``,this.message=r,this.line=o?o.line:void 0,this.name=Ox(i.place)||`1:1`,this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=a&&i.cause&&typeof i.cause.stack==`string`?i.cause.stack:``,this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}};Mx.prototype.file=``,Mx.prototype.name=``,Mx.prototype.reason=``,Mx.prototype.message=``,Mx.prototype.stack=``,Mx.prototype.column=void 0,Mx.prototype.line=void 0,Mx.prototype.ancestors=void 0,Mx.prototype.cause=void 0,Mx.prototype.fatal=void 0,Mx.prototype.place=void 0,Mx.prototype.ruleId=void 0,Mx.prototype.source=void 0;var Nx=l(Cx(),1),Px={}.hasOwnProperty,Fx=new Map,Ix=/[A-Z]/g,Lx=new Set([`table`,`tbody`,`thead`,`tfoot`,`tr`]),Rx=new Set([`td`,`th`]),zx=`https://github.com/syntax-tree/hast-util-to-jsx-runtime`;function Bx(e,t){if(!t||t.Fragment===void 0)throw TypeError("Expected `Fragment` in options");let n=t.filePath||void 0,r;if(t.development){if(typeof t.jsxDEV!=`function`)throw TypeError("Expected `jsxDEV` in options when `development: true`");r=Zx(n,t.jsxDEV)}else{if(typeof t.jsx!=`function`)throw TypeError("Expected `jsx` in production options");if(typeof t.jsxs!=`function`)throw TypeError("Expected `jsxs` in production options");r=Xx(n,t.jsx,t.jsxs)}let i={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||`react`,evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space===`svg`?vx:_x,stylePropertyNameCase:t.stylePropertyNameCase||`dom`,tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},a=Vx(i,e,void 0);return a&&typeof a!=`string`?a:i.create(e,i.Fragment,{children:a||void 0},void 0)}function Vx(e,t,n){if(t.type===`element`)return Hx(e,t,n);if(t.type===`mdxFlowExpression`||t.type===`mdxTextExpression`)return Ux(e,t);if(t.type===`mdxJsxFlowElement`||t.type===`mdxJsxTextElement`)return Gx(e,t,n);if(t.type===`mdxjsEsm`)return Wx(e,t);if(t.type===`root`)return Kx(e,t,n);if(t.type===`text`)return qx(e,t)}function Hx(e,t,n){let r=e.schema,i=r;t.tagName.toLowerCase()===`svg`&&r.space===`html`&&(i=vx,e.schema=i),e.ancestors.push(t);let a=rS(e,t.tagName,!1),o=Qx(e,t),s=eS(e,t);return Lx.has(t.tagName)&&(s=s.filter(function(e){return typeof e!=`string`||!Rb(e)})),Jx(e,o,a,t),Yx(o,s),e.ancestors.pop(),e.schema=r,e.create(t,a,o,n)}function Ux(e,t){if(t.data&&t.data.estree&&e.evaluater){let n=t.data.estree.body[0];return n.type,e.evaluater.evaluateExpression(n.expression)}iS(e,t.position)}function Wx(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);iS(e,t.position)}function Gx(e,t,n){let r=e.schema,i=r;t.name===`svg`&&r.space===`html`&&(i=vx,e.schema=i),e.ancestors.push(t);let a=t.name===null?e.Fragment:rS(e,t.name,!0),o=$x(e,t),s=eS(e,t);return Jx(e,o,a,t),Yx(o,s),e.ancestors.pop(),e.schema=r,e.create(t,a,o,n)}function Kx(e,t,n){let r={};return Yx(r,eS(e,t)),e.create(t,e.Fragment,r,n)}function qx(e,t){return t.value}function Jx(e,t,n,r){typeof n!=`string`&&n!==e.Fragment&&e.passNode&&(t.node=r)}function Yx(e,t){if(t.length>0){let n=t.length>1?t:t[0];n&&(e.children=n)}}function Xx(e,t,n){return r;function r(e,r,i,a){let o=Array.isArray(i.children)?n:t;return a?o(r,i,a):o(r,i)}}function Zx(e,t){return n;function n(n,r,i,a){let o=Array.isArray(i.children),s=Tx(n);return t(r,i,a,o,{columnNumber:s?s.column-1:void 0,fileName:e,lineNumber:s?s.line:void 0},void 0)}}function Qx(e,t){let n={},r,i;for(i in t.properties)if(i!==`children`&&Px.call(t.properties,i)){let a=tS(e,i,t.properties[i]);if(a){let[i,o]=a;e.tableCellAlignToStyle&&i===`align`&&typeof o==`string`&&Rx.has(t.tagName)?r=o:n[i]=o}}if(r){let t=n.style||={};t[e.stylePropertyNameCase===`css`?`text-align`:`textAlign`]=r}return n}function $x(e,t){let n={};for(let r of t.attributes)if(r.type===`mdxJsxExpressionAttribute`){if(r.data&&r.data.estree&&e.evaluater){let t=r.data.estree.body[0];t.type;let i=t.expression;i.type;let a=i.properties[0];a.type,Object.assign(n,e.evaluater.evaluateExpression(a.argument))}else iS(e,t.position)}else{let i=r.name,a;if(r.value&&typeof r.value==`object`){if(r.value.data&&r.value.data.estree&&e.evaluater){let t=r.value.data.estree.body[0];t.type,a=e.evaluater.evaluateExpression(t.expression)}else iS(e,t.position)}else a=r.value===null||r.value;n[i]=a}return n}function eS(e,t){let n=[],r=-1,i=e.passKeys?new Map:Fx;for(;++ri?0:i+t:t>i?i:t,n=n>0?n:0,r.length<1e4)o=Array.from(r),o.unshift(t,n),e.splice(...o);else for(n&&e.splice(t,n);a0?(gS(e,e.length,0,t),e):t}var vS={}.hasOwnProperty;function yS(e){let t={},n=-1;for(;++n13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)==65535||(n&65535)==65534||n>1114111?`�`:String.fromCodePoint(n)}function CS(e){return e.replace(/[\t\n\r ]+/g,` `).replace(/^ | $/g,``).toLowerCase().toUpperCase()}var wS=FS(/[A-Za-z]/),TS=FS(/[\dA-Za-z]/),ES=FS(/[#-'*+\--9=?A-Z^-~]/);function DS(e){return e!==null&&(e<32||e===127)}var OS=FS(/\d/),kS=FS(/[\dA-Fa-f]/),AS=FS(/[!-/:-@[-`{-~]/);function $(e){return e!==null&&e<-2}function jS(e){return e!==null&&(e<0||e===32)}function MS(e){return e===-2||e===-1||e===32}var NS=FS(/\p{P}|\p{S}/u),PS=FS(/\s/);function FS(e){return t;function t(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}function IS(e){let t=[],n=-1,r=0,i=0;for(;++n55295&&a<57344){let t=e.charCodeAt(n+1);a<56320&&t>56319&&t<57344?(o=String.fromCharCode(a,t),i=1):o=`�`}else o=String.fromCharCode(a);o&&=(t.push(e.slice(r,n),encodeURIComponent(o)),r=n+i+1,``),i&&=(n+=i,0)}return t.join(``)+e.slice(r)}function LS(e,t,n,r){let i=r?r-1:1/0,a=0;return o;function o(r){return MS(r)?(e.enter(n),s(r)):t(r)}function s(r){return MS(r)&&a++o))return;let n=t.events.length,a=n,s,c;for(;a--;)if(t.events[a][0]===`exit`&&t.events[a][1].type===`chunkFlow`){if(s){c=t.events[a][1].end;break}s=!0}for(_(r),e=n;er;){let r=n[i];t.containerState=r[1],r[0].exit.call(t,e)}n.length=r}function v(){i.write([null]),a=void 0,i=void 0,t.containerState._closeFlow=void 0}}function US(e,t,n){return LS(e,e.attempt(this.parser.constructs.document,t,n),`linePrefix`,this.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)}function WS(e){if(e===null||jS(e)||PS(e))return 1;if(NS(e))return 2}function GS(e,t,n){let r=[],i=-1;for(;++i1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;let d={...e[r][1].end},f={...e[n][1].start};YS(d,-c),YS(f,c),o={type:c>1?`strongSequence`:`emphasisSequence`,start:d,end:{...e[r][1].end}},s={type:c>1?`strongSequence`:`emphasisSequence`,start:{...e[n][1].start},end:f},a={type:c>1?`strongText`:`emphasisText`,start:{...e[r][1].end},end:{...e[n][1].start}},i={type:c>1?`strong`:`emphasis`,start:{...o.start},end:{...s.end}},e[r][1].end={...o.start},e[n][1].start={...s.end},l=[],e[r][1].end.offset-e[r][1].start.offset&&(l=_S(l,[[`enter`,e[r][1],t],[`exit`,e[r][1],t]])),l=_S(l,[[`enter`,i,t],[`enter`,o,t],[`exit`,o,t],[`enter`,a,t]]),l=_S(l,GS(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),l=_S(l,[[`exit`,a,t],[`enter`,s,t],[`exit`,s,t],[`exit`,i,t]]),e[n][1].end.offset-e[n][1].start.offset?(u=2,l=_S(l,[[`enter`,e[n][1],t],[`exit`,e[n][1],t]])):u=0,gS(e,r-1,n-r+3,l),n=r+l.length-u-2;break}}for(n=-1;++n0&&MS(t)?LS(e,v,`linePrefix`,a+1)(t):v(t)}function v(t){return t===null||$(t)?e.check(cC,h,b)(t):(e.enter(`codeFlowValue`),y(t))}function y(t){return t===null||$(t)?(e.exit(`codeFlowValue`),v(t)):(e.consume(t),y)}function b(n){return e.exit(`codeFenced`),t(n)}function x(e,t,n){let i=0;return a;function a(t){return e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),c}function c(t){return e.enter(`codeFencedFence`),MS(t)?LS(e,l,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):l(t)}function l(t){return t===s?(e.enter(`codeFencedFenceSequence`),u(t)):n(t)}function u(t){return t===s?(i++,e.consume(t),u):i>=o?(e.exit(`codeFencedFenceSequence`),MS(t)?LS(e,d,`whitespace`)(t):d(t)):n(t)}function d(r){return r===null||$(r)?(e.exit(`codeFencedFence`),t(r)):n(r)}}}function dC(e,t,n){let r=this;return i;function i(t){return t===null?n(t):(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),a)}function a(e){return r.parser.lazy[r.now().line]?n(e):t(e)}}var fC={name:`codeIndented`,tokenize:mC},pC={partial:!0,tokenize:hC};function mC(e,t,n){let r=this;return i;function i(t){return e.enter(`codeIndented`),LS(e,a,`linePrefix`,5)(t)}function a(e){let t=r.events[r.events.length-1];return t&&t[1].type===`linePrefix`&&t[2].sliceSerialize(t[1],!0).length>=4?o(e):n(e)}function o(t){return t===null?c(t):$(t)?e.attempt(pC,o,c)(t):(e.enter(`codeFlowValue`),s(t))}function s(t){return t===null||$(t)?(e.exit(`codeFlowValue`),o(t)):(e.consume(t),s)}function c(n){return e.exit(`codeIndented`),t(n)}}function hC(e,t,n){let r=this;return i;function i(t){return r.parser.lazy[r.now().line]?n(t):$(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),i):LS(e,a,`linePrefix`,5)(t)}function a(e){let a=r.events[r.events.length-1];return a&&a[1].type===`linePrefix`&&a[2].sliceSerialize(a[1],!0).length>=4?t(e):$(e)?i(e):n(e)}}var gC={name:`codeText`,previous:vC,resolve:_C,tokenize:yC};function _C(e){let t=e.length-4,n=3,r,i;if((e[n][1].type===`lineEnding`||e[n][1].type===`space`)&&(e[t][1].type===`lineEnding`||e[t][1].type===`space`)){for(r=n;++r=this.left.length+this.right.length)throw RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return ethis.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(e,t,n){let r=t||0;this.setCursor(Math.trunc(e));let i=this.right.splice(this.right.length-r,1/0);return n&&xC(this.left,n),i.reverse()}pop(){return this.setCursor(1/0),this.left.pop()}push(e){this.setCursor(1/0),this.left.push(e)}pushMany(e){this.setCursor(1/0),xC(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),xC(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&this.right.length===0||e<0&&this.left.length===0)){if(e=4?t(i):e.interrupt(r.parser.constructs.flow,n,t)(i)}}function kC(e,t,n,r,i,a,o,s,c){let l=c||1/0,u=0;return d;function d(t){return t===60?(e.enter(r),e.enter(i),e.enter(a),e.consume(t),e.exit(a),f):t===null||t===32||t===41||DS(t)?n(t):(e.enter(r),e.enter(o),e.enter(s),e.enter(`chunkString`,{contentType:`string`}),h(t))}function f(n){return n===62?(e.enter(a),e.consume(n),e.exit(a),e.exit(i),e.exit(r),t):(e.enter(s),e.enter(`chunkString`,{contentType:`string`}),p(n))}function p(t){return t===62?(e.exit(`chunkString`),e.exit(s),f(t)):t===null||t===60||$(t)?n(t):(e.consume(t),t===92?m:p)}function m(t){return t===60||t===62||t===92?(e.consume(t),p):p(t)}function h(i){return!u&&(i===null||i===41||jS(i))?(e.exit(`chunkString`),e.exit(s),e.exit(o),e.exit(r),t(i)):u999||l===null||l===91||l===93&&!c||l===94&&!s&&`_hiddenFootnoteSupport`in o.parser.constructs?n(l):l===93?(e.exit(a),e.enter(i),e.consume(l),e.exit(i),e.exit(r),t):$(l)?(e.enter(`lineEnding`),e.consume(l),e.exit(`lineEnding`),u):(e.enter(`chunkString`,{contentType:`string`}),d(l))}function d(t){return t===null||t===91||t===93||$(t)||s++>999?(e.exit(`chunkString`),u(t)):(e.consume(t),c||=!MS(t),t===92?f:d)}function f(t){return t===91||t===92||t===93?(e.consume(t),s++,d):d(t)}}function jC(e,t,n,r,i,a){let o;return s;function s(t){return t===34||t===39||t===40?(e.enter(r),e.enter(i),e.consume(t),e.exit(i),o=t===40?41:t,c):n(t)}function c(n){return n===o?(e.enter(i),e.consume(n),e.exit(i),e.exit(r),t):(e.enter(a),l(n))}function l(t){return t===o?(e.exit(a),c(o)):t===null?n(t):$(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),LS(e,l,`linePrefix`)):(e.enter(`chunkString`,{contentType:`string`}),u(t))}function u(t){return t===o||t===null||$(t)?(e.exit(`chunkString`),l(t)):(e.consume(t),t===92?d:u)}function d(t){return t===o||t===92?(e.consume(t),u):u(t)}}function MC(e,t){let n;return r;function r(i){return $(i)?(e.enter(`lineEnding`),e.consume(i),e.exit(`lineEnding`),n=!0,r):MS(i)?LS(e,r,n?`linePrefix`:`lineSuffix`)(i):t(i)}}var NC={name:`definition`,tokenize:FC},PC={partial:!0,tokenize:IC};function FC(e,t,n){let r=this,i;return a;function a(t){return e.enter(`definition`),o(t)}function o(t){return AC.call(r,e,s,n,`definitionLabel`,`definitionLabelMarker`,`definitionLabelString`)(t)}function s(t){return i=CS(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),t===58?(e.enter(`definitionMarker`),e.consume(t),e.exit(`definitionMarker`),c):n(t)}function c(t){return jS(t)?MC(e,l)(t):l(t)}function l(t){return kC(e,u,n,`definitionDestination`,`definitionDestinationLiteral`,`definitionDestinationLiteralMarker`,`definitionDestinationRaw`,`definitionDestinationString`)(t)}function u(t){return e.attempt(PC,d,d)(t)}function d(t){return MS(t)?LS(e,f,`whitespace`)(t):f(t)}function f(a){return a===null||$(a)?(e.exit(`definition`),r.parser.defined.push(i),t(a)):n(a)}}function IC(e,t,n){return r;function r(t){return jS(t)?MC(e,i)(t):n(t)}function i(t){return jC(e,a,n,`definitionTitle`,`definitionTitleMarker`,`definitionTitleString`)(t)}function a(t){return MS(t)?LS(e,o,`whitespace`)(t):o(t)}function o(e){return e===null||$(e)?t(e):n(e)}}var LC={name:`hardBreakEscape`,tokenize:RC};function RC(e,t,n){return r;function r(t){return e.enter(`hardBreakEscape`),e.consume(t),i}function i(r){return $(r)?(e.exit(`hardBreakEscape`),t(r)):n(r)}}var zC={name:`headingAtx`,resolve:BC,tokenize:VC};function BC(e,t){let n=e.length-2,r=3,i,a;return e[r][1].type===`whitespace`&&(r+=2),n-2>r&&e[n][1].type===`whitespace`&&(n-=2),e[n][1].type===`atxHeadingSequence`&&(r===n-1||n-4>r&&e[n-2][1].type===`whitespace`)&&(n-=r+1===n?2:4),n>r&&(i={type:`atxHeadingText`,start:e[r][1].start,end:e[n][1].end},a={type:`chunkText`,start:e[r][1].start,end:e[n][1].end,contentType:`text`},gS(e,r,n-r+1,[[`enter`,i,t],[`enter`,a,t],[`exit`,a,t],[`exit`,i,t]])),e}function VC(e,t,n){let r=0;return i;function i(t){return e.enter(`atxHeading`),a(t)}function a(t){return e.enter(`atxHeadingSequence`),o(t)}function o(t){return t===35&&r++<6?(e.consume(t),o):t===null||jS(t)?(e.exit(`atxHeadingSequence`),s(t)):n(t)}function s(n){return n===35?(e.enter(`atxHeadingSequence`),c(n)):n===null||$(n)?(e.exit(`atxHeading`),t(n)):MS(n)?LS(e,s,`whitespace`)(n):(e.enter(`atxHeadingText`),l(n))}function c(t){return t===35?(e.consume(t),c):(e.exit(`atxHeadingSequence`),s(t))}function l(t){return t===null||t===35||jS(t)?(e.exit(`atxHeadingText`),s(t)):(e.consume(t),l)}}var HC=`address.article.aside.base.basefont.blockquote.body.caption.center.col.colgroup.dd.details.dialog.dir.div.dl.dt.fieldset.figcaption.figure.footer.form.frame.frameset.h1.h2.h3.h4.h5.h6.head.header.hr.html.iframe.legend.li.link.main.menu.menuitem.nav.noframes.ol.optgroup.option.p.param.search.section.summary.table.tbody.td.tfoot.th.thead.title.tr.track.ul`.split(`.`),UC=[`pre`,`script`,`style`,`textarea`],WC={concrete:!0,name:`htmlFlow`,resolveTo:qC,tokenize:JC},GC={partial:!0,tokenize:XC},KC={partial:!0,tokenize:YC};function qC(e){let t=e.length;for(;t--&&(e[t][0]!==`enter`||e[t][1].type!==`htmlFlow`););return t>1&&e[t-2][1].type===`linePrefix`&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function JC(e,t,n){let r=this,i,a,o,s,c;return l;function l(e){return u(e)}function u(t){return e.enter(`htmlFlow`),e.enter(`htmlFlowData`),e.consume(t),d}function d(s){return s===33?(e.consume(s),f):s===47?(e.consume(s),a=!0,h):s===63?(e.consume(s),i=3,r.interrupt?t:F):wS(s)?(e.consume(s),o=String.fromCharCode(s),g):n(s)}function f(a){return a===45?(e.consume(a),i=2,p):a===91?(e.consume(a),i=5,s=0,m):wS(a)?(e.consume(a),i=4,r.interrupt?t:F):n(a)}function p(i){return i===45?(e.consume(i),r.interrupt?t:F):n(i)}function m(i){return i===`CDATA[`.charCodeAt(s++)?(e.consume(i),s===6?r.interrupt?t:O:m):n(i)}function h(t){return wS(t)?(e.consume(t),o=String.fromCharCode(t),g):n(t)}function g(s){if(s===null||s===47||s===62||jS(s)){let c=s===47,l=o.toLowerCase();return!c&&!a&&UC.includes(l)?(i=1,r.interrupt?t(s):O(s)):HC.includes(o.toLowerCase())?(i=6,c?(e.consume(s),_):r.interrupt?t(s):O(s)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(s):a?v(s):y(s))}return s===45||TS(s)?(e.consume(s),o+=String.fromCharCode(s),g):n(s)}function _(i){return i===62?(e.consume(i),r.interrupt?t:O):n(i)}function v(t){return MS(t)?(e.consume(t),v):E(t)}function y(t){return t===47?(e.consume(t),E):t===58||t===95||wS(t)?(e.consume(t),b):MS(t)?(e.consume(t),y):E(t)}function b(t){return t===45||t===46||t===58||t===95||TS(t)?(e.consume(t),b):x(t)}function x(t){return t===61?(e.consume(t),S):MS(t)?(e.consume(t),x):y(t)}function S(t){return t===null||t===60||t===61||t===62||t===96?n(t):t===34||t===39?(e.consume(t),c=t,C):MS(t)?(e.consume(t),S):w(t)}function C(t){return t===c?(e.consume(t),c=null,T):t===null||$(t)?n(t):(e.consume(t),C)}function w(t){return t===null||t===34||t===39||t===47||t===60||t===61||t===62||t===96||jS(t)?x(t):(e.consume(t),w)}function T(e){return e===47||e===62||MS(e)?y(e):n(e)}function E(t){return t===62?(e.consume(t),D):n(t)}function D(t){return t===null||$(t)?O(t):MS(t)?(e.consume(t),D):n(t)}function O(t){return t===45&&i===2?(e.consume(t),j):t===60&&i===1?(e.consume(t),M):t===62&&i===4?(e.consume(t),te):t===63&&i===3?(e.consume(t),F):t===93&&i===5?(e.consume(t),P):$(t)&&(i===6||i===7)?(e.exit(`htmlFlowData`),e.check(GC,ne,ee)(t)):t===null||$(t)?(e.exit(`htmlFlowData`),ee(t)):(e.consume(t),O)}function ee(t){return e.check(KC,k,ne)(t)}function k(t){return e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),A}function A(t){return t===null||$(t)?ee(t):(e.enter(`htmlFlowData`),O(t))}function j(t){return t===45?(e.consume(t),F):O(t)}function M(t){return t===47?(e.consume(t),o=``,N):O(t)}function N(t){if(t===62){let n=o.toLowerCase();return UC.includes(n)?(e.consume(t),te):O(t)}return wS(t)&&o.length<8?(e.consume(t),o+=String.fromCharCode(t),N):O(t)}function P(t){return t===93?(e.consume(t),F):O(t)}function F(t){return t===62?(e.consume(t),te):t===45&&i===2?(e.consume(t),F):O(t)}function te(t){return t===null||$(t)?(e.exit(`htmlFlowData`),ne(t)):(e.consume(t),te)}function ne(n){return e.exit(`htmlFlow`),t(n)}}function YC(e,t,n){let r=this;return i;function i(t){return $(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),a):n(t)}function a(e){return r.parser.lazy[r.now().line]?n(e):t(e)}}function XC(e,t,n){return r;function r(r){return e.enter(`lineEnding`),e.consume(r),e.exit(`lineEnding`),e.attempt(QS,t,n)}}var ZC={name:`htmlText`,tokenize:QC};function QC(e,t,n){let r=this,i,a,o;return s;function s(t){return e.enter(`htmlText`),e.enter(`htmlTextData`),e.consume(t),c}function c(t){return t===33?(e.consume(t),l):t===47?(e.consume(t),x):t===63?(e.consume(t),y):wS(t)?(e.consume(t),w):n(t)}function l(t){return t===45?(e.consume(t),u):t===91?(e.consume(t),a=0,m):wS(t)?(e.consume(t),v):n(t)}function u(t){return t===45?(e.consume(t),p):n(t)}function d(t){return t===null?n(t):t===45?(e.consume(t),f):$(t)?(o=d,M(t)):(e.consume(t),d)}function f(t){return t===45?(e.consume(t),p):d(t)}function p(e){return e===62?j(e):e===45?f(e):d(e)}function m(t){return t===`CDATA[`.charCodeAt(a++)?(e.consume(t),a===6?h:m):n(t)}function h(t){return t===null?n(t):t===93?(e.consume(t),g):$(t)?(o=h,M(t)):(e.consume(t),h)}function g(t){return t===93?(e.consume(t),_):h(t)}function _(t){return t===62?j(t):t===93?(e.consume(t),_):h(t)}function v(t){return t===null||t===62?j(t):$(t)?(o=v,M(t)):(e.consume(t),v)}function y(t){return t===null?n(t):t===63?(e.consume(t),b):$(t)?(o=y,M(t)):(e.consume(t),y)}function b(e){return e===62?j(e):y(e)}function x(t){return wS(t)?(e.consume(t),S):n(t)}function S(t){return t===45||TS(t)?(e.consume(t),S):C(t)}function C(t){return $(t)?(o=C,M(t)):MS(t)?(e.consume(t),C):j(t)}function w(t){return t===45||TS(t)?(e.consume(t),w):t===47||t===62||jS(t)?T(t):n(t)}function T(t){return t===47?(e.consume(t),j):t===58||t===95||wS(t)?(e.consume(t),E):$(t)?(o=T,M(t)):MS(t)?(e.consume(t),T):j(t)}function E(t){return t===45||t===46||t===58||t===95||TS(t)?(e.consume(t),E):D(t)}function D(t){return t===61?(e.consume(t),O):$(t)?(o=D,M(t)):MS(t)?(e.consume(t),D):T(t)}function O(t){return t===null||t===60||t===61||t===62||t===96?n(t):t===34||t===39?(e.consume(t),i=t,ee):$(t)?(o=O,M(t)):MS(t)?(e.consume(t),O):(e.consume(t),k)}function ee(t){return t===i?(e.consume(t),i=void 0,A):t===null?n(t):$(t)?(o=ee,M(t)):(e.consume(t),ee)}function k(t){return t===null||t===34||t===39||t===60||t===61||t===96?n(t):t===47||t===62||jS(t)?T(t):(e.consume(t),k)}function A(e){return e===47||e===62||jS(e)?T(e):n(e)}function j(r){return r===62?(e.consume(r),e.exit(`htmlTextData`),e.exit(`htmlText`),t):n(r)}function M(t){return e.exit(`htmlTextData`),e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),N}function N(t){return MS(t)?LS(e,P,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):P(t)}function P(t){return e.enter(`htmlTextData`),o(t)}}var $C={name:`labelEnd`,resolveAll:rw,resolveTo:iw,tokenize:aw},ew={tokenize:ow},tw={tokenize:sw},nw={tokenize:cw};function rw(e){let t=-1,n=[];for(;++t=3&&(a===null||$(a))?(e.exit(`thematicBreak`),t(a)):n(a)}function c(t){return t===i?(e.consume(t),r++,c):(e.exit(`thematicBreakSequence`),MS(t)?LS(e,s,`whitespace`)(t):s(t))}}var _w={continuation:{tokenize:xw},exit:Cw,name:`list`,tokenize:bw},vw={partial:!0,tokenize:ww},yw={partial:!0,tokenize:Sw};function bw(e,t,n){let r=this,i=r.events[r.events.length-1],a=i&&i[1].type===`linePrefix`?i[2].sliceSerialize(i[1],!0).length:0,o=0;return s;function s(t){let i=r.containerState.type||(t===42||t===43||t===45?`listUnordered`:`listOrdered`);if(i===`listUnordered`?!r.containerState.marker||t===r.containerState.marker:OS(t)){if(r.containerState.type||(r.containerState.type=i,e.enter(i,{_container:!0})),i===`listUnordered`)return e.enter(`listItemPrefix`),t===42||t===45?e.check(hw,n,l)(t):l(t);if(!r.interrupt||t===49)return e.enter(`listItemPrefix`),e.enter(`listItemValue`),c(t)}return n(t)}function c(t){return OS(t)&&++o<10?(e.consume(t),c):(!r.interrupt||o<2)&&(r.containerState.marker?t===r.containerState.marker:t===41||t===46)?(e.exit(`listItemValue`),l(t)):n(t)}function l(t){return e.enter(`listItemMarker`),e.consume(t),e.exit(`listItemMarker`),r.containerState.marker=r.containerState.marker||t,e.check(QS,r.interrupt?n:u,e.attempt(vw,f,d))}function u(e){return r.containerState.initialBlankLine=!0,a++,f(e)}function d(t){return MS(t)?(e.enter(`listItemPrefixWhitespace`),e.consume(t),e.exit(`listItemPrefixWhitespace`),f):n(t)}function f(n){return r.containerState.size=a+r.sliceSerialize(e.exit(`listItemPrefix`),!0).length,t(n)}}function xw(e,t,n){let r=this;return r.containerState._closeFlow=void 0,e.check(QS,i,a);function i(n){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,LS(e,t,`listItemIndent`,r.containerState.size+1)(n)}function a(n){return r.containerState.furtherBlankLines||!MS(n)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,o(n)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(yw,t,o)(n))}function o(i){return r.containerState._closeFlow=!0,r.interrupt=void 0,LS(e,e.attempt(_w,t,n),`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(i)}}function Sw(e,t,n){let r=this;return LS(e,i,`listItemIndent`,r.containerState.size+1);function i(e){let i=r.events[r.events.length-1];return i&&i[1].type===`listItemIndent`&&i[2].sliceSerialize(i[1],!0).length===r.containerState.size?t(e):n(e)}}function Cw(e){e.exit(this.containerState.type)}function ww(e,t,n){let r=this;return LS(e,i,`listItemPrefixWhitespace`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:5);function i(e){let i=r.events[r.events.length-1];return!MS(e)&&i&&i[1].type===`listItemPrefixWhitespace`?t(e):n(e)}}var Tw={name:`setextUnderline`,resolveTo:Ew,tokenize:Dw};function Ew(e,t){let n=e.length,r,i,a;for(;n--;)if(e[n][0]===`enter`){if(e[n][1].type===`content`){r=n;break}e[n][1].type===`paragraph`&&(i=n)}else e[n][1].type===`content`&&e.splice(n,1),!a&&e[n][1].type===`definition`&&(a=n);let o={type:`setextHeading`,start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[i][1].type=`setextHeadingText`,a?(e.splice(i,0,[`enter`,o,t]),e.splice(a+1,0,[`exit`,e[r][1],t]),e[r][1].end={...e[a][1].end}):e[r][1]=o,e.push([`exit`,o,t]),e}function Dw(e,t,n){let r=this,i;return a;function a(t){let a=r.events.length,s;for(;a--;)if(r.events[a][1].type!==`lineEnding`&&r.events[a][1].type!==`linePrefix`&&r.events[a][1].type!==`content`){s=r.events[a][1].type===`paragraph`;break}return!r.parser.lazy[r.now().line]&&(r.interrupt||s)?(e.enter(`setextHeadingLine`),i=t,o(t)):n(t)}function o(t){return e.enter(`setextHeadingLineSequence`),s(t)}function s(t){return t===i?(e.consume(t),s):(e.exit(`setextHeadingLineSequence`),MS(t)?LS(e,c,`lineSuffix`)(t):c(t))}function c(r){return r===null||$(r)?(e.exit(`setextHeadingLine`),t(r)):n(r)}}var Ow={tokenize:kw};function kw(e){let t=this,n=e.attempt(QS,r,e.attempt(this.parser.constructs.flowInitial,i,LS(e,e.attempt(this.parser.constructs.flow,i,e.attempt(wC,i)),`linePrefix`)));return n;function r(r){if(r===null){e.consume(r);return}return e.enter(`lineEndingBlank`),e.consume(r),e.exit(`lineEndingBlank`),t.currentConstruct=void 0,n}function i(r){if(r===null){e.consume(r);return}return e.enter(`lineEnding`),e.consume(r),e.exit(`lineEnding`),t.currentConstruct=void 0,n}}var Aw={resolveAll:Pw()},jw=Nw(`string`),Mw=Nw(`text`);function Nw(e){return{resolveAll:Pw(e===`text`?Fw:void 0),tokenize:t};function t(t){let n=this,r=this.parser.constructs[e],i=t.attempt(r,a,o);return a;function a(e){return c(e)?i(e):o(e)}function o(e){if(e===null){t.consume(e);return}return t.enter(`data`),t.consume(e),s}function s(e){return c(e)?(t.exit(`data`),i(e)):(t.consume(e),s)}function c(e){if(e===null)return!0;let t=r[e],i=-1;if(t)for(;++iWw,contentInitial:()=>Rw,disable:()=>Gw,document:()=>Lw,flow:()=>Bw,flowInitial:()=>zw,insideSpan:()=>Uw,string:()=>Vw,text:()=>Hw}),Lw={42:_w,43:_w,45:_w,48:_w,49:_w,50:_w,51:_w,52:_w,53:_w,54:_w,55:_w,56:_w,57:_w,62:eC},Rw={91:NC},zw={[-2]:fC,[-1]:fC,32:fC},Bw={35:zC,42:hw,45:[Tw,hw],60:WC,61:Tw,95:hw,96:lC,126:lC},Vw={38:oC,92:iC},Hw={[-5]:pw,[-4]:pw,[-3]:pw,33:lw,38:oC,42:KS,60:[XS,ZC],91:dw,92:[LC,iC],93:$C,95:KS,96:gC},Uw={null:[KS,Aw]},Ww={null:[42,95]},Gw={null:[]};function Kw(e,t,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0},i={},a=[],o=[],s=[],c={attempt:C(x),check:C(S),consume:v,enter:y,exit:b,interrupt:C(S,{interrupt:!0})},l={code:null,containerState:{},defineSkip:h,events:[],now:m,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:d},u=t.tokenize.call(l,c);return t.resolveAll&&a.push(t),l;function d(e){return o=_S(o,e),g(),o[o.length-1]===null?(w(t,0),l.events=GS(a,l.events,l),l.events):[]}function f(e,t){return Jw(p(e),t)}function p(e){return qw(o,e)}function m(){let{_bufferIndex:e,_index:t,line:n,column:i,offset:a}=r;return{_bufferIndex:e,_index:t,line:n,column:i,offset:a}}function h(e){i[e.line]=e.column,E()}function g(){let e;for(;r._index-1){let e=o[0];typeof e==`string`?o[0]=e.slice(r):o.shift()}a>0&&o.push(e[i].slice(0,a))}return o}function Jw(e,t){let n=-1,r=[],i;for(;++n0){let e=a.tokenStack[a.tokenStack.length-1];(e[1]||cT).call(a,void 0,e[0])}for(r.position={start:aT(e.length>0?e[0][1].start:{line:1,column:1,offset:0}),end:aT(e.length>0?e[e.length-2][1].end:{line:1,column:1,offset:0})},d=-1;++d0&&(r.className=[`language-`+i[0]]);let a={type:`element`,tagName:`code`,properties:r,children:[{type:`text`,value:n}]};return t.meta&&(a.data={meta:t.meta}),e.patch(t,a),a=e.applyData(t,a),a={type:`element`,tagName:`pre`,properties:{},children:[a]},e.patch(t,a),a}function pT(e,t){let n={type:`element`,tagName:`del`,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function mT(e,t){let n={type:`element`,tagName:`em`,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function hT(e,t){let n=typeof e.options.clobberPrefix==`string`?e.options.clobberPrefix:`user-content-`,r=String(t.identifier).toUpperCase(),i=IS(r.toLowerCase()),a=e.footnoteOrder.indexOf(r),o,s=e.footnoteCounts.get(r);s===void 0?(s=0,e.footnoteOrder.push(r),o=e.footnoteOrder.length):o=a+1,s+=1,e.footnoteCounts.set(r,s);let c={type:`element`,tagName:`a`,properties:{href:`#`+n+`fn-`+i,id:n+`fnref-`+i+(s>1?`-`+s:``),dataFootnoteRef:!0,ariaDescribedBy:[`footnote-label`]},children:[{type:`text`,value:String(o)}]};e.patch(t,c);let l={type:`element`,tagName:`sup`,properties:{},children:[c]};return e.patch(t,l),e.applyData(t,l)}function gT(e,t){let n={type:`element`,tagName:`h`+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function _T(e,t){if(e.options.allowDangerousHtml){let n={type:`raw`,value:t.value};return e.patch(t,n),e.applyData(t,n)}}function vT(e,t){let n=t.referenceType,r=`]`;if(n===`collapsed`?r+=`[]`:n===`full`&&(r+=`[`+(t.label||t.identifier)+`]`),t.type===`imageReference`)return[{type:`text`,value:`![`+t.alt+r}];let i=e.all(t),a=i[0];a&&a.type===`text`?a.value=`[`+a.value:i.unshift({type:`text`,value:`[`});let o=i[i.length-1];return o&&o.type===`text`?o.value+=r:i.push({type:`text`,value:r}),i}function yT(e,t){let n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return vT(e,t);let i={src:IS(r.url||``),alt:t.alt};r.title!==null&&r.title!==void 0&&(i.title=r.title);let a={type:`element`,tagName:`img`,properties:i,children:[]};return e.patch(t,a),e.applyData(t,a)}function bT(e,t){let n={src:IS(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);let r={type:`element`,tagName:`img`,properties:n,children:[]};return e.patch(t,r),e.applyData(t,r)}function xT(e,t){let n={type:`text`,value:t.value.replace(/\r?\n|\r/g,` `)};e.patch(t,n);let r={type:`element`,tagName:`code`,properties:{},children:[n]};return e.patch(t,r),e.applyData(t,r)}function ST(e,t){let n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return vT(e,t);let i={href:IS(r.url||``)};r.title!==null&&r.title!==void 0&&(i.title=r.title);let a={type:`element`,tagName:`a`,properties:i,children:e.all(t)};return e.patch(t,a),e.applyData(t,a)}function CT(e,t){let n={href:IS(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);let r={type:`element`,tagName:`a`,properties:n,children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function wT(e,t,n){let r=e.all(t),i=n?TT(n):ET(t),a={},o=[];if(typeof t.checked==`boolean`){let e=r[0],n;e&&e.type===`element`&&e.tagName===`p`?n=e:(n={type:`element`,tagName:`p`,properties:{},children:[]},r.unshift(n)),n.children.length>0&&n.children.unshift({type:`text`,value:` `}),n.children.unshift({type:`element`,tagName:`input`,properties:{type:`checkbox`,checked:t.checked,disabled:!0},children:[]}),a.className=[`task-list-item`]}let s=-1;for(;++s1}function DT(e,t){let n={},r=e.all(t),i=-1;for(typeof t.start==`number`&&t.start!==1&&(n.start=t.start);++i0){let r={type:`element`,tagName:`tbody`,properties:{},children:e.wrap(n,!0)},a=Tx(t.children[1]),o=wx(t.children[t.children.length-1]);a&&o&&(r.position={start:a,end:o}),i.push(r)}let a={type:`element`,tagName:`table`,properties:{},children:e.wrap(i,!0)};return e.patch(t,a),e.applyData(t,a)}function MT(e,t,n){let r=n?n.children:void 0,i=(r?r.indexOf(t):1)===0?`th`:`td`,a=n&&n.type===`table`?n.align:void 0,o=a?a.length:t.children.length,s=-1,c=[];for(;++s0,!0),r[0]),i=r.index+r[0].length,r=n.exec(t);return a.push(LT(t.slice(i),i>0,!1)),a.join(``)}function LT(e,t,n){let r=0,i=e.length;if(t){let t=e.codePointAt(r);for(;t===PT||t===FT;)r++,t=e.codePointAt(r)}if(n){let t=e.codePointAt(i-1);for(;t===PT||t===FT;)i--,t=e.codePointAt(i-1)}return i>r?e.slice(r,i):``}function RT(e,t){let n={type:`text`,value:IT(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function zT(e,t){let n={type:`element`,tagName:`hr`,properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}var BT={blockquote:uT,break:dT,code:fT,delete:pT,emphasis:mT,footnoteReference:hT,heading:gT,html:_T,imageReference:yT,image:bT,inlineCode:xT,linkReference:ST,link:CT,listItem:wT,list:DT,paragraph:OT,root:kT,strong:AT,table:jT,tableCell:NT,tableRow:MT,text:RT,thematicBreak:zT,toml:VT,yaml:VT,definition:VT,footnoteDefinition:VT};function VT(){}var{defineProperty:HT}=Object,UT=typeof self==`object`?self:globalThis,WT=(e,t)=>{switch(e){case`Function`:case`SharedWorker`:case`Worker`:case`eval`:case`setInterval`:case`setTimeout`:throw TypeError(`unable to deserialize `+e)}return new UT[e](t)},GT=(e,t)=>{let n=(t,n)=>(e.set(n,t),t),r=i=>{if(e.has(i))return e.get(i);let[a,o]=t[i];switch(a){case 0:case-1:return n(o,i);case 1:{let e=n([],i);for(let t of o)e.push(r(t));return e}case 2:{let e=n({},i);for(let[t,n]of o){let i=r(t),a=r(n);i===`__proto__`?HT(e,i,{value:a,configurable:!0,enumerable:!0,writable:!0}):e[i]=a}return e}case 3:return n(new Date(o),i);case 4:{let{source:e,flags:t}=o;return n(new RegExp(e,t),i)}case 5:{let e=n(new Map,i);for(let[t,n]of o)e.set(r(t),r(n));return e}case 6:{let e=n(new Set,i);for(let t of o)e.add(r(t));return e}case 7:{let{name:e,message:t}=o;return n(typeof UT[e]==`function`?WT(e,t):Error(t),i)}case 8:return n(BigInt(o),i);case`BigInt`:return n(Object(BigInt(o)),i);case`ArrayBuffer`:return n(new Uint8Array(o).buffer,o);case`DataView`:{let{buffer:e}=new Uint8Array(o);return n(new DataView(e),o)}case`-0`:return-0}return n(WT(a,o),i)};return r},KT=e=>GT(new Map,e)(0),qT=``,{toString:JT}={},{keys:YT,is:XT}=Object,ZT=e=>{let t=typeof e;if(t!==`object`||!e)return[0,t];let n=JT.call(e).slice(8,-1);switch(n){case`Array`:return[1,qT];case`Object`:return[2,qT];case`Date`:return[3,qT];case`RegExp`:return[4,qT];case`Map`:return[5,qT];case`Set`:return[6,qT];case`DataView`:return[1,n]}return n.includes(`Array`)?[1,n]:e instanceof Error?[7,e.name||`Error`]:[2,n]},QT=([e,t])=>e===0&&(t===`function`||t===`symbol`),$T=(e,t,n,r)=>{let i=(e,t)=>{let i=r.push(e)-1;return n.set(t,i),i},a=o=>{if(n.has(o))return n.get(o);let[s,c]=ZT(o);switch(s){case 0:{let t=o;switch(c){case`bigint`:s=8,t=o.toString();break;case`number`:if(!o&&XT(o,-0))return r.push([`-0`])-1;break;case`function`:case`symbol`:if(e)throw TypeError(`unable to serialize `+c);t=null;break;case`undefined`:return i([-1],o)}return i([s,t],o)}case 1:{if(c){let e=o;return c===`DataView`?e=new Uint8Array(o.buffer):c===`ArrayBuffer`&&(e=new Uint8Array(o)),i([c,[...e]],o)}let e=[],t=i([s,e],o);for(let t of o)e.push(a(t));return t}case 2:{if(c)switch(c){case`BigInt`:return i([c,o.toString()],o);case`Boolean`:case`Number`:case`String`:return i([c,o.valueOf()],o)}if(t&&`toJSON`in o)return a(o.toJSON());let n=[],r=i([s,n],o);for(let t of YT(o))(e||!QT(ZT(o[t])))&&n.push([a(t),a(o[t])]);return r}case 3:return i([s,isNaN(o.getTime())?qT:o.toISOString()],o);case 4:{let{source:e,flags:t}=o;return i([s,{source:e,flags:t}],o)}case 5:{let t=[],n=i([s,t],o);for(let[n,r]of o)(e||!(QT(ZT(n))||QT(ZT(r))))&&t.push([a(n),a(r)]);return n}case 6:{let t=[],n=i([s,t],o);for(let n of o)(e||!QT(ZT(n)))&&t.push(a(n));return n}}let{message:l}=o;return i([s,{name:c,message:l}],o)};return a},eE=(e,{json:t,lossy:n}={})=>{let r=[];return $T(!(t||n),!!t,new Map,r)(e),r},tE=typeof structuredClone==`function`?(e,t)=>t&&(`json`in t||`lossy`in t)?KT(eE(e,t)):structuredClone(e):(e,t)=>KT(eE(e,t));function nE(e,t){let n=[{type:`text`,value:`↩`}];return t>1&&n.push({type:`element`,tagName:`sup`,properties:{},children:[{type:`text`,value:String(t)}]}),n}function rE(e,t){return`Back to reference `+(e+1)+(t>1?`-`+t:``)}function iE(e){let t=typeof e.options.clobberPrefix==`string`?e.options.clobberPrefix:`user-content-`,n=e.options.footnoteBackContent||nE,r=e.options.footnoteBackLabel||rE,i=e.options.footnoteLabel||`Footnotes`,a=e.options.footnoteLabelTagName||`h2`,o=e.options.footnoteLabelProperties||{className:[`sr-only`]},s=[],c=-1;for(;++c0&&d.push({type:`text`,value:` `});let e=typeof n==`string`?n:n(c,u);typeof e==`string`&&(e={type:`text`,value:e}),d.push({type:`element`,tagName:`a`,properties:{href:`#`+t+`fnref-`+l+(u>1?`-`+u:``),dataFootnoteBackref:``,ariaLabel:typeof r==`string`?r:r(c,u),className:[`data-footnote-backref`]},children:Array.isArray(e)?e:[e]})}let p=a[a.length-1];if(p&&p.type===`element`&&p.tagName===`p`){let e=p.children[p.children.length-1];e&&e.type===`text`?e.value+=` `:p.children.push({type:`text`,value:` `}),p.children.push(...d)}else a.push(...d);let m={type:`element`,tagName:`li`,properties:{id:t+`fn-`+l},children:e.wrap(a,!0)};e.patch(i,m),s.push(m)}if(s.length!==0)return{type:`element`,tagName:`section`,properties:{dataFootnotes:!0,className:[`footnotes`]},children:[{type:`element`,tagName:a,properties:{...tE(o),id:`footnote-label`},children:[{type:`text`,value:i}]},{type:`text`,value:` -`},{type:`element`,tagName:`ol`,properties:{},children:e.wrap(s,!0)},{type:`text`,value:` -`}]}}var aE=(function(e){if(e==null)return uE;if(typeof e==`function`)return lE(e);if(typeof e==`object`)return Array.isArray(e)?oE(e):sE(e);if(typeof e==`string`)return cE(e);throw Error(`Expected function, string, or object as test`)});function oE(e){let t=[],n=-1;for(;++n`:``))+`)`})}return u;function u(){let l=pE,u,d,f;if((!t||a(e,i,c[c.length-1]||void 0))&&(l=hE(n(e,c)),l[0]===!1))return l;if(`children`in e&&e.children){let t=e;if(t.children&&l[0]!==`skip`)for(d=(r?t.children.length:-1)+o,f=c.concat(t);d>-1&&d0&&n.push({type:`text`,value:` -`}),n}function wE(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function TE(e,t){let n=yE(e,t),r=n.one(e,void 0),i=iE(n),a=Array.isArray(r)?{type:`root`,children:r}:r||{type:`root`,children:[]};return i&&(`children`in a,a.children.push({type:`text`,value:` -`},i)),a}function EE(e,t){return e&&`run`in e?async function(n,r){let i=TE(n,{file:r,...t});await e.run(i,r)}:function(n,r){return TE(n,{file:r,...e||t})}}function DE(e){if(e)throw e}var OE=o(((e,t)=>{var n=Object.prototype.hasOwnProperty,r=Object.prototype.toString,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=function(e){return typeof Array.isArray==`function`?Array.isArray(e):r.call(e)===`[object Array]`},s=function(e){if(!e||r.call(e)!==`[object Object]`)return!1;var t=n.call(e,`constructor`),i=e.constructor&&e.constructor.prototype&&n.call(e.constructor.prototype,`isPrototypeOf`);if(e.constructor&&!t&&!i)return!1;for(var a in e);return a===void 0||n.call(e,a)},c=function(e,t){i&&t.name===`__proto__`?i(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue},l=function(e,t){if(t===`__proto__`){if(!n.call(e,t))return;if(a)return a(e,t).value}return e[t]};t.exports=function e(){var t,n,r,i,a,u,d=arguments[0],f=1,p=arguments.length,m=!1;for(typeof d==`boolean`&&(m=d,d=arguments[1]||{},f=2),(d==null||typeof d!=`object`&&typeof d!=`function`)&&(d={});ft.length,o;r&&t.push(i);try{o=e.apply(this,t)}catch(e){let t=e;if(r&&n)throw t;return i(t)}r||(o&&o.then&&typeof o.then==`function`?o.then(a,i):o instanceof Error?i(o):a(o))}function i(e,...r){n||(n=!0,t(e,...r))}function a(e){i(null,e)}}var ME={basename:NE,dirname:PE,extname:FE,join:IE,sep:`/`};function NE(e,t){if(t!==void 0&&typeof t!=`string`)throw TypeError(`"ext" argument must be a string`);zE(e);let n=0,r=-1,i=e.length,a;if(t===void 0||t.length===0||t.length>e.length){for(;i--;)if(e.codePointAt(i)===47){if(a){n=i+1;break}}else r<0&&(a=!0,r=i+1);return r<0?``:e.slice(n,r)}if(t===e)return``;let o=-1,s=t.length-1;for(;i--;)if(e.codePointAt(i)===47){if(a){n=i+1;break}}else o<0&&(a=!0,o=i+1),s>-1&&(e.codePointAt(i)===t.codePointAt(s--)?s<0&&(r=i):(s=-1,r=o));return n===r?r=o:r<0&&(r=e.length),e.slice(n,r)}function PE(e){if(zE(e),e.length===0)return`.`;let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||=!0;return t<0?e.codePointAt(0)===47?`/`:`.`:t===1&&e.codePointAt(0)===47?`//`:e.slice(0,t)}function FE(e){zE(e);let t=e.length,n=-1,r=0,i=-1,a=0,o;for(;t--;){let s=e.codePointAt(t);if(s===47){if(o){r=t+1;break}continue}n<0&&(o=!0,n=t+1),s===46?i<0?i=t:a!==1&&(a=1):i>-1&&(a=-1)}return i<0||n<0||a===0||a===1&&i===n-1&&i===r+1?``:e.slice(i,n)}function IE(...e){let t=-1,n;for(;++t0&&e.codePointAt(e.length-1)===47&&(n+=`/`),t?`/`+n:n}function RE(e,t){let n=``,r=0,i=-1,a=0,o=-1,s,c;for(;++o<=e.length;){if(o2){if(c=n.lastIndexOf(`/`),c!==n.length-1){c<0?(n=``,r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf(`/`)),i=o,a=0;continue}}else if(n.length>0){n=``,r=0,i=o,a=0;continue}}t&&(n=n.length>0?n+`/..`:`..`,r=2)}else n.length>0?n+=`/`+e.slice(i+1,o):n=e.slice(i+1,o),r=o-i-1}i=o,a=0}else s===46&&a>-1?a++:a=-1}return n}function zE(e){if(typeof e!=`string`)throw TypeError(`Path must be a string. Received `+JSON.stringify(e))}var BE={cwd:VE};function VE(){return`/`}function HE(e){return!!(typeof e==`object`&&e&&`href`in e&&e.href&&`protocol`in e&&e.protocol&&e.auth===void 0)}function UE(e){if(typeof e==`string`)e=new URL(e);else if(!HE(e)){let t=TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code=`ERR_INVALID_ARG_TYPE`,t}if(e.protocol!==`file:`){let e=TypeError(`The URL must be of scheme file`);throw e.code=`ERR_INVALID_URL_SCHEME`,e}return WE(e)}function WE(e){if(e.hostname!==``){let e=TypeError(`File URL host must be "localhost" or empty on darwin`);throw e.code=`ERR_INVALID_FILE_URL_HOST`,e}let t=e.pathname,n=-1;for(;++n0){let[r,...a]=t,o=n[i][1];kE(o)&&kE(r)&&(r=(0,QE.default)(!0,o,r)),n[i]=[e,r,...a]}}}}().freeze();function tD(e,t){if(typeof t!=`function`)throw TypeError("Cannot `"+e+"` without `parser`")}function nD(e,t){if(typeof t!=`function`)throw TypeError("Cannot `"+e+"` without `compiler`")}function rD(e,t){if(t)throw Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function iD(e){if(!kE(e)||typeof e.type!=`string`)throw TypeError("Expected node, got `"+e+"`")}function aD(e,t,n){if(!n)throw Error("`"+e+"` finished async. Use `"+t+"` instead")}function oD(e){return sD(e)?e:new KE(e)}function sD(e){return!!(e&&typeof e==`object`&&`message`in e&&`messages`in e)}function cD(e){return typeof e==`string`||lD(e)}function lD(e){return!!(e&&typeof e==`object`&&`byteLength`in e&&`byteOffset`in e)}var uD=[],dD={allowDangerousHtml:!0},fD=/^(https?|ircs?|mailto|xmpp)$/i,pD=[{from:`astPlugins`,id:`remove-buggy-html-in-markdown-parser`},{from:`allowDangerousHtml`,id:`remove-buggy-html-in-markdown-parser`},{from:`allowNode`,id:`replace-allownode-allowedtypes-and-disallowedtypes`,to:`allowElement`},{from:`allowedTypes`,id:`replace-allownode-allowedtypes-and-disallowedtypes`,to:`allowedElements`},{from:`className`,id:`remove-classname`},{from:`disallowedTypes`,id:`replace-allownode-allowedtypes-and-disallowedtypes`,to:`disallowedElements`},{from:`escapeHtml`,id:`remove-buggy-html-in-markdown-parser`},{from:`includeElementIndex`,id:`#remove-includeelementindex`},{from:`includeNodeIndex`,id:`change-includenodeindex-to-includeelementindex`},{from:`linkTarget`,id:`remove-linktarget`},{from:`plugins`,id:`change-plugins-to-remarkplugins`,to:`remarkPlugins`},{from:`rawSourcePos`,id:`#remove-rawsourcepos`},{from:`renderers`,id:`change-renderers-to-components`,to:`components`},{from:`source`,id:`change-source-to-children`,to:`children`},{from:`sourcePos`,id:`#remove-sourcepos`},{from:`transformImageUri`,id:`#add-urltransform`,to:`urlTransform`},{from:`transformLinkUri`,id:`#add-urltransform`,to:`urlTransform`}];function mD(e){let t=hD(e),n=gD(e);return _D(t.runSync(t.parse(n),n),e)}function hD(e){let t=e.rehypePlugins||uD,n=e.remarkPlugins||uD,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...dD}:dD;return eD().use(lT).use(n).use(EE,r).use(t)}function gD(e){let t=e.children||``,n=new KE;return typeof t==`string`?n.value=t:``+t,n}function _D(e,t){let n=t.allowedElements,r=t.allowElement,i=t.components,a=t.disallowedElements,o=t.skipHtml,s=t.unwrapDisallowed,c=t.urlTransform||vD;for(let e of pD)Object.hasOwn(t,e.from)&&``+e.from+(e.to?"use `"+e.to+"` instead":`remove it`)+e.id;return gE(e,l),Bx(e,{Fragment:h.Fragment,components:i,ignoreInvalidStyle:!0,jsx:h.jsx,jsxs:h.jsxs,passKeys:!0,passNode:!0});function l(e,t,i){if(e.type===`raw`&&i&&typeof t==`number`)return o?i.children.splice(t,1):i.children[t]={type:`text`,value:e.value},t;if(e.type===`element`){let t;for(t in cS)if(Object.hasOwn(cS,t)&&Object.hasOwn(e.properties,t)){let n=e.properties[t],r=cS[t];(r===null||r.includes(e.tagName))&&(e.properties[t]=c(String(n||``),t,e))}}if(e.type===`element`){let o=n?!n.includes(e.tagName):a?a.includes(e.tagName):!1;if(!o&&r&&typeof t==`number`&&(o=!r(e,t,i)),o&&i&&typeof t==`number`)return s&&e.children?i.children.splice(t,1,...e.children):i.children.splice(t,1),t}}}function vD(e){let t=e.indexOf(`:`),n=e.indexOf(`?`),r=e.indexOf(`#`),i=e.indexOf(`/`);return t===-1||i!==-1&&t>i||n!==-1&&t>n||r!==-1&&t>r||fD.test(e.slice(0,t))?e:``}function yD(e,t){let n=String(e);if(typeof t!=`string`)throw TypeError(`Expected character`);let r=0,i=n.indexOf(t);for(;i!==-1;)r++,i=n.indexOf(t,i+t.length);return r}function bD(e){if(typeof e!=`string`)throw TypeError(`Expected a string`);return e.replace(/[|\\{}()[\]^$+*?.]/g,`\\$&`).replace(/-/g,`\\x2d`)}function xD(e,t,n){let r=aE((n||{}).ignore||[]),i=SD(t),a=-1;for(;++a0?{type:`text`,value:a}:void 0),a===!1?r.lastIndex=n+1:(s!==n&&u.push({type:`text`,value:e.value.slice(s,n)}),Array.isArray(a)?u.push(...a):a&&u.push(a),s=n+d[0].length,l=!0),!r.global)break;d=r.exec(e.value)}return l?(s?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(`)`),i=yD(e,`(`),a=yD(e,`)`);for(;r!==-1&&i>a;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(`)`),a++;return[e,n]}function BD(e,t){let n=e.input.charCodeAt(e.index-1);return(e.index===0||PS(n)||NS(n))&&(!t||n!==47)}XD.peek=YD;function VD(){this.buffer()}function HD(e){this.enter({type:`footnoteReference`,identifier:``,label:``},e)}function UD(){this.buffer()}function WD(e){this.enter({type:`footnoteDefinition`,identifier:``,label:``,children:[]},e)}function GD(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=CS(this.sliceSerialize(e)).toLowerCase(),n.label=t}function KD(e){this.exit(e)}function qD(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=CS(this.sliceSerialize(e)).toLowerCase(),n.label=t}function JD(e){this.exit(e)}function YD(){return`[`}function XD(e,t,n,r){let i=n.createTracker(r),a=i.move(`[^`),o=n.enter(`footnoteReference`),s=n.enter(`reference`);return a+=i.move(n.safe(n.associationId(e),{after:`]`,before:a})),s(),o(),a+=i.move(`]`),a}function ZD(){return{enter:{gfmFootnoteCallString:VD,gfmFootnoteCall:HD,gfmFootnoteDefinitionLabelString:UD,gfmFootnoteDefinition:WD},exit:{gfmFootnoteCallString:GD,gfmFootnoteCall:KD,gfmFootnoteDefinitionLabelString:qD,gfmFootnoteDefinition:JD}}}function QD(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:XD},unsafe:[{character:`[`,inConstruct:[`label`,`phrasing`,`reference`]}]};function n(e,n,r,i){let a=r.createTracker(i),o=a.move(`[^`),s=r.enter(`footnoteDefinition`),c=r.enter(`label`);return o+=a.move(r.safe(r.associationId(e),{before:o,after:`]`})),c(),o+=a.move(`]:`),e.children&&e.children.length>0&&(a.shift(4),o+=a.move((t?` -`:` `)+r.indentLines(r.containerFlow(e,a.current()),t?eO:$D))),s(),o}}function $D(e,t,n){return t===0?e:eO(e,t,n)}function eO(e,t,n){return(n?``:` `)+e}var tO=[`autolink`,`destinationLiteral`,`destinationRaw`,`reference`,`titleQuote`,`titleApostrophe`];oO.peek=sO;function nO(){return{canContainEols:[`delete`],enter:{strikethrough:iO},exit:{strikethrough:aO}}}function rO(){return{unsafe:[{character:`~`,inConstruct:`phrasing`,notInConstruct:tO}],handlers:{delete:oO}}}function iO(e){this.enter({type:`delete`,children:[]},e)}function aO(e){this.exit(e)}function oO(e,t,n,r){let i=n.createTracker(r),a=n.enter(`strikethrough`),o=i.move(`~~`);return o+=n.containerPhrasing(e,{...i.current(),before:o,after:`~`}),o+=i.move(`~~`),a(),o}function sO(){return`~`}function cO(e){return e.length}function lO(e,t){let n=t||{},r=(n.align||[]).concat(),i=n.stringLength||cO,a=[],o=[],s=[],c=[],l=0,u=-1;for(;++ul&&(l=e[u].length);++ac[a])&&(c[a]=e)}t.push(o)}o[u]=t,s[u]=r}let d=-1;if(typeof r==`object`&&`length`in r)for(;++dc[d]&&(c[d]=i),p[d]=i),f[d]=o}o.splice(1,0,f),s.splice(1,0,p),u=-1;let m=[];for(;++u `),a.shift(2);let o=n.indentLines(n.containerFlow(e,a.current()),pO);return i(),o}function pO(e,t,n){return`>`+(n?``:` `)+e}function mO(e,t){return hO(e,t.inConstruct,!0)&&!hO(e,t.notInConstruct,!1)}function hO(e,t,n){if(typeof t==`string`&&(t=[t]),!t||t.length===0)return n;let r=-1;for(;++ro&&(o=a):a=1,i=r+t.length,r=n.indexOf(t,i);return o}function vO(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function yO(e){let t=e.options.fence||"`";if(t!=="`"&&t!==`~`)throw Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function bO(e,t,n,r){let i=yO(n),a=e.value||``,o=i==="`"?`GraveAccent`:`Tilde`;if(vO(e,n)){let e=n.enter(`codeIndented`),t=n.indentLines(a,xO);return e(),t}let s=n.createTracker(r),c=i.repeat(Math.max(_O(a,i)+1,3)),l=n.enter(`codeFenced`),u=s.move(c);if(e.lang){let t=n.enter(`codeFencedLang${o}`);u+=s.move(n.safe(e.lang,{before:u,after:` `,encode:["`"],...s.current()})),t()}if(e.lang&&e.meta){let t=n.enter(`codeFencedMeta${o}`);u+=s.move(` `),u+=s.move(n.safe(e.meta,{before:u,after:` -`,encode:["`"],...s.current()})),t()}return u+=s.move(` -`),a&&(u+=s.move(a+` -`)),u+=s.move(c),l(),u}function xO(e,t,n){return(n?``:` `)+e}function SO(e){let t=e.options.quote||`"`;if(t!==`"`&&t!==`'`)throw Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function CO(e,t,n,r){let i=SO(n),a=i===`"`?`Quote`:`Apostrophe`,o=n.enter(`definition`),s=n.enter(`label`),c=n.createTracker(r),l=c.move(`[`);return l+=c.move(n.safe(n.associationId(e),{before:l,after:`]`,...c.current()})),l+=c.move(`]: `),s(),!e.url||/[\0- \u007F]/.test(e.url)?(s=n.enter(`destinationLiteral`),l+=c.move(`<`),l+=c.move(n.safe(e.url,{before:l,after:`>`,...c.current()})),l+=c.move(`>`)):(s=n.enter(`destinationRaw`),l+=c.move(n.safe(e.url,{before:l,after:e.title?` `:` -`,...c.current()}))),s(),e.title&&(s=n.enter(`title${a}`),l+=c.move(` `+i),l+=c.move(n.safe(e.title,{before:l,after:i,...c.current()})),l+=c.move(i),s()),o(),l}function wO(e){let t=e.options.emphasis||`*`;if(t!==`*`&&t!==`_`)throw Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function TO(e){return`&#x`+e.toString(16).toUpperCase()+`;`}function EO(e,t,n){let r=WS(e),i=WS(t);return r===void 0?i===void 0?n===`_`?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:r===1?i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}DO.peek=OO;function DO(e,t,n,r){let i=wO(n),a=n.enter(`emphasis`),o=n.createTracker(r),s=o.move(i),c=o.move(n.containerPhrasing(e,{after:i,before:s,...o.current()})),l=c.charCodeAt(0),u=EO(r.before.charCodeAt(r.before.length-1),l,i);u.inside&&(c=TO(l)+c.slice(1));let d=c.charCodeAt(c.length-1),f=EO(r.after.charCodeAt(0),d,i);f.inside&&(c=c.slice(0,-1)+TO(d));let p=o.move(i);return a(),n.attentionEncodeSurroundingInfo={after:f.outside,before:u.outside},s+c+p}function OO(e,t,n){return n.options.emphasis||`*`}function kO(e,t){let n=!1;return gE(e,function(e){if(`value`in e&&/\r?\n|\r/.test(e.value)||e.type===`break`)return n=!0,!1}),!!((!e.depth||e.depth<3)&&uS(e)&&(t.options.setext||n))}function AO(e,t,n,r){let i=Math.max(Math.min(6,e.depth||1),1),a=n.createTracker(r);if(kO(e,n)){let t=n.enter(`headingSetext`),r=n.enter(`phrasing`),o=n.containerPhrasing(e,{...a.current(),before:` -`,after:` -`});return r(),t(),o+` -`+(i===1?`=`:`-`).repeat(o.length-(Math.max(o.lastIndexOf(`\r`),o.lastIndexOf(` -`))+1))}let o=`#`.repeat(i),s=n.enter(`headingAtx`),c=n.enter(`phrasing`);a.move(o+` `);let l=n.containerPhrasing(e,{before:`# `,after:` -`,...a.current()});return/^[\t ]/.test(l)&&(l=TO(l.charCodeAt(0))+l.slice(1)),l=l?o+` `+l:o,n.options.closeAtx&&(l+=` `+o),c(),s(),l}jO.peek=MO;function jO(e){return e.value||``}function MO(){return`<`}NO.peek=PO;function NO(e,t,n,r){let i=SO(n),a=i===`"`?`Quote`:`Apostrophe`,o=n.enter(`image`),s=n.enter(`label`),c=n.createTracker(r),l=c.move(`![`);return l+=c.move(n.safe(e.alt,{before:l,after:`]`,...c.current()})),l+=c.move(`](`),s(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(s=n.enter(`destinationLiteral`),l+=c.move(`<`),l+=c.move(n.safe(e.url,{before:l,after:`>`,...c.current()})),l+=c.move(`>`)):(s=n.enter(`destinationRaw`),l+=c.move(n.safe(e.url,{before:l,after:e.title?` `:`)`,...c.current()}))),s(),e.title&&(s=n.enter(`title${a}`),l+=c.move(` `+i),l+=c.move(n.safe(e.title,{before:l,after:i,...c.current()})),l+=c.move(i),s()),l+=c.move(`)`),o(),l}function PO(){return`!`}FO.peek=IO;function FO(e,t,n,r){let i=e.referenceType,a=n.enter(`imageReference`),o=n.enter(`label`),s=n.createTracker(r),c=s.move(`![`),l=n.safe(e.alt,{before:c,after:`]`,...s.current()});c+=s.move(l+`][`),o();let u=n.stack;n.stack=[],o=n.enter(`reference`);let d=n.safe(n.associationId(e),{before:c,after:`]`,...s.current()});return o(),n.stack=u,a(),i===`full`||!l||l!==d?c+=s.move(d+`]`):i===`shortcut`?c=c.slice(0,-1):c+=s.move(`]`),c}function IO(){return`!`}LO.peek=RO;function LO(e,t,n){let r=e.value||``,i="`",a=-1;for(;RegExp("(^|[^`])"+i+"([^`]|$)").test(r);)i+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=` `+r+` `);++a\u007F]/.test(e.url))}BO.peek=VO;function BO(e,t,n,r){let i=SO(n),a=i===`"`?`Quote`:`Apostrophe`,o=n.createTracker(r),s,c;if(zO(e,n)){let t=n.stack;n.stack=[],s=n.enter(`autolink`);let r=o.move(`<`);return r+=o.move(n.containerPhrasing(e,{before:r,after:`>`,...o.current()})),r+=o.move(`>`),s(),n.stack=t,r}s=n.enter(`link`),c=n.enter(`label`);let l=o.move(`[`);return l+=o.move(n.containerPhrasing(e,{before:l,after:`](`,...o.current()})),l+=o.move(`](`),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=n.enter(`destinationLiteral`),l+=o.move(`<`),l+=o.move(n.safe(e.url,{before:l,after:`>`,...o.current()})),l+=o.move(`>`)):(c=n.enter(`destinationRaw`),l+=o.move(n.safe(e.url,{before:l,after:e.title?` `:`)`,...o.current()}))),c(),e.title&&(c=n.enter(`title${a}`),l+=o.move(` `+i),l+=o.move(n.safe(e.title,{before:l,after:i,...o.current()})),l+=o.move(i),c()),l+=o.move(`)`),s(),l}function VO(e,t,n){return zO(e,n)?`<`:`[`}HO.peek=UO;function HO(e,t,n,r){let i=e.referenceType,a=n.enter(`linkReference`),o=n.enter(`label`),s=n.createTracker(r),c=s.move(`[`),l=n.containerPhrasing(e,{before:c,after:`]`,...s.current()});c+=s.move(l+`][`),o();let u=n.stack;n.stack=[],o=n.enter(`reference`);let d=n.safe(n.associationId(e),{before:c,after:`]`,...s.current()});return o(),n.stack=u,a(),i===`full`||!l||l!==d?c+=s.move(d+`]`):i===`shortcut`?c=c.slice(0,-1):c+=s.move(`]`),c}function UO(){return`[`}function WO(e){let t=e.options.bullet||`*`;if(t!==`*`&&t!==`+`&&t!==`-`)throw Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function GO(e){let t=WO(e),n=e.options.bulletOther;if(!n)return t===`*`?`-`:`*`;if(n!==`*`&&n!==`+`&&n!==`-`)throw Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function KO(e){let t=e.options.bulletOrdered||`.`;if(t!==`.`&&t!==`)`)throw Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function qO(e){let t=e.options.rule||`*`;if(t!==`*`&&t!==`-`&&t!==`_`)throw Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function JO(e,t,n,r){let i=n.enter(`list`),a=n.bulletCurrent,o=e.ordered?KO(n):WO(n),s=e.ordered?o===`.`?`)`:`.`:GO(n),c=t&&n.bulletLastUsed?o===n.bulletLastUsed:!1;if(!e.ordered){let t=e.children?e.children[0]:void 0;if((o===`*`||o===`-`)&&t&&(!t.children||!t.children[0])&&n.stack[n.stack.length-1]===`list`&&n.stack[n.stack.length-2]===`listItem`&&n.stack[n.stack.length-3]===`list`&&n.stack[n.stack.length-4]===`listItem`&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(c=!0),qO(n)===o&&t){let t=-1;for(;++t-1?t.start:1)+(n.options.incrementListMarker===!1?0:t.children.indexOf(e))+a);let o=a.length+1;(i===`tab`||i===`mixed`&&(t&&t.type===`list`&&t.spread||e.spread))&&(o=Math.ceil(o/4)*4);let s=n.createTracker(r);s.move(a+` `.repeat(o-a.length)),s.shift(o);let c=n.enter(`listItem`),l=n.indentLines(n.containerFlow(e,s.current()),u);return c(),l;function u(e,t,n){return t?(n?``:` `.repeat(o))+e:(n?a:a+` `.repeat(o-a.length))+e}}function ZO(e,t,n,r){let i=n.enter(`paragraph`),a=n.enter(`phrasing`),o=n.containerPhrasing(e,r);return a(),i(),o}var QO=aE([`break`,`delete`,`emphasis`,`footnote`,`footnoteReference`,`image`,`imageReference`,`inlineCode`,`inlineMath`,`link`,`linkReference`,`mdxJsxTextElement`,`mdxTextExpression`,`strong`,`text`,`textDirective`]);function $O(e,t,n,r){return(e.children.some(function(e){return QO(e)})?n.containerPhrasing:n.containerFlow).call(n,e,r)}function ek(e){let t=e.options.strong||`*`;if(t!==`*`&&t!==`_`)throw Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}tk.peek=nk;function tk(e,t,n,r){let i=ek(n),a=n.enter(`strong`),o=n.createTracker(r),s=o.move(i+i),c=o.move(n.containerPhrasing(e,{after:i,before:s,...o.current()})),l=c.charCodeAt(0),u=EO(r.before.charCodeAt(r.before.length-1),l,i);u.inside&&(c=TO(l)+c.slice(1));let d=c.charCodeAt(c.length-1),f=EO(r.after.charCodeAt(0),d,i);f.inside&&(c=c.slice(0,-1)+TO(d));let p=o.move(i+i);return a(),n.attentionEncodeSurroundingInfo={after:f.outside,before:u.outside},s+c+p}function nk(e,t,n){return n.options.strong||`*`}function rk(e,t,n,r){return n.safe(e.value,r)}function ik(e){let t=e.options.ruleRepetition||3;if(t<3)throw Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function ak(e,t,n){let r=(qO(n)+(n.options.ruleSpaces?` `:``)).repeat(ik(n));return n.options.ruleSpaces?r.slice(0,-1):r}var ok={blockquote:fO,break:gO,code:bO,definition:CO,emphasis:DO,hardBreak:gO,heading:AO,html:jO,image:NO,imageReference:FO,inlineCode:LO,link:BO,linkReference:HO,list:JO,listItem:XO,paragraph:ZO,root:$O,strong:tk,text:rk,thematicBreak:ak};function sk(){return{enter:{table:ck,tableData:fk,tableHeader:fk,tableRow:uk},exit:{codeText:pk,table:lk,tableData:dk,tableHeader:dk,tableRow:dk}}}function ck(e){let t=e._align;this.enter({type:`table`,align:t.map(function(e){return e===`none`?null:e}),children:[]},e),this.data.inTable=!0}function lk(e){this.exit(e),this.data.inTable=void 0}function uk(e){this.enter({type:`tableRow`,children:[]},e)}function dk(e){this.exit(e)}function fk(e){this.enter({type:`tableCell`,children:[]},e)}function pk(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,mk));let n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function mk(e,t){return t===`|`?t:e}function hk(e){let t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,i=t.stringLength,a=n?` `:`|`;return{unsafe:[{character:`\r`,inConstruct:`tableCell`},{character:` -`,inConstruct:`tableCell`},{atBreak:!0,character:`|`,after:`[ :-]`},{character:`|`,inConstruct:`tableCell`},{atBreak:!0,character:`:`,after:`-`},{atBreak:!0,character:`-`,after:`[:|-]`}],handlers:{inlineCode:f,table:o,tableCell:c,tableRow:s}};function o(e,t,n,r){return l(u(e,n,r),e.align)}function s(e,t,n,r){let i=l([d(e,n,r)]);return i.slice(0,i.indexOf(` -`))}function c(e,t,n,r){let i=n.enter(`tableCell`),o=n.enter(`phrasing`),s=n.containerPhrasing(e,{...r,before:a,after:a});return o(),i(),s}function l(e,t){return lO(e,{align:t,alignDelimiters:r,padding:n,stringLength:i})}function u(e,t,n){let r=e.children,i=-1,a=[],o=t.enter(`table`);for(;++i0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}var qk={tokenize:tA,partial:!0};function Jk(){return{document:{91:{name:`gfmFootnoteDefinition`,tokenize:Qk,continuation:{tokenize:$k},exit:eA}},text:{91:{name:`gfmFootnoteCall`,tokenize:Zk},93:{name:`gfmPotentialFootnoteCall`,add:`after`,tokenize:Yk,resolveTo:Xk}}}}function Yk(e,t,n){let r=this,i=r.events.length,a=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),o;for(;i--;){let e=r.events[i][1];if(e.type===`labelImage`){o=e;break}if(e.type===`gfmFootnoteCall`||e.type===`labelLink`||e.type===`label`||e.type===`image`||e.type===`link`)break}return s;function s(i){if(!o||!o._balanced)return n(i);let s=CS(r.sliceSerialize({start:o.end,end:r.now()}));return s.codePointAt(0)!==94||!a.includes(s.slice(1))?n(i):(e.enter(`gfmFootnoteCallLabelMarker`),e.consume(i),e.exit(`gfmFootnoteCallLabelMarker`),t(i))}}function Xk(e,t){let n=e.length;for(;n--;)if(e[n][1].type===`labelImage`&&e[n][0]===`enter`){e[n][1];break}e[n+1][1].type=`data`,e[n+3][1].type=`gfmFootnoteCallLabelMarker`;let r={type:`gfmFootnoteCall`,start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:`gfmFootnoteCallMarker`,start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;let a={type:`gfmFootnoteCallString`,start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},o={type:`chunkString`,contentType:`string`,start:Object.assign({},a.start),end:Object.assign({},a.end)},s=[e[n+1],e[n+2],[`enter`,r,t],e[n+3],e[n+4],[`enter`,i,t],[`exit`,i,t],[`enter`,a,t],[`enter`,o,t],[`exit`,o,t],[`exit`,a,t],e[e.length-2],e[e.length-1],[`exit`,r,t]];return e.splice(n,e.length-n+1,...s),e}function Zk(e,t,n){let r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),a=0,o;return s;function s(t){return e.enter(`gfmFootnoteCall`),e.enter(`gfmFootnoteCallLabelMarker`),e.consume(t),e.exit(`gfmFootnoteCallLabelMarker`),c}function c(t){return t===94?(e.enter(`gfmFootnoteCallMarker`),e.consume(t),e.exit(`gfmFootnoteCallMarker`),e.enter(`gfmFootnoteCallString`),e.enter(`chunkString`).contentType=`string`,l):n(t)}function l(s){if(a>999||s===93&&!o||s===null||s===91||jS(s))return n(s);if(s===93){e.exit(`chunkString`);let a=e.exit(`gfmFootnoteCallString`);return i.includes(CS(r.sliceSerialize(a)))?(e.enter(`gfmFootnoteCallLabelMarker`),e.consume(s),e.exit(`gfmFootnoteCallLabelMarker`),e.exit(`gfmFootnoteCall`),t):n(s)}return jS(s)||(o=!0),a++,e.consume(s),s===92?u:l}function u(t){return t===91||t===92||t===93?(e.consume(t),a++,l):l(t)}}function Qk(e,t,n){let r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),a,o=0,s;return c;function c(t){return e.enter(`gfmFootnoteDefinition`)._container=!0,e.enter(`gfmFootnoteDefinitionLabel`),e.enter(`gfmFootnoteDefinitionLabelMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionLabelMarker`),l}function l(t){return t===94?(e.enter(`gfmFootnoteDefinitionMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionMarker`),e.enter(`gfmFootnoteDefinitionLabelString`),e.enter(`chunkString`).contentType=`string`,u):n(t)}function u(t){if(o>999||t===93&&!s||t===null||t===91||jS(t))return n(t);if(t===93){e.exit(`chunkString`);let n=e.exit(`gfmFootnoteDefinitionLabelString`);return a=CS(r.sliceSerialize(n)),e.enter(`gfmFootnoteDefinitionLabelMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionLabelMarker`),e.exit(`gfmFootnoteDefinitionLabel`),f}return jS(t)||(s=!0),o++,e.consume(t),t===92?d:u}function d(t){return t===91||t===92||t===93?(e.consume(t),o++,u):u(t)}function f(t){return t===58?(e.enter(`definitionMarker`),e.consume(t),e.exit(`definitionMarker`),i.includes(a)||i.push(a),LS(e,p,`gfmFootnoteDefinitionWhitespace`)):n(t)}function p(e){return t(e)}}function $k(e,t,n){return e.check(QS,t,e.attempt(qk,t,n))}function eA(e){e.exit(`gfmFootnoteDefinition`)}function tA(e,t,n){let r=this;return LS(e,i,`gfmFootnoteDefinitionIndent`,5);function i(e){let i=r.events[r.events.length-1];return i&&i[1].type===`gfmFootnoteDefinitionIndent`&&i[2].sliceSerialize(i[1],!0).length===4?t(e):n(e)}}function nA(e){let t=(e||{}).singleTilde,n={name:`strikethrough`,tokenize:i,resolveAll:r};return t??=!0,{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}};function r(e,t){let n=-1;for(;++n1?r(a):(e.consume(a),o++,c);if(o<2&&!t)return r(a);let l=e.exit(`strikethroughSequenceTemporary`),u=WS(a);return l._open=!u||u===2&&!!s,l._close=!s||s===2&&!!u,n(a)}}}var rA=class{constructor(){this.map=[]}add(e,t,n){iA(this,e,t,n)}consume(e){if(this.map.sort(function(e,t){return e[0]-t[0]}),this.map.length===0)return;let t=this.map.length,n=[];for(;t>0;)--t,n.push(e.slice(this.map[t][0]+this.map[t][1]),this.map[t][2]),e.length=this.map[t][0];n.push(e.slice()),e.length=0;let r=n.pop();for(;r;){for(let t of r)e.push(t);r=n.pop()}this.map.length=0}};function iA(e,t,n,r){let i=0;if(n!==0||r.length!==0){for(;i-1;){let e=r.events[t][1].type;if(e===`lineEnding`||e===`linePrefix`)t--;else break}let i=t>-1?r.events[t][1].type:null,a=i===`tableHead`||i===`tableRow`?S:c;return a===S&&r.parser.lazy[r.now().line]?n(e):a(e)}function c(t){return e.enter(`tableHead`),e.enter(`tableRow`),l(t)}function l(e){return e===124?u(e):(o=!0,a+=1,u(e))}function u(t){return t===null?n(t):$(t)?a>1?(a=0,r.interrupt=!0,e.exit(`tableRow`),e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),p):n(t):MS(t)?LS(e,u,`whitespace`)(t):(a+=1,o&&(o=!1,i+=1),t===124?(e.enter(`tableCellDivider`),e.consume(t),e.exit(`tableCellDivider`),o=!0,u):(e.enter(`data`),d(t)))}function d(t){return t===null||t===124||jS(t)?(e.exit(`data`),u(t)):(e.consume(t),t===92?f:d)}function f(t){return t===92||t===124?(e.consume(t),d):d(t)}function p(t){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(t):(e.enter(`tableDelimiterRow`),o=!1,MS(t)?LS(e,m,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):m(t))}function m(t){return t===45||t===58?g(t):t===124?(o=!0,e.enter(`tableCellDivider`),e.consume(t),e.exit(`tableCellDivider`),h):x(t)}function h(t){return MS(t)?LS(e,g,`whitespace`)(t):g(t)}function g(t){return t===58?(a+=1,o=!0,e.enter(`tableDelimiterMarker`),e.consume(t),e.exit(`tableDelimiterMarker`),_):t===45?(a+=1,_(t)):t===null||$(t)?b(t):x(t)}function _(t){return t===45?(e.enter(`tableDelimiterFiller`),v(t)):x(t)}function v(t){return t===45?(e.consume(t),v):t===58?(o=!0,e.exit(`tableDelimiterFiller`),e.enter(`tableDelimiterMarker`),e.consume(t),e.exit(`tableDelimiterMarker`),y):(e.exit(`tableDelimiterFiller`),y(t))}function y(t){return MS(t)?LS(e,b,`whitespace`)(t):b(t)}function b(n){return n===124?m(n):n===null||$(n)?!o||i!==a?x(n):(e.exit(`tableDelimiterRow`),e.exit(`tableHead`),t(n)):x(n)}function x(e){return n(e)}function S(t){return e.enter(`tableRow`),C(t)}function C(n){return n===124?(e.enter(`tableCellDivider`),e.consume(n),e.exit(`tableCellDivider`),C):n===null||$(n)?(e.exit(`tableRow`),t(n)):MS(n)?LS(e,C,`whitespace`)(n):(e.enter(`data`),w(n))}function w(t){return t===null||t===124||jS(t)?(e.exit(`data`),C(t)):(e.consume(t),t===92?T:w)}function T(t){return t===92||t===124?(e.consume(t),w):w(t)}}function cA(e,t){let n=-1,r=!0,i=0,a=[0,0,0,0],o=[0,0,0,0],s=!1,c=0,l,u,d,f=new rA;for(;++nn[2]+1){let t=n[2]+1,r=n[3]-n[2]-1;e.add(t,r,[])}}e.add(n[3]+1,0,[[`exit`,o,t]])}return i!==void 0&&(a.end=Object.assign({},dA(t.events,i)),e.add(i,0,[[`exit`,a,t]]),a=void 0),a}function uA(e,t,n,r,i){let a=[],o=dA(t.events,n);i&&(i.end=Object.assign({},o),a.push([`exit`,i,t])),r.end=Object.assign({},o),a.push([`exit`,r,t]),e.add(n+1,0,a)}function dA(e,t){let n=e[t],r=n[0]===`enter`?`start`:`end`;return n[1][r]}var fA={name:`tasklistCheck`,tokenize:mA};function pA(){return{text:{91:fA}}}function mA(e,t,n){let r=this;return i;function i(t){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(t):(e.enter(`taskListCheck`),e.enter(`taskListCheckMarker`),e.consume(t),e.exit(`taskListCheckMarker`),a)}function a(t){return jS(t)?(e.enter(`taskListCheckValueUnchecked`),e.consume(t),e.exit(`taskListCheckValueUnchecked`),o):t===88||t===120?(e.enter(`taskListCheckValueChecked`),e.consume(t),e.exit(`taskListCheckValueChecked`),o):n(t)}function o(t){return t===93?(e.enter(`taskListCheckMarker`),e.consume(t),e.exit(`taskListCheckMarker`),e.exit(`taskListCheck`),s):n(t)}function s(r){return $(r)?t(r):MS(r)?e.check({tokenize:hA},t,n)(r):n(r)}}function hA(e,t,n){return LS(e,r,`whitespace`);function r(e){return e===null?n(e):t(e)}}function gA(e){return yS([Mk(),Jk(),nA(e),oA(),pA()])}var _A={};function vA(e){let t=this,n=e||_A,r=t.data(),i=r.micromarkExtensions||=[],a=r.fromMarkdownExtensions||=[],o=r.toMarkdownExtensions||=[];i.push(gA(n)),a.push(xk()),o.push(Sk(n))}function yA(e,t,n){return e.title.trim()?e.title:e.subagentName?t(`history.subagentTitle`,{name:e.subagentName}):t(`history.untitledIdentity`,{date:ub(e.createdAt||e.updatedAt,n),id:e.id.slice(-8)})}function bA(e){let t=e.nativeSessionId;return typeof t==`string`&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(t)?`codex resume ${t}`:null}function xA({session:e,detail:t,host:n,profile:r,onOpenParent:i,openInformation:a=!1}){let{t:o,i18n:s}=Dn(),[c,l]=(0,m.useState)(``),u=xb(),[d,f]=(0,m.useState)(!1),p=bA(e),g=t?.storage,_=async e=>{try{await u(e),l(o(`common.copied`))}catch{l(o(`history.copyFailed`))}},v=async()=>{if(n?.revealHistoryFile){f(!0);try{let t=await n.revealHistoryFile(cb(r),e.id);l(o(t.revealed?`history.fileRevealed`:`history.revealFailed`))}catch{l(o(`history.revealFailed`))}finally{f(!1)}}};return(0,h.jsxs)(`section`,{"aria-label":o(`history.sessionActions`),className:`mb-4 min-w-0 space-y-3`,children:[(0,h.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,h.jsxs)(X,{disabled:!e.nativeSessionId,onClick:()=>void _(e.nativeSessionId),type:`button`,variant:`secondary`,children:[(0,h.jsx)(hi,{size:14}),o(`history.copyId`)]}),(0,h.jsxs)(X,{disabled:!p,onClick:()=>void _(p),type:`button`,variant:`secondary`,children:[(0,h.jsx)(hi,{size:14}),o(`history.copyResume`)]})]}),e.nativeSessionId?null:(0,h.jsx)(`p`,{className:`text-xs text-[var(--muted)]`,children:o(`history.missingNativeId`)}),p?(0,h.jsx)(`p`,{className:`text-xs text-[var(--muted)]`,children:o(`history.resumeHint`)}):null,(0,h.jsxs)(`details`,{className:`rounded-lg border border-[var(--border)] p-3`,open:a||void 0,children:[(0,h.jsx)(`summary`,{className:`cursor-pointer font-medium focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--accent)]`,children:o(`history.sessionInformation`)}),(0,h.jsxs)(`dl`,{className:`mt-3 grid min-w-0 gap-3 text-sm`,children:[(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:o(`history.nativeId`)}),(0,h.jsx)(`dd`,{className:`select-text break-all font-mono`,children:e.nativeSessionId||o(`history.notRecorded`)})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:o(`history.sessionType`)}),(0,h.jsx)(`dd`,{children:o(e.sessionKind===`subagent`?`history.subtasks`:`history.mainSessions`)})]}),e.parentSessionId?(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:o(`history.parentId`)}),(0,h.jsxs)(`dd`,{className:`flex flex-wrap items-center gap-2`,children:[(0,h.jsx)(`span`,{className:`select-text break-all font-mono`,children:e.parentSessionId}),(0,h.jsx)(X,{onClick:()=>i(e.parentSessionId),type:`button`,variant:`secondary`,children:o(`history.openParent`)})]})]}):null,(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:o(`history.recordedProvider`)}),(0,h.jsx)(`dd`,{children:e.provider})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:o(`history.recordedModel`)}),(0,h.jsx)(`dd`,{children:e.model||o(`history.notRecorded`)})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:o(`history.createdAt`)}),(0,h.jsx)(`dd`,{children:ub(e.createdAt,s.language)})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:o(`history.fileModifiedAt`)}),(0,h.jsx)(`dd`,{children:ub(e.fileModifiedAt,s.language)})]}),(0,h.jsx)(`p`,{className:`text-xs text-[var(--muted)]`,children:o(`history.fileTimeHint`)}),g?(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:o(`history.projectDirectory`)}),(0,h.jsx)(`dd`,{className:`select-text break-all`,children:g.cwd||o(`history.notRecorded`)})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:o(`history.sessionFile`)}),(0,h.jsx)(`dd`,{className:`select-text break-all`,children:g.rolloutPath})]}),(0,h.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,h.jsxs)(X,{onClick:()=>void _(g.rolloutPath),type:`button`,variant:`secondary`,children:[(0,h.jsx)(hi,{size:14}),o(`history.copyPath`)]}),n?.revealHistoryFile?(0,h.jsxs)(X,{disabled:d,onClick:()=>void v(),type:`button`,variant:`secondary`,children:[(0,h.jsx)(bi,{size:14}),o(`history.revealFile`)]}):null]})]}):(0,h.jsx)(`p`,{className:`text-xs text-[var(--muted)]`,children:o(`history.localInfoHint`)})]})]}),(0,h.jsx)(`p`,{"aria-live":`polite`,className:`text-xs text-[var(--muted)]`,role:`status`,children:c})]})}function SA({target:e,close:t,save:n}){let{t:r}=Dn(),[i,a]=(0,m.useState)(!1),[o,s]=(0,m.useState)(e.alias||e.name),[c,l]=(0,m.useState)(!1),u=(0,m.useRef)(null),[d,f]=(0,m.useState)({x:e.x,y:e.y}),p=()=>{e.trigger.isConnected&&e.trigger.focus({preventScroll:!0})},g=()=>{p(),t()};(0,m.useLayoutEffect)(()=>{let t=u.current?.getBoundingClientRect();f({x:Math.max(8,Math.min(e.x,window.innerWidth-(t?.width||256)-8)),y:Math.max(8,Math.min(e.y,window.innerHeight-(t?.height||100)-8))}),u.current?.querySelector(`button`)?.focus({preventScroll:!0})},[e]),(0,m.useEffect)(()=>{if(i)return;let e=e=>{u.current?.contains(e.target)||t()},n=()=>t();return document.addEventListener(`pointerdown`,e,!0),document.addEventListener(`scroll`,e,!0),window.addEventListener(`resize`,n),window.addEventListener(`blur`,n),()=>{document.removeEventListener(`pointerdown`,e,!0),document.removeEventListener(`scroll`,e,!0),window.removeEventListener(`resize`,n),window.removeEventListener(`blur`,n)}},[i,t]);let _=t=>{try{n(e.id,t),g()}catch{l(!0),a(!0)}};if(i)return(0,h.jsx)(ib,{open:!0,onOpenChange:e=>{e||t()},restoreFocus:p,title:r(`history.projectAliasTitle`),description:r(`history.projectAliasHint`),closeLabel:r(`common.close`),children:(0,h.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),_(o.trim())},children:[(0,h.jsx)(nb,{label:r(`history.projectDisplayName`),error:c?r(`history.projectAliasFailed`):void 0,children:(0,h.jsx)(tb,{maxLength:160,value:o,onChange:e=>{s(e.target.value),l(!1)}})}),(0,h.jsxs)(`div`,{className:`mt-5 flex justify-end gap-2`,children:[(0,h.jsx)(X,{type:`button`,variant:`secondary`,onClick:g,children:r(`common.cancel`)}),(0,h.jsx)(X,{type:`submit`,children:r(`common.save`)})]})]})});let v=`min-h-10 w-full rounded-md px-3 text-left text-sm hover:bg-[var(--surface-hover)] focus:bg-[var(--accent-soft)] focus:outline-none disabled:opacity-40`;return(0,rm.createPortal)((0,h.jsxs)(`div`,{ref:u,role:`menu`,"aria-label":r(`history.projectActions`),style:{left:d.x,top:d.y},className:`fixed z-[70] w-64 max-w-[calc(100vw-16px)] overflow-auto rounded-xl border border-[var(--border)] bg-[var(--surface-raised)] p-1.5 text-[var(--text)] shadow-xl`,onContextMenu:e=>e.preventDefault(),onKeyDown:e=>{if(e.key===`Escape`||e.key===`Tab`){e.preventDefault(),g();return}let t=Array.from(u.current?.querySelectorAll(`button:not(:disabled)`)||[]),n=t.indexOf(document.activeElement),r=e.key===`Home`?0:e.key===`End`?t.length-1:e.key===`ArrowDown`?(n+1)%t.length:e.key===`ArrowUp`?(n+t.length-1)%t.length:-1;r>=0&&(e.preventDefault(),t[r]?.focus())},children:[(0,h.jsx)(`button`,{className:v,role:`menuitem`,tabIndex:-1,type:`button`,onClick:()=>a(!0),children:r(`history.projectAliasTitle`)}),(0,h.jsx)(`button`,{className:v,role:`menuitem`,tabIndex:-1,type:`button`,disabled:!e.alias,onClick:()=>_(``),children:r(`history.projectAliasReset`)})]}),document.body)}function CA(e,t){(e.key===`ContextMenu`||e.shiftKey&&e.key===`F10`)&&(e.preventDefault(),t())}function wA(e,t,n,r,i=!1){return ct({queryKey:[`history-rows`,e.scope,i?`children`:`project`,t],initialPageParam:1,initialData:r?{pages:[r],pageParams:[1]}:void 0,queryFn:({signal:n,pageParam:r})=>e.core.listHistory({...e.input,view:`projects`,page:r,...i?{parentId:t}:{projectId:t}},{signal:n}),getNextPageParam:e=>e.hasNextPage?e.page+1:void 0,enabled:n,staleTime:1/0,gcTime:0,retry:!1,refetchOnMount:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1})}function TA(e){return[...new Map((e??[]).flatMap(e=>e.sessions).map(e=>[e.id,e])).values()]}function EA({query:e}){let{t}=Dn();return(0,h.jsxs)(h.Fragment,{children:[e.isError?(0,h.jsxs)(`div`,{className:`px-3 py-2 text-xs text-[var(--danger)]`,role:`alert`,children:[db(e.error,t),` `,(0,h.jsx)(`button`,{className:`underline`,type:`button`,onClick:()=>void(e.data?e.fetchNextPage():e.refetch()),children:t(`history.retryLoad`)})]}):null,e.isFetching?(0,h.jsx)(`p`,{role:`status`,className:`px-3 py-2 text-xs text-[var(--muted)]`,children:t(`common.loading`)}):e.hasNextPage&&!e.isError?(0,h.jsx)(`button`,{className:`min-h-9 w-full rounded-md px-3 text-left text-xs text-[var(--muted)] hover:bg-[var(--surface-hover)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--focus)]`,type:`button`,onClick:()=>void e.fetchNextPage(),children:t(`history.loadMore`)}):null]})}function DA({session:e,props:t,fallback:n,depth:r=0}){let{t:i,i18n:a}=Dn(),[o,s]=(0,m.useState)(!1),c=(0,m.useRef)(null),l=wA(t,e.id,o,void 0,!0),u=TA(l.data?.pages),d=yA(e,i,a.language),f=(e.childCount??0)>0,p=[d,e.provider,e.model,`${i(`history.fileModifiedAt`)}: ${ub(e.fileModifiedAt||e.updatedAt,a.language)}`,i(`history.contextMenuHint`)].filter(Boolean).join(` -`);return(0,h.jsxs)(`li`,{className:`min-w-0`,children:[(0,h.jsxs)(`div`,{className:`flex min-w-0 items-center`,style:{paddingLeft:`${Math.min(r,6)*12+16}px`},children:[f?(0,h.jsx)(`button`,{ref:c,type:`button`,className:`flex h-8 w-6 shrink-0 items-center justify-center rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--focus)]`,"aria-label":i(`history.toggleSubtasks`,{title:d,count:e.childCount}),"aria-expanded":o,onClick:()=>s(!o),children:o?(0,h.jsx)(fi,{size:12}):(0,h.jsx)(pi,{size:12})}):(0,h.jsx)(`span`,{className:`w-6 shrink-0`}),(0,h.jsxs)(`button`,{"aria-current":t.selectedId===e.id?`true`:void 0,"aria-haspopup":`menu`,"aria-label":`${i(`history.open`)}: ${d}`,className:Qy(`flex min-h-9 min-w-0 flex-1 items-center gap-2 rounded-lg px-2 py-1.5 text-left text-sm hover:bg-[var(--surface-hover)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--focus)]`,t.selectedId===e.id&&`bg-[var(--accent-soft)] font-medium`),"data-history-session":!0,onClick:()=>t.onSelect(e),onContextMenu:n=>{n.preventDefault(),t.onMenu(e,n.currentTarget,{x:n.clientX,y:n.clientY})},onKeyDown:n=>CA(n,()=>t.onMenu(e,n.currentTarget)),ref:r=>{t.registerButton(e.id,r),r&&t.registerGroupButton([e.id],n())},title:p,type:`button`,children:[(0,h.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:d}),e.sessionKind===`subagent`?(0,h.jsx)(Ci,{"aria-label":i(`history.subtasks`),className:`shrink-0 text-[var(--muted)]`,size:12}):null,e.archived?(0,h.jsx)(li,{"aria-label":i(`history.archived`),className:`shrink-0 text-[var(--muted)]`,size:12}):null]})]}),f&&o?(0,h.jsxs)(`ul`,{"aria-label":i(`history.childrenOf`,{title:d}),className:`min-w-0 space-y-0.5`,children:[u.map(e=>(0,h.jsx)(DA,{session:e,props:t,depth:r+1,fallback:()=>c.current||n()},e.id)),(0,h.jsx)(`li`,{style:{paddingLeft:`${Math.min(r+1,6)*12+40}px`},children:(0,h.jsx)(EA,{query:l})})]}):null]})}function OA({project:e,props:t,label:n,alias:r,onAlias:i}){let{t:a}=Dn(),o=t.initialPage.projectId===e.id?t.initialPage:void 0,[s,c]=(0,m.useState)(!!o&&e.kind!==`orphans`),l=(0,m.useRef)(null),u=wA(t,e.id,s,o),d=TA(u.data?.pages),f=!!t.preferences?.setHistoryProjectAlias&&[`workspace`,`directory`].includes(e.kind),p=(t,n)=>{if(!f)return;let a=t.getBoundingClientRect();i({id:e.id,name:e.name,alias:r,trigger:t,x:n?.x??a.left+12,y:n?.y??a.bottom})};return(0,h.jsxs)(`section`,{"aria-label":n,children:[(0,h.jsxs)(`button`,{ref:l,type:`button`,"aria-expanded":s,"aria-haspopup":f?`menu`:void 0,title:[n,a(`history.projectKinds.${e.kind}`),f?a(`history.projectAliasContextHint`):``].filter(Boolean).join(` -`),className:`flex min-h-9 w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-sm font-medium hover:bg-[var(--surface-hover)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--focus)]`,onClick:()=>c(!s),onContextMenu:e=>{f&&(e.preventDefault(),p(e.currentTarget,{x:e.clientX,y:e.clientY}))},onKeyDown:e=>{f&&CA(e,()=>p(e.currentTarget))},children:[s?(0,h.jsx)(fi,{className:`shrink-0 text-[var(--muted)]`,size:12}):(0,h.jsx)(pi,{className:`shrink-0 text-[var(--muted)]`,size:12}),e.kind===`orphans`?(0,h.jsx)(Ci,{className:`shrink-0`,size:16}):s?(0,h.jsx)(bi,{className:`shrink-0`,size:16}):(0,h.jsx)(xi,{className:`shrink-0`,size:16}),(0,h.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:n}),e.kind===`directory`&&!r?(0,h.jsx)(`span`,{className:`shrink-0 text-[10px] font-normal text-[var(--muted)]`,children:a(`history.directoryBadge`)}):null,(0,h.jsx)(`span`,{className:`text-xs font-normal text-[var(--muted)]`,"aria-label":a(e.kind===`orphans`?`history.orphanCount`:`history.rootCount`,{count:e.total}),children:e.total})]}),s?(0,h.jsxs)(`ul`,{className:`mt-0.5 min-w-0 space-y-0.5`,children:[e.kind===`orphans`?(0,h.jsx)(`li`,{className:`px-3 py-2 text-xs text-[var(--muted)]`,children:a(`history.orphansHint`)}):null,d.map(e=>(0,h.jsx)(DA,{session:e,props:t,fallback:()=>l.current},e.id)),(0,h.jsx)(`li`,{className:`pl-8`,children:(0,h.jsx)(EA,{query:u})})]}):null]})}function kA(e){let{t}=Dn(),[n,r]=(0,m.useState)(null),[i,a]=(0,m.useState)({}),o=e.initialPage.projects??[],s=e=>e.kind===`orphans`?t(`history.orphans`):e.kind===`unassigned`?t(`history.noProject`):e.name,c=t=>{if(t.id in i)return i[t.id];try{return e.preferences?.getHistoryProjectAlias?.(e.preferenceScope,t.id)||``}catch{return``}},l=o.map(e=>c(e)||s(e));return(0,h.jsxs)(`div`,{className:`space-y-2 p-2`,"data-history-projects":!0,children:[o.map((t,n)=>{let i=l[n],a=l.filter(e=>e===i).length>1;return(0,h.jsx)(OA,{project:t,props:e,label:a?`${i} · ${t.id.slice(0,6)}`:i,alias:c(t),onAlias:r},t.id)}),n?(0,h.jsx)(SA,{target:n,close:()=>r(null),save:(t,n)=>{e.preferences.setHistoryProjectAlias(e.preferenceScope,t,n),a(e=>({...e,[t]:n}))}}):null]})}function AA({target:e,host:t,profile:n,close:r,open:i,information:a,notice:o}){let{t:s,i18n:c}=Dn(),l=(0,m.useRef)(null),[u,d]=(0,m.useState)({x:e.x,y:e.y}),f=xb(),p=e.session,g=bA(p);(0,m.useLayoutEffect)(()=>{let t=l.current?.getBoundingClientRect();d({x:Math.max(8,Math.min(e.x,window.innerWidth-(t?.width||240)-8)),y:Math.max(8,Math.min(e.y,window.innerHeight-(t?.height||240)-8))}),l.current?.querySelector(`button:not(:disabled)`)?.focus({preventScroll:!0})},[e]),(0,m.useEffect)(()=>{let e=()=>r(!1),t=e=>{l.current?.contains(e.target)||r(!1)};return window.addEventListener(`resize`,e),window.addEventListener(`blur`,e),document.addEventListener(`scroll`,t,!0),document.addEventListener(`pointerdown`,t,!0),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`blur`,e),document.removeEventListener(`scroll`,t,!0),document.removeEventListener(`pointerdown`,t,!0)}},[r]);let _=async e=>{r();try{await f(e),o(s(`common.copied`))}catch{o(s(`history.copyFailed`))}},v=async()=>{r();try{let e=await t.revealHistoryFile(cb(n),p.id);o(s(e.revealed?`history.fileRevealed`:`history.revealFailed`))}catch{o(s(`history.revealFailed`))}},y=`flex min-h-10 w-full items-center gap-3 rounded-md px-3 text-left text-sm hover:bg-[var(--surface-hover)] focus:bg-[var(--accent-soft)] focus:outline-none disabled:opacity-40`;return(0,rm.createPortal)((0,h.jsxs)(`div`,{"aria-label":`${s(`history.sessionActions`)}: ${yA(p,s,c.language)}`,className:`fixed z-[70] w-64 max-w-[calc(100vw-16px)] max-h-[calc(100dvh-16px)] overflow-y-auto overscroll-contain rounded-xl border border-[var(--border)] bg-[var(--surface-raised)] p-1.5 text-[var(--text)] shadow-xl`,ref:l,role:`menu`,style:{left:u.x,top:u.y},onContextMenu:e=>e.preventDefault(),onKeyDown:e=>{if(e.key===`Escape`||e.key===`Tab`){e.preventDefault(),r();return}let t=Array.from(l.current?.querySelectorAll(`button:not(:disabled)`)||[]),n=t.indexOf(document.activeElement),i=e.key===`Home`?0:e.key===`End`?t.length-1:e.key===`ArrowDown`?(n+1)%t.length:e.key===`ArrowUp`?(n+t.length-1)%t.length:-1;i>=0&&(e.preventDefault(),t[i]?.focus())},children:[(0,h.jsxs)(`button`,{className:y,role:`menuitem`,tabIndex:-1,type:`button`,onClick:()=>{r(!1),i()},children:[(0,h.jsx)(Ei,{size:16}),s(`history.open`)]}),(0,h.jsxs)(`button`,{className:y,disabled:!p.nativeSessionId,role:`menuitem`,tabIndex:-1,type:`button`,onClick:()=>void _(p.nativeSessionId),children:[(0,h.jsx)(hi,{size:16}),s(`history.copyId`)]}),(0,h.jsxs)(`button`,{className:y,disabled:!g,role:`menuitem`,tabIndex:-1,title:s(`history.resumeHint`),type:`button`,onClick:()=>void _(g),children:[(0,h.jsx)(Ii,{size:16}),s(`history.copyResume`)]}),(0,h.jsx)(`div`,{className:`my-1 border-t border-[var(--border)]`,role:`separator`}),(0,h.jsxs)(`button`,{className:y,role:`menuitem`,tabIndex:-1,type:`button`,onClick:()=>{r(!1),a()},children:[(0,h.jsx)(wi,{size:16}),s(`history.sessionInformation`)]}),t?.revealHistoryFile?(0,h.jsxs)(`button`,{className:y,role:`menuitem`,tabIndex:-1,type:`button`,onClick:()=>void v(),children:[(0,h.jsx)(bi,{size:16}),s(`history.revealFile`)]}):null]}),document.body)}function jA(e){return typeof e==`string`||typeof e==`number`?String(e):Array.isArray(e)?e.map(jA).join(``):(0,m.isValidElement)(e)?jA(e.props.children):``}function MA({children:e}){let{t}=Dn(),[n,r]=(0,m.useState)(!1),[i,a]=(0,m.useState)(!1),o=xb(),s=async()=>{try{await o(jA(e).replace(/\n$/,``)),r(!0),a(!1),globalThis.setTimeout(()=>r(!1),1500)}catch{r(!1),a(!0)}};return(0,h.jsxs)(`div`,{className:`group relative my-4 overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--surface)]`,children:[(0,h.jsxs)(X,{"aria-label":t(`common.copy`),className:`absolute right-2 top-2 min-h-8 px-2`,onClick:()=>void s(),type:`button`,variant:`secondary`,children:[n?(0,h.jsx)(di,{size:14}):(0,h.jsx)(hi,{size:14}),(0,h.jsx)(`span`,{className:`sr-only`,children:t(n?`common.copied`:`common.copy`)})]}),(0,h.jsx)(`pre`,{className:`overflow-x-auto p-4 pr-12 text-sm leading-6`,children:e}),i?(0,h.jsx)(`p`,{className:`px-4 pb-3 text-sm text-[var(--danger)]`,role:`status`,children:t(`history.copyFailed`)}):null]})}function NA({text:e}){return(0,h.jsx)(`div`,{className:`min-w-0 break-words text-sm leading-7`,children:(0,h.jsx)(mD,{components:{a:({node:e,...t})=>(0,h.jsx)(`a`,{...t,className:`text-[var(--accent-strong)] underline underline-offset-2`,rel:`noreferrer`,target:`_blank`}),blockquote:({node:e,...t})=>(0,h.jsx)(`blockquote`,{...t,className:`my-3 border-l-4 border-[var(--border)] pl-4 text-[var(--muted)]`}),code:({node:e,...t})=>(0,h.jsx)(`code`,{...t,className:Qy(`rounded bg-[var(--surface)] px-1.5 py-0.5 font-mono text-[0.9em]`,t.className)}),h1:({node:e,...t})=>(0,h.jsx)(`h1`,{...t,className:`mb-3 mt-5 text-xl font-bold`}),h2:({node:e,...t})=>(0,h.jsx)(`h2`,{...t,className:`mb-3 mt-5 text-lg font-bold`}),h3:({node:e,...t})=>(0,h.jsx)(`h3`,{...t,className:`mb-2 mt-4 font-semibold`}),li:({node:e,...t})=>(0,h.jsx)(`li`,{...t,className:`my-1`}),ol:({node:e,...t})=>(0,h.jsx)(`ol`,{...t,className:`my-3 list-decimal pl-6`}),p:({node:e,...t})=>(0,h.jsx)(`p`,{...t,className:`my-3 whitespace-pre-wrap first:mt-0 last:mb-0`}),pre:({node:e,children:t})=>(0,h.jsx)(MA,{children:t}),table:({node:e,...t})=>(0,h.jsx)(`div`,{className:`my-4 overflow-x-auto`,children:(0,h.jsx)(`table`,{...t,className:`w-full border-collapse text-sm`})}),td:({node:e,...t})=>(0,h.jsx)(`td`,{...t,className:`border border-[var(--border)] px-3 py-2`}),th:({node:e,...t})=>(0,h.jsx)(`th`,{...t,className:`border border-[var(--border)] bg-[var(--surface)] px-3 py-2 text-left`}),ul:({node:e,...t})=>(0,h.jsx)(`ul`,{...t,className:`my-3 list-disc pl-6`})},remarkPlugins:[vA],children:e})})}function PA({core:e,profile:t,host:n,preferences:r}){let{t:i,i18n:a}=Dn(),[o,s]=(0,m.useState)(null),[c,l]=(0,m.useState)(null),[u,d]=(0,m.useState)(!1),[f,p]=(0,m.useState)(null),g=f?.session.id===o?f:null,[_,v]=(0,m.useState)(!1),[y,b]=(0,m.useState)(null),[x,S]=(0,m.useState)(``),[C,w]=(0,m.useState)(``),[T,E]=(0,m.useState)(`metadata`),D=(0,m.useRef)(null),[O,ee]=(0,m.useState)(`metadata`),[k,A]=(0,m.useState)(`all`),[j,M]=(0,m.useState)(0),[N,P]=(0,m.useState)(!1),[F,te]=(0,m.useState)(``),[ne,re]=(0,m.useState)(``),[ie,I]=(0,m.useState)(`all`),[L,ae]=(0,m.useState)(null),oe=JSON.stringify([t.id,t.revision,C,ne,ie,O,k]),[se,ce]=(0,m.useState)(null),le=se?.scope===oe?se:null,[ue,de]=(0,m.useState)(null),[fe,pe]=(0,m.useState)(``),me=(0,m.useRef)(null),he=(0,m.useRef)(null),ge=(0,m.useRef)(null),_e=(0,m.useRef)(new Map),ve=(0,m.useRef)(new Map),ye=(0,m.useCallback)((e=!0)=>{e&&le?.trigger.isConnected&&le.trigger.focus({preventScroll:!0}),ce(null)},[le]),be=(e,t,n)=>{let r=t.getBoundingClientRect();pe(``),ce({session:e,trigger:t,scope:oe,x:n?.x??r.left+24,y:n?.y??r.bottom})},xe={profile:cb(t),view:`projects`,page:1,pageSize:10,...C?{query:C}:{},...ne?{provider:ne}:{},archived:ie,searchScope:O,sessionKind:k},Se=rt({queryKey:[`history`,oe],queryFn:({signal:t})=>e.listHistory(xe,{signal:t}),gcTime:0,retry:!1,staleTime:1/0,refetchOnWindowFocus:!1,refetchOnReconnect:!1});(0,m.useEffect)(()=>{s(null),l(null),p(null),b(null),E(`metadata`),ee(`metadata`),A(`all`),P(!1),S(``),w(``),te(``),re(``),I(`all`)},[t.id,t.revision]),(0,m.useEffect)(()=>{s(null),l(null),p(null),b(null),_e.current.clear(),ve.current.clear()},[C,ne,ie,O,k]),(0,m.useEffect)(()=>{ce(null),de(null),pe(``)},[t.id,t.revision,C,ne,ie,O,k,Se.dataUpdatedAt]),(0,m.useEffect)(()=>{if(!o){p(null),b(null),v(!1);return}let n=new AbortController;return p(null),b(null),v(!0),e.getHistorySession({profile:cb(t),sessionId:o,...u?{metadataOnly:!0}:{messageLimit:200}},{signal:n.signal}).then(e=>{n.signal.aborted||p(e)}).catch(e=>{n.signal.aborted||b(N&&e instanceof Rr&&e.code===`INVALID_INPUT`?i(`history.parentUnavailable`):db(e,i))}).finally(()=>{n.signal.aborted||v(!1)}),()=>{n.abort(),p(null)}},[e,t.id,t.revision,o,i,j,N,u]),(0,m.useEffect)(()=>{g&&!le&&me.current?.focus({preventScroll:!0})},[g]),(0,m.useEffect)(()=>{he.current&&(he.current.scrollTop=0)},[o,t.id,t.revision]),(0,m.useEffect)(()=>{o||!L||(([_e.current.get(L),ve.current.get(L)].find(e=>e?.isConnected)||ge.current)?.focus({preventScroll:!0}),ae(null))},[Se.data,L,o]);let R=Se.data?.sessions??[],Ce=g?.session??(c?.id===o?c:R.find(e=>e.id===o)),we=Ce?yA(Ce,i,a.language):i(y?`history.sessionInformation`:`common.loading`),Te=()=>{o&&!L&&ae(o),s(null)},Ee=x.trim()!==C||F.trim()!==ne||T!==O,De=Ee||!!(C||ne||x||F)||O!==`metadata`||ie!==`all`||k!==`all`;return(0,h.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden`,"data-history-layout":!0,children:[(0,h.jsxs)(`div`,{className:Qy(`max-h-[45%] shrink-0 overflow-y-auto overscroll-contain`,o&&`hidden lg:block`),"data-history-controls":!0,children:[(0,h.jsx)(mb,{title:i(`history.title`),subtitle:i(`history.subtitle`),action:(0,h.jsxs)(X,{disabled:Se.isFetching,onClick:()=>{Se.refetch(),M(e=>e+1)},type:`button`,variant:`secondary`,children:[(0,h.jsx)(U,{className:Qy(Se.isFetching&&`animate-spin`),size:16}),i(`common.refresh`)]})}),(0,h.jsxs)(`form`,{className:`mb-3 grid grid-cols-[minmax(0,1fr)_auto] gap-2`,onSubmit:e=>{e.preventDefault(),w(x.trim()),ee(T),re(F.trim())},children:[(0,h.jsx)(tb,{ref:D,"aria-label":i(`common.search`),onChange:e=>S(e.target.value),placeholder:i(`history.searchPlaceholder`),value:x}),(0,h.jsxs)(X,{type:`submit`,children:[(0,h.jsx)(Mi,{size:16}),i(`common.search`)]}),De?(0,h.jsxs)(`div`,{className:`col-span-2 flex flex-wrap items-center gap-2`,children:[(0,h.jsx)(X,{type:`button`,size:`compact`,variant:`secondary`,onClick:()=>{S(``),w(``),te(``),re(``),E(`metadata`),ee(`metadata`),I(`all`),A(`all`),D.current?.focus()},children:i(`ux.clearFilters`)}),Ee?(0,h.jsx)(`p`,{className:`text-xs text-[var(--muted)]`,role:`status`,children:i(`ux.pendingFilters`)}):null]}):null,(0,h.jsxs)(`details`,{className:`col-span-2 rounded-lg border border-[var(--border)] bg-[var(--surface-raised)] px-3 py-2`,children:[(0,h.jsx)(`summary`,{className:`cursor-pointer text-xs text-[var(--muted)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--focus)]`,children:i(`history.filters`)}),(0,h.jsxs)(`div`,{className:`mt-2 grid gap-2 md:grid-cols-2 xl:grid-cols-4`,children:[(0,h.jsx)(tb,{"aria-label":i(`history.providerFilter`),onChange:e=>te(e.target.value),placeholder:i(`history.providerFilter`),value:F}),(0,h.jsxs)(`select`,{"aria-label":i(`history.archivedFilter`),className:`min-h-10 rounded-lg border border-[var(--border)] bg-[var(--input)] px-3`,onChange:e=>I(e.target.value),value:ie,children:[(0,h.jsx)(`option`,{value:`all`,children:i(`history.all`)}),(0,h.jsx)(`option`,{value:`active`,children:i(`history.active`)}),(0,h.jsx)(`option`,{value:`archived`,children:i(`history.archived`)})]}),(0,h.jsxs)(`select`,{"aria-label":i(`history.searchScope`),className:`min-h-10 rounded-lg border border-[var(--border)] bg-[var(--input)] px-3`,value:T,onChange:e=>E(e.target.value),children:[(0,h.jsx)(`option`,{value:`metadata`,children:i(`history.metadataSearch`)}),(0,h.jsx)(`option`,{value:`content`,children:i(`history.contentSearch`)})]}),(0,h.jsxs)(`select`,{"aria-label":i(`history.sessionType`),className:`min-h-10 rounded-lg border border-[var(--border)] bg-[var(--input)] px-3`,value:k,onChange:e=>A(e.target.value),children:[(0,h.jsx)(`option`,{value:`all`,children:i(`history.mainWithSubtasks`)}),(0,h.jsx)(`option`,{value:`main`,children:i(`history.mainSessions`)}),(0,h.jsx)(`option`,{value:`subagent`,children:i(`history.subtasks`)})]}),(0,h.jsx)(`p`,{className:`text-xs text-[var(--muted)] md:col-span-2 xl:col-span-4`,children:i(T===`content`?`history.contentSearchHint`:`history.metadataSearchHint`)})]})]})]})]}),(0,h.jsxs)(`div`,{className:`grid min-h-0 flex-1 grid-rows-1 gap-0 overflow-hidden rounded-xl border border-[var(--border)] lg:grid-cols-[minmax(240px,300px)_minmax(0,1fr)]`,children:[(0,h.jsxs)(eb,{"aria-busy":Se.isPending||Se.isFetching,className:Qy(`min-h-0 min-w-0 flex-col overflow-hidden rounded-none border-0 bg-[var(--surface)] p-0 shadow-none lg:border-r`,o?`hidden lg:flex`:`flex`),children:[(0,h.jsx)(`p`,{className:`shrink-0 px-3 py-2 text-xs text-[var(--muted)]`,children:i(`history.projectTreeHint`)}),(0,h.jsx)(`div`,{"aria-label":i(`history.listRegion`),className:`min-h-0 flex-1 overflow-y-auto overscroll-contain focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--focus)]`,ref:ge,role:`region`,tabIndex:0,"data-history-list":!0,children:Se.isPending?(0,h.jsx)(`div`,{className:`p-5`,"aria-live":`polite`,role:`status`,children:i(`common.loading`)}):Se.isError?(0,h.jsx)(`div`,{className:`p-5 text-[var(--danger)]`,role:`alert`,children:db(Se.error,i)}):Se.data?.projects?.length?(0,h.jsx)(kA,{scope:`${oe}:${Se.dataUpdatedAt}`,preferenceScope:JSON.stringify([t.id,t.revision]),preferences:r,core:e,input:xe,initialPage:Se.data,selectedId:o,onSelect:e=>{ae(null),de(null),d(!1),P(!1),l(e),s(e.id)},onMenu:be,registerButton:(e,t)=>{t?_e.current.set(e,t):_e.current.delete(e)},registerGroupButton:(e,t)=>{for(let n of e)t?ve.current.set(n,t):ve.current.delete(n)}},`${oe}:${Se.dataUpdatedAt}`):(0,h.jsx)(`div`,{className:`p-5 text-[var(--muted)]`,children:i(`history.empty`)})}),fe?(0,h.jsx)(`p`,{className:`shrink-0 px-3 py-2 text-xs`,role:`status`,children:fe}):null]}),(0,h.jsx)(eb,{className:Qy(`min-h-0 min-w-0 flex-col overflow-hidden rounded-none border-0 p-0 shadow-none`,o?`flex`:`hidden lg:flex`),children:o?(0,h.jsxs)(m.Fragment,{children:[(0,h.jsxs)(`div`,{className:`flex max-h-[40%] shrink-0 items-start justify-between gap-3 overflow-y-auto overscroll-contain border-b border-[var(--border)] p-3 md:p-4`,"data-history-detail-header":!0,children:[(0,h.jsxs)(`div`,{className:`min-w-0`,children:[(0,h.jsx)(`h2`,{className:`truncate text-lg font-semibold`,ref:me,tabIndex:-1,children:we}),g?(0,h.jsxs)(`div`,{className:`mt-1 flex flex-wrap gap-2 text-xs text-[var(--muted)]`,children:[(0,h.jsx)(`span`,{children:g.session.provider}),g.session.model?(0,h.jsx)(`span`,{children:g.session.model}):null,(0,h.jsx)(`span`,{children:ub(g.session.updatedAt,a.language)})]}):null]}),(0,h.jsxs)(`div`,{className:`flex shrink-0 gap-1`,children:[(0,h.jsx)(X,{"aria-label":i(`history.refreshDetail`),disabled:_,onClick:()=>M(e=>e+1),type:`button`,variant:`secondary`,children:(0,h.jsx)(U,{size:16})}),(0,h.jsxs)(X,{className:`lg:hidden`,onClick:Te,type:`button`,variant:`secondary`,children:[(0,h.jsx)(ui,{size:16}),i(`history.back`)]})]})]}),(0,h.jsxs)(`div`,{"aria-label":i(`history.detailRegion`),className:`min-h-0 flex-1 overflow-y-auto overscroll-contain p-3 focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--focus)] md:p-4`,ref:he,role:`region`,tabIndex:0,"data-history-detail-scroll":!0,children:[Ce&&ue===o?(0,h.jsxs)(`div`,{className:`mb-4 rounded-xl border border-[var(--border)] p-3`,children:[(0,h.jsx)(`div`,{className:`mb-2 flex justify-end`,children:(0,h.jsx)(X,{size:`compact`,onClick:()=>de(null),type:`button`,variant:`ghost`,children:i(`common.close`)})}),(0,h.jsx)(xA,{openInformation:!0,session:Ce,detail:g,host:n,profile:t,onOpenParent:e=>{de(null),d(!1),P(!0),L||ae(o),s(e)}},`${t.id}:${Ce.id}`)]}):null,u&&!_?(0,h.jsx)(X,{className:`mb-4`,onClick:()=>{d(!1),de(null)},type:`button`,variant:`secondary`,children:i(`history.open`)}):null,_?(0,h.jsx)(`span`,{"aria-live":`polite`,role:`status`,children:i(`common.loading`)}):y?(0,h.jsxs)(`div`,{className:`grid justify-items-start gap-3`,children:[(0,h.jsx)(`p`,{className:`text-[var(--danger)]`,role:`alert`,children:y}),(0,h.jsx)(X,{onClick:()=>M(e=>e+1),type:`button`,variant:`secondary`,children:i(`common.retry`)})]}):g&&!u?(0,h.jsxs)(`div`,{children:[g.truncated?(0,h.jsx)(`div`,{className:`mb-4 rounded-lg border border-[var(--warning)] bg-[var(--warning-soft)] p-3 text-sm`,children:i(`history.truncated`)}):null,(0,h.jsx)(`div`,{className:`grid gap-6`,children:g.messages.map(e=>e.role===`user`?(0,h.jsxs)(`article`,{className:`ml-auto max-w-[85%] rounded-2xl rounded-br-md bg-[var(--accent-soft)] px-4 py-3`,children:[(0,h.jsxs)(`div`,{className:`mb-1 text-xs font-semibold text-[var(--muted)]`,children:[i(`history.roles.user`),e.timestamp?(0,h.jsx)(`span`,{className:`ml-2 font-normal`,children:ub(e.timestamp,a.language)}):null]}),(0,h.jsx)(`div`,{className:`whitespace-pre-wrap break-words text-sm leading-7`,children:e.text})]},`${e.sequence}-${e.role}`):(0,h.jsxs)(`article`,{className:`min-w-0`,children:[(0,h.jsxs)(`div`,{className:`mb-2 text-xs font-semibold text-[var(--muted)]`,children:[i(`history.roles.assistant`),e.timestamp?(0,h.jsx)(`span`,{className:`ml-2 font-normal`,children:ub(e.timestamp,a.language)}):null]}),(0,h.jsx)(NA,{text:e.text})]},`${e.sequence}-${e.role}`))})]}):null]})]}):(0,h.jsx)(`div`,{className:`grid min-h-0 flex-1 place-items-center p-4 text-sm text-[var(--muted)]`,children:i(`history.select`)})})]}),le?(0,h.jsx)(AA,{target:le,host:n,profile:t,close:ye,open:()=>{de(null),d(!1),ae(null),P(!1),l(le.session),s(le.session.id)},information:()=>{de(le.session.id),d(!0),ae(null),P(!1),l(le.session),s(le.session.id)},notice:pe}):null]})}var FA=new Set([...jn,`prepare`,`validate_plan`,`scan`,`scan_rollout_files`,`check_locked_rollout_files`,`create_backup`,`rewrite_rollout_files`,`repair_workspace_roots`,`update_sqlite`,`update_config`,`verify_repair`,`clean_backups`,`create_restore_pre_snapshot`,`persist_restore_journal`,`apply_restore_targets`,`commit_restore`,`acknowledge_restore_commit`,`rollback_restore`,`prune`,`start`,`stop`,`automatic-sync`,`create`,`update`,`delete`,`export`,`check`,`download`,`install`,`startup-check`]),IA=new Set([...An,`WRITE_FAILED`,...Mn,`SQLITE_READONLY`,`SQLITE_FULL`]);function LA(e,t){return FA.has(e)?t(`logs.stages.${e}`,{defaultValue:t(`logs.unknownStage`)}):t(`logs.unknownStage`)}function RA(e,t){let n=IA.has(e)?e:`INTERNAL_ERROR`;return`${t(`errors.${n}`,{defaultValue:t(`errors.fallback`)})} (${n})`}function zA(e){return!!(e&&typeof e.snapshotAt==`string`&&Number.isFinite(Date.parse(e.snapshotAt)))}function BA(e){if(!zA(e)||e.operationInProgress||e.pendingRecovery||e.statusReadBlocked||!e.rolloutScanComplete||e.lockedRolloutFiles.length>0)return`unknown`;let t=e.alignment;return!t||typeof t!=`object`||Array.isArray(t)||t.sqliteReadable!==!0||typeof t.aligned!=`boolean`?`unknown`:t.aligned?`aligned`:`notAligned`}function VA(e,t){if(![`sync`,`switch`].includes(e)||!t||typeof t!=`object`||Array.isArray(t))return!1;let n=t.rewrittenSessionFiles;return typeof n==`number`&&Number.isSafeInteger(n)&&n>=100}function HA({afterOperation:e=!1}){let{t}=Dn();return(0,h.jsxs)(`details`,{className:`rounded-lg border border-[var(--border)] px-3 py-2 text-sm`,children:[(0,h.jsx)(`summary`,{className:`cursor-pointer rounded py-1 font-medium text-[var(--accent-strong)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus)]`,children:t(e?`sync.performance.resultLink`:`sync.performance.title`)}),(0,h.jsxs)(`div`,{className:`grid gap-2 pb-1 pt-2 text-[var(--muted)]`,children:[(0,h.jsx)(`p`,{children:t(`sync.performance.equalLength`)}),(0,h.jsx)(`p`,{children:t(`sync.performance.differentLength`)}),(0,h.jsx)(`p`,{children:t(`sync.performance.configuration`)})]})]})}var UA={completed:{tone:`success`,titleKey:`operationResult.completed.title`,descriptionKey:`operationResult.completed.description`,toastKey:`global.completed`},partial:{tone:`warning`,titleKey:`operationResult.partial.title`,descriptionKey:`operationResult.partial.description`,toastKey:`global.partial`},failed_rolled_back:{tone:`warning`,titleKey:`operationResult.failedRolledBack.title`,descriptionKey:`operationResult.failedRolledBack.description`,toastKey:`global.failed`},recovery_required:{tone:`danger`,titleKey:`operationResult.recoveryRequired.title`,descriptionKey:`operationResult.recoveryRequired.description`,toastKey:`global.failed`},cancelled:{tone:`warning`,titleKey:`operationResult.cancelled.title`,descriptionKey:`operationResult.cancelled.description`,toastKey:`global.cancelled`},stale:{tone:`warning`,titleKey:`operationResult.stale.title`,descriptionKey:`operationResult.stale.description`,toastKey:`global.stale`}};function WA(e){return UA[e]}function GA(e){if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=[],n=new Set([`targetProvider`,`targetModel`,`partialReason`,`failedStage`,`failureCode`]),r=new Set([`changedSessionFiles`,`sqliteRowsUpdated`,`sqliteProviderRowsUpdated`,`sqliteModelRowsUpdated`,`sqliteUserEventRowsUpdated`,`sqliteCwdRowsUpdated`,`updatedWorkspaceRoots`,`savedWorkspaceRootCount`,`resolvedOperationCount`]);for(let[i,a]of Object.entries(e)){if(i===`repairTargets`&&Array.isArray(a)){t.push([i,a.filter(e=>typeof e==`string`).join(`, `)]);continue}!(n.has(i)&&typeof a==`string`)&&!(r.has(i)&&typeof a==`number`&&Number.isSafeInteger(a)&&a>=0)||t.push([i,String(a)])}return t}function KA(e){if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e.skippedLockedRolloutFiles;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function qA(e){if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e.skippedChangedRolloutFiles;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function JA(e,t,n){return e===`failedStage`?LA(t,n):e===`failureCode`?RA(t,n):e===`partialReason`?n(`operationResult.partialReasons.${t}`,{defaultValue:n(`global.partial`)}):e===`repairTargets`?t.split(`, `).map(e=>n(`diagnostics.repairTargets.${e}`,{defaultValue:e})).join(`, `):t}function YA(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e.verification;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t;return![`verified`,`remaining`,`unavailable`].includes(String(n.status))||![`remainingRolloutFiles`,`remainingSqliteRows`,`remainingWorkspaceRoots`,`skippedSessions`].every(e=>typeof n[e]==`number`&&Number.isSafeInteger(n[e])&&n[e]>=0)?null:{status:n.status,remainingRolloutFiles:n.remainingRolloutFiles,remainingSqliteRows:n.remainingSqliteRows,remainingWorkspaceRoots:n.remainingWorkspaceRoots,skippedSessions:n.skippedSessions}}function XA({result:e,postWriteStatus:t,close:n,closeDisabled:r=!1,openBackupRestore:i,reviewOperation:a,restoreFocus:o}){let{t:s,i18n:c}=Dn(),l=t?.operationId===e?.operationId?t:void 0,u=l?.state===`received`?l.snapshot:void 0,d=BA(u),f=e?WA(e.outcome):null,p=e?GA(e.result):[],m=e?KA(e.result):[],g=e?qA(e.result):[],_=m.length+g.length,v=e?.result&&typeof e.result==`object`&&!Array.isArray(e.result)&&typeof e.result.partialReason==`string`?e.result.partialReason:null,y=e?.result&&typeof e.result==`object`&&!Array.isArray(e.result)&&e.result.retryRecommended===!0,b=e?YA(e.result):null,x=e?.outcome===`recovery_required`;return(0,h.jsx)(ib,{closeDisabled:r,closeLabel:s(`common.close`),description:r?s(`operationResult.resolveBeforeClose`):void 0,footer:(0,h.jsx)(X,{disabled:r,onClick:n,type:`button`,children:s(`common.close`)}),onOpenChange:e=>{!e&&!r&&n()},open:!!e,restoreFocus:o,title:s(`operationResult.title`),children:e&&f?(0,h.jsxs)(`div`,{"aria-live":`polite`,className:`grid gap-4`,role:x?`alert`:`status`,children:[(0,h.jsxs)(`div`,{className:f.tone===`danger`?`rounded-lg border border-[var(--danger)] bg-[var(--danger-soft)] p-4`:f.tone===`warning`?`rounded-lg border border-[var(--warning)] bg-[var(--warning-soft)] p-4`:`rounded-lg border border-[var(--success)] bg-[var(--success-soft)] p-4`,children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:s(f.titleKey)}),(0,h.jsx)(`p`,{className:`mt-1 text-sm`,children:s(f.descriptionKey)})]}),l?(0,h.jsxs)(eb,{children:[(0,h.jsx)(`h3`,{className:`text-sm font-semibold`,children:s(`ux.finalStatus`)}),l.state===`checking`?(0,h.jsx)(`p`,{className:`mt-2 text-sm`,children:s(`ux.finalChecking`)}):(0,h.jsxs)(`div`,{className:`mt-2 grid gap-2 text-sm`,children:[u?(0,h.jsxs)(`p`,{children:[s(`common.provider`),`: `,(0,h.jsx)(`span`,{className:`break-all font-semibold`,children:u.currentProvider})]}):null,(0,h.jsx)(`p`,{children:s(d===`unknown`?`ux.finalUnavailable`:`overview.${d}`)}),u?(0,h.jsxs)(`p`,{className:`text-xs text-[var(--muted)]`,children:[s(`overview.snapshot`),`: `,ub(u.snapshotAt,c.language)]}):null]})]}):null,e.backup?(0,h.jsxs)(`div`,{className:`rounded-lg border border-[var(--success)] bg-[var(--success-soft)] p-4 text-sm font-medium text-[var(--success)]`,children:[(0,h.jsx)(`p`,{children:s(`operationResult.backupCreated`)}),(0,h.jsxs)(`p`,{className:`mt-2 break-all font-mono text-xs`,children:[s(`operationResult.backupId`),`: `,e.backup.backupId]}),i?(0,h.jsx)(X,{className:`mt-3`,onClick:()=>i(e.backup.backupId),type:`button`,variant:`secondary`,children:s(`operationResult.openBackupRestore`)}):null]}):null,p.length?(0,h.jsx)(eb,{children:(0,h.jsx)(`dl`,{className:`grid gap-3 text-sm`,children:p.map(([e,t])=>(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:s(`operationResult.fields.${e}`,{defaultValue:e})}),(0,h.jsx)(`dd`,{className:`mt-1 break-words`,children:JA(e,t,s)})]},e))})}):null,VA(e.operation,e.result)?(0,h.jsx)(HA,{afterOperation:!0},e.operationId):null,e.warnings.length?(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:s(`common.warnings`)}),(0,h.jsx)(`ul`,{className:`mt-2 list-disc space-y-1 pl-5 text-sm`,children:e.warnings.map((e,t)=>(0,h.jsx)(`li`,{children:pb(e,s)},`${t}-${e}`))})]}):null,_?(0,h.jsx)(`p`,{className:`rounded-lg border border-[var(--warning)] bg-[var(--warning-soft)] p-3 text-sm`,children:s(`operationResult.skippedCount`,{count:_})}):null,y?(0,h.jsx)(`p`,{className:`text-sm text-[var(--warning)]`,children:s(v===`locked-session`?`operationResult.retryAfterSession`:`operationResult.retryFreshPlan`)}):null,y&&a?(0,h.jsx)(X,{onClick:a,type:`button`,variant:`secondary`,children:s(`operationResult.reviewOperation`)}):null,b?(0,h.jsxs)(eb,{children:[(0,h.jsx)(`h3`,{className:`text-sm font-semibold`,children:s(`operationResult.verification.title`)}),(0,h.jsx)(`p`,{className:`mt-1 text-sm text-[var(--muted)]`,children:s(`operationResult.verification.status.${b.status}`)}),b.status===`remaining`?(0,h.jsxs)(`dl`,{className:`mt-3 grid gap-2 text-sm sm:grid-cols-2`,children:[(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:s(`operationResult.verification.remainingRolloutFiles`)}),(0,h.jsx)(`dd`,{children:b.remainingRolloutFiles})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:s(`operationResult.verification.remainingSqliteRows`)}),(0,h.jsx)(`dd`,{children:b.remainingSqliteRows})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:s(`operationResult.verification.remainingWorkspaceRoots`)}),(0,h.jsx)(`dd`,{children:b.remainingWorkspaceRoots})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:s(`operationResult.verification.skippedSessions`)}),(0,h.jsx)(`dd`,{children:b.skippedSessions})]})]}):null]}):null,p.length?(0,h.jsx)(`p`,{className:`text-xs text-[var(--muted)]`,children:s(`operationResult.changeCountersHint`)}):null,r?(0,h.jsx)(`p`,{className:`text-sm text-[var(--danger)]`,children:s(`operationResult.resolveBeforeClose`)}):null]}):null})}var ZA=[`copyTailMs`,`flushMs`,`replaceMs`,`cleanupMs`,`restoreMtimeMs`],QA=[`workerStartupMs`,`workerCloseMs`,`requestRoundTripMs`,`workerMs`,`sourceOpenMs`,`readHeaderMs`,`tempCreateMs`];function $A({timing:e,pending:t}){let{t:n}=Dn();if(!e)return(0,h.jsx)(`p`,{className:`text-sm text-[var(--muted)]`,children:n(t?`logs.fileTiming.pending`:`logs.fileTiming.unavailable`)});let r=e=>n(e<1e3?`logs.fileTiming.milliseconds`:`logs.seconds`,{value:(e<1e3?e:e/1e3).toFixed(e<1e3?1:3)}),i=t=>(0,h.jsx)(`dl`,{className:`mt-2 grid gap-2 text-sm`,children:t.map(t=>(0,h.jsxs)(`div`,{className:`flex items-baseline justify-between gap-3`,children:[(0,h.jsx)(`dt`,{children:n(`logs.fileTiming.phases.${t}`)}),(0,h.jsx)(`dd`,{className:`shrink-0 tabular-nums`,children:r(e[t])})]},t))});return(0,h.jsxs)(`section`,{"aria-label":n(`logs.fileTiming.title`),className:`rounded-lg border border-[var(--border)] p-3`,children:[(0,h.jsxs)(`div`,{className:`flex flex-wrap items-baseline justify-between gap-2`,children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:n(`logs.fileTiming.title`)}),(0,h.jsx)(`span`,{className:`text-sm tabular-nums`,children:r(e.totalMs)})]}),(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:n(`logs.fileTiming.files`,{measured:e.measuredFiles,attempted:e.attemptedFiles,inPlace:e.inPlaceFiles,rewritten:e.rewrittenFiles,skipped:e.skippedFiles})}),e.measuredFiles{try{await r(t),a(n(`common.copied`))}catch{a(n(`history.copyFailed`))}};return(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:e}),(0,h.jsxs)(`dd`,{className:`flex min-w-0 items-center gap-2`,children:[(0,h.jsx)(`span`,{className:`min-w-0 break-all font-mono text-xs`,children:t}),(0,h.jsx)(X,{"aria-label":`${n(`common.copy`)} ${e}`,onClick:()=>void o(),type:`button`,variant:`ghost`,children:n(`common.copy`)}),(0,h.jsx)(`span`,{"aria-live":`polite`,className:`text-xs`,children:i})]})]})}function cj({host:e,profileId:t,profileRevision:n,openBackupRestore:r,reviewOperation:i}){let{t:a,i18n:o}=Dn(),[s,c]=(0,m.useState)(1),[l,u]=(0,m.useState)(``),[d,f]=(0,m.useState)(``),[p,g]=(0,m.useState)(t),[_,v]=(0,m.useState)(null),y=(0,m.useRef)(null),b=(0,m.useRef)(null),x=(0,m.useRef)(null),S=rt({queryKey:[`profiles`],queryFn:({signal:t})=>e.listProfiles(t),retry:!1,staleTime:1/0,refetchOnWindowFocus:!1,refetchOnReconnect:!1}),C=rt({queryKey:[`operation-logs`,s,p,l,d],queryFn:({signal:t})=>e.listOperationLogs({page:s,pageSize:ej,...p?{profileId:p}:{},...l?{operation:l}:{},...d?{status:d}:{}},t),enabled:!!e.listOperationLogs,retry:!1,staleTime:1/0,refetchOnWindowFocus:!1,refetchOnReconnect:!1}),w=rt({queryKey:[`operation-log`,_],queryFn:({signal:t})=>e.getOperationLog(_,t),enabled:!!(_&&e.getOperationLog),retry:!1,staleTime:1/0,refetchOnWindowFocus:!1,refetchOnReconnect:!1});(0,m.useEffect)(()=>{g(t),c(1)},[t]),(0,m.useEffect)(()=>{v(null),y.current&&(y.current.scrollTop=0)},[s,p,l,d,t,n]),(0,m.useEffect)(()=>{_&&!C.isFetching&&C.isSuccess&&!C.data.entries.some(e=>e.id===_)&&v(null)},[C.data,C.isFetching,C.isSuccess,_]),(0,m.useLayoutEffect)(()=>{if(!_){b.current?.parentElement?.contains(document.activeElement)&&globalThis.requestAnimationFrame(()=>{(x.current?.isConnected?x.current:y.current)?.focus({preventScroll:!0})});return}b.current&&(b.current.scrollTop=0,globalThis.matchMedia?.(`(min-width: 1024px)`).matches||b.current.focus({preventScroll:!0}))},[_]);let T=()=>{v(null),globalThis.requestAnimationFrame(()=>(x.current?.isConnected?x.current:y.current)?.focus({preventScroll:!0}))},E=w.data===void 0?C.data?.entries.find(e=>e.id===_)??null:w.data?.id===_?w.data:null,D=E?Object.entries(E.counts??{}).filter(([e])=>rj.has(e)):[],O=E?.previewCounts?[[`rolloutFilesToChange`,E.previewCounts.rolloutFilesToChange],[`sqliteRowsToChange`,E.previewCounts.sqliteRowsToChange],[`lockedRolloutFiles`,E.previewCounts.lockedRolloutFiles]]:[];return(0,h.jsxs)(`section`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden`,"data-testid":`operation-logs-workspace`,children:[(0,h.jsxs)(`div`,{className:Qy(`max-h-[45%] shrink-0 overflow-y-auto overscroll-contain`,_&&`hidden lg:block`),children:[(0,h.jsx)(mb,{title:a(`logs.title`),subtitle:a(`logs.subtitle`),action:(0,h.jsxs)(X,{disabled:C.isFetching||w.isFetching,onClick:()=>{C.refetch(),_&&w.refetch()},type:`button`,variant:`secondary`,children:[(0,h.jsx)(U,{className:Qy((C.isFetching||w.isFetching)&&`animate-spin`),size:16}),a(`common.refresh`)]})}),(0,h.jsxs)(`div`,{className:`mb-3 flex flex-wrap gap-2 text-sm [&>select]:max-w-full`,children:[(0,h.jsxs)(`select`,{"aria-label":a(`logs.profileFilter`),className:`min-h-10 rounded-lg border border-[var(--border)] bg-[var(--input)] px-3`,onChange:e=>{g(e.target.value),c(1),v(null)},value:p,children:[(0,h.jsx)(`option`,{value:``,children:a(`logs.allProfiles`)}),S.data?.map(e=>(0,h.jsx)(`option`,{value:e.id,children:fb(e,a)},e.id))]}),(0,h.jsxs)(`select`,{"aria-label":a(`logs.operationFilter`),className:`min-h-10 rounded-lg border border-[var(--border)] bg-[var(--input)] px-3`,onChange:e=>{u(e.target.value),c(1),v(null)},value:l,children:[(0,h.jsx)(`option`,{value:``,children:a(`logs.allOperations`)}),tj.map(e=>(0,h.jsx)(`option`,{value:e,children:oj(e,a)},e))]}),(0,h.jsxs)(`select`,{"aria-label":a(`logs.statusFilter`),className:`min-h-10 rounded-lg border border-[var(--border)] bg-[var(--input)] px-3`,onChange:e=>{f(e.target.value),c(1),v(null)},value:d,children:[(0,h.jsx)(`option`,{value:``,children:a(`logs.allStatuses`)}),nj.map(e=>(0,h.jsx)(`option`,{value:e,children:a(`logs.statuses.${e}`)},e))]})]})]}),(0,h.jsxs)(`div`,{className:`grid min-h-0 flex-1 gap-4 overflow-hidden lg:grid-cols-[minmax(240px,0.85fr)_minmax(0,1.4fr)]`,children:[(0,h.jsxs)(eb,{className:Qy(`min-h-0 min-w-0 flex-col overflow-hidden p-0`,_?`hidden lg:flex`:`flex`),children:[(0,h.jsx)(`div`,{"aria-label":a(`logs.listRegion`),className:`min-h-0 flex-1 overflow-y-auto overscroll-contain focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--focus)]`,ref:y,role:`region`,tabIndex:0,children:C.isPending?(0,h.jsx)(`div`,{className:`p-5`,children:a(`common.loading`)}):C.isError?(0,h.jsx)(`div`,{className:`p-5 text-[var(--danger)]`,role:`alert`,children:db(C.error,a)}):C.data?.entries.length?(0,h.jsx)(`div`,{className:`divide-y divide-[var(--border)]`,children:C.data.entries.map(e=>(0,h.jsxs)(`button`,{"aria-pressed":e.id===_,className:Qy(`block w-full px-4 py-3 text-left hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--focus)]`,e.id===_&&`bg-[var(--accent-soft)]`),onClick:t=>{x.current=t.currentTarget,v(e.id)},type:`button`,children:[(0,h.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,h.jsx)(`span`,{className:`font-semibold`,children:oj(e.operation,a)}),(0,h.jsx)(rb,{tone:aj(e.status),children:a(`logs.statuses.${e.status}`)})]}),(0,h.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-3 text-xs text-[var(--muted)]`,children:[(0,h.jsx)(`span`,{children:ub(e.startedAt,o.language)}),(0,h.jsx)(`span`,{children:ij(e.wallDurationMs??e.activeDurationMs,a)})]})]},e.id))}):(0,h.jsx)(`div`,{className:`p-5 text-[var(--muted)]`,children:a(`logs.empty`)})}),C.data?(0,h.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center justify-between gap-2 border-t border-[var(--border)] p-3`,children:[(0,h.jsx)(`span`,{className:`text-xs text-[var(--muted)]`,children:a(`logs.pageSummary`,{page:s,total:C.data.total})}),(0,h.jsxs)(`div`,{className:`flex gap-2`,children:[(0,h.jsx)(X,{disabled:s<=1||C.isFetching,onClick:()=>c(e=>Math.max(1,e-1)),type:`button`,variant:`secondary`,children:a(`history.previous`)}),(0,h.jsx)(X,{disabled:!C.data.hasNextPage||C.isFetching,onClick:()=>c(e=>e+1),type:`button`,variant:`secondary`,children:a(`history.next`)})]})]}):null]}),(0,h.jsxs)(eb,{className:Qy(`min-h-0 min-w-0 flex-col overflow-hidden p-0`,_?`flex`:`hidden lg:flex`),children:[(0,h.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-b border-[var(--border)] p-3`,children:[(0,h.jsxs)(X,{className:`lg:hidden`,onClick:T,size:`compact`,type:`button`,variant:`ghost`,children:[(0,h.jsx)(ui,{size:16}),a(`logs.backToList`)]}),(0,h.jsx)(`span`,{className:`hidden text-sm font-semibold lg:inline`,children:a(`logs.detailRegion`)}),_?(0,h.jsx)(X,{"aria-label":a(`logs.refreshDetail`),className:`lg:hidden`,disabled:w.isFetching,onClick:()=>void w.refetch(),size:`icon`,type:`button`,variant:`ghost`,children:(0,h.jsx)(U,{size:16,className:Qy(w.isFetching&&`animate-spin`)})}):null]}),(0,h.jsx)(`div`,{"aria-label":a(`logs.detailRegion`),className:`min-h-0 flex-1 overflow-y-auto overscroll-contain p-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--focus)]`,ref:b,role:`region`,tabIndex:0,children:_?w.isFetching&&!E?(0,h.jsx)(`div`,{children:a(`common.loading`)}):w.isError?(0,h.jsxs)(`div`,{className:`text-[var(--danger)]`,role:`alert`,children:[db(w.error,a),(0,h.jsx)(X,{className:`mt-3`,disabled:w.isFetching,onClick:()=>void w.refetch(),type:`button`,variant:`secondary`,children:a(`common.retry`)})]}):E?(0,h.jsxs)(`div`,{className:`grid min-w-0 gap-5`,children:[(0,h.jsxs)(`div`,{children:[(0,h.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,h.jsx)(`h2`,{className:`text-lg font-semibold`,children:oj(E.operation,a)}),(0,h.jsx)(rb,{tone:aj(E.status),children:a(`logs.statuses.${E.status}`)})]}),(0,h.jsxs)(`dl`,{className:`mt-4 grid gap-2 text-sm sm:grid-cols-2`,children:[(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:a(`logs.startedAt`)}),(0,h.jsx)(`dd`,{children:ub(E.startedAt,o.language)})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:a(`logs.completedAt`)}),(0,h.jsx)(`dd`,{children:E.completedAt?ub(E.completedAt,o.language):`—`})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:a(`logs.activeDuration`)}),(0,h.jsx)(`dd`,{children:ij(E.activeDurationMs,a)})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:a(`logs.wallDuration`)}),(0,h.jsx)(`dd`,{children:ij(E.wallDurationMs,a)})]}),E.targetProvider?(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:a(`logs.targetProvider`)}),(0,h.jsx)(`dd`,{className:`break-all font-mono text-xs`,children:E.targetProvider})]}):null]})]}),VA(E.operation,E.counts)?(0,h.jsx)(HA,{afterOperation:!0}):null,[`sync`,`switch`,`watch`].includes(E.operation)?(0,h.jsx)($A,{timing:E.fileUpdateTiming,pending:[`running`,`awaiting-confirmation`].includes(E.status)}):null,E.failedStage||E.failureCode||E.partialReason?(0,h.jsxs)(`dl`,{className:`grid gap-3 rounded-lg border border-[var(--warning)] bg-[var(--warning-soft)] p-3 text-sm`,children:[E.failedStage?(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{children:a(`operationResult.fields.failedStage`)}),(0,h.jsx)(`dd`,{children:LA(E.failedStage,a)})]}):null,E.failureCode?(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{children:a(`operationResult.fields.failureCode`)}),(0,h.jsx)(`dd`,{children:RA(E.failureCode,a)})]}):null,E.partialReason?(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{children:a(`operationResult.fields.partialReason`)}),(0,h.jsx)(`dd`,{children:a(`operationResult.partialReasons.${E.partialReason}`,{defaultValue:a(`global.partial`)})})]}):null]}):null,E.retryRecommended?(0,h.jsx)(`p`,{className:`text-sm text-[var(--warning)]`,children:a(E.partialReason===`locked-session`?`operationResult.retryAfterSession`:`operationResult.retryFreshPlan`)}):null,(E.backupId||E.retryRecommended)&&(r||i)?E.profileId===t&&E.profileRevision!==void 0&&E.profileRevision===n?(0,h.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[E.retryRecommended&&i&&[`sync`,`switch`,`repair`,`watch`].includes(E.operation)?(0,h.jsx)(X,{onClick:()=>i(E.operation),type:`button`,variant:`secondary`,children:a(`operationResult.reviewOperation`)}):null,E.backupId&&r?(0,h.jsx)(X,{onClick:()=>r(E.backupId),type:`button`,variant:`secondary`,children:a(`operationResult.openBackupRestore`)}):null]}):(0,h.jsx)(`p`,{className:`text-sm text-[var(--muted)]`,children:a(`logs.profileMismatch`)}):null,O.length?(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:a(`logs.previewCounts`)}),(0,h.jsx)(`dl`,{className:`mt-2 grid gap-2 text-sm sm:grid-cols-2`,children:O.map(([e,t])=>(0,h.jsxs)(`div`,{className:`flex justify-between gap-3 rounded-lg border border-[var(--border)] px-3 py-2`,children:[(0,h.jsx)(`dt`,{children:a(`logs.previewCountLabels.${e}`)}),(0,h.jsx)(`dd`,{children:t})]},e))})]}):null,E.switchPlan?(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:a(`logs.switchPlan`)}),(0,h.jsxs)(`dl`,{className:`mt-2 grid gap-2 text-sm sm:grid-cols-2`,children:[(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:a(`logs.providerChange`)}),(0,h.jsxs)(`dd`,{className:`break-all font-mono text-xs`,children:[E.switchPlan.previousProvider,` → `,E.switchPlan.targetProvider]})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:a(`logs.rootModelChange`)}),(0,h.jsxs)(`dd`,{className:`break-all font-mono text-xs`,children:[E.switchPlan.previousRootModel??a(`logs.notSet`),` → `,E.switchPlan.targetRootModel??a(`logs.notSet`)]})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:a(`logs.modelMode`)}),(0,h.jsx)(`dd`,{children:a(`plan.modelModes.${E.switchPlan.modelMode}`)})]})]}),E.status===`partial`?(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--warning)]`,children:a(`logs.switchPlanPartial`)}):null]}):E.operation===`switch`?(0,h.jsx)(`p`,{className:`text-sm text-[var(--muted)]`,children:a(`logs.switchPlanUnavailable`)}):null,D.length?(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:a(`logs.counts`)}),(0,h.jsx)(`dl`,{className:`mt-2 grid gap-2 text-sm sm:grid-cols-2`,children:D.map(([e,t])=>(0,h.jsxs)(`div`,{className:`flex justify-between gap-3 rounded-lg border border-[var(--border)] px-3 py-2`,children:[(0,h.jsx)(`dt`,{children:a(`logs.countLabels.${e}`)}),(0,h.jsx)(`dd`,{children:t})]},e))})]}):null,(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:a(`logs.timeline`)}),(0,h.jsx)(`ol`,{className:`mt-3 grid gap-3`,children:E.stages.map((e,t)=>(0,h.jsxs)(`li`,{className:`rounded-lg border border-[var(--border)] p-3`,children:[(0,h.jsxs)(`div`,{className:`flex justify-between gap-3`,children:[(0,h.jsx)(`span`,{className:`font-medium`,children:LA(e.stage,a)}),(0,h.jsx)(`span`,{className:`text-sm text-[var(--muted)]`,children:ij(e.durationMs,a)})]}),(0,h.jsxs)(`div`,{className:`mt-1 text-xs text-[var(--muted)]`,children:[a(`logs.stageStatuses.${e.status}`,{defaultValue:a(`logs.unknownStage`)}),e.count===void 0?``:` · ${e.count}`,` · `,ub(e.startedAt,o.language),e.completedAt?` → ${ub(e.completedAt,o.language)}`:``]})]},`${e.stage}-${t}`))})]}),E.errorCode?(0,h.jsxs)(`div`,{className:`rounded-lg border border-[var(--danger)] bg-[var(--danger-soft)] p-3 text-sm`,role:`alert`,children:[(0,h.jsx)(`p`,{children:a(`errors.${E.errorCode}`,{defaultValue:a(`errors.fallback`)})}),E.errorReason?(0,h.jsxs)(`p`,{className:`mt-1 text-[var(--muted)]`,children:[a(`logs.errorReason`),`: `,a(`logs.errorReasons.${E.errorReason}`)]}):null]}):null,E.warnings.length?(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:a(`common.warnings`)}),(0,h.jsx)(`ul`,{className:`mt-2 list-disc pl-5 text-sm`,children:E.warnings.map((e,t)=>(0,h.jsx)(`li`,{children:pb(e,a)},`${t}-${e}`))})]}):null,(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:a(`logs.identifiers`)}),(0,h.jsxs)(`dl`,{className:`mt-3 grid gap-3 text-sm sm:grid-cols-2`,children:[(0,h.jsx)(sj,{label:a(`logs.logId`),value:E.id}),E.requestIds.map((e,t)=>(0,h.jsx)(sj,{label:`${a(`logs.requestId`)} ${t+1}`,value:e},e)),(0,h.jsx)(sj,{label:a(`logs.planId`),value:E.planId}),(0,h.jsx)(sj,{label:a(`logs.operationId`),value:E.operationId}),(0,h.jsx)(sj,{label:a(`logs.backupId`),value:E.backupId})]})]})]},E.id):(0,h.jsx)(`div`,{className:`text-sm text-[var(--muted)]`,role:`status`,children:a(`logs.detailUnavailable`)}):(0,h.jsx)(`div`,{className:`grid h-full place-items-center text-sm text-[var(--muted)]`,children:a(`logs.select`)})})]})]})]})}function lj(e,t,n){return t==null||t===``?n(`common.none`):typeof t==`boolean`?n(t?`common.yes`:`common.no`):e===`modelMode`&&typeof t==`string`?n(`plan.modelModes.${t}`,{defaultValue:t}):e===`targets`&&Array.isArray(t)?t.map(e=>n(`diagnostics.repairTargets.${String(e)}`,{defaultValue:String(e)})).join(`, `):Array.isArray(t)?n(`plan.items`,{count:t.length}):String(t)}function uj(e){let t=e.impact.repairPreview;return Array.isArray(t)?t.flatMap(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e;if(typeof t.sessionId!=`string`||!Array.isArray(t.changes))return[];let n=t.changes.flatMap(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e;return[`models`,`cwd`,`userEvent`].includes(String(t.target))&&typeof t.before==`string`&&typeof t.after==`string`?[{target:t.target,before:t.before,after:t.after}]:[]});return n.length?[{sessionId:t.sessionId,changes:n}]:[]}):[]}function dj(e,t){if(e.target.scope!==`selected`)return null;let n=e.target.sessionIds;return Array.isArray(n)&&n.every(e=>typeof e==`string`)?n:t.map(e=>e.sessionId)}function fj(e,t,n){if(e===`models`)return t;let r=t===`different`||t===`rollout-cwd`||t===`false`||t===`true`?t:null;return r?n(`plan.repairPreview.markers.${r}`):t}function pj({plan:e,applying:t,cancelling:n,confirmDisabled:r=!1,currentModel:i,directSyncPhase:a=null,progress:o,repairSelectionPending:s=!1,repairProgress:c,repairSelectionFailed:l=!1,repairDraftChanged:u,refineRepairSessions:d,close:f,apply:p,cancel:g,restoreFocus:_}){let{t:v,i18n:y}=Dn(),b=e?v(`plan.operations.${e.operation}`,{defaultValue:e.operation}):``,x=e?v(`plan.titles.${e.operation}`,{defaultValue:v(`plan.title`)}):v(`plan.title`),S=e?v(`plan.confirmActions.${e.operation}`,{defaultValue:v(`common.confirm`)}):v(`common.confirm`),C=e?[[`provider`,v(`common.provider`)],...e.operation===`switch`?[]:[[`model`,v(`common.model`)]],[`modelMode`,v(`plan.fields.modelMode`)],[`targets`,v(`plan.fields.repairTargets`)],[`backupId`,v(`operationResult.backupId`)],[`restoreConfig`,v(`plan.fields.restoreConfig`)],[`restoreDatabase`,v(`plan.fields.restoreDatabase`)],[`restoreSessions`,v(`plan.fields.restoreSessions`)],[`allowSqliteHomeRelocation`,v(`plan.fields.relocation`)]].filter(([t])=>t in e.target):[],w=e?[[`rolloutFilesToChange`,v(`plan.fields.rolloutFiles`)],...e.operation===`repair`?[[`repairPreviewTotal`,v(`plan.fields.affectedSessions`)],[`sqliteRowsToChange`,v(`plan.fields.sqliteFields`)],[`sqliteModelRowsToChange`,v(`plan.fields.sqliteModels`)],[`sqliteCwdRowsToChange`,v(`plan.fields.sqliteCwd`)],[`sqliteUserEventRowsToChange`,v(`plan.fields.sqliteUserEvent`)]]:[[`sqliteRowsToChange`,v(`plan.fields.sqliteRows`)]],[`workspaceRootsToChange`,v(`plan.fields.workspaceSettings`)],[`stateDbFilesToChange`,v(`plan.fields.stateDbFiles`)],[`configFilesToChange`,v(`plan.fields.configFiles`)],[`lockedRolloutFiles`,v(`plan.fields.lockedRollouts`)]].filter(([t])=>t in e.impact):[],T=e?.operation===`switch`?`${lj(`model`,i,v)} → ${lj(`model`,e.target.model,v)}`:null,E=e?.impact.sessionActivity,D=E&&typeof E==`object`&&!Array.isArray(E)&&E.state===`checked`&&typeof E.count==`number`?E.count:v(`overview.usageUnknown`),O=e?.operation===`repair`&&Array.isArray(e.target.targets)&&e.target.targets.includes(`workspaceRoots`),ee=[`savedRoots`,`projectOrder`,`activeRoots`,`labels`,`openTargets`,`settingsBackup`].filter(t=>e?.operation===`repair`&&Array.isArray(e.impact.workspaceSettingsChangeKinds)&&e.impact.workspaceSettingsChangeKinds.includes(t)),k=(0,m.useMemo)(()=>e?.operation===`repair`?uj(e):[],[e]),A=(0,m.useMemo)(()=>e?.operation===`repair`?dj(e,k):null,[e,k]),[j,M]=(0,m.useState)(A);(0,m.useEffect)(()=>{M(A)},[e?.planId,A]);let N=e?.operation===`repair`&&!O?j===null!=(A===null)||JSON.stringify(j??[])!==JSON.stringify(A??[]):!1;(0,m.useEffect)(()=>{u?.(N)},[u,N]);let P=n=>{!e||O||s||t||M(n)};return(0,h.jsx)(ib,{closeDisabled:t||s,closeLabel:v(`common.close`),description:a?v(`sync.directHint`):e?`${b} · ${v(`plan.expires`)} ${ub(e.expiresAt,y.language)}`:void 0,footer:(0,h.jsxs)(m.Fragment,{children:[(0,h.jsx)(X,{disabled:t||s,onClick:f,type:`button`,variant:`secondary`,children:v(`common.close`)}),t?(0,h.jsx)(X,{disabled:n,onClick:g,type:`button`,variant:`danger`,children:v(n?`plan.cancelling`:`plan.cancelOperation`)}):(0,h.jsx)(X,{disabled:r||l||s||N,onClick:p,type:`button`,children:S})]}),onOpenChange:e=>{!e&&!t&&!s&&f()},open:!!(e||a),restoreFocus:_,title:a?v(a===`preparing`?`sync.preparingDirect`:`sync.runningDirect`):x,children:a?(0,h.jsxs)(eb,{"aria-live":`polite`,role:`status`,children:[(0,h.jsx)(`h3`,{className:`text-sm font-semibold`,children:v(`plan.progress`)}),(0,h.jsx)(`p`,{className:`mt-2 text-sm`,children:o?`${v(`plan.stages.${o.stage}`,{defaultValue:v(`common.processing`)})} · ${v(`plan.statuses.${o.status}`,{defaultValue:v(`common.processing`)})}${o.count===void 0?``:` · ${o.count}`}`:v(a===`preparing`?`sync.preparingDirect`:`plan.starting`)}),o?.progress===void 0?null:(0,h.jsx)(`progress`,{"aria-label":v(`plan.progress`),className:`mt-3 w-full`,max:1,value:o.progress}),n?(0,h.jsx)(`p`,{className:`mt-3 text-sm text-[var(--warning)]`,children:v(`plan.cancelPending`)}):null]}):e?(0,h.jsxs)(`div`,{className:`grid gap-4`,children:[(0,h.jsxs)(eb,{children:[(0,h.jsx)(`h3`,{className:`mb-2 text-sm font-semibold`,children:v(`plan.target`)}),(0,h.jsxs)(`dl`,{children:[T?(0,h.jsx)(hb,{label:v(`plan.fields.rootModelChange`),value:T}):null,C.map(([t,n])=>(0,h.jsx)(hb,{label:n,value:lj(t,e.target[t],v)},t))]})]}),e.operation===`repair`?(0,h.jsxs)(eb,{children:[(0,h.jsx)(`h3`,{className:`mb-2 text-sm font-semibold`,children:v(`plan.repairPreview.effectsTitle`)}),(0,h.jsx)(`ul`,{className:`mb-3 grid gap-2 text-sm text-[var(--muted)]`,children:[`models`,`cwd`,`userEvent`,`workspaceRoots`].filter(t=>Array.isArray(e.target.targets)&&e.target.targets.includes(t)).map(e=>(0,h.jsx)(`li`,{children:v(`diagnostics.repairTargetHints.${e}`)},e))}),(0,h.jsx)(`p`,{className:`mb-4 text-sm text-[var(--muted)]`,children:v(`plan.repairPreview.unchanged`)}),(0,h.jsx)(`h3`,{className:`mb-2 text-sm font-semibold`,children:v(`plan.repairPreview.title`)}),(0,h.jsx)(`p`,{className:`text-sm text-[var(--muted)]`,children:v(O?`plan.repairPreview.workspaceGlobal`:`plan.repairPreview.hint`)}),O?null:(0,h.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-3 text-sm`,children:[(0,h.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,h.jsx)(`input`,{checked:j===null,disabled:s||t,name:`repair-scope`,onChange:()=>P(null),type:`radio`}),v(`plan.repairPreview.all`)]}),(0,h.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,h.jsx)(`input`,{checked:j!==null,disabled:s||t||k.length===0,name:`repair-scope`,onChange:()=>P(j??[]),type:`radio`}),v(`plan.repairPreview.selected`)]})]}),k.length?(0,h.jsx)(`div`,{className:`mt-3 grid max-h-80 gap-2 overflow-y-auto overscroll-contain`,role:`region`,"aria-label":v(`plan.repairPreview.title`),tabIndex:0,children:k.map(e=>{let n=j?.includes(e.sessionId)??!1;return(0,h.jsxs)(`div`,{className:`rounded-[var(--radius-control)] border border-[var(--border)] bg-[var(--surface)] p-3 text-sm`,children:[(0,h.jsxs)(`label`,{className:`flex items-start gap-2`,children:[O?null:(0,h.jsx)(`input`,{"aria-label":v(`plan.repairPreview.selectSession`,{sessionId:e.sessionId}),checked:n,disabled:s||t,onChange:t=>{let n=j??[],r=t.target.checked?[...new Set([...n,e.sessionId])]:n.filter(t=>t!==e.sessionId);P(r)},type:`checkbox`}),(0,h.jsx)(`span`,{className:`break-all font-mono text-xs`,children:e.sessionId})]}),(0,h.jsx)(`ul`,{className:`mt-2 grid gap-1 text-xs text-[var(--muted)]`,children:e.changes.map((e,t)=>(0,h.jsxs)(`li`,{children:[v(`plan.repairPreview.changes.${e.target}`),`: `,fj(e.target,e.before,v),` → `,fj(e.target,e.after,v)]},`${t}-${e.target}`))})]},e.sessionId)})}):(0,h.jsx)(`p`,{className:`mt-3 text-sm text-[var(--muted)]`,children:v(`plan.repairPreview.none`)}),typeof e.impact.repairPreviewTotal==`number`?(0,h.jsxs)(`p`,{className:`mt-3 text-xs text-[var(--muted)]`,children:[v(`plan.repairPreview.total`,{count:e.impact.repairPreviewTotal}),e.impact.repairPreviewTruncated===!0?` · ${v(`plan.repairPreview.truncated`)}`:``]}):null,!O&&(N||l)?(0,h.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-3`,children:[(0,h.jsx)(`p`,{className:`text-sm font-medium text-[var(--warning)]`,role:`status`,children:v(`plan.repairPreview.selectionChanged`)}),(0,h.jsx)(X,{disabled:s||t||Array.isArray(j)&&j.length===0,onClick:()=>d?.(j),type:`button`,variant:`secondary`,children:v(`plan.repairPreview.update`)})]}):null,s?(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)(`p`,{className:`mt-3 text-sm font-medium text-[var(--warning)]`,role:`status`,children:v(`plan.repairPreview.regenerating`)}),(0,h.jsx)(Eb,{state:c})]}):null,l?(0,h.jsx)(`p`,{className:`mt-3 text-sm font-medium text-[var(--danger)]`,role:`alert`,children:v(`plan.repairPreview.refineFailed`)}):null]}):null,e.operation===`switch`?(0,h.jsx)(`p`,{className:`rounded-[var(--radius-control)] border border-[var(--border)] bg-[var(--surface)] p-3 text-sm text-[var(--muted)]`,children:v(`plan.historyModelsUnaffected`)}):null,(0,h.jsxs)(eb,{children:[(0,h.jsx)(`h3`,{className:`mb-2 text-sm font-semibold`,children:v(`plan.impact`)}),(0,h.jsxs)(`dl`,{children:[e.operation===`sync`||e.operation===`switch`?(0,h.jsx)(hb,{label:v(`overview.locked`),value:D}):null,w.map(([t,n])=>(0,h.jsx)(hb,{label:n,value:lj(t,e.impact[t],v)},t))]}),ee.length?(0,h.jsx)(`ul`,{className:`mt-3 list-disc space-y-1 pl-5 text-sm text-[var(--muted)]`,"aria-label":v(`plan.fields.workspaceSettings`),children:ee.map(e=>(0,h.jsx)(`li`,{children:v(`plan.workspaceChanges.${e}`)},e))}):null]}),e.impact.backupExpected===!0?(0,h.jsx)(`div`,{className:`rounded-[var(--radius-control)] border border-[var(--success)] bg-[var(--success-soft)] p-4 text-sm font-medium text-[var(--success)]`,children:v(`plan.backupExpected`)}):null,e.warnings.length?(0,h.jsxs)(`div`,{className:`rounded-lg border border-[var(--warning)] bg-[var(--warning-soft)] p-4`,children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:v(`common.warnings`)}),(0,h.jsx)(`ul`,{className:`mt-2 list-disc space-y-1 pl-5 text-sm`,children:e.warnings.map((e,t)=>(0,h.jsx)(`li`,{children:pb(e,v)},`${t}-${e}`))})]}):null,t?(0,h.jsxs)(eb,{"aria-live":`polite`,role:`status`,children:[(0,h.jsx)(`h3`,{className:`text-sm font-semibold`,children:v(`plan.progress`)}),(0,h.jsx)(`div`,{className:`mt-2 text-xs text-[var(--muted)]`,children:v(`plan.starting`)}),o?(0,h.jsxs)(`div`,{className:`mt-3 grid gap-2`,children:[(0,h.jsxs)(`div`,{className:`text-sm`,children:[v(`plan.stages.${o.stage}`,{defaultValue:v(`common.processing`)}),` · `,v(`plan.statuses.${o.status}`,{defaultValue:v(`common.processing`)}),o.count===void 0?``:` · ${o.count}`]}),o.progress===void 0?null:(0,h.jsx)(`progress`,{"aria-label":v(`plan.progress`),className:`w-full`,max:1,value:o.progress})]}):null,n?(0,h.jsx)(`p`,{className:`mt-3 text-sm text-[var(--warning)]`,children:v(`plan.cancelPending`)}):null]}):null,r&&!t?(0,h.jsx)(`p`,{className:`text-sm font-medium text-[var(--warning)]`,role:`status`,children:v(`plan.writeBlocked`)}):null,(0,h.jsx)(`p`,{className:`text-sm text-[var(--muted)]`,children:v(`plan.exactApply`)})]}):null})}function mj({disabled:e,prepare:t,directSync:n,embedded:r=!1}){let{t:i}=Dn(),a=Co({resolver:No(pp),defaultValues:{}}),o=(0,m.useRef)(null),s=(0,m.useRef)(null);return(0,h.jsxs)(m.Fragment,{children:[r?null:(0,h.jsx)(mb,{title:i(`sync.title`),subtitle:i(`sync.subtitle`)}),(0,h.jsxs)(eb,{className:r?`min-w-0 p-4`:`max-w-2xl`,children:[r?(0,h.jsxs)(`div`,{className:`mb-3`,children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:i(`sync.title`)}),(0,h.jsx)(`p`,{className:`mt-1 text-sm text-[var(--muted)]`,children:i(`sync.subtitle`)})]}):null,(0,h.jsxs)(`form`,{className:`grid gap-5`,onSubmit:a.handleSubmit(e=>t(e,o.current)),children:[(0,h.jsxs)(`div`,{className:`flex flex-wrap gap-3`,children:[(0,h.jsxs)(X,{disabled:e||a.formState.isSubmitting,ref:o,type:`submit`,variant:`secondary`,children:[(0,h.jsx)(Ri,{size:17}),i(`sync.prepare`)]}),n?(0,h.jsxs)(X,{disabled:e||a.formState.isSubmitting,onClick:()=>void a.handleSubmit(e=>n(e,s.current))(),ref:s,type:`button`,children:[(0,h.jsx)(Ri,{size:17}),i(`sync.direct`)]}):null]}),n?(0,h.jsx)(`p`,{className:`text-sm text-[var(--muted)]`,children:i(`sync.directHint`)}):null]}),(0,h.jsx)(`div`,{className:`mt-3`,children:(0,h.jsx)(HA,{})})]})]})}function hj({disabled:e,providers:t,currentProvider:n,recentSuccessfulProviders:r=[],profileKey:i,prepare:a,embedded:o=!1}){let{t:s}=Dn(),c=(0,m.useRef)(null),l=(0,m.useRef)(i),u=n||t[0]||`openai`,d=[...new Set([`openai`,...t,...n?[n]:[]])],f=Co({resolver:No(mp),defaultValues:{provider:u,modelMode:`provider-default`,model:``}}),p=f.watch(`provider`),g=f.watch(`modelMode`);return(0,m.useEffect)(()=>{if(l.current!==i){l.current=i,f.reset({provider:u,modelMode:`provider-default`,model:``});return}n&&(!f.getFieldState(`provider`).isDirty||f.getValues(`provider`)===n)&&f.resetField(`provider`,{defaultValue:n})},[n,u,f,i]),(0,m.useEffect)(()=>{g!==`explicit`&&f.setValue(`model`,``)},[f,g]),(0,h.jsxs)(m.Fragment,{children:[o?null:(0,h.jsx)(mb,{title:s(`switchPage.title`),subtitle:s(`switchPage.subtitle`)}),(0,h.jsxs)(eb,{className:o?`min-w-0`:`max-w-2xl`,children:[o?(0,h.jsxs)(`div`,{className:`mb-5`,children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:s(`switchPage.title`)}),(0,h.jsx)(`p`,{className:`mt-1 text-sm text-[var(--muted)]`,children:s(`switchPage.subtitle`)})]}):null,(0,h.jsxs)(`form`,{className:`grid gap-5`,onSubmit:f.handleSubmit(e=>a(e,c.current)),children:[r.length?(0,h.jsxs)(`div`,{className:`grid gap-2`,children:[(0,h.jsx)(`span`,{className:`text-sm font-medium`,children:s(`switchPage.recentSuccessful`)}),(0,h.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:r.map(e=>(0,h.jsx)(X,{onClick:()=>f.setValue(`provider`,e,{shouldDirty:!0,shouldTouch:!0}),size:`compact`,type:`button`,variant:`secondary`,children:e},e))})]}):null,(0,h.jsx)(nb,{error:f.formState.errors.provider?s(`validation.provider`):void 0,label:s(`switchPage.provider`),children:(0,h.jsx)(tb,{list:`configured-providers`,...f.register(`provider`)})}),(0,h.jsx)(`datalist`,{id:`configured-providers`,children:d.map(e=>(0,h.jsx)(`option`,{value:e},e))}),(0,h.jsx)(nb,{error:f.formState.errors.modelMode?s(`validation.model`):void 0,label:s(`switchPage.modelMode`),children:(0,h.jsxs)(`select`,{"aria-describedby":`switch-model-mode-description`,className:`min-h-10 rounded-lg border border-[var(--border)] bg-[var(--input)] px-3`,...f.register(`modelMode`),children:[(0,h.jsx)(`option`,{value:`provider-default`,children:s(`switchPage.providerDefault`)}),(0,h.jsx)(`option`,{value:`keep-root-model`,children:s(`switchPage.keepModel`)}),(0,h.jsx)(`option`,{value:`explicit`,children:s(`switchPage.explicitModel`)})]})}),(0,h.jsxs)(`div`,{className:`rounded-lg border border-[var(--border)] bg-[var(--surface)] p-3 text-sm text-[var(--muted)]`,id:`switch-model-mode-description`,children:[(0,h.jsx)(`p`,{children:s(`switchPage.modelModeDescriptions.${g}`,{provider:p||s(`common.provider`)})}),(0,h.jsx)(`p`,{className:`mt-2`,children:s(`switchPage.historyModelHint`)})]}),g===`explicit`?(0,h.jsx)(nb,{error:f.formState.errors.model?s(`validation.model`):void 0,label:s(`switchPage.model`),children:(0,h.jsx)(tb,{...f.register(`model`)})}):null,(0,h.jsxs)(X,{disabled:e||f.formState.isSubmitting,ref:c,type:`submit`,children:[(0,h.jsx)(Ai,{size:17}),s(`switchPage.prepare`)]})]})]})]})}function gj({title:e,counts:t,current:n}){let r=t&&typeof t==`object`&&!Array.isArray(t)?t:{},i=new Map;for(let e of[`sessions`,`archived_sessions`]){let t=r[e];if(!(!t||typeof t!=`object`||Array.isArray(t)))for(let[e,n]of Object.entries(t))typeof n==`number`&&i.set(e,(i.get(e)??0)+n)}let a=[...i.entries()].sort((e,t)=>t[1]-e[1]),o=a.reduce((e,[,t])=>e+t,0);return(0,h.jsxs)(eb,{className:`min-w-0 p-4`,children:[(0,h.jsxs)(`div`,{className:`mb-3 flex items-center justify-between gap-2`,children:[(0,h.jsx)(`h2`,{className:`font-semibold`,children:e}),(0,h.jsx)(rb,{children:o})]}),(0,h.jsx)(`div`,{className:`grid gap-3`,children:a.length===0?(0,h.jsx)(`span`,{className:`text-sm text-[var(--muted)]`,children:`—`}):a.map(([e,t])=>(0,h.jsxs)(`div`,{children:[(0,h.jsxs)(`div`,{className:`mb-1 flex justify-between text-sm`,children:[(0,h.jsx)(`span`,{className:`font-medium`,children:e}),(0,h.jsx)(`span`,{children:t})]}),(0,h.jsx)(`progress`,{"aria-label":`${e}: ${t}`,className:Qy(`h-2 w-full overflow-hidden rounded-full`,e===n?`accent-[var(--accent)]`:`accent-[var(--muted)]`),max:Math.max(o,1),value:t})]},e))})]})}function _j(e,t,n){return n(t?`overview.sources.profile`:e===`profile`||e===`cli`?`overview.sources.explicit`:e===`config`||e===`env`||e==="default"?`overview.sources.${e}`:`overview.sources.unknown`)}function vj({status:e,loading:t,refresh:n,profileName:r,profileKey:i,providers:a,recentSuccessfulProviders:o,sqliteHomeConfigured:s,writeDisabled:c,prepareSync:l,directSync:u,prepareSwitch:d,manageStorage:f,retentionCount:p=2}){let{t:g,i18n:_}=Dn(),v=zA(e)&&!e.statusReadBlocked,y=v&&!e.statusReadBlocked&&!e.operationInProgress&&e.sessionActivity?.state===`checked`,b=BA(e);return(0,h.jsxs)(m.Fragment,{children:[(0,h.jsx)(mb,{title:g(`overview.title`),subtitle:g(`overview.subtitle`),action:(0,h.jsxs)(X,{disabled:t,onClick:n,type:`button`,variant:`secondary`,children:[(0,h.jsx)(U,{className:Qy(t&&`animate-spin`),size:16}),g(`common.refresh`)]})}),(0,h.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-4`,children:[(0,h.jsxs)(eb,{className:`min-w-0 p-4`,children:[(0,h.jsx)(`div`,{className:`text-sm text-[var(--muted)]`,children:g(`common.provider`)}),(0,h.jsx)(`div`,{className:`mt-1 break-words text-xl font-bold`,children:v?e.currentProvider:`—`})]}),(0,h.jsxs)(eb,{className:`min-w-0 p-4`,children:[(0,h.jsx)(`div`,{className:`text-sm text-[var(--muted)]`,children:g(`overview.alignment`)}),(0,h.jsxs)(`div`,{className:`mt-1 flex items-center gap-2 text-lg font-bold`,children:[b===`aligned`?(0,h.jsx)(mi,{className:`shrink-0 text-[var(--success)]`,size:20}):b===`notAligned`?(0,h.jsx)(Li,{className:`shrink-0 text-[var(--warning)]`,size:20}):null,g(b===`unknown`?t&&!v?`ux.reading`:`ux.unknown`:`overview.${b}`)]})]}),(0,h.jsxs)(eb,{className:`min-w-0 p-4`,children:[(0,h.jsx)(`div`,{className:`text-sm text-[var(--muted)]`,children:g(`overview.backupCount`)}),(0,h.jsx)(`div`,{className:`mt-1 text-xl font-bold`,children:v?e.backupSummary.count:`—`}),v?(0,h.jsx)(`div`,{className:`text-xs text-[var(--muted)]`,children:lb(e.backupSummary.totalBytes)}):null]}),(0,h.jsxs)(eb,{className:`min-w-0 p-4`,children:[(0,h.jsx)(`div`,{className:`text-sm text-[var(--muted)]`,children:g(`overview.locked`)}),(0,h.jsx)(`div`,{className:`mt-1 text-xl font-bold`,children:y?e.sessionActivity?.count:g(`overview.usageUnknown`)})]})]}),t&&v?(0,h.jsx)(`p`,{className:`mt-2 text-xs text-[var(--muted)]`,role:`status`,children:g(`ux.previousSnapshot`)}):null,v?(0,h.jsxs)(`div`,{className:`mt-4 grid gap-4 lg:grid-cols-2`,children:[(0,h.jsx)(gj,{counts:e.rolloutCounts,current:e.currentProvider,title:g(`overview.rollout`)}),(0,h.jsx)(gj,{counts:e.sqliteCounts,current:e.currentProvider,title:g(`overview.sqlite`)})]}):null,(0,h.jsxs)(`section`,{"aria-labelledby":`provider-operations`,className:`mt-4`,children:[(0,h.jsx)(`h2`,{className:`sr-only`,id:`provider-operations`,children:g(`overview.operations`)}),(0,h.jsxs)(`div`,{className:`grid items-start gap-4 lg:grid-cols-2`,"data-testid":`overview-storage-sync`,children:[(0,h.jsxs)(eb,{className:`min-w-0 p-4`,children:[(0,h.jsxs)(`dl`,{className:`[&>div]:py-2 sm:[&>div]:grid-cols-[140px_minmax(0,1fr)]`,children:[(0,h.jsx)(hb,{label:g(`overview.profile`),value:r}),(0,h.jsx)(hb,{label:g(`overview.codexHomeSource`),value:e?.displayPaths?(0,h.jsx)(`span`,{className:`select-text break-all`,children:e.displayPaths.codexHome}):_j(e?.codexHomeSource,!0,g)}),(0,h.jsx)(hb,{label:g(`overview.sqliteHomeSource`),value:e?.displayPaths?(0,h.jsx)(`span`,{className:`select-text break-all`,children:e.displayPaths.sqliteHome}):_j(e?.sqliteHomeSource,s,g)}),e?.displayPaths?(0,h.jsx)(hb,{label:g(`overview.stateDbPath`),value:e.displayPaths.stateDbPath?(0,h.jsx)(`span`,{className:`select-text break-all`,children:e.displayPaths.stateDbPath}):g(`overview.stateDbMissing`)}):null,(0,h.jsx)(hb,{label:g(`overview.snapshot`),value:ub(e?.snapshotAt,_.language)})]}),(0,h.jsx)(X,{className:`mt-4`,onClick:f,type:`button`,variant:`secondary`,children:g(`overview.manageStorage`)})]}),(0,h.jsxs)(`div`,{className:`min-w-0`,children:[(0,h.jsx)(mj,{directSync:u,disabled:c,embedded:!0,prepare:l}),(0,h.jsx)(`p`,{className:`mt-3 text-sm text-[var(--muted)]`,children:g(`backupPolicy.operationHint`,{count:p})})]})]}),(0,h.jsx)(`div`,{className:`mt-4`,children:(0,h.jsx)(hj,{profileKey:i,currentProvider:v?e.currentProvider:void 0,disabled:c,embedded:!0,prepare:d,providers:a,recentSuccessfulProviders:o})})]})]})}function yj({profiles:e,selectedProfileId:t,refresh:n,selectProfile:r,host:i,canManage:a,revealPaths:o,surface:s}){let{t:c}=Dn(),l=sb(),u=s===`desktop`,[d,f]=(0,m.useState)(null),[p,g]=(0,m.useState)(null),[_,v]=(0,m.useState)(null),[y,b]=(0,m.useState)(`inherit`),x=Co({defaultValues:{profileId:``,name:``,codexHome:``,sqliteHome:``}});(0,m.useEffect)(()=>{x.reset(d?{profileId:d.id,name:d.name,codexHome:d.codexHome??``,sqliteHome:d.sqliteHome??``}:{profileId:``,name:``,codexHome:``,sqliteHome:``}),g(null),v(null),b(d?.sqliteHomeConfigured?`preserve`:`inherit`)},[d,x]);let S=async e=>{if(!i.selectProfileDirectory)return;let t=await i.selectProfileDirectory(e);if(t.status!==`selected`)return;let n={token:t.token,displayName:t.displayName};e===`codex-home`?g(n):(v(n),b(`selected`))},C=st({mutationFn:async e=>{if(!a||!i.saveProfile)throw Error(c(`profiles.unavailable`));if(!e.name.trim())throw Error(c(`validation.required`));if(u){if(!d&&!p)throw Error(c(`profiles.selectCodexRequired`));return i.saveProfile({name:e.name,...d?{profileId:d.id,profileRevision:d.revision}:{},...p?{codexHomeSelectionToken:p.token}:{},sqliteHomeMode:y,...bj(y,_)})}return i.saveProfile({...e,...d?{profileRevision:d.revision}:{}})},onSuccess:async e=>{await n(),r(e.id),f(null),x.reset(),l.push({title:c(`profiles.saved`),tone:`success`})},onError:e=>l.push({title:c(`global.failed`),description:db(e,c),tone:`danger`})}),w=st({mutationFn:e=>{if(!a||!i.deleteProfile)throw Error(c(`profiles.unavailable`));return i.deleteProfile(e.id,e.revision)},onSuccess:async(e,i)=>{i.id===t&&r(`default`),await n(),f(null),l.push({title:c(`profiles.deleted`),tone:`success`})},onError:e=>l.push({title:c(`global.failed`),description:db(e,c),tone:`danger`})});return(0,h.jsxs)(m.Fragment,{children:[(0,h.jsx)(mb,{title:c(`profiles.title`),subtitle:c(`profiles.subtitle`)}),(0,h.jsxs)(`div`,{className:Qy(`grid min-w-0 gap-4`,a&&`xl:grid-cols-[minmax(0,1fr)_420px]`),children:[(0,h.jsxs)(eb,{className:`min-w-0`,children:[(0,h.jsx)(`div`,{className:`grid gap-3`,children:e.map(e=>{let n=(0,h.jsxs)(m.Fragment,{children:[(0,h.jsxs)(`div`,{className:`flex min-w-0 flex-wrap justify-between gap-2`,children:[(0,h.jsx)(`span`,{className:`min-w-0 truncate font-semibold`,children:fb(e,c)}),(0,h.jsxs)(`span`,{className:`flex flex-wrap gap-1`,children:[e.id===t?(0,h.jsx)(rb,{tone:`success`,children:c(`ux.currentProfile`)}):null,e.id==="default"?(0,h.jsx)(rb,{children:c(`profiles.managed`)}):null]})]}),u?null:(0,h.jsx)(`div`,{className:`mt-2 font-mono text-xs text-[var(--muted)]`,children:e.id}),o&&e.codexHome?(0,h.jsx)(`div`,{className:`mt-1 max-w-full truncate font-mono text-xs text-[var(--muted)]`,children:e.codexHome}):(0,h.jsx)(`div`,{className:`mt-1 text-xs text-[var(--muted)]`,children:c(`profiles.pathManaged.${s}`)})]});return!a||e.id==="default"?(0,h.jsx)(`div`,{className:`min-w-0 max-w-full overflow-hidden rounded-lg border border-[var(--border)] p-4 text-left`,children:n},e.id):(0,h.jsx)(`button`,{className:Qy(`min-w-0 max-w-full overflow-hidden rounded-lg border p-4 text-left`,d?.id===e.id?`border-[var(--accent)] bg-[var(--accent-soft)]`:`border-[var(--border)] hover:bg-[var(--surface-hover)]`),onClick:()=>f(e),type:`button`,children:n},e.id)})}),a?null:(0,h.jsx)(`p`,{className:`mt-4 text-xs text-[var(--muted)]`,children:c(`profiles.readOnly`)})]}),a?(0,h.jsxs)(eb,{className:`min-w-0`,children:[(0,h.jsxs)(`form`,{className:`grid min-w-0 gap-4`,onSubmit:x.handleSubmit(e=>C.mutateAsync(e)),children:[u?null:(0,h.jsx)(nb,{label:c(`profiles.id`),children:(0,h.jsx)(tb,{disabled:!!d,...x.register(`profileId`,{required:!0})})}),(0,h.jsx)(nb,{label:c(`profiles.name`),children:(0,h.jsx)(tb,{...x.register(`name`,{required:!0,maxLength:120})})}),u?(0,h.jsxs)(m.Fragment,{children:[(0,h.jsx)(nb,{label:c(`profiles.codexHome`),children:(0,h.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,h.jsx)(X,{onClick:()=>void S(`codex-home`),type:`button`,variant:`secondary`,children:c(`profiles.chooseFolder`)}),(0,h.jsx)(`span`,{className:`truncate text-sm text-[var(--muted)]`,children:p?.displayName??c(d?`profiles.keepCurrent`:`profiles.notSelected`)})]})}),(0,h.jsx)(nb,{label:c(`profiles.sqliteHome`),children:(0,h.jsxs)(`div`,{className:`grid gap-2`,children:[(0,h.jsxs)(`select`,{className:`h-10 rounded-lg border border-[var(--border)] bg-[var(--surface)] px-3`,onChange:e=>b(e.target.value),value:y,children:[d?(0,h.jsx)(`option`,{value:`preserve`,children:c(`profiles.keepCurrent`)}):null,(0,h.jsx)(`option`,{value:`inherit`,children:c(`profiles.inheritSqlite`)}),(0,h.jsx)(`option`,{value:`selected`,children:c(`profiles.customSqlite`)})]}),y===`selected`?(0,h.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,h.jsx)(X,{onClick:()=>void S(`sqlite-home`),type:`button`,variant:`secondary`,children:c(`profiles.chooseFolder`)}),(0,h.jsx)(`span`,{className:`truncate text-sm text-[var(--muted)]`,children:_?.displayName??c(`profiles.notSelected`)})]}):null]})})]}):(0,h.jsxs)(m.Fragment,{children:[(0,h.jsx)(nb,{label:c(`profiles.codexHome`),children:(0,h.jsx)(tb,{...x.register(`codexHome`,{required:!0})})}),(0,h.jsx)(nb,{label:c(`profiles.sqliteHome`),children:(0,h.jsx)(tb,{...x.register(`sqliteHome`)})})]}),(0,h.jsxs)(`div`,{className:`flex flex-wrap gap-3`,children:[(0,h.jsx)(X,{disabled:C.isPending||u&&y===`selected`&&!_,type:`submit`,children:c(d?`profiles.update`:`profiles.create`)}),d?(0,h.jsx)(X,{disabled:w.isPending,onClick:()=>w.mutate(d),type:`button`,variant:`danger`,children:c(`common.delete`)}):null]})]}),u&&d&&i.revealProfileDirectory?(0,h.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-2`,children:[(0,h.jsx)(X,{onClick:()=>void i.revealProfileDirectory?.(d.id,d.revision,`codex-home`),type:`button`,variant:`ghost`,children:c(`profiles.revealCodex`)}),d.sqliteHomeConfigured?(0,h.jsx)(X,{onClick:()=>void i.revealProfileDirectory?.(d.id,d.revision,`sqlite-home`),type:`button`,variant:`ghost`,children:c(`profiles.revealSqlite`)}):null]}):null,(0,h.jsx)(`p`,{className:`mt-4 text-xs text-[var(--muted)]`,children:c(`profiles.defaultManaged`)})]}):null]})]})}function bj(e,t){return e===`selected`&&t?{sqliteHomeSelectionToken:t.token}:{}}function xj(e){return e?`watches`in e?e.watches.find(e=>e.status!==`stopped`)??e.watches[0]??null:e:null}function Sj(e){return[`watch-status`,e.id,e.revision]}function Cj({props:e,profile:t,capabilities:n,recoveryBlocked:r,writeBlocked:i,isWatchTerminal:a,retentionCount:o=2}){let{t:s,i18n:c}=Dn(),l=_(),[u,d]=(0,m.useState)(e.preferences.getTheme()??e.initialTheme),f=rt({queryKey:Sj(t),queryFn:({signal:n})=>e.core.getWatchStatus({profile:cb(t)},{signal:n}),enabled:n.watch}),p=xj(f.data),g=(e,t)=>{e.status!==`stopped`&&a?.(e.watchId)||(l.setQueriesData({queryKey:[`watch-status`]},t=>t&&(`watches`in t?{...t,watches:t.watches.map(t=>t.watchId===e.watchId?e:t)}:t.watchId===e.watchId?e:t)),l.setQueryData(Sj(t),e))},v=st({mutationFn:t=>e.core.startWatch({profile:cb(t),includeStateDb:!0,keepCount:o}),onSuccess:g}),y=st({mutationFn:({watchId:t})=>e.core.stopWatch({watchId:t}),onSuccess:(e,t)=>g(e,t.profile)}),b=e=>e?.id===t.id&&e.revision===t.revision,x=f.error??(b(v.variables)?v.error:null)??(b(y.variables?.profile)?y.error:null),S=rt({queryKey:[`desktop-update-status`],queryFn:({signal:t})=>e.host.getUpdateStatus?.(t),enabled:n.viewUpdateStatus&&!!e.host.getUpdateStatus}),C=n.watch||n.viewUpdateStatus&&!!e.host.getUpdateStatus,w=f.isFetching||S.isFetching,T=async()=>{await Promise.all([n.watch?f.refetch():Promise.resolve(),n.viewUpdateStatus&&e.host.getUpdateStatus?S.refetch():Promise.resolve()])},E=e=>l.setQueryData([`desktop-update-status`],e),D=st({mutationFn:()=>e.host.checkForUpdates?.()??Promise.reject(Error(`Update check unavailable.`)),onSuccess:E}),O=st({mutationFn:()=>e.host.downloadUpdate?.()??Promise.reject(Error(`Update download unavailable.`)),onSuccess:E}),ee=st({mutationFn:()=>e.host.installUpdate?.()??Promise.reject(Error(`Update install unavailable.`)),onSuccess:E}),k=S.isError||D.isError||O.isError||ee.isError,A=D.isPending||O.isPending||ee.isPending,j=async t=>{e.preferences.setLocale(t),await c.changeLanguage(t)},M=t=>{d(t),e.preferences.setTheme(t),document.documentElement.dataset.theme=t};return(0,h.jsxs)(m.Fragment,{children:[(0,h.jsx)(mb,{action:C?(0,h.jsxs)(X,{disabled:w,onClick:()=>void T(),type:`button`,variant:`secondary`,children:[(0,h.jsx)(U,{className:Qy(w&&`animate-spin`),size:16}),s(`common.refresh`)]}):void 0,title:s(`settings.title`),subtitle:s(`settings.subtitle.${e.surface}`)}),(0,h.jsxs)(`div`,{className:`grid gap-4 lg:grid-cols-2`,children:[(0,h.jsxs)(eb,{children:[(0,h.jsx)(nb,{label:s(`settings.language`),children:(0,h.jsxs)(`select`,{className:`min-h-10 rounded-lg border border-[var(--border)] bg-[var(--input)] px-3`,onChange:e=>void j(e.target.value),value:c.language===`zh-CN`?`zh-CN`:`en`,children:[(0,h.jsx)(`option`,{value:`zh-CN`,children:`简体中文`}),(0,h.jsx)(`option`,{value:`en`,children:`English`})]})}),(0,h.jsxs)(`div`,{className:`mt-3 flex items-center gap-2 text-xs text-[var(--muted)]`,children:[(0,h.jsx)(Ti,{size:15}),s(`settings.languageHint`)]})]}),(0,h.jsx)(eb,{children:(0,h.jsxs)(`fieldset`,{children:[(0,h.jsx)(`legend`,{className:`mb-1.5 text-sm font-medium text-[var(--text)]`,children:s(`settings.theme`)}),(0,h.jsx)(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-3`,children:[`system`,`light`,`dark`].map(e=>(0,h.jsxs)(X,{"aria-pressed":u===e,onClick:()=>M(e),type:`button`,variant:u===e?`primary`:`secondary`,children:[e===`system`?(0,h.jsx)(_i,{size:16}):e===`light`?(0,h.jsx)(Fi,{size:16}):(0,h.jsx)(Di,{size:16}),s(`settings.${e}`)]},e))})]})}),n.watch?(0,h.jsxs)(eb,{children:[(0,h.jsx)(`h2`,{className:`font-semibold`,children:s(`settings.watch`)}),(0,h.jsx)(`p`,{className:`mt-1 text-sm text-[var(--muted)]`,children:s(`settings.watchHint`)}),(0,h.jsxs)(`div`,{className:`mt-3 flex items-center justify-between gap-3`,children:[(0,h.jsx)(rb,{tone:p?.status===`running`?`success`:`neutral`,children:f.isPending?s(`common.loading`):f.isError?s(`common.unknown`):p?s(`settings.watchStatuses.${p.status}`,{defaultValue:s(`common.unknown`)}):s(`settings.watchStatuses.stopped`)}),p?.status===`running`?(0,h.jsx)(X,{disabled:!f.isSuccess||f.isFetching||y.isPending&&b(y.variables?.profile),onClick:()=>y.mutate({watchId:p.watchId,profile:t}),type:`button`,variant:`secondary`,children:s(`settings.watchStop`)}):(0,h.jsxs)(X,{disabled:v.isPending&&b(v.variables)||r||i||!f.isSuccess||f.isFetching||p?.status===`stopping`,onClick:()=>v.mutate(t),type:`button`,children:[(0,h.jsx)(Oi,{size:16}),s(`settings.watchStart`)]})]}),x?(0,h.jsx)(`p`,{className:`mt-3 text-xs text-[var(--danger)]`,role:`alert`,children:db(x,s)}):null,r&&p?.status!==`running`?(0,h.jsx)(`p`,{className:`mt-3 text-xs text-[var(--danger)]`,children:s(`settings.watchRecoveryBlocked`)}):null]}):null,n.viewUpdateStatus&&e.host.getUpdateStatus?(0,h.jsxs)(eb,{children:[(0,h.jsx)(`h2`,{className:`font-semibold`,children:s(`settings.update`)}),S.data?.currentVersion?(0,h.jsx)(`p`,{className:`mt-2 text-sm`,children:s(`settings.updateCurrentVersion`,{version:S.data.currentVersion})}):null,(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:s(S.data?.mode===`manual`?`settings.updateManualHint`:`settings.updateAutomaticHint`)}),(0,h.jsxs)(`div`,{className:`mt-3`,children:[(0,h.jsx)(rb,{tone:S.data?.state===`error`||S.data?.installBlockedReason?`warning`:S.data?.state===`downloaded`?`success`:`neutral`,children:S.isPending?s(`common.loading`):S.data?s(`settings.updateStatus.${S.data.state}`):s(`common.unknown`)}),S.data?.version?(0,h.jsx)(`p`,{className:`mt-3 text-sm`,children:s(`settings.updateVersion`,{version:S.data.version})}):null,S.data?.progressPercent===void 0?null:(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:s(`settings.updateProgress`,{percent:S.data.progressPercent})}),S.data?.reason?(0,h.jsx)(`p`,{className:`mt-3 text-sm text-[var(--muted)]`,children:s(`settings.updateReason.${S.data.reason}`)}):null,S.data?.installBlockedReason?(0,h.jsx)(`p`,{className:`mt-3 text-sm text-[var(--danger)]`,children:s(`settings.updateBlocked.${S.data.installBlockedReason}`)}):null,(0,h.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-2`,children:[k?(0,h.jsx)(`p`,{className:`w-full text-sm text-[var(--danger)]`,role:`alert`,children:s(`settings.updateRequestFailed`)}):null,S.data&&[`idle`,`not-available`,`error`,`available`].includes(S.data.state)&&e.host.checkForUpdates?(0,h.jsx)(X,{disabled:A,onClick:()=>D.mutate(),type:`button`,variant:`secondary`,children:D.isPending?s(`settings.updateStatus.checking`):s(`settings.updateCheck`)}):null,S.data?.state===`available`&&e.host.downloadUpdate?(0,h.jsx)(X,{disabled:A,onClick:()=>O.mutate(),type:`button`,children:s(S.data.mode===`manual`?`settings.updateOpenDownload`:`settings.updateDownload`)}):null,S.data?.state===`downloaded`&&e.host.installUpdate?(0,h.jsx)(X,{disabled:!S.data.installAllowed||A||i||r||p?.status===`running`,onClick:()=>ee.mutate(),type:`button`,children:s(`settings.updateInstall`)}):null]})]})]}):null,n.forgetBrowser?(0,h.jsxs)(eb,{children:[(0,h.jsx)(`h2`,{className:`font-semibold`,children:s(`settings.forget`)}),(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:s(`settings.forgetHint`)}),(0,h.jsx)(X,{className:`mt-4`,onClick:()=>void(e.onForgetBrowser?.()??e.host.forgetBrowser?.()),type:`button`,variant:`danger`,children:s(`settings.forget`)})]}):null]})]})}function wj(e){try{let t=e.getBackupRetention?.();return fp.safeParse(t).success?t:2}catch{return 2}}function Tj(e,t){let n=`${t}.backup.retention`;return{getBackupRetention(){let t=e.getItem(n);if(!t||!/^\d{1,4}$/.test(t))return null;let r=Number(t);return fp.safeParse(r).success?r:null},setBackupRetention(t){fp.parse(t),e.setItem(n,String(t))}}}var Ej=Object.freeze({sync:!0,switchProvider:!0,repair:!0,restore:!0,pruneBackups:!0,watch:!0,manageProfiles:!0,revealProfilePaths:!0,forgetBrowser:!0,exportDiagnostics:!0,viewUpdateStatus:!0,operationLogs:!1});Object.freeze({sync:!1,switchProvider:!1,repair:!1,restore:!1,pruneBackups:!1,watch:!1,manageProfiles:!1,revealProfilePaths:!1,forgetBrowser:!1,exportDiagnostics:!1,viewUpdateStatus:!1,operationLogs:!1}),Object.freeze({sync:!0,switchProvider:!0,repair:!0,restore:!1,pruneBackups:!1,watch:!1,manageProfiles:!1,revealProfilePaths:!1,forgetBrowser:!1,exportDiagnostics:!1,viewUpdateStatus:!1,operationLogs:!1}),Object.freeze({sync:!0,switchProvider:!0,repair:!0,restore:!0,pruneBackups:!0,watch:!0,manageProfiles:!0,revealProfilePaths:!1,forgetBrowser:!1,exportDiagnostics:!0,viewUpdateStatus:!0,operationLogs:!0});var Dj=[[`overview`,`nav.overview`,Si],[`backups-restore`,`nav.backupsRestore`,ci],[`history`,`nav.history`,ki],[`operation-logs`,`nav.operationLogs`,ji],[`profiles`,`nav.profiles`,yi],[`diagnostics`,`nav.diagnostics`,si],[`settings`,`nav.settings`,Ni]];function Oj(e){return{...Ej,...e}}function kj(e,t){return e!==`operation-logs`||t.operationLogs}function Aj(e){return e instanceof Rr&&(e.code===`PROFILE_CHANGED`||e.code===`STALE_STATE`&&e.dto.details?.reason===`profile`)}function jj(e){return e?`${e.id}:${e.revision}`:``}function Mj(e,t){return[`watch-status`,e,t]}function Nj(e,t){e.setQueriesData({queryKey:[`watch-status`]},e=>e&&(`watches`in e?{...e,watches:e.watches.map(e=>e.watchId===t.watchId?t:e)}:e.watchId===t.watchId?t:e))}function Pj({props:e}){let{t,i18n:n}=Dn(),r=sb(),i=_(),a=(0,m.useMemo)(()=>Oj(e.capabilities),[e.capabilities]),o=(0,m.useRef)(new Map);(0,m.useEffect)(()=>{if(a.viewUpdateStatus)return e.host.subscribeUpdateStatus?.(e=>i.setQueryData([`desktop-update-status`],e))},[a.viewUpdateStatus,e.host,i]),(0,m.useEffect)(()=>{if(a.watch)return e.host.subscribeWatchStopped?.(e=>{let t=o.current.get(e.watch.watchId);if(!(t!==void 0&&t>=e.generation)){for(;o.current.size>=256;){let e=o.current.keys().next().value;if(!e)break;o.current.delete(e)}o.current.set(e.watch.watchId,e.generation),Nj(i,e.watch),i.setQueryData(Mj(e.profileId,e.profileRevision),e.watch)}})},[a.watch,e.host,i]);let s=(0,m.useMemo)(()=>Dj.filter(([e])=>kj(e,a)),[a]),[c,l]=(0,m.useState)(`overview`),[u,d]=(0,m.useState)(()=>wj(e.preferences)),[f,p]=(0,m.useState)(`default`),[g,v]=(0,m.useState)(null),[y,b]=(0,m.useState)(null),[x,S]=(0,m.useState)(),[C,w]=(0,m.useState)(!0),[T,E]=(0,m.useState)(null),[D,O]=(0,m.useState)(!1),[ee,k]=(0,m.useState)(null),[A,j]=(0,m.useState)(!1),[M,N]=(0,m.useState)(!1),[P,F]=(0,m.useState)(!1),[te,ne]=(0,m.useState)(null),[re,ie]=(0,m.useState)({}),[I,L]=(0,m.useState)(),[ae,oe]=(0,m.useState)(null),se=(0,m.useRef)(null),ce=(0,m.useRef)(null),le=(0,m.useRef)(!1),ue=(0,m.useRef)(!1),de=(0,m.useRef)(!1),fe=(0,m.useRef)(null),pe=(0,m.useRef)({}),me=(0,m.useRef)(0),he=(0,m.useRef)(``),ge=(0,m.useRef)(null),_e=(0,m.useRef)(!1),ve=(0,m.useRef)(!1),ye=(0,m.useRef)(null),be=it(),xe=rt({queryKey:[`profiles`],queryFn:({signal:t})=>e.host.listProfiles(t)}),Se=xe.data??[],R=Se.find(e=>e.id===f)??Se[0],Ce=jj(R),{state:we,start:Te}=Tb(Ce),{state:Ee,start:De}=Tb(Ce);he.current=Ce;let Oe=(0,m.useCallback)(e=>{let t=jj(e),n=++me.current;pe.current={...pe.current,[t]:n},ie(pe.current)},[]),ke=(0,m.useCallback)(async()=>{if(ve.current||(ve.current=!0,r.push({title:t(`global.profileChanged`),description:t(`global.profileChangedHint`),tone:`warning`})),!ye.current){let e=xe.refetch().then(()=>void 0).finally(()=>{ye.current===e&&(ye.current=null)});ye.current=e}await ye.current},[xe.refetch,t,r]);(0,m.useEffect)(()=>{document.documentElement.lang=n.resolvedLanguage?.toLowerCase().startsWith(`zh`)?`zh-CN`:`en`},[n.resolvedLanguage]),(0,m.useEffect)(()=>{Se.length&&!Se.some(e=>e.id===f)&&p(Se[0].id)},[Se,f]),(0,m.useEffect)(()=>{L(void 0),fe.current?.abort(),fe.current=null,ue.current=!1,de.current=!1,j(!1),F(!1),N(!1)},[Ce]),(0,m.useEffect)(()=>()=>{fe.current?.abort()},[]),(0,m.useEffect)(()=>{kj(c,a)||l(`overview`)},[a,c]);let Ae=rt({queryKey:[`status`,R?.id,R?.revision],queryFn:({signal:t})=>e.core.getStatus({profile:cb(R)},{signal:t}),enabled:!!R}),je=Ae.isError?void 0:Ae.data,Me=!!je?.statusReadBlocked,Ne=je?.statusReadBlocked,Pe=typeof Ne==`object`&&!!Ne&&!Array.isArray(Ne)&&Ne.reason===`state-changed-during-status`,Fe=Ae.isSuccess&&je!==void 0&&!Me,Ie=rt({queryKey:[`recent-successful-switches`,R?.id,R?.revision],queryFn:({signal:t})=>e.host.listOperationLogs({page:1,pageSize:100,profileId:R.id,profileRevision:R.revision,operation:`switch`,status:`completed`},t),enabled:!!(R&&a.operationLogs&&e.host.listOperationLogs),retry:!1,staleTime:1/0,refetchOnWindowFocus:!1,refetchOnReconnect:!1});(0,m.useEffect)(()=>{if(Fe&&je.profile.revision===R?.revision){ve.current=!1;return}Aj(Ae.error)&&!ve.current&&ke()},[ke,R?.revision,je?.profile.revision,Ae.error,Fe]);let Le=je?.operationInProgress!=null,Re=je?.operationInProgress?.lockState===`unverifiable`,ze=!R||!Fe||je?.pendingRecovery===!0||Le||be>0||ee!==null||Ee!==null,Be=!R||!Fe||Le||be>0||ee!==null,Ve=rt({queryKey:[`backups`,R?.id,R?.revision],queryFn:({signal:t})=>e.core.listBackups({profile:cb(R)},{signal:t}),enabled:!!(R&&c===`backups-restore`)}),He=rt({queryKey:[`diagnostics`,R?.id,R?.revision],queryFn:async({signal:t})=>{let n=Te();try{return await e.core.getDiagnostics({profile:cb(R)},{signal:t,onRequestProgress:n.onRequestProgress})}finally{n.finish()}},enabled:!1}),Ue=(0,m.useCallback)(async()=>{if(!R)return;let e=jj(R),t=pe.current[e]??0;if((await He.refetch()).isSuccess&&he.current===e&&(pe.current[e]??0)===t){let t={...pe.current};delete t[e],pe.current=t,ie(t)}},[He,R]),We=(0,m.useCallback)(async({refreshStatus:e=!0}={})=>{let t=[i.invalidateQueries({queryKey:[`backups`]}),i.invalidateQueries({queryKey:[`history`]}),i.invalidateQueries({queryKey:[`diagnostics`]}),i.invalidateQueries({queryKey:[`recent-successful-switches`]})];t.push(i.invalidateQueries({queryKey:[`status`],refetchType:e?`active`:`none`})),await Promise.all(t)},[i]),Ge=(0,m.useCallback)(async(e,n)=>{ge.current=n;try{v(await e())}catch(e){if(ge.current=null,Aj(e)){await ke();return}r.push({title:t(`global.failed`),description:db(e,t),tone:`danger`})}},[ke,t,r]),Ke=(0,m.useCallback)(()=>{let e=ge.current;_e.current=!1,v(null),F(!1),de.current=!1,N(!1),ce.current=null,E(null),O(!1),globalThis.requestAnimationFrame(()=>globalThis.requestAnimationFrame(()=>{e?.isConnected&&e.focus(),ge.current===e&&(ge.current=null)}))},[]),qe=(0,m.useCallback)(()=>{g&&e.host.dismissOperationPlan?.(g.planId),Ke()},[Ke,g,e.host]),Je=(0,m.useCallback)(()=>{v(null),k(null),ce.current=null,E(null),O(!1)},[]),Ye=(0,m.useCallback)(()=>{if(_e.current)return;let e=ge.current;ge.current=null,e?.focus()},[]),Xe=(0,m.useCallback)(()=>{let e=ge.current;ge.current=null,_e.current=!1,e?.focus()},[]),Ze=st({mutationFn:async t=>{let n={schemaVersion:1,planId:t.planId},r=new AbortController;se.current=r,ce.current=null,E(null),O(!1);let i={signal:r.signal,onOperationStarted:e=>{ce.current=e.operationId},onProgress:e=>E(e.progress)};try{return t.operation===`sync`?await e.core.applySync(n,i):t.operation===`switch`?await e.core.applySwitch(n,i):t.operation===`repair`?await e.core.applyRepair(n,i):await e.core.applyRestore(n,i)}finally{se.current===r&&(se.current=null)}},onSuccess:async(e,n)=>{let i=WA(e.outcome),a=e.outcome===`recovery_required`;_e.current=!0,w(!a),b(e),S({operationId:e.operationId,state:`checking`}),oe(n.profile),Oe(n.profile),Je();let[,o]=await Promise.allSettled([We({refreshStatus:!1}),Ae.refetch()]),s=o.status===`fulfilled`?o.value:void 0,c=s?.isSuccess&&zA(s.data)&&s.data.profile.id===n.profile.id&&s.data.profile.revision===n.profile.revision&&he.current===jj(n.profile)?s.data:void 0;S({operationId:e.operationId,state:c?`received`:`unverified`,...c?{snapshot:c}:{}}),a&&w(!!c),r.push({title:t(i.toastKey),description:e.backup?t(`operationResult.backupCreated`):void 0,tone:i.tone})},onError:async(e,n)=>{if(Oe(n.profile),await We(),Ke(),e instanceof Rr&&e.code===`OPERATION_CANCELLED`){r.push({title:t(`global.cancelled`),tone:`warning`});return}if(Aj(e)){await ke();return}r.push({title:t(`global.failed`),description:db(e,t),tone:`danger`})}}),Qe=async(n,i)=>{if(ze||!a.sync||g||y||le.current)return;le.current=!0,ge.current=i;let o=new AbortController;se.current=o,O(!1),E(null),k(`preparing`);let s=!1;try{let n=await e.core.prepareSync({profile:cb(R),keepCount:u},{signal:o.signal});if(o.signal.aborted){e.host.dismissOperationPlan?.(n.planId),r.push({title:t(`global.cancelled`),tone:`warning`});return}k(`applying`),s=!0,await Ze.mutateAsync(n)}catch(e){s||(o.signal.aborted||e instanceof Rr&&e.code===`OPERATION_CANCELLED`?r.push({title:t(`global.cancelled`),tone:`warning`}):Aj(e)?await ke():r.push({title:t(`global.failed`),description:db(e,t),tone:`danger`}))}finally{se.current===o&&(se.current=null),le.current=!1,k(null),O(!1)}},$e=(0,m.useCallback)(async(n,i,o)=>{if(!a.repair||ze||!R||n.length===0||fe.current)return;ne({targets:n,keepCount:i}),N(!1),F(!1),de.current=!1;let s=new AbortController;fe.current=s;let c=Ce,l=De();ge.current=o;try{let t=await e.core.prepareRepair({profile:cb(R),targets:n,keepCount:i},{signal:s.signal,onRequestProgress:l.onRequestProgress});if(s.signal.aborted||c!==he.current){e.host.dismissOperationPlan?.(t.planId);return}v(t)}catch(e){s.signal.aborted||(ge.current=null,Aj(e)?await ke():r.push({title:t(`global.failed`),description:db(e,t),tone:`danger`}))}finally{fe.current===s&&(fe.current=null),l.finish()}},[a.repair,Ce,ke,ze,R,e.core,e.host,De,t,r]),et=(0,m.useCallback)(async n=>{if(!g||g.operation!==`repair`||!te||A||Array.isArray(n)&&n.length===0)return;let i=g.planId,a=Ce,o=new AbortController;fe.current?.abort(),fe.current=o;let s=De();j(!0),ue.current=!0,N(!1),F(!0),de.current=!0,e.host.dismissOperationPlan?.(i);try{let t={profile:cb(R),targets:te.targets,keepCount:te.keepCount,...n===null?{}:{sessionIds:n}},r=await e.core.prepareRepair(t,{signal:o.signal,onRequestProgress:s.onRequestProgress});if(o.signal.aborted||a!==he.current){e.host.dismissOperationPlan?.(r.planId);return}v(r),F(!1),de.current=!1}catch(e){o.signal.aborted||(N(!0),Aj(e)?await ke():r.push({title:t(`global.failed`),description:db(e,t),tone:`danger`}))}finally{s.finish(),fe.current===o&&(fe.current=null,j(!1),ue.current=!1)}},[Ce,ke,g,R,e.core,e.host,te,A,De,t,r]),tt=st({mutationFn:async t=>{if(fp.parse(t),!e.preferences.setBackupRetention||g||y||Le||!Fe||ee!==null)throw Error(`Backup preference unavailable.`);let n=await e.core.getWatchStatus({});return(`watches`in n?n.watches:[n]).some(e=>e.status!==`stopped`)?`watch-active`:(e.preferences.setBackupRetention(t),d(t),`saved`)}}),nt=st({mutationFn:async t=>e.core.pruneBackups({profile:{profileId:t.profile.id,profileRevision:t.profile.revision},keepCount:t.keepCount}),onSuccess:async(e,n)=>{Oe(n.profile),await We(),r.push({title:t(`global.completed`),tone:`success`})},onError:(e,n)=>{Oe(n.profile),r.push({title:t(`global.failed`),description:db(e,t),tone:`danger`})}}),at=st({mutationFn:async()=>{if(!R||!e.host.exportDiagnostics)throw Error(`Diagnostics export is unavailable.`);return e.host.exportDiagnostics(cb(R))},onSuccess:e=>{r.push({title:e.status===`created`?t(`diagnostics.exportCreated`):e.status===`cancelled`?t(`diagnostics.exportCancelled`):t(`diagnostics.exportFailed`),tone:e.status===`created`?`success`:e.status===`cancelled`?`warning`:`danger`})},onError:()=>r.push({title:t(`diagnostics.exportFailed`),tone:`danger`})}),ot=je?.configuredProviders&&Array.isArray(je.configuredProviders)?je.configuredProviders.filter(e=>typeof e==`string`):[je?.currentProvider??`openai`],ct=Fe?[...new Set((Ie.data?.entries??[]).filter(e=>e.profileId===R?.id&&e.profileRevision===R?.revision&&e.status===`completed`&&e.outcome===`completed`&&e.switchPlan!==void 0).map(e=>e.switchPlan.targetProvider).filter(e=>ot.includes(e)))].slice(0,5):[],z=R?fb(R,t):``,lt=je?.pendingRecovery?{label:t(`global.recoveryTitle`),tone:`warning`}:Ae.isError?{label:t(`global.statusUnavailable`),tone:`danger`}:Re?{label:t(`global.lockUnverified`),tone:`warning`}:be>0||ee!==null||Le?{label:t(`global.busy`),tone:`warning`}:Me?{label:t(`global.statusNeedsRefresh`),tone:`neutral`}:Fe?{label:t(`global.ready`),tone:`success`}:{label:t(`global.readingStatus`),tone:`neutral`},ut=R?c===`overview`?(0,h.jsx)(vj,{profileKey:Ce,retentionCount:u,directSync:a.sync?Qe:void 0,loading:Ae.isFetching,manageStorage:()=>l(`profiles`),prepareSwitch:(t,n)=>Ge(()=>e.core.prepareSwitch({profile:cb(R),provider:t.provider,modelMode:t.modelMode,...t.modelMode===`explicit`?{model:t.model}:{},keepCount:u}),n),prepareSync:(t,n)=>Ge(()=>e.core.prepareSync({profile:cb(R),keepCount:u}),n),profileName:z,providers:ot,recentSuccessfulProviders:ct,refresh:()=>{Ae.refetch(),Ie.refetch()},sqliteHomeConfigured:R.sqliteHomeConfigured===!0||!!R.sqliteHome,status:je,writeDisabled:ze}):c===`backups-restore`?(0,h.jsx)(vb,{retentionCount:u,saveRetention:e.preferences.setBackupRetention?e=>tt.mutateAsync(e):void 0,error:Ve.error,refresh:()=>void Ve.refetch(),refreshing:Ve.isFetching,backups:Ve.data?.backups??[],canPrune:a.pruneBackups,canRestore:a.restore,disabled:Be||nt.isPending,initialBackupId:I,loading:Ve.isPending,prepare:(t,n)=>Ge(()=>e.core.prepareRestore({profile:cb(R),backupId:t.backupId,restoreConfig:t.restoreConfig,restoreDatabase:t.restoreDatabase,restoreSessions:t.restoreSessions,...t.allowSqliteHomeRelocation?{allowSqliteHomeRelocation:!0,relocationTargetProfileId:t.relocationTargetProfileId}:{}}),n),profile:R,profiles:Se,prune:e=>nt.mutate({keepCount:e,profile:{id:R.id,revision:R.revision}})},Ce):c===`history`?(0,h.jsx)(PA,{core:e.core,host:e.host,preferences:e.preferences,profile:R},`${R.id}:${R.revision}`):c===`operation-logs`&&a.operationLogs&&e.host.listOperationLogs&&e.host.getOperationLog?(0,h.jsx)(cj,{host:e.host,profileId:R.id,profileRevision:R.revision,openBackupRestore:a.restore?e=>{L(e),l(`backups-restore`)}:void 0,reviewOperation:e=>l(e===`repair`?`diagnostics`:`overview`)},Ce):c===`profiles`?(0,h.jsx)(yj,{selectedProfileId:f,canManage:a.manageProfiles,host:e.host,profiles:Se,refresh:()=>xe.refetch(),revealPaths:a.revealProfilePaths,selectProfile:p,surface:e.surface}):c===`diagnostics`?(0,h.jsx)(jb,{canExport:a.exportDiagnostics&&!!e.host.exportDiagnostics,canRepair:a.repair,diagnostics:He.data,error:He.error,expired:!!re[Ce],exportBundle:()=>at.mutate(),exporting:at.isPending,loading:He.isFetching,prepareRepair:(e,t)=>{let n=[`models`,`cwd`,`userEvent`,`workspaceRoots`].filter(t=>e[t]);return $e(n,u,t)},refresh:()=>{Ue()},repairDisabled:ze||He.isFetching,scanProgress:we,repairProgress:Ee},Ce):c===`settings`?(0,h.jsx)(Cj,{retentionCount:u,capabilities:a,isWatchTerminal:e=>o.current.has(e),profile:R,props:e,recoveryBlocked:je?.pendingRecovery===!0,writeBlocked:!Fe||Le||be>0||ee!==null},Ce):(0,h.jsx)(vj,{profileKey:Ce,retentionCount:u,directSync:a.sync?Qe:void 0,loading:Ae.isFetching,manageStorage:()=>l(`profiles`),prepareSwitch:(t,n)=>Ge(()=>e.core.prepareSwitch({profile:cb(R),provider:t.provider,modelMode:t.modelMode,...t.modelMode===`explicit`?{model:t.model}:{},keepCount:u}),n),prepareSync:(t,n)=>Ge(()=>e.core.prepareSync({profile:cb(R),keepCount:u}),n),profileName:z,providers:ot,recentSuccessfulProviders:ct,refresh:()=>{Ae.refetch(),Ie.refetch()},sqliteHomeConfigured:R.sqliteHomeConfigured===!0||!!R.sqliteHome,status:je,writeDisabled:ze}):(0,h.jsx)(eb,{children:xe.isPending?t(`common.loading`):db(xe.error,t)});return(0,h.jsxs)(`div`,{className:Qy(`bg-[var(--surface)] text-[var(--text)]`,[`history`,`operation-logs`].includes(c)?`flex h-dvh min-h-0 flex-col overflow-hidden`:`min-h-screen`),children:[(0,h.jsx)(`a`,{className:`sr-only focus:not-sr-only focus:fixed focus:left-4 focus:top-4 focus:z-[70] focus:rounded focus:bg-[var(--accent)] focus:px-4 focus:py-2 focus:text-white`,href:`#main-content`,onClick:e=>{e.preventDefault(),document.getElementById(`main-content`)?.focus()},children:t(`a11y.skipToContent`)}),(0,h.jsxs)(`header`,{className:Qy(`sticky top-0 z-30 flex min-h-16 shrink-0 flex-wrap items-center justify-between gap-3 border-b border-[var(--border)] bg-[color:var(--surface-raised)/.96] px-4 py-3 backdrop-blur md:px-6`,[`history`,`operation-logs`].includes(c)&&`[@media(max-height:500px)]:min-h-0 [@media(max-height:500px)]:py-1`),children:[(0,h.jsxs)(`div`,{className:Qy(`flex min-w-0 items-center gap-3`,[`history`,`operation-logs`].includes(c)&&`[@media(max-height:500px)]:hidden`),children:[(0,h.jsx)(`div`,{className:`grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-[var(--accent)] text-white`,children:(0,h.jsx)(gi,{size:20})}),(0,h.jsxs)(`div`,{className:`min-w-0`,children:[(0,h.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,h.jsx)(`div`,{className:`truncate font-bold`,children:`Codex Provider Sync`}),(0,h.jsx)(rb,{children:t(`brand.${e.surface}.label`)})]}),(0,h.jsx)(`div`,{className:`truncate text-xs text-[var(--muted)]`,children:t(`brand.${e.surface}.subtitle`)})]})]}),(0,h.jsxs)(`div`,{className:`flex w-full min-w-0 items-center justify-between gap-3 sm:w-auto sm:justify-end`,children:[(0,h.jsx)(`select`,{"aria-label":t(`a11y.profile`),className:`min-w-0 max-w-[min(12rem,70vw)] rounded-[var(--radius-control)] border border-[var(--border)] bg-[var(--input)] px-3 py-2 text-sm`,disabled:be>0||ee!==null||Le||A,onChange:e=>p(e.target.value),value:R?.id??``,children:Se.map(e=>(0,h.jsx)(`option`,{value:e.id,children:fb(e,t)},e.id))}),(0,h.jsx)(rb,{tone:lt.tone,children:lt.label})]})]}),(0,h.jsxs)(`div`,{className:Qy(`mx-auto grid w-full min-w-0 max-w-[1600px] md:grid-cols-[240px_minmax(0,1fr)]`,[`history`,`operation-logs`].includes(c)&&`min-h-0 flex-1 grid-rows-[auto_minmax(0,1fr)] overflow-hidden md:grid-rows-1`),children:[(0,h.jsx)(`aside`,{className:Qy(`min-w-0 max-w-full border-b border-[var(--border)] bg-[var(--surface-raised)] p-3 md:border-b-0 md:border-r`,[`history`,`operation-logs`].includes(c)?`min-h-0 overflow-y-auto overscroll-contain [@media(max-height:500px)]:p-1`:`overflow-hidden md:min-h-[calc(100vh-4rem)]`),children:(0,h.jsx)(`nav`,{"aria-label":t(`a11y.primaryNavigation`),className:`flex w-full min-w-0 max-w-full gap-1 overflow-x-auto pb-1 sm:grid sm:grid-cols-4 sm:overflow-visible sm:pb-0 md:grid-cols-1`,children:s.map(([e,n,r])=>(0,h.jsxs)(`button`,{"aria-current":c===e?`page`:void 0,className:Qy(`flex min-h-11 shrink-0 items-center gap-3 whitespace-nowrap rounded-[var(--radius-control)] px-3 text-left text-sm font-medium text-[var(--muted)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus)] sm:shrink`,c===e?`bg-[var(--accent-soft)] text-[var(--accent-strong)]`:`hover:bg-[var(--surface-hover)] hover:text-[var(--text)]`),onClick:()=>l(e),type:`button`,children:[(0,h.jsx)(r,{size:17}),(0,h.jsx)(`span`,{children:t(n)})]},e))})}),(0,h.jsxs)(`main`,{className:Qy(`min-w-0`,[`history`,`operation-logs`].includes(c)?`flex min-h-0 flex-col overflow-hidden p-3 md:p-4`:`p-4 md:p-8`),id:`main-content`,tabIndex:-1,children:[(0,h.jsxs)(`div`,{className:[`history`,`operation-logs`].includes(c)?`max-h-[30%] shrink-0 overflow-y-auto overscroll-contain`:void 0,children:[je?.pendingRecovery?(0,h.jsxs)(`div`,{className:`mb-5 flex items-start gap-3 rounded-xl border border-[var(--danger)] bg-[var(--danger-soft)] p-4 text-sm`,role:`alert`,children:[(0,h.jsx)(Pi,{className:`mt-0.5 shrink-0 text-[var(--danger)]`,size:20}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`div`,{className:`font-semibold`,children:t(`global.recoveryTitle`)}),(0,h.jsx)(`div`,{className:`mt-1`,children:t(`global.recovery`)})]})]}):null,je?.operationInProgress?(0,h.jsxs)(`div`,{className:`mb-5 flex flex-wrap items-start gap-3 rounded-xl border border-[var(--warning)] bg-[var(--warning-soft)] p-4 text-sm`,role:`status`,children:[(0,h.jsx)(vi,{className:`mt-0.5 shrink-0 text-[var(--warning)]`,size:20}),(0,h.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,h.jsx)(`div`,{className:`font-semibold`,children:t(Re?`global.lockUnverified`:`global.busy`)}),(0,h.jsx)(`div`,{className:`mt-1 text-[var(--muted)]`,children:t(Re?`global.lockUnverifiedHint`:`global.busyHint`)})]}),Re?(0,h.jsx)(X,{disabled:Ae.isFetching,onClick:()=>void Ae.refetch(),type:`button`,variant:`secondary`,children:t(`global.retryStatus`)}):null]}):null,je?.staleLockDetected&&Fe&&!Le&&!je.pendingRecovery?(0,h.jsxs)(`div`,{className:`mb-5 rounded-xl border border-[var(--border)] bg-[var(--surface-raised)] p-4 text-sm`,role:`status`,children:[(0,h.jsx)(`div`,{className:`font-semibold`,children:t(`global.staleLock`)}),(0,h.jsx)(`p`,{className:`mt-1 text-[var(--muted)]`,children:t(`global.staleLockHint`)})]}):null,Me&&!Le?(0,h.jsxs)(`div`,{className:`mb-5 flex flex-wrap items-center justify-between gap-3 rounded-xl border border-[var(--border)] bg-[var(--surface-raised)] p-4 text-sm`,role:`status`,children:[(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`div`,{className:`font-semibold`,children:t(`global.statusNeedsRefresh`)}),(0,h.jsx)(`p`,{className:`mt-1 text-[var(--muted)]`,children:t(Pe?`global.statusChangedHint`:`global.statusUnavailableHint`)})]}),(0,h.jsx)(X,{disabled:Ae.isFetching,onClick:()=>void Ae.refetch(),type:`button`,variant:`secondary`,children:t(`global.retryStatus`)})]}):null,Ae.isError?(0,h.jsx)(`div`,{className:`mb-5 rounded-xl border border-[var(--danger)] bg-[var(--danger-soft)] p-4 text-sm text-[var(--danger)]`,role:`alert`,children:db(Ae.error,t)}):null]}),ut]})]}),a.sync||a.switchProvider||a.repair||a.restore?(0,h.jsx)(pj,{repairProgress:Ee,apply:()=>{!g||M||ue.current||de.current||le.current||Ze.isPending||(le.current=!0,Ze.mutate(g,{onSettled:()=>{le.current=!1}}))},directSyncPhase:ee,applying:Ze.isPending||ee!==null,cancel:()=>{!Ze.isPending&&ee===null||D||(O(!0),se.current?.abort())},cancelling:D,close:qe,confirmDisabled:!Fe||Le||je?.pendingRecovery===!0,currentModel:je?.currentModel,plan:g,progress:T,repairDraftChanged:e=>{de.current=e,F(e)},repairSelectionFailed:M,repairSelectionPending:A,refineRepairSessions:et,restoreFocus:Ye}):null,(0,h.jsx)(XA,{postWriteStatus:ae?.id===R?.id&&ae?.revision===R?.revision?x:y?{operationId:y.operationId,state:`unverified`}:void 0,reviewOperation:y?.outcome===`partial`&&ae?.id===R?.id&&ae?.revision===R?.revision?()=>{let e=y.operation;ge.current=null,b(null),oe(null),l(e===`repair`?`diagnostics`:`overview`),globalThis.requestAnimationFrame(()=>document.getElementById(`main-content`)?.focus())}:void 0,close:()=>{b(null),oe(null),w(!0)},closeDisabled:y?.outcome===`recovery_required`&&(!C||je?.pendingRecovery!==!1),openBackupRestore:a.restore&&ae?.id===R?.id&&ae?.revision===R?.revision?e=>{L(e),b(null),oe(null),w(!0),l(`backups-restore`)}:void 0,restoreFocus:Xe,result:y})]})}var Fj=class extends m.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(e,t){}render(){if(!this.state.failed)return this.props.children;let e=this.props.locale().toLowerCase().startsWith(`zh`);return(0,h.jsx)(`div`,{className:`grid min-h-screen place-items-center bg-[var(--surface)] p-6 text-[var(--text)]`,children:(0,h.jsxs)(eb,{className:`max-w-lg text-center`,children:[(0,h.jsx)(Pi,{className:`mx-auto text-[var(--danger)]`,size:40}),(0,h.jsx)(`h1`,{className:`mt-4 text-xl font-bold`,children:e?`页面暂时无法显示`:`This page is temporarily unavailable`}),(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:e?`你的数据没有被更改。请重新打开应用;如果问题持续,请查看操作日志或导出诊断信息。`:`Your data was not changed. Reopen the app; if the problem continues, check Operation logs or export diagnostics.`}),(0,h.jsx)(X,{className:`mt-5`,onClick:()=>globalThis.location?.reload(),type:`button`,children:e?`重新打开`:`Reopen`})]})})}},Ij={en:{translation:{requestProgress:{working:`Working…`,elapsed:`Elapsed {{time}}`,files:`{{count}} files checked`,stagePercent:`This stage: {{percent}}%`,stages:{waiting:`Starting…`,prepare_repair_context:`Reading configuration and checking preview state…`,prepare_diagnostics:`Preparing diagnostics…`,scan_sessions:`Checking session files…`,scan_archived_sessions:`Checking archived sessions…`,inspect_repair_sqlite:`Checking affected chat index entries…`,inspect_workspace_roots:`Checking workspace settings…`,build_repair_preview:`Building the change preview…`,inspect_diagnostics_index:`Checking the chat index…`,inspect_diagnostics_backups:`Checking backups and recovery state…`,inspect_history_integrity:`Preparing history integrity checks…`,integrity_sessions:`Checking session record integrity…`,integrity_archived_sessions:`Checking archived record integrity…`,finish_diagnostics:`Completing diagnostics…`}},backupPolicy:{title:`Backup settings`,count:`Backups to retain`,save:`Save backup settings`,scope:`One rule for this app: Sync, Switch, Repair and automatic sync share it. Each Codex Home keeps its own backup pool; operations do not each keep a separate quota.`,current:`Saved rule: keep the newest {{count}} backups per Codex Home.`,operationHint:`Automatically back up changes and retain {{count}} backups. Manage this rule in Backups / Restore.`,hint:`Saving does not delete backups. Future writes use the saved rule; manual cleanup asks for confirmation. Recovery-protected backups may exceed this count. Stop automatic sync before changing the rule.`,saved:`Backup settings saved. No backups were deleted.`,"watch-active":`Automatic sync is active. Stop it in Settings, then save this rule again.`,failed:`Could not save backup settings. The previous rule is unchanged; try again.`,clear:`Delete all eligible backups`},ux:{reading:`Reading status…`,unknown:`Not verified`,previousSnapshot:`Refreshing; showing the last snapshot.`,currentProfile:`In use`,finalStatus:`Final Provider check`,finalChecking:`Reading the post-operation status…`,finalUnavailable:`The operation result is available, but the final Provider alignment has not been verified. Refresh Overview to check.`,pruneEstimate:`From the current list: up to {{remove}} backups may be removed; at least {{keep}} will remain.`,pruneCaution:`Backups needed for recovery stay protected. The list may change; the actual result determines how many are removed.`,pruneTitle:`Confirm backup cleanup`,pruneConfirm:`Confirm cleanup`,pruneZero:`This cleanup requests removal of every eligible managed backup, not protected recovery backups. Deleted backups cannot be restored by this tool. Your automatic retention rule will not change.`,pruneChanged:`The backup list or storage profile changed. Close this preview and review cleanup again.`,clearFilters:`Clear filters`,pendingFilters:`Search text, Provider or scope changed. Press Search to apply.`},brand:{desktop:{label:`Desktop`,subtitle:`Manage Codex Providers and local session history`},web:{label:`Web`,subtitle:`Local Web management interface`}},a11y:{skipToContent:`Skip to content`,profile:`Profile`,primaryNavigation:`Primary navigation`},nav:{overview:`Overview`,sync:`Sync`,switchProvider:`Switch Provider`,backupsRestore:`Backups / Restore`,history:`History`,operationLogs:`Operation logs`,profiles:`Profiles`,diagnostics:`Advanced features`,settings:`Settings`},common:{refresh:`Refresh`,loading:`Loading…`,processing:`Processing`,cancel:`Cancel`,confirm:`Confirm and apply`,save:`Save`,delete:`Delete`,close:`Close`,dismissNotification:`Dismiss notification: {{title}}`,yes:`Yes`,no:`No`,none:`None`,unknown:`Unknown`,current:`Current`,provider:`Provider`,model:`Model`,status:`Status`,warnings:`Warnings`,retry:`Retry`,advanced:`Advanced options`,search:`Search`,copy:`Copy`,copied:`Copied`},global:{ready:`Ready`,readingStatus:`Reading status…`,statusUnavailable:`Status unavailable`,statusNeedsRefresh:`Refresh needed`,statusChangedHint:`Data changed while checking. Refresh to check again.`,statusUnavailableHint:`The current status could not be fully checked. Please refresh and try again.`,retryStatus:`Check status again`,busy:`Operation in progress`,busyHint:`Another operation is using the current storage location. You can continue when it finishes.`,lockUnverified:`Storage lock needs checking`,lockUnverifiedHint:`We cannot confirm whether another operation has finished. Check again after closing other sync tools. If this persists, export a diagnostic package from Advanced features. Do not delete the lock manually.`,staleLock:`A previous operation has ended`,staleLockHint:`You can preview or sync normally. Before writing, the app will recheck and safely reclaim the previous operation’s lock.`,recoveryTitle:`Recovery required`,recovery:`A previous restore did not finish. Complete recovery before making more changes.`,stale:`The data changed. Review the operation again before continuing.`,unexpected:`Something went wrong. Try again.`,partial:`Some records were not updated. Close any active Codex sessions and try again.`,completed:`Operation completed.`,cancelled:`Operation cancelled.`,profileChanged:`Profile changed.`,profileChangedHint:`Review the selected storage location and try again.`,failed:`The operation could not be completed.`},overview:{title:`Provider sync overview`,subtitle:`See whether the current Provider matches your local chat history.`,alignment:`Sync status`,aligned:`In sync`,notAligned:`Sync recommended`,rollout:`Session files`,sqlite:`Local chat index`,codexHomeSource:`Codex data location`,sqliteHomeSource:`Chat index location`,stateDbPath:`Current database file`,stateDbMissing:`No database found`,snapshot:`Snapshot`,backupCount:`Available backups`,locked:`Sessions currently in use`,usageUnknown:`Unknown`,profile:`Storage profile`,manageStorage:`Manage storage profiles`,operations:`Sync and switch`,operationsHint:`Sync the current Provider or switch to another Provider here.`,sources:{profile:`Selected storage profile`,config:`Codex configuration`,env:`Environment setting`,default:`Default location`,explicit:`Selected storage profile`,unknown:`Could not determine`}},sync:{title:`Sync current Provider`,subtitle:`Sync only Provider information from the current configuration. Models, chat content and history records are not repaired.`,keep:`Number of recent backups to keep`,prepare:`Preview sync`,direct:`Sync now`,directHint:`Sync now uses the current Provider without another confirmation. Changes are checked and backed up before writing; no advanced repairs are run.`,preparingDirect:`Checking sync changes`,runningDirect:`Syncing`,performance:{title:`How to speed up sync`,resultLink:`View speed-up tips`,equalLength:`Equal-length English Provider IDs can be updated in place after file checks, without copying the entire chat file. For example, openai and prov_a both have 6 characters.`,differentLength:`Different-length IDs still sync normally, but require copying the file. Larger chat files take longer. The app chooses the method automatically; there is no setting to enable.`,configuration:`If you change a Provider ID, keep it consistent in your configuration and Provider management tool. Changing only its display name does not help. You do not need to rename Providers to use sync.`}},switchPage:{title:`Switch Provider separately`,subtitle:`Change the Provider in your configuration, then run the same Provider sync. Review the changes before applying.`,provider:`Provider ID`,modelMode:`Model handling`,providerDefault:`Use model configured for this Provider`,keepModel:`Keep current root model`,explicitModel:`Specify root model`,modelModeDescriptions:{"provider-default":`Read [model_providers.{{provider}}].model from config.toml. If it is not configured, keep the current root model. This does not query the Provider online.`,"keep-root-model":`Only switch model_provider. Do not change the root-level model in config.toml.`,explicit:`Write the model name below to the root-level model in config.toml. Remote availability is not checked.`},historyModelHint:`Switch synchronizes historical Provider metadata, but does not change the models recorded by historical sessions. Use Advanced features > Advanced adjustments for that.`,recentSuccessful:`Recently used successfully`,model:`Model name`,prepare:`Preview switch`},backups:{title:`Backups and Restore`,subtitle:`View backups created by this app and restore one when needed.`,empty:`No backups yet. A backup is created automatically before data is changed.`,loadFailed:`Could not read backups. No backup was changed.`,requestedMissing:`This backup is no longer available in the current profile. It may have been removed by backup retention. Select an available backup instead.`,selectBackup:`Select a backup to choose what to restore.`,capturedHint:`Only data captured in this backup can be selected. Configuration includes workspace settings when present.`,relocationTargetRequired:`Choose a destination profile with a custom SQLite location.`,relocationHint:`The chat index will be restored to the selected destination. Codex configuration and workspace settings will not be restored. Session files, if selected, remain in the source Codex Home.`,restoreConfig:`Restore Codex configuration`,restoreDatabase:`Restore local chat index`,restoreSessions:`Restore session files`,relocation:`Restore to another storage profile`,targetProfile:`Destination storage profile`,prepare:`Preview restore`,pruneKeep:`Keep newest backups`,prune:`Delete older backups`,readOnly:`This version can view backups but cannot restore or delete them.`},history:{title:`Chats`,subtitle:`Select a chat to view its messages.`,empty:`No chats found.`,untitled:`Untitled chat`,subagentTitle:`Subtask · {{name}}`,sessionActions:`Session actions`,noProject:`Other chats`,filters:`Search options and filters`,projectTreeHint:`Main chats by project · expand arrows for subtasks`,mainWithSubtasks:`Main chats with nested subtasks`,rootCount:`{{count}} main chats`,orphanCount:`{{count}} unlinked subtasks`,orphans:`Unlinked subtasks`,orphansHint:`No reliable main-session link was found. These records are kept separately, not deleted.`,toggleSubtasks:`Subtasks of {{title}} ({{count}})`,childrenOf:`Subtasks of {{title}}`,loadMore:`Load more`,retryLoad:`Retry`,directoryBadge:`Directory`,projectKinds:{workspace:`Saved workspace`,directory:`Recorded working directory; no saved workspace matched.`,unassigned:`No recorded project directory`,orphans:`Missing or invalid parent-session relationship`},projectActions:`Project display options`,projectAliasTitle:`Set project display name`,projectAliasReset:`Use original name`,projectDisplayName:`Display name`,projectAliasHint:`Only changes the name shown in this app for this storage profile. Does not rename the directory or edit Codex data. Leave empty to use the original name.`,projectAliasContextHint:`Right-click or press Shift+F10 to set a local display name.`,projectAliasFailed:`Could not save the display name. Use up to 160 characters without control characters, then retry.`,contextMenuHint:`Right-click or press Shift+F10 for session actions.`,groupCount:`{{count}} chats on this page`,showMore:`Show more`,showLess:`Show less`,copyId:`Copy session ID`,copyResume:`Copy resume command`,copyPath:`Copy file path`,revealFile:`Show in File Explorer`,fileRevealed:`Session file located.`,revealFailed:`Could not locate the file. Refresh and try again.`,copyFailed:`Could not copy. Try again, or select the text and copy it manually.`,missingNativeId:`This record has no original session ID. Its internal list ID cannot be used to resume it.`,resumeHint:`Copies a command only. Run it in the matching Codex Home environment and original project directory; it does not switch Provider or guarantee continuation.`,sessionInformation:`Session information`,nativeId:`Original session ID`,sessionType:`Session type`,mainSessions:`Main sessions`,subtasks:`Subtasks`,parentId:`Parent session ID`,openParent:`View parent session`,parentUnavailable:`The parent session is not available in this storage profile.`,recordedProvider:`Recorded Provider`,recordedModel:`Recorded model`,notRecorded:`Not recorded`,createdAt:`Created`,fileModifiedAt:`File modified`,fileTimeHint:`File modification time can change after sync; it is not the last chat time.`,projectDirectory:`Project directory`,sessionFile:`Session file`,localInfoHint:`Local paths are available in the desktop app after this session is loaded.`,searchScope:`Search scope`,metadataSearch:`Title / ID / project`,contentSearch:`Chat content`,metadataSearchHint:`Searches names, IDs, projects and Providers without reading chat messages. Press Enter or Search to run.`,contentSearchHint:`Searches full chat content only when you press Enter or Search. Large histories may take a moment.`,untitledIdentity:`Untitled chat · {{date}} · {{id}}`,open:`View chat`,back:`Back to chats`,messages:`messages`,archived:`Archived`,active:`Active`,pagination:`Chat pagination`,listRegion:`Chat list`,detailRegion:`Chat details and messages`,refreshDetail:`Refresh chat`,pageSummary:`Page {{page}} · {{total}} chats`,previous:`Previous`,next:`Next`,searchPlaceholder:`Search chats`,providerFilter:`Filter by Provider`,archivedFilter:`Chat status`,all:`All chats`,select:`Select a chat on the left to view its messages.`,truncated:`This chat is long. Only the 200 most recent messages are shown.`,searchHint:`Search starts only after you submit. Large chat histories may take a moment.`,roles:{user:`You`,assistant:`Assistant`}},logs:{profileMismatch:`These actions require the original storage profile and revision. Select that profile, or locate a backup manually if its settings have changed.`,title:`Operation logs`,subtitle:`View operations started by this app, including their progress, results, and timing. Chat content and credentials are never recorded.`,empty:`No operations yet. Sync, switch, restore, or repair activity will appear here.`,select:`Select an operation to view its result and timing.`,listRegion:`Operation list`,detailRegion:`Operation details`,backToList:`Back to operations`,refreshDetail:`Refresh operation details`,identifiers:`Reference numbers`,detailUnavailable:`This log is no longer available. It may have been removed by log rotation.`,profileFilter:`Profile filter`,allProfiles:`All profiles`,operationFilter:`Operation filter`,statusFilter:`Filter by status`,allOperations:`All operations`,allStatuses:`All statuses`,activeDuration:`Processing time`,wallDuration:`Total time (including confirmation)`,startedAt:`Started`,completedAt:`Finished`,timeline:`Progress`,counts:`Completed changes`,previewCounts:`Previewed changes`,switchPlan:`Planned Provider switch`,switchPlanUnavailable:`This older record did not save switch details.`,fileTiming:{title:`File update timing`,pending:`File timing will be available after execution.`,unavailable:`File timing was not recorded for this operation.`,files:`Measured {{measured}} of {{attempted}} files · In-place {{inPlace}} · Replaced {{rewritten}} · Skipped {{skipped}}`,incomplete:`Some file timing was not returned. These are partial measurements, not the complete update cost.`,milliseconds:`{{value}} ms`,more:`Technical timing details`,nested:`Request time includes worker time; worker time includes its file stages. These measurements overlap and must not be added together. Timestamp restoration is still performed.`,phases:{copyTailMs:`Copy unchanged content`,flushMs:`Flush file data`,replaceMs:`Replace file`,cleanupMs:`Clean up temporary files`,restoreMtimeMs:`Restore file timestamps`,workerStartupMs:`Start file worker`,workerCloseMs:`Close file worker`,requestRoundTripMs:`Requests (including worker processing)`,workerMs:`Worker processing`,sourceOpenMs:`Open and check access`,readHeaderMs:`Read and check metadata`,tempCreateMs:`Create temporary files`}},notSet:`Not set`,providerChange:`Provider`,rootModelChange:`Root model`,modelMode:`Model handling`,switchPlanPartial:`This was the planned target. The operation finished partially; review the completed changes above before retrying.`,targetProvider:`Target Provider`,errorReason:`Reason`,errorReasons:{profile:`Storage profile changed`,config:`Codex configuration changed`,storage:`Storage location changed`,rollout:`Session files changed`,"state-db":`Local chat index changed`,backup:`Backup state changed`,"provider-not-configured":`Provider is not configured`},previewCountLabels:{rolloutFilesToChange:`Session files to update`,sqliteRowsToChange:`Local index records to update`,lockedRolloutFiles:`Sessions in use`},pageSummary:`Page {{page}} · {{total}} operations`,lessThanSecond:`Less than 1 second`,seconds:`{{value}} seconds`,minutesSeconds:`{{minutes}} min {{seconds}} sec`,logId:`Log number`,requestId:`Request number`,planId:`Confirmation number`,operationId:`Operation number`,backupId:`Backup number`,otherOperation:`Other operation`,unknownStage:`Processing`,operations:{sync:`Sync`,switch:`Switch Provider`,repair:`Repair`,restore:`Restore`,pruneBackups:`Delete older backups`,diagnostics:`Diagnostics`,watch:`Automatic sync`,update:`Update`,profile:`Storage profile`,runtime:`Background service`},statuses:{running:`Running`,"awaiting-confirmation":`Awaiting confirmation`,completed:`Completed`,partial:`Partially completed`,failed:`Failed`,cancelled:`Cancelled`,dismissed:`Cancelled before start`,interrupted:`Interrupted`},stages:{prepare:`Review changes`,prepare_config:`Read Codex configuration`,prepare_storage:`Resolve storage`,prepare_rollouts:`Prepare session files`,prepare_status:`Read current status`,prepare_revisions:`Capture protected revisions`,prepare_usage:`Check session use`,acquire_lock:`Acquire write lock`,read_config:`Read Codex configuration`,resolve_storage:`Resolve storage`,check_pending_restore:`Check pending restore`,validate_plan:`Recheck before writing`,scan:`Check data`,scan_rollout_files:`Check session files`,check_locked_rollout_files:`Check sessions in use`,create_backup:`Create backup`,rewrite_rollout_files:`Update session files`,repair_workspace_roots:`Update workspace locations`,update_sqlite:`Update local chat index`,update_config:`Update Codex configuration`,preflight_sqlite:`Check local chat index access`,release_lock:`Release write lock`,clean_backups:`Organize older backups`,verify_repair:`Verify repair results`,create_restore_pre_snapshot:`Create pre-restore snapshot`,persist_restore_journal:`Prepare recovery record`,apply_restore_targets:`Restore selected data`,commit_restore:`Finish restore`,acknowledge_restore_commit:`Confirm restored data`,rollback_restore:`Undo incomplete restore`,prune:`Delete older backups`,start:`Start automatic sync`,stop:`Stop automatic sync`,"automatic-sync":`Run automatic sync`,create:`Create storage profile`,update:`Update storage profile`,delete:`Delete storage profile`,export:`Export diagnostics`,check:`Check for updates`,download:`Download update`,install:`Install update`},stageStatuses:{running:`In progress`,completed:`Completed`,failed:`Failed`},countLabels:{changedSessionFiles:`Session files updated`,inPlaceSessionFiles:`Session files updated in place`,rewrittenSessionFiles:`Session files rewritten`,sqliteRowsUpdated:`Local index records updated`,sqliteProviderRowsUpdated:`Provider records updated`,sqliteModelRowsUpdated:`Model records updated`,sqliteUserEventRowsUpdated:`User-event records updated`,sqliteCwdRowsUpdated:`Workspace records updated`,skippedLockedRolloutFiles:`Sessions still in use`,skippedChangedRolloutFiles:`Sessions changed during the operation`,updatedWorkspaceRoots:`Workspace locations updated`,savedWorkspaceRootCount:`Workspace locations saved`,resolvedOperationCount:`Recovery items resolved`}},profiles:{title:`Storage profiles`,subtitle:`Create a profile for each Codex data location you use. Folder locations stay on this device.`,id:`Profile ID`,name:`Name`,codexHome:`Codex data folder`,sqliteHome:`Chat index folder (optional)`,create:`Create profile`,update:`Save changes`,managed:`Default`,chooseFolder:`Choose folder`,keepCurrent:`Do not change the current folder`,notSelected:`No folder selected`,inheritSqlite:`Find the chat index automatically`,customSqlite:`Choose a chat index folder`,revealCodex:`Open Codex data folder`,revealSqlite:`Open chat index folder`,selectCodexRequired:`Choose a Codex data folder for the new profile.`,defaultName:`Default location`,defaultManaged:`The default location is determined when the app starts and cannot be edited or deleted. Create another profile to use a different location.`,saved:`Storage profile saved`,deleted:`Storage profile deleted`,unavailable:`Storage profile management is unavailable.`,pathManaged:{desktop:`The folder location is stored securely by this app.`,web:`The folder location is stored by the local Web app.`},readOnly:`This version can view storage profiles but cannot edit them.`},diagnostics:{title:`Advanced features`,subtitle:`Optional tools for specific problems. For everyday Provider sync and switching, use Overview.`,scanTitle:`Full diagnostics · Read only`,scanHint:`Run a detailed check only when needed. It does not modify data or start repairs; chat content and credentials are never included in the report.`,repairScope:`These repairs do not fix session record numbering or rebuild the Codex history display index. They do not run during Provider sync.`,runtime:`App environment`,storage:`Storage locations`,provider:`Provider`,issues:`Check results`,issuesHint:`These counts show metadata differences and compatibility notices, not a count of damaged chats. Nothing is repaired automatically.`,modelDifferenceHint:`Historical chats may use different models intentionally. Unify model labels only if you need them to match the current root model.`,workspaceCountHint:`Workspace items count settings to adjust (including a missing settings backup), not folders or chats.`,encryptedHint:`Encrypted content is normal session data, not corruption. This check only detects the field; it does not test decryption or modify it. Continuing a chat with another Provider/account may require the original Provider/account.`,safety:`Operation status`,runScan:`Start diagnostics`,retryScan:`Retry diagnostics`,scanning:`Scanning… Full diagnostics may take several minutes. You can leave this page and return to view the result.`,scanFailed:`Diagnostics could not finish`,scanFailedHint:`No data was changed. Retry diagnostics; if it fails again, check Operation logs for details.`,previousResult:`Previous successful result · {{time}} (not the current scan)`,expiredResult:`Earlier diagnostic result · {{time}} (a write completed afterwards; run diagnostics again for a current result)`,scanCompleted:`Diagnostics completed · {{time}}`,incompleteScan:`Some data changed or could not be read during this scan. Results are for reference; run diagnostics again when the chats are idle.`,notScanned:`Diagnostics have not been run`,notScannedHint:`Start diagnostics when you need a detailed check. It runs only when requested and never changes your data.`,repairTitle:`Targeted repair`,repairHint:`Use for the specific issues described below. Everyday Provider sync does not need these options. Select an item and preview its changes before confirming.`,adjustmentTitle:`Advanced adjustments`,adjustmentHint:`Optional changes, not fault repairs. Different models in past chats are normal; leave this unchanged unless you want to unify their recorded names.`,previewAdjustment:`Preview adjustment`,availableRepairs:`Items to review from this check`,viewRepair:`View repair`,viewSpecificRepair:`View repair: {{target}}`,findings:{cwd:`{{count}} chat index entries record a different working folder`,userEvent:`{{count}} chat index entries lack a user-message marker`,workspaceRoots:`{{count}} project settings items can be organized`},repairTargetHints:{models:`Use only to make recorded model names in past chats match the model currently configured. Updates those names in chat files and the index; does not regenerate replies or change the Provider.`,cwd:`Use when the chat index records a different project folder than the chat file. Corrects the index using the folder recorded in that file; does not move files or change your current project.`,userEvent:`Use when a chat contains a user message but its index says it does not. Completes that index marker; does not add, remove or edit messages.`,workspaceRoots:`Use when saved project directory settings have duplicate or inconsistent entries. Normalizes those settings and preserves a settings backup; does not move or delete project folders. Applies to the whole profile and also corrects chat working folders.`},repairTargetRequired:`Select at least one repair target.`,workspaceRootsIncludesCwd:`This also corrects chat working folders across the whole profile; it cannot be limited to selected chats.`,prepareRepair:`Preview repair`,repairTargets:{models:`Unify historical model names`,cwd:`Correct chat project folders`,userEvent:`Complete user-message markers`,workspaceRoots:`Organize project directory records`},items:`{{count}} items`,fieldsAvailable:`{{count}} redacted fields`,technicalDetails:`Show technical details`,fields:{arch:`Architecture`,node:`Node.js`,platform:`Platform`,sqliteHomeSource:`SQLite Home source`,sqliteSupported:`SQLite supported`,stateDbFound:`State DB found`,configured:`Configured Providers`,current:`Current Provider`,implicit:`Implicit Provider`,rolloutCounts:`Rollout distribution`,sqliteCounts:`SQLite distribution`,rootModelAvailable:`Root model available`,rolloutModelFilesNeedingRepair:`Session files with model labels differing from the root model`,sqliteModelRowsNeedingRepair:`Index rows with model labels differing from the root model`,cwdRowsNeedingRepair:`Index rows with differing working folders`,userEventRowsNeedingRepair:`Index rows missing a recorded user-message marker`,workspaceRootsNeedingRepair:`Workspace settings to adjust`,encryptedContentFiles:`Session files containing encrypted content (informational)`,lockedRolloutCount:`Locked rollouts`,operationInProgress:`Operation in progress`,pendingRecovery:`Recovery required`,pendingTransactions:`Pending transactions`,projectThreadVisibilityAvailable:`Project visibility available`,rolloutScanComplete:`Rollout scan complete`,storageRevision:`Storage revision`},export:`Export redacted bundle`,exporting:`Exporting…`,exportCreated:`Redacted diagnostics bundle created.`,exportCancelled:`Diagnostics export cancelled.`,exportFailed:`Diagnostics export failed.`,historyIntegrity:{title:`History record checks`,scope:`This bounded, read-only check observes JSON records and numeric record order only. It does not declare the history display healthy, repair records, or infer missing sequence gaps as damage.`,displayIndexUnsupported:`The Codex display-index format is not known to this app, so it was not verified or rebuilt.`,outcomes:{"no-findings":`No observations`,findings:`Observations found`,inconclusive:`Incomplete check`,"findings-and-inconclusive":`Observations and incomplete check`},skipped:`Some records were skipped within the scan limits; treat the result as incomplete.`,findings:`Observations requiring review`,moreFindings:`Additional findings were omitted from this list; see technical details.`,manualReview:`Requires manual review`,session:`Session {{sessionId}}`,line:`line {{line}}`,copySessionId:`Copy session ID`,copiedSessionId:`Session ID copied`,issueCodes:{"unsupported-format":`Record format requires manual review`,"invalid-utf8":`Record text could not be read as UTF-8`},counts:{filesDiscovered:`Files discovered`,filesScanned:`Files scanned`,recordsRead:`Records read`,sessionsWithId:`Sessions with an ID`,jsonCorruptRecords:`Records with invalid JSON`,oversizedRecords:`Records above the size limit`,duplicateOrdinals:`Repeated numeric record order`,outOfOrderOrdinals:`Out-of-order numeric records`,changedFiles:`Files changed during scan`,truncatedFiles:`Files stopped at a scan limit`}}},settings:{title:`Settings`,subtitle:{desktop:`Manage appearance, automatic sync, and app updates. Preferences stay on this device.`,web:`Manage appearance and browser settings. Preferences stay in this browser.`},language:`Language`,languageHint:`Changes take effect immediately.`,theme:`Theme`,system:`System`,light:`Light`,dark:`Dark`,watch:`Automatic sync`,watchHint:`Automatically sync Provider information when files in the selected storage change. Profiles using the same Codex Home share one watcher; disabling it stops that shared watcher. Its options and execution/stop logs belong to the first profile that enabled it (visible under All profiles in logs).`,watchStart:`Enable automatic sync`,watchStop:`Disable automatic sync`,watchRecoveryBlocked:`Complete recovery before enabling automatic sync.`,watchStatuses:{running:`Enabled`,stopped:`Disabled`,starting:`Starting`,stopping:`Stopping`,failed:`Needs attention`},update:`Updates`,updateCurrentVersion:`Current version: {{version}}`,updateManualHint:`Check once on the first launch each day; only newer releases trigger a popup. This portable or local build opens the GitHub download page; download and replace it manually. It does not install or restart automatically.`,updateAutomaticHint:`Check once on the first launch each day and notify only for newer releases. Download when ready, then confirm a restart to install. Your Codex data is not part of the update.`,updateOpenDownload:`Open official download page`,updateRequestFailed:`The update request failed. Refresh the status or retry; the current app remains available.`,updateStatus:{disabled:`In-app updates unavailable`,idle:`Not checked yet`,checking:`Checking`,available:`Update available`,downloading:`Downloading`,downloaded:`Ready to install`,"not-available":`Up to date`,error:`Update failed`,installing:`Restarting to install`},updateReason:{"not-packaged":`This installation does not support in-app updates.`,"not-authorized":`In-app updates are not enabled in this version.`,"not-configured":`In-app updates are not enabled in this version.`,"unsupported-target":`In-app updates are not supported on this platform.`,"check-failed":`Could not check for updates. Try again later.`,"download-failed":`Could not download the update. Try again later.`,"install-failed":`The installer could not be started; the current version remains active.`},updateBlocked:{"write-in-progress":`Wait for the current operation to finish before installing the update.`,"watch-active":`Disable automatic sync before installing the update.`,"pending-recovery":`Complete recovery before installing the update.`,"recovery-unverified":`The app could not verify that all storage profiles are ready. Installation remains paused.`},updateVersion:`Version {{version}}`,updateProgress:`{{percent}}% downloaded`,updateCheck:`Check for updates`,updateDownload:`Download update`,updateInstall:`Restart and install`,forget:`Forget this browser`,englishFallback:`English is used when a translation is unavailable.`,forgetHint:`This browser's connection information will be removed from the local app.`},plan:{title:`Confirm operation`,switchTitle:`Confirm Provider switch`,confirmSwitch:`Confirm switch`,titles:{sync:`Confirm sync`,switch:`Confirm Provider switch`,repair:`Confirm repair`,restore:`Confirm restore`},confirmActions:{sync:`Confirm sync`,switch:`Confirm switch`,repair:`Confirm repair`,restore:`Confirm restore`},operations:{sync:`Sync Provider information`,switch:`Switch Provider`,repair:`Repair chat information`,restore:`Restore backup`,operation:`Operation`},modelModes:{"provider-default":`Use model configured for this Provider`,"keep-root-model":`Keep current root model`,explicit:`Specify root model`},historyModelsUnaffected:`Historical Provider metadata will be synchronized, but models recorded by historical sessions will not be changed.`,fields:{modelMode:`Model handling`,rootModelChange:`Root model change`,repairTargets:`Repair targets`,restoreConfig:`Restore Codex configuration`,restoreDatabase:`Restore local chat index`,restoreSessions:`Restore session files`,relocation:`Restore to another storage profile`,rolloutFiles:`Session files to update`,sqliteRows:`Local index records to update`,affectedSessions:`Affected chats (unique)`,sqliteFields:`Index field changes (total)`,sqliteModels:`Model fields`,sqliteCwd:`Working-folder fields`,sqliteUserEvent:`User-message markers`,workspaceSettings:`Workspace settings to update`,workspaceRoots:`Workspace locations to update`,stateDbFiles:`Local index files to restore`,configFiles:`Codex configuration files to restore`,lockedRollouts:`Sessions to skip this time`},stages:{prepare_config:`Read Codex configuration`,prepare_storage:`Resolve storage`,prepare_rollouts:`Prepare session files`,prepare_status:`Read current status`,prepare_revisions:`Capture protected revisions`,prepare_usage:`Check session use`,acquire_lock:`Acquire write lock`,read_config:`Read Codex configuration`,resolve_storage:`Resolve storage`,check_pending_restore:`Check pending restore`,validate_plan:`Recheck before writing`,scan_rollout_files:`Check chat records`,check_locked_rollout_files:`Check chats in use`,preflight_sqlite:`Check local chat index access`,create_backup:`Create backup`,rewrite_rollout_files:`Update chat records`,update_sqlite:`Update local chat index`,update_config:`Update Codex settings`,release_lock:`Release write lock`,clean_backups:`Organize older backups`,verify_repair:`Verify repair results`,create_restore_pre_snapshot:`Create a recovery point`,persist_restore_journal:`Prepare restore`,apply_restore_targets:`Restore selected data`,commit_restore:`Finish restore`,acknowledge_restore_commit:`Confirm restored data`,rollback_restore:`Undo incomplete restore`},statuses:{start:`Starting`,progress:`In progress`,complete:`Completed`},target:`Selected changes`,impact:`Expected changes`,expires:`Confirm before`,items:`{{count}} items`,backupExpected:`A backup will be created before writes.`,exactApply:`The app checks the data again before applying these changes. If anything changed, you will be asked to review again.`,workspaceChanges:{savedRoots:`Organize saved project folders`,projectOrder:`Organize project order`,activeRoots:`Normalize active workspace folders`,labels:`Normalize project folder labels`,openTargets:`Normalize project opening preferences`,settingsBackup:`Create the missing settings backup`},repairPreview:{effectsTitle:`What will change`,unchanged:`Chat text, message order and timestamps stay unchanged. This does not rebuild the Codex history display index.`,title:`Affected chat preview`,hint:`Choose the whole profile or only listed chats. Changing the selection creates a new preview before it can be confirmed.`,all:`Whole profile`,selected:`Selected chats`,selectSession:`Select chat {{sessionId}}`,none:`No affected chats are included in this preview.`,total:`{{count}} affected chats found`,truncated:`Only the first 100 are shown.`,regenerating:`Updating the preview. The earlier confirmation cannot be applied.`,selectionChanged:`The selection changed. Update the preview before confirming.`,update:`Update repair preview`,refineFailed:`The earlier preview has been dismissed and cannot be confirmed. Resolve the error, then prepare a new preview.`,workspaceGlobal:`Workspace settings are global. This repair applies to the whole profile and cannot be limited to selected chats.`,changes:{models:`Model label`,cwd:`Working folder`,userEvent:`User-message marker`},markers:{different:`different`,"rollout-cwd":`folder recorded in the chat file`,false:`not recorded`,true:`recorded`}},writeBlocked:`Another operation is running, or recovery is required. Wait until it is safe to continue.`,technicalDetails:`Operation details`,progress:`Operation progress`,starting:`Starting…`,cancelOperation:`Cancel operation`,cancelling:`Cancelling…`,cancelPending:`Cancellation will take effect at the next safe point.`},operationResult:{title:`Operation result`,operationId:`Operation ID`,backupId:`Managed backup ID`,backupCreated:`A backup was created. You can find it under Backups and Restore.`,openBackupRestore:`Open restore preview`,changeCountersHint:`These are changed records or settings, not a count of unique chats.`,skippedRollouts:`Sessions still in use`,skippedChangedRollouts:`Sessions changed during the operation`,skippedCount:`{{count}} session records were not updated.`,retryAfterSession:`Close the active Codex session, then run sync again.`,retryFreshPlan:`Review the operation again and retry.`,reviewOperation:`Back to operation tools`,verification:{title:`Verification after repair`,status:{verified:`The selected repair targets were verified after the write.`,remaining:`Some selected metadata still needs attention. Review the remaining counts before preparing another repair.`,unavailable:`A post-write verification result was not available. No additional repair was started.`},remainingRolloutFiles:`Remaining session-file differences`,remainingSqliteRows:`Remaining local index differences`,remainingWorkspaceRoots:`Remaining workspace settings`,skippedSessions:`Skipped chat records`},partialReasons:{"locked-session":`A chat is still in use`,"rollout-changed":`A chat changed during the operation`,"mutation-failed":`The operation stopped after some changes were saved`},resolveBeforeClose:`Resolve the pending recovery before closing this result.`,fields:{inPlaceSessionFiles:`In-place rollout updates`,rewrittenSessionFiles:`Fully rewritten rollouts`,targetProvider:`Target Provider`,targetModel:`Target model`,modelSource:`Model source`,partialReason:`Partial reason`,failedStage:`Failed stage`,failureCode:`Failure code`,retryRecommended:`Retry recommended`,restoreOperationId:`Restore operation ID`,preRestoreSnapshotId:`Pre-restore snapshot ID`,restoreJournalState:`Restore journal state`,backupDurationMs:`Backup duration (ms)`,changedSessionFiles:`Chat records updated`,sqliteRowsUpdated:`Local index records updated`,sqliteProviderRowsUpdated:`Provider records updated`,sqliteModelRowsUpdated:`Model records updated`,sqliteUserEventRowsUpdated:`User activity records updated`,sqliteCwdRowsUpdated:`Workspace records updated`,updatedWorkspaceRoots:`Workspace locations updated`,savedWorkspaceRootCount:`Workspace locations saved`,repairTargets:`Repair targets`,restoreVersion:`Restore format version`,resolvedOperationCount:`Resolved operations`,commitAcknowledgementRecovered:`Commit acknowledgement recovered`},completed:{title:`Completed`,description:`The operation completed and the changes were saved.`},partial:{title:`Partially completed`,description:`Some changes were not completed. Follow the guidance below to retry, or restore from a backup.`},failedRolledBack:{title:`Failed and rolled back`,description:`The operation failed, and the previous state was restored successfully.`},recoveryRequired:{title:`Recovery required`,description:`A previous restore did not finish. Complete recovery before making more changes.`},cancelled:{title:`Cancelled`,description:`The operation was cancelled and no further steps were performed.`},stale:{title:`Review required`,description:`The data changed before the operation started. Review the changes again and retry.`}},validation:{required:`This field is required.`,keep:`Use a whole number from 1 to 1000.`,provider:`Enter a valid Provider ID.`,model:`Enter the model name you want to use.`,restore:`Select at least one item to restore.`,profileId:`Use letters, numbers, dots, underscores, or hyphens.`,path:`Enter a complete folder path.`},errors:{fallback:`The operation could not be completed. Try again; if the problem continues, check Operation logs or export diagnostics.`,INVALID_INPUT:`Check the information you entered and try again.`,providerNotConfigured:`The selected Provider is not defined in config.toml. Configure or switch it using your Provider tool, then sync again. No data was changed.`,PROFILE_CHANGED:`The selected storage profile changed. Review it and try again.`,STORAGE_CHANGED:`The storage location changed. Review the operation and try again.`,PLAN_STALE:`The data changed. Review the operation again before continuing.`,PLAN_EXPIRED:`This preview expired. Preview the operation again.`,STALE_STATE:`The data changed. Review the operation again before continuing.`,CODEX_HOME_NOT_FOUND:`The Codex data folder could not be found. Check the selected storage profile.`,STATE_DB_NOT_FOUND:`The local chat index could not be found. Check the selected storage profile.`,SQLITE_UNSUPPORTED_PATH:`This chat index location cannot be used on the current platform.`,SQLITE_BUSY:`The local chat index is in use. Close Codex and try again.`,SQLITE_UNREADABLE:`The local chat index could not be read. Run diagnostics or restore a backup.`,ROLLOUT_LOCKED:`Some chats are in use. Close the active Codex sessions and try again.`,ROLLOUT_CHANGED:`Some chats changed during the operation. Review and try again.`,PENDING_TRANSACTION:`A previous restore must be completed before continuing.`,BACKUP_FAILED:`A backup could not be created, so no changes were made.`,SYNC_FAILED_ROLLED_BACK:`The sync did not finish. The previous data was restored.`,RECOVERY_REQUIRED:`A previous restore did not finish. Complete recovery before continuing.`,RESTORE_VALIDATION_FAILED:`This backup cannot be restored to the selected location.`,PERMISSION_DENIED:`The app does not have permission to access the selected folder.`,OPERATION_BUSY:`Another operation is in progress. Wait for it to finish and try again.`,OPERATION_CANCELLED:`The operation was cancelled.`,CORE_RUNTIME_CRASHED:`The background service stopped unexpectedly. It will restart automatically when possible.`,PROTOCOL_VERSION_MISMATCH:`This app contains incompatible components. Reinstall the latest version.`,LOCK_UNVERIFIABLE:`The app could not verify that the storage location is available. Close Codex and try again.`,INTERNAL_ERROR:`An internal error occurred. Try again; if it continues, export diagnostics.`},warnings:{backupInventory:`The backup list could not be refreshed. Your existing backups were not changed.`,backupCleanup:`The operation completed, but older backups could not be deleted automatically.`,encryptedHistory:`Some encrypted chats may require the original Provider or account to continue.`,lockedSessions:`Some chats are currently in use and may not be updated. Close them and sync again.`,missingDefaultModel:`This Provider has no model configured. The current root model will be kept.`,projectVisibility:`Project chat visibility could not be checked. A backup will still be created before changes.`,relocationConfig:`The chat index will be restored to another storage profile, but the Codex configuration will not be restored.`,restoreSkipped:`The selected backup does not contain one of the requested items, so that item will be skipped.`,partial:`Only part of the requested change was completed. Try again or restore the backup.`,additional:`The operation completed with an additional warning. Review the operation log for details.`}}},"zh-CN":{translation:{requestProgress:{working:`处理中…`,elapsed:`已耗时 {{time}}`,files:`已检查 {{count}} 个文件`,stagePercent:`当前阶段 {{percent}}%`,stages:{waiting:`正在开始…`,prepare_repair_context:`正在读取配置并核对预览状态…`,prepare_diagnostics:`正在准备检查…`,scan_sessions:`正在检查会话记录…`,scan_archived_sessions:`正在检查已归档会话…`,inspect_repair_sqlite:`正在检查需要调整的聊天索引…`,inspect_workspace_roots:`正在检查工作区设置…`,build_repair_preview:`正在生成改动预览…`,inspect_diagnostics_index:`正在检查聊天索引…`,inspect_diagnostics_backups:`正在检查备份与恢复状态…`,inspect_history_integrity:`正在准备会话完整性检查…`,integrity_sessions:`正在检查会话记录完整性…`,integrity_archived_sessions:`正在检查归档记录完整性…`,finish_diagnostics:`正在汇总检查结果…`}},backupPolicy:{title:`备份设置`,count:`保留备份数量`,save:`保存备份设置`,scope:`本应用统一使用一套规则,同步、切换、专项修复和自动同步共用。每个 Codex Home 分别保留备份,不按操作类型重复计算。`,current:`已保存规则:每个 Codex Home 保留最近 {{count}} 份备份。`,operationHint:`改动前自动备份,保留最近 {{count}} 份。统一在“备份与恢复”中管理。`,hint:`保存设置不会删除备份;后续写操作使用已保存规则,手动清理仍需确认。恢复所需的受保护备份可能超过该数量。修改前请先停止自动同步。`,saved:`备份设置已保存,没有删除任何备份。`,"watch-active":`自动同步正在运行,请先在设置中停止,再保存备份规则。`,failed:`备份设置保存失败,原规则未变,请重试。`,clear:`删除全部可清理备份`},ux:{reading:`正在读取状态…`,unknown:`尚未验证`,previousSnapshot:`正在刷新,当前显示上次快照。`,currentProfile:`正在使用`,finalStatus:`最终 Provider 检查`,finalChecking:`正在读取操作后的状态…`,finalUnavailable:`操作结果已返回,但最终 Provider 对齐状态尚未验证。请刷新概览后确认。`,pruneEstimate:`按当前列表估算:最多清理 {{remove}} 份备份,至少保留 {{keep}} 份。`,pruneCaution:`恢复所需的备份仍受保护。列表可能变化,实际清理数量以执行结果为准。`,pruneTitle:`确认清理备份`,pruneConfirm:`确认清理`,pruneZero:`本次将请求删除所有可清理的受管备份,不会删除受保护的恢复备份。删除后无法通过本工具找回,自动保留规则不会改变。`,pruneChanged:`备份列表或存储配置已变化,请关闭后重新确认清理范围。`,clearFilters:`清除筛选`,pendingFilters:`搜索词、Provider 或搜索范围已修改,点击搜索后生效。`},brand:{desktop:{label:`桌面端`,subtitle:`管理 Codex Provider 与本地会话记录`},web:{label:`Web`,subtitle:`本地 Web 管理界面`}},a11y:{skipToContent:`跳到主要内容`,profile:`存储配置`,primaryNavigation:`主导航`},nav:{overview:`概览`,sync:`同步`,switchProvider:`切换 Provider`,backupsRestore:`备份 / 恢复`,history:`聊天记录`,operationLogs:`操作日志`,profiles:`存储配置`,diagnostics:`高级功能`,settings:`设置`},common:{refresh:`刷新`,loading:`正在加载…`,processing:`处理中`,cancel:`取消`,confirm:`确认并执行`,save:`保存`,delete:`删除`,close:`关闭`,dismissNotification:`关闭通知:{{title}}`,yes:`是`,no:`否`,none:`无`,unknown:`未知`,current:`当前`,provider:`Provider`,model:`模型`,status:`状态`,warnings:`警告`,retry:`重试`,advanced:`高级选项`,search:`搜索`,copy:`复制`,copied:`已复制`},global:{ready:`就绪`,readingStatus:`正在读取状态…`,statusUnavailable:`无法读取当前状态`,statusNeedsRefresh:`状态待刷新`,statusChangedHint:`数据发生变化,请刷新后重试。`,statusUnavailableHint:`未能读取完整状态,请刷新重试。`,retryStatus:`重新读取状态`,busy:`操作执行中`,busyHint:`另一项操作正在使用当前存储位置,完成后即可继续。`,lockUnverified:`存储锁需要检查`,lockUnverifiedHint:`无法确认另一项操作是否已结束。关闭其他同步工具后重新检查;若仍无法继续,请在高级功能中导出诊断包。请勿手动删除锁。`,staleLock:`上次操作已结束`,staleLockHint:`可以正常预览或同步。写入前会重新检查,并在确认安全后清理上次操作留下的锁。`,recoveryTitle:`需要先恢复数据`,recovery:`上一次恢复没有完成。请先完成恢复,再执行其他修改。`,stale:`数据已经发生变化,请重新检查后再执行。`,unexpected:`出现了问题,请重试。`,partial:`部分记录暂未更新。请关闭正在使用的 Codex 会话后重试。`,completed:`操作已完成。`,cancelled:`操作已取消。`,profileChanged:`存储配置已变化。`,profileChangedHint:`请检查当前选择的存储位置,然后重试。`,failed:`本次操作未能完成。`},overview:{title:`Provider 同步概览`,subtitle:`查看当前 Provider 与本地聊天记录是否保持一致。`,alignment:`同步状态`,aligned:`已同步`,notAligned:`建议同步`,rollout:`会话记录文件`,sqlite:`本地聊天索引`,codexHomeSource:`Codex 数据位置`,sqliteHomeSource:`聊天索引位置`,stateDbPath:`当前数据库文件`,stateDbMissing:`尚未找到数据库`,snapshot:`快照时间`,backupCount:`可用备份`,locked:`正在使用的会话`,usageUnknown:`未知`,profile:`当前存储配置`,manageStorage:`管理存储配置`,operations:`同步与切换`,operationsHint:`在这里同步当前 Provider,或切换到其他 Provider。`,sources:{profile:`当前存储配置`,config:`Codex 配置文件`,env:`环境变量`,default:`默认位置`,explicit:`当前存储配置`,unknown:`未能确定`}},sync:{title:`同步当前 Provider`,subtitle:`只按当前配置同步 Provider 信息,不修复模型、聊天正文或历史记录。`,keep:`保留最近备份数量`,prepare:`预览同步`,direct:`直接同步`,directHint:`直接同步使用当前 Provider,不再弹出确认。写入前仍会检查并备份,不执行高级修复。`,preparingDirect:`正在检查同步内容`,runningDirect:`正在同步`,performance:{title:`如何加快同步`,resultLink:`查看提速建议`,equalLength:`使用等长的英文 Provider ID 并通过文件检查时,可直接更新标记,无需复制整个聊天文件,通常更快。例如 openai 与 prov_a 都是 6 个字符。`,differentLength:`长度不同时仍可正常同步,但需要复制文件,聊天文件越大,耗时越长。软件会自动选择合适的方式,无需开启设置。`,configuration:`如需调整 Provider ID,请在配置及所用的 Provider 管理工具中保持一致,只修改显示名称无效。不改名也可以正常同步。`}},switchPage:{title:`单独切换 Provider`,subtitle:`修改配置中的 Provider,再执行同样的 Provider 同步。执行前可以预览改动范围。`,provider:`Provider ID`,modelMode:`模型处理方式`,providerDefault:`使用 config.toml 中该 Provider 的模型`,keepModel:`保留当前根模型`,explicitModel:`手动指定根模型`,modelModeDescriptions:{"provider-default":`读取 config.toml 中 [model_providers.{{provider}}].model;未配置时保留当前根模型,不会联网查询 Provider。`,"keep-root-model":`只切换 model_provider,不修改 config.toml 根级 model。`,explicit:`将下方填写的模型名写入 config.toml 根级 model;不会验证远程 Provider 是否支持。`},historyModelHint:`切换时只同步历史记录的 Provider,不修改历史会话记录的模型;如需修改,请前往“高级功能 → 高级调整”。`,recentSuccessful:`最近成功使用`,model:`模型名称`,prepare:`预览切换`},backups:{title:`备份与恢复`,subtitle:`查看本应用创建的备份,并在需要时恢复数据。`,empty:`还没有备份。应用会在修改数据前自动创建备份。`,loadFailed:`无法读取备份,未更改任何备份。`,requestedMissing:`当前存储配置中已找不到这份备份,可能已按保留数量清理。请选择现有备份。`,selectBackup:`请先选择一份备份,再选择恢复内容。`,capturedHint:`只能恢复这份备份实际保存的内容;配置恢复也包含已备份的工作区设置。`,relocationTargetRequired:`请选择已设置自定义 SQLite 位置的目标存储配置。`,relocationHint:`聊天索引将恢复到所选目标;不恢复 Codex 配置和工作区设置。如果选择了会话记录文件,它们仍恢复到来源 Codex Home。`,restoreConfig:`恢复 Codex 配置`,restoreDatabase:`恢复本地聊天索引`,restoreSessions:`恢复会话记录文件`,relocation:`恢复到其他存储配置`,targetProfile:`恢复到的存储配置`,prepare:`预览恢复`,pruneKeep:`保留最新备份数`,prune:`删除较早的备份`,readOnly:`当前版本可以查看备份,但暂不支持恢复或删除。`},history:{title:`聊天记录`,subtitle:`选择一条会话即可查看聊天内容。`,empty:`没有找到会话。`,untitled:`未命名会话`,subagentTitle:`子任务 · {{name}}`,sessionActions:`会话操作`,noProject:`其他会话`,filters:`搜索选项与筛选`,projectTreeHint:`按项目显示主会话 · 点击箭头展开子任务`,mainWithSubtasks:`主会话及其子任务`,rootCount:`{{count}} 条主会话`,orphanCount:`{{count}} 条未关联子任务`,orphans:`未关联子任务`,orphansHint:`这些记录缺少可靠的主会话关联,单独保留,不会删除。`,toggleSubtasks:`{{title}} 的子任务({{count}})`,childrenOf:`{{title}} 的子任务`,loadMore:`加载更多`,retryLoad:`重试`,directoryBadge:`工作目录`,projectKinds:{workspace:`已保存的工作区`,directory:`会话记录的工作目录,尚未匹配已保存的工作区。`,unassigned:`未记录项目目录`,orphans:`父会话关系缺失或无效`},projectActions:`项目显示设置`,projectAliasTitle:`设置项目显示名`,projectAliasReset:`恢复原名称`,projectDisplayName:`显示名称`,projectAliasHint:`仅修改本应用在当前存储配置中的显示名称,不重命名目录、不修改 Codex 数据。留空可恢复原名称。`,projectAliasContextHint:`右键或按 Shift+F10 可设置本地显示名。`,projectAliasFailed:`未能保存显示名称,请使用不含控制字符的名称(最多 160 字),然后重试。`,contextMenuHint:`右键或按 Shift+F10 打开会话菜单。`,groupCount:`本页 {{count}} 条会话`,showMore:`展开显示`,showLess:`收起显示`,copyId:`复制会话 ID`,copyResume:`复制继续命令`,copyPath:`复制文件路径`,revealFile:`在资源管理器中显示`,fileRevealed:`已定位会话文件。`,revealFailed:`无法定位文件,请刷新后重试。`,copyFailed:`未能复制,请重试,或选中文字后手动复制。`,missingNativeId:`此记录没有原始会话 ID,内部列表标识不能用于继续会话。`,resumeHint:`仅复制命令。请在对应的 Codex Home 环境及原项目目录中运行;不会切换 Provider,也不保证旧会话可以继续。`,sessionInformation:`会话信息`,nativeId:`原始会话 ID`,sessionType:`会话类型`,mainSessions:`主会话`,subtasks:`子任务`,parentId:`父会话 ID`,openParent:`查看父会话`,parentUnavailable:`当前存储配置中找不到该父会话。`,recordedProvider:`记录的 Provider`,recordedModel:`记录的模型`,notRecorded:`未记录`,createdAt:`创建时间`,fileModifiedAt:`文件更新`,fileTimeHint:`同步等操作可能改变文件时间;这不代表最后聊天时间。`,projectDirectory:`项目目录`,sessionFile:`会话文件`,localInfoHint:`桌面端加载该会话后可查看本地路径。`,searchScope:`搜索范围`,metadataSearch:`标题 / ID / 项目`,contentSearch:`聊天正文`,metadataSearchHint:`只查名称、ID、项目和 Provider,不读取聊天正文。按回车或点击搜索后运行。`,contentSearchHint:`按回车或点击搜索后才扫描聊天正文;会话较多时可能需要一些时间。`,untitledIdentity:`无标题会话 · {{date}} · {{id}}`,open:`查看会话`,back:`返回聊天列表`,messages:`条消息`,archived:`已归档`,active:`活动`,pagination:`聊天分页`,listRegion:`会话列表`,detailRegion:`会话详情与消息`,refreshDetail:`刷新当前会话`,pageSummary:`第 {{page}} 页 · 共 {{total}} 个聊天`,previous:`上一页`,next:`下一页`,searchPlaceholder:`搜索聊天记录`,providerFilter:`按 Provider 筛选`,archivedFilter:`会话状态`,all:`全部会话`,select:`从左侧选择一条会话查看聊天内容。`,truncated:`该会话内容较长,仅显示最近 200 条消息。`,searchHint:`点击搜索后才会查找聊天内容;会话较多时可能需要一些时间。`,roles:{user:`你`,assistant:`助手`}},logs:{profileMismatch:`这些操作需要匹配原来的存储配置及版本。请选择原配置;如果位置已更改,请手动查找对应备份。`,title:`操作日志`,subtitle:`查看本应用发起的操作、执行过程、结果与耗时。不会记录聊天内容或凭据。`,empty:`还没有操作记录。完成同步、切换、恢复或修复后会显示在这里。`,select:`选择一条操作,查看执行结果和耗时。`,listRegion:`操作列表`,detailRegion:`操作详情`,backToList:`返回操作列表`,refreshDetail:`刷新操作详情`,identifiers:`关联编号`,detailUnavailable:`这条日志已不可用,可能已被日志保留策略清理。`,profileFilter:`存储配置筛选`,allProfiles:`全部存储配置`,operationFilter:`操作类型筛选`,statusFilter:`按状态筛选`,allOperations:`全部操作`,allStatuses:`全部结果`,activeDuration:`执行耗时`,wallDuration:`总耗时(含等待确认)`,startedAt:`开始时间`,completedAt:`结束时间`,timeline:`执行过程`,counts:`实际完成数量`,previewCounts:`预览改动数量`,switchPlan:`计划的 Provider 切换`,switchPlanUnavailable:`这条旧记录未保存切换详情。`,fileTiming:{title:`文件更新耗时`,pending:`执行结束后显示文件更新耗时。`,unavailable:`本次操作未记录文件分项耗时。`,files:`已计时 {{measured}} / {{attempted}} 个文件 · 原地更新 {{inPlace}} · 替换 {{rewritten}} · 跳过 {{skipped}}`,incomplete:`部分文件未返回计时,以下不是全部文件的完整耗时。`,milliseconds:`{{value}} 毫秒`,more:`技术耗时详情`,nested:`请求耗时包含工作进程处理,进程处理包含各文件阶段,不能重复相加。文件时间戳恢复仍保留。`,phases:{copyTailMs:`复制未改动内容`,flushMs:`数据落盘`,replaceMs:`替换文件`,cleanupMs:`清理临时文件`,restoreMtimeMs:`恢复文件时间戳`,workerStartupMs:`启动文件工作进程`,workerCloseMs:`关闭文件工作进程`,requestRoundTripMs:`请求往返(含文件处理)`,workerMs:`工作进程处理`,sourceOpenMs:`打开文件与检查占用`,readHeaderMs:`读取与核对首行`,tempCreateMs:`创建临时文件`}},notSet:`未设置`,providerChange:`Provider`,rootModelChange:`根模型`,modelMode:`模型处理方式`,switchPlanPartial:`这里显示的是预览目标;本次操作仅部分完成,请先查看上方实际完成数量再决定是否重试。`,targetProvider:`目标 Provider`,errorReason:`原因`,errorReasons:{profile:`存储配置已变化`,config:`Codex 配置已变化`,storage:`存储位置已变化`,rollout:`会话记录已变化`,"state-db":`本地聊天索引已变化`,backup:`备份状态已变化`,"provider-not-configured":`Provider 尚未配置`},previewCountLabels:{rolloutFilesToChange:`待更新会话记录`,sqliteRowsToChange:`待更新本地索引记录`,lockedRolloutFiles:`正在使用的会话`},pageSummary:`第 {{page}} 页 · 共 {{total}} 条操作`,lessThanSecond:`不足 1 秒`,seconds:`{{value}} 秒`,minutesSeconds:`{{minutes}} 分 {{seconds}} 秒`,logId:`日志编号`,requestId:`请求编号`,planId:`确认编号`,operationId:`操作编号`,backupId:`备份编号`,otherOperation:`其他操作`,unknownStage:`正在处理`,operations:{sync:`同步`,switch:`切换 Provider`,repair:`修复`,restore:`恢复`,pruneBackups:`删除较早备份`,diagnostics:`诊断`,watch:`自动同步`,update:`更新`,profile:`存储配置`,runtime:`后台服务`},statuses:{running:`执行中`,"awaiting-confirmation":`等待确认`,completed:`已完成`,partial:`部分完成`,failed:`失败`,cancelled:`已取消`,dismissed:`开始前取消`,interrupted:`异常中断`},stages:{prepare:`预览改动`,prepare_config:`读取 Codex 配置`,prepare_storage:`解析存储位置`,prepare_rollouts:`准备会话记录`,prepare_status:`读取当前状态`,prepare_revisions:`记录受保护版本`,prepare_usage:`检查会话使用情况`,acquire_lock:`获取写入锁`,read_config:`读取 Codex 配置`,resolve_storage:`解析存储位置`,check_pending_restore:`检查未完成的恢复`,validate_plan:`写入前复核`,scan:`检查数据`,scan_rollout_files:`检查会话记录`,check_locked_rollout_files:`检查正在使用的会话`,create_backup:`创建备份`,rewrite_rollout_files:`更新会话记录`,repair_workspace_roots:`更新工作区位置`,update_sqlite:`更新本地聊天索引`,update_config:`更新 Codex 配置`,preflight_sqlite:`检查本地聊天索引访问`,release_lock:`释放写入锁`,clean_backups:`整理较早备份`,verify_repair:`核验修复结果`,create_restore_pre_snapshot:`创建恢复前快照`,persist_restore_journal:`准备恢复记录`,apply_restore_targets:`恢复所选数据`,commit_restore:`完成恢复`,acknowledge_restore_commit:`确认恢复结果`,rollback_restore:`撤销未完成的恢复`,prune:`删除较早备份`,start:`开启自动同步`,stop:`关闭自动同步`,"automatic-sync":`执行自动同步`,create:`新建存储配置`,update:`更新存储配置`,delete:`删除存储配置`,export:`导出诊断信息`,check:`检查更新`,download:`下载更新`,install:`安装更新`},stageStatuses:{running:`执行中`,completed:`已完成`,failed:`失败`},countLabels:{changedSessionFiles:`已更新会话记录`,inPlaceSessionFiles:`已原地更新会话记录`,rewrittenSessionFiles:`已重写会话记录`,sqliteRowsUpdated:`已更新本地索引记录`,sqliteProviderRowsUpdated:`已更新 Provider 记录`,sqliteModelRowsUpdated:`已更新模型记录`,sqliteUserEventRowsUpdated:`已更新用户操作记录`,sqliteCwdRowsUpdated:`已更新工作区记录`,skippedLockedRolloutFiles:`仍在使用的会话`,skippedChangedRolloutFiles:`操作期间发生变化的会话`,updatedWorkspaceRoots:`已更新工作区位置`,savedWorkspaceRootCount:`已保存工作区位置`,resolvedOperationCount:`已完成恢复的项目`}},profiles:{title:`存储配置`,subtitle:`为使用的不同 Codex 数据位置创建配置。目录信息只保存在此设备。`,id:`配置 ID`,name:`名称`,codexHome:`Codex 数据目录`,sqliteHome:`聊天索引目录(可选)`,create:`新建配置`,update:`保存修改`,managed:`默认`,chooseFolder:`选择目录`,keepCurrent:`不更改当前目录`,notSelected:`尚未选择目录`,inheritSqlite:`自动查找聊天索引目录`,customSqlite:`选择聊天索引目录`,revealCodex:`打开 Codex 数据目录`,revealSqlite:`打开聊天索引目录`,selectCodexRequired:`请为新配置选择 Codex 数据目录。`,defaultName:`默认位置`,defaultManaged:`默认位置由应用启动时的 Codex 设置确定,不能修改或删除。如需使用其他位置,请新建存储配置。`,saved:`存储配置已保存`,deleted:`存储配置已删除`,unavailable:`当前无法管理存储配置。`,pathManaged:{desktop:`目录位置由本应用在此设备上安全保存。`,web:`目录位置由本地 Web 应用保存。`},readOnly:`当前版本可以查看存储配置,但暂不支持编辑。`},diagnostics:{title:`高级功能`,subtitle:`仅在遇到具体问题时使用。日常同步和切换 Provider,请在概览中操作。`,scanTitle:`完整诊断 · 只读`,scanHint:`需要排查问题时再手动检查。不会修改数据或自动修复,报告不包含聊天正文和凭据。`,repairScope:`以下修复不处理会话记录序号,也不重建 Codex 历史显示索引;普通 Provider 同步不会执行这些修复。`,runtime:`应用环境`,storage:`存储位置`,provider:`Provider`,issues:`检查结果`,issuesHint:`以下是元数据差异和兼容性提示,不是聊天损坏数量,也不会自动修复。`,modelDifferenceHint:`历史会话使用不同模型可能是正常情况。只有希望统一为当前根模型时,才需要调整模型标签。`,workspaceCountHint:`工作区按待调整的设置项计数(包括缺少设置备份),不是目录数或会话数。`,encryptedHint:`加密内容是正常的会话数据,不代表损坏。这里只检测字段存在,不验证能否解密,也不会修改;跨 Provider/账号继续对话时,可能需要切回原 Provider/账号。`,safety:`运行状态`,runScan:`开始诊断`,retryScan:`重试诊断`,scanning:`正在扫描… 完整诊断可能需要几分钟。可以先切换页面,稍后回来查看结果。`,scanFailed:`诊断未能完成`,scanFailedHint:`数据未被修改。请重试诊断;若再次失败,可在操作日志中查看详情。`,previousResult:`上次成功结果 · {{time}}(不是本次扫描结果)`,expiredResult:`较早的诊断结果 · {{time}}(之后已完成一次写入;请重新运行诊断以获取当前结果)`,scanCompleted:`诊断完成 · {{time}}`,incompleteScan:`检查时部分数据发生变化或无法读取。结果仅供参考,可在会话空闲后重新检查。`,notScanned:`尚未运行诊断`,notScannedHint:`需要详细检查时再手动运行。诊断不会自动执行,也不会修改数据。`,repairTitle:`专项修复`,repairHint:`遇到下面对应的问题时再使用。日常同步无需勾选;选择一项后先预览改动,再确认执行。`,adjustmentTitle:`高级调整`,adjustmentHint:`这里是可选调整,不是故障修复。历史会话使用不同模型很正常;不需要统一名称时,请保持不选。`,previewAdjustment:`预览调整`,availableRepairs:`本次检查可处理的项目`,viewRepair:`查看修复`,viewSpecificRepair:`查看修复:{{target}}`,findings:{cwd:`{{count}} 条聊天索引的所属目录与聊天文件不一致`,userEvent:`{{count}} 条聊天索引缺少用户消息标记`,workspaceRoots:`{{count}} 项项目目录设置可整理`},repairTargetHints:{models:`仅在想把历史会话记录的模型名称统一为当前配置模型时使用。会修改聊天文件和索引中的模型名称,不会重新生成回答,也不切换 Provider。`,cwd:`聊天索引记录的项目目录与聊天文件不一致时使用。按聊天文件中记录的目录修正索引,不移动文件,也不改变你当前打开的项目。`,userEvent:`聊天中已有用户消息,但索引未标记时使用。只补全索引中的“包含用户消息”标记,不新增、删除或修改消息。`,workspaceRoots:`保存的项目目录设置有重复或格式不一致时使用。会整理设置并保留设置备份,不移动或删除项目文件夹;作用于整个存储配置,并一并修正会话所属目录。`},repairTargetRequired:`请至少选择一个修复目标。`,workspaceRootsIncludesCwd:`此项会一并修正整个存储配置中的会话所属目录,不能只选择个别会话。`,prepareRepair:`预览修复`,repairTargets:{models:`统一历史模型名称`,cwd:`修正会话所属目录`,userEvent:`补全用户消息标记`,workspaceRoots:`整理项目目录记录`},items:`{{count}} 项`,fieldsAvailable:`{{count}} 个脱敏字段`,technicalDetails:`显示技术详情`,fields:{arch:`架构`,node:`Node.js`,platform:`平台`,sqliteHomeSource:`SQLite Home 来源`,sqliteSupported:`SQLite 支持状态`,stateDbFound:`State DB 是否存在`,configured:`已配置 Provider`,current:`当前 Provider`,implicit:`隐式 Provider`,rolloutCounts:`Rollout 分布`,sqliteCounts:`SQLite 分布`,rootModelAvailable:`根模型可用`,rolloutModelFilesNeedingRepair:`模型标签与根模型不同的会话文件`,sqliteModelRowsNeedingRepair:`模型标签与根模型不同的索引记录`,cwdRowsNeedingRepair:`工作目录与会话文件不同的索引记录`,userEventRowsNeedingRepair:`缺少已有用户消息标记的索引记录`,workspaceRootsNeedingRepair:`工作区设置待调整项`,encryptedContentFiles:`包含加密内容的会话文件(仅提示)`,lockedRolloutCount:`锁定的 rollout`,operationInProgress:`执行中的操作`,pendingRecovery:`需要恢复`,pendingTransactions:`待处理事务`,projectThreadVisibilityAvailable:`项目可见性可用`,rolloutScanComplete:`Rollout 扫描完成`,storageRevision:`存储 revision`},export:`导出脱敏诊断包`,exporting:`正在导出…`,exportCreated:`脱敏诊断包已创建。`,exportCancelled:`已取消诊断导出。`,exportFailed:`诊断导出失败。`,historyIntegrity:{title:`历史记录检查`,scope:`此项有边界的只读检查仅观察 JSON 记录和数字顺序;不宣称历史显示正常,不修复记录,也不会把缺少序号视为损坏。`,displayIndexUnsupported:`本应用不知道 Codex 历史显示索引的格式,因此未验证或重建该索引。`,outcomes:{"no-findings":`未发现观察项`,findings:`发现观察项`,inconclusive:`检查未完成`,"findings-and-inconclusive":`有观察项且检查未完成`},skipped:`部分记录在扫描限制内被跳过,结果应视为未完成。`,findings:`需要人工查看的观察项`,moreFindings:`部分观察结果未列出,请在技术详情中查看。`,manualReview:`需要人工查看`,session:`会话 {{sessionId}}`,line:`第 {{line}} 行`,copySessionId:`复制会话 ID`,copiedSessionId:`会话 ID 已复制`,issueCodes:{"unsupported-format":`记录格式需要人工查看`,"invalid-utf8":`记录文本无法按 UTF-8 读取`},counts:{filesDiscovered:`发现的文件`,filesScanned:`已扫描文件`,recordsRead:`已读取记录`,sessionsWithId:`带会话 ID 的记录`,jsonCorruptRecords:`JSON 无效的记录`,oversizedRecords:`超过大小限制的记录`,duplicateOrdinals:`重复的数字顺序`,outOfOrderOrdinals:`顺序错位的数字记录`,changedFiles:`扫描中发生变化的文件`,truncatedFiles:`达到扫描限制后停止的文件`}}},settings:{title:`设置`,subtitle:{desktop:`管理显示、自动同步与应用更新。偏好只保存在此设备。`,web:`管理显示与浏览器设置。偏好只保存在此浏览器。`},language:`语言`,languageHint:`修改后立即生效。`,theme:`主题`,system:`跟随系统`,light:`浅色`,dark:`深色`,watch:`自动同步`,watchHint:`当前存储位置的文件变化时,自动同步 Provider 信息。同一 Codex Home 共用一个监听,关闭时一起停止。监听选项及执行、停止日志归首次启用的配置所有(日志中选“全部配置”可查看)。`,watchStart:`开启自动同步`,watchStop:`关闭自动同步`,watchRecoveryBlocked:`请先完成数据恢复,再开启自动同步。`,watchStatuses:{running:`已开启`,stopped:`已关闭`,starting:`正在开启`,stopping:`正在关闭`,failed:`需要处理`},update:`更新`,updateCurrentVersion:`当前版本:{{version}}`,updateManualHint:`每天首次启动检查一次,仅发现新版时弹窗。便携版或本地构建会打开 GitHub 下载页,请下载后手动替换;不会自动安装或退出。`,updateAutomaticHint:`每天首次启动检查一次,有新版时弹窗提示。按需下载,再确认重启安装。更新不替换你的 Codex 数据。`,updateOpenDownload:`打开官方下载页`,updateRequestFailed:`更新请求失败,请刷新状态或重试;当前软件仍可正常使用。`,updateStatus:{disabled:`应用内更新不可用`,idle:`尚未检查更新`,checking:`正在检查`,available:`发现新版本`,downloading:`正在下载`,downloaded:`可安装`,"not-available":`已是最新版本`,error:`更新失败`,installing:`正在重启安装`},updateReason:{"not-packaged":`当前安装方式不支持应用内更新。`,"not-authorized":`此版本暂未启用应用内更新。`,"not-configured":`此版本暂未启用应用内更新。`,"unsupported-target":`当前平台不支持应用内更新。`,"check-failed":`检查更新失败,请稍后重试。`,"download-failed":`下载更新失败,请稍后重试。`,"install-failed":`无法启动安装程序,当前版本仍保持可用。`},updateBlocked:{"write-in-progress":`请等待当前操作完成后再安装更新。`,"watch-active":`请先关闭自动同步,再安装更新。`,"pending-recovery":`请先完成数据恢复,再安装更新。`,"recovery-unverified":`无法确认所有存储配置均可安全更新,安装已暂停。`},updateVersion:`版本 {{version}}`,updateProgress:`已下载 {{percent}}%`,updateCheck:`检查更新`,updateDownload:`下载更新`,updateInstall:`重启并安装`,forget:`忘记此浏览器`,englishFallback:`缺少翻译时将显示英文。`,forgetHint:`将从本地应用中移除此浏览器的连接信息。`},plan:{title:`确认操作`,switchTitle:`确认切换`,confirmSwitch:`确认切换`,titles:{sync:`确认同步`,switch:`确认切换`,repair:`确认修复`,restore:`确认恢复`},confirmActions:{sync:`确认同步`,switch:`确认切换`,repair:`确认修复`,restore:`确认恢复`},operations:{sync:`同步 Provider 信息`,switch:`切换 Provider`,repair:`修复聊天信息`,restore:`恢复备份`,operation:`操作`},modelModes:{"provider-default":`使用 config.toml 中该 Provider 的模型`,"keep-root-model":`保留当前根模型`,explicit:`手动指定根模型`},historyModelsUnaffected:`将同步历史记录的 Provider,但不会修改历史会话实际记录的模型。`,fields:{modelMode:`模型处理方式`,rootModelChange:`根模型变化`,repairTargets:`修复目标`,restoreConfig:`恢复 Codex 配置`,restoreDatabase:`恢复本地聊天索引`,restoreSessions:`恢复会话记录文件`,relocation:`恢复到其他存储配置`,rolloutFiles:`需要更新的会话记录`,sqliteRows:`需要更新的本地索引记录`,affectedSessions:`受影响会话(去重)`,sqliteFields:`索引字段改动(合计)`,sqliteModels:`模型名称字段`,sqliteCwd:`会话所属目录字段`,sqliteUserEvent:`用户消息标记`,workspaceSettings:`工作区设置改动项`,workspaceRoots:`需要更新的工作区位置`,stateDbFiles:`需要恢复的本地索引文件`,configFiles:`需要恢复的 Codex 配置文件`,lockedRollouts:`本次将跳过的会话`},stages:{prepare_config:`读取 Codex 配置`,prepare_storage:`解析存储位置`,prepare_rollouts:`准备会话记录`,prepare_status:`读取当前状态`,prepare_revisions:`记录受保护版本`,prepare_usage:`检查会话使用情况`,acquire_lock:`获取写入锁`,read_config:`读取 Codex 配置`,resolve_storage:`解析存储位置`,check_pending_restore:`检查未完成的恢复`,validate_plan:`写入前复核`,scan_rollout_files:`检查聊天记录`,check_locked_rollout_files:`检查正在使用的聊天`,preflight_sqlite:`检查本地聊天索引访问`,create_backup:`创建备份`,rewrite_rollout_files:`更新聊天记录`,update_sqlite:`更新本地聊天索引`,update_config:`更新 Codex 设置`,release_lock:`释放写入锁`,clean_backups:`整理较早备份`,verify_repair:`核验修复结果`,create_restore_pre_snapshot:`创建恢复点`,persist_restore_journal:`准备恢复`,apply_restore_targets:`恢复所选数据`,commit_restore:`完成恢复`,acknowledge_restore_commit:`确认恢复结果`,rollback_restore:`撤销未完成的恢复`},statuses:{start:`正在开始`,progress:`执行中`,complete:`已完成`},target:`本次选择`,impact:`预计改动`,expires:`请在此时间前确认`,items:`{{count}} 项`,backupExpected:`写入前会先创建备份。`,exactApply:`执行前会再次确认数据没有变化;如果数据已变化,需要重新预览。`,workspaceChanges:{savedRoots:`整理已保存的项目目录`,projectOrder:`整理项目排序`,activeRoots:`统一当前工作区目录格式`,labels:`统一项目目录标签`,openTargets:`统一项目打开方式设置`,settingsBackup:`补建缺失的设置备份`},repairPreview:{title:`受影响会话预览`,effectsTitle:`将修改什么`,unchanged:`聊天正文、消息顺序和时间保持不变;不会重建 Codex 历史显示索引。`,hint:`可选择整个存储配置,或仅选择列表中的会话。修改选择后会生成新的预览,不能继续确认旧预览。`,all:`整个存储配置`,selected:`已选会话`,selectSession:`选择会话 {{sessionId}}`,none:`本次预览未包含受影响会话。`,total:`共找到 {{count}} 个受影响会话`,truncated:`仅显示前 100 个。`,regenerating:`正在更新预览,之前的确认不能执行。`,selectionChanged:`选择已变更,请先更新预览,再确认执行。`,update:`更新修复预览`,refineFailed:`之前的预览已撤销,不能确认执行。请先处理错误,再重新生成预览。`,workspaceGlobal:`工作区设置属于全局项。该修复会作用于整个存储配置,不能仅限所选会话。`,changes:{models:`模型标签`,cwd:`工作目录`,userEvent:`用户消息标记`},markers:{different:`不一致`,"rollout-cwd":`聊天文件中记录的目录`,false:`未记录`,true:`已记录`}},writeBlocked:`当前有其他操作正在执行,或存在待恢复数据,暂时不能继续。`,technicalDetails:`操作详情`,progress:`操作进度`,starting:`正在开始…`,cancelOperation:`取消操作`,cancelling:`正在取消…`,cancelPending:`取消将在下一个安全点生效。`},operationResult:{title:`操作结果`,operationId:`操作 ID`,backupId:`受管备份 ID`,backupCreated:`已创建备份,可在“备份与恢复”中查看。`,openBackupRestore:`打开恢复预览`,changeCountersHint:`这些是已修改的记录或设置数量,不代表唯一会话数量。`,skippedRollouts:`仍在使用的会话`,skippedChangedRollouts:`操作期间发生变化的会话`,skippedCount:`有 {{count}} 条会话记录暂未更新。`,retryAfterSession:`请关闭正在使用的 Codex 会话,然后再次同步。`,retryFreshPlan:`请重新预览本次操作后再试。`,reviewOperation:`返回操作页面`,verification:{title:`修复后的核验`,status:{verified:`写入后已核验所选修复目标。`,remaining:`仍有部分所选元数据需要处理,请先查看剩余数量,再预览新的修复。`,unavailable:`没有可用的写入后核验结果,系统没有启动其他修复。`},remainingRolloutFiles:`剩余会话文件差异`,remainingSqliteRows:`剩余本地索引差异`,remainingWorkspaceRoots:`剩余工作区设置`,skippedSessions:`跳过的会话记录`},partialReasons:{"locked-session":`有聊天仍在使用`,"rollout-changed":`操作期间聊天记录发生变化`,"mutation-failed":`部分更改保存后操作中断`},resolveBeforeClose:`请先完成待处理的恢复,再关闭此结果。`,fields:{inPlaceSessionFiles:`原地更新的 rollout`,rewrittenSessionFiles:`完整重写的 rollout`,targetProvider:`目标 Provider`,targetModel:`目标模型`,modelSource:`模型来源`,partialReason:`部分完成原因`,failedStage:`失败阶段`,failureCode:`失败代码`,retryRecommended:`建议重试`,restoreOperationId:`恢复操作 ID`,preRestoreSnapshotId:`恢复前快照 ID`,restoreJournalState:`恢复 journal 状态`,backupDurationMs:`备份耗时(毫秒)`,changedSessionFiles:`已更新聊天记录`,sqliteRowsUpdated:`已更新本地索引记录`,sqliteProviderRowsUpdated:`已更新 Provider 记录`,sqliteModelRowsUpdated:`已更新模型记录`,sqliteUserEventRowsUpdated:`已更新用户操作记录`,sqliteCwdRowsUpdated:`已更新工作区记录`,updatedWorkspaceRoots:`已更新工作区位置`,savedWorkspaceRootCount:`已保存工作区位置`,repairTargets:`修复目标`,restoreVersion:`恢复格式版本`,resolvedOperationCount:`已解决操作数`,commitAcknowledgementRecovered:`已恢复提交确认`},completed:{title:`已完成`,description:`操作已完成,相关数据已经保存。`},partial:{title:`部分完成`,description:`部分更改尚未完成。请按照下方提示重试,或从备份恢复。`},failedRolledBack:{title:`失败并已回滚`,description:`操作失败,且先前状态已成功恢复。`},recoveryRequired:{title:`需要先恢复数据`,description:`上一次恢复没有完成。请先完成恢复,再执行其他修改。`},cancelled:{title:`已取消`,description:`操作已经取消,后续步骤没有继续执行。`},stale:{title:`需要重新确认`,description:`操作开始前数据已经变化,请重新预览后再试。`}},validation:{required:`此项必填。`,keep:`请输入 1 到 1000 的整数。`,provider:`请输入有效的 Provider ID。`,model:`请输入要使用的模型名称。`,restore:`至少选择一种恢复内容。`,profileId:`只能使用字母、数字、点、下划线或连字符。`,path:`请输入完整的目录路径。`},errors:{fallback:`本次操作未能完成。请重试;如果问题持续,请查看操作日志或导出诊断信息。`,INVALID_INPUT:`请检查填写的内容后重试。`,providerNotConfigured:`当前 Provider 尚未在 config.toml 中配置。请先用 Provider 管理工具完成配置或切换,再重新同步。本次未修改数据。`,PROFILE_CHANGED:`当前存储配置已经变化,请检查后重试。`,STORAGE_CHANGED:`存储位置已经变化,请重新预览后再试。`,PLAN_STALE:`数据已经发生变化,请重新预览后再执行。`,PLAN_EXPIRED:`本次预览已经过期,请重新预览。`,STALE_STATE:`数据已经发生变化,请重新预览后再执行。`,CODEX_HOME_NOT_FOUND:`找不到 Codex 数据目录,请检查当前存储配置。`,STATE_DB_NOT_FOUND:`找不到本地聊天索引,请检查当前存储配置。`,SQLITE_UNSUPPORTED_PATH:`当前平台无法使用所选的聊天索引位置。`,SQLITE_BUSY:`本地聊天索引正在被占用,请关闭 Codex 后重试。`,SQLITE_UNREADABLE:`无法读取本地聊天索引,请运行诊断或从备份恢复。`,ROLLOUT_LOCKED:`部分会话正在使用中,请关闭相关 Codex 会话后重试。`,ROLLOUT_CHANGED:`部分会话在操作期间发生变化,请重新检查后重试。`,PENDING_TRANSACTION:`上一次恢复需要先完成,才能继续操作。`,BACKUP_FAILED:`无法创建备份,因此没有修改任何数据。`,SYNC_FAILED_ROLLED_BACK:`同步未能完成,原有数据已经恢复。`,RECOVERY_REQUIRED:`上一次恢复没有完成,请先完成恢复。`,RESTORE_VALIDATION_FAILED:`所选备份无法恢复到当前存储位置。`,PERMISSION_DENIED:`应用没有访问所选目录的权限。`,OPERATION_BUSY:`另一项操作正在执行,请等待完成后重试。`,OPERATION_CANCELLED:`操作已取消。`,CORE_RUNTIME_CRASHED:`后台服务意外停止,应用会在可行时自动重新启动。`,PROTOCOL_VERSION_MISMATCH:`应用组件版本不兼容,请重新安装最新版本。`,LOCK_UNVERIFIABLE:`无法确认当前存储位置是否可用,请关闭 Codex 后重试。`,INTERNAL_ERROR:`应用内部出现错误,请重试;如果问题持续,请导出诊断信息。`},warnings:{backupInventory:`无法刷新备份列表,但现有备份没有被修改。`,backupCleanup:`操作已经完成,但未能自动删除较早的备份。`,encryptedHistory:`部分加密会话可能需要使用原 Provider 或原账号才能继续。`,lockedSessions:`部分会话正在使用中,可能暂时无法更新。请关闭后再次同步。`,missingDefaultModel:`该 Provider 没有配置模型,将继续保留当前根模型。`,projectVisibility:`无法检查项目会话可见性,但修改前仍会创建备份。`,relocationConfig:`聊天索引将恢复到其他存储配置,但不会恢复 Codex 配置。`,restoreSkipped:`所选备份不包含其中一项恢复内容,该项将被跳过。`,partial:`本次操作只完成了部分修改,请重试或从备份恢复。`,additional:`操作带有额外提醒,请在操作日志中查看详情。`}}}};async function Lj(e){let t=rn.createInstance();return await t.init({resources:Ij,lng:e,fallbackLng:`en`,interpolation:{escapeValue:!1},returnNull:!1}),t}function Rj(e){let t=e.preferences.getLocale()??e.initialLocale,n=e.preferences.getTheme()??e.initialTheme,[r,i]=(0,m.useState)(null),[a]=(0,m.useState)(()=>new We({defaultOptions:{queries:{retry:!1,staleTime:1/0,refetchOnWindowFocus:!1,refetchOnReconnect:!1},mutations:{retry:!1}}}));return(0,m.useEffect)(()=>{let e=!0;return Lj(t).then(t=>{e&&i(t)}),()=>{e=!1,a.clear()}},[e.initialTheme,e.preferences,a,t]),(0,m.useLayoutEffect)(()=>{document.documentElement.dataset.theme=n},[n]),r?(0,h.jsx)(On,{i18n:r,children:(0,h.jsx)(Fj,{locale:()=>r.language,children:(0,h.jsx)(v,{client:a,children:(0,h.jsx)(bb.Provider,{value:e.host.copyText??yb,children:(0,h.jsx)(ob,{children:(0,h.jsx)(Pj,{props:e})})})})})}):(0,h.jsx)(`div`,{className:`grid min-h-screen place-items-center bg-[var(--surface)] text-[var(--text)]`,children:t===`zh-CN`?`正在加载…`:`Loading…`})}function zj(e,t){let n=(e,n)=>{if(e.length>512||!/^[a-f0-9]{64}$/.test(n))throw Error(`Invalid project preference.`);return`${t}.history.project-alias.${JSON.stringify([e,n])}`},r=e=>typeof e==`string`&&e.length<=160&&!/[\x00-\x1f\x7f]/.test(e);return{getHistoryProjectAlias(t,i){try{let a=e.getItem(n(t,i));return r(a)&&a.trim()?a.trim():null}catch{return null}},setHistoryProjectAlias(t,i,a){if(!r(a))throw Error(`Invalid project display name.`);let o=n(t,i);a.trim()?e.setItem(o,a.trim()):e.removeItem(o)}}}var Bj=o((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0>>1,a=e[r];if(0>>1;ri(c,n))li(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(li(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m){if(n(c)!==null)m=!0,S||(S=!0,O());else{var t=n(l);t!==null&&A(x,t.startTime-e)}}}var S=!1,C=-1,w=5,T=-1;function E(){return g?!0:!(e.unstable_now()-Tt&&E());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&A(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?O():S=!1}}}var O;if(typeof y==`function`)O=function(){y(D)};else if(typeof MessageChannel<`u`){var ee=new MessageChannel,k=ee.port2;ee.port1.onmessage=D,O=function(){k.postMessage(null)}}else O=function(){_(D,0)};function A(t,n){C=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(C),C=-1):h=!0,A(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,O()))),r},e.unstable_shouldYield=E,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),Vj=o(((e,t)=>{t.exports=Bj()})),Hj=o((e=>{var t=Vj(),n=p(),r=nm();function i(e){var t=`https://react.dev/errors/`+e;if(1ne||(e.current=te[ne],te[ne]=null,ne--)}function I(e,t){ne++,te[ne]=e.current,e.current=t}var L=re(null),ae=re(null),oe=re(null),se=re(null);function ce(e,t){switch(I(oe,t),I(ae,e),I(L,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?Gd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Gd(t),e=Kd(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}ie(L),I(L,e)}function le(){ie(L),ie(ae),ie(oe)}function ue(e){e.memoizedState!==null&&I(se,e);var t=L.current,n=Kd(t,e.type);t!==n&&(I(ae,e),I(L,n))}function de(e){ae.current===e&&(ie(L),ie(ae)),se.current===e&&(ie(se),np._currentValue=F)}var fe,pe;function me(e){if(fe===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);fe=t&&t[1]||``,pe=-1)`:-1i||c[r]!==l[i]){var u=` -`+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(``)&&(u=u.replace(``,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{he=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?me(n):``}function _e(e,t){switch(e.tag){case 26:case 27:case 5:return me(e.type);case 16:return me(`Lazy`);case 13:return e.child!==t&&t!==null?me(`Suspense Fallback`):me(`Suspense`);case 19:return me(`SuspenseList`);case 0:case 15:return ge(e.type,!1);case 11:return ge(e.type.render,!1);case 1:return ge(e.type,!0);case 31:return me(`Activity`);default:return``}}function ve(e){try{var t=``,n=null;do t+=_e(e,n),n=e,e=e.return;while(e);return t}catch(e){return` -Error generating stack: `+e.message+` -`+e.stack}}var ye=Object.prototype.hasOwnProperty,be=t.unstable_scheduleCallback,xe=t.unstable_cancelCallback,Se=t.unstable_shouldYield,R=t.unstable_requestPaint,Ce=t.unstable_now,we=t.unstable_getCurrentPriorityLevel,Te=t.unstable_ImmediatePriority,Ee=t.unstable_UserBlockingPriority,De=t.unstable_NormalPriority,Oe=t.unstable_LowPriority,ke=t.unstable_IdlePriority,Ae=t.log,je=t.unstable_setDisableYieldValue,Me=null,Ne=null;function Pe(e){if(typeof Ae==`function`&&je(e),Ne&&typeof Ne.setStrictMode==`function`)try{Ne.setStrictMode(Me,e)}catch{}}var Fe=Math.clz32?Math.clz32:Re,Ie=Math.log,Le=Math.LN2;function Re(e){return e>>>=0,e===0?32:31-(Ie(e)/Le|0)|0}var ze=256,Be=262144,Ve=4194304;function He(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function Ue(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=He(n))):i=He(o):i=He(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=He(n))):i=He(o)):i=He(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function We(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function Ge(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Ke(){var e=Ve;return Ve<<=1,!(Ve&62914560)&&(Ve=4194304),e}function qe(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Je(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function Ye(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0`u`||window.document===void 0||window.document.createElement===void 0),sn=!1;if(on)try{var cn={};Object.defineProperty(cn,"passive",{get:function(){sn=!0}}),window.addEventListener(`test`,cn,cn),window.removeEventListener(`test`,cn,cn)}catch{sn=!1}var ln=null,un=null,dn=null;function fn(){if(dn)return dn;var e,t=un,n=t.length,r,i=`value`in ln?ln.value:ln.textContent,a=i.length;for(e=0;e=Wn),qn=` `,Jn=!1;function Yn(e,t){switch(e){case`keyup`:return Hn.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function Xn(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var Zn=!1;function Qn(e,t){switch(e){case`compositionend`:return Xn(t);case`keypress`:return t.which===32?(Jn=!0,qn):null;case`textInput`:return e=t.data,e===qn&&Jn?null:e;default:return null}}function $n(e,t){if(Zn)return e===`compositionend`||!Un&&Yn(e,t)?(e=fn(),dn=un=ln=null,Zn=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=vr(n)}}function br(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?br(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function xr(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Nt(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=Nt(e.document)}return t}function Sr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}var Cr=on&&`documentMode`in document&&11>=document.documentMode,wr=null,Tr=null,Er=null,Dr=!1;function Or(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Dr||wr==null||wr!==Nt(r)||(r=wr,`selectionStart`in r&&Sr(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Er&&_r(Er,r)||(Er=r,r=kd(Tr,`onSelect`),0>=o,i-=o,bi=1<<32-Fe(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),a=o(_,a,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),U&&Si(i,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(a,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(a,h),s=o(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(a,h),U&&Si(a,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(a,v.value,l),v!==null&&(s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return U&&Si(a,g),u}for(h=r(h);!v.done;g++,v=c.next())v=m(h,a,g,v.value,l),v!==null&&(e&&v.alternate!==null&&h.delete(v.key===null?g:v.key),s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(a,e)}),U&&Si(a,g),u}function b(e,r,o,c){if(typeof o==`object`&&o&&o.type===_&&o.key===null&&(o=o.props.children),typeof o==`object`&&o){switch(o.$$typeof){case h:a:{for(var l=o.key;r!==null;){if(r.key===l){if(l=o.type,l===_){if(r.tag===7){n(e,r.sibling),c=a(r,o.props.children),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===E&&xa(l)===r.type){n(e,r.sibling),c=a(r,o.props),Oa(c,o),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}o.type===_?(c=si(o.props.children,e.mode,c,o.key),c.return=e,e=c):(c=oi(o.type,o.key,o.props,null,e.mode,c),Oa(c,o),c.return=e,e=c)}return s(e);case g:a:{for(l=o.key;r!==null;){if(r.key===l){if(r.tag===4&&r.stateNode.containerInfo===o.containerInfo&&r.stateNode.implementation===o.implementation){n(e,r.sibling),c=a(r,o.children||[]),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}c=ui(o,e.mode,c),c.return=e,e=c}return s(e);case E:return o=xa(o),b(e,r,o,c)}if(M(o))return v(e,r,o,c);if(k(o)){if(l=k(o),typeof l!=`function`)throw Error(i(150));return o=l.call(o),y(e,r,o,c)}if(typeof o.then==`function`)return b(e,r,Da(o),c);if(o.$$typeof===x)return b(e,r,Xi(e,o),c);ka(e,o)}return typeof o==`string`&&o!==``||typeof o==`number`||typeof o==`bigint`?(o=``+o,r!==null&&r.tag===6?(n(e,r.sibling),c=a(r,o),c.return=e,e=c):(n(e,r),c=ci(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{Ea=0;var i=b(e,t,n,r);return Ta=null,i}catch(t){if(t===ha||t===_a)throw t;var a=ni(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var ja=Aa(!0),Ma=Aa(!1),Na=!1;function Pa(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Fa(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function Ia(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function La(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Fl&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=$r(e),Qr(e,null,n),t}return Yr(e,r,t,n),$r(e)}function Ra(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194048)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Ze(e,n)}}function za(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var Ba=!1;function Va(){if(Ba){var e=W;if(e!==null)throw e}}function Ha(e,t,n,r){Ba=!1;var i=e.updateQueue;Na=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var p=s.lane&-536870913,m=p!==s.lane;if(m?(Rl&p)===p:(r&p)===p){p!==0&&p===oa&&(Ba=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var h=e,g=s;p=t;var _=n;switch(g.tag){case 1:if(h=g.payload,typeof h==`function`){d=h.call(_,d,p);break a}d=h;break a;case 3:h.flags=h.flags&-65537|128;case 0:if(h=g.payload,p=typeof h==`function`?h.call(_,d,p):h,p==null)break a;d=f({},d,p);break a;case 2:Na=!0}}p=s.callback,p!==null&&(e.flags|=64,m&&(e.flags|=8192),m=i.callbacks,m===null?i.callbacks=[p]:m.push(p))}else m={lane:p,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=m,c=d):u=u.next=m,o|=p;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;m=s,s=m.next,m.next=null,i.lastBaseUpdate=m,i.shared.pending=null}}while(1);u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,a===null&&(i.shared.lanes=0),Kl|=o,e.lanes=o,e.memoizedState=d}}function Ua(e,t){if(typeof e!=`function`)throw Error(i(191,e));e.call(t)}function Wa(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=N.T,s={};N.T=s,Os(e,!1,t,n);try{var c=i(),l=N.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?Ds(e,t,la(c,r),mu(e)):Ds(e,t,r,mu(e))}catch(n){Ds(e,t,{then:function(){},status:`rejected`,reason:n},mu())}finally{P.p=a,o!==null&&s.types!==null&&(o.types=s.types),N.T=o}}function _s(){}function vs(e,t,n,r){if(e.tag!==5)throw Error(i(476));var a=ys(e).queue;gs(e,a,t,F,n===null?_s:function(){return bs(e),n(r)})}function ys(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:F,baseState:F,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:jo,lastRenderedState:F},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:jo,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function bs(e){var t=ys(e);t.next===null&&(t=e.alternate.memoizedState),Ds(e,t.next.queue,{},mu())}function xs(){return Yi(np)}function Ss(){return Eo().memoizedState}function Cs(){return Eo().memoizedState}function ws(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=mu();e=Ia(n);var r=La(t,e,n);r!==null&&(gu(r,t,n),Ra(r,t,n)),t={cache:na()},e.payload=t;return}t=t.return}}function Ts(e,t,n){var r=mu();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},ks(e)?As(t,n):(n=Xr(e,t,n,r),n!==null&&(gu(n,e,r),js(n,t,r)))}function Es(e,t,n){Ds(e,t,n,mu())}function Ds(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(ks(e))As(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,gr(s,o))return Yr(e,t,i,0),Il===null&&Jr(),!1}catch{}if(n=Xr(e,t,i,r),n!==null)return gu(n,e,r),js(n,t,r),!0}return!1}function Os(e,t,n,r){if(r={lane:2,revertLane:pd(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},ks(e)){if(t)throw Error(i(479))}else t=Xr(e,n,r,2),t!==null&&gu(t,e,2)}function ks(e){var t=e.alternate;return e===G||t!==null&&t===G}function As(e,t){lo=co=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function js(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Ze(e,n)}}var Ms={readContext:Yi,use:ko,useCallback:go,useContext:go,useEffect:go,useImperativeHandle:go,useLayoutEffect:go,useInsertionEffect:go,useMemo:go,useReducer:go,useRef:go,useState:go,useDebugValue:go,useDeferredValue:go,useTransition:go,useSyncExternalStore:go,useId:go,useHostTransitionStatus:go,useFormState:go,useActionState:go,useOptimistic:go,useMemoCache:go,useCacheRefresh:go};Ms.useEffectEvent=go;var Ns={readContext:Yi,use:ko,useCallback:function(e,t){return To().memoizedState=[e,t===void 0?null:t],e},useContext:Yi,useEffect:is,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),ns(4194308,4,ls.bind(null,t,e),n)},useLayoutEffect:function(e,t){return ns(4194308,4,e,t)},useInsertionEffect:function(e,t){ns(4,2,e,t)},useMemo:function(e,t){var n=To();t=t===void 0?null:t;var r=e();if(uo){Pe(!0);try{e()}finally{Pe(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=To();if(n!==void 0){var i=n(t);if(uo){Pe(!0);try{n(t)}finally{Pe(!1)}}}else i=t;return r.memoizedState=r.baseState=i,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:i},r.queue=e,e=e.dispatch=Ts.bind(null,G,e),[r.memoizedState,e]},useRef:function(e){var t=To();return e={current:e},t.memoizedState=e},useState:function(e){e=Bo(e);var t=e.queue,n=Es.bind(null,G,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:ds,useDeferredValue:function(e,t){return ms(To(),e,t)},useTransition:function(){var e=Bo(!1);return e=gs.bind(null,G,e.queue,!0,!1),To().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=G,a=To();if(U){if(n===void 0)throw Error(i(407));n=n()}else{if(n=t(),Il===null)throw Error(i(349));Rl&127||Fo(r,t,n)}a.memoizedState=n;var o={value:n,getSnapshot:t};return a.queue=o,is(Lo.bind(null,r,o,e),[e]),r.flags|=2048,es(9,{destroy:void 0},Io.bind(null,r,o,n,t),null),n},useId:function(){var e=To(),t=Il.identifierPrefix;if(U){var n=xi,r=bi;n=(r&~(1<<32-Fe(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=fo++,0<\/script>`,o=o.removeChild(o.firstChild);break;case`select`:o=typeof r.is==`string`?s.createElement(`select`,{is:r.is}):s.createElement(`select`),r.multiple?o.multiple=!0:r.size&&(o.size=r.size);break;default:o=typeof r.is==`string`?s.createElement(a,{is:r.is}):s.createElement(a)}}o[it]=t,o[at]=r;a:for(s=t.child;s!==null;){if(s.tag===5||s.tag===6)o.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===t)break a;for(;s.sibling===null;){if(s.return===null||s.return===t)break a;s=s.return}s.sibling.return=s.return,s=s.sibling}t.stateNode=o;a:switch(Rd(o,a,r),a){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&Dc(t)}}return Mc(t),Oc(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&Dc(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(i(166));if(e=oe.current,Fi(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,a=Di,a!==null)switch(a.tag){case 27:case 5:r=a.memoizedProps}e[it]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||Fd(e.nodeValue,n)),e||Mi(t,!0)}else e=Wd(e).createTextNode(r),e[it]=t,t.stateNode=e}return Mc(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=Fi(t),n!==null){if(e===null){if(!r)throw Error(i(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(i(557));e[it]=t}else Ii(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Mc(t),e=!1}else n=Li(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(no(t),t):(no(t),null);if(t.flags&128)throw Error(i(558))}return Mc(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(a=Fi(t),r!==null&&r.dehydrated!==null){if(e===null){if(!a)throw Error(i(318));if(a=t.memoizedState,a=a===null?null:a.dehydrated,!a)throw Error(i(317));a[it]=t}else Ii(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Mc(t),a=!1}else a=Li(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),a=!0;if(!a)return t.flags&256?(no(t),t):(no(t),null)}return no(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,a=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(a=r.alternate.memoizedState.cachePool.pool),o=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(o=r.memoizedState.cachePool.pool),o!==a&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),Ac(t,t.updateQueue),Mc(t),null);case 4:return le(),e===null&&Td(t.stateNode.containerInfo),Mc(t),null;case 10:return Ui(t.type),Mc(t),null;case 19:if(ie(ro),r=t.memoizedState,r===null)return Mc(t),null;if(a=!!(t.flags&128),o=r.rendering,o===null){if(a)jc(r,!1);else{if(Gl!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=io(e),o!==null){for(t.flags|=128,jc(r,!1),e=o.updateQueue,t.updateQueue=e,Ac(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)ai(n,e),n=n.sibling;return I(ro,ro.current&1|2),U&&Si(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Ce()>nu&&(t.flags|=128,a=!0,jc(r,!1),t.lanes=4194304)}}else{if(!a){if(e=io(o),e!==null){if(t.flags|=128,a=!0,e=e.updateQueue,t.updateQueue=e,Ac(t,e),jc(r,!0),r.tail===null&&r.tailMode===`hidden`&&!o.alternate&&!U)return Mc(t),null}else 2*Ce()-r.renderingStartTime>nu&&n!==536870912&&(t.flags|=128,a=!0,jc(r,!1),t.lanes=4194304)}r.isBackwards?(o.sibling=t.child,t.child=o):(e=r.last,e===null?t.child=o:e.sibling=o,r.last=o)}return r.tail===null?(Mc(t),null):(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=Ce(),e.sibling=null,n=ro.current,I(ro,a?n&1|2:n&1),U&&Si(t,r.treeForkCount),e);case 22:case 23:return no(t),Ya(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(Mc(t),t.subtreeFlags&6&&(t.flags|=8192)):Mc(t),n=t.updateQueue,n!==null&&Ac(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),r=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),e!==null&&ie(da),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),Ui(ta),Mc(t),null;case 25:return null;case 30:return null}throw Error(i(156,t.tag))}function Pc(e,t){switch(Ti(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ui(ta),le(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return de(t),null;case 31:if(t.memoizedState!==null){if(no(t),t.alternate===null)throw Error(i(340));Ii()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(no(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(i(340));Ii()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ie(ro),null;case 4:return le(),null;case 10:return Ui(t.type),null;case 22:case 23:return no(t),Ya(),e!==null&&ie(da),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Ui(ta),null;case 25:return null;default:return null}}function Fc(e,t){switch(Ti(t),t.tag){case 3:Ui(ta),le();break;case 26:case 27:case 5:de(t);break;case 4:le();break;case 31:t.memoizedState!==null&&no(t);break;case 13:no(t);break;case 19:ie(ro);break;case 10:Ui(t.type);break;case 22:case 23:no(t),Ya(),e!==null&&ie(da);break;case 24:Ui(ta)}}function Ic(e,t){try{var n=t.updateQueue,r=n===null?null:n.lastEffect;if(r!==null){var i=r.next;n=i;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==i)}}catch(e){Ku(t,t.return,e)}}function Lc(e,t,n){try{var r=t.updateQueue,i=r===null?null:r.lastEffect;if(i!==null){var a=i.next;r=a;do{if((r.tag&e)===e){var o=r.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,i=t;var c=n,l=s;try{l()}catch(e){Ku(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){Ku(t,t.return,e)}}function Rc(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{Wa(t,n)}catch(t){Ku(e,e.return,t)}}}function zc(e,t,n){n.props=Bs(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){Ku(e,t,n)}}function Bc(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;case 30:r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){Ku(e,t,n)}}function Vc(e,t){var n=e.ref,r=e.refCleanup;if(n!==null){if(typeof r==`function`)try{r()}catch(n){Ku(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n==`function`)try{n(null)}catch(n){Ku(e,t,n)}else n.current=null}}function Hc(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{a:switch(t){case`button`:case`input`:case`select`:case`textarea`:n.autoFocus&&r.focus();break a;case`img`:n.src?r.src=n.src:n.srcSet&&(r.srcset=n.srcSet)}}catch(t){Ku(e,e.return,t)}}function Uc(e,t,n){try{var r=e.stateNode;zd(r,e.type,n,t),r[at]=t}catch(t){Ku(e,e.return,t)}}function Wc(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&tf(e.type)||e.tag===4}function Gc(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||Wc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&tf(e.type)||e.flags&2||e.child===null||e.tag===4)continue a;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Kc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?(n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n).insertBefore(e,t):(t=n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n,t.appendChild(e),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Xt));else if(r!==4&&(r===27&&tf(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for(Kc(e,t,n),e=e.sibling;e!==null;)Kc(e,t,n),e=e.sibling}function qc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(r===27&&tf(e.type)&&(n=e.stateNode),e=e.child,e!==null))for(qc(e,t,n),e=e.sibling;e!==null;)qc(e,t,n),e=e.sibling}function Jc(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,i=t.attributes;i.length;)t.removeAttributeNode(i[0]);Rd(t,r,n),t[it]=e,t[at]=n}catch(t){Ku(e,e.return,t)}}var Yc=!1,Xc=!1,Zc=!1,Qc=typeof WeakSet==`function`?WeakSet:Set,$c=null;function el(e,t){if(e=e.containerInfo,Hd=dp,e=xr(e),Sr(e)){if(`selectionStart`in e)var n={start:e.selectionStart,end:e.selectionEnd};else a:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break a}var s=0,c=-1,l=-1,u=0,d=0,f=e,p=null;b:for(;;){for(var m;f!==n||a!==0&&f.nodeType!==3||(c=s+a),f!==o||r!==0&&f.nodeType!==3||(l=s+r),f.nodeType===3&&(s+=f.nodeValue.length),(m=f.firstChild)!==null;)p=f,f=m;for(;;){if(f===e)break b;if(p===n&&++u===a&&(c=s),p===o&&++d===r&&(l=s),(m=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=m}n=c===-1||l===-1?null:{start:c,end:l}}else n=null}n||={start:0,end:0}}else n=null;for(Ud={focusedElem:e,selectionRange:n},dp=!1,$c=t;$c!==null;)if(t=$c,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,$c=e;else for(;$c!==null;){switch(t=$c,o=t.alternate,e=t.flags,t.tag){case 0:if(e&4&&(e=t.updateQueue,e=e===null?null:e.events,e!==null))for(n=0;n title`))),Rd(o,r,n),o[it]=e,gt(o),r=o;break a;case`link`:var s=Gf(`link`,`href`,a).get(r+(n.href||``));if(s){for(var c=0;cg&&(o=g,g=h,h=o);var _=yr(s,h),v=yr(s,g);if(_&&v&&(p.rangeCount!==1||p.anchorNode!==_.node||p.anchorOffset!==_.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var y=d.createRange();y.setStart(_.node,_.offset),p.removeAllRanges(),h>g?(p.addRange(y),p.extend(v.node,v.offset)):(y.setEnd(v.node,v.offset),p.addRange(y))}}}}for(d=[],p=s;p=p.parentNode;)p.nodeType===1&&d.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof s.focus==`function`&&s.focus(),s=0;sn?32:n,N.T=null,n=uu,uu=null;var o=ou,s=cu;if(au=0,su=ou=null,cu=0,Fl&6)throw Error(i(331));var c=Fl;if(Fl|=4,Al(o.current),Sl(o,o.current,s,n),Fl=c,od(0,!1),Ne&&typeof Ne.onPostCommitFiberRoot==`function`)try{Ne.onPostCommitFiberRoot(Me,o)}catch{}return!0}finally{P.p=a,N.T=r,Hu(e,t)}}function Gu(e,t,n){t=fi(n,t),t=Ks(e.stateNode,t,2),e=La(e,t,2),e!==null&&(Je(e,2),ad(e))}function Ku(e,t,n){if(e.tag===3)Gu(e,e,n);else for(;t!==null;){if(t.tag===3){Gu(t,e,n);break}if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(iu===null||!iu.has(r))){e=fi(n,e),n=qs(2),r=La(t,n,2),r!==null&&(Js(n,r,t,e),Je(r,2),ad(r));break}}t=t.return}}function qu(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new Pl;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(Ul=!0,i.add(n),e=Ju.bind(null,e,t,n),t.then(e,e))}function Ju(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,Il===e&&(Rl&n)===n&&(Gl===4||Gl===3&&(Rl&62914560)===Rl&&300>Ce()-eu?!(Fl&2)&&Cu(e,0):Jl|=n,Xl===Rl&&(Xl=0)),ad(e)}function Yu(e,t){t===0&&(t=Ke()),e=Zr(e,t),e!==null&&(Je(e,t),ad(e))}function Xu(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Yu(e,n)}function Zu(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(i(314))}r!==null&&r.delete(t),Yu(e,n)}function Qu(e,t){return be(e,t)}var $u=null,ed=null,td=!1,nd=!1,rd=!1,id=0;function ad(e){e!==ed&&e.next===null&&(ed===null?$u=ed=e:ed=ed.next=e),nd=!0,td||(td=!0,fd())}function od(e,t){if(!rd&&nd){rd=!0;do for(var n=!1,r=$u;r!==null;){if(!t){if(e!==0){var i=r.pendingLanes;if(i===0)var a=0;else{var o=r.suspendedLanes,s=r.pingedLanes;a=(1<<31-Fe(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,dd(r,a))}else a=Rl,a=Ue(r,r===Il?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||We(r,a)||(n=!0,dd(r,a))}r=r.next}while(n);rd=!1}}function sd(){cd()}function cd(){nd=td=!1;var e=0;id!==0&&Yd()&&(e=id);for(var t=Ce(),n=null,r=$u;r!==null;){var i=r.next,a=ld(r,t);a===0?(r.next=null,n===null?$u=i:n.next=i,i===null&&(ed=n)):(n=r,(e!==0||a&3)&&(nd=!0)),r=i}au!==0&&au!==5||od(e,!1),id!==0&&(id=0)}function ld(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes&-62914561;0s)break;var u=c.transferSize,d=c.initiatorType;u&&Bd(d)&&(c=c.responseEnd,o+=u*(c`u`?null:document;function Tf(e,t,n){var r=wf;if(r&&typeof t==`string`&&t){var i=Ft(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),yf.has(i)||(yf.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),Rd(t,`link`,e),gt(t),r.head.appendChild(t)))}}function Ef(e){xf.D(e),Tf(`dns-prefetch`,e,null)}function Df(e,t){xf.C(e,t),Tf(`preconnect`,e,t)}function Of(e,t,n){xf.L(e,t,n);var r=wf;if(r&&e&&t){var i=`link[rel="preload"][as="`+Ft(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+Ft(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+Ft(n.imageSizes)+`"]`)):i+=`[href="`+Ft(e)+`"]`;var a=i;switch(t){case`style`:a=Pf(e);break;case`script`:a=Rf(e)}vf.has(a)||(e=f({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),vf.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(Ff(a))||t===`script`&&r.querySelector(zf(a))||(t=r.createElement(`link`),Rd(t,`link`,e),gt(t),r.head.appendChild(t)))}}function kf(e,t){xf.m(e,t);var n=wf;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+Ft(r)+`"][href="`+Ft(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Rf(e)}if(!vf.has(a)&&(e=f({rel:`modulepreload`,href:e},t),vf.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(zf(a)))return}r=n.createElement(`link`),Rd(r,`link`,e),gt(r),n.head.appendChild(r)}}}function Af(e,t,n){xf.S(e,t,n);var r=wf;if(r&&e){var i=ht(r).hoistableStyles,a=Pf(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(Ff(a)))s.loading=5;else{e=f({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=vf.get(a))&&Hf(e,n);var c=o=r.createElement(`link`);gt(c),Rd(c,`link`,e),c._p=new Promise(function(e,t){c.onload=e,c.onerror=t}),c.addEventListener(`load`,function(){s.loading|=1}),c.addEventListener(`error`,function(){s.loading|=2}),s.loading|=4,Vf(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function jf(e,t){xf.X(e,t);var n=wf;if(n&&e){var r=ht(n).hoistableScripts,i=Rf(e),a=r.get(i);a||(a=n.querySelector(zf(i)),a||(e=f({src:e,async:!0},t),(t=vf.get(i))&&Uf(e,t),a=n.createElement(`script`),gt(a),Rd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Mf(e,t){xf.M(e,t);var n=wf;if(n&&e){var r=ht(n).hoistableScripts,i=Rf(e),a=r.get(i);a||(a=n.querySelector(zf(i)),a||(e=f({src:e,async:!0,type:`module`},t),(t=vf.get(i))&&Uf(e,t),a=n.createElement(`script`),gt(a),Rd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Nf(e,t,n,r){var a=(a=oe.current)?bf(a):null;if(!a)throw Error(i(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(t=Pf(n.href),n=ht(a).hoistableStyles,r=n.get(t),r||(r={type:`style`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};case`link`:if(n.rel===`stylesheet`&&typeof n.href==`string`&&typeof n.precedence==`string`){e=Pf(n.href);var o=ht(a).hoistableStyles,s=o.get(e);if(s||(a=a.ownerDocument||a,s={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},o.set(e,s),(o=a.querySelector(Ff(e)))&&!o._p&&(s.instance=o,s.state.loading=5),vf.has(e)||(n={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},vf.set(e,n),o||Lf(a,e,n,s.state))),t&&r===null)throw Error(i(528,``));return s}if(t&&r!==null)throw Error(i(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(t=Rf(n),n=ht(a).hoistableScripts,r=n.get(t),r||(r={type:`script`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(i(444,e))}}function Pf(e){return`href="`+Ft(e)+`"`}function Ff(e){return`link[rel="stylesheet"][`+e+`]`}function If(e){return f({},e,{"data-precedence":e.precedence,precedence:null})}function Lf(e,t,n,r){e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)?r.loading=1:(t=e.createElement(`link`),r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2}),Rd(t,`link`,n),gt(t),e.head.appendChild(t))}function Rf(e){return`[src="`+Ft(e)+`"]`}function zf(e){return`script[async]`+e}function Bf(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+Ft(n.href)+`"]`);if(r)return t.instance=r,gt(r),r;var a=f({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),gt(r),Rd(r,`style`,a),Vf(r,n.precedence,e),t.instance=r;case`stylesheet`:a=Pf(n.href);var o=e.querySelector(Ff(a));if(o)return t.state.loading|=4,t.instance=o,gt(o),o;r=If(n),(a=vf.get(a))&&Hf(r,a),o=(e.ownerDocument||e).createElement(`link`),gt(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),Rd(o,`link`,r),t.state.loading|=4,Vf(o,n.precedence,e),t.instance=o;case`script`:return o=Rf(n.src),(a=e.querySelector(zf(o)))?(t.instance=a,gt(a),a):(r=n,(a=vf.get(o))&&(r=f({},n),Uf(r,a)),e=e.ownerDocument||e,a=e.createElement(`script`),gt(a),Rd(a,`link`,r),e.head.appendChild(a),t.instance=a);case`void`:return null;default:throw Error(i(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Vf(r,n.precedence,e));return t.instance}function Vf(e,t,n){for(var r=n.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),i=r.length?r[r.length-1]:null,a=i,o=0;o title`):null)}function qf(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof t.precedence!=`string`||typeof t.href!=`string`||t.href===``)break;return!0;case`link`:if(typeof t.rel!=`string`||typeof t.href!=`string`||t.href===``||t.onLoad||t.onError)break;switch(t.rel){case`stylesheet`:return e=t.disabled,typeof t.precedence==`string`&&e==null;default:return!0}case`script`:if(t.async&&typeof t.async!=`function`&&typeof t.async!=`symbol`&&!t.onLoad&&!t.onError&&t.src&&typeof t.src==`string`)return!0}return!1}function Jf(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Yf(e,t,n,r){if(n.type===`stylesheet`&&(typeof r.media!=`string`||!1!==matchMedia(r.media).matches)&&!(n.state.loading&4)){if(n.instance===null){var i=Pf(r.href),a=t.querySelector(Ff(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=Qf.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,gt(a);return}a=t.ownerDocument||t,r=If(r),(i=vf.get(i))&&Hf(r,i),a=a.createElement(`link`),gt(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),Rd(a,`link`,r),n.instance=a}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=Qf.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var Xf=0;function Zf(e,t){return e.stylesheets&&e.count===0&&ep(e,e.stylesheets),0Xf?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function Qf(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)ep(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var $f=null;function ep(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,$f=new Map,t.forEach(tp,e),$f=null,Qf.call(e))}function tp(e,t){if(!(t.state.loading&4)){var n=$f.get(e);if(n)var r=n.get(null);else{n=new Map,$f.set(e,n);for(var i=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),a=0;a{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=Hj()}))(),Wj=`cps.web.deviceCredential`,Gj=`cps.preference.locale`,Kj=`cps.preference.theme`;function qj(){return globalThis.localStorage.getItem(Wj)??``}async function Jj(e){let t=await e.json().catch(()=>({}));return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}function Yj(e,t){let n=typeof e.code==`string`?e.code:`HOST_REQUEST_FAILED`;return Object.assign(Error(`${t} (${n})`),{code:n})}async function Xj(){let e=new URLSearchParams(globalThis.location.hash.replace(/^#/,``)).get(`pair`);if(!e)return qj()||null;globalThis.history.replaceState(null,``,`${globalThis.location.pathname}${globalThis.location.search}`);let t=await globalThis.fetch(`/api/pair`,{method:`POST`,redirect:`error`,credentials:`same-origin`,headers:{"X-Codex-Provider-Pairing":e}}),n=await Jj(t),r=typeof n.deviceCredential==`string`?n.deviceCredential:``;return!t.ok||!r?null:(globalThis.localStorage.setItem(Wj,r),r)}function Zj(e){return async(t,n={})=>{let r=await globalThis.fetch(t,{...n,headers:{...Object.fromEntries(new Headers(n.headers).entries()),"X-Codex-Provider-Device":e}});return r.status===403&&(await Jj(r.clone())).code===`PAIRING_REQUIRED`&&(globalThis.localStorage.removeItem(Wj),globalThis.dispatchEvent(new CustomEvent(`cps:pairing-required`))),r}}function Qj(e){let t=Zj(e),n={"Content-Type":`application/json`};return{listProfiles:async e=>{let n=await t(`/api/profiles`,{credentials:`same-origin`,redirect:`error`,signal:e}),r=await Jj(n);if(!n.ok||!Array.isArray(r.profiles))throw Yj(r,`Unable to load profiles`);return r.profiles},async saveProfile(e,r){let i=await t(`/api/profiles/save`,{method:`POST`,credentials:`same-origin`,redirect:`error`,headers:n,body:JSON.stringify(e),signal:r}),a=await Jj(i);if(!i.ok||!a.profile)throw Yj(a,`Unable to save profile`);return a.profile},async deleteProfile(e,r,i){let a=await t(`/api/profiles/delete`,{method:`POST`,credentials:`same-origin`,redirect:`error`,headers:n,body:JSON.stringify({profileId:e,profileRevision:r}),signal:i}),o=await Jj(a);if(!a.ok)throw Yj(o,`Unable to delete profile`)},async forgetBrowser(){try{await t(`/api/access/forget`,{method:`POST`,credentials:`same-origin`,redirect:`error`,headers:n,body:`{}`})}finally{globalThis.localStorage.removeItem(Wj)}}}}var $j={...Tj(globalThis.localStorage,`cps.web`),...zj(globalThis.localStorage,`cps.web`),getLocale(){let e=globalThis.localStorage.getItem(Gj);return e===`zh-CN`||e===`en`?e:null},setLocale(e){globalThis.localStorage.setItem(Gj,e)},getTheme(){let e=globalThis.localStorage.getItem(Kj);return e===`system`||e===`light`||e===`dark`?e:null},setTheme(e){globalThis.localStorage.setItem(Kj,e)}};async function eM(e){await e.forgetBrowser?.(),globalThis.location.reload()}var tM=(0,Uj.createRoot)(document.getElementById(`root`)),nM=await Xj();if(!nM)tM.render((0,h.jsx)(m.StrictMode,{children:(0,h.jsx)(`main`,{className:`grid min-h-screen place-items-center bg-[var(--surface)] p-6 text-[var(--text)]`,children:(0,h.jsxs)(`section`,{className:`max-w-lg rounded-2xl border border-[var(--border)] bg-[var(--surface-raised)] p-8 text-center shadow-xl`,children:[(0,h.jsx)(`h1`,{className:`text-2xl font-bold`,children:`Codex Provider Sync`}),(0,h.jsxs)(`p`,{className:`mt-3 text-sm leading-6 text-[var(--muted)]`,children:[`This browser is not paired. Run `,(0,h.jsx)(`code`,{children:`codex-provider web`}),` again and open the new one-time link.`]})]})})}));else{let e=Qj(nM),t=Zj(nM),n=new Xr({baseUrl:globalThis.location.origin,fetch:t});globalThis.addEventListener(`cps:pairing-required`,()=>globalThis.location.reload(),{once:!0}),tM.render((0,h.jsx)(m.StrictMode,{children:(0,h.jsx)(Rj,{core:n,host:e,initialLocale:globalThis.navigator.language.toLowerCase().startsWith(`zh`)?`zh-CN`:`en`,initialTheme:`system`,onForgetBrowser:()=>eM(e),preferences:$j,surface:`web`})}))} \ No newline at end of file diff --git a/web/dist/assets/index-CmcveSDP.css b/web/dist/assets/index-CmcveSDP.css new file mode 100644 index 0000000..c7d12c2 --- /dev/null +++ b/web/dist/assets/index-CmcveSDP.css @@ -0,0 +1,2 @@ +/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */ +@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-space-y-reverse:0;--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-outline-style:solid}::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-space-y-reverse:0;--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-outline-style:solid}}}@layer theme{:root,:host{--font-sans:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-lg:32rem;--container-2xl:42rem;--container-3xl:48rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75 / 1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--leading-tight:1.25;--leading-normal:1.5;--leading-relaxed:1.625;--radius-md:.375rem;--radius-lg:.5rem;--radius-xl:.75rem;--radius-2xl:1rem;--animate-spin:spin 1s linear infinite;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before{box-sizing:border-box;border:0 solid;margin:0;padding:0}::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.sticky{position:sticky}.inset-0{inset:0}.top-0{top:0}.top-1\/2{top:50%}.top-2{top:calc(var(--spacing) * 2)}.top-4{top:calc(var(--spacing) * 4)}.right-2{right:calc(var(--spacing) * 2)}.right-4{right:calc(var(--spacing) * 4)}.right-5{right:calc(var(--spacing) * 5)}.bottom-5{bottom:calc(var(--spacing) * 5)}.left-1\/2{left:50%}.z-30{z-index:30}.z-40{z-index:40}.z-50{z-index:50}.z-\[60\]{z-index:60}.z-\[70\]{z-index:70}.col-span-2{grid-column:span 2/span 2}.mx-auto{margin-inline:auto}.my-1{margin-block:var(--spacing)}.my-3{margin-block:calc(var(--spacing) * 3)}.my-4{margin-block:calc(var(--spacing) * 4)}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mt-1{margin-top:var(--spacing)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mt-5{margin-top:calc(var(--spacing) * 5)}.mt-\[var\(--space-1\)\]{margin-top:var(--space-1)}.mt-\[var\(--space-5\)\]{margin-top:var(--space-5)}.mt-\[var\(--space-6\)\]{margin-top:var(--space-6)}.mb-1{margin-bottom:var(--spacing)}.mb-1\.5{margin-bottom:calc(var(--spacing) * 1.5)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-5{margin-bottom:calc(var(--spacing) * 5)}.mb-\[var\(--space-6\)\]{margin-bottom:var(--space-6)}.ml-1{margin-left:var(--spacing)}.ml-2{margin-left:calc(var(--spacing) * 2)}.ml-auto{margin-left:auto}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline-flex{display:inline-flex}.table{display:table}.h-2{height:calc(var(--spacing) * 2)}.h-4{height:calc(var(--spacing) * 4)}.h-8{height:calc(var(--spacing) * 8)}.h-9{height:calc(var(--spacing) * 9)}.h-10{height:calc(var(--spacing) * 10)}.h-\[var\(--control-height\)\]{height:var(--control-height)}.h-dvh{height:100dvh}.h-full{height:100%}.max-h-64{max-height:calc(var(--spacing) * 64)}.max-h-72{max-height:calc(var(--spacing) * 72)}.max-h-80{max-height:calc(var(--spacing) * 80)}.max-h-\[30\%\]{max-height:30%}.max-h-\[40\%\]{max-height:40%}.max-h-\[45\%\]{max-height:45%}.max-h-\[90vh\]{max-height:90vh}.max-h-\[calc\(100dvh-16px\)\]{max-height:calc(100dvh - 16px)}.min-h-0{min-height:0}.min-h-8{min-height:calc(var(--spacing) * 8)}.min-h-9{min-height:calc(var(--spacing) * 9)}.min-h-10{min-height:calc(var(--spacing) * 10)}.min-h-11{min-height:calc(var(--spacing) * 11)}.min-h-16{min-height:calc(var(--spacing) * 16)}.min-h-\[var\(--control-height\)\]{min-height:var(--control-height)}.min-h-screen{min-height:100vh}.w-4{width:calc(var(--spacing) * 4)}.w-6{width:calc(var(--spacing) * 6)}.w-10{width:calc(var(--spacing) * 10)}.w-64{width:calc(var(--spacing) * 64)}.w-\[min\(92vw\,420px\)\]{width:min(92vw,420px)}.w-\[min\(92vw\,680px\)\]{width:min(92vw,680px)}.w-full{width:100%}.max-w-2xl{max-width:var(--container-2xl)}.max-w-3xl{max-width:var(--container-3xl)}.max-w-\[85\%\]{max-width:85%}.max-w-\[1600px\]{max-width:1600px}.max-w-\[calc\(100vw-16px\)\]{max-width:calc(100vw - 16px)}.max-w-\[min\(12rem\,70vw\)\]{max-width:min(12rem,70vw)}.max-w-full{max-width:100%}.max-w-lg{max-width:var(--container-lg)}.min-w-0{min-width:0}.flex-1{flex:1}.shrink-0{flex-shrink:0}.border-collapse{border-collapse:collapse}.-translate-x-1\/2{--tw-translate-x:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.-translate-y-1\/2{--tw-translate-y:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.resize{resize:both}.list-decimal{list-style-type:decimal}.list-disc{list-style-type:disc}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-\[minmax\(0\,1fr\)_auto\]{grid-template-columns:minmax(0,1fr) auto}.grid-rows-1{grid-template-rows:repeat(1,minmax(0,1fr))}.grid-rows-\[auto_minmax\(0\,1fr\)\]{grid-template-rows:auto minmax(0,1fr)}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.place-items-center{place-items:center}.content-start{align-content:flex-start}.items-baseline{align-items:baseline}.items-center{align-items:center}.items-end{align-items:flex-end}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.justify-items-start{justify-items:start}.gap-0{gap:0}.gap-1{gap:var(--spacing)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-5{gap:calc(var(--spacing) * 5)}.gap-6{gap:calc(var(--spacing) * 6)}.gap-\[var\(--space-1\)\]{gap:var(--space-1)}.gap-\[var\(--space-2\)\]{gap:var(--space-2)}.gap-\[var\(--space-3\)\]{gap:var(--space-3)}.gap-\[var\(--space-4\)\]{gap:var(--space-4)}:where(.space-y-0\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * .5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * .5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(var(--spacing) * var(--tw-space-y-reverse));margin-block-end:calc(var(--spacing) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px * var(--tw-divide-y-reverse));border-bottom-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-\[var\(--border\)\]>:not(:last-child)){border-color:var(--border)}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.overscroll-contain{overscroll-behavior:contain}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-\[var\(--radius-control\)\]{border-radius:var(--radius-control)}.rounded-\[var\(--radius-panel\)\]{border-radius:var(--radius-panel)}.rounded-full{border-radius:2147483647px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-none{border-radius:0}.rounded-xl{border-radius:var(--radius-xl)}.rounded-br-md{border-bottom-right-radius:var(--radius-md)}.border{border-style:var(--tw-border-style);border-width:1px}.border-0{border-style:var(--tw-border-style);border-width:0}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-l-4{border-left-style:var(--tw-border-style);border-left-width:4px}.border-\[var\(--accent\)\]{border-color:var(--accent)}.border-\[var\(--border\)\]{border-color:var(--border)}.border-\[var\(--danger\)\]{border-color:var(--danger)}.border-\[var\(--success\)\]{border-color:var(--success)}.border-\[var\(--warning\)\]{border-color:var(--warning)}.bg-\[color\:var\(--surface-raised\)\/\.96\]{background-color:var(--surface-raised)/.96}.bg-\[var\(--accent\)\]{background-color:var(--accent)}.bg-\[var\(--accent-soft\)\]{background-color:var(--accent-soft)}.bg-\[var\(--danger\)\]{background-color:var(--danger)}.bg-\[var\(--danger-soft\)\]{background-color:var(--danger-soft)}.bg-\[var\(--input\)\]{background-color:var(--input)}.bg-\[var\(--success-soft\)\]{background-color:var(--success-soft)}.bg-\[var\(--surface\)\]{background-color:var(--surface)}.bg-\[var\(--surface-hover\)\]{background-color:var(--surface-hover)}.bg-\[var\(--surface-raised\)\]{background-color:var(--surface-raised)}.bg-\[var\(--warning-soft\)\]{background-color:var(--warning-soft)}.bg-black\/50{background-color:#00000080}@supports (color:color-mix(in lab, red, red)){.bg-black\/50{background-color:color-mix(in oklab, var(--color-black) 50%, transparent)}}.p-0{padding:0}.p-1\.5{padding:calc(var(--spacing) * 1.5)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-5{padding:calc(var(--spacing) * 5)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.p-\[var\(--space-4\)\]{padding:var(--space-4)}.p-\[var\(--space-5\)\]{padding:var(--space-5)}.p-\[var\(--space-6\)\]{padding:var(--space-6)}.px-0{padding-inline:0}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-\[var\(--space-3\)\]{padding-inline:var(--space-3)}.px-\[var\(--space-4\)\]{padding-inline:var(--space-4)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:var(--spacing)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-\[var\(--space-1\)\]{padding-block:var(--space-1)}.pt-2{padding-top:calc(var(--spacing) * 2)}.pr-10{padding-right:calc(var(--spacing) * 10)}.pr-12{padding-right:calc(var(--spacing) * 12)}.pb-1{padding-bottom:var(--spacing)}.pb-3{padding-bottom:calc(var(--spacing) * 3)}.pl-4{padding-left:calc(var(--spacing) * 4)}.pl-5{padding-left:calc(var(--spacing) * 5)}.pl-6{padding-left:calc(var(--spacing) * 6)}.pl-7{padding-left:calc(var(--spacing) * 7)}.pl-8{padding-left:calc(var(--spacing) * 8)}.text-center{text-align:center}.text-left{text-align:left}.align-middle{vertical-align:middle}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.\[font-size\:var\(--text-2xl\)\]{font-size:var(--text-2xl)}.\[font-size\:var\(--text-sm\)\]{font-size:var(--text-sm)}.\[font-size\:var\(--text-xs\)\]{font-size:var(--text-xs)}.text-\[0\.9em\]{font-size:.9em}.text-\[10px\]{font-size:10px}.leading-5{--tw-leading:calc(var(--spacing) * 5);line-height:calc(var(--spacing) * 5)}.leading-6{--tw-leading:calc(var(--spacing) * 6);line-height:calc(var(--spacing) * 6)}.leading-7{--tw-leading:calc(var(--spacing) * 7);line-height:calc(var(--spacing) * 7)}.leading-\[var\(--leading-normal\)\]{--tw-leading:var(--leading-normal);line-height:var(--leading-normal)}.leading-\[var\(--leading-relaxed\)\]{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.leading-\[var\(--leading-tight\)\]{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.text-\[var\(--accent-strong\)\]{color:var(--accent-strong)}.text-\[var\(--danger\)\]{color:var(--danger)}.text-\[var\(--muted\)\]{color:var(--muted)}.text-\[var\(--success\)\]{color:var(--success)}.text-\[var\(--text\)\]{color:var(--text)}.text-\[var\(--warning\)\]{color:var(--warning)}.text-white{color:var(--color-white)}.tabular-nums{--tw-numeric-spacing:tabular-nums;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.underline{text-decoration-line:underline}.underline-offset-2{text-underline-offset:2px}.accent-\[var\(--accent\)\]{accent-color:var(--accent)}.accent-\[var\(--muted\)\]{accent-color:var(--muted)}.shadow-2xl{--tw-shadow:0 25px 50px -12px var(--tw-shadow-color,#00000040);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-none{--tw-shadow:0 0 #0000;box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-xl{--tw-shadow:0 20px 25px -5px var(--tw-shadow-color,#0000001a), 0 8px 10px -6px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.\[box-shadow\:var\(--shadow-panel\)\]{box-shadow:var(--shadow-panel)}.blur{--tw-blur:blur(8px);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.backdrop-blur{--tw-backdrop-blur:blur(8px);-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.backdrop-blur-\[2px\]{--tw-backdrop-blur:blur(2px);-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}.select-text{-webkit-user-select:text;user-select:text}.placeholder\:text-\[var\(--muted\)\]::placeholder{color:var(--muted)}.first\:mt-0:first-child{margin-top:0}.last\:mb-0:last-child{margin-bottom:0}.last\:border-0:last-child{border-style:var(--tw-border-style);border-width:0}@media (hover:hover){.hover\:bg-\[var\(--accent-strong\)\]:hover{background-color:var(--accent-strong)}.hover\:bg-\[var\(--surface-hover\)\]:hover{background-color:var(--surface-hover)}.hover\:text-\[var\(--text\)\]:hover{color:var(--text)}.hover\:brightness-95:hover{--tw-brightness:brightness(95%);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}}.focus\:not-sr-only:focus{clip-path:none;white-space:normal;width:auto;height:auto;margin:0;padding:0;position:static;overflow:visible}.focus\:fixed:focus{position:fixed}.focus\:top-4:focus{top:calc(var(--spacing) * 4)}.focus\:left-4:focus{left:calc(var(--spacing) * 4)}.focus\:z-\[70\]:focus{z-index:70}.focus\:rounded:focus{border-radius:.25rem}.focus\:bg-\[var\(--accent\)\]:focus{background-color:var(--accent)}.focus\:bg-\[var\(--accent-soft\)\]:focus{background-color:var(--accent-soft)}.focus\:px-4:focus{padding-inline:calc(var(--spacing) * 4)}.focus\:py-2:focus{padding-block:calc(var(--spacing) * 2)}.focus\:text-white:focus{color:var(--color-white)}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.focus-visible\:ring-2:focus-visible{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus-visible\:ring-\[var\(--focus\)\]:focus-visible{--tw-ring-color:var(--focus)}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.focus-visible\:ring-offset-\[var\(--surface\)\]:focus-visible{--tw-ring-offset-color:var(--surface)}.focus-visible\:outline:focus-visible{outline-style:var(--tw-outline-style);outline-width:1px}.focus-visible\:outline-2:focus-visible{outline-style:var(--tw-outline-style);outline-width:2px}.focus-visible\:outline-\[var\(--accent\)\]:focus-visible{outline-color:var(--accent)}.focus-visible\:outline-\[var\(--focus\)\]:focus-visible{outline-color:var(--focus)}.focus-visible\:outline-none:focus-visible{--tw-outline-style:none;outline-style:none}.focus-visible\:ring-inset:focus-visible{--tw-ring-inset:inset}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:opacity-40:disabled{opacity:.4}.disabled\:opacity-50:disabled{opacity:.5}.data-\[state\=closed\]\:animate-none[data-state=closed]{animation:none}@media (min-width:40rem){.sm\:grid{display:grid}.sm\:w-auto{width:auto}.sm\:shrink{flex-shrink:1}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.sm\:grid-cols-\[180px_1fr\]{grid-template-columns:180px 1fr}.sm\:justify-end{justify-content:flex-end}.sm\:overflow-visible{overflow:visible}.sm\:pb-0{padding-bottom:0}}@media (min-width:48rem){.md\:col-span-2{grid-column:span 2/span 2}.md\:min-h-\[calc\(100vh-4rem\)\]{min-height:calc(100vh - 4rem)}.md\:grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-\[240px_minmax\(0\,1fr\)\]{grid-template-columns:240px minmax(0,1fr)}.md\:grid-rows-1{grid-template-rows:repeat(1,minmax(0,1fr))}.md\:border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.md\:border-b-0{border-bottom-style:var(--tw-border-style);border-bottom-width:0}.md\:p-4{padding:calc(var(--spacing) * 4)}.md\:p-8{padding:calc(var(--spacing) * 8)}.md\:px-6{padding-inline:calc(var(--spacing) * 6)}}@media (min-width:64rem){.lg\:block{display:block}.lg\:flex{display:flex}.lg\:hidden{display:none}.lg\:inline{display:inline}.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.lg\:grid-cols-\[minmax\(240px\,0\.85fr\)_minmax\(0\,1\.4fr\)\]{grid-template-columns:minmax(240px,.85fr) minmax(0,1.4fr)}.lg\:grid-cols-\[minmax\(240px\,300px\)_minmax\(0\,1fr\)\]{grid-template-columns:minmax(240px,300px) minmax(0,1fr)}.lg\:border-r{border-right-style:var(--tw-border-style);border-right-width:1px}}@media (min-width:80rem){.xl\:col-span-4{grid-column:span 4/span 4}.xl\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.xl\:grid-cols-\[minmax\(0\,1fr\)_420px\]{grid-template-columns:minmax(0,1fr) 420px}.xl\:grid-cols-\[minmax\(0\,1fr\)_minmax\(320px\,440px\)\]{grid-template-columns:minmax(0,1fr) minmax(320px,440px)}}.\[\&\>div\]\:py-2>div{padding-block:calc(var(--spacing) * 2)}@media (min-width:40rem){.sm\:\[\&\>div\]\:grid-cols-\[140px_minmax\(0\,1fr\)\]>div{grid-template-columns:140px minmax(0,1fr)}}.\[\&\>select\]\:max-w-full>select{max-width:100%}@media (max-height:500px){.\[\@media\(max-height\:500px\)\]\:hidden{display:none}.\[\@media\(max-height\:500px\)\]\:min-h-0{min-height:0}.\[\@media\(max-height\:500px\)\]\:p-1{padding:var(--spacing)}.\[\@media\(max-height\:500px\)\]\:py-1{padding-block:var(--spacing)}}}:root,:root[data-theme=light]{--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light;--surface:#f6f7fb;--surface-raised:#fff;--surface-hover:#eef1f7;--input:#fff;--border:#dce1eb;--text:#172033;--muted:#657086;--accent:#4867e8;--accent-strong:#3452ce;--accent-soft:#e9edff;--focus:#315ee8;--success:#16734a;--success-soft:#e6f6ee;--warning:#9a5b00;--warning-soft:#fff3d8;--danger:#b42335;--danger-soft:#fdebed;--control-height:2.5rem;--radius-control:.5rem;--radius-panel:.75rem;--shadow-panel:0 1px 2px #17203314, 0 8px 24px #17203308;--font-sans:"Segoe UI Variable Text", "Segoe UI", Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, sans-serif;--text-xs:.75rem;--text-sm:.875rem;--text-base:1rem;--text-lg:1.125rem;--text-xl:1.25rem;--text-2xl:1.5rem;--leading-tight:1.25;--leading-normal:1.5;--leading-relaxed:1.625;--space-1:.25rem;--space-2:.5rem;--space-3:.75rem;--space-4:1rem;--space-5:1.25rem;--space-6:1.5rem;font-family:var(--font-sans)}:root[data-theme=dark]{--lightningcss-light: ;--lightningcss-dark:initial;color-scheme:dark;--surface:#11141b;--surface-raised:#181d27;--surface-hover:#242b38;--input:#111722;--border:#30394a;--text:#eef2f8;--muted:#a6b0c1;--accent:#7189ff;--accent-strong:#8fa1ff;--accent-soft:#222d58;--focus:#91a3ff;--success:#67d8a4;--success-soft:#17392d;--warning:#f2bb61;--warning-soft:#3d2e17;--danger:#ff8c99;--danger-soft:#461e26}@media (prefers-color-scheme:dark){:root[data-theme=system]{--lightningcss-light: ;--lightningcss-dark:initial;color-scheme:dark;--surface:#11141b;--surface-raised:#181d27;--surface-hover:#242b38;--input:#111722;--border:#30394a;--text:#eef2f8;--muted:#a6b0c1;--accent:#7189ff;--accent-strong:#8fa1ff;--accent-soft:#222d58;--focus:#91a3ff;--success:#67d8a4;--success-soft:#17392d;--warning:#f2bb61;--warning-soft:#3d2e17;--danger:#ff8c99;--danger-soft:#461e26}}@media (prefers-reduced-motion:reduce){*,:before,:after{scroll-behavior:auto!important;transition-duration:.001ms!important;animation-duration:.001ms!important;animation-iteration-count:1!important}}html{background:var(--surface);min-width:320px}body{background:var(--surface);min-width:320px;min-height:100vh;margin:0}button,input,select{font:inherit}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-ordinal{syntax:"*";inherits:false}@property --tw-slashed-zero{syntax:"*";inherits:false}@property --tw-numeric-figure{syntax:"*";inherits:false}@property --tw-numeric-spacing{syntax:"*";inherits:false}@property --tw-numeric-fraction{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@keyframes spin{to{transform:rotate(360deg)}} diff --git a/web/dist/assets/index-D-VUimW_.js b/web/dist/assets/index-D-VUimW_.js new file mode 100644 index 0000000..c1528e6 --- /dev/null +++ b/web/dist/assets/index-D-VUimW_.js @@ -0,0 +1,143 @@ +var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;li[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,o)=>(o=n==null?{}:e(i(n)),c(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var u=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),d=o(((e,t)=>{t.exports=u()})),f=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.iterator;function m(e){return typeof e!=`object`||!e?null:(e=p&&e[p]||e[`@@iterator`],typeof e==`function`?e:null)}var h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,_={};function v(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}v.prototype.isReactComponent={},v.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function y(){}y.prototype=v.prototype;function b(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}var x=b.prototype=new y;x.constructor=b,g(x,v.prototype),x.isPureReactComponent=!0;var S=Array.isArray;function C(){}var w={H:null,A:null,T:null,S:null},T=Object.prototype.hasOwnProperty;function E(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function D(e,t){return E(e.type,t,e.props)}function O(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function ee(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var k=/\/+/g;function A(e,t){return typeof e==`object`&&e&&e.key!=null?ee(``+e.key):t.toString(36)}function j(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(C,C):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function M(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,M(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+A(e,0):a,S(o)?(i=``,c!=null&&(i=c.replace(k,`$&/`)+`/`),M(o,r,i,``,function(e){return e})):o!=null&&(O(o)&&(o=D(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(k,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(S(e))for(var u=0;u{t.exports=f()})),m=l(p(),1),h=d(),g=m.createContext(void 0),_=e=>{let t=m.useContext(g);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},v=({client:e,children:t})=>(m.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,h.jsx)(g.Provider,{value:e,children:t})),y={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},b=new class{#e=y;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function x(e){setTimeout(e,0)}var S=typeof window>`u`||`Deno`in globalThis;function C(){}function w(e,t){return typeof e==`function`?e(t):e}function T(e){return typeof e==`number`&&e>=0&&e!==1/0}function E(e,t){return Math.max(e+(t||0)-Date.now(),0)}function D(e,t){return typeof e==`function`?e(t):e}function O(e,t){return typeof e==`function`?e(t):e}function ee(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==A(o,t.options))return!1}else if(!M(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function k(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(j(t.options.mutationKey)!==j(a))return!1}else if(!M(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function A(e,t){return(t?.queryKeyHashFn||j)(e)}function j(e){return JSON.stringify(e,(e,t)=>ne(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function M(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){for(let n=0;n500)return t;let r=te(e)&&te(t);if(!r&&!(ne(e)&&ne(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l{b.setTimeout(t,e)})}function I(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:P(e,t)}function L(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function ae(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var oe=Symbol();function se(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===oe?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ce(e,t){return typeof e==`function`?e(...t):!!e}function le(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var ue=(()=>{let e=()=>S;return{isServer(){return e()},setIsServer(t){e=t}}})(),de=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},fe=new class extends de{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},pe=x;function me(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=pe,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var he=me(),ge=new class extends de{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function _e(e){return Math.min(1e3*2**e,3e4)}function ve(e){return(e??`online`)!==`online`||ge.isOnline()}var ye=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function be(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(C);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new ye(t);h(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>fe.isFocused()&&(e.networkMode===`always`||ge.isOnline())&&e.canRun(),p=()=>ve(e.networkMode)&&e.canRun(),m=e=>{c()||(r?.(),i=`resolved`,a(e))},h=e=>{c()||(r?.(),i=`rejected`,o(e))},g=()=>new Promise(t=>{r=e=>{(c()||f())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),_=()=>{if(c())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(m).catch(r=>{if(c())return;let i=e.retry??(ue.isServer()?0:3),a=e.retryDelay??_e,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&nf()?void 0:g()).then(()=>{t?h(r):_()})})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:p,start:()=>(p()?_():g().then(_),s)}}var xe=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),T(this.gcTime)&&(this.#e=b.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(ue.isServer()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(b.clearTimeout(this.#e),this.#e=void 0)}};function Se(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{le(e,()=>t.signal,()=>n=!0)},u=se(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?ae:L;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?Ce:R,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:R(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(ct.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function R(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Ce(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function we(e,t){return t?R(e,t)!=null:!1}function Te(e,t){return!t||!e.getPreviousPageParam?!1:Ce(e,t)!=null}var Ee=class extends xe{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=ke(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=ke(this.options);e.data!==void 0&&(this.setState(Oe(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=I(this.state.data,e,this.options);return this.#l({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(C).catch(C):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>O(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===oe||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>D(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!E(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#s||this.#c()?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}#c(){return this.state.fetchStatus===`paused`&&this.state.status===`pending`}invalidate(){this.state.isInvalidated||this.#l({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=se(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?Se(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#l({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=be({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof ye&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#l({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#l({type:`pause`})},onContinue:()=>{this.#l({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await o.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof ye){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#l({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0),this.scheduleGc()}}#l(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...De(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...Oe(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),he.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function De(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ve(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function Oe(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function ke(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var Ae=class extends de{#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Me(this.#t,this.options)?this.#m():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ne(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ne(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#y(),this.#b(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof O(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#x(),this.#t.setOptions(this.options),t._defaulted&&!F(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&Pe(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||O(this.options.enabled,this.#t)!==O(t.enabled,this.#t)||D(this.options.staleTime,this.#t)!==D(t.staleTime,this.#t))&&this.#h();let i=this.#g();r&&(this.#t!==n||O(this.options.enabled,this.#t)!==O(t.enabled,this.#t)||i!==this.#f)&&this.#_(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return Ie(this,n)&&(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t),r=()=>{},i,a=new Promise(e=>{i=e,r=this.#e.getQueryCache().subscribe(i=>{i.type===`updated`&&i.query.queryHash===n.queryHash&&n.state.data!==void 0&&(r(),e(this.createResult(n,t)))})});return Promise.race([n.fetch().then(()=>{let e=this.createResult(n,t);return i?.(e),e}).finally(()=>{r()}),a])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#x();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(C)),t}#h(){this.#y();let e=D(this.options.staleTime,this.#t);if(ue.isServer()||this.#r.isStale||!T(e))return;let t=E(this.#r.dataUpdatedAt,e)+1;this.#u=b.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#g(){return(typeof this.options.refetchInterval==`function`?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#_(e){this.#b(),this.#f=e,!(ue.isServer()||O(this.options.enabled,this.#t)===!1||!T(this.#f)||this.#f===0)&&(this.#d=b.setInterval(()=>{(this.options.refetchIntervalInBackground||fe.isFocused())&&this.#m()},this.#f))}#v(){this.#h(),this.#_(this.#g())}#y(){this.#u!==void 0&&(b.clearTimeout(this.#u),this.#u=void 0)}#b(){this.#d!==void 0&&(b.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&Me(e,t),o=i&&Pe(e,n,t,r);(a||o)&&(l={...l,...De(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(m=`success`,d=I(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h){if(i&&d===a?.data&&t.select===this.#s)d=this.#c;else try{this.#s=t.select,d=t.select(d),d=I(i?.data,d,t),this.#c=d,this.#o=null}catch(e){this.#o=e}}else d===void 0&&(this.#o=null);this.#o&&(f=this.#o,d=this.#c,p=Date.now(),m=`error`,u=!1);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0;return{status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:y,isLoading:y,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:Fe(e,t),refetch:this.refetch,isEnabled:O(t.enabled,e)!==!1}}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#l=this.#t),!F(t,e)&&(this.#r=t,this.#S({listeners:(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#p.size)return!0;let r=new Set(n??this.#p);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})()}))}#x(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#v()}#S(e){he.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function je(e,t){return O(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||O(t.retryOnMount,e)!==!1)}function Me(e,t){return je(e,t)||e.state.data!==void 0&&Ne(e,t,t.refetchOnMount)}function Ne(e,t,n){if(O(t.enabled,e)!==!1&&D(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&Fe(e,t)}return!1}function Pe(e,t,n,r){return(e!==t||O(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&Fe(e,n)}function Fe(e,t){return O(t.enabled,e)!==!1&&e.isStaleByTime(D(t.staleTime,e))}function Ie(e,t){return!F(e.getCurrentResult(),t)}var Le=class extends Ae{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type=`infinite`,super.setOptions(e)}getOptimisticResult(e){return e._type=`infinite`,super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:`forward`}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:`backward`}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:a,isError:o,isRefetchError:s}=r,c=n.fetchMeta?.fetchMore?.direction,l=o&&c===`forward`,u=i&&c===`forward`,d=o&&c===`backward`,f=i&&c===`backward`;return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:we(t,n.data),hasPreviousPage:Te(t,n.data),isFetchNextPageError:l,isFetchingNextPage:u,isFetchPreviousPageError:d,isFetchingPreviousPage:f,isRefetchError:s&&!l&&!d,isRefetching:a&&!u&&!f}}},Re=class extends xe{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||ze(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??(this.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},r=this.#r=be({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),i=this.state.status===`pending`,a=!r.canStart();try{if(i)t();else{this.#i({type:`pending`,variables:e,isPaused:a}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:a})}let o=await r.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#i({type:`success`,data:o}),o}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#r===r&&(this.#r=void 0),this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),he.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function ze(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var Be=class extends de{#e;#t;#n;constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}build(e,t,n){let r=new Re({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=Ve(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=Ve(e);if(typeof t==`string`){let n=this.#t.get(t);if(n){if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=Ve(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}return!0}runNext(e){let t=Ve(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){he.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>k(t,e))}findAll(e={}){return this.getAll().filter(t=>k(e,t))}notify(e){he.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return he.batch(()=>Promise.all(e.map(e=>e.continue().catch(C))))}};function Ve(e){return e.options.scope?.id}var He=class extends de{#e;#t=void 0;#n;#r;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),F(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&j(t.mutationKey)!==j(this.options.mutationKey)?this.reset():this.#n?.state.status===`pending`&&this.#n.setOptions(this.options)}onSubscribe(){this.listeners.size===1&&this.#n&&(this.#n.addObserver(this),this.#i())}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#i(),this.#a()}mutate(e,t){return this.#r=t,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(e)}#i(){let e=this.#n?.state??ze();this.#t={...e,isPending:e.status===`pending`,isSuccess:e.status===`success`,isError:e.status===`error`,isIdle:e.status===`idle`,mutate:this.mutate,reset:this.reset}}#a(e){he.batch(()=>{if(this.#r&&this.hasListeners()){let t=this.#t.variables,n=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{this.#r.onSuccess?.(e.data,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(e.data,null,t,n,r)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{this.#r.onError?.(e.error,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(void 0,e.error,t,n,r)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},Ue=class extends de{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){let r=t.queryKey,i=t.queryHash??A(r,t),a=this.get(i);return a||(a=new Ee({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){he.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>ee(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>ee(e,t)):t}notify(e){he.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){he.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){he.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},We=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new Ue,this.#t=e.mutationCache||new Be,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=fe.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=ge.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(D(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=w(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return he.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;he.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return he.batch(()=>{let r=n.findAll(e),i=new Set(r);return r.forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,predicate:e=>i.has(e)},t)})}cancelQueries(e,t={}){let n={revert:!0,...t},r=he.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(C).catch(C)}invalidateQueries(e,t={}){return he.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=he.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(C)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(C)}async query(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t),r=n.isStaleByTime(D(t.staleTime,n))?await n.fetch(t):n.state.data,i=t.select;return i?i(r):r}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(D(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(C).catch(C)}infiniteQuery(e){return e._type=`infinite`,this.query(e)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(C).catch(C)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return ge.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(j(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{M(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(j(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{M(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=A(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===oe&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},Ge=m.createContext(!1),Ke=()=>m.useContext(Ge);Ge.Provider;function qe(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Je=m.createContext(qe()),Ye=()=>m.useContext(Je),Xe=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?ce(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},Ze=e=>{m.useEffect(()=>{e.clearReset()},[e])},Qe=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||ce(n,[e.error,r])),$e=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},et=(e,t)=>e?.suspense&&t.isPending,tt=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function nt(e,t,n){let r=Ke(),i=Ye(),a=_(n),o=a.defaultQueryOptions(e),s=a.getQueryCache().get(o.queryHash),c=e.subscribed!==!1;o._optimisticResults=r?`isRestoring`:c?`optimistic`:void 0,$e(o),Xe(o,i,s),Ze(i);let[l]=m.useState(()=>new t(a,o)),u=l.getOptimisticResult(o),d=!r&&c;if(m.useSyncExternalStore(m.useCallback(e=>{let t=d?l.subscribe(he.batchCalls(e)):C;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),m.useEffect(()=>{l.setOptions(o)},[o,l]),et(o,u))throw tt(o,l,i);if(Qe({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return o.notifyOnChangeProps?u:l.trackResult(u)}function rt(e,t){return nt(e,Ae,t)}function it(e,t){let n=_(t);return ot({filters:{...e,status:`pending`}},n).length}function at(e,t){return e.findAll(t.filters).map(e=>t.select?t.select(e):e.state)}function ot(e={},t){let n=_(t).getMutationCache(),r=m.useRef(e),i=m.useRef(null);return i.current===null&&(i.current=at(n,e)),m.useEffect(()=>{r.current=e}),m.useSyncExternalStore(m.useCallback(e=>n.subscribe(()=>{let t=P(i.current,at(n,r.current));i.current!==t&&(i.current=t,he.schedule(e))}),[n]),()=>i.current,()=>i.current)}function st(e,t){let n=_(t),[r]=m.useState(()=>new He(n,e));m.useEffect(()=>{r.setOptions(e)},[r,e]);let i=m.useSyncExternalStore(m.useCallback(e=>r.subscribe(he.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=m.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(C)},[r]);if(i.error&&ce(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}function ct(e,t){return nt(e,Le,t)}var z=e=>typeof e==`string`,lt=()=>{let e,t,n=new Promise((n,r)=>{e=n,t=r});return n.resolve=e,n.reject=t,n},ut=e=>e==null?``:String(e),dt=(e,t,n)=>{e.forEach(e=>{t[e]&&(n[e]=t[e])})},ft=/###/g,pt=e=>e&&e.includes(`###`)?e.replace(ft,`.`):e,mt=e=>!e||z(e),ht=(e,t,n)=>{let r=z(t)?t.split(`.`):t,i=0;for(;i{let{obj:r,k:i}=ht(e,t,Object);if(r!==void 0||t.length===1){r[i]=n;return}let a=t[t.length-1],o=t.slice(0,t.length-1),s=ht(e,o,Object);for(;s.obj===void 0&&o.length;)a=`${o[o.length-1]}.${a}`,o=o.slice(0,o.length-1),s=ht(e,o,Object),s?.obj&&s.obj[`${s.k}.${a}`]!==void 0&&(s.obj=void 0);s.obj[`${s.k}.${a}`]=n},_t=(e,t,n,r)=>{let{obj:i,k:a}=ht(e,t,Object);i[a]=i[a]||[],i[a].push(n)},vt=(e,t)=>{let{obj:n,k:r}=ht(e,t);if(n&&Object.prototype.hasOwnProperty.call(n,r))return n[r]},yt=(e,t,n)=>{let r=vt(e,n);return r===void 0?vt(t,n):r},bt=(e,t,n)=>{for(let r in t)r!==`__proto__`&&r!==`constructor`&&(Object.prototype.hasOwnProperty.call(e,r)?z(e[r])||e[r]instanceof String||z(t[r])||t[r]instanceof String?n&&(e[r]=t[r]):bt(e[r],t[r],n):e[r]=t[r]);return e},xt=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,`\\$&`),St={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`,"/":`/`},Ct=e=>z(e)?e.replace(/[&<>"'\/]/g,e=>St[e]):e,wt=class{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){let t=this.regExpMap.get(e);if(t!==void 0)return t;let n=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,n),this.regExpQueue.push(e),n}},Tt=[` `,`,`,`?`,`!`,`;`],Et=new wt(20),Dt=(e,t,n)=>{t||=``,n||=``;let r=Tt.filter(e=>!t.includes(e)&&!n.includes(e));if(r.length===0)return!0;let i=Et.getRegExp(`(${r.map(e=>e===`?`?`\\?`:e).join(`|`)})`),a=!i.test(e);if(!a){let t=e.indexOf(n);t>0&&!i.test(e.substring(0,t))&&(a=!0)}return a},Ot=(e,t,n=`.`)=>{if(!e)return;if(e[t])return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;let r=t.split(n),i=e;for(let e=0;ee?.replace(/_/g,`-`),At={type:`logger`,log(e){this.output(`log`,e)},warn(e){this.output(`warn`,e)},error(e){this.output(`error`,e)},output(e,t){console?.[e]?.apply?.(console,t)}},jt=new class e{constructor(e,t={}){this.init(e,t)}init(e,t={}){this.prefix=t.prefix||`i18next:`,this.logger=e||At,this.options=t,this.debug=t.debug}log(...e){return this.forward(e,`log`,``,!0)}warn(...e){return this.forward(e,`warn`,``,!0)}error(...e){return this.forward(e,`error`,``)}deprecate(...e){return this.forward(e,`warn`,`WARNING DEPRECATED: `,!0)}forward(e,t,n,r){return r&&!this.debug?null:(e=e.map(e=>z(e)?e.replace(/[\r\n\x00-\x1F\x7F]/g,` `):e),z(e[0])&&(e[0]=`${n}${this.prefix} ${e[0]}`),this.logger[t](e))}create(t){return new e(this.logger,{prefix:`${this.prefix}:${t}:`,...this.options})}clone(t){return t||=this.options,t.prefix=t.prefix||this.prefix,new e(this.logger,t)}},Mt=class{constructor(){this.observers={}}on(e,t){return e.split(` `).forEach(e=>{this.observers[e]||(this.observers[e]=new Map);let n=this.observers[e].get(t)||0;this.observers[e].set(t,n+1)}),this}off(e,t){if(this.observers[e]){if(!t){delete this.observers[e];return}this.observers[e].delete(t)}}once(e,t){let n=(...r)=>{t(...r),this.off(e,n)};return this.on(e,n),this}emit(e,...t){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([e,n])=>{for(let r=0;r{for(let i=0;i-1&&this.options.ns.splice(t,1)}getResource(e,t,n,r={}){let i=r.keySeparator===void 0?this.options.keySeparator:r.keySeparator,a=r.ignoreJSONStructure===void 0?this.options.ignoreJSONStructure:r.ignoreJSONStructure,o;e.includes(`.`)?o=e.split(`.`):(o=[e,t],n&&(Array.isArray(n)?o.push(...n):z(n)&&i?o.push(...n.split(i)):o.push(n)));let s=vt(this.data,o);return!s&&!t&&!n&&e.includes(`.`)&&(e=o[0],t=o[1],n=o.slice(2).join(`.`)),s||!a||!z(n)?s:Ot(this.data?.[e]?.[t],n,i)}addResource(e,t,n,r,i={silent:!1}){let a=i.keySeparator===void 0?this.options.keySeparator:i.keySeparator,o=[e,t];n&&(o=o.concat(a?n.split(a):n)),e.includes(`.`)&&(o=e.split(`.`),r=t,t=o[1]),this.addNamespaces(t),gt(this.data,o,r),i.silent||this.emit(`added`,e,t,n,r)}addResources(e,t,n,r={silent:!1}){for(let r in n)(z(n[r])||Array.isArray(n[r]))&&this.addResource(e,t,r,n[r],{silent:!0});r.silent||this.emit(`added`,e,t,n)}addResourceBundle(e,t,n,r,i,a={silent:!1,skipCopy:!1}){let o=[e,t];e.includes(`.`)&&(o=e.split(`.`),r=n,n=t,t=o[1]),this.addNamespaces(t);let s=vt(this.data,o)||{};a.skipCopy||(n=JSON.parse(JSON.stringify(n))),r?bt(s,n,i):s={...s,...n},gt(this.data,o,s),a.silent||this.emit(`added`,e,t,n)}removeResourceBundle(e,t){this.hasResourceBundle(e,t)&&delete this.data[e][t],this.removeNamespaces(t),this.emit(`removed`,e,t)}hasResourceBundle(e,t){return this.getResource(e,t)!==void 0}getResourceBundle(e,t){return t||=this.options.defaultNS,this.getResource(e,t)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){let t=this.getDataByLanguage(e);return!!(t&&Object.keys(t)||[]).find(e=>t[e]&&Object.keys(t[e]).length>0)}toJSON(){return this.data}},Pt={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,n,r,i){return e.forEach(e=>{t=this.processors[e]?.process(t,n,r,i)??t}),t}},Ft=Symbol(`i18next/PATH_KEY`);function It(){let e=[],t=Object.create(null),n;return t.get=(r,i)=>(n?.revoke?.(),i===Ft?e:(e.push(i),n=Proxy.revocable(r,t),n.proxy)),Proxy.revocable(Object.create(null),t).proxy}function Lt(e,t){let{[Ft]:n}=e(It()),r=t?.keySeparator??`.`,i=t?.nsSeparator??`:`,a=t?.enableSelector===`strict`;if(n.length>1&&i){let e=t?.ns,o=a?Array.isArray(e)?e:e?[e]:null:Array.isArray(e)?e:null;if(o&&(a?o:o.length>1?o.slice(1):[]).includes(n[0]))return`${n[0]}${i}${n.slice(1).join(r)}`}return n.join(r)}var Rt=e=>!z(e)&&typeof e!=`boolean`&&typeof e!=`number`,zt=class e extends Mt{constructor(e,t={}){super(),dt([`resourceStore`,`languageUtils`,`pluralResolver`,`interpolator`,`backendConnector`,`i18nFormat`,`utils`],e,this),this.options=t,this.options.keySeparator===void 0&&(this.options.keySeparator=`.`),this.logger=jt.create(`translator`),this.checkedLoadedFor={}}changeLanguage(e){e&&(this.language=e)}exists(e,t={interpolation:{}}){let n={...t};if(e==null)return!1;let r=this.resolve(e,n);if(r?.res===void 0)return!1;let i=Rt(r.res);return!(n.returnObjects===!1&&i)}extractFromKey(e,t){let n=t.nsSeparator===void 0?this.options.nsSeparator:t.nsSeparator;n===void 0&&(n=`:`);let r=t.keySeparator===void 0?this.options.keySeparator:t.keySeparator,i=t.ns||this.options.defaultNS||[],a=n&&e.includes(n),o=!this.options.userDefinedKeySeparator&&!t.keySeparator&&!this.options.userDefinedNsSeparator&&!t.nsSeparator&&!Dt(e,n,r);if(a&&!o){let t=e.match(this.interpolator.nestingRegexp);if(t&&t.length>0)return{key:e,namespaces:z(i)?[i]:i};let a=e.split(n);(n!==r||n===r&&this.options.ns.includes(a[0]))&&(i=a.shift()),e=a.join(r)}return{key:e,namespaces:z(i)?[i]:i}}translate(t,n,r){let i=typeof n==`object`?{...n}:n;if(typeof i!=`object`&&this.options.overloadTranslationOptionHandler&&(i=this.options.overloadTranslationOptionHandler(arguments)),typeof i==`object`&&(i={...i}),i||={},t==null)return``;typeof t==`function`&&(t=Lt(t,{...this.options,...i})),Array.isArray(t)||(t=[String(t)]),t=t.map(e=>typeof e==`function`?Lt(e,{...this.options,...i}):String(e));let a=i.returnDetails===void 0?this.options.returnDetails:i.returnDetails,o=i.keySeparator===void 0?this.options.keySeparator:i.keySeparator,{key:s,namespaces:c}=this.extractFromKey(t[t.length-1],i),l=c[c.length-1],u=i.nsSeparator===void 0?this.options.nsSeparator:i.nsSeparator;u===void 0&&(u=`:`);let d=i.lng||this.language,f=i.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(d?.toLowerCase()===`cimode`)return f?a?{res:`${l}${u}${s}`,usedKey:s,exactUsedKey:s,usedLng:d,usedNS:l,usedParams:this.getUsedParamsDetails(i)}:`${l}${u}${s}`:a?{res:s,usedKey:s,exactUsedKey:s,usedLng:d,usedNS:l,usedParams:this.getUsedParamsDetails(i)}:s;let p=this.resolve(t,i),m=p?.res,h=p?.usedKey||s,g=p?.exactUsedKey||s,_=[`[object Number]`,`[object Function]`,`[object RegExp]`],v=i.joinArrays===void 0?this.options.joinArrays:i.joinArrays,y=!this.i18nFormat||this.i18nFormat.handleAsObject,b=i.count!==void 0&&!z(i.count),x=e.hasDefaultValue(i),S=b?this.pluralResolver.getSuffix(d,i.count,i):``,C=i.ordinal&&b?this.pluralResolver.getSuffix(d,i.count,{ordinal:!1}):``,w=b&&!i.ordinal&&i.count===0,T=w&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${S}`]||i[`defaultValue${C}`]||i.defaultValue,E=m;y&&!m&&x&&(E=T);let D=Rt(E),O=Object.prototype.toString.apply(E);if(y&&E&&D&&!_.includes(O)&&!(z(v)&&Array.isArray(E))){if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn(`accessing an object - but returnObjects options is not enabled!`);let e=this.options.returnedObjectHandler?this.options.returnedObjectHandler(h,E,{...i,ns:c}):`key '${s} (${this.language})' returned an object instead of string.`;return a?(p.res=e,p.usedParams=this.getUsedParamsDetails(i),p):e}if(o){let e=Array.isArray(E),t=e?[]:{},n=e?g:h;for(let e in E)if(Object.prototype.hasOwnProperty.call(E,e)){let r=`${n}${o}${e}`;t[e]=x&&!m?this.translate(r,{...i,defaultValue:Rt(T)?T[e]:void 0,joinArrays:!1,ns:c}):this.translate(r,{...i,joinArrays:!1,ns:c}),t[e]===r&&(t[e]=E[e])}m=t}}else if(y&&z(v)&&Array.isArray(m))m=m.join(v),m&&=this.extendTranslation(m,t,i,r);else{let e=!1,n=!1;!this.isValidLookup(m)&&x&&(e=!0,m=T),this.isValidLookup(m)||(n=!0,m=s);let a=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&n?void 0:m,c=x&&T!==m&&this.options.updateMissing;if(n||e||c){if(this.logger.log(c?`updateKey`:`missingKey`,d,l,b&&!c?`${s}${this.pluralResolver.getSuffix(d,i.count,i)}`:s,c?T:m),o){let e=this.resolve(s,{...i,keySeparator:!1});e&&e.res&&this.logger.warn(`Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.`)}let e=[],t=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if(this.options.saveMissingTo===`fallback`&&t&&t[0])for(let n=0;n{let r=x&&n!==m?n:a;this.options.missingKeyHandler?this.options.missingKeyHandler(e,l,t,r,c,i):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(e,l,t,r,c,i),this.emit(`missingKey`,e,l,t,m)};this.options.saveMissing&&(this.options.saveMissingPlurals&&b?e.forEach(e=>{let t=this.pluralResolver.getSuffixes(e,i);w&&i[`defaultValue${this.options.pluralSeparator}zero`]&&!t.includes(`${this.options.pluralSeparator}zero`)&&t.push(`${this.options.pluralSeparator}zero`),t.forEach(t=>{n([e],s+t,i[`defaultValue${t}`]||T)})}):n(e,s,T))}m=this.extendTranslation(m,t,i,p,r),n&&m===s&&this.options.appendNamespaceToMissingKey&&(m=`${l}${u}${s}`),(n||e)&&this.options.parseMissingKeyHandler&&(m=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${l}${u}${s}`:s,e?m:void 0,i))}return a?(p.res=m,p.usedParams=this.getUsedParamsDetails(i),p):m}extendTranslation(e,t,n,r,i){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...n},n.lng||this.language||r.usedLng,r.usedNS,r.usedKey,{resolved:r});else if(!n.skipInterpolation){n.interpolation&&this.interpolator.init({...n,interpolation:{...this.options.interpolation,...n.interpolation}});let a=z(e)&&(n?.interpolation?.skipOnVariables===void 0?this.options.interpolation.skipOnVariables:n.interpolation.skipOnVariables),o;if(a){let t=e.match(this.interpolator.nestingRegexp);o=t&&t.length}let s=n.replace&&!z(n.replace)?n.replace:n;if(this.options.interpolation.defaultVariables&&(s={...this.options.interpolation.defaultVariables,...s}),e=this.interpolator.interpolate(e,s,n.lng||this.language||r.usedLng,n),a){let t=e.match(this.interpolator.nestingRegexp),r=t&&t.length;oi?.[0]===e[0]&&!n.context?(this.logger.warn(`It seems you are nesting recursively key: ${e[0]} in key: ${t[0]}`),null):this.translate(...e,t),n)),n.interpolation&&this.interpolator.reset()}let a=n.postProcess||this.options.postProcess,o=z(a)?[a]:a;return e!=null&&o?.length&&n.applyPostProcessor!==!1&&(e=Pt.handle(o,e,t,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...r,usedParams:this.getUsedParamsDetails(n)},...n}:n,this)),e}resolve(e,t={}){let n,r,i,a,o;return z(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(e=>typeof e==`function`?Lt(e,{...this.options,...t}):e)),e.forEach(e=>{if(this.isValidLookup(n))return;let s=this.extractFromKey(e,t),c=s.key;r=c;let l=s.namespaces;this.options.fallbackNS&&(l=l.concat(this.options.fallbackNS));let u=t.count!==void 0&&!z(t.count),d=u&&!t.ordinal&&t.count===0,f=t.context!==void 0&&(z(t.context)||typeof t.context==`number`)&&t.context!==``,p=t.lngs?t.lngs:this.languageUtils.toResolveHierarchy(t.lng||this.language,t.fallbackLng);l.forEach(e=>{this.isValidLookup(n)||(o=e,!this.checkedLoadedFor[`${p[0]}-${e}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(o)&&(this.checkedLoadedFor[`${p[0]}-${e}`]=!0,this.logger.warn(`key "${r}" for languages "${p.join(`, `)}" won't get resolved as namespace "${o}" was not yet loaded`,`This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!`)),p.forEach(r=>{if(this.isValidLookup(n))return;a=r;let o=[c];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(o,c,r,e,t);else{let e;u&&(e=this.pluralResolver.getSuffix(r,t.count,t));let n=`${this.options.pluralSeparator}zero`,i=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(u&&(t.ordinal&&e.startsWith(i)&&o.push(c+e.replace(i,this.options.pluralSeparator)),o.push(c+e),d&&o.push(c+n)),f){let r=`${c}${this.options.contextSeparator||`_`}${t.context}`;o.push(r),u&&(t.ordinal&&e.startsWith(i)&&o.push(r+e.replace(i,this.options.pluralSeparator)),o.push(r+e),d&&o.push(r+n))}}let s;for(;s=o.pop();)this.isValidLookup(n)||(i=s,n=this.getResource(r,e,s,t))}))})}),{res:n,usedKey:r,exactUsedKey:i,usedLng:a,usedNS:o}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e===``)}getResource(e,t,n,r={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,t,n,r):this.resourceStore.getResource(e,t,n,r)}getUsedParamsDetails(e={}){let t=[`defaultValue`,`ordinal`,`context`,`replace`,`lng`,`lngs`,`fallbackLng`,`ns`,`keySeparator`,`nsSeparator`,`returnObjects`,`returnDetails`,`joinArrays`,`postProcess`,`interpolation`],n=e.replace&&!z(e.replace),r=n?e.replace:e;if(n&&e.count!==void 0&&(r={...r,count:e.count}),this.options.interpolation.defaultVariables&&(r={...this.options.interpolation.defaultVariables,...r}),!n){r={...r};for(let e of t)delete r[e]}return r}static hasDefaultValue(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&t.startsWith(`defaultValue`)&&e[t]!==void 0)return!0;return!1}},Bt=class{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=jt.create(`languageUtils`),this.resolveHierarchyCache={}}clearCache(){this.resolveHierarchyCache={}}getScriptPartFromCode(e){if(e=kt(e),!e||!e.includes(`-`))return null;let t=e.split(`-`);return t.length===2||(t.pop(),t[t.length-1].toLowerCase()===`x`)?null:this.formatLanguageCode(t.join(`-`))}getLanguagePartFromCode(e){if(e=kt(e),!e||!e.includes(`-`))return e;let t=e.split(`-`);return this.formatLanguageCode(t[0])}formatLanguageCode(e){if(z(e)&&e.includes(`-`)){let t;try{t=Intl.getCanonicalLocales(e)[0]}catch{}return t&&this.options.lowerCaseLng&&(t=t.toLowerCase()),t||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load===`languageOnly`||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.includes(e)}getBestMatchFromCodes(e){if(!e)return null;let t;return e.forEach(e=>{if(t)return;let n=this.formatLanguageCode(e);(!this.options.supportedLngs||this.isSupportedCode(n))&&(t=n)}),!t&&this.options.supportedLngs&&e.forEach(e=>{if(t)return;let n=this.getScriptPartFromCode(e);if(this.isSupportedCode(n))return t=n;let r=this.getLanguagePartFromCode(e);if(this.isSupportedCode(r))return t=r;t=this.options.supportedLngs.find(e=>e===r?!0:!e.includes(`-`)&&!r.includes(`-`)?!1:!!(e.includes(`-`)&&!r.includes(`-`)&&e.slice(0,e.indexOf(`-`))===r||e.startsWith(r)&&r.length>1))}),t||=this.getFallbackCodes(this.options.fallbackLng)[0],t}getFallbackCodes(e,t){if(!e)return[];if(typeof e==`function`&&(e=e(t)),z(e)&&(e=[e]),Array.isArray(e))return e;if(!t)return e.default||[];let n=e[t];return n||=e[this.getScriptPartFromCode(t)],n||=e[this.formatLanguageCode(t)],n||=e[this.getLanguagePartFromCode(t)],n||=e.default,n||[]}toResolveHierarchy(e,t){let n=this.options.fallbackLng,r=Array.isArray(n)?n.join(`|`):n;r!==this._cachedFallbackLng&&(this.resolveHierarchyCache={},this._cachedFallbackLng=r);let i=t===void 0||t===!1||z(t),a=t===void 0&&typeof this.options.fallbackLng==`function`,o=z(e)&&i&&!a,s=null;if(o){let n;n=t===void 0?`undefined`:t===!1?`boolean:false`:`string:${t}`,s=`${e.length}:${e}|${n}`}if(s!==null){let e=this.resolveHierarchyCache[s];if(e!==void 0)return e.slice()}let c=this.getFallbackCodes((t===!1?[]:t)||this.options.fallbackLng||[],e),l=[],u=e=>{e&&(this.isSupportedCode(e)?l.push(e):this.logger.warn(`rejecting language code not found in supportedLngs: ${e}`))};return z(e)&&(e.includes(`-`)||e.includes(`_`))?(this.options.load!==`languageOnly`&&u(this.formatLanguageCode(e)),this.options.load!==`languageOnly`&&this.options.load!==`currentOnly`&&u(this.getScriptPartFromCode(e)),this.options.load!==`currentOnly`&&u(this.getLanguagePartFromCode(e))):z(e)&&u(this.formatLanguageCode(e)),c.forEach(e=>{l.includes(e)||u(this.formatLanguageCode(e))}),s===null?l:(this.resolveHierarchyCache[s]=l,l.slice())}},Vt={zero:0,one:1,two:2,few:3,many:4,other:5},Ht={select:e=>e===1?`one`:`other`,resolvedOptions:()=>({pluralCategories:[`one`,`other`]})},Ut=class{constructor(e,t={}){this.languageUtils=e,this.options=t,this.logger=jt.create(`pluralResolver`),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,t={}){let n=kt(e===`dev`?`en`:e),r=t.ordinal?`ordinal`:`cardinal`,i=JSON.stringify({cleanedCode:n,type:r});if(i in this.pluralRulesCache)return this.pluralRulesCache[i];let a;try{a=new Intl.PluralRules(n,{type:r})}catch{if(typeof Intl>`u`)return this.logger.error(`No Intl support, please use an Intl polyfill!`),Ht;if(!e.match(/-|_/))return Ht;let n=this.languageUtils.getLanguagePartFromCode(e);a=this.getRule(n,t)}return this.pluralRulesCache[i]=a,a}needsPlural(e,t={}){let n=this.getRule(e,t);return n||=this.getRule(`dev`,t),n?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,t,n={}){return this.getSuffixes(e,n).map(e=>`${t}${e}`)}getSuffixes(e,t={}){let n=this.getRule(e,t);return n||=this.getRule(`dev`,t),n?n.resolvedOptions().pluralCategories.sort((e,t)=>Vt[e]-Vt[t]).map(e=>`${this.options.prepend}${t.ordinal?`ordinal${this.options.prepend}`:``}${e}`):[]}getSuffix(e,t,n={}){let r=this.getRule(e,n);return r?`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:``}${r.select(t)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix(`dev`,t,n))}},Wt=(e,t,n,r=`.`,i=!0)=>{let a=yt(e,t,n);return!a&&i&&z(n)&&(a=Ot(e,n,r),a===void 0&&(a=Ot(t,n,r))),a},Gt=e=>e.replace(/\$/g,`$$$$`),Kt=class{constructor(e={}){this.logger=jt.create(`interpolator`),this.options=e,this.format=e?.interpolation?.format||(e=>e),this.init(e)}init(e={}){e.interpolation||={escapeValue:!0};let{escape:t,escapeValue:n,useRawValueToEscape:r,prefix:i,prefixEscaped:a,suffix:o,suffixEscaped:s,formatSeparator:c,unescapeSuffix:l,unescapePrefix:u,nestingPrefix:d,nestingPrefixEscaped:f,nestingSuffix:p,nestingSuffixEscaped:m,nestingOptionsSeparator:h,maxReplaces:g,alwaysFormat:_}=e.interpolation;this.escape=t===void 0?Ct:t,this.escapeValue=n===void 0||n,this.useRawValueToEscape=r!==void 0&&r,this.prefix=i?xt(i):a||`{{`,this.suffix=o?xt(o):s||`}}`,this.formatSeparator=c||`,`,this.unescapePrefix=l?``:u?xt(u):`-`,this.unescapeSuffix=this.unescapePrefix?``:l?xt(l):``,this.nestingPrefix=d?xt(d):f||xt(`$t(`),this.nestingSuffix=p?xt(p):m||xt(`)`),this.nestingOptionsSeparator=h||`,`,this.maxReplaces=g||1e3,this.alwaysFormat=_!==void 0&&_,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){let e=(e,t)=>e?.source===t?(e.lastIndex=0,e):new RegExp(t,`g`);this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,t,n,r){let i,a,o,s=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},c=e=>{if(!e.includes(this.formatSeparator)){let i=Wt(t,s,e,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(i,void 0,n,{...r,...t,interpolationkey:e}):i}let i=e.split(this.formatSeparator),a=i.shift().trim(),o=i.join(this.formatSeparator).trim();return this.format(Wt(t,s,a,this.options.keySeparator,this.options.ignoreJSONStructure),o,n,{...r,...t,interpolationkey:a})};this.resetRegExp(),!this.escapeValue&&typeof e==`string`&&/\$t\([^)]*\{[^}]*\{\{/.test(e)&&this.logger.warn(`nesting options string contains interpolated variables with escapeValue: false — if any of those values are attacker-controlled they can inject additional nesting options (e.g. redirect lng/ns). Sanitise untrusted input before passing it to t(), or keep escapeValue: true.`);let l=r?.missingInterpolationHandler||this.options.missingInterpolationHandler,u=r?.interpolation?.skipOnVariables===void 0?this.options.interpolation.skipOnVariables:r.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:e=>e},{regex:this.regexp,safeValue:e=>this.escapeValue?this.escape(e):e}].forEach(t=>{for(o=0;i=t.regex.exec(e);){let n=i[1].trim();if(a=c(n),a===void 0){if(typeof l==`function`){let t=l(e,i,r);a=z(t)?t:``}else if(r&&Object.prototype.hasOwnProperty.call(r,n))a=``;else if(u){a=i[0];continue}else this.logger.warn(`missed to pass in variable ${n} for interpolating ${e}`),a=``}else!z(a)&&!this.useRawValueToEscape&&(a=ut(a));let s=t.safeValue(a);if(e=e.replace(i[0],Gt(s)),u?(t.regex.lastIndex+=s.length,t.regex.lastIndex-=i[0].length):t.regex.lastIndex=0,o++,o>=this.maxReplaces)break}}),e}nest(e,t,n={}){let r,i,a,o=(e,t)=>{let n=this.nestingOptionsSeparator;if(!e.includes(n))return e;let r=e.split(RegExp(`${xt(n)}[ ]*{`)),i=`{${r[1]}`;e=r[0],i=this.interpolate(i,a);let o=i.match(/'/g),s=i.match(/"/g);((o?.length??0)%2==0&&!s||(s?.length??0)%2!=0)&&(i=i.replace(/'/g,`"`));try{a=JSON.parse(i),t&&(a={...t,...a})}catch(t){return this.logger.warn(`failed parsing options string in nesting for key ${e}`,t),`${e}${n}${i}`}return a.defaultValue&&a.defaultValue.includes(this.prefix)&&delete a.defaultValue,e};for(;r=this.nestingRegexp.exec(e);){let s=[];a={...n},a=a.replace&&!z(a.replace)?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;let c=/{.*}/s.test(r[1])?r[1].lastIndexOf(`}`)+1:r[1].indexOf(this.formatSeparator);if(c!==-1&&(s=r[1].slice(c).split(this.formatSeparator).map(e=>e.trim()).filter(Boolean),r[1]=r[1].slice(0,c)),i=t(o.call(this,r[1].trim(),a),a),i&&r[0]===e&&!z(i))return i;z(i)||(i=ut(i)),i||=(this.logger.warn(`missed to resolve ${r[1]} for nesting ${e}`),``),s.length&&(i=s.reduce((e,t)=>this.format(e,t,n.lng,{...n,interpolationkey:r[1].trim()}),i.trim())),e=e.replace(r[0],i),this.regexp.lastIndex=0}return e}},qt=e=>{let t=e.toLowerCase().trim(),n={};if(e.includes(`(`)){let r=e.split(`(`);t=r[0].toLowerCase().trim();let i=r[1].slice(0,-1);t===`currency`&&!i.includes(`:`)?n.currency||=i.trim():t===`relativetime`&&!i.includes(`:`)?n.range||=i.trim():i.split(`;`).forEach(e=>{if(e){let[t,...r]=e.split(`:`),i=r.join(`:`).trim().replace(/^'+|'+$/g,``),a=t.trim();n[a]||(n[a]=i),i===`false`&&(n[a]=!1),i===`true`&&(n[a]=!0),isNaN(i)||(n[a]=parseInt(i,10))}})}return{formatName:t,formatOptions:n}},Jt=e=>{let t={};return(n,r,i)=>{let a=i;i&&i.interpolationkey&&i.formatParams&&i.formatParams[i.interpolationkey]&&i[i.interpolationkey]&&(a={...a,[i.interpolationkey]:void 0});let o=r+JSON.stringify(a),s=t[o];return s||(s=e(kt(r),i),t[o]=s),s(n)}},Yt=e=>(t,n,r)=>e(kt(n),r)(t),Xt=class{constructor(e={}){this.logger=jt.create(`formatter`),this.options=e,this.init(e)}init(e,t={interpolation:{}}){this.formatSeparator=t.interpolation.formatSeparator||`,`;let n=t.cacheInBuiltFormats?Jt:Yt;this.formats={number:n((e,t)=>{let n=new Intl.NumberFormat(e,{...t});return e=>n.format(e)}),currency:n((e,t)=>{let n=new Intl.NumberFormat(e,{...t,style:`currency`});return e=>n.format(e)}),datetime:n((e,t)=>{let n=new Intl.DateTimeFormat(e,{...t});return e=>n.format(e)}),relativetime:n((e,t)=>{let n=new Intl.RelativeTimeFormat(e,{...t});return e=>n.format(e,t.range||`day`)}),list:n((e,t)=>{let n=new Intl.ListFormat(e,{...t});return e=>n.format(e)})}}add(e,t){this.formats[e.toLowerCase().trim()]=t}addCached(e,t){this.formats[e.toLowerCase().trim()]=Jt(t)}format(e,t,n,r={}){if(!t||e==null)return e;let i=t.split(this.formatSeparator),a=[];for(let e=0;e-1&&!t.includes(`)`)&&e+1{let{formatName:i,formatOptions:a}=qt(t);if(this.formats[i]){let t=e;try{let o=r?.formatParams?.[r.interpolationkey]||{},s=o.locale||o.lng||r.locale||r.lng||n;t=this.formats[i](e,s,{...a,...r,...o})}catch(e){this.logger.warn(e)}return t}return this.logger.warn(`there was no format function for ${i}`),e},e)}},Zt=(e,t)=>{e.pending[t]!==void 0&&(delete e.pending[t],e.pendingCount--)},Qt=class extends Mt{constructor(e,t,n,r={}){super(),this.backend=e,this.store=t,this.services=n,this.languageUtils=n.languageUtils,this.options=r,this.logger=jt.create(`backendConnector`),this.waitingReads=[],this.maxParallelReads=r.maxParallelReads||10,this.readingCalls=0,this.maxRetries=r.maxRetries>=0?r.maxRetries:5,this.retryTimeout=r.retryTimeout>=1?r.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(n,r.backend,r)}queueLoad(e,t,n,r){let i={},a={},o={},s={};return e.forEach(e=>{let r=!0;t.forEach(t=>{let o=`${e}|${t}`;!n.reload&&this.store.hasResourceBundle(e,t)?this.state[o]=2:this.state[o]<0||(this.state[o]===1?a[o]===void 0&&(a[o]=!0):(this.state[o]=1,r=!1,a[o]===void 0&&(a[o]=!0),i[o]===void 0&&(i[o]=!0),s[t]===void 0&&(s[t]=!0)))}),r||(o[e]=!0)}),(Object.keys(i).length||Object.keys(a).length)&&this.queue.push({pending:a,pendingCount:Object.keys(a).length,loaded:{},errors:[],callback:r}),{toLoad:Object.keys(i),pending:Object.keys(a),toLoadLanguages:Object.keys(o),toLoadNamespaces:Object.keys(s)}}loaded(e,t,n){let r=e.split(`|`),i=r[0],a=r[1];t&&this.emit(`failedLoading`,i,a,t),!t&&n&&this.store.addResourceBundle(i,a,n,void 0,void 0,{skipCopy:!0}),this.state[e]=t?-1:2,t&&n&&(this.state[e]=0);let o={};this.queue.forEach(n=>{_t(n.loaded,[i],a),Zt(n,e),t&&n.errors.push(t),n.pendingCount===0&&!n.done&&(Object.keys(n.loaded).forEach(e=>{o[e]||(o[e]={});let t=n.loaded[e];t.length&&t.forEach(t=>{o[e][t]===void 0&&(o[e][t]=!0)})}),n.done=!0,n.errors.length?n.callback(n.errors):n.callback())}),this.emit(`loaded`,o),this.queue=this.queue.filter(e=>!e.done)}read(e,t,n,r=0,i=this.retryTimeout,a){if(!e.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:t,fcName:n,tried:r,wait:i,callback:a});return}this.readingCalls++;let o=(o,s)=>{if(this.readingCalls--,this.waitingReads.length>0){let e=this.waitingReads.shift();this.read(e.lng,e.ns,e.fcName,e.tried,e.wait,e.callback)}if(o&&s&&r{this.read(e,t,n,r+1,i*2,a)},i);return}a(o,s)},s=this.backend[n].bind(this.backend);if(s.length===2){try{let n=s(e,t);n&&typeof n.then==`function`?n.then(e=>o(null,e)).catch(o):o(null,n)}catch(e){o(e)}return}return s(e,t,o)}prepareLoading(e,t,n={},r){if(!this.backend)return this.logger.warn(`No backend was added via i18next.use. Will not load resources.`),r&&r();z(e)&&(e=this.languageUtils.toResolveHierarchy(e)),z(t)&&(t=[t]);let i=this.queueLoad(e,t,n,r);if(!i.toLoad.length)return i.pending.length||r(),null;i.toLoad.forEach(e=>{this.loadOne(e)})}load(e,t,n){this.prepareLoading(e,t,{},n)}reload(e,t,n){this.prepareLoading(e,t,{reload:!0},n)}loadOne(e,t=``){let n=e.split(`|`),r=n[0],i=n[1];this.read(r,i,`read`,void 0,void 0,(n,a)=>{n&&this.logger.warn(`${t}loading namespace ${i} for language ${r} failed`,n),!n&&a&&this.logger.log(`${t}loaded namespace ${i} for language ${r}`,a),this.loaded(e,n,a)})}saveMissing(e,t,n,r,i,a={},o=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(t)){this.logger.warn(`did not save key "${n}" as the namespace "${t}" was not yet loaded`,`This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!`);return}if(n!=null&&n!==``){if(this.backend?.create){let s={...a,isUpdate:i},c=this.backend.create.bind(this.backend);if(c.length<6)try{let i;i=c.length===5?c(e,t,n,r,s):c(e,t,n,r),i&&typeof i.then==`function`?i.then(e=>o(null,e)).catch(o):o(null,i)}catch(e){o(e)}else c(e,t,n,r,o,s)}!e||!e[0]||this.store.addResource(e[0],t,n,r)}}},$t=()=>({debug:!1,initAsync:!0,ns:[`translation`],defaultNS:[`translation`],fallbackLng:[`dev`],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:`all`,preload:!1,keySeparator:`.`,nsSeparator:`:`,pluralSeparator:`_`,contextSeparator:`_`,enableSelector:!1,partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:`fallback`,saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:e=>{let t={};if(typeof e[1]==`object`&&(t=e[1]),z(e[1])&&(t.defaultValue=e[1]),z(e[2])&&(t.tDescription=e[2]),typeof e[2]==`object`||typeof e[3]==`object`){let n=e[3]||e[2];Object.keys(n).forEach(e=>{t[e]=n[e]})}return t},interpolation:{escapeValue:!0,prefix:`{{`,suffix:`}}`,formatSeparator:`,`,unescapePrefix:`-`,nestingPrefix:`$t(`,nestingSuffix:`)`,nestingOptionsSeparator:`,`,maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),en=e=>(z(e.ns)&&(e.ns=[e.ns]),z(e.fallbackLng)&&(e.fallbackLng=[e.fallbackLng]),z(e.fallbackNS)&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs&&!e.supportedLngs.includes(`cimode`)&&(e.supportedLngs=e.supportedLngs.concat([`cimode`])),e),tn=()=>{},nn=e=>{Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(t=>{typeof e[t]==`function`&&(e[t]=e[t].bind(e))})},rn=class e extends Mt{constructor(e={},t){if(super(),this.options=en(e),this.services={},this.logger=jt,this.modules={external:[]},nn(this),t&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,t),this;setTimeout(()=>{this.init(e,t)},0)}}init(e={},t){this.isInitializing=!0,typeof e==`function`&&(t=e,e={}),e.defaultNS==null&&e.ns&&(z(e.ns)?e.defaultNS=e.ns:e.ns.includes(`translation`)||(e.defaultNS=e.ns[0]));let n=$t();this.options={...n,...this.options,...en(e)},this.options.interpolation={...n.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!=`function`&&(this.options.overloadTranslationOptionHandler=n.overloadTranslationOptionHandler);let r=e=>e?typeof e==`function`?new e:e:null;if(!this.options.isClone){this.modules.logger?jt.init(r(this.modules.logger),this.options):jt.init(null,this.options);let e;e=this.modules.formatter?this.modules.formatter:Xt;let t=new Bt(this.options);this.store=new Nt(this.options.resources,this.options);let n=this.services;n.logger=jt,n.resourceStore=this.store,n.languageUtils=t,n.pluralResolver=new Ut(t,{prepend:this.options.pluralSeparator}),e&&(n.formatter=r(e),n.formatter.init&&n.formatter.init(n,this.options),this.options.interpolation.format=n.formatter.format.bind(n.formatter)),n.interpolator=new Kt(this.options),n.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},n.backendConnector=new Qt(r(this.modules.backend),n.resourceStore,n,this.options),n.backendConnector.on(`*`,(e,...t)=>{this.emit(e,...t)}),this.modules.languageDetector&&(n.languageDetector=r(this.modules.languageDetector),n.languageDetector.init&&n.languageDetector.init(n,this.options.detection,this.options)),this.modules.i18nFormat&&(n.i18nFormat=r(this.modules.i18nFormat),n.i18nFormat.init&&n.i18nFormat.init(this)),this.translator=new zt(this.services,this.options),this.translator.on(`*`,(e,...t)=>{this.emit(e,...t)}),this.modules.external.forEach(e=>{e.init&&e.init(this)})}if(this.format=this.options.interpolation.format,t||=tn,this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){let e=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);e.length>0&&e[0]!==`dev`&&(this.options.lng=e[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn(`init: no languageDetector is used and no lng is defined`),[`getResource`,`hasResourceBundle`,`getResourceBundle`,`getDataByLanguage`].forEach(e=>{this[e]=(...t)=>this.store[e](...t)}),[`addResource`,`addResources`,`addResourceBundle`,`removeResourceBundle`].forEach(e=>{this[e]=(...t)=>(this.store[e](...t),this)});let i=lt(),a=()=>{let e=(e,n)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn(`init: i18next is already initialized. You should call init just once!`),this.isInitialized=!0,this.options.isClone||this.logger.log(`initialized`,this.options),this.emit(`initialized`,this.options),i.resolve(n),t(e,n)};if((this.languages||this.isLanguageChangingTo)&&!this.isInitialized)return e(null,this.t.bind(this));this.changeLanguage(this.options.lng,e)};return this.options.resources||!this.options.initAsync?a():setTimeout(a,0),i}loadResources(e,t=tn){let n=t,r=z(e)?e:this.language;if(typeof e==`function`&&(n=e),!this.options.resources||this.options.partialBundledLanguages){if(r?.toLowerCase()===`cimode`&&(!this.options.preload||this.options.preload.length===0))return n();let e=[],t=t=>{t&&t!==`cimode`&&this.services.languageUtils.toResolveHierarchy(t).forEach(t=>{t!==`cimode`&&(e.includes(t)||e.push(t))})};r?t(r):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(e=>t(e)),this.options.preload?.forEach?.(e=>t(e)),this.services.backendConnector.load(e,this.options.ns,e=>{!e&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),n(e)})}else n(null)}reloadResources(e,t,n){let r=lt();return typeof e==`function`&&(n=e,e=void 0),typeof t==`function`&&(n=t,t=void 0),e||=this.languages,t||=this.options.ns,n||=tn,this.services.backendConnector.reload(e,t,e=>{r.resolve(),n(e)}),r}use(e){if(!e)throw Error(`You are passing an undefined module! Please check the object you are passing to i18next.use()`);if(!e.type)throw Error(`You are passing a wrong module! Please check the object you are passing to i18next.use()`);return e.type===`backend`&&(this.modules.backend=e),(e.type===`logger`||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type===`languageDetector`&&(this.modules.languageDetector=e),e.type===`i18nFormat`&&(this.modules.i18nFormat=e),e.type===`postProcessor`&&Pt.addPostProcessor(e),e.type===`formatter`&&(this.modules.formatter=e),e.type===`3rdParty`&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&![`cimode`,`dev`].includes(e)){for(let e=0;e{this.language=e,this.languages=this.services.languageUtils.toResolveHierarchy(e),this.resolvedLanguage=void 0,this.setResolvedLanguage(e)},i=(i,a)=>{a?this.isLanguageChangingTo===e&&(r(a),this.translator.changeLanguage(a),this.isLanguageChangingTo=void 0,this.emit(`languageChanged`,a),this.logger.log(`languageChanged`,a)):this.isLanguageChangingTo=void 0,n.resolve((...e)=>this.t(...e)),t&&t(i,(...e)=>this.t(...e))},a=t=>{!e&&!t&&this.services.languageDetector&&(t=[]);let n=z(t)?t:t&&t[0],a=this.store.hasLanguageSomeTranslations(n)?n:this.services.languageUtils.getBestMatchFromCodes(z(t)?[t]:t);a&&(this.language||r(a),this.translator.language||this.translator.changeLanguage(a),this.services.languageDetector?.cacheUserLanguage?.(a)),this.loadResources(a,e=>{i(e,a)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?a(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(a):this.services.languageDetector.detect(a):a(e),n}getFixedT(e,t,n,r){let i=r?.scopeNs,a=(e,t,...r)=>{let o;o=typeof t==`object`?{...t}:this.options.overloadTranslationOptionHandler([e,t].concat(r)),o.lng=o.lng||a.lng,o.lngs=o.lngs||a.lngs;let s=o.ns!==void 0&&o.ns!==null;o.ns=o.ns||a.ns,o.keyPrefix!==``&&(o.keyPrefix=o.keyPrefix||n||a.keyPrefix);let c={...this.options,...o};Array.isArray(i)&&!s&&(c.ns=i),typeof o.keyPrefix==`function`&&(o.keyPrefix=Lt(o.keyPrefix,c));let l=this.options.keySeparator||`.`,u;return o.keyPrefix&&Array.isArray(e)?u=e.map(e=>(typeof e==`function`&&(e=Lt(e,c)),`${o.keyPrefix}${l}${e}`)):(typeof e==`function`&&(e=Lt(e,c)),u=o.keyPrefix?`${o.keyPrefix}${l}${e}`:e),this.t(u,o)};return z(e)?a.lng=e:a.lngs=e,a.ns=t,a.keyPrefix=n,a}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,t={}){if(!this.isInitialized)return this.logger.warn(`hasLoadedNamespace: i18next was not initialized`,this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn(`hasLoadedNamespace: i18n.languages were undefined or empty`,this.languages),!1;let n=t.lng||this.resolvedLanguage||this.languages[0],r=this.options?this.options.fallbackLng:!1,i=this.languages[this.languages.length-1];if(n.toLowerCase()===`cimode`)return!0;let a=(e,t)=>{let n=this.services.backendConnector.state[`${e}|${t}`];return n===-1||n===0||n===2};if(t.precheck){let e=t.precheck(this,a);if(e!==void 0)return e}return!!(this.hasResourceBundle(n,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||a(n,e)&&(!r||a(i,e)))}loadNamespaces(e,t){let n=lt();return this.options.ns?(z(e)&&(e=[e]),e.forEach(e=>{this.options.ns.includes(e)||this.options.ns.push(e)}),this.loadResources(e=>{n.resolve(),t&&t(e)}),n):(t&&t(),Promise.resolve())}loadLanguages(e,t){let n=lt();z(e)&&(e=[e]);let r=this.options.preload||[],i=e.filter(e=>!r.includes(e)&&this.services.languageUtils.isSupportedCode(e));return i.length?(this.options.preload=r.concat(i),this.loadResources(e=>{n.resolve(),t&&t(e)}),n):(t&&t(),Promise.resolve())}dir(e){if(e||=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language),!e)return`rtl`;try{let t=new Intl.Locale(e);if(t&&t.getTextInfo){let e=t.getTextInfo();if(e&&e.direction)return e.direction}}catch{}let t=`ar.shu.sqr.ssh.xaa.yhd.yud.aao.abh.abv.acm.acq.acw.acx.acy.adf.ads.aeb.aec.afb.ajp.apc.apd.arb.arq.ars.ary.arz.auz.avl.ayh.ayl.ayn.ayp.bbz.pga.he.iw.ps.pbt.pbu.pst.prp.prd.ug.ur.ydd.yds.yih.ji.yi.hbo.men.xmn.fa.jpr.peo.pes.prs.dv.sam.ckb`.split(`.`),n=this.services?.languageUtils||new Bt($t());return e.toLowerCase().indexOf(`-latn`)>1?`ltr`:t.includes(n.getLanguagePartFromCode(e))||e.toLowerCase().indexOf(`-arab`)>1?`rtl`:`ltr`}static createInstance(t={},n){let r=new e(t,n);return r.createInstance=e.createInstance,r}cloneInstance(t={},n=tn){let r=t.forkResourceStore;r&&delete t.forkResourceStore;let i={...this.options,...t,isClone:!0},a=new e(i);if((t.debug!==void 0||t.prefix!==void 0)&&(a.logger=a.logger.clone(t)),[`store`,`services`,`language`].forEach(e=>{a[e]=this[e]}),a.services={...this.services},a.services.utils={hasLoadedNamespace:a.hasLoadedNamespace.bind(a)},r&&(a.store=new Nt(Object.keys(this.store.data).reduce((e,t)=>(e[t]={...this.store.data[t]},e[t]=Object.keys(e[t]).reduce((n,r)=>(n[r]={...e[t][r]},n),e[t]),e),{}),i),a.services.resourceStore=a.store),t.interpolation){let e={...$t().interpolation,...this.options.interpolation,...t.interpolation},n={...i,interpolation:e};a.services.interpolator=new Kt(n)}return a.translator=new zt(a.services,i),a.translator.on(`*`,(e,...t)=>{a.emit(e,...t)}),a.init(i,n),a.translator.options=i,a.translator.backendConnector.services.utils={hasLoadedNamespace:a.hasLoadedNamespace.bind(a)},a}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}.createInstance();rn.createInstance,rn.dir,rn.init,rn.loadResources,rn.reloadResources,rn.use,rn.changeLanguage,rn.getFixedT,rn.t,rn.exists,rn.setDefaultNamespace,rn.hasLoadedNamespace,rn.loadNamespaces,rn.loadLanguages;var an=(e,t,n,r)=>{let i=[n,{code:t,...r||{}}];if(e?.services?.logger?.forward)return e.services.logger.forward(i,`warn`,`react-i18next::`,!0);fn(i[0])&&(i[0]=`react-i18next:: ${i[0]}`),e?.services?.logger?.warn?e.services.logger.warn(...i):console?.warn&&console.warn(...i)},on={},sn=(e,t,n,r)=>{fn(n)&&on[n]||(fn(n)&&(on[n]=new Date),an(e,t,n,r))},cn=(e,t)=>()=>{if(e.isInitialized)t();else{let n=()=>{setTimeout(()=>{e.off(`initialized`,n)},0),t()};e.on(`initialized`,n)}},ln=(e,t,n)=>{e.loadNamespaces(t,cn(e,n))},un=(e,t,n,r)=>{if(fn(n)&&(n=[n]),e.options.preload&&e.options.preload.indexOf(t)>-1)return ln(e,n,r);n.forEach(t=>{e.options.ns.indexOf(t)<0&&e.options.ns.push(t)}),e.loadLanguages(t,cn(e,r))},dn=(e,t,n={})=>!t.languages||!t.languages.length?(sn(t,`NO_LANGUAGES`,`i18n.languages were undefined or empty`,{languages:t.languages}),!0):t.hasLoadedNamespace(e,{lng:n.lng,precheck:(t,r)=>{if(n.bindI18n&&n.bindI18n.indexOf(`languageChanging`)>-1&&t.services.backendConnector.backend&&t.isLanguageChangingTo&&!r(t.isLanguageChangingTo,e))return!1}}),fn=e=>typeof e==`string`,pn=e=>typeof e==`object`&&!!e,mn=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,hn={"&":`&`,"&":`&`,"<":`<`,"<":`<`,">":`>`,">":`>`,"'":`'`,"'":`'`,""":`"`,""":`"`," ":` `," ":` `,"©":`©`,"©":`©`,"®":`®`,"®":`®`,"…":`…`,"…":`…`,"/":`/`,"/":`/`},gn=e=>hn[e],_n={bindI18n:`languageChanged`,bindI18nStore:``,transEmptyNodeValue:``,transSupportBasicHtmlNodes:!0,transWrapTextNodes:``,transKeepBasicHtmlNodesFor:[`br`,`strong`,`i`,`p`],useSuspense:!0,unescape:e=>e.replace(mn,gn),transDefaultProps:void 0},vn=()=>_n,yn,bn=()=>yn,xn=(0,m.createContext)(),Sn=class{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach(e=>{this.usedNamespaces[e]||(this.usedNamespaces[e]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}},Cn=o((e=>{var t=p();function n(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var r=typeof Object.is==`function`?Object.is:n,i=t.useState,a=t.useEffect,o=t.useLayoutEffect,s=t.useDebugValue;function c(e,t){var n=t(),r=i({inst:{value:n,getSnapshot:t}}),c=r[0].inst,u=r[1];return o(function(){c.value=n,c.getSnapshot=t,l(c)&&u({inst:c})},[e,n,t]),a(function(){return l(c)&&u({inst:c}),e(function(){l(c)&&u({inst:c})})},[e]),s(n),n}function l(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!r(e,n)}catch{return!0}}function u(e,t){return t()}var d=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?u:c;e.useSyncExternalStore=t.useSyncExternalStore===void 0?d:t.useSyncExternalStore})),wn=o(((e,t)=>{t.exports=Cn()}))(),Tn={t:(e,t)=>{if(fn(t))return t;if(pn(t)&&fn(t.defaultValue))return t.defaultValue;if(typeof e==`function`)return``;if(Array.isArray(e)){let t=e[e.length-1];return typeof t==`function`?``:t}return e},ready:!1},En=()=>()=>{},Dn=(e,t={})=>{let{i18n:n}=t,{i18n:r,defaultNS:i}=(0,m.useContext)(xn)||{},a=n||r||bn();a&&!a.reportNamespaces&&(a.reportNamespaces=new Sn),a||sn(a,`NO_I18NEXT_INSTANCE`,`useTranslation: You will need to pass in an i18next instance by using initReactI18next or by passing it via props or context. In monorepo setups, make sure there is only one instance of react-i18next.`);let o=(0,m.useMemo)(()=>({...vn(),...a?.options?.react,...t}),[a,t]),{useSuspense:s,keyPrefix:c}=o,l=e||i||a?.options?.defaultNS,u=fn(l)?[l]:l||[`translation`],d=(0,m.useMemo)(()=>u,u);a?.reportNamespaces?.addUsedNamespaces?.(d);let f=(0,m.useRef)(0),p=(0,m.useCallback)(e=>{if(!a)return En;let{bindI18n:t,bindI18nStore:n}=o,r=()=>{f.current+=1,e()};return t&&a.on(t,r),n&&a.store.on(n,r),()=>{t&&t.split(` `).forEach(e=>a.off(e,r)),n&&n.split(` `).forEach(e=>a.store.off(e,r))}},[a,o]),h=(0,m.useRef)(),g=(0,m.useCallback)(()=>{if(!a)return Tn;let e=!!(a.isInitialized||a.initializedStoreOnce)&&d.every(e=>dn(e,a,o)),n=t.lng||a.language,r=f.current,i=h.current;if(i&&i.ready===e&&i.lng===n&&i.keyPrefix===c&&i.revision===r)return i;let s={t:a.getFixedT(n,o.nsMode===`fallback`?d:d[0],c,{scopeNs:d}),ready:e,lng:n,keyPrefix:c,revision:r};return h.current=s,s},[a,d,c,o,t.lng]),[_,v]=(0,m.useState)(0),{t:y,ready:b}=(0,wn.useSyncExternalStore)(p,g,g);(0,m.useEffect)(()=>{if(a&&!b&&!s){let e=()=>v(e=>e+1);t.lng?un(a,t.lng,d,e):ln(a,d,e)}},[a,t.lng,d,b,s,_]);let x=a||{},S=(0,m.useRef)(null),C=(0,m.useRef)(),w=e=>{let t=Object.getOwnPropertyDescriptors(e);t.__original&&delete t.__original;let n=Object.create(Object.getPrototypeOf(e),t);if(!Object.prototype.hasOwnProperty.call(n,`__original`))try{Object.defineProperty(n,"__original",{value:e,writable:!1,enumerable:!1,configurable:!1})}catch{}return n},T=(0,m.useMemo)(()=>{let e=x,t=e?.language,n=e;e&&(S.current&&S.current.__original===e&&C.current===t?n=S.current:(n=w(e),S.current=n,C.current=t));let r=!b&&!s?(...e)=>(sn(a,`USE_T_BEFORE_READY`,`useTranslation: t was called before ready. When using useSuspense: false, make sure to check the ready flag before using t.`),y(...e)):y,i=[r,n,b];return i.t=r,i.i18n=n,i.ready=b,i},[y,x,b,x.resolvedLanguage,x.language,x.languages]);if(a&&s&&!b){let e=!1;try{e=!1}catch{}throw e&&sn(a,`SUSPENDED_WHILE_LOADING`,`useTranslation: suspended while translations are loading (useSuspense is true by default). Add a boundary above this component, or set react.useSuspense: false in the i18next init options. https://react.i18next.com/latest/usetranslation-hook`),new Promise(e=>{let n=()=>e();t.lng?un(a,t.lng,d,n):ln(a,d,n)})}return T};function On({i18n:e,defaultNS:t,children:n}){let r=(0,m.useMemo)(()=>({i18n:e,defaultNS:t}),[e,t]);return(0,m.createElement)(xn.Provider,{value:r},n)}var kn=[`getStatus`,`prepareSync`,`applySync`,`prepareSwitch`,`applySwitch`,`prepareRepair`,`applyRepair`,`listBackups`,`prepareRestore`,`applyRestore`,`pruneBackups`,`listHistory`,`getHistorySession`,`startWatch`,`stopWatch`,`getWatchStatus`,`getDiagnostics`],An=`INVALID_INPUT.PROFILE_CHANGED.STORAGE_CHANGED.PLAN_STALE.PLAN_EXPIRED.STALE_STATE.CODEX_HOME_NOT_FOUND.STATE_DB_NOT_FOUND.SQLITE_UNSUPPORTED_PATH.SQLITE_BUSY.SQLITE_UNREADABLE.ROLLOUT_LOCKED.ROLLOUT_CHANGED.ROLLOUT_METADATA_TOO_LARGE.ROLLOUT_METADATA_INVALID.PENDING_TRANSACTION.BACKUP_FAILED.SYNC_FAILED_ROLLED_BACK.RECOVERY_REQUIRED.RESTORE_VALIDATION_FAILED.PERMISSION_DENIED.OPERATION_BUSY.LOCK_UNVERIFIABLE.OPERATION_CANCELLED.CORE_RUNTIME_CRASHED.PROTOCOL_VERSION_MISMATCH.INTERNAL_ERROR`.split(`.`),jn=new Set([`prepare_config`,`prepare_storage`,`prepare_rollouts`,`prepare_status`,`prepare_revisions`,`prepare_usage`,`acquire_lock`,`read_config`,`resolve_storage`,`check_pending_restore`,`validate_plan`,`scan_rollout_files`,`check_locked_rollout_files`,`preflight_sqlite`,`create_backup`,`update_config`,`rewrite_rollout_files`,`update_sqlite`,`release_lock`]),Mn=new Set([`ENOENT`,`EACCES`,`EPERM`,`EIO`,`EBUSY`,`ENOSPC`,`EMFILE`,`ENFILE`,`ETIMEDOUT`,`SQLITE_BUSY`,`SQLITE_LOCKED`,`SQLITE_CORRUPT`,`SQLITE_NOTADB`,`ERR_SQLITE_ERROR`]),Nn=Object.freeze({INVALID_INPUT:`The command input is invalid.`,PROFILE_CHANGED:`The selected profile changed. Prepare the operation again.`,STORAGE_CHANGED:`The resolved storage changed. Prepare the operation again.`,PLAN_STALE:`The prepared operation is stale. Prepare it again.`,PLAN_EXPIRED:`The prepared operation expired. Prepare it again.`,STALE_STATE:`The protected state changed. Prepare the operation again.`,CODEX_HOME_NOT_FOUND:`The selected Codex Home was not found.`,STATE_DB_NOT_FOUND:`The selected state database was not found.`,SQLITE_UNSUPPORTED_PATH:`The selected SQLite path is not supported by this runtime.`,SQLITE_BUSY:`The state database is busy. Close Codex processes and retry.`,SQLITE_UNREADABLE:`The state database is unreadable or malformed.`,ROLLOUT_LOCKED:`One or more rollout files are locked.`,ROLLOUT_CHANGED:`One or more rollout files changed during the operation.`,ROLLOUT_METADATA_TOO_LARGE:`Session metadata must stay within 128 MiB before and after syncing. Resolve the oversized header before syncing again.`,ROLLOUT_METADATA_INVALID:`The first rollout record is not valid session metadata. Resolve the invalid header before syncing again.`,PENDING_TRANSACTION:`An unfinished transaction must be resolved before another write.`,BACKUP_FAILED:`The required backup could not be completed.`,SYNC_FAILED_ROLLED_BACK:`The operation failed and its changes were rolled back.`,RECOVERY_REQUIRED:`The operation requires explicit recovery.`,RESTORE_VALIDATION_FAILED:`The selected backup or restore target failed validation.`,PERMISSION_DENIED:`The operation does not have permission to access a required resource.`,OPERATION_BUSY:`Another write operation is using the protected resource.`,LOCK_UNVERIFIABLE:`The lock owner or protected resource identity cannot be verified.`,OPERATION_CANCELLED:`The operation was cancelled.`,CORE_RUNTIME_CRASHED:`The Core runtime stopped unexpectedly.`,PROTOCOL_VERSION_MISMATCH:`The client and Core protocol versions are incompatible.`,INTERNAL_ERROR:`An internal error occurred.`}),Pn=new Set([`PROFILE_CHANGED`,`STORAGE_CHANGED`,`PLAN_STALE`,`PLAN_EXPIRED`,`STALE_STATE`,`SQLITE_BUSY`,`ROLLOUT_LOCKED`,`ROLLOUT_CHANGED`,`OPERATION_BUSY`]),Fn=new Set([`PENDING_TRANSACTION`,`RECOVERY_REQUIRED`]),In=new Set([`codex-home`,`state-db`]),Ln=new Set([`profile`,`config`,`storage`,`rollout`,`state-db`,`provider-not-configured`,`windows-wsl-unc`]),Rn=new Set([`cli`,`config`,`env`,`default`]),zn=new Set([`sync`,`switch`,`repair`,`restore`,`prune-backups`,`watch`]),Bn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Vn=new Set(An);function Hn(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Un(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null?e:null}function Wn(e,t){if(!e)return;let n=Object.getOwnPropertyDescriptor(e,t);return n&&`value`in n?n.value:void 0}function Gn(e){return e===`OPERATION_CANCELLED`?`info`:e===`CORE_RUNTIME_CRASHED`||e===`INTERNAL_ERROR`?`fatal`:Pn.has(e)?`warning`:`error`}function Kn(e){let t=Un(e);if(!t)return;let n={},r=Wn(t,`busyScope`),i=Wn(t,`lockScope`),a=Wn(t,`causeCode`),o=Wn(t,`reason`),s=Wn(t,`missing`),c=Wn(t,`sqliteHomeSource`),l=Wn(t,`operationKind`),u=Wn(t,`failureStage`);In.has(String(r))&&(n.busyScope=String(r)),In.has(String(i))&&(n.lockScope=String(i)),Mn.has(String(a))&&(n.causeCode=String(a)),jn.has(String(u))&&(n.failureStage=String(u)),Ln.has(String(o))&&(n.reason=String(o)),(s===`config.toml`||s===`state_5.sqlite`)&&(n.missing=s),Rn.has(String(c))&&(n.sqliteHomeSource=String(c));for(let e of[`sqlitePrimaryCode`,`sqliteExtendedCode`]){let r=Wn(t,e);Number.isInteger(r)&&Number(r)>=0&&Number(r)<=65535&&(n[e]=Number(r))}return zn.has(String(l))&&(n.operationKind=String(l)),Object.keys(n).length>0?n:void 0}function qn(e,t={}){Vn.has(e)||(e=`INTERNAL_ERROR`);let n=Kn(t.details),r=n?Object.fromEntries(Object.entries(n).filter(([e])=>e===`failureStage`||e===`causeCode`)):void 0;if(e===`INTERNAL_ERROR`)return{code:e,message:Nn[e],severity:`fatal`,retryable:!1,recoveryRequired:!1,...typeof t.operationId==`string`&&Bn.test(t.operationId)?{operationId:t.operationId}:{},...r&&Object.keys(r).length>0?{details:r}:{}};if(e===`OPERATION_BUSY`&&n?.busyScope===void 0||e===`LOCK_UNVERIFIABLE`&&n?.lockScope===void 0)return qn(`INTERNAL_ERROR`);let i=typeof t.operationId==`string`&&Bn.test(t.operationId)?t.operationId:void 0;return{code:e,message:Nn[e],severity:Gn(e),retryable:e!==`ROLLOUT_METADATA_TOO_LARGE`&&e!==`ROLLOUT_METADATA_INVALID`,recoveryRequired:Fn.has(e),...i?{operationId:i}:{},...n?{details:n}:{}}}function Jn(e){let t=Hn(e),n=Wn(t,`code`);return qn(typeof n==`string`&&Vn.has(n)?n:`INTERNAL_ERROR`,{operationId:Wn(t,`operationId`),details:Wn(t,`details`)})}function Yn(e){let t=Un(e);if(!t)return!1;let n=Wn(t,`code`);if(typeof n!=`string`||!Vn.has(n))return!1;let r=Jn(t),i=Object.keys(t).sort(),a=Object.keys(r).sort();if(i.length!==a.length||i.some((e,t)=>e!==a[t]))return!1;for(let e of a)if(e!==`details`&&Wn(t,e)!==r[e])return!1;let o=Un(Wn(t,`details`)),s=r.details;if(s===void 0)return o===null;if(!o)return!1;let c=Object.keys(o).sort(),l=Object.keys(s).sort();return c.length===l.length&&c.every((e,t)=>e===l[t]&&Wn(o,e)===s[e])}var Xn=[`attemptedFiles`,`measuredFiles`,`inPlaceFiles`,`rewrittenFiles`,`skippedFiles`],Zn=[`totalMs`,`workerStartupMs`,`workerCloseMs`,`requestRoundTripMs`,`workerMs`,`sourceOpenMs`,`readHeaderMs`,`tempCreateMs`,`copyTailMs`,`flushMs`,`replaceMs`,`cleanupMs`,`restoreMtimeMs`],Qn=new Set([`schemaVersion`,`scope`,...Xn,...Zn]);function $n(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return t.schemaVersion!==1||t.scope!==`windows-first-line`||Object.keys(t).some(e=>!Qn.has(e))||!Xn.every(e=>Number.isSafeInteger(t[e])&&Number(t[e])>=0)||!Zn.every(e=>typeof t[e]==`number`&&Number.isFinite(t[e])&&Number(t[e])>=0)?!1:Number(t.measuredFiles)<=Number(t.attemptedFiles)&&Number(t.inPlaceFiles)+Number(t.rewrittenFiles)+Number(t.skippedFiles)<=Number(t.attemptedFiles)}var er=[`metadata-invalid`,`metadata-invalid-utf8`,`metadata-too-complex`,`metadata-too-large`,`locked`,`unreadable`,`missing`,`changed`,`write-not-applied`,`association-unknown`,`association-conflict`,`row-changed`,`row-missing`,`deferred`],tr=[`scan`,`plan`,`revalidate`,`write`,`sqlite`],nr=e=>!!e&&typeof e==`object`&&!Array.isArray(e),rr=e=>Number.isSafeInteger(e)&&Number(e)>=0,ir=new Set([`total`,`rolloutFiles`,`sqliteRows`,`unconfirmed`,`omitted`,`retryRecommended`,`items`]),ar=new Set([`kind`,`path`,`id`,`reason`,`stage`,`retryable`]);function or(e){return!nr(e)||Object.keys(e).some(e=>!ir.has(e))||![`total`,`rolloutFiles`,`sqliteRows`,`unconfirmed`,`omitted`].every(t=>rr(e[t]))||typeof e.retryRecommended!=`boolean`||!Array.isArray(e.items)||e.items.length>200||Number(e.total)!==Number(e.rolloutFiles)+Number(e.sqliteRows)||Number(e.total)!==e.items.length+Number(e.omitted)||new TextEncoder().encode(JSON.stringify(e)).length>1048576?!1:e.items.every(e=>nr(e)&&Object.keys(e).every(e=>ar.has(e))&&[`rollout`,`sqlite`].includes(String(e.kind))&&er.includes(e.reason)&&tr.includes(e.stage)&&typeof e.retryable==`boolean`&&(e.path===void 0||e.kind===`rollout`&&typeof e.path==`string`&&e.path.length>0&&e.path.length<=32768&&!/[\u0000-\u001f]/.test(e.path))&&(e.id===void 0||e.kind===`sqlite`&&typeof e.id==`string`&&/^[A-Za-z0-9_.:-]{1,128}$/.test(e.id)))}function sr(e){return or(e)?{...e,items:e.items.map(e=>({...e}))}:void 0}var cr=new Set(kn);new Set(An);var lr=[`models`,`cwd`,`userEvent`,`workspaceRoots`],ur=new Set(lr);function B(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function V(e){return typeof e==`string`&&e.length>0}function dr(e,t){let n=new Set(t);return Object.keys(e).every(e=>n.has(e))}function fr(e){if(!B(e)||!dr(e,[`profileId`,`profileRevision`])||typeof e.profileId!=`string`||!/^[A-Za-z0-9._-]{1,80}$/.test(e.profileId)||e.profileRevision!==void 0&&(!V(e.profileRevision)||e.profileRevision.length>512))throw new H(`INVALID_INPUT`,`Invalid profile selector.`)}function pr(e,t){if(!B(e)||!dr(e,[`profile`,...t]))throw new H(`INVALID_INPUT`,`Invalid Core method input.`);fr(e.profile)}var H=class extends Error{code;constructor(e,t){super(t),this.name=`ContractValidationError`,this.code=e}};function mr(e){if(e!==1)throw new H(`PROTOCOL_VERSION_MISMATCH`,`Unsupported Core protocol version: ${String(e)}.`)}function hr(e){if(!B(e)||Object.keys(e).sort().join(`,`)!==`planId,schemaVersion`||e.schemaVersion!==1||!V(e.planId))throw new H(`INVALID_INPUT`,`Apply accepts exactly { schemaVersion: 1, planId }.`)}function gr(e,t){switch(e){case`applySync`:case`applySwitch`:case`applyRepair`:case`applyRestore`:hr(t);return;case`getStatus`:case`listBackups`:case`getDiagnostics`:pr(t,[]);return;case`prepareSync`:if(pr(t,[`keepCount`]),t.keepCount!==void 0&&(!Number.isSafeInteger(t.keepCount)||Number(t.keepCount)<1))throw new H(`INVALID_INPUT`,`Invalid Sync retention count.`);return;case`prepareSwitch`:if(pr(t,[`provider`,`modelMode`,`model`,`keepCount`]),!V(t.provider)||![`provider-default`,`keep-root-model`,`explicit`].includes(String(t.modelMode))||t.modelMode===`explicit`&&!V(t.model)||t.modelMode!==`explicit`&&t.model!==void 0||t.keepCount!==void 0&&(!Number.isSafeInteger(t.keepCount)||Number(t.keepCount)<1))throw new H(`INVALID_INPUT`,`Invalid Switch Provider input.`);return;case`prepareRepair`:{pr(t,[`targets`,`keepCount`,`sessionIds`]);let e=Array.isArray(t.targets)?t.targets:[];if(e.length<1||e.length>lr.length||e.some(e=>typeof e!=`string`||!ur.has(e))||new Set(e).size!==e.length||t.sessionIds!==void 0&&(!Array.isArray(t.sessionIds)||t.sessionIds.length<1||t.sessionIds.length>100||t.sessionIds.some(e=>typeof e!=`string`||!/^[A-Za-z0-9_-]{1,128}$/.test(e))||new Set(t.sessionIds).size!==t.sessionIds.length||e.includes(`workspaceRoots`))||t.keepCount!==void 0&&(!Number.isSafeInteger(t.keepCount)||Number(t.keepCount)<1))throw new H(`INVALID_INPUT`,`Invalid Repair input.`);return}case`prepareRestore`:if(pr(t,[`backupId`,`restoreConfig`,`restoreDatabase`,`restoreSessions`,`allowSqliteHomeRelocation`,`relocationTargetProfileId`]),!V(t.backupId)||typeof t.restoreConfig!=`boolean`||typeof t.restoreDatabase!=`boolean`||typeof t.restoreSessions!=`boolean`||t.allowSqliteHomeRelocation!==void 0&&typeof t.allowSqliteHomeRelocation!=`boolean`||t.relocationTargetProfileId!==void 0&&(typeof t.relocationTargetProfileId!=`string`||!/^[A-Za-z0-9._-]{1,80}$/.test(t.relocationTargetProfileId))||t.allowSqliteHomeRelocation===!0&&(t.restoreConfig!==!1||t.relocationTargetProfileId===void 0)||t.relocationTargetProfileId!==void 0&&t.allowSqliteHomeRelocation!==!0)throw new H(`INVALID_INPUT`,`Invalid Restore input.`);return;case`pruneBackups`:if(pr(t,[`keepCount`]),!Number.isSafeInteger(t.keepCount)||Number(t.keepCount)<0)throw new H(`INVALID_INPUT`,`Invalid Prune retention count.`);return;case`listHistory`:if(pr(t,[`page`,`pageSize`,`query`,`project`,`provider`,`archived`,`searchScope`,`sessionKind`,`view`,`projectId`,`parentId`]),t.page!==void 0&&(!Number.isSafeInteger(t.page)||Number(t.page)<1)||t.pageSize!==void 0&&(!Number.isSafeInteger(t.pageSize)||Number(t.pageSize)<10||Number(t.pageSize)>100)||[`query`,`project`,`provider`,`projectId`,`parentId`].some(e=>t[e]!==void 0&&typeof t[e]!=`string`)||t.view!==void 0&&![`flat`,`projects`].includes(String(t.view))||t.projectId!==void 0&&!(/^[a-f0-9]{64}$/.test(String(t.projectId))||[`unassigned`,`orphans`].includes(String(t.projectId)))||t.parentId!==void 0&&(!V(t.parentId)||t.parentId.length>512)||t.searchScope!==void 0&&![`metadata`,`content`].includes(String(t.searchScope))||t.sessionKind!==void 0&&![`all`,`main`,`subagent`].includes(String(t.sessionKind))||t.archived!==void 0&&![`all`,`active`,`archived`].includes(String(t.archived)))throw new H(`INVALID_INPUT`,`Invalid History list input.`);return;case`getHistorySession`:if(pr(t,[`sessionId`,`messageLimit`,`metadataOnly`]),!V(t.sessionId)||t.metadataOnly!==void 0&&typeof t.metadataOnly!=`boolean`||t.messageLimit!==void 0&&(!Number.isSafeInteger(t.messageLimit)||Number(t.messageLimit)<1||Number(t.messageLimit)>200))throw new H(`INVALID_INPUT`,`Invalid History detail input.`);return;case`startWatch`:if(pr(t,[`includeStateDb`,`debounceMs`,`once`,`keepCount`]),t.includeStateDb!==void 0&&typeof t.includeStateDb!=`boolean`||t.once!==void 0&&typeof t.once!=`boolean`||t.debounceMs!==void 0&&(!Number.isSafeInteger(t.debounceMs)||Number(t.debounceMs)<0)||t.keepCount!==void 0&&(!Number.isSafeInteger(t.keepCount)||Number(t.keepCount)<1))throw new H(`INVALID_INPUT`,`Invalid Watch input.`);return;case`stopWatch`:if(!B(t)||!dr(t,[`watchId`])||!V(t.watchId))throw new H(`INVALID_INPUT`,`Invalid Watch reference.`);return;case`getWatchStatus`:if(!B(t)||!dr(t,[`profile`,`watchId`])||t.watchId!==void 0&&!V(t.watchId)||t.profile!==void 0&&t.watchId!==void 0)throw new H(`INVALID_INPUT`,`Invalid Watch status input.`);t.profile!==void 0&&fr(t.profile);return;default:throw new H(`INVALID_INPUT`,`Unknown Core method input.`)}}function _r(e){if(!Yn(e))throw new H(`INVALID_INPUT`,`Invalid public CoreErrorDto.`)}function vr(e){if(!B(e))throw new H(`INVALID_INPUT`,`Core request envelope must be an object.`);let t=new Set([`protocolVersion`,`requestId`,`operationId`,`method`,`payload`]);if(Object.keys(e).some(e=>!t.has(e)))throw new H(`INVALID_INPUT`,`Core request envelope has unknown fields.`);if(mr(e.protocolVersion),!V(e.requestId)||!V(e.method)||!cr.has(e.method)||!B(e.payload))throw new H(`INVALID_INPUT`,`Invalid Core request envelope.`);if(e.operationId!==void 0&&!V(e.operationId))throw new H(`INVALID_INPUT`,`Invalid Core request operationId.`);gr(e.method,e.payload)}function yr(e,t){if(!B(e))throw new H(`INVALID_INPUT`,`Core response envelope must be an object.`);let n=e.ok===!0?new Set([`protocolVersion`,`requestId`,`operationId`,`ok`,`result`]):new Set([`protocolVersion`,`requestId`,`operationId`,`ok`,`error`]);if(Object.keys(e).some(e=>!n.has(e)))throw new H(`INVALID_INPUT`,`Core response envelope has unknown fields.`);if(mr(e.protocolVersion),!V(e.requestId)||t!==void 0&&e.requestId!==t||typeof e.ok!=`boolean`)throw new H(`INVALID_INPUT`,`Invalid Core response envelope.`);if(e.operationId!==void 0&&!V(e.operationId))throw new H(`INVALID_INPUT`,`Invalid Core response operationId.`);if(e.ok){if(!(`result`in e)||`error`in e)throw new H(`INVALID_INPUT`,`Invalid successful Core response.`)}else{if(!(`error`in e)||`result`in e)throw new H(`INVALID_INPUT`,`Invalid failed Core response.`);_r(e.error)}}function br(e,t){if(!B(e)||e.schemaVersion!==1)throw new H(`INVALID_INPUT`,`Invalid ${t}.`);return e}function xr(e,t){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw new H(`INVALID_INPUT`,`Invalid ${t}.`)}function Sr(e){return Number.isSafeInteger(e)&&Number(e)>=0}function Cr(e){return e===null||typeof e==`string`}function wr(e,t=0){return t>16?!1:e===null||typeof e==`string`||typeof e==`boolean`?!0:typeof e==`number`?Number.isFinite(e):Array.isArray(e)?e.every(e=>wr(e,t+1)):B(e)?Object.values(e).every(e=>wr(e,t+1)):!1}function Tr(e){return B(e)?Object.values(e).every(e=>B(e)&&Object.values(e).every(Sr)):!1}var Er=new Set([`prepared`,`applying`,`applied`,`skipped`,`committing`,`committed-pending-ack`,`rollback-pending`,`rollingBack`,`recovery-required`,`recoveryRequired`,`unknown`]);function Dr(e){return typeof e==`string`&&/^[A-Za-z0-9._()-]{1,200}$/.test(e)}function Or(e){return typeof e==`string`&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}function kr(e){return!B(e)||Object.keys(e).length>512?!1:Object.entries(e).every(([e,t])=>Dr(e)&&Sr(t))}function Ar(e,t=!1){return!B(e)||!dr(e,t?[`sessions`,`archived_sessions`,`unreadable`]:[`sessions`,`archived_sessions`])||!(`sessions`in e)||!(`archived_sessions`in e)||!kr(e.sessions)||!kr(e.archived_sessions)?!1:!t||e.unreadable===void 0||e.unreadable===!0}function jr(e){return B(e)&&Object.keys(e).sort().join(`,`)===`operationId,operationKind,preRestoreSnapshotId,sourceBackupId,state`&&(e.operationId===null||Or(e.operationId))&&[`sync`,`switch`,`restore`].includes(String(e.operationKind))&&Er.has(String(e.state))&&(e.sourceBackupId===null||Dr(e.sourceBackupId))&&(e.preRestoreSnapshotId===null||Dr(e.preRestoreSnapshotId))}function Mr(e){return e===null?!0:!B(e)||!dr(e,[`operationId`,`operation`,`actor`,`startedAt`,`busyScope`,`lockState`,`errorCode`])?!1:(e.operationId===void 0||Or(e.operationId))&&(e.operation===void 0||[`sync`,`switch`,`repair`,`restore`,`prune`,`watch`,`unknown`].includes(String(e.operation)))&&(e.actor===void 0||[`manual`,`watch`,`external`].includes(String(e.actor)))&&(e.startedAt===void 0||V(e.startedAt)&&e.startedAt.length<=64)&&(e.busyScope===void 0||[`codex-home`,`state-db`].includes(String(e.busyScope)))&&(e.lockState===void 0||Dr(e.lockState)&&e.lockState.length<=80)&&(e.errorCode===void 0||typeof e.errorCode==`string`&&/^[A-Z0-9_]{1,80}$/.test(e.errorCode))}function Nr(e){if(!B(e)||!dr(e,[`version`,`outcome`,`issuesTruncated`,`counts`,`skipped`,`displayIndex`,`issues`,`limits`]))return!1;let t=[[`counts`,[`filesDiscovered`,`filesScanned`,`recordsRead`,`sessionsWithId`,`jsonCorruptRecords`,`oversizedRecords`,`duplicateOrdinals`,`outOfOrderOrdinals`,`changedFiles`,`truncatedFiles`,`unsupportedFiles`]],[`skipped`,[`symlinkOrReparse`,`outOfRoot`,`notRegular`,`unreadable`,`scanLimit`]],[`limits`,[`maxFiles`,`maxRecordsPerFile`,`maxLineBytes`,`maxIssues`]]],n=[`json-corrupt`,`record-too-large`,`ordinal-duplicate-observed`,`ordinal-out-of-order-observed`,`record-limit-reached`,`changed-during-scan`,`unterminated-record`,`unsupported-format`,`invalid-utf8`,`unverified`];return e.version===1&&[`no-findings`,`findings`,`inconclusive`,`findings-and-inconclusive`].includes(String(e.outcome))&&typeof e.issuesTruncated==`boolean`&&t.every(([t,n])=>{let r=e[t];return B(r)&&dr(r,[...n])&&n.every(e=>Sr(r[e]))})&&B(e.displayIndex)&&dr(e.displayIndex,[`status`,`reason`])&&e.displayIndex.status===`unsupported`&&e.displayIndex.reason===`no-known-display-index-schema`&&Array.isArray(e.issues)&&e.issues.length<=100&&e.issues.every(e=>B(e)&&dr(e,[`code`,`sessionId`,`scope`,`line`])&&n.includes(String(e.code))&&(e.sessionId===null||typeof e.sessionId==`string`&&/^[A-Za-z0-9_-]{1,128}$/.test(e.sessionId))&&[`sessions`,`archived_sessions`].includes(String(e.scope))&&(e.line===null||Sr(e.line)&&Number(e.line)>0))}function Pr(e){let t=br(e,`DiagnosticsSnapshot`),n=B(t.runtime)?t.runtime:null,r=B(t.storage)?t.storage:null,i=B(t.provider)?t.provider:null,a=B(t.issues)?t.issues:null,o=B(t.safety)?t.safety:null;if(!(dr(t,[`schemaVersion`,`generatedAt`,`runtime`,`storage`,`provider`,`issues`,`safety`,`historyIntegrity`])&&(t.historyIntegrity===void 0||Nr(t.historyIntegrity))&&V(t.generatedAt)&&t.generatedAt.length<=64&&n!==null&&Object.keys(n).sort().join(`,`)===`arch,node,platform`&&[n.node,n.platform,n.arch].every(e=>typeof e==`string`&&/^[A-Za-z0-9._-]{1,80}$/.test(e))&&r!==null&&Object.keys(r).sort().join(`,`)===`sqliteHomeSource,sqliteSupported,stateDbFound`&&[`cli`,`config`,`env`,`default`,`unknown`].includes(String(r.sqliteHomeSource))&&typeof r.stateDbFound==`boolean`&&typeof r.sqliteSupported==`boolean`&&i!==null&&Object.keys(i).sort().join(`,`)===`configured,current,implicit,rolloutCounts,sqliteCounts`&&Dr(i.current)&&typeof i.implicit==`boolean`&&Array.isArray(i.configured)&&i.configured.length<=256&&i.configured.every(Dr)&&Ar(i.rolloutCounts)&&(i.sqliteCounts===null||Ar(i.sqliteCounts,!0))&&a!==null&&Object.keys(a).sort().join(`,`)===`cwdRowsNeedingRepair,encryptedContentFiles,rolloutModelFilesNeedingRepair,rootModelAvailable,sqliteModelRowsNeedingRepair,userEventRowsNeedingRepair,workspaceRootsNeedingRepair`&&typeof a.rootModelAvailable==`boolean`&&[a.rolloutModelFilesNeedingRepair,a.sqliteModelRowsNeedingRepair,a.cwdRowsNeedingRepair,a.userEventRowsNeedingRepair,a.workspaceRootsNeedingRepair,a.encryptedContentFiles].every(Sr)&&o!==null&&dr(o,[`storageRevision`,`pendingRecovery`,`pendingTransactions`,`operationInProgress`,`rolloutScanComplete`,`lockedRolloutCount`,`projectThreadVisibilityAvailable`,...o.staleLockDetected===void 0?[]:[`staleLockDetected`]])&&(o.storageRevision===void 0||typeof o.storageRevision==`string`&&/^[A-Za-z0-9_-]{1,256}$/.test(o.storageRevision))&&typeof o.pendingRecovery==`boolean`&&Array.isArray(o.pendingTransactions)&&o.pendingTransactions.length<=256&&o.pendingTransactions.every(jr)&&Mr(o.operationInProgress)&&typeof o.rolloutScanComplete==`boolean`&&Sr(o.lockedRolloutCount)&&typeof o.projectThreadVisibilityAvailable==`boolean`&&(o.staleLockDetected===void 0||typeof o.staleLockDetected==`boolean`)))throw new H(`INVALID_INPUT`,`Invalid DiagnosticsSnapshot.`)}function Fr(e){return B(e)?V(e.id)&&typeof e.title==`string`&&(e.project===void 0||e.project===null||B(e.project)&&Object.keys(e.project).every(e=>[`id`,`name`].includes(e))&&typeof e.project.id==`string`&&(/^[a-f0-9]{64}$/.test(e.project.id)||[`unassigned`,`orphans`].includes(e.project.id))&&V(e.project.name)&&e.project.name.length<=160&&!/[\x00-\x1f\x7f]/.test(e.project.name))&&(e.nativeSessionId===void 0||e.nativeSessionId===null||V(e.nativeSessionId)&&e.nativeSessionId.length<=512)&&(e.parentSessionId===void 0||e.parentSessionId===null||V(e.parentSessionId)&&e.parentSessionId.length<=512)&&(e.sessionKind===void 0||[`main`,`subagent`].includes(String(e.sessionKind)))&&(e.childCount===void 0||Sr(e.childCount))&&(e.fileModifiedAt===void 0||V(e.fileModifiedAt))&&(e.subagentName===void 0||V(e.subagentName)&&e.subagentName.length<=160&&!/[\\/\x00-\x1f]/.test(e.subagentName))&&!(`cwd`in e)&&V(e.provider)&&typeof e.archived==`boolean`&&V(e.updatedAt)&&Sr(e.messageCount)&&(e.messageCountKnown===void 0||typeof e.messageCountKnown==`boolean`)&&(e.model===void 0||Cr(e.model))&&(e.createdAt===void 0||V(e.createdAt)):!1}function Ir(e){let t=br(e,`WatchSnapshot`);if(!V(t.watchId)||![`running`,`stopping`,`stopped`].includes(String(t.status))||!V(t.startedAt)||!Cr(t.stoppedAt)||!Cr(t.stopReason)||typeof t.includeStateDb!=`boolean`||typeof t.once!=`boolean`)throw new H(`INVALID_INPUT`,`Invalid WatchSnapshot.`)}function Lr(e){return B(e)&&Object.keys(e).sort().join(`,`)===`count,state`&&(e.state===`checked`?Sr(e.count):(e.state===`unavailable`||e.state===`unsupported`)&&e.count===null)}function Rr(e,t){switch(e){case`getStatus`:{let e=br(t,`StatusSnapshot`),n=B(e.profile)?e.profile:null,r=e=>typeof e==`string`&&e.length>0&&e.length<=32768&&!e.includes(`\0`)&&/^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(e),i=e.displayPaths,a=e.syncSessionUsage;if(!V(e.snapshotAt)||!V(e.storageRevision)||!n||!V(n.id)||!V(n.revision)||!V(e.currentProvider)||e.skipSummary!==void 0&&!or(e.skipSummary)||e.sessionActivity!==void 0&&!Lr(e.sessionActivity)||a!==void 0&&(!B(a)||Object.keys(a).sort().join(`,`)!==`count,state`||!(a.state===`checked`?Sr(a.count):(a.state===`unavailable`||a.state===`unsupported`)&&a.count===null))||!Tr(e.rolloutCounts)||e.modelCounts!==void 0&&!Tr(e.modelCounts)||!(`sqliteCounts`in e)||!wr(e.sqliteCounts)||`codexHome`in e||`sqliteHome`in e||i!==void 0&&(!B(i)||Object.keys(i).sort().join(`,`)!==`codexHome,sqliteHome,stateDbPath`||!r(i.codexHome)||!r(i.sqliteHome)||!(i.stateDbPath===null||r(i.stateDbPath)))||!V(e.codexHomeSource)||!V(e.sqliteHomeSource)||!B(e.backupSummary)||!Sr(e.backupSummary.count)||!Sr(e.backupSummary.totalBytes)||typeof e.pendingRecovery!=`boolean`||e.staleLockDetected!==void 0&&typeof e.staleLockDetected!=`boolean`||!Array.isArray(e.pendingTransactions)||e.pendingTransactions.some(e=>!B(e)||!wr(e))||!(e.operationInProgress===null||B(e.operationInProgress)&&wr(e.operationInProgress))||typeof e.rolloutScanComplete!=`boolean`||!Array.isArray(e.lockedRolloutFiles)||e.lockedRolloutFiles.some(e=>typeof e!=`string`)||e.currentModel!==void 0&&!Cr(e.currentModel))throw new H(`INVALID_INPUT`,`Invalid StatusSnapshot.`);return}case`prepareSync`:case`prepareSwitch`:case`prepareRepair`:case`prepareRestore`:{let n=br(t,`PlanSummary`),r=e===`prepareSync`?`sync`:e===`prepareSwitch`?`switch`:e===`prepareRepair`?`repair`:`restore`;if(!dr(n,[`schemaVersion`,`planId`,`operation`,`createdAt`,`expiresAt`,`profile`,`storageRevision`,`configRevision`,`rolloutRevision`,`stateDbRevision`,`target`,`impact`,`warnings`,`requiresConfirmation`,...n.backupRevision===void 0?[]:[`backupRevision`]])||!V(n.planId)||n.operation!==r||!V(n.createdAt)||!V(n.expiresAt)||!B(n.profile)||!V(n.profile.id)||!V(n.profile.revision)||!V(n.storageRevision)||!V(n.configRevision)||!V(n.rolloutRevision)||!V(n.stateDbRevision)||n.backupRevision!==void 0&&!V(n.backupRevision)||!B(n.target)||!wr(n.target)||!B(n.impact)||!wr(n.impact)||n.impact.skipSummary!==void 0&&!or(n.impact.skipSummary)||n.impact.sessionActivity!==void 0&&!Lr(n.impact.sessionActivity)||!Array.isArray(n.warnings)||n.warnings.some(e=>typeof e!=`string`)||typeof n.requiresConfirmation!=`boolean`)throw new H(`INVALID_INPUT`,`Invalid PlanSummary.`);return}case`applySync`:case`applySwitch`:case`applyRepair`:case`applyRestore`:{let n=br(t,`OperationResult`),r=e===`applySync`?`sync`:e===`applySwitch`?`switch`:e===`applyRepair`?`repair`:`restore`;if(!dr(n,[`schemaVersion`,`operationId`,`operation`,`outcome`,`backup`,`warnings`,`result`])||!V(n.operationId)||n.operation!==r||![`completed`,`partial`,`failed_rolled_back`,`recovery_required`,`cancelled`,`stale`].includes(String(n.outcome))||!(n.backup===null||B(n.backup)&&V(n.backup.backupId)))throw new H(`INVALID_INPUT`,`Invalid OperationResult.`);if(xr(n.warnings,`OperationResult warnings`),!(`result`in n)||!wr(n.result))throw new H(`INVALID_INPUT`,`OperationResult result is required.`);if(B(n.result)&&n.result.skipSummary!==void 0&&!or(n.result.skipSummary))throw new H(`INVALID_INPUT`,`Invalid skip summary.`);if(B(n.result)&&n.result.fileUpdateTiming!==void 0&&!$n(n.result.fileUpdateTiming))throw new H(`INVALID_INPUT`,`Invalid file update timing.`);return}case`listBackups`:if(!B(t)||!Array.isArray(t.backups)||t.backups.some(e=>{let t=B(e)?e:null;return!t||!V(t.backupId)||!Sr(t.sizeBytes)||!B(t.metadata)||!wr(t.metadata)||t.createdAt!==void 0&&!V(t.createdAt)}))throw new H(`INVALID_INPUT`,`Invalid BackupList.`);return;case`pruneBackups`:if(!B(t)||!Sr(t.deletedCount)||!Sr(t.remainingCount)||!Sr(t.freedBytes))throw new H(`INVALID_INPUT`,`Invalid PruneBackupsResult.`);return;case`listHistory`:if(!B(t)||!Number.isSafeInteger(t.page)||Number(t.page)<1||!Number.isSafeInteger(t.pageSize)||Number(t.pageSize)<1||!Sr(t.total)||typeof t.hasNextPage!=`boolean`||!Array.isArray(t.sessions)||t.sessions.some(e=>!Fr(e))||t.view!==void 0&&t.view!==`projects`||t.projects!==void 0&&(!Array.isArray(t.projects)||t.projects.some(e=>!B(e)||Object.keys(e).sort().join(`,`)!==`id,kind,name,total`||typeof e.id!=`string`||!(/^[a-f0-9]{64}$/.test(e.id)||[`unassigned`,`orphans`].includes(e.id))||!V(e.name)||e.name.length>160||![`workspace`,`directory`,`unassigned`,`orphans`].includes(String(e.kind))||!Sr(e.total)))||t.projectId!==void 0&&t.projectId!==null&&typeof t.projectId!=`string`)throw new H(`INVALID_INPUT`,`Invalid HistoryPage.`);return;case`getHistorySession`:if(!B(t)||!Fr(t.session)||t.storage!==void 0&&(!B(t.storage)||Object.keys(t.storage).some(e=>![`cwd`,`rolloutPath`].includes(e))||typeof t.storage.cwd!=`string`||t.storage.cwd.length>32768||!V(t.storage.rolloutPath)||t.storage.rolloutPath.length>32768||/[\x00]/.test(t.storage.cwd+t.storage.rolloutPath))||!Array.isArray(t.messages)||t.messages.some(e=>{let t=B(e)?e:null;return!t||!V(t.role)||typeof t.text!=`string`||!Sr(t.sequence)||t.timestamp!==void 0&&!V(t.timestamp)})||typeof t.truncated!=`boolean`||!Sr(t.returnedMessageCount)||Number(t.returnedMessageCount)!==t.messages.length)throw new H(`INVALID_INPUT`,`Invalid HistorySessionDetail.`);return;case`startWatch`:case`stopWatch`:Ir(t);return;case`getWatchStatus`:if(B(t)&&Array.isArray(t.watches)){br(t,`WatchStatusList`),t.watches.forEach(Ir);return}Ir(t);return;case`getDiagnostics`:Pr(t);return;default:throw new H(`INVALID_INPUT`,`Unknown Core method output.`)}}function zr(e){if(!B(e))throw new H(`INVALID_INPUT`,`Progress event must be an object.`);let t=new Set([`stage`,`status`,`progress`,`count`]);if(Object.keys(e).some(e=>!t.has(e))||!V(e.stage)||!V(e.status)||e.stage.length>80||e.status.length>40||e.progress!==void 0&&(typeof e.progress!=`number`||!Number.isFinite(e.progress)||e.progress<0||e.progress>1)||e.count!==void 0&&(!Number.isSafeInteger(e.count)||Number(e.count)<0))throw new H(`INVALID_INPUT`,`Invalid ProgressEvent.`)}function Br(e,t,n){if(!B(e)||!dr(e,[`protocolVersion`,`requestId`,`operationId`,`event`,`operation`])||(mr(e.protocolVersion),!V(e.requestId)||e.requestId.length>512||t!==void 0&&e.requestId!==t||!V(e.operationId)||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e.operationId)||n!==void 0&&e.operationId!==n||e.event!==`operation-started`||![`sync`,`switch`,`repair`,`restore`].includes(String(e.operation))))throw new H(`INVALID_INPUT`,`Invalid operation-started envelope.`)}function Vr(e,t,n){if(!B(e)||!dr(e,[`protocolVersion`,`requestId`,`operationId`,`event`,`progress`])||(mr(e.protocolVersion),!V(e.requestId)||e.requestId.length>512||t!==void 0&&e.requestId!==t||!V(e.operationId)||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e.operationId)||n!==void 0&&e.operationId!==n||e.event!==`progress`))throw new H(`INVALID_INPUT`,`Invalid Core progress envelope.`);zr(e.progress)}function Hr(e,t){if(!B(e)||!dr(e,[`protocolVersion`,`requestId`,`event`,`progress`])||(mr(e.protocolVersion),!V(e.requestId)||e.requestId.length>512||t!==void 0&&e.requestId!==t||e.event!==`request-progress`))throw new H(`INVALID_INPUT`,`Invalid Core request progress envelope.`);zr(e.progress)}function Ur(e,t,n){if(B(e)&&e.event===`operation-started`){Br(e,t,n);return}Vr(e,t,n)}function Wr(e,t,n,r){let i={protocolVersion:1,requestId:n,...r?{operationId:r}:{},method:e,payload:t};return vr(i),i}function Gr(e,t,n){return _r(t),{protocolVersion:1,requestId:e.requestId,...n??t.operationId??e.operationId?{operationId:n??t.operationId??e.operationId}:{},ok:!1,error:t}}var Kr=class extends Error{dto;code;constructor(e){_r(e),super(e.message),this.name=`CoreClientError`,this.dto=e,this.code=e.code}};function qr(){return globalThis.crypto?.randomUUID?.()??`request-${Date.now()}-${Math.random().toString(16).slice(2)}`}var Jr=class{#e;#t;constructor(e,{requestIdFactory:t=qr}={}){this.#e=e,this.#t=t}async#n(e,t,n={}){let r=n.requestId??this.#t(),i=Wr(e,t,r,n.operationId),a=await this.#e.request(i,{signal:n.signal,onOperationStarted:n.onOperationStarted,onProgress:n.onProgress,onRequestProgress:n.onRequestProgress});try{yr(a,r),a.ok&&Rr(e,a.result)}catch(e){throw e instanceof H?new Kr(qn(e.code===`PROTOCOL_VERSION_MISMATCH`?`PROTOCOL_VERSION_MISMATCH`:`INTERNAL_ERROR`)):e}if(!a.ok)throw new Kr(a.error);return a.result}getStatus(e,t){return this.#n(`getStatus`,e,t)}prepareSync(e,t){return this.#n(`prepareSync`,e,t)}applySync(e,t){return this.#n(`applySync`,e,t)}prepareSwitch(e,t){return this.#n(`prepareSwitch`,e,t)}applySwitch(e,t){return this.#n(`applySwitch`,e,t)}prepareRepair(e,t){return this.#n(`prepareRepair`,e,t)}applyRepair(e,t){return this.#n(`applyRepair`,e,t)}listBackups(e,t){return this.#n(`listBackups`,e,t)}prepareRestore(e,t){return this.#n(`prepareRestore`,e,t)}applyRestore(e,t){return this.#n(`applyRestore`,e,t)}pruneBackups(e,t){return this.#n(`pruneBackups`,e,t)}listHistory(e,t){return this.#n(`listHistory`,e,t)}getHistorySession(e,t){return this.#n(`getHistorySession`,e,t)}startWatch(e,t){return this.#n(`startWatch`,e,t)}stopWatch(e,t){return this.#n(`stopWatch`,e,t)}getWatchStatus(e,t){return this.#n(`getWatchStatus`,e,t)}getDiagnostics(e,t){return this.#n(`getDiagnostics`,e,t)}},Yr=Object.freeze([`getStatus`,`listBackups`,`listHistory`,`getHistorySession`,`getDiagnostics`]),Xr=Object.freeze([`prepareSync`,`applySync`,`prepareSwitch`,`applySwitch`,`prepareRepair`,`applyRepair`]),Zr=Object.freeze([`prepareRestore`,`applyRestore`]),Qr=Object.freeze([`pruneBackups`,`startWatch`,`stopWatch`,`getWatchStatus`]);Object.freeze([...Yr,...Xr,...Zr,...Qr]),new Set(Yr),new Set(Xr),new Set(Zr),new Set(Qr);function $r(e){return e===`prepareRepair`||e===`getDiagnostics`}var ei=`application/x-ndjson`;function ti(e,t){if(e)try{e(t)}catch{}}var ni=class extends Error{status;constructor(e,t=null){super(e),this.name=`CoreTransportError`,this.status=t}},ri=class{#e;#t;#n;#r;constructor({baseUrl:e,endpoint:t=`/api/core`,fetch:n=globalThis.fetch,headers:r={}}){if(typeof n!=`function`)throw TypeError(`HttpCoreTransport requires a Fetch implementation.`);this.#e=new URL(t,e),this.#t=new URL(`${t.replace(/\/$/,``)}/cancel`,e),this.#n=n,this.#r=Object.freeze({...r})}async request(e,t={}){let n=JSON.stringify(e);if(new TextEncoder().encode(n).byteLength>65536)throw new ni(`Core request exceeds the 64 KiB transport limit.`);let r=e.method===`applySync`||e.method===`applySwitch`||e.method===`applyRepair`||e.method===`applyRestore`,i=$r(e.method);if(t.signal?.aborted){if(r)return Gr(e,qn(`OPERATION_CANCELLED`));throw new DOMException(`The Core HTTP request was cancelled.`,`AbortError`)}let a,o=!1,s=()=>{o=!0,this.#n(this.#t,{method:`POST`,credentials:`same-origin`,redirect:`error`,headers:{"Content-Type":`application/json`,...this.#r},body:JSON.stringify({protocolVersion:e.protocolVersion,requestId:e.requestId,...a?{operationId:a}:{}})}).catch(()=>void 0)},c=r||i?s:void 0;c&&t.signal?.addEventListener(`abort`,c,{once:!0});let l;try{l=await this.#n(this.#e,{method:`POST`,credentials:`same-origin`,redirect:`error`,headers:{"Content-Type":`application/json`,Accept:ei,...this.#r},body:n,signal:r||i?void 0:t.signal})}catch{throw c&&t.signal?.removeEventListener(`abort`,c),new ni(`Core HTTP request failed.`)}if((l.headers.get(`content-type`)?.toLowerCase()??``).startsWith(ei))try{let n=await this.#i(l,e,t,{get operationId(){return a},set operationId(e){a=e},get cancellationRequested(){return o},requestCancellation:s});if(!l.ok&&typeof n==`object`&&n&&!Array.isArray(n)&&`ok`in n&&n.ok===!0)throw new ni(`Core HTTP request failed.`,l.status);return n}finally{c&&t.signal?.removeEventListener(`abort`,c)}let u;try{u=await l.json()}catch{throw c&&t.signal?.removeEventListener(`abort`,c),new ni(`Core HTTP response was not valid JSON.`,l.status)}if(c&&t.signal?.removeEventListener(`abort`,c),!l.ok&&(typeof u!=`object`||!u||Array.isArray(u)||!(`ok`in u)||u.ok!==!1))throw new ni(`Core HTTP request failed.`,l.status);return u}async#i(e,t,n,r){if(!e.body)throw new ni(`Core HTTP stream has no body.`,e.status);let i=t.method===`applySync`||t.method===`applySwitch`||t.method===`applyRepair`||t.method===`applyRestore`,a=$r(t.method),o=t.method===`applySync`?`sync`:t.method===`applySwitch`?`switch`:t.method===`applyRepair`?`repair`:t.method===`applyRestore`?`restore`:null,s=e.body.getReader(),c=new TextDecoder,l=``,u=0,d,f=s=>{if(!s.trim())return;if(d!==void 0)throw new ni(`Core HTTP stream contained data after its terminal envelope.`,e.status);let c;try{c=JSON.parse(s)}catch{throw new ni(`Core HTTP stream contained invalid JSON.`,e.status)}if(typeof c==`object`&&c&&!Array.isArray(c)&&`event`in c){if(c.event===`request-progress`){if(!a)throw new ni(`Core HTTP stream contained request progress for an unsupported method.`,e.status);try{Hr(c,t.requestId)}catch{throw new ni(`Core HTTP stream contained invalid request progress.`,e.status)}ti(n.onRequestProgress,c),r.cancellationRequested&&r.requestCancellation();return}if(!i)throw new ni(`Core HTTP read stream contained an operation event.`,e.status);let s=`event`in c?c.event:void 0;if(r.operationId===void 0&&s!==`operation-started`)throw new ni(`Core HTTP stream emitted progress before operation-started.`,e.status);if(r.operationId!==void 0&&s===`operation-started`)throw new ni(`Core HTTP stream emitted multiple operation-started events.`,e.status);try{Ur(c,t.requestId,r.operationId)}catch{throw new ni(`Core HTTP stream contained an invalid operation event.`,e.status)}let l=c;if(l.event===`operation-started`&&l.operation!==o)throw new ni(`Core HTTP stream started the wrong operation.`,e.status);r.operationId=l.operationId,l.event===`operation-started`?ti(n.onOperationStarted,l):ti(n.onProgress,l),r.cancellationRequested&&r.requestCancellation();return}try{yr(c,t.requestId)}catch{throw new ni(`Core HTTP stream contained an invalid terminal envelope.`,e.status)}let l=c,u=r.operationId;if(u!==void 0){if(l.operationId!==u||!l.ok&&l.error.operationId!==void 0&&l.error.operationId!==u)throw new ni(`Core HTTP stream terminal operationId did not match its lifecycle.`,e.status)}else if(i&&l.operationId!==void 0)throw new ni(`Core HTTP stream ended an unannounced operation.`,e.status);if(l.ok){try{Rr(t.method,l.result)}catch{throw new ni(`Core HTTP stream contained an invalid terminal result.`,e.status)}if(i){if(u===void 0)throw new ni(`Core HTTP apply stream ended without operation-started.`,e.status);if(l.result.operationId!==u)throw new ni(`Core HTTP stream result operationId did not match its lifecycle.`,e.status)}}d=l};for(;;){let{value:t,done:n}=await s.read();if(n)break;if(u+=t.byteLength,u>16777216)throw await s.cancel(),new ni(`Core HTTP stream exceeded its response limit.`,e.status);l+=c.decode(t,{stream:!0});let r;for(;(r=l.indexOf(` +`))>=0;)f(l.slice(0,r)),l=l.slice(r+1)}if(l+=c.decode(),f(l),d===void 0)throw new ni(`Core HTTP stream ended without a terminal envelope.`,e.status);return d}},ii=class extends Jr{constructor(e){super(new ri(e),{requestIdFactory:e.requestIdFactory})}},ai=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim(),oi=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),si=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()),ci=e=>{let t=si(e);return t.charAt(0).toUpperCase()+t.slice(1)},li={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`},ui=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0;return!1},di=(0,m.createContext)({}),fi=()=>(0,m.useContext)(di),pi=(0,m.forwardRef)(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:i=``,children:a,iconNode:o,...s},c)=>{let{size:l=24,strokeWidth:u=2,absoluteStrokeWidth:d=!1,color:f=`currentColor`,className:p=``}=fi()??{},h=r??d?Number(n??u)*24/Number(t??l):n??u;return(0,m.createElement)(`svg`,{ref:c,...li,width:t??l??li.width,height:t??l??li.height,stroke:e??f,strokeWidth:h,className:ai(`lucide`,p,i),...!a&&!ui(s)&&{"aria-hidden":`true`},...s},[...o.map(([e,t])=>(0,m.createElement)(e,t)),...Array.isArray(a)?a:[a]])}),U=(e,t)=>{let n=(0,m.forwardRef)(({className:n,...r},i)=>(0,m.createElement)(pi,{ref:i,iconNode:t,className:ai(`lucide-${oi(ci(e))}`,`lucide-${e}`,n),...r}));return n.displayName=ci(e),n},mi=U(`activity`,[[`path`,{d:`M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2`,key:`169zse`}]]),hi=U(`archive-restore`,[[`rect`,{width:`20`,height:`5`,x:`2`,y:`3`,rx:`1`,key:`1wp1u1`}],[`path`,{d:`M4 8v11a2 2 0 0 0 2 2h2`,key:`tvwodi`}],[`path`,{d:`M20 8v11a2 2 0 0 1-2 2h-2`,key:`1gkqxj`}],[`path`,{d:`m9 15 3-3 3 3`,key:`1pd0qc`}],[`path`,{d:`M12 12v9`,key:`192myk`}]]),gi=U(`archive`,[[`rect`,{width:`20`,height:`5`,x:`2`,y:`3`,rx:`1`,key:`1wp1u1`}],[`path`,{d:`M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8`,key:`1s80jp`}],[`path`,{d:`M10 12h4`,key:`a56b0p`}]]),_i=U(`arrow-left`,[[`path`,{d:`m12 19-7-7 7-7`,key:`1l729n`}],[`path`,{d:`M19 12H5`,key:`x3x0zl`}]]),vi=U(`check`,[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]),yi=U(`chevron-down`,[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]),bi=U(`chevron-right`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]),xi=U(`circle-check`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),Si=U(`copy`,[[`rect`,{width:`14`,height:`14`,x:`8`,y:`8`,rx:`2`,ry:`2`,key:`17jyea`}],[`path`,{d:`M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2`,key:`zix9uf`}]]),Ci=U(`database`,[[`ellipse`,{cx:`12`,cy:`5`,rx:`9`,ry:`3`,key:`msslwz`}],[`path`,{d:`M3 5V19A9 3 0 0 0 21 19V5`,key:`1wlel7`}],[`path`,{d:`M3 12A9 3 0 0 0 21 12`,key:`mv7ke4`}]]),wi=U(`earth`,[[`path`,{d:`M21.54 15H17a2 2 0 0 0-2 2v4.54`,key:`1djwo0`}],[`path`,{d:`M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17`,key:`1tzkfa`}],[`path`,{d:`M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05`,key:`14pb5j`}],[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}]]),Ti=U(`file-clock`,[[`path`,{d:`M16 22h2a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v2.85`,key:`ryk6xj`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M8 14v2.2l1.6 1`,key:`6m4bie`}],[`circle`,{cx:`8`,cy:`16`,r:`6`,key:`10v15b`}]]),Ei=U(`folder-cog`,[[`path`,{d:`M10.3 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.98a2 2 0 0 1 1.69.9l.66 1.2A2 2 0 0 0 12 6h8a2 2 0 0 1 2 2v3.3`,key:`128dxu`}],[`path`,{d:`m14.305 19.53.923-.382`,key:`3m78fa`}],[`path`,{d:`m15.228 16.852-.923-.383`,key:`npixar`}],[`path`,{d:`m16.852 15.228-.383-.923`,key:`5xggr7`}],[`path`,{d:`m16.852 20.772-.383.924`,key:`dpfhf9`}],[`path`,{d:`m19.148 15.228.383-.923`,key:`1reyyz`}],[`path`,{d:`m19.53 21.696-.382-.924`,key:`1goivc`}],[`path`,{d:`m20.772 16.852.924-.383`,key:`htqkph`}],[`path`,{d:`m20.772 19.148.924.383`,key:`9w9pjp`}],[`circle`,{cx:`18`,cy:`18`,r:`3`,key:`1xkwt0`}]]),Di=U(`folder-open`,[[`path`,{d:`m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2`,key:`usdka0`}]]),Oi=U(`folder`,[[`path`,{d:`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`,key:`1kt360`}]]),ki=U(`gauge`,[[`path`,{d:`m12 14 4-4`,key:`9kzdfg`}],[`path`,{d:`M3.34 19a10 10 0 1 1 17.32 0`,key:`19p75a`}]]),Ai=U(`git-branch`,[[`path`,{d:`M15 6a9 9 0 0 0-9 9V3`,key:`1cii5b`}],[`circle`,{cx:`18`,cy:`6`,r:`3`,key:`1h7g24`}],[`circle`,{cx:`6`,cy:`18`,r:`3`,key:`fqmcym`}]]),ji=U(`info`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 16v-4`,key:`1dtifu`}],[`path`,{d:`M12 8h.01`,key:`e9boi3`}]]),Mi=U(`languages`,[[`path`,{d:`m5 8 6 6`,key:`1wu5hv`}],[`path`,{d:`m4 14 6-6 2-3`,key:`1k1g8d`}],[`path`,{d:`M2 5h12`,key:`or177f`}],[`path`,{d:`M7 2h1`,key:`1t2jsx`}],[`path`,{d:`m22 22-5-10-5 10`,key:`don7ne`}],[`path`,{d:`M14 18h6`,key:`1m8k6r`}]]),Ni=U(`message-square`,[[`path`,{d:`M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z`,key:`18887p`}]]),Pi=U(`moon`,[[`path`,{d:`M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401`,key:`kfwtm`}]]),Fi=U(`play`,[[`path`,{d:`M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z`,key:`10ikf1`}]]),Ii=U(`refresh-cw`,[[`path`,{d:`M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8`,key:`v9h5vc`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}],[`path`,{d:`M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16`,key:`3uifl3`}],[`path`,{d:`M8 16H3v5`,key:`1cv678`}]]),Li=U(`rotate-ccw-clock`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}],[`path`,{d:`M12 7v5l4 2`,key:`1fdv2h`}]]),Ri=U(`rotate-ccw`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}]]),zi=U(`scroll-text`,[[`path`,{d:`M15 12h-5`,key:`r7krc0`}],[`path`,{d:`M15 8h-5`,key:`1khuty`}],[`path`,{d:`M19 17V5a2 2 0 0 0-2-2H4`,key:`zz82l3`}],[`path`,{d:`M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3`,key:`1ph1d7`}]]),Bi=U(`search`,[[`path`,{d:`m21 21-4.34-4.34`,key:`14j7rj`}],[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}]]),Vi=U(`settings`,[[`path`,{d:`M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915`,key:`1i5ecw`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),Hi=U(`shield-alert`,[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`M12 8v4`,key:`1got3b`}],[`path`,{d:`M12 16h.01`,key:`1drbdi`}]]),Ui=U(`sun`,[[`circle`,{cx:`12`,cy:`12`,r:`4`,key:`4exip2`}],[`path`,{d:`M12 2v2`,key:`tus03m`}],[`path`,{d:`M12 20v2`,key:`1lh1kg`}],[`path`,{d:`m4.93 4.93 1.41 1.41`,key:`149t6j`}],[`path`,{d:`m17.66 17.66 1.41 1.41`,key:`ptbguv`}],[`path`,{d:`M2 12h2`,key:`1t8f8n`}],[`path`,{d:`M20 12h2`,key:`1q8mjw`}],[`path`,{d:`m6.34 17.66-1.41 1.41`,key:`1m8zz5`}],[`path`,{d:`m19.07 4.93-1.41 1.41`,key:`1shlcs`}]]),Wi=U(`terminal`,[[`path`,{d:`M12 19h8`,key:`baeox8`}],[`path`,{d:`m4 17 6-6-6-6`,key:`1yngyt`}]]),Gi=U(`triangle-alert`,[[`path`,{d:`m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3`,key:`wmoenq`}],[`path`,{d:`M12 9v4`,key:`juzpu7`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),Ki=U(`workflow`,[[`rect`,{width:`8`,height:`8`,x:`3`,y:`3`,rx:`2`,key:`by2w9f`}],[`path`,{d:`M7 11v4a2 2 0 0 0 2 2h4`,key:`xkn7yn`}],[`rect`,{width:`8`,height:`8`,x:`13`,y:`13`,rx:`2`,key:`1cgmvn`}]]),qi=U(`wrench`,[[`path`,{d:`M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z`,key:`1ngwbx`}]]),Ji=U(`x`,[[`path`,{d:`M18 6 6 18`,key:`1bl5f8`}],[`path`,{d:`m6 6 12 12`,key:`d8bk6v`}]]),Yi=e=>e.type===`checkbox`,Xi=e=>e.type===`file`,Zi=e=>e instanceof Date,Qi=e=>e==null,$i=e=>typeof e==`object`,ea=e=>!Qi(e)&&!Array.isArray(e)&&$i(e)&&!Zi(e),ta=e=>ea(e)&&e.target?Yi(e.target)?e.target.checked:Xi(e.target)?e.target.files:e.target.value:e,na=(e,t)=>t.split(`.`).some((t,n,r)=>!isNaN(Number(t))&&e.has(r.slice(0,n).join(`.`))),ra=typeof window<`u`&&window.HTMLElement!==void 0&&typeof document<`u`;function ia(e){if(typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e);let t=typeof FileList<`u`&&e instanceof FileList;if(ra&&(e instanceof Blob||t))return e;let n=Array.isArray(e);if(!n&&e.constructor!==Object)return e;let r=n?[]:Object.create(Object.getPrototypeOf(e));for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&(r[t]=ia(e[t]));return r}var aa={BLUR:`blur`,FOCUS_OUT:`focusout`,CHANGE:`change`,SUBMIT:`submit`,TRIGGER:`trigger`,VALID:`valid`},oa={onBlur:`onBlur`,onChange:`onChange`,onSubmit:`onSubmit`,onTouched:`onTouched`,all:`all`},sa={max:`max`,min:`min`,maxLength:`maxLength`,minLength:`minLength`,pattern:`pattern`,required:`required`,validate:`validate`},ca=`root`,la=[`__proto__`,`constructor`,`prototype`],ua=/^\w*$/,da=e=>ua.test(e),fa=e=>e===void 0,pa=/[.[\]'"]/,ma=e=>e.split(pa).filter(Boolean),W=(e,t,n)=>{if(!t||!ea(e))return n;let r=da(t)?[t]:ma(t);if(r.some(e=>la.includes(e)))return n;let i=r.reduce((e,t)=>Qi(e)?void 0:e[t],e);return fa(i)||i===e?fa(e[t])?n:e[t]:i},ha=e=>typeof e==`boolean`,ga=e=>typeof e==`function`,_a=(e,t,n)=>{let r=-1,i=da(t)?[t]:ma(t),a=i.length,o=a-1;for(;++r{let i={};for(let a in e)Object.defineProperty(i,a,{get:()=>{let i=a;return t._proxyFormState[i]!==oa.all&&(t._proxyFormState[i]=!r||oa.all),n&&(n[i]=!0),e[i]}});return i},ba=ra?m.useLayoutEffect:m.useEffect,xa=e=>{let t=e.constructor&&e.constructor.prototype;return ea(t)&&t.hasOwnProperty(`isPrototypeOf`)},Sa=e=>Qi(e)||!$i(e),Ca=(e,t)=>t.length===0&&!Array.isArray(e)&&!xa(e);function wa(e,t,n=new WeakMap){if(e===t)return!0;if(Sa(e)||Sa(t))return Object.is(e,t);if(Zi(e)&&Zi(t))return Object.is(e.getTime(),t.getTime());let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;if(Ca(e,r)||Ca(t,i))return Object.is(e,t);if(!r.length&&Array.isArray(e)!==Array.isArray(t))return!1;let a=n.get(e);if(a&&a.has(t))return!0;if(a)a.add(t);else{let r=new WeakSet;r.add(t),n.set(e,r)}for(let i of r){let r=e[i];if(!(i in t))return!1;if(i!==`ref`){let e=t[i];if(Zi(r)&&Zi(e)||(ea(r)||Array.isArray(r))&&(ea(e)||Array.isArray(e))?!wa(r,e,n):!Object.is(r,e))return!1}}return!0}function Ta(){let e=m.useRef(!1),t=m.useRef(void 0);return{resyncIfNeeded:m.useCallback((n,r,i)=>{if(n&&e.current){let e=r();wa(t.current,e)||i(e)}e.current=!0},[]),snapshot:m.useCallback((e,n)=>{e&&(t.current=ia(n()))},[])}}var Ea=e=>typeof e==`string`,Da=(e,t,n,r,i)=>Ea(e)?(r&&t.watch.add(e),W(n,e,i)):Array.isArray(e)?e.map(e=>(r&&t.watch.add(e),W(n,e))):(r&&(t.watchAll=!0),n),Oa=e=>({isOnSubmit:!e||e===oa.onSubmit,isOnBlur:e===oa.onBlur,isOnChange:e===oa.onChange,isOnAll:e===oa.all,isOnTouch:e===oa.onTouched}),ka=(e,t,n)=>{if(n)return!1;if(t.watchAll||t.watch.has(e))return!0;for(let n of t.watch)if(e.startsWith(n)&&e.charAt(n.length)===`.`)return!0;return!1},Aa=(e,t,n,r)=>{for(let i of n||Object.keys(e)){if(i===`_f`)continue;let a=n?W(e,i):e[i];if(a){let{_f:e}=a;if(e){if(e.refs&&e.refs[0]&&t(e.refs[0],i)&&!r||e.ref&&t(e.ref,e.name)&&!r)return!0;if(Aa(a,t))break}else if((ea(a)||Array.isArray(a))&&Aa(a,t))break}}},ja=(e,t,n)=>{let r=W(e,n),i=Array.isArray(r)?r:[];return _a(i,ca,t[n]),_a(e,n,i),e},Ma=e=>ea(e)&&!Object.keys(e).length,Na=e=>{if(!ra)return!1;let t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Pa=e=>e.type===`radio`,Fa=e=>e instanceof RegExp,Ia=(e,t,n,r,i)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:i||!0}}:{},La={value:!1,isValid:!1},Ra={value:!0,isValid:!0},za=e=>{if(!Array.isArray(e))return La;if(e.length>1){let t=e.filter(e=>e&&e.checked&&!e.disabled).map(e=>e.value);return{value:t,isValid:!!t.length}}let t=e[0];return!t||!t.checked||t.disabled?La:!t.attributes||!(`value`in t.attributes)||fa(t.value)||t.value===``?Ra:{value:t.value,isValid:!0}},Ba={isValid:!1,value:null},Va=e=>Array.isArray(e)?e.reduce((e,t)=>t&&t.checked&&!t.disabled?{isValid:!0,value:t.value}:e,Ba):Ba;function Ha(e,t,n=`validate`){if(Ea(e)||Array.isArray(e)&&e.every(Ea)||ha(e)&&!e)return{type:n,message:Ea(e)?e:``,ref:t}}var Ua=e=>ea(e)&&!Fa(e)?e:{value:e,message:``},Wa=async(e,t,n,r,i,a)=>{let{ref:o,refs:s,required:c,maxLength:l,minLength:u,min:d,max:f,pattern:p,validate:m,name:h,valueAsNumber:g,mount:_}=e._f,v=W(n,h);if(!_||t.has(h))return{};let y=s?s[0]:o,b=e=>{if(i&&y.reportValidity){let t=ha(e)?``:e||``;s?s.forEach(e=>e.setCustomValidity(t)):y.setCustomValidity(t),y.reportValidity()}},x={},S=Pa(o),C=Yi(o),w=S||C,T=(g||Xi(o))&&fa(o.value)&&fa(v)||Na(o)&&o.value===``||v===``||Array.isArray(v)&&!v.length,E=Ia.bind(null,h,r,x),D=(e,t,n,r=sa.maxLength,i=sa.minLength)=>{let a=e?t:n;x[h]={type:e?r:i,message:a,ref:o,...E(e?r:i,a)}};if(a?!Array.isArray(v)||!v.length:c&&(!w&&(T||Qi(v))||ha(v)&&!v||C&&!za(s).isValid||S&&!Va(s).isValid)){let{value:e,message:t}=Ea(c)?{value:!!c,message:c}:Ua(c);if(e&&(x[h]={type:sa.required,message:t,ref:y,...E(sa.required,t)},!r))return b(t),x}if(!T&&(!Qi(d)||!Qi(f))){let e,t,n=Ua(f),i=Ua(d);if(!Qi(v)&&!Zi(v)&&!isNaN(v)){let r=o.valueAsNumber||v&&+v;Qi(n.value)||(e=r>n.value),Qi(i.value)||(t=rnew Date(new Date().toDateString()+` `+e),s=o.type==`time`,c=o.type==`week`;Ea(n.value)&&v&&(e=s?a(v)>a(n.value):c?v>n.value:r>new Date(n.value)),Ea(i.value)&&v&&(t=s?a(v)+e.value,i=!Qi(t.value)&&v.length<+t.value;if((n||i)&&(D(n,e.message,t.message),!r))return b(x[h].message),x}if(p&&!T&&Ea(v)){let{value:e,message:t}=Ua(p);if(Fa(e)&&!v.match(e)&&(x[h]={type:sa.pattern,message:t,ref:o,...E(sa.pattern,t)},!r))return b(t),x}if(m){if(ga(m)){let e=Ha(await m(v,n),y);if(e&&(x[h]={...e,...E(sa.validate,e.message)},!r))return b(e.message),x}else if(ea(m)){let e={};for(let t in m){if(!Ma(e)&&!r)break;let i=Ha(await m[t](v,n),y,t);i&&(e={...i,...E(t,i.message)},b(i.message),r&&(x[h]=e))}if(!Ma(e)&&(x[h]={ref:y,...e},!r))return x}}let O=x[h];return b(!O||O.message),x},Ga=e=>Array.isArray(e)?e:[e],Ka=e=>Array.isArray(e)?e.filter(Boolean):[];function qa(e,t){let n=t.length-1,r=0;for(;rla.includes(String(e))))return e;let r=n.length===1?e:qa(e,n),i=n.length-1,a=n[i];return r&&delete r[a],i!==0&&(ea(r)&&Ma(r)||Array.isArray(r)&&Ja(r))&&Ya(e,n.slice(0,-1)),e}var Xa=m.createContext(null);Xa.displayName=`HookFormContext`;var Za=()=>{let e=[];return{get observers(){return e},next:t=>{for(let n of e)n.next&&n.next(t)},subscribe:t=>(e.push(t),{unsubscribe:()=>{e=e.filter(e=>e!==t)}}),unsubscribe:()=>{e=[]}}};function Qa(e,t){let n={};for(let r in e)if(e.hasOwnProperty(r)){let i=e[r],a=t[r];if(i&&ea(i)&&a){let e=Qa(i,a);ea(e)&&(n[r]=e)}else e[r]&&(n[r]=a)}return n}var $a=(e,t)=>e!==null&&$i(e)&&Object.prototype.hasOwnProperty.call(e,t),eo=(e,t)=>{if(!t)return!1;let n=e;for(let r of da(t)?[t]:ma(t)){if(!$a(n,r))return $a(e,t);n=n[r]}return!0},to=e=>e.type===`select-multiple`,no=e=>Pa(e)||Yi(e),ro=e=>Na(e)&&e.isConnected;function io(e){return Array.isArray(e)||ea(e)}function ao(e,t,n=``,r=[]){for(let i in e){let a=n?`${n}.${i}`:i,o=e[i];io(o)&&io(W(t,a))?ao(o,t,a,r):r.push(a)}return r}var G=e=>{for(let t in e)if(ga(e[t]))return!0;return!1};function oo(e){return Array.isArray(e)||ea(e)&&!G(e)}function so(e){return!!(e&&`_f`in e)}function co(e){return Array.isArray(e)?!e.some(e=>!fa(e)):!Object.keys(e).length}function lo(e,t){Array.isArray(e)?e[t]=void 0:delete e[t]}function uo(e,t={},n){for(let r in e){let i=e[r],a=n&&n[r];oo(i)&&(!Array.isArray(i)||!so(a))?(t[r]=Array.isArray(i)?[]:{},uo(i,t[r],a),co(t[r])&&lo(t,r)):fa(i)||(t[r]=!0)}return t}function fo(e,t,n,r){n||=uo(t,{},r);for(let i in e){let a=e[i],o=r&&r[i];oo(a)&&(!Array.isArray(a)||!so(o))?(fa(t)||Sa(n[i])?n[i]=uo(a,Array.isArray(a)?[]:{},o):fo(a,Qi(t)?{}:t[i],n[i],o),co(n[i])&&lo(n,i)):wa(a,t[i])?lo(n,i):n[i]=!0}return n}var po=(e,t)=>{let n=t.split(`.`),r=[],i=n[0];for(let t=1;tfa(e)?e:t?e===``?NaN:e&&+e:n&&Ea(e)?new Date(e):r?r(e):e;function ho(e){let t=e.ref;return Xi(t)?t.files:Pa(t)?Va(e.refs).value:to(t)?[...t.selectedOptions].map(({value:e})=>e):Yi(t)?za(e.refs).value:mo(t.value,e)}var go=(e,t,n,r)=>{let i={};for(let n of e){let e=W(t,n);e&&_a(i,n,e._f)}return{criteriaMode:n,names:[...e],fields:i,shouldUseNativeValidation:r}},_o=e=>fa(e)?e:Fa(e)?e.source:ea(e)?Fa(e.value)?e.value.source:e.value:e,vo=`AsyncFunction`,yo=e=>{if(!e||!e.validate)return!1;if(ga(e.validate))return e.validate.constructor.name===vo;if(ea(e.validate)){for(let t in e.validate)if(e.validate[t].constructor.name===vo)return!0}return!1},bo=e=>e.mount&&(e.required||!fa(e.required)&&e.required!==!1||!fa(e.min)||!fa(e.max)||!fa(e.maxLength)||!fa(e.minLength)||e.pattern||e.validate);function xo(e,t,n){let r=W(e,n);if(r||da(n))return{error:r,name:n};let i=n.split(`.`);for(;i.length;){let r=i.join(`.`),a=W(t,r),o=W(e,r);if(a&&!Array.isArray(a)&&n!==r)return{name:n};if(o&&o.type)return{name:r,error:o};if(o&&o.root&&o.root.type)return{name:`${r}.root`,error:o.root};i.pop()}return{name:n}}var So=(e,t,n,r)=>{n(e);let i=Object.keys(e).filter(e=>e!==`name`);return!i.length||r&&i.length>=Object.keys(t).length||i.find(e=>t[e]===(!r||oa.all))},Co=(e,t,n)=>!e||!t||e===t||Ga(e).some(e=>e&&(n?e===t||e.startsWith(t+`.`):e.startsWith(t)||t.startsWith(e))),wo=(e,t,n,r,i)=>i.isOnAll?!1:!n&&i.isOnTouch?!(t||e):(n?r.isOnBlur:i.isOnBlur)?!e:!(n?r.isOnChange:i.isOnChange)||e,To=(e,t)=>{let n=W(e,t);!Ka(n).length&&!(n!=null&&n.root)&&Ya(e,t)},Eo={mode:oa.onSubmit,reValidateMode:oa.onChange,shouldFocusError:!0},Do=`form`,Oo=(e,t)=>{for(let n in e)n in t||delete e[n];Object.assign(e,t)},ko={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function Ao(e={}){let t={...Eo,...e},n={...ia(ko),isLoading:ga(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1},r={},i=(ea(t.defaultValues)||ea(t.values))&&ia(t.defaultValues||t.values)||{},a=t.shouldUnregister?{}:ia(i),o={action:!1,actionArrayLengths:new Map,mount:!1,watch:!1,keepIsValid:!1},s={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set,registerName:new Set},c={},l={},u=0,d=Oa(t.mode),f=Oa(t.reValidateMode),p={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},m={...p},h={...m},g={array:Za(),state:Za()},_=0,v=t.criteriaMode===oa.all,y=(e,t)=>n=>{clearTimeout(l[e]),l[e]=setTimeout(t,n)},b=async e=>{if(!o.keepIsValid&&!t.disabled&&(m.isValid||h.isValid||e)){let e=++_,i;t.resolver?(i=Ma((await A()).errors),e===_&&x()):i=await N({fields:r,onlyCheckValid:!0,eventType:aa.VALID}),e===_&&i!==n.isValid&&g.state.next({isValid:i})}},x=(e,r)=>{!t.disabled&&(m.isValidating||m.validatingFields||h.isValidating||h.validatingFields)&&((e||s.mount).forEach(e=>{e&&(r?_a(n.validatingFields,e,r):Ya(n.validatingFields,e))}),g.state.next({validatingFields:n.validatingFields,isValidating:!Ma(n.validatingFields)}))},S=()=>{n.dirtyFields=fo(i,a,void 0,r)},C=(e,i=[],s,c,l=!0,u=!0)=>{if(c&&s&&!t.disabled){o.action=!0;let t=W(r,e);if(o.actionArrayLengths.has(e)||o.actionArrayLengths.set(e,Array.isArray(t)?t.length:0),u&&Array.isArray(t)){let n=s(t,c.argA,c.argB);l&&_a(r,e,n)}let a=W(n.errors,e);if(u&&Array.isArray(a)){let t=a.root,r=s(a,c.argA,c.argB)||a;t&&(r.root=t),l&&_a(n.errors,e,r),To(n.errors,e)}let d=W(n.touchedFields,e);if((m.touchedFields||h.touchedFields)&&u&&Array.isArray(d)){let t=s(d,c.argA,c.argB);l&&_a(n.touchedFields,e,t)}(m.dirtyFields||h.dirtyFields)&&S(),g.state.next({name:e,isDirty:F(e,i),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else _a(a,e,i)},w=(e,t)=>{_a(n.errors,e,t),n.errors={...n.errors},g.state.next({errors:n.errors})},T=e=>{n.errors=e,g.state.next({errors:n.errors,isValid:!1})},E=e=>{let t=da(e)?[e]:ma(e),n=a,r=i;for(let e=0;e{if(!o.actionArrayLengths.size)return!1;let t=da(e)?[e]:ma(e),n=a,r=``,i=-1,s=0;for(let e=0;e=n.length)return i===-1?!1:e!==i||+a{let d=W(r,t);if(d){if(E(t)||D(t))return;let r=fa(W(a,t)),f=W(a,t,fa(l)?W(i,t):l);fa(f)||u&&u.defaultChecked||c?_a(a,t,c?f:ho(d._f)):re(t,f),o.mount&&!o.action&&(b(),r&&n.isDirty&&(m.isDirty||h.isDirty)&&(F()||(n.isDirty=!1,g.state.next({...n}))),e.shouldUnregister&&r&&!fa(W(a,t))&&ka(t,s)&&(o.watch=!0))}},ee=(e,o,s,c,l)=>{let u=!1,d=!1,f={name:e};if(!t.disabled||c===!0){if(!s||c){let t=wa(W(i,e),o);(m.isDirty||h.isDirty)&&(d=n.isDirty,n.isDirty=f.isDirty=!t||F(),u=d!==f.isDirty),d=!!W(n.dirtyFields,e),t===n.isDirty?t?Ya(n.dirtyFields,e):_a(n.dirtyFields,e,!0):Oo(n.dirtyFields,fo(i,a,void 0,r)),f.dirtyFields=n.dirtyFields,u||=(m.dirtyFields||h.dirtyFields)&&d!==!t}if(s){let t=W(n.touchedFields,e);t||(_a(n.touchedFields,e,s),f.touchedFields=n.touchedFields,u||=(m.touchedFields||h.touchedFields)&&t!==s)}u&&l&&g.state.next(f)}return u?f:{}},k=(e,r,i,a)=>{let o=W(n.errors,e),s=(m.isValid||h.isValid)&&ha(r)&&n.isValid!==r;if(t.delayError&&i?(c[e]=y(e,()=>w(e,i)),c[e](t.delayError)):(clearTimeout(l[e]),delete c[e],i?_a(n.errors,e,i):Ya(n.errors,e),n.errors={...n.errors}),(i?!wa(o,i):o)||!Ma(a)||s){let t={...a,...s&&ha(r)?{isValid:r}:{},errors:n.errors,name:e};g.state.next(t)}},A=async e=>(x(e,!0),await t.resolver(a,t.context,go(e||s.mount,r,t.criteriaMode,t.shouldUseNativeValidation))),j=async e=>{let{errors:t}=await A(e);if(x(e),e){for(let r of e){let e=W(t,r);e?s.array.has(r)&&ea(e)&&!Object.keys(e).some(e=>!Number.isNaN(Number(e)))?ja(n.errors,{[r]:e},r):_a(n.errors,r,e):Ya(n.errors,r)}n.errors={...n.errors}}else n.errors=t;return t},M=async({name:t,eventType:r})=>{if(e.validate){let i=await e.validate({formValues:a,formState:n,name:t,eventType:r});if(ea(i))for(let e in i){let t=i[e];t&&pe(`${Do}.${e}`,{message:Ea(t.message)?t.message:``,type:t.type||sa.validate})}else Ea(i)||!i?pe(Do,{message:i||``,type:sa.validate}):fe(Do);return i}return!0},N=async({fields:r,onlyCheckValid:i,name:o,eventType:c,context:l={valid:!0,runRootValidation:!1}})=>{if(e.validate&&(l.runRootValidation=!0,!await M({name:o,eventType:c})&&(l.valid=!1,i)))return l.valid;for(let o in r){let u=r[o];if(u){let{_f:r,...d}=u;if(r){let o=s.array.has(r.name),c=u._f&&yo(u._f),d=m.validatingFields||m.isValidating||h.validatingFields||h.isValidating;c&&d&&x([r.name],!0);let f=await Wa(u,s.disabled,a,v,t.shouldUseNativeValidation&&!i,o);if(c&&d&&x([r.name]),f[r.name]&&(l.valid=!1,i)||(!i&&(W(f,r.name)?o?ja(n.errors,f,r.name):_a(n.errors,r.name,f[r.name]):Ya(n.errors,r.name)),e.shouldUseNativeValidation&&f[r.name]))break}!Ma(d)&&await N({context:l,onlyCheckValid:i,fields:d,name:o,eventType:c})}}return l.valid},P=()=>{for(let e of s.unMount){let t=W(r,e);t&&(t._f.refs?t._f.refs.every(e=>!ro(e)):!ro(t._f.ref))&&_e(e)}s.unMount=new Set},F=(e,t)=>(e&&t&&_a(a,e,t),!wa(o.mount?a:i,i)),te=(e,t,n)=>Da(e,s,{...o.mount?a:fa(t)||Ea(e)?i:t},n,t),ne=e=>Ka(W(o.mount?a:i,e,t.shouldUnregister?W(i,e,[]):[])),re=(e,t,n={},i=!1,o=!1,s=!1)=>{let c=W(r,e),l=t;if(c){let n=c._f;n&&(!n.disabled&&_a(a,e,mo(t,n)),l=Na(n.ref)&&Qi(t)?``:t,to(n.ref)?[...n.ref.options].forEach(e=>e.selected=l.includes(e.value)):n.refs?Yi(n.ref)?n.refs.forEach(e=>{(!e.defaultChecked||!e.disabled)&&(e.checked=Array.isArray(l)?!!l.find(t=>t===e.value):l===e.value||!!l)}):n.refs.forEach(e=>e.checked=e.value===l):Xi(n.ref)?n.ref.value=``:(n.ref.value=l,!n.ref.type&&!o&&!s&&g.state.next({name:e,values:i?a:ia(a)})))}(n.shouldDirty||n.shouldTouch)&&ee(e,l,n.shouldTouch,n.shouldDirty,!o),n.shouldValidate&&ce(e,{delayError:n.delayError})},ie=(e,t,n,i=!1,o=!1,c=!1)=>{s.array.has(e)&&g.array.next({name:e,values:i?a:ia(a)});for(let a in t){if(!t.hasOwnProperty(a))return;let l=t[a],u=e+`.`+a,d=W(r,u);(s.array.has(e)||ea(l)||d&&!d._f)&&!Zi(l)?ie(u,l,n,i,o,c):re(u,l,n,i,o,c)}},I=(e,t,i,c,l=!1)=>{let u=W(r,e),d=s.array.has(e),f=c?t:ia(t),p=wa(W(a,e),f);if(p||_a(a,e,f),d)g.array.next({name:e,values:c?a:ia(a)}),(m.isDirty||m.dirtyFields||h.isDirty||h.dirtyFields)&&i.shouldDirty&&(S(),l||g.state.next({name:e,dirtyFields:n.dirtyFields,isDirty:F(e,f)}));else{let t=Array.isArray(f)&&!f.length||Ma(f),n=!p&&!l;!u||u._f||Qi(f)||t?re(e,f,i,c,l,n):ie(e,f,i,c,l,n)}if(!p&&!l){let t=ka(e,s),r=c?a:ia(a);if(g.state.next({...t&&n,name:o.mount||t?e:void 0,values:r}),!d)for(let t of po(s.array,e))g.state.next({name:t,values:r})}},L=(e,t,n={})=>I(e,t,n,!1),ae=(e,t={})=>{let r=ga(e)?e(a):e;if(!wa(a,r)){a={...a,...r};for(let e of s.mount)eo(r,e)&&I(e,W(r,e),t,!0,!0);g.state.next({...n,name:void 0,type:void 0,...u?{values:a}:{}}),t.shouldValidate&&b()}},oe=async i=>{o.mount=!0;let l=i.target,p=l.name,_=!0,y=W(r,p),S=e=>{_=Number.isNaN(e)||Zi(e)&&isNaN(e.getTime())||wa(e,W(a,p,e))};if(y){let o,C,w=l.type?ho(y._f):ta(i),T=i.type===aa.BLUR||i.type===aa.FOCUS_OUT,E=!bo(y._f)&&!e.validate&&!t.resolver&&!W(n.errors,p)&&!y._f.deps,D=E||wo(T,W(n.touchedFields,p),n.isSubmitted,f,d),O=ka(p,s,T);if(_a(a,p,w),T){if(!l||!l.readOnly){y._f.onBlur&&y._f.onBlur(i);let e=c[p];e&&e(0)}}else y._f.onChange&&y._f.onChange(i);let j=ee(p,w,T),P=!Ma(j)||O;if(!T&&g.state.next({name:p,type:i.type,...u?{values:ia(a)}:{}}),D)return(!E||!n.isValid)&&(m.isValid||h.isValid)&&(t.mode===`onBlur`?T&&b():T||b()),P&&g.state.next({name:p,...O?{}:j});if(!t.resolver&&e.validate&&await M({name:p,eventType:i.type}),!T&&O&&g.state.next({...n}),t.resolver){let{errors:e}=await A([p]);if(x([p]),S(w),!_){!Ma(j)&&g.state.next(j);return}let t=xo(n.errors,r,p),i=xo(e,r,t.name||p);o=i.error,p=i.name,C=Ma(e)}else x([p],!0),o=(await Wa(y,s.disabled,a,v,t.shouldUseNativeValidation))[p],x([p]),S(w),_&&(o?C=!1:(m.isValid||h.isValid)&&(C=await N({fields:r,onlyCheckValid:!0,name:p,eventType:i.type})));_&&(y._f.deps&&(!Array.isArray(y._f.deps)||y._f.deps.length>0)&&ce(y._f.deps),k(p,C,o,j))}},se=(e,t)=>{if(W(n.errors,t)&&e.focus)return e.focus(),1},ce=async(e,i={})=>{let a,o,u=Ga(e);if(t.resolver){let t=await j(fa(e)?e:u);a=Ma(t),o=e?!u.some(e=>W(t,e)):a}else e?(o=(await Promise.all(u.map(async e=>{let t=W(r,e);return await N({fields:t&&t._f?{[e]:t}:t,eventType:aa.TRIGGER})}))).every(Boolean),!(!o&&!n.isValid)&&b()):o=a=await N({fields:r,name:e,eventType:aa.TRIGGER});if(i.delayError&&t.delayError&&Ea(e)){let r=W(n.errors,e);r?(Ya(n.errors,e),c[e]=y(e,()=>w(e,r)),c[e](t.delayError)):(clearTimeout(l[e]),delete c[e])}return g.state.next({...!Ea(e)||(m.isValid||h.isValid)&&a!==n.isValid?{}:{name:e},...t.resolver||!e?{isValid:a}:{},errors:n.errors}),i.shouldFocus&&!o&&Aa(r,se,e?u:s.mount),o},le=(e,t)=>{let r={...o.mount?a:i};return t&&(r=Qa(t.dirtyFields?n.dirtyFields:n.touchedFields,r)),fa(e)?r:Ea(e)?W(r,e):e.map(e=>W(r,e))},ue=e=>fa(e)?{...n.errors}:Ea(e)?W(n.errors,e):e.map(e=>W(n.errors,e)),de=(e,t)=>{let r=t||n,i=W(r.errors,e);return{invalid:!!i,isDirty:!!W(r.dirtyFields,e),error:i,isValidating:!!W(n.validatingFields,e),isTouched:!!W(r.touchedFields,e)}},fe=e=>{let t=e?Ga(e):void 0;t?.forEach(e=>Ya(n.errors,e)),t?t.forEach(e=>{g.state.next({name:e,errors:n.errors})}):(n.errors={},g.state.next({errors:n.errors}))},pe=(e,t,i)=>{let a=(W(r,e,{_f:{}})._f||{}).ref,{ref:o,message:s,type:c,...l}=W(n.errors,e)||{};_a(n.errors,e,{...l,...t,ref:a}),g.state.next({name:e,errors:n.errors,isValid:!1}),i&&i.shouldFocus&&a&&a.focus&&a.focus()},me=(e,t)=>{if(ga(e)){u++;let{unsubscribe:n}=g.state.subscribe({next:n=>`values`in n&&e(n.values||te(void 0,t),n)}),r=!1;return{unsubscribe:()=>{r||(r=!0,u--,n())}}}return te(e,t,!0)},he=e=>{let t=!!e.formState?.values;t&&u++;let{unsubscribe:r}=g.state.subscribe({next:t=>{if(Co(e.name,t.name,e.exact)&&So(t,e.formState||m,Ee,e.reRenderRoot)){let r={...a};e.callback({values:r,...n,...t,defaultValues:i})}}});if(!t)return r;let o=!1;return()=>{o||(o=!0,u--,r())}},ge=e=>(o.mount=!0,h={...h,...e.formState},he({...e,formState:{...p,...e.formState}})),_e=(e,o={})=>{for(let c of e?Ga(e):s.mount)s.mount.delete(c),s.array.delete(c),o.keepValue||(Ya(r,c),Ya(a,c)),!o.keepError&&Ya(n.errors,c),!o.keepDirty&&Ya(n.dirtyFields,c),!o.keepTouched&&Ya(n.touchedFields,c),!o.keepIsValidating&&Ya(n.validatingFields,c),!t.shouldUnregister&&!o.keepDefaultValue&&Ya(i,c);u&&g.state.next({values:ia(a)}),g.state.next({...n,...o.keepDirty?{}:{isDirty:F()}}),!o.keepIsValid&&b()},ve=({disabled:e,name:t})=>{if(ha(e)&&o.mount||e||s.disabled.has(t)){let n=s.disabled.has(t)!==!!e;e?s.disabled.add(t):s.disabled.delete(t),n&&o.mount&&!o.action&&b()}},ye=(e,n={})=>{let a=W(r,e),c=ha(n.disabled)||ha(t.disabled),l=!s.registerName.has(e)&&a&&a._f&&!a._f.mount;return _a(r,e,{...a||{},_f:{...a&&a._f?a._f:{ref:{name:e}},name:e,mount:!0,...n}}),s.mount.add(e),a&&!l?ve({disabled:ha(n.disabled)?n.disabled:t.disabled,name:e}):O(e,!0,n.value),{...c?{disabled:n.disabled||t.disabled}:{},...t.progressive?{required:!!n.required,min:_o(n.min),max:_o(n.max),minLength:_o(n.minLength),maxLength:_o(n.maxLength),pattern:_o(n.pattern)}:{},name:e,onChange:oe,onBlur:oe,ref:c=>{if(c){s.registerName.add(e),ye(e,n),s.registerName.delete(e),a=W(r,e);let t=fa(c.value)&&c.querySelectorAll&&c.querySelectorAll(`input,select,textarea`)[0]||c,o=no(t),l=a._f.refs||[];if(o?l.find(e=>e===t):t===a._f.ref)return;let u={...a._f};o?(u.refs=[...l.filter(ro),t,...Array.isArray(W(i,e))?[{}]:[]],u.ref={type:t.type,name:e}):(u.ref=t,delete u.refs),_a(r,e,{_f:u}),O(e,!1,void 0,t)}else a=W(r,e,{}),a._f&&(a._f.mount=!1),(t.shouldUnregister||n.shouldUnregister)&&!(na(s.array,e)&&o.action)&&s.unMount.add(e)}}},be=()=>t.shouldFocusError&&!t.shouldUseNativeValidation&&Aa(r,se,s.mount),xe=e=>{ha(e)&&(g.state.next({disabled:e}),Aa(r,(t,n)=>{let i=W(r,n);i&&(t.disabled=i._f.disabled||e,Array.isArray(i._f.refs)&&i._f.refs.forEach(t=>{t.disabled=i._f.disabled||e}))},0,!1))},Se=(e,i)=>async o=>{let c,l;o&&(o.preventDefault&&o.preventDefault(),o.persist&&o.persist());let u=ia(a);if(g.state.next({isSubmitting:!0}),t.resolver){let{errors:e,values:t}=await A();x(),n.errors=e,u=ia(t)}else await N({fields:r,eventType:aa.SUBMIT});if(s.disabled.size)for(let e of s.disabled)Ya(u,e);if(Ya(n.errors,ca),Ma(n.errors)){g.state.next({errors:{}});try{c=await e(u,o)}catch(e){l=e}}else i&&await i({...n.errors},o),be(),setTimeout(be);if(g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Ma(n.errors)&&!l,submitCount:n.submitCount+1,errors:n.errors}),l)throw l;return c},R=(e,t={})=>{W(r,e)&&(fa(t.defaultValue)?L(e,ia(W(i,e))):(L(e,t.defaultValue),_a(i,e,ia(t.defaultValue))),t.keepTouched||Ya(n.touchedFields,e),t.keepDirty||(Ya(n.dirtyFields,e),n.isDirty=t.defaultValue?F(e,ia(W(i,e))):F()),t.keepError||(Ya(n.errors,e),m.isValid&&b()),g.state.next({...n}))},Ce=(e,c={})=>{let l=e?ia(e):i,u=ia(l),d=Ma(e),f=u,p=r;if(c.keepDefaultValues||(i=l),!c.keepValues){if(c.keepDirtyValues){let e=new Set([...s.mount,...ao(fo(i,a,void 0,p),n.dirtyFields)]);for(let t of e){let e=W(n.dirtyFields,t),r=W(a,t),i=W(f,t);e&&!fa(r)?_a(f,t,r):!e&&!fa(i)&&L(t,i)}}else{if(ra&&fa(e))for(let e of s.mount){let t=W(r,e);if(t&&t._f){let e=Array.isArray(t._f.refs)?t._f.refs[0]:t._f.ref;if(Na(e)){let t=e.closest(`form`);if(t){t.reset();break}}}}if(c.keepFieldsRef)for(let e of s.mount)L(e,W(f,e));else r={}}if(t.shouldUnregister){if(a=c.keepDefaultValues?ia(i):{},c.keepFieldsRef)for(let e of s.mount)_a(a,e,W(f,e))}else a=ia(f);g.array.next({values:{...f}}),g.state.next({name:void 0,type:void 0,values:{...f}})}s={mount:c.keepDirtyValues?s.mount:new Set,unMount:new Set,array:new Set,registerName:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:``},o.mount=!m.isValid||!!c.keepIsValid||!!c.keepDirtyValues||!t.shouldUnregister&&!Ma(f),o.watch=!!t.shouldUnregister,o.keepIsValid=!!c.keepIsValid,o.action=!1,o.actionArrayLengths.clear(),c.keepErrors||(n.errors={}),g.state.next({submitCount:c.keepSubmitCount?n.submitCount:0,isDirty:d?!1:c.keepDirty?n.isDirty:c.keepValues?F():!!(c.keepDefaultValues&&!wa(e,i)),isSubmitted:c.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:d?{}:c.keepDirtyValues?c.keepDefaultValues&&a?fo(i,a,void 0,p):n.dirtyFields:c.keepDefaultValues&&e?fo(i,e,void 0,p):c.keepDirty?n.dirtyFields:{},touchedFields:c.keepTouched?n.touchedFields:{},errors:c.keepErrors?n.errors:{},isSubmitSuccessful:c.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:i})},we=(e,n)=>Ce(ga(e)?e(a):e,{...t.resetOptions,...n}),Te=(e,t={})=>{let n=W(r,e),i=n&&n._f;if(i){let e=i.refs?i.refs[0]:i.ref;e.focus&&setTimeout(()=>{e.focus(),t.shouldSelect&&ga(e.select)&&e.select()})}},Ee=e=>{let{name:t,type:r,values:i,...a}=e;n={...n,...a}};g.state.subscribe({next:Ee});let De={control:{register:ye,unregister:_e,getFieldState:de,handleSubmit:Se,setError:pe,_subscribe:he,_runSchema:A,_updateIsValidating:x,_focusError:be,_getWatch:te,_getDirty:F,_setValid:b,_setFieldArray:C,_setDisabledField:ve,_setErrors:T,_getFieldArray:ne,_reset:Ce,_resetDefaultValues:()=>ga(t.defaultValues)&&t.defaultValues().then(e=>{we(e,t.resetOptions),g.state.next({isLoading:!1})}),_removeUnmounted:P,_disableForm:xe,_subjects:g,_proxyFormState:m,get _fields(){return r},get _formValues(){return a},get _state(){return o},set _state(e){o=e},get _defaultValues(){return i},get _names(){return s},set _names(e){s=e},get _formState(){return n},get _options(){return t},set _options(e){t={...t,...e},d=Oa(t.mode),f=Oa(t.reValidateMode)}},subscribe:ge,trigger:ce,register:ye,handleSubmit:Se,watch:me,setValue:L,setValues:ae,getValues:le,getErrors:ue,reset:we,resetField:R,resetDefaultValues:(e,t={})=>{if(i=ia(e),!t.keepDirty){let e=fo(i,a,void 0,r);n.dirtyFields=e,n.isDirty=!Ma(e)}t.keepIsValid||b(),g.state.next({...n,defaultValues:i})},clearErrors:fe,unregister:_e,setError:pe,setFocus:Te,getFieldState:de};return{...De,formControl:De}}function jo(e={}){let t=m.useRef(void 0),n=m.useRef(void 0),r=m.useRef(e.formControl),[i,a]=m.useState(()=>({...ia(ko),isLoading:ga(e.defaultValues),errors:e.errors||{},disabled:e.disabled||!1,defaultValues:ga(e.defaultValues)?void 0:e.defaultValues}));if(!t.current||e.formControl&&r.current!==e.formControl){if(r.current=e.formControl,e.formControl)t.current={...e.formControl,formState:i},e.defaultValues&&!ga(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{let{formControl:n,...r}=Ao(e);t.current={...r,formState:i}}}let o=t.current.control;o._options=e;let{resyncIfNeeded:s,snapshot:c}=Ta();return ba(()=>{let e=()=>({...o._formState,defaultValues:o._defaultValues});s(!0,e,a);let t=o._subscribe({formState:o._proxyFormState,callback:()=>a({...o._formState,defaultValues:o._defaultValues}),reRenderRoot:!0});return a(e=>({...e,isReady:!0})),o._formState.isReady=!0,()=>{t(),c(!0,e)}},[o,s,c]),m.useEffect(()=>o._disableForm(e.disabled),[o,e.disabled]),m.useEffect(()=>{e.mode&&(o._options.mode=e.mode),e.reValidateMode&&(o._options.reValidateMode=e.reValidateMode)},[o,e.mode,e.reValidateMode]),m.useEffect(()=>{e.errors&&(o._setErrors(e.errors),o._focusError())},[o,e.errors]),m.useEffect(()=>{e.shouldUnregister&&o._subjects.state.next({values:o._getWatch()})},[o,e.shouldUnregister]),m.useEffect(()=>{if(o._proxyFormState.isDirty){let e=o._getDirty();e!==i.isDirty&&o._subjects.state.next({isDirty:e})}},[o,i.isDirty]),m.useEffect(()=>{e.values&&!wa(e.values,n.current)?(o._reset(e.values,{keepFieldsRef:!0,...o._options.resetOptions}),o._options.resetOptions?.keepIsValid||o._setValid(),n.current=e.values,a(e=>({...e}))):o._resetDefaultValues()},[o,e.values]),m.useEffect(()=>{o._state.mount||(o._setValid(),o._state.mount=!0),o._state.watch&&(o._state.watch=!1,o._subjects.state.next({...o._formState})),o._removeUnmounted()}),t.current.formState=m.useMemo(()=>ya(i,o),[o,i]),t.current}var Mo=(e,t,n)=>{if(e&&`reportValidity`in e){let r=W(n,t);e.setCustomValidity(r&&r.message||``),e.reportValidity()}},No=(e,t)=>{for(let n in t.fields){let r=t.fields[n];r&&r.ref&&`reportValidity`in r.ref?Mo(r.ref,n,e):r&&r.refs&&r.refs.forEach(t=>Mo(t,n,e))}},Po=(e,t)=>{t.shouldUseNativeValidation&&No(e,t);let n={};for(let r in e){let i=W(t.fields,r),a=Object.assign(e[r]||{},{ref:i&&i.refs?i.refs[0]:i&&i.ref});if(Fo(t.names||Object.keys(e),r)){let e=Object.assign({},W(n,r));_a(e,`root`,a),_a(n,r,e)}else _a(n,r,a)}return n},Fo=(e,t)=>{let n=Io(t).replace(/[.*+?^${}()|\\]/g,`\\$&`);return e.some(e=>Io(e).match(`^${n}\\.\\d+`))};function Io(e){return e.replace(/\[(\d+)]/g,`.$1`).replace(/[[\]]/g,``)}function Lo(){return Lo=Object.assign?Object.assign.bind():function(e){for(var t=1;t0){var s=r.errors.reduce(function(e,t){return t.lengthn?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var Uo=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},Wo=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Ho=globalThis).__zod_globalConfig??(Ho.__zod_globalConfig={});var Go=globalThis.__zod_globalConfig;function Ko(e){return e&&Object.assign(Go,e),Go}function qo(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function Jo(e,t){return typeof t==`bigint`?t.toString():t}function Yo(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Xo(e){return e==null}function Zo(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Qo(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r){};function os(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ss=Yo(()=>{if(Go.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function cs(e){if(os(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return os(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function ls(e){return cs(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var us=new Set([`string`,`number`,`symbol`]);function ds(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function fs(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function q(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function ps(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}var ms={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function hs(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return fs(e,ns(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return ts(this,`shape`,e),e},checks:[]}))}function gs(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return fs(e,ns(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return ts(this,`shape`,r),r},checks:[]}))}function _s(e,t){if(!cs(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return fs(e,ns(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return ts(this,`shape`,n),n}}))}function vs(e,t){if(!cs(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return fs(e,ns(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return ts(this,`shape`,n),n}}))}function ys(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return fs(e,ns(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return ts(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function bs(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return fs(t,ns(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return ts(this,`shape`,i),i},checks:[]}))}function xs(e,t,n){return fs(t,ns(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return ts(this,`shape`,i),i}}))}function Ss(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Ts(e){return typeof e==`string`?e:e?.message}function Es(e,t,n){let r=e.message?e.message:Ts(e.inst?._zod.def?.error?.(e))??Ts(t?.error?.(e))??Ts(n.customError?.(e))??Ts(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function Ds(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function Os(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}var ks=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Jo,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},As=K(`$ZodError`,ks),js=K(`$ZodError`,ks,{Parent:Error});function Ms(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Ns(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new Uo;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>Es(e,a,Ko())));throw as(t,i?.callee),t}return o.value},Fs=e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>Es(e,a,Ko())));throw as(t,i?.callee),t}return o.value},Is=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Uo;return a.issues.length?{success:!1,error:new(e??As)(a.issues.map(e=>Es(e,i,Ko())))}:{success:!0,data:a.value}},Ls=Is(js),Rs=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>Es(e,i,Ko())))}:{success:!0,data:a.value}},zs=Rs(js),Bs=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ps(e)(t,n,i)},Vs=e=>(t,n,r)=>Ps(e)(t,n,r),Hs=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Fs(e)(t,n,i)},Us=e=>async(t,n,r)=>Fs(e)(t,n,r),Ws=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Is(e)(t,n,i)},Gs=e=>(t,n,r)=>Is(e)(t,n,r),Ks=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Rs(e)(t,n,i)},qs=e=>async(t,n,r)=>Rs(e)(t,n,r),Js=/^[cC][0-9a-z]{6,}$/,Ys=/^[0-9a-z]+$/,Xs=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Zs=/^[0-9a-vA-V]{20}$/,Qs=/^[A-Za-z0-9]{27}$/,$s=/^[a-zA-Z0-9_-]{21}$/,ec=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,tc=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,nc=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,rc=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,ic=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;function ac(){return new RegExp(ic,`u`)}var oc=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,sc=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,cc=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,lc=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,uc=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,dc=/^[A-Za-z0-9_-]*$/,fc=/^https?$/,pc=/^\+[1-9]\d{6,14}$/,mc=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,hc=RegExp(`^${mc}$`);function gc(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function _c(e){return RegExp(`^${gc(e)}$`)}function vc(e){let t=gc({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${mc}T(?:${r})$`)}var yc=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},bc=/^-?\d+$/,xc=/^-?\d+(?:\.\d+)?$/,Sc=/^(?:true|false)$/i,Cc=/^[^A-Z]*$/,wc=/^[^a-z]*$/,Tc=K(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ec={number:`number`,bigint:`bigint`,object:`date`},Dc=K(`$ZodCheckLessThan`,(e,t)=>{Tc.init(e,t);let n=Ec[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value{(t.inclusive?r.value<=t.value:r.value{Tc.init(e,t);let n=Ec[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),kc=K(`$ZodCheckMultipleOf`,(e,t)=>{Tc.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):Qo(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Ac=K(`$ZodCheckNumberFormat`,(e,t)=>{Tc.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=ms[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=bc)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}sa&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),jc=K(`$ZodCheckMaxLength`,(e,t)=>{var n;Tc.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Xo(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum{let r=n.value;if(r.length<=t.maximum)return;let i=Ds(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Mc=K(`$ZodCheckMinLength`,(e,t)=>{var n;Tc.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Xo(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=Ds(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Nc=K(`$ZodCheckLengthEquals`,(e,t)=>{var n;Tc.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Xo(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=Ds(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Pc=K(`$ZodCheckStringFormat`,(e,t)=>{var n,r;Tc.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Fc=K(`$ZodCheckRegex`,(e,t)=>{Pc.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Ic=K(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Cc,Pc.init(e,t)}),Lc=K(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=wc,Pc.init(e,t)}),Rc=K(`$ZodCheckIncludes`,(e,t)=>{Tc.init(e,t);let n=ds(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),zc=K(`$ZodCheckStartsWith`,(e,t)=>{Tc.init(e,t);let n=RegExp(`^${ds(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Bc=K(`$ZodCheckEndsWith`,(e,t)=>{Tc.init(e,t);let n=RegExp(`.*${ds(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Vc=K(`$ZodCheckOverwrite`,(e,t)=>{Tc.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),Hc=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(` +`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(` +`))}},Uc={major:4,minor:4,patch:3},Wc=K(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Uc;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=Ss(e),i;for(let a of t){if(a._zod.def.when){if(Cs(e)||!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new Uo;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=Ss(e,t))});else{if(e.issues.length===t)continue;r||=Ss(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(Ss(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new Uo;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new Uo;return o.then(e=>t(e,r,a))}return t(o,r,a)}}es(e,`~standard`,()=>({validate:t=>{try{let n=Ls(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return zs(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),Gc=K(`$ZodString`,(e,t)=>{Wc.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??yc(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),Kc=K(`$ZodStringFormat`,(e,t)=>{Pc.init(e,t),Gc.init(e,t)}),qc=K(`$ZodGUID`,(e,t)=>{t.pattern??=tc,Kc.init(e,t)}),Jc=K(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=nc(e)}else t.pattern??=nc();Kc.init(e,t)}),Yc=K(`$ZodEmail`,(e,t)=>{t.pattern??=rc,Kc.init(e,t)}),Xc=K(`$ZodURL`,(e,t)=>{Kc.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===fc.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}let i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),n.value=t.normalize?i.href:r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Zc=K(`$ZodEmoji`,(e,t)=>{t.pattern??=ac(),Kc.init(e,t)}),Qc=K(`$ZodNanoID`,(e,t)=>{t.pattern??=$s,Kc.init(e,t)}),$c=K(`$ZodCUID`,(e,t)=>{t.pattern??=Js,Kc.init(e,t)}),el=K(`$ZodCUID2`,(e,t)=>{t.pattern??=Ys,Kc.init(e,t)}),tl=K(`$ZodULID`,(e,t)=>{t.pattern??=Xs,Kc.init(e,t)}),nl=K(`$ZodXID`,(e,t)=>{t.pattern??=Zs,Kc.init(e,t)}),rl=K(`$ZodKSUID`,(e,t)=>{t.pattern??=Qs,Kc.init(e,t)}),il=K(`$ZodISODateTime`,(e,t)=>{t.pattern??=vc(t),Kc.init(e,t)}),al=K(`$ZodISODate`,(e,t)=>{t.pattern??=hc,Kc.init(e,t)}),ol=K(`$ZodISOTime`,(e,t)=>{t.pattern??=_c(t),Kc.init(e,t)}),sl=K(`$ZodISODuration`,(e,t)=>{t.pattern??=ec,Kc.init(e,t)}),cl=K(`$ZodIPv4`,(e,t)=>{t.pattern??=oc,Kc.init(e,t),e._zod.bag.format=`ipv4`}),ll=K(`$ZodIPv6`,(e,t)=>{t.pattern??=sc,Kc.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),ul=K(`$ZodCIDRv4`,(e,t)=>{t.pattern??=cc,Kc.init(e,t)}),dl=K(`$ZodCIDRv6`,(e,t)=>{t.pattern??=lc,Kc.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function fl(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var pl=K(`$ZodBase64`,(e,t)=>{t.pattern??=uc,Kc.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{fl(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function ml(e){if(!dc.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return fl(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var hl=K(`$ZodBase64URL`,(e,t)=>{t.pattern??=dc,Kc.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{ml(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),gl=K(`$ZodE164`,(e,t)=>{t.pattern??=pc,Kc.init(e,t)});function _l(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var vl=K(`$ZodJWT`,(e,t)=>{Kc.init(e,t),e._zod.check=n=>{_l(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),yl=K(`$ZodNumber`,(e,t)=>{Wc.init(e,t),e._zod.pattern=e._zod.bag.pattern??xc,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),bl=K(`$ZodNumberFormat`,(e,t)=>{Ac.init(e,t),yl.init(e,t)}),xl=K(`$ZodBoolean`,(e,t)=>{Wc.init(e,t),e._zod.pattern=Sc,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Sl=K(`$ZodUnknown`,(e,t)=>{Wc.init(e,t),e._zod.parse=e=>e}),Cl=K(`$ZodNever`,(e,t)=>{Wc.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function wl(e,t,n){e.issues.length&&t.issues.push(...ws(n,e.issues)),t.value[n]=e.value}var Tl=K(`$ZodArray`,(e,t)=>{Wc.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;ewl(t,n,e))):wl(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function El(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...ws(n,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function Dl(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=ps(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Ol(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>El(e,n,i,t,u,d))):El(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}var kl=K(`$ZodObject`,(e,t)=>{if(Wc.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}let n=Yo(()=>Dl(t));es(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=os,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>El(n,t,e,s,r,i))):El(a,t,e,s,r,i)}return i?Ol(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),Al=K(`$ZodObjectJIT`,(e,t)=>{kl.init(e,t);let n=e._zod.parse,r=Yo(()=>Dl(t)),i=e=>{let t=new Hc([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=rs(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=rs(r),s=e[r],c=s?._zod?.optin===`optional`,l=s?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),c&&l?t.write(` + if (${n}.issues.length) { + if (${o} in input) { + payload.issues = payload.issues.concat(${n}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${o}, ...iss.path] : [${o}] + }))); + } + } + + if (${n}.value === undefined) { + if (${o} in input) { + newResult[${o}] = undefined; + } + } else { + newResult[${o}] = ${n}.value; + } + + `):c?t.write(` + if (${n}.issues.length) { + payload.issues = payload.issues.concat(${n}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${o}, ...iss.path] : [${o}] + }))); + } + + if (${n}.value === undefined) { + if (${o} in input) { + newResult[${o}] = undefined; + } + } else { + newResult[${o}] = ${n}.value; + } + + `):t.write(` + const ${n}_present = ${o} in input; + if (${n}.issues.length) { + payload.issues = payload.issues.concat(${n}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${o}, ...iss.path] : [${o}] + }))); + } + if (!${n}_present && !${n}.issues.length) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [${o}] + }); + } + + if (${n}_present) { + if (${n}.value === undefined) { + newResult[${o}] = undefined; + } else { + newResult[${o}] = ${n}.value; + } + } + + `)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=os,s=!Go.jitless,c=s&&ss.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?Ol([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function jl(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!Ss(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Es(e,r,Ko())))}),t)}var Ml=K(`$ZodUnion`,(e,t)=>{Wc.init(e,t),es(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),es(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),es(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),es(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>Zo(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>jl(t,r,e,i)):jl(o,r,e,i)}}),Nl=K(`$ZodIntersection`,(e,t)=>{Wc.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>Fl(e,t,n)):Fl(e,i,a)}});function Pl(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(cs(e)&&cs(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Pl(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;re.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),Ss(e))return e;let o=Pl(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var Il=K(`$ZodEnum`,(e,t)=>{Wc.init(e,t);let n=qo(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>us.has(typeof e)).map(e=>typeof e==`string`?ds(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),Ll=K(`$ZodLiteral`,(e,t)=>{if(Wc.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?ds(e):e?ds(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),Rl=K(`$ZodTransform`,(e,t)=>{Wc.init(e,t),e._zod.optin=`optional`,e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Wo(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n.fallback=!0,n));if(i instanceof Promise)throw new Uo;return n.value=i,n.fallback=!0,n}});function zl(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var Bl=K(`$ZodOptional`,(e,t)=>{Wc.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,es(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),es(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${Zo(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>zl(e,r)):zl(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),Vl=K(`$ZodExactOptional`,(e,t)=>{Bl.init(e,t),es(e._zod,`values`,()=>t.innerType._zod.values),es(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Hl=K(`$ZodNullable`,(e,t)=>{Wc.init(e,t),es(e._zod,`optin`,()=>t.innerType._zod.optin),es(e._zod,`optout`,()=>t.innerType._zod.optout),es(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${Zo(e.source)}|null)$`):void 0}),es(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Ul=K(`$ZodDefault`,(e,t)=>{Wc.init(e,t),e._zod.optin=`optional`,es(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Wl(e,t)):Wl(r,t)}});function Wl(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Gl=K(`$ZodPrefault`,(e,t)=>{Wc.init(e,t),e._zod.optin=`optional`,es(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Kl=K(`$ZodNonOptional`,(e,t)=>{Wc.init(e,t),es(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>ql(t,e)):ql(i,e)}});function ql(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}var Jl=K(`$ZodCatch`,(e,t)=>{Wc.init(e,t),e._zod.optin=`optional`,es(e._zod,`optout`,()=>t.innerType._zod.optout),es(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Es(e,n,Ko()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Es(e,n,Ko()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),Yl=K(`$ZodPipe`,(e,t)=>{Wc.init(e,t),es(e._zod,`values`,()=>t.in._zod.values),es(e._zod,`optin`,()=>t.in._zod.optin),es(e._zod,`optout`,()=>t.out._zod.optout),es(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Xl(e,t.in,n)):Xl(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Xl(e,t.out,n)):Xl(r,t.out,n)}});function Xl(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var Zl=K(`$ZodReadonly`,(e,t)=>{Wc.init(e,t),es(e._zod,`propValues`,()=>t.innerType._zod.propValues),es(e._zod,`values`,()=>t.innerType._zod.values),es(e._zod,`optin`,()=>t.innerType?._zod?.optin),es(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Ql):Ql(r)}});function Ql(e){return e.value=Object.freeze(e.value),e}var $l=K(`$ZodCustom`,(e,t)=>{Tc.init(e,t),Wc.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>eu(t,n,r,e));eu(i,n,r,e)}});function eu(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Os(e))}}var tu,nu=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function ru(){return new nu}(tu=globalThis).__zod_globalRegistry??(tu.__zod_globalRegistry=ru());var iu=globalThis.__zod_globalRegistry;function au(e,t){return new e({type:`string`,...q(t)})}function ou(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...q(t)})}function su(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...q(t)})}function cu(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...q(t)})}function lu(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...q(t)})}function uu(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...q(t)})}function du(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...q(t)})}function fu(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...q(t)})}function pu(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...q(t)})}function mu(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...q(t)})}function hu(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...q(t)})}function gu(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...q(t)})}function _u(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...q(t)})}function vu(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...q(t)})}function yu(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...q(t)})}function bu(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...q(t)})}function xu(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...q(t)})}function Su(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...q(t)})}function Cu(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...q(t)})}function wu(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...q(t)})}function Tu(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...q(t)})}function Eu(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...q(t)})}function Du(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...q(t)})}function Ou(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...q(t)})}function ku(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...q(t)})}function Au(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...q(t)})}function ju(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...q(t)})}function Mu(e,t){return new e({type:`number`,checks:[],...q(t)})}function Nu(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...q(t)})}function Pu(e,t){return new e({type:`boolean`,...q(t)})}function Fu(e){return new e({type:`unknown`})}function Iu(e,t){return new e({type:`never`,...q(t)})}function Lu(e,t){return new Dc({check:`less_than`,...q(t),value:e,inclusive:!1})}function Ru(e,t){return new Dc({check:`less_than`,...q(t),value:e,inclusive:!0})}function zu(e,t){return new Oc({check:`greater_than`,...q(t),value:e,inclusive:!1})}function Bu(e,t){return new Oc({check:`greater_than`,...q(t),value:e,inclusive:!0})}function Vu(e,t){return new kc({check:`multiple_of`,...q(t),value:e})}function Hu(e,t){return new jc({check:`max_length`,...q(t),maximum:e})}function Uu(e,t){return new Mc({check:`min_length`,...q(t),minimum:e})}function Wu(e,t){return new Nc({check:`length_equals`,...q(t),length:e})}function Gu(e,t){return new Fc({check:`string_format`,format:`regex`,...q(t),pattern:e})}function Ku(e){return new Ic({check:`string_format`,format:`lowercase`,...q(e)})}function qu(e){return new Lc({check:`string_format`,format:`uppercase`,...q(e)})}function Ju(e,t){return new Rc({check:`string_format`,format:`includes`,...q(t),includes:e})}function Yu(e,t){return new zc({check:`string_format`,format:`starts_with`,...q(t),prefix:e})}function Xu(e,t){return new Bc({check:`string_format`,format:`ends_with`,...q(t),suffix:e})}function Zu(e){return new Vc({check:`overwrite`,tx:e})}function Qu(e){return Zu(t=>t.normalize(e))}function $u(){return Zu(e=>e.trim())}function ed(){return Zu(e=>e.toLowerCase())}function td(){return Zu(e=>e.toUpperCase())}function nd(){return Zu(e=>is(e))}function rd(e,t,n){return new e({type:`array`,element:t,...q(n)})}function id(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...q(n)})}function ad(e,t){let n=od(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(Os(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(Os(r))}},e(t.value,t)),t);return n}function od(e,t){let n=new Tc({check:`custom`,...q(t)});return n._zod.check=e,n}function sd(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??iu,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function cd(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,cd(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&dd(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function ld(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/ + +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function ud(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:pd(t,`input`,e.processors),output:pd(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function dd(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return dd(r.element,n);if(r.type===`set`)return dd(r.valueType,n);if(r.type===`lazy`)return dd(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return dd(r.innerType,n);if(r.type===`intersection`)return dd(r.left,n)||dd(r.right,n);if(r.type===`record`||r.type===`map`)return dd(r.keyType,n)||dd(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:dd(r.in,n)||dd(r.out,n);if(r.type===`object`){for(let e in r.shape)if(dd(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(dd(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(dd(e,n))return!0;return!!(r.rest&&dd(r.rest,n))}return!1}var fd=(e,t={})=>n=>{let r=sd({...n,processors:t});return cd(e,r),ld(r,e),ud(r,e)},pd=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=sd({...i??{},target:a,io:t,processors:n});return cd(e,o),ld(o,e),ud(o,e)},md={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},hd=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=md[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},gd=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},_d=(e,t,n,r)=>{n.type=`boolean`},vd=(e,t,n,r)=>{n.not={}},yd=(e,t,n,r)=>{let i=e._zod.def,a=qo(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},bd=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},xd=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},Sd=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Cd=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=cd(a.element,t,{...r,path:[...r.path,`items`]})},wd=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=cd(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=cd(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Td=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>cd(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Ed=(e,t,n,r)=>{let i=e._zod.def,a=cd(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=cd(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},Dd=(e,t,n,r)=>{let i=e._zod.def,a=cd(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Od=(e,t,n,r)=>{let i=e._zod.def;cd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},kd=(e,t,n,r)=>{let i=e._zod.def;cd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Ad=(e,t,n,r)=>{let i=e._zod.def;cd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},jd=(e,t,n,r)=>{let i=e._zod.def;cd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},Md=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;cd(o,t,r);let s=t.seen.get(e);s.ref=o},Nd=(e,t,n,r)=>{let i=e._zod.def;cd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Pd=(e,t,n,r)=>{let i=e._zod.def;cd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Fd=K(`ZodISODateTime`,(e,t)=>{il.init(e,t),lf.init(e,t)});function Id(e){return Ou(Fd,e)}var Ld=K(`ZodISODate`,(e,t)=>{al.init(e,t),lf.init(e,t)});function Rd(e){return ku(Ld,e)}var zd=K(`ZodISOTime`,(e,t)=>{ol.init(e,t),lf.init(e,t)});function Bd(e){return Au(zd,e)}var Vd=K(`ZodISODuration`,(e,t)=>{sl.init(e,t),lf.init(e,t)});function Hd(e){return ju(Vd,e)}var Ud=K(`ZodError`,(e,t)=>{As.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>Ns(e,t)},flatten:{value:t=>Ms(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Jo,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Jo,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),Wd=Ps(Ud),Gd=Fs(Ud),Kd=Is(Ud),qd=Rs(Ud),Jd=Bs(Ud),Yd=Vs(Ud),Xd=Hs(Ud),Zd=Us(Ud),Qd=Ws(Ud),$d=Gs(Ud),ef=Ks(Ud),tf=qs(Ud),nf=new WeakMap;function rf(e,t,n){let r=Object.getPrototypeOf(e),i=nf.get(r);if(i||(i=new Set,nf.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var af=K(`ZodType`,(e,t)=>(Wc.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:pd(e,`input`),output:pd(e,`output`)}}),e.toJSONSchema=fd(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>Wd(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Kd(e,t,n),e.parseAsync=async(t,n)=>Gd(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>qd(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Jd(e,t,n),e.decode=(t,n)=>Yd(e,t,n),e.encodeAsync=async(t,n)=>Xd(e,t,n),e.decodeAsync=async(t,n)=>Zd(e,t,n),e.safeEncode=(t,n)=>Qd(e,t,n),e.safeDecode=(t,n)=>$d(e,t,n),e.safeEncodeAsync=async(t,n)=>ef(e,t,n),e.safeDecodeAsync=async(t,n)=>tf(e,t,n),rf(e,`ZodType`,{check(...e){let t=this.def;return this.clone(ns(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return fs(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(vp(e,t))},superRefine(e,t){return this.check(yp(e,t))},overwrite(e){return this.check(Zu(e))},optional(){return ep(this)},exactOptional(){return np(this)},nullable(){return ip(this)},nullish(){return ep(ip(this))},nonoptional(e){return up(this,e)},array(){return Bf(this)},or(e){return Wf([this,e])},and(e){return Kf(this,e)},transform(e){return mp(this,Qf(e))},default(e){return op(this,e)},prefault(e){return cp(this,e)},catch(e){return fp(this,e)},pipe(e){return mp(this,e)},readonly(){return gp(this)},describe(e){let t=this.clone();return iu.add(t,{description:e}),t},meta(...e){if(e.length===0)return iu.get(this);let t=this.clone();return iu.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return iu.get(e)?.description},configurable:!0}),e)),of=K(`_ZodString`,(e,t)=>{Gc.init(e,t),af.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hd(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,rf(e,`_ZodString`,{regex(...e){return this.check(Gu(...e))},includes(...e){return this.check(Ju(...e))},startsWith(...e){return this.check(Yu(...e))},endsWith(...e){return this.check(Xu(...e))},min(...e){return this.check(Uu(...e))},max(...e){return this.check(Hu(...e))},length(...e){return this.check(Wu(...e))},nonempty(...e){return this.check(Uu(1,...e))},lowercase(e){return this.check(Ku(e))},uppercase(e){return this.check(qu(e))},trim(){return this.check($u())},normalize(...e){return this.check(Qu(...e))},toLowerCase(){return this.check(ed())},toUpperCase(){return this.check(td())},slugify(){return this.check(nd())}})}),sf=K(`ZodString`,(e,t)=>{Gc.init(e,t),of.init(e,t),e.email=t=>e.check(ou(uf,t)),e.url=t=>e.check(fu(pf,t)),e.jwt=t=>e.check(Du(Of,t)),e.emoji=t=>e.check(pu(mf,t)),e.guid=t=>e.check(su(df,t)),e.uuid=t=>e.check(cu(ff,t)),e.uuidv4=t=>e.check(lu(ff,t)),e.uuidv6=t=>e.check(uu(ff,t)),e.uuidv7=t=>e.check(du(ff,t)),e.nanoid=t=>e.check(mu(hf,t)),e.guid=t=>e.check(su(df,t)),e.cuid=t=>e.check(hu(gf,t)),e.cuid2=t=>e.check(gu(_f,t)),e.ulid=t=>e.check(_u(vf,t)),e.base64=t=>e.check(wu(Tf,t)),e.base64url=t=>e.check(Tu(Ef,t)),e.xid=t=>e.check(vu(yf,t)),e.ksuid=t=>e.check(yu(bf,t)),e.ipv4=t=>e.check(bu(xf,t)),e.ipv6=t=>e.check(xu(Sf,t)),e.cidrv4=t=>e.check(Su(Cf,t)),e.cidrv6=t=>e.check(Cu(wf,t)),e.e164=t=>e.check(Eu(Df,t)),e.datetime=t=>e.check(Id(t)),e.date=t=>e.check(Rd(t)),e.time=t=>e.check(Bd(t)),e.duration=t=>e.check(Hd(t))});function cf(e){return au(sf,e)}var lf=K(`ZodStringFormat`,(e,t)=>{Kc.init(e,t),of.init(e,t)}),uf=K(`ZodEmail`,(e,t)=>{Yc.init(e,t),lf.init(e,t)}),df=K(`ZodGUID`,(e,t)=>{qc.init(e,t),lf.init(e,t)}),ff=K(`ZodUUID`,(e,t)=>{Jc.init(e,t),lf.init(e,t)}),pf=K(`ZodURL`,(e,t)=>{Xc.init(e,t),lf.init(e,t)}),mf=K(`ZodEmoji`,(e,t)=>{Zc.init(e,t),lf.init(e,t)}),hf=K(`ZodNanoID`,(e,t)=>{Qc.init(e,t),lf.init(e,t)}),gf=K(`ZodCUID`,(e,t)=>{$c.init(e,t),lf.init(e,t)}),_f=K(`ZodCUID2`,(e,t)=>{el.init(e,t),lf.init(e,t)}),vf=K(`ZodULID`,(e,t)=>{tl.init(e,t),lf.init(e,t)}),yf=K(`ZodXID`,(e,t)=>{nl.init(e,t),lf.init(e,t)}),bf=K(`ZodKSUID`,(e,t)=>{rl.init(e,t),lf.init(e,t)}),xf=K(`ZodIPv4`,(e,t)=>{cl.init(e,t),lf.init(e,t)}),Sf=K(`ZodIPv6`,(e,t)=>{ll.init(e,t),lf.init(e,t)}),Cf=K(`ZodCIDRv4`,(e,t)=>{ul.init(e,t),lf.init(e,t)}),wf=K(`ZodCIDRv6`,(e,t)=>{dl.init(e,t),lf.init(e,t)}),Tf=K(`ZodBase64`,(e,t)=>{pl.init(e,t),lf.init(e,t)}),Ef=K(`ZodBase64URL`,(e,t)=>{hl.init(e,t),lf.init(e,t)}),Df=K(`ZodE164`,(e,t)=>{gl.init(e,t),lf.init(e,t)}),Of=K(`ZodJWT`,(e,t)=>{vl.init(e,t),lf.init(e,t)}),kf=K(`ZodNumber`,(e,t)=>{yl.init(e,t),af.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gd(e,t,n,r),rf(e,`ZodNumber`,{gt(e,t){return this.check(zu(e,t))},gte(e,t){return this.check(Bu(e,t))},min(e,t){return this.check(Bu(e,t))},lt(e,t){return this.check(Lu(e,t))},lte(e,t){return this.check(Ru(e,t))},max(e,t){return this.check(Ru(e,t))},int(e){return this.check(Mf(e))},safe(e){return this.check(Mf(e))},positive(e){return this.check(zu(0,e))},nonnegative(e){return this.check(Bu(0,e))},negative(e){return this.check(Lu(0,e))},nonpositive(e){return this.check(Ru(0,e))},multipleOf(e,t){return this.check(Vu(e,t))},step(e,t){return this.check(Vu(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function Af(e){return Mu(kf,e)}var jf=K(`ZodNumberFormat`,(e,t)=>{bl.init(e,t),kf.init(e,t)});function Mf(e){return Nu(jf,e)}var Nf=K(`ZodBoolean`,(e,t)=>{xl.init(e,t),af.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_d(e,t,n,r)});function Pf(e){return Pu(Nf,e)}var Ff=K(`ZodUnknown`,(e,t)=>{Sl.init(e,t),af.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function If(){return Fu(Ff)}var Lf=K(`ZodNever`,(e,t)=>{Cl.init(e,t),af.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vd(e,t,n,r)});function Rf(e){return Iu(Lf,e)}var zf=K(`ZodArray`,(e,t)=>{Tl.init(e,t),af.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Cd(e,t,n,r),e.element=t.element,rf(e,`ZodArray`,{min(e,t){return this.check(Uu(e,t))},nonempty(e){return this.check(Uu(1,e))},max(e,t){return this.check(Hu(e,t))},length(e,t){return this.check(Wu(e,t))},unwrap(){return this.element}})});function Bf(e,t){return rd(zf,e,t)}var Vf=K(`ZodObject`,(e,t)=>{Al.init(e,t),af.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wd(e,t,n,r),es(e,`shape`,()=>t.shape),rf(e,`ZodObject`,{keyof(){return Jf(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:If()})},loose(){return this.clone({...this._zod.def,catchall:If()})},strict(){return this.clone({...this._zod.def,catchall:Rf()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return _s(this,e)},safeExtend(e){return vs(this,e)},merge(e){return ys(this,e)},pick(e){return hs(this,e)},omit(e){return gs(this,e)},partial(...e){return bs($f,this,e[0])},required(...e){return xs(lp,this,e[0])}})});function Hf(e,t){return new Vf({type:`object`,shape:e??{},...q(t)})}var Uf=K(`ZodUnion`,(e,t)=>{Ml.init(e,t),af.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Td(e,t,n,r),e.options=t.options});function Wf(e,t){return new Uf({type:`union`,options:e,...q(t)})}var Gf=K(`ZodIntersection`,(e,t)=>{Nl.init(e,t),af.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ed(e,t,n,r)});function Kf(e,t){return new Gf({type:`intersection`,left:e,right:t})}var qf=K(`ZodEnum`,(e,t)=>{Il.init(e,t),af.init(e,t),e._zod.processJSONSchema=(t,n,r)=>yd(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new qf({...t,checks:[],...q(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new qf({...t,checks:[],...q(r),entries:i})}});function Jf(e,t){return new qf({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...q(t)})}var Yf=K(`ZodLiteral`,(e,t)=>{Ll.init(e,t),af.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bd(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Xf(e,t){return new Yf({type:`literal`,values:Array.isArray(e)?e:[e],...q(t)})}var Zf=K(`ZodTransform`,(e,t)=>{Rl.init(e,t),af.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Sd(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Wo(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Os(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(Os(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function Qf(e){return new Zf({type:`transform`,transform:e})}var $f=K(`ZodOptional`,(e,t)=>{Bl.init(e,t),af.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Pd(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ep(e){return new $f({type:`optional`,innerType:e})}var tp=K(`ZodExactOptional`,(e,t)=>{Vl.init(e,t),af.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Pd(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function np(e){return new tp({type:`optional`,innerType:e})}var rp=K(`ZodNullable`,(e,t)=>{Hl.init(e,t),af.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Dd(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ip(e){return new rp({type:`nullable`,innerType:e})}var ap=K(`ZodDefault`,(e,t)=>{Ul.init(e,t),af.init(e,t),e._zod.processJSONSchema=(t,n,r)=>kd(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function op(e,t){return new ap({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ls(t)}})}var sp=K(`ZodPrefault`,(e,t)=>{Gl.init(e,t),af.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ad(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function cp(e,t){return new sp({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ls(t)}})}var lp=K(`ZodNonOptional`,(e,t)=>{Kl.init(e,t),af.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Od(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function up(e,t){return new lp({type:`nonoptional`,innerType:e,...q(t)})}var dp=K(`ZodCatch`,(e,t)=>{Jl.init(e,t),af.init(e,t),e._zod.processJSONSchema=(t,n,r)=>jd(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function fp(e,t){return new dp({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var pp=K(`ZodPipe`,(e,t)=>{Yl.init(e,t),af.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Md(e,t,n,r),e.in=t.in,e.out=t.out});function mp(e,t){return new pp({type:`pipe`,in:e,out:t})}var hp=K(`ZodReadonly`,(e,t)=>{Zl.init(e,t),af.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Nd(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function gp(e){return new hp({type:`readonly`,innerType:e})}var _p=K(`ZodCustom`,(e,t)=>{$l.init(e,t),af.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xd(e,t,n,r)});function vp(e,t={}){return id(_p,e,t)}function yp(e,t){return ad(e,t)}var bp=Af().int().min(1).max(1e3),xp=Hf({}).strict(),Sp=Hf({provider:cf().trim().min(1).max(200).regex(/^[A-Za-z0-9._-]+$/),modelMode:Jf([`provider-default`,`keep-root-model`,`explicit`]),model:cf().trim().max(500).optional()}).strict().superRefine((e,t)=>{e.modelMode===`explicit`&&!e.model&&t.addIssue({code:`custom`,path:[`model`],message:`model-required`}),e.modelMode!==`explicit`&&e.model&&t.addIssue({code:`custom`,path:[`model`],message:`model-not-accepted`})}),Cp=Hf({models:Pf(),cwd:Pf(),userEvent:Pf(),workspaceRoots:Pf()}).strict().superRefine((e,t)=>{!e.models&&!e.cwd&&!e.userEvent&&!e.workspaceRoots&&t.addIssue({code:`custom`,path:[`models`],message:`repair-target-required`})}),wp=Hf({backupId:cf().trim().min(1).max(300),restoreConfig:Pf(),restoreDatabase:Pf(),restoreSessions:Pf(),allowSqliteHomeRelocation:Pf(),relocationTargetProfileId:cf().trim().max(80).optional()}).superRefine((e,t)=>{!e.restoreConfig&&!e.restoreDatabase&&!e.restoreSessions&&t.addIssue({code:`custom`,path:[`restoreSessions`],message:`restore-required`}),e.allowSqliteHomeRelocation&&(!e.relocationTargetProfileId||e.restoreConfig)&&t.addIssue({code:`custom`,path:[`relocationTargetProfileId`],message:`relocation-invalid`})}),Tp=cf().trim().min(1).max(4096).refine(e=>/^(?:[A-Za-z]:[\\/]|\\\\|\/)/.test(e),`absolute-path-required`);Hf({profileId:cf().trim().min(1).max(80).regex(/^[A-Za-z0-9._-]+$/),name:cf().trim().min(1).max(120),codexHome:Tp,sqliteHome:Wf([Tp,Xf(``)]).optional()});var Ep=Object.defineProperty,Dp=(e,t)=>Ep(e,`name`,{value:t,configurable:!0}),Op=!!(typeof window<`u`&&window.document&&window.document.createElement);function kp(e,t,{checkForDefaultPrevented:n=!0}={}){return Dp(function(r){if(e?.(r),n===!1||!r||!r.defaultPrevented)return t?.(r)},`handleEvent`)}Dp(kp,`composeEventHandlers`);function Ap(e){if(!Op)throw Error(`Cannot access window outside of the DOM`);return e?.ownerDocument?.defaultView??window}Dp(Ap,`getOwnerWindow`);function jp(e){if(!Op)throw Error(`Cannot access document outside of the DOM`);return e?.ownerDocument??document}Dp(jp,`getOwnerDocument`);function Mp(e,t=!1){let{activeElement:n}=jp(e);if(!n?.nodeName)return null;if(Np(n)&&n.contentDocument)return Mp(n.contentDocument.body,t);if(t){let e=n.getAttribute(`aria-activedescendant`);if(e){let t=jp(n).getElementById(e);if(t)return t}}return n}Dp(Mp,`getActiveElement`);function Np(e){return e.tagName===`IFRAME`}Dp(Np,`isFrame`);var Pp=Object.defineProperty,Fp=(e,t)=>Pp(e,`name`,{value:t,configurable:!0});function Ip(e,t){if(typeof e==`function`)return e(t);e!=null&&(e.current=t)}Fp(Ip,`setRef`);function Lp(...e){return t=>{let n=!1,r=e.map(e=>{let r=Ip(e,t);return!n&&typeof r==`function`&&(n=!0),r});if(n)return()=>{for(let t=0;tzp(e,`name`,{value:t,configurable:!0});function Vp(e,t){let n=m.createContext(t);n.displayName=e+`Context`;let r=Bp(e=>{let{children:t,...r}=e,i=m.useMemo(()=>r,Object.values(r));return(0,h.jsx)(n.Provider,{value:i,children:t})},`Provider`);r.displayName=e+`Provider`;function i(r,i={}){let{optional:a=!1}=i,o=m.useContext(n);if(o)return o;if(t!==void 0)return t;if(!a)throw Error(`\`${r}\` must be used within \`${e}\``)}return Bp(i,`useContext`),[r,i]}Bp(Vp,`createContext`);function Hp(e,t=[]){let n=[];function r(t,r){let i=m.createContext(r);i.displayName=t+`Context`;let a=n.length;n=[...n,r];let o=Bp(t=>{let{scope:n,children:r,...o}=t,s=n?.[e]?.[a]||i,c=m.useMemo(()=>o,Object.values(o));return(0,h.jsx)(s.Provider,{value:c,children:r})},`Provider`);o.displayName=t+`Provider`;function s(n,o,s={}){let{optional:c=!1}=s,l=o?.[e]?.[a]||i,u=m.useContext(l);if(u)return u;if(r!==void 0)return r;if(!c)throw Error(`\`${n}\` must be used within \`${t}\``)}return Bp(s,`useContext`),[o,s]}Bp(r,`createContext`);let i=Bp(()=>{let t=n.map(e=>m.createContext(e));return Bp(function(n){let r=n?.[e]||t;return m.useMemo(()=>({[`__scope${e}`]:{...n,[e]:r}}),[n,r])},`useScope`)},`createScope`);return i.scopeName=e,[r,Up(i,...t)]}Bp(Hp,`createContextScope`);function Up(...e){let t=e[0];if(e.length===1)return t;let n=Bp(()=>{let n=e.map(e=>({useScope:e(),scopeName:e.scopeName}));return Bp(function(e){let r=n.reduce((t,{useScope:n,scopeName:r})=>{let i=n(e)[`__scope${r}`];return{...t,...i}},{});return m.useMemo(()=>({[`__scope${t.scopeName}`]:r}),[r])},`useComposedScopes`)},`createScope`);return n.scopeName=t.scopeName,n}Bp(Up,`composeContextScopes`);var Wp=globalThis?.document?m.useLayoutEffect:()=>{},Gp=Object.defineProperty,Kp=(e,t)=>Gp(e,`name`,{value:t,configurable:!0}),qp=m.useId||(()=>void 0),Jp=0;function Yp(e){let[t,n]=m.useState(qp());return Wp(()=>{e||n(e=>e??String(Jp++))},[e]),e||(t?`radix-${t}`:``)}Kp(Yp,`useId`);var Xp=Object.defineProperty,Zp=(e,t)=>Xp(e,`name`,{value:t,configurable:!0}),Qp=m.useEffectEvent,$p=m.useInsertionEffect;function em(e){if(typeof Qp==`function`)return Qp(e);let t=m.useRef(()=>{throw Error(`Cannot call an event handler while rendering.`)});return typeof $p==`function`?$p(()=>{t.current=e}):Wp(()=>{t.current=e}),m.useMemo(()=>((...e)=>t.current?.(...e)),[])}Zp(em,`useEffectEvent`);var tm=Object.defineProperty,nm=(e,t)=>tm(e,`name`,{value:t,configurable:!0}),rm=m.useInsertionEffect||Wp;function im({prop:e,defaultProp:t,onChange:n=nm(()=>{},`onChange`),caller:r}){let[i,a,o]=am({defaultProp:t,onChange:n}),s=e!==void 0;return[s?e:i,m.useCallback(t=>{if(s){let n=om(t)?t(e):t;n!==e&&o.current?.(n)}else a(t)},[s,e,a,o])]}nm(im,`useControllableState`);function am({defaultProp:e,onChange:t}){let[n,r]=m.useState(e),i=m.useRef(n),a=m.useRef(t);return rm(()=>{a.current=t},[t]),m.useEffect(()=>{i.current!==n&&(a.current?.(n),i.current=n)},[n,i]),[n,r,a]}nm(am,`useUncontrolledState`);function om(e){return typeof e==`function`}nm(om,`isFunction`);var sm=Symbol(`RADIX:SYNC_STATE`);function cm(e,t,n,r){let{prop:i,defaultProp:a,onChange:o,caller:s}=t,c=i!==void 0,l=em(o),u=[{...n,state:a}];r&&u.push(r);let[d,f]=m.useReducer((t,n)=>{if(n.type===sm)return{...t,state:n.state};let r=e(t,n);return c&&!Object.is(r.state,t.state)&&l(r.state),r},...u),p=d.state,h=m.useRef(p);m.useEffect(()=>{h.current!==p&&(h.current=p,c||l(p))},[p,h,c]);let g=m.useMemo(()=>i===void 0?d:{...d,state:i},[d,i]);return m.useEffect(()=>{c&&!Object.is(i,d.state)&&f({type:sm,state:i})},[i,d.state,c]),[g,f]}nm(cm,`useControllableStateReducer`);var lm=o((e=>{var t=p();function n(e){var t=`https://react.dev/errors/`+e;if(1{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=lm()})),dm=l(um(),1),fm=Object.defineProperty,pm=(e,t)=>fm(e,`name`,{value:t,configurable:!0});function mm(e){let t=m.forwardRef((t,n)=>{let{children:r,...i}=t,a=null,o=!1,s=[];Cm(r)&&typeof Dm==`function`&&(r=Dm(r._payload)),m.Children.forEach(r,e=>{if(xm(e)){o=!0;let t=e,n=`child`in t.props?t.props.child:t.props.children;Cm(n)&&typeof Dm==`function`&&(n=Dm(n._payload)),a=vm(t,n),s.push(a?.props?.children)}else s.push(e)}),a?a=m.cloneElement(a,void 0,s):!o&&m.Children.count(r)===1&&m.isValidElement(r)&&(a=r);let c=a?bm(a):void 0,l=Rp(n,c);if(!a){if(r||r===0)throw Error(o?Em(e):Tm(e));return r}let u=ym(i,a.props??{});return a.type!==m.Fragment&&(u.ref=n?l:c),m.cloneElement(a,u)});return t.displayName=`${e}.Slot`,t}pm(mm,`createSlot`);var hm=mm(`Slot`),gm=Symbol.for(`radix.slottable`);function _m(e){let t=pm(e=>`child`in e?e.children(e.child):e.children,`Slottable`);return t.displayName=`${e}.Slottable`,t.__radixId=gm,t}pm(_m,`createSlottable`);var vm=pm((e,t)=>{if(`child`in e.props){let t=e.props.child;return m.isValidElement(t)?m.cloneElement(t,void 0,e.props.children(t.props.children)):null}return m.isValidElement(t)?t:null},`getSlottableElementFromSlottable`);function ym(e,t){let n={...t};for(let r in t){let i=e[r],a=t[r];/^on[A-Z]/.test(r)?i&&a?n[r]=(...e)=>{let t=a(...e);return i(...e),t}:i&&(n[r]=i):r===`style`?n[r]={...i,...a}:r===`className`&&(n[r]=[i,a].filter(Boolean).join(` `))}return{...e,...n}}pm(ym,`mergeProps`);function bm(e){let t=Object.getOwnPropertyDescriptor(e.props,`ref`)?.get,n=t&&`isReactWarning`in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,`ref`)?.get,n=t&&`isReactWarning`in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}pm(bm,`getElementRef`);function xm(e){return m.isValidElement(e)&&typeof e.type==`function`&&`__radixId`in e.type&&e.type.__radixId===gm}pm(xm,`isSlottable`);var Sm=Symbol.for(`react.lazy`);function Cm(e){return typeof e==`object`&&!!e&&`$$typeof`in e&&e.$$typeof===Sm&&`_payload`in e&&wm(e._payload)}pm(Cm,`isLazyComponent`);function wm(e){return typeof e==`object`&&!!e&&`then`in e}pm(wm,`isPromiseLike`);var Tm=pm(e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,`createSlotError`),Em=pm(e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,`createSlottableError`),Dm=m.use,Om=Object.defineProperty,km=(e,t)=>Om(e,`name`,{value:t,configurable:!0}),Am=[`a`,`button`,`div`,`form`,`h2`,`h3`,`img`,`input`,`label`,`li`,`nav`,`ol`,`p`,`select`,`span`,`svg`,`ul`].reduce((e,t)=>{let n=mm(`Primitive.${t}`),r=m.forwardRef((e,r)=>{let{asChild:i,...a}=e,o=i?n:t;return typeof window<`u`&&(window[Symbol.for(`radix-ui`)]=!0),(0,h.jsx)(o,{...a,ref:r})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function jm(e,t){e&&dm.flushSync(()=>e.dispatchEvent(t))}km(jm,`dispatchDiscreteCustomEvent`);var Mm=Object.defineProperty,Nm=(e,t)=>Mm(e,`name`,{value:t,configurable:!0});function Pm(e){let t=m.useRef(e);return m.useEffect(()=>{t.current=e}),m.useMemo(()=>((...e)=>t.current?.(...e)),[])}Nm(Pm,`useCallbackRef`);var Fm=Object.defineProperty,Im=(e,t)=>Fm(e,`name`,{value:t,configurable:!0}),Lm=`dismissableLayer.update`,Rm=`dismissableLayer.pointerDownOutside`,zm=`dismissableLayer.focusOutside`,Bm,Vm=m.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Hm=m.forwardRef(Im(function(e,t){let{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:a,onFocusOutside:o,onInteractOutside:s,onDismiss:c,...l}=e,u=m.useContext(Vm),[d,f]=m.useState(null),p=d?.ownerDocument??globalThis?.document,[,g]=m.useState({}),_=Rp(t,f),v=Array.from(u.layers),[y]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),b=y?v.indexOf(y):-1,x=d?v.indexOf(d):-1,S=u.layersWithOutsidePointerEventsDisabled.size>0,C=x>=b,w=m.useRef(!1),T=Km(e=>{a?.(e),s?.(e),e.defaultPrevented||c?.()},{ownerDocument:p,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:w,dismissableSurfaces:u.dismissableSurfaces,shouldHandlePointerDownOutside:m.useCallback(e=>{if(!(e instanceof Node))return!1;let t=[...u.branches].some(t=>t.contains(e));return C&&!t},[u.branches,C])}),E=qm(e=>{if(r&&w.current)return;let t=e.target;[...u.branches].some(e=>e.contains(t))||(o?.(e),s?.(e),e.defaultPrevented||c?.())},p),D=d?x===v.length-1:!1,O=Pm(e=>{e.key===`Escape`&&(i?.(e),!e.defaultPrevented&&c&&(e.preventDefault(),c()))});return m.useEffect(()=>{if(D)return p.addEventListener(`keydown`,O,{capture:!0}),()=>p.removeEventListener(`keydown`,O,{capture:!0})},[p,D,O]),m.useEffect(()=>{if(d)return n&&(u.layersWithOutsidePointerEventsDisabled.size===0&&(Bm=p.body.style.pointerEvents,p.body.style.pointerEvents=`none`),u.layersWithOutsidePointerEventsDisabled.add(d)),u.layers.add(d),Jm(),()=>{n&&(u.layersWithOutsidePointerEventsDisabled.delete(d),u.layersWithOutsidePointerEventsDisabled.size===0&&(p.body.style.pointerEvents=Bm))}},[d,p,n,u]),m.useEffect(()=>()=>{d&&(u.layers.delete(d),u.layersWithOutsidePointerEventsDisabled.delete(d),Jm())},[d,u]),m.useEffect(()=>{let e=Im(()=>g({}),`handleUpdate`);return document.addEventListener(Lm,e),()=>document.removeEventListener(Lm,e)},[]),(0,h.jsx)(Am.div,{...l,ref:_,style:{pointerEvents:S?C?`auto`:`none`:void 0,...e.style},onFocusCapture:kp(e.onFocusCapture,E.onFocusCapture),onBlurCapture:kp(e.onBlurCapture,E.onBlurCapture),onPointerDownCapture:kp(e.onPointerDownCapture,T.onPointerDownCapture)})},`DismissableLayer`)),Um=m.forwardRef(Im(function(e,t){let n=m.useContext(Vm),r=m.useRef(null),i=Rp(t,r);return m.useEffect(()=>{let e=r.current;if(e)return n.branches.add(e),()=>{n.branches.delete(e)}},[n.branches]),(0,h.jsx)(Am.div,{...e,ref:i})},`DismissableLayerBranch`));function Wm(){let e=m.useContext(Vm),[t,n]=m.useState(null);return m.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}Im(Wm,`useDismissableLayerSurface`);var Gm=Im(()=>!0,`IS_TRUE`);function Km(e,t){let{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:a,shouldHandlePointerDownOutside:o=Gm}=t,s=Pm(e),c=m.useRef(!1),l=m.useRef(!1),u=m.useRef(new Map),d=m.useRef(()=>{});return m.useEffect(()=>{function e(){l.current=!1,i.current=!1,u.current.clear()}Im(e,`resetOutsideInteraction`);function t(){return Array.from(u.current.values()).some(Boolean)}Im(t,`isOutsideInteractionIntercepted`);function f(e){if(!l.current)return;let t=e.target;t instanceof Node&&[...a].some(e=>e.contains(t))||u.current.set(e.type,!0),e.type===`click`&&window.setTimeout(()=>{l.current&&d.current()},0)}Im(f,`handleInteractionCapture`);function p(e){l.current&&u.current.set(e.type,!1)}Im(p,`handleInteractionBubble`);let m=Im(a=>{if(a.target&&!c.current){let f=function(){n.removeEventListener(`click`,d.current);let r=t();e(),r||Ym(Rm,s,p,{discrete:!0})};if(Im(f,`handleAndDispatchPointerDownOutsideEvent`),!o(a.target)){n.removeEventListener(`click`,d.current),e(),c.current=!1;return}let p={originalEvent:a};l.current=!0,i.current=r&&a.button===0,u.current.clear(),!r||a.button!==0?f():(n.removeEventListener(`click`,d.current),d.current=f,n.addEventListener(`click`,d.current,{once:!0}))}else n.removeEventListener(`click`,d.current),e();c.current=!1},`handlePointerDown`),h=[`pointerup`,`mousedown`,`mouseup`,`touchstart`,`touchend`,`click`];for(let e of h)n.addEventListener(e,f,!0),n.addEventListener(e,p);let g=window.setTimeout(()=>{n.addEventListener(`pointerdown`,m)},0);return()=>{window.clearTimeout(g),n.removeEventListener(`pointerdown`,m),n.removeEventListener(`click`,d.current);for(let e of h)n.removeEventListener(e,f,!0),n.removeEventListener(e,p)}},[n,s,r,i,a,o]),{onPointerDownCapture:Im(()=>c.current=!0,`onPointerDownCapture`)}}Im(Km,`usePointerDownOutside`);function qm(e,t=globalThis?.document){let n=Pm(e),r=m.useRef(!1);return m.useEffect(()=>{let e=Im(e=>{e.target&&!r.current&&Ym(zm,n,{originalEvent:e},{discrete:!1})},`handleFocus`);return t.addEventListener(`focusin`,e),()=>t.removeEventListener(`focusin`,e)},[t,n]),{onFocusCapture:Im(()=>r.current=!0,`onFocusCapture`),onBlurCapture:Im(()=>r.current=!1,`onBlurCapture`)}}Im(qm,`useFocusOutside`);function Jm(){let e=new CustomEvent(Lm);document.dispatchEvent(e)}Im(Jm,`dispatchUpdate`);function Ym(e,t,n,{discrete:r}){let i=n.originalEvent.target,a=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?jm(i,a):i.dispatchEvent(a)}Im(Ym,`handleAndDispatchCustomEvent`);var Xm=Hm,Zm=Um,Qm=Object.defineProperty,$m=(e,t)=>Qm(e,`name`,{value:t,configurable:!0}),eh=`focusScope.autoFocusOnMount`,th=`focusScope.autoFocusOnUnmount`,nh={bubbles:!1,cancelable:!0},rh=m.forwardRef($m(function(e,t){let{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:a,...o}=e,[s,c]=m.useState(null),l=Pm(i),u=Pm(a),d=m.useRef(null),f=Rp(t,c),p=m.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;m.useEffect(()=>{if(r){let e=function(e){if(p.paused||!s)return;let t=e.target;s.contains(t)?d.current=t:uh(d.current,{select:!0})},t=function(e){if(p.paused||!s)return;let t=e.relatedTarget;t!==null&&(s.contains(t)||uh(d.current,{select:!0}))},n=function(e){if(document.activeElement===document.body)for(let t of e)t.removedNodes.length>0&&uh(s)};$m(e,`handleFocusIn`),$m(t,`handleFocusOut`),$m(n,`handleMutations`),document.addEventListener(`focusin`,e),document.addEventListener(`focusout`,t);let r=new MutationObserver(n);return s&&r.observe(s,{childList:!0,subtree:!0}),()=>{document.removeEventListener(`focusin`,e),document.removeEventListener(`focusout`,t),r.disconnect()}}},[r,s,p.paused]),m.useEffect(()=>{if(s){dh.add(p);let e=document.activeElement;if(!s.contains(e)){let t=new CustomEvent(eh,nh);s.addEventListener(eh,l),s.dispatchEvent(t),t.defaultPrevented||(ih(mh(oh(s)),{select:!0}),document.activeElement===e&&uh(s))}return()=>{s.removeEventListener(eh,l),setTimeout(()=>{let t=new CustomEvent(th,nh);s.addEventListener(th,u),s.dispatchEvent(t),t.defaultPrevented||uh(e??document.body,{select:!0}),s.removeEventListener(th,u),dh.remove(p)},0)}}},[s,l,u,p]);let g=m.useCallback(e=>{if(!n&&!r||p.paused)return;let t=e.key===`Tab`&&!e.altKey&&!e.ctrlKey&&!e.metaKey,i=document.activeElement;if(t&&i){let t=e.currentTarget,[r,a]=ah(t);r&&a?!e.shiftKey&&i===a?(e.preventDefault(),n&&uh(r,{select:!0})):e.shiftKey&&i===r&&(e.preventDefault(),n&&uh(a,{select:!0})):i===t&&e.preventDefault()}},[n,r,p.paused]);return(0,h.jsx)(Am.div,{tabIndex:-1,...o,ref:f,onKeyDown:g})},`FocusScope`));function ih(e,{select:t=!1}={}){let n=document.activeElement;for(let r of e)if(uh(r,{select:t}),document.activeElement!==n)return}$m(ih,`focusFirst`);function ah(e){let t=oh(e);return[sh(t,e),sh(t.reverse(),e)]}$m(ah,`getTabbableEdges`);function oh(e){let t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:$m(e=>{let t=e.tagName===`INPUT`&&e.type===`hidden`;return e.disabled||e.hidden||t?NodeFilter.FILTER_SKIP:e.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},`acceptNode`)});for(;n.nextNode();)t.push(n.currentNode);return t}$m(oh,`getTabbableCandidates`);function sh(e,t){let n=typeof t.checkVisibility==`function`&&t.checkVisibility({checkVisibilityCSS:!0});for(let r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):ch(r,{upTo:t})))return r}$m(sh,`findVisible`);function ch(e,{upTo:t}){if(getComputedStyle(e).visibility===`hidden`)return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display===`none`)return!0;e=e.parentElement}return!1}$m(ch,`isHidden`);function lh(e){return e instanceof HTMLInputElement&&`select`in e}$m(lh,`isSelectableInput`);function uh(e,{select:t=!1}={}){if(e&&e.focus){let n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&lh(e)&&t&&e.select()}}$m(uh,`focus`);var dh=fh();function fh(){let e=[];return{add(t){let n=e[0];t!==n&&n?.pause(),e=ph(e,t),e.unshift(t)},remove(t){e=ph(e,t),e[0]?.resume()}}}$m(fh,`createFocusScopesStack`);function ph(e,t){let n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}$m(ph,`arrayRemove`);function mh(e){return e.filter(e=>e.tagName!==`A`)}$m(mh,`removeLinks`);var hh=Object.defineProperty,gh=m.forwardRef(((e,t)=>hh(e,`name`,{value:t,configurable:!0}))(function(e,t){let{container:n,...r}=e,[i,a]=m.useState(!1);Wp(()=>a(!0),[]);let o=n||i&&globalThis?.document?.body;return o?dm.createPortal((0,h.jsx)(Am.div,{...r,ref:t}),o):null},`Portal`)),_h=Object.defineProperty,vh=(e,t)=>_h(e,`name`,{value:t,configurable:!0});function yh(e,t){return m.useReducer((e,n)=>t[e][n]??e,e)}vh(yh,`useStateMachine`);var bh=vh(e=>{let{present:t,children:n}=e,r=xh(t),i=typeof n==`function`?n({present:r.isPresent}):m.Children.only(n),a=Ch(r.ref,Th(i));return typeof n==`function`||r.isPresent?m.cloneElement(i,{ref:a}):null},`Presence`);function xh(e){let[t,n]=m.useState(),r=m.useRef(null),i=m.useRef(e),a=m.useRef(`none`),o=m.useRef(void 0),[s,c]=yh(e?`mounted`:`unmounted`,{mounted:{UNMOUNT:`unmounted`,ANIMATION_OUT:`unmountSuspended`},unmountSuspended:{MOUNT:`mounted`,ANIMATION_END:`unmounted`},unmounted:{MOUNT:`mounted`}});return m.useEffect(()=>{s===`mounted`?(a.current=o.current??wh(r.current),o.current=void 0):a.current=`none`},[s]),Wp(()=>{let t=r.current,n=i.current;if(n!==e){let r=a.current,s=wh(t);e?(o.current=s,c(`MOUNT`)):s===`none`||t?.display===`none`?c(`UNMOUNT`):c(n&&r!==s?`ANIMATION_OUT`:`UNMOUNT`),i.current=e}},[e,c]),Wp(()=>{if(t){let e,n=t.ownerDocument.defaultView??window,o=vh(a=>{let o=wh(r.current).includes(CSS.escape(a.animationName));if(a.target===t&&o&&(c(`ANIMATION_END`),!i.current)){let r=t.style.animationFillMode;t.style.animationFillMode=`forwards`,e=n.setTimeout(()=>{t.style.animationFillMode===`forwards`&&(t.style.animationFillMode=r)})}},`handleAnimationEnd`),s=vh(e=>{e.target===t&&(a.current=wh(r.current))},`handleAnimationStart`);return t.addEventListener(`animationstart`,s),t.addEventListener(`animationcancel`,o),t.addEventListener(`animationend`,o),()=>{n.clearTimeout(e),t.removeEventListener(`animationstart`,s),t.removeEventListener(`animationcancel`,o),t.removeEventListener(`animationend`,o)}}c(`ANIMATION_END`)},[t,c]),{isPresent:[`mounted`,`unmountSuspended`].includes(s),ref:m.useCallback(e=>{if(e){let t=getComputedStyle(e);r.current=t,o.current=wh(t)}else r.current=null;n(e)},[])}}vh(xh,`usePresence`);function Sh(e,t){if(typeof e==`function`)return e(t);e!=null&&(e.current=t)}vh(Sh,`setRef`);function Ch(...e){let t=m.useRef(e);return t.current=e,m.useCallback(e=>{let n=t.current,r=!1,i=n.map(t=>{let n=Sh(t,e);return!r&&typeof n==`function`&&(r=!0),n});if(r)return()=>{for(let e=0;eEh(e,`name`,{value:t,configurable:!0}),Oh=0,kh=null;function Ah(e){return jh(),e.children}Dh(Ah,`FocusGuards`);function jh(){m.useEffect(()=>{kh||={start:Mh(),end:Mh()};let{start:e,end:t}=kh;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement(`afterbegin`,e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement(`beforeend`,t),Oh++,()=>{Oh===1&&(kh?.start.remove(),kh?.end.remove(),kh=null),Oh=Math.max(0,Oh-1)}},[])}Dh(jh,`useFocusGuards`);function Mh(){let e=document.createElement(`span`);return e.setAttribute(`data-radix-focus-guard`,``),e.tabIndex=0,e.style.outline=`none`,e.style.opacity=`0`,e.style.position=`fixed`,e.style.pointerEvents=`none`,e}Dh(Mh,`createFocusGuard`);var Nh=function(){return Nh=Object.assign||function(e){for(var t,n=1,r=arguments.length;n`u`)return og;var t=cg(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},ug=ag(),dg=`data-scroll-locked`,fg=function(e,t,n,r){var i=e.left,a=e.top,o=e.right,s=e.gap;return n===void 0&&(n=`margin`),` + .${Rh} { + overflow: hidden ${r}; + padding-right: ${s}px ${r}; + } + body[${dg}] { + overflow: hidden ${r}; + overscroll-behavior: contain; + ${[t&&`position: relative ${r};`,n===`margin`&&` + padding-left: ${i}px; + padding-top: ${a}px; + padding-right: ${o}px; + margin-left:0; + margin-top:0; + margin-right: ${s}px ${r}; + `,n===`padding`&&`padding-right: ${s}px ${r};`].filter(Boolean).join(``)} + } + + .${Ih} { + right: ${s}px ${r}; + } + + .${Lh} { + margin-right: ${s}px ${r}; + } + + .${Ih} .${Ih} { + right: 0 ${r}; + } + + .${Lh} .${Lh} { + margin-right: 0 ${r}; + } + + body[${dg}] { + ${zh}: ${s}px; + } +`},pg=function(){var e=parseInt(document.body.getAttribute(`data-scroll-locked`)||`0`,10);return isFinite(e)?e:0},mg=function(){m.useEffect(function(){return document.body.setAttribute(dg,(pg()+1).toString()),function(){var e=pg()-1;e<=0?document.body.removeAttribute(dg):document.body.setAttribute(dg,e.toString())}},[])},hg=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?`margin`:r;mg();var a=m.useMemo(function(){return lg(i)},[i]);return m.createElement(ug,{styles:fg(a,!t,i,n?``:`!important`)})},gg=!1;if(typeof window<`u`)try{var _g=Object.defineProperty({},"passive",{get:function(){return gg=!0,!0}});window.addEventListener(`test`,_g,_g),window.removeEventListener(`test`,_g,_g)}catch{gg=!1}var vg=gg?{passive:!1}:!1,yg=function(e){return e.tagName===`TEXTAREA`},bg=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!==`hidden`&&!(n.overflowY===n.overflowX&&!yg(e)&&n[t]===`visible`)},xg=function(e){return bg(e,`overflowY`)},Sg=function(e){return bg(e,`overflowX`)},Cg=function(e,t){var n=t.ownerDocument,r=t;do{if(typeof ShadowRoot<`u`&&r instanceof ShadowRoot&&(r=r.host),Eg(e,r)){var i=Dg(e,r);if(i[1]>i[2])return!0}r=r.parentNode}while(r&&r!==n.body);return!1},wg=function(e){return[e.scrollTop,e.scrollHeight,e.clientHeight]},Tg=function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]},Eg=function(e,t){return e===`v`?xg(t):Sg(t)},Dg=function(e,t){return e===`v`?wg(t):Tg(t)},Og=function(e,t){return e===`h`&&t===`rtl`?-1:1},kg=function(e,t,n,r,i){var a=Og(e,window.getComputedStyle(t).direction),o=a*r,s=n.target,c=t.contains(s),l=!1,u=o>0,d=0,f=0;do{if(!s)break;var p=Dg(e,s),m=p[0],h=p[1]-p[2]-a*m;(m||h)&&Eg(e,s)&&(d+=h,f+=m);var g=s.parentNode;s=g&&g.nodeType===Node.DOCUMENT_FRAGMENT_NODE?g.host:g}while(!c&&s!==document.body||c&&(t.contains(s)||t===s));return(u&&(i&&Math.abs(d)<1||!i&&o>d)||!u&&(i&&Math.abs(f)<1||!i&&-o>f))&&(l=!0),l},Ag=function(e){return`changedTouches`in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},jg=function(e){return[e.deltaX,e.deltaY]},Mg=function(e){return e&&`current`in e?e.current:e},Ng=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Pg=function(e){return` + .block-interactivity-${e} {pointer-events: none;} + .allow-interactivity-${e} {pointer-events: all;} +`},Fg=0,Ig=[];function Lg(e){var t=m.useRef([]),n=m.useRef([0,0]),r=m.useRef(),i=m.useState(Fg++)[0],a=m.useState(ag)[0],o=m.useRef(e);m.useEffect(function(){o.current=e},[e]),m.useEffect(function(){if(e.inert){document.body.classList.add(`block-interactivity-${i}`);var t=Fh([e.lockRef.current],(e.shards||[]).map(Mg),!0).filter(Boolean);return t.forEach(function(e){return e.classList.add(`allow-interactivity-${i}`)}),function(){document.body.classList.remove(`block-interactivity-${i}`),t.forEach(function(e){return e.classList.remove(`allow-interactivity-${i}`)})}}},[e.inert,e.lockRef.current,e.shards]);var s=m.useCallback(function(e,t){if(`touches`in e&&e.touches.length===2||e.type===`wheel`&&e.ctrlKey)return!o.current.allowPinchZoom;var i=Ag(e),a=n.current,s=`deltaX`in e?e.deltaX:a[0]-i[0],c=`deltaY`in e?e.deltaY:a[1]-i[1],l,u=e.target,d=Math.abs(s)>Math.abs(c)?`h`:`v`;if(`touches`in e&&d===`h`&&u.type===`range`)return!1;var f=window.getSelection(),p=f&&f.anchorNode;if(p&&(p===u||p.contains(u)))return!1;var m=Cg(d,u);if(!m)return!0;if(m?l=d:(l=d===`v`?`h`:`v`,m=Cg(d,u)),!m)return!1;if(!r.current&&`changedTouches`in e&&(s||c)&&(r.current=l),!l)return!0;var h=r.current||l;return kg(h,t,e,h===`h`?s:c,!0)},[]),c=m.useCallback(function(e){var n=e;if(!(!Ig.length||Ig[Ig.length-1]!==a)){var r=`deltaY`in n?jg(n):Ag(n),i=t.current.filter(function(e){return e.name===n.type&&(e.target===n.target||n.target===e.shadowParent)&&Ng(e.delta,r)})[0];if(i&&i.should){n.cancelable&&n.preventDefault();return}if(!i){var c=(o.current.shards||[]).map(Mg).filter(Boolean).filter(function(e){return e.contains(n.target)});(c.length>0?s(n,c[0]):!o.current.noIsolation)&&n.cancelable&&n.preventDefault()}}},[]),l=m.useCallback(function(e,n,r,i){var a={name:e,delta:n,target:r,should:i,shadowParent:Rg(r)};t.current.push(a),setTimeout(function(){t.current=t.current.filter(function(e){return e!==a})},1)},[]),u=m.useCallback(function(e){n.current=Ag(e),r.current=void 0},[]),d=m.useCallback(function(t){l(t.type,jg(t),t.target,s(t,e.lockRef.current))},[]),f=m.useCallback(function(t){l(t.type,Ag(t),t.target,s(t,e.lockRef.current))},[]);m.useEffect(function(){return Ig.push(a),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener(`wheel`,c,vg),document.addEventListener(`touchmove`,c,vg),document.addEventListener(`touchstart`,u,vg),function(){Ig=Ig.filter(function(e){return e!==a}),document.removeEventListener(`wheel`,c,vg),document.removeEventListener(`touchmove`,c,vg),document.removeEventListener(`touchstart`,u,vg)}},[]);var p=e.removeScrollBar,h=e.inert;return m.createElement(m.Fragment,null,h?m.createElement(a,{styles:Pg(i)}):null,p?m.createElement(hg,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Rg(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var zg=Yh(Xh,Lg),Bg=m.forwardRef(function(e,t){return m.createElement(Qh,Nh({},e,{ref:t,sideCar:zg}))});Bg.classNames=Qh.classNames;var Vg=function(e){return typeof document>`u`?null:(Array.isArray(e)?e[0]:e).ownerDocument.body},Hg=new WeakMap,Ug=new WeakMap,Wg={},Gg=0,Kg=function(e){return e&&(e.host||Kg(e.parentNode))},qg=function(e,t){return t.map(function(t){if(e.contains(t))return t;var n=Kg(t);return n&&e.contains(n)?n:(console.error(`aria-hidden`,t,`in not contained inside`,e,`. Doing nothing`),null)}).filter(function(e){return!!e})},Jg=function(e,t,n,r){var i=qg(t,Array.isArray(e)?e:[e]);Wg[n]||(Wg[n]=new WeakMap);var a=Wg[n],o=[],s=new Set,c=new Set(i),l=function(e){!e||s.has(e)||(s.add(e),l(e.parentNode))};i.forEach(l);var u=function(e){!e||c.has(e)||Array.prototype.forEach.call(e.children,function(e){if(s.has(e))u(e);else try{var t=e.getAttribute(r),i=t!==null&&t!==`false`,c=(Hg.get(e)||0)+1,l=(a.get(e)||0)+1;Hg.set(e,c),a.set(e,l),o.push(e),c===1&&i&&Ug.set(e,!0),l===1&&e.setAttribute(n,`true`),i||e.setAttribute(r,`true`)}catch(t){console.error(`aria-hidden: cannot operate on `,e,t)}})};return u(t),s.clear(),Gg++,function(){o.forEach(function(e){var t=Hg.get(e)-1,i=a.get(e)-1;Hg.set(e,t),a.set(e,i),t||(Ug.has(e)||e.removeAttribute(r),Ug.delete(e)),i||e.removeAttribute(n)}),Gg--,Gg||(Hg=new WeakMap,Hg=new WeakMap,Ug=new WeakMap,Wg={})}},Yg=function(e,t,n){n===void 0&&(n=`data-aria-hidden`);var r=Array.from(Array.isArray(e)?e:[e]),i=t||Vg(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll(`[aria-live], script`))),Jg(r,i,n,`aria-hidden`)):function(){return null}},Xg=Object.defineProperty,Zg=(e,t)=>Xg(e,`name`,{value:t,configurable:!0}),Qg=`Dialog`,[$g,e_]=Hp(Qg),[t_,n_]=$g(Qg),r_=Zg(e=>{let{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:a,modal:o=!0}=e,s=m.useRef(null),c=m.useRef(null),[l,u]=im({prop:r,defaultProp:i??!1,onChange:a,caller:Qg}),[d,f]=m.useState(0),[p,g]=m.useState(0);return(0,h.jsx)(t_,{scope:t,triggerRef:s,contentRef:c,contentId:Yp(),titleId:Yp(),descriptionId:Yp(),titlePresent:d>0,descriptionPresent:p>0,setTitleCount:f,setDescriptionCount:g,open:l,onOpenChange:u,onOpenToggle:m.useCallback(()=>u(e=>!e),[u]),modal:o,children:n})},`Dialog`),i_=`DialogPortal`,[a_,o_]=$g(i_,{forceMount:void 0}),s_=Zg(e=>{let{__scopeDialog:t,forceMount:n,children:r,container:i}=e,a=n_(i_,t);return(0,h.jsx)(a_,{scope:t,forceMount:n,children:m.Children.map(r,e=>(0,h.jsx)(bh,{present:n||a.open,children:(0,h.jsx)(gh,{asChild:!0,container:i,children:e})}))})},`DialogPortal`),c_=`DialogOverlay`,l_=m.forwardRef(Zg(function(e,t){let n=o_(c_,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,a=n_(c_,e.__scopeDialog);return a.modal?(0,h.jsx)(bh,{present:r||a.open,children:(0,h.jsx)(d_,{...i,ref:t})}):null},`DialogOverlay`)),u_=mm(`DialogOverlay.RemoveScroll`),d_=m.forwardRef(Zg(function(e,t){let{__scopeDialog:n,...r}=e,i=n_(c_,n),a=Rp(t,Wm());return(0,h.jsx)(Bg,{as:u_,allowPinchZoom:!0,shards:[i.contentRef],children:(0,h.jsx)(Am.div,{"data-state":C_(i.open),...r,ref:a,style:{pointerEvents:`auto`,...r.style}})})},`DialogOverlayImpl`)),f_=`DialogContent`,p_=m.forwardRef(Zg(function(e,t){let n=o_(f_,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,a=n_(f_,e.__scopeDialog);return(0,h.jsx)(bh,{present:r||a.open,children:a.modal?(0,h.jsx)(m_,{...i,ref:t}):(0,h.jsx)(h_,{...i,ref:t})})},`DialogContent`)),m_=m.forwardRef(Zg(function(e,t){let n=n_(f_,e.__scopeDialog),r=m.useRef(null),i=Rp(t,n.contentRef,r);return m.useEffect(()=>{let e=r.current;if(e)return Yg(e)},[]),(0,h.jsx)(g_,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,onCloseAutoFocus:kp(e.onCloseAutoFocus,e=>{e.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:kp(e.onPointerDownOutside,e=>{let t=e.detail.originalEvent,n=t.button===0&&t.ctrlKey===!0;(t.button===2||n)&&e.preventDefault()}),onFocusOutside:kp(e.onFocusOutside,e=>e.preventDefault())})},`DialogContentModal`)),h_=m.forwardRef(Zg(function(e,t){let n=n_(f_,e.__scopeDialog),r=m.useRef(!1),i=m.useRef(!1);return(0,h.jsx)(g_,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:t=>{e.onCloseAutoFocus?.(t),t.defaultPrevented||(r.current||n.triggerRef.current?.focus(),t.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:t=>{e.onInteractOutside?.(t),t.defaultPrevented||(r.current=!0,t.detail.originalEvent.type===`pointerdown`&&(i.current=!0));let a=t.target;n.triggerRef.current?.contains(a)&&t.preventDefault(),t.detail.originalEvent.type===`focusin`&&i.current&&t.preventDefault()}})},`DialogContentNonModal`)),g_=m.forwardRef(Zg(function(e,t){let{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:a,...o}=e,s=n_(f_,n);return jh(),(0,h.jsx)(h.Fragment,{children:(0,h.jsx)(rh,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:a,children:(0,h.jsx)(Hm,{role:`dialog`,id:s.contentId,"aria-describedby":s.descriptionPresent?s.descriptionId:void 0,"aria-labelledby":s.titlePresent?s.titleId:void 0,"data-state":C_(s.open),...o,ref:t,deferPointerDownOutside:!0,onDismiss:()=>s.onOpenChange(!1)})})})},`DialogContentImpl`)),__=`DialogTitle`,v_=m.forwardRef(Zg(function(e,t){let{__scopeDialog:n,...r}=e,i=n_(__,n),{setTitleCount:a}=i;return Wp(()=>(a(e=>e+1),()=>a(e=>e-1)),[a]),(0,h.jsx)(Am.h2,{id:i.titleId,...r,ref:t})},`DialogTitle`)),y_=`DialogDescription`,b_=m.forwardRef(Zg(function(e,t){let{__scopeDialog:n,...r}=e,i=n_(y_,n),{setDescriptionCount:a}=i;return Wp(()=>(a(e=>e+1),()=>a(e=>e-1)),[a]),(0,h.jsx)(Am.p,{id:i.descriptionId,...r,ref:t})},`DialogDescription`)),x_=`DialogClose`,S_=m.forwardRef(Zg(function(e,t){let{__scopeDialog:n,...r}=e,i=n_(x_,n);return(0,h.jsx)(Am.button,{type:`button`,...r,ref:t,onClick:kp(e.onClick,()=>i.onOpenChange(!1))})},`DialogClose`));function C_(e){return e?`open`:`closed`}Zg(C_,`getState`);var w_=Object.defineProperty,T_=(e,t)=>w_(e,`name`,{value:t,configurable:!0});function E_(e){let t=e+`CollectionProvider`,[n,r]=Hp(t),[i,a]=n(t,{collectionRef:{current:null},itemMap:new Map}),o=T_(e=>{let{scope:t,children:n}=e,r=m.useRef(null),a=m.useRef(new Map).current;return(0,h.jsx)(i,{scope:t,itemMap:a,collectionRef:r,children:n})},`CollectionProvider`);o.displayName=t;let s=e+`CollectionSlot`,c=mm(s),l=m.forwardRef((e,t)=>{let{scope:n,children:r}=e,i=Rp(t,a(s,n).collectionRef);return(0,h.jsx)(c,{ref:i,children:r})});l.displayName=s;let u=e+`CollectionItemSlot`,d=`data-radix-collection-item`,f=mm(u),p=m.forwardRef((e,t)=>{let{scope:n,children:r,...i}=e,o=m.useRef(null),s=Rp(t,o),c=a(u,n);return m.useEffect(()=>(c.itemMap.set(o,{ref:o,...i}),()=>void c.itemMap.delete(o))),(0,h.jsx)(f,{[d]:``,ref:s,children:r})});p.displayName=u;function g(t){let n=a(e+`CollectionConsumer`,t);return m.useCallback(()=>{let e=n.collectionRef.current;if(!e)return[];let t=Array.from(e.querySelectorAll(`[${d}]`));return Array.from(n.itemMap.values()).sort((e,n)=>t.indexOf(e.ref.current)-t.indexOf(n.ref.current))},[n.collectionRef,n.itemMap])}return T_(g,`useCollection`),[{Provider:o,Slot:l,ItemSlot:p},g,r]}T_(E_,`createCollection`);var D_=new WeakMap,O_=class e extends Map{static{T_(this,`OrderedDict`)}#e;constructor(e){super(e),this.#e=[...super.keys()],D_.set(this,!0)}set(e,t){return D_.get(this)&&(this.has(e)?this.#e[this.#e.indexOf(e)]=e:this.#e.push(e)),super.set(e,t),this}insert(e,t,n){let r=this.has(t),i=this.#e.length,a=j_(e),o=a>=0?a:i+a,s=o<0||o>=i?-1:o;if(s===this.size||r&&s===this.size-1||s===-1)return this.set(t,n),this;let c=this.size+ +!r;a<0&&o++;let l=[...this.#e],u,d=!1;for(let e=o;e=this.size&&(r=this.size-1),this.at(r)}keyFrom(e,t){let n=this.indexOf(e);if(n===-1)return;let r=n+t;return r<0&&(r=0),r>=this.size&&(r=this.size-1),this.keyAt(r)}find(e,t){let n=0;for(let r of this){if(Reflect.apply(e,t,[r,n,this]))return r;n++}}findIndex(e,t){let n=0;for(let r of this){if(Reflect.apply(e,t,[r,n,this]))return n;n++}return-1}filter(t,n){let r=[],i=0;for(let e of this)Reflect.apply(t,n,[e,i,this])&&r.push(e),i++;return new e(r)}map(t,n){let r=[],i=0;for(let e of this)r.push([e[0],Reflect.apply(t,n,[e,i,this])]),i++;return new e(r)}reduce(...e){let[t,n]=e,r=0,i=n??this.at(0);for(let n of this)i=r===0&&e.length===1?n:Reflect.apply(t,this,[i,n,r,this]),r++;return i}reduceRight(...e){let[t,n]=e,r=n??this.at(-1);for(let n=this.size-1;n>=0;n--){let i=this.at(n);r=n===this.size-1&&e.length===1?i:Reflect.apply(t,this,[r,i,n,this])}return r}toSorted(t){let n=[...this.entries()].sort(t);return new e(n)}toReversed(){let t=new e;for(let e=this.size-1;e>=0;e--){let n=this.keyAt(e),r=this.get(n);t.set(n,r)}return t}toSpliced(...t){let n=[...this.entries()];return n.splice(...t),new e(n)}slice(t,n){let r=new e,i=this.size-1;if(t===void 0)return r;t<0&&(t+=this.size),n!==void 0&&n>0&&(i=n-1);for(let e=t;e<=i;e++){let t=this.keyAt(e),n=this.get(t);r.set(t,n)}return r}every(e,t){let n=0;for(let r of this){if(!Reflect.apply(e,t,[r,n,this]))return!1;n++}return!0}some(e,t){let n=0;for(let r of this){if(Reflect.apply(e,t,[r,n,this]))return!0;n++}return!1}};function k_(e,t){if(`at`in Array.prototype)return Array.prototype.at.call(e,t);let n=A_(e,t);return n===-1?void 0:e[n]}T_(k_,`at`);function A_(e,t){let n=e.length,r=j_(t),i=r>=0?r:n+r;return i<0||i>=n?-1:i}T_(A_,`toSafeIndex`);function j_(e){return e!==e||e===0?0:Math.trunc(e)}T_(j_,`toSafeInteger`);function M_(e){let t=e+`CollectionProvider`,[n,r]=Hp(t),[i,a]=n(t,{collectionElement:null,collectionRef:{current:null},collectionRefObject:{current:null},itemMap:new O_,setItemMap:T_(()=>void 0,`setItemMap`)}),o=T_(({state:e,...t})=>e?(0,h.jsx)(c,{...t,state:e}):(0,h.jsx)(s,{...t}),`CollectionProvider`);o.displayName=t;let s=T_(e=>{let t=_();return(0,h.jsx)(c,{...e,state:t})},`CollectionInit`);s.displayName=t+`Init`;let c=T_(e=>{let{scope:t,children:n,state:r}=e,a=m.useRef(null),[o,s]=m.useState(null),c=Rp(a,s),[l,u]=r;return m.useEffect(()=>{if(!o)return;let e=I_(()=>{});return e.observe(o,{childList:!0,subtree:!0}),()=>{e.disconnect()}},[o]),(0,h.jsx)(i,{scope:t,itemMap:l,setItemMap:u,collectionRef:c,collectionRefObject:a,collectionElement:o,children:n})},`CollectionProviderImpl`);c.displayName=t+`Impl`;let l=e+`CollectionSlot`,u=mm(l),d=m.forwardRef((e,t)=>{let{scope:n,children:r}=e,i=Rp(t,a(l,n).collectionRef);return(0,h.jsx)(u,{ref:i,children:r})});d.displayName=l;let f=e+`CollectionItemSlot`,p=mm(f),g=m.forwardRef((e,t)=>{let{scope:n,children:r,...i}=e,o=m.useRef(null),[s,c]=m.useState(null),l=Rp(t,o,c),{setItemMap:u}=a(f,n),d=m.useRef(i);N_(d.current,i)||(d.current=i);let g=d.current;return m.useEffect(()=>{let e=g;return u(t=>s?t.has(s)?t.set(s,{...e,element:s}).toSorted(F_):(t.set(s,{...e,element:s}),t.toSorted(F_)):t),()=>{u(e=>!s||!e.has(s)?e:(e.delete(s),new O_(e)))}},[s,g,u]),(0,h.jsx)(p,{"data-radix-collection-item":``,ref:l,children:r})});g.displayName=f;function _(){return m.useState(new O_)}T_(_,`useInitCollection`);function v(t){let{itemMap:n}=a(e+`CollectionConsumer`,t);return n}return T_(v,`useCollection`),[{Provider:o,Slot:d,ItemSlot:g},{createCollectionScope:r,useCollection:v,useInitCollection:_}]}T_(M_,`createCollection`);function N_(e,t){if(e===t)return!0;if(typeof e!=`object`||typeof t!=`object`||e==null||t==null)return!1;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||e[r]!==t[r])return!1;return!0}T_(N_,`shallowEqual`);function P_(e,t){return!!(t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_PRECEDING)}T_(P_,`isElementPreceding`);function F_(e,t){return!e[1].element||!t[1].element?0:P_(e[1].element,t[1].element)?-1:1}T_(F_,`sortByDocumentPosition`);function I_(e){return new MutationObserver(t=>{for(let n of t)if(n.type===`childList`){e();return}})}T_(I_,`getChildListObserver`);var L_=Object.defineProperty,R_=(e,t)=>L_(e,`name`,{value:t,configurable:!0}),z_=Object.freeze({position:`absolute`,border:0,width:1,height:1,padding:0,margin:-1,overflow:`hidden`,clip:`rect(0, 0, 0, 0)`,whiteSpace:`nowrap`,wordWrap:`normal`}),B_=m.forwardRef(R_(function(e,t){return(0,h.jsx)(Am.span,{...e,ref:t,style:{...z_,...e.style}})},`VisuallyHidden`)),V_=Object.defineProperty,H_=(e,t)=>V_(e,`name`,{value:t,configurable:!0}),U_=`ToastProvider`,[W_,G_,K_]=E_(`Toast`),[q_,J_]=Hp(`Toast`,[K_]),[Y_,X_]=q_(U_),Z_=H_(e=>{let{__scopeToast:t,label:n=`Notification`,duration:r=5e3,swipeDirection:i=`right`,swipeThreshold:a=50,announcerContainer:o,children:s}=e,[c,l]=m.useState(null),[u,d]=m.useState(0),f=m.useRef(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${U_}\`. Expected non-empty \`string\`.`),(0,h.jsx)(W_.Provider,{scope:t,children:(0,h.jsx)(Y_,{scope:t,label:n,duration:r,swipeDirection:i,swipeThreshold:a,toastCount:u,viewport:c,onViewportChange:l,onToastAdd:m.useCallback(()=>d(e=>e+1),[]),onToastRemove:m.useCallback(()=>d(e=>e-1),[]),isClosePausedRef:f,announcerContainer:o,children:s})})},`ToastProvider`),Q_=`ToastViewport`,$_=[`F8`],ev=`toast.viewportPause`,tv=`toast.viewportResume`,nv=m.forwardRef(H_(function(e,t){let{__scopeToast:n,hotkey:r=$_,label:i=`Notifications ({hotkey})`,...a}=e,o=X_(Q_,n),s=G_(n),c=m.useRef(null),l=m.useRef(null),u=m.useRef(null),d=m.useRef(null),f=Rp(t,d,o.onViewportChange),p=r.join(`+`).replace(/Key/g,``).replace(/Digit/g,``),g=o.toastCount>0;m.useEffect(()=>{let e=H_(e=>{r.length!==0&&r.every(t=>e[t]||e.code===t)&&d.current?.focus()},`handleKeyDown`);return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[r]),m.useEffect(()=>{let e=c.current,t=d.current;if(g&&e&&t){let n=H_(()=>{if(!o.isClosePausedRef.current){let e=new CustomEvent(ev);t.dispatchEvent(e),o.isClosePausedRef.current=!0}},`handlePause`),r=H_(()=>{if(o.isClosePausedRef.current){let e=new CustomEvent(tv);t.dispatchEvent(e),o.isClosePausedRef.current=!1}},`handleResume`),i=H_(t=>{e.contains(t.relatedTarget)||r()},`handleFocusOutResume`),a=H_(()=>{e.contains(document.activeElement)||r()},`handlePointerLeaveResume`);return e.addEventListener(`focusin`,n),e.addEventListener(`focusout`,i),e.addEventListener(`pointermove`,n),e.addEventListener(`pointerleave`,a),window.addEventListener(`blur`,n),window.addEventListener(`focus`,r),()=>{e.removeEventListener(`focusin`,n),e.removeEventListener(`focusout`,i),e.removeEventListener(`pointermove`,n),e.removeEventListener(`pointerleave`,a),window.removeEventListener(`blur`,n),window.removeEventListener(`focus`,r)}}},[g,o.isClosePausedRef]);let _=m.useCallback(({tabbingDirection:e})=>{let t=s().map(t=>{let n=t.ref.current,r=[n,...Sv(n)];return e===`forwards`?r:r.reverse()});return(e===`forwards`?t.reverse():t).flat()},[s]);return m.useEffect(()=>{let e=d.current;if(e){let t=H_(t=>{let n=t.altKey||t.ctrlKey||t.metaKey;if(t.key===`Tab`&&!n){let n=document.activeElement,r=t.shiftKey;if(t.target===e&&r){l.current?.focus();return}let i=_({tabbingDirection:r?`backwards`:`forwards`}),a=i.findIndex(e=>e===n);Cv(i.slice(a+1))?t.preventDefault():r?l.current?.focus():u.current?.focus()}},`handleKeyDown`);return e.addEventListener(`keydown`,t),()=>e.removeEventListener(`keydown`,t)}},[s,_]),(0,h.jsxs)(Zm,{ref:c,role:`region`,"aria-label":i.replace(`{hotkey}`,p),tabIndex:-1,style:{pointerEvents:g?void 0:`none`},children:[g&&(0,h.jsx)(iv,{ref:l,onFocusFromOutsideViewport:()=>{Cv(_({tabbingDirection:`forwards`}))}}),(0,h.jsx)(W_.Slot,{scope:n,children:(0,h.jsx)(Am.ol,{tabIndex:-1,...a,ref:f})}),g&&(0,h.jsx)(iv,{ref:u,onFocusFromOutsideViewport:()=>{Cv(_({tabbingDirection:`backwards`}))}})]})},`ToastViewport`)),rv=`ToastFocusProxy`,iv=m.forwardRef(H_(function(e,t){let{__scopeToast:n,onFocusFromOutsideViewport:r,...i}=e,a=X_(rv,n);return(0,h.jsx)(B_,{tabIndex:0,...i,ref:t,style:{position:`fixed`},onFocus:e=>{let t=e.relatedTarget;a.viewport?.contains(t)||r()}})},`ToastFocusProxy`)),av=`Toast`,ov=`toast.swipeStart`,sv=`toast.swipeMove`,cv=`toast.swipeCancel`,lv=`toast.swipeEnd`,uv=m.forwardRef(H_(function(e,t){let{forceMount:n,open:r,defaultOpen:i,onOpenChange:a,...o}=e,[s,c]=im({prop:r,defaultProp:i??!0,onChange:a,caller:av});return(0,h.jsx)(bh,{present:n||s,children:(0,h.jsx)(pv,{open:s,...o,ref:t,onClose:()=>c(!1),onPause:Pm(e.onPause),onResume:Pm(e.onResume),onSwipeStart:kp(e.onSwipeStart,e=>{e.currentTarget.setAttribute(`data-swipe`,`start`)}),onSwipeMove:kp(e.onSwipeMove,e=>{let{x:t,y:n}=e.detail.delta;e.currentTarget.setAttribute(`data-swipe`,`move`),e.currentTarget.style.setProperty(`--radix-toast-swipe-move-x`,`${t}px`),e.currentTarget.style.setProperty(`--radix-toast-swipe-move-y`,`${n}px`)}),onSwipeCancel:kp(e.onSwipeCancel,e=>{e.currentTarget.setAttribute(`data-swipe`,`cancel`),e.currentTarget.style.removeProperty(`--radix-toast-swipe-move-x`),e.currentTarget.style.removeProperty(`--radix-toast-swipe-move-y`),e.currentTarget.style.removeProperty(`--radix-toast-swipe-end-x`),e.currentTarget.style.removeProperty(`--radix-toast-swipe-end-y`)}),onSwipeEnd:kp(e.onSwipeEnd,e=>{let{x:t,y:n}=e.detail.delta;e.currentTarget.setAttribute(`data-swipe`,`end`),e.currentTarget.style.removeProperty(`--radix-toast-swipe-move-x`),e.currentTarget.style.removeProperty(`--radix-toast-swipe-move-y`),e.currentTarget.style.setProperty(`--radix-toast-swipe-end-x`,`${t}px`),e.currentTarget.style.setProperty(`--radix-toast-swipe-end-y`,`${n}px`),c(!1)})})})},`Toast`)),[dv,fv]=q_(av,{onClose(){}}),pv=m.forwardRef(H_(function(e,t){let{__scopeToast:n,type:r=`foreground`,duration:i,open:a,onClose:o,onEscapeKeyDown:s,onPause:c,onResume:l,onSwipeStart:u,onSwipeMove:d,onSwipeCancel:f,onSwipeEnd:p,...g}=e,_=X_(av,n),v=G_(n),[y,b]=m.useState(null),x=Rp(t,b),S=m.useRef(null),C=m.useRef(null),w=i||_.duration,T=m.useRef(0),E=m.useRef(w),D=m.useRef(0),{onToastAdd:O,onToastRemove:ee}=_,k=Pm(()=>{y?.contains(document.activeElement)&&_.viewport?.focus(),o()}),A=m.useCallback(e=>{!e||e===1/0||(window.clearTimeout(D.current),T.current=new Date().getTime(),D.current=window.setTimeout(k,e))},[k]);m.useEffect(()=>{let e=_.viewport;if(e){let t=H_(()=>{A(E.current),l?.()},`handleResume`),n=H_(()=>{let e=new Date().getTime()-T.current;E.current-=e,window.clearTimeout(D.current),c?.()},`handlePause`);return e.addEventListener(ev,n),e.addEventListener(tv,t),()=>{e.removeEventListener(ev,n),e.removeEventListener(tv,t)}}},[_.viewport,w,c,l,A]),m.useEffect(()=>{a&&!_.isClosePausedRef.current&&A(w)},[a,w,_.isClosePausedRef,A]),m.useEffect(()=>()=>{window.clearTimeout(D.current)},[]),m.useEffect(()=>(O(),()=>ee()),[O,ee]);let j=m.useMemo(()=>y?_v(y):null,[y]);return _.viewport?(0,h.jsxs)(h.Fragment,{children:[j&&(0,h.jsx)(mv,{__scopeToast:n,role:`status`,"aria-live":r===`foreground`?`assertive`:`polite`,children:j}),(0,h.jsx)(dv,{scope:n,onClose:k,children:dm.createPortal((0,h.jsx)(W_.ItemSlot,{scope:n,children:(0,h.jsx)(Xm,{asChild:!0,onEscapeKeyDown:kp(s,e=>{v().some(t=>t.ref.current?.contains(e.target))||k()}),children:(0,h.jsx)(Am.li,{tabIndex:0,"data-state":a?`open`:`closed`,"data-swipe-direction":_.swipeDirection,...g,ref:x,style:{userSelect:`none`,touchAction:`none`,...e.style},onKeyDown:kp(e.onKeyDown,e=>{e.key===`Escape`&&(s?.(e.nativeEvent),e.nativeEvent.defaultPrevented||k())}),onPointerDown:kp(e.onPointerDown,e=>{e.button===0&&(S.current={x:e.clientX,y:e.clientY})}),onPointerMove:kp(e.onPointerMove,e=>{if(!S.current)return;let t=e.clientX-S.current.x,n=e.clientY-S.current.y,r=!!C.current,i=[`left`,`right`].includes(_.swipeDirection),a=[`left`,`up`].includes(_.swipeDirection)?Math.min:Math.max,o=i?a(0,t):0,s=i?0:a(0,n),c=e.pointerType===`touch`?10:2,l={x:o,y:s},f={originalEvent:e,delta:l};r?(C.current=l,vv(sv,d,f,{discrete:!1})):yv(l,_.swipeDirection,c)?(C.current=l,vv(ov,u,f,{discrete:!1}),e.target.setPointerCapture(e.pointerId)):(Math.abs(t)>c||Math.abs(n)>c)&&(S.current=null)}),onPointerUp:kp(e.onPointerUp,e=>{let t=C.current,n=e.target;if(n.hasPointerCapture(e.pointerId)&&n.releasePointerCapture(e.pointerId),C.current=null,S.current=null,t){let n=e.currentTarget,r={originalEvent:e,delta:t};yv(t,_.swipeDirection,_.swipeThreshold)?vv(lv,p,r,{discrete:!0}):vv(cv,f,r,{discrete:!0}),n.addEventListener(`click`,e=>e.preventDefault(),{once:!0})}})})})}),_.viewport)})]}):null},`ToastImpl`)),mv=H_(e=>{let{__scopeToast:t,children:n,...r}=e,i=X_(av,t),[a,o]=m.useState(!1),[s,c]=m.useState(!1);return bv(()=>o(!0)),m.useEffect(()=>{let e=window.setTimeout(()=>c(!0),1e3);return()=>window.clearTimeout(e)},[]),s?null:(0,h.jsx)(gh,{asChild:!0,container:i.announcerContainer||void 0,children:(0,h.jsx)(B_,{...r,children:a&&(0,h.jsxs)(h.Fragment,{children:[i.label,` `,n]})})})},`ToastAnnounce`),hv=m.forwardRef(H_(function(e,t){let{__scopeToast:n,...r}=e;return(0,h.jsx)(Am.div,{...r,ref:t})},`ToastTitle`)),gv=m.forwardRef(H_(function(e,t){let{__scopeToast:n,...r}=e;return(0,h.jsx)(Am.div,{...r,ref:t})},`ToastDescription`));function _v(e){let t=[];return Array.from(e.childNodes).forEach(e=>{if(e.nodeType===e.TEXT_NODE&&e.textContent&&t.push(e.textContent),xv(e)){let n=e.ariaHidden||e.hidden||e.style.display===`none`,r=e.dataset.radixToastAnnounceExclude===``;if(!n){if(r){let n=e.dataset.radixToastAnnounceAlt;n&&t.push(n)}else t.push(..._v(e))}}}),t}H_(_v,`getAnnounceTextContent`);function vv(e,t,n,{discrete:r}){let i=n.originalEvent.currentTarget,a=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?jm(i,a):i.dispatchEvent(a)}H_(vv,`handleAndDispatchCustomEvent`);var yv=H_((e,t,n=0)=>{let r=Math.abs(e.x),i=Math.abs(e.y),a=r>i;return t===`left`||t===`right`?a&&r>n:!a&&i>n},`isDeltaInDirection`);function bv(e=()=>{}){let t=Pm(e);Wp(()=>{let e=0,n=0;return e=window.requestAnimationFrame(()=>n=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(e),window.cancelAnimationFrame(n)}},[t])}H_(bv,`useNextFrame`);function xv(e){return e.nodeType===e.ELEMENT_NODE}H_(xv,`isHTMLElement`);function Sv(e){let t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:H_(e=>{let t=e.tagName===`INPUT`&&e.type===`hidden`;return e.disabled||e.hidden||t?NodeFilter.FILTER_SKIP:e.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},`acceptNode`)});for(;n.nextNode();)t.push(n.currentNode);return t}H_(Sv,`getTabbableCandidates`);function Cv(e){let t=document.activeElement;return e.some(e=>e===t||(e.focus(),document.activeElement!==t))}H_(Cv,`focusFirst`);var wv=Z_,Tv=nv,Ev=uv,Dv=hv,Ov=gv;function kv(e){var t,n,r=``;if(typeof e==`string`||typeof e==`number`)r+=e;else if(typeof e==`object`){if(Array.isArray(e)){var i=e.length;for(t=0;ttypeof e==`boolean`?`${e}`:e===0?`0`:e,Mv=Av,Nv=(e,t)=>n=>{if(t?.variants==null)return Mv(e,n?.class,n?.className);let{variants:r,defaultVariants:i}=t,a=Object.keys(r).map(e=>{let t=n?.[e],a=i?.[e];if(t===null)return null;let o=jv(t)||jv(a);return r[e][o]}),o=n&&Object.entries(n).reduce((e,t)=>{let[n,r]=t;return r===void 0||(e[n]=r),e},{});return Mv(e,a,t?.compoundVariants?.reduce((e,t)=>{let{class:n,className:r,...a}=t;return Object.entries(a).every(e=>{let[t,n]=e;return Array.isArray(n)?n.includes({...i,...o}[t]):{...i,...o}[t]===n})?[...e,n,r]:e},[]),n?.class,n?.className)},Pv=(e,t)=>{let n=Array(e.length+t.length);for(let t=0;t({classGroupId:e,validator:t}),Iv=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Lv=`-`,Rv=[],zv=`arbitrary..`,Bv=e=>{let t=Uv(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:e=>{if(e.startsWith(`[`)&&e.endsWith(`]`))return Hv(e);let n=e.split(Lv);return Vv(n,+(n[0]===``&&n.length>1),t)},getConflictingClassGroupIds:(e,t)=>{if(t){let t=r[e],i=n[e];return t?i?Pv(i,t):t:i||Rv}return n[e]||Rv}}},Vv=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;let r=e[t],i=n.nextPart.get(r);if(i){let n=Vv(e,t+1,i);if(n)return n}let a=n.validators;if(a===null)return;let o=t===0?e.join(Lv):e.slice(t).join(Lv),s=a.length;for(let e=0;ee.slice(1,-1).indexOf(`:`)===-1?void 0:(()=>{let t=e.slice(1,-1),n=t.indexOf(`:`),r=t.slice(0,n);return r?zv+r:void 0})(),Uv=e=>{let{theme:t,classGroups:n}=e;return Wv(n,t)},Wv=(e,t)=>{let n=Iv();for(let r in e){let i=e[r];Gv(i,n,r,t)}return n},Gv=(e,t,n,r)=>{let i=e.length;for(let a=0;a{if(typeof e==`string`){qv(e,t,n);return}if(typeof e==`function`){Jv(e,t,n,r);return}Yv(e,t,n,r)},qv=(e,t,n)=>{let r=e===``?t:Xv(t,e);r.classGroupId=n},Jv=(e,t,n,r)=>{if(Zv(e)){Gv(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(Fv(n,e))},Yv=(e,t,n,r)=>{let i=Object.entries(e),a=i.length;for(let e=0;e{let n=e,r=t.split(Lv),i=r.length;for(let e=0;e`isThemeGetter`in e&&e.isThemeGetter===!0,Qv=e=>{if(e<1)return{get:()=>void 0,set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null),i=(i,a)=>{n[i]=a,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(e){let t=n[e];if(t!==void 0)return t;if((t=r[e])!==void 0)return i(e,t),t},set(e,t){e in n?n[e]=t:i(e,t)}}},$v=`!`,ey=`:`,ty=[],ny=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),ry=e=>{let{prefix:t,experimentalParseClassName:n}=e,r=e=>{let t=[],n=0,r=0,i=0,a,o=e.length;for(let s=0;si?a-i:void 0;return ny(t,l,c,u)};if(t){let e=t+ey,n=r;r=t=>t.startsWith(e)?n(t.slice(e.length)):ny(ty,!1,t,void 0,!0)}if(n){let e=r;r=t=>n({className:t,parseClassName:e})}return r},iy=e=>{let t=new Map;return e.orderSensitiveModifiers.forEach((e,n)=>{t.set(e,1e6+n)}),e=>{let n=[],r=[];for(let i=0;i0&&(r.sort(),n.push(...r),r=[]),n.push(a)):r.push(a)}return r.length>0&&(r.sort(),n.push(...r)),n}},ay=e=>({cache:Qv(e.cacheSize),parseClassName:ry(e),sortModifiers:iy(e),postfixLookupClassGroupIds:oy(e),...Bv(e)}),oy=e=>{let t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let e=0;e{let{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:a,postfixLookupClassGroupIds:o}=t,s=[],c=e.trim().split(sy),l=``;for(let e=c.length-1;e>=0;--e){let t=c[e],{isExternal:u,modifiers:d,hasImportantModifier:f,baseClassName:p,maybePostfixModifierPosition:m}=n(t);if(u){l=t+(l.length>0?` `+l:l);continue}let h=!!m,g;if(h){g=r(p.substring(0,m));let e=g&&o[g]?r(p):void 0;e&&e!==g&&(g=e,h=!1)}else g=r(p);if(!g){if(!h){l=t+(l.length>0?` `+l:l);continue}if(g=r(p),!g){l=t+(l.length>0?` `+l:l);continue}h=!1}let _=d.length===0?``:d.length===1?d[0]:a(d).join(`:`),v=f?_+$v:_,y=v+g;if(s.indexOf(y)>-1)continue;s.push(y);let b=i(g,h);for(let e=0;e0?` `+l:l)}return l},ly=(...e)=>{let t=0,n,r,i=``;for(;t{if(typeof e==`string`)return e;let t,n=``;for(let r=0;r{let n,r,i,a,o=o=>(n=ay(t.reduce((e,t)=>t(e),e())),r=n.cache.get,i=n.cache.set,a=s,s(o)),s=e=>{let t=r(e);if(t)return t;let a=cy(e,n);return i(e,a),a};return a=o,(...e)=>a(ly(...e))},fy=[],py=e=>{let t=t=>t[e]||fy;return t.isThemeGetter=!0,t},my=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,hy=/^\((?:(\w[\w-]*):)?(.+)\)$/i,gy=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,_y=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,vy=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,yy=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,by=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,xy=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Sy=e=>gy.test(e),Cy=e=>!!e&&!Number.isNaN(Number(e)),wy=e=>!!e&&Number.isInteger(Number(e)),Ty=e=>e.endsWith(`%`)&&Cy(e.slice(0,-1)),Ey=e=>_y.test(e),Dy=()=>!0,Oy=e=>vy.test(e)&&!yy.test(e),ky=()=>!1,Ay=e=>by.test(e),jy=e=>xy.test(e),My=e=>!J(e)&&!Y(e),Ny=e=>e.startsWith(`@container`)&&(e[10]===`/`&&e[11]!==void 0||e[11]===`s`&&e[16]!==void 0&&e.startsWith(`-size/`,10)||e[11]===`n`&&e[18]!==void 0&&e.startsWith(`-normal/`,10)),Py=e=>Yy(e,$y,ky),J=e=>my.test(e),Fy=e=>Yy(e,eb,Oy),Iy=e=>Yy(e,tb,Cy),Ly=e=>Yy(e,rb,Dy),Ry=e=>Yy(e,nb,ky),zy=e=>Yy(e,Zy,ky),By=e=>Yy(e,Qy,jy),Vy=e=>Yy(e,ib,Ay),Y=e=>hy.test(e),Hy=e=>Xy(e,eb),Uy=e=>Xy(e,nb),Wy=e=>Xy(e,Zy),Gy=e=>Xy(e,$y),Ky=e=>Xy(e,Qy),qy=e=>Xy(e,ib,!0),Jy=e=>Xy(e,rb,!0),Yy=(e,t,n)=>{let r=my.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Xy=(e,t,n=!1)=>{let r=hy.exec(e);return r?r[1]?t(r[1]):n:!1},Zy=e=>e===`position`||e===`percentage`,Qy=e=>e===`image`||e===`url`,$y=e=>e===`length`||e===`size`||e===`bg-size`,eb=e=>e===`length`,tb=e=>e===`number`,nb=e=>e===`family-name`,rb=e=>e===`number`||e===`weight`,ib=e=>e===`shadow`,ab=dy(()=>{let e=py(`color`),t=py(`font`),n=py(`text`),r=py(`font-weight`),i=py(`tracking`),a=py(`leading`),o=py(`breakpoint`),s=py(`container`),c=py(`spacing`),l=py(`radius`),u=py(`shadow`),d=py(`inset-shadow`),f=py(`text-shadow`),p=py(`drop-shadow`),m=py(`blur`),h=py(`perspective`),g=py(`aspect`),_=py(`ease`),v=py(`animate`),y=()=>[`auto`,`avoid`,`all`,`avoid-page`,`page`,`left`,`right`,`column`],b=()=>[`center`,`top`,`bottom`,`left`,`right`,`top-left`,`left-top`,`top-right`,`right-top`,`bottom-right`,`right-bottom`,`bottom-left`,`left-bottom`],x=()=>[...b(),Y,J],S=()=>[`auto`,`hidden`,`clip`,`visible`,`scroll`],C=()=>[`auto`,`contain`,`none`],w=()=>[Y,J,c],T=()=>[Sy,`full`,`auto`,...w()],E=()=>[wy,`none`,`subgrid`,Y,J],D=()=>[`auto`,{span:[`full`,wy,Y,J]},wy,Y,J],O=()=>[wy,`auto`,Y,J],ee=()=>[`auto`,`min`,`max`,`fr`,Y,J],k=()=>[`start`,`end`,`center`,`between`,`around`,`evenly`,`stretch`,`baseline`,`center-safe`,`end-safe`],A=()=>[`start`,`end`,`center`,`stretch`,`center-safe`,`end-safe`],j=()=>[`auto`,...w()],M=()=>[Sy,`auto`,`full`,`dvw`,`dvh`,`lvw`,`lvh`,`svw`,`svh`,`min`,`max`,`fit`,...w()],N=()=>[Sy,`screen`,`full`,`dvw`,`lvw`,`svw`,`min`,`max`,`fit`,...w()],P=()=>[Sy,`screen`,`full`,`lh`,`dvh`,`lvh`,`svh`,`min`,`max`,`fit`,...w()],F=()=>[e,Y,J],te=()=>[...b(),Wy,zy,{position:[Y,J]}],ne=()=>[`no-repeat`,{repeat:[``,`x`,`y`,`space`,`round`]}],re=()=>[`auto`,`cover`,`contain`,Gy,Py,{size:[Y,J]}],ie=()=>[Ty,Hy,Fy],I=()=>[``,`none`,`full`,l,Y,J],L=()=>[``,Cy,Hy,Fy],ae=()=>[`solid`,`dashed`,`dotted`,`double`],oe=()=>[`normal`,`multiply`,`screen`,`overlay`,`darken`,`lighten`,`color-dodge`,`color-burn`,`hard-light`,`soft-light`,`difference`,`exclusion`,`hue`,`saturation`,`color`,`luminosity`],se=()=>[Cy,Ty,Wy,zy],ce=()=>[``,`none`,m,Y,J],le=()=>[`none`,Cy,Y,J],ue=()=>[`none`,Cy,Y,J],de=()=>[Cy,Y,J],fe=()=>[Sy,`full`,...w()];return{cacheSize:500,theme:{animate:[`spin`,`ping`,`pulse`,`bounce`],aspect:[`video`],blur:[Ey],breakpoint:[Ey],color:[Dy],container:[Ey],"drop-shadow":[Ey],ease:[`in`,`out`,`in-out`],font:[My],"font-weight":[`thin`,`extralight`,`light`,`normal`,`medium`,`semibold`,`bold`,`extrabold`,`black`],"inset-shadow":[Ey],leading:[`none`,`tight`,`snug`,`normal`,`relaxed`,`loose`],perspective:[`dramatic`,`near`,`normal`,`midrange`,`distant`,`none`],radius:[Ey],shadow:[Ey],spacing:[`px`,Cy],text:[Ey],"text-shadow":[Ey],tracking:[`tighter`,`tight`,`normal`,`wide`,`wider`,`widest`]},classGroups:{aspect:[{aspect:[`auto`,`square`,Sy,J,Y,g]}],container:[`container`],"container-type":[{"@container":[``,`normal`,`size`,Y,J]}],"container-named":[Ny],columns:[{columns:[Cy,J,Y,s]}],"break-after":[{"break-after":y()}],"break-before":[{"break-before":y()}],"break-inside":[{"break-inside":[`auto`,`avoid`,`avoid-page`,`avoid-column`]}],"box-decoration":[{"box-decoration":[`slice`,`clone`]}],box:[{box:[`border`,`content`]}],display:[`block`,`inline-block`,`inline`,`flex`,`inline-flex`,`table`,`inline-table`,`table-caption`,`table-cell`,`table-column`,`table-column-group`,`table-footer-group`,`table-header-group`,`table-row-group`,`table-row`,`flow-root`,`grid`,`inline-grid`,`contents`,`list-item`,`hidden`],sr:[`sr-only`,`not-sr-only`],float:[{float:[`right`,`left`,`none`,`start`,`end`]}],clear:[{clear:[`left`,`right`,`both`,`none`,`start`,`end`]}],isolation:[`isolate`,`isolation-auto`],"object-fit":[{object:[`contain`,`cover`,`fill`,`none`,`scale-down`]}],"object-position":[{object:x()}],overflow:[{overflow:S()}],"overflow-x":[{"overflow-x":S()}],"overflow-y":[{"overflow-y":S()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:[`static`,`fixed`,`absolute`,`relative`,`sticky`],inset:[{inset:T()}],"inset-x":[{"inset-x":T()}],"inset-y":[{"inset-y":T()}],start:[{"inset-s":T(),start:T()}],end:[{"inset-e":T(),end:T()}],"inset-bs":[{"inset-bs":T()}],"inset-be":[{"inset-be":T()}],top:[{top:T()}],right:[{right:T()}],bottom:[{bottom:T()}],left:[{left:T()}],visibility:[`visible`,`invisible`,`collapse`],z:[{z:[wy,`auto`,Y,J]}],basis:[{basis:[Sy,`full`,`auto`,s,...w()]}],"flex-direction":[{flex:[`row`,`row-reverse`,`col`,`col-reverse`]}],"flex-wrap":[{flex:[`nowrap`,`wrap`,`wrap-reverse`]}],flex:[{flex:[Cy,Sy,`auto`,`initial`,`none`,J]}],grow:[{grow:[``,Cy,Y,J]}],shrink:[{shrink:[``,Cy,Y,J]}],order:[{order:[wy,`first`,`last`,`none`,Y,J]}],"grid-cols":[{"grid-cols":E()}],"col-start-end":[{col:D()}],"col-start":[{"col-start":O()}],"col-end":[{"col-end":O()}],"grid-rows":[{"grid-rows":E()}],"row-start-end":[{row:D()}],"row-start":[{"row-start":O()}],"row-end":[{"row-end":O()}],"grid-flow":[{"grid-flow":[`row`,`col`,`dense`,`row-dense`,`col-dense`]}],"auto-cols":[{"auto-cols":ee()}],"auto-rows":[{"auto-rows":ee()}],gap:[{gap:w()}],"gap-x":[{"gap-x":w()}],"gap-y":[{"gap-y":w()}],"justify-content":[{justify:[...k(),`normal`]}],"justify-items":[{"justify-items":[...A(),`normal`]}],"justify-self":[{"justify-self":[`auto`,...A()]}],"align-content":[{content:[`normal`,...k()]}],"align-items":[{items:[...A(),{baseline:[``,`last`]}]}],"align-self":[{self:[`auto`,...A(),{baseline:[``,`last`]}]}],"place-content":[{"place-content":k()}],"place-items":[{"place-items":[...A(),`baseline`]}],"place-self":[{"place-self":[`auto`,...A()]}],p:[{p:w()}],px:[{px:w()}],py:[{py:w()}],ps:[{ps:w()}],pe:[{pe:w()}],pbs:[{pbs:w()}],pbe:[{pbe:w()}],pt:[{pt:w()}],pr:[{pr:w()}],pb:[{pb:w()}],pl:[{pl:w()}],m:[{m:j()}],mx:[{mx:j()}],my:[{my:j()}],ms:[{ms:j()}],me:[{me:j()}],mbs:[{mbs:j()}],mbe:[{mbe:j()}],mt:[{mt:j()}],mr:[{mr:j()}],mb:[{mb:j()}],ml:[{ml:j()}],"space-x":[{"space-x":w()}],"space-x-reverse":[`space-x-reverse`],"space-y":[{"space-y":w()}],"space-y-reverse":[`space-y-reverse`],size:[{size:M()}],"inline-size":[{inline:[`auto`,...N()]}],"min-inline-size":[{"min-inline":[`auto`,...N()]}],"max-inline-size":[{"max-inline":[`none`,...N()]}],"block-size":[{block:[`auto`,...P()]}],"min-block-size":[{"min-block":[`auto`,...P()]}],"max-block-size":[{"max-block":[`none`,...P()]}],w:[{w:[s,`screen`,...M()]}],"min-w":[{"min-w":[s,`screen`,`none`,...M()]}],"max-w":[{"max-w":[s,`screen`,`none`,`prose`,{screen:[o]},...M()]}],h:[{h:[`screen`,`lh`,...M()]}],"min-h":[{"min-h":[`screen`,`lh`,`none`,...M()]}],"max-h":[{"max-h":[`screen`,`lh`,...M()]}],"font-size":[{text:[`base`,n,Hy,Fy]}],"font-smoothing":[`antialiased`,`subpixel-antialiased`],"font-style":[`italic`,`not-italic`],"font-weight":[{font:[r,Jy,Ly]}],"font-stretch":[{"font-stretch":[`ultra-condensed`,`extra-condensed`,`condensed`,`semi-condensed`,`normal`,`semi-expanded`,`expanded`,`extra-expanded`,`ultra-expanded`,Ty,J]}],"font-family":[{font:[Uy,Ry,t]}],"font-features":[{"font-features":[J]}],"fvn-normal":[`normal-nums`],"fvn-ordinal":[`ordinal`],"fvn-slashed-zero":[`slashed-zero`],"fvn-figure":[`lining-nums`,`oldstyle-nums`],"fvn-spacing":[`proportional-nums`,`tabular-nums`],"fvn-fraction":[`diagonal-fractions`,`stacked-fractions`],tracking:[{tracking:[i,Y,J]}],"line-clamp":[{"line-clamp":[Cy,`none`,Y,Iy]}],leading:[{leading:[a,...w()]}],"list-image":[{"list-image":[`none`,Y,J]}],"list-style-position":[{list:[`inside`,`outside`]}],"list-style-type":[{list:[`disc`,`decimal`,`none`,Y,J]}],"text-alignment":[{text:[`left`,`center`,`right`,`justify`,`start`,`end`]}],"placeholder-color":[{placeholder:F()}],"text-color":[{text:F()}],"text-decoration":[`underline`,`overline`,`line-through`,`no-underline`],"text-decoration-style":[{decoration:[...ae(),`wavy`]}],"text-decoration-thickness":[{decoration:[Cy,`from-font`,`auto`,Y,Fy]}],"text-decoration-color":[{decoration:F()}],"underline-offset":[{"underline-offset":[Cy,`auto`,Y,J]}],"text-transform":[`uppercase`,`lowercase`,`capitalize`,`normal-case`],"text-overflow":[`truncate`,`text-ellipsis`,`text-clip`],"text-wrap":[{text:[`wrap`,`nowrap`,`balance`,`pretty`]}],indent:[{indent:w()}],"tab-size":[{tab:[wy,Y,J]}],"vertical-align":[{align:[`baseline`,`top`,`middle`,`bottom`,`text-top`,`text-bottom`,`sub`,`super`,Y,J]}],whitespace:[{whitespace:[`normal`,`nowrap`,`pre`,`pre-line`,`pre-wrap`,`break-spaces`]}],break:[{break:[`normal`,`words`,`all`,`keep`]}],wrap:[{wrap:[`break-word`,`anywhere`,`normal`]}],hyphens:[{hyphens:[`none`,`manual`,`auto`]}],content:[{content:[`none`,Y,J]}],"bg-attachment":[{bg:[`fixed`,`local`,`scroll`]}],"bg-clip":[{"bg-clip":[`border`,`padding`,`content`,`text`]}],"bg-origin":[{"bg-origin":[`border`,`padding`,`content`]}],"bg-position":[{bg:te()}],"bg-repeat":[{bg:ne()}],"bg-size":[{bg:re()}],"bg-image":[{bg:[`none`,{linear:[{to:[`t`,`tr`,`r`,`br`,`b`,`bl`,`l`,`tl`]},wy,Y,J],radial:[``,Y,J],conic:[wy,Y,J]},Ky,By]}],"bg-color":[{bg:F()}],"gradient-from-pos":[{from:ie()}],"gradient-via-pos":[{via:ie()}],"gradient-to-pos":[{to:ie()}],"gradient-from":[{from:F()}],"gradient-via":[{via:F()}],"gradient-to":[{to:F()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:L()}],"border-w-x":[{"border-x":L()}],"border-w-y":[{"border-y":L()}],"border-w-s":[{"border-s":L()}],"border-w-e":[{"border-e":L()}],"border-w-bs":[{"border-bs":L()}],"border-w-be":[{"border-be":L()}],"border-w-t":[{"border-t":L()}],"border-w-r":[{"border-r":L()}],"border-w-b":[{"border-b":L()}],"border-w-l":[{"border-l":L()}],"divide-x":[{"divide-x":L()}],"divide-x-reverse":[`divide-x-reverse`],"divide-y":[{"divide-y":L()}],"divide-y-reverse":[`divide-y-reverse`],"border-style":[{border:[...ae(),`hidden`,`none`]}],"divide-style":[{divide:[...ae(),`hidden`,`none`]}],"border-color":[{border:F()}],"border-color-x":[{"border-x":F()}],"border-color-y":[{"border-y":F()}],"border-color-s":[{"border-s":F()}],"border-color-e":[{"border-e":F()}],"border-color-bs":[{"border-bs":F()}],"border-color-be":[{"border-be":F()}],"border-color-t":[{"border-t":F()}],"border-color-r":[{"border-r":F()}],"border-color-b":[{"border-b":F()}],"border-color-l":[{"border-l":F()}],"divide-color":[{divide:F()}],"outline-style":[{outline:[...ae(),`none`,`hidden`]}],"outline-offset":[{"outline-offset":[Cy,Y,J]}],"outline-w":[{outline:[``,Cy,Hy,Fy]}],"outline-color":[{outline:F()}],shadow:[{shadow:[``,`none`,u,qy,Vy]}],"shadow-color":[{shadow:F()}],"inset-shadow":[{"inset-shadow":[`none`,d,qy,Vy]}],"inset-shadow-color":[{"inset-shadow":F()}],"ring-w":[{ring:L()}],"ring-w-inset":[`ring-inset`],"ring-color":[{ring:F()}],"ring-offset-w":[{"ring-offset":[Cy,Fy]}],"ring-offset-color":[{"ring-offset":F()}],"inset-ring-w":[{"inset-ring":L()}],"inset-ring-color":[{"inset-ring":F()}],"text-shadow":[{"text-shadow":[`none`,f,qy,Vy]}],"text-shadow-color":[{"text-shadow":F()}],opacity:[{opacity:[Cy,Y,J]}],"mix-blend":[{"mix-blend":[...oe(),`plus-darker`,`plus-lighter`]}],"bg-blend":[{"bg-blend":oe()}],"mask-clip":[{"mask-clip":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]},`mask-no-clip`],"mask-composite":[{mask:[`add`,`subtract`,`intersect`,`exclude`]}],"mask-image-linear-pos":[{"mask-linear":[Cy]}],"mask-image-linear-from-pos":[{"mask-linear-from":se()}],"mask-image-linear-to-pos":[{"mask-linear-to":se()}],"mask-image-linear-from-color":[{"mask-linear-from":F()}],"mask-image-linear-to-color":[{"mask-linear-to":F()}],"mask-image-t-from-pos":[{"mask-t-from":se()}],"mask-image-t-to-pos":[{"mask-t-to":se()}],"mask-image-t-from-color":[{"mask-t-from":F()}],"mask-image-t-to-color":[{"mask-t-to":F()}],"mask-image-r-from-pos":[{"mask-r-from":se()}],"mask-image-r-to-pos":[{"mask-r-to":se()}],"mask-image-r-from-color":[{"mask-r-from":F()}],"mask-image-r-to-color":[{"mask-r-to":F()}],"mask-image-b-from-pos":[{"mask-b-from":se()}],"mask-image-b-to-pos":[{"mask-b-to":se()}],"mask-image-b-from-color":[{"mask-b-from":F()}],"mask-image-b-to-color":[{"mask-b-to":F()}],"mask-image-l-from-pos":[{"mask-l-from":se()}],"mask-image-l-to-pos":[{"mask-l-to":se()}],"mask-image-l-from-color":[{"mask-l-from":F()}],"mask-image-l-to-color":[{"mask-l-to":F()}],"mask-image-x-from-pos":[{"mask-x-from":se()}],"mask-image-x-to-pos":[{"mask-x-to":se()}],"mask-image-x-from-color":[{"mask-x-from":F()}],"mask-image-x-to-color":[{"mask-x-to":F()}],"mask-image-y-from-pos":[{"mask-y-from":se()}],"mask-image-y-to-pos":[{"mask-y-to":se()}],"mask-image-y-from-color":[{"mask-y-from":F()}],"mask-image-y-to-color":[{"mask-y-to":F()}],"mask-image-radial":[{"mask-radial":[Y,J]}],"mask-image-radial-from-pos":[{"mask-radial-from":se()}],"mask-image-radial-to-pos":[{"mask-radial-to":se()}],"mask-image-radial-from-color":[{"mask-radial-from":F()}],"mask-image-radial-to-color":[{"mask-radial-to":F()}],"mask-image-radial-shape":[{"mask-radial":[`circle`,`ellipse`]}],"mask-image-radial-size":[{"mask-radial":[{closest:[`side`,`corner`],farthest:[`side`,`corner`]}]}],"mask-image-radial-pos":[{"mask-radial-at":b()}],"mask-image-conic-pos":[{"mask-conic":[Cy]}],"mask-image-conic-from-pos":[{"mask-conic-from":se()}],"mask-image-conic-to-pos":[{"mask-conic-to":se()}],"mask-image-conic-from-color":[{"mask-conic-from":F()}],"mask-image-conic-to-color":[{"mask-conic-to":F()}],"mask-mode":[{mask:[`alpha`,`luminance`,`match`]}],"mask-origin":[{"mask-origin":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]}],"mask-position":[{mask:te()}],"mask-repeat":[{mask:ne()}],"mask-size":[{mask:re()}],"mask-type":[{"mask-type":[`alpha`,`luminance`]}],"mask-image":[{mask:[`none`,Y,J]}],filter:[{filter:[``,`none`,Y,J]}],blur:[{blur:ce()}],brightness:[{brightness:[Cy,Y,J]}],contrast:[{contrast:[Cy,Y,J]}],"drop-shadow":[{"drop-shadow":[``,`none`,p,qy,Vy]}],"drop-shadow-color":[{"drop-shadow":F()}],grayscale:[{grayscale:[``,Cy,Y,J]}],"hue-rotate":[{"hue-rotate":[Cy,Y,J]}],invert:[{invert:[``,Cy,Y,J]}],saturate:[{saturate:[Cy,Y,J]}],sepia:[{sepia:[``,Cy,Y,J]}],"backdrop-filter":[{"backdrop-filter":[``,`none`,Y,J]}],"backdrop-blur":[{"backdrop-blur":ce()}],"backdrop-brightness":[{"backdrop-brightness":[Cy,Y,J]}],"backdrop-contrast":[{"backdrop-contrast":[Cy,Y,J]}],"backdrop-grayscale":[{"backdrop-grayscale":[``,Cy,Y,J]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Cy,Y,J]}],"backdrop-invert":[{"backdrop-invert":[``,Cy,Y,J]}],"backdrop-opacity":[{"backdrop-opacity":[Cy,Y,J]}],"backdrop-saturate":[{"backdrop-saturate":[Cy,Y,J]}],"backdrop-sepia":[{"backdrop-sepia":[``,Cy,Y,J]}],"border-collapse":[{border:[`collapse`,`separate`]}],"border-spacing":[{"border-spacing":w()}],"border-spacing-x":[{"border-spacing-x":w()}],"border-spacing-y":[{"border-spacing-y":w()}],"table-layout":[{table:[`auto`,`fixed`]}],caption:[{caption:[`top`,`bottom`]}],transition:[{transition:[``,`all`,`colors`,`opacity`,`shadow`,`transform`,`none`,Y,J]}],"transition-behavior":[{transition:[`normal`,`discrete`]}],duration:[{duration:[Cy,`initial`,Y,J]}],ease:[{ease:[`linear`,`initial`,_,Y,J]}],delay:[{delay:[Cy,Y,J]}],animate:[{animate:[`none`,v,Y,J]}],backface:[{backface:[`hidden`,`visible`]}],perspective:[{perspective:[h,Y,J]}],"perspective-origin":[{"perspective-origin":x()}],rotate:[{rotate:le()}],"rotate-x":[{"rotate-x":le()}],"rotate-y":[{"rotate-y":le()}],"rotate-z":[{"rotate-z":le()}],scale:[{scale:ue()}],"scale-x":[{"scale-x":ue()}],"scale-y":[{"scale-y":ue()}],"scale-z":[{"scale-z":ue()}],"scale-3d":[`scale-3d`],skew:[{skew:de()}],"skew-x":[{"skew-x":de()}],"skew-y":[{"skew-y":de()}],transform:[{transform:[Y,J,``,`none`,`gpu`,`cpu`]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:[`3d`,`flat`]}],translate:[{translate:fe()}],"translate-x":[{"translate-x":fe()}],"translate-y":[{"translate-y":fe()}],"translate-z":[{"translate-z":fe()}],"translate-none":[`translate-none`],zoom:[{zoom:[wy,Y,J]}],accent:[{accent:F()}],appearance:[{appearance:[`none`,`auto`]}],"caret-color":[{caret:F()}],"color-scheme":[{scheme:[`normal`,`dark`,`light`,`light-dark`,`only-dark`,`only-light`]}],cursor:[{cursor:[`auto`,`default`,`pointer`,`wait`,`text`,`move`,`help`,`not-allowed`,`none`,`context-menu`,`progress`,`cell`,`crosshair`,`vertical-text`,`alias`,`copy`,`no-drop`,`grab`,`grabbing`,`all-scroll`,`col-resize`,`row-resize`,`n-resize`,`e-resize`,`s-resize`,`w-resize`,`ne-resize`,`nw-resize`,`se-resize`,`sw-resize`,`ew-resize`,`ns-resize`,`nesw-resize`,`nwse-resize`,`zoom-in`,`zoom-out`,Y,J]}],"field-sizing":[{"field-sizing":[`fixed`,`content`]}],"pointer-events":[{"pointer-events":[`auto`,`none`]}],resize:[{resize:[`none`,``,`y`,`x`]}],"scroll-behavior":[{scroll:[`auto`,`smooth`]}],"scrollbar-thumb-color":[{"scrollbar-thumb":F()}],"scrollbar-track-color":[{"scrollbar-track":F()}],"scrollbar-gutter":[{"scrollbar-gutter":[`auto`,`stable`,`both`]}],"scrollbar-w":[{scrollbar:[`auto`,`thin`,`none`]}],"scroll-m":[{"scroll-m":w()}],"scroll-mx":[{"scroll-mx":w()}],"scroll-my":[{"scroll-my":w()}],"scroll-ms":[{"scroll-ms":w()}],"scroll-me":[{"scroll-me":w()}],"scroll-mbs":[{"scroll-mbs":w()}],"scroll-mbe":[{"scroll-mbe":w()}],"scroll-mt":[{"scroll-mt":w()}],"scroll-mr":[{"scroll-mr":w()}],"scroll-mb":[{"scroll-mb":w()}],"scroll-ml":[{"scroll-ml":w()}],"scroll-p":[{"scroll-p":w()}],"scroll-px":[{"scroll-px":w()}],"scroll-py":[{"scroll-py":w()}],"scroll-ps":[{"scroll-ps":w()}],"scroll-pe":[{"scroll-pe":w()}],"scroll-pbs":[{"scroll-pbs":w()}],"scroll-pbe":[{"scroll-pbe":w()}],"scroll-pt":[{"scroll-pt":w()}],"scroll-pr":[{"scroll-pr":w()}],"scroll-pb":[{"scroll-pb":w()}],"scroll-pl":[{"scroll-pl":w()}],"snap-align":[{snap:[`start`,`end`,`center`,`align-none`]}],"snap-stop":[{snap:[`normal`,`always`]}],"snap-type":[{snap:[`none`,`x`,`y`,`both`]}],"snap-strictness":[{snap:[`mandatory`,`proximity`]}],touch:[{touch:[`auto`,`none`,`manipulation`]}],"touch-x":[{"touch-pan":[`x`,`left`,`right`]}],"touch-y":[{"touch-pan":[`y`,`up`,`down`]}],"touch-pz":[`touch-pinch-zoom`],select:[{select:[`none`,`text`,`all`,`auto`]}],"will-change":[{"will-change":[`auto`,`scroll`,`contents`,`transform`,Y,J]}],fill:[{fill:[`none`,...F()]}],"stroke-w":[{stroke:[Cy,Hy,Fy,Iy]}],stroke:[{stroke:[`none`,...F()]}],"forced-color-adjust":[{"forced-color-adjust":[`auto`,`none`]}]},conflictingClassGroups:{"container-named":[`container-type`],overflow:[`overflow-x`,`overflow-y`],overscroll:[`overscroll-x`,`overscroll-y`],inset:[`inset-x`,`inset-y`,`inset-bs`,`inset-be`,`start`,`end`,`top`,`right`,`bottom`,`left`],"inset-x":[`right`,`left`],"inset-y":[`top`,`bottom`],flex:[`basis`,`grow`,`shrink`],gap:[`gap-x`,`gap-y`],p:[`px`,`py`,`ps`,`pe`,`pbs`,`pbe`,`pt`,`pr`,`pb`,`pl`],px:[`pr`,`pl`],py:[`pt`,`pb`],m:[`mx`,`my`,`ms`,`me`,`mbs`,`mbe`,`mt`,`mr`,`mb`,`ml`],mx:[`mr`,`ml`],my:[`mt`,`mb`],size:[`w`,`h`],"font-size":[`leading`],"fvn-normal":[`fvn-ordinal`,`fvn-slashed-zero`,`fvn-figure`,`fvn-spacing`,`fvn-fraction`],"fvn-ordinal":[`fvn-normal`],"fvn-slashed-zero":[`fvn-normal`],"fvn-figure":[`fvn-normal`],"fvn-spacing":[`fvn-normal`],"fvn-fraction":[`fvn-normal`],"line-clamp":[`display`,`overflow`],rounded:[`rounded-s`,`rounded-e`,`rounded-t`,`rounded-r`,`rounded-b`,`rounded-l`,`rounded-ss`,`rounded-se`,`rounded-ee`,`rounded-es`,`rounded-tl`,`rounded-tr`,`rounded-br`,`rounded-bl`],"rounded-s":[`rounded-ss`,`rounded-es`],"rounded-e":[`rounded-se`,`rounded-ee`],"rounded-t":[`rounded-tl`,`rounded-tr`],"rounded-r":[`rounded-tr`,`rounded-br`],"rounded-b":[`rounded-br`,`rounded-bl`],"rounded-l":[`rounded-tl`,`rounded-bl`],"border-spacing":[`border-spacing-x`,`border-spacing-y`],"border-w":[`border-w-x`,`border-w-y`,`border-w-s`,`border-w-e`,`border-w-bs`,`border-w-be`,`border-w-t`,`border-w-r`,`border-w-b`,`border-w-l`],"border-w-x":[`border-w-r`,`border-w-l`],"border-w-y":[`border-w-t`,`border-w-b`],"border-color":[`border-color-x`,`border-color-y`,`border-color-s`,`border-color-e`,`border-color-bs`,`border-color-be`,`border-color-t`,`border-color-r`,`border-color-b`,`border-color-l`],"border-color-x":[`border-color-r`,`border-color-l`],"border-color-y":[`border-color-t`,`border-color-b`],translate:[`translate-x`,`translate-y`,`translate-none`],"translate-none":[`translate`,`translate-x`,`translate-y`,`translate-z`],"scroll-m":[`scroll-mx`,`scroll-my`,`scroll-ms`,`scroll-me`,`scroll-mbs`,`scroll-mbe`,`scroll-mt`,`scroll-mr`,`scroll-mb`,`scroll-ml`],"scroll-mx":[`scroll-mr`,`scroll-ml`],"scroll-my":[`scroll-mt`,`scroll-mb`],"scroll-p":[`scroll-px`,`scroll-py`,`scroll-ps`,`scroll-pe`,`scroll-pbs`,`scroll-pbe`,`scroll-pt`,`scroll-pr`,`scroll-pb`,`scroll-pl`],"scroll-px":[`scroll-pr`,`scroll-pl`],"scroll-py":[`scroll-pt`,`scroll-pb`],touch:[`touch-x`,`touch-y`,`touch-pz`],"touch-x":[`touch`],"touch-y":[`touch`],"touch-pz":[`touch`]},conflictingClassGroupModifiers:{"font-size":[`leading`]},postfixLookupClassGroups:[`container-type`],orderSensitiveModifiers:[`*`,`**`,`after`,`backdrop`,`before`,`details-content`,`file`,`first-letter`,`first-line`,`marker`,`placeholder`,`selection`]}});function ob(...e){return ab(Av(e))}var sb=Nv(`inline-flex min-h-[var(--control-height)] items-center justify-center gap-[var(--space-2)] rounded-[var(--radius-control)] px-[var(--space-4)] [font-size:var(--text-sm)] leading-[var(--leading-tight)] font-semibold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--surface)] disabled:pointer-events-none disabled:opacity-50`,{variants:{variant:{primary:`bg-[var(--accent)] text-white hover:bg-[var(--accent-strong)]`,secondary:`border border-[var(--border)] bg-[var(--surface-raised)] text-[var(--text)] hover:bg-[var(--surface-hover)]`,danger:`bg-[var(--danger)] text-white hover:brightness-95`,ghost:`text-[var(--muted)] hover:bg-[var(--surface-hover)] hover:text-[var(--text)]`},size:{default:`h-[var(--control-height)]`,compact:`h-9 min-h-9 px-[var(--space-3)]`,icon:`h-10 w-10 px-0`}},defaultVariants:{variant:`primary`,size:`default`}}),X=(0,m.forwardRef)(function({asChild:e=!1,className:t,variant:n,size:r,...i},a){return(0,h.jsx)(e?hm:`button`,{className:ob(sb({variant:n,size:r}),t),ref:a,...i})}),cb=(0,m.forwardRef)(function({className:e,...t},n){return(0,h.jsx)(`div`,{ref:n,className:ob(`rounded-[var(--radius-panel)] border border-[var(--border)] bg-[var(--surface-raised)] p-[var(--space-5)] [box-shadow:var(--shadow-panel)]`,e),...t})}),lb=(0,m.forwardRef)(function({className:e,...t},n){return(0,h.jsx)(`input`,{ref:n,className:ob(`min-h-[var(--control-height)] w-full rounded-[var(--radius-control)] border border-[var(--border)] bg-[var(--input)] px-[var(--space-3)] [font-size:var(--text-sm)] leading-[var(--leading-normal)] text-[var(--text)] outline-none placeholder:text-[var(--muted)] focus-visible:ring-2 focus-visible:ring-[var(--focus)]`,e),...t})});function ub({label:e,error:t,hint:n,children:r}){return(0,h.jsxs)(`label`,{className:`grid gap-[var(--space-1)] [font-size:var(--text-sm)] leading-[var(--leading-normal)] font-medium text-[var(--text)]`,children:[(0,h.jsx)(`span`,{children:e}),r,t?(0,h.jsx)(`span`,{className:`[font-size:var(--text-xs)] text-[var(--danger)]`,role:`alert`,children:t}):null,!t&&n?(0,h.jsx)(`span`,{className:`[font-size:var(--text-xs)] font-normal text-[var(--muted)]`,children:n}):null]})}function db({tone:e=`neutral`,children:t}){return(0,h.jsx)(`span`,{className:ob(`inline-flex items-center rounded-full px-[var(--space-3)] py-[var(--space-1)] [font-size:var(--text-xs)] leading-[var(--leading-tight)] font-semibold`,{neutral:`bg-[var(--surface-hover)] text-[var(--muted)]`,success:`bg-[var(--success-soft)] text-[var(--success)]`,warning:`bg-[var(--warning-soft)] text-[var(--warning)]`,danger:`bg-[var(--danger-soft)] text-[var(--danger)]`}[e]),children:t})}function fb({open:e,onOpenChange:t,restoreFocus:n,title:r,description:i,children:a,footer:o,closeLabel:s,closeDisabled:c=!1}){return(0,h.jsx)(r_,{open:e,onOpenChange:t,children:(0,h.jsxs)(s_,{children:[(0,h.jsx)(l_,{className:`fixed inset-0 z-40 bg-black/50 backdrop-blur-[2px] data-[state=closed]:animate-none`}),(0,h.jsxs)(p_,{className:`fixed left-1/2 top-1/2 z-50 max-h-[90vh] w-[min(92vw,680px)] -translate-x-1/2 -translate-y-1/2 overflow-auto rounded-[var(--radius-panel)] border border-[var(--border)] bg-[var(--surface-raised)] p-[var(--space-6)] text-[var(--text)] shadow-2xl focus:outline-none`,onCloseAutoFocus:e=>{n&&(e.preventDefault(),n())},children:[(0,h.jsxs)(`div`,{className:`pr-10`,children:[(0,h.jsx)(v_,{className:`text-xl font-bold`,children:r}),i?(0,h.jsx)(b_,{className:`mt-1 text-sm text-[var(--muted)]`,children:i}):null]}),(0,h.jsx)(S_,{asChild:!0,children:(0,h.jsx)(X,{"aria-label":s,className:`absolute right-4 top-4`,disabled:c,size:`icon`,type:`button`,variant:`ghost`,children:(0,h.jsx)(Ji,{size:18})})}),(0,h.jsx)(`div`,{className:`mt-[var(--space-5)]`,children:a}),o?(0,h.jsx)(`div`,{className:`mt-[var(--space-6)] flex flex-wrap justify-end gap-[var(--space-3)]`,children:o}):null]})]})})}var pb=(0,m.createContext)(null);function mb({children:e}){let{t}=Dn(),n=(0,m.useRef)(null),[r,i]=(0,m.useState)([]),a=(0,m.useCallback)(e=>{let t=Date.now()+Math.floor(Math.random()*1e3);i(n=>[...n,{...e,id:t}])},[]),o=(0,m.useMemo)(()=>({push:a}),[a]);return(0,h.jsx)(pb.Provider,{value:o,children:(0,h.jsxs)(wv,{duration:5e3,swipeDirection:`right`,children:[e,r.map(e=>(0,h.jsx)(Ev,{className:ob(`w-[min(92vw,420px)] rounded-xl border bg-[var(--surface-raised)] text-[var(--text)] shadow-xl`,e.tone===`danger`?`border-[var(--danger)]`:e.tone===`warning`?`border-[var(--warning)]`:`border-[var(--success)]`),onOpenChange:t=>{t||i(t=>t.filter(t=>t.id!==e.id))},children:(0,h.jsxs)(`button`,{type:`button`,"aria-label":t(`common.dismissNotification`,{title:e.title}),onClick:t=>{t.currentTarget.contains(document.activeElement)&&n.current?.focus(),i(t=>t.filter(t=>t.id!==e.id))},className:`relative grid min-h-11 w-full cursor-pointer gap-[var(--space-1)] rounded-xl p-[var(--space-4)] pr-12 text-left hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--surface)]`,children:[(0,h.jsx)(Dv,{asChild:!0,children:(0,h.jsx)(`span`,{className:`font-semibold`,children:e.title})}),e.description?(0,h.jsx)(Ov,{asChild:!0,children:(0,h.jsx)(`span`,{className:`[font-size:var(--text-sm)] leading-[var(--leading-normal)] text-[var(--muted)]`,children:e.description})}):null,(0,h.jsx)(Ji,{"aria-hidden":`true`,size:18,className:`absolute right-4 top-4 text-[var(--muted)]`})]})},e.id)),(0,h.jsx)(Tv,{ref:n,className:`fixed bottom-5 right-5 z-[60] grid gap-[var(--space-3)] outline-none`})]})})}function hb(){let e=(0,m.useContext)(pb);if(!e)throw Error(`useToast must be used inside ToastProvider.`);return e}function gb(e){return{profileId:e.id,profileRevision:e.revision}}function _b(e){let t=[`B`,`KB`,`MB`,`GB`,`TB`],n=Number.isFinite(e)?e:0,r=0;for(;n>=1024&&r=10?1:2)} ${t[r]}`}function vb(e,t=`en`){if(!e)return`—`;let n=new Date(e);return Number.isNaN(n.valueOf())?`—`:new Intl.DateTimeFormat(t,{dateStyle:`medium`,timeStyle:`medium`}).format(n)}function yb(e,t){let n=t(`errors.fallback`);return e instanceof Kr?e.code===`INVALID_INPUT`&&e.dto.details?.reason===`provider-not-configured`?t(`errors.providerNotConfigured`):t(`errors.${e.code}`,{defaultValue:n}):n}function bb(e,t){return e.id==="default"?t(`profiles.defaultName`):e.name}function xb(e,t){return e===`Backup inventory refresh failed.`?t(`warnings.backupInventory`):e===`Automatic backup cleanup failed.`?t(`warnings.backupCleanup`):e===`Some encrypted histories may require their original Provider or account for continuation.`?t(`warnings.encryptedHistory`):e===`One or more rollout files are locked and may be skipped.`?t(`warnings.lockedSessions`):e===`The selected Provider has no default model; the root model will remain unchanged.`?t(`warnings.missingDefaultModel`):e===`Project visibility diagnostics are unavailable; backup-first protection remains enabled.`?t(`warnings.projectVisibility`):e===`SQLite Home relocation is confirmed; config.toml will not be restored.`?t(`warnings.relocationConfig`):/^Restore skipped /.test(e)?t(`warnings.restoreSkipped`):t(e===`The operation made only part of the requested change. Retry it to converge, or restore the managed backup.`?`warnings.partial`:`warnings.additional`)}function Sb({title:e,subtitle:t,action:n,headingRef:r,headingTabIndex:i}){return(0,h.jsxs)(`div`,{className:`mb-[var(--space-6)] flex flex-wrap items-start justify-between gap-[var(--space-4)]`,children:[(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`h1`,{className:`[font-size:var(--text-2xl)] leading-[var(--leading-tight)] font-bold tracking-tight text-[var(--text)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus)]`,ref:r,tabIndex:i,children:e}),(0,h.jsx)(`p`,{className:`mt-[var(--space-1)] max-w-3xl [font-size:var(--text-sm)] leading-[var(--leading-relaxed)] text-[var(--muted)]`,children:t})]}),n]})}function Cb({label:e,value:t,mono:n=!1}){return(0,h.jsxs)(`div`,{className:`grid gap-1 border-b border-[var(--border)] py-3 last:border-0 sm:grid-cols-[180px_1fr]`,children:[(0,h.jsx)(`dt`,{className:`text-sm text-[var(--muted)]`,children:e}),(0,h.jsx)(`dd`,{className:ob(`min-w-0 break-words text-sm font-medium text-[var(--text)]`,n&&`font-mono text-xs`),children:t})]})}function wb(e){let t=e?.metadata.capturedTargetKinds,n=!!e&&t===void 0,r=t&&typeof t==`object`&&!Array.isArray(t)?t:{};return{restoreConfig:n||r.config===!0||r.globalState===!0,restoreDatabase:n||r.sqlite===!0,restoreSessions:n||r.rollout===!0}}function Tb({backup:e,selected:t,onSelect:n}){let r=(0,h.jsxs)(m.Fragment,{children:[(0,h.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,h.jsx)(`span`,{className:`font-mono text-xs font-semibold`,children:e.backupId}),(0,h.jsx)(db,{children:_b(e.sizeBytes)})]}),e.createdAt?(0,h.jsx)(`div`,{className:`mt-2 text-xs text-[var(--muted)]`,children:vb(e.createdAt)}):null]}),i=ob(`w-full rounded-lg border p-4 text-left`,t?`border-[var(--accent)] bg-[var(--accent-soft)]`:`border-[var(--border)]`);return n?(0,h.jsx)(`button`,{"aria-pressed":t,className:ob(i,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus)] hover:bg-[var(--surface-hover)]`),onClick:n,type:`button`,children:r}):(0,h.jsx)(`div`,{className:i,children:r})}function Eb({profile:e,profiles:t,backups:n,loading:r,refreshing:i=!1,error:a,refresh:o,disabled:s,canRestore:c,canPrune:l,initialBackupId:u,retentionCount:d=2,saveRetention:f,prepare:p,prune:g}){let{t:_}=Dn(),v=jo({resolver:Vo(wp),defaultValues:{backupId:``,restoreConfig:!1,restoreDatabase:!1,restoreSessions:!1,allowSqliteHomeRelocation:!1,relocationTargetProfileId:``}}),y=v.watch(`allowSqliteHomeRelocation`),b=v.watch(`restoreDatabase`),x=d,[S,C]=(0,m.useState)(String(d)),[w,T]=(0,m.useState)(!1),[E,D]=(0,m.useState)(null),O=/^\d+$/.test(S)?Number(S):NaN,ee=bp.safeParse(O).success,k=S!==String(d);(0,m.useEffect)(()=>{C(String(d))},[d]);let[A,j]=(0,m.useState)(null),M=(0,m.useRef)(null),N=(0,m.useRef)(null),P=JSON.stringify([e.id,e.revision,x,n.map(({backupId:e,createdAt:t,sizeBytes:n})=>[e,t,n]).sort((e,t)=>String(e[0]).localeCompare(String(t[0])))]),F=Number.isInteger(x)&&x>=0&&x<=1e3,te=e=>_(`ux.pruneEstimate`,{remove:Math.max(0,n.length-e),keep:Math.min(n.length,e)}),ne=(0,m.useRef)(null),re=v.watch(`backupId`),ie=n.find(e=>e.backupId===re),I=wb(ie),L=s||r||i||!!a;return(0,m.useEffect)(()=>{v.setValue(`restoreConfig`,I.restoreConfig&&!v.getValues(`allowSqliteHomeRelocation`)),v.setValue(`restoreDatabase`,I.restoreDatabase),v.setValue(`restoreSessions`,I.restoreSessions),v.clearErrors()},[v,re,I.restoreConfig,I.restoreDatabase,I.restoreSessions]),(0,m.useEffect)(()=>{y&&v.setValue(`restoreConfig`,!1),v.clearErrors(`relocationTargetProfileId`)},[v,y]),(0,m.useEffect)(()=>{b||v.setValue(`allowSqliteHomeRelocation`,!1)},[v,b]),(0,m.useEffect)(()=>{u&&v.setValue(`backupId`,u,{shouldValidate:!0})},[v,u]),(0,h.jsxs)(m.Fragment,{children:[(0,h.jsx)(Sb,{title:_(`backups.title`),subtitle:_(`backups.subtitle`),action:o?(0,h.jsxs)(X,{disabled:r||i,onClick:o,type:`button`,variant:`secondary`,children:[(0,h.jsx)(Ii,{size:16}),_(`common.refresh`)]}):void 0}),l?(0,h.jsxs)(cb,{className:`mb-4`,children:[(0,h.jsx)(`h2`,{className:`font-semibold`,children:_(`backupPolicy.title`)}),(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:_(`backupPolicy.scope`)}),(0,h.jsx)(`p`,{className:`mt-2 text-sm`,children:_(`backupPolicy.current`,{count:x})}),f?(0,h.jsxs)(`form`,{className:`mt-3 flex flex-wrap items-end gap-3`,onSubmit:async e=>{if(e.preventDefault(),!(!ee||!k||L||w)){T(!0),D(null);try{D(await f(O))}catch{D(`failed`)}finally{T(!1)}}},children:[(0,h.jsx)(ub,{label:_(`backupPolicy.count`),error:ee?void 0:_(`validation.keep`),children:(0,h.jsx)(lb,{min:1,max:1e3,type:`number`,value:S,disabled:L||w,onChange:e=>{C(e.target.value),D(null)}})}),(0,h.jsx)(X,{type:`submit`,disabled:!k||!ee||L||w,children:_(w?`common.loading`:`backupPolicy.save`)})]}):null,(0,h.jsx)(`p`,{className:`mt-3 text-xs text-[var(--muted)]`,children:_(`backupPolicy.hint`)}),E?(0,h.jsx)(`p`,{className:`mt-2 text-sm`,role:E===`saved`?`status`:`alert`,children:_(`backupPolicy.${E}`)}):null]}):null,u&&!r&&!a&&!n.some(e=>e.backupId===u)?(0,h.jsx)(`p`,{className:`mb-4 text-sm text-[var(--warning)]`,role:`alert`,children:_(`backups.requestedMissing`)}):null,(0,h.jsxs)(`div`,{className:ob(`grid gap-4`,(c||l)&&`xl:grid-cols-[minmax(0,1fr)_minmax(320px,440px)]`),children:[(0,h.jsxs)(cb,{children:[(0,h.jsx)(`div`,{className:`grid gap-3`,children:r?(0,h.jsx)(`span`,{className:`text-sm text-[var(--muted)]`,children:_(`common.loading`)}):a?(0,h.jsxs)(`div`,{className:`grid justify-items-start gap-3`,children:[(0,h.jsxs)(`p`,{className:`text-sm text-[var(--danger)]`,role:`alert`,children:[_(`backups.loadFailed`),` `,yb(a,_)]}),o?(0,h.jsx)(X,{disabled:i,onClick:o,type:`button`,variant:`secondary`,children:_(`common.retry`)}):null]}):n.length===0?(0,h.jsx)(`span`,{className:`text-sm text-[var(--muted)]`,children:_(`backups.empty`)}):n.map(e=>(0,h.jsx)(Tb,{backup:e,onSelect:c?()=>v.setValue(`backupId`,e.backupId,{shouldValidate:!0}):void 0,selected:c&&re===e.backupId},e.backupId))}),!c&&!l?(0,h.jsx)(`p`,{className:`mt-4 text-xs text-[var(--muted)]`,children:_(`backups.readOnly`)}):null]}),c||l?(0,h.jsxs)(`div`,{className:`grid content-start gap-4`,children:[c?(0,h.jsx)(cb,{children:(0,h.jsx)(`form`,{onSubmit:v.handleSubmit(e=>p(e,ne.current)),children:(0,h.jsxs)(`fieldset`,{className:`grid gap-4`,disabled:L||v.formState.isSubmitting||!ie,children:[(0,h.jsx)(`p`,{className:`text-xs text-[var(--muted)]`,children:_(ie?`backups.capturedHint`:`backups.selectBackup`)}),[`restoreConfig`,`restoreDatabase`,`restoreSessions`].map(e=>(0,h.jsxs)(`label`,{className:`flex items-center gap-3 text-sm`,children:[(0,h.jsx)(`input`,{className:`h-4 w-4 accent-[var(--accent)]`,type:`checkbox`,disabled:!I[e]||e===`restoreConfig`&&y,...v.register(e)}),_(`backups.${e}`)]},e)),(0,h.jsxs)(`label`,{className:`flex items-center gap-3 text-sm`,children:[(0,h.jsx)(`input`,{className:`h-4 w-4 accent-[var(--accent)]`,type:`checkbox`,disabled:!b,...v.register(`allowSqliteHomeRelocation`)}),_(`backups.relocation`)]}),y?(0,h.jsx)(ub,{error:v.formState.errors.relocationTargetProfileId?_(`backups.relocationTargetRequired`):void 0,label:_(`backups.targetProfile`),children:(0,h.jsxs)(`select`,{"aria-label":_(`backups.targetProfile`),"aria-invalid":!!v.formState.errors.relocationTargetProfileId,className:`min-h-10 rounded-lg border border-[var(--border)] bg-[var(--input)] px-3`,...v.register(`relocationTargetProfileId`),children:[(0,h.jsx)(`option`,{value:``,children:`—`}),t.filter(t=>t.id!==e.id&&(!!t.sqliteHome||t.sqliteHomeConfigured===!0)).map(e=>(0,h.jsx)(`option`,{value:e.id,children:bb(e,_)},e.id))]})}):null,y?(0,h.jsx)(`p`,{className:`text-xs text-[var(--muted)]`,children:_(`backups.relocationHint`)}):null,v.formState.errors.restoreSessions?(0,h.jsx)(`span`,{className:`text-xs text-[var(--danger)]`,role:`alert`,children:_(`validation.restore`)}):null,(0,h.jsxs)(X,{ref:ne,type:`submit`,children:[(0,h.jsx)(hi,{size:17}),_(`backups.prepare`)]})]})})}):null,l?(0,h.jsxs)(cb,{children:[(0,h.jsx)(`p`,{className:`text-sm font-medium`,children:_(`backupPolicy.current`,{count:x})}),!L&&F?(0,h.jsx)(`p`,{className:`mt-3 text-sm`,children:te(x)}):null,(0,h.jsx)(`p`,{className:`mt-2 text-xs text-[var(--muted)]`,children:_(`ux.pruneCaution`)}),(0,h.jsx)(X,{ref:M,className:`mt-4 w-full`,disabled:L||!F||k||w,onClick:e=>{N.current=e.currentTarget,j({keep:x,revision:P})},type:`button`,variant:`secondary`,children:_(`backups.prune`)}),(0,h.jsxs)(`details`,{className:`mt-3 text-sm`,children:[(0,h.jsx)(`summary`,{className:`cursor-pointer`,children:_(`common.advanced`)}),(0,h.jsx)(X,{className:`mt-3`,disabled:L||k||w,onClick:e=>{N.current=e.currentTarget,j({keep:0,revision:P})},type:`button`,variant:`danger`,children:_(`backupPolicy.clear`)})]})]}):null]}):null]}),(0,h.jsx)(fb,{open:!!A,onOpenChange:e=>{e||j(null)},closeLabel:_(`common.close`),title:_(`ux.pruneTitle`),description:_(`ux.pruneCaution`),restoreFocus:()=>(N.current??M.current)?.focus(),footer:(0,h.jsx)(X,{type:`button`,variant:`danger`,disabled:!l||L||!A||A.revision!==P,onClick:()=>{if(!l||!A||L||A.revision!==P)return;let e=A.keep;j(null),g(e)},children:_(`ux.pruneConfirm`)}),children:A?(0,h.jsxs)(`div`,{className:`mt-4 grid gap-3 text-sm`,children:[(0,h.jsx)(`p`,{children:te(A.keep)}),A.keep===0?(0,h.jsx)(`p`,{className:`text-[var(--danger)]`,children:_(`ux.pruneZero`)}):null,A.revision===P?null:(0,h.jsx)(`p`,{role:`alert`,children:_(`ux.pruneChanged`)})]}):null})]})}var Db=async e=>{await navigator.clipboard.writeText(e)},Ob=(0,m.createContext)(Db);function kb(){return(0,m.useContext)(Ob)}function Ab(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function jb(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e;if(t.version!==1||![`no-findings`,`findings`,`inconclusive`,`findings-and-inconclusive`].includes(String(t.outcome))||!t.counts||typeof t.counts!=`object`||Array.isArray(t.counts)||!t.skipped||typeof t.skipped!=`object`||Array.isArray(t.skipped)||!t.displayIndex||typeof t.displayIndex!=`object`||Array.isArray(t.displayIndex)||!Array.isArray(t.issues)||!t.limits||typeof t.limits!=`object`||Array.isArray(t.limits)||!Object.values(t.counts).every(Ab)||!Object.values(t.skipped).every(Ab)||!Object.values(t.limits).every(Ab))return null;let n=t.displayIndex;return n.status!==`unsupported`||n.reason!==`no-known-display-index-schema`||!t.issues.every(e=>e&&typeof e==`object`&&!Array.isArray(e)&&typeof e.code==`string`)?null:t}function Mb({historyIntegrity:e}){let{t}=Dn(),n=kb(),[r,i]=(0,m.useState)(null),a=jb(e);if(!a)return null;let o=a.issues.slice(0,20),s=a.issuesTruncated===!0||a.issues.length>o.length,c=a.outcome===`no-findings`?`success`:a.outcome===`findings`?`warning`:`neutral`;return(0,h.jsxs)(cb,{className:`mt-4 max-w-3xl`,children:[(0,h.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,h.jsx)(`h2`,{className:`font-semibold`,children:t(`diagnostics.historyIntegrity.title`)}),(0,h.jsx)(db,{tone:c,children:t(`diagnostics.historyIntegrity.outcomes.${a.outcome}`)})]}),(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:t(`diagnostics.historyIntegrity.scope`)}),(0,h.jsx)(`p`,{className:`mt-2 rounded-[var(--radius-control)] border border-[var(--border)] bg-[var(--surface)] p-3 text-sm`,children:t(`diagnostics.historyIntegrity.displayIndexUnsupported`)}),(0,h.jsx)(`dl`,{className:`mt-3 grid gap-2 text-sm sm:grid-cols-2`,children:Object.entries(a.counts).map(([e,n])=>(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:t(`diagnostics.historyIntegrity.counts.${e}`,{defaultValue:e})}),(0,h.jsx)(`dd`,{children:n})]},e))}),Object.values(a.skipped).some(e=>e>0)?(0,h.jsx)(`p`,{className:`mt-3 text-sm text-[var(--warning)]`,children:t(`diagnostics.historyIntegrity.skipped`)}):null,o.length?(0,h.jsxs)(`div`,{className:`mt-3`,children:[(0,h.jsx)(`h3`,{className:`text-sm font-semibold`,children:t(`diagnostics.historyIntegrity.findings`)}),(0,h.jsx)(`ul`,{className:`mt-2 list-disc space-y-2 pl-5 text-sm`,children:o.map((e,a)=>(0,h.jsxs)(`li`,{children:[(0,h.jsx)(`span`,{children:t(`diagnostics.historyIntegrity.issueCodes.${e.code}`,{defaultValue:t(`diagnostics.historyIntegrity.manualReview`)})}),e.sessionId?(0,h.jsxs)(`span`,{className:`ml-1 text-[var(--muted)]`,children:[`· `,t(`diagnostics.historyIntegrity.session`,{sessionId:e.sessionId}),e.line?` · ${t(`diagnostics.historyIntegrity.line`,{line:e.line})}`:``]}):e.line?(0,h.jsxs)(`span`,{className:`ml-1 text-[var(--muted)]`,children:[`· `,t(`diagnostics.historyIntegrity.line`,{line:e.line})]}):null,e.sessionId?(0,h.jsx)(X,{"aria-label":t(`diagnostics.historyIntegrity.copySessionId`),className:`ml-2 align-middle`,onClick:()=>{n(e.sessionId).then(()=>i(e.sessionId))},size:`compact`,type:`button`,variant:`ghost`,children:r===e.sessionId?t(`diagnostics.historyIntegrity.copiedSessionId`):t(`diagnostics.historyIntegrity.copySessionId`)}):null]},`${a}-${e.code}`))}),s?(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:t(`diagnostics.historyIntegrity.moreFindings`)}):null]}):null,(0,h.jsxs)(`details`,{className:`mt-3 rounded-[var(--radius-control)] border border-[var(--border)] bg-[var(--surface)] p-3 text-sm`,children:[(0,h.jsx)(`summary`,{className:`cursor-pointer font-medium`,children:t(`diagnostics.technicalDetails`)}),(0,h.jsx)(`pre`,{className:`mt-3 max-h-72 overflow-auto whitespace-pre-wrap break-words text-xs leading-5 text-[var(--muted)]`,children:JSON.stringify(a,null,2)})]})]})}function Nb(e){let[t,n]=(0,m.useState)(null),r=(0,m.useRef)(null),i=(0,m.useRef)(e);i.current=e,(0,m.useEffect)(()=>(r.current=null,n(null),()=>{r.current=null}),[e]);let a=(0,m.useCallback)(()=>{let t={};return r.current=t,n({profileKey:e,startedAt:performance.now(),progress:null}),{onRequestProgress(a){r.current===t&&i.current===e&&n(e=>e&&{...e,progress:a.progress})},finish(){r.current===t&&(r.current=null,n(null))}}},[e]);return{state:t?.profileKey===e?t:null,start:a}}function Pb({state:e}){let{t}=Dn(),[n,r]=(0,m.useState)(()=>performance.now()),i=e?.startedAt;if((0,m.useEffect)(()=>{if(i===void 0)return;r(performance.now());let e=setInterval(()=>r(performance.now()),1e3);return()=>clearInterval(e)},[i]),!e)return null;let a=e.progress,o=a?.progress===void 0?void 0:Math.round(a.progress*100),s=Math.max(0,Math.floor((n-e.startedAt)/1e3)),c=`${Math.floor(s/60)}:${String(s%60).padStart(2,`0`)}`,l=t(`requestProgress.stages.${a?.stage??`waiting`}`,{defaultValue:t(`requestProgress.working`)});return(0,h.jsxs)(`div`,{className:`mt-3 space-y-2 rounded-lg border border-[var(--border)] bg-[var(--surface)] p-3 text-sm`,"data-testid":`request-progress`,children:[(0,h.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,h.jsx)(`span`,{role:`status`,children:l}),(0,h.jsx)(`span`,{className:`tabular-nums text-[var(--muted)]`,children:t(`requestProgress.elapsed`,{time:c})})]}),(0,h.jsx)(`progress`,{"aria-label":l,className:`block h-2 w-full accent-[var(--accent)]`,max:100,value:o}),(0,h.jsxs)(`div`,{className:`flex flex-wrap justify-between gap-2 text-xs text-[var(--muted)]`,children:[a?.count===void 0?(0,h.jsx)(`span`,{children:t(`requestProgress.working`)}):(0,h.jsx)(`span`,{children:t(`requestProgress.files`,{count:a.count})}),o===void 0?null:(0,h.jsx)(`span`,{children:t(`requestProgress.stagePercent`,{percent:o})})]})]})}var Fb=[`cwd`,`userEvent`,`workspaceRoots`],Ib={models:!1,cwd:!1,userEvent:!1,workspaceRoots:!1};function Lb({targets:e,disabled:t,adjustment:n=!1,prepare:r,progress:i}){let{t:a}=Dn(),o=(0,m.useId)(),s=(0,m.useRef)(null),c=jo({resolver:Vo(Cp),defaultValues:{...Ib}}),l=t||c.formState.isSubmitting;return(0,h.jsxs)(`form`,{className:`mt-4 grid gap-4`,onSubmit:c.handleSubmit(async n=>{if(t)return;let i={...Ib};for(let t of e)i[t]=n[t];await r(i,s.current)}),children:[(0,h.jsx)(`div`,{className:`grid gap-3`,children:e.map(e=>(0,h.jsxs)(`label`,{className:`grid gap-2 rounded-lg border border-[var(--border)] bg-[var(--surface)] p-3`,children:[(0,h.jsxs)(`span`,{className:`flex min-h-8 items-center gap-3`,children:[(0,h.jsx)(`input`,{"aria-label":a(`diagnostics.repairTargets.${e}`),"aria-describedby":`${o}-${e}`,"data-repair-target":e,disabled:l,type:`checkbox`,...c.register(e)}),(0,h.jsx)(`span`,{className:`font-medium`,children:a(`diagnostics.repairTargets.${e}`)})]}),(0,h.jsx)(`span`,{className:`pl-7 text-sm text-[var(--muted)]`,id:`${o}-${e}`,children:a(`diagnostics.repairTargetHints.${e}`)})]},e))}),c.formState.errors.models?(0,h.jsx)(`p`,{className:`text-sm text-[var(--danger)]`,role:`alert`,children:a(`diagnostics.repairTargetRequired`)}):null,!n&&c.watch(`workspaceRoots`)?(0,h.jsx)(`p`,{className:`text-sm text-[var(--muted)]`,children:a(`diagnostics.workspaceRootsIncludesCwd`)}):null,(0,h.jsxs)(X,{disabled:l,ref:s,type:`submit`,children:[(0,h.jsx)(qi,{size:16}),a(n?`diagnostics.previewAdjustment`:`diagnostics.prepareRepair`)]}),c.formState.isSubmitting?(0,h.jsx)(Pb,{state:i}):null]})}function Rb({diagnostics:e,fresh:t,disabled:n,prepare:r,progress:i}){let{t:a}=Dn(),o=(0,m.useRef)(null),s=e?.safety,c=t&&!n&&s?.rolloutScanComplete===!0&&s.pendingRecovery===!1&&s.operationInProgress===null&&s.lockedRolloutCount===0&&e?.storage.stateDbFound===!0&&e.storage.sqliteSupported===!0&&e.provider.sqliteCounts!==null&&typeof e.provider.sqliteCounts==`object`,l={cwd:`cwdRowsNeedingRepair`,userEvent:`userEventRowsNeedingRepair`,workspaceRoots:`workspaceRootsNeedingRepair`},u=c?Fb.flatMap(t=>{let n=e?.issues[l[t]];return typeof n==`number`&&Number.isSafeInteger(n)&&n>0?[{target:t,count:n}]:[]}):[];return(0,h.jsxs)(`div`,{className:`mt-4 grid max-w-3xl gap-4`,children:[u.length?(0,h.jsxs)(cb,{children:[(0,h.jsx)(`h2`,{className:`font-semibold`,children:a(`diagnostics.availableRepairs`)}),(0,h.jsx)(`ul`,{className:`mt-3 grid gap-3`,children:u.map(({target:e,count:t})=>(0,h.jsxs)(`li`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,h.jsx)(`span`,{className:`text-sm`,children:a(`diagnostics.findings.${e}`,{count:t})}),(0,h.jsx)(X,{"aria-label":a(`diagnostics.viewSpecificRepair`,{target:a(`diagnostics.repairTargets.${e}`)}),onClick:()=>{n||!o.current||(o.current.open=!0,o.current.querySelector(`input[data-repair-target="${e}"]`)?.focus())},type:`button`,variant:`secondary`,children:a(`diagnostics.viewRepair`)})]},e))})]}):null,(0,h.jsx)(cb,{children:(0,h.jsxs)(`details`,{ref:o,children:[(0,h.jsx)(`summary`,{className:`cursor-pointer font-semibold focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--accent)]`,children:a(`diagnostics.repairTitle`)}),(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:a(`diagnostics.repairHint`)}),(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:a(`diagnostics.repairScope`)}),(0,h.jsx)(Lb,{progress:i,disabled:n,targets:Fb,prepare:r})]})}),(0,h.jsx)(cb,{children:(0,h.jsxs)(`details`,{children:[(0,h.jsx)(`summary`,{className:`cursor-pointer font-semibold focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--accent)]`,children:a(`diagnostics.adjustmentTitle`)}),(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:a(`diagnostics.adjustmentHint`)}),(0,h.jsx)(Lb,{progress:i,adjustment:!0,disabled:n,targets:[`models`],prepare:r})]})})]})}function zb({diagnostics:e,error:t,expired:n=!1,loading:r,exporting:i,canExport:a,canRepair:o,repairDisabled:s,refresh:c,exportBundle:l,prepareRepair:u,scanProgress:d,repairProgress:f}){let{t:p,i18n:g}=Dn(),_=e?[[`runtime`,e.runtime],[`storage`,e.storage],[`provider`,e.provider],[`issues`,e.issues],[`safety`,e.safety]]:[],v=e=>e==null||e===``?p(`common.none`):typeof e==`boolean`?(0,h.jsx)(db,{tone:e?`success`:`neutral`,children:p(e?`common.yes`:`common.no`)}):typeof e==`string`||typeof e==`number`?String(e):Array.isArray(e)?p(`diagnostics.items`,{count:e.length}):typeof e==`object`?p(`diagnostics.fieldsAvailable`,{count:Object.keys(e).length}):p(`common.unknown`);return(0,h.jsxs)(m.Fragment,{children:[(0,h.jsx)(Sb,{title:p(`diagnostics.title`),subtitle:p(`diagnostics.subtitle`)}),(0,h.jsxs)(cb,{className:`mb-4`,children:[(0,h.jsx)(`h2`,{className:`font-semibold`,children:p(`diagnostics.scanTitle`)}),(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:p(`diagnostics.scanHint`)}),(0,h.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-2`,children:[(0,h.jsxs)(X,{disabled:r,onClick:c,type:`button`,variant:`secondary`,children:[(0,h.jsx)(Ii,{size:16}),p(r?`common.loading`:t?`diagnostics.retryScan`:`diagnostics.runScan`)]}),a?(0,h.jsxs)(X,{disabled:i||r||!!t||!e,onClick:l,type:`button`,variant:`secondary`,children:[(0,h.jsx)(hi,{size:16}),p(i?`diagnostics.exporting`:`diagnostics.export`)]}):null]}),r?(0,h.jsx)(`p`,{className:`mt-3 text-sm text-[var(--muted)]`,role:`status`,children:p(`diagnostics.scanning`)}):t?(0,h.jsxs)(`div`,{className:`mt-3 rounded-lg border border-[var(--danger)] p-3 text-sm`,role:`alert`,children:[(0,h.jsx)(`p`,{className:`font-semibold`,children:p(`diagnostics.scanFailed`)}),(0,h.jsx)(`p`,{children:yb(t,p)}),(0,h.jsx)(`p`,{children:p(`diagnostics.scanFailedHint`)})]}):e?null:(0,h.jsx)(`p`,{className:`mt-3 text-sm text-[var(--muted)]`,children:p(`diagnostics.notScanned`)}),r?(0,h.jsx)(Pb,{state:d}):null,e?(0,h.jsx)(`p`,{className:`mt-3 text-sm text-[var(--muted)]`,children:p(t||r?`diagnostics.previousResult`:n?`diagnostics.expiredResult`:`diagnostics.scanCompleted`,{time:vb(e.generatedAt,g.language)})}):null,e?.safety.rolloutScanComplete===!1&&!r&&!t?(0,h.jsx)(`p`,{className:`mt-3 text-sm text-[var(--warning)]`,role:`status`,children:p(`diagnostics.incompleteScan`)}):null]}),(0,h.jsx)(`div`,{className:`grid gap-4 lg:grid-cols-2`,children:_.map(([e,t])=>(0,h.jsxs)(cb,{children:[(0,h.jsx)(`h2`,{className:`mb-2 font-semibold`,children:p(`diagnostics.${e}`)}),e===`issues`?(0,h.jsxs)(`div`,{className:`mb-3 space-y-2 text-sm text-[var(--muted)]`,children:[(0,h.jsx)(`p`,{children:p(`diagnostics.issuesHint`)}),(0,h.jsx)(`p`,{children:p(`diagnostics.modelDifferenceHint`)}),(0,h.jsx)(`p`,{children:p(`diagnostics.workspaceCountHint`)}),(0,h.jsx)(`p`,{children:p(`diagnostics.encryptedHint`)})]}):null,(0,h.jsx)(`dl`,{children:Object.entries(t).map(([e,t])=>(0,h.jsx)(Cb,{label:p(`diagnostics.fields.${e}`,{defaultValue:e}),value:v(t)},e))}),(0,h.jsxs)(`details`,{className:`mt-3 rounded-[var(--radius-control)] border border-[var(--border)] bg-[var(--surface)] p-3 text-sm`,children:[(0,h.jsx)(`summary`,{className:`cursor-pointer font-medium`,children:p(`diagnostics.technicalDetails`)}),(0,h.jsx)(`pre`,{className:`mt-3 max-h-72 overflow-auto whitespace-pre-wrap break-words text-xs leading-5 text-[var(--muted)]`,children:JSON.stringify(t,null,2)})]})]},e))}),e?(0,h.jsx)(Mb,{historyIntegrity:e.historyIntegrity}):null,o?(0,h.jsx)(Rb,{progress:f,diagnostics:e,fresh:!!e&&!t&&!n&&!r,disabled:s,prepare:u}):null]})}function Bb(e,t){let n=t||{};return(e[e.length-1]===``?[...e,``]:e).join((n.padRight?` `:``)+`,`+(n.padLeft===!1?``:` `)).trim()}var Vb=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Hb=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Ub={};function Wb(e,t){return((t||Ub).jsx?Hb:Vb).test(e)}var Gb=/[ \t\n\f\r]/g;function Kb(e){return typeof e==`object`?e.type===`text`&&qb(e.value):qb(e)}function qb(e){return e.replace(Gb,``)===``}var Jb=class{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}};Jb.prototype.normal={},Jb.prototype.property={},Jb.prototype.space=void 0;function Yb(e,t){let n={},r={};for(let t of e)Object.assign(n,t.property),Object.assign(r,t.normal);return new Jb(n,r,t)}function Xb(e){return e.toLowerCase()}var Zb=class{constructor(e,t){this.attribute=t,this.property=e}};Zb.prototype.attribute=``,Zb.prototype.booleanish=!1,Zb.prototype.boolean=!1,Zb.prototype.commaOrSpaceSeparated=!1,Zb.prototype.commaSeparated=!1,Zb.prototype.defined=!1,Zb.prototype.mustUseProperty=!1,Zb.prototype.number=!1,Zb.prototype.overloadedBoolean=!1,Zb.prototype.property=``,Zb.prototype.spaceSeparated=!1,Zb.prototype.space=void 0;var Qb=s({boolean:()=>Z,booleanish:()=>ex,commaOrSpaceSeparated:()=>ix,commaSeparated:()=>rx,number:()=>Q,overloadedBoolean:()=>tx,spaceSeparated:()=>nx}),$b=0,Z=ax(),ex=ax(),tx=ax(),Q=ax(),nx=ax(),rx=ax(),ix=ax();function ax(){return 2**++$b}var ox=Object.keys(Qb),sx=class extends Zb{constructor(e,t,n,r){let i=-1;if(super(e,t),cx(this,`space`,r),typeof n==`number`)for(;++i4&&n.slice(0,4)===`data`&&xx.test(t)){if(t.charAt(4)===`-`){let e=t.slice(5).replace(bx,wx);r=`data`+e.charAt(0).toUpperCase()+e.slice(1)}else{let e=t.slice(4);if(!bx.test(e)){let n=e.replace(yx,Cx);n.charAt(0)!==`-`&&(n=`-`+n),t=`data`+n}}i=sx}return new i(r,t)}function Cx(e){return`-`+e.toLowerCase()}function wx(e){return e.charAt(1).toUpperCase()}var Tx=Yb([ux,px,hx,gx,_x],`html`),Ex=Yb([ux,mx,hx,gx,_x],`svg`);function Dx(e){return e.join(` `).trim()}var Ox=o(((e,t)=>{var n=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,r=/\n/g,i=/^\s*/,a=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,o=/^:\s*/,s=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,l=/^\s+|\s+$/g;function u(e,t){if(typeof e!=`string`)throw TypeError(`First argument must be a string`);if(!e)return[];t||={};var l=1,u=1;function f(e){var t=e.match(r);t&&(l+=t.length);var n=e.lastIndexOf(` +`);u=~n?e.length-n:u+e.length}function p(){var e={line:l,column:u};return function(t){return t.position=new m(e),_(),t}}function m(e){this.start=e,this.end={line:l,column:u},this.source=t.source}m.prototype.content=e;function h(n){var r=Error(t.source+`:`+l+`:`+u+`: `+n);if(r.reason=n,r.filename=t.source,r.line=l,r.column=u,r.source=e,!t.silent)throw r}function g(t){var n=t.exec(e);if(n){var r=n[0];return f(r),e=e.slice(r.length),n}}function _(){g(i)}function v(e){var t;for(e||=[];t=y();)t!==!1&&e.push(t);return e}function y(){var t=p();if(e.charAt(0)==`/`&&e.charAt(1)==`*`){for(var n=2;e.charAt(n)!=``&&(e.charAt(n)!=`*`||e.charAt(n+1)!=`/`);)++n;if(n+=2,e.charAt(n-1)===``)return h(`End of comment missing`);var r=e.slice(2,n-2);return u+=2,f(r),e=e.slice(n),u+=2,t({type:`comment`,comment:r})}}function b(){var e=p(),t=g(a);if(t){if(y(),!g(o))return h(`property missing ':'`);var r=g(s),i=e({type:`declaration`,property:d(t[0].replace(n,``)),value:r?d(r[0].replace(n,``)):``});return g(c),i}}function x(){var e=[];v(e);for(var t;t=b();)t!==!1&&(e.push(t),v(e));return e}return _(),x()}function d(e){return e?e.replace(l,``):``}t.exports=u})),kx=o((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.default=r;var n=t(Ox());function r(e,t){let r=null;if(!e||typeof e!=`string`)return r;let i=(0,n.default)(e),a=typeof t==`function`;return i.forEach(e=>{if(e.type!==`declaration`)return;let{property:n,value:i}=e;a?t(n,i,e):i&&(r||={},r[n]=i)}),r}})),Ax=o((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.camelCase=void 0;var t=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,r=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(e){return!e||r.test(e)||t.test(e)},s=function(e,t){return t.toUpperCase()},c=function(e,t){return`${t}-`};e.camelCase=function(e,t){return t===void 0&&(t={}),o(e)?e:(e=e.toLowerCase(),e=t.reactCompat?e.replace(a,c):e.replace(i,c),e.replace(n,s))}})),jx=o(((e,t)=>{var n=(e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(kx()),r=Ax();function i(e,t){var i={};return!e||typeof e!=`string`||(0,n.default)(e,function(e,n){e&&n&&(i[(0,r.camelCase)(e,t)]=n)}),i}i.default=i,t.exports=i})),Mx=Px(`end`),Nx=Px(`start`);function Px(e){return t;function t(t){let n=t&&t.position&&t.position[e]||{};if(typeof n.line==`number`&&n.line>0&&typeof n.column==`number`&&n.column>0)return{line:n.line,column:n.column,offset:typeof n.offset==`number`&&n.offset>-1?n.offset:void 0}}}function Fx(e){let t=Nx(e),n=Mx(e);if(t&&n)return{start:t,end:n}}function Ix(e){return!e||typeof e!=`object`?``:`position`in e||`type`in e?Rx(e.position):`start`in e||`end`in e?Rx(e):`line`in e||`column`in e?Lx(e):``}function Lx(e){return zx(e&&e.line)+`:`+zx(e&&e.column)}function Rx(e){return Lx(e&&e.start)+`-`+Lx(e&&e.end)}function zx(e){return e&&typeof e==`number`?e:1}var Bx=class extends Error{constructor(e,t,n){super(),typeof t==`string`&&(n=t,t=void 0);let r=``,i={},a=!1;if(t&&(i=`line`in t&&`column`in t||`start`in t&&`end`in t?{place:t}:`type`in t?{ancestors:[t],place:t.position}:{...t}),typeof e==`string`?r=e:!i.cause&&e&&(a=!0,r=e.message,i.cause=e),!i.ruleId&&!i.source&&typeof n==`string`){let e=n.indexOf(`:`);e===-1?i.ruleId=n:(i.source=n.slice(0,e),i.ruleId=n.slice(e+1))}if(!i.place&&i.ancestors&&i.ancestors){let e=i.ancestors[i.ancestors.length-1];e&&(i.place=e.position)}let o=i.place&&`start`in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file=``,this.message=r,this.line=o?o.line:void 0,this.name=Ix(i.place)||`1:1`,this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=a&&i.cause&&typeof i.cause.stack==`string`?i.cause.stack:``,this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}};Bx.prototype.file=``,Bx.prototype.name=``,Bx.prototype.reason=``,Bx.prototype.message=``,Bx.prototype.stack=``,Bx.prototype.column=void 0,Bx.prototype.line=void 0,Bx.prototype.ancestors=void 0,Bx.prototype.cause=void 0,Bx.prototype.fatal=void 0,Bx.prototype.place=void 0,Bx.prototype.ruleId=void 0,Bx.prototype.source=void 0;var Vx=l(jx(),1),Hx={}.hasOwnProperty,Ux=new Map,Wx=/[A-Z]/g,Gx=new Set([`table`,`tbody`,`thead`,`tfoot`,`tr`]),Kx=new Set([`td`,`th`]),qx=`https://github.com/syntax-tree/hast-util-to-jsx-runtime`;function Jx(e,t){if(!t||t.Fragment===void 0)throw TypeError("Expected `Fragment` in options");let n=t.filePath||void 0,r;if(t.development){if(typeof t.jsxDEV!=`function`)throw TypeError("Expected `jsxDEV` in options when `development: true`");r=aS(n,t.jsxDEV)}else{if(typeof t.jsx!=`function`)throw TypeError("Expected `jsx` in production options");if(typeof t.jsxs!=`function`)throw TypeError("Expected `jsxs` in production options");r=iS(n,t.jsx,t.jsxs)}let i={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||`react`,evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space===`svg`?Ex:Tx,stylePropertyNameCase:t.stylePropertyNameCase||`dom`,tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},a=Yx(i,e,void 0);return a&&typeof a!=`string`?a:i.create(e,i.Fragment,{children:a||void 0},void 0)}function Yx(e,t,n){if(t.type===`element`)return Xx(e,t,n);if(t.type===`mdxFlowExpression`||t.type===`mdxTextExpression`)return Zx(e,t);if(t.type===`mdxJsxFlowElement`||t.type===`mdxJsxTextElement`)return $x(e,t,n);if(t.type===`mdxjsEsm`)return Qx(e,t);if(t.type===`root`)return eS(e,t,n);if(t.type===`text`)return tS(e,t)}function Xx(e,t,n){let r=e.schema,i=r;t.tagName.toLowerCase()===`svg`&&r.space===`html`&&(i=Ex,e.schema=i),e.ancestors.push(t);let a=dS(e,t.tagName,!1),o=oS(e,t),s=cS(e,t);return Gx.has(t.tagName)&&(s=s.filter(function(e){return typeof e!=`string`||!Kb(e)})),nS(e,o,a,t),rS(o,s),e.ancestors.pop(),e.schema=r,e.create(t,a,o,n)}function Zx(e,t){if(t.data&&t.data.estree&&e.evaluater){let n=t.data.estree.body[0];return n.type,e.evaluater.evaluateExpression(n.expression)}fS(e,t.position)}function Qx(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);fS(e,t.position)}function $x(e,t,n){let r=e.schema,i=r;t.name===`svg`&&r.space===`html`&&(i=Ex,e.schema=i),e.ancestors.push(t);let a=t.name===null?e.Fragment:dS(e,t.name,!0),o=sS(e,t),s=cS(e,t);return nS(e,o,a,t),rS(o,s),e.ancestors.pop(),e.schema=r,e.create(t,a,o,n)}function eS(e,t,n){let r={};return rS(r,cS(e,t)),e.create(t,e.Fragment,r,n)}function tS(e,t){return t.value}function nS(e,t,n,r){typeof n!=`string`&&n!==e.Fragment&&e.passNode&&(t.node=r)}function rS(e,t){if(t.length>0){let n=t.length>1?t:t[0];n&&(e.children=n)}}function iS(e,t,n){return r;function r(e,r,i,a){let o=Array.isArray(i.children)?n:t;return a?o(r,i,a):o(r,i)}}function aS(e,t){return n;function n(n,r,i,a){let o=Array.isArray(i.children),s=Nx(n);return t(r,i,a,o,{columnNumber:s?s.column-1:void 0,fileName:e,lineNumber:s?s.line:void 0},void 0)}}function oS(e,t){let n={},r,i;for(i in t.properties)if(i!==`children`&&Hx.call(t.properties,i)){let a=lS(e,i,t.properties[i]);if(a){let[i,o]=a;e.tableCellAlignToStyle&&i===`align`&&typeof o==`string`&&Kx.has(t.tagName)?r=o:n[i]=o}}if(r){let t=n.style||={};t[e.stylePropertyNameCase===`css`?`text-align`:`textAlign`]=r}return n}function sS(e,t){let n={};for(let r of t.attributes)if(r.type===`mdxJsxExpressionAttribute`){if(r.data&&r.data.estree&&e.evaluater){let t=r.data.estree.body[0];t.type;let i=t.expression;i.type;let a=i.properties[0];a.type,Object.assign(n,e.evaluater.evaluateExpression(a.argument))}else fS(e,t.position)}else{let i=r.name,a;if(r.value&&typeof r.value==`object`){if(r.value.data&&r.value.data.estree&&e.evaluater){let t=r.value.data.estree.body[0];t.type,a=e.evaluater.evaluateExpression(t.expression)}else fS(e,t.position)}else a=r.value===null||r.value;n[i]=a}return n}function cS(e,t){let n=[],r=-1,i=e.passKeys?new Map:Ux;for(;++ri?0:i+t:t>i?i:t,n=n>0?n:0,r.length<1e4)o=Array.from(r),o.unshift(t,n),e.splice(...o);else for(n&&e.splice(t,n);a0?(wS(e,e.length,0,t),e):t}var ES={}.hasOwnProperty;function DS(e){let t={},n=-1;for(;++n13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)==65535||(n&65535)==65534||n>1114111?`�`:String.fromCodePoint(n)}function jS(e){return e.replace(/[\t\n\r ]+/g,` `).replace(/^ | $/g,``).toLowerCase().toUpperCase()}var MS=US(/[A-Za-z]/),NS=US(/[\dA-Za-z]/),PS=US(/[#-'*+\--9=?A-Z^-~]/);function FS(e){return e!==null&&(e<32||e===127)}var IS=US(/\d/),LS=US(/[\dA-Fa-f]/),RS=US(/[!-/:-@[-`{-~]/);function $(e){return e!==null&&e<-2}function zS(e){return e!==null&&(e<0||e===32)}function BS(e){return e===-2||e===-1||e===32}var VS=US(/\p{P}|\p{S}/u),HS=US(/\s/);function US(e){return t;function t(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}function WS(e){let t=[],n=-1,r=0,i=0;for(;++n55295&&a<57344){let t=e.charCodeAt(n+1);a<56320&&t>56319&&t<57344?(o=String.fromCharCode(a,t),i=1):o=`�`}else o=String.fromCharCode(a);o&&=(t.push(e.slice(r,n),encodeURIComponent(o)),r=n+i+1,``),i&&=(n+=i,0)}return t.join(``)+e.slice(r)}function GS(e,t,n,r){let i=r?r-1:1/0,a=0;return o;function o(r){return BS(r)?(e.enter(n),s(r)):t(r)}function s(r){return BS(r)&&a++o))return;let n=t.events.length,a=n,s,c;for(;a--;)if(t.events[a][0]===`exit`&&t.events[a][1].type===`chunkFlow`){if(s){c=t.events[a][1].end;break}s=!0}for(_(r),e=n;er;){let r=n[i];t.containerState=r[1],r[0].exit.call(t,e)}n.length=r}function v(){i.write([null]),a=void 0,i=void 0,t.containerState._closeFlow=void 0}}function ZS(e,t,n){return GS(e,e.attempt(this.parser.constructs.document,t,n),`linePrefix`,this.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)}function QS(e){if(e===null||zS(e)||HS(e))return 1;if(VS(e))return 2}function $S(e,t,n){let r=[],i=-1;for(;++i1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;let d={...e[r][1].end},f={...e[n][1].start};rC(d,-c),rC(f,c),o={type:c>1?`strongSequence`:`emphasisSequence`,start:d,end:{...e[r][1].end}},s={type:c>1?`strongSequence`:`emphasisSequence`,start:{...e[n][1].start},end:f},a={type:c>1?`strongText`:`emphasisText`,start:{...e[r][1].end},end:{...e[n][1].start}},i={type:c>1?`strong`:`emphasis`,start:{...o.start},end:{...s.end}},e[r][1].end={...o.start},e[n][1].start={...s.end},l=[],e[r][1].end.offset-e[r][1].start.offset&&(l=TS(l,[[`enter`,e[r][1],t],[`exit`,e[r][1],t]])),l=TS(l,[[`enter`,i,t],[`enter`,o,t],[`exit`,o,t],[`enter`,a,t]]),l=TS(l,$S(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),l=TS(l,[[`exit`,a,t],[`enter`,s,t],[`exit`,s,t],[`exit`,i,t]]),e[n][1].end.offset-e[n][1].start.offset?(u=2,l=TS(l,[[`enter`,e[n][1],t],[`exit`,e[n][1],t]])):u=0,wS(e,r-1,n-r+3,l),n=r+l.length-u-2;break}}for(n=-1;++n0&&BS(t)?GS(e,v,`linePrefix`,a+1)(t):v(t)}function v(t){return t===null||$(t)?e.check(gC,h,b)(t):(e.enter(`codeFlowValue`),y(t))}function y(t){return t===null||$(t)?(e.exit(`codeFlowValue`),v(t)):(e.consume(t),y)}function b(n){return e.exit(`codeFenced`),t(n)}function x(e,t,n){let i=0;return a;function a(t){return e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),c}function c(t){return e.enter(`codeFencedFence`),BS(t)?GS(e,l,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):l(t)}function l(t){return t===s?(e.enter(`codeFencedFenceSequence`),u(t)):n(t)}function u(t){return t===s?(i++,e.consume(t),u):i>=o?(e.exit(`codeFencedFenceSequence`),BS(t)?GS(e,d,`whitespace`)(t):d(t)):n(t)}function d(r){return r===null||$(r)?(e.exit(`codeFencedFence`),t(r)):n(r)}}}function yC(e,t,n){let r=this;return i;function i(t){return t===null?n(t):(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),a)}function a(e){return r.parser.lazy[r.now().line]?n(e):t(e)}}var bC={name:`codeIndented`,tokenize:SC},xC={partial:!0,tokenize:CC};function SC(e,t,n){let r=this;return i;function i(t){return e.enter(`codeIndented`),GS(e,a,`linePrefix`,5)(t)}function a(e){let t=r.events[r.events.length-1];return t&&t[1].type===`linePrefix`&&t[2].sliceSerialize(t[1],!0).length>=4?o(e):n(e)}function o(t){return t===null?c(t):$(t)?e.attempt(xC,o,c)(t):(e.enter(`codeFlowValue`),s(t))}function s(t){return t===null||$(t)?(e.exit(`codeFlowValue`),o(t)):(e.consume(t),s)}function c(n){return e.exit(`codeIndented`),t(n)}}function CC(e,t,n){let r=this;return i;function i(t){return r.parser.lazy[r.now().line]?n(t):$(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),i):GS(e,a,`linePrefix`,5)(t)}function a(e){let a=r.events[r.events.length-1];return a&&a[1].type===`linePrefix`&&a[2].sliceSerialize(a[1],!0).length>=4?t(e):$(e)?i(e):n(e)}}var wC={name:`codeText`,previous:EC,resolve:TC,tokenize:DC};function TC(e){let t=e.length-4,n=3,r,i;if((e[n][1].type===`lineEnding`||e[n][1].type===`space`)&&(e[t][1].type===`lineEnding`||e[t][1].type===`space`)){for(r=n;++r=this.left.length+this.right.length)throw RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return ethis.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(e,t,n){let r=t||0;this.setCursor(Math.trunc(e));let i=this.right.splice(this.right.length-r,1/0);return n&&kC(this.left,n),i.reverse()}pop(){return this.setCursor(1/0),this.left.pop()}push(e){this.setCursor(1/0),this.left.push(e)}pushMany(e){this.setCursor(1/0),kC(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),kC(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&this.right.length===0||e<0&&this.left.length===0)){if(e=4?t(i):e.interrupt(r.parser.constructs.flow,n,t)(i)}}function LC(e,t,n,r,i,a,o,s,c){let l=c||1/0,u=0;return d;function d(t){return t===60?(e.enter(r),e.enter(i),e.enter(a),e.consume(t),e.exit(a),f):t===null||t===32||t===41||FS(t)?n(t):(e.enter(r),e.enter(o),e.enter(s),e.enter(`chunkString`,{contentType:`string`}),h(t))}function f(n){return n===62?(e.enter(a),e.consume(n),e.exit(a),e.exit(i),e.exit(r),t):(e.enter(s),e.enter(`chunkString`,{contentType:`string`}),p(n))}function p(t){return t===62?(e.exit(`chunkString`),e.exit(s),f(t)):t===null||t===60||$(t)?n(t):(e.consume(t),t===92?m:p)}function m(t){return t===60||t===62||t===92?(e.consume(t),p):p(t)}function h(i){return!u&&(i===null||i===41||zS(i))?(e.exit(`chunkString`),e.exit(s),e.exit(o),e.exit(r),t(i)):u999||l===null||l===91||l===93&&!c||l===94&&!s&&`_hiddenFootnoteSupport`in o.parser.constructs?n(l):l===93?(e.exit(a),e.enter(i),e.consume(l),e.exit(i),e.exit(r),t):$(l)?(e.enter(`lineEnding`),e.consume(l),e.exit(`lineEnding`),u):(e.enter(`chunkString`,{contentType:`string`}),d(l))}function d(t){return t===null||t===91||t===93||$(t)||s++>999?(e.exit(`chunkString`),u(t)):(e.consume(t),c||=!BS(t),t===92?f:d)}function f(t){return t===91||t===92||t===93?(e.consume(t),s++,d):d(t)}}function zC(e,t,n,r,i,a){let o;return s;function s(t){return t===34||t===39||t===40?(e.enter(r),e.enter(i),e.consume(t),e.exit(i),o=t===40?41:t,c):n(t)}function c(n){return n===o?(e.enter(i),e.consume(n),e.exit(i),e.exit(r),t):(e.enter(a),l(n))}function l(t){return t===o?(e.exit(a),c(o)):t===null?n(t):$(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),GS(e,l,`linePrefix`)):(e.enter(`chunkString`,{contentType:`string`}),u(t))}function u(t){return t===o||t===null||$(t)?(e.exit(`chunkString`),l(t)):(e.consume(t),t===92?d:u)}function d(t){return t===o||t===92?(e.consume(t),u):u(t)}}function BC(e,t){let n;return r;function r(i){return $(i)?(e.enter(`lineEnding`),e.consume(i),e.exit(`lineEnding`),n=!0,r):BS(i)?GS(e,r,n?`linePrefix`:`lineSuffix`)(i):t(i)}}var VC={name:`definition`,tokenize:UC},HC={partial:!0,tokenize:WC};function UC(e,t,n){let r=this,i;return a;function a(t){return e.enter(`definition`),o(t)}function o(t){return RC.call(r,e,s,n,`definitionLabel`,`definitionLabelMarker`,`definitionLabelString`)(t)}function s(t){return i=jS(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),t===58?(e.enter(`definitionMarker`),e.consume(t),e.exit(`definitionMarker`),c):n(t)}function c(t){return zS(t)?BC(e,l)(t):l(t)}function l(t){return LC(e,u,n,`definitionDestination`,`definitionDestinationLiteral`,`definitionDestinationLiteralMarker`,`definitionDestinationRaw`,`definitionDestinationString`)(t)}function u(t){return e.attempt(HC,d,d)(t)}function d(t){return BS(t)?GS(e,f,`whitespace`)(t):f(t)}function f(a){return a===null||$(a)?(e.exit(`definition`),r.parser.defined.push(i),t(a)):n(a)}}function WC(e,t,n){return r;function r(t){return zS(t)?BC(e,i)(t):n(t)}function i(t){return zC(e,a,n,`definitionTitle`,`definitionTitleMarker`,`definitionTitleString`)(t)}function a(t){return BS(t)?GS(e,o,`whitespace`)(t):o(t)}function o(e){return e===null||$(e)?t(e):n(e)}}var GC={name:`hardBreakEscape`,tokenize:KC};function KC(e,t,n){return r;function r(t){return e.enter(`hardBreakEscape`),e.consume(t),i}function i(r){return $(r)?(e.exit(`hardBreakEscape`),t(r)):n(r)}}var qC={name:`headingAtx`,resolve:JC,tokenize:YC};function JC(e,t){let n=e.length-2,r=3,i,a;return e[r][1].type===`whitespace`&&(r+=2),n-2>r&&e[n][1].type===`whitespace`&&(n-=2),e[n][1].type===`atxHeadingSequence`&&(r===n-1||n-4>r&&e[n-2][1].type===`whitespace`)&&(n-=r+1===n?2:4),n>r&&(i={type:`atxHeadingText`,start:e[r][1].start,end:e[n][1].end},a={type:`chunkText`,start:e[r][1].start,end:e[n][1].end,contentType:`text`},wS(e,r,n-r+1,[[`enter`,i,t],[`enter`,a,t],[`exit`,a,t],[`exit`,i,t]])),e}function YC(e,t,n){let r=0;return i;function i(t){return e.enter(`atxHeading`),a(t)}function a(t){return e.enter(`atxHeadingSequence`),o(t)}function o(t){return t===35&&r++<6?(e.consume(t),o):t===null||zS(t)?(e.exit(`atxHeadingSequence`),s(t)):n(t)}function s(n){return n===35?(e.enter(`atxHeadingSequence`),c(n)):n===null||$(n)?(e.exit(`atxHeading`),t(n)):BS(n)?GS(e,s,`whitespace`)(n):(e.enter(`atxHeadingText`),l(n))}function c(t){return t===35?(e.consume(t),c):(e.exit(`atxHeadingSequence`),s(t))}function l(t){return t===null||t===35||zS(t)?(e.exit(`atxHeadingText`),s(t)):(e.consume(t),l)}}var XC=`address.article.aside.base.basefont.blockquote.body.caption.center.col.colgroup.dd.details.dialog.dir.div.dl.dt.fieldset.figcaption.figure.footer.form.frame.frameset.h1.h2.h3.h4.h5.h6.head.header.hr.html.iframe.legend.li.link.main.menu.menuitem.nav.noframes.ol.optgroup.option.p.param.search.section.summary.table.tbody.td.tfoot.th.thead.title.tr.track.ul`.split(`.`),ZC=[`pre`,`script`,`style`,`textarea`],QC={concrete:!0,name:`htmlFlow`,resolveTo:tw,tokenize:nw},$C={partial:!0,tokenize:iw},ew={partial:!0,tokenize:rw};function tw(e){let t=e.length;for(;t--&&(e[t][0]!==`enter`||e[t][1].type!==`htmlFlow`););return t>1&&e[t-2][1].type===`linePrefix`&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function nw(e,t,n){let r=this,i,a,o,s,c;return l;function l(e){return u(e)}function u(t){return e.enter(`htmlFlow`),e.enter(`htmlFlowData`),e.consume(t),d}function d(s){return s===33?(e.consume(s),f):s===47?(e.consume(s),a=!0,h):s===63?(e.consume(s),i=3,r.interrupt?t:F):MS(s)?(e.consume(s),o=String.fromCharCode(s),g):n(s)}function f(a){return a===45?(e.consume(a),i=2,p):a===91?(e.consume(a),i=5,s=0,m):MS(a)?(e.consume(a),i=4,r.interrupt?t:F):n(a)}function p(i){return i===45?(e.consume(i),r.interrupt?t:F):n(i)}function m(i){return i===`CDATA[`.charCodeAt(s++)?(e.consume(i),s===6?r.interrupt?t:O:m):n(i)}function h(t){return MS(t)?(e.consume(t),o=String.fromCharCode(t),g):n(t)}function g(s){if(s===null||s===47||s===62||zS(s)){let c=s===47,l=o.toLowerCase();return!c&&!a&&ZC.includes(l)?(i=1,r.interrupt?t(s):O(s)):XC.includes(o.toLowerCase())?(i=6,c?(e.consume(s),_):r.interrupt?t(s):O(s)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(s):a?v(s):y(s))}return s===45||NS(s)?(e.consume(s),o+=String.fromCharCode(s),g):n(s)}function _(i){return i===62?(e.consume(i),r.interrupt?t:O):n(i)}function v(t){return BS(t)?(e.consume(t),v):E(t)}function y(t){return t===47?(e.consume(t),E):t===58||t===95||MS(t)?(e.consume(t),b):BS(t)?(e.consume(t),y):E(t)}function b(t){return t===45||t===46||t===58||t===95||NS(t)?(e.consume(t),b):x(t)}function x(t){return t===61?(e.consume(t),S):BS(t)?(e.consume(t),x):y(t)}function S(t){return t===null||t===60||t===61||t===62||t===96?n(t):t===34||t===39?(e.consume(t),c=t,C):BS(t)?(e.consume(t),S):w(t)}function C(t){return t===c?(e.consume(t),c=null,T):t===null||$(t)?n(t):(e.consume(t),C)}function w(t){return t===null||t===34||t===39||t===47||t===60||t===61||t===62||t===96||zS(t)?x(t):(e.consume(t),w)}function T(e){return e===47||e===62||BS(e)?y(e):n(e)}function E(t){return t===62?(e.consume(t),D):n(t)}function D(t){return t===null||$(t)?O(t):BS(t)?(e.consume(t),D):n(t)}function O(t){return t===45&&i===2?(e.consume(t),j):t===60&&i===1?(e.consume(t),M):t===62&&i===4?(e.consume(t),te):t===63&&i===3?(e.consume(t),F):t===93&&i===5?(e.consume(t),P):$(t)&&(i===6||i===7)?(e.exit(`htmlFlowData`),e.check($C,ne,ee)(t)):t===null||$(t)?(e.exit(`htmlFlowData`),ee(t)):(e.consume(t),O)}function ee(t){return e.check(ew,k,ne)(t)}function k(t){return e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),A}function A(t){return t===null||$(t)?ee(t):(e.enter(`htmlFlowData`),O(t))}function j(t){return t===45?(e.consume(t),F):O(t)}function M(t){return t===47?(e.consume(t),o=``,N):O(t)}function N(t){if(t===62){let n=o.toLowerCase();return ZC.includes(n)?(e.consume(t),te):O(t)}return MS(t)&&o.length<8?(e.consume(t),o+=String.fromCharCode(t),N):O(t)}function P(t){return t===93?(e.consume(t),F):O(t)}function F(t){return t===62?(e.consume(t),te):t===45&&i===2?(e.consume(t),F):O(t)}function te(t){return t===null||$(t)?(e.exit(`htmlFlowData`),ne(t)):(e.consume(t),te)}function ne(n){return e.exit(`htmlFlow`),t(n)}}function rw(e,t,n){let r=this;return i;function i(t){return $(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),a):n(t)}function a(e){return r.parser.lazy[r.now().line]?n(e):t(e)}}function iw(e,t,n){return r;function r(r){return e.enter(`lineEnding`),e.consume(r),e.exit(`lineEnding`),e.attempt(oC,t,n)}}var aw={name:`htmlText`,tokenize:ow};function ow(e,t,n){let r=this,i,a,o;return s;function s(t){return e.enter(`htmlText`),e.enter(`htmlTextData`),e.consume(t),c}function c(t){return t===33?(e.consume(t),l):t===47?(e.consume(t),x):t===63?(e.consume(t),y):MS(t)?(e.consume(t),w):n(t)}function l(t){return t===45?(e.consume(t),u):t===91?(e.consume(t),a=0,m):MS(t)?(e.consume(t),v):n(t)}function u(t){return t===45?(e.consume(t),p):n(t)}function d(t){return t===null?n(t):t===45?(e.consume(t),f):$(t)?(o=d,M(t)):(e.consume(t),d)}function f(t){return t===45?(e.consume(t),p):d(t)}function p(e){return e===62?j(e):e===45?f(e):d(e)}function m(t){return t===`CDATA[`.charCodeAt(a++)?(e.consume(t),a===6?h:m):n(t)}function h(t){return t===null?n(t):t===93?(e.consume(t),g):$(t)?(o=h,M(t)):(e.consume(t),h)}function g(t){return t===93?(e.consume(t),_):h(t)}function _(t){return t===62?j(t):t===93?(e.consume(t),_):h(t)}function v(t){return t===null||t===62?j(t):$(t)?(o=v,M(t)):(e.consume(t),v)}function y(t){return t===null?n(t):t===63?(e.consume(t),b):$(t)?(o=y,M(t)):(e.consume(t),y)}function b(e){return e===62?j(e):y(e)}function x(t){return MS(t)?(e.consume(t),S):n(t)}function S(t){return t===45||NS(t)?(e.consume(t),S):C(t)}function C(t){return $(t)?(o=C,M(t)):BS(t)?(e.consume(t),C):j(t)}function w(t){return t===45||NS(t)?(e.consume(t),w):t===47||t===62||zS(t)?T(t):n(t)}function T(t){return t===47?(e.consume(t),j):t===58||t===95||MS(t)?(e.consume(t),E):$(t)?(o=T,M(t)):BS(t)?(e.consume(t),T):j(t)}function E(t){return t===45||t===46||t===58||t===95||NS(t)?(e.consume(t),E):D(t)}function D(t){return t===61?(e.consume(t),O):$(t)?(o=D,M(t)):BS(t)?(e.consume(t),D):T(t)}function O(t){return t===null||t===60||t===61||t===62||t===96?n(t):t===34||t===39?(e.consume(t),i=t,ee):$(t)?(o=O,M(t)):BS(t)?(e.consume(t),O):(e.consume(t),k)}function ee(t){return t===i?(e.consume(t),i=void 0,A):t===null?n(t):$(t)?(o=ee,M(t)):(e.consume(t),ee)}function k(t){return t===null||t===34||t===39||t===60||t===61||t===96?n(t):t===47||t===62||zS(t)?T(t):(e.consume(t),k)}function A(e){return e===47||e===62||zS(e)?T(e):n(e)}function j(r){return r===62?(e.consume(r),e.exit(`htmlTextData`),e.exit(`htmlText`),t):n(r)}function M(t){return e.exit(`htmlTextData`),e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),N}function N(t){return BS(t)?GS(e,P,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):P(t)}function P(t){return e.enter(`htmlTextData`),o(t)}}var sw={name:`labelEnd`,resolveAll:dw,resolveTo:fw,tokenize:pw},cw={tokenize:mw},lw={tokenize:hw},uw={tokenize:gw};function dw(e){let t=-1,n=[];for(;++t=3&&(a===null||$(a))?(e.exit(`thematicBreak`),t(a)):n(a)}function c(t){return t===i?(e.consume(t),r++,c):(e.exit(`thematicBreakSequence`),BS(t)?GS(e,s,`whitespace`)(t):s(t))}}var Tw={continuation:{tokenize:kw},exit:jw,name:`list`,tokenize:Ow},Ew={partial:!0,tokenize:Mw},Dw={partial:!0,tokenize:Aw};function Ow(e,t,n){let r=this,i=r.events[r.events.length-1],a=i&&i[1].type===`linePrefix`?i[2].sliceSerialize(i[1],!0).length:0,o=0;return s;function s(t){let i=r.containerState.type||(t===42||t===43||t===45?`listUnordered`:`listOrdered`);if(i===`listUnordered`?!r.containerState.marker||t===r.containerState.marker:IS(t)){if(r.containerState.type||(r.containerState.type=i,e.enter(i,{_container:!0})),i===`listUnordered`)return e.enter(`listItemPrefix`),t===42||t===45?e.check(Cw,n,l)(t):l(t);if(!r.interrupt||t===49)return e.enter(`listItemPrefix`),e.enter(`listItemValue`),c(t)}return n(t)}function c(t){return IS(t)&&++o<10?(e.consume(t),c):(!r.interrupt||o<2)&&(r.containerState.marker?t===r.containerState.marker:t===41||t===46)?(e.exit(`listItemValue`),l(t)):n(t)}function l(t){return e.enter(`listItemMarker`),e.consume(t),e.exit(`listItemMarker`),r.containerState.marker=r.containerState.marker||t,e.check(oC,r.interrupt?n:u,e.attempt(Ew,f,d))}function u(e){return r.containerState.initialBlankLine=!0,a++,f(e)}function d(t){return BS(t)?(e.enter(`listItemPrefixWhitespace`),e.consume(t),e.exit(`listItemPrefixWhitespace`),f):n(t)}function f(n){return r.containerState.size=a+r.sliceSerialize(e.exit(`listItemPrefix`),!0).length,t(n)}}function kw(e,t,n){let r=this;return r.containerState._closeFlow=void 0,e.check(oC,i,a);function i(n){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,GS(e,t,`listItemIndent`,r.containerState.size+1)(n)}function a(n){return r.containerState.furtherBlankLines||!BS(n)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,o(n)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(Dw,t,o)(n))}function o(i){return r.containerState._closeFlow=!0,r.interrupt=void 0,GS(e,e.attempt(Tw,t,n),`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(i)}}function Aw(e,t,n){let r=this;return GS(e,i,`listItemIndent`,r.containerState.size+1);function i(e){let i=r.events[r.events.length-1];return i&&i[1].type===`listItemIndent`&&i[2].sliceSerialize(i[1],!0).length===r.containerState.size?t(e):n(e)}}function jw(e){e.exit(this.containerState.type)}function Mw(e,t,n){let r=this;return GS(e,i,`listItemPrefixWhitespace`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:5);function i(e){let i=r.events[r.events.length-1];return!BS(e)&&i&&i[1].type===`listItemPrefixWhitespace`?t(e):n(e)}}var Nw={name:`setextUnderline`,resolveTo:Pw,tokenize:Fw};function Pw(e,t){let n=e.length,r,i,a;for(;n--;)if(e[n][0]===`enter`){if(e[n][1].type===`content`){r=n;break}e[n][1].type===`paragraph`&&(i=n)}else e[n][1].type===`content`&&e.splice(n,1),!a&&e[n][1].type===`definition`&&(a=n);let o={type:`setextHeading`,start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[i][1].type=`setextHeadingText`,a?(e.splice(i,0,[`enter`,o,t]),e.splice(a+1,0,[`exit`,e[r][1],t]),e[r][1].end={...e[a][1].end}):e[r][1]=o,e.push([`exit`,o,t]),e}function Fw(e,t,n){let r=this,i;return a;function a(t){let a=r.events.length,s;for(;a--;)if(r.events[a][1].type!==`lineEnding`&&r.events[a][1].type!==`linePrefix`&&r.events[a][1].type!==`content`){s=r.events[a][1].type===`paragraph`;break}return!r.parser.lazy[r.now().line]&&(r.interrupt||s)?(e.enter(`setextHeadingLine`),i=t,o(t)):n(t)}function o(t){return e.enter(`setextHeadingLineSequence`),s(t)}function s(t){return t===i?(e.consume(t),s):(e.exit(`setextHeadingLineSequence`),BS(t)?GS(e,c,`lineSuffix`)(t):c(t))}function c(r){return r===null||$(r)?(e.exit(`setextHeadingLine`),t(r)):n(r)}}var Iw={tokenize:Lw};function Lw(e){let t=this,n=e.attempt(oC,r,e.attempt(this.parser.constructs.flowInitial,i,GS(e,e.attempt(this.parser.constructs.flow,i,e.attempt(MC,i)),`linePrefix`)));return n;function r(r){if(r===null){e.consume(r);return}return e.enter(`lineEndingBlank`),e.consume(r),e.exit(`lineEndingBlank`),t.currentConstruct=void 0,n}function i(r){if(r===null){e.consume(r);return}return e.enter(`lineEnding`),e.consume(r),e.exit(`lineEnding`),t.currentConstruct=void 0,n}}var Rw={resolveAll:Hw()},zw=Vw(`string`),Bw=Vw(`text`);function Vw(e){return{resolveAll:Hw(e===`text`?Uw:void 0),tokenize:t};function t(t){let n=this,r=this.parser.constructs[e],i=t.attempt(r,a,o);return a;function a(e){return c(e)?i(e):o(e)}function o(e){if(e===null){t.consume(e);return}return t.enter(`data`),t.consume(e),s}function s(e){return c(e)?(t.exit(`data`),i(e)):(t.consume(e),s)}function c(e){if(e===null)return!0;let t=r[e],i=-1;if(t)for(;++iQw,contentInitial:()=>Kw,disable:()=>$w,document:()=>Gw,flow:()=>Jw,flowInitial:()=>qw,insideSpan:()=>Zw,string:()=>Yw,text:()=>Xw}),Gw={42:Tw,43:Tw,45:Tw,48:Tw,49:Tw,50:Tw,51:Tw,52:Tw,53:Tw,54:Tw,55:Tw,56:Tw,57:Tw,62:cC},Kw={91:VC},qw={[-2]:bC,[-1]:bC,32:bC},Jw={35:qC,42:Cw,45:[Nw,Cw],60:QC,61:Nw,95:Cw,96:_C,126:_C},Yw={38:mC,92:fC},Xw={[-5]:xw,[-4]:xw,[-3]:xw,33:_w,38:mC,42:eC,60:[iC,aw],91:yw,92:[GC,fC],93:sw,95:eC,96:wC},Zw={null:[eC,Rw]},Qw={null:[42,95]},$w={null:[]};function eT(e,t,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0},i={},a=[],o=[],s=[],c={attempt:C(x),check:C(S),consume:v,enter:y,exit:b,interrupt:C(S,{interrupt:!0})},l={code:null,containerState:{},defineSkip:h,events:[],now:m,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:d},u=t.tokenize.call(l,c);return t.resolveAll&&a.push(t),l;function d(e){return o=TS(o,e),g(),o[o.length-1]===null?(w(t,0),l.events=$S(a,l.events,l),l.events):[]}function f(e,t){return nT(p(e),t)}function p(e){return tT(o,e)}function m(){let{_bufferIndex:e,_index:t,line:n,column:i,offset:a}=r;return{_bufferIndex:e,_index:t,line:n,column:i,offset:a}}function h(e){i[e.line]=e.column,E()}function g(){let e;for(;r._index-1){let e=o[0];typeof e==`string`?o[0]=e.slice(r):o.shift()}a>0&&o.push(e[i].slice(0,a))}return o}function nT(e,t){let n=-1,r=[],i;for(;++n0){let e=a.tokenStack[a.tokenStack.length-1];(e[1]||gT).call(a,void 0,e[0])}for(r.position={start:pT(e.length>0?e[0][1].start:{line:1,column:1,offset:0}),end:pT(e.length>0?e[e.length-2][1].end:{line:1,column:1,offset:0})},d=-1;++d0&&(r.className=[`language-`+i[0]]);let a={type:`element`,tagName:`code`,properties:r,children:[{type:`text`,value:n}]};return t.meta&&(a.data={meta:t.meta}),e.patch(t,a),a=e.applyData(t,a),a={type:`element`,tagName:`pre`,properties:{},children:[a]},e.patch(t,a),a}function xT(e,t){let n={type:`element`,tagName:`del`,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function ST(e,t){let n={type:`element`,tagName:`em`,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function CT(e,t){let n=typeof e.options.clobberPrefix==`string`?e.options.clobberPrefix:`user-content-`,r=String(t.identifier).toUpperCase(),i=WS(r.toLowerCase()),a=e.footnoteOrder.indexOf(r),o,s=e.footnoteCounts.get(r);s===void 0?(s=0,e.footnoteOrder.push(r),o=e.footnoteOrder.length):o=a+1,s+=1,e.footnoteCounts.set(r,s);let c={type:`element`,tagName:`a`,properties:{href:`#`+n+`fn-`+i,id:n+`fnref-`+i+(s>1?`-`+s:``),dataFootnoteRef:!0,ariaDescribedBy:[`footnote-label`]},children:[{type:`text`,value:String(o)}]};e.patch(t,c);let l={type:`element`,tagName:`sup`,properties:{},children:[c]};return e.patch(t,l),e.applyData(t,l)}function wT(e,t){let n={type:`element`,tagName:`h`+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function TT(e,t){if(e.options.allowDangerousHtml){let n={type:`raw`,value:t.value};return e.patch(t,n),e.applyData(t,n)}}function ET(e,t){let n=t.referenceType,r=`]`;if(n===`collapsed`?r+=`[]`:n===`full`&&(r+=`[`+(t.label||t.identifier)+`]`),t.type===`imageReference`)return[{type:`text`,value:`![`+t.alt+r}];let i=e.all(t),a=i[0];a&&a.type===`text`?a.value=`[`+a.value:i.unshift({type:`text`,value:`[`});let o=i[i.length-1];return o&&o.type===`text`?o.value+=r:i.push({type:`text`,value:r}),i}function DT(e,t){let n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return ET(e,t);let i={src:WS(r.url||``),alt:t.alt};r.title!==null&&r.title!==void 0&&(i.title=r.title);let a={type:`element`,tagName:`img`,properties:i,children:[]};return e.patch(t,a),e.applyData(t,a)}function OT(e,t){let n={src:WS(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);let r={type:`element`,tagName:`img`,properties:n,children:[]};return e.patch(t,r),e.applyData(t,r)}function kT(e,t){let n={type:`text`,value:t.value.replace(/\r?\n|\r/g,` `)};e.patch(t,n);let r={type:`element`,tagName:`code`,properties:{},children:[n]};return e.patch(t,r),e.applyData(t,r)}function AT(e,t){let n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return ET(e,t);let i={href:WS(r.url||``)};r.title!==null&&r.title!==void 0&&(i.title=r.title);let a={type:`element`,tagName:`a`,properties:i,children:e.all(t)};return e.patch(t,a),e.applyData(t,a)}function jT(e,t){let n={href:WS(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);let r={type:`element`,tagName:`a`,properties:n,children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function MT(e,t,n){let r=e.all(t),i=n?NT(n):PT(t),a={},o=[];if(typeof t.checked==`boolean`){let e=r[0],n;e&&e.type===`element`&&e.tagName===`p`?n=e:(n={type:`element`,tagName:`p`,properties:{},children:[]},r.unshift(n)),n.children.length>0&&n.children.unshift({type:`text`,value:` `}),n.children.unshift({type:`element`,tagName:`input`,properties:{type:`checkbox`,checked:t.checked,disabled:!0},children:[]}),a.className=[`task-list-item`]}let s=-1;for(;++s1}function FT(e,t){let n={},r=e.all(t),i=-1;for(typeof t.start==`number`&&t.start!==1&&(n.start=t.start);++i0){let r={type:`element`,tagName:`tbody`,properties:{},children:e.wrap(n,!0)},a=Nx(t.children[1]),o=Mx(t.children[t.children.length-1]);a&&o&&(r.position={start:a,end:o}),i.push(r)}let a={type:`element`,tagName:`table`,properties:{},children:e.wrap(i,!0)};return e.patch(t,a),e.applyData(t,a)}function BT(e,t,n){let r=n?n.children:void 0,i=(r?r.indexOf(t):1)===0?`th`:`td`,a=n&&n.type===`table`?n.align:void 0,o=a?a.length:t.children.length,s=-1,c=[];for(;++s0,!0),r[0]),i=r.index+r[0].length,r=n.exec(t);return a.push(GT(t.slice(i),i>0,!1)),a.join(``)}function GT(e,t,n){let r=0,i=e.length;if(t){let t=e.codePointAt(r);for(;t===HT||t===UT;)r++,t=e.codePointAt(r)}if(n){let t=e.codePointAt(i-1);for(;t===HT||t===UT;)i--,t=e.codePointAt(i-1)}return i>r?e.slice(r,i):``}function KT(e,t){let n={type:`text`,value:WT(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function qT(e,t){let n={type:`element`,tagName:`hr`,properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}var JT={blockquote:vT,break:yT,code:bT,delete:xT,emphasis:ST,footnoteReference:CT,heading:wT,html:TT,imageReference:DT,image:OT,inlineCode:kT,linkReference:AT,link:jT,listItem:MT,list:FT,paragraph:IT,root:LT,strong:RT,table:zT,tableCell:VT,tableRow:BT,text:KT,thematicBreak:qT,toml:YT,yaml:YT,definition:YT,footnoteDefinition:YT};function YT(){}var{defineProperty:XT}=Object,ZT=typeof self==`object`?self:globalThis,QT=(e,t)=>{switch(e){case`Function`:case`SharedWorker`:case`Worker`:case`eval`:case`setInterval`:case`setTimeout`:throw TypeError(`unable to deserialize `+e)}return new ZT[e](t)},$T=(e,t)=>{let n=(t,n)=>(e.set(n,t),t),r=i=>{if(e.has(i))return e.get(i);let[a,o]=t[i];switch(a){case 0:case-1:return n(o,i);case 1:{let e=n([],i);for(let t of o)e.push(r(t));return e}case 2:{let e=n({},i);for(let[t,n]of o){let i=r(t),a=r(n);i===`__proto__`?XT(e,i,{value:a,configurable:!0,enumerable:!0,writable:!0}):e[i]=a}return e}case 3:return n(new Date(o),i);case 4:{let{source:e,flags:t}=o;return n(new RegExp(e,t),i)}case 5:{let e=n(new Map,i);for(let[t,n]of o)e.set(r(t),r(n));return e}case 6:{let e=n(new Set,i);for(let t of o)e.add(r(t));return e}case 7:{let{name:e,message:t}=o;return n(typeof ZT[e]==`function`?QT(e,t):Error(t),i)}case 8:return n(BigInt(o),i);case`BigInt`:return n(Object(BigInt(o)),i);case`ArrayBuffer`:return n(new Uint8Array(o).buffer,o);case`DataView`:{let{buffer:e}=new Uint8Array(o);return n(new DataView(e),o)}case`-0`:return-0}return n(QT(a,o),i)};return r},eE=e=>$T(new Map,e)(0),tE=``,{toString:nE}={},{keys:rE,is:iE}=Object,aE=e=>{let t=typeof e;if(t!==`object`||!e)return[0,t];let n=nE.call(e).slice(8,-1);switch(n){case`Array`:return[1,tE];case`Object`:return[2,tE];case`Date`:return[3,tE];case`RegExp`:return[4,tE];case`Map`:return[5,tE];case`Set`:return[6,tE];case`DataView`:return[1,n]}return n.includes(`Array`)?[1,n]:e instanceof Error?[7,e.name||`Error`]:[2,n]},oE=([e,t])=>e===0&&(t===`function`||t===`symbol`),sE=(e,t,n,r)=>{let i=(e,t)=>{let i=r.push(e)-1;return n.set(t,i),i},a=o=>{if(n.has(o))return n.get(o);let[s,c]=aE(o);switch(s){case 0:{let t=o;switch(c){case`bigint`:s=8,t=o.toString();break;case`number`:if(!o&&iE(o,-0))return r.push([`-0`])-1;break;case`function`:case`symbol`:if(e)throw TypeError(`unable to serialize `+c);t=null;break;case`undefined`:return i([-1],o)}return i([s,t],o)}case 1:{if(c){let e=o;return c===`DataView`?e=new Uint8Array(o.buffer):c===`ArrayBuffer`&&(e=new Uint8Array(o)),i([c,[...e]],o)}let e=[],t=i([s,e],o);for(let t of o)e.push(a(t));return t}case 2:{if(c)switch(c){case`BigInt`:return i([c,o.toString()],o);case`Boolean`:case`Number`:case`String`:return i([c,o.valueOf()],o)}if(t&&`toJSON`in o)return a(o.toJSON());let n=[],r=i([s,n],o);for(let t of rE(o))(e||!oE(aE(o[t])))&&n.push([a(t),a(o[t])]);return r}case 3:return i([s,isNaN(o.getTime())?tE:o.toISOString()],o);case 4:{let{source:e,flags:t}=o;return i([s,{source:e,flags:t}],o)}case 5:{let t=[],n=i([s,t],o);for(let[n,r]of o)(e||!(oE(aE(n))||oE(aE(r))))&&t.push([a(n),a(r)]);return n}case 6:{let t=[],n=i([s,t],o);for(let n of o)(e||!oE(aE(n)))&&t.push(a(n));return n}}let{message:l}=o;return i([s,{name:c,message:l}],o)};return a},cE=(e,{json:t,lossy:n}={})=>{let r=[];return sE(!(t||n),!!t,new Map,r)(e),r},lE=typeof structuredClone==`function`?(e,t)=>t&&(`json`in t||`lossy`in t)?eE(cE(e,t)):structuredClone(e):(e,t)=>eE(cE(e,t));function uE(e,t){let n=[{type:`text`,value:`↩`}];return t>1&&n.push({type:`element`,tagName:`sup`,properties:{},children:[{type:`text`,value:String(t)}]}),n}function dE(e,t){return`Back to reference `+(e+1)+(t>1?`-`+t:``)}function fE(e){let t=typeof e.options.clobberPrefix==`string`?e.options.clobberPrefix:`user-content-`,n=e.options.footnoteBackContent||uE,r=e.options.footnoteBackLabel||dE,i=e.options.footnoteLabel||`Footnotes`,a=e.options.footnoteLabelTagName||`h2`,o=e.options.footnoteLabelProperties||{className:[`sr-only`]},s=[],c=-1;for(;++c0&&d.push({type:`text`,value:` `});let e=typeof n==`string`?n:n(c,u);typeof e==`string`&&(e={type:`text`,value:e}),d.push({type:`element`,tagName:`a`,properties:{href:`#`+t+`fnref-`+l+(u>1?`-`+u:``),dataFootnoteBackref:``,ariaLabel:typeof r==`string`?r:r(c,u),className:[`data-footnote-backref`]},children:Array.isArray(e)?e:[e]})}let p=a[a.length-1];if(p&&p.type===`element`&&p.tagName===`p`){let e=p.children[p.children.length-1];e&&e.type===`text`?e.value+=` `:p.children.push({type:`text`,value:` `}),p.children.push(...d)}else a.push(...d);let m={type:`element`,tagName:`li`,properties:{id:t+`fn-`+l},children:e.wrap(a,!0)};e.patch(i,m),s.push(m)}if(s.length!==0)return{type:`element`,tagName:`section`,properties:{dataFootnotes:!0,className:[`footnotes`]},children:[{type:`element`,tagName:a,properties:{...lE(o),id:`footnote-label`},children:[{type:`text`,value:i}]},{type:`text`,value:` +`},{type:`element`,tagName:`ol`,properties:{},children:e.wrap(s,!0)},{type:`text`,value:` +`}]}}var pE=(function(e){if(e==null)return vE;if(typeof e==`function`)return _E(e);if(typeof e==`object`)return Array.isArray(e)?mE(e):hE(e);if(typeof e==`string`)return gE(e);throw Error(`Expected function, string, or object as test`)});function mE(e){let t=[],n=-1;for(;++n`:``))+`)`})}return u;function u(){let l=xE,u,d,f;if((!t||a(e,i,c[c.length-1]||void 0))&&(l=CE(n(e,c)),l[0]===!1))return l;if(`children`in e&&e.children){let t=e;if(t.children&&l[0]!==`skip`)for(d=(r?t.children.length:-1)+o,f=c.concat(t);d>-1&&d0&&n.push({type:`text`,value:` +`}),n}function ME(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function NE(e,t){let n=DE(e,t),r=n.one(e,void 0),i=fE(n),a=Array.isArray(r)?{type:`root`,children:r}:r||{type:`root`,children:[]};return i&&(`children`in a,a.children.push({type:`text`,value:` +`},i)),a}function PE(e,t){return e&&`run`in e?async function(n,r){let i=NE(n,{file:r,...t});await e.run(i,r)}:function(n,r){return NE(n,{file:r,...e||t})}}function FE(e){if(e)throw e}var IE=o(((e,t)=>{var n=Object.prototype.hasOwnProperty,r=Object.prototype.toString,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=function(e){return typeof Array.isArray==`function`?Array.isArray(e):r.call(e)===`[object Array]`},s=function(e){if(!e||r.call(e)!==`[object Object]`)return!1;var t=n.call(e,`constructor`),i=e.constructor&&e.constructor.prototype&&n.call(e.constructor.prototype,`isPrototypeOf`);if(e.constructor&&!t&&!i)return!1;for(var a in e);return a===void 0||n.call(e,a)},c=function(e,t){i&&t.name===`__proto__`?i(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue},l=function(e,t){if(t===`__proto__`){if(!n.call(e,t))return;if(a)return a(e,t).value}return e[t]};t.exports=function e(){var t,n,r,i,a,u,d=arguments[0],f=1,p=arguments.length,m=!1;for(typeof d==`boolean`&&(m=d,d=arguments[1]||{},f=2),(d==null||typeof d!=`object`&&typeof d!=`function`)&&(d={});ft.length,o;r&&t.push(i);try{o=e.apply(this,t)}catch(e){let t=e;if(r&&n)throw t;return i(t)}r||(o&&o.then&&typeof o.then==`function`?o.then(a,i):o instanceof Error?i(o):a(o))}function i(e,...r){n||(n=!0,t(e,...r))}function a(e){i(null,e)}}var BE={basename:VE,dirname:HE,extname:UE,join:WE,sep:`/`};function VE(e,t){if(t!==void 0&&typeof t!=`string`)throw TypeError(`"ext" argument must be a string`);qE(e);let n=0,r=-1,i=e.length,a;if(t===void 0||t.length===0||t.length>e.length){for(;i--;)if(e.codePointAt(i)===47){if(a){n=i+1;break}}else r<0&&(a=!0,r=i+1);return r<0?``:e.slice(n,r)}if(t===e)return``;let o=-1,s=t.length-1;for(;i--;)if(e.codePointAt(i)===47){if(a){n=i+1;break}}else o<0&&(a=!0,o=i+1),s>-1&&(e.codePointAt(i)===t.codePointAt(s--)?s<0&&(r=i):(s=-1,r=o));return n===r?r=o:r<0&&(r=e.length),e.slice(n,r)}function HE(e){if(qE(e),e.length===0)return`.`;let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||=!0;return t<0?e.codePointAt(0)===47?`/`:`.`:t===1&&e.codePointAt(0)===47?`//`:e.slice(0,t)}function UE(e){qE(e);let t=e.length,n=-1,r=0,i=-1,a=0,o;for(;t--;){let s=e.codePointAt(t);if(s===47){if(o){r=t+1;break}continue}n<0&&(o=!0,n=t+1),s===46?i<0?i=t:a!==1&&(a=1):i>-1&&(a=-1)}return i<0||n<0||a===0||a===1&&i===n-1&&i===r+1?``:e.slice(i,n)}function WE(...e){let t=-1,n;for(;++t0&&e.codePointAt(e.length-1)===47&&(n+=`/`),t?`/`+n:n}function KE(e,t){let n=``,r=0,i=-1,a=0,o=-1,s,c;for(;++o<=e.length;){if(o2){if(c=n.lastIndexOf(`/`),c!==n.length-1){c<0?(n=``,r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf(`/`)),i=o,a=0;continue}}else if(n.length>0){n=``,r=0,i=o,a=0;continue}}t&&(n=n.length>0?n+`/..`:`..`,r=2)}else n.length>0?n+=`/`+e.slice(i+1,o):n=e.slice(i+1,o),r=o-i-1}i=o,a=0}else s===46&&a>-1?a++:a=-1}return n}function qE(e){if(typeof e!=`string`)throw TypeError(`Path must be a string. Received `+JSON.stringify(e))}var JE={cwd:YE};function YE(){return`/`}function XE(e){return!!(typeof e==`object`&&e&&`href`in e&&e.href&&`protocol`in e&&e.protocol&&e.auth===void 0)}function ZE(e){if(typeof e==`string`)e=new URL(e);else if(!XE(e)){let t=TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code=`ERR_INVALID_ARG_TYPE`,t}if(e.protocol!==`file:`){let e=TypeError(`The URL must be of scheme file`);throw e.code=`ERR_INVALID_URL_SCHEME`,e}return QE(e)}function QE(e){if(e.hostname!==``){let e=TypeError(`File URL host must be "localhost" or empty on darwin`);throw e.code=`ERR_INVALID_FILE_URL_HOST`,e}let t=e.pathname,n=-1;for(;++n0){let[r,...a]=t,o=n[i][1];LE(o)&&LE(r)&&(r=(0,oD.default)(!0,o,r)),n[i]=[e,r,...a]}}}}().freeze();function lD(e,t){if(typeof t!=`function`)throw TypeError("Cannot `"+e+"` without `parser`")}function uD(e,t){if(typeof t!=`function`)throw TypeError("Cannot `"+e+"` without `compiler`")}function dD(e,t){if(t)throw Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function fD(e){if(!LE(e)||typeof e.type!=`string`)throw TypeError("Expected node, got `"+e+"`")}function pD(e,t,n){if(!n)throw Error("`"+e+"` finished async. Use `"+t+"` instead")}function mD(e){return hD(e)?e:new eD(e)}function hD(e){return!!(e&&typeof e==`object`&&`message`in e&&`messages`in e)}function gD(e){return typeof e==`string`||_D(e)}function _D(e){return!!(e&&typeof e==`object`&&`byteLength`in e&&`byteOffset`in e)}var vD=[],yD={allowDangerousHtml:!0},bD=/^(https?|ircs?|mailto|xmpp)$/i,xD=[{from:`astPlugins`,id:`remove-buggy-html-in-markdown-parser`},{from:`allowDangerousHtml`,id:`remove-buggy-html-in-markdown-parser`},{from:`allowNode`,id:`replace-allownode-allowedtypes-and-disallowedtypes`,to:`allowElement`},{from:`allowedTypes`,id:`replace-allownode-allowedtypes-and-disallowedtypes`,to:`allowedElements`},{from:`className`,id:`remove-classname`},{from:`disallowedTypes`,id:`replace-allownode-allowedtypes-and-disallowedtypes`,to:`disallowedElements`},{from:`escapeHtml`,id:`remove-buggy-html-in-markdown-parser`},{from:`includeElementIndex`,id:`#remove-includeelementindex`},{from:`includeNodeIndex`,id:`change-includenodeindex-to-includeelementindex`},{from:`linkTarget`,id:`remove-linktarget`},{from:`plugins`,id:`change-plugins-to-remarkplugins`,to:`remarkPlugins`},{from:`rawSourcePos`,id:`#remove-rawsourcepos`},{from:`renderers`,id:`change-renderers-to-components`,to:`components`},{from:`source`,id:`change-source-to-children`,to:`children`},{from:`sourcePos`,id:`#remove-sourcepos`},{from:`transformImageUri`,id:`#add-urltransform`,to:`urlTransform`},{from:`transformLinkUri`,id:`#add-urltransform`,to:`urlTransform`}];function SD(e){let t=CD(e),n=wD(e);return TD(t.runSync(t.parse(n),n),e)}function CD(e){let t=e.rehypePlugins||vD,n=e.remarkPlugins||vD,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...yD}:yD;return cD().use(_T).use(n).use(PE,r).use(t)}function wD(e){let t=e.children||``,n=new eD;return typeof t==`string`?n.value=t:``+t,n}function TD(e,t){let n=t.allowedElements,r=t.allowElement,i=t.components,a=t.disallowedElements,o=t.skipHtml,s=t.unwrapDisallowed,c=t.urlTransform||ED;for(let e of xD)Object.hasOwn(t,e.from)&&``+e.from+(e.to?"use `"+e.to+"` instead":`remove it`)+e.id;return wE(e,l),Jx(e,{Fragment:h.Fragment,components:i,ignoreInvalidStyle:!0,jsx:h.jsx,jsxs:h.jsxs,passKeys:!0,passNode:!0});function l(e,t,i){if(e.type===`raw`&&i&&typeof t==`number`)return o?i.children.splice(t,1):i.children[t]={type:`text`,value:e.value},t;if(e.type===`element`){let t;for(t in gS)if(Object.hasOwn(gS,t)&&Object.hasOwn(e.properties,t)){let n=e.properties[t],r=gS[t];(r===null||r.includes(e.tagName))&&(e.properties[t]=c(String(n||``),t,e))}}if(e.type===`element`){let o=n?!n.includes(e.tagName):a?a.includes(e.tagName):!1;if(!o&&r&&typeof t==`number`&&(o=!r(e,t,i)),o&&i&&typeof t==`number`)return s&&e.children?i.children.splice(t,1,...e.children):i.children.splice(t,1),t}}}function ED(e){let t=e.indexOf(`:`),n=e.indexOf(`?`),r=e.indexOf(`#`),i=e.indexOf(`/`);return t===-1||i!==-1&&t>i||n!==-1&&t>n||r!==-1&&t>r||bD.test(e.slice(0,t))?e:``}function DD(e,t){let n=String(e);if(typeof t!=`string`)throw TypeError(`Expected character`);let r=0,i=n.indexOf(t);for(;i!==-1;)r++,i=n.indexOf(t,i+t.length);return r}function OD(e){if(typeof e!=`string`)throw TypeError(`Expected a string`);return e.replace(/[|\\{}()[\]^$+*?.]/g,`\\$&`).replace(/-/g,`\\x2d`)}function kD(e,t,n){let r=pE((n||{}).ignore||[]),i=AD(t),a=-1;for(;++a0?{type:`text`,value:a}:void 0),a===!1?r.lastIndex=n+1:(s!==n&&u.push({type:`text`,value:e.value.slice(s,n)}),Array.isArray(a)?u.push(...a):a&&u.push(a),s=n+d[0].length,l=!0),!r.global)break;d=r.exec(e.value)}return l?(s?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(`)`),i=DD(e,`(`),a=DD(e,`)`);for(;r!==-1&&i>a;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(`)`),a++;return[e,n]}function JD(e,t){let n=e.input.charCodeAt(e.index-1);return(e.index===0||HS(n)||VS(n))&&(!t||n!==47)}iO.peek=rO;function YD(){this.buffer()}function XD(e){this.enter({type:`footnoteReference`,identifier:``,label:``},e)}function ZD(){this.buffer()}function QD(e){this.enter({type:`footnoteDefinition`,identifier:``,label:``,children:[]},e)}function $D(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=jS(this.sliceSerialize(e)).toLowerCase(),n.label=t}function eO(e){this.exit(e)}function tO(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=jS(this.sliceSerialize(e)).toLowerCase(),n.label=t}function nO(e){this.exit(e)}function rO(){return`[`}function iO(e,t,n,r){let i=n.createTracker(r),a=i.move(`[^`),o=n.enter(`footnoteReference`),s=n.enter(`reference`);return a+=i.move(n.safe(n.associationId(e),{after:`]`,before:a})),s(),o(),a+=i.move(`]`),a}function aO(){return{enter:{gfmFootnoteCallString:YD,gfmFootnoteCall:XD,gfmFootnoteDefinitionLabelString:ZD,gfmFootnoteDefinition:QD},exit:{gfmFootnoteCallString:$D,gfmFootnoteCall:eO,gfmFootnoteDefinitionLabelString:tO,gfmFootnoteDefinition:nO}}}function oO(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:iO},unsafe:[{character:`[`,inConstruct:[`label`,`phrasing`,`reference`]}]};function n(e,n,r,i){let a=r.createTracker(i),o=a.move(`[^`),s=r.enter(`footnoteDefinition`),c=r.enter(`label`);return o+=a.move(r.safe(r.associationId(e),{before:o,after:`]`})),c(),o+=a.move(`]:`),e.children&&e.children.length>0&&(a.shift(4),o+=a.move((t?` +`:` `)+r.indentLines(r.containerFlow(e,a.current()),t?cO:sO))),s(),o}}function sO(e,t,n){return t===0?e:cO(e,t,n)}function cO(e,t,n){return(n?``:` `)+e}var lO=[`autolink`,`destinationLiteral`,`destinationRaw`,`reference`,`titleQuote`,`titleApostrophe`];mO.peek=hO;function uO(){return{canContainEols:[`delete`],enter:{strikethrough:fO},exit:{strikethrough:pO}}}function dO(){return{unsafe:[{character:`~`,inConstruct:`phrasing`,notInConstruct:lO}],handlers:{delete:mO}}}function fO(e){this.enter({type:`delete`,children:[]},e)}function pO(e){this.exit(e)}function mO(e,t,n,r){let i=n.createTracker(r),a=n.enter(`strikethrough`),o=i.move(`~~`);return o+=n.containerPhrasing(e,{...i.current(),before:o,after:`~`}),o+=i.move(`~~`),a(),o}function hO(){return`~`}function gO(e){return e.length}function _O(e,t){let n=t||{},r=(n.align||[]).concat(),i=n.stringLength||gO,a=[],o=[],s=[],c=[],l=0,u=-1;for(;++ul&&(l=e[u].length);++ac[a])&&(c[a]=e)}t.push(o)}o[u]=t,s[u]=r}let d=-1;if(typeof r==`object`&&`length`in r)for(;++dc[d]&&(c[d]=i),p[d]=i),f[d]=o}o.splice(1,0,f),s.splice(1,0,p),u=-1;let m=[];for(;++u `),a.shift(2);let o=n.indentLines(n.containerFlow(e,a.current()),xO);return i(),o}function xO(e,t,n){return`>`+(n?``:` `)+e}function SO(e,t){return CO(e,t.inConstruct,!0)&&!CO(e,t.notInConstruct,!1)}function CO(e,t,n){if(typeof t==`string`&&(t=[t]),!t||t.length===0)return n;let r=-1;for(;++ro&&(o=a):a=1,i=r+t.length,r=n.indexOf(t,i);return o}function EO(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function DO(e){let t=e.options.fence||"`";if(t!=="`"&&t!==`~`)throw Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function OO(e,t,n,r){let i=DO(n),a=e.value||``,o=i==="`"?`GraveAccent`:`Tilde`;if(EO(e,n)){let e=n.enter(`codeIndented`),t=n.indentLines(a,kO);return e(),t}let s=n.createTracker(r),c=i.repeat(Math.max(TO(a,i)+1,3)),l=n.enter(`codeFenced`),u=s.move(c);if(e.lang){let t=n.enter(`codeFencedLang${o}`);u+=s.move(n.safe(e.lang,{before:u,after:` `,encode:["`"],...s.current()})),t()}if(e.lang&&e.meta){let t=n.enter(`codeFencedMeta${o}`);u+=s.move(` `),u+=s.move(n.safe(e.meta,{before:u,after:` +`,encode:["`"],...s.current()})),t()}return u+=s.move(` +`),a&&(u+=s.move(a+` +`)),u+=s.move(c),l(),u}function kO(e,t,n){return(n?``:` `)+e}function AO(e){let t=e.options.quote||`"`;if(t!==`"`&&t!==`'`)throw Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function jO(e,t,n,r){let i=AO(n),a=i===`"`?`Quote`:`Apostrophe`,o=n.enter(`definition`),s=n.enter(`label`),c=n.createTracker(r),l=c.move(`[`);return l+=c.move(n.safe(n.associationId(e),{before:l,after:`]`,...c.current()})),l+=c.move(`]: `),s(),!e.url||/[\0- \u007F]/.test(e.url)?(s=n.enter(`destinationLiteral`),l+=c.move(`<`),l+=c.move(n.safe(e.url,{before:l,after:`>`,...c.current()})),l+=c.move(`>`)):(s=n.enter(`destinationRaw`),l+=c.move(n.safe(e.url,{before:l,after:e.title?` `:` +`,...c.current()}))),s(),e.title&&(s=n.enter(`title${a}`),l+=c.move(` `+i),l+=c.move(n.safe(e.title,{before:l,after:i,...c.current()})),l+=c.move(i),s()),o(),l}function MO(e){let t=e.options.emphasis||`*`;if(t!==`*`&&t!==`_`)throw Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function NO(e){return`&#x`+e.toString(16).toUpperCase()+`;`}function PO(e,t,n){let r=QS(e),i=QS(t);return r===void 0?i===void 0?n===`_`?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:r===1?i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}FO.peek=IO;function FO(e,t,n,r){let i=MO(n),a=n.enter(`emphasis`),o=n.createTracker(r),s=o.move(i),c=o.move(n.containerPhrasing(e,{after:i,before:s,...o.current()})),l=c.charCodeAt(0),u=PO(r.before.charCodeAt(r.before.length-1),l,i);u.inside&&(c=NO(l)+c.slice(1));let d=c.charCodeAt(c.length-1),f=PO(r.after.charCodeAt(0),d,i);f.inside&&(c=c.slice(0,-1)+NO(d));let p=o.move(i);return a(),n.attentionEncodeSurroundingInfo={after:f.outside,before:u.outside},s+c+p}function IO(e,t,n){return n.options.emphasis||`*`}function LO(e,t){let n=!1;return wE(e,function(e){if(`value`in e&&/\r?\n|\r/.test(e.value)||e.type===`break`)return n=!0,!1}),!!((!e.depth||e.depth<3)&&vS(e)&&(t.options.setext||n))}function RO(e,t,n,r){let i=Math.max(Math.min(6,e.depth||1),1),a=n.createTracker(r);if(LO(e,n)){let t=n.enter(`headingSetext`),r=n.enter(`phrasing`),o=n.containerPhrasing(e,{...a.current(),before:` +`,after:` +`});return r(),t(),o+` +`+(i===1?`=`:`-`).repeat(o.length-(Math.max(o.lastIndexOf(`\r`),o.lastIndexOf(` +`))+1))}let o=`#`.repeat(i),s=n.enter(`headingAtx`),c=n.enter(`phrasing`);a.move(o+` `);let l=n.containerPhrasing(e,{before:`# `,after:` +`,...a.current()});return/^[\t ]/.test(l)&&(l=NO(l.charCodeAt(0))+l.slice(1)),l=l?o+` `+l:o,n.options.closeAtx&&(l+=` `+o),c(),s(),l}zO.peek=BO;function zO(e){return e.value||``}function BO(){return`<`}VO.peek=HO;function VO(e,t,n,r){let i=AO(n),a=i===`"`?`Quote`:`Apostrophe`,o=n.enter(`image`),s=n.enter(`label`),c=n.createTracker(r),l=c.move(`![`);return l+=c.move(n.safe(e.alt,{before:l,after:`]`,...c.current()})),l+=c.move(`](`),s(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(s=n.enter(`destinationLiteral`),l+=c.move(`<`),l+=c.move(n.safe(e.url,{before:l,after:`>`,...c.current()})),l+=c.move(`>`)):(s=n.enter(`destinationRaw`),l+=c.move(n.safe(e.url,{before:l,after:e.title?` `:`)`,...c.current()}))),s(),e.title&&(s=n.enter(`title${a}`),l+=c.move(` `+i),l+=c.move(n.safe(e.title,{before:l,after:i,...c.current()})),l+=c.move(i),s()),l+=c.move(`)`),o(),l}function HO(){return`!`}UO.peek=WO;function UO(e,t,n,r){let i=e.referenceType,a=n.enter(`imageReference`),o=n.enter(`label`),s=n.createTracker(r),c=s.move(`![`),l=n.safe(e.alt,{before:c,after:`]`,...s.current()});c+=s.move(l+`][`),o();let u=n.stack;n.stack=[],o=n.enter(`reference`);let d=n.safe(n.associationId(e),{before:c,after:`]`,...s.current()});return o(),n.stack=u,a(),i===`full`||!l||l!==d?c+=s.move(d+`]`):i===`shortcut`?c=c.slice(0,-1):c+=s.move(`]`),c}function WO(){return`!`}GO.peek=KO;function GO(e,t,n){let r=e.value||``,i="`",a=-1;for(;RegExp("(^|[^`])"+i+"([^`]|$)").test(r);)i+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=` `+r+` `);++a\u007F]/.test(e.url))}JO.peek=YO;function JO(e,t,n,r){let i=AO(n),a=i===`"`?`Quote`:`Apostrophe`,o=n.createTracker(r),s,c;if(qO(e,n)){let t=n.stack;n.stack=[],s=n.enter(`autolink`);let r=o.move(`<`);return r+=o.move(n.containerPhrasing(e,{before:r,after:`>`,...o.current()})),r+=o.move(`>`),s(),n.stack=t,r}s=n.enter(`link`),c=n.enter(`label`);let l=o.move(`[`);return l+=o.move(n.containerPhrasing(e,{before:l,after:`](`,...o.current()})),l+=o.move(`](`),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=n.enter(`destinationLiteral`),l+=o.move(`<`),l+=o.move(n.safe(e.url,{before:l,after:`>`,...o.current()})),l+=o.move(`>`)):(c=n.enter(`destinationRaw`),l+=o.move(n.safe(e.url,{before:l,after:e.title?` `:`)`,...o.current()}))),c(),e.title&&(c=n.enter(`title${a}`),l+=o.move(` `+i),l+=o.move(n.safe(e.title,{before:l,after:i,...o.current()})),l+=o.move(i),c()),l+=o.move(`)`),s(),l}function YO(e,t,n){return qO(e,n)?`<`:`[`}XO.peek=ZO;function XO(e,t,n,r){let i=e.referenceType,a=n.enter(`linkReference`),o=n.enter(`label`),s=n.createTracker(r),c=s.move(`[`),l=n.containerPhrasing(e,{before:c,after:`]`,...s.current()});c+=s.move(l+`][`),o();let u=n.stack;n.stack=[],o=n.enter(`reference`);let d=n.safe(n.associationId(e),{before:c,after:`]`,...s.current()});return o(),n.stack=u,a(),i===`full`||!l||l!==d?c+=s.move(d+`]`):i===`shortcut`?c=c.slice(0,-1):c+=s.move(`]`),c}function ZO(){return`[`}function QO(e){let t=e.options.bullet||`*`;if(t!==`*`&&t!==`+`&&t!==`-`)throw Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function $O(e){let t=QO(e),n=e.options.bulletOther;if(!n)return t===`*`?`-`:`*`;if(n!==`*`&&n!==`+`&&n!==`-`)throw Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function ek(e){let t=e.options.bulletOrdered||`.`;if(t!==`.`&&t!==`)`)throw Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function tk(e){let t=e.options.rule||`*`;if(t!==`*`&&t!==`-`&&t!==`_`)throw Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function nk(e,t,n,r){let i=n.enter(`list`),a=n.bulletCurrent,o=e.ordered?ek(n):QO(n),s=e.ordered?o===`.`?`)`:`.`:$O(n),c=t&&n.bulletLastUsed?o===n.bulletLastUsed:!1;if(!e.ordered){let t=e.children?e.children[0]:void 0;if((o===`*`||o===`-`)&&t&&(!t.children||!t.children[0])&&n.stack[n.stack.length-1]===`list`&&n.stack[n.stack.length-2]===`listItem`&&n.stack[n.stack.length-3]===`list`&&n.stack[n.stack.length-4]===`listItem`&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(c=!0),tk(n)===o&&t){let t=-1;for(;++t-1?t.start:1)+(n.options.incrementListMarker===!1?0:t.children.indexOf(e))+a);let o=a.length+1;(i===`tab`||i===`mixed`&&(t&&t.type===`list`&&t.spread||e.spread))&&(o=Math.ceil(o/4)*4);let s=n.createTracker(r);s.move(a+` `.repeat(o-a.length)),s.shift(o);let c=n.enter(`listItem`),l=n.indentLines(n.containerFlow(e,s.current()),u);return c(),l;function u(e,t,n){return t?(n?``:` `.repeat(o))+e:(n?a:a+` `.repeat(o-a.length))+e}}function ak(e,t,n,r){let i=n.enter(`paragraph`),a=n.enter(`phrasing`),o=n.containerPhrasing(e,r);return a(),i(),o}var ok=pE([`break`,`delete`,`emphasis`,`footnote`,`footnoteReference`,`image`,`imageReference`,`inlineCode`,`inlineMath`,`link`,`linkReference`,`mdxJsxTextElement`,`mdxTextExpression`,`strong`,`text`,`textDirective`]);function sk(e,t,n,r){return(e.children.some(function(e){return ok(e)})?n.containerPhrasing:n.containerFlow).call(n,e,r)}function ck(e){let t=e.options.strong||`*`;if(t!==`*`&&t!==`_`)throw Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}lk.peek=uk;function lk(e,t,n,r){let i=ck(n),a=n.enter(`strong`),o=n.createTracker(r),s=o.move(i+i),c=o.move(n.containerPhrasing(e,{after:i,before:s,...o.current()})),l=c.charCodeAt(0),u=PO(r.before.charCodeAt(r.before.length-1),l,i);u.inside&&(c=NO(l)+c.slice(1));let d=c.charCodeAt(c.length-1),f=PO(r.after.charCodeAt(0),d,i);f.inside&&(c=c.slice(0,-1)+NO(d));let p=o.move(i+i);return a(),n.attentionEncodeSurroundingInfo={after:f.outside,before:u.outside},s+c+p}function uk(e,t,n){return n.options.strong||`*`}function dk(e,t,n,r){return n.safe(e.value,r)}function fk(e){let t=e.options.ruleRepetition||3;if(t<3)throw Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function pk(e,t,n){let r=(tk(n)+(n.options.ruleSpaces?` `:``)).repeat(fk(n));return n.options.ruleSpaces?r.slice(0,-1):r}var mk={blockquote:bO,break:wO,code:OO,definition:jO,emphasis:FO,hardBreak:wO,heading:RO,html:zO,image:VO,imageReference:UO,inlineCode:GO,link:JO,linkReference:XO,list:nk,listItem:ik,paragraph:ak,root:sk,strong:lk,text:dk,thematicBreak:pk};function hk(){return{enter:{table:gk,tableData:bk,tableHeader:bk,tableRow:vk},exit:{codeText:xk,table:_k,tableData:yk,tableHeader:yk,tableRow:yk}}}function gk(e){let t=e._align;this.enter({type:`table`,align:t.map(function(e){return e===`none`?null:e}),children:[]},e),this.data.inTable=!0}function _k(e){this.exit(e),this.data.inTable=void 0}function vk(e){this.enter({type:`tableRow`,children:[]},e)}function yk(e){this.exit(e)}function bk(e){this.enter({type:`tableCell`,children:[]},e)}function xk(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,Sk));let n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function Sk(e,t){return t===`|`?t:e}function Ck(e){let t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,i=t.stringLength,a=n?` `:`|`;return{unsafe:[{character:`\r`,inConstruct:`tableCell`},{character:` +`,inConstruct:`tableCell`},{atBreak:!0,character:`|`,after:`[ :-]`},{character:`|`,inConstruct:`tableCell`},{atBreak:!0,character:`:`,after:`-`},{atBreak:!0,character:`-`,after:`[:|-]`}],handlers:{inlineCode:f,table:o,tableCell:c,tableRow:s}};function o(e,t,n,r){return l(u(e,n,r),e.align)}function s(e,t,n,r){let i=l([d(e,n,r)]);return i.slice(0,i.indexOf(` +`))}function c(e,t,n,r){let i=n.enter(`tableCell`),o=n.enter(`phrasing`),s=n.containerPhrasing(e,{...r,before:a,after:a});return o(),i(),s}function l(e,t){return _O(e,{align:t,alignDelimiters:r,padding:n,stringLength:i})}function u(e,t,n){let r=e.children,i=-1,a=[],o=t.enter(`table`);for(;++i0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}var tA={tokenize:lA,partial:!0};function nA(){return{document:{91:{name:`gfmFootnoteDefinition`,tokenize:oA,continuation:{tokenize:sA},exit:cA}},text:{91:{name:`gfmFootnoteCall`,tokenize:aA},93:{name:`gfmPotentialFootnoteCall`,add:`after`,tokenize:rA,resolveTo:iA}}}}function rA(e,t,n){let r=this,i=r.events.length,a=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),o;for(;i--;){let e=r.events[i][1];if(e.type===`labelImage`){o=e;break}if(e.type===`gfmFootnoteCall`||e.type===`labelLink`||e.type===`label`||e.type===`image`||e.type===`link`)break}return s;function s(i){if(!o||!o._balanced)return n(i);let s=jS(r.sliceSerialize({start:o.end,end:r.now()}));return s.codePointAt(0)!==94||!a.includes(s.slice(1))?n(i):(e.enter(`gfmFootnoteCallLabelMarker`),e.consume(i),e.exit(`gfmFootnoteCallLabelMarker`),t(i))}}function iA(e,t){let n=e.length;for(;n--;)if(e[n][1].type===`labelImage`&&e[n][0]===`enter`){e[n][1];break}e[n+1][1].type=`data`,e[n+3][1].type=`gfmFootnoteCallLabelMarker`;let r={type:`gfmFootnoteCall`,start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:`gfmFootnoteCallMarker`,start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;let a={type:`gfmFootnoteCallString`,start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},o={type:`chunkString`,contentType:`string`,start:Object.assign({},a.start),end:Object.assign({},a.end)},s=[e[n+1],e[n+2],[`enter`,r,t],e[n+3],e[n+4],[`enter`,i,t],[`exit`,i,t],[`enter`,a,t],[`enter`,o,t],[`exit`,o,t],[`exit`,a,t],e[e.length-2],e[e.length-1],[`exit`,r,t]];return e.splice(n,e.length-n+1,...s),e}function aA(e,t,n){let r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),a=0,o;return s;function s(t){return e.enter(`gfmFootnoteCall`),e.enter(`gfmFootnoteCallLabelMarker`),e.consume(t),e.exit(`gfmFootnoteCallLabelMarker`),c}function c(t){return t===94?(e.enter(`gfmFootnoteCallMarker`),e.consume(t),e.exit(`gfmFootnoteCallMarker`),e.enter(`gfmFootnoteCallString`),e.enter(`chunkString`).contentType=`string`,l):n(t)}function l(s){if(a>999||s===93&&!o||s===null||s===91||zS(s))return n(s);if(s===93){e.exit(`chunkString`);let a=e.exit(`gfmFootnoteCallString`);return i.includes(jS(r.sliceSerialize(a)))?(e.enter(`gfmFootnoteCallLabelMarker`),e.consume(s),e.exit(`gfmFootnoteCallLabelMarker`),e.exit(`gfmFootnoteCall`),t):n(s)}return zS(s)||(o=!0),a++,e.consume(s),s===92?u:l}function u(t){return t===91||t===92||t===93?(e.consume(t),a++,l):l(t)}}function oA(e,t,n){let r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),a,o=0,s;return c;function c(t){return e.enter(`gfmFootnoteDefinition`)._container=!0,e.enter(`gfmFootnoteDefinitionLabel`),e.enter(`gfmFootnoteDefinitionLabelMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionLabelMarker`),l}function l(t){return t===94?(e.enter(`gfmFootnoteDefinitionMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionMarker`),e.enter(`gfmFootnoteDefinitionLabelString`),e.enter(`chunkString`).contentType=`string`,u):n(t)}function u(t){if(o>999||t===93&&!s||t===null||t===91||zS(t))return n(t);if(t===93){e.exit(`chunkString`);let n=e.exit(`gfmFootnoteDefinitionLabelString`);return a=jS(r.sliceSerialize(n)),e.enter(`gfmFootnoteDefinitionLabelMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionLabelMarker`),e.exit(`gfmFootnoteDefinitionLabel`),f}return zS(t)||(s=!0),o++,e.consume(t),t===92?d:u}function d(t){return t===91||t===92||t===93?(e.consume(t),o++,u):u(t)}function f(t){return t===58?(e.enter(`definitionMarker`),e.consume(t),e.exit(`definitionMarker`),i.includes(a)||i.push(a),GS(e,p,`gfmFootnoteDefinitionWhitespace`)):n(t)}function p(e){return t(e)}}function sA(e,t,n){return e.check(oC,t,e.attempt(tA,t,n))}function cA(e){e.exit(`gfmFootnoteDefinition`)}function lA(e,t,n){let r=this;return GS(e,i,`gfmFootnoteDefinitionIndent`,5);function i(e){let i=r.events[r.events.length-1];return i&&i[1].type===`gfmFootnoteDefinitionIndent`&&i[2].sliceSerialize(i[1],!0).length===4?t(e):n(e)}}function uA(e){let t=(e||{}).singleTilde,n={name:`strikethrough`,tokenize:i,resolveAll:r};return t??=!0,{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}};function r(e,t){let n=-1;for(;++n1?r(a):(e.consume(a),o++,c);if(o<2&&!t)return r(a);let l=e.exit(`strikethroughSequenceTemporary`),u=QS(a);return l._open=!u||u===2&&!!s,l._close=!s||s===2&&!!u,n(a)}}}var dA=class{constructor(){this.map=[]}add(e,t,n){fA(this,e,t,n)}consume(e){if(this.map.sort(function(e,t){return e[0]-t[0]}),this.map.length===0)return;let t=this.map.length,n=[];for(;t>0;)--t,n.push(e.slice(this.map[t][0]+this.map[t][1]),this.map[t][2]),e.length=this.map[t][0];n.push(e.slice()),e.length=0;let r=n.pop();for(;r;){for(let t of r)e.push(t);r=n.pop()}this.map.length=0}};function fA(e,t,n,r){let i=0;if(n!==0||r.length!==0){for(;i-1;){let e=r.events[t][1].type;if(e===`lineEnding`||e===`linePrefix`)t--;else break}let i=t>-1?r.events[t][1].type:null,a=i===`tableHead`||i===`tableRow`?S:c;return a===S&&r.parser.lazy[r.now().line]?n(e):a(e)}function c(t){return e.enter(`tableHead`),e.enter(`tableRow`),l(t)}function l(e){return e===124?u(e):(o=!0,a+=1,u(e))}function u(t){return t===null?n(t):$(t)?a>1?(a=0,r.interrupt=!0,e.exit(`tableRow`),e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),p):n(t):BS(t)?GS(e,u,`whitespace`)(t):(a+=1,o&&(o=!1,i+=1),t===124?(e.enter(`tableCellDivider`),e.consume(t),e.exit(`tableCellDivider`),o=!0,u):(e.enter(`data`),d(t)))}function d(t){return t===null||t===124||zS(t)?(e.exit(`data`),u(t)):(e.consume(t),t===92?f:d)}function f(t){return t===92||t===124?(e.consume(t),d):d(t)}function p(t){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(t):(e.enter(`tableDelimiterRow`),o=!1,BS(t)?GS(e,m,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):m(t))}function m(t){return t===45||t===58?g(t):t===124?(o=!0,e.enter(`tableCellDivider`),e.consume(t),e.exit(`tableCellDivider`),h):x(t)}function h(t){return BS(t)?GS(e,g,`whitespace`)(t):g(t)}function g(t){return t===58?(a+=1,o=!0,e.enter(`tableDelimiterMarker`),e.consume(t),e.exit(`tableDelimiterMarker`),_):t===45?(a+=1,_(t)):t===null||$(t)?b(t):x(t)}function _(t){return t===45?(e.enter(`tableDelimiterFiller`),v(t)):x(t)}function v(t){return t===45?(e.consume(t),v):t===58?(o=!0,e.exit(`tableDelimiterFiller`),e.enter(`tableDelimiterMarker`),e.consume(t),e.exit(`tableDelimiterMarker`),y):(e.exit(`tableDelimiterFiller`),y(t))}function y(t){return BS(t)?GS(e,b,`whitespace`)(t):b(t)}function b(n){return n===124?m(n):n===null||$(n)?!o||i!==a?x(n):(e.exit(`tableDelimiterRow`),e.exit(`tableHead`),t(n)):x(n)}function x(e){return n(e)}function S(t){return e.enter(`tableRow`),C(t)}function C(n){return n===124?(e.enter(`tableCellDivider`),e.consume(n),e.exit(`tableCellDivider`),C):n===null||$(n)?(e.exit(`tableRow`),t(n)):BS(n)?GS(e,C,`whitespace`)(n):(e.enter(`data`),w(n))}function w(t){return t===null||t===124||zS(t)?(e.exit(`data`),C(t)):(e.consume(t),t===92?T:w)}function T(t){return t===92||t===124?(e.consume(t),w):w(t)}}function gA(e,t){let n=-1,r=!0,i=0,a=[0,0,0,0],o=[0,0,0,0],s=!1,c=0,l,u,d,f=new dA;for(;++nn[2]+1){let t=n[2]+1,r=n[3]-n[2]-1;e.add(t,r,[])}}e.add(n[3]+1,0,[[`exit`,o,t]])}return i!==void 0&&(a.end=Object.assign({},yA(t.events,i)),e.add(i,0,[[`exit`,a,t]]),a=void 0),a}function vA(e,t,n,r,i){let a=[],o=yA(t.events,n);i&&(i.end=Object.assign({},o),a.push([`exit`,i,t])),r.end=Object.assign({},o),a.push([`exit`,r,t]),e.add(n+1,0,a)}function yA(e,t){let n=e[t],r=n[0]===`enter`?`start`:`end`;return n[1][r]}var bA={name:`tasklistCheck`,tokenize:SA};function xA(){return{text:{91:bA}}}function SA(e,t,n){let r=this;return i;function i(t){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(t):(e.enter(`taskListCheck`),e.enter(`taskListCheckMarker`),e.consume(t),e.exit(`taskListCheckMarker`),a)}function a(t){return zS(t)?(e.enter(`taskListCheckValueUnchecked`),e.consume(t),e.exit(`taskListCheckValueUnchecked`),o):t===88||t===120?(e.enter(`taskListCheckValueChecked`),e.consume(t),e.exit(`taskListCheckValueChecked`),o):n(t)}function o(t){return t===93?(e.enter(`taskListCheckMarker`),e.consume(t),e.exit(`taskListCheckMarker`),e.exit(`taskListCheck`),s):n(t)}function s(r){return $(r)?t(r):BS(r)?e.check({tokenize:CA},t,n)(r):n(r)}}function CA(e,t,n){return GS(e,r,`whitespace`);function r(e){return e===null?n(e):t(e)}}function wA(e){return DS([Bk(),nA(),uA(e),mA(),xA()])}var TA={};function EA(e){let t=this,n=e||TA,r=t.data(),i=r.micromarkExtensions||=[],a=r.fromMarkdownExtensions||=[],o=r.toMarkdownExtensions||=[];i.push(wA(n)),a.push(kk()),o.push(Ak(n))}function DA(e,t,n){return e.title.trim()?e.title:e.subagentName?t(`history.subagentTitle`,{name:e.subagentName}):t(`history.untitledIdentity`,{date:vb(e.createdAt||e.updatedAt,n),id:e.id.slice(-8)})}function OA(e){let t=e.nativeSessionId;return typeof t==`string`&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(t)?`codex resume ${t}`:null}function kA({session:e,detail:t,host:n,profile:r,onOpenParent:i,openInformation:a=!1}){let{t:o,i18n:s}=Dn(),[c,l]=(0,m.useState)(``),u=kb(),[d,f]=(0,m.useState)(!1),p=OA(e),g=t?.storage,_=async e=>{try{await u(e),l(o(`common.copied`))}catch{l(o(`history.copyFailed`))}},v=async()=>{if(n?.revealHistoryFile){f(!0);try{let t=await n.revealHistoryFile(gb(r),e.id);l(o(t.revealed?`history.fileRevealed`:`history.revealFailed`))}catch{l(o(`history.revealFailed`))}finally{f(!1)}}};return(0,h.jsxs)(`section`,{"aria-label":o(`history.sessionActions`),className:`mb-4 min-w-0 space-y-3`,children:[(0,h.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,h.jsxs)(X,{disabled:!e.nativeSessionId,onClick:()=>void _(e.nativeSessionId),type:`button`,variant:`secondary`,children:[(0,h.jsx)(Si,{size:14}),o(`history.copyId`)]}),(0,h.jsxs)(X,{disabled:!p,onClick:()=>void _(p),type:`button`,variant:`secondary`,children:[(0,h.jsx)(Si,{size:14}),o(`history.copyResume`)]})]}),e.nativeSessionId?null:(0,h.jsx)(`p`,{className:`text-xs text-[var(--muted)]`,children:o(`history.missingNativeId`)}),p?(0,h.jsx)(`p`,{className:`text-xs text-[var(--muted)]`,children:o(`history.resumeHint`)}):null,(0,h.jsxs)(`details`,{className:`rounded-lg border border-[var(--border)] p-3`,open:a||void 0,children:[(0,h.jsx)(`summary`,{className:`cursor-pointer font-medium focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--accent)]`,children:o(`history.sessionInformation`)}),(0,h.jsxs)(`dl`,{className:`mt-3 grid min-w-0 gap-3 text-sm`,children:[(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:o(`history.nativeId`)}),(0,h.jsx)(`dd`,{className:`select-text break-all font-mono`,children:e.nativeSessionId||o(`history.notRecorded`)})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:o(`history.sessionType`)}),(0,h.jsx)(`dd`,{children:o(e.sessionKind===`subagent`?`history.subtasks`:`history.mainSessions`)})]}),e.parentSessionId?(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:o(`history.parentId`)}),(0,h.jsxs)(`dd`,{className:`flex flex-wrap items-center gap-2`,children:[(0,h.jsx)(`span`,{className:`select-text break-all font-mono`,children:e.parentSessionId}),(0,h.jsx)(X,{onClick:()=>i(e.parentSessionId),type:`button`,variant:`secondary`,children:o(`history.openParent`)})]})]}):null,(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:o(`history.recordedProvider`)}),(0,h.jsx)(`dd`,{children:e.provider})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:o(`history.recordedModel`)}),(0,h.jsx)(`dd`,{children:e.model||o(`history.notRecorded`)})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:o(`history.createdAt`)}),(0,h.jsx)(`dd`,{children:vb(e.createdAt,s.language)})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:o(`history.fileModifiedAt`)}),(0,h.jsx)(`dd`,{children:vb(e.fileModifiedAt,s.language)})]}),(0,h.jsx)(`p`,{className:`text-xs text-[var(--muted)]`,children:o(`history.fileTimeHint`)}),g?(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:o(`history.projectDirectory`)}),(0,h.jsx)(`dd`,{className:`select-text break-all`,children:g.cwd||o(`history.notRecorded`)})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:o(`history.sessionFile`)}),(0,h.jsx)(`dd`,{className:`select-text break-all`,children:g.rolloutPath})]}),(0,h.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,h.jsxs)(X,{onClick:()=>void _(g.rolloutPath),type:`button`,variant:`secondary`,children:[(0,h.jsx)(Si,{size:14}),o(`history.copyPath`)]}),n?.revealHistoryFile?(0,h.jsxs)(X,{disabled:d,onClick:()=>void v(),type:`button`,variant:`secondary`,children:[(0,h.jsx)(Di,{size:14}),o(`history.revealFile`)]}):null]})]}):(0,h.jsx)(`p`,{className:`text-xs text-[var(--muted)]`,children:o(`history.localInfoHint`)})]})]}),(0,h.jsx)(`p`,{"aria-live":`polite`,className:`text-xs text-[var(--muted)]`,role:`status`,children:c})]})}function AA({target:e,close:t,save:n}){let{t:r}=Dn(),[i,a]=(0,m.useState)(!1),[o,s]=(0,m.useState)(e.alias||e.name),[c,l]=(0,m.useState)(!1),u=(0,m.useRef)(null),[d,f]=(0,m.useState)({x:e.x,y:e.y}),p=()=>{e.trigger.isConnected&&e.trigger.focus({preventScroll:!0})},g=()=>{p(),t()};(0,m.useLayoutEffect)(()=>{let t=u.current?.getBoundingClientRect();f({x:Math.max(8,Math.min(e.x,window.innerWidth-(t?.width||256)-8)),y:Math.max(8,Math.min(e.y,window.innerHeight-(t?.height||100)-8))}),u.current?.querySelector(`button`)?.focus({preventScroll:!0})},[e]),(0,m.useEffect)(()=>{if(i)return;let e=e=>{u.current?.contains(e.target)||t()},n=()=>t();return document.addEventListener(`pointerdown`,e,!0),document.addEventListener(`scroll`,e,!0),window.addEventListener(`resize`,n),window.addEventListener(`blur`,n),()=>{document.removeEventListener(`pointerdown`,e,!0),document.removeEventListener(`scroll`,e,!0),window.removeEventListener(`resize`,n),window.removeEventListener(`blur`,n)}},[i,t]);let _=t=>{try{n(e.id,t),g()}catch{l(!0),a(!0)}};if(i)return(0,h.jsx)(fb,{open:!0,onOpenChange:e=>{e||t()},restoreFocus:p,title:r(`history.projectAliasTitle`),description:r(`history.projectAliasHint`),closeLabel:r(`common.close`),children:(0,h.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),_(o.trim())},children:[(0,h.jsx)(ub,{label:r(`history.projectDisplayName`),error:c?r(`history.projectAliasFailed`):void 0,children:(0,h.jsx)(lb,{maxLength:160,value:o,onChange:e=>{s(e.target.value),l(!1)}})}),(0,h.jsxs)(`div`,{className:`mt-5 flex justify-end gap-2`,children:[(0,h.jsx)(X,{type:`button`,variant:`secondary`,onClick:g,children:r(`common.cancel`)}),(0,h.jsx)(X,{type:`submit`,children:r(`common.save`)})]})]})});let v=`min-h-10 w-full rounded-md px-3 text-left text-sm hover:bg-[var(--surface-hover)] focus:bg-[var(--accent-soft)] focus:outline-none disabled:opacity-40`;return(0,dm.createPortal)((0,h.jsxs)(`div`,{ref:u,role:`menu`,"aria-label":r(`history.projectActions`),style:{left:d.x,top:d.y},className:`fixed z-[70] w-64 max-w-[calc(100vw-16px)] overflow-auto rounded-xl border border-[var(--border)] bg-[var(--surface-raised)] p-1.5 text-[var(--text)] shadow-xl`,onContextMenu:e=>e.preventDefault(),onKeyDown:e=>{if(e.key===`Escape`||e.key===`Tab`){e.preventDefault(),g();return}let t=Array.from(u.current?.querySelectorAll(`button:not(:disabled)`)||[]),n=t.indexOf(document.activeElement),r=e.key===`Home`?0:e.key===`End`?t.length-1:e.key===`ArrowDown`?(n+1)%t.length:e.key===`ArrowUp`?(n+t.length-1)%t.length:-1;r>=0&&(e.preventDefault(),t[r]?.focus())},children:[(0,h.jsx)(`button`,{className:v,role:`menuitem`,tabIndex:-1,type:`button`,onClick:()=>a(!0),children:r(`history.projectAliasTitle`)}),(0,h.jsx)(`button`,{className:v,role:`menuitem`,tabIndex:-1,type:`button`,disabled:!e.alias,onClick:()=>_(``),children:r(`history.projectAliasReset`)})]}),document.body)}function jA(e,t){(e.key===`ContextMenu`||e.shiftKey&&e.key===`F10`)&&(e.preventDefault(),t())}function MA(e,t,n,r,i=!1){return ct({queryKey:[`history-rows`,e.scope,i?`children`:`project`,t],initialPageParam:1,initialData:r?{pages:[r],pageParams:[1]}:void 0,queryFn:({signal:n,pageParam:r})=>e.core.listHistory({...e.input,view:`projects`,page:r,...i?{parentId:t}:{projectId:t}},{signal:n}),getNextPageParam:e=>e.hasNextPage?e.page+1:void 0,enabled:n,staleTime:1/0,gcTime:0,retry:!1,refetchOnMount:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1})}function NA(e){return[...new Map((e??[]).flatMap(e=>e.sessions).map(e=>[e.id,e])).values()]}function PA({query:e}){let{t}=Dn();return(0,h.jsxs)(h.Fragment,{children:[e.isError?(0,h.jsxs)(`div`,{className:`px-3 py-2 text-xs text-[var(--danger)]`,role:`alert`,children:[yb(e.error,t),` `,(0,h.jsx)(`button`,{className:`underline`,type:`button`,onClick:()=>void(e.data?e.fetchNextPage():e.refetch()),children:t(`history.retryLoad`)})]}):null,e.isFetching?(0,h.jsx)(`p`,{role:`status`,className:`px-3 py-2 text-xs text-[var(--muted)]`,children:t(`common.loading`)}):e.hasNextPage&&!e.isError?(0,h.jsx)(`button`,{className:`min-h-9 w-full rounded-md px-3 text-left text-xs text-[var(--muted)] hover:bg-[var(--surface-hover)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--focus)]`,type:`button`,onClick:()=>void e.fetchNextPage(),children:t(`history.loadMore`)}):null]})}function FA({session:e,props:t,fallback:n,depth:r=0}){let{t:i,i18n:a}=Dn(),[o,s]=(0,m.useState)(!1),c=(0,m.useRef)(null),l=MA(t,e.id,o,void 0,!0),u=NA(l.data?.pages),d=DA(e,i,a.language),f=(e.childCount??0)>0,p=[d,e.provider,e.model,`${i(`history.fileModifiedAt`)}: ${vb(e.fileModifiedAt||e.updatedAt,a.language)}`,i(`history.contextMenuHint`)].filter(Boolean).join(` +`);return(0,h.jsxs)(`li`,{className:`min-w-0`,children:[(0,h.jsxs)(`div`,{className:`flex min-w-0 items-center`,style:{paddingLeft:`${Math.min(r,6)*12+16}px`},children:[f?(0,h.jsx)(`button`,{ref:c,type:`button`,className:`flex h-8 w-6 shrink-0 items-center justify-center rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--focus)]`,"aria-label":i(`history.toggleSubtasks`,{title:d,count:e.childCount}),"aria-expanded":o,onClick:()=>s(!o),children:o?(0,h.jsx)(yi,{size:12}):(0,h.jsx)(bi,{size:12})}):(0,h.jsx)(`span`,{className:`w-6 shrink-0`}),(0,h.jsxs)(`button`,{"aria-current":t.selectedId===e.id?`true`:void 0,"aria-haspopup":`menu`,"aria-label":`${i(`history.open`)}: ${d}`,className:ob(`flex min-h-9 min-w-0 flex-1 items-center gap-2 rounded-lg px-2 py-1.5 text-left text-sm hover:bg-[var(--surface-hover)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--focus)]`,t.selectedId===e.id&&`bg-[var(--accent-soft)] font-medium`),"data-history-session":!0,onClick:()=>t.onSelect(e),onContextMenu:n=>{n.preventDefault(),t.onMenu(e,n.currentTarget,{x:n.clientX,y:n.clientY})},onKeyDown:n=>jA(n,()=>t.onMenu(e,n.currentTarget)),ref:r=>{t.registerButton(e.id,r),r&&t.registerGroupButton([e.id],n())},title:p,type:`button`,children:[(0,h.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:d}),e.sessionKind===`subagent`?(0,h.jsx)(Ai,{"aria-label":i(`history.subtasks`),className:`shrink-0 text-[var(--muted)]`,size:12}):null,e.archived?(0,h.jsx)(gi,{"aria-label":i(`history.archived`),className:`shrink-0 text-[var(--muted)]`,size:12}):null]})]}),f&&o?(0,h.jsxs)(`ul`,{"aria-label":i(`history.childrenOf`,{title:d}),className:`min-w-0 space-y-0.5`,children:[u.map(e=>(0,h.jsx)(FA,{session:e,props:t,depth:r+1,fallback:()=>c.current||n()},e.id)),(0,h.jsx)(`li`,{style:{paddingLeft:`${Math.min(r+1,6)*12+40}px`},children:(0,h.jsx)(PA,{query:l})})]}):null]})}function IA({project:e,props:t,label:n,alias:r,onAlias:i}){let{t:a}=Dn(),o=t.initialPage.projectId===e.id?t.initialPage:void 0,[s,c]=(0,m.useState)(!!o&&e.kind!==`orphans`),l=(0,m.useRef)(null),u=MA(t,e.id,s,o),d=NA(u.data?.pages),f=!!t.preferences?.setHistoryProjectAlias&&[`workspace`,`directory`].includes(e.kind),p=(t,n)=>{if(!f)return;let a=t.getBoundingClientRect();i({id:e.id,name:e.name,alias:r,trigger:t,x:n?.x??a.left+12,y:n?.y??a.bottom})};return(0,h.jsxs)(`section`,{"aria-label":n,children:[(0,h.jsxs)(`button`,{ref:l,type:`button`,"aria-expanded":s,"aria-haspopup":f?`menu`:void 0,title:[n,a(`history.projectKinds.${e.kind}`),f?a(`history.projectAliasContextHint`):``].filter(Boolean).join(` +`),className:`flex min-h-9 w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-sm font-medium hover:bg-[var(--surface-hover)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--focus)]`,onClick:()=>c(!s),onContextMenu:e=>{f&&(e.preventDefault(),p(e.currentTarget,{x:e.clientX,y:e.clientY}))},onKeyDown:e=>{f&&jA(e,()=>p(e.currentTarget))},children:[s?(0,h.jsx)(yi,{className:`shrink-0 text-[var(--muted)]`,size:12}):(0,h.jsx)(bi,{className:`shrink-0 text-[var(--muted)]`,size:12}),e.kind===`orphans`?(0,h.jsx)(Ai,{className:`shrink-0`,size:16}):s?(0,h.jsx)(Di,{className:`shrink-0`,size:16}):(0,h.jsx)(Oi,{className:`shrink-0`,size:16}),(0,h.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:n}),e.kind===`directory`&&!r?(0,h.jsx)(`span`,{className:`shrink-0 text-[10px] font-normal text-[var(--muted)]`,children:a(`history.directoryBadge`)}):null,(0,h.jsx)(`span`,{className:`text-xs font-normal text-[var(--muted)]`,"aria-label":a(e.kind===`orphans`?`history.orphanCount`:`history.rootCount`,{count:e.total}),children:e.total})]}),s?(0,h.jsxs)(`ul`,{className:`mt-0.5 min-w-0 space-y-0.5`,children:[e.kind===`orphans`?(0,h.jsx)(`li`,{className:`px-3 py-2 text-xs text-[var(--muted)]`,children:a(`history.orphansHint`)}):null,d.map(e=>(0,h.jsx)(FA,{session:e,props:t,fallback:()=>l.current},e.id)),(0,h.jsx)(`li`,{className:`pl-8`,children:(0,h.jsx)(PA,{query:u})})]}):null]})}function LA(e){let{t}=Dn(),[n,r]=(0,m.useState)(null),[i,a]=(0,m.useState)({}),o=e.initialPage.projects??[],s=e=>e.kind===`orphans`?t(`history.orphans`):e.kind===`unassigned`?t(`history.noProject`):e.name,c=t=>{if(t.id in i)return i[t.id];try{return e.preferences?.getHistoryProjectAlias?.(e.preferenceScope,t.id)||``}catch{return``}},l=o.map(e=>c(e)||s(e));return(0,h.jsxs)(`div`,{className:`space-y-2 p-2`,"data-history-projects":!0,children:[o.map((t,n)=>{let i=l[n],a=l.filter(e=>e===i).length>1;return(0,h.jsx)(IA,{project:t,props:e,label:a?`${i} · ${t.id.slice(0,6)}`:i,alias:c(t),onAlias:r},t.id)}),n?(0,h.jsx)(AA,{target:n,close:()=>r(null),save:(t,n)=>{e.preferences.setHistoryProjectAlias(e.preferenceScope,t,n),a(e=>({...e,[t]:n}))}}):null]})}function RA({target:e,host:t,profile:n,close:r,open:i,information:a,notice:o}){let{t:s,i18n:c}=Dn(),l=(0,m.useRef)(null),[u,d]=(0,m.useState)({x:e.x,y:e.y}),f=kb(),p=e.session,g=OA(p);(0,m.useLayoutEffect)(()=>{let t=l.current?.getBoundingClientRect();d({x:Math.max(8,Math.min(e.x,window.innerWidth-(t?.width||240)-8)),y:Math.max(8,Math.min(e.y,window.innerHeight-(t?.height||240)-8))}),l.current?.querySelector(`button:not(:disabled)`)?.focus({preventScroll:!0})},[e]),(0,m.useEffect)(()=>{let e=()=>r(!1),t=e=>{l.current?.contains(e.target)||r(!1)};return window.addEventListener(`resize`,e),window.addEventListener(`blur`,e),document.addEventListener(`scroll`,t,!0),document.addEventListener(`pointerdown`,t,!0),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`blur`,e),document.removeEventListener(`scroll`,t,!0),document.removeEventListener(`pointerdown`,t,!0)}},[r]);let _=async e=>{r();try{await f(e),o(s(`common.copied`))}catch{o(s(`history.copyFailed`))}},v=async()=>{r();try{let e=await t.revealHistoryFile(gb(n),p.id);o(s(e.revealed?`history.fileRevealed`:`history.revealFailed`))}catch{o(s(`history.revealFailed`))}},y=`flex min-h-10 w-full items-center gap-3 rounded-md px-3 text-left text-sm hover:bg-[var(--surface-hover)] focus:bg-[var(--accent-soft)] focus:outline-none disabled:opacity-40`;return(0,dm.createPortal)((0,h.jsxs)(`div`,{"aria-label":`${s(`history.sessionActions`)}: ${DA(p,s,c.language)}`,className:`fixed z-[70] w-64 max-w-[calc(100vw-16px)] max-h-[calc(100dvh-16px)] overflow-y-auto overscroll-contain rounded-xl border border-[var(--border)] bg-[var(--surface-raised)] p-1.5 text-[var(--text)] shadow-xl`,ref:l,role:`menu`,style:{left:u.x,top:u.y},onContextMenu:e=>e.preventDefault(),onKeyDown:e=>{if(e.key===`Escape`||e.key===`Tab`){e.preventDefault(),r();return}let t=Array.from(l.current?.querySelectorAll(`button:not(:disabled)`)||[]),n=t.indexOf(document.activeElement),i=e.key===`Home`?0:e.key===`End`?t.length-1:e.key===`ArrowDown`?(n+1)%t.length:e.key===`ArrowUp`?(n+t.length-1)%t.length:-1;i>=0&&(e.preventDefault(),t[i]?.focus())},children:[(0,h.jsxs)(`button`,{className:y,role:`menuitem`,tabIndex:-1,type:`button`,onClick:()=>{r(!1),i()},children:[(0,h.jsx)(Ni,{size:16}),s(`history.open`)]}),(0,h.jsxs)(`button`,{className:y,disabled:!p.nativeSessionId,role:`menuitem`,tabIndex:-1,type:`button`,onClick:()=>void _(p.nativeSessionId),children:[(0,h.jsx)(Si,{size:16}),s(`history.copyId`)]}),(0,h.jsxs)(`button`,{className:y,disabled:!g,role:`menuitem`,tabIndex:-1,title:s(`history.resumeHint`),type:`button`,onClick:()=>void _(g),children:[(0,h.jsx)(Wi,{size:16}),s(`history.copyResume`)]}),(0,h.jsx)(`div`,{className:`my-1 border-t border-[var(--border)]`,role:`separator`}),(0,h.jsxs)(`button`,{className:y,role:`menuitem`,tabIndex:-1,type:`button`,onClick:()=>{r(!1),a()},children:[(0,h.jsx)(ji,{size:16}),s(`history.sessionInformation`)]}),t?.revealHistoryFile?(0,h.jsxs)(`button`,{className:y,role:`menuitem`,tabIndex:-1,type:`button`,onClick:()=>void v(),children:[(0,h.jsx)(Di,{size:16}),s(`history.revealFile`)]}):null]}),document.body)}function zA(e){return typeof e==`string`||typeof e==`number`?String(e):Array.isArray(e)?e.map(zA).join(``):(0,m.isValidElement)(e)?zA(e.props.children):``}function BA({children:e}){let{t}=Dn(),[n,r]=(0,m.useState)(!1),[i,a]=(0,m.useState)(!1),o=kb(),s=async()=>{try{await o(zA(e).replace(/\n$/,``)),r(!0),a(!1),globalThis.setTimeout(()=>r(!1),1500)}catch{r(!1),a(!0)}};return(0,h.jsxs)(`div`,{className:`group relative my-4 overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--surface)]`,children:[(0,h.jsxs)(X,{"aria-label":t(`common.copy`),className:`absolute right-2 top-2 min-h-8 px-2`,onClick:()=>void s(),type:`button`,variant:`secondary`,children:[n?(0,h.jsx)(vi,{size:14}):(0,h.jsx)(Si,{size:14}),(0,h.jsx)(`span`,{className:`sr-only`,children:t(n?`common.copied`:`common.copy`)})]}),(0,h.jsx)(`pre`,{className:`overflow-x-auto p-4 pr-12 text-sm leading-6`,children:e}),i?(0,h.jsx)(`p`,{className:`px-4 pb-3 text-sm text-[var(--danger)]`,role:`status`,children:t(`history.copyFailed`)}):null]})}function VA({text:e}){return(0,h.jsx)(`div`,{className:`min-w-0 break-words text-sm leading-7`,children:(0,h.jsx)(SD,{components:{a:({node:e,...t})=>(0,h.jsx)(`a`,{...t,className:`text-[var(--accent-strong)] underline underline-offset-2`,rel:`noreferrer`,target:`_blank`}),blockquote:({node:e,...t})=>(0,h.jsx)(`blockquote`,{...t,className:`my-3 border-l-4 border-[var(--border)] pl-4 text-[var(--muted)]`}),code:({node:e,...t})=>(0,h.jsx)(`code`,{...t,className:ob(`rounded bg-[var(--surface)] px-1.5 py-0.5 font-mono text-[0.9em]`,t.className)}),h1:({node:e,...t})=>(0,h.jsx)(`h1`,{...t,className:`mb-3 mt-5 text-xl font-bold`}),h2:({node:e,...t})=>(0,h.jsx)(`h2`,{...t,className:`mb-3 mt-5 text-lg font-bold`}),h3:({node:e,...t})=>(0,h.jsx)(`h3`,{...t,className:`mb-2 mt-4 font-semibold`}),li:({node:e,...t})=>(0,h.jsx)(`li`,{...t,className:`my-1`}),ol:({node:e,...t})=>(0,h.jsx)(`ol`,{...t,className:`my-3 list-decimal pl-6`}),p:({node:e,...t})=>(0,h.jsx)(`p`,{...t,className:`my-3 whitespace-pre-wrap first:mt-0 last:mb-0`}),pre:({node:e,children:t})=>(0,h.jsx)(BA,{children:t}),table:({node:e,...t})=>(0,h.jsx)(`div`,{className:`my-4 overflow-x-auto`,children:(0,h.jsx)(`table`,{...t,className:`w-full border-collapse text-sm`})}),td:({node:e,...t})=>(0,h.jsx)(`td`,{...t,className:`border border-[var(--border)] px-3 py-2`}),th:({node:e,...t})=>(0,h.jsx)(`th`,{...t,className:`border border-[var(--border)] bg-[var(--surface)] px-3 py-2 text-left`}),ul:({node:e,...t})=>(0,h.jsx)(`ul`,{...t,className:`my-3 list-disc pl-6`})},remarkPlugins:[EA],children:e})})}function HA({core:e,profile:t,host:n,preferences:r}){let{t:i,i18n:a}=Dn(),[o,s]=(0,m.useState)(null),[c,l]=(0,m.useState)(null),[u,d]=(0,m.useState)(!1),[f,p]=(0,m.useState)(null),g=f?.session.id===o?f:null,[_,v]=(0,m.useState)(!1),[y,b]=(0,m.useState)(null),[x,S]=(0,m.useState)(``),[C,w]=(0,m.useState)(``),[T,E]=(0,m.useState)(`metadata`),D=(0,m.useRef)(null),[O,ee]=(0,m.useState)(`metadata`),[k,A]=(0,m.useState)(`all`),[j,M]=(0,m.useState)(0),[N,P]=(0,m.useState)(!1),[F,te]=(0,m.useState)(``),[ne,re]=(0,m.useState)(``),[ie,I]=(0,m.useState)(`all`),[L,ae]=(0,m.useState)(null),oe=JSON.stringify([t.id,t.revision,C,ne,ie,O,k]),[se,ce]=(0,m.useState)(null),le=se?.scope===oe?se:null,[ue,de]=(0,m.useState)(null),[fe,pe]=(0,m.useState)(``),me=(0,m.useRef)(null),he=(0,m.useRef)(null),ge=(0,m.useRef)(null),_e=(0,m.useRef)(new Map),ve=(0,m.useRef)(new Map),ye=(0,m.useCallback)((e=!0)=>{e&&le?.trigger.isConnected&&le.trigger.focus({preventScroll:!0}),ce(null)},[le]),be=(e,t,n)=>{let r=t.getBoundingClientRect();pe(``),ce({session:e,trigger:t,scope:oe,x:n?.x??r.left+24,y:n?.y??r.bottom})},xe={profile:gb(t),view:`projects`,page:1,pageSize:10,...C?{query:C}:{},...ne?{provider:ne}:{},archived:ie,searchScope:O,sessionKind:k},Se=rt({queryKey:[`history`,oe],queryFn:({signal:t})=>e.listHistory(xe,{signal:t}),gcTime:0,retry:!1,staleTime:1/0,refetchOnWindowFocus:!1,refetchOnReconnect:!1});(0,m.useEffect)(()=>{s(null),l(null),p(null),b(null),E(`metadata`),ee(`metadata`),A(`all`),P(!1),S(``),w(``),te(``),re(``),I(`all`)},[t.id,t.revision]),(0,m.useEffect)(()=>{s(null),l(null),p(null),b(null),_e.current.clear(),ve.current.clear()},[C,ne,ie,O,k]),(0,m.useEffect)(()=>{ce(null),de(null),pe(``)},[t.id,t.revision,C,ne,ie,O,k,Se.dataUpdatedAt]),(0,m.useEffect)(()=>{if(!o){p(null),b(null),v(!1);return}let n=new AbortController;return p(null),b(null),v(!0),e.getHistorySession({profile:gb(t),sessionId:o,...u?{metadataOnly:!0}:{messageLimit:200}},{signal:n.signal}).then(e=>{n.signal.aborted||p(e)}).catch(e=>{n.signal.aborted||b(N&&e instanceof Kr&&e.code===`INVALID_INPUT`?i(`history.parentUnavailable`):yb(e,i))}).finally(()=>{n.signal.aborted||v(!1)}),()=>{n.abort(),p(null)}},[e,t.id,t.revision,o,i,j,N,u]),(0,m.useEffect)(()=>{g&&!le&&me.current?.focus({preventScroll:!0})},[g]),(0,m.useEffect)(()=>{he.current&&(he.current.scrollTop=0)},[o,t.id,t.revision]),(0,m.useEffect)(()=>{o||!L||(([_e.current.get(L),ve.current.get(L)].find(e=>e?.isConnected)||ge.current)?.focus({preventScroll:!0}),ae(null))},[Se.data,L,o]);let R=Se.data?.sessions??[],Ce=g?.session??(c?.id===o?c:R.find(e=>e.id===o)),we=Ce?DA(Ce,i,a.language):i(y?`history.sessionInformation`:`common.loading`),Te=()=>{o&&!L&&ae(o),s(null)},Ee=x.trim()!==C||F.trim()!==ne||T!==O,De=Ee||!!(C||ne||x||F)||O!==`metadata`||ie!==`all`||k!==`all`;return(0,h.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden`,"data-history-layout":!0,children:[(0,h.jsxs)(`div`,{className:ob(`max-h-[45%] shrink-0 overflow-y-auto overscroll-contain`,o&&`hidden lg:block`),"data-history-controls":!0,children:[(0,h.jsx)(Sb,{title:i(`history.title`),subtitle:i(`history.subtitle`),action:(0,h.jsxs)(X,{disabled:Se.isFetching,onClick:()=>{Se.refetch(),M(e=>e+1)},type:`button`,variant:`secondary`,children:[(0,h.jsx)(Ii,{className:ob(Se.isFetching&&`animate-spin`),size:16}),i(`common.refresh`)]})}),(0,h.jsxs)(`form`,{className:`mb-3 grid grid-cols-[minmax(0,1fr)_auto] gap-2`,onSubmit:e=>{e.preventDefault(),w(x.trim()),ee(T),re(F.trim())},children:[(0,h.jsx)(lb,{ref:D,"aria-label":i(`common.search`),onChange:e=>S(e.target.value),placeholder:i(`history.searchPlaceholder`),value:x}),(0,h.jsxs)(X,{type:`submit`,children:[(0,h.jsx)(Bi,{size:16}),i(`common.search`)]}),De?(0,h.jsxs)(`div`,{className:`col-span-2 flex flex-wrap items-center gap-2`,children:[(0,h.jsx)(X,{type:`button`,size:`compact`,variant:`secondary`,onClick:()=>{S(``),w(``),te(``),re(``),E(`metadata`),ee(`metadata`),I(`all`),A(`all`),D.current?.focus()},children:i(`ux.clearFilters`)}),Ee?(0,h.jsx)(`p`,{className:`text-xs text-[var(--muted)]`,role:`status`,children:i(`ux.pendingFilters`)}):null]}):null,(0,h.jsxs)(`details`,{className:`col-span-2 rounded-lg border border-[var(--border)] bg-[var(--surface-raised)] px-3 py-2`,children:[(0,h.jsx)(`summary`,{className:`cursor-pointer text-xs text-[var(--muted)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--focus)]`,children:i(`history.filters`)}),(0,h.jsxs)(`div`,{className:`mt-2 grid gap-2 md:grid-cols-2 xl:grid-cols-4`,children:[(0,h.jsx)(lb,{"aria-label":i(`history.providerFilter`),onChange:e=>te(e.target.value),placeholder:i(`history.providerFilter`),value:F}),(0,h.jsxs)(`select`,{"aria-label":i(`history.archivedFilter`),className:`min-h-10 rounded-lg border border-[var(--border)] bg-[var(--input)] px-3`,onChange:e=>I(e.target.value),value:ie,children:[(0,h.jsx)(`option`,{value:`all`,children:i(`history.all`)}),(0,h.jsx)(`option`,{value:`active`,children:i(`history.active`)}),(0,h.jsx)(`option`,{value:`archived`,children:i(`history.archived`)})]}),(0,h.jsxs)(`select`,{"aria-label":i(`history.searchScope`),className:`min-h-10 rounded-lg border border-[var(--border)] bg-[var(--input)] px-3`,value:T,onChange:e=>E(e.target.value),children:[(0,h.jsx)(`option`,{value:`metadata`,children:i(`history.metadataSearch`)}),(0,h.jsx)(`option`,{value:`content`,children:i(`history.contentSearch`)})]}),(0,h.jsxs)(`select`,{"aria-label":i(`history.sessionType`),className:`min-h-10 rounded-lg border border-[var(--border)] bg-[var(--input)] px-3`,value:k,onChange:e=>A(e.target.value),children:[(0,h.jsx)(`option`,{value:`all`,children:i(`history.mainWithSubtasks`)}),(0,h.jsx)(`option`,{value:`main`,children:i(`history.mainSessions`)}),(0,h.jsx)(`option`,{value:`subagent`,children:i(`history.subtasks`)})]}),(0,h.jsx)(`p`,{className:`text-xs text-[var(--muted)] md:col-span-2 xl:col-span-4`,children:i(T===`content`?`history.contentSearchHint`:`history.metadataSearchHint`)})]})]})]})]}),(0,h.jsxs)(`div`,{className:`grid min-h-0 flex-1 grid-rows-1 gap-0 overflow-hidden rounded-xl border border-[var(--border)] lg:grid-cols-[minmax(240px,300px)_minmax(0,1fr)]`,children:[(0,h.jsxs)(cb,{"aria-busy":Se.isPending||Se.isFetching,className:ob(`min-h-0 min-w-0 flex-col overflow-hidden rounded-none border-0 bg-[var(--surface)] p-0 shadow-none lg:border-r`,o?`hidden lg:flex`:`flex`),children:[(0,h.jsx)(`p`,{className:`shrink-0 px-3 py-2 text-xs text-[var(--muted)]`,children:i(`history.projectTreeHint`)}),(0,h.jsx)(`div`,{"aria-label":i(`history.listRegion`),className:`min-h-0 flex-1 overflow-y-auto overscroll-contain focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--focus)]`,ref:ge,role:`region`,tabIndex:0,"data-history-list":!0,children:Se.isPending?(0,h.jsx)(`div`,{className:`p-5`,"aria-live":`polite`,role:`status`,children:i(`common.loading`)}):Se.isError?(0,h.jsx)(`div`,{className:`p-5 text-[var(--danger)]`,role:`alert`,children:yb(Se.error,i)}):Se.data?.projects?.length?(0,h.jsx)(LA,{scope:`${oe}:${Se.dataUpdatedAt}`,preferenceScope:JSON.stringify([t.id,t.revision]),preferences:r,core:e,input:xe,initialPage:Se.data,selectedId:o,onSelect:e=>{ae(null),de(null),d(!1),P(!1),l(e),s(e.id)},onMenu:be,registerButton:(e,t)=>{t?_e.current.set(e,t):_e.current.delete(e)},registerGroupButton:(e,t)=>{for(let n of e)t?ve.current.set(n,t):ve.current.delete(n)}},`${oe}:${Se.dataUpdatedAt}`):(0,h.jsx)(`div`,{className:`p-5 text-[var(--muted)]`,children:i(`history.empty`)})}),fe?(0,h.jsx)(`p`,{className:`shrink-0 px-3 py-2 text-xs`,role:`status`,children:fe}):null]}),(0,h.jsx)(cb,{className:ob(`min-h-0 min-w-0 flex-col overflow-hidden rounded-none border-0 p-0 shadow-none`,o?`flex`:`hidden lg:flex`),children:o?(0,h.jsxs)(m.Fragment,{children:[(0,h.jsxs)(`div`,{className:`flex max-h-[40%] shrink-0 items-start justify-between gap-3 overflow-y-auto overscroll-contain border-b border-[var(--border)] p-3 md:p-4`,"data-history-detail-header":!0,children:[(0,h.jsxs)(`div`,{className:`min-w-0`,children:[(0,h.jsx)(`h2`,{className:`truncate text-lg font-semibold`,ref:me,tabIndex:-1,children:we}),g?(0,h.jsxs)(`div`,{className:`mt-1 flex flex-wrap gap-2 text-xs text-[var(--muted)]`,children:[(0,h.jsx)(`span`,{children:g.session.provider}),g.session.model?(0,h.jsx)(`span`,{children:g.session.model}):null,(0,h.jsx)(`span`,{children:vb(g.session.updatedAt,a.language)})]}):null]}),(0,h.jsxs)(`div`,{className:`flex shrink-0 gap-1`,children:[(0,h.jsx)(X,{"aria-label":i(`history.refreshDetail`),disabled:_,onClick:()=>M(e=>e+1),type:`button`,variant:`secondary`,children:(0,h.jsx)(Ii,{size:16})}),(0,h.jsxs)(X,{className:`lg:hidden`,onClick:Te,type:`button`,variant:`secondary`,children:[(0,h.jsx)(_i,{size:16}),i(`history.back`)]})]})]}),(0,h.jsxs)(`div`,{"aria-label":i(`history.detailRegion`),className:`min-h-0 flex-1 overflow-y-auto overscroll-contain p-3 focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--focus)] md:p-4`,ref:he,role:`region`,tabIndex:0,"data-history-detail-scroll":!0,children:[Ce&&ue===o?(0,h.jsxs)(`div`,{className:`mb-4 rounded-xl border border-[var(--border)] p-3`,children:[(0,h.jsx)(`div`,{className:`mb-2 flex justify-end`,children:(0,h.jsx)(X,{size:`compact`,onClick:()=>de(null),type:`button`,variant:`ghost`,children:i(`common.close`)})}),(0,h.jsx)(kA,{openInformation:!0,session:Ce,detail:g,host:n,profile:t,onOpenParent:e=>{de(null),d(!1),P(!0),L||ae(o),s(e)}},`${t.id}:${Ce.id}`)]}):null,u&&!_?(0,h.jsx)(X,{className:`mb-4`,onClick:()=>{d(!1),de(null)},type:`button`,variant:`secondary`,children:i(`history.open`)}):null,_?(0,h.jsx)(`span`,{"aria-live":`polite`,role:`status`,children:i(`common.loading`)}):y?(0,h.jsxs)(`div`,{className:`grid justify-items-start gap-3`,children:[(0,h.jsx)(`p`,{className:`text-[var(--danger)]`,role:`alert`,children:y}),(0,h.jsx)(X,{onClick:()=>M(e=>e+1),type:`button`,variant:`secondary`,children:i(`common.retry`)})]}):g&&!u?(0,h.jsxs)(`div`,{children:[g.truncated?(0,h.jsx)(`div`,{className:`mb-4 rounded-lg border border-[var(--warning)] bg-[var(--warning-soft)] p-3 text-sm`,children:i(`history.truncated`)}):null,(0,h.jsx)(`div`,{className:`grid gap-6`,children:g.messages.map(e=>e.role===`user`?(0,h.jsxs)(`article`,{className:`ml-auto max-w-[85%] rounded-2xl rounded-br-md bg-[var(--accent-soft)] px-4 py-3`,children:[(0,h.jsxs)(`div`,{className:`mb-1 text-xs font-semibold text-[var(--muted)]`,children:[i(`history.roles.user`),e.timestamp?(0,h.jsx)(`span`,{className:`ml-2 font-normal`,children:vb(e.timestamp,a.language)}):null]}),(0,h.jsx)(`div`,{className:`whitespace-pre-wrap break-words text-sm leading-7`,children:e.text})]},`${e.sequence}-${e.role}`):(0,h.jsxs)(`article`,{className:`min-w-0`,children:[(0,h.jsxs)(`div`,{className:`mb-2 text-xs font-semibold text-[var(--muted)]`,children:[i(`history.roles.assistant`),e.timestamp?(0,h.jsx)(`span`,{className:`ml-2 font-normal`,children:vb(e.timestamp,a.language)}):null]}),(0,h.jsx)(VA,{text:e.text})]},`${e.sequence}-${e.role}`))})]}):null]})]}):(0,h.jsx)(`div`,{className:`grid min-h-0 flex-1 place-items-center p-4 text-sm text-[var(--muted)]`,children:i(`history.select`)})})]}),le?(0,h.jsx)(RA,{target:le,host:n,profile:t,close:ye,open:()=>{de(null),d(!1),ae(null),P(!1),l(le.session),s(le.session.id)},information:()=>{de(le.session.id),d(!0),ae(null),P(!1),l(le.session),s(le.session.id)},notice:pe}):null]})}function UA({value:e}){let{t}=Dn(),n=sr(e);return!n||!n.total&&!n.unconfirmed?null:(0,h.jsxs)(`section`,{className:`grid gap-2 rounded-lg border border-[var(--warning)] bg-[var(--warning-soft)] p-3 text-sm`,"aria-label":t(`skips.title`),children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:t(`skips.title`)}),(0,h.jsx)(`p`,{children:t(`skips.counts`,{total:n.total,files:n.rolloutFiles,rows:n.sqliteRows,unknown:n.unconfirmed})}),(0,h.jsx)(`p`,{children:t(n.retryRecommended?`skips.retry`:`skips.fix`)}),(0,h.jsxs)(`details`,{children:[(0,h.jsx)(`summary`,{className:`cursor-pointer`,children:t(`skips.details`)}),(0,h.jsx)(`ul`,{className:`mt-2 max-h-64 space-y-2 overflow-auto`,children:n.items.map((e,n)=>(0,h.jsxs)(`li`,{children:[(0,h.jsx)(`span`,{className:`block select-text break-all font-mono text-xs`,children:e.path??e.id??t(`skips.unidentified`)}),(0,h.jsxs)(`span`,{children:[t(`skips.reasons.${e.reason}`),` · `,t(`skips.stages.${e.stage}`)]})]},`${e.kind}-${e.path??e.id??n}`))})]}),(0,h.jsx)(`p`,{children:t(`skips.shown`,{shown:n.items.length,omitted:n.omitted,total:n.total})})]})}var WA=new Set([...jn,`prepare`,`validate_plan`,`scan`,`scan_rollout_files`,`check_locked_rollout_files`,`create_backup`,`rewrite_rollout_files`,`repair_workspace_roots`,`update_sqlite`,`update_config`,`verify_repair`,`clean_backups`,`create_restore_pre_snapshot`,`persist_restore_journal`,`apply_restore_targets`,`commit_restore`,`acknowledge_restore_commit`,`rollback_restore`,`prune`,`start`,`stop`,`automatic-sync`,`create`,`update`,`delete`,`export`,`check`,`download`,`install`,`startup-check`]),GA=new Set([...An,`WRITE_FAILED`,...Mn,`SQLITE_READONLY`,`SQLITE_FULL`]);function KA(e,t){return WA.has(e)?t(`logs.stages.${e}`,{defaultValue:t(`logs.unknownStage`)}):t(`logs.unknownStage`)}function qA(e,t){let n=GA.has(e)?e:`INTERNAL_ERROR`;return`${t(`errors.${n}`,{defaultValue:t(`errors.fallback`)})} (${n})`}function JA(e){return!!(e&&typeof e.snapshotAt==`string`&&Number.isFinite(Date.parse(e.snapshotAt)))}function YA(e){if(!JA(e)||e.operationInProgress||e.pendingRecovery||e.statusReadBlocked||!e.rolloutScanComplete||e.lockedRolloutFiles.length>0)return`unknown`;let t=e.alignment;return!t||typeof t!=`object`||Array.isArray(t)||t.sqliteReadable!==!0||typeof t.aligned!=`boolean`?`unknown`:t.aligned?`aligned`:`notAligned`}function XA(e,t){if(![`sync`,`switch`].includes(e)||!t||typeof t!=`object`||Array.isArray(t))return!1;let n=t.rewrittenSessionFiles;return typeof n==`number`&&Number.isSafeInteger(n)&&n>=100}function ZA({afterOperation:e=!1}){let{t}=Dn();return(0,h.jsxs)(`details`,{className:`rounded-lg border border-[var(--border)] px-3 py-2 text-sm`,children:[(0,h.jsx)(`summary`,{className:`cursor-pointer rounded py-1 font-medium text-[var(--accent-strong)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus)]`,children:t(e?`sync.performance.resultLink`:`sync.performance.title`)}),(0,h.jsxs)(`div`,{className:`grid gap-2 pb-1 pt-2 text-[var(--muted)]`,children:[(0,h.jsx)(`p`,{children:t(`sync.performance.equalLength`)}),(0,h.jsx)(`p`,{children:t(`sync.performance.differentLength`)}),(0,h.jsx)(`p`,{children:t(`sync.performance.configuration`)})]})]})}var QA={completed:{tone:`success`,titleKey:`operationResult.completed.title`,descriptionKey:`operationResult.completed.description`,toastKey:`global.completed`},partial:{tone:`warning`,titleKey:`operationResult.partial.title`,descriptionKey:`operationResult.partial.description`,toastKey:`global.partial`},failed_rolled_back:{tone:`warning`,titleKey:`operationResult.failedRolledBack.title`,descriptionKey:`operationResult.failedRolledBack.description`,toastKey:`global.failed`},recovery_required:{tone:`danger`,titleKey:`operationResult.recoveryRequired.title`,descriptionKey:`operationResult.recoveryRequired.description`,toastKey:`global.failed`},cancelled:{tone:`warning`,titleKey:`operationResult.cancelled.title`,descriptionKey:`operationResult.cancelled.description`,toastKey:`global.cancelled`},stale:{tone:`warning`,titleKey:`operationResult.stale.title`,descriptionKey:`operationResult.stale.description`,toastKey:`global.stale`}};function $A(e){return QA[e]}function ej(e){if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=[],n=new Set([`targetProvider`,`targetModel`,`partialReason`,`failedStage`,`failureCode`]),r=new Set([`unconfirmedSessionFiles`,`changedSessionFiles`,`sqliteRowsUpdated`,`sqliteProviderRowsUpdated`,`sqliteModelRowsUpdated`,`sqliteUserEventRowsUpdated`,`sqliteCwdRowsUpdated`,`updatedWorkspaceRoots`,`savedWorkspaceRootCount`,`resolvedOperationCount`]);for(let[i,a]of Object.entries(e)){if(i===`repairTargets`&&Array.isArray(a)){t.push([i,a.filter(e=>typeof e==`string`).join(`, `)]);continue}!(n.has(i)&&typeof a==`string`)&&!(r.has(i)&&typeof a==`number`&&Number.isSafeInteger(a)&&a>=0)||t.push([i,String(a)])}return t}function tj(e){if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e.skippedLockedRolloutFiles;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function nj(e){if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e.skippedChangedRolloutFiles;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function rj(e,t,n){return e===`failedStage`?KA(t,n):e===`failureCode`?qA(t,n):e===`partialReason`?n(`operationResult.partialReasons.${t}`,{defaultValue:n(`global.partial`)}):e===`repairTargets`?t.split(`, `).map(e=>n(`diagnostics.repairTargets.${e}`,{defaultValue:e})).join(`, `):t}function ij(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e.verification;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t;return![`verified`,`remaining`,`unavailable`].includes(String(n.status))||![`remainingRolloutFiles`,`remainingSqliteRows`,`remainingWorkspaceRoots`,`skippedSessions`].every(e=>typeof n[e]==`number`&&Number.isSafeInteger(n[e])&&n[e]>=0)?null:{status:n.status,remainingRolloutFiles:n.remainingRolloutFiles,remainingSqliteRows:n.remainingSqliteRows,remainingWorkspaceRoots:n.remainingWorkspaceRoots,skippedSessions:n.skippedSessions}}function aj({result:e,postWriteStatus:t,close:n,closeDisabled:r=!1,openBackupRestore:i,reviewOperation:a,restoreFocus:o}){let{t:s,i18n:c}=Dn(),l=t?.operationId===e?.operationId?t:void 0,u=l?.state===`received`?l.snapshot:void 0,d=YA(u),f=e?$A(e.outcome):null,p=e?ej(e.result):[],m=e?tj(e.result):[],g=e?nj(e.result):[],_=sr(e?.result&&typeof e.result==`object`&&!Array.isArray(e.result)?e.result.skipSummary:void 0),v=_?0:m.length+g.length,y=e?.result&&typeof e.result==`object`&&!Array.isArray(e.result)&&typeof e.result.partialReason==`string`?e.result.partialReason:null,b=e?.result&&typeof e.result==`object`&&!Array.isArray(e.result)&&e.result.retryRecommended===!0,x=e?ij(e.result):null,S=e?.outcome===`recovery_required`;return(0,h.jsx)(fb,{closeDisabled:r,closeLabel:s(`common.close`),description:r?s(`operationResult.resolveBeforeClose`):void 0,footer:(0,h.jsx)(X,{disabled:r,onClick:n,type:`button`,children:s(`common.close`)}),onOpenChange:e=>{!e&&!r&&n()},open:!!e,restoreFocus:o,title:s(`operationResult.title`),children:e&&f?(0,h.jsxs)(`div`,{"aria-live":`polite`,className:`grid gap-4`,role:S?`alert`:`status`,children:[(0,h.jsxs)(`div`,{className:f.tone===`danger`?`rounded-lg border border-[var(--danger)] bg-[var(--danger-soft)] p-4`:f.tone===`warning`?`rounded-lg border border-[var(--warning)] bg-[var(--warning-soft)] p-4`:`rounded-lg border border-[var(--success)] bg-[var(--success-soft)] p-4`,children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:s(f.titleKey)}),(0,h.jsx)(`p`,{className:`mt-1 text-sm`,children:s(f.descriptionKey)})]}),l?(0,h.jsxs)(cb,{children:[(0,h.jsx)(`h3`,{className:`text-sm font-semibold`,children:s(`ux.finalStatus`)}),l.state===`checking`?(0,h.jsx)(`p`,{className:`mt-2 text-sm`,children:s(`ux.finalChecking`)}):(0,h.jsxs)(`div`,{className:`mt-2 grid gap-2 text-sm`,children:[u?(0,h.jsxs)(`p`,{children:[s(`common.provider`),`: `,(0,h.jsx)(`span`,{className:`break-all font-semibold`,children:u.currentProvider})]}):null,(0,h.jsx)(`p`,{children:s(d===`unknown`?`ux.finalUnavailable`:`overview.${d}`)}),u?(0,h.jsxs)(`p`,{className:`text-xs text-[var(--muted)]`,children:[s(`overview.snapshot`),`: `,vb(u.snapshotAt,c.language)]}):null]})]}):null,e.backup?(0,h.jsxs)(`div`,{className:`rounded-lg border border-[var(--success)] bg-[var(--success-soft)] p-4 text-sm font-medium text-[var(--success)]`,children:[(0,h.jsx)(`p`,{children:s(`operationResult.backupCreated`)}),(0,h.jsxs)(`p`,{className:`mt-2 break-all font-mono text-xs`,children:[s(`operationResult.backupId`),`: `,e.backup.backupId]}),i?(0,h.jsx)(X,{className:`mt-3`,onClick:()=>i(e.backup.backupId),type:`button`,variant:`secondary`,children:s(`operationResult.openBackupRestore`)}):null]}):null,p.length?(0,h.jsx)(cb,{children:(0,h.jsx)(`dl`,{className:`grid gap-3 text-sm`,children:p.map(([e,t])=>(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:s(`operationResult.fields.${e}`,{defaultValue:e})}),(0,h.jsx)(`dd`,{className:`mt-1 break-words`,children:rj(e,t,s)})]},e))})}):null,XA(e.operation,e.result)?(0,h.jsx)(ZA,{afterOperation:!0},e.operationId):null,e.warnings.length?(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:s(`common.warnings`)}),(0,h.jsx)(`ul`,{className:`mt-2 list-disc space-y-1 pl-5 text-sm`,children:e.warnings.map((e,t)=>(0,h.jsx)(`li`,{children:xb(e,s)},`${t}-${e}`))})]}):null,(0,h.jsx)(UA,{value:_}),e.operation===`switch`&&e.result&&typeof e.result==`object`&&!Array.isArray(e.result)&&e.result.configUpdated===!0?(0,h.jsx)(`p`,{children:s(`skips.configSwitched`,{count:e.result.changedSessionFiles??0})}):null,v?(0,h.jsx)(`p`,{className:`rounded-lg border border-[var(--warning)] bg-[var(--warning-soft)] p-3 text-sm`,children:s(`operationResult.skippedCount`,{count:v})}):null,b&&(y===`mutation-failed`||!_||!_.total&&!_.unconfirmed)?(0,h.jsx)(`p`,{className:`text-sm text-[var(--warning)]`,children:s(y===`locked-session`?`operationResult.retryAfterSession`:`operationResult.retryFreshPlan`)}):null,b&&a?(0,h.jsx)(X,{onClick:a,type:`button`,variant:`secondary`,children:s(`operationResult.reviewOperation`)}):null,x?(0,h.jsxs)(cb,{children:[(0,h.jsx)(`h3`,{className:`text-sm font-semibold`,children:s(`operationResult.verification.title`)}),(0,h.jsx)(`p`,{className:`mt-1 text-sm text-[var(--muted)]`,children:s(`operationResult.verification.status.${x.status}`)}),x.status===`remaining`?(0,h.jsxs)(`dl`,{className:`mt-3 grid gap-2 text-sm sm:grid-cols-2`,children:[(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:s(`operationResult.verification.remainingRolloutFiles`)}),(0,h.jsx)(`dd`,{children:x.remainingRolloutFiles})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:s(`operationResult.verification.remainingSqliteRows`)}),(0,h.jsx)(`dd`,{children:x.remainingSqliteRows})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:s(`operationResult.verification.remainingWorkspaceRoots`)}),(0,h.jsx)(`dd`,{children:x.remainingWorkspaceRoots})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:s(`operationResult.verification.skippedSessions`)}),(0,h.jsx)(`dd`,{children:x.skippedSessions})]})]}):null]}):null,p.length?(0,h.jsx)(`p`,{className:`text-xs text-[var(--muted)]`,children:s(`operationResult.changeCountersHint`)}):null,r?(0,h.jsx)(`p`,{className:`text-sm text-[var(--danger)]`,children:s(`operationResult.resolveBeforeClose`)}):null]}):null})}var oj=[`copyTailMs`,`flushMs`,`replaceMs`,`cleanupMs`,`restoreMtimeMs`],sj=[`workerStartupMs`,`workerCloseMs`,`requestRoundTripMs`,`workerMs`,`sourceOpenMs`,`readHeaderMs`,`tempCreateMs`];function cj({timing:e,pending:t}){let{t:n}=Dn();if(!e)return(0,h.jsx)(`p`,{className:`text-sm text-[var(--muted)]`,children:n(t?`logs.fileTiming.pending`:`logs.fileTiming.unavailable`)});let r=e=>n(e<1e3?`logs.fileTiming.milliseconds`:`logs.seconds`,{value:(e<1e3?e:e/1e3).toFixed(e<1e3?1:3)}),i=t=>(0,h.jsx)(`dl`,{className:`mt-2 grid gap-2 text-sm`,children:t.map(t=>(0,h.jsxs)(`div`,{className:`flex items-baseline justify-between gap-3`,children:[(0,h.jsx)(`dt`,{children:n(`logs.fileTiming.phases.${t}`)}),(0,h.jsx)(`dd`,{className:`shrink-0 tabular-nums`,children:r(e[t])})]},t))});return(0,h.jsxs)(`section`,{"aria-label":n(`logs.fileTiming.title`),className:`rounded-lg border border-[var(--border)] p-3`,children:[(0,h.jsxs)(`div`,{className:`flex flex-wrap items-baseline justify-between gap-2`,children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:n(`logs.fileTiming.title`)}),(0,h.jsx)(`span`,{className:`text-sm tabular-nums`,children:r(e.totalMs)})]}),(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:n(`logs.fileTiming.files`,{measured:e.measuredFiles,attempted:e.attemptedFiles,inPlace:e.inPlaceFiles,rewritten:e.rewrittenFiles,skipped:e.skippedFiles})}),e.measuredFiles{try{await r(t),a(n(`common.copied`))}catch{a(n(`history.copyFailed`))}};return(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:e}),(0,h.jsxs)(`dd`,{className:`flex min-w-0 items-center gap-2`,children:[(0,h.jsx)(`span`,{className:`min-w-0 break-all font-mono text-xs`,children:t}),(0,h.jsx)(X,{"aria-label":`${n(`common.copy`)} ${e}`,onClick:()=>void o(),type:`button`,variant:`ghost`,children:n(`common.copy`)}),(0,h.jsx)(`span`,{"aria-live":`polite`,className:`text-xs`,children:i})]})]})}function _j({host:e,profileId:t,profileRevision:n,openBackupRestore:r,reviewOperation:i}){let{t:a,i18n:o}=Dn(),[s,c]=(0,m.useState)(1),[l,u]=(0,m.useState)(``),[d,f]=(0,m.useState)(``),[p,g]=(0,m.useState)(t),[_,v]=(0,m.useState)(null),y=(0,m.useRef)(null),b=(0,m.useRef)(null),x=(0,m.useRef)(null),S=rt({queryKey:[`profiles`],queryFn:({signal:t})=>e.listProfiles(t),retry:!1,staleTime:1/0,refetchOnWindowFocus:!1,refetchOnReconnect:!1}),C=rt({queryKey:[`operation-logs`,s,p,l,d],queryFn:({signal:t})=>e.listOperationLogs({page:s,pageSize:lj,...p?{profileId:p}:{},...l?{operation:l}:{},...d?{status:d}:{}},t),enabled:!!e.listOperationLogs,retry:!1,staleTime:1/0,refetchOnWindowFocus:!1,refetchOnReconnect:!1}),w=rt({queryKey:[`operation-log`,_],queryFn:({signal:t})=>e.getOperationLog(_,t),enabled:!!(_&&e.getOperationLog),retry:!1,staleTime:1/0,refetchOnWindowFocus:!1,refetchOnReconnect:!1});(0,m.useEffect)(()=>{g(t),c(1)},[t]),(0,m.useEffect)(()=>{v(null),y.current&&(y.current.scrollTop=0)},[s,p,l,d,t,n]),(0,m.useEffect)(()=>{_&&!C.isFetching&&C.isSuccess&&!C.data.entries.some(e=>e.id===_)&&v(null)},[C.data,C.isFetching,C.isSuccess,_]),(0,m.useLayoutEffect)(()=>{if(!_){b.current?.parentElement?.contains(document.activeElement)&&globalThis.requestAnimationFrame(()=>{(x.current?.isConnected?x.current:y.current)?.focus({preventScroll:!0})});return}b.current&&(b.current.scrollTop=0,globalThis.matchMedia?.(`(min-width: 1024px)`).matches||b.current.focus({preventScroll:!0}))},[_]);let T=()=>{v(null),globalThis.requestAnimationFrame(()=>(x.current?.isConnected?x.current:y.current)?.focus({preventScroll:!0}))},E=w.data===void 0?C.data?.entries.find(e=>e.id===_)??null:w.data?.id===_?w.data:null,D=E?Object.entries(E.counts??{}).filter(([e])=>fj.has(e)):[],O=E?.previewCounts?[[`rolloutFilesToChange`,E.previewCounts.rolloutFilesToChange],[`sqliteRowsToChange`,E.previewCounts.sqliteRowsToChange],[`lockedRolloutFiles`,E.previewCounts.lockedRolloutFiles]]:[];return(0,h.jsxs)(`section`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden`,"data-testid":`operation-logs-workspace`,children:[(0,h.jsxs)(`div`,{className:ob(`max-h-[45%] shrink-0 overflow-y-auto overscroll-contain`,_&&`hidden lg:block`),children:[(0,h.jsx)(Sb,{title:a(`logs.title`),subtitle:a(`logs.subtitle`),action:(0,h.jsxs)(X,{disabled:C.isFetching||w.isFetching,onClick:()=>{C.refetch(),_&&w.refetch()},type:`button`,variant:`secondary`,children:[(0,h.jsx)(Ii,{className:ob((C.isFetching||w.isFetching)&&`animate-spin`),size:16}),a(`common.refresh`)]})}),(0,h.jsxs)(`div`,{className:`mb-3 flex flex-wrap gap-2 text-sm [&>select]:max-w-full`,children:[(0,h.jsxs)(`select`,{"aria-label":a(`logs.profileFilter`),className:`min-h-10 rounded-lg border border-[var(--border)] bg-[var(--input)] px-3`,onChange:e=>{g(e.target.value),c(1),v(null)},value:p,children:[(0,h.jsx)(`option`,{value:``,children:a(`logs.allProfiles`)}),S.data?.map(e=>(0,h.jsx)(`option`,{value:e.id,children:bb(e,a)},e.id))]}),(0,h.jsxs)(`select`,{"aria-label":a(`logs.operationFilter`),className:`min-h-10 rounded-lg border border-[var(--border)] bg-[var(--input)] px-3`,onChange:e=>{u(e.target.value),c(1),v(null)},value:l,children:[(0,h.jsx)(`option`,{value:``,children:a(`logs.allOperations`)}),uj.map(e=>(0,h.jsx)(`option`,{value:e,children:hj(e,a)},e))]}),(0,h.jsxs)(`select`,{"aria-label":a(`logs.statusFilter`),className:`min-h-10 rounded-lg border border-[var(--border)] bg-[var(--input)] px-3`,onChange:e=>{f(e.target.value),c(1),v(null)},value:d,children:[(0,h.jsx)(`option`,{value:``,children:a(`logs.allStatuses`)}),dj.map(e=>(0,h.jsx)(`option`,{value:e,children:a(`logs.statuses.${e}`)},e))]})]})]}),(0,h.jsxs)(`div`,{className:`grid min-h-0 flex-1 gap-4 overflow-hidden lg:grid-cols-[minmax(240px,0.85fr)_minmax(0,1.4fr)]`,children:[(0,h.jsxs)(cb,{className:ob(`min-h-0 min-w-0 flex-col overflow-hidden p-0`,_?`hidden lg:flex`:`flex`),children:[(0,h.jsx)(`div`,{"aria-label":a(`logs.listRegion`),className:`min-h-0 flex-1 overflow-y-auto overscroll-contain focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--focus)]`,ref:y,role:`region`,tabIndex:0,children:C.isPending?(0,h.jsx)(`div`,{className:`p-5`,children:a(`common.loading`)}):C.isError?(0,h.jsx)(`div`,{className:`p-5 text-[var(--danger)]`,role:`alert`,children:yb(C.error,a)}):C.data?.entries.length?(0,h.jsx)(`div`,{className:`divide-y divide-[var(--border)]`,children:C.data.entries.map(e=>(0,h.jsxs)(`button`,{"aria-pressed":e.id===_,className:ob(`block w-full px-4 py-3 text-left hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--focus)]`,e.id===_&&`bg-[var(--accent-soft)]`),onClick:t=>{x.current=t.currentTarget,v(e.id)},type:`button`,children:[(0,h.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,h.jsx)(`span`,{className:`font-semibold`,children:hj(e.operation,a)}),(0,h.jsx)(db,{tone:mj(e.status),children:a(`logs.statuses.${e.status}`)})]}),(0,h.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-3 text-xs text-[var(--muted)]`,children:[(0,h.jsx)(`span`,{children:vb(e.startedAt,o.language)}),(0,h.jsx)(`span`,{children:pj(e.wallDurationMs??e.activeDurationMs,a)})]})]},e.id))}):(0,h.jsx)(`div`,{className:`p-5 text-[var(--muted)]`,children:a(`logs.empty`)})}),C.data?(0,h.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center justify-between gap-2 border-t border-[var(--border)] p-3`,children:[(0,h.jsx)(`span`,{className:`text-xs text-[var(--muted)]`,children:a(`logs.pageSummary`,{page:s,total:C.data.total})}),(0,h.jsxs)(`div`,{className:`flex gap-2`,children:[(0,h.jsx)(X,{disabled:s<=1||C.isFetching,onClick:()=>c(e=>Math.max(1,e-1)),type:`button`,variant:`secondary`,children:a(`history.previous`)}),(0,h.jsx)(X,{disabled:!C.data.hasNextPage||C.isFetching,onClick:()=>c(e=>e+1),type:`button`,variant:`secondary`,children:a(`history.next`)})]})]}):null]}),(0,h.jsxs)(cb,{className:ob(`min-h-0 min-w-0 flex-col overflow-hidden p-0`,_?`flex`:`hidden lg:flex`),children:[(0,h.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-b border-[var(--border)] p-3`,children:[(0,h.jsxs)(X,{className:`lg:hidden`,onClick:T,size:`compact`,type:`button`,variant:`ghost`,children:[(0,h.jsx)(_i,{size:16}),a(`logs.backToList`)]}),(0,h.jsx)(`span`,{className:`hidden text-sm font-semibold lg:inline`,children:a(`logs.detailRegion`)}),_?(0,h.jsx)(X,{"aria-label":a(`logs.refreshDetail`),className:`lg:hidden`,disabled:w.isFetching,onClick:()=>void w.refetch(),size:`icon`,type:`button`,variant:`ghost`,children:(0,h.jsx)(Ii,{size:16,className:ob(w.isFetching&&`animate-spin`)})}):null]}),(0,h.jsx)(`div`,{"aria-label":a(`logs.detailRegion`),className:`min-h-0 flex-1 overflow-y-auto overscroll-contain p-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--focus)]`,ref:b,role:`region`,tabIndex:0,children:_?w.isFetching&&!E?(0,h.jsx)(`div`,{children:a(`common.loading`)}):w.isError?(0,h.jsxs)(`div`,{className:`text-[var(--danger)]`,role:`alert`,children:[yb(w.error,a),(0,h.jsx)(X,{className:`mt-3`,disabled:w.isFetching,onClick:()=>void w.refetch(),type:`button`,variant:`secondary`,children:a(`common.retry`)})]}):E?(0,h.jsxs)(`div`,{className:`grid min-w-0 gap-5`,children:[(0,h.jsxs)(`div`,{children:[(0,h.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,h.jsx)(`h2`,{className:`text-lg font-semibold`,children:hj(E.operation,a)}),(0,h.jsx)(db,{tone:mj(E.status),children:a(`logs.statuses.${E.status}`)})]}),(0,h.jsxs)(`dl`,{className:`mt-4 grid gap-2 text-sm sm:grid-cols-2`,children:[(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:a(`logs.startedAt`)}),(0,h.jsx)(`dd`,{children:vb(E.startedAt,o.language)})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:a(`logs.completedAt`)}),(0,h.jsx)(`dd`,{children:E.completedAt?vb(E.completedAt,o.language):`—`})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:a(`logs.activeDuration`)}),(0,h.jsx)(`dd`,{children:pj(E.activeDurationMs,a)})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:a(`logs.wallDuration`)}),(0,h.jsx)(`dd`,{children:pj(E.wallDurationMs,a)})]}),E.targetProvider?(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:a(`logs.targetProvider`)}),(0,h.jsx)(`dd`,{className:`break-all font-mono text-xs`,children:E.targetProvider})]}):null]})]}),XA(E.operation,E.counts)?(0,h.jsx)(ZA,{afterOperation:!0}):null,[`sync`,`switch`,`watch`].includes(E.operation)?(0,h.jsx)(cj,{timing:E.fileUpdateTiming,pending:[`running`,`awaiting-confirmation`].includes(E.status)}):null,E.failedStage||E.failureCode||E.partialReason?(0,h.jsxs)(`dl`,{className:`grid gap-3 rounded-lg border border-[var(--warning)] bg-[var(--warning-soft)] p-3 text-sm`,children:[E.failedStage?(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{children:a(`operationResult.fields.failedStage`)}),(0,h.jsx)(`dd`,{children:KA(E.failedStage,a)})]}):null,E.failureCode?(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{children:a(`operationResult.fields.failureCode`)}),(0,h.jsx)(`dd`,{children:qA(E.failureCode,a)})]}):null,E.partialReason?(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{children:a(`operationResult.fields.partialReason`)}),(0,h.jsx)(`dd`,{children:a(`operationResult.partialReasons.${E.partialReason}`,{defaultValue:a(`global.partial`)})})]}):null]}):null,(0,h.jsx)(UA,{value:E.skipSummary}),!E.skipSummary&&E.retryRecommended?(0,h.jsx)(`p`,{className:`text-sm text-[var(--warning)]`,children:a(E.partialReason===`locked-session`?`operationResult.retryAfterSession`:`operationResult.retryFreshPlan`)}):null,(E.backupId||E.retryRecommended)&&(r||i)?E.profileId===t&&E.profileRevision!==void 0&&E.profileRevision===n?(0,h.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[E.retryRecommended&&i&&[`sync`,`switch`,`repair`,`watch`].includes(E.operation)?(0,h.jsx)(X,{onClick:()=>i(E.operation),type:`button`,variant:`secondary`,children:a(`operationResult.reviewOperation`)}):null,E.backupId&&r?(0,h.jsx)(X,{onClick:()=>r(E.backupId),type:`button`,variant:`secondary`,children:a(`operationResult.openBackupRestore`)}):null]}):(0,h.jsx)(`p`,{className:`text-sm text-[var(--muted)]`,children:a(`logs.profileMismatch`)}):null,O.length?(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:a(`logs.previewCounts`)}),(0,h.jsx)(`dl`,{className:`mt-2 grid gap-2 text-sm sm:grid-cols-2`,children:O.map(([e,t])=>(0,h.jsxs)(`div`,{className:`flex justify-between gap-3 rounded-lg border border-[var(--border)] px-3 py-2`,children:[(0,h.jsx)(`dt`,{children:a(`logs.previewCountLabels.${e}`)}),(0,h.jsx)(`dd`,{children:t})]},e))})]}):null,E.switchPlan?(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:a(`logs.switchPlan`)}),(0,h.jsxs)(`dl`,{className:`mt-2 grid gap-2 text-sm sm:grid-cols-2`,children:[(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:a(`logs.providerChange`)}),(0,h.jsxs)(`dd`,{className:`break-all font-mono text-xs`,children:[E.switchPlan.previousProvider,` → `,E.switchPlan.targetProvider]})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:a(`logs.rootModelChange`)}),(0,h.jsxs)(`dd`,{className:`break-all font-mono text-xs`,children:[E.switchPlan.previousRootModel??a(`logs.notSet`),` → `,E.switchPlan.targetRootModel??a(`logs.notSet`)]})]}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`dt`,{className:`text-[var(--muted)]`,children:a(`logs.modelMode`)}),(0,h.jsx)(`dd`,{children:a(`plan.modelModes.${E.switchPlan.modelMode}`)})]})]}),E.status===`partial`?(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--warning)]`,children:a(`logs.switchPlanPartial`)}):null]}):E.operation===`switch`?(0,h.jsx)(`p`,{className:`text-sm text-[var(--muted)]`,children:a(`logs.switchPlanUnavailable`)}):null,D.length?(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:a(`logs.counts`)}),(0,h.jsx)(`dl`,{className:`mt-2 grid gap-2 text-sm sm:grid-cols-2`,children:D.map(([e,t])=>(0,h.jsxs)(`div`,{className:`flex justify-between gap-3 rounded-lg border border-[var(--border)] px-3 py-2`,children:[(0,h.jsx)(`dt`,{children:a(`logs.countLabels.${e}`)}),(0,h.jsx)(`dd`,{children:t})]},e))})]}):null,(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:a(`logs.timeline`)}),(0,h.jsx)(`ol`,{className:`mt-3 grid gap-3`,children:E.stages.map((e,t)=>(0,h.jsxs)(`li`,{className:`rounded-lg border border-[var(--border)] p-3`,children:[(0,h.jsxs)(`div`,{className:`flex justify-between gap-3`,children:[(0,h.jsx)(`span`,{className:`font-medium`,children:KA(e.stage,a)}),(0,h.jsx)(`span`,{className:`text-sm text-[var(--muted)]`,children:pj(e.durationMs,a)})]}),(0,h.jsxs)(`div`,{className:`mt-1 text-xs text-[var(--muted)]`,children:[a(`logs.stageStatuses.${e.status}`,{defaultValue:a(`logs.unknownStage`)}),e.count===void 0?``:` · ${e.count}`,` · `,vb(e.startedAt,o.language),e.completedAt?` → ${vb(e.completedAt,o.language)}`:``]})]},`${e.stage}-${t}`))})]}),E.errorCode?(0,h.jsxs)(`div`,{className:`rounded-lg border border-[var(--danger)] bg-[var(--danger-soft)] p-3 text-sm`,role:`alert`,children:[(0,h.jsx)(`p`,{children:a(`errors.${E.errorCode}`,{defaultValue:a(`errors.fallback`)})}),E.errorReason?(0,h.jsxs)(`p`,{className:`mt-1 text-[var(--muted)]`,children:[a(`logs.errorReason`),`: `,a(`logs.errorReasons.${E.errorReason}`)]}):null]}):null,E.warnings.length?(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:a(`common.warnings`)}),(0,h.jsx)(`ul`,{className:`mt-2 list-disc pl-5 text-sm`,children:E.warnings.map((e,t)=>(0,h.jsx)(`li`,{children:xb(e,a)},`${t}-${e}`))})]}):null,(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:a(`logs.identifiers`)}),(0,h.jsxs)(`dl`,{className:`mt-3 grid gap-3 text-sm sm:grid-cols-2`,children:[(0,h.jsx)(gj,{label:a(`logs.logId`),value:E.id}),E.requestIds.map((e,t)=>(0,h.jsx)(gj,{label:`${a(`logs.requestId`)} ${t+1}`,value:e},e)),(0,h.jsx)(gj,{label:a(`logs.planId`),value:E.planId}),(0,h.jsx)(gj,{label:a(`logs.operationId`),value:E.operationId}),(0,h.jsx)(gj,{label:a(`logs.backupId`),value:E.backupId})]})]})]},E.id):(0,h.jsx)(`div`,{className:`text-sm text-[var(--muted)]`,role:`status`,children:a(`logs.detailUnavailable`)}):(0,h.jsx)(`div`,{className:`grid h-full place-items-center text-sm text-[var(--muted)]`,children:a(`logs.select`)})})]})]})]})}function vj(e,t,n){return t==null||t===``?n(`common.none`):typeof t==`boolean`?n(t?`common.yes`:`common.no`):e===`modelMode`&&typeof t==`string`?n(`plan.modelModes.${t}`,{defaultValue:t}):e===`targets`&&Array.isArray(t)?t.map(e=>n(`diagnostics.repairTargets.${String(e)}`,{defaultValue:String(e)})).join(`, `):Array.isArray(t)?n(`plan.items`,{count:t.length}):String(t)}function yj(e){let t=e.impact.repairPreview;return Array.isArray(t)?t.flatMap(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e;if(typeof t.sessionId!=`string`||!Array.isArray(t.changes))return[];let n=t.changes.flatMap(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e;return[`models`,`cwd`,`userEvent`].includes(String(t.target))&&typeof t.before==`string`&&typeof t.after==`string`?[{target:t.target,before:t.before,after:t.after}]:[]});return n.length?[{sessionId:t.sessionId,changes:n}]:[]}):[]}function bj(e,t){if(e.target.scope!==`selected`)return null;let n=e.target.sessionIds;return Array.isArray(n)&&n.every(e=>typeof e==`string`)?n:t.map(e=>e.sessionId)}function xj(e,t,n){if(e===`models`)return t;let r=t===`different`||t===`rollout-cwd`||t===`false`||t===`true`?t:null;return r?n(`plan.repairPreview.markers.${r}`):t}function Sj({plan:e,applying:t,cancelling:n,confirmDisabled:r=!1,currentModel:i,directSyncPhase:a=null,progress:o,repairSelectionPending:s=!1,repairProgress:c,repairSelectionFailed:l=!1,repairDraftChanged:u,refineRepairSessions:d,close:f,apply:p,cancel:g,restoreFocus:_}){let{t:v,i18n:y}=Dn(),b=e?v(`plan.operations.${e.operation}`,{defaultValue:e.operation}):``,x=e?v(`plan.titles.${e.operation}`,{defaultValue:v(`plan.title`)}):v(`plan.title`),S=e?v(`plan.confirmActions.${e.operation}`,{defaultValue:v(`common.confirm`)}):v(`common.confirm`),C=e?[[`provider`,v(`common.provider`)],...e.operation===`switch`?[]:[[`model`,v(`common.model`)]],[`modelMode`,v(`plan.fields.modelMode`)],[`targets`,v(`plan.fields.repairTargets`)],[`backupId`,v(`operationResult.backupId`)],[`restoreConfig`,v(`plan.fields.restoreConfig`)],[`restoreDatabase`,v(`plan.fields.restoreDatabase`)],[`restoreSessions`,v(`plan.fields.restoreSessions`)],[`allowSqliteHomeRelocation`,v(`plan.fields.relocation`)]].filter(([t])=>t in e.target):[],w=e?[[`rolloutFilesToChange`,v(`plan.fields.rolloutFiles`)],...e.operation===`repair`?[[`repairPreviewTotal`,v(`plan.fields.affectedSessions`)],[`sqliteRowsToChange`,v(`plan.fields.sqliteFields`)],[`sqliteModelRowsToChange`,v(`plan.fields.sqliteModels`)],[`sqliteCwdRowsToChange`,v(`plan.fields.sqliteCwd`)],[`sqliteUserEventRowsToChange`,v(`plan.fields.sqliteUserEvent`)]]:[[`sqliteRowsToChange`,v(`plan.fields.sqliteRows`)]],[`workspaceRootsToChange`,v(`plan.fields.workspaceSettings`)],[`stateDbFilesToChange`,v(`plan.fields.stateDbFiles`)],[`configFilesToChange`,v(`plan.fields.configFiles`)],[`lockedRolloutFiles`,v(`plan.fields.lockedRollouts`)]].filter(([t])=>t in e.impact):[],T=e?.operation===`switch`?`${vj(`model`,i,v)} → ${vj(`model`,e.target.model,v)}`:null,E=e?.impact.sessionActivity,D=E&&typeof E==`object`&&!Array.isArray(E)&&E.state===`checked`&&typeof E.count==`number`?E.count:v(`overview.usageUnknown`),O=e?.operation===`repair`&&Array.isArray(e.target.targets)&&e.target.targets.includes(`workspaceRoots`),ee=[`savedRoots`,`projectOrder`,`activeRoots`,`labels`,`openTargets`,`settingsBackup`].filter(t=>e?.operation===`repair`&&Array.isArray(e.impact.workspaceSettingsChangeKinds)&&e.impact.workspaceSettingsChangeKinds.includes(t)),k=(0,m.useMemo)(()=>e?.operation===`repair`?yj(e):[],[e]),A=(0,m.useMemo)(()=>e?.operation===`repair`?bj(e,k):null,[e,k]),[j,M]=(0,m.useState)(A);(0,m.useEffect)(()=>{M(A)},[e?.planId,A]);let N=e?.operation===`repair`&&!O?j===null!=(A===null)||JSON.stringify(j??[])!==JSON.stringify(A??[]):!1;(0,m.useEffect)(()=>{u?.(N)},[u,N]);let P=n=>{!e||O||s||t||M(n)};return(0,h.jsx)(fb,{closeDisabled:t||s,closeLabel:v(`common.close`),description:a?v(`sync.directHint`):e?`${b} · ${v(`plan.expires`)} ${vb(e.expiresAt,y.language)}`:void 0,footer:(0,h.jsxs)(m.Fragment,{children:[(0,h.jsx)(X,{disabled:t||s,onClick:f,type:`button`,variant:`secondary`,children:v(`common.close`)}),t?(0,h.jsx)(X,{disabled:n,onClick:g,type:`button`,variant:`danger`,children:v(n?`plan.cancelling`:`plan.cancelOperation`)}):(0,h.jsx)(X,{disabled:r||l||s||N,onClick:p,type:`button`,children:S})]}),onOpenChange:e=>{!e&&!t&&!s&&f()},open:!!(e||a),restoreFocus:_,title:a?v(a===`preparing`?`sync.preparingDirect`:`sync.runningDirect`):x,children:a?(0,h.jsxs)(cb,{"aria-live":`polite`,role:`status`,children:[(0,h.jsx)(`h3`,{className:`text-sm font-semibold`,children:v(`plan.progress`)}),(0,h.jsx)(`p`,{className:`mt-2 text-sm`,children:o?`${v(`plan.stages.${o.stage}`,{defaultValue:v(`common.processing`)})} · ${v(`plan.statuses.${o.status}`,{defaultValue:v(`common.processing`)})}${o.count===void 0?``:` · ${o.count}`}`:v(a===`preparing`?`sync.preparingDirect`:`plan.starting`)}),o?.progress===void 0?null:(0,h.jsx)(`progress`,{"aria-label":v(`plan.progress`),className:`mt-3 w-full`,max:1,value:o.progress}),n?(0,h.jsx)(`p`,{className:`mt-3 text-sm text-[var(--warning)]`,children:v(`plan.cancelPending`)}):null]}):e?(0,h.jsxs)(`div`,{className:`grid gap-4`,children:[(0,h.jsx)(UA,{value:e.impact.skipSummary}),(0,h.jsxs)(cb,{children:[(0,h.jsx)(`h3`,{className:`mb-2 text-sm font-semibold`,children:v(`plan.target`)}),(0,h.jsxs)(`dl`,{children:[T?(0,h.jsx)(Cb,{label:v(`plan.fields.rootModelChange`),value:T}):null,C.map(([t,n])=>(0,h.jsx)(Cb,{label:n,value:vj(t,e.target[t],v)},t))]})]}),e.operation===`repair`?(0,h.jsxs)(cb,{children:[(0,h.jsx)(`h3`,{className:`mb-2 text-sm font-semibold`,children:v(`plan.repairPreview.effectsTitle`)}),(0,h.jsx)(`ul`,{className:`mb-3 grid gap-2 text-sm text-[var(--muted)]`,children:[`models`,`cwd`,`userEvent`,`workspaceRoots`].filter(t=>Array.isArray(e.target.targets)&&e.target.targets.includes(t)).map(e=>(0,h.jsx)(`li`,{children:v(`diagnostics.repairTargetHints.${e}`)},e))}),(0,h.jsx)(`p`,{className:`mb-4 text-sm text-[var(--muted)]`,children:v(`plan.repairPreview.unchanged`)}),(0,h.jsx)(`h3`,{className:`mb-2 text-sm font-semibold`,children:v(`plan.repairPreview.title`)}),(0,h.jsx)(`p`,{className:`text-sm text-[var(--muted)]`,children:v(O?`plan.repairPreview.workspaceGlobal`:`plan.repairPreview.hint`)}),O?null:(0,h.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-3 text-sm`,children:[(0,h.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,h.jsx)(`input`,{checked:j===null,disabled:s||t,name:`repair-scope`,onChange:()=>P(null),type:`radio`}),v(`plan.repairPreview.all`)]}),(0,h.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,h.jsx)(`input`,{checked:j!==null,disabled:s||t||k.length===0,name:`repair-scope`,onChange:()=>P(j??[]),type:`radio`}),v(`plan.repairPreview.selected`)]})]}),k.length?(0,h.jsx)(`div`,{className:`mt-3 grid max-h-80 gap-2 overflow-y-auto overscroll-contain`,role:`region`,"aria-label":v(`plan.repairPreview.title`),tabIndex:0,children:k.map(e=>{let n=j?.includes(e.sessionId)??!1;return(0,h.jsxs)(`div`,{className:`rounded-[var(--radius-control)] border border-[var(--border)] bg-[var(--surface)] p-3 text-sm`,children:[(0,h.jsxs)(`label`,{className:`flex items-start gap-2`,children:[O?null:(0,h.jsx)(`input`,{"aria-label":v(`plan.repairPreview.selectSession`,{sessionId:e.sessionId}),checked:n,disabled:s||t,onChange:t=>{let n=j??[],r=t.target.checked?[...new Set([...n,e.sessionId])]:n.filter(t=>t!==e.sessionId);P(r)},type:`checkbox`}),(0,h.jsx)(`span`,{className:`break-all font-mono text-xs`,children:e.sessionId})]}),(0,h.jsx)(`ul`,{className:`mt-2 grid gap-1 text-xs text-[var(--muted)]`,children:e.changes.map((e,t)=>(0,h.jsxs)(`li`,{children:[v(`plan.repairPreview.changes.${e.target}`),`: `,xj(e.target,e.before,v),` → `,xj(e.target,e.after,v)]},`${t}-${e.target}`))})]},e.sessionId)})}):(0,h.jsx)(`p`,{className:`mt-3 text-sm text-[var(--muted)]`,children:v(`plan.repairPreview.none`)}),typeof e.impact.repairPreviewTotal==`number`?(0,h.jsxs)(`p`,{className:`mt-3 text-xs text-[var(--muted)]`,children:[v(`plan.repairPreview.total`,{count:e.impact.repairPreviewTotal}),e.impact.repairPreviewTruncated===!0?` · ${v(`plan.repairPreview.truncated`)}`:``]}):null,!O&&(N||l)?(0,h.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-3`,children:[(0,h.jsx)(`p`,{className:`text-sm font-medium text-[var(--warning)]`,role:`status`,children:v(`plan.repairPreview.selectionChanged`)}),(0,h.jsx)(X,{disabled:s||t||Array.isArray(j)&&j.length===0,onClick:()=>d?.(j),type:`button`,variant:`secondary`,children:v(`plan.repairPreview.update`)})]}):null,s?(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)(`p`,{className:`mt-3 text-sm font-medium text-[var(--warning)]`,role:`status`,children:v(`plan.repairPreview.regenerating`)}),(0,h.jsx)(Pb,{state:c})]}):null,l?(0,h.jsx)(`p`,{className:`mt-3 text-sm font-medium text-[var(--danger)]`,role:`alert`,children:v(`plan.repairPreview.refineFailed`)}):null]}):null,e.operation===`switch`?(0,h.jsx)(`p`,{className:`rounded-[var(--radius-control)] border border-[var(--border)] bg-[var(--surface)] p-3 text-sm text-[var(--muted)]`,children:v(`plan.historyModelsUnaffected`)}):null,(0,h.jsxs)(cb,{children:[(0,h.jsx)(`h3`,{className:`mb-2 text-sm font-semibold`,children:v(`plan.impact`)}),(0,h.jsxs)(`dl`,{children:[e.operation===`sync`||e.operation===`switch`?(0,h.jsx)(Cb,{label:v(`overview.locked`),value:D}):null,w.map(([t,n])=>(0,h.jsx)(Cb,{label:n,value:vj(t,e.impact[t],v)},t))]}),ee.length?(0,h.jsx)(`ul`,{className:`mt-3 list-disc space-y-1 pl-5 text-sm text-[var(--muted)]`,"aria-label":v(`plan.fields.workspaceSettings`),children:ee.map(e=>(0,h.jsx)(`li`,{children:v(`plan.workspaceChanges.${e}`)},e))}):null]}),e.impact.backupExpected===!0?(0,h.jsx)(`div`,{className:`rounded-[var(--radius-control)] border border-[var(--success)] bg-[var(--success-soft)] p-4 text-sm font-medium text-[var(--success)]`,children:v(`plan.backupExpected`)}):null,e.warnings.length?(0,h.jsxs)(`div`,{className:`rounded-lg border border-[var(--warning)] bg-[var(--warning-soft)] p-4`,children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:v(`common.warnings`)}),(0,h.jsx)(`ul`,{className:`mt-2 list-disc space-y-1 pl-5 text-sm`,children:e.warnings.map((e,t)=>(0,h.jsx)(`li`,{children:xb(e,v)},`${t}-${e}`))})]}):null,t?(0,h.jsxs)(cb,{"aria-live":`polite`,role:`status`,children:[(0,h.jsx)(`h3`,{className:`text-sm font-semibold`,children:v(`plan.progress`)}),(0,h.jsx)(`div`,{className:`mt-2 text-xs text-[var(--muted)]`,children:v(`plan.starting`)}),o?(0,h.jsxs)(`div`,{className:`mt-3 grid gap-2`,children:[(0,h.jsxs)(`div`,{className:`text-sm`,children:[v(`plan.stages.${o.stage}`,{defaultValue:v(`common.processing`)}),` · `,v(`plan.statuses.${o.status}`,{defaultValue:v(`common.processing`)}),o.count===void 0?``:` · ${o.count}`]}),o.progress===void 0?null:(0,h.jsx)(`progress`,{"aria-label":v(`plan.progress`),className:`w-full`,max:1,value:o.progress})]}):null,n?(0,h.jsx)(`p`,{className:`mt-3 text-sm text-[var(--warning)]`,children:v(`plan.cancelPending`)}):null]}):null,r&&!t?(0,h.jsx)(`p`,{className:`text-sm font-medium text-[var(--warning)]`,role:`status`,children:v(`plan.writeBlocked`)}):null,(0,h.jsx)(`p`,{className:`text-sm text-[var(--muted)]`,children:v(`plan.exactApply`)})]}):null})}function Cj({disabled:e,prepare:t,directSync:n,embedded:r=!1}){let{t:i}=Dn(),a=jo({resolver:Vo(xp),defaultValues:{}}),o=(0,m.useRef)(null),s=(0,m.useRef)(null);return(0,h.jsxs)(m.Fragment,{children:[r?null:(0,h.jsx)(Sb,{title:i(`sync.title`),subtitle:i(`sync.subtitle`)}),(0,h.jsxs)(cb,{className:r?`min-w-0 p-4`:`max-w-2xl`,children:[r?(0,h.jsxs)(`div`,{className:`mb-3`,children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:i(`sync.title`)}),(0,h.jsx)(`p`,{className:`mt-1 text-sm text-[var(--muted)]`,children:i(`sync.subtitle`)})]}):null,(0,h.jsxs)(`form`,{className:`grid gap-5`,onSubmit:a.handleSubmit(e=>t(e,o.current)),children:[(0,h.jsxs)(`div`,{className:`flex flex-wrap gap-3`,children:[(0,h.jsxs)(X,{disabled:e||a.formState.isSubmitting,ref:o,type:`submit`,variant:`secondary`,children:[(0,h.jsx)(Ki,{size:17}),i(`sync.prepare`)]}),n?(0,h.jsxs)(X,{disabled:e||a.formState.isSubmitting,onClick:()=>void a.handleSubmit(e=>n(e,s.current))(),ref:s,type:`button`,children:[(0,h.jsx)(Ki,{size:17}),i(`sync.direct`)]}):null]}),n?(0,h.jsx)(`p`,{className:`text-sm text-[var(--muted)]`,children:i(`sync.directHint`)}):null]}),(0,h.jsx)(`div`,{className:`mt-3`,children:(0,h.jsx)(ZA,{})})]})]})}function wj({disabled:e,providers:t,currentProvider:n,recentSuccessfulProviders:r=[],profileKey:i,prepare:a,embedded:o=!1}){let{t:s}=Dn(),c=(0,m.useRef)(null),l=(0,m.useRef)(i),u=n||t[0]||`openai`,d=[...new Set([`openai`,...t,...n?[n]:[]])],f=jo({resolver:Vo(Sp),defaultValues:{provider:u,modelMode:`provider-default`,model:``}}),p=f.watch(`provider`),g=f.watch(`modelMode`);return(0,m.useEffect)(()=>{if(l.current!==i){l.current=i,f.reset({provider:u,modelMode:`provider-default`,model:``});return}n&&(!f.getFieldState(`provider`).isDirty||f.getValues(`provider`)===n)&&f.resetField(`provider`,{defaultValue:n})},[n,u,f,i]),(0,m.useEffect)(()=>{g!==`explicit`&&f.setValue(`model`,``)},[f,g]),(0,h.jsxs)(m.Fragment,{children:[o?null:(0,h.jsx)(Sb,{title:s(`switchPage.title`),subtitle:s(`switchPage.subtitle`)}),(0,h.jsxs)(cb,{className:o?`min-w-0`:`max-w-2xl`,children:[o?(0,h.jsxs)(`div`,{className:`mb-5`,children:[(0,h.jsx)(`h3`,{className:`font-semibold`,children:s(`switchPage.title`)}),(0,h.jsx)(`p`,{className:`mt-1 text-sm text-[var(--muted)]`,children:s(`switchPage.subtitle`)})]}):null,(0,h.jsxs)(`form`,{className:`grid gap-5`,onSubmit:f.handleSubmit(e=>a(e,c.current)),children:[r.length?(0,h.jsxs)(`div`,{className:`grid gap-2`,children:[(0,h.jsx)(`span`,{className:`text-sm font-medium`,children:s(`switchPage.recentSuccessful`)}),(0,h.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:r.map(e=>(0,h.jsx)(X,{onClick:()=>f.setValue(`provider`,e,{shouldDirty:!0,shouldTouch:!0}),size:`compact`,type:`button`,variant:`secondary`,children:e},e))})]}):null,(0,h.jsx)(ub,{error:f.formState.errors.provider?s(`validation.provider`):void 0,label:s(`switchPage.provider`),children:(0,h.jsx)(lb,{list:`configured-providers`,...f.register(`provider`)})}),(0,h.jsx)(`datalist`,{id:`configured-providers`,children:d.map(e=>(0,h.jsx)(`option`,{value:e},e))}),(0,h.jsx)(ub,{error:f.formState.errors.modelMode?s(`validation.model`):void 0,label:s(`switchPage.modelMode`),children:(0,h.jsxs)(`select`,{"aria-describedby":`switch-model-mode-description`,className:`min-h-10 rounded-lg border border-[var(--border)] bg-[var(--input)] px-3`,...f.register(`modelMode`),children:[(0,h.jsx)(`option`,{value:`provider-default`,children:s(`switchPage.providerDefault`)}),(0,h.jsx)(`option`,{value:`keep-root-model`,children:s(`switchPage.keepModel`)}),(0,h.jsx)(`option`,{value:`explicit`,children:s(`switchPage.explicitModel`)})]})}),(0,h.jsxs)(`div`,{className:`rounded-lg border border-[var(--border)] bg-[var(--surface)] p-3 text-sm text-[var(--muted)]`,id:`switch-model-mode-description`,children:[(0,h.jsx)(`p`,{children:s(`switchPage.modelModeDescriptions.${g}`,{provider:p||s(`common.provider`)})}),(0,h.jsx)(`p`,{className:`mt-2`,children:s(`switchPage.historyModelHint`)})]}),g===`explicit`?(0,h.jsx)(ub,{error:f.formState.errors.model?s(`validation.model`):void 0,label:s(`switchPage.model`),children:(0,h.jsx)(lb,{...f.register(`model`)})}):null,(0,h.jsxs)(X,{disabled:e||f.formState.isSubmitting,ref:c,type:`submit`,children:[(0,h.jsx)(Ri,{size:17}),s(`switchPage.prepare`)]})]})]})]})}function Tj({title:e,counts:t,current:n}){let r=t&&typeof t==`object`&&!Array.isArray(t)?t:{},i=new Map;for(let e of[`sessions`,`archived_sessions`]){let t=r[e];if(!(!t||typeof t!=`object`||Array.isArray(t)))for(let[e,n]of Object.entries(t))typeof n==`number`&&i.set(e,(i.get(e)??0)+n)}let a=[...i.entries()].sort((e,t)=>t[1]-e[1]),o=a.reduce((e,[,t])=>e+t,0);return(0,h.jsxs)(cb,{className:`min-w-0 p-4`,children:[(0,h.jsxs)(`div`,{className:`mb-3 flex items-center justify-between gap-2`,children:[(0,h.jsx)(`h2`,{className:`font-semibold`,children:e}),(0,h.jsx)(db,{children:o})]}),(0,h.jsx)(`div`,{className:`grid gap-3`,children:a.length===0?(0,h.jsx)(`span`,{className:`text-sm text-[var(--muted)]`,children:`—`}):a.map(([e,t])=>(0,h.jsxs)(`div`,{children:[(0,h.jsxs)(`div`,{className:`mb-1 flex justify-between text-sm`,children:[(0,h.jsx)(`span`,{className:`font-medium`,children:e}),(0,h.jsx)(`span`,{children:t})]}),(0,h.jsx)(`progress`,{"aria-label":`${e}: ${t}`,className:ob(`h-2 w-full overflow-hidden rounded-full`,e===n?`accent-[var(--accent)]`:`accent-[var(--muted)]`),max:Math.max(o,1),value:t})]},e))})]})}function Ej(e,t,n){return n(t?`overview.sources.profile`:e===`profile`||e===`cli`?`overview.sources.explicit`:e===`config`||e===`env`||e==="default"?`overview.sources.${e}`:`overview.sources.unknown`)}function Dj({status:e,loading:t,refresh:n,profileName:r,profileKey:i,providers:a,recentSuccessfulProviders:o,sqliteHomeConfigured:s,writeDisabled:c,prepareSync:l,directSync:u,prepareSwitch:d,manageStorage:f,retentionCount:p=2}){let{t:g,i18n:_}=Dn(),v=JA(e)&&!e.statusReadBlocked,y=v&&!e.statusReadBlocked&&!e.operationInProgress&&e.sessionActivity?.state===`checked`,b=YA(e);return(0,h.jsxs)(m.Fragment,{children:[(0,h.jsx)(Sb,{title:g(`overview.title`),subtitle:g(`overview.subtitle`),action:(0,h.jsxs)(X,{disabled:t,onClick:n,type:`button`,variant:`secondary`,children:[(0,h.jsx)(Ii,{className:ob(t&&`animate-spin`),size:16}),g(`common.refresh`)]})}),(0,h.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-4`,children:[(0,h.jsxs)(cb,{className:`min-w-0 p-4`,children:[(0,h.jsx)(`div`,{className:`text-sm text-[var(--muted)]`,children:g(`common.provider`)}),(0,h.jsx)(`div`,{className:`mt-1 break-words text-xl font-bold`,children:v?e.currentProvider:`—`})]}),(0,h.jsxs)(cb,{className:`min-w-0 p-4`,children:[(0,h.jsx)(`div`,{className:`text-sm text-[var(--muted)]`,children:g(`overview.alignment`)}),(0,h.jsxs)(`div`,{className:`mt-1 flex items-center gap-2 text-lg font-bold`,children:[b===`aligned`?(0,h.jsx)(xi,{className:`shrink-0 text-[var(--success)]`,size:20}):b===`notAligned`?(0,h.jsx)(Gi,{className:`shrink-0 text-[var(--warning)]`,size:20}):null,g(b===`unknown`?t&&!v?`ux.reading`:`ux.unknown`:`overview.${b}`)]})]}),(0,h.jsxs)(cb,{className:`min-w-0 p-4`,children:[(0,h.jsx)(`div`,{className:`text-sm text-[var(--muted)]`,children:g(`overview.backupCount`)}),(0,h.jsx)(`div`,{className:`mt-1 text-xl font-bold`,children:v?e.backupSummary.count:`—`}),v?(0,h.jsx)(`div`,{className:`text-xs text-[var(--muted)]`,children:_b(e.backupSummary.totalBytes)}):null]}),(0,h.jsxs)(cb,{className:`min-w-0 p-4`,children:[(0,h.jsx)(`div`,{className:`text-sm text-[var(--muted)]`,children:g(`overview.locked`)}),(0,h.jsx)(`div`,{className:`mt-1 text-xl font-bold`,children:y?e.sessionActivity?.count:g(`overview.usageUnknown`)})]})]}),v&&!e.rolloutScanComplete?(0,h.jsx)(`p`,{className:`mt-3 text-sm text-[var(--warning)]`,role:`status`,children:g(`skips.incomplete`)}):null,(0,h.jsx)(UA,{value:e?.skipSummary}),t&&v?(0,h.jsx)(`p`,{className:`mt-2 text-xs text-[var(--muted)]`,role:`status`,children:g(`ux.previousSnapshot`)}):null,v?(0,h.jsxs)(`div`,{className:`mt-4 grid gap-4 lg:grid-cols-2`,children:[(0,h.jsx)(Tj,{counts:e.rolloutCounts,current:e.currentProvider,title:g(`overview.rollout`)}),(0,h.jsx)(Tj,{counts:e.sqliteCounts,current:e.currentProvider,title:g(`overview.sqlite`)})]}):null,(0,h.jsxs)(`section`,{"aria-labelledby":`provider-operations`,className:`mt-4`,children:[(0,h.jsx)(`h2`,{className:`sr-only`,id:`provider-operations`,children:g(`overview.operations`)}),(0,h.jsxs)(`div`,{className:`grid items-start gap-4 lg:grid-cols-2`,"data-testid":`overview-storage-sync`,children:[(0,h.jsxs)(cb,{className:`min-w-0 p-4`,children:[(0,h.jsxs)(`dl`,{className:`[&>div]:py-2 sm:[&>div]:grid-cols-[140px_minmax(0,1fr)]`,children:[(0,h.jsx)(Cb,{label:g(`overview.profile`),value:r}),(0,h.jsx)(Cb,{label:g(`overview.codexHomeSource`),value:e?.displayPaths?(0,h.jsx)(`span`,{className:`select-text break-all`,children:e.displayPaths.codexHome}):Ej(e?.codexHomeSource,!0,g)}),(0,h.jsx)(Cb,{label:g(`overview.sqliteHomeSource`),value:e?.displayPaths?(0,h.jsx)(`span`,{className:`select-text break-all`,children:e.displayPaths.sqliteHome}):Ej(e?.sqliteHomeSource,s,g)}),e?.displayPaths?(0,h.jsx)(Cb,{label:g(`overview.stateDbPath`),value:e.displayPaths.stateDbPath?(0,h.jsx)(`span`,{className:`select-text break-all`,children:e.displayPaths.stateDbPath}):g(`overview.stateDbMissing`)}):null,(0,h.jsx)(Cb,{label:g(`overview.snapshot`),value:vb(e?.snapshotAt,_.language)})]}),(0,h.jsx)(X,{className:`mt-4`,onClick:f,type:`button`,variant:`secondary`,children:g(`overview.manageStorage`)})]}),(0,h.jsxs)(`div`,{className:`min-w-0`,children:[(0,h.jsx)(Cj,{directSync:u,disabled:c,embedded:!0,prepare:l}),(0,h.jsx)(`p`,{className:`mt-3 text-sm text-[var(--muted)]`,children:g(`backupPolicy.operationHint`,{count:p})})]})]}),(0,h.jsx)(`div`,{className:`mt-4`,children:(0,h.jsx)(wj,{profileKey:i,currentProvider:v?e.currentProvider:void 0,disabled:c,embedded:!0,prepare:d,providers:a,recentSuccessfulProviders:o})})]})]})}function Oj({profiles:e,selectedProfileId:t,refresh:n,selectProfile:r,host:i,canManage:a,revealPaths:o,surface:s}){let{t:c}=Dn(),l=hb(),u=s===`desktop`,[d,f]=(0,m.useState)(null),[p,g]=(0,m.useState)(null),[_,v]=(0,m.useState)(null),[y,b]=(0,m.useState)(`inherit`),x=jo({defaultValues:{profileId:``,name:``,codexHome:``,sqliteHome:``}});(0,m.useEffect)(()=>{x.reset(d?{profileId:d.id,name:d.name,codexHome:d.codexHome??``,sqliteHome:d.sqliteHome??``}:{profileId:``,name:``,codexHome:``,sqliteHome:``}),g(null),v(null),b(d?.sqliteHomeConfigured?`preserve`:`inherit`)},[d,x]);let S=async e=>{if(!i.selectProfileDirectory)return;let t=await i.selectProfileDirectory(e);if(t.status!==`selected`)return;let n={token:t.token,displayName:t.displayName};e===`codex-home`?g(n):(v(n),b(`selected`))},C=st({mutationFn:async e=>{if(!a||!i.saveProfile)throw Error(c(`profiles.unavailable`));if(!e.name.trim())throw Error(c(`validation.required`));if(u){if(!d&&!p)throw Error(c(`profiles.selectCodexRequired`));return i.saveProfile({name:e.name,...d?{profileId:d.id,profileRevision:d.revision}:{},...p?{codexHomeSelectionToken:p.token}:{},sqliteHomeMode:y,...kj(y,_)})}return i.saveProfile({...e,...d?{profileRevision:d.revision}:{}})},onSuccess:async e=>{await n(),r(e.id),f(null),x.reset(),l.push({title:c(`profiles.saved`),tone:`success`})},onError:e=>l.push({title:c(`global.failed`),description:yb(e,c),tone:`danger`})}),w=st({mutationFn:e=>{if(!a||!i.deleteProfile)throw Error(c(`profiles.unavailable`));return i.deleteProfile(e.id,e.revision)},onSuccess:async(e,i)=>{i.id===t&&r(`default`),await n(),f(null),l.push({title:c(`profiles.deleted`),tone:`success`})},onError:e=>l.push({title:c(`global.failed`),description:yb(e,c),tone:`danger`})});return(0,h.jsxs)(m.Fragment,{children:[(0,h.jsx)(Sb,{title:c(`profiles.title`),subtitle:c(`profiles.subtitle`)}),(0,h.jsxs)(`div`,{className:ob(`grid min-w-0 gap-4`,a&&`xl:grid-cols-[minmax(0,1fr)_420px]`),children:[(0,h.jsxs)(cb,{className:`min-w-0`,children:[(0,h.jsx)(`div`,{className:`grid gap-3`,children:e.map(e=>{let n=(0,h.jsxs)(m.Fragment,{children:[(0,h.jsxs)(`div`,{className:`flex min-w-0 flex-wrap justify-between gap-2`,children:[(0,h.jsx)(`span`,{className:`min-w-0 truncate font-semibold`,children:bb(e,c)}),(0,h.jsxs)(`span`,{className:`flex flex-wrap gap-1`,children:[e.id===t?(0,h.jsx)(db,{tone:`success`,children:c(`ux.currentProfile`)}):null,e.id==="default"?(0,h.jsx)(db,{children:c(`profiles.managed`)}):null]})]}),u?null:(0,h.jsx)(`div`,{className:`mt-2 font-mono text-xs text-[var(--muted)]`,children:e.id}),o&&e.codexHome?(0,h.jsx)(`div`,{className:`mt-1 max-w-full truncate font-mono text-xs text-[var(--muted)]`,children:e.codexHome}):(0,h.jsx)(`div`,{className:`mt-1 text-xs text-[var(--muted)]`,children:c(`profiles.pathManaged.${s}`)})]});return!a||e.id==="default"?(0,h.jsx)(`div`,{className:`min-w-0 max-w-full overflow-hidden rounded-lg border border-[var(--border)] p-4 text-left`,children:n},e.id):(0,h.jsx)(`button`,{className:ob(`min-w-0 max-w-full overflow-hidden rounded-lg border p-4 text-left`,d?.id===e.id?`border-[var(--accent)] bg-[var(--accent-soft)]`:`border-[var(--border)] hover:bg-[var(--surface-hover)]`),onClick:()=>f(e),type:`button`,children:n},e.id)})}),a?null:(0,h.jsx)(`p`,{className:`mt-4 text-xs text-[var(--muted)]`,children:c(`profiles.readOnly`)})]}),a?(0,h.jsxs)(cb,{className:`min-w-0`,children:[(0,h.jsxs)(`form`,{className:`grid min-w-0 gap-4`,onSubmit:x.handleSubmit(e=>C.mutateAsync(e)),children:[u?null:(0,h.jsx)(ub,{label:c(`profiles.id`),children:(0,h.jsx)(lb,{disabled:!!d,...x.register(`profileId`,{required:!0})})}),(0,h.jsx)(ub,{label:c(`profiles.name`),children:(0,h.jsx)(lb,{...x.register(`name`,{required:!0,maxLength:120})})}),u?(0,h.jsxs)(m.Fragment,{children:[(0,h.jsx)(ub,{label:c(`profiles.codexHome`),children:(0,h.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,h.jsx)(X,{onClick:()=>void S(`codex-home`),type:`button`,variant:`secondary`,children:c(`profiles.chooseFolder`)}),(0,h.jsx)(`span`,{className:`truncate text-sm text-[var(--muted)]`,children:p?.displayName??c(d?`profiles.keepCurrent`:`profiles.notSelected`)})]})}),(0,h.jsx)(ub,{label:c(`profiles.sqliteHome`),children:(0,h.jsxs)(`div`,{className:`grid gap-2`,children:[(0,h.jsxs)(`select`,{className:`h-10 rounded-lg border border-[var(--border)] bg-[var(--surface)] px-3`,onChange:e=>b(e.target.value),value:y,children:[d?(0,h.jsx)(`option`,{value:`preserve`,children:c(`profiles.keepCurrent`)}):null,(0,h.jsx)(`option`,{value:`inherit`,children:c(`profiles.inheritSqlite`)}),(0,h.jsx)(`option`,{value:`selected`,children:c(`profiles.customSqlite`)})]}),y===`selected`?(0,h.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,h.jsx)(X,{onClick:()=>void S(`sqlite-home`),type:`button`,variant:`secondary`,children:c(`profiles.chooseFolder`)}),(0,h.jsx)(`span`,{className:`truncate text-sm text-[var(--muted)]`,children:_?.displayName??c(`profiles.notSelected`)})]}):null]})})]}):(0,h.jsxs)(m.Fragment,{children:[(0,h.jsx)(ub,{label:c(`profiles.codexHome`),children:(0,h.jsx)(lb,{...x.register(`codexHome`,{required:!0})})}),(0,h.jsx)(ub,{label:c(`profiles.sqliteHome`),children:(0,h.jsx)(lb,{...x.register(`sqliteHome`)})})]}),(0,h.jsxs)(`div`,{className:`flex flex-wrap gap-3`,children:[(0,h.jsx)(X,{disabled:C.isPending||u&&y===`selected`&&!_,type:`submit`,children:c(d?`profiles.update`:`profiles.create`)}),d?(0,h.jsx)(X,{disabled:w.isPending,onClick:()=>w.mutate(d),type:`button`,variant:`danger`,children:c(`common.delete`)}):null]})]}),u&&d&&i.revealProfileDirectory?(0,h.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-2`,children:[(0,h.jsx)(X,{onClick:()=>void i.revealProfileDirectory?.(d.id,d.revision,`codex-home`),type:`button`,variant:`ghost`,children:c(`profiles.revealCodex`)}),d.sqliteHomeConfigured?(0,h.jsx)(X,{onClick:()=>void i.revealProfileDirectory?.(d.id,d.revision,`sqlite-home`),type:`button`,variant:`ghost`,children:c(`profiles.revealSqlite`)}):null]}):null,(0,h.jsx)(`p`,{className:`mt-4 text-xs text-[var(--muted)]`,children:c(`profiles.defaultManaged`)})]}):null]})]})}function kj(e,t){return e===`selected`&&t?{sqliteHomeSelectionToken:t.token}:{}}function Aj(e){return e?`watches`in e?e.watches.find(e=>e.status!==`stopped`)??e.watches[0]??null:e:null}function jj(e){return[`watch-status`,e.id,e.revision]}function Mj({props:e,profile:t,capabilities:n,recoveryBlocked:r,writeBlocked:i,isWatchTerminal:a,retentionCount:o=2}){let{t:s,i18n:c}=Dn(),l=_(),[u,d]=(0,m.useState)(e.preferences.getTheme()??e.initialTheme),f=rt({queryKey:jj(t),queryFn:({signal:n})=>e.core.getWatchStatus({profile:gb(t)},{signal:n}),enabled:n.watch}),p=Aj(f.data),g=(e,t)=>{e.status!==`stopped`&&a?.(e.watchId)||(l.setQueriesData({queryKey:[`watch-status`]},t=>t&&(`watches`in t?{...t,watches:t.watches.map(t=>t.watchId===e.watchId?e:t)}:t.watchId===e.watchId?e:t)),l.setQueryData(jj(t),e))},v=st({mutationFn:t=>e.core.startWatch({profile:gb(t),includeStateDb:!0,keepCount:o}),onSuccess:g}),y=st({mutationFn:({watchId:t})=>e.core.stopWatch({watchId:t}),onSuccess:(e,t)=>g(e,t.profile)}),b=e=>e?.id===t.id&&e.revision===t.revision,x=f.error??(b(v.variables)?v.error:null)??(b(y.variables?.profile)?y.error:null),S=rt({queryKey:[`desktop-update-status`],queryFn:({signal:t})=>e.host.getUpdateStatus?.(t),enabled:n.viewUpdateStatus&&!!e.host.getUpdateStatus}),C=n.watch||n.viewUpdateStatus&&!!e.host.getUpdateStatus,w=f.isFetching||S.isFetching,T=async()=>{await Promise.all([n.watch?f.refetch():Promise.resolve(),n.viewUpdateStatus&&e.host.getUpdateStatus?S.refetch():Promise.resolve()])},E=e=>l.setQueryData([`desktop-update-status`],e),D=st({mutationFn:()=>e.host.checkForUpdates?.()??Promise.reject(Error(`Update check unavailable.`)),onSuccess:E}),O=st({mutationFn:()=>e.host.downloadUpdate?.()??Promise.reject(Error(`Update download unavailable.`)),onSuccess:E}),ee=st({mutationFn:()=>e.host.installUpdate?.()??Promise.reject(Error(`Update install unavailable.`)),onSuccess:E}),k=st({mutationFn:({version:t,ignored:n})=>e.host.setUpdateReminder?.(t,n)??Promise.reject(Error(`Update preference unavailable.`)),onSuccess:E}),A=S.isError||D.isError||O.isError||ee.isError,j=D.isPending||O.isPending||ee.isPending||k.isPending,M=async t=>{e.preferences.setLocale(t),await c.changeLanguage(t)},N=t=>{d(t),e.preferences.setTheme(t),document.documentElement.dataset.theme=t};return(0,h.jsxs)(m.Fragment,{children:[(0,h.jsx)(Sb,{action:C?(0,h.jsxs)(X,{disabled:w,onClick:()=>void T(),type:`button`,variant:`secondary`,children:[(0,h.jsx)(Ii,{className:ob(w&&`animate-spin`),size:16}),s(`common.refresh`)]}):void 0,title:s(`settings.title`),subtitle:s(`settings.subtitle.${e.surface}`)}),(0,h.jsxs)(`div`,{className:`grid gap-4 lg:grid-cols-2`,children:[(0,h.jsxs)(cb,{children:[(0,h.jsx)(ub,{label:s(`settings.language`),children:(0,h.jsxs)(`select`,{className:`min-h-10 rounded-lg border border-[var(--border)] bg-[var(--input)] px-3`,onChange:e=>void M(e.target.value),value:c.language===`zh-CN`?`zh-CN`:`en`,children:[(0,h.jsx)(`option`,{value:`zh-CN`,children:`简体中文`}),(0,h.jsx)(`option`,{value:`en`,children:`English`})]})}),(0,h.jsxs)(`div`,{className:`mt-3 flex items-center gap-2 text-xs text-[var(--muted)]`,children:[(0,h.jsx)(Mi,{size:15}),s(`settings.languageHint`)]})]}),(0,h.jsx)(cb,{children:(0,h.jsxs)(`fieldset`,{children:[(0,h.jsx)(`legend`,{className:`mb-1.5 text-sm font-medium text-[var(--text)]`,children:s(`settings.theme`)}),(0,h.jsx)(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-3`,children:[`system`,`light`,`dark`].map(e=>(0,h.jsxs)(X,{"aria-pressed":u===e,onClick:()=>N(e),type:`button`,variant:u===e?`primary`:`secondary`,children:[e===`system`?(0,h.jsx)(wi,{size:16}):e===`light`?(0,h.jsx)(Ui,{size:16}):(0,h.jsx)(Pi,{size:16}),s(`settings.${e}`)]},e))})]})}),n.watch?(0,h.jsxs)(cb,{children:[(0,h.jsx)(`h2`,{className:`font-semibold`,children:s(`settings.watch`)}),(0,h.jsx)(`p`,{className:`mt-1 text-sm text-[var(--muted)]`,children:s(`settings.watchHint`)}),(0,h.jsxs)(`div`,{className:`mt-3 flex items-center justify-between gap-3`,children:[(0,h.jsx)(db,{tone:p?.status===`running`?`success`:`neutral`,children:f.isPending?s(`common.loading`):f.isError?s(`common.unknown`):p?s(`settings.watchStatuses.${p.status}`,{defaultValue:s(`common.unknown`)}):s(`settings.watchStatuses.stopped`)}),p?.status===`running`?(0,h.jsx)(X,{disabled:!f.isSuccess||f.isFetching||y.isPending&&b(y.variables?.profile),onClick:()=>y.mutate({watchId:p.watchId,profile:t}),type:`button`,variant:`secondary`,children:s(`settings.watchStop`)}):(0,h.jsxs)(X,{disabled:v.isPending&&b(v.variables)||r||i||!f.isSuccess||f.isFetching||p?.status===`stopping`,onClick:()=>v.mutate(t),type:`button`,children:[(0,h.jsx)(Fi,{size:16}),s(`settings.watchStart`)]})]}),x?(0,h.jsx)(`p`,{className:`mt-3 text-xs text-[var(--danger)]`,role:`alert`,children:yb(x,s)}):null,r&&p?.status!==`running`?(0,h.jsx)(`p`,{className:`mt-3 text-xs text-[var(--danger)]`,children:s(`settings.watchRecoveryBlocked`)}):null]}):null,n.viewUpdateStatus&&e.host.getUpdateStatus?(0,h.jsxs)(cb,{children:[(0,h.jsx)(`h2`,{className:`font-semibold`,children:s(`settings.update`)}),S.data?.currentVersion?(0,h.jsx)(`p`,{className:`mt-2 text-sm`,children:s(`settings.updateCurrentVersion`,{version:S.data.currentVersion})}):null,(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:s(S.data?.mode===`manual`?`settings.updateManualHint`:`settings.updateAutomaticHint`)}),(0,h.jsxs)(`div`,{className:`mt-3`,children:[(0,h.jsx)(db,{tone:S.data?.state===`error`||S.data?.installBlockedReason?`warning`:S.data?.state===`downloaded`?`success`:`neutral`,children:S.isPending?s(`common.loading`):S.data?s(`settings.updateStatus.${S.data.state}`):s(`common.unknown`)}),S.data?.version?(0,h.jsx)(`p`,{className:`mt-3 text-sm`,children:s(`settings.updateVersion`,{version:S.data.version})}):null,S.data?.reminderIgnored?(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,role:`status`,children:s(`settings.updateIgnored`)}):null,S.data?.progressPercent===void 0?null:(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:s(`settings.updateProgress`,{percent:S.data.progressPercent})}),S.data?.reason?(0,h.jsx)(`p`,{className:`mt-3 text-sm text-[var(--muted)]`,children:s(`settings.updateReason.${S.data.reason}`)}):null,S.data?.installBlockedReason?(0,h.jsx)(`p`,{className:`mt-3 text-sm text-[var(--danger)]`,children:s(`settings.updateBlocked.${S.data.installBlockedReason}`)}):null,(0,h.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-2`,children:[A?(0,h.jsx)(`p`,{className:`w-full text-sm text-[var(--danger)]`,role:`alert`,children:s(`settings.updateRequestFailed`)}):null,k.isError?(0,h.jsx)(`p`,{className:`w-full text-sm text-[var(--danger)]`,role:`alert`,children:s(`settings.updateReminderFailed`)}):null,S.data&&[`idle`,`not-available`,`error`,`available`].includes(S.data.state)&&e.host.checkForUpdates?(0,h.jsx)(X,{disabled:j,onClick:()=>D.mutate(),type:`button`,variant:`secondary`,children:D.isPending?s(`settings.updateStatus.checking`):s(`settings.updateCheck`)}):null,S.data?.state===`available`&&e.host.downloadUpdate?(0,h.jsx)(X,{disabled:j,onClick:()=>O.mutate(),type:`button`,children:s(S.data.mode===`manual`?`settings.updateOpenDownload`:`settings.updateDownload`)}):null,S.data?.state===`downloaded`&&e.host.installUpdate?(0,h.jsx)(X,{disabled:!S.data.installAllowed||j||i||r||p?.status===`running`,onClick:()=>ee.mutate(),type:`button`,children:s(`settings.updateInstall`)}):null,S.data?.version&&[`available`,`downloaded`].includes(S.data.state)&&e.host.setUpdateReminder?(0,h.jsx)(X,{disabled:j,onClick:()=>k.mutate({version:S.data.version,ignored:!S.data.reminderIgnored}),type:`button`,variant:`secondary`,children:s(S.data.reminderIgnored?`settings.updateRestoreReminder`:`settings.updateIgnore`)}):null]})]})]}):null,n.forgetBrowser?(0,h.jsxs)(cb,{children:[(0,h.jsx)(`h2`,{className:`font-semibold`,children:s(`settings.forget`)}),(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:s(`settings.forgetHint`)}),(0,h.jsx)(X,{className:`mt-4`,onClick:()=>void(e.onForgetBrowser?.()??e.host.forgetBrowser?.()),type:`button`,variant:`danger`,children:s(`settings.forget`)})]}):null]})]})}function Nj(e){try{let t=e.getBackupRetention?.();return bp.safeParse(t).success?t:2}catch{return 2}}function Pj(e,t){let n=`${t}.backup.retention`;return{getBackupRetention(){let t=e.getItem(n);if(!t||!/^\d{1,4}$/.test(t))return null;let r=Number(t);return bp.safeParse(r).success?r:null},setBackupRetention(t){bp.parse(t),e.setItem(n,String(t))}}}var Fj=Object.freeze({sync:!0,switchProvider:!0,repair:!0,restore:!0,pruneBackups:!0,watch:!0,manageProfiles:!0,revealProfilePaths:!0,forgetBrowser:!0,exportDiagnostics:!0,viewUpdateStatus:!0,operationLogs:!1});Object.freeze({sync:!1,switchProvider:!1,repair:!1,restore:!1,pruneBackups:!1,watch:!1,manageProfiles:!1,revealProfilePaths:!1,forgetBrowser:!1,exportDiagnostics:!1,viewUpdateStatus:!1,operationLogs:!1}),Object.freeze({sync:!0,switchProvider:!0,repair:!0,restore:!1,pruneBackups:!1,watch:!1,manageProfiles:!1,revealProfilePaths:!1,forgetBrowser:!1,exportDiagnostics:!1,viewUpdateStatus:!1,operationLogs:!1}),Object.freeze({sync:!0,switchProvider:!0,repair:!0,restore:!0,pruneBackups:!0,watch:!0,manageProfiles:!0,revealProfilePaths:!1,forgetBrowser:!1,exportDiagnostics:!0,viewUpdateStatus:!0,operationLogs:!0});var Ij=[[`overview`,`nav.overview`,ki],[`backups-restore`,`nav.backupsRestore`,hi],[`history`,`nav.history`,Li],[`operation-logs`,`nav.operationLogs`,zi],[`profiles`,`nav.profiles`,Ei],[`diagnostics`,`nav.diagnostics`,mi],[`settings`,`nav.settings`,Vi]];function Lj(e){return{...Fj,...e}}function Rj(e,t){return e!==`operation-logs`||t.operationLogs}function zj(e){return e instanceof Kr&&(e.code===`PROFILE_CHANGED`||e.code===`STALE_STATE`&&e.dto.details?.reason===`profile`)}function Bj(e){return e?`${e.id}:${e.revision}`:``}function Vj(e,t){return[`watch-status`,e,t]}function Hj(e,t){e.setQueriesData({queryKey:[`watch-status`]},e=>e&&(`watches`in e?{...e,watches:e.watches.map(e=>e.watchId===t.watchId?t:e)}:e.watchId===t.watchId?t:e))}function Uj({props:e}){let{t,i18n:n}=Dn(),r=hb(),i=_(),a=(0,m.useMemo)(()=>Lj(e.capabilities),[e.capabilities]),o=(0,m.useRef)(new Map);(0,m.useEffect)(()=>{if(a.viewUpdateStatus)return e.host.subscribeUpdateStatus?.(e=>i.setQueryData([`desktop-update-status`],e))},[a.viewUpdateStatus,e.host,i]),(0,m.useEffect)(()=>{if(a.watch)return e.host.subscribeWatchStopped?.(e=>{let t=o.current.get(e.watch.watchId);if(!(t!==void 0&&t>=e.generation)){for(;o.current.size>=256;){let e=o.current.keys().next().value;if(!e)break;o.current.delete(e)}o.current.set(e.watch.watchId,e.generation),Hj(i,e.watch),i.setQueryData(Vj(e.profileId,e.profileRevision),e.watch)}})},[a.watch,e.host,i]);let s=(0,m.useMemo)(()=>Ij.filter(([e])=>Rj(e,a)),[a]),[c,l]=(0,m.useState)(`overview`),[u,d]=(0,m.useState)(()=>Nj(e.preferences)),[f,p]=(0,m.useState)(`default`),[g,v]=(0,m.useState)(null),[y,b]=(0,m.useState)(null),[x,S]=(0,m.useState)(),[C,w]=(0,m.useState)(!0),[T,E]=(0,m.useState)(null),[D,O]=(0,m.useState)(!1),[ee,k]=(0,m.useState)(null),[A,j]=(0,m.useState)(!1),[M,N]=(0,m.useState)(!1),[P,F]=(0,m.useState)(!1),[te,ne]=(0,m.useState)(null),[re,ie]=(0,m.useState)({}),[I,L]=(0,m.useState)(),[ae,oe]=(0,m.useState)(null),se=(0,m.useRef)(null),ce=(0,m.useRef)(null),le=(0,m.useRef)(!1),ue=(0,m.useRef)(!1),de=(0,m.useRef)(!1),fe=(0,m.useRef)(null),pe=(0,m.useRef)({}),me=(0,m.useRef)(0),he=(0,m.useRef)(``),ge=(0,m.useRef)(null),_e=(0,m.useRef)(!1),ve=(0,m.useRef)(!1),ye=(0,m.useRef)(null),be=it(),xe=rt({queryKey:[`profiles`],queryFn:({signal:t})=>e.host.listProfiles(t)}),Se=xe.data??[],R=Se.find(e=>e.id===f)??Se[0],Ce=Bj(R),{state:we,start:Te}=Nb(Ce),{state:Ee,start:De}=Nb(Ce);he.current=Ce;let Oe=(0,m.useCallback)(e=>{let t=Bj(e),n=++me.current;pe.current={...pe.current,[t]:n},ie(pe.current)},[]),ke=(0,m.useCallback)(async()=>{if(ve.current||(ve.current=!0,r.push({title:t(`global.profileChanged`),description:t(`global.profileChangedHint`),tone:`warning`})),!ye.current){let e=xe.refetch().then(()=>void 0).finally(()=>{ye.current===e&&(ye.current=null)});ye.current=e}await ye.current},[xe.refetch,t,r]);(0,m.useEffect)(()=>{document.documentElement.lang=n.resolvedLanguage?.toLowerCase().startsWith(`zh`)?`zh-CN`:`en`},[n.resolvedLanguage]),(0,m.useEffect)(()=>{Se.length&&!Se.some(e=>e.id===f)&&p(Se[0].id)},[Se,f]),(0,m.useEffect)(()=>{L(void 0),fe.current?.abort(),fe.current=null,ue.current=!1,de.current=!1,j(!1),F(!1),N(!1)},[Ce]),(0,m.useEffect)(()=>()=>{fe.current?.abort()},[]),(0,m.useEffect)(()=>{Rj(c,a)||l(`overview`)},[a,c]);let Ae=rt({queryKey:[`status`,R?.id,R?.revision],queryFn:({signal:t})=>e.core.getStatus({profile:gb(R)},{signal:t}),enabled:!!R}),je=Ae.isError?void 0:Ae.data,Me=!!je?.statusReadBlocked,Ne=je?.statusReadBlocked,Pe=typeof Ne==`object`&&!!Ne&&!Array.isArray(Ne)&&Ne.reason===`state-changed-during-status`,Fe=Ae.isSuccess&&je!==void 0&&!Me,Ie=rt({queryKey:[`recent-successful-switches`,R?.id,R?.revision],queryFn:({signal:t})=>e.host.listOperationLogs({page:1,pageSize:100,profileId:R.id,profileRevision:R.revision,operation:`switch`,status:`completed`},t),enabled:!!(R&&a.operationLogs&&e.host.listOperationLogs),retry:!1,staleTime:1/0,refetchOnWindowFocus:!1,refetchOnReconnect:!1});(0,m.useEffect)(()=>{if(Fe&&je.profile.revision===R?.revision){ve.current=!1;return}zj(Ae.error)&&!ve.current&&ke()},[ke,R?.revision,je?.profile.revision,Ae.error,Fe]);let Le=je?.operationInProgress!=null,Re=je?.operationInProgress?.lockState===`unverifiable`,ze=!R||!Fe||je?.pendingRecovery===!0||Le||be>0||ee!==null||Ee!==null,Be=!R||!Fe||Le||be>0||ee!==null,Ve=rt({queryKey:[`backups`,R?.id,R?.revision],queryFn:({signal:t})=>e.core.listBackups({profile:gb(R)},{signal:t}),enabled:!!(R&&c===`backups-restore`)}),He=rt({queryKey:[`diagnostics`,R?.id,R?.revision],queryFn:async({signal:t})=>{let n=Te();try{return await e.core.getDiagnostics({profile:gb(R)},{signal:t,onRequestProgress:n.onRequestProgress})}finally{n.finish()}},enabled:!1}),Ue=(0,m.useCallback)(async()=>{if(!R)return;let e=Bj(R),t=pe.current[e]??0;if((await He.refetch()).isSuccess&&he.current===e&&(pe.current[e]??0)===t){let t={...pe.current};delete t[e],pe.current=t,ie(t)}},[He,R]),We=(0,m.useCallback)(async({refreshStatus:e=!0}={})=>{let t=[i.invalidateQueries({queryKey:[`backups`]}),i.invalidateQueries({queryKey:[`history`]}),i.invalidateQueries({queryKey:[`diagnostics`]}),i.invalidateQueries({queryKey:[`recent-successful-switches`]})];t.push(i.invalidateQueries({queryKey:[`status`],refetchType:e?`active`:`none`})),await Promise.all(t)},[i]),Ge=(0,m.useCallback)(async(e,n)=>{ge.current=n;try{v(await e())}catch(e){if(ge.current=null,zj(e)){await ke();return}r.push({title:t(`global.failed`),description:yb(e,t),tone:`danger`})}},[ke,t,r]),Ke=(0,m.useCallback)(()=>{let e=ge.current;_e.current=!1,v(null),F(!1),de.current=!1,N(!1),ce.current=null,E(null),O(!1),globalThis.requestAnimationFrame(()=>globalThis.requestAnimationFrame(()=>{e?.isConnected&&e.focus(),ge.current===e&&(ge.current=null)}))},[]),qe=(0,m.useCallback)(()=>{g&&e.host.dismissOperationPlan?.(g.planId),Ke()},[Ke,g,e.host]),Je=(0,m.useCallback)(()=>{v(null),k(null),ce.current=null,E(null),O(!1)},[]),Ye=(0,m.useCallback)(()=>{if(_e.current)return;let e=ge.current;ge.current=null,e?.focus()},[]),Xe=(0,m.useCallback)(()=>{let e=ge.current;ge.current=null,_e.current=!1,e?.focus()},[]),Ze=st({mutationFn:async t=>{let n={schemaVersion:1,planId:t.planId},r=new AbortController;se.current=r,ce.current=null,E(null),O(!1);let i={signal:r.signal,onOperationStarted:e=>{ce.current=e.operationId},onProgress:e=>E(e.progress)};try{return t.operation===`sync`?await e.core.applySync(n,i):t.operation===`switch`?await e.core.applySwitch(n,i):t.operation===`repair`?await e.core.applyRepair(n,i):await e.core.applyRestore(n,i)}finally{se.current===r&&(se.current=null)}},onSuccess:async(e,n)=>{let i=$A(e.outcome),a=e.outcome===`recovery_required`;_e.current=!0,w(!a),b(e),S({operationId:e.operationId,state:`checking`}),oe(n.profile),Oe(n.profile),Je();let[,o]=await Promise.allSettled([We({refreshStatus:!1}),Ae.refetch()]),s=o.status===`fulfilled`?o.value:void 0,c=s?.isSuccess&&JA(s.data)&&s.data.profile.id===n.profile.id&&s.data.profile.revision===n.profile.revision&&he.current===Bj(n.profile)?s.data:void 0;S({operationId:e.operationId,state:c?`received`:`unverified`,...c?{snapshot:c}:{}}),a&&w(!!c),r.push({title:t(i.toastKey),description:e.backup?t(`operationResult.backupCreated`):void 0,tone:i.tone})},onError:async(e,n)=>{if(Oe(n.profile),await We(),Ke(),e instanceof Kr&&e.code===`OPERATION_CANCELLED`){r.push({title:t(`global.cancelled`),tone:`warning`});return}if(zj(e)){await ke();return}r.push({title:t(`global.failed`),description:yb(e,t),tone:`danger`})}}),Qe=async(n,i)=>{if(ze||!a.sync||g||y||le.current)return;le.current=!0,ge.current=i;let o=new AbortController;se.current=o,O(!1),E(null),k(`preparing`);let s=!1;try{let n=await e.core.prepareSync({profile:gb(R),keepCount:u},{signal:o.signal});if(o.signal.aborted){e.host.dismissOperationPlan?.(n.planId),r.push({title:t(`global.cancelled`),tone:`warning`});return}k(`applying`),s=!0,await Ze.mutateAsync(n)}catch(e){s||(o.signal.aborted||e instanceof Kr&&e.code===`OPERATION_CANCELLED`?r.push({title:t(`global.cancelled`),tone:`warning`}):zj(e)?await ke():r.push({title:t(`global.failed`),description:yb(e,t),tone:`danger`}))}finally{se.current===o&&(se.current=null),le.current=!1,k(null),O(!1)}},$e=(0,m.useCallback)(async(n,i,o)=>{if(!a.repair||ze||!R||n.length===0||fe.current)return;ne({targets:n,keepCount:i}),N(!1),F(!1),de.current=!1;let s=new AbortController;fe.current=s;let c=Ce,l=De();ge.current=o;try{let t=await e.core.prepareRepair({profile:gb(R),targets:n,keepCount:i},{signal:s.signal,onRequestProgress:l.onRequestProgress});if(s.signal.aborted||c!==he.current){e.host.dismissOperationPlan?.(t.planId);return}v(t)}catch(e){s.signal.aborted||(ge.current=null,zj(e)?await ke():r.push({title:t(`global.failed`),description:yb(e,t),tone:`danger`}))}finally{fe.current===s&&(fe.current=null),l.finish()}},[a.repair,Ce,ke,ze,R,e.core,e.host,De,t,r]),et=(0,m.useCallback)(async n=>{if(!g||g.operation!==`repair`||!te||A||Array.isArray(n)&&n.length===0)return;let i=g.planId,a=Ce,o=new AbortController;fe.current?.abort(),fe.current=o;let s=De();j(!0),ue.current=!0,N(!1),F(!0),de.current=!0,e.host.dismissOperationPlan?.(i);try{let t={profile:gb(R),targets:te.targets,keepCount:te.keepCount,...n===null?{}:{sessionIds:n}},r=await e.core.prepareRepair(t,{signal:o.signal,onRequestProgress:s.onRequestProgress});if(o.signal.aborted||a!==he.current){e.host.dismissOperationPlan?.(r.planId);return}v(r),F(!1),de.current=!1}catch(e){o.signal.aborted||(N(!0),zj(e)?await ke():r.push({title:t(`global.failed`),description:yb(e,t),tone:`danger`}))}finally{s.finish(),fe.current===o&&(fe.current=null,j(!1),ue.current=!1)}},[Ce,ke,g,R,e.core,e.host,te,A,De,t,r]),tt=st({mutationFn:async t=>{if(bp.parse(t),!e.preferences.setBackupRetention||g||y||Le||!Fe||ee!==null)throw Error(`Backup preference unavailable.`);let n=await e.core.getWatchStatus({});return(`watches`in n?n.watches:[n]).some(e=>e.status!==`stopped`)?`watch-active`:(e.preferences.setBackupRetention(t),d(t),`saved`)}}),nt=st({mutationFn:async t=>e.core.pruneBackups({profile:{profileId:t.profile.id,profileRevision:t.profile.revision},keepCount:t.keepCount}),onSuccess:async(e,n)=>{Oe(n.profile),await We(),r.push({title:t(`global.completed`),tone:`success`})},onError:(e,n)=>{Oe(n.profile),r.push({title:t(`global.failed`),description:yb(e,t),tone:`danger`})}}),at=st({mutationFn:async()=>{if(!R||!e.host.exportDiagnostics)throw Error(`Diagnostics export is unavailable.`);return e.host.exportDiagnostics(gb(R))},onSuccess:e=>{r.push({title:e.status===`created`?t(`diagnostics.exportCreated`):e.status===`cancelled`?t(`diagnostics.exportCancelled`):t(`diagnostics.exportFailed`),tone:e.status===`created`?`success`:e.status===`cancelled`?`warning`:`danger`})},onError:()=>r.push({title:t(`diagnostics.exportFailed`),tone:`danger`})}),ot=je?.configuredProviders&&Array.isArray(je.configuredProviders)?je.configuredProviders.filter(e=>typeof e==`string`):[je?.currentProvider??`openai`],ct=Fe?[...new Set((Ie.data?.entries??[]).filter(e=>e.profileId===R?.id&&e.profileRevision===R?.revision&&e.status===`completed`&&e.outcome===`completed`&&e.switchPlan!==void 0).map(e=>e.switchPlan.targetProvider).filter(e=>ot.includes(e)))].slice(0,5):[],z=R?bb(R,t):``,lt=je?.pendingRecovery?{label:t(`global.recoveryTitle`),tone:`warning`}:Ae.isError?{label:t(`global.statusUnavailable`),tone:`danger`}:Re?{label:t(`global.lockUnverified`),tone:`warning`}:be>0||ee!==null||Le?{label:t(`global.busy`),tone:`warning`}:Me?{label:t(`global.statusNeedsRefresh`),tone:`neutral`}:Fe?{label:t(`global.ready`),tone:`success`}:{label:t(`global.readingStatus`),tone:`neutral`},ut=R?c===`overview`?(0,h.jsx)(Dj,{profileKey:Ce,retentionCount:u,directSync:a.sync?Qe:void 0,loading:Ae.isFetching,manageStorage:()=>l(`profiles`),prepareSwitch:(t,n)=>Ge(()=>e.core.prepareSwitch({profile:gb(R),provider:t.provider,modelMode:t.modelMode,...t.modelMode===`explicit`?{model:t.model}:{},keepCount:u}),n),prepareSync:(t,n)=>Ge(()=>e.core.prepareSync({profile:gb(R),keepCount:u}),n),profileName:z,providers:ot,recentSuccessfulProviders:ct,refresh:()=>{Ae.refetch(),Ie.refetch()},sqliteHomeConfigured:R.sqliteHomeConfigured===!0||!!R.sqliteHome,status:je,writeDisabled:ze}):c===`backups-restore`?(0,h.jsx)(Eb,{retentionCount:u,saveRetention:e.preferences.setBackupRetention?e=>tt.mutateAsync(e):void 0,error:Ve.error,refresh:()=>void Ve.refetch(),refreshing:Ve.isFetching,backups:Ve.data?.backups??[],canPrune:a.pruneBackups,canRestore:a.restore,disabled:Be||nt.isPending,initialBackupId:I,loading:Ve.isPending,prepare:(t,n)=>Ge(()=>e.core.prepareRestore({profile:gb(R),backupId:t.backupId,restoreConfig:t.restoreConfig,restoreDatabase:t.restoreDatabase,restoreSessions:t.restoreSessions,...t.allowSqliteHomeRelocation?{allowSqliteHomeRelocation:!0,relocationTargetProfileId:t.relocationTargetProfileId}:{}}),n),profile:R,profiles:Se,prune:e=>nt.mutate({keepCount:e,profile:{id:R.id,revision:R.revision}})},Ce):c===`history`?(0,h.jsx)(HA,{core:e.core,host:e.host,preferences:e.preferences,profile:R},`${R.id}:${R.revision}`):c===`operation-logs`&&a.operationLogs&&e.host.listOperationLogs&&e.host.getOperationLog?(0,h.jsx)(_j,{host:e.host,profileId:R.id,profileRevision:R.revision,openBackupRestore:a.restore?e=>{L(e),l(`backups-restore`)}:void 0,reviewOperation:e=>l(e===`repair`?`diagnostics`:`overview`)},Ce):c===`profiles`?(0,h.jsx)(Oj,{selectedProfileId:f,canManage:a.manageProfiles,host:e.host,profiles:Se,refresh:()=>xe.refetch(),revealPaths:a.revealProfilePaths,selectProfile:p,surface:e.surface}):c===`diagnostics`?(0,h.jsx)(zb,{canExport:a.exportDiagnostics&&!!e.host.exportDiagnostics,canRepair:a.repair,diagnostics:He.data,error:He.error,expired:!!re[Ce],exportBundle:()=>at.mutate(),exporting:at.isPending,loading:He.isFetching,prepareRepair:(e,t)=>{let n=[`models`,`cwd`,`userEvent`,`workspaceRoots`].filter(t=>e[t]);return $e(n,u,t)},refresh:()=>{Ue()},repairDisabled:ze||He.isFetching,scanProgress:we,repairProgress:Ee},Ce):c===`settings`?(0,h.jsx)(Mj,{retentionCount:u,capabilities:a,isWatchTerminal:e=>o.current.has(e),profile:R,props:e,recoveryBlocked:je?.pendingRecovery===!0,writeBlocked:!Fe||Le||be>0||ee!==null},Ce):(0,h.jsx)(Dj,{profileKey:Ce,retentionCount:u,directSync:a.sync?Qe:void 0,loading:Ae.isFetching,manageStorage:()=>l(`profiles`),prepareSwitch:(t,n)=>Ge(()=>e.core.prepareSwitch({profile:gb(R),provider:t.provider,modelMode:t.modelMode,...t.modelMode===`explicit`?{model:t.model}:{},keepCount:u}),n),prepareSync:(t,n)=>Ge(()=>e.core.prepareSync({profile:gb(R),keepCount:u}),n),profileName:z,providers:ot,recentSuccessfulProviders:ct,refresh:()=>{Ae.refetch(),Ie.refetch()},sqliteHomeConfigured:R.sqliteHomeConfigured===!0||!!R.sqliteHome,status:je,writeDisabled:ze}):(0,h.jsx)(cb,{children:xe.isPending?t(`common.loading`):yb(xe.error,t)});return(0,h.jsxs)(`div`,{className:ob(`bg-[var(--surface)] text-[var(--text)]`,[`history`,`operation-logs`].includes(c)?`flex h-dvh min-h-0 flex-col overflow-hidden`:`min-h-screen`),children:[(0,h.jsx)(`a`,{className:`sr-only focus:not-sr-only focus:fixed focus:left-4 focus:top-4 focus:z-[70] focus:rounded focus:bg-[var(--accent)] focus:px-4 focus:py-2 focus:text-white`,href:`#main-content`,onClick:e=>{e.preventDefault(),document.getElementById(`main-content`)?.focus()},children:t(`a11y.skipToContent`)}),(0,h.jsxs)(`header`,{className:ob(`sticky top-0 z-30 flex min-h-16 shrink-0 flex-wrap items-center justify-between gap-3 border-b border-[var(--border)] bg-[color:var(--surface-raised)/.96] px-4 py-3 backdrop-blur md:px-6`,[`history`,`operation-logs`].includes(c)&&`[@media(max-height:500px)]:min-h-0 [@media(max-height:500px)]:py-1`),children:[(0,h.jsxs)(`div`,{className:ob(`flex min-w-0 items-center gap-3`,[`history`,`operation-logs`].includes(c)&&`[@media(max-height:500px)]:hidden`),children:[(0,h.jsx)(`div`,{className:`grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-[var(--accent)] text-white`,children:(0,h.jsx)(Ci,{size:20})}),(0,h.jsxs)(`div`,{className:`min-w-0`,children:[(0,h.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,h.jsx)(`div`,{className:`truncate font-bold`,children:`Codex Provider Sync`}),(0,h.jsx)(db,{children:t(`brand.${e.surface}.label`)})]}),(0,h.jsx)(`div`,{className:`truncate text-xs text-[var(--muted)]`,children:t(`brand.${e.surface}.subtitle`)})]})]}),(0,h.jsxs)(`div`,{className:`flex w-full min-w-0 items-center justify-between gap-3 sm:w-auto sm:justify-end`,children:[(0,h.jsx)(`select`,{"aria-label":t(`a11y.profile`),className:`min-w-0 max-w-[min(12rem,70vw)] rounded-[var(--radius-control)] border border-[var(--border)] bg-[var(--input)] px-3 py-2 text-sm`,disabled:be>0||ee!==null||Le||A,onChange:e=>p(e.target.value),value:R?.id??``,children:Se.map(e=>(0,h.jsx)(`option`,{value:e.id,children:bb(e,t)},e.id))}),(0,h.jsx)(db,{tone:lt.tone,children:lt.label})]})]}),(0,h.jsxs)(`div`,{className:ob(`mx-auto grid w-full min-w-0 max-w-[1600px] md:grid-cols-[240px_minmax(0,1fr)]`,[`history`,`operation-logs`].includes(c)&&`min-h-0 flex-1 grid-rows-[auto_minmax(0,1fr)] overflow-hidden md:grid-rows-1`),children:[(0,h.jsx)(`aside`,{className:ob(`min-w-0 max-w-full border-b border-[var(--border)] bg-[var(--surface-raised)] p-3 md:border-b-0 md:border-r`,[`history`,`operation-logs`].includes(c)?`min-h-0 overflow-y-auto overscroll-contain [@media(max-height:500px)]:p-1`:`overflow-hidden md:min-h-[calc(100vh-4rem)]`),children:(0,h.jsx)(`nav`,{"aria-label":t(`a11y.primaryNavigation`),className:`flex w-full min-w-0 max-w-full gap-1 overflow-x-auto pb-1 sm:grid sm:grid-cols-4 sm:overflow-visible sm:pb-0 md:grid-cols-1`,children:s.map(([e,n,r])=>(0,h.jsxs)(`button`,{"aria-current":c===e?`page`:void 0,className:ob(`flex min-h-11 shrink-0 items-center gap-3 whitespace-nowrap rounded-[var(--radius-control)] px-3 text-left text-sm font-medium text-[var(--muted)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus)] sm:shrink`,c===e?`bg-[var(--accent-soft)] text-[var(--accent-strong)]`:`hover:bg-[var(--surface-hover)] hover:text-[var(--text)]`),onClick:()=>l(e),type:`button`,children:[(0,h.jsx)(r,{size:17}),(0,h.jsx)(`span`,{children:t(n)})]},e))})}),(0,h.jsxs)(`main`,{className:ob(`min-w-0`,[`history`,`operation-logs`].includes(c)?`flex min-h-0 flex-col overflow-hidden p-3 md:p-4`:`p-4 md:p-8`),id:`main-content`,tabIndex:-1,children:[(0,h.jsxs)(`div`,{className:[`history`,`operation-logs`].includes(c)?`max-h-[30%] shrink-0 overflow-y-auto overscroll-contain`:void 0,children:[je?.pendingRecovery?(0,h.jsxs)(`div`,{className:`mb-5 flex items-start gap-3 rounded-xl border border-[var(--danger)] bg-[var(--danger-soft)] p-4 text-sm`,role:`alert`,children:[(0,h.jsx)(Hi,{className:`mt-0.5 shrink-0 text-[var(--danger)]`,size:20}),(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`div`,{className:`font-semibold`,children:t(`global.recoveryTitle`)}),(0,h.jsx)(`div`,{className:`mt-1`,children:t(`global.recovery`)})]})]}):null,je?.operationInProgress?(0,h.jsxs)(`div`,{className:`mb-5 flex flex-wrap items-start gap-3 rounded-xl border border-[var(--warning)] bg-[var(--warning-soft)] p-4 text-sm`,role:`status`,children:[(0,h.jsx)(Ti,{className:`mt-0.5 shrink-0 text-[var(--warning)]`,size:20}),(0,h.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,h.jsx)(`div`,{className:`font-semibold`,children:t(Re?`global.lockUnverified`:`global.busy`)}),(0,h.jsx)(`div`,{className:`mt-1 text-[var(--muted)]`,children:t(Re?`global.lockUnverifiedHint`:`global.busyHint`)})]}),Re?(0,h.jsx)(X,{disabled:Ae.isFetching,onClick:()=>void Ae.refetch(),type:`button`,variant:`secondary`,children:t(`global.retryStatus`)}):null]}):null,je?.staleLockDetected&&Fe&&!Le&&!je.pendingRecovery?(0,h.jsxs)(`div`,{className:`mb-5 rounded-xl border border-[var(--border)] bg-[var(--surface-raised)] p-4 text-sm`,role:`status`,children:[(0,h.jsx)(`div`,{className:`font-semibold`,children:t(`global.staleLock`)}),(0,h.jsx)(`p`,{className:`mt-1 text-[var(--muted)]`,children:t(`global.staleLockHint`)})]}):null,Me&&!Le?(0,h.jsxs)(`div`,{className:`mb-5 flex flex-wrap items-center justify-between gap-3 rounded-xl border border-[var(--border)] bg-[var(--surface-raised)] p-4 text-sm`,role:`status`,children:[(0,h.jsxs)(`div`,{children:[(0,h.jsx)(`div`,{className:`font-semibold`,children:t(`global.statusNeedsRefresh`)}),(0,h.jsx)(`p`,{className:`mt-1 text-[var(--muted)]`,children:t(Pe?`global.statusChangedHint`:`global.statusUnavailableHint`)})]}),(0,h.jsx)(X,{disabled:Ae.isFetching,onClick:()=>void Ae.refetch(),type:`button`,variant:`secondary`,children:t(`global.retryStatus`)})]}):null,Ae.isError?(0,h.jsx)(`div`,{className:`mb-5 rounded-xl border border-[var(--danger)] bg-[var(--danger-soft)] p-4 text-sm text-[var(--danger)]`,role:`alert`,children:yb(Ae.error,t)}):null]}),ut]})]}),a.sync||a.switchProvider||a.repair||a.restore?(0,h.jsx)(Sj,{repairProgress:Ee,apply:()=>{!g||M||ue.current||de.current||le.current||Ze.isPending||(le.current=!0,Ze.mutate(g,{onSettled:()=>{le.current=!1}}))},directSyncPhase:ee,applying:Ze.isPending||ee!==null,cancel:()=>{!Ze.isPending&&ee===null||D||(O(!0),se.current?.abort())},cancelling:D,close:qe,confirmDisabled:!Fe||Le||je?.pendingRecovery===!0,currentModel:je?.currentModel,plan:g,progress:T,repairDraftChanged:e=>{de.current=e,F(e)},repairSelectionFailed:M,repairSelectionPending:A,refineRepairSessions:et,restoreFocus:Ye}):null,(0,h.jsx)(aj,{postWriteStatus:ae?.id===R?.id&&ae?.revision===R?.revision?x:y?{operationId:y.operationId,state:`unverified`}:void 0,reviewOperation:y?.outcome===`partial`&&ae?.id===R?.id&&ae?.revision===R?.revision?()=>{let e=y.operation;ge.current=null,b(null),oe(null),l(e===`repair`?`diagnostics`:`overview`),globalThis.requestAnimationFrame(()=>document.getElementById(`main-content`)?.focus())}:void 0,close:()=>{b(null),oe(null),w(!0)},closeDisabled:y?.outcome===`recovery_required`&&(!C||je?.pendingRecovery!==!1),openBackupRestore:a.restore&&ae?.id===R?.id&&ae?.revision===R?.revision?e=>{L(e),b(null),oe(null),w(!0),l(`backups-restore`)}:void 0,restoreFocus:Xe,result:y})]})}var Wj=class extends m.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(e,t){}render(){if(!this.state.failed)return this.props.children;let e=this.props.locale().toLowerCase().startsWith(`zh`);return(0,h.jsx)(`div`,{className:`grid min-h-screen place-items-center bg-[var(--surface)] p-6 text-[var(--text)]`,children:(0,h.jsxs)(cb,{className:`max-w-lg text-center`,children:[(0,h.jsx)(Hi,{className:`mx-auto text-[var(--danger)]`,size:40}),(0,h.jsx)(`h1`,{className:`mt-4 text-xl font-bold`,children:e?`页面暂时无法显示`:`This page is temporarily unavailable`}),(0,h.jsx)(`p`,{className:`mt-2 text-sm text-[var(--muted)]`,children:e?`你的数据没有被更改。请重新打开应用;如果问题持续,请查看操作日志或导出诊断信息。`:`Your data was not changed. Reopen the app; if the problem continues, check Operation logs or export diagnostics.`}),(0,h.jsx)(X,{className:`mt-5`,onClick:()=>globalThis.location?.reload(),type:`button`,children:e?`重新打开`:`Reopen`})]})})}},Gj={en:{translation:{requestProgress:{working:`Working…`,elapsed:`Elapsed {{time}}`,files:`{{count}} files checked`,stagePercent:`This stage: {{percent}}%`,stages:{waiting:`Starting…`,prepare_repair_context:`Reading configuration and checking preview state…`,prepare_diagnostics:`Preparing diagnostics…`,scan_sessions:`Checking session files…`,scan_archived_sessions:`Checking archived sessions…`,inspect_repair_sqlite:`Checking affected chat index entries…`,inspect_workspace_roots:`Checking workspace settings…`,build_repair_preview:`Building the change preview…`,inspect_diagnostics_index:`Checking the chat index…`,inspect_diagnostics_backups:`Checking backups and recovery state…`,inspect_history_integrity:`Preparing history integrity checks…`,integrity_sessions:`Checking session record integrity…`,integrity_archived_sessions:`Checking archived record integrity…`,finish_diagnostics:`Completing diagnostics…`}},backupPolicy:{title:`Backup settings`,count:`Backups to retain`,save:`Save backup settings`,scope:`One rule for this app: Sync, Switch, Repair and automatic sync share it. Each Codex Home keeps its own backup pool; operations do not each keep a separate quota.`,current:`Saved rule: keep the newest {{count}} backups per Codex Home.`,operationHint:`Automatically back up changes and retain {{count}} backups. Manage this rule in Backups / Restore.`,hint:`Saving does not delete backups. Future writes use the saved rule; manual cleanup asks for confirmation. Recovery-protected backups may exceed this count. Stop automatic sync before changing the rule.`,saved:`Backup settings saved. No backups were deleted.`,"watch-active":`Automatic sync is active. Stop it in Settings, then save this rule again.`,failed:`Could not save backup settings. The previous rule is unchanged; try again.`,clear:`Delete all eligible backups`},ux:{reading:`Reading status…`,unknown:`Not verified`,previousSnapshot:`Refreshing; showing the last snapshot.`,currentProfile:`In use`,finalStatus:`Final Provider check`,finalChecking:`Reading the post-operation status…`,finalUnavailable:`The operation result is available, but the final Provider alignment has not been verified. Refresh Overview to check.`,pruneEstimate:`From the current list: up to {{remove}} backups may be removed; at least {{keep}} will remain.`,pruneCaution:`Backups needed for recovery stay protected. The list may change; the actual result determines how many are removed.`,pruneTitle:`Confirm backup cleanup`,pruneConfirm:`Confirm cleanup`,pruneZero:`This cleanup requests removal of every eligible managed backup, not protected recovery backups. Deleted backups cannot be restored by this tool. Your automatic retention rule will not change.`,pruneChanged:`The backup list or storage profile changed. Close this preview and review cleanup again.`,clearFilters:`Clear filters`,pendingFilters:`Search text, Provider or scope changed. Press Search to apply.`},brand:{desktop:{label:`Desktop`,subtitle:`Manage Codex Providers and local session history`},web:{label:`Web`,subtitle:`Local Web management interface`}},a11y:{skipToContent:`Skip to content`,profile:`Profile`,primaryNavigation:`Primary navigation`},nav:{overview:`Overview`,sync:`Sync`,switchProvider:`Switch Provider`,backupsRestore:`Backups / Restore`,history:`History`,operationLogs:`Operation logs`,profiles:`Profiles`,diagnostics:`Advanced features`,settings:`Settings`},common:{refresh:`Refresh`,loading:`Loading…`,processing:`Processing`,cancel:`Cancel`,confirm:`Confirm and apply`,save:`Save`,delete:`Delete`,close:`Close`,dismissNotification:`Dismiss notification: {{title}}`,yes:`Yes`,no:`No`,none:`None`,unknown:`Unknown`,current:`Current`,provider:`Provider`,model:`Model`,status:`Status`,warnings:`Warnings`,retry:`Retry`,advanced:`Advanced options`,search:`Search`,copy:`Copy`,copied:`Copied`},global:{ready:`Ready`,readingStatus:`Reading status…`,statusUnavailable:`Status unavailable`,statusNeedsRefresh:`Refresh needed`,statusChangedHint:`Data changed while checking. Refresh to check again.`,statusUnavailableHint:`The current status could not be fully checked. Please refresh and try again.`,retryStatus:`Check status again`,busy:`Operation in progress`,busyHint:`Another operation is using the current storage location. You can continue when it finishes.`,lockUnverified:`Storage lock needs checking`,lockUnverifiedHint:`We cannot confirm whether another operation has finished. Check again after closing other sync tools. If this persists, export a diagnostic package from Advanced features. Do not delete the lock manually.`,staleLock:`A previous operation has ended`,staleLockHint:`You can preview or sync normally. Before writing, the app will recheck and safely reclaim the previous operation’s lock.`,recoveryTitle:`Recovery required`,recovery:`A previous restore did not finish. Complete recovery before making more changes.`,stale:`The data changed. Review the operation again before continuing.`,unexpected:`Something went wrong. Try again.`,partial:`Some records were not updated. Close any active Codex sessions and try again.`,completed:`Operation completed.`,cancelled:`Operation cancelled.`,profileChanged:`Profile changed.`,profileChangedHint:`Review the selected storage location and try again.`,failed:`The operation could not be completed.`},overview:{title:`Provider sync overview`,subtitle:`See whether the current Provider matches your local chat history.`,alignment:`Sync status`,aligned:`In sync`,notAligned:`Sync recommended`,rollout:`Session files`,sqlite:`Local chat index`,codexHomeSource:`Codex data location`,sqliteHomeSource:`Chat index location`,stateDbPath:`Current database file`,stateDbMissing:`No database found`,snapshot:`Snapshot`,backupCount:`Available backups`,locked:`Sessions currently in use`,usageUnknown:`Unknown`,profile:`Storage profile`,manageStorage:`Manage storage profiles`,operations:`Sync and switch`,operationsHint:`Sync the current Provider or switch to another Provider here.`,sources:{profile:`Selected storage profile`,config:`Codex configuration`,env:`Environment setting`,default:`Default location`,explicit:`Selected storage profile`,unknown:`Could not determine`}},sync:{title:`Sync current Provider`,subtitle:`Sync only Provider information from the current configuration. Models, chat content and history records are not repaired.`,keep:`Number of recent backups to keep`,prepare:`Preview sync`,direct:`Sync now`,directHint:`Sync now uses the current Provider without another confirmation. Changes are checked and backed up before writing; no advanced repairs are run.`,preparingDirect:`Checking sync changes`,runningDirect:`Syncing`,performance:{title:`How to speed up sync`,resultLink:`View speed-up tips`,equalLength:`Equal-length English Provider IDs can be updated in place after file checks, without copying the entire chat file. For example, openai and prov_a both have 6 characters.`,differentLength:`Different-length IDs still sync normally, but require copying the file. Larger chat files take longer. The app chooses the method automatically; there is no setting to enable.`,configuration:`If you change a Provider ID, keep it consistent in your configuration and Provider management tool. Changing only its display name does not help. You do not need to rename Providers to use sync.`}},switchPage:{title:`Switch Provider separately`,subtitle:`Change the Provider in your configuration, then run the same Provider sync. Review the changes before applying.`,provider:`Provider ID`,modelMode:`Model handling`,providerDefault:`Use model configured for this Provider`,keepModel:`Keep current root model`,explicitModel:`Specify root model`,modelModeDescriptions:{"provider-default":`Read [model_providers.{{provider}}].model from config.toml. If it is not configured, keep the current root model. This does not query the Provider online.`,"keep-root-model":`Only switch model_provider. Do not change the root-level model in config.toml.`,explicit:`Write the model name below to the root-level model in config.toml. Remote availability is not checked.`},historyModelHint:`Switch synchronizes historical Provider metadata, but does not change the models recorded by historical sessions. Use Advanced features > Advanced adjustments for that.`,recentSuccessful:`Recently used successfully`,model:`Model name`,prepare:`Preview switch`},backups:{title:`Backups and Restore`,subtitle:`View backups created by this app and restore one when needed.`,empty:`No backups yet. A backup is created automatically before data is changed.`,loadFailed:`Could not read backups. No backup was changed.`,requestedMissing:`This backup is no longer available in the current profile. It may have been removed by backup retention. Select an available backup instead.`,selectBackup:`Select a backup to choose what to restore.`,capturedHint:`Only data captured in this backup can be selected. Configuration includes workspace settings when present.`,relocationTargetRequired:`Choose a destination profile with a custom SQLite location.`,relocationHint:`The chat index will be restored to the selected destination. Codex configuration and workspace settings will not be restored. Session files, if selected, remain in the source Codex Home.`,restoreConfig:`Restore Codex configuration`,restoreDatabase:`Restore local chat index`,restoreSessions:`Restore session files`,relocation:`Restore to another storage profile`,targetProfile:`Destination storage profile`,prepare:`Preview restore`,pruneKeep:`Keep newest backups`,prune:`Delete older backups`,readOnly:`This version can view backups but cannot restore or delete them.`},history:{title:`Chats`,subtitle:`Select a chat to view its messages.`,empty:`No chats found.`,untitled:`Untitled chat`,subagentTitle:`Subtask · {{name}}`,sessionActions:`Session actions`,noProject:`Other chats`,filters:`Search options and filters`,projectTreeHint:`Main chats by project · expand arrows for subtasks`,mainWithSubtasks:`Main chats with nested subtasks`,rootCount:`{{count}} main chats`,orphanCount:`{{count}} unlinked subtasks`,orphans:`Unlinked subtasks`,orphansHint:`No reliable main-session link was found. These records are kept separately, not deleted.`,toggleSubtasks:`Subtasks of {{title}} ({{count}})`,childrenOf:`Subtasks of {{title}}`,loadMore:`Load more`,retryLoad:`Retry`,directoryBadge:`Directory`,projectKinds:{workspace:`Saved workspace`,directory:`Recorded working directory; no saved workspace matched.`,unassigned:`No recorded project directory`,orphans:`Missing or invalid parent-session relationship`},projectActions:`Project display options`,projectAliasTitle:`Set project display name`,projectAliasReset:`Use original name`,projectDisplayName:`Display name`,projectAliasHint:`Only changes the name shown in this app for this storage profile. Does not rename the directory or edit Codex data. Leave empty to use the original name.`,projectAliasContextHint:`Right-click or press Shift+F10 to set a local display name.`,projectAliasFailed:`Could not save the display name. Use up to 160 characters without control characters, then retry.`,contextMenuHint:`Right-click or press Shift+F10 for session actions.`,groupCount:`{{count}} chats on this page`,showMore:`Show more`,showLess:`Show less`,copyId:`Copy session ID`,copyResume:`Copy resume command`,copyPath:`Copy file path`,revealFile:`Show in File Explorer`,fileRevealed:`Session file located.`,revealFailed:`Could not locate the file. Refresh and try again.`,copyFailed:`Could not copy. Try again, or select the text and copy it manually.`,missingNativeId:`This record has no original session ID. Its internal list ID cannot be used to resume it.`,resumeHint:`Copies a command only. Run it in the matching Codex Home environment and original project directory; it does not switch Provider or guarantee continuation.`,sessionInformation:`Session information`,nativeId:`Original session ID`,sessionType:`Session type`,mainSessions:`Main sessions`,subtasks:`Subtasks`,parentId:`Parent session ID`,openParent:`View parent session`,parentUnavailable:`The parent session is not available in this storage profile.`,recordedProvider:`Recorded Provider`,recordedModel:`Recorded model`,notRecorded:`Not recorded`,createdAt:`Created`,fileModifiedAt:`File modified`,fileTimeHint:`File modification time can change after sync; it is not the last chat time.`,projectDirectory:`Project directory`,sessionFile:`Session file`,localInfoHint:`Local paths are available in the desktop app after this session is loaded.`,searchScope:`Search scope`,metadataSearch:`Title / ID / project`,contentSearch:`Chat content`,metadataSearchHint:`Searches names, IDs, projects and Providers without reading chat messages. Press Enter or Search to run.`,contentSearchHint:`Searches full chat content only when you press Enter or Search. Large histories may take a moment.`,untitledIdentity:`Untitled chat · {{date}} · {{id}}`,open:`View chat`,back:`Back to chats`,messages:`messages`,archived:`Archived`,active:`Active`,pagination:`Chat pagination`,listRegion:`Chat list`,detailRegion:`Chat details and messages`,refreshDetail:`Refresh chat`,pageSummary:`Page {{page}} · {{total}} chats`,previous:`Previous`,next:`Next`,searchPlaceholder:`Search chats`,providerFilter:`Filter by Provider`,archivedFilter:`Chat status`,all:`All chats`,select:`Select a chat on the left to view its messages.`,truncated:`This chat is long. Only the 200 most recent messages are shown.`,searchHint:`Search starts only after you submit. Large chat histories may take a moment.`,roles:{user:`You`,assistant:`Assistant`}},logs:{profileMismatch:`These actions require the original storage profile and revision. Select that profile, or locate a backup manually if its settings have changed.`,title:`Operation logs`,subtitle:`View operations started by this app, including their progress, results, and timing. Chat content and credentials are never recorded.`,empty:`No operations yet. Sync, switch, restore, or repair activity will appear here.`,select:`Select an operation to view its result and timing.`,listRegion:`Operation list`,detailRegion:`Operation details`,backToList:`Back to operations`,refreshDetail:`Refresh operation details`,identifiers:`Reference numbers`,detailUnavailable:`This log is no longer available. It may have been removed by log rotation.`,profileFilter:`Profile filter`,allProfiles:`All profiles`,operationFilter:`Operation filter`,statusFilter:`Filter by status`,allOperations:`All operations`,allStatuses:`All statuses`,activeDuration:`Processing time`,wallDuration:`Total time (including confirmation)`,startedAt:`Started`,completedAt:`Finished`,timeline:`Progress`,counts:`Completed changes`,previewCounts:`Previewed changes`,switchPlan:`Planned Provider switch`,switchPlanUnavailable:`This older record did not save switch details.`,fileTiming:{title:`File update timing`,pending:`File timing will be available after execution.`,unavailable:`File timing was not recorded for this operation.`,files:`Measured {{measured}} of {{attempted}} files · In-place {{inPlace}} · Replaced {{rewritten}} · Skipped {{skipped}}`,incomplete:`Some file timing was not returned. These are partial measurements, not the complete update cost.`,milliseconds:`{{value}} ms`,more:`Technical timing details`,nested:`Request time includes worker time; worker time includes its file stages. These measurements overlap and must not be added together. Timestamp restoration is still performed.`,phases:{copyTailMs:`Copy unchanged content`,flushMs:`Flush file data`,replaceMs:`Replace file`,cleanupMs:`Clean up temporary files`,restoreMtimeMs:`Restore file timestamps`,workerStartupMs:`Start file worker`,workerCloseMs:`Close file worker`,requestRoundTripMs:`Requests (including worker processing)`,workerMs:`Worker processing`,sourceOpenMs:`Open and check access`,readHeaderMs:`Read and check metadata`,tempCreateMs:`Create temporary files`}},notSet:`Not set`,providerChange:`Provider`,rootModelChange:`Root model`,modelMode:`Model handling`,switchPlanPartial:`This was the planned target. The operation finished partially; review the completed changes above before retrying.`,targetProvider:`Target Provider`,errorReason:`Reason`,errorReasons:{profile:`Storage profile changed`,config:`Codex configuration changed`,storage:`Storage location changed`,rollout:`Session files changed`,"state-db":`Local chat index changed`,backup:`Backup state changed`,"provider-not-configured":`Provider is not configured`},previewCountLabels:{rolloutFilesToChange:`Session files to update`,sqliteRowsToChange:`Local index records to update`,lockedRolloutFiles:`Sessions in use`},pageSummary:`Page {{page}} · {{total}} operations`,lessThanSecond:`Less than 1 second`,seconds:`{{value}} seconds`,minutesSeconds:`{{minutes}} min {{seconds}} sec`,logId:`Log number`,requestId:`Request number`,planId:`Confirmation number`,operationId:`Operation number`,backupId:`Backup number`,otherOperation:`Other operation`,unknownStage:`Processing`,operations:{sync:`Sync`,switch:`Switch Provider`,repair:`Repair`,restore:`Restore`,pruneBackups:`Delete older backups`,diagnostics:`Diagnostics`,watch:`Automatic sync`,update:`Update`,profile:`Storage profile`,runtime:`Background service`},statuses:{running:`Running`,"awaiting-confirmation":`Awaiting confirmation`,completed:`Completed`,partial:`Partially completed`,failed:`Failed`,cancelled:`Cancelled`,dismissed:`Cancelled before start`,interrupted:`Interrupted`},stages:{prepare:`Review changes`,prepare_config:`Read Codex configuration`,prepare_storage:`Resolve storage`,prepare_rollouts:`Prepare session files`,prepare_status:`Read current status`,prepare_revisions:`Capture protected revisions`,prepare_usage:`Check session use`,acquire_lock:`Acquire write lock`,read_config:`Read Codex configuration`,resolve_storage:`Resolve storage`,check_pending_restore:`Check pending restore`,validate_plan:`Recheck before writing`,scan:`Check data`,scan_rollout_files:`Check session files`,check_locked_rollout_files:`Check sessions in use`,create_backup:`Create backup`,rewrite_rollout_files:`Update session files`,repair_workspace_roots:`Update workspace locations`,update_sqlite:`Update local chat index`,update_config:`Update Codex configuration`,preflight_sqlite:`Check local chat index access`,release_lock:`Release write lock`,clean_backups:`Organize older backups`,verify_repair:`Verify repair results`,create_restore_pre_snapshot:`Create pre-restore snapshot`,persist_restore_journal:`Prepare recovery record`,apply_restore_targets:`Restore selected data`,commit_restore:`Finish restore`,acknowledge_restore_commit:`Confirm restored data`,rollback_restore:`Undo incomplete restore`,prune:`Delete older backups`,start:`Start automatic sync`,stop:`Stop automatic sync`,"automatic-sync":`Run automatic sync`,create:`Create storage profile`,update:`Update storage profile`,delete:`Delete storage profile`,export:`Export diagnostics`,check:`Check for updates`,download:`Download update`,install:`Install update`},stageStatuses:{running:`In progress`,completed:`Completed`,failed:`Failed`},countLabels:{changedSessionFiles:`Session files updated`,inPlaceSessionFiles:`Session files updated in place`,rewrittenSessionFiles:`Session files rewritten`,sqliteRowsUpdated:`Local index records updated`,sqliteProviderRowsUpdated:`Provider records updated`,sqliteModelRowsUpdated:`Model records updated`,sqliteUserEventRowsUpdated:`User-event records updated`,sqliteCwdRowsUpdated:`Workspace records updated`,skippedLockedRolloutFiles:`Sessions still in use`,skippedChangedRolloutFiles:`Sessions changed during the operation`,updatedWorkspaceRoots:`Workspace locations updated`,savedWorkspaceRootCount:`Workspace locations saved`,resolvedOperationCount:`Recovery items resolved`}},profiles:{title:`Storage profiles`,subtitle:`Create a profile for each Codex data location you use. Folder locations stay on this device.`,id:`Profile ID`,name:`Name`,codexHome:`Codex data folder`,sqliteHome:`Chat index folder (optional)`,create:`Create profile`,update:`Save changes`,managed:`Default`,chooseFolder:`Choose folder`,keepCurrent:`Do not change the current folder`,notSelected:`No folder selected`,inheritSqlite:`Find the chat index automatically`,customSqlite:`Choose a chat index folder`,revealCodex:`Open Codex data folder`,revealSqlite:`Open chat index folder`,selectCodexRequired:`Choose a Codex data folder for the new profile.`,defaultName:`Default location`,defaultManaged:`The default location is determined when the app starts and cannot be edited or deleted. Create another profile to use a different location.`,saved:`Storage profile saved`,deleted:`Storage profile deleted`,unavailable:`Storage profile management is unavailable.`,pathManaged:{desktop:`The folder location is stored securely by this app.`,web:`The folder location is stored by the local Web app.`},readOnly:`This version can view storage profiles but cannot edit them.`},diagnostics:{title:`Advanced features`,subtitle:`Optional tools for specific problems. For everyday Provider sync and switching, use Overview.`,scanTitle:`Full diagnostics · Read only`,scanHint:`Run a detailed check only when needed. It does not modify data or start repairs; chat content and credentials are never included in the report.`,repairScope:`These repairs do not fix session record numbering or rebuild the Codex history display index. They do not run during Provider sync.`,runtime:`App environment`,storage:`Storage locations`,provider:`Provider`,issues:`Check results`,issuesHint:`These counts show metadata differences and compatibility notices, not a count of damaged chats. Nothing is repaired automatically.`,modelDifferenceHint:`Historical chats may use different models intentionally. Unify model labels only if you need them to match the current root model.`,workspaceCountHint:`Workspace items count settings to adjust (including a missing settings backup), not folders or chats.`,encryptedHint:`Encrypted content is normal session data, not corruption. This check only detects the field; it does not test decryption or modify it. Continuing a chat with another Provider/account may require the original Provider/account.`,safety:`Operation status`,runScan:`Start diagnostics`,retryScan:`Retry diagnostics`,scanning:`Scanning… Full diagnostics may take several minutes. You can leave this page and return to view the result.`,scanFailed:`Diagnostics could not finish`,scanFailedHint:`No data was changed. Retry diagnostics; if it fails again, check Operation logs for details.`,previousResult:`Previous successful result · {{time}} (not the current scan)`,expiredResult:`Earlier diagnostic result · {{time}} (a write completed afterwards; run diagnostics again for a current result)`,scanCompleted:`Diagnostics completed · {{time}}`,incompleteScan:`Some data changed or could not be read during this scan. Results are for reference; run diagnostics again when the chats are idle.`,notScanned:`Diagnostics have not been run`,notScannedHint:`Start diagnostics when you need a detailed check. It runs only when requested and never changes your data.`,repairTitle:`Targeted repair`,repairHint:`Use for the specific issues described below. Everyday Provider sync does not need these options. Select an item and preview its changes before confirming.`,adjustmentTitle:`Advanced adjustments`,adjustmentHint:`Optional changes, not fault repairs. Different models in past chats are normal; leave this unchanged unless you want to unify their recorded names.`,previewAdjustment:`Preview adjustment`,availableRepairs:`Items to review from this check`,viewRepair:`View repair`,viewSpecificRepair:`View repair: {{target}}`,findings:{cwd:`{{count}} chat index entries record a different working folder`,userEvent:`{{count}} chat index entries lack a user-message marker`,workspaceRoots:`{{count}} project settings items can be organized`},repairTargetHints:{models:`Use only to make recorded model names in past chats match the model currently configured. Updates those names in chat files and the index; does not regenerate replies or change the Provider.`,cwd:`Use when the chat index records a different project folder than the chat file. Corrects the index using the folder recorded in that file; does not move files or change your current project.`,userEvent:`Use when a chat contains a user message but its index says it does not. Completes that index marker; does not add, remove or edit messages.`,workspaceRoots:`Use when saved project directory settings have duplicate or inconsistent entries. Normalizes those settings and preserves a settings backup; does not move or delete project folders. Applies to the whole profile and also corrects chat working folders.`},repairTargetRequired:`Select at least one repair target.`,workspaceRootsIncludesCwd:`This also corrects chat working folders across the whole profile; it cannot be limited to selected chats.`,prepareRepair:`Preview repair`,repairTargets:{models:`Unify historical model names`,cwd:`Correct chat project folders`,userEvent:`Complete user-message markers`,workspaceRoots:`Organize project directory records`},items:`{{count}} items`,fieldsAvailable:`{{count}} redacted fields`,technicalDetails:`Show technical details`,fields:{arch:`Architecture`,node:`Node.js`,platform:`Platform`,sqliteHomeSource:`SQLite Home source`,sqliteSupported:`SQLite supported`,stateDbFound:`State DB found`,configured:`Configured Providers`,current:`Current Provider`,implicit:`Implicit Provider`,rolloutCounts:`Rollout distribution`,sqliteCounts:`SQLite distribution`,rootModelAvailable:`Root model available`,rolloutModelFilesNeedingRepair:`Session files with model labels differing from the root model`,sqliteModelRowsNeedingRepair:`Index rows with model labels differing from the root model`,cwdRowsNeedingRepair:`Index rows with differing working folders`,userEventRowsNeedingRepair:`Index rows missing a recorded user-message marker`,workspaceRootsNeedingRepair:`Workspace settings to adjust`,encryptedContentFiles:`Session files containing encrypted content (informational)`,lockedRolloutCount:`Locked rollouts`,operationInProgress:`Operation in progress`,pendingRecovery:`Recovery required`,pendingTransactions:`Pending transactions`,projectThreadVisibilityAvailable:`Project visibility available`,rolloutScanComplete:`Rollout scan complete`,storageRevision:`Storage revision`},export:`Export redacted bundle`,exporting:`Exporting…`,exportCreated:`Redacted diagnostics bundle created.`,exportCancelled:`Diagnostics export cancelled.`,exportFailed:`Diagnostics export failed.`,historyIntegrity:{title:`History record checks`,scope:`This bounded, read-only check observes JSON records and numeric record order only. It does not declare the history display healthy, repair records, or infer missing sequence gaps as damage.`,displayIndexUnsupported:`The Codex display-index format is not known to this app, so it was not verified or rebuilt.`,outcomes:{"no-findings":`No observations`,findings:`Observations found`,inconclusive:`Incomplete check`,"findings-and-inconclusive":`Observations and incomplete check`},skipped:`Some records were skipped within the scan limits; treat the result as incomplete.`,findings:`Observations requiring review`,moreFindings:`Additional findings were omitted from this list; see technical details.`,manualReview:`Requires manual review`,session:`Session {{sessionId}}`,line:`line {{line}}`,copySessionId:`Copy session ID`,copiedSessionId:`Session ID copied`,issueCodes:{"unsupported-format":`Record format requires manual review`,"invalid-utf8":`Record text could not be read as UTF-8`},counts:{filesDiscovered:`Files discovered`,filesScanned:`Files scanned`,recordsRead:`Records read`,sessionsWithId:`Sessions with an ID`,jsonCorruptRecords:`Records with invalid JSON`,oversizedRecords:`Records above the size limit`,duplicateOrdinals:`Repeated numeric record order`,outOfOrderOrdinals:`Out-of-order numeric records`,changedFiles:`Files changed during scan`,truncatedFiles:`Files stopped at a scan limit`}}},settings:{title:`Settings`,subtitle:{desktop:`Manage appearance, automatic sync, and app updates. Preferences stay on this device.`,web:`Manage appearance and browser settings. Preferences stay in this browser.`},language:`Language`,languageHint:`Changes take effect immediately.`,theme:`Theme`,system:`System`,light:`Light`,dark:`Dark`,watch:`Automatic sync`,watchHint:`Automatically sync Provider information when files in the selected storage change. Profiles using the same Codex Home share one watcher; disabling it stops that shared watcher. Its options and execution/stop logs belong to the first profile that enabled it (visible under All profiles in logs).`,watchStart:`Enable automatic sync`,watchStop:`Disable automatic sync`,watchRecoveryBlocked:`Complete recovery before enabling automatic sync.`,watchStatuses:{running:`Enabled`,stopped:`Disabled`,starting:`Starting`,stopping:`Stopping`,failed:`Needs attention`},update:`Updates`,updateCurrentVersion:`Current version: {{version}}`,updateManualHint:`Check once on the first launch each day; only newer releases trigger a popup. This portable or local build opens the GitHub download page; download and replace it manually. It does not install or restart automatically.`,updateAutomaticHint:`Check once on the first launch each day and notify only for newer releases. Download when ready, then confirm a restart to install. Your Codex data is not part of the update.`,updateOpenDownload:`Open official download page`,updateIgnore:`Don't remind me about this version`,updateRestoreReminder:`Remind me about this version`,updateIgnored:`Reminders for this version are off. You can still update now.`,updateReminderFailed:`Could not save your preference. Please try again.`,updateRequestFailed:`The update request failed. Refresh the status or retry; the current app remains available.`,updateStatus:{disabled:`In-app updates unavailable`,idle:`Not checked yet`,checking:`Checking`,available:`Update available`,downloading:`Downloading`,downloaded:`Ready to install`,"not-available":`Up to date`,error:`Update failed`,installing:`Restarting to install`},updateReason:{"not-packaged":`This installation does not support in-app updates.`,"not-authorized":`In-app updates are not enabled in this version.`,"not-configured":`In-app updates are not enabled in this version.`,"unsupported-target":`In-app updates are not supported on this platform.`,"check-failed":`Could not check for updates. Try again later.`,"download-failed":`Could not download the update. Try again later.`,"install-failed":`The installer could not be started; the current version remains active.`},updateBlocked:{"write-in-progress":`Wait for the current operation to finish before installing the update.`,"watch-active":`Disable automatic sync before installing the update.`,"pending-recovery":`Complete recovery before installing the update.`,"recovery-unverified":`The app could not verify that all storage profiles are ready. Installation remains paused.`},updateVersion:`Version {{version}}`,updateProgress:`{{percent}}% downloaded`,updateCheck:`Check for updates`,updateDownload:`Download update`,updateInstall:`Restart and install`,forget:`Forget this browser`,englishFallback:`English is used when a translation is unavailable.`,forgetHint:`This browser's connection information will be removed from the local app.`},plan:{title:`Confirm operation`,switchTitle:`Confirm Provider switch`,confirmSwitch:`Confirm switch`,titles:{sync:`Confirm sync`,switch:`Confirm Provider switch`,repair:`Confirm repair`,restore:`Confirm restore`},confirmActions:{sync:`Confirm sync`,switch:`Confirm switch`,repair:`Confirm repair`,restore:`Confirm restore`},operations:{sync:`Sync Provider information`,switch:`Switch Provider`,repair:`Repair chat information`,restore:`Restore backup`,operation:`Operation`},modelModes:{"provider-default":`Use model configured for this Provider`,"keep-root-model":`Keep current root model`,explicit:`Specify root model`},historyModelsUnaffected:`Historical Provider metadata will be synchronized, but models recorded by historical sessions will not be changed.`,fields:{modelMode:`Model handling`,rootModelChange:`Root model change`,repairTargets:`Repair targets`,restoreConfig:`Restore Codex configuration`,restoreDatabase:`Restore local chat index`,restoreSessions:`Restore session files`,relocation:`Restore to another storage profile`,rolloutFiles:`Session files to update`,sqliteRows:`Local index records to update`,affectedSessions:`Affected chats (unique)`,sqliteFields:`Index field changes (total)`,sqliteModels:`Model fields`,sqliteCwd:`Working-folder fields`,sqliteUserEvent:`User-message markers`,workspaceSettings:`Workspace settings to update`,workspaceRoots:`Workspace locations to update`,stateDbFiles:`Local index files to restore`,configFiles:`Codex configuration files to restore`,lockedRollouts:`Sessions to skip this time`},stages:{prepare_config:`Read Codex configuration`,prepare_storage:`Resolve storage`,prepare_rollouts:`Prepare session files`,prepare_status:`Read current status`,prepare_revisions:`Capture protected revisions`,prepare_usage:`Check session use`,acquire_lock:`Acquire write lock`,read_config:`Read Codex configuration`,resolve_storage:`Resolve storage`,check_pending_restore:`Check pending restore`,validate_plan:`Recheck before writing`,scan_rollout_files:`Check chat records`,check_locked_rollout_files:`Check chats in use`,preflight_sqlite:`Check local chat index access`,create_backup:`Create backup`,rewrite_rollout_files:`Update chat records`,update_sqlite:`Update local chat index`,update_config:`Update Codex settings`,release_lock:`Release write lock`,clean_backups:`Organize older backups`,verify_repair:`Verify repair results`,create_restore_pre_snapshot:`Create a recovery point`,persist_restore_journal:`Prepare restore`,apply_restore_targets:`Restore selected data`,commit_restore:`Finish restore`,acknowledge_restore_commit:`Confirm restored data`,rollback_restore:`Undo incomplete restore`},statuses:{start:`Starting`,progress:`In progress`,complete:`Completed`},target:`Selected changes`,impact:`Expected changes`,expires:`Confirm before`,items:`{{count}} items`,backupExpected:`A backup will be created before writes.`,exactApply:`The app checks the data again before applying these changes. If anything changed, you will be asked to review again.`,workspaceChanges:{savedRoots:`Organize saved project folders`,projectOrder:`Organize project order`,activeRoots:`Normalize active workspace folders`,labels:`Normalize project folder labels`,openTargets:`Normalize project opening preferences`,settingsBackup:`Create the missing settings backup`},repairPreview:{effectsTitle:`What will change`,unchanged:`Chat text, message order and timestamps stay unchanged. This does not rebuild the Codex history display index.`,title:`Affected chat preview`,hint:`Choose the whole profile or only listed chats. Changing the selection creates a new preview before it can be confirmed.`,all:`Whole profile`,selected:`Selected chats`,selectSession:`Select chat {{sessionId}}`,none:`No affected chats are included in this preview.`,total:`{{count}} affected chats found`,truncated:`Only the first 100 are shown.`,regenerating:`Updating the preview. The earlier confirmation cannot be applied.`,selectionChanged:`The selection changed. Update the preview before confirming.`,update:`Update repair preview`,refineFailed:`The earlier preview has been dismissed and cannot be confirmed. Resolve the error, then prepare a new preview.`,workspaceGlobal:`Workspace settings are global. This repair applies to the whole profile and cannot be limited to selected chats.`,changes:{models:`Model label`,cwd:`Working folder`,userEvent:`User-message marker`},markers:{different:`different`,"rollout-cwd":`folder recorded in the chat file`,false:`not recorded`,true:`recorded`}},writeBlocked:`Another operation is running, or recovery is required. Wait until it is safe to continue.`,technicalDetails:`Operation details`,progress:`Operation progress`,starting:`Starting…`,cancelOperation:`Cancel operation`,cancelling:`Cancelling…`,cancelPending:`Cancellation will take effect at the next safe point.`},skips:{title:`Skipped data`,counts:`Skipped {{total}} items: {{files}} files, {{rows}} index rows; {{unknown}} unconfirmed.`,details:`Show local details`,unidentified:`Unidentified index row`,shown:`Showing {{shown}} of {{total}}; {{omitted}} omitted.`,retry:`Some files are in use or have changed. Retry those with a fresh preview; fix other listed issues first.`,fix:`Resolve the listed issues, then create a fresh preview to include these items.`,configSwitched:`Configuration switched; history files updated: {{count}}.`,incomplete:`Some session data could not be verified. You can preview and synchronize the healthy portion.`,reasons:{"metadata-invalid":`Invalid first-line metadata`,"metadata-invalid-utf8":`First-line metadata is not valid UTF-8`,"metadata-too-complex":`Metadata exceeds the processing capacity`,"metadata-too-large":`Metadata exceeds the 128 MiB input/output limit`,locked:`File is in use`,unreadable:`File cannot be read`,missing:`File disappeared`,changed:`File changed`,"write-not-applied":`Write failed; source confirmed unchanged`,"association-unknown":`Cannot confirm session association`,"association-conflict":`Session associations conflict`,"row-changed":`Index Provider changed`,"row-missing":`Index row disappeared`,deferred:`New item deferred to the next preview`},stages:{scan:`Scan`,plan:`Preview`,revalidate:`Recheck`,write:`Write`,sqlite:`Index update`}},operationResult:{title:`Operation result`,operationId:`Operation ID`,backupId:`Managed backup ID`,backupCreated:`A backup was created. You can find it under Backups and Restore.`,openBackupRestore:`Open restore preview`,changeCountersHint:`These are changed records or settings, not a count of unique chats.`,skippedRollouts:`Sessions still in use`,skippedChangedRollouts:`Sessions changed during the operation`,skippedCount:`{{count}} session records were not updated.`,retryAfterSession:`Close the active Codex session, then run sync again.`,retryFreshPlan:`Review the operation again and retry.`,reviewOperation:`Back to operation tools`,verification:{title:`Verification after repair`,status:{verified:`The selected repair targets were verified after the write.`,remaining:`Some selected metadata still needs attention. Review the remaining counts before preparing another repair.`,unavailable:`A post-write verification result was not available. No additional repair was started.`},remainingRolloutFiles:`Remaining session-file differences`,remainingSqliteRows:`Remaining local index differences`,remainingWorkspaceRoots:`Remaining workspace settings`,skippedSessions:`Skipped chat records`},partialReasons:{"skipped-data":`Some session data was skipped`,"locked-session":`A chat is still in use`,"rollout-changed":`A chat changed during the operation`,"mutation-failed":`The operation stopped after some changes were saved`},resolveBeforeClose:`Resolve the pending recovery before closing this result.`,fields:{unconfirmedSessionFiles:`Files with unconfirmed write outcome`,inPlaceSessionFiles:`In-place rollout updates`,rewrittenSessionFiles:`Fully rewritten rollouts`,targetProvider:`Target Provider`,targetModel:`Target model`,modelSource:`Model source`,partialReason:`Partial reason`,failedStage:`Failed stage`,failureCode:`Failure code`,retryRecommended:`Retry recommended`,restoreOperationId:`Restore operation ID`,preRestoreSnapshotId:`Pre-restore snapshot ID`,restoreJournalState:`Restore journal state`,backupDurationMs:`Backup duration (ms)`,changedSessionFiles:`Chat records updated`,sqliteRowsUpdated:`Local index records updated`,sqliteProviderRowsUpdated:`Provider records updated`,sqliteModelRowsUpdated:`Model records updated`,sqliteUserEventRowsUpdated:`User activity records updated`,sqliteCwdRowsUpdated:`Workspace records updated`,updatedWorkspaceRoots:`Workspace locations updated`,savedWorkspaceRootCount:`Workspace locations saved`,repairTargets:`Repair targets`,restoreVersion:`Restore format version`,resolvedOperationCount:`Resolved operations`,commitAcknowledgementRecovered:`Commit acknowledgement recovered`},completed:{title:`Completed`,description:`The operation completed and the changes were saved.`},partial:{title:`Partially completed`,description:`Some changes were not completed. Follow the guidance below to retry, or restore from a backup.`},failedRolledBack:{title:`Failed and rolled back`,description:`The operation failed, and the previous state was restored successfully.`},recoveryRequired:{title:`Recovery required`,description:`A previous restore did not finish. Complete recovery before making more changes.`},cancelled:{title:`Cancelled`,description:`The operation was cancelled and no further steps were performed.`},stale:{title:`Review required`,description:`The data changed before the operation started. Review the changes again and retry.`}},validation:{required:`This field is required.`,keep:`Use a whole number from 1 to 1000.`,provider:`Enter a valid Provider ID.`,model:`Enter the model name you want to use.`,restore:`Select at least one item to restore.`,profileId:`Use letters, numbers, dots, underscores, or hyphens.`,path:`Enter a complete folder path.`},errors:{fallback:`The operation could not be completed. Try again; if the problem continues, check Operation logs or export diagnostics.`,INVALID_INPUT:`Check the information you entered and try again.`,providerNotConfigured:`The selected Provider is not defined in config.toml. Configure or switch it using your Provider tool, then sync again. No data was changed.`,PROFILE_CHANGED:`The selected storage profile changed. Review it and try again.`,STORAGE_CHANGED:`The storage location changed. Review the operation and try again.`,PLAN_STALE:`The data changed. Review the operation again before continuing.`,PLAN_EXPIRED:`This preview expired. Preview the operation again.`,STALE_STATE:`The data changed. Review the operation again before continuing.`,CODEX_HOME_NOT_FOUND:`The Codex data folder could not be found. Check the selected storage profile.`,STATE_DB_NOT_FOUND:`The local chat index could not be found. Check the selected storage profile.`,SQLITE_UNSUPPORTED_PATH:`This chat index location cannot be used on the current platform.`,SQLITE_BUSY:`The local chat index is in use. Close Codex and try again.`,SQLITE_UNREADABLE:`The local chat index could not be read. Run diagnostics or restore a backup.`,ROLLOUT_LOCKED:`Some chats are in use. Close the active Codex sessions and try again.`,ROLLOUT_CHANGED:`Some chats changed during the operation. Review and try again.`,ROLLOUT_METADATA_TOO_LARGE:`Session metadata must stay within 128 MiB before and after syncing. Resolve the oversized header before syncing again.`,ROLLOUT_METADATA_INVALID:`The first rollout record is not valid session metadata. Resolve the invalid header before syncing again.`,PENDING_TRANSACTION:`A previous restore must be completed before continuing.`,BACKUP_FAILED:`A backup could not be created, so no changes were made.`,SYNC_FAILED_ROLLED_BACK:`The sync did not finish. The previous data was restored.`,RECOVERY_REQUIRED:`A previous restore did not finish. Complete recovery before continuing.`,RESTORE_VALIDATION_FAILED:`This backup cannot be restored to the selected location.`,PERMISSION_DENIED:`The app does not have permission to access the selected folder.`,OPERATION_BUSY:`Another operation is in progress. Wait for it to finish and try again.`,OPERATION_CANCELLED:`The operation was cancelled.`,CORE_RUNTIME_CRASHED:`The background service stopped unexpectedly. It will restart automatically when possible.`,PROTOCOL_VERSION_MISMATCH:`This app contains incompatible components. Reinstall the latest version.`,LOCK_UNVERIFIABLE:`The app could not verify that the storage location is available. Close Codex and try again.`,INTERNAL_ERROR:`An internal error occurred. Try again; if it continues, export diagnostics.`},warnings:{backupInventory:`The backup list could not be refreshed. Your existing backups were not changed.`,backupCleanup:`The operation completed, but older backups could not be deleted automatically.`,encryptedHistory:`Some encrypted chats may require the original Provider or account to continue.`,lockedSessions:`Some chats are currently in use and may not be updated. Close them and sync again.`,missingDefaultModel:`This Provider has no model configured. The current root model will be kept.`,projectVisibility:`Project chat visibility could not be checked. A backup will still be created before changes.`,relocationConfig:`The chat index will be restored to another storage profile, but the Codex configuration will not be restored.`,restoreSkipped:`The selected backup does not contain one of the requested items, so that item will be skipped.`,partial:`Only part of the requested change was completed. Try again or restore the backup.`,additional:`The operation completed with an additional warning. Review the operation log for details.`}}},"zh-CN":{translation:{requestProgress:{working:`处理中…`,elapsed:`已耗时 {{time}}`,files:`已检查 {{count}} 个文件`,stagePercent:`当前阶段 {{percent}}%`,stages:{waiting:`正在开始…`,prepare_repair_context:`正在读取配置并核对预览状态…`,prepare_diagnostics:`正在准备检查…`,scan_sessions:`正在检查会话记录…`,scan_archived_sessions:`正在检查已归档会话…`,inspect_repair_sqlite:`正在检查需要调整的聊天索引…`,inspect_workspace_roots:`正在检查工作区设置…`,build_repair_preview:`正在生成改动预览…`,inspect_diagnostics_index:`正在检查聊天索引…`,inspect_diagnostics_backups:`正在检查备份与恢复状态…`,inspect_history_integrity:`正在准备会话完整性检查…`,integrity_sessions:`正在检查会话记录完整性…`,integrity_archived_sessions:`正在检查归档记录完整性…`,finish_diagnostics:`正在汇总检查结果…`}},backupPolicy:{title:`备份设置`,count:`保留备份数量`,save:`保存备份设置`,scope:`本应用统一使用一套规则,同步、切换、专项修复和自动同步共用。每个 Codex Home 分别保留备份,不按操作类型重复计算。`,current:`已保存规则:每个 Codex Home 保留最近 {{count}} 份备份。`,operationHint:`改动前自动备份,保留最近 {{count}} 份。统一在“备份与恢复”中管理。`,hint:`保存设置不会删除备份;后续写操作使用已保存规则,手动清理仍需确认。恢复所需的受保护备份可能超过该数量。修改前请先停止自动同步。`,saved:`备份设置已保存,没有删除任何备份。`,"watch-active":`自动同步正在运行,请先在设置中停止,再保存备份规则。`,failed:`备份设置保存失败,原规则未变,请重试。`,clear:`删除全部可清理备份`},ux:{reading:`正在读取状态…`,unknown:`尚未验证`,previousSnapshot:`正在刷新,当前显示上次快照。`,currentProfile:`正在使用`,finalStatus:`最终 Provider 检查`,finalChecking:`正在读取操作后的状态…`,finalUnavailable:`操作结果已返回,但最终 Provider 对齐状态尚未验证。请刷新概览后确认。`,pruneEstimate:`按当前列表估算:最多清理 {{remove}} 份备份,至少保留 {{keep}} 份。`,pruneCaution:`恢复所需的备份仍受保护。列表可能变化,实际清理数量以执行结果为准。`,pruneTitle:`确认清理备份`,pruneConfirm:`确认清理`,pruneZero:`本次将请求删除所有可清理的受管备份,不会删除受保护的恢复备份。删除后无法通过本工具找回,自动保留规则不会改变。`,pruneChanged:`备份列表或存储配置已变化,请关闭后重新确认清理范围。`,clearFilters:`清除筛选`,pendingFilters:`搜索词、Provider 或搜索范围已修改,点击搜索后生效。`},brand:{desktop:{label:`桌面端`,subtitle:`管理 Codex Provider 与本地会话记录`},web:{label:`Web`,subtitle:`本地 Web 管理界面`}},a11y:{skipToContent:`跳到主要内容`,profile:`存储配置`,primaryNavigation:`主导航`},nav:{overview:`概览`,sync:`同步`,switchProvider:`切换 Provider`,backupsRestore:`备份 / 恢复`,history:`聊天记录`,operationLogs:`操作日志`,profiles:`存储配置`,diagnostics:`高级功能`,settings:`设置`},common:{refresh:`刷新`,loading:`正在加载…`,processing:`处理中`,cancel:`取消`,confirm:`确认并执行`,save:`保存`,delete:`删除`,close:`关闭`,dismissNotification:`关闭通知:{{title}}`,yes:`是`,no:`否`,none:`无`,unknown:`未知`,current:`当前`,provider:`Provider`,model:`模型`,status:`状态`,warnings:`警告`,retry:`重试`,advanced:`高级选项`,search:`搜索`,copy:`复制`,copied:`已复制`},global:{ready:`就绪`,readingStatus:`正在读取状态…`,statusUnavailable:`无法读取当前状态`,statusNeedsRefresh:`状态待刷新`,statusChangedHint:`数据发生变化,请刷新后重试。`,statusUnavailableHint:`未能读取完整状态,请刷新重试。`,retryStatus:`重新读取状态`,busy:`操作执行中`,busyHint:`另一项操作正在使用当前存储位置,完成后即可继续。`,lockUnverified:`存储锁需要检查`,lockUnverifiedHint:`无法确认另一项操作是否已结束。关闭其他同步工具后重新检查;若仍无法继续,请在高级功能中导出诊断包。请勿手动删除锁。`,staleLock:`上次操作已结束`,staleLockHint:`可以正常预览或同步。写入前会重新检查,并在确认安全后清理上次操作留下的锁。`,recoveryTitle:`需要先恢复数据`,recovery:`上一次恢复没有完成。请先完成恢复,再执行其他修改。`,stale:`数据已经发生变化,请重新检查后再执行。`,unexpected:`出现了问题,请重试。`,partial:`部分记录暂未更新。请关闭正在使用的 Codex 会话后重试。`,completed:`操作已完成。`,cancelled:`操作已取消。`,profileChanged:`存储配置已变化。`,profileChangedHint:`请检查当前选择的存储位置,然后重试。`,failed:`本次操作未能完成。`},overview:{title:`Provider 同步概览`,subtitle:`查看当前 Provider 与本地聊天记录是否保持一致。`,alignment:`同步状态`,aligned:`已同步`,notAligned:`建议同步`,rollout:`会话记录文件`,sqlite:`本地聊天索引`,codexHomeSource:`Codex 数据位置`,sqliteHomeSource:`聊天索引位置`,stateDbPath:`当前数据库文件`,stateDbMissing:`尚未找到数据库`,snapshot:`快照时间`,backupCount:`可用备份`,locked:`正在使用的会话`,usageUnknown:`未知`,profile:`当前存储配置`,manageStorage:`管理存储配置`,operations:`同步与切换`,operationsHint:`在这里同步当前 Provider,或切换到其他 Provider。`,sources:{profile:`当前存储配置`,config:`Codex 配置文件`,env:`环境变量`,default:`默认位置`,explicit:`当前存储配置`,unknown:`未能确定`}},sync:{title:`同步当前 Provider`,subtitle:`只按当前配置同步 Provider 信息,不修复模型、聊天正文或历史记录。`,keep:`保留最近备份数量`,prepare:`预览同步`,direct:`直接同步`,directHint:`直接同步使用当前 Provider,不再弹出确认。写入前仍会检查并备份,不执行高级修复。`,preparingDirect:`正在检查同步内容`,runningDirect:`正在同步`,performance:{title:`如何加快同步`,resultLink:`查看提速建议`,equalLength:`使用等长的英文 Provider ID 并通过文件检查时,可直接更新标记,无需复制整个聊天文件,通常更快。例如 openai 与 prov_a 都是 6 个字符。`,differentLength:`长度不同时仍可正常同步,但需要复制文件,聊天文件越大,耗时越长。软件会自动选择合适的方式,无需开启设置。`,configuration:`如需调整 Provider ID,请在配置及所用的 Provider 管理工具中保持一致,只修改显示名称无效。不改名也可以正常同步。`}},switchPage:{title:`单独切换 Provider`,subtitle:`修改配置中的 Provider,再执行同样的 Provider 同步。执行前可以预览改动范围。`,provider:`Provider ID`,modelMode:`模型处理方式`,providerDefault:`使用 config.toml 中该 Provider 的模型`,keepModel:`保留当前根模型`,explicitModel:`手动指定根模型`,modelModeDescriptions:{"provider-default":`读取 config.toml 中 [model_providers.{{provider}}].model;未配置时保留当前根模型,不会联网查询 Provider。`,"keep-root-model":`只切换 model_provider,不修改 config.toml 根级 model。`,explicit:`将下方填写的模型名写入 config.toml 根级 model;不会验证远程 Provider 是否支持。`},historyModelHint:`切换时只同步历史记录的 Provider,不修改历史会话记录的模型;如需修改,请前往“高级功能 → 高级调整”。`,recentSuccessful:`最近成功使用`,model:`模型名称`,prepare:`预览切换`},backups:{title:`备份与恢复`,subtitle:`查看本应用创建的备份,并在需要时恢复数据。`,empty:`还没有备份。应用会在修改数据前自动创建备份。`,loadFailed:`无法读取备份,未更改任何备份。`,requestedMissing:`当前存储配置中已找不到这份备份,可能已按保留数量清理。请选择现有备份。`,selectBackup:`请先选择一份备份,再选择恢复内容。`,capturedHint:`只能恢复这份备份实际保存的内容;配置恢复也包含已备份的工作区设置。`,relocationTargetRequired:`请选择已设置自定义 SQLite 位置的目标存储配置。`,relocationHint:`聊天索引将恢复到所选目标;不恢复 Codex 配置和工作区设置。如果选择了会话记录文件,它们仍恢复到来源 Codex Home。`,restoreConfig:`恢复 Codex 配置`,restoreDatabase:`恢复本地聊天索引`,restoreSessions:`恢复会话记录文件`,relocation:`恢复到其他存储配置`,targetProfile:`恢复到的存储配置`,prepare:`预览恢复`,pruneKeep:`保留最新备份数`,prune:`删除较早的备份`,readOnly:`当前版本可以查看备份,但暂不支持恢复或删除。`},history:{title:`聊天记录`,subtitle:`选择一条会话即可查看聊天内容。`,empty:`没有找到会话。`,untitled:`未命名会话`,subagentTitle:`子任务 · {{name}}`,sessionActions:`会话操作`,noProject:`其他会话`,filters:`搜索选项与筛选`,projectTreeHint:`按项目显示主会话 · 点击箭头展开子任务`,mainWithSubtasks:`主会话及其子任务`,rootCount:`{{count}} 条主会话`,orphanCount:`{{count}} 条未关联子任务`,orphans:`未关联子任务`,orphansHint:`这些记录缺少可靠的主会话关联,单独保留,不会删除。`,toggleSubtasks:`{{title}} 的子任务({{count}})`,childrenOf:`{{title}} 的子任务`,loadMore:`加载更多`,retryLoad:`重试`,directoryBadge:`工作目录`,projectKinds:{workspace:`已保存的工作区`,directory:`会话记录的工作目录,尚未匹配已保存的工作区。`,unassigned:`未记录项目目录`,orphans:`父会话关系缺失或无效`},projectActions:`项目显示设置`,projectAliasTitle:`设置项目显示名`,projectAliasReset:`恢复原名称`,projectDisplayName:`显示名称`,projectAliasHint:`仅修改本应用在当前存储配置中的显示名称,不重命名目录、不修改 Codex 数据。留空可恢复原名称。`,projectAliasContextHint:`右键或按 Shift+F10 可设置本地显示名。`,projectAliasFailed:`未能保存显示名称,请使用不含控制字符的名称(最多 160 字),然后重试。`,contextMenuHint:`右键或按 Shift+F10 打开会话菜单。`,groupCount:`本页 {{count}} 条会话`,showMore:`展开显示`,showLess:`收起显示`,copyId:`复制会话 ID`,copyResume:`复制继续命令`,copyPath:`复制文件路径`,revealFile:`在资源管理器中显示`,fileRevealed:`已定位会话文件。`,revealFailed:`无法定位文件,请刷新后重试。`,copyFailed:`未能复制,请重试,或选中文字后手动复制。`,missingNativeId:`此记录没有原始会话 ID,内部列表标识不能用于继续会话。`,resumeHint:`仅复制命令。请在对应的 Codex Home 环境及原项目目录中运行;不会切换 Provider,也不保证旧会话可以继续。`,sessionInformation:`会话信息`,nativeId:`原始会话 ID`,sessionType:`会话类型`,mainSessions:`主会话`,subtasks:`子任务`,parentId:`父会话 ID`,openParent:`查看父会话`,parentUnavailable:`当前存储配置中找不到该父会话。`,recordedProvider:`记录的 Provider`,recordedModel:`记录的模型`,notRecorded:`未记录`,createdAt:`创建时间`,fileModifiedAt:`文件更新`,fileTimeHint:`同步等操作可能改变文件时间;这不代表最后聊天时间。`,projectDirectory:`项目目录`,sessionFile:`会话文件`,localInfoHint:`桌面端加载该会话后可查看本地路径。`,searchScope:`搜索范围`,metadataSearch:`标题 / ID / 项目`,contentSearch:`聊天正文`,metadataSearchHint:`只查名称、ID、项目和 Provider,不读取聊天正文。按回车或点击搜索后运行。`,contentSearchHint:`按回车或点击搜索后才扫描聊天正文;会话较多时可能需要一些时间。`,untitledIdentity:`无标题会话 · {{date}} · {{id}}`,open:`查看会话`,back:`返回聊天列表`,messages:`条消息`,archived:`已归档`,active:`活动`,pagination:`聊天分页`,listRegion:`会话列表`,detailRegion:`会话详情与消息`,refreshDetail:`刷新当前会话`,pageSummary:`第 {{page}} 页 · 共 {{total}} 个聊天`,previous:`上一页`,next:`下一页`,searchPlaceholder:`搜索聊天记录`,providerFilter:`按 Provider 筛选`,archivedFilter:`会话状态`,all:`全部会话`,select:`从左侧选择一条会话查看聊天内容。`,truncated:`该会话内容较长,仅显示最近 200 条消息。`,searchHint:`点击搜索后才会查找聊天内容;会话较多时可能需要一些时间。`,roles:{user:`你`,assistant:`助手`}},logs:{profileMismatch:`这些操作需要匹配原来的存储配置及版本。请选择原配置;如果位置已更改,请手动查找对应备份。`,title:`操作日志`,subtitle:`查看本应用发起的操作、执行过程、结果与耗时。不会记录聊天内容或凭据。`,empty:`还没有操作记录。完成同步、切换、恢复或修复后会显示在这里。`,select:`选择一条操作,查看执行结果和耗时。`,listRegion:`操作列表`,detailRegion:`操作详情`,backToList:`返回操作列表`,refreshDetail:`刷新操作详情`,identifiers:`关联编号`,detailUnavailable:`这条日志已不可用,可能已被日志保留策略清理。`,profileFilter:`存储配置筛选`,allProfiles:`全部存储配置`,operationFilter:`操作类型筛选`,statusFilter:`按状态筛选`,allOperations:`全部操作`,allStatuses:`全部结果`,activeDuration:`执行耗时`,wallDuration:`总耗时(含等待确认)`,startedAt:`开始时间`,completedAt:`结束时间`,timeline:`执行过程`,counts:`实际完成数量`,previewCounts:`预览改动数量`,switchPlan:`计划的 Provider 切换`,switchPlanUnavailable:`这条旧记录未保存切换详情。`,fileTiming:{title:`文件更新耗时`,pending:`执行结束后显示文件更新耗时。`,unavailable:`本次操作未记录文件分项耗时。`,files:`已计时 {{measured}} / {{attempted}} 个文件 · 原地更新 {{inPlace}} · 替换 {{rewritten}} · 跳过 {{skipped}}`,incomplete:`部分文件未返回计时,以下不是全部文件的完整耗时。`,milliseconds:`{{value}} 毫秒`,more:`技术耗时详情`,nested:`请求耗时包含工作进程处理,进程处理包含各文件阶段,不能重复相加。文件时间戳恢复仍保留。`,phases:{copyTailMs:`复制未改动内容`,flushMs:`数据落盘`,replaceMs:`替换文件`,cleanupMs:`清理临时文件`,restoreMtimeMs:`恢复文件时间戳`,workerStartupMs:`启动文件工作进程`,workerCloseMs:`关闭文件工作进程`,requestRoundTripMs:`请求往返(含文件处理)`,workerMs:`工作进程处理`,sourceOpenMs:`打开文件与检查占用`,readHeaderMs:`读取与核对首行`,tempCreateMs:`创建临时文件`}},notSet:`未设置`,providerChange:`Provider`,rootModelChange:`根模型`,modelMode:`模型处理方式`,switchPlanPartial:`这里显示的是预览目标;本次操作仅部分完成,请先查看上方实际完成数量再决定是否重试。`,targetProvider:`目标 Provider`,errorReason:`原因`,errorReasons:{profile:`存储配置已变化`,config:`Codex 配置已变化`,storage:`存储位置已变化`,rollout:`会话记录已变化`,"state-db":`本地聊天索引已变化`,backup:`备份状态已变化`,"provider-not-configured":`Provider 尚未配置`},previewCountLabels:{rolloutFilesToChange:`待更新会话记录`,sqliteRowsToChange:`待更新本地索引记录`,lockedRolloutFiles:`正在使用的会话`},pageSummary:`第 {{page}} 页 · 共 {{total}} 条操作`,lessThanSecond:`不足 1 秒`,seconds:`{{value}} 秒`,minutesSeconds:`{{minutes}} 分 {{seconds}} 秒`,logId:`日志编号`,requestId:`请求编号`,planId:`确认编号`,operationId:`操作编号`,backupId:`备份编号`,otherOperation:`其他操作`,unknownStage:`正在处理`,operations:{sync:`同步`,switch:`切换 Provider`,repair:`修复`,restore:`恢复`,pruneBackups:`删除较早备份`,diagnostics:`诊断`,watch:`自动同步`,update:`更新`,profile:`存储配置`,runtime:`后台服务`},statuses:{running:`执行中`,"awaiting-confirmation":`等待确认`,completed:`已完成`,partial:`部分完成`,failed:`失败`,cancelled:`已取消`,dismissed:`开始前取消`,interrupted:`异常中断`},stages:{prepare:`预览改动`,prepare_config:`读取 Codex 配置`,prepare_storage:`解析存储位置`,prepare_rollouts:`准备会话记录`,prepare_status:`读取当前状态`,prepare_revisions:`记录受保护版本`,prepare_usage:`检查会话使用情况`,acquire_lock:`获取写入锁`,read_config:`读取 Codex 配置`,resolve_storage:`解析存储位置`,check_pending_restore:`检查未完成的恢复`,validate_plan:`写入前复核`,scan:`检查数据`,scan_rollout_files:`检查会话记录`,check_locked_rollout_files:`检查正在使用的会话`,create_backup:`创建备份`,rewrite_rollout_files:`更新会话记录`,repair_workspace_roots:`更新工作区位置`,update_sqlite:`更新本地聊天索引`,update_config:`更新 Codex 配置`,preflight_sqlite:`检查本地聊天索引访问`,release_lock:`释放写入锁`,clean_backups:`整理较早备份`,verify_repair:`核验修复结果`,create_restore_pre_snapshot:`创建恢复前快照`,persist_restore_journal:`准备恢复记录`,apply_restore_targets:`恢复所选数据`,commit_restore:`完成恢复`,acknowledge_restore_commit:`确认恢复结果`,rollback_restore:`撤销未完成的恢复`,prune:`删除较早备份`,start:`开启自动同步`,stop:`关闭自动同步`,"automatic-sync":`执行自动同步`,create:`新建存储配置`,update:`更新存储配置`,delete:`删除存储配置`,export:`导出诊断信息`,check:`检查更新`,download:`下载更新`,install:`安装更新`},stageStatuses:{running:`执行中`,completed:`已完成`,failed:`失败`},countLabels:{changedSessionFiles:`已更新会话记录`,inPlaceSessionFiles:`已原地更新会话记录`,rewrittenSessionFiles:`已重写会话记录`,sqliteRowsUpdated:`已更新本地索引记录`,sqliteProviderRowsUpdated:`已更新 Provider 记录`,sqliteModelRowsUpdated:`已更新模型记录`,sqliteUserEventRowsUpdated:`已更新用户操作记录`,sqliteCwdRowsUpdated:`已更新工作区记录`,skippedLockedRolloutFiles:`仍在使用的会话`,skippedChangedRolloutFiles:`操作期间发生变化的会话`,updatedWorkspaceRoots:`已更新工作区位置`,savedWorkspaceRootCount:`已保存工作区位置`,resolvedOperationCount:`已完成恢复的项目`}},profiles:{title:`存储配置`,subtitle:`为使用的不同 Codex 数据位置创建配置。目录信息只保存在此设备。`,id:`配置 ID`,name:`名称`,codexHome:`Codex 数据目录`,sqliteHome:`聊天索引目录(可选)`,create:`新建配置`,update:`保存修改`,managed:`默认`,chooseFolder:`选择目录`,keepCurrent:`不更改当前目录`,notSelected:`尚未选择目录`,inheritSqlite:`自动查找聊天索引目录`,customSqlite:`选择聊天索引目录`,revealCodex:`打开 Codex 数据目录`,revealSqlite:`打开聊天索引目录`,selectCodexRequired:`请为新配置选择 Codex 数据目录。`,defaultName:`默认位置`,defaultManaged:`默认位置由应用启动时的 Codex 设置确定,不能修改或删除。如需使用其他位置,请新建存储配置。`,saved:`存储配置已保存`,deleted:`存储配置已删除`,unavailable:`当前无法管理存储配置。`,pathManaged:{desktop:`目录位置由本应用在此设备上安全保存。`,web:`目录位置由本地 Web 应用保存。`},readOnly:`当前版本可以查看存储配置,但暂不支持编辑。`},diagnostics:{title:`高级功能`,subtitle:`仅在遇到具体问题时使用。日常同步和切换 Provider,请在概览中操作。`,scanTitle:`完整诊断 · 只读`,scanHint:`需要排查问题时再手动检查。不会修改数据或自动修复,报告不包含聊天正文和凭据。`,repairScope:`以下修复不处理会话记录序号,也不重建 Codex 历史显示索引;普通 Provider 同步不会执行这些修复。`,runtime:`应用环境`,storage:`存储位置`,provider:`Provider`,issues:`检查结果`,issuesHint:`以下是元数据差异和兼容性提示,不是聊天损坏数量,也不会自动修复。`,modelDifferenceHint:`历史会话使用不同模型可能是正常情况。只有希望统一为当前根模型时,才需要调整模型标签。`,workspaceCountHint:`工作区按待调整的设置项计数(包括缺少设置备份),不是目录数或会话数。`,encryptedHint:`加密内容是正常的会话数据,不代表损坏。这里只检测字段存在,不验证能否解密,也不会修改;跨 Provider/账号继续对话时,可能需要切回原 Provider/账号。`,safety:`运行状态`,runScan:`开始诊断`,retryScan:`重试诊断`,scanning:`正在扫描… 完整诊断可能需要几分钟。可以先切换页面,稍后回来查看结果。`,scanFailed:`诊断未能完成`,scanFailedHint:`数据未被修改。请重试诊断;若再次失败,可在操作日志中查看详情。`,previousResult:`上次成功结果 · {{time}}(不是本次扫描结果)`,expiredResult:`较早的诊断结果 · {{time}}(之后已完成一次写入;请重新运行诊断以获取当前结果)`,scanCompleted:`诊断完成 · {{time}}`,incompleteScan:`检查时部分数据发生变化或无法读取。结果仅供参考,可在会话空闲后重新检查。`,notScanned:`尚未运行诊断`,notScannedHint:`需要详细检查时再手动运行。诊断不会自动执行,也不会修改数据。`,repairTitle:`专项修复`,repairHint:`遇到下面对应的问题时再使用。日常同步无需勾选;选择一项后先预览改动,再确认执行。`,adjustmentTitle:`高级调整`,adjustmentHint:`这里是可选调整,不是故障修复。历史会话使用不同模型很正常;不需要统一名称时,请保持不选。`,previewAdjustment:`预览调整`,availableRepairs:`本次检查可处理的项目`,viewRepair:`查看修复`,viewSpecificRepair:`查看修复:{{target}}`,findings:{cwd:`{{count}} 条聊天索引的所属目录与聊天文件不一致`,userEvent:`{{count}} 条聊天索引缺少用户消息标记`,workspaceRoots:`{{count}} 项项目目录设置可整理`},repairTargetHints:{models:`仅在想把历史会话记录的模型名称统一为当前配置模型时使用。会修改聊天文件和索引中的模型名称,不会重新生成回答,也不切换 Provider。`,cwd:`聊天索引记录的项目目录与聊天文件不一致时使用。按聊天文件中记录的目录修正索引,不移动文件,也不改变你当前打开的项目。`,userEvent:`聊天中已有用户消息,但索引未标记时使用。只补全索引中的“包含用户消息”标记,不新增、删除或修改消息。`,workspaceRoots:`保存的项目目录设置有重复或格式不一致时使用。会整理设置并保留设置备份,不移动或删除项目文件夹;作用于整个存储配置,并一并修正会话所属目录。`},repairTargetRequired:`请至少选择一个修复目标。`,workspaceRootsIncludesCwd:`此项会一并修正整个存储配置中的会话所属目录,不能只选择个别会话。`,prepareRepair:`预览修复`,repairTargets:{models:`统一历史模型名称`,cwd:`修正会话所属目录`,userEvent:`补全用户消息标记`,workspaceRoots:`整理项目目录记录`},items:`{{count}} 项`,fieldsAvailable:`{{count}} 个脱敏字段`,technicalDetails:`显示技术详情`,fields:{arch:`架构`,node:`Node.js`,platform:`平台`,sqliteHomeSource:`SQLite Home 来源`,sqliteSupported:`SQLite 支持状态`,stateDbFound:`State DB 是否存在`,configured:`已配置 Provider`,current:`当前 Provider`,implicit:`隐式 Provider`,rolloutCounts:`Rollout 分布`,sqliteCounts:`SQLite 分布`,rootModelAvailable:`根模型可用`,rolloutModelFilesNeedingRepair:`模型标签与根模型不同的会话文件`,sqliteModelRowsNeedingRepair:`模型标签与根模型不同的索引记录`,cwdRowsNeedingRepair:`工作目录与会话文件不同的索引记录`,userEventRowsNeedingRepair:`缺少已有用户消息标记的索引记录`,workspaceRootsNeedingRepair:`工作区设置待调整项`,encryptedContentFiles:`包含加密内容的会话文件(仅提示)`,lockedRolloutCount:`锁定的 rollout`,operationInProgress:`执行中的操作`,pendingRecovery:`需要恢复`,pendingTransactions:`待处理事务`,projectThreadVisibilityAvailable:`项目可见性可用`,rolloutScanComplete:`Rollout 扫描完成`,storageRevision:`存储 revision`},export:`导出脱敏诊断包`,exporting:`正在导出…`,exportCreated:`脱敏诊断包已创建。`,exportCancelled:`已取消诊断导出。`,exportFailed:`诊断导出失败。`,historyIntegrity:{title:`历史记录检查`,scope:`此项有边界的只读检查仅观察 JSON 记录和数字顺序;不宣称历史显示正常,不修复记录,也不会把缺少序号视为损坏。`,displayIndexUnsupported:`本应用不知道 Codex 历史显示索引的格式,因此未验证或重建该索引。`,outcomes:{"no-findings":`未发现观察项`,findings:`发现观察项`,inconclusive:`检查未完成`,"findings-and-inconclusive":`有观察项且检查未完成`},skipped:`部分记录在扫描限制内被跳过,结果应视为未完成。`,findings:`需要人工查看的观察项`,moreFindings:`部分观察结果未列出,请在技术详情中查看。`,manualReview:`需要人工查看`,session:`会话 {{sessionId}}`,line:`第 {{line}} 行`,copySessionId:`复制会话 ID`,copiedSessionId:`会话 ID 已复制`,issueCodes:{"unsupported-format":`记录格式需要人工查看`,"invalid-utf8":`记录文本无法按 UTF-8 读取`},counts:{filesDiscovered:`发现的文件`,filesScanned:`已扫描文件`,recordsRead:`已读取记录`,sessionsWithId:`带会话 ID 的记录`,jsonCorruptRecords:`JSON 无效的记录`,oversizedRecords:`超过大小限制的记录`,duplicateOrdinals:`重复的数字顺序`,outOfOrderOrdinals:`顺序错位的数字记录`,changedFiles:`扫描中发生变化的文件`,truncatedFiles:`达到扫描限制后停止的文件`}}},settings:{title:`设置`,subtitle:{desktop:`管理显示、自动同步与应用更新。偏好只保存在此设备。`,web:`管理显示与浏览器设置。偏好只保存在此浏览器。`},language:`语言`,languageHint:`修改后立即生效。`,theme:`主题`,system:`跟随系统`,light:`浅色`,dark:`深色`,watch:`自动同步`,watchHint:`当前存储位置的文件变化时,自动同步 Provider 信息。同一 Codex Home 共用一个监听,关闭时一起停止。监听选项及执行、停止日志归首次启用的配置所有(日志中选“全部配置”可查看)。`,watchStart:`开启自动同步`,watchStop:`关闭自动同步`,watchRecoveryBlocked:`请先完成数据恢复,再开启自动同步。`,watchStatuses:{running:`已开启`,stopped:`已关闭`,starting:`正在开启`,stopping:`正在关闭`,failed:`需要处理`},update:`更新`,updateCurrentVersion:`当前版本:{{version}}`,updateManualHint:`每天首次启动检查一次,仅发现新版时弹窗。便携版或本地构建会打开 GitHub 下载页,请下载后手动替换;不会自动安装或退出。`,updateAutomaticHint:`每天首次启动检查一次,有新版时弹窗提示。按需下载,再确认重启安装。更新不替换你的 Codex 数据。`,updateOpenDownload:`打开官方下载页`,updateIgnore:`不再提醒此版本`,updateRestoreReminder:`恢复此版本提醒`,updateIgnored:`已关闭此版本提醒,仍可正常更新。`,updateReminderFailed:`未能保存提醒设置,请重试。`,updateRequestFailed:`更新请求失败,请刷新状态或重试;当前软件仍可正常使用。`,updateStatus:{disabled:`应用内更新不可用`,idle:`尚未检查更新`,checking:`正在检查`,available:`发现新版本`,downloading:`正在下载`,downloaded:`可安装`,"not-available":`已是最新版本`,error:`更新失败`,installing:`正在重启安装`},updateReason:{"not-packaged":`当前安装方式不支持应用内更新。`,"not-authorized":`此版本暂未启用应用内更新。`,"not-configured":`此版本暂未启用应用内更新。`,"unsupported-target":`当前平台不支持应用内更新。`,"check-failed":`检查更新失败,请稍后重试。`,"download-failed":`下载更新失败,请稍后重试。`,"install-failed":`无法启动安装程序,当前版本仍保持可用。`},updateBlocked:{"write-in-progress":`请等待当前操作完成后再安装更新。`,"watch-active":`请先关闭自动同步,再安装更新。`,"pending-recovery":`请先完成数据恢复,再安装更新。`,"recovery-unverified":`无法确认所有存储配置均可安全更新,安装已暂停。`},updateVersion:`版本 {{version}}`,updateProgress:`已下载 {{percent}}%`,updateCheck:`检查更新`,updateDownload:`下载更新`,updateInstall:`重启并安装`,forget:`忘记此浏览器`,englishFallback:`缺少翻译时将显示英文。`,forgetHint:`将从本地应用中移除此浏览器的连接信息。`},plan:{title:`确认操作`,switchTitle:`确认切换`,confirmSwitch:`确认切换`,titles:{sync:`确认同步`,switch:`确认切换`,repair:`确认修复`,restore:`确认恢复`},confirmActions:{sync:`确认同步`,switch:`确认切换`,repair:`确认修复`,restore:`确认恢复`},operations:{sync:`同步 Provider 信息`,switch:`切换 Provider`,repair:`修复聊天信息`,restore:`恢复备份`,operation:`操作`},modelModes:{"provider-default":`使用 config.toml 中该 Provider 的模型`,"keep-root-model":`保留当前根模型`,explicit:`手动指定根模型`},historyModelsUnaffected:`将同步历史记录的 Provider,但不会修改历史会话实际记录的模型。`,fields:{modelMode:`模型处理方式`,rootModelChange:`根模型变化`,repairTargets:`修复目标`,restoreConfig:`恢复 Codex 配置`,restoreDatabase:`恢复本地聊天索引`,restoreSessions:`恢复会话记录文件`,relocation:`恢复到其他存储配置`,rolloutFiles:`需要更新的会话记录`,sqliteRows:`需要更新的本地索引记录`,affectedSessions:`受影响会话(去重)`,sqliteFields:`索引字段改动(合计)`,sqliteModels:`模型名称字段`,sqliteCwd:`会话所属目录字段`,sqliteUserEvent:`用户消息标记`,workspaceSettings:`工作区设置改动项`,workspaceRoots:`需要更新的工作区位置`,stateDbFiles:`需要恢复的本地索引文件`,configFiles:`需要恢复的 Codex 配置文件`,lockedRollouts:`本次将跳过的会话`},stages:{prepare_config:`读取 Codex 配置`,prepare_storage:`解析存储位置`,prepare_rollouts:`准备会话记录`,prepare_status:`读取当前状态`,prepare_revisions:`记录受保护版本`,prepare_usage:`检查会话使用情况`,acquire_lock:`获取写入锁`,read_config:`读取 Codex 配置`,resolve_storage:`解析存储位置`,check_pending_restore:`检查未完成的恢复`,validate_plan:`写入前复核`,scan_rollout_files:`检查聊天记录`,check_locked_rollout_files:`检查正在使用的聊天`,preflight_sqlite:`检查本地聊天索引访问`,create_backup:`创建备份`,rewrite_rollout_files:`更新聊天记录`,update_sqlite:`更新本地聊天索引`,update_config:`更新 Codex 设置`,release_lock:`释放写入锁`,clean_backups:`整理较早备份`,verify_repair:`核验修复结果`,create_restore_pre_snapshot:`创建恢复点`,persist_restore_journal:`准备恢复`,apply_restore_targets:`恢复所选数据`,commit_restore:`完成恢复`,acknowledge_restore_commit:`确认恢复结果`,rollback_restore:`撤销未完成的恢复`},statuses:{start:`正在开始`,progress:`执行中`,complete:`已完成`},target:`本次选择`,impact:`预计改动`,expires:`请在此时间前确认`,items:`{{count}} 项`,backupExpected:`写入前会先创建备份。`,exactApply:`执行前会再次确认数据没有变化;如果数据已变化,需要重新预览。`,workspaceChanges:{savedRoots:`整理已保存的项目目录`,projectOrder:`整理项目排序`,activeRoots:`统一当前工作区目录格式`,labels:`统一项目目录标签`,openTargets:`统一项目打开方式设置`,settingsBackup:`补建缺失的设置备份`},repairPreview:{title:`受影响会话预览`,effectsTitle:`将修改什么`,unchanged:`聊天正文、消息顺序和时间保持不变;不会重建 Codex 历史显示索引。`,hint:`可选择整个存储配置,或仅选择列表中的会话。修改选择后会生成新的预览,不能继续确认旧预览。`,all:`整个存储配置`,selected:`已选会话`,selectSession:`选择会话 {{sessionId}}`,none:`本次预览未包含受影响会话。`,total:`共找到 {{count}} 个受影响会话`,truncated:`仅显示前 100 个。`,regenerating:`正在更新预览,之前的确认不能执行。`,selectionChanged:`选择已变更,请先更新预览,再确认执行。`,update:`更新修复预览`,refineFailed:`之前的预览已撤销,不能确认执行。请先处理错误,再重新生成预览。`,workspaceGlobal:`工作区设置属于全局项。该修复会作用于整个存储配置,不能仅限所选会话。`,changes:{models:`模型标签`,cwd:`工作目录`,userEvent:`用户消息标记`},markers:{different:`不一致`,"rollout-cwd":`聊天文件中记录的目录`,false:`未记录`,true:`已记录`}},writeBlocked:`当前有其他操作正在执行,或存在待恢复数据,暂时不能继续。`,technicalDetails:`操作详情`,progress:`操作进度`,starting:`正在开始…`,cancelOperation:`取消操作`,cancelling:`正在取消…`,cancelPending:`取消将在下一个安全点生效。`},skips:{title:`已跳过的问题数据`,counts:`跳过 {{total}} 项:文件 {{files}} 个、索引 {{rows}} 条;未确认 {{unknown}} 项。`,details:`查看本机明细`,unidentified:`无法安全标识的索引行`,shown:`共 {{total}} 项,展示 {{shown}} 项,省略 {{omitted}} 项。`,retry:`部分文件正在使用或已变化,可稍后重新预览同步;其他问题请按明细处理后再试。`,fix:`请先处理明细中的问题,再重新预览,将修好的数据纳入同步。`,configSwitched:`配置已切换,历史成功 {{count}} 条。`,incomplete:`存在无法确认的问题数据。可以继续预览并同步正常部分。`,reasons:{"metadata-invalid":`首行元数据格式无效`,"metadata-invalid-utf8":`首行元数据不是有效的 UTF-8 编码`,"metadata-too-complex":`首行元数据超出处理能力`,"metadata-too-large":`首行元数据在同步前或同步后超过 128 MiB`,locked:`文件正在使用`,unreadable:`文件无法读取`,missing:`文件已消失`,changed:`文件已变化`,"write-not-applied":`写入失败,已确认源文件未受损`,"association-unknown":`无法确认会话归属`,"association-conflict":`会话关联冲突`,"row-changed":`索引 Provider 已变化`,"row-missing":`索引行已消失`,deferred:`新数据留待下一次预览`},stages:{scan:`扫描`,plan:`预览`,revalidate:`执行前复核`,write:`写入`,sqlite:`索引更新`}},operationResult:{title:`操作结果`,operationId:`操作 ID`,backupId:`受管备份 ID`,backupCreated:`已创建备份,可在“备份与恢复”中查看。`,openBackupRestore:`打开恢复预览`,changeCountersHint:`这些是已修改的记录或设置数量,不代表唯一会话数量。`,skippedRollouts:`仍在使用的会话`,skippedChangedRollouts:`操作期间发生变化的会话`,skippedCount:`有 {{count}} 条会话记录暂未更新。`,retryAfterSession:`请关闭正在使用的 Codex 会话,然后再次同步。`,retryFreshPlan:`请重新预览本次操作后再试。`,reviewOperation:`返回操作页面`,verification:{title:`修复后的核验`,status:{verified:`写入后已核验所选修复目标。`,remaining:`仍有部分所选元数据需要处理,请先查看剩余数量,再预览新的修复。`,unavailable:`没有可用的写入后核验结果,系统没有启动其他修复。`},remainingRolloutFiles:`剩余会话文件差异`,remainingSqliteRows:`剩余本地索引差异`,remainingWorkspaceRoots:`剩余工作区设置`,skippedSessions:`跳过的会话记录`},partialReasons:{"skipped-data":`部分会话数据已跳过`,"locked-session":`有聊天仍在使用`,"rollout-changed":`操作期间聊天记录发生变化`,"mutation-failed":`部分更改保存后操作中断`},resolveBeforeClose:`请先完成待处理的恢复,再关闭此结果。`,fields:{unconfirmedSessionFiles:`写入结果未确认的文件`,inPlaceSessionFiles:`原地更新的 rollout`,rewrittenSessionFiles:`完整重写的 rollout`,targetProvider:`目标 Provider`,targetModel:`目标模型`,modelSource:`模型来源`,partialReason:`部分完成原因`,failedStage:`失败阶段`,failureCode:`失败代码`,retryRecommended:`建议重试`,restoreOperationId:`恢复操作 ID`,preRestoreSnapshotId:`恢复前快照 ID`,restoreJournalState:`恢复 journal 状态`,backupDurationMs:`备份耗时(毫秒)`,changedSessionFiles:`已更新聊天记录`,sqliteRowsUpdated:`已更新本地索引记录`,sqliteProviderRowsUpdated:`已更新 Provider 记录`,sqliteModelRowsUpdated:`已更新模型记录`,sqliteUserEventRowsUpdated:`已更新用户操作记录`,sqliteCwdRowsUpdated:`已更新工作区记录`,updatedWorkspaceRoots:`已更新工作区位置`,savedWorkspaceRootCount:`已保存工作区位置`,repairTargets:`修复目标`,restoreVersion:`恢复格式版本`,resolvedOperationCount:`已解决操作数`,commitAcknowledgementRecovered:`已恢复提交确认`},completed:{title:`已完成`,description:`操作已完成,相关数据已经保存。`},partial:{title:`部分完成`,description:`部分更改尚未完成。请按照下方提示重试,或从备份恢复。`},failedRolledBack:{title:`失败并已回滚`,description:`操作失败,且先前状态已成功恢复。`},recoveryRequired:{title:`需要先恢复数据`,description:`上一次恢复没有完成。请先完成恢复,再执行其他修改。`},cancelled:{title:`已取消`,description:`操作已经取消,后续步骤没有继续执行。`},stale:{title:`需要重新确认`,description:`操作开始前数据已经变化,请重新预览后再试。`}},validation:{required:`此项必填。`,keep:`请输入 1 到 1000 的整数。`,provider:`请输入有效的 Provider ID。`,model:`请输入要使用的模型名称。`,restore:`至少选择一种恢复内容。`,profileId:`只能使用字母、数字、点、下划线或连字符。`,path:`请输入完整的目录路径。`},errors:{fallback:`本次操作未能完成。请重试;如果问题持续,请查看操作日志或导出诊断信息。`,INVALID_INPUT:`请检查填写的内容后重试。`,providerNotConfigured:`当前 Provider 尚未在 config.toml 中配置。请先用 Provider 管理工具完成配置或切换,再重新同步。本次未修改数据。`,PROFILE_CHANGED:`当前存储配置已经变化,请检查后重试。`,STORAGE_CHANGED:`存储位置已经变化,请重新预览后再试。`,PLAN_STALE:`数据已经发生变化,请重新预览后再执行。`,PLAN_EXPIRED:`本次预览已经过期,请重新预览。`,STALE_STATE:`数据已经发生变化,请重新预览后再执行。`,CODEX_HOME_NOT_FOUND:`找不到 Codex 数据目录,请检查当前存储配置。`,STATE_DB_NOT_FOUND:`找不到本地聊天索引,请检查当前存储配置。`,SQLITE_UNSUPPORTED_PATH:`当前平台无法使用所选的聊天索引位置。`,SQLITE_BUSY:`本地聊天索引正在被占用,请关闭 Codex 后重试。`,SQLITE_UNREADABLE:`无法读取本地聊天索引,请运行诊断或从备份恢复。`,ROLLOUT_LOCKED:`部分会话正在使用中,请关闭相关 Codex 会话后重试。`,ROLLOUT_CHANGED:`部分会话在操作期间发生变化,请重新检查后重试。`,ROLLOUT_METADATA_TOO_LARGE:`会话首行元数据必须在同步前后均不超过 128 MiB,请处理超限问题后再同步。`,ROLLOUT_METADATA_INVALID:`会话首行不是有效的会话元数据,请处理格式问题后再同步。`,PENDING_TRANSACTION:`上一次恢复需要先完成,才能继续操作。`,BACKUP_FAILED:`无法创建备份,因此没有修改任何数据。`,SYNC_FAILED_ROLLED_BACK:`同步未能完成,原有数据已经恢复。`,RECOVERY_REQUIRED:`上一次恢复没有完成,请先完成恢复。`,RESTORE_VALIDATION_FAILED:`所选备份无法恢复到当前存储位置。`,PERMISSION_DENIED:`应用没有访问所选目录的权限。`,OPERATION_BUSY:`另一项操作正在执行,请等待完成后重试。`,OPERATION_CANCELLED:`操作已取消。`,CORE_RUNTIME_CRASHED:`后台服务意外停止,应用会在可行时自动重新启动。`,PROTOCOL_VERSION_MISMATCH:`应用组件版本不兼容,请重新安装最新版本。`,LOCK_UNVERIFIABLE:`无法确认当前存储位置是否可用,请关闭 Codex 后重试。`,INTERNAL_ERROR:`应用内部出现错误,请重试;如果问题持续,请导出诊断信息。`},warnings:{backupInventory:`无法刷新备份列表,但现有备份没有被修改。`,backupCleanup:`操作已经完成,但未能自动删除较早的备份。`,encryptedHistory:`部分加密会话可能需要使用原 Provider 或原账号才能继续。`,lockedSessions:`部分会话正在使用中,可能暂时无法更新。请关闭后再次同步。`,missingDefaultModel:`该 Provider 没有配置模型,将继续保留当前根模型。`,projectVisibility:`无法检查项目会话可见性,但修改前仍会创建备份。`,relocationConfig:`聊天索引将恢复到其他存储配置,但不会恢复 Codex 配置。`,restoreSkipped:`所选备份不包含其中一项恢复内容,该项将被跳过。`,partial:`本次操作只完成了部分修改,请重试或从备份恢复。`,additional:`操作带有额外提醒,请在操作日志中查看详情。`}}}};async function Kj(e){let t=rn.createInstance();return await t.init({resources:Gj,lng:e,fallbackLng:`en`,interpolation:{escapeValue:!1},returnNull:!1}),t}function qj(e){let t=e.preferences.getLocale()??e.initialLocale,n=e.preferences.getTheme()??e.initialTheme,[r,i]=(0,m.useState)(null),[a]=(0,m.useState)(()=>new We({defaultOptions:{queries:{retry:!1,staleTime:1/0,refetchOnWindowFocus:!1,refetchOnReconnect:!1},mutations:{retry:!1}}}));return(0,m.useEffect)(()=>{let e=!0;return Kj(t).then(t=>{e&&i(t)}),()=>{e=!1,a.clear()}},[e.initialTheme,e.preferences,a,t]),(0,m.useLayoutEffect)(()=>{document.documentElement.dataset.theme=n},[n]),r?(0,h.jsx)(On,{i18n:r,children:(0,h.jsx)(Wj,{locale:()=>r.language,children:(0,h.jsx)(v,{client:a,children:(0,h.jsx)(Ob.Provider,{value:e.host.copyText??Db,children:(0,h.jsx)(mb,{children:(0,h.jsx)(Uj,{props:e})})})})})}):(0,h.jsx)(`div`,{className:`grid min-h-screen place-items-center bg-[var(--surface)] text-[var(--text)]`,children:t===`zh-CN`?`正在加载…`:`Loading…`})}function Jj(e,t){let n=(e,n)=>{if(e.length>512||!/^[a-f0-9]{64}$/.test(n))throw Error(`Invalid project preference.`);return`${t}.history.project-alias.${JSON.stringify([e,n])}`},r=e=>typeof e==`string`&&e.length<=160&&!/[\x00-\x1f\x7f]/.test(e);return{getHistoryProjectAlias(t,i){try{let a=e.getItem(n(t,i));return r(a)&&a.trim()?a.trim():null}catch{return null}},setHistoryProjectAlias(t,i,a){if(!r(a))throw Error(`Invalid project display name.`);let o=n(t,i);a.trim()?e.setItem(o,a.trim()):e.removeItem(o)}}}var Yj=o((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0>>1,a=e[r];if(0>>1;ri(c,n))li(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(li(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m){if(n(c)!==null)m=!0,S||(S=!0,O());else{var t=n(l);t!==null&&A(x,t.startTime-e)}}}var S=!1,C=-1,w=5,T=-1;function E(){return g?!0:!(e.unstable_now()-Tt&&E());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&A(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?O():S=!1}}}var O;if(typeof y==`function`)O=function(){y(D)};else if(typeof MessageChannel<`u`){var ee=new MessageChannel,k=ee.port2;ee.port1.onmessage=D,O=function(){k.postMessage(null)}}else O=function(){_(D,0)};function A(t,n){C=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(C),C=-1):h=!0,A(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,O()))),r},e.unstable_shouldYield=E,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),Xj=o(((e,t)=>{t.exports=Yj()})),Zj=o((e=>{var t=Xj(),n=p(),r=um();function i(e){var t=`https://react.dev/errors/`+e;if(1ne||(e.current=te[ne],te[ne]=null,ne--)}function I(e,t){ne++,te[ne]=e.current,e.current=t}var L=re(null),ae=re(null),oe=re(null),se=re(null);function ce(e,t){switch(I(oe,t),I(ae,e),I(L,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?Gd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Gd(t),e=Kd(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}ie(L),I(L,e)}function le(){ie(L),ie(ae),ie(oe)}function ue(e){e.memoizedState!==null&&I(se,e);var t=L.current,n=Kd(t,e.type);t!==n&&(I(ae,e),I(L,n))}function de(e){ae.current===e&&(ie(L),ie(ae)),se.current===e&&(ie(se),np._currentValue=F)}var fe,pe;function me(e){if(fe===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);fe=t&&t[1]||``,pe=-1)`:-1i||c[r]!==l[i]){var u=` +`+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(``)&&(u=u.replace(``,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{he=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?me(n):``}function _e(e,t){switch(e.tag){case 26:case 27:case 5:return me(e.type);case 16:return me(`Lazy`);case 13:return e.child!==t&&t!==null?me(`Suspense Fallback`):me(`Suspense`);case 19:return me(`SuspenseList`);case 0:case 15:return ge(e.type,!1);case 11:return ge(e.type.render,!1);case 1:return ge(e.type,!0);case 31:return me(`Activity`);default:return``}}function ve(e){try{var t=``,n=null;do t+=_e(e,n),n=e,e=e.return;while(e);return t}catch(e){return` +Error generating stack: `+e.message+` +`+e.stack}}var ye=Object.prototype.hasOwnProperty,be=t.unstable_scheduleCallback,xe=t.unstable_cancelCallback,Se=t.unstable_shouldYield,R=t.unstable_requestPaint,Ce=t.unstable_now,we=t.unstable_getCurrentPriorityLevel,Te=t.unstable_ImmediatePriority,Ee=t.unstable_UserBlockingPriority,De=t.unstable_NormalPriority,Oe=t.unstable_LowPriority,ke=t.unstable_IdlePriority,Ae=t.log,je=t.unstable_setDisableYieldValue,Me=null,Ne=null;function Pe(e){if(typeof Ae==`function`&&je(e),Ne&&typeof Ne.setStrictMode==`function`)try{Ne.setStrictMode(Me,e)}catch{}}var Fe=Math.clz32?Math.clz32:Re,Ie=Math.log,Le=Math.LN2;function Re(e){return e>>>=0,e===0?32:31-(Ie(e)/Le|0)|0}var ze=256,Be=262144,Ve=4194304;function He(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function Ue(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=He(n))):i=He(o):i=He(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=He(n))):i=He(o)):i=He(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function We(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function Ge(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Ke(){var e=Ve;return Ve<<=1,!(Ve&62914560)&&(Ve=4194304),e}function qe(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Je(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function Ye(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0`u`||window.document===void 0||window.document.createElement===void 0),sn=!1;if(on)try{var cn={};Object.defineProperty(cn,"passive",{get:function(){sn=!0}}),window.addEventListener(`test`,cn,cn),window.removeEventListener(`test`,cn,cn)}catch{sn=!1}var ln=null,un=null,dn=null;function fn(){if(dn)return dn;var e,t=un,n=t.length,r,i=`value`in ln?ln.value:ln.textContent,a=i.length;for(e=0;e=Wn),qn=` `,Jn=!1;function Yn(e,t){switch(e){case`keyup`:return Hn.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function Xn(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var Zn=!1;function Qn(e,t){switch(e){case`compositionend`:return Xn(t);case`keypress`:return t.which===32?(Jn=!0,qn):null;case`textInput`:return e=t.data,e===qn&&Jn?null:e;default:return null}}function $n(e,t){if(Zn)return e===`compositionend`||!Un&&Yn(e,t)?(e=fn(),dn=un=ln=null,Zn=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=vr(n)}}function br(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?br(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function xr(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Nt(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=Nt(e.document)}return t}function Sr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}var Cr=on&&`documentMode`in document&&11>=document.documentMode,wr=null,Tr=null,Er=null,Dr=!1;function Or(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Dr||wr==null||wr!==Nt(r)||(r=wr,`selectionStart`in r&&Sr(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Er&&_r(Er,r)||(Er=r,r=kd(Tr,`onSelect`),0>=o,i-=o,yi=1<<32-Fe(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),a=o(_,a,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),Oi&&xi(i,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(a,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(a,h),s=o(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(a,h),Oi&&xi(a,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(a,v.value,l),v!==null&&(s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return Oi&&xi(a,g),u}for(h=r(h);!v.done;g++,v=c.next())v=m(h,a,g,v.value,l),v!==null&&(e&&v.alternate!==null&&h.delete(v.key===null?g:v.key),s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(a,e)}),Oi&&xi(a,g),u}function b(e,r,o,c){if(typeof o==`object`&&o&&o.type===_&&o.key===null&&(o=o.props.children),typeof o==`object`&&o){switch(o.$$typeof){case h:a:{for(var l=o.key;r!==null;){if(r.key===l){if(l=o.type,l===_){if(r.tag===7){n(e,r.sibling),c=a(r,o.props.children),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===E&&xa(l)===r.type){n(e,r.sibling),c=a(r,o.props),Oa(c,o),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}o.type===_?(c=si(o.props.children,e.mode,c,o.key),c.return=e,e=c):(c=oi(o.type,o.key,o.props,null,e.mode,c),Oa(c,o),c.return=e,e=c)}return s(e);case g:a:{for(l=o.key;r!==null;){if(r.key===l){if(r.tag===4&&r.stateNode.containerInfo===o.containerInfo&&r.stateNode.implementation===o.implementation){n(e,r.sibling),c=a(r,o.children||[]),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}c=ui(o,e.mode,c),c.return=e,e=c}return s(e);case E:return o=xa(o),b(e,r,o,c)}if(M(o))return v(e,r,o,c);if(k(o)){if(l=k(o),typeof l!=`function`)throw Error(i(150));return o=l.call(o),y(e,r,o,c)}if(typeof o.then==`function`)return b(e,r,Da(o),c);if(o.$$typeof===x)return b(e,r,Xi(e,o),c);ka(e,o)}return typeof o==`string`&&o!==``||typeof o==`number`||typeof o==`bigint`?(o=``+o,r!==null&&r.tag===6?(n(e,r.sibling),c=a(r,o),c.return=e,e=c):(n(e,r),c=ci(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{Ea=0;var i=b(e,t,n,r);return Ta=null,i}catch(t){if(t===ha||t===_a)throw t;var a=ni(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var ja=Aa(!0),Ma=Aa(!1),Na=!1;function Pa(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Fa(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function Ia(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function La(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Fl&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=$r(e),Qr(e,null,n),t}return Yr(e,r,t,n),$r(e)}function Ra(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194048)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Ze(e,n)}}function za(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var Ba=!1;function Va(){if(Ba){var e=sa;if(e!==null)throw e}}function Ha(e,t,n,r){Ba=!1;var i=e.updateQueue;Na=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var p=s.lane&-536870913,m=p!==s.lane;if(m?(Rl&p)===p:(r&p)===p){p!==0&&p===oa&&(Ba=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var h=e,g=s;p=t;var _=n;switch(g.tag){case 1:if(h=g.payload,typeof h==`function`){d=h.call(_,d,p);break a}d=h;break a;case 3:h.flags=h.flags&-65537|128;case 0:if(h=g.payload,p=typeof h==`function`?h.call(_,d,p):h,p==null)break a;d=f({},d,p);break a;case 2:Na=!0}}p=s.callback,p!==null&&(e.flags|=64,m&&(e.flags|=8192),m=i.callbacks,m===null?i.callbacks=[p]:m.push(p))}else m={lane:p,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=m,c=d):u=u.next=m,o|=p;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;m=s,s=m.next,m.next=null,i.lastBaseUpdate=m,i.shared.pending=null}}while(1);u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,a===null&&(i.shared.lanes=0),Kl|=o,e.lanes=o,e.memoizedState=d}}function Ua(e,t){if(typeof e!=`function`)throw Error(i(191,e));e.call(t)}function Wa(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=N.T,s={};N.T=s,Os(e,!1,t,n);try{var c=i(),l=N.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?Ds(e,t,ua(c,r),mu(e)):Ds(e,t,r,mu(e))}catch(n){Ds(e,t,{then:function(){},status:`rejected`,reason:n},mu())}finally{P.p=a,o!==null&&s.types!==null&&(o.types=s.types),N.T=o}}function _s(){}function vs(e,t,n,r){if(e.tag!==5)throw Error(i(476));var a=ys(e).queue;gs(e,a,t,F,n===null?_s:function(){return bs(e),n(r)})}function ys(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:F,baseState:F,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:jo,lastRenderedState:F},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:jo,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function bs(e){var t=ys(e);t.next===null&&(t=e.alternate.memoizedState),Ds(e,t.next.queue,{},mu())}function xs(){return Yi(np)}function Ss(){return Eo().memoizedState}function Cs(){return Eo().memoizedState}function ws(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=mu();e=Ia(n);var r=La(t,e,n);r!==null&&(gu(r,t,n),Ra(r,t,n)),t={cache:na()},e.payload=t;return}t=t.return}}function Ts(e,t,n){var r=mu();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},ks(e)?As(t,n):(n=Xr(e,t,n,r),n!==null&&(gu(n,e,r),js(n,t,r)))}function Es(e,t,n){Ds(e,t,n,mu())}function Ds(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(ks(e))As(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,gr(s,o))return Yr(e,t,i,0),Il===null&&Jr(),!1}catch{}if(n=Xr(e,t,i,r),n!==null)return gu(n,e,r),js(n,t,r),!0}return!1}function Os(e,t,n,r){if(r={lane:2,revertLane:pd(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},ks(e)){if(t)throw Error(i(479))}else t=Xr(e,n,r,2),t!==null&&gu(t,e,2)}function ks(e){var t=e.alternate;return e===G||t!==null&&t===G}function As(e,t){lo=co=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function js(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Ze(e,n)}}var Ms={readContext:Yi,use:ko,useCallback:go,useContext:go,useEffect:go,useImperativeHandle:go,useLayoutEffect:go,useInsertionEffect:go,useMemo:go,useReducer:go,useRef:go,useState:go,useDebugValue:go,useDeferredValue:go,useTransition:go,useSyncExternalStore:go,useId:go,useHostTransitionStatus:go,useFormState:go,useActionState:go,useOptimistic:go,useMemoCache:go,useCacheRefresh:go};Ms.useEffectEvent=go;var Ns={readContext:Yi,use:ko,useCallback:function(e,t){return To().memoizedState=[e,t===void 0?null:t],e},useContext:Yi,useEffect:is,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),ns(4194308,4,us.bind(null,t,e),n)},useLayoutEffect:function(e,t){return ns(4194308,4,e,t)},useInsertionEffect:function(e,t){ns(4,2,e,t)},useMemo:function(e,t){var n=To();t=t===void 0?null:t;var r=e();if(uo){Pe(!0);try{e()}finally{Pe(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=To();if(n!==void 0){var i=n(t);if(uo){Pe(!0);try{n(t)}finally{Pe(!1)}}}else i=t;return r.memoizedState=r.baseState=i,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:i},r.queue=e,e=e.dispatch=Ts.bind(null,G,e),[r.memoizedState,e]},useRef:function(e){var t=To();return e={current:e},t.memoizedState=e},useState:function(e){e=Vo(e);var t=e.queue,n=Es.bind(null,G,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:fs,useDeferredValue:function(e,t){return ms(To(),e,t)},useTransition:function(){var e=Vo(!1);return e=gs.bind(null,G,e.queue,!0,!1),To().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=G,a=To();if(Oi){if(n===void 0)throw Error(i(407));n=n()}else{if(n=t(),Il===null)throw Error(i(349));Rl&127||Io(r,t,n)}a.memoizedState=n;var o={value:n,getSnapshot:t};return a.queue=o,is(Ro.bind(null,r,o,e),[e]),r.flags|=2048,es(9,{destroy:void 0},Lo.bind(null,r,o,n,t),null),n},useId:function(){var e=To(),t=Il.identifierPrefix;if(Oi){var n=bi,r=yi;n=(r&~(1<<32-Fe(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=fo++,0<\/script>`,o=o.removeChild(o.firstChild);break;case`select`:o=typeof r.is==`string`?s.createElement(`select`,{is:r.is}):s.createElement(`select`),r.multiple?o.multiple=!0:r.size&&(o.size=r.size);break;default:o=typeof r.is==`string`?s.createElement(a,{is:r.is}):s.createElement(a)}}o[it]=t,o[at]=r;a:for(s=t.child;s!==null;){if(s.tag===5||s.tag===6)o.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===t)break a;for(;s.sibling===null;){if(s.return===null||s.return===t)break a;s=s.return}s.sibling.return=s.return,s=s.sibling}t.stateNode=o;a:switch(Rd(o,a,r),a){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&Dc(t)}}return Mc(t),Oc(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&Dc(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(i(166));if(e=oe.current,Fi(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,a=Ei,a!==null)switch(a.tag){case 27:case 5:r=a.memoizedProps}e[it]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||Fd(e.nodeValue,n)),e||Mi(t,!0)}else e=Wd(e).createTextNode(r),e[it]=t,t.stateNode=e}return Mc(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=Fi(t),n!==null){if(e===null){if(!r)throw Error(i(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(i(557));e[it]=t}else Ii(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Mc(t),e=!1}else n=Li(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(no(t),t):(no(t),null);if(t.flags&128)throw Error(i(558))}return Mc(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(a=Fi(t),r!==null&&r.dehydrated!==null){if(e===null){if(!a)throw Error(i(318));if(a=t.memoizedState,a=a===null?null:a.dehydrated,!a)throw Error(i(317));a[it]=t}else Ii(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Mc(t),a=!1}else a=Li(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),a=!0;if(!a)return t.flags&256?(no(t),t):(no(t),null)}return no(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,a=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(a=r.alternate.memoizedState.cachePool.pool),o=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(o=r.memoizedState.cachePool.pool),o!==a&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),Ac(t,t.updateQueue),Mc(t),null);case 4:return le(),e===null&&Td(t.stateNode.containerInfo),Mc(t),null;case 10:return Ui(t.type),Mc(t),null;case 19:if(ie(ro),r=t.memoizedState,r===null)return Mc(t),null;if(a=!!(t.flags&128),o=r.rendering,o===null){if(a)jc(r,!1);else{if(Gl!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=io(e),o!==null){for(t.flags|=128,jc(r,!1),e=o.updateQueue,t.updateQueue=e,Ac(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)ai(n,e),n=n.sibling;return I(ro,ro.current&1|2),Oi&&xi(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Ce()>nu&&(t.flags|=128,a=!0,jc(r,!1),t.lanes=4194304)}}else{if(!a){if(e=io(o),e!==null){if(t.flags|=128,a=!0,e=e.updateQueue,t.updateQueue=e,Ac(t,e),jc(r,!0),r.tail===null&&r.tailMode===`hidden`&&!o.alternate&&!Oi)return Mc(t),null}else 2*Ce()-r.renderingStartTime>nu&&n!==536870912&&(t.flags|=128,a=!0,jc(r,!1),t.lanes=4194304)}r.isBackwards?(o.sibling=t.child,t.child=o):(e=r.last,e===null?t.child=o:e.sibling=o,r.last=o)}return r.tail===null?(Mc(t),null):(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=Ce(),e.sibling=null,n=ro.current,I(ro,a?n&1|2:n&1),Oi&&xi(t,r.treeForkCount),e);case 22:case 23:return no(t),Ya(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(Mc(t),t.subtreeFlags&6&&(t.flags|=8192)):Mc(t),n=t.updateQueue,n!==null&&Ac(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),r=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),e!==null&&ie(fa),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),Ui(ta),Mc(t),null;case 25:return null;case 30:return null}throw Error(i(156,t.tag))}function Pc(e,t){switch(wi(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ui(ta),le(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return de(t),null;case 31:if(t.memoizedState!==null){if(no(t),t.alternate===null)throw Error(i(340));Ii()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(no(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(i(340));Ii()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ie(ro),null;case 4:return le(),null;case 10:return Ui(t.type),null;case 22:case 23:return no(t),Ya(),e!==null&&ie(fa),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Ui(ta),null;case 25:return null;default:return null}}function Fc(e,t){switch(wi(t),t.tag){case 3:Ui(ta),le();break;case 26:case 27:case 5:de(t);break;case 4:le();break;case 31:t.memoizedState!==null&&no(t);break;case 13:no(t);break;case 19:ie(ro);break;case 10:Ui(t.type);break;case 22:case 23:no(t),Ya(),e!==null&&ie(fa);break;case 24:Ui(ta)}}function Ic(e,t){try{var n=t.updateQueue,r=n===null?null:n.lastEffect;if(r!==null){var i=r.next;n=i;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==i)}}catch(e){Ku(t,t.return,e)}}function Lc(e,t,n){try{var r=t.updateQueue,i=r===null?null:r.lastEffect;if(i!==null){var a=i.next;r=a;do{if((r.tag&e)===e){var o=r.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,i=t;var c=n,l=s;try{l()}catch(e){Ku(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){Ku(t,t.return,e)}}function Rc(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{Wa(t,n)}catch(t){Ku(e,e.return,t)}}}function zc(e,t,n){n.props=Bs(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){Ku(e,t,n)}}function Bc(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;case 30:r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){Ku(e,t,n)}}function Vc(e,t){var n=e.ref,r=e.refCleanup;if(n!==null){if(typeof r==`function`)try{r()}catch(n){Ku(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n==`function`)try{n(null)}catch(n){Ku(e,t,n)}else n.current=null}}function Hc(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{a:switch(t){case`button`:case`input`:case`select`:case`textarea`:n.autoFocus&&r.focus();break a;case`img`:n.src?r.src=n.src:n.srcSet&&(r.srcset=n.srcSet)}}catch(t){Ku(e,e.return,t)}}function Uc(e,t,n){try{var r=e.stateNode;zd(r,e.type,n,t),r[at]=t}catch(t){Ku(e,e.return,t)}}function Wc(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&tf(e.type)||e.tag===4}function Gc(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||Wc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&tf(e.type)||e.flags&2||e.child===null||e.tag===4)continue a;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Kc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?(n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n).insertBefore(e,t):(t=n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n,t.appendChild(e),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Xt));else if(r!==4&&(r===27&&tf(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for(Kc(e,t,n),e=e.sibling;e!==null;)Kc(e,t,n),e=e.sibling}function qc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(r===27&&tf(e.type)&&(n=e.stateNode),e=e.child,e!==null))for(qc(e,t,n),e=e.sibling;e!==null;)qc(e,t,n),e=e.sibling}function Jc(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,i=t.attributes;i.length;)t.removeAttributeNode(i[0]);Rd(t,r,n),t[it]=e,t[at]=n}catch(t){Ku(e,e.return,t)}}var Yc=!1,Xc=!1,Zc=!1,Qc=typeof WeakSet==`function`?WeakSet:Set,$c=null;function el(e,t){if(e=e.containerInfo,Hd=dp,e=xr(e),Sr(e)){if(`selectionStart`in e)var n={start:e.selectionStart,end:e.selectionEnd};else a:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break a}var s=0,c=-1,l=-1,u=0,d=0,f=e,p=null;b:for(;;){for(var m;f!==n||a!==0&&f.nodeType!==3||(c=s+a),f!==o||r!==0&&f.nodeType!==3||(l=s+r),f.nodeType===3&&(s+=f.nodeValue.length),(m=f.firstChild)!==null;)p=f,f=m;for(;;){if(f===e)break b;if(p===n&&++u===a&&(c=s),p===o&&++d===r&&(l=s),(m=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=m}n=c===-1||l===-1?null:{start:c,end:l}}else n=null}n||={start:0,end:0}}else n=null;for(Ud={focusedElem:e,selectionRange:n},dp=!1,$c=t;$c!==null;)if(t=$c,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,$c=e;else for(;$c!==null;){switch(t=$c,o=t.alternate,e=t.flags,t.tag){case 0:if(e&4&&(e=t.updateQueue,e=e===null?null:e.events,e!==null))for(n=0;n title`))),Rd(o,r,n),o[it]=e,gt(o),r=o;break a;case`link`:var s=Gf(`link`,`href`,a).get(r+(n.href||``));if(s){for(var c=0;cg&&(o=g,g=h,h=o);var _=yr(s,h),v=yr(s,g);if(_&&v&&(p.rangeCount!==1||p.anchorNode!==_.node||p.anchorOffset!==_.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var y=d.createRange();y.setStart(_.node,_.offset),p.removeAllRanges(),h>g?(p.addRange(y),p.extend(v.node,v.offset)):(y.setEnd(v.node,v.offset),p.addRange(y))}}}}for(d=[],p=s;p=p.parentNode;)p.nodeType===1&&d.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof s.focus==`function`&&s.focus(),s=0;sn?32:n,N.T=null,n=uu,uu=null;var o=ou,s=cu;if(au=0,su=ou=null,cu=0,Fl&6)throw Error(i(331));var c=Fl;if(Fl|=4,Al(o.current),Sl(o,o.current,s,n),Fl=c,od(0,!1),Ne&&typeof Ne.onPostCommitFiberRoot==`function`)try{Ne.onPostCommitFiberRoot(Me,o)}catch{}return!0}finally{P.p=a,N.T=r,Hu(e,t)}}function Gu(e,t,n){t=fi(n,t),t=Ks(e.stateNode,t,2),e=La(e,t,2),e!==null&&(Je(e,2),ad(e))}function Ku(e,t,n){if(e.tag===3)Gu(e,e,n);else for(;t!==null;){if(t.tag===3){Gu(t,e,n);break}if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(iu===null||!iu.has(r))){e=fi(n,e),n=qs(2),r=La(t,n,2),r!==null&&(Js(n,r,t,e),Je(r,2),ad(r));break}}t=t.return}}function qu(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new Pl;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(Ul=!0,i.add(n),e=Ju.bind(null,e,t,n),t.then(e,e))}function Ju(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,Il===e&&(Rl&n)===n&&(Gl===4||Gl===3&&(Rl&62914560)===Rl&&300>Ce()-eu?!(Fl&2)&&Cu(e,0):Jl|=n,Xl===Rl&&(Xl=0)),ad(e)}function Yu(e,t){t===0&&(t=Ke()),e=Zr(e,t),e!==null&&(Je(e,t),ad(e))}function Xu(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Yu(e,n)}function Zu(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(i(314))}r!==null&&r.delete(t),Yu(e,n)}function Qu(e,t){return be(e,t)}var $u=null,ed=null,td=!1,nd=!1,rd=!1,id=0;function ad(e){e!==ed&&e.next===null&&(ed===null?$u=ed=e:ed=ed.next=e),nd=!0,td||(td=!0,fd())}function od(e,t){if(!rd&&nd){rd=!0;do for(var n=!1,r=$u;r!==null;){if(!t){if(e!==0){var i=r.pendingLanes;if(i===0)var a=0;else{var o=r.suspendedLanes,s=r.pingedLanes;a=(1<<31-Fe(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,dd(r,a))}else a=Rl,a=Ue(r,r===Il?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||We(r,a)||(n=!0,dd(r,a))}r=r.next}while(n);rd=!1}}function sd(){cd()}function cd(){nd=td=!1;var e=0;id!==0&&Yd()&&(e=id);for(var t=Ce(),n=null,r=$u;r!==null;){var i=r.next,a=ld(r,t);a===0?(r.next=null,n===null?$u=i:n.next=i,i===null&&(ed=n)):(n=r,(e!==0||a&3)&&(nd=!0)),r=i}au!==0&&au!==5||od(e,!1),id!==0&&(id=0)}function ld(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes&-62914561;0s)break;var u=c.transferSize,d=c.initiatorType;u&&Bd(d)&&(c=c.responseEnd,o+=u*(c`u`?null:document;function Tf(e,t,n){var r=wf;if(r&&typeof t==`string`&&t){var i=Ft(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),yf.has(i)||(yf.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),Rd(t,`link`,e),gt(t),r.head.appendChild(t)))}}function Ef(e){xf.D(e),Tf(`dns-prefetch`,e,null)}function Df(e,t){xf.C(e,t),Tf(`preconnect`,e,t)}function Of(e,t,n){xf.L(e,t,n);var r=wf;if(r&&e&&t){var i=`link[rel="preload"][as="`+Ft(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+Ft(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+Ft(n.imageSizes)+`"]`)):i+=`[href="`+Ft(e)+`"]`;var a=i;switch(t){case`style`:a=Pf(e);break;case`script`:a=Rf(e)}vf.has(a)||(e=f({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),vf.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(Ff(a))||t===`script`&&r.querySelector(zf(a))||(t=r.createElement(`link`),Rd(t,`link`,e),gt(t),r.head.appendChild(t)))}}function kf(e,t){xf.m(e,t);var n=wf;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+Ft(r)+`"][href="`+Ft(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Rf(e)}if(!vf.has(a)&&(e=f({rel:`modulepreload`,href:e},t),vf.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(zf(a)))return}r=n.createElement(`link`),Rd(r,`link`,e),gt(r),n.head.appendChild(r)}}}function Af(e,t,n){xf.S(e,t,n);var r=wf;if(r&&e){var i=ht(r).hoistableStyles,a=Pf(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(Ff(a)))s.loading=5;else{e=f({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=vf.get(a))&&Hf(e,n);var c=o=r.createElement(`link`);gt(c),Rd(c,`link`,e),c._p=new Promise(function(e,t){c.onload=e,c.onerror=t}),c.addEventListener(`load`,function(){s.loading|=1}),c.addEventListener(`error`,function(){s.loading|=2}),s.loading|=4,Vf(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function jf(e,t){xf.X(e,t);var n=wf;if(n&&e){var r=ht(n).hoistableScripts,i=Rf(e),a=r.get(i);a||(a=n.querySelector(zf(i)),a||(e=f({src:e,async:!0},t),(t=vf.get(i))&&Uf(e,t),a=n.createElement(`script`),gt(a),Rd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Mf(e,t){xf.M(e,t);var n=wf;if(n&&e){var r=ht(n).hoistableScripts,i=Rf(e),a=r.get(i);a||(a=n.querySelector(zf(i)),a||(e=f({src:e,async:!0,type:`module`},t),(t=vf.get(i))&&Uf(e,t),a=n.createElement(`script`),gt(a),Rd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Nf(e,t,n,r){var a=(a=oe.current)?bf(a):null;if(!a)throw Error(i(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(t=Pf(n.href),n=ht(a).hoistableStyles,r=n.get(t),r||(r={type:`style`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};case`link`:if(n.rel===`stylesheet`&&typeof n.href==`string`&&typeof n.precedence==`string`){e=Pf(n.href);var o=ht(a).hoistableStyles,s=o.get(e);if(s||(a=a.ownerDocument||a,s={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},o.set(e,s),(o=a.querySelector(Ff(e)))&&!o._p&&(s.instance=o,s.state.loading=5),vf.has(e)||(n={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},vf.set(e,n),o||Lf(a,e,n,s.state))),t&&r===null)throw Error(i(528,``));return s}if(t&&r!==null)throw Error(i(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(t=Rf(n),n=ht(a).hoistableScripts,r=n.get(t),r||(r={type:`script`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(i(444,e))}}function Pf(e){return`href="`+Ft(e)+`"`}function Ff(e){return`link[rel="stylesheet"][`+e+`]`}function If(e){return f({},e,{"data-precedence":e.precedence,precedence:null})}function Lf(e,t,n,r){e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)?r.loading=1:(t=e.createElement(`link`),r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2}),Rd(t,`link`,n),gt(t),e.head.appendChild(t))}function Rf(e){return`[src="`+Ft(e)+`"]`}function zf(e){return`script[async]`+e}function Bf(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+Ft(n.href)+`"]`);if(r)return t.instance=r,gt(r),r;var a=f({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),gt(r),Rd(r,`style`,a),Vf(r,n.precedence,e),t.instance=r;case`stylesheet`:a=Pf(n.href);var o=e.querySelector(Ff(a));if(o)return t.state.loading|=4,t.instance=o,gt(o),o;r=If(n),(a=vf.get(a))&&Hf(r,a),o=(e.ownerDocument||e).createElement(`link`),gt(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),Rd(o,`link`,r),t.state.loading|=4,Vf(o,n.precedence,e),t.instance=o;case`script`:return o=Rf(n.src),(a=e.querySelector(zf(o)))?(t.instance=a,gt(a),a):(r=n,(a=vf.get(o))&&(r=f({},n),Uf(r,a)),e=e.ownerDocument||e,a=e.createElement(`script`),gt(a),Rd(a,`link`,r),e.head.appendChild(a),t.instance=a);case`void`:return null;default:throw Error(i(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Vf(r,n.precedence,e));return t.instance}function Vf(e,t,n){for(var r=n.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),i=r.length?r[r.length-1]:null,a=i,o=0;o title`):null)}function qf(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof t.precedence!=`string`||typeof t.href!=`string`||t.href===``)break;return!0;case`link`:if(typeof t.rel!=`string`||typeof t.href!=`string`||t.href===``||t.onLoad||t.onError)break;switch(t.rel){case`stylesheet`:return e=t.disabled,typeof t.precedence==`string`&&e==null;default:return!0}case`script`:if(t.async&&typeof t.async!=`function`&&typeof t.async!=`symbol`&&!t.onLoad&&!t.onError&&t.src&&typeof t.src==`string`)return!0}return!1}function Jf(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Yf(e,t,n,r){if(n.type===`stylesheet`&&(typeof r.media!=`string`||!1!==matchMedia(r.media).matches)&&!(n.state.loading&4)){if(n.instance===null){var i=Pf(r.href),a=t.querySelector(Ff(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=Qf.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,gt(a);return}a=t.ownerDocument||t,r=If(r),(i=vf.get(i))&&Hf(r,i),a=a.createElement(`link`),gt(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),Rd(a,`link`,r),n.instance=a}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=Qf.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var Xf=0;function Zf(e,t){return e.stylesheets&&e.count===0&&ep(e,e.stylesheets),0Xf?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function Qf(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)ep(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var $f=null;function ep(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,$f=new Map,t.forEach(tp,e),$f=null,Qf.call(e))}function tp(e,t){if(!(t.state.loading&4)){var n=$f.get(e);if(n)var r=n.get(null);else{n=new Map,$f.set(e,n);for(var i=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),a=0;a{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=Zj()}))(),$j=`cps.web.deviceCredential`,eM=`cps.preference.locale`,tM=`cps.preference.theme`;function nM(){return globalThis.localStorage.getItem($j)??``}async function rM(e){let t=await e.json().catch(()=>({}));return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}function iM(e,t){let n=typeof e.code==`string`?e.code:`HOST_REQUEST_FAILED`;return Object.assign(Error(`${t} (${n})`),{code:n})}async function aM(){let e=new URLSearchParams(globalThis.location.hash.replace(/^#/,``)).get(`pair`);if(!e)return nM()||null;globalThis.history.replaceState(null,``,`${globalThis.location.pathname}${globalThis.location.search}`);let t=await globalThis.fetch(`/api/pair`,{method:`POST`,redirect:`error`,credentials:`same-origin`,headers:{"X-Codex-Provider-Pairing":e}}),n=await rM(t),r=typeof n.deviceCredential==`string`?n.deviceCredential:``;return!t.ok||!r?null:(globalThis.localStorage.setItem($j,r),r)}function oM(e){return async(t,n={})=>{let r=await globalThis.fetch(t,{...n,headers:{...Object.fromEntries(new Headers(n.headers).entries()),"X-Codex-Provider-Device":e}});return r.status===403&&(await rM(r.clone())).code===`PAIRING_REQUIRED`&&(globalThis.localStorage.removeItem($j),globalThis.dispatchEvent(new CustomEvent(`cps:pairing-required`))),r}}function sM(e){let t=oM(e),n={"Content-Type":`application/json`};return{listProfiles:async e=>{let n=await t(`/api/profiles`,{credentials:`same-origin`,redirect:`error`,signal:e}),r=await rM(n);if(!n.ok||!Array.isArray(r.profiles))throw iM(r,`Unable to load profiles`);return r.profiles},async saveProfile(e,r){let i=await t(`/api/profiles/save`,{method:`POST`,credentials:`same-origin`,redirect:`error`,headers:n,body:JSON.stringify(e),signal:r}),a=await rM(i);if(!i.ok||!a.profile)throw iM(a,`Unable to save profile`);return a.profile},async deleteProfile(e,r,i){let a=await t(`/api/profiles/delete`,{method:`POST`,credentials:`same-origin`,redirect:`error`,headers:n,body:JSON.stringify({profileId:e,profileRevision:r}),signal:i}),o=await rM(a);if(!a.ok)throw iM(o,`Unable to delete profile`)},async forgetBrowser(){try{await t(`/api/access/forget`,{method:`POST`,credentials:`same-origin`,redirect:`error`,headers:n,body:`{}`})}finally{globalThis.localStorage.removeItem($j)}}}}var cM={...Pj(globalThis.localStorage,`cps.web`),...Jj(globalThis.localStorage,`cps.web`),getLocale(){let e=globalThis.localStorage.getItem(eM);return e===`zh-CN`||e===`en`?e:null},setLocale(e){globalThis.localStorage.setItem(eM,e)},getTheme(){let e=globalThis.localStorage.getItem(tM);return e===`system`||e===`light`||e===`dark`?e:null},setTheme(e){globalThis.localStorage.setItem(tM,e)}};async function lM(e){await e.forgetBrowser?.(),globalThis.location.reload()}var uM=(0,Qj.createRoot)(document.getElementById(`root`)),dM=await aM();if(!dM)uM.render((0,h.jsx)(m.StrictMode,{children:(0,h.jsx)(`main`,{className:`grid min-h-screen place-items-center bg-[var(--surface)] p-6 text-[var(--text)]`,children:(0,h.jsxs)(`section`,{className:`max-w-lg rounded-2xl border border-[var(--border)] bg-[var(--surface-raised)] p-8 text-center shadow-xl`,children:[(0,h.jsx)(`h1`,{className:`text-2xl font-bold`,children:`Codex Provider Sync`}),(0,h.jsxs)(`p`,{className:`mt-3 text-sm leading-6 text-[var(--muted)]`,children:[`This browser is not paired. Run `,(0,h.jsx)(`code`,{children:`codex-provider web`}),` again and open the new one-time link.`]})]})})}));else{let e=sM(dM),t=oM(dM),n=new ii({baseUrl:globalThis.location.origin,fetch:t});globalThis.addEventListener(`cps:pairing-required`,()=>globalThis.location.reload(),{once:!0}),uM.render((0,h.jsx)(m.StrictMode,{children:(0,h.jsx)(qj,{core:n,host:e,initialLocale:globalThis.navigator.language.toLowerCase().startsWith(`zh`)?`zh-CN`:`en`,initialTheme:`system`,onForgetBrowser:()=>lM(e),preferences:cM,surface:`web`})}))} \ No newline at end of file diff --git a/web/dist/index.html b/web/dist/index.html index 676a652..2601998 100644 --- a/web/dist/index.html +++ b/web/dist/index.html @@ -7,8 +7,8 @@ Codex Provider Sync - - + +
From bfe452f75ff3a9f8d8cbcb067dc1adc5562dd3fb Mon Sep 17 00:00:00 2001 From: "DAL\\Administrator" <3452720699@qq.com> Date: Tue, 15 Sep 2026 15:45:38 +0800 Subject: [PATCH 2/4] fix(sync): preserve POSIX known-unwritten skip outcomes --- docs/adr/0045-isolated-provider-data-skips.md | 2 ++ docs/migration/BEHAVIOR_FIXTURES_ZH.md | 2 ++ src/session-files.js | 2 +- test/in-place-transaction.test.js | 22 +++++++++++++++---- 4 files changed, 23 insertions(+), 5 deletions(-) diff --git a/docs/adr/0045-isolated-provider-data-skips.md b/docs/adr/0045-isolated-provider-data-skips.md index 3efb1c8..036603e 100644 --- a/docs/adr/0045-isolated-provider-data-skips.md +++ b/docs/adr/0045-isolated-provider-data-skips.md @@ -10,6 +10,8 @@ Provider 计划保存内部文件身份、首行校验、SQLite 行原 Provider 和排除集合。预览排除项在本次执行始终排除,修好后需新预览;正常候选逐个复核,新增文件和行留待下一次。Repair/Restore 的严格计划校验不变。Status 保留不完整标记,允许预览健康部分,不能将未知数据计为对齐。读取中发生单条变化时仍只允许一次受限重读;新一轮完整且稳定的事实可以成为有效快照,持续漂移仍不完整。 +POSIX 原地写在打开描述符时发现硬链接数量已变化,按 `changed` 跳过且不回退替换;后续身份复核、写后及恢复校验仍严格。短写、零进度或 fsync 失败仅在立即恢复并验证原字节成功后返回 `write-not-applied`;恢复失败仍停止并保留备份。 + SQLite 通过有效 metadata 的 ID 或经规范化和边界验证的 `rollout_path` 建立关联。不猜文件名,不扫描正文找 ID。跳过文件的关联行不更新;冲突及未知归属保留。有无法关联的坏文件时,仅更新正向确认健康的索引;无歧义时继续支持 SQLite-only。预览与 SQL 使用同一选择集合,空集合零更新。事务内逐行比较原 Provider,变化/消失的行跳过,数据库级故障停止。 备份先于业务写入,仅包含可写候选。写后复用 sessions manifest 的恢复范围,排除明确未写入的文件,保留写入成功和结果不确定的文件。范围落盘失败需提示,不能声称已排除。旧备份和崩溃时未记录结果的备份保守恢复;SQLite Restore 仍是整库快照。普通同步不引入 journal。 diff --git a/docs/migration/BEHAVIOR_FIXTURES_ZH.md b/docs/migration/BEHAVIOR_FIXTURES_ZH.md index b8e6437..6b0d060 100644 --- a/docs/migration/BEHAVIOR_FIXTURES_ZH.md +++ b/docs/migration/BEHAVIOR_FIXTURES_ZH.md @@ -4,6 +4,8 @@ 当前 Provider 跳过合同见 [ADR-0045](../adr/0045-isolated-provider-data-skips.md):内部逐文件/逐行计划绑定、关联索引排除、已知未写恢复范围及有界本机日志。`test/provider-skip-data.test.js` 覆盖混合数据、未知归属、冻结排除、删除及全部跳过。全局故障和 Repair/Restore 仍严格;不完整状态不能宣称对齐。 +`test/in-place-transaction.test.js` 的 POSIX 回归覆盖写前新增硬链接按变化跳过,以及短写、零进度、fsync 故障在验证恢复成功后返回 `SKIP_NOT_APPLIED`;同时断言原字节、inode、大小、mtime 和跳过原因。写后身份冲突或恢复失败仍停止,禁止回退整文件替换。 + ## ADR-0044:大首行与明确错误 `test/large-session-metadata.test.js` 覆盖 8 MiB 完整 Status→Sync/Switch→Restore、原地/变长正文不变、128 MiB LF/CRLF/EOF 读取边界与线性合并、超限/无效 Prepare 零写入及安全错误。`CPS_LARGE_HEADER_MIB=128` 可显式运行完整近上限读写。`provider-preparation-facts.test.js`、`status-coordination.test.js` 保留无效/超限拒绝及 Status 不完整检查。生产 Electron smoke 使用 8 MiB 首行验证大首行同步与恢复。 diff --git a/src/session-files.js b/src/session-files.js index 0dfeb62..b561b4c 100644 --- a/src/session-files.js +++ b/src/session-files.js @@ -735,7 +735,7 @@ async function tryRewriteProviderInPlace(change, options = {}) { dev: String(identity.dev), ino: String(identity.ino) }; - if (!snapshotMatches(change, snapshot) + if (identity.nlink !== 1n || !snapshotMatches(change, snapshot) || mutation.originalSize !== change.originalSize || mutation.originalMtimeMs !== change.originalMtimeMs) { return "SKIP_CHANGED"; diff --git a/test/in-place-transaction.test.js b/test/in-place-transaction.test.js index c93ac15..e69747a 100644 --- a/test/in-place-transaction.test.js +++ b/test/in-place-transaction.test.js @@ -92,7 +92,7 @@ test("short writes preserve inode, size, content and original mtime", posix, asy assert.equal(await fs.readFile(f.file, "utf8"), f.original.toString().replace('"openai"', '"prov_a"')); }); -test("short-write exception, zero progress and fsync failure restore original bytes", posix, async (t) => { +test("short-write exception, zero progress and fsync failure skip after verified byte restoration", posix, async (t) => { for (const kind of ["short", "zero", "sync"]) { const f = await fixture(t); const { changes } = await collectSessionChanges(f.codexHome, "prov_a"); @@ -105,9 +105,20 @@ test("short-write exception, zero progress and fsync failure restore original by return h.write(b, o, 3, p); } }; - await assert.rejects(applySessionChanges(changes, options)); + const skipped = []; + const result = await applySessionChanges(changes, { + ...options, + onSkipped(change, reason) { skipped.push({ path: change.path, reason }); } + }); + assert.equal(result.appliedChanges, 0); + assert.equal(result.inPlaceChanges, 0); + assert.deepEqual(result.skippedPaths, [f.file]); + assert.deepEqual(skipped, [{ path: f.file, reason: "SKIP_NOT_APPLIED" }]); assert.deepEqual(await fs.readFile(f.file), f.original); - assert.equal((await fs.stat(f.file)).ino, before.ino); + const after = await fs.stat(f.file); + assert.equal(after.ino, before.ino); + assert.equal(after.size, before.size); + assert.equal(Math.round(after.mtimeMs), Math.round(before.mtimeMs)); } }); @@ -281,8 +292,11 @@ test("hardlinked files are not eligible and late links prevent byte mutation", p const { changes } = await collectSessionChanges(f.codexHome, "prov_a"); await fs.link(f.file, f.file + ".link"); assert.equal((await collectSessionChanges(f.codexHome, "prov_a")).changes[0].inPlaceMutation, null); - assert.equal((await applySessionChanges(changes)).appliedChanges, 0); + const result = await applySessionChanges(changes); + assert.equal(result.appliedChanges, 0); + assert.deepEqual(result.skippedChangedPaths, [f.file]); assert.deepEqual(await fs.readFile(f.file), f.original); + assert.deepEqual(await fs.readFile(f.file + ".link"), f.original); }); test("a post-mutation conflict returns partial and preserves the UndoBackup", async (t) => { From 7812b5c609aecb6545e523a785348fff0664bdf5 Mon Sep 17 00:00:00 2001 From: "DAL\\Administrator" <3452720699@qq.com> Date: Tue, 15 Sep 2026 16:01:40 +0800 Subject: [PATCH 3/4] fix(sync): retain wrapped busy-read skip facts --- docs/migration/BEHAVIOR_FIXTURES_ZH.md | 2 ++ src/session-files.js | 14 +++++++--- test/in-place-transaction.test.js | 30 +++++++++++++++++++++ test/provider-skip-data.test.js | 37 ++++++++++++++++++++++++++ 4 files changed, 80 insertions(+), 3 deletions(-) diff --git a/docs/migration/BEHAVIOR_FIXTURES_ZH.md b/docs/migration/BEHAVIOR_FIXTURES_ZH.md index 6b0d060..7206be1 100644 --- a/docs/migration/BEHAVIOR_FIXTURES_ZH.md +++ b/docs/migration/BEHAVIOR_FIXTURES_ZH.md @@ -6,6 +6,8 @@ `test/in-place-transaction.test.js` 的 POSIX 回归覆盖写前新增硬链接按变化跳过,以及短写、零进度、fsync 故障在验证恢复成功后返回 `SKIP_NOT_APPLIED`;同时断言原字节、inode、大小、mtime 和跳过原因。写后身份冲突或恢复失败仍停止,禁止回退整文件替换。 +占用错误包装回归覆盖 Status/Provider 扫描明细保留路径、原因和重试提示;Node 流式写入的写前读取保留原始错误码,EBUSY/EPERM 明确未写入后跳过,后续健康文件继续。Repair 共享读取的默认错误包装不变。 + ## ADR-0044:大首行与明确错误 `test/large-session-metadata.test.js` 覆盖 8 MiB 完整 Status→Sync/Switch→Restore、原地/变长正文不变、128 MiB LF/CRLF/EOF 读取边界与线性合并、超限/无效 Prepare 零写入及安全错误。`CPS_LARGE_HEADER_MIB=128` 可显式运行完整近上限读写。`provider-preparation-facts.test.js`、`status-coordination.test.js` 保留无效/超限拒绝及 Status 不完整检查。生产 Electron smoke 使用 8 MiB 首行验证大首行同步与恢复。 diff --git a/src/session-files.js b/src/session-files.js index b561b4c..ccc476f 100644 --- a/src/session-files.js +++ b/src/session-files.js @@ -1442,7 +1442,11 @@ async function tryRewriteCollectedFirstLine(change, options = {}) { let current; try { - current = await readFirstLineRecord(change.path, { maxBytes: Buffer.byteLength(change.originalFirstLine, "utf8"), strictMetadata: change.strictProviderMetadata === true }); + current = await readFirstLineRecord(change.path, { + maxBytes: Buffer.byteLength(change.originalFirstLine, "utf8"), + strictMetadata: change.strictProviderMetadata === true, + wrapBusyErrors: change.strictProviderMetadata !== true + }); } catch (error) { if (error instanceof RolloutMetadataLimitError || error instanceof RolloutMetadataEncodingError) return "SKIP_CHANGED"; const reason = fileReadSkipReason(error); @@ -1711,6 +1715,8 @@ export async function collectStatusRolloutMetadata(codexHome, options = {}) { continue; } if (skipLockedReads && isRolloutFileBusyError(error)) { + skippedItems.push(rolloutSkip(rolloutPath, "locked")); + incompletePaths.push(rolloutPath); lockedPaths.push(rolloutPath); continue; } @@ -1812,7 +1818,8 @@ export async function collectSessionChanges(codexHome, targetProvider, options = continue; } if (skipLockedReads && isRolloutFileBusyError(error)) { - lockedPaths.push(rolloutPath); + if (rejectInvalidMetadata) skip(rolloutPath, "locked"); + else lockedPaths.push(rolloutPath); continue; } if (rejectInvalidMetadata && error instanceof RolloutMetadataLimitError) { @@ -1865,7 +1872,8 @@ export async function collectSessionChanges(codexHome, targetProvider, options = continue; } if (skipLockedReads && isRolloutFileBusyError(error)) { - lockedPaths.push(rolloutPath); + if (rejectInvalidMetadata) skip(rolloutPath, "locked"); + else lockedPaths.push(rolloutPath); continue; } throw error; diff --git a/test/in-place-transaction.test.js b/test/in-place-transaction.test.js index e69747a..f58bcac 100644 --- a/test/in-place-transaction.test.js +++ b/test/in-place-transaction.test.js @@ -122,6 +122,36 @@ test("short-write exception, zero progress and fsync failure skip after verified } }); +test("Provider streaming prewrite busy reads skip without replacement and continue healthy files", posix, async (t) => { + for (const [code, reason] of [["EBUSY", "SKIP_BUSY"], ["EPERM", "SKIP_UNREADABLE"]]) { + const f = await fixture(t, header.replace('"openai"', '"old-provider"')); + const healthy = path.join(f.codexHome, "sessions", "rollout-z.jsonl"); + await fs.writeFile(healthy, header + tail); + const { changes } = await collectSessionChanges(f.codexHome, "prov_a", { + rejectInvalidMetadata: true, includeModels: false, includeUserEvent: false, includeEncryptedContent: false + }); + assert.equal(changes.find(change => change.path === f.file).inPlaceMutation, null); + const before = await fs.stat(f.file); + const originalOpen = fs.open; + const skipped = []; + fs.open = async (file, ...args) => { + if (String(file) === f.file) throw Object.assign(new Error("synthetic prewrite read failure"), { code }); + return originalOpen(file, ...args); + }; + try { + const result = await applySessionChanges(changes, { onSkipped(change, value) { skipped.push([change.path, value]); } }); + assert.deepEqual(result.appliedPaths, [healthy]); + assert.deepEqual(result.skippedPaths, [f.file]); + assert.deepEqual(skipped, [[f.file, reason]]); + } finally { fs.open = originalOpen; } + assert.deepEqual(await fs.readFile(f.file), f.original); + assert.equal((await fs.stat(f.file)).ino, before.ino); + assert.equal((await fs.stat(f.file)).mtimeMs, before.mtimeMs); + assert.equal(await fs.readFile(healthy, "utf8"), (header + tail).replace('"openai"', '"prov_a"')); + assert.ok((await fs.readdir(path.dirname(f.file))).every(name => !name.endsWith(".tmp"))); + } +}); + test("failed immediate restoration never falls back and remains recoverable", posix, async (t) => { const f = await fixture(t); const { changes, entry } = await prepare(f); diff --git a/test/provider-skip-data.test.js b/test/provider-skip-data.test.js index 9a32233..014f936 100644 --- a/test/provider-skip-data.test.js +++ b/test/provider-skip-data.test.js @@ -8,6 +8,7 @@ const cleanups = []; afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); }); import { prepareSync, applySync, prepareSwitch, applySwitch, prepareRestore, applyRestore, getStatus } from "../src/service.js"; import { openDatabase } from "../src/sqlite.js"; +import { collectStatusRolloutMetadata, collectSessionChanges } from "../src/session-files.js"; const line = id => JSON.stringify({ type: "session_meta", payload: { id, model_provider: "custom" } }) + '\n{"type":"event_msg","payload":{"message":"synthetic body"}}\n'; async function fixture(t, withPath = true) { @@ -37,6 +38,42 @@ async function fixture(t, withPath = true) { } const apply = plan => applySync({ schemaVersion: 1, planId: plan.planId }); +test("wrapped busy reads retain the path and retry reason in Status and Provider scan summaries", async t => { + for (const code of ["EBUSY", "EPERM"]) { + const f = await fixture(t); + const archived = path.join(f.home, "archived_sessions", "rollout-healthy.jsonl"); + await fs.mkdir(path.dirname(archived), { recursive: true }); + await fs.writeFile(archived, line("archived")); + const originalOpen = fs.open; + fs.open = async (file, ...args) => { + if (String(file) === f.good) throw Object.assign(new Error("synthetic busy read"), { code }); + return originalOpen(file, ...args); + }; + try { + const status = await collectStatusRolloutMetadata(f.home, { skipLockedReads: true }); + assert.deepEqual(status.lockedPaths, [f.good]); + assert.ok(status.incompletePaths.includes(f.good)); + assert.equal(status.providerCounts.archived_sessions.get("custom"), 1); + assert.equal(status.skipSummary.total, 2); + assert.equal(status.skipSummary.retryRecommended, true); + assert.deepEqual(status.skipSummary.items.filter(item => item.reason === "locked"), [ + { kind: "rollout", path: f.good, reason: "locked", stage: "scan", retryable: true } + ]); + const scan = await collectSessionChanges(f.home, "openai", { + skipLockedReads: true, rejectInvalidMetadata: true, + includeModels: false, includeUserEvent: false, includeEncryptedContent: false + }); + assert.deepEqual(scan.lockedPaths, [f.good]); + assert.equal(scan.skippedItems.filter(item => item.path === f.good && item.reason === "locked").length, 1); + assert.deepEqual(scan.changes.map(change => change.path), [archived]); + const plan = await prepareSync({ codexHome: f.home }); + assert.equal(plan.impact.rolloutFilesToChange, 1); + assert.ok(plan.impact.skipSummary.items.some(item => item.path === f.good && item.reason === (code === "EPERM" ? "unreadable" : "locked"))); + } finally { fs.open = originalOpen; } + assert.equal(await fs.readFile(f.good, "utf8"), line("good")); + } +}); + test("mixed metadata preserves a bad file and its index, updates healthy data, and restores only written files", async t => { const f = await fixture(t); const before = await fs.readFile(f.good, "utf8"); From 575de0103411e88ef8a91c93de4ba12c6d3348aa Mon Sep 17 00:00:00 2001 From: "DAL\\Administrator" <3452720699@qq.com> Date: Tue, 15 Sep 2026 16:20:25 +0800 Subject: [PATCH 4/4] fix(sync): report drift in initially aligned index rows --- docs/adr/0045-isolated-provider-data-skips.md | 4 ++ .../contracts/CORE_EXTERNAL_BEHAVIOR_ZH.md | 2 + docs/migration/BEHAVIOR_FIXTURES_ZH.md | 2 + .../core/src/application/provider-sync.js | 12 ++++ src/sqlite-state.js | 11 ++++ test/provider-skip-data.test.js | 60 +++++++++++++++++++ 6 files changed, 91 insertions(+) diff --git a/docs/adr/0045-isolated-provider-data-skips.md b/docs/adr/0045-isolated-provider-data-skips.md index 036603e..f46a969 100644 --- a/docs/adr/0045-isolated-provider-data-skips.md +++ b/docs/adr/0045-isolated-provider-data-skips.md @@ -14,6 +14,10 @@ POSIX 原地写在打开描述符时发现硬链接数量已变化,按 `change SQLite 通过有效 metadata 的 ID 或经规范化和边界验证的 `rollout_path` 建立关联。不猜文件名,不扫描正文找 ID。跳过文件的关联行不更新;冲突及未知归属保留。有无法关联的坏文件时,仅更新正向确认健康的索引;无歧义时继续支持 SQLite-only。预览与 SQL 使用同一选择集合,空集合零更新。事务内逐行比较原 Provider,变化/消失的行跳过,数据库级故障停止。 +执行前复核所有预览时已观察到的 SQLite 行,包括当时已经对齐、无需更新的行。Provider 或关联路径变化、行消失均记为跳过,不能把后来失配的行计为完成,也不能临时扩大已确认的写入集合;没有其他写目标时返回部分完成且不建备份。 + +已有 SQLite 写事务还会在事务内复核完整预览行快照,记录文件处理期间发生的行变化;实际 UPDATE 仍只执行原确认候选,不为纯观察创建额外写事务或备份。 + 备份先于业务写入,仅包含可写候选。写后复用 sessions manifest 的恢复范围,排除明确未写入的文件,保留写入成功和结果不确定的文件。范围落盘失败需提示,不能声称已排除。旧备份和崩溃时未记录结果的备份保守恢复;SQLite Restore 仍是整库快照。普通同步不引入 journal。 有跳过即部分完成。全部历史跳过且无其他写目标时 Sync 不创建备份;Switch 仍备份并切换配置,明确报告历史成功 0 条。成功文件和索引计数分开;跳过摘要含未确认数量。 diff --git a/docs/architecture/contracts/CORE_EXTERNAL_BEHAVIOR_ZH.md b/docs/architecture/contracts/CORE_EXTERNAL_BEHAVIOR_ZH.md index 4f2ad54..66f1f0e 100644 --- a/docs/architecture/contracts/CORE_EXTERNAL_BEHAVIOR_ZH.md +++ b/docs/architecture/contracts/CORE_EXTERNAL_BEHAVIOR_ZH.md @@ -4,6 +4,8 @@ ADR-0045 当前增量:Provider Sync/Switch/Watch 将单条首行无效、128 MiB 输入/输出超限、占用/不可读、消失/变化及明确未损坏源文件的写入失败列为跳过,正常候选继续;对应 SQLite 行及不确定关联保持原样。计划排除集合冻结,新增数据留待下次;全局安全、目录枚举、配置/存储、数据库和备份故障仍停止。部分完成新增有界 `skipSummary`(最多 200 项本机完整路径/安全行标识、原因/阶段/可重试性及总数/省略/未确认数);诊断导出单独移除路径和标识。全部跳过的 Sync 无备份,Switch 仍备份并切换配置。JSON 部分完成退出 3,Human 保持既有行为;协议结构版本不变。保留 128 MiB 与 PIO,Repair/Restore 边界不变。详见 [ADR-0045](../../adr/0045-isolated-provider-data-skips.md)。 +预览时已对齐的 SQLite 行也参与执行前复核:Provider/关联路径变化或行消失时保留现场并报告部分完成。已有 SQLite 写事务内再次核对完整预览快照,实际 UPDATE 始终限于原确认候选;纯观察不新增写事务或备份。 + ## 2026-09-11:轻量状态相关性(ADR-0043) 普通 Status 使用内部 `status` revision:正文追加、非 Provider SQLite 列及 WAL/SHM 变化不导致失效;仍校验首行、文件身份/链接数/集合/最小大小、threads schema/ID/Provider/archived 和配置路径。Provider 状态不再整读/哈希数据库文件。真实漂移最多重试一次,实际锁与 pending Restore 继续优先阻断。超限/非法首行仍不完整、不可读数据库仍不可读,WSL 不执行 SQL。完整 Diagnostics、显式 full Status、Plan/Apply、Repair/Restore 与 PIO 不变。见 [ADR-0043](../../adr/0043-status-provider-relevant-revisions.md)。 diff --git a/docs/migration/BEHAVIOR_FIXTURES_ZH.md b/docs/migration/BEHAVIOR_FIXTURES_ZH.md index 7206be1..2336805 100644 --- a/docs/migration/BEHAVIOR_FIXTURES_ZH.md +++ b/docs/migration/BEHAVIOR_FIXTURES_ZH.md @@ -8,6 +8,8 @@ 占用错误包装回归覆盖 Status/Provider 扫描明细保留路径、原因和重试提示;Node 流式写入的写前读取保留原始错误码,EBUSY/EPERM 明确未写入后跳过,后续健康文件继续。Repair 共享读取的默认错误包装不变。 +`provider-skip-data.test.js` 验证预览时已对齐的 SQLite 行在执行前改 Provider 或消失:有/无 `rollout_path`、无写目标/混合健康目标均返回部分完成,变化行和对应 rollout 保持原样,空写集合不创建备份。 + ## ADR-0044:大首行与明确错误 `test/large-session-metadata.test.js` 覆盖 8 MiB 完整 Status→Sync/Switch→Restore、原地/变长正文不变、128 MiB LF/CRLF/EOF 读取边界与线性合并、超限/无效 Prepare 零写入及安全错误。`CPS_LARGE_HEADER_MIB=128` 可显式运行完整近上限读写。`provider-preparation-facts.test.js`、`status-coordination.test.js` 保留无效/超限拒绝及 Status 不完整检查。生产 Electron smoke 使用 8 MiB 首行验证大首行同步与恢复。 diff --git a/packages/core/src/application/provider-sync.js b/packages/core/src/application/provider-sync.js index d7a433b..8446a2b 100644 --- a/packages/core/src/application/provider-sync.js +++ b/packages/core/src/application/provider-sync.js @@ -162,6 +162,17 @@ export async function buildProviderWriteProgram(context, settings = {}) { if (currentState.schema !== sqliteState.schema || JSON.stringify(currentState.identity) !== JSON.stringify(sqliteState.identity)) { throw new CoreError("STALE_STATE", "The thread index changed before backup.", { details: { reason: "state-db" } }); } + const currentRows = new Map(currentState.rows.map(row => [String(row.id), row])); + const changedRows = new Set(); + for (const expected of sqliteState.rows) { + const id = String(expected.id); + const row = currentRows.get(id); + if (!row || row.model_provider !== expected.model_provider || row.rollout_path !== expected.rollout_path) { + changedRows.add(id); + selection.skippedItems.push({ kind: "sqlite", id, reason: row ? "row-changed" : "row-missing", stage: "revalidate", retryable: true }); + } + } + selection.rows = selection.rows.filter(row => !changedRows.has(String(row.id))); for (const row of currentState.rows) if (!expectedRowIds.has(String(row.id)) && row.model_provider !== targetProvider) { selection.skippedItems.push({ kind: "sqlite", id: String(row.id), reason: "deferred", stage: "revalidate", retryable: true }); } @@ -310,6 +321,7 @@ export async function buildProviderWriteProgram(context, settings = {}) { const result = await sqliteTransaction.updateProvider(writeContext.storage, targetProvider, { busyTimeoutMs: writeContext.sqliteBusyTimeoutMs, plannedRows: finalSelection.rows, + expectedRows: sqliteState.rows, expectedSchema: sqliteState.schema, expectedIdentity: sqliteState.identity, expectedRowIds: [...expectedRowIds], diff --git a/src/sqlite-state.js b/src/sqlite-state.js index 97c2dd6..2bc653c 100644 --- a/src/sqlite-state.js +++ b/src/sqlite-state.js @@ -709,7 +709,18 @@ export async function updateSqliteProvider(storageOrLocation, targetProvider, af const read = db.prepare(`SELECT model_provider${hasPath ? ", rollout_path" : ""} FROM threads WHERE ${key} = ?`); const update = db.prepare(`UPDATE threads SET model_provider = ? WHERE ${key} = ? AND model_provider IS ?${hasPath ? " AND rollout_path IS ?" : ""}`); let changes = 0; + const changedRows = new Set(); + if (Array.isArray(options.expectedRows)) { + for (const row of options.expectedRows) { + const current = read.get(row.id); + if (!current || current.model_provider !== row.model_provider || (hasPath && current.rollout_path !== row.rollout_path)) { + changedRows.add(String(row.id)); + skippedItems.push({ kind: "sqlite", id: String(row.id), reason: current ? "row-changed" : "row-missing", stage: "sqlite", retryable: true }); + } + } + } for (const row of options.plannedRows) { + if (changedRows.has(String(row.id))) continue; const current = read.get(row.id); if (!current || current.model_provider !== row.model_provider || (hasPath && current.rollout_path !== row.rollout_path)) { skippedItems.push({ kind: "sqlite", id: String(row.id), reason: current ? "row-changed" : "row-missing", stage: "sqlite", retryable: true }); diff --git a/test/provider-skip-data.test.js b/test/provider-skip-data.test.js index 014f936..3dd1458 100644 --- a/test/provider-skip-data.test.js +++ b/test/provider-skip-data.test.js @@ -162,6 +162,66 @@ test("a row whose rollout_path changes after preview is preserved", async t => { assert.ok(result.result.skipSummary.items.some(item => item.kind === "sqlite" && item.id === "good")); }); +test("initially aligned SQLite rows that change or disappear make Apply partial without expanding the plan", async t => { + for (const withPath of [false, true]) for (const mixed of [false, true]) for (const drift of ["provider", "missing"]) { + const f = await fixture(t, withPath); + await fs.writeFile(f.good, line("good").replace('"custom"', '"openai"')); + await fs.writeFile(f.bad, line("bad").replace('"custom"', mixed ? '"custom"' : '"openai"')); + const setupDb = await openDatabase(f.dbPath); + try { + setupDb.exec("UPDATE threads SET model_provider='openai'"); + if (mixed) setupDb.exec("UPDATE threads SET model_provider='custom' WHERE id='bad'"); + } finally { setupDb.close(); } + const original = await fs.readFile(f.good); + const plan = await prepareSync({ codexHome: f.home }); + assert.equal(plan.impact.rolloutFilesToChange, mixed ? 1 : 0); + assert.equal(plan.impact.sqliteRowsToChange, mixed ? 1 : 0); + const changedDb = await openDatabase(f.dbPath); + try { + changedDb.exec(drift === "missing" ? "DELETE FROM threads WHERE id='good'" : "UPDATE threads SET model_provider='custom' WHERE id='good'"); + } finally { changedDb.close(); } + const result = await apply(plan); + assert.equal(result.outcome, "partial"); + assert.equal(result.result.changedSessionFiles, mixed ? 1 : 0); + assert.equal(result.result.sqliteRowsUpdated, mixed ? 1 : 0); + assert.equal(Boolean(result.backup), mixed); + assert.deepEqual(result.result.skipSummary.items.filter(item => item.id === "good"), [{ + kind: "sqlite", id: "good", reason: drift === "missing" ? "row-missing" : "row-changed", stage: "revalidate", retryable: true + }]); + assert.deepEqual(await fs.readFile(f.good), original); + assert.deepEqual(await f.rows(), { ...(drift === "missing" ? {} : { good: "custom" }), bad: "openai", "sqlite-only": "openai" }); + } +}); + +test("SQLite transaction reports initially aligned row drift during rollout writes", async t => { + for (const drift of ["provider", "missing"]) { + const f = await fixture(t); + await fs.writeFile(f.good, line("good").replace('"custom"', '"openai"')); + await fs.writeFile(f.bad, line("bad")); + const setupDb = await openDatabase(f.dbPath); + try { setupDb.exec("UPDATE threads SET model_provider='openai' WHERE id <> 'bad'"); } finally { setupDb.close(); } + const original = await fs.readFile(f.good); + let changed = false; + const plan = await prepareSync({ codexHome: f.home, faultInjector: async ({ point }) => { + if (point !== "after_rollout_apply" || changed) return; + changed = true; + const db = await openDatabase(f.dbPath); + try { db.exec(drift === "missing" ? "DELETE FROM threads WHERE id='good'" : "UPDATE threads SET model_provider='custom' WHERE id='good'"); } + finally { db.close(); } + } }); + const result = await apply(plan); + assert.equal(changed, true); + assert.equal(result.outcome, "partial"); + assert.equal(result.result.changedSessionFiles, 1); + assert.equal(result.result.sqliteRowsUpdated, 1); + assert.deepEqual(result.result.skipSummary.items.filter(item => item.id === "good"), [{ + kind: "sqlite", id: "good", reason: drift === "missing" ? "row-missing" : "row-changed", stage: "sqlite", retryable: true + }]); + assert.deepEqual(await fs.readFile(f.good), original); + assert.deepEqual(await f.rows(), { ...(drift === "missing" ? {} : { good: "custom" }), bad: "openai", "sqlite-only": "openai" }); + } +}); + test("a file disappearing after backup is excluded from physical Restore validation", async t => { const f = await fixture(t); await fs.writeFile(f.bad, line("bad"));