@agimon-ai/doompi-web 0.0.1-alpha.17 → 0.0.1-alpha.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/src/adapters/syncGuard.cjs +1 -1
  2. package/dist/src/adapters/syncGuard.cjs.map +1 -1
  3. package/dist/src/adapters/syncGuard.mjs +1 -1
  4. package/dist/src/adapters/syncGuard.mjs.map +1 -1
  5. package/dist/web/assets/{CodeEditorView-Vcq41fvN.js → CodeEditorView-CsSmzevS.js} +2 -2
  6. package/dist/web/assets/{CodeEditorView-Vcq41fvN.js.map → CodeEditorView-CsSmzevS.js.map} +1 -1
  7. package/dist/web/assets/{dist-fXu9lXcM.js → dist-BPunhDDV.js} +2 -2
  8. package/dist/web/assets/{dist-fXu9lXcM.js.map → dist-BPunhDDV.js.map} +1 -1
  9. package/dist/web/assets/{dist-DHeBCSod.js → dist-B_vtqt6-.js} +2 -2
  10. package/dist/web/assets/{dist-DHeBCSod.js.map → dist-B_vtqt6-.js.map} +1 -1
  11. package/dist/web/assets/{dist-VjxpG4yr.js → dist-BrPKNQB5.js} +2 -2
  12. package/dist/web/assets/{dist-VjxpG4yr.js.map → dist-BrPKNQB5.js.map} +1 -1
  13. package/dist/web/assets/{dist-0Xx-ctg3.js → dist-CIPu76lT.js} +2 -2
  14. package/dist/web/assets/{dist-0Xx-ctg3.js.map → dist-CIPu76lT.js.map} +1 -1
  15. package/dist/web/assets/{dist-CwttV9P8.js → dist-D5NFcAGB.js} +2 -2
  16. package/dist/web/assets/{dist-CwttV9P8.js.map → dist-D5NFcAGB.js.map} +1 -1
  17. package/dist/web/assets/{dist-PTC7K_TU.js → dist-DyAruYQ6.js} +2 -2
  18. package/dist/web/assets/{dist-PTC7K_TU.js.map → dist-DyAruYQ6.js.map} +1 -1
  19. package/dist/web/assets/{dist-Gi0bJbX1.js → dist-HHgaJ6ky.js} +2 -2
  20. package/dist/web/assets/{dist-Gi0bJbX1.js.map → dist-HHgaJ6ky.js.map} +1 -1
  21. package/dist/web/assets/{dist-DDX_XVB8.js → dist-YcRiLe9R.js} +2 -2
  22. package/dist/web/assets/{dist-DDX_XVB8.js.map → dist-YcRiLe9R.js.map} +1 -1
  23. package/dist/web/assets/{dist-9y0keW18.js → dist-yaVqrml-.js} +2 -2
  24. package/dist/web/assets/{dist-9y0keW18.js.map → dist-yaVqrml-.js.map} +1 -1
  25. package/dist/web/assets/index-BURdA48M.js +196 -0
  26. package/dist/web/assets/{index-CN4JqlUs.js.map → index-BURdA48M.js.map} +1 -1
  27. package/dist/web/index.html +1 -1
  28. package/package.json +10 -10
  29. package/src/adapters/syncGuard.ts +16 -3
  30. package/src/web/features/activity/ContextPanel.tsx +16 -2
  31. package/src/web/features/session/Timeline.tsx +4 -5
  32. package/src/web/lib/pluginSlotProps.ts +3 -0
  33. package/src/web/lib/sessionModel.ts +13 -2
  34. package/src/web/stores/usePluginSlotProps.ts +5 -0
  35. package/dist/web/assets/index-CN4JqlUs.js +0 -198
@@ -1,2 +1,2 @@
1
- const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("./bundledServer.cjs");let n=require("node:path");n=e.__toESM(n,1);let r=require("node:module"),i=require("@agimon-ai/doompi/services"),a=require("node:child_process"),o=require("@agimon-ai/doompi/utils");const s=[`dist`,`bin`,`cli.mjs`],c=[`sync`];function l(){return{ensureSynced:async()=>{},watch:()=>{},close:()=>{}}}function u(e){return process.env.DOOMPI_SYNC_COMMAND??t.repositoryDoomPiCli(e)??process.env.DOOMPI_AGENT_COMMAND??n.default.join(n.default.dirname((0,r.createRequire)(require("url").pathToFileURL(__filename).href).resolve(`@agimon-ai/doompi/package.json`)),...s)}function d(e){let t=u(e);return new Promise(n=>{let r=(0,a.spawn)(process.execPath,[t,...c],{cwd:e,env:{...process.env,DOOMPI_ROOT:e},stdio:[`ignore`,`pipe`,`pipe`]}),i=[],o=e=>{i.push(e.toString()),i.length>20&&i.shift()};r.stdout?.on(`data`,o),r.stderr?.on(`data`,o),r.once(`error`,e=>n({ok:!1,detail:`it could not start: ${e.message}`})),r.once(`exit`,e=>{n(e===0?{ok:!0}:{ok:!1,detail:`exit ${String(e)}: ${i.join(``).trim().slice(-400)}`})})})}function f(e){let t=e.onNotice??(()=>{}),n=e.repoRoot;if(n===void 0)try{n=(e.findRoot??o.findRepositoryRoot)(e.cwd??process.cwd())}catch{return l()}let r=e.runSync??(e=>d(e)),a=process.env.DOOMPI_BOOTSTRAP_ENTRY,s=e.readDrift??((e,t)=>(0,i.readSyncDrift)({repoRoot:e,expectedBootstrapEntry:t})),c=e.intervalMs??2e3,u,f,p=!1,m=0,h,g=e=>(m+=1,e!==h&&(t(e),h=e),{ready:!1,rebuilt:!1,error:e}),_=async e=>{t(`syncing: ${(0,i.describeSyncDrift)({fresh:!1,reasons:e.reasons})}`);let o;try{o=await r(n)??{ok:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return g(`sync failed (${t})`)}if(!o.ok)return g(`sync failed (${o.detail??`no detail`})`);let c=s(n,a);return c.fresh?(m=0,h=void 0,t(`sync complete`),{ready:!0,rebuilt:!0}):g(`sync completed but did not resolve drift (${(0,i.describeSyncDrift)({fresh:!1,reasons:c.reasons})})`)},v=async()=>{if(p)return{ready:!1,rebuilt:!1,error:`sync guard is closed`};if(u)return u;let e=s(n,a);return e.fresh?{ready:!0,rebuilt:!1}:(u=_(e).finally(()=>{u=void 0}),u)};return{async ensureSynced(){let e=await v();if(!e.ready)throw Error(`DoomPi cannot launch this session because ${e.error??`sync failed`}.`)},watch(e){if(f)return;let t=()=>{if(p)return;let e=Math.min(c*2**m,6e4);f=setTimeout(r,e),f.unref?.()},r=()=>{if(p||u){t();return}if(s(n,a).fresh){t();return}v().then(n=>{!p&&n.rebuilt&&e(),t()})};t()},close(){p=!0,f&&clearTimeout(f),f=void 0}}}exports.createSyncGuard=f;
1
+ const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("./webPluginGenerate.cjs"),n=require("./bundledServer.cjs");let r=require("node:path");r=e.__toESM(r,1);let i=require("node:module"),a=require("@agimon-ai/doompi/services"),o=require("node:child_process"),s=require("@agimon-ai/doompi/utils");const c=`DOOMPI_WEB_PACKAGE_ROOT`,l=[`dist`,`bin`,`cli.mjs`],u=[`sync`];function d(){return{ensureSynced:async()=>{},watch:()=>{},close:()=>{}}}function f(e){return process.env.DOOMPI_SYNC_COMMAND??n.repositoryDoomPiCli(e)??process.env.DOOMPI_AGENT_COMMAND??r.default.join(r.default.dirname((0,i.createRequire)(require("url").pathToFileURL(__filename).href).resolve(`@agimon-ai/doompi/package.json`)),...l)}function p(e){let n=f(e);return new Promise(r=>{let i=(0,o.spawn)(process.execPath,[n,...u],{cwd:e,env:{...process.env,DOOMPI_ROOT:e,[c]:process.env[c]||t.webHostPackageRoot()},stdio:[`ignore`,`pipe`,`pipe`]}),a=[],s=e=>{a.push(e.toString()),a.length>20&&a.shift()};i.stdout?.on(`data`,s),i.stderr?.on(`data`,s),i.once(`error`,e=>r({ok:!1,detail:`it could not start: ${e.message}`})),i.once(`exit`,e=>{r(e===0?{ok:!0}:{ok:!1,detail:`exit ${String(e)}: ${a.join(``).trim().slice(-400)}`})})})}function m(e){let t=e.onNotice??(()=>{}),n=e.repoRoot;if(n===void 0)try{n=(e.findRoot??s.findRepositoryRoot)(e.cwd??process.cwd())}catch{return d()}let r=e.runSync??(e=>p(e)),i=process.env.DOOMPI_BOOTSTRAP_ENTRY,o=e.readDrift??((e,t)=>{let n=(0,a.readSyncDrift)({repoRoot:e,expectedBootstrapEntry:t});return n.fresh&&(0,a.readSyncRegistration)(e)?.webDirectory==null?{fresh:!1,reasons:[`cockpit-bundle-missing`]}:n}),c=e.intervalMs??2e3,l,u,f=!1,m=0,h,g=e=>(m+=1,e!==h&&(t(e),h=e),{ready:!1,rebuilt:!1,error:e}),_=async e=>{t(`syncing: ${(0,a.describeSyncDrift)({fresh:!1,reasons:e.reasons})}`);let s;try{s=await r(n)??{ok:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return g(`sync failed (${t})`)}if(!s.ok)return g(`sync failed (${s.detail??`no detail`})`);let c=o(n,i);return c.fresh?(m=0,h=void 0,t(`sync complete`),{ready:!0,rebuilt:!0}):g(`sync completed but did not resolve drift (${(0,a.describeSyncDrift)({fresh:!1,reasons:c.reasons})})`)},v=async()=>{if(f)return{ready:!1,rebuilt:!1,error:`sync guard is closed`};if(l)return l;let e=o(n,i);return e.fresh?{ready:!0,rebuilt:!1}:(l=_(e).finally(()=>{l=void 0}),l)};return{async ensureSynced(){let e=await v();if(!e.ready)throw Error(`DoomPi cannot launch this session because ${e.error??`sync failed`}.`)},watch(e){if(u)return;let t=()=>{if(f)return;let e=Math.min(c*2**m,6e4);u=setTimeout(r,e),u.unref?.()},r=()=>{if(f||l){t();return}if(o(n,i).fresh){t();return}v().then(n=>{!f&&n.rebuilt&&e(),t()})};t()},close(){f=!0,u&&clearTimeout(u),u=void 0}}}exports.createSyncGuard=m;
2
2
  //# sourceMappingURL=syncGuard.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"syncGuard.cjs","names":["repositoryDoomPiCli","path","createRequire","spawn","findRepositoryRoot","readSyncDrift","describeSyncDrift"],"sources":["../../../src/adapters/syncGuard.ts"],"sourcesContent":["import { spawn } from 'node:child_process';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport { describeSyncDrift, readSyncDrift } from '@agimon-ai/doompi/services';\nimport { findRepositoryRoot } from '@agimon-ai/doompi/utils';\nimport { repositoryDoomPiCli } from './bundledServer.ts';\n\nconst DOOMPI_PACKAGE = '@agimon-ai/doompi';\nconst AGENT_COMMAND_ENV = 'DOOMPI_AGENT_COMMAND';\nconst SYNC_COMMAND_ENV = 'DOOMPI_SYNC_COMMAND';\nconst BOOTSTRAP_ENTRY_ENV = 'DOOMPI_BOOTSTRAP_ENTRY';\nconst HARNESS_ROOT_ENV = 'DOOMPI_ROOT';\nconst CLI_SEGMENTS = ['dist', 'bin', 'cli.mjs'];\nconst SYNC_ARGS = ['sync'];\n/** How often the watcher re-reads the drift inputs. */\nconst WATCH_INTERVAL_MS = 2_000;\n/** Ceiling for the retry delay after a sync that keeps failing. */\nconst MAX_RETRY_INTERVAL_MS = 60_000;\n\n/** What one sync attempt did, so a failure is never reported as a rebuild. */\nexport interface SyncRunOutcome {\n ok: boolean;\n detail?: string;\n}\n\nexport interface SyncGuardOptions {\n /** Known repository root, or a launch directory to discover one from. */\n repoRoot?: string;\n cwd?: string;\n onNotice?: (message: string) => void;\n /** Test seam for running the sync itself; returning nothing reads as success. */\n runSync?: (repoRoot: string) => Promise<SyncRunOutcome | void>;\n /** Test seam for the per-repository drift read and launcher-owned Doom entry. */\n readDrift?: (repoRoot: string, expectedBootstrapEntry?: string) => { fresh: boolean; reasons: readonly string[] };\n /** Test seam over repository discovery. */\n findRoot?: (cwd: string) => string;\n intervalMs?: number;\n}\nexport interface SyncGuard {\n /**\n * Syncs the repository when anything a session reads has drifted.\n *\n * Serialized: several sessions starting at once wait on one sync rather\n * than racing to rebuild the same artifacts over each other.\n */\n ensureSynced(): Promise<void>;\n /** Re-syncs on drift and reports when artifacts changed under a running cockpit. */\n watch(onSynced: () => void): void;\n close(): void;\n}\n\nfunction inactiveSyncGuard(): SyncGuard {\n return {\n ensureSynced: async () => {},\n watch: () => {},\n close: () => {},\n };\n}\n\n/**\n * The DoomPi CLI this repository should sync with.\n *\n * A repository that pins its own DoomPi must be synced by that one: extensions\n * are version-coupled to the harness that resolves them, and the copy sitting\n * in the hub's dependency tree may not be the copy the repository runs.\n */\nfunction syncCliFor(repoRoot: string): string {\n return (\n process.env[SYNC_COMMAND_ENV] ??\n repositoryDoomPiCli(repoRoot) ??\n process.env[AGENT_COMMAND_ENV] ??\n path.join(path.dirname(createRequire(import.meta.url).resolve(`${DOOMPI_PACKAGE}/package.json`)), ...CLI_SEGMENTS)\n );\n}\n\n/** Runs the launcher's own sync, in its own process so the hub keeps serving. */\nfunction spawnSync(repoRoot: string): Promise<SyncRunOutcome> {\n const cli = syncCliFor(repoRoot);\n return new Promise((resolve) => {\n const child = spawn(process.execPath, [cli, ...SYNC_ARGS], {\n cwd: repoRoot,\n env: { ...process.env, [HARNESS_ROOT_ENV]: repoRoot },\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n const tail: string[] = [];\n const keep = (chunk: Buffer): void => {\n tail.push(chunk.toString());\n if (tail.length > 20) tail.shift();\n };\n child.stdout?.on('data', keep);\n child.stderr?.on('data', keep);\n // A failed sync is reported, not thrown: the session the caller wanted still\n // starts, and it starts against whatever the last good sync left. What it\n // must not do is claim the artifacts were rebuilt.\n child.once('error', (error) => resolve({ ok: false, detail: `it could not start: ${error.message}` }));\n child.once('exit', (code) => {\n if (code === 0) resolve({ ok: true });\n else resolve({ ok: false, detail: `exit ${String(code)}: ${tail.join('').trim().slice(-400)}` });\n });\n });\n}\n\n/**\n * Keeps the repository synced under a running cockpit.\n *\n * A session launched from the browser reads what sync produced: the resolved\n * composition, the plugin bundle, and the package API routes. Nothing forces\n * a person clicking \"new session\" to have run sync first, and a stale one\n * fails quietly rather than loudly, so the hub checks and syncs itself.\n */\nexport function createSyncGuard(options: SyncGuardOptions): SyncGuard {\n const notice = options.onNotice ?? ((): void => {});\n let repoRoot = options.repoRoot;\n if (repoRoot === undefined) {\n try {\n repoRoot = (options.findRoot ?? findRepositoryRoot)(options.cwd ?? process.cwd());\n } catch {\n return inactiveSyncGuard();\n }\n }\n const runSync = options.runSync ?? ((root: string) => spawnSync(root));\n const expectedBootstrapEntry = process.env[BOOTSTRAP_ENTRY_ENV];\n const readDrift =\n options.readDrift ??\n ((root: string, entry?: string) => readSyncDrift({ repoRoot: root, expectedBootstrapEntry: entry }));\n const baseInterval = options.intervalMs ?? WATCH_INTERVAL_MS;\n let inFlight: Promise<{ ready: boolean; rebuilt: boolean; error?: string }> | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let closed = false;\n let consecutiveFailures = 0;\n let lastFailureNotice: string | undefined;\n\n /**\n * One sync attempt, reporting whether it actually rebuilt anything.\n *\n * A sync that exits non-zero published nothing, so saying \"complete\" and\n * telling every attached page to reload is two lies and a reload storm: the\n * repository is still drifted, so the next poll tries again immediately.\n */\n const failedResult = (failure: string): { ready: false; rebuilt: false; error: string } => {\n consecutiveFailures += 1;\n // The same failure every few seconds buries everything else in the log.\n if (failure !== lastFailureNotice) {\n notice(failure);\n lastFailureNotice = failure;\n }\n return { ready: false, rebuilt: false, error: failure };\n };\n\n const syncOnce = async (drift: {\n reasons: readonly string[];\n }): Promise<{ ready: boolean; rebuilt: boolean; error?: string }> => {\n notice(`syncing: ${describeSyncDrift({ fresh: false, reasons: drift.reasons as never })}`);\n let outcome: SyncRunOutcome;\n try {\n outcome = (await runSync(repoRoot)) ?? { ok: true };\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n return failedResult(`sync failed (${detail})`);\n }\n if (!outcome.ok) return failedResult(`sync failed (${outcome.detail ?? 'no detail'})`);\n\n const remaining = readDrift(repoRoot, expectedBootstrapEntry);\n if (!remaining.fresh) {\n return failedResult(\n `sync completed but did not resolve drift (${describeSyncDrift({ fresh: false, reasons: remaining.reasons as never })})`,\n );\n }\n consecutiveFailures = 0;\n lastFailureNotice = undefined;\n notice('sync complete');\n return { ready: true, rebuilt: true };\n };\n\n const ensureSynced = async (): Promise<{ ready: boolean; rebuilt: boolean; error?: string }> => {\n if (closed) return { ready: false, rebuilt: false, error: 'sync guard is closed' };\n // Joining the run already in flight is what makes concurrent launches\n // wait for one sync instead of starting several.\n if (inFlight) return inFlight;\n const drift = readDrift(repoRoot, expectedBootstrapEntry);\n if (drift.fresh) return { ready: true, rebuilt: false };\n inFlight = syncOnce(drift).finally(() => {\n inFlight = undefined;\n });\n return inFlight;\n };\n\n return {\n async ensureSynced() {\n const result = await ensureSynced();\n if (!result.ready) throw new Error(`DoomPi cannot launch this session because ${result.error ?? 'sync failed'}.`);\n },\n watch(onSynced) {\n if (timer) return;\n const schedule = (): void => {\n if (closed) return;\n // Backing off after a failure: a repository that cannot sync will not\n // start syncing because it was asked again two seconds later, and the\n // retries drown the reason in the log.\n const delay = Math.min(baseInterval * 2 ** consecutiveFailures, MAX_RETRY_INTERVAL_MS);\n timer = setTimeout(tick, delay);\n // The hub should not be held open by its own watcher.\n timer.unref?.();\n };\n const tick = (): void => {\n if (closed || inFlight) {\n schedule();\n return;\n }\n const drift = readDrift(repoRoot, expectedBootstrapEntry);\n if (drift.fresh) {\n schedule();\n return;\n }\n void ensureSynced().then((result) => {\n if (!closed && result.rebuilt) onSynced();\n schedule();\n });\n };\n schedule();\n },\n close() {\n closed = true;\n if (timer) clearTimeout(timer);\n timer = undefined;\n },\n };\n}\n"],"mappings":"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"}
1
+ {"version":3,"file":"syncGuard.cjs","names":["repositoryDoomPiCli","path","createRequire","spawn","webHostPackageRoot","findRepositoryRoot","readSyncDrift","readSyncRegistration","describeSyncDrift"],"sources":["../../../src/adapters/syncGuard.ts"],"sourcesContent":["import { spawn } from 'node:child_process';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport { describeSyncDrift, readSyncDrift, readSyncRegistration } from '@agimon-ai/doompi/services';\nimport { findRepositoryRoot } from '@agimon-ai/doompi/utils';\nimport { repositoryDoomPiCli } from './bundledServer.ts';\nimport { webHostPackageRoot } from './webPluginGenerate.ts';\n\nconst DOOMPI_PACKAGE = '@agimon-ai/doompi';\nconst AGENT_COMMAND_ENV = 'DOOMPI_AGENT_COMMAND';\nconst SYNC_COMMAND_ENV = 'DOOMPI_SYNC_COMMAND';\nconst BOOTSTRAP_ENTRY_ENV = 'DOOMPI_BOOTSTRAP_ENTRY';\nconst HARNESS_ROOT_ENV = 'DOOMPI_ROOT';\nconst WEB_PACKAGE_ROOT_ENV = 'DOOMPI_WEB_PACKAGE_ROOT';\nconst CLI_SEGMENTS = ['dist', 'bin', 'cli.mjs'];\nconst SYNC_ARGS = ['sync'];\n/** How often the watcher re-reads the drift inputs. */\nconst WATCH_INTERVAL_MS = 2_000;\n/** Ceiling for the retry delay after a sync that keeps failing. */\nconst MAX_RETRY_INTERVAL_MS = 60_000;\n\n/** What one sync attempt did, so a failure is never reported as a rebuild. */\nexport interface SyncRunOutcome {\n ok: boolean;\n detail?: string;\n}\n\nexport interface SyncGuardOptions {\n /** Known repository root, or a launch directory to discover one from. */\n repoRoot?: string;\n cwd?: string;\n onNotice?: (message: string) => void;\n /** Test seam for running the sync itself; returning nothing reads as success. */\n runSync?: (repoRoot: string) => Promise<SyncRunOutcome | void>;\n /** Test seam for the per-repository drift read and launcher-owned Doom entry. */\n readDrift?: (repoRoot: string, expectedBootstrapEntry?: string) => { fresh: boolean; reasons: readonly string[] };\n /** Test seam over repository discovery. */\n findRoot?: (cwd: string) => string;\n intervalMs?: number;\n}\nexport interface SyncGuard {\n /**\n * Syncs the repository when anything a session reads has drifted.\n *\n * Serialized: several sessions starting at once wait on one sync rather\n * than racing to rebuild the same artifacts over each other.\n */\n ensureSynced(): Promise<void>;\n /** Re-syncs on drift and reports when artifacts changed under a running cockpit. */\n watch(onSynced: () => void): void;\n close(): void;\n}\n\nfunction inactiveSyncGuard(): SyncGuard {\n return {\n ensureSynced: async () => {},\n watch: () => {},\n close: () => {},\n };\n}\n\n/**\n * The DoomPi CLI this repository should sync with.\n *\n * A repository that pins its own DoomPi must be synced by that one: extensions\n * are version-coupled to the harness that resolves them, and the copy sitting\n * in the hub's dependency tree may not be the copy the repository runs.\n */\nfunction syncCliFor(repoRoot: string): string {\n return (\n process.env[SYNC_COMMAND_ENV] ??\n repositoryDoomPiCli(repoRoot) ??\n process.env[AGENT_COMMAND_ENV] ??\n path.join(path.dirname(createRequire(import.meta.url).resolve(`${DOOMPI_PACKAGE}/package.json`)), ...CLI_SEGMENTS)\n );\n}\n\n/** Runs the launcher's own sync, in its own process so the hub keeps serving. */\nfunction spawnSync(repoRoot: string): Promise<SyncRunOutcome> {\n const cli = syncCliFor(repoRoot);\n return new Promise((resolve) => {\n const child = spawn(process.execPath, [cli, ...SYNC_ARGS], {\n cwd: repoRoot,\n env: {\n ...process.env,\n [HARNESS_ROOT_ENV]: repoRoot,\n [WEB_PACKAGE_ROOT_ENV]: process.env[WEB_PACKAGE_ROOT_ENV] || webHostPackageRoot(),\n },\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n const tail: string[] = [];\n const keep = (chunk: Buffer): void => {\n tail.push(chunk.toString());\n if (tail.length > 20) tail.shift();\n };\n child.stdout?.on('data', keep);\n child.stderr?.on('data', keep);\n // A failed sync is reported, not thrown: the session the caller wanted still\n // starts, and it starts against whatever the last good sync left. What it\n // must not do is claim the artifacts were rebuilt.\n child.once('error', (error) => resolve({ ok: false, detail: `it could not start: ${error.message}` }));\n child.once('exit', (code) => {\n if (code === 0) resolve({ ok: true });\n else resolve({ ok: false, detail: `exit ${String(code)}: ${tail.join('').trim().slice(-400)}` });\n });\n });\n}\n\n/**\n * Keeps the repository synced under a running cockpit.\n *\n * A session launched from the browser reads what sync produced: the resolved\n * composition, the plugin bundle, and the package API routes. Nothing forces\n * a person clicking \"new session\" to have run sync first, and a stale one\n * fails quietly rather than loudly, so the hub checks and syncs itself.\n */\nexport function createSyncGuard(options: SyncGuardOptions): SyncGuard {\n const notice = options.onNotice ?? ((): void => {});\n let repoRoot = options.repoRoot;\n if (repoRoot === undefined) {\n try {\n repoRoot = (options.findRoot ?? findRepositoryRoot)(options.cwd ?? process.cwd());\n } catch {\n return inactiveSyncGuard();\n }\n }\n const runSync = options.runSync ?? ((root: string) => spawnSync(root));\n const expectedBootstrapEntry = process.env[BOOTSTRAP_ENTRY_ENV];\n const readDrift =\n options.readDrift ??\n ((root: string, entry?: string) => {\n const drift = readSyncDrift({ repoRoot: root, expectedBootstrapEntry: entry });\n // A CLI-only sync is valid for the terminal, but cannot supply session UI.\n if (drift.fresh && readSyncRegistration(root)?.webDirectory == null) {\n return { fresh: false, reasons: ['cockpit-bundle-missing'] };\n }\n return drift;\n });\n const baseInterval = options.intervalMs ?? WATCH_INTERVAL_MS;\n let inFlight: Promise<{ ready: boolean; rebuilt: boolean; error?: string }> | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let closed = false;\n let consecutiveFailures = 0;\n let lastFailureNotice: string | undefined;\n\n /**\n * One sync attempt, reporting whether it actually rebuilt anything.\n *\n * A sync that exits non-zero published nothing, so saying \"complete\" and\n * telling every attached page to reload is two lies and a reload storm: the\n * repository is still drifted, so the next poll tries again immediately.\n */\n const failedResult = (failure: string): { ready: false; rebuilt: false; error: string } => {\n consecutiveFailures += 1;\n // The same failure every few seconds buries everything else in the log.\n if (failure !== lastFailureNotice) {\n notice(failure);\n lastFailureNotice = failure;\n }\n return { ready: false, rebuilt: false, error: failure };\n };\n\n const syncOnce = async (drift: {\n reasons: readonly string[];\n }): Promise<{ ready: boolean; rebuilt: boolean; error?: string }> => {\n notice(`syncing: ${describeSyncDrift({ fresh: false, reasons: drift.reasons as never })}`);\n let outcome: SyncRunOutcome;\n try {\n outcome = (await runSync(repoRoot)) ?? { ok: true };\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n return failedResult(`sync failed (${detail})`);\n }\n if (!outcome.ok) return failedResult(`sync failed (${outcome.detail ?? 'no detail'})`);\n\n const remaining = readDrift(repoRoot, expectedBootstrapEntry);\n if (!remaining.fresh) {\n return failedResult(\n `sync completed but did not resolve drift (${describeSyncDrift({ fresh: false, reasons: remaining.reasons as never })})`,\n );\n }\n consecutiveFailures = 0;\n lastFailureNotice = undefined;\n notice('sync complete');\n return { ready: true, rebuilt: true };\n };\n\n const ensureSynced = async (): Promise<{ ready: boolean; rebuilt: boolean; error?: string }> => {\n if (closed) return { ready: false, rebuilt: false, error: 'sync guard is closed' };\n // Joining the run already in flight is what makes concurrent launches\n // wait for one sync instead of starting several.\n if (inFlight) return inFlight;\n const drift = readDrift(repoRoot, expectedBootstrapEntry);\n if (drift.fresh) return { ready: true, rebuilt: false };\n inFlight = syncOnce(drift).finally(() => {\n inFlight = undefined;\n });\n return inFlight;\n };\n\n return {\n async ensureSynced() {\n const result = await ensureSynced();\n if (!result.ready) throw new Error(`DoomPi cannot launch this session because ${result.error ?? 'sync failed'}.`);\n },\n watch(onSynced) {\n if (timer) return;\n const schedule = (): void => {\n if (closed) return;\n // Backing off after a failure: a repository that cannot sync will not\n // start syncing because it was asked again two seconds later, and the\n // retries drown the reason in the log.\n const delay = Math.min(baseInterval * 2 ** consecutiveFailures, MAX_RETRY_INTERVAL_MS);\n timer = setTimeout(tick, delay);\n // The hub should not be held open by its own watcher.\n timer.unref?.();\n };\n const tick = (): void => {\n if (closed || inFlight) {\n schedule();\n return;\n }\n const drift = readDrift(repoRoot, expectedBootstrapEntry);\n if (drift.fresh) {\n schedule();\n return;\n }\n void ensureSynced().then((result) => {\n if (!closed && result.rebuilt) onSynced();\n schedule();\n });\n };\n schedule();\n },\n close() {\n closed = true;\n if (timer) clearTimeout(timer);\n timer = undefined;\n },\n };\n}\n"],"mappings":"oTAQA,MAKM,EAAuB,0BACvB,EAAe,CAAC,OAAQ,MAAO,SAAS,EACxC,EAAY,CAAC,MAAM,EAsCzB,SAAS,GAA+B,CACtC,MAAO,CACL,aAAc,SAAY,CAAC,EAC3B,UAAa,CAAC,EACd,UAAa,CAAC,CAChB,CACF,CASA,SAAS,EAAW,EAA0B,CAC5C,OACE,QAAQ,IAAI,qBACZA,EAAAA,oBAAoB,CAAQ,GAC5B,QAAQ,IAAI,sBACZC,EAAAA,QAAK,KAAKA,EAAAA,QAAK,SAAA,EAAQC,EAAAA,cAAAA,CAAAA,QAAAA,KAAAA,CAAAA,CAAAA,cAAAA,UAAAA,CAAAA,CAAAA,IAA6B,CAAC,CAAC,QAAQ,gCAAgC,CAAC,EAAG,GAAG,CAAY,CAErH,CAGA,SAAS,EAAU,EAA2C,CAC5D,IAAM,EAAM,EAAW,CAAQ,EAC/B,OAAO,IAAI,QAAS,GAAY,CAC9B,IAAM,GAAA,EAAQC,EAAAA,MAAAA,CAAM,QAAQ,SAAU,CAAC,EAAK,GAAG,CAAS,EAAG,CACzD,IAAK,EACL,IAAK,CACH,GAAG,QAAQ,IACV,YAAmB,GACnB,GAAuB,QAAQ,IAAI,IAAyBC,EAAAA,mBAAmB,CAClF,EACA,MAAO,CAAC,SAAU,OAAQ,MAAM,CAClC,CAAC,EACK,EAAiB,CAAC,EAClB,EAAQ,GAAwB,CACpC,EAAK,KAAK,EAAM,SAAS,CAAC,EACtB,EAAK,OAAS,IAAI,EAAK,MAAM,CACnC,EACA,EAAM,QAAQ,GAAG,OAAQ,CAAI,EAC7B,EAAM,QAAQ,GAAG,OAAQ,CAAI,EAI7B,EAAM,KAAK,QAAU,GAAU,EAAQ,CAAE,GAAI,GAAO,OAAQ,uBAAuB,EAAM,SAAU,CAAC,CAAC,EACrG,EAAM,KAAK,OAAS,GAAS,CACX,EAAZ,IAAS,EAAW,CAAE,GAAI,EAAK,EACtB,CAAE,GAAI,GAAO,OAAQ,QAAQ,OAAO,CAAI,EAAE,IAAI,EAAK,KAAK,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,MAAM,IAAI,GAAI,CAAC,CACjG,CAAC,CACH,CAAC,CACH,CAUA,SAAgB,EAAgB,EAAsC,CACpE,IAAM,EAAS,EAAQ,eAAyB,CAAC,GAC7C,EAAW,EAAQ,SACvB,GAAI,IAAa,IAAA,GACf,GAAI,CACF,GAAY,EAAQ,UAAYC,EAAAA,mBAAAA,CAAoB,EAAQ,KAAO,QAAQ,IAAI,CAAC,CAClF,MAAQ,CACN,OAAO,EAAkB,CAC3B,CAEF,IAAM,EAAU,EAAQ,UAAa,GAAiB,EAAU,CAAI,GAC9D,EAAyB,QAAQ,IAAI,uBACrC,EACJ,EAAQ,aACN,EAAc,IAAmB,CACjC,IAAM,GAAA,EAAQC,EAAAA,cAAAA,CAAc,CAAE,SAAU,EAAM,uBAAwB,CAAM,CAAC,EAK7E,OAHI,EAAM,QAAA,EAASC,EAAAA,qBAAAA,CAAqB,CAAI,CAAC,EAAE,cAAgB,KACtD,CAAE,MAAO,GAAO,QAAS,CAAC,wBAAwB,CAAE,EAEtD,CACT,GACI,EAAe,EAAQ,YAAc,IACvC,EACA,EACA,EAAS,GACT,EAAsB,EACtB,EASE,EAAgB,IACpB,GAAuB,EAEnB,IAAY,IACd,EAAO,CAAO,EACd,EAAoB,GAEf,CAAE,MAAO,GAAO,QAAS,GAAO,MAAO,CAAQ,GAGlD,EAAW,KAAO,IAE6C,CACnE,EAAO,aAAA,EAAYC,EAAAA,kBAAAA,CAAkB,CAAE,MAAO,GAAO,QAAS,EAAM,OAAiB,CAAC,GAAG,EACzF,IAAI,EACJ,GAAI,CACF,EAAW,MAAM,EAAQ,CAAQ,GAAM,CAAE,GAAI,EAAK,CACpD,OAAS,EAAO,CACd,IAAM,EAAS,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,EACpE,OAAO,EAAa,gBAAgB,EAAO,EAAE,CAC/C,CACA,GAAI,CAAC,EAAQ,GAAI,OAAO,EAAa,gBAAgB,EAAQ,QAAU,YAAY,EAAE,EAErF,IAAM,EAAY,EAAU,EAAU,CAAsB,EAS5D,OARK,EAAU,OAKf,EAAsB,EACtB,EAAoB,IAAA,GACpB,EAAO,eAAe,EACf,CAAE,MAAO,GAAM,QAAS,EAAK,GAP3B,EACL,8CAAA,EAA6CA,EAAAA,kBAAAA,CAAkB,CAAE,MAAO,GAAO,QAAS,EAAU,OAAiB,CAAC,EAAE,EACxH,CAMJ,EAEM,EAAe,SAA2E,CAC9F,GAAI,EAAQ,MAAO,CAAE,MAAO,GAAO,QAAS,GAAO,MAAO,sBAAuB,EAGjF,GAAI,EAAU,OAAO,EACrB,IAAM,EAAQ,EAAU,EAAU,CAAsB,EAKxD,OAJI,EAAM,MAAc,CAAE,MAAO,GAAM,QAAS,EAAM,GACtD,EAAW,EAAS,CAAK,CAAC,CAAC,YAAc,CACvC,EAAW,IAAA,EACb,CAAC,EACM,EACT,EAEA,MAAO,CACL,MAAM,cAAe,CACnB,IAAM,EAAS,MAAM,EAAa,EAClC,GAAI,CAAC,EAAO,MAAO,MAAU,MAAM,6CAA6C,EAAO,OAAS,cAAc,EAAE,CAClH,EACA,MAAM,EAAU,CACd,GAAI,EAAO,OACX,IAAM,MAAuB,CAC3B,GAAI,EAAQ,OAIZ,IAAM,EAAQ,KAAK,IAAI,EAAe,GAAK,EAAqB,GAAqB,EACrF,EAAQ,WAAW,EAAM,CAAK,EAE9B,EAAM,QAAQ,CAChB,EACM,MAAmB,CACvB,GAAI,GAAU,EAAU,CACtB,EAAS,EACT,MACF,CAEA,GADc,EAAU,EAAU,CAC1B,CAAC,CAAC,MAAO,CACf,EAAS,EACT,MACF,CACA,EAAkB,CAAC,CAAC,KAAM,GAAW,CAC/B,CAAC,GAAU,EAAO,SAAS,EAAS,EACxC,EAAS,CACX,CAAC,CACH,EACA,EAAS,CACX,EACA,OAAQ,CACN,EAAS,GACL,GAAO,aAAa,CAAK,EAC7B,EAAQ,IAAA,EACV,CACF,CACF"}
@@ -1,2 +1,2 @@
1
- import{repositoryDoomPiCli as e}from"./bundledServer.mjs";import{createRequire as t}from"node:module";import n from"node:path";import{describeSyncDrift as r,readSyncDrift as i}from"@agimon-ai/doompi/services";import{spawn as a}from"node:child_process";import{findRepositoryRoot as o}from"@agimon-ai/doompi/utils";const s=[`dist`,`bin`,`cli.mjs`],c=[`sync`];function l(){return{ensureSynced:async()=>{},watch:()=>{},close:()=>{}}}function u(r){return process.env.DOOMPI_SYNC_COMMAND??e(r)??process.env.DOOMPI_AGENT_COMMAND??n.join(n.dirname(t(import.meta.url).resolve(`@agimon-ai/doompi/package.json`)),...s)}function d(e){let t=u(e);return new Promise(n=>{let r=a(process.execPath,[t,...c],{cwd:e,env:{...process.env,DOOMPI_ROOT:e},stdio:[`ignore`,`pipe`,`pipe`]}),i=[],o=e=>{i.push(e.toString()),i.length>20&&i.shift()};r.stdout?.on(`data`,o),r.stderr?.on(`data`,o),r.once(`error`,e=>n({ok:!1,detail:`it could not start: ${e.message}`})),r.once(`exit`,e=>{n(e===0?{ok:!0}:{ok:!1,detail:`exit ${String(e)}: ${i.join(``).trim().slice(-400)}`})})})}function f(e){let t=e.onNotice??(()=>{}),n=e.repoRoot;if(n===void 0)try{n=(e.findRoot??o)(e.cwd??process.cwd())}catch{return l()}let a=e.runSync??(e=>d(e)),s=process.env.DOOMPI_BOOTSTRAP_ENTRY,c=e.readDrift??((e,t)=>i({repoRoot:e,expectedBootstrapEntry:t})),u=e.intervalMs??2e3,f,p,m=!1,h=0,g,_=e=>(h+=1,e!==g&&(t(e),g=e),{ready:!1,rebuilt:!1,error:e}),v=async e=>{t(`syncing: ${r({fresh:!1,reasons:e.reasons})}`);let i;try{i=await a(n)??{ok:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return _(`sync failed (${t})`)}if(!i.ok)return _(`sync failed (${i.detail??`no detail`})`);let o=c(n,s);return o.fresh?(h=0,g=void 0,t(`sync complete`),{ready:!0,rebuilt:!0}):_(`sync completed but did not resolve drift (${r({fresh:!1,reasons:o.reasons})})`)},y=async()=>{if(m)return{ready:!1,rebuilt:!1,error:`sync guard is closed`};if(f)return f;let e=c(n,s);return e.fresh?{ready:!0,rebuilt:!1}:(f=v(e).finally(()=>{f=void 0}),f)};return{async ensureSynced(){let e=await y();if(!e.ready)throw Error(`DoomPi cannot launch this session because ${e.error??`sync failed`}.`)},watch(e){if(p)return;let t=()=>{if(m)return;let e=Math.min(u*2**h,6e4);p=setTimeout(r,e),p.unref?.()},r=()=>{if(m||f){t();return}if(c(n,s).fresh){t();return}y().then(n=>{!m&&n.rebuilt&&e(),t()})};t()},close(){m=!0,p&&clearTimeout(p),p=void 0}}}export{f as createSyncGuard};
1
+ import{webHostPackageRoot as e}from"./webPluginGenerate.mjs";import{repositoryDoomPiCli as t}from"./bundledServer.mjs";import{createRequire as n}from"node:module";import r from"node:path";import{describeSyncDrift as i,readSyncDrift as a,readSyncRegistration as o}from"@agimon-ai/doompi/services";import{spawn as s}from"node:child_process";import{findRepositoryRoot as c}from"@agimon-ai/doompi/utils";const l=`DOOMPI_WEB_PACKAGE_ROOT`,u=[`dist`,`bin`,`cli.mjs`],d=[`sync`];function f(){return{ensureSynced:async()=>{},watch:()=>{},close:()=>{}}}function p(e){return process.env.DOOMPI_SYNC_COMMAND??t(e)??process.env.DOOMPI_AGENT_COMMAND??r.join(r.dirname(n(import.meta.url).resolve(`@agimon-ai/doompi/package.json`)),...u)}function m(t){let n=p(t);return new Promise(r=>{let i=s(process.execPath,[n,...d],{cwd:t,env:{...process.env,DOOMPI_ROOT:t,[l]:process.env[l]||e()},stdio:[`ignore`,`pipe`,`pipe`]}),a=[],o=e=>{a.push(e.toString()),a.length>20&&a.shift()};i.stdout?.on(`data`,o),i.stderr?.on(`data`,o),i.once(`error`,e=>r({ok:!1,detail:`it could not start: ${e.message}`})),i.once(`exit`,e=>{r(e===0?{ok:!0}:{ok:!1,detail:`exit ${String(e)}: ${a.join(``).trim().slice(-400)}`})})})}function h(e){let t=e.onNotice??(()=>{}),n=e.repoRoot;if(n===void 0)try{n=(e.findRoot??c)(e.cwd??process.cwd())}catch{return f()}let r=e.runSync??(e=>m(e)),s=process.env.DOOMPI_BOOTSTRAP_ENTRY,l=e.readDrift??((e,t)=>{let n=a({repoRoot:e,expectedBootstrapEntry:t});return n.fresh&&o(e)?.webDirectory==null?{fresh:!1,reasons:[`cockpit-bundle-missing`]}:n}),u=e.intervalMs??2e3,d,p,h=!1,g=0,_,v=e=>(g+=1,e!==_&&(t(e),_=e),{ready:!1,rebuilt:!1,error:e}),y=async e=>{t(`syncing: ${i({fresh:!1,reasons:e.reasons})}`);let a;try{a=await r(n)??{ok:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return v(`sync failed (${t})`)}if(!a.ok)return v(`sync failed (${a.detail??`no detail`})`);let o=l(n,s);return o.fresh?(g=0,_=void 0,t(`sync complete`),{ready:!0,rebuilt:!0}):v(`sync completed but did not resolve drift (${i({fresh:!1,reasons:o.reasons})})`)},b=async()=>{if(h)return{ready:!1,rebuilt:!1,error:`sync guard is closed`};if(d)return d;let e=l(n,s);return e.fresh?{ready:!0,rebuilt:!1}:(d=y(e).finally(()=>{d=void 0}),d)};return{async ensureSynced(){let e=await b();if(!e.ready)throw Error(`DoomPi cannot launch this session because ${e.error??`sync failed`}.`)},watch(e){if(p)return;let t=()=>{if(h)return;let e=Math.min(u*2**g,6e4);p=setTimeout(r,e),p.unref?.()},r=()=>{if(h||d){t();return}if(l(n,s).fresh){t();return}b().then(n=>{!h&&n.rebuilt&&e(),t()})};t()},close(){h=!0,p&&clearTimeout(p),p=void 0}}}export{h as createSyncGuard};
2
2
  //# sourceMappingURL=syncGuard.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"syncGuard.mjs","names":[],"sources":["../../../src/adapters/syncGuard.ts"],"sourcesContent":["import { spawn } from 'node:child_process';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport { describeSyncDrift, readSyncDrift } from '@agimon-ai/doompi/services';\nimport { findRepositoryRoot } from '@agimon-ai/doompi/utils';\nimport { repositoryDoomPiCli } from './bundledServer.ts';\n\nconst DOOMPI_PACKAGE = '@agimon-ai/doompi';\nconst AGENT_COMMAND_ENV = 'DOOMPI_AGENT_COMMAND';\nconst SYNC_COMMAND_ENV = 'DOOMPI_SYNC_COMMAND';\nconst BOOTSTRAP_ENTRY_ENV = 'DOOMPI_BOOTSTRAP_ENTRY';\nconst HARNESS_ROOT_ENV = 'DOOMPI_ROOT';\nconst CLI_SEGMENTS = ['dist', 'bin', 'cli.mjs'];\nconst SYNC_ARGS = ['sync'];\n/** How often the watcher re-reads the drift inputs. */\nconst WATCH_INTERVAL_MS = 2_000;\n/** Ceiling for the retry delay after a sync that keeps failing. */\nconst MAX_RETRY_INTERVAL_MS = 60_000;\n\n/** What one sync attempt did, so a failure is never reported as a rebuild. */\nexport interface SyncRunOutcome {\n ok: boolean;\n detail?: string;\n}\n\nexport interface SyncGuardOptions {\n /** Known repository root, or a launch directory to discover one from. */\n repoRoot?: string;\n cwd?: string;\n onNotice?: (message: string) => void;\n /** Test seam for running the sync itself; returning nothing reads as success. */\n runSync?: (repoRoot: string) => Promise<SyncRunOutcome | void>;\n /** Test seam for the per-repository drift read and launcher-owned Doom entry. */\n readDrift?: (repoRoot: string, expectedBootstrapEntry?: string) => { fresh: boolean; reasons: readonly string[] };\n /** Test seam over repository discovery. */\n findRoot?: (cwd: string) => string;\n intervalMs?: number;\n}\nexport interface SyncGuard {\n /**\n * Syncs the repository when anything a session reads has drifted.\n *\n * Serialized: several sessions starting at once wait on one sync rather\n * than racing to rebuild the same artifacts over each other.\n */\n ensureSynced(): Promise<void>;\n /** Re-syncs on drift and reports when artifacts changed under a running cockpit. */\n watch(onSynced: () => void): void;\n close(): void;\n}\n\nfunction inactiveSyncGuard(): SyncGuard {\n return {\n ensureSynced: async () => {},\n watch: () => {},\n close: () => {},\n };\n}\n\n/**\n * The DoomPi CLI this repository should sync with.\n *\n * A repository that pins its own DoomPi must be synced by that one: extensions\n * are version-coupled to the harness that resolves them, and the copy sitting\n * in the hub's dependency tree may not be the copy the repository runs.\n */\nfunction syncCliFor(repoRoot: string): string {\n return (\n process.env[SYNC_COMMAND_ENV] ??\n repositoryDoomPiCli(repoRoot) ??\n process.env[AGENT_COMMAND_ENV] ??\n path.join(path.dirname(createRequire(import.meta.url).resolve(`${DOOMPI_PACKAGE}/package.json`)), ...CLI_SEGMENTS)\n );\n}\n\n/** Runs the launcher's own sync, in its own process so the hub keeps serving. */\nfunction spawnSync(repoRoot: string): Promise<SyncRunOutcome> {\n const cli = syncCliFor(repoRoot);\n return new Promise((resolve) => {\n const child = spawn(process.execPath, [cli, ...SYNC_ARGS], {\n cwd: repoRoot,\n env: { ...process.env, [HARNESS_ROOT_ENV]: repoRoot },\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n const tail: string[] = [];\n const keep = (chunk: Buffer): void => {\n tail.push(chunk.toString());\n if (tail.length > 20) tail.shift();\n };\n child.stdout?.on('data', keep);\n child.stderr?.on('data', keep);\n // A failed sync is reported, not thrown: the session the caller wanted still\n // starts, and it starts against whatever the last good sync left. What it\n // must not do is claim the artifacts were rebuilt.\n child.once('error', (error) => resolve({ ok: false, detail: `it could not start: ${error.message}` }));\n child.once('exit', (code) => {\n if (code === 0) resolve({ ok: true });\n else resolve({ ok: false, detail: `exit ${String(code)}: ${tail.join('').trim().slice(-400)}` });\n });\n });\n}\n\n/**\n * Keeps the repository synced under a running cockpit.\n *\n * A session launched from the browser reads what sync produced: the resolved\n * composition, the plugin bundle, and the package API routes. Nothing forces\n * a person clicking \"new session\" to have run sync first, and a stale one\n * fails quietly rather than loudly, so the hub checks and syncs itself.\n */\nexport function createSyncGuard(options: SyncGuardOptions): SyncGuard {\n const notice = options.onNotice ?? ((): void => {});\n let repoRoot = options.repoRoot;\n if (repoRoot === undefined) {\n try {\n repoRoot = (options.findRoot ?? findRepositoryRoot)(options.cwd ?? process.cwd());\n } catch {\n return inactiveSyncGuard();\n }\n }\n const runSync = options.runSync ?? ((root: string) => spawnSync(root));\n const expectedBootstrapEntry = process.env[BOOTSTRAP_ENTRY_ENV];\n const readDrift =\n options.readDrift ??\n ((root: string, entry?: string) => readSyncDrift({ repoRoot: root, expectedBootstrapEntry: entry }));\n const baseInterval = options.intervalMs ?? WATCH_INTERVAL_MS;\n let inFlight: Promise<{ ready: boolean; rebuilt: boolean; error?: string }> | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let closed = false;\n let consecutiveFailures = 0;\n let lastFailureNotice: string | undefined;\n\n /**\n * One sync attempt, reporting whether it actually rebuilt anything.\n *\n * A sync that exits non-zero published nothing, so saying \"complete\" and\n * telling every attached page to reload is two lies and a reload storm: the\n * repository is still drifted, so the next poll tries again immediately.\n */\n const failedResult = (failure: string): { ready: false; rebuilt: false; error: string } => {\n consecutiveFailures += 1;\n // The same failure every few seconds buries everything else in the log.\n if (failure !== lastFailureNotice) {\n notice(failure);\n lastFailureNotice = failure;\n }\n return { ready: false, rebuilt: false, error: failure };\n };\n\n const syncOnce = async (drift: {\n reasons: readonly string[];\n }): Promise<{ ready: boolean; rebuilt: boolean; error?: string }> => {\n notice(`syncing: ${describeSyncDrift({ fresh: false, reasons: drift.reasons as never })}`);\n let outcome: SyncRunOutcome;\n try {\n outcome = (await runSync(repoRoot)) ?? { ok: true };\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n return failedResult(`sync failed (${detail})`);\n }\n if (!outcome.ok) return failedResult(`sync failed (${outcome.detail ?? 'no detail'})`);\n\n const remaining = readDrift(repoRoot, expectedBootstrapEntry);\n if (!remaining.fresh) {\n return failedResult(\n `sync completed but did not resolve drift (${describeSyncDrift({ fresh: false, reasons: remaining.reasons as never })})`,\n );\n }\n consecutiveFailures = 0;\n lastFailureNotice = undefined;\n notice('sync complete');\n return { ready: true, rebuilt: true };\n };\n\n const ensureSynced = async (): Promise<{ ready: boolean; rebuilt: boolean; error?: string }> => {\n if (closed) return { ready: false, rebuilt: false, error: 'sync guard is closed' };\n // Joining the run already in flight is what makes concurrent launches\n // wait for one sync instead of starting several.\n if (inFlight) return inFlight;\n const drift = readDrift(repoRoot, expectedBootstrapEntry);\n if (drift.fresh) return { ready: true, rebuilt: false };\n inFlight = syncOnce(drift).finally(() => {\n inFlight = undefined;\n });\n return inFlight;\n };\n\n return {\n async ensureSynced() {\n const result = await ensureSynced();\n if (!result.ready) throw new Error(`DoomPi cannot launch this session because ${result.error ?? 'sync failed'}.`);\n },\n watch(onSynced) {\n if (timer) return;\n const schedule = (): void => {\n if (closed) return;\n // Backing off after a failure: a repository that cannot sync will not\n // start syncing because it was asked again two seconds later, and the\n // retries drown the reason in the log.\n const delay = Math.min(baseInterval * 2 ** consecutiveFailures, MAX_RETRY_INTERVAL_MS);\n timer = setTimeout(tick, delay);\n // The hub should not be held open by its own watcher.\n timer.unref?.();\n };\n const tick = (): void => {\n if (closed || inFlight) {\n schedule();\n return;\n }\n const drift = readDrift(repoRoot, expectedBootstrapEntry);\n if (drift.fresh) {\n schedule();\n return;\n }\n void ensureSynced().then((result) => {\n if (!closed && result.rebuilt) onSynced();\n schedule();\n });\n };\n schedule();\n },\n close() {\n closed = true;\n if (timer) clearTimeout(timer);\n timer = undefined;\n },\n };\n}\n"],"mappings":"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"}
1
+ {"version":3,"file":"syncGuard.mjs","names":[],"sources":["../../../src/adapters/syncGuard.ts"],"sourcesContent":["import { spawn } from 'node:child_process';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport { describeSyncDrift, readSyncDrift, readSyncRegistration } from '@agimon-ai/doompi/services';\nimport { findRepositoryRoot } from '@agimon-ai/doompi/utils';\nimport { repositoryDoomPiCli } from './bundledServer.ts';\nimport { webHostPackageRoot } from './webPluginGenerate.ts';\n\nconst DOOMPI_PACKAGE = '@agimon-ai/doompi';\nconst AGENT_COMMAND_ENV = 'DOOMPI_AGENT_COMMAND';\nconst SYNC_COMMAND_ENV = 'DOOMPI_SYNC_COMMAND';\nconst BOOTSTRAP_ENTRY_ENV = 'DOOMPI_BOOTSTRAP_ENTRY';\nconst HARNESS_ROOT_ENV = 'DOOMPI_ROOT';\nconst WEB_PACKAGE_ROOT_ENV = 'DOOMPI_WEB_PACKAGE_ROOT';\nconst CLI_SEGMENTS = ['dist', 'bin', 'cli.mjs'];\nconst SYNC_ARGS = ['sync'];\n/** How often the watcher re-reads the drift inputs. */\nconst WATCH_INTERVAL_MS = 2_000;\n/** Ceiling for the retry delay after a sync that keeps failing. */\nconst MAX_RETRY_INTERVAL_MS = 60_000;\n\n/** What one sync attempt did, so a failure is never reported as a rebuild. */\nexport interface SyncRunOutcome {\n ok: boolean;\n detail?: string;\n}\n\nexport interface SyncGuardOptions {\n /** Known repository root, or a launch directory to discover one from. */\n repoRoot?: string;\n cwd?: string;\n onNotice?: (message: string) => void;\n /** Test seam for running the sync itself; returning nothing reads as success. */\n runSync?: (repoRoot: string) => Promise<SyncRunOutcome | void>;\n /** Test seam for the per-repository drift read and launcher-owned Doom entry. */\n readDrift?: (repoRoot: string, expectedBootstrapEntry?: string) => { fresh: boolean; reasons: readonly string[] };\n /** Test seam over repository discovery. */\n findRoot?: (cwd: string) => string;\n intervalMs?: number;\n}\nexport interface SyncGuard {\n /**\n * Syncs the repository when anything a session reads has drifted.\n *\n * Serialized: several sessions starting at once wait on one sync rather\n * than racing to rebuild the same artifacts over each other.\n */\n ensureSynced(): Promise<void>;\n /** Re-syncs on drift and reports when artifacts changed under a running cockpit. */\n watch(onSynced: () => void): void;\n close(): void;\n}\n\nfunction inactiveSyncGuard(): SyncGuard {\n return {\n ensureSynced: async () => {},\n watch: () => {},\n close: () => {},\n };\n}\n\n/**\n * The DoomPi CLI this repository should sync with.\n *\n * A repository that pins its own DoomPi must be synced by that one: extensions\n * are version-coupled to the harness that resolves them, and the copy sitting\n * in the hub's dependency tree may not be the copy the repository runs.\n */\nfunction syncCliFor(repoRoot: string): string {\n return (\n process.env[SYNC_COMMAND_ENV] ??\n repositoryDoomPiCli(repoRoot) ??\n process.env[AGENT_COMMAND_ENV] ??\n path.join(path.dirname(createRequire(import.meta.url).resolve(`${DOOMPI_PACKAGE}/package.json`)), ...CLI_SEGMENTS)\n );\n}\n\n/** Runs the launcher's own sync, in its own process so the hub keeps serving. */\nfunction spawnSync(repoRoot: string): Promise<SyncRunOutcome> {\n const cli = syncCliFor(repoRoot);\n return new Promise((resolve) => {\n const child = spawn(process.execPath, [cli, ...SYNC_ARGS], {\n cwd: repoRoot,\n env: {\n ...process.env,\n [HARNESS_ROOT_ENV]: repoRoot,\n [WEB_PACKAGE_ROOT_ENV]: process.env[WEB_PACKAGE_ROOT_ENV] || webHostPackageRoot(),\n },\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n const tail: string[] = [];\n const keep = (chunk: Buffer): void => {\n tail.push(chunk.toString());\n if (tail.length > 20) tail.shift();\n };\n child.stdout?.on('data', keep);\n child.stderr?.on('data', keep);\n // A failed sync is reported, not thrown: the session the caller wanted still\n // starts, and it starts against whatever the last good sync left. What it\n // must not do is claim the artifacts were rebuilt.\n child.once('error', (error) => resolve({ ok: false, detail: `it could not start: ${error.message}` }));\n child.once('exit', (code) => {\n if (code === 0) resolve({ ok: true });\n else resolve({ ok: false, detail: `exit ${String(code)}: ${tail.join('').trim().slice(-400)}` });\n });\n });\n}\n\n/**\n * Keeps the repository synced under a running cockpit.\n *\n * A session launched from the browser reads what sync produced: the resolved\n * composition, the plugin bundle, and the package API routes. Nothing forces\n * a person clicking \"new session\" to have run sync first, and a stale one\n * fails quietly rather than loudly, so the hub checks and syncs itself.\n */\nexport function createSyncGuard(options: SyncGuardOptions): SyncGuard {\n const notice = options.onNotice ?? ((): void => {});\n let repoRoot = options.repoRoot;\n if (repoRoot === undefined) {\n try {\n repoRoot = (options.findRoot ?? findRepositoryRoot)(options.cwd ?? process.cwd());\n } catch {\n return inactiveSyncGuard();\n }\n }\n const runSync = options.runSync ?? ((root: string) => spawnSync(root));\n const expectedBootstrapEntry = process.env[BOOTSTRAP_ENTRY_ENV];\n const readDrift =\n options.readDrift ??\n ((root: string, entry?: string) => {\n const drift = readSyncDrift({ repoRoot: root, expectedBootstrapEntry: entry });\n // A CLI-only sync is valid for the terminal, but cannot supply session UI.\n if (drift.fresh && readSyncRegistration(root)?.webDirectory == null) {\n return { fresh: false, reasons: ['cockpit-bundle-missing'] };\n }\n return drift;\n });\n const baseInterval = options.intervalMs ?? WATCH_INTERVAL_MS;\n let inFlight: Promise<{ ready: boolean; rebuilt: boolean; error?: string }> | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let closed = false;\n let consecutiveFailures = 0;\n let lastFailureNotice: string | undefined;\n\n /**\n * One sync attempt, reporting whether it actually rebuilt anything.\n *\n * A sync that exits non-zero published nothing, so saying \"complete\" and\n * telling every attached page to reload is two lies and a reload storm: the\n * repository is still drifted, so the next poll tries again immediately.\n */\n const failedResult = (failure: string): { ready: false; rebuilt: false; error: string } => {\n consecutiveFailures += 1;\n // The same failure every few seconds buries everything else in the log.\n if (failure !== lastFailureNotice) {\n notice(failure);\n lastFailureNotice = failure;\n }\n return { ready: false, rebuilt: false, error: failure };\n };\n\n const syncOnce = async (drift: {\n reasons: readonly string[];\n }): Promise<{ ready: boolean; rebuilt: boolean; error?: string }> => {\n notice(`syncing: ${describeSyncDrift({ fresh: false, reasons: drift.reasons as never })}`);\n let outcome: SyncRunOutcome;\n try {\n outcome = (await runSync(repoRoot)) ?? { ok: true };\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n return failedResult(`sync failed (${detail})`);\n }\n if (!outcome.ok) return failedResult(`sync failed (${outcome.detail ?? 'no detail'})`);\n\n const remaining = readDrift(repoRoot, expectedBootstrapEntry);\n if (!remaining.fresh) {\n return failedResult(\n `sync completed but did not resolve drift (${describeSyncDrift({ fresh: false, reasons: remaining.reasons as never })})`,\n );\n }\n consecutiveFailures = 0;\n lastFailureNotice = undefined;\n notice('sync complete');\n return { ready: true, rebuilt: true };\n };\n\n const ensureSynced = async (): Promise<{ ready: boolean; rebuilt: boolean; error?: string }> => {\n if (closed) return { ready: false, rebuilt: false, error: 'sync guard is closed' };\n // Joining the run already in flight is what makes concurrent launches\n // wait for one sync instead of starting several.\n if (inFlight) return inFlight;\n const drift = readDrift(repoRoot, expectedBootstrapEntry);\n if (drift.fresh) return { ready: true, rebuilt: false };\n inFlight = syncOnce(drift).finally(() => {\n inFlight = undefined;\n });\n return inFlight;\n };\n\n return {\n async ensureSynced() {\n const result = await ensureSynced();\n if (!result.ready) throw new Error(`DoomPi cannot launch this session because ${result.error ?? 'sync failed'}.`);\n },\n watch(onSynced) {\n if (timer) return;\n const schedule = (): void => {\n if (closed) return;\n // Backing off after a failure: a repository that cannot sync will not\n // start syncing because it was asked again two seconds later, and the\n // retries drown the reason in the log.\n const delay = Math.min(baseInterval * 2 ** consecutiveFailures, MAX_RETRY_INTERVAL_MS);\n timer = setTimeout(tick, delay);\n // The hub should not be held open by its own watcher.\n timer.unref?.();\n };\n const tick = (): void => {\n if (closed || inFlight) {\n schedule();\n return;\n }\n const drift = readDrift(repoRoot, expectedBootstrapEntry);\n if (drift.fresh) {\n schedule();\n return;\n }\n void ensureSynced().then((result) => {\n if (!closed && result.rebuilt) onSynced();\n schedule();\n });\n };\n schedule();\n },\n close() {\n closed = true;\n if (timer) clearTimeout(timer);\n timer = undefined;\n },\n };\n}\n"],"mappings":"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"}
@@ -1,3 +1,3 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as f,M as p,O as m,P as h,R as ee,S as te,T as ne,U as re,V as ie,W as ae,X as oe,Y as se,_ as ce,a as le,c as ue,d as de,f as fe,g as pe,h as me,n as he,o as ge,p as _e,q as ve,r as g,s as ye,t as _,u as be,v as xe,w as v,x as Se,y,z as Ce}from"./index-CN4JqlUs.js";import{l as we,o as b}from"./dist-CYkOb3JV.js";import{HighlightStyle as Te,IndentContext as Ee,bracketMatching as De,foldGutter as Oe,foldKeymap as ke,getIndentUnit as Ae,getIndentation as je,indentOnInput as Me,indentString as Ne,indentUnit as Pe,matchBrackets as x,syntaxHighlighting as Fe,syntaxTree as Ie}from"./dist-0Xx-ctg3.js";function S(e,t){let n=[...t].sort((e,t)=>e.from-t.from||e.to-t.to),r=0;for(let[t,i]of n.entries()){if(!Number.isInteger(i.from)||!Number.isInteger(i.to))throw RangeError(`Editor ranges must use integer offsets`);if(i.from<0||i.to<i.from||i.to>e)throw RangeError(`Editor range ${t} is outside the document`);if(t>0&&i.from<r)throw RangeError(`Editor ranges must not overlap`);r=Math.max(r,i.to)}return n}function Le(e,t){return S(e,t)}var C=e(oe(),1),Re=e(u(),1),ze=e=>{let{state:t}=e,n=t.doc.lineAt(t.selection.main.from),r=We(e.state,n.from);return r.line?Ve(e):r.block?Ue(e):!1};function Be(e,t){return({state:n,dispatch:r})=>{if(n.readOnly)return!1;let i=e(t,n);return i?(r(n.update(i)),!0):!1}}var Ve=Be(Je,0),He=Be(qe,0),Ue=Be((e,t)=>qe(e,t,Ke(t)),0);function We(e,t){let n=e.languageDataAt(`commentTokens`,t,1);return n.length?n[0]:{}}var w=50;function Ge(e,{open:t,close:n},r,i){let a=e.sliceDoc(r-w,r),o=e.sliceDoc(i,i+w),s=/\s*$/.exec(a)[0].length,c=/^\s*/.exec(o)[0].length,l=a.length-s;if(a.slice(l-t.length,l)==t&&o.slice(c,c+n.length)==n)return{open:{pos:r-s,margin:s&&1},close:{pos:i+c,margin:c&&1}};let u,d;i-r<=100?u=d=e.sliceDoc(r,i):(u=e.sliceDoc(r,r+w),d=e.sliceDoc(i-w,i));let f=/^\s*/.exec(u)[0].length,p=/\s*$/.exec(d)[0].length,m=d.length-p-n.length;return u.slice(f,f+t.length)==t&&d.slice(m,m+n.length)==n?{open:{pos:r+f+t.length,margin:+!!/\s/.test(u.charAt(f+t.length))},close:{pos:i-p-n.length,margin:+!!/\s/.test(d.charAt(m-1))}}:null}function Ke(e){let t=[];for(let n of e.selection.ranges){let r=e.doc.lineAt(n.from),i=n.to<=r.to?r:e.doc.lineAt(n.to);i.from>r.from&&i.from==n.to&&(i=n.to==r.to+1?r:e.doc.lineAt(n.to-1));let a=t.length-1;a>=0&&t[a].to>r.from?t[a].to=i.to:t.push({from:r.from+/^\s*/.exec(r.text)[0].length,to:i.to})}return t}function qe(e,t,n=t.selection.ranges){let r=n.map(e=>We(t,e.from).block);if(!r.every(e=>e))return null;let i=n.map((e,n)=>Ge(t,r[n],e.from,e.to));if(e!=2&&!i.every(e=>e))return{changes:t.changes(n.map((e,t)=>i[t]?[]:[{from:e.from,insert:r[t].open+` `},{from:e.to,insert:` `+r[t].close}]))};if(e!=1&&i.some(e=>e)){let e=[];for(let t=0,n;t<i.length;t++)if(n=i[t]){let i=r[t],{open:a,close:o}=n;e.push({from:a.pos-i.open.length,to:a.pos+a.margin},{from:o.pos-o.margin,to:o.pos+i.close.length})}return{changes:e}}return null}function Je(e,t,n=t.selection.ranges){let r=[],i=-1;ranges:for(let{from:e,to:a}of n){let n=r.length,o=1e9,s;for(let n=e;n<=a;){let c=t.doc.lineAt(n);if(s==null&&(s=We(t,c.from).line,!s))continue ranges;if(c.from>i&&(e==a||a>c.from)){i=c.from;let e=/^\s*/.exec(c.text)[0].length,t=e==c.length,n=c.text.slice(e,e+s.length)==s?e:-1;e<c.text.length&&e<o&&(o=e),r.push({line:c,comment:n,token:s,indent:e,empty:t,single:!1})}n=c.to+1}if(o<1e9)for(let e=n;e<r.length;e++)r[e].indent<r[e].line.text.length&&(r[e].indent=o);r.length==n+1&&(r[n].single=!0)}if(e!=2&&r.some(e=>e.comment<0&&(!e.empty||e.single))){let e=[];for(let{line:t,token:n,indent:i,empty:a,single:o}of r)(o||!a)&&e.push({from:t.from+i,insert:n+` `});let n=t.changes(e);return{changes:n,selection:t.selection.map(n,1)}}if(e!=1&&r.some(e=>e.comment>=0)){let e=[];for(let{line:t,comment:n,token:i}of r)if(n>=0){let r=t.from+n,a=r+i.length;t.text[a-t.from]==` `&&a++,e.push({from:r,to:a})}return{changes:e}}return null}var Ye=Se.define(),Xe=Se.define(),Ze=m.define(),Qe=m.define({combine(e){return n(e,{minDepth:100,newGroupDelay:500,joinToEvent:(e,t)=>t},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,t)=>(n,r)=>e(n,r)||t(n,r)})}}),$e=o.define({create(){return k.empty},update(e,t){let n=t.state.facet(Qe),r=t.annotation(Ye);if(r){let i=E.fromTransaction(t,r.selection),a=r.side,o=a==0?e.undone:e.done;return o=i?D(o,o.length,n.minDepth,i):lt(o,t.startState.selection),new k(a==0?r.rest:o,a==0?o:r.rest)}let i=t.annotation(Xe);if((i==`full`||i==`before`)&&(e=e.isolate()),t.annotation(f.addToHistory)===!1)return t.changes.empty?e:e.addMapping(t.changes.desc);let a=E.fromTransaction(t),o=t.annotation(f.time),s=t.annotation(f.userEvent);return a?e=e.addChanges(a,o,s,n,t):t.selection&&(e=e.addSelection(t.startState.selection,o,s,n.newGroupDelay)),(i==`full`||i==`after`)&&(e=e.isolate()),e},toJSON(e){return{done:e.done.map(e=>e.toJSON()),undone:e.undone.map(e=>e.toJSON())}},fromJSON(e){return new k(e.done.map(E.fromJSON),e.undone.map(E.fromJSON))}});function et(e={}){return[$e,Qe.of(e),g.domEventHandlers({beforeinput(e,t){let n=e.inputType==`historyUndo`?tt:e.inputType==`historyRedo`?nt:null;return n?(e.preventDefault(),n(t)):!1}})]}function T(e,t){return function({state:n,dispatch:r}){if(!t&&n.readOnly)return!1;let i=n.field($e,!1);if(!i)return!1;let a=i.pop(e,n,t);return a?(r(a),!0):!1}}var tt=T(0,!1),nt=T(1,!1),rt=T(0,!0),it=T(1,!0),E=class e{constructor(e,t,n,r,i){this.changes=e,this.effects=t,this.mapped=n,this.startSelection=r,this.selectionsAfter=i}setSelAfter(t){return new e(this.changes,this.effects,this.mapped,this.startSelection,t)}toJSON(){return{changes:this.changes?.toJSON(),mapped:this.mapped?.toJSON(),startSelection:this.startSelection?.toJSON(),selectionsAfter:this.selectionsAfter.map(e=>e.toJSON())}}static fromJSON(t){return new e(t.changes&&r.fromJSON(t.changes),[],t.mapped&&te.fromJSON(t.mapped),t.startSelection&&a.fromJSON(t.startSelection),t.selectionsAfter.map(a.fromJSON))}static fromTransaction(t,n){let r=O;for(let e of t.startState.facet(Ze)){let n=e(t);n.length&&(r=r.concat(n))}return!r.length&&t.changes.empty?null:new e(t.changes.invert(t.startState.doc),r,void 0,n||t.startState.selection,O)}static selection(t){return new e(void 0,O,void 0,void 0,t)}};function D(e,t,n,r){let i=t+1>n+20?t-n-1:0,a=e.slice(i,t);return a.push(r),a}function at(e,t){let n=[],r=!1;return e.iterChangedRanges((e,t)=>n.push(e,t)),t.iterChangedRanges((e,t,i,a)=>{for(let e=0;e<n.length;){let t=n[e++],o=n[e++];a>=t&&i<=o&&(r=!0)}}),r}function ot(e,t){return e.ranges.length==t.ranges.length&&e.ranges.filter((e,n)=>e.empty!=t.ranges[n].empty).length===0}function st(e,t){return e.length?t.length?e.concat(t):e:t}var O=[],ct=200;function lt(e,t){if(e.length){let n=e[e.length-1],r=n.selectionsAfter.slice(Math.max(0,n.selectionsAfter.length-ct));return r.length&&r[r.length-1].eq(t)?e:(r.push(t),D(e,e.length-1,1e9,n.setSelAfter(r)))}return[E.selection([t])]}function ut(e){let t=e[e.length-1],n=e.slice();return n[e.length-1]=t.setSelAfter(t.selectionsAfter.slice(0,t.selectionsAfter.length-1)),n}function dt(e,t){if(!e.length)return e;let n=e.length,r=O;for(;n;){let i=ft(e[n-1],t,r);if(i.changes&&!i.changes.empty||i.effects.length){let t=e.slice(0,n);return t[n-1]=i,t}t=i.mapped,n--,r=i.selectionsAfter}return r.length?[E.selection(r)]:O}function ft(e,t,n){let r=st(e.selectionsAfter.length?e.selectionsAfter.map(e=>e.map(t)):O,n);if(!e.changes)return E.selection(r);let i=e.changes.map(t),a=t.mapDesc(e.changes,!0),o=e.mapped?e.mapped.composeDesc(a):a;return new E(i,h.mapEffects(e.effects,t),o,e.startSelection.map(a),r)}var pt=/^(input\.type|delete)($|\.)/,k=class e{constructor(e,t,n=0,r=void 0){this.done=e,this.undone=t,this.prevTime=n,this.prevUserEvent=r}isolate(){return this.prevTime?new e(this.done,this.undone):this}addChanges(t,n,r,i,a){let o=this.done,s=o[o.length-1];return o=s&&s.changes&&!s.changes.empty&&t.changes&&(!r||pt.test(r))&&(!s.selectionsAfter.length&&n-this.prevTime<i.newGroupDelay&&i.joinToEvent(a,at(s.changes,t.changes))||r==`input.type.compose`)?D(o,o.length-1,i.minDepth,new E(t.changes.compose(s.changes),st(h.mapEffects(t.effects,s.changes),s.effects),s.mapped,s.startSelection,O)):D(o,o.length,i.minDepth,t),new e(o,O,n,r)}addSelection(t,n,r,i){let a=this.done.length?this.done[this.done.length-1].selectionsAfter:O;return a.length>0&&n-this.prevTime<i&&r==this.prevUserEvent&&r&&/^select($|\.)/.test(r)&&ot(a[a.length-1],t)?this:new e(lt(this.done,t),this.undone,n,r)}addMapping(t){return new e(dt(this.done,t),dt(this.undone,t),this.prevTime,this.prevUserEvent)}pop(e,t,n){let r=e==0?this.done:this.undone;if(r.length==0)return null;let i=r[r.length-1],a=i.selectionsAfter[0]||(i.startSelection?i.startSelection.map(i.changes.invertedDesc,1):t.selection);if(n&&i.selectionsAfter.length)return t.update({selection:i.selectionsAfter[i.selectionsAfter.length-1],annotations:Ye.of({side:e,rest:ut(r),selection:a}),userEvent:e==0?`select.undo`:`select.redo`,scrollIntoView:!0});if(i.changes){let n=r.length==1?O:r.slice(0,r.length-1);return i.mapped&&(n=dt(n,i.mapped)),t.update({changes:i.changes,selection:i.startSelection,effects:i.effects,annotations:Ye.of({side:e,rest:n,selection:a}),filter:!1,userEvent:e==0?`undo`:`redo`,scrollIntoView:!0})}return null}};k.empty=new k(O,O);var mt=[{key:`Mod-z`,run:tt,preventDefault:!0},{key:`Mod-y`,mac:`Mod-Shift-z`,run:nt,preventDefault:!0},{linux:`Ctrl-Shift-z`,run:nt,preventDefault:!0},{key:`Mod-u`,run:rt,preventDefault:!0},{key:`Alt-u`,mac:`Mod-Shift-u`,run:it,preventDefault:!0}];function A(e,t){return a.create(e.ranges.map(t),e.mainIndex)}function j(e,t){return e.update({selection:t,scrollIntoView:!0,userEvent:`select`})}function M({state:e,dispatch:t},n){let r=A(e.selection,n);return!r.eq(e.selection,!0)&&(t(j(e,r)),!0)}function N(e,t){return a.cursor(t?e.to:e.from)}function ht(e,t){return M(e,n=>n.empty?e.moveByChar(n,t):N(n,t))}function P(e){return e.textDirectionAt(e.state.selection.main.head)==he.LTR}var gt=e=>ht(e,!P(e)),_t=e=>ht(e,P(e));function vt(e,t){return M(e,n=>n.empty?e.moveByGroup(n,t):N(n,t))}var yt=e=>vt(e,!P(e)),bt=e=>vt(e,P(e));typeof Intl<`u`&&Intl.Segmenter;function xt(e,t,n){if(t.type.prop(n))return!0;let r=t.to-t.from;return r&&(r>2||/[^\s,.;:]/.test(e.sliceDoc(t.from,t.to)))||t.firstChild}function F(e,t,n){let r=Ie(e).resolveInner(t.head),i=n?we.closedBy:we.openedBy;for(let a=t.head;;){let t=n?r.childAfter(a):r.childBefore(a);if(!t)break;xt(e,t,i)?r=t:a=n?t.to:t.from}let o=r.type.prop(i),s,c;return c=o&&(s=n?x(e,r.from,1):x(e,r.to,-1))&&s.matched?n?s.end.to:s.end.from:n?r.to:r.from,a.cursor(c,n?-1:1)}var St=e=>M(e,t=>F(e.state,t,!P(e))),Ct=e=>M(e,t=>F(e.state,t,P(e)));function wt(e,t){return M(e,n=>{if(!n.empty)return N(n,t);let r=e.moveVertically(n,t);return r.head==n.head?e.moveToLineBoundary(n,t):r})}var Tt=e=>wt(e,!1),Et=e=>wt(e,!0);function Dt(e){let t=e.scrollDOM.clientHeight<e.scrollDOM.scrollHeight-2,n=0,r=0,i;if(t){for(let t of e.state.facet(g.scrollMargins)){let i=t(e);i?.top&&(n=Math.max(i?.top,n)),i?.bottom&&(r=Math.max(i?.bottom,r))}i=e.scrollDOM.clientHeight-n-r}else i=(e.dom.ownerDocument.defaultView||window).innerHeight;return{marginTop:n,marginBottom:r,selfScroll:t,height:Math.max(e.defaultLineHeight,i-5)}}function Ot(e,t){let n=Dt(e),{state:r}=e,i=A(r.selection,r=>r.empty?e.moveVertically(r,t,n.height):N(r,t));if(i.eq(r.selection))return!1;let a;if(n.selfScroll){let t=e.coordsAtPos(r.selection.main.head),o=e.scrollDOM.getBoundingClientRect(),s=o.top+n.marginTop,c=o.bottom-n.marginBottom;t&&t.top>s&&t.bottom<c&&(a=g.scrollIntoView(i.main.head,{y:`start`,yMargin:t.top-s}))}return e.dispatch(j(r,i),{effects:a}),!0}var kt=e=>Ot(e,!1),At=e=>Ot(e,!0);function I(e,t,n){let r=e.lineBlockAt(t.head),i=e.moveToLineBoundary(t,n);if(i.head==t.head&&i.head!=(n?r.to:r.from)&&(i=e.moveToLineBoundary(t,n,!1)),!n&&i.head==r.from&&r.length){let n=/^\s*/.exec(e.state.sliceDoc(r.from,Math.min(r.from+100,r.to)))[0].length;n&&t.head!=r.from+n&&(i=a.cursor(r.from+n))}return i}var jt=e=>M(e,t=>I(e,t,!0)),Mt=e=>M(e,t=>I(e,t,!1)),Nt=e=>M(e,t=>I(e,t,!P(e))),Pt=e=>M(e,t=>I(e,t,P(e))),Ft=e=>M(e,t=>a.cursor(e.lineBlockAt(t.head).from,1)),It=e=>M(e,t=>a.cursor(e.lineBlockAt(t.head).to,-1));function Lt(e,t,n){let r=!1,i=A(e.selection,t=>{let i=x(e,t.head,-1)||x(e,t.head,1)||t.head>0&&x(e,t.head-1,1)||t.head<e.doc.length&&x(e,t.head+1,-1);if(!i||!i.end)return t;r=!0;let o=i.start.from==t.head?i.end.to:i.end.from;return n?a.range(t.anchor,o):a.cursor(o)});return r?(t(j(e,i)),!0):!1}var Rt=({state:e,dispatch:t})=>Lt(e,t,!1);function L(e,t,n){let r=A(e.state.selection,e=>{e.undirectional&&e.head>=e.anchor!=t&&(e=a.range(e.head,e.anchor));let r=n(e);return a.range(e.anchor,r.head,r.goalColumn,r.bidiLevel||void 0,r.assoc)});return!r.eq(e.state.selection)&&(e.dispatch(j(e.state,r)),!0)}function zt(e,t){return L(e,t,n=>e.moveByChar(n,t))}var Bt=e=>zt(e,!P(e)),Vt=e=>zt(e,P(e));function Ht(e,t){return L(e,t,n=>e.moveByGroup(n,t))}var Ut=e=>Ht(e,!P(e)),Wt=e=>Ht(e,P(e)),Gt=e=>{let t=!P(e);return L(e,t,n=>F(e.state,n,t))},Kt=e=>{let t=P(e);return L(e,t,n=>F(e.state,n,t))};function qt(e,t){return L(e,t,n=>e.moveVertically(n,t))}var Jt=e=>qt(e,!1),Yt=e=>qt(e,!0);function Xt(e,t){return L(e,t,n=>e.moveVertically(n,t,Dt(e).height))}var Zt=e=>Xt(e,!1),Qt=e=>Xt(e,!0),$t=e=>L(e,!0,t=>I(e,t,!0)),en=e=>L(e,!1,t=>I(e,t,!1)),tn=e=>{let t=!P(e);return L(e,t,n=>I(e,n,t))},nn=e=>{let t=P(e);return L(e,t,n=>I(e,n,t))},rn=e=>L(e,!1,t=>a.cursor(e.lineBlockAt(t.head).from)),an=e=>L(e,!0,t=>a.cursor(e.lineBlockAt(t.head).to)),on=({state:e,dispatch:t})=>(t(j(e,{anchor:0})),!0),sn=({state:e,dispatch:t})=>(t(j(e,{anchor:e.doc.length})),!0),cn=({state:e,dispatch:t})=>(t(j(e,{anchor:e.selection.main.anchor,head:0})),!0),ln=({state:e,dispatch:t})=>(t(j(e,{anchor:e.selection.main.anchor,head:e.doc.length})),!0),un=({state:e,dispatch:t})=>(t(e.update({selection:{anchor:0,head:e.doc.length},userEvent:`select`})),!0),dn=({state:e,dispatch:t})=>{let n=B(e).map(({from:t,to:n})=>a.undirectionalRange(t,Math.min(n+1,e.doc.length)));return t(e.update({selection:a.create(n),userEvent:`select`})),!0},fn=({state:e,dispatch:t})=>{let n=A(e.selection,t=>{let n=Ie(e),r=n.resolveStack(t.from,1);if(t.empty){let e=n.resolveStack(t.from,-1);e.node.from>=r.node.from&&e.node.to<=r.node.to&&(r=e)}for(let e=r;e;e=e.next){let{node:n}=e;if((n.from<t.from&&n.to>=t.to||n.to>t.to&&n.from<=t.from)&&e.next)return a.undirectionalRange(n.from,n.to)}return t});return!n.eq(e.selection)&&(t(j(e,n)),!0)};function pn(e,t){let{state:n}=e,r=n.selection,i=n.selection.ranges.slice();for(let r of n.selection.ranges){let a=n.doc.lineAt(r.head);if(t?a.to<e.state.doc.length:a.from>0)for(let n=r;;){let r=e.moveVertically(n,t);if(r.head<a.from||r.head>a.to){i.some(e=>e.head==r.head)||i.push(r);break}if(r.head==n.head)break;n=r}}return i.length!=r.ranges.length&&(e.dispatch(j(n,a.create(i,i.length-1))),!0)}var mn=e=>pn(e,!1),hn=e=>pn(e,!0),gn=({state:e,dispatch:t})=>{let n=e.selection,r=null;return n.ranges.length>1?r=a.create([n.main]):n.main.empty||(r=a.create([a.cursor(n.main.head)])),r?(t(j(e,r)),!0):!1};function R(e,t){if(e.state.readOnly)return!1;let n=`delete.selection`,{state:r}=e,i=r.changeByRange(r=>{let{from:i,to:o}=r;if(i==o){let a=t(r);a<i?(n=`delete.backward`,a=z(e,a,!1)):a>i&&(n=`delete.forward`,a=z(e,a,!0)),i=Math.min(i,a),o=Math.max(o,a)}else i=z(e,i,!1),o=z(e,o,!0);return i==o?{range:r}:{changes:{from:i,to:o},range:a.cursor(i,i<r.head?-1:1)}});return!i.changes.empty&&(e.dispatch(r.update(i,{scrollIntoView:!0,userEvent:n,effects:n==`delete.selection`?g.announce.of(r.phrase(`Selection deleted`)):void 0})),!0)}function z(e,t,n){if(e instanceof g)for(let r of e.state.facet(g.atomicRanges).map(t=>t(e)))r.between(t,t,(e,r)=>{e<t&&r>t&&(t=n?r:e)});return t}var _n=(e,t,n)=>R(e,r=>{let i=r.from,{state:a}=e,o=a.doc.lineAt(i),s,l;if(n&&!t&&i>o.from&&i<o.from+200&&!/[^ \t]/.test(s=o.text.slice(0,i-o.from))){if(s[s.length-1]==` `)return i-1;let e=ie(s,a.tabSize)%Ae(a)||Ae(a);for(let t=0;t<e&&s[s.length-1-t]==` `;t++)i--;l=i}else l=c(o.text,i-o.from,t,t)+o.from,l==i&&o.number!=(t?a.doc.lines:1)?l+=t?1:-1:!t&&/[\ufe00-\ufe0f]/.test(o.text.slice(l-o.from,i-o.from))&&(l=c(o.text,l-o.from,!1,!1)+o.from);return l}),vn=e=>_n(e,!1,!0),yn=e=>_n(e,!0,!1),bn=(e,t)=>R(e,n=>{let r=n.head,{state:i}=e,a=i.doc.lineAt(r),o=i.charCategorizer(r);for(let e=null;;){if(r==(t?a.to:a.from)){r==n.head&&a.number!=(t?i.doc.lines:1)&&(r+=t?1:-1);break}let s=c(a.text,r-a.from,t)+a.from,l=a.text.slice(Math.min(r,s)-a.from,Math.max(r,s)-a.from),u=o(l);if(e!=null&&u!=e)break;(l!=` `||r!=n.head)&&(e=u),r=s}return r}),xn=e=>bn(e,!1),Sn=e=>bn(e,!0),Cn=e=>R(e,t=>{let n=e.lineBlockAt(t.head).to;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),wn=e=>R(e,t=>{let n=e.moveToLineBoundary(t,!1).head;return t.head>n?n:Math.max(0,t.head-1)}),Tn=e=>R(e,t=>{let n=e.moveToLineBoundary(t,!0).head;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),En=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(e=>({changes:{from:e.from,to:e.to,insert:l.of([``,``])},range:a.cursor(e.from)}));return t(e.update(n,{scrollIntoView:!0,userEvent:`input`})),!0},Dn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(t=>{if(!t.empty||t.from==0||t.from==e.doc.length)return{range:t};let n=t.from,r=e.doc.lineAt(n),i=n==r.from?n-1:c(r.text,n-r.from,!1)+r.from,o=n==r.to?n+1:c(r.text,n-r.from,!0)+r.from;return{changes:{from:i,to:o,insert:e.doc.slice(n,o).append(e.doc.slice(i,n))},range:a.cursor(o)}});return!n.changes.empty&&(t(e.update(n,{scrollIntoView:!0,userEvent:`move.character`})),!0)};function B(e){let t=[],n=-1;for(let r of e.selection.ranges){let i=e.doc.lineAt(r.from),a=e.doc.lineAt(r.to);if(!r.empty&&r.to==a.from&&(a=e.doc.lineAt(r.to-1)),n>=i.number){let e=t[t.length-1];e.to=a.to,e.ranges.push(r)}else t.push({from:i.from,to:a.to,ranges:[r]});n=a.number+1}return t}function On(e,t,n){if(e.readOnly)return!1;let r=[],i=[];for(let t of B(e)){if(n?t.to==e.doc.length:t.from==0)continue;let o=e.doc.lineAt(n?t.to+1:t.from-1),s=o.length+1;if(n){r.push({from:t.to,to:o.to},{from:t.from,insert:o.text+e.lineBreak});for(let n of t.ranges)i.push(a.range(Math.min(e.doc.length,n.anchor+s),Math.min(e.doc.length,n.head+s)))}else{r.push({from:o.from,to:t.from},{from:t.to,insert:e.lineBreak+o.text});for(let e of t.ranges)i.push(a.range(e.anchor-s,e.head-s))}}return r.length?(t(e.update({changes:r,scrollIntoView:!0,selection:a.create(i,e.selection.mainIndex),userEvent:`move.line`})),!0):!1}var kn=({state:e,dispatch:t})=>On(e,t,!1),An=({state:e,dispatch:t})=>On(e,t,!0);function jn(e,t,n){if(e.readOnly)return!1;let r=[];for(let t of B(e))n?r.push({from:t.from,insert:e.doc.slice(t.from,t.to)+e.lineBreak}):r.push({from:t.to,insert:e.lineBreak+e.doc.slice(t.from,t.to)});let i=e.changes(r);return t(e.update({changes:i,selection:e.selection.map(i,n?1:-1),scrollIntoView:!0,userEvent:`input.copyline`})),!0}var Mn=({state:e,dispatch:t})=>jn(e,t,!1),Nn=({state:e,dispatch:t})=>jn(e,t,!0),Pn=e=>{if(e.state.readOnly)return!1;let{state:t}=e,n=t.changes(B(t).map(({from:e,to:n})=>(e>0?e--:n<t.doc.length&&n++,{from:e,to:n}))),r=A(t.selection,t=>{let n;if(e.lineWrapping){let r=e.lineBlockAt(t.head),i=e.coordsAtPos(t.head,t.assoc||1);i&&(n=r.bottom+e.documentTop-i.bottom+e.defaultLineHeight/2)}return e.moveVertically(t,!0,n)}).map(n);return e.dispatch({changes:n,selection:r,scrollIntoView:!0,userEvent:`delete.line`}),!0};function Fn(e,t){if(/\(\)|\[\]|\{\}/.test(e.sliceDoc(t-1,t+1)))return{from:t,to:t};let n=Ie(e).resolveInner(t),r=n.childBefore(t),i=n.childAfter(t),a;return r&&i&&r.to<=t&&i.from>=t&&(a=r.type.prop(we.closedBy))&&a.indexOf(i.name)>-1&&e.doc.lineAt(r.to).from==e.doc.lineAt(i.from).from&&!/\S/.test(e.sliceDoc(r.to,i.from))?{from:r.to,to:i.from}:null}var In=Rn(!1),Ln=Rn(!0);function Rn(e){return({state:t,dispatch:n})=>{if(t.readOnly)return!1;let r=t.changeByRange(n=>{let{from:r,to:i}=n,o=t.doc.lineAt(r),s=!e&&r==i&&Fn(t,r);e&&(r=i=(i<=o.to?o:t.doc.lineAt(i)).to);let c=new Ee(t,{simulateBreak:r,simulateDoubleBreak:!!s}),u=je(c,r);for(u??=ie(/^\s*/.exec(t.doc.lineAt(r).text)[0],t.tabSize);i<o.to&&/\s/.test(o.text[i-o.from]);)i++;s?{from:r,to:i}=s:r>o.from&&r<o.from+100&&!/\S/.test(o.text.slice(0,r))&&(r=o.from);let d=[``,Ne(t,u)];return s&&d.push(Ne(t,c.lineIndent(o.from,-1))),{changes:{from:r,to:i,insert:l.of(d)},range:a.cursor(r+1+d[1].length)}});return n(t.update(r,{scrollIntoView:!0,userEvent:`input`})),!0}}function zn(e,t){let n=-1;return e.changeByRange(r=>{let i=[];for(let a=r.from;a<=r.to;){let o=e.doc.lineAt(a);o.number>n&&(r.empty||r.to>o.from)&&(t(o,i,r),n=o.number),a=o.to+1}let o=e.changes(i);return{changes:i,range:a.range(o.mapPos(r.anchor,1),o.mapPos(r.head,1))}})}var Bn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=Object.create(null),r=new Ee(e,{overrideIndentation:e=>n[e]??-1}),i=zn(e,(t,i,a)=>{let o=je(r,t.from);if(o==null)return;/\S/.test(t.text)||(o=0);let s=/^\s*/.exec(t.text)[0],c=Ne(e,o);(s!=c||a.from<t.from+s.length)&&(n[t.from]=o,i.push({from:t.from,to:t.from+s.length,insert:c}))});return i.changes.empty||t(e.update(i,{userEvent:`indent`})),!0},Vn=({state:e,dispatch:t})=>!e.readOnly&&(t(e.update(zn(e,(t,n)=>{n.push({from:t.from,insert:e.facet(Pe)})}),{userEvent:`input.indent`})),!0),Hn=({state:e,dispatch:t})=>!e.readOnly&&(t(e.update(zn(e,(t,n)=>{let r=/^\s*/.exec(t.text)[0];if(!r)return;let i=ie(r,e.tabSize),a=0,o=Ne(e,Math.max(0,i-Ae(e)));for(;a<r.length&&a<o.length&&r.charCodeAt(a)==o.charCodeAt(a);)a++;n.push({from:t.from+a,to:t.from+r.length,insert:o.slice(a)})}),{userEvent:`delete.dedent`})),!0),Un=e=>(e.setTabFocusMode(),!0),Wn=[{key:`Ctrl-b`,run:gt,shift:Bt,preventDefault:!0},{key:`Ctrl-f`,run:_t,shift:Vt},{key:`Ctrl-p`,run:Tt,shift:Jt},{key:`Ctrl-n`,run:Et,shift:Yt},{key:`Ctrl-a`,run:Ft,shift:rn},{key:`Ctrl-e`,run:It,shift:an},{key:`Ctrl-d`,run:yn},{key:`Ctrl-h`,run:vn},{key:`Ctrl-k`,run:Cn},{key:`Ctrl-Alt-h`,run:xn},{key:`Ctrl-o`,run:En},{key:`Ctrl-t`,run:Dn},{key:`Ctrl-v`,run:At}],Gn=[{key:`ArrowLeft`,run:gt,shift:Bt,preventDefault:!0},{key:`Mod-ArrowLeft`,mac:`Alt-ArrowLeft`,run:yt,shift:Ut,preventDefault:!0},{mac:`Cmd-ArrowLeft`,run:Nt,shift:tn,preventDefault:!0},{key:`ArrowRight`,run:_t,shift:Vt,preventDefault:!0},{key:`Mod-ArrowRight`,mac:`Alt-ArrowRight`,run:bt,shift:Wt,preventDefault:!0},{mac:`Cmd-ArrowRight`,run:Pt,shift:nn,preventDefault:!0},{key:`ArrowUp`,run:Tt,shift:Jt,preventDefault:!0},{mac:`Cmd-ArrowUp`,run:on,shift:cn},{mac:`Ctrl-ArrowUp`,run:kt,shift:Zt},{key:`ArrowDown`,run:Et,shift:Yt,preventDefault:!0},{mac:`Cmd-ArrowDown`,run:sn,shift:ln},{mac:`Ctrl-ArrowDown`,run:At,shift:Qt},{key:`PageUp`,run:kt,shift:Zt},{key:`PageDown`,run:At,shift:Qt},{key:`Home`,run:Mt,shift:en,preventDefault:!0},{key:`Mod-Home`,run:on,shift:cn},{key:`End`,run:jt,shift:$t,preventDefault:!0},{key:`Mod-End`,run:sn,shift:ln},{key:`Enter`,run:In,shift:In},{key:`Mod-a`,run:un},{key:`Backspace`,run:vn,shift:vn,preventDefault:!0},{key:`Delete`,run:yn,preventDefault:!0},{key:`Mod-Backspace`,mac:`Alt-Backspace`,run:xn,preventDefault:!0},{key:`Mod-Delete`,mac:`Alt-Delete`,run:Sn,preventDefault:!0},{mac:`Mod-Backspace`,run:wn,preventDefault:!0},{mac:`Mod-Delete`,run:Tn,preventDefault:!0}].concat(Wn.map(e=>({mac:e.key,run:e.run,shift:e.shift}))),Kn=[{key:`Alt-ArrowLeft`,mac:`Ctrl-ArrowLeft`,run:St,shift:Gt},{key:`Alt-ArrowRight`,mac:`Ctrl-ArrowRight`,run:Ct,shift:Kt},{key:`Alt-ArrowUp`,run:kn},{key:`Shift-Alt-ArrowUp`,run:Mn},{key:`Alt-ArrowDown`,run:An},{key:`Shift-Alt-ArrowDown`,run:Nn},{key:`Mod-Alt-ArrowUp`,run:mn},{key:`Mod-Alt-ArrowDown`,run:hn},{key:`Escape`,run:gn},{key:`Mod-Enter`,run:Ln},{key:`Alt-l`,mac:`Ctrl-l`,run:dn},{key:`Mod-i`,run:fn,preventDefault:!0},{key:`Mod-[`,run:Hn},{key:`Mod-]`,run:Vn},{key:`Mod-Alt-\\`,run:Bn},{key:`Shift-Mod-k`,run:Pn},{key:`Shift-Mod-\\`,run:Rt},{key:`Mod-/`,run:ze},{key:`Alt-A`,mac:`Ctrl-A`,run:He},{key:`Ctrl-m`,mac:`Shift-Alt-m`,run:Un}].concat(Gn),qn={key:`Tab`,run:Vn,shift:Hn},Jn=typeof String.prototype.normalize==`function`?e=>e.normalize(`NFKD`):e=>e,V=class{constructor(e,t,n=0,r=e.length,i,a){this.test=a,this.value={from:0,to:0,precise:!1},this.done=!1,this.matches=[],this.buffer=``,this.bufferPos=0,this.iter=e.iterRange(n,r),this.bufferStart=n,this.normalize=i?e=>i(Jn(e)):Jn,this.query=this.normalize(t)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return ee(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let e=this.peek();if(e<0)return this.done=!0,this;let t=re(e),n=this.bufferStart+this.bufferPos;this.bufferPos+=Ce(e);let r=this.normalize(t);if(r.length)for(let e=0,i=n,a=!0;;e++){let n=r.charCodeAt(e),o=this.match(n,i,a,this.bufferPos+this.bufferStart,e==r.length-1);if(o)return this.value=o,this;if(e==r.length-1)break;a&&e<t.length&&t.charCodeAt(e)==n?i++:a=!1}}}match(e,t,n,r,i){let a=null;for(let t=0;t<this.matches.length;){let n=this.matches[t],o=!1;this.query.charCodeAt(n.index)==e&&(n.index==this.query.length-1?a={from:n.from,to:r,precise:i&&n.precise}:(n.index++,o=!0)),o?t++:this.matches.splice(t,1)}return this.query.charCodeAt(0)==e&&(this.query.length==1?a={from:t,to:r,precise:n&&i}:this.matches.push({from:t,index:1,precise:n})),a&&this.test&&!this.test(a.from,a.to,this.buffer,this.bufferStart)&&(a=null),a}};typeof Symbol<`u`&&(V.prototype[Symbol.iterator]=function(){return this});var Yn={from:-1,to:-1,match:/.*/.exec(``),precise:!0},Xn=`gm`+(/x/.unicode==null?``:`u`),Zn=class{constructor(e,t,n,r=0,i=e.length){if(this.text=e,this.to=i,this.curLine=``,this.done=!1,this.value=Yn,/\\[sWDnr]|\n|\r|\[\^/.test(t))return new er(e,t,n,r,i);this.re=new RegExp(t,Xn+(n?.ignoreCase?`i`:``)),this.test=n?.test,this.iter=e.iter();let a=e.lineAt(r);this.curLineStart=a.from,this.matchPos=H(e,r),this.getLine(this.curLineStart)}getLine(e){this.iter.next(e),this.iter.lineBreak?this.curLine=``:(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine=``:this.getLine(0)}next(){for(let e=this.matchPos-this.curLineStart;;){this.re.lastIndex=e;let t=this.matchPos<=this.to&&this.re.exec(this.curLine);if(t){let n=this.curLineStart+t.index,r=n+t[0].length;if(this.matchPos=H(this.text,r+ +(n==r)),n==this.curLineStart+this.curLine.length&&this.nextLine(),(n<r||n>this.value.to)&&(!this.test||this.test(n,r,t)))return this.value={from:n,to:r,precise:!0,match:t},this;e=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length<this.to)this.nextLine(),e=0;else return this.done=!0,this}}},Qn=new WeakMap,$n=class e{constructor(e,t){this.from=e,this.text=t}get to(){return this.from+this.text.length}static get(t,n,r){let i=Qn.get(t);if(!i||i.from>=r||i.to<=n){let i=new e(n,t.sliceString(n,r));return Qn.set(t,i),i}if(i.from==n&&i.to==r)return i;let{text:a,from:o}=i;return o>n&&(a=t.sliceString(n,o)+a,o=n),i.to<r&&(a+=t.sliceString(i.to,r)),Qn.set(t,new e(o,a)),new e(n,a.slice(n-o,r-o))}},er=class{constructor(e,t,n,r,i){this.text=e,this.to=i,this.done=!1,this.value=Yn,this.matchPos=H(e,r),this.re=new RegExp(t,Xn+(n?.ignoreCase?`i`:``)),this.test=n?.test,this.flat=$n.get(e,r,this.chunkEnd(r+5e3))}chunkEnd(e){return e>=this.to?this.to:this.text.lineAt(e).to}next(){for(;;){let e=this.re.lastIndex=this.matchPos-this.flat.from,t=this.re.exec(this.flat.text);if(t&&!t[0]&&t.index==e&&(this.re.lastIndex=e+1,t=this.re.exec(this.flat.text)),t){let e=this.flat.from+t.index,n=e+t[0].length;if((this.flat.to>=this.to||t.index+t[0].length<=this.flat.text.length-10)&&(!this.test||this.test(e,n,t)))return this.value={from:e,to:n,precise:!0,match:t},this.matchPos=H(this.text,n+ +(e==n)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=$n.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}};typeof Symbol<`u`&&(Zn.prototype[Symbol.iterator]=er.prototype[Symbol.iterator]=function(){return this});function tr(e){try{return new RegExp(e,Xn),!0}catch{return!1}}function H(e,t){if(t>=e.length)return t;let n=e.lineAt(t),r;for(;t<n.to&&(r=n.text.charCodeAt(t-n.from))>=56320&&r<57344;)t++;return t}var nr=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:i}=ce(e,{label:t.phrase(`Go to line`),input:{type:`text`,name:`line`,value:n},focus:!0,submitLabel:t.phrase(`go`)});return i.then(n=>{let i=n&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(n.elements.line.value);if(!i){e.dispatch({effects:r});return}let o=t.doc.lineAt(t.selection.main.head),[,s,c,l,u]=i,d=l?+l.slice(1):0,f=c?+c:o.number;if(c&&u){let e=f/100;s&&(e=e*(s==`-`?-1:1)+o.number/t.doc.lines),f=Math.round(t.doc.lines*e)}else c&&s&&(f=f*(s==`-`?-1:1)+o.number);let p=t.doc.line(Math.max(1,Math.min(t.doc.lines,f))),m=a.cursor(p.from+Math.max(0,Math.min(d,p.length)));e.dispatch({effects:[r,g.scrollIntoView(m.from,{y:`center`})],selection:m})}),!0},rr={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},ir=m.define({combine(e){return n(e,rr,{highlightWordAroundCursor:(e,t)=>e||t,minSelectionLength:Math.min,maxMatches:Math.min})}});function ar(e){let t=[dr,ur];return e&&t.push(ir.of(e)),t}var or=_.mark({class:`cm-selectionMatch`}),sr=_.mark({class:`cm-selectionMatch cm-selectionMatch-main`});function cr(e,t,n,r){return(n==0||e(t.sliceDoc(n-1,n))!=v.Word)&&(r==t.doc.length||e(t.sliceDoc(r,r+1))!=v.Word)}function lr(e,t,n,r){return e(t.sliceDoc(n,n+1))==v.Word&&e(t.sliceDoc(r-1,r))==v.Word}var ur=le.fromClass(class{constructor(e){this.decorations=this.getDeco(e)}update(e){(e.selectionSet||e.docChanged||e.viewportChanged)&&(this.decorations=this.getDeco(e.view))}getDeco(e){let t=e.state.facet(ir),{state:n}=e,r=n.selection;if(r.ranges.length>1)return _.none;let i=r.main,a,o=null;if(i.empty){if(!t.highlightWordAroundCursor)return _.none;let e=n.wordAt(i.head);if(!e)return _.none;o=n.charCategorizer(i.head),a=n.sliceDoc(e.from,e.to)}else{let e=i.to-i.from;if(e<t.minSelectionLength||e>200)return _.none;if(t.wholeWords){if(a=n.sliceDoc(i.from,i.to),o=n.charCategorizer(i.head),!(cr(o,n,i.from,i.to)&&lr(o,n,i.from,i.to)))return _.none}else if(a=n.sliceDoc(i.from,i.to),!a)return _.none}let s=[];for(let r of e.visibleRanges){let e=new V(n.doc,a,r.from,r.to);for(;!e.next().done;){let{from:r,to:a}=e.value;if((!o||cr(o,n,r,a))&&(i.empty&&r<=i.from&&a>=i.to?s.push(sr.range(r,a)):(r>=i.to||a<=i.from)&&s.push(or.range(r,a)),s.length>t.maxMatches))return _.none}}return _.set(s)}},{decorations:e=>e.decorations}),dr=g.baseTheme({".cm-selectionMatch":{backgroundColor:`#99ff7780`},".cm-searchMatch .cm-selectionMatch":{backgroundColor:`transparent`}}),fr=({state:e,dispatch:t})=>{let{selection:n}=e,r=a.create(n.ranges.map(t=>e.wordAt(t.head)||a.cursor(t.head)),n.mainIndex);return!r.eq(n)&&(t(e.update({selection:r})),!0)};function pr(e,t){let{main:n,ranges:r}=e.selection,i=e.wordAt(n.head),a=i&&i.from==n.from&&i.to==n.to;for(let n=!1,i=new V(e.doc,t,r[r.length-1].to);;)if(i.next(),i.done){if(n)return null;i=new V(e.doc,t,0,Math.max(0,r[r.length-1].from-1)),n=!0}else{if(n&&r.some(e=>e.from==i.value.from))continue;if(a){let t=e.wordAt(i.value.from);if(!t||t.from!=i.value.from||t.to!=i.value.to)continue}return i.value}}var mr=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(e=>e.from===e.to))return fr({state:e,dispatch:t});let r=e.sliceDoc(n[0].from,n[0].to);if(e.selection.ranges.some(t=>e.sliceDoc(t.from,t.to)!=r))return!1;let i=pr(e,r);return i?(t(e.update({selection:e.selection.addRange(a.range(i.from,i.to),!1),effects:g.scrollIntoView(i.to)})),!0):!1},U=m.define({combine(e){return n(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:e=>new Br(e),scrollToMatch:e=>g.scrollIntoView(e)})}});function hr(e){return e?[U.of(e),Gr]:Gr}var gr=class{constructor(e){this.search=e.search,this.caseSensitive=!!e.caseSensitive,this.literal=!!e.literal,this.regexp=!!e.regexp,this.replace=e.replace||``,this.valid=!!this.search&&(!this.regexp||tr(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!e.wholeWord,this.test=e.test}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,(e,t)=>t==`n`?`
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as f,M as p,O as m,P as h,R as ee,S as te,T as ne,U as re,V as ie,W as ae,X as oe,Y as se,_ as ce,a as le,c as ue,d as de,f as fe,g as pe,h as me,n as he,o as ge,p as _e,q as ve,r as g,s as ye,t as _,u as be,v as xe,w as v,x as Se,y,z as Ce}from"./index-BURdA48M.js";import{l as we,o as b}from"./dist-CYkOb3JV.js";import{HighlightStyle as Te,IndentContext as Ee,bracketMatching as De,foldGutter as Oe,foldKeymap as ke,getIndentUnit as Ae,getIndentation as je,indentOnInput as Me,indentString as Ne,indentUnit as Pe,matchBrackets as x,syntaxHighlighting as Fe,syntaxTree as Ie}from"./dist-CIPu76lT.js";function S(e,t){let n=[...t].sort((e,t)=>e.from-t.from||e.to-t.to),r=0;for(let[t,i]of n.entries()){if(!Number.isInteger(i.from)||!Number.isInteger(i.to))throw RangeError(`Editor ranges must use integer offsets`);if(i.from<0||i.to<i.from||i.to>e)throw RangeError(`Editor range ${t} is outside the document`);if(t>0&&i.from<r)throw RangeError(`Editor ranges must not overlap`);r=Math.max(r,i.to)}return n}function Le(e,t){return S(e,t)}var C=e(oe(),1),Re=e(u(),1),ze=e=>{let{state:t}=e,n=t.doc.lineAt(t.selection.main.from),r=We(e.state,n.from);return r.line?Ve(e):r.block?Ue(e):!1};function Be(e,t){return({state:n,dispatch:r})=>{if(n.readOnly)return!1;let i=e(t,n);return i?(r(n.update(i)),!0):!1}}var Ve=Be(Je,0),He=Be(qe,0),Ue=Be((e,t)=>qe(e,t,Ke(t)),0);function We(e,t){let n=e.languageDataAt(`commentTokens`,t,1);return n.length?n[0]:{}}var w=50;function Ge(e,{open:t,close:n},r,i){let a=e.sliceDoc(r-w,r),o=e.sliceDoc(i,i+w),s=/\s*$/.exec(a)[0].length,c=/^\s*/.exec(o)[0].length,l=a.length-s;if(a.slice(l-t.length,l)==t&&o.slice(c,c+n.length)==n)return{open:{pos:r-s,margin:s&&1},close:{pos:i+c,margin:c&&1}};let u,d;i-r<=100?u=d=e.sliceDoc(r,i):(u=e.sliceDoc(r,r+w),d=e.sliceDoc(i-w,i));let f=/^\s*/.exec(u)[0].length,p=/\s*$/.exec(d)[0].length,m=d.length-p-n.length;return u.slice(f,f+t.length)==t&&d.slice(m,m+n.length)==n?{open:{pos:r+f+t.length,margin:+!!/\s/.test(u.charAt(f+t.length))},close:{pos:i-p-n.length,margin:+!!/\s/.test(d.charAt(m-1))}}:null}function Ke(e){let t=[];for(let n of e.selection.ranges){let r=e.doc.lineAt(n.from),i=n.to<=r.to?r:e.doc.lineAt(n.to);i.from>r.from&&i.from==n.to&&(i=n.to==r.to+1?r:e.doc.lineAt(n.to-1));let a=t.length-1;a>=0&&t[a].to>r.from?t[a].to=i.to:t.push({from:r.from+/^\s*/.exec(r.text)[0].length,to:i.to})}return t}function qe(e,t,n=t.selection.ranges){let r=n.map(e=>We(t,e.from).block);if(!r.every(e=>e))return null;let i=n.map((e,n)=>Ge(t,r[n],e.from,e.to));if(e!=2&&!i.every(e=>e))return{changes:t.changes(n.map((e,t)=>i[t]?[]:[{from:e.from,insert:r[t].open+` `},{from:e.to,insert:` `+r[t].close}]))};if(e!=1&&i.some(e=>e)){let e=[];for(let t=0,n;t<i.length;t++)if(n=i[t]){let i=r[t],{open:a,close:o}=n;e.push({from:a.pos-i.open.length,to:a.pos+a.margin},{from:o.pos-o.margin,to:o.pos+i.close.length})}return{changes:e}}return null}function Je(e,t,n=t.selection.ranges){let r=[],i=-1;ranges:for(let{from:e,to:a}of n){let n=r.length,o=1e9,s;for(let n=e;n<=a;){let c=t.doc.lineAt(n);if(s==null&&(s=We(t,c.from).line,!s))continue ranges;if(c.from>i&&(e==a||a>c.from)){i=c.from;let e=/^\s*/.exec(c.text)[0].length,t=e==c.length,n=c.text.slice(e,e+s.length)==s?e:-1;e<c.text.length&&e<o&&(o=e),r.push({line:c,comment:n,token:s,indent:e,empty:t,single:!1})}n=c.to+1}if(o<1e9)for(let e=n;e<r.length;e++)r[e].indent<r[e].line.text.length&&(r[e].indent=o);r.length==n+1&&(r[n].single=!0)}if(e!=2&&r.some(e=>e.comment<0&&(!e.empty||e.single))){let e=[];for(let{line:t,token:n,indent:i,empty:a,single:o}of r)(o||!a)&&e.push({from:t.from+i,insert:n+` `});let n=t.changes(e);return{changes:n,selection:t.selection.map(n,1)}}if(e!=1&&r.some(e=>e.comment>=0)){let e=[];for(let{line:t,comment:n,token:i}of r)if(n>=0){let r=t.from+n,a=r+i.length;t.text[a-t.from]==` `&&a++,e.push({from:r,to:a})}return{changes:e}}return null}var Ye=Se.define(),Xe=Se.define(),Ze=m.define(),Qe=m.define({combine(e){return n(e,{minDepth:100,newGroupDelay:500,joinToEvent:(e,t)=>t},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,t)=>(n,r)=>e(n,r)||t(n,r)})}}),$e=o.define({create(){return k.empty},update(e,t){let n=t.state.facet(Qe),r=t.annotation(Ye);if(r){let i=E.fromTransaction(t,r.selection),a=r.side,o=a==0?e.undone:e.done;return o=i?D(o,o.length,n.minDepth,i):lt(o,t.startState.selection),new k(a==0?r.rest:o,a==0?o:r.rest)}let i=t.annotation(Xe);if((i==`full`||i==`before`)&&(e=e.isolate()),t.annotation(f.addToHistory)===!1)return t.changes.empty?e:e.addMapping(t.changes.desc);let a=E.fromTransaction(t),o=t.annotation(f.time),s=t.annotation(f.userEvent);return a?e=e.addChanges(a,o,s,n,t):t.selection&&(e=e.addSelection(t.startState.selection,o,s,n.newGroupDelay)),(i==`full`||i==`after`)&&(e=e.isolate()),e},toJSON(e){return{done:e.done.map(e=>e.toJSON()),undone:e.undone.map(e=>e.toJSON())}},fromJSON(e){return new k(e.done.map(E.fromJSON),e.undone.map(E.fromJSON))}});function et(e={}){return[$e,Qe.of(e),g.domEventHandlers({beforeinput(e,t){let n=e.inputType==`historyUndo`?tt:e.inputType==`historyRedo`?nt:null;return n?(e.preventDefault(),n(t)):!1}})]}function T(e,t){return function({state:n,dispatch:r}){if(!t&&n.readOnly)return!1;let i=n.field($e,!1);if(!i)return!1;let a=i.pop(e,n,t);return a?(r(a),!0):!1}}var tt=T(0,!1),nt=T(1,!1),rt=T(0,!0),it=T(1,!0),E=class e{constructor(e,t,n,r,i){this.changes=e,this.effects=t,this.mapped=n,this.startSelection=r,this.selectionsAfter=i}setSelAfter(t){return new e(this.changes,this.effects,this.mapped,this.startSelection,t)}toJSON(){return{changes:this.changes?.toJSON(),mapped:this.mapped?.toJSON(),startSelection:this.startSelection?.toJSON(),selectionsAfter:this.selectionsAfter.map(e=>e.toJSON())}}static fromJSON(t){return new e(t.changes&&r.fromJSON(t.changes),[],t.mapped&&te.fromJSON(t.mapped),t.startSelection&&a.fromJSON(t.startSelection),t.selectionsAfter.map(a.fromJSON))}static fromTransaction(t,n){let r=O;for(let e of t.startState.facet(Ze)){let n=e(t);n.length&&(r=r.concat(n))}return!r.length&&t.changes.empty?null:new e(t.changes.invert(t.startState.doc),r,void 0,n||t.startState.selection,O)}static selection(t){return new e(void 0,O,void 0,void 0,t)}};function D(e,t,n,r){let i=t+1>n+20?t-n-1:0,a=e.slice(i,t);return a.push(r),a}function at(e,t){let n=[],r=!1;return e.iterChangedRanges((e,t)=>n.push(e,t)),t.iterChangedRanges((e,t,i,a)=>{for(let e=0;e<n.length;){let t=n[e++],o=n[e++];a>=t&&i<=o&&(r=!0)}}),r}function ot(e,t){return e.ranges.length==t.ranges.length&&e.ranges.filter((e,n)=>e.empty!=t.ranges[n].empty).length===0}function st(e,t){return e.length?t.length?e.concat(t):e:t}var O=[],ct=200;function lt(e,t){if(e.length){let n=e[e.length-1],r=n.selectionsAfter.slice(Math.max(0,n.selectionsAfter.length-ct));return r.length&&r[r.length-1].eq(t)?e:(r.push(t),D(e,e.length-1,1e9,n.setSelAfter(r)))}return[E.selection([t])]}function ut(e){let t=e[e.length-1],n=e.slice();return n[e.length-1]=t.setSelAfter(t.selectionsAfter.slice(0,t.selectionsAfter.length-1)),n}function dt(e,t){if(!e.length)return e;let n=e.length,r=O;for(;n;){let i=ft(e[n-1],t,r);if(i.changes&&!i.changes.empty||i.effects.length){let t=e.slice(0,n);return t[n-1]=i,t}t=i.mapped,n--,r=i.selectionsAfter}return r.length?[E.selection(r)]:O}function ft(e,t,n){let r=st(e.selectionsAfter.length?e.selectionsAfter.map(e=>e.map(t)):O,n);if(!e.changes)return E.selection(r);let i=e.changes.map(t),a=t.mapDesc(e.changes,!0),o=e.mapped?e.mapped.composeDesc(a):a;return new E(i,h.mapEffects(e.effects,t),o,e.startSelection.map(a),r)}var pt=/^(input\.type|delete)($|\.)/,k=class e{constructor(e,t,n=0,r=void 0){this.done=e,this.undone=t,this.prevTime=n,this.prevUserEvent=r}isolate(){return this.prevTime?new e(this.done,this.undone):this}addChanges(t,n,r,i,a){let o=this.done,s=o[o.length-1];return o=s&&s.changes&&!s.changes.empty&&t.changes&&(!r||pt.test(r))&&(!s.selectionsAfter.length&&n-this.prevTime<i.newGroupDelay&&i.joinToEvent(a,at(s.changes,t.changes))||r==`input.type.compose`)?D(o,o.length-1,i.minDepth,new E(t.changes.compose(s.changes),st(h.mapEffects(t.effects,s.changes),s.effects),s.mapped,s.startSelection,O)):D(o,o.length,i.minDepth,t),new e(o,O,n,r)}addSelection(t,n,r,i){let a=this.done.length?this.done[this.done.length-1].selectionsAfter:O;return a.length>0&&n-this.prevTime<i&&r==this.prevUserEvent&&r&&/^select($|\.)/.test(r)&&ot(a[a.length-1],t)?this:new e(lt(this.done,t),this.undone,n,r)}addMapping(t){return new e(dt(this.done,t),dt(this.undone,t),this.prevTime,this.prevUserEvent)}pop(e,t,n){let r=e==0?this.done:this.undone;if(r.length==0)return null;let i=r[r.length-1],a=i.selectionsAfter[0]||(i.startSelection?i.startSelection.map(i.changes.invertedDesc,1):t.selection);if(n&&i.selectionsAfter.length)return t.update({selection:i.selectionsAfter[i.selectionsAfter.length-1],annotations:Ye.of({side:e,rest:ut(r),selection:a}),userEvent:e==0?`select.undo`:`select.redo`,scrollIntoView:!0});if(i.changes){let n=r.length==1?O:r.slice(0,r.length-1);return i.mapped&&(n=dt(n,i.mapped)),t.update({changes:i.changes,selection:i.startSelection,effects:i.effects,annotations:Ye.of({side:e,rest:n,selection:a}),filter:!1,userEvent:e==0?`undo`:`redo`,scrollIntoView:!0})}return null}};k.empty=new k(O,O);var mt=[{key:`Mod-z`,run:tt,preventDefault:!0},{key:`Mod-y`,mac:`Mod-Shift-z`,run:nt,preventDefault:!0},{linux:`Ctrl-Shift-z`,run:nt,preventDefault:!0},{key:`Mod-u`,run:rt,preventDefault:!0},{key:`Alt-u`,mac:`Mod-Shift-u`,run:it,preventDefault:!0}];function A(e,t){return a.create(e.ranges.map(t),e.mainIndex)}function j(e,t){return e.update({selection:t,scrollIntoView:!0,userEvent:`select`})}function M({state:e,dispatch:t},n){let r=A(e.selection,n);return!r.eq(e.selection,!0)&&(t(j(e,r)),!0)}function N(e,t){return a.cursor(t?e.to:e.from)}function ht(e,t){return M(e,n=>n.empty?e.moveByChar(n,t):N(n,t))}function P(e){return e.textDirectionAt(e.state.selection.main.head)==he.LTR}var gt=e=>ht(e,!P(e)),_t=e=>ht(e,P(e));function vt(e,t){return M(e,n=>n.empty?e.moveByGroup(n,t):N(n,t))}var yt=e=>vt(e,!P(e)),bt=e=>vt(e,P(e));typeof Intl<`u`&&Intl.Segmenter;function xt(e,t,n){if(t.type.prop(n))return!0;let r=t.to-t.from;return r&&(r>2||/[^\s,.;:]/.test(e.sliceDoc(t.from,t.to)))||t.firstChild}function F(e,t,n){let r=Ie(e).resolveInner(t.head),i=n?we.closedBy:we.openedBy;for(let a=t.head;;){let t=n?r.childAfter(a):r.childBefore(a);if(!t)break;xt(e,t,i)?r=t:a=n?t.to:t.from}let o=r.type.prop(i),s,c;return c=o&&(s=n?x(e,r.from,1):x(e,r.to,-1))&&s.matched?n?s.end.to:s.end.from:n?r.to:r.from,a.cursor(c,n?-1:1)}var St=e=>M(e,t=>F(e.state,t,!P(e))),Ct=e=>M(e,t=>F(e.state,t,P(e)));function wt(e,t){return M(e,n=>{if(!n.empty)return N(n,t);let r=e.moveVertically(n,t);return r.head==n.head?e.moveToLineBoundary(n,t):r})}var Tt=e=>wt(e,!1),Et=e=>wt(e,!0);function Dt(e){let t=e.scrollDOM.clientHeight<e.scrollDOM.scrollHeight-2,n=0,r=0,i;if(t){for(let t of e.state.facet(g.scrollMargins)){let i=t(e);i?.top&&(n=Math.max(i?.top,n)),i?.bottom&&(r=Math.max(i?.bottom,r))}i=e.scrollDOM.clientHeight-n-r}else i=(e.dom.ownerDocument.defaultView||window).innerHeight;return{marginTop:n,marginBottom:r,selfScroll:t,height:Math.max(e.defaultLineHeight,i-5)}}function Ot(e,t){let n=Dt(e),{state:r}=e,i=A(r.selection,r=>r.empty?e.moveVertically(r,t,n.height):N(r,t));if(i.eq(r.selection))return!1;let a;if(n.selfScroll){let t=e.coordsAtPos(r.selection.main.head),o=e.scrollDOM.getBoundingClientRect(),s=o.top+n.marginTop,c=o.bottom-n.marginBottom;t&&t.top>s&&t.bottom<c&&(a=g.scrollIntoView(i.main.head,{y:`start`,yMargin:t.top-s}))}return e.dispatch(j(r,i),{effects:a}),!0}var kt=e=>Ot(e,!1),At=e=>Ot(e,!0);function I(e,t,n){let r=e.lineBlockAt(t.head),i=e.moveToLineBoundary(t,n);if(i.head==t.head&&i.head!=(n?r.to:r.from)&&(i=e.moveToLineBoundary(t,n,!1)),!n&&i.head==r.from&&r.length){let n=/^\s*/.exec(e.state.sliceDoc(r.from,Math.min(r.from+100,r.to)))[0].length;n&&t.head!=r.from+n&&(i=a.cursor(r.from+n))}return i}var jt=e=>M(e,t=>I(e,t,!0)),Mt=e=>M(e,t=>I(e,t,!1)),Nt=e=>M(e,t=>I(e,t,!P(e))),Pt=e=>M(e,t=>I(e,t,P(e))),Ft=e=>M(e,t=>a.cursor(e.lineBlockAt(t.head).from,1)),It=e=>M(e,t=>a.cursor(e.lineBlockAt(t.head).to,-1));function Lt(e,t,n){let r=!1,i=A(e.selection,t=>{let i=x(e,t.head,-1)||x(e,t.head,1)||t.head>0&&x(e,t.head-1,1)||t.head<e.doc.length&&x(e,t.head+1,-1);if(!i||!i.end)return t;r=!0;let o=i.start.from==t.head?i.end.to:i.end.from;return n?a.range(t.anchor,o):a.cursor(o)});return r?(t(j(e,i)),!0):!1}var Rt=({state:e,dispatch:t})=>Lt(e,t,!1);function L(e,t,n){let r=A(e.state.selection,e=>{e.undirectional&&e.head>=e.anchor!=t&&(e=a.range(e.head,e.anchor));let r=n(e);return a.range(e.anchor,r.head,r.goalColumn,r.bidiLevel||void 0,r.assoc)});return!r.eq(e.state.selection)&&(e.dispatch(j(e.state,r)),!0)}function zt(e,t){return L(e,t,n=>e.moveByChar(n,t))}var Bt=e=>zt(e,!P(e)),Vt=e=>zt(e,P(e));function Ht(e,t){return L(e,t,n=>e.moveByGroup(n,t))}var Ut=e=>Ht(e,!P(e)),Wt=e=>Ht(e,P(e)),Gt=e=>{let t=!P(e);return L(e,t,n=>F(e.state,n,t))},Kt=e=>{let t=P(e);return L(e,t,n=>F(e.state,n,t))};function qt(e,t){return L(e,t,n=>e.moveVertically(n,t))}var Jt=e=>qt(e,!1),Yt=e=>qt(e,!0);function Xt(e,t){return L(e,t,n=>e.moveVertically(n,t,Dt(e).height))}var Zt=e=>Xt(e,!1),Qt=e=>Xt(e,!0),$t=e=>L(e,!0,t=>I(e,t,!0)),en=e=>L(e,!1,t=>I(e,t,!1)),tn=e=>{let t=!P(e);return L(e,t,n=>I(e,n,t))},nn=e=>{let t=P(e);return L(e,t,n=>I(e,n,t))},rn=e=>L(e,!1,t=>a.cursor(e.lineBlockAt(t.head).from)),an=e=>L(e,!0,t=>a.cursor(e.lineBlockAt(t.head).to)),on=({state:e,dispatch:t})=>(t(j(e,{anchor:0})),!0),sn=({state:e,dispatch:t})=>(t(j(e,{anchor:e.doc.length})),!0),cn=({state:e,dispatch:t})=>(t(j(e,{anchor:e.selection.main.anchor,head:0})),!0),ln=({state:e,dispatch:t})=>(t(j(e,{anchor:e.selection.main.anchor,head:e.doc.length})),!0),un=({state:e,dispatch:t})=>(t(e.update({selection:{anchor:0,head:e.doc.length},userEvent:`select`})),!0),dn=({state:e,dispatch:t})=>{let n=B(e).map(({from:t,to:n})=>a.undirectionalRange(t,Math.min(n+1,e.doc.length)));return t(e.update({selection:a.create(n),userEvent:`select`})),!0},fn=({state:e,dispatch:t})=>{let n=A(e.selection,t=>{let n=Ie(e),r=n.resolveStack(t.from,1);if(t.empty){let e=n.resolveStack(t.from,-1);e.node.from>=r.node.from&&e.node.to<=r.node.to&&(r=e)}for(let e=r;e;e=e.next){let{node:n}=e;if((n.from<t.from&&n.to>=t.to||n.to>t.to&&n.from<=t.from)&&e.next)return a.undirectionalRange(n.from,n.to)}return t});return!n.eq(e.selection)&&(t(j(e,n)),!0)};function pn(e,t){let{state:n}=e,r=n.selection,i=n.selection.ranges.slice();for(let r of n.selection.ranges){let a=n.doc.lineAt(r.head);if(t?a.to<e.state.doc.length:a.from>0)for(let n=r;;){let r=e.moveVertically(n,t);if(r.head<a.from||r.head>a.to){i.some(e=>e.head==r.head)||i.push(r);break}if(r.head==n.head)break;n=r}}return i.length!=r.ranges.length&&(e.dispatch(j(n,a.create(i,i.length-1))),!0)}var mn=e=>pn(e,!1),hn=e=>pn(e,!0),gn=({state:e,dispatch:t})=>{let n=e.selection,r=null;return n.ranges.length>1?r=a.create([n.main]):n.main.empty||(r=a.create([a.cursor(n.main.head)])),r?(t(j(e,r)),!0):!1};function R(e,t){if(e.state.readOnly)return!1;let n=`delete.selection`,{state:r}=e,i=r.changeByRange(r=>{let{from:i,to:o}=r;if(i==o){let a=t(r);a<i?(n=`delete.backward`,a=z(e,a,!1)):a>i&&(n=`delete.forward`,a=z(e,a,!0)),i=Math.min(i,a),o=Math.max(o,a)}else i=z(e,i,!1),o=z(e,o,!0);return i==o?{range:r}:{changes:{from:i,to:o},range:a.cursor(i,i<r.head?-1:1)}});return!i.changes.empty&&(e.dispatch(r.update(i,{scrollIntoView:!0,userEvent:n,effects:n==`delete.selection`?g.announce.of(r.phrase(`Selection deleted`)):void 0})),!0)}function z(e,t,n){if(e instanceof g)for(let r of e.state.facet(g.atomicRanges).map(t=>t(e)))r.between(t,t,(e,r)=>{e<t&&r>t&&(t=n?r:e)});return t}var _n=(e,t,n)=>R(e,r=>{let i=r.from,{state:a}=e,o=a.doc.lineAt(i),s,l;if(n&&!t&&i>o.from&&i<o.from+200&&!/[^ \t]/.test(s=o.text.slice(0,i-o.from))){if(s[s.length-1]==` `)return i-1;let e=ie(s,a.tabSize)%Ae(a)||Ae(a);for(let t=0;t<e&&s[s.length-1-t]==` `;t++)i--;l=i}else l=c(o.text,i-o.from,t,t)+o.from,l==i&&o.number!=(t?a.doc.lines:1)?l+=t?1:-1:!t&&/[\ufe00-\ufe0f]/.test(o.text.slice(l-o.from,i-o.from))&&(l=c(o.text,l-o.from,!1,!1)+o.from);return l}),vn=e=>_n(e,!1,!0),yn=e=>_n(e,!0,!1),bn=(e,t)=>R(e,n=>{let r=n.head,{state:i}=e,a=i.doc.lineAt(r),o=i.charCategorizer(r);for(let e=null;;){if(r==(t?a.to:a.from)){r==n.head&&a.number!=(t?i.doc.lines:1)&&(r+=t?1:-1);break}let s=c(a.text,r-a.from,t)+a.from,l=a.text.slice(Math.min(r,s)-a.from,Math.max(r,s)-a.from),u=o(l);if(e!=null&&u!=e)break;(l!=` `||r!=n.head)&&(e=u),r=s}return r}),xn=e=>bn(e,!1),Sn=e=>bn(e,!0),Cn=e=>R(e,t=>{let n=e.lineBlockAt(t.head).to;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),wn=e=>R(e,t=>{let n=e.moveToLineBoundary(t,!1).head;return t.head>n?n:Math.max(0,t.head-1)}),Tn=e=>R(e,t=>{let n=e.moveToLineBoundary(t,!0).head;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),En=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(e=>({changes:{from:e.from,to:e.to,insert:l.of([``,``])},range:a.cursor(e.from)}));return t(e.update(n,{scrollIntoView:!0,userEvent:`input`})),!0},Dn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(t=>{if(!t.empty||t.from==0||t.from==e.doc.length)return{range:t};let n=t.from,r=e.doc.lineAt(n),i=n==r.from?n-1:c(r.text,n-r.from,!1)+r.from,o=n==r.to?n+1:c(r.text,n-r.from,!0)+r.from;return{changes:{from:i,to:o,insert:e.doc.slice(n,o).append(e.doc.slice(i,n))},range:a.cursor(o)}});return!n.changes.empty&&(t(e.update(n,{scrollIntoView:!0,userEvent:`move.character`})),!0)};function B(e){let t=[],n=-1;for(let r of e.selection.ranges){let i=e.doc.lineAt(r.from),a=e.doc.lineAt(r.to);if(!r.empty&&r.to==a.from&&(a=e.doc.lineAt(r.to-1)),n>=i.number){let e=t[t.length-1];e.to=a.to,e.ranges.push(r)}else t.push({from:i.from,to:a.to,ranges:[r]});n=a.number+1}return t}function On(e,t,n){if(e.readOnly)return!1;let r=[],i=[];for(let t of B(e)){if(n?t.to==e.doc.length:t.from==0)continue;let o=e.doc.lineAt(n?t.to+1:t.from-1),s=o.length+1;if(n){r.push({from:t.to,to:o.to},{from:t.from,insert:o.text+e.lineBreak});for(let n of t.ranges)i.push(a.range(Math.min(e.doc.length,n.anchor+s),Math.min(e.doc.length,n.head+s)))}else{r.push({from:o.from,to:t.from},{from:t.to,insert:e.lineBreak+o.text});for(let e of t.ranges)i.push(a.range(e.anchor-s,e.head-s))}}return r.length?(t(e.update({changes:r,scrollIntoView:!0,selection:a.create(i,e.selection.mainIndex),userEvent:`move.line`})),!0):!1}var kn=({state:e,dispatch:t})=>On(e,t,!1),An=({state:e,dispatch:t})=>On(e,t,!0);function jn(e,t,n){if(e.readOnly)return!1;let r=[];for(let t of B(e))n?r.push({from:t.from,insert:e.doc.slice(t.from,t.to)+e.lineBreak}):r.push({from:t.to,insert:e.lineBreak+e.doc.slice(t.from,t.to)});let i=e.changes(r);return t(e.update({changes:i,selection:e.selection.map(i,n?1:-1),scrollIntoView:!0,userEvent:`input.copyline`})),!0}var Mn=({state:e,dispatch:t})=>jn(e,t,!1),Nn=({state:e,dispatch:t})=>jn(e,t,!0),Pn=e=>{if(e.state.readOnly)return!1;let{state:t}=e,n=t.changes(B(t).map(({from:e,to:n})=>(e>0?e--:n<t.doc.length&&n++,{from:e,to:n}))),r=A(t.selection,t=>{let n;if(e.lineWrapping){let r=e.lineBlockAt(t.head),i=e.coordsAtPos(t.head,t.assoc||1);i&&(n=r.bottom+e.documentTop-i.bottom+e.defaultLineHeight/2)}return e.moveVertically(t,!0,n)}).map(n);return e.dispatch({changes:n,selection:r,scrollIntoView:!0,userEvent:`delete.line`}),!0};function Fn(e,t){if(/\(\)|\[\]|\{\}/.test(e.sliceDoc(t-1,t+1)))return{from:t,to:t};let n=Ie(e).resolveInner(t),r=n.childBefore(t),i=n.childAfter(t),a;return r&&i&&r.to<=t&&i.from>=t&&(a=r.type.prop(we.closedBy))&&a.indexOf(i.name)>-1&&e.doc.lineAt(r.to).from==e.doc.lineAt(i.from).from&&!/\S/.test(e.sliceDoc(r.to,i.from))?{from:r.to,to:i.from}:null}var In=Rn(!1),Ln=Rn(!0);function Rn(e){return({state:t,dispatch:n})=>{if(t.readOnly)return!1;let r=t.changeByRange(n=>{let{from:r,to:i}=n,o=t.doc.lineAt(r),s=!e&&r==i&&Fn(t,r);e&&(r=i=(i<=o.to?o:t.doc.lineAt(i)).to);let c=new Ee(t,{simulateBreak:r,simulateDoubleBreak:!!s}),u=je(c,r);for(u??=ie(/^\s*/.exec(t.doc.lineAt(r).text)[0],t.tabSize);i<o.to&&/\s/.test(o.text[i-o.from]);)i++;s?{from:r,to:i}=s:r>o.from&&r<o.from+100&&!/\S/.test(o.text.slice(0,r))&&(r=o.from);let d=[``,Ne(t,u)];return s&&d.push(Ne(t,c.lineIndent(o.from,-1))),{changes:{from:r,to:i,insert:l.of(d)},range:a.cursor(r+1+d[1].length)}});return n(t.update(r,{scrollIntoView:!0,userEvent:`input`})),!0}}function zn(e,t){let n=-1;return e.changeByRange(r=>{let i=[];for(let a=r.from;a<=r.to;){let o=e.doc.lineAt(a);o.number>n&&(r.empty||r.to>o.from)&&(t(o,i,r),n=o.number),a=o.to+1}let o=e.changes(i);return{changes:i,range:a.range(o.mapPos(r.anchor,1),o.mapPos(r.head,1))}})}var Bn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=Object.create(null),r=new Ee(e,{overrideIndentation:e=>n[e]??-1}),i=zn(e,(t,i,a)=>{let o=je(r,t.from);if(o==null)return;/\S/.test(t.text)||(o=0);let s=/^\s*/.exec(t.text)[0],c=Ne(e,o);(s!=c||a.from<t.from+s.length)&&(n[t.from]=o,i.push({from:t.from,to:t.from+s.length,insert:c}))});return i.changes.empty||t(e.update(i,{userEvent:`indent`})),!0},Vn=({state:e,dispatch:t})=>!e.readOnly&&(t(e.update(zn(e,(t,n)=>{n.push({from:t.from,insert:e.facet(Pe)})}),{userEvent:`input.indent`})),!0),Hn=({state:e,dispatch:t})=>!e.readOnly&&(t(e.update(zn(e,(t,n)=>{let r=/^\s*/.exec(t.text)[0];if(!r)return;let i=ie(r,e.tabSize),a=0,o=Ne(e,Math.max(0,i-Ae(e)));for(;a<r.length&&a<o.length&&r.charCodeAt(a)==o.charCodeAt(a);)a++;n.push({from:t.from+a,to:t.from+r.length,insert:o.slice(a)})}),{userEvent:`delete.dedent`})),!0),Un=e=>(e.setTabFocusMode(),!0),Wn=[{key:`Ctrl-b`,run:gt,shift:Bt,preventDefault:!0},{key:`Ctrl-f`,run:_t,shift:Vt},{key:`Ctrl-p`,run:Tt,shift:Jt},{key:`Ctrl-n`,run:Et,shift:Yt},{key:`Ctrl-a`,run:Ft,shift:rn},{key:`Ctrl-e`,run:It,shift:an},{key:`Ctrl-d`,run:yn},{key:`Ctrl-h`,run:vn},{key:`Ctrl-k`,run:Cn},{key:`Ctrl-Alt-h`,run:xn},{key:`Ctrl-o`,run:En},{key:`Ctrl-t`,run:Dn},{key:`Ctrl-v`,run:At}],Gn=[{key:`ArrowLeft`,run:gt,shift:Bt,preventDefault:!0},{key:`Mod-ArrowLeft`,mac:`Alt-ArrowLeft`,run:yt,shift:Ut,preventDefault:!0},{mac:`Cmd-ArrowLeft`,run:Nt,shift:tn,preventDefault:!0},{key:`ArrowRight`,run:_t,shift:Vt,preventDefault:!0},{key:`Mod-ArrowRight`,mac:`Alt-ArrowRight`,run:bt,shift:Wt,preventDefault:!0},{mac:`Cmd-ArrowRight`,run:Pt,shift:nn,preventDefault:!0},{key:`ArrowUp`,run:Tt,shift:Jt,preventDefault:!0},{mac:`Cmd-ArrowUp`,run:on,shift:cn},{mac:`Ctrl-ArrowUp`,run:kt,shift:Zt},{key:`ArrowDown`,run:Et,shift:Yt,preventDefault:!0},{mac:`Cmd-ArrowDown`,run:sn,shift:ln},{mac:`Ctrl-ArrowDown`,run:At,shift:Qt},{key:`PageUp`,run:kt,shift:Zt},{key:`PageDown`,run:At,shift:Qt},{key:`Home`,run:Mt,shift:en,preventDefault:!0},{key:`Mod-Home`,run:on,shift:cn},{key:`End`,run:jt,shift:$t,preventDefault:!0},{key:`Mod-End`,run:sn,shift:ln},{key:`Enter`,run:In,shift:In},{key:`Mod-a`,run:un},{key:`Backspace`,run:vn,shift:vn,preventDefault:!0},{key:`Delete`,run:yn,preventDefault:!0},{key:`Mod-Backspace`,mac:`Alt-Backspace`,run:xn,preventDefault:!0},{key:`Mod-Delete`,mac:`Alt-Delete`,run:Sn,preventDefault:!0},{mac:`Mod-Backspace`,run:wn,preventDefault:!0},{mac:`Mod-Delete`,run:Tn,preventDefault:!0}].concat(Wn.map(e=>({mac:e.key,run:e.run,shift:e.shift}))),Kn=[{key:`Alt-ArrowLeft`,mac:`Ctrl-ArrowLeft`,run:St,shift:Gt},{key:`Alt-ArrowRight`,mac:`Ctrl-ArrowRight`,run:Ct,shift:Kt},{key:`Alt-ArrowUp`,run:kn},{key:`Shift-Alt-ArrowUp`,run:Mn},{key:`Alt-ArrowDown`,run:An},{key:`Shift-Alt-ArrowDown`,run:Nn},{key:`Mod-Alt-ArrowUp`,run:mn},{key:`Mod-Alt-ArrowDown`,run:hn},{key:`Escape`,run:gn},{key:`Mod-Enter`,run:Ln},{key:`Alt-l`,mac:`Ctrl-l`,run:dn},{key:`Mod-i`,run:fn,preventDefault:!0},{key:`Mod-[`,run:Hn},{key:`Mod-]`,run:Vn},{key:`Mod-Alt-\\`,run:Bn},{key:`Shift-Mod-k`,run:Pn},{key:`Shift-Mod-\\`,run:Rt},{key:`Mod-/`,run:ze},{key:`Alt-A`,mac:`Ctrl-A`,run:He},{key:`Ctrl-m`,mac:`Shift-Alt-m`,run:Un}].concat(Gn),qn={key:`Tab`,run:Vn,shift:Hn},Jn=typeof String.prototype.normalize==`function`?e=>e.normalize(`NFKD`):e=>e,V=class{constructor(e,t,n=0,r=e.length,i,a){this.test=a,this.value={from:0,to:0,precise:!1},this.done=!1,this.matches=[],this.buffer=``,this.bufferPos=0,this.iter=e.iterRange(n,r),this.bufferStart=n,this.normalize=i?e=>i(Jn(e)):Jn,this.query=this.normalize(t)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return ee(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let e=this.peek();if(e<0)return this.done=!0,this;let t=re(e),n=this.bufferStart+this.bufferPos;this.bufferPos+=Ce(e);let r=this.normalize(t);if(r.length)for(let e=0,i=n,a=!0;;e++){let n=r.charCodeAt(e),o=this.match(n,i,a,this.bufferPos+this.bufferStart,e==r.length-1);if(o)return this.value=o,this;if(e==r.length-1)break;a&&e<t.length&&t.charCodeAt(e)==n?i++:a=!1}}}match(e,t,n,r,i){let a=null;for(let t=0;t<this.matches.length;){let n=this.matches[t],o=!1;this.query.charCodeAt(n.index)==e&&(n.index==this.query.length-1?a={from:n.from,to:r,precise:i&&n.precise}:(n.index++,o=!0)),o?t++:this.matches.splice(t,1)}return this.query.charCodeAt(0)==e&&(this.query.length==1?a={from:t,to:r,precise:n&&i}:this.matches.push({from:t,index:1,precise:n})),a&&this.test&&!this.test(a.from,a.to,this.buffer,this.bufferStart)&&(a=null),a}};typeof Symbol<`u`&&(V.prototype[Symbol.iterator]=function(){return this});var Yn={from:-1,to:-1,match:/.*/.exec(``),precise:!0},Xn=`gm`+(/x/.unicode==null?``:`u`),Zn=class{constructor(e,t,n,r=0,i=e.length){if(this.text=e,this.to=i,this.curLine=``,this.done=!1,this.value=Yn,/\\[sWDnr]|\n|\r|\[\^/.test(t))return new er(e,t,n,r,i);this.re=new RegExp(t,Xn+(n?.ignoreCase?`i`:``)),this.test=n?.test,this.iter=e.iter();let a=e.lineAt(r);this.curLineStart=a.from,this.matchPos=H(e,r),this.getLine(this.curLineStart)}getLine(e){this.iter.next(e),this.iter.lineBreak?this.curLine=``:(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine=``:this.getLine(0)}next(){for(let e=this.matchPos-this.curLineStart;;){this.re.lastIndex=e;let t=this.matchPos<=this.to&&this.re.exec(this.curLine);if(t){let n=this.curLineStart+t.index,r=n+t[0].length;if(this.matchPos=H(this.text,r+ +(n==r)),n==this.curLineStart+this.curLine.length&&this.nextLine(),(n<r||n>this.value.to)&&(!this.test||this.test(n,r,t)))return this.value={from:n,to:r,precise:!0,match:t},this;e=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length<this.to)this.nextLine(),e=0;else return this.done=!0,this}}},Qn=new WeakMap,$n=class e{constructor(e,t){this.from=e,this.text=t}get to(){return this.from+this.text.length}static get(t,n,r){let i=Qn.get(t);if(!i||i.from>=r||i.to<=n){let i=new e(n,t.sliceString(n,r));return Qn.set(t,i),i}if(i.from==n&&i.to==r)return i;let{text:a,from:o}=i;return o>n&&(a=t.sliceString(n,o)+a,o=n),i.to<r&&(a+=t.sliceString(i.to,r)),Qn.set(t,new e(o,a)),new e(n,a.slice(n-o,r-o))}},er=class{constructor(e,t,n,r,i){this.text=e,this.to=i,this.done=!1,this.value=Yn,this.matchPos=H(e,r),this.re=new RegExp(t,Xn+(n?.ignoreCase?`i`:``)),this.test=n?.test,this.flat=$n.get(e,r,this.chunkEnd(r+5e3))}chunkEnd(e){return e>=this.to?this.to:this.text.lineAt(e).to}next(){for(;;){let e=this.re.lastIndex=this.matchPos-this.flat.from,t=this.re.exec(this.flat.text);if(t&&!t[0]&&t.index==e&&(this.re.lastIndex=e+1,t=this.re.exec(this.flat.text)),t){let e=this.flat.from+t.index,n=e+t[0].length;if((this.flat.to>=this.to||t.index+t[0].length<=this.flat.text.length-10)&&(!this.test||this.test(e,n,t)))return this.value={from:e,to:n,precise:!0,match:t},this.matchPos=H(this.text,n+ +(e==n)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=$n.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}};typeof Symbol<`u`&&(Zn.prototype[Symbol.iterator]=er.prototype[Symbol.iterator]=function(){return this});function tr(e){try{return new RegExp(e,Xn),!0}catch{return!1}}function H(e,t){if(t>=e.length)return t;let n=e.lineAt(t),r;for(;t<n.to&&(r=n.text.charCodeAt(t-n.from))>=56320&&r<57344;)t++;return t}var nr=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:i}=ce(e,{label:t.phrase(`Go to line`),input:{type:`text`,name:`line`,value:n},focus:!0,submitLabel:t.phrase(`go`)});return i.then(n=>{let i=n&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(n.elements.line.value);if(!i){e.dispatch({effects:r});return}let o=t.doc.lineAt(t.selection.main.head),[,s,c,l,u]=i,d=l?+l.slice(1):0,f=c?+c:o.number;if(c&&u){let e=f/100;s&&(e=e*(s==`-`?-1:1)+o.number/t.doc.lines),f=Math.round(t.doc.lines*e)}else c&&s&&(f=f*(s==`-`?-1:1)+o.number);let p=t.doc.line(Math.max(1,Math.min(t.doc.lines,f))),m=a.cursor(p.from+Math.max(0,Math.min(d,p.length)));e.dispatch({effects:[r,g.scrollIntoView(m.from,{y:`center`})],selection:m})}),!0},rr={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},ir=m.define({combine(e){return n(e,rr,{highlightWordAroundCursor:(e,t)=>e||t,minSelectionLength:Math.min,maxMatches:Math.min})}});function ar(e){let t=[dr,ur];return e&&t.push(ir.of(e)),t}var or=_.mark({class:`cm-selectionMatch`}),sr=_.mark({class:`cm-selectionMatch cm-selectionMatch-main`});function cr(e,t,n,r){return(n==0||e(t.sliceDoc(n-1,n))!=v.Word)&&(r==t.doc.length||e(t.sliceDoc(r,r+1))!=v.Word)}function lr(e,t,n,r){return e(t.sliceDoc(n,n+1))==v.Word&&e(t.sliceDoc(r-1,r))==v.Word}var ur=le.fromClass(class{constructor(e){this.decorations=this.getDeco(e)}update(e){(e.selectionSet||e.docChanged||e.viewportChanged)&&(this.decorations=this.getDeco(e.view))}getDeco(e){let t=e.state.facet(ir),{state:n}=e,r=n.selection;if(r.ranges.length>1)return _.none;let i=r.main,a,o=null;if(i.empty){if(!t.highlightWordAroundCursor)return _.none;let e=n.wordAt(i.head);if(!e)return _.none;o=n.charCategorizer(i.head),a=n.sliceDoc(e.from,e.to)}else{let e=i.to-i.from;if(e<t.minSelectionLength||e>200)return _.none;if(t.wholeWords){if(a=n.sliceDoc(i.from,i.to),o=n.charCategorizer(i.head),!(cr(o,n,i.from,i.to)&&lr(o,n,i.from,i.to)))return _.none}else if(a=n.sliceDoc(i.from,i.to),!a)return _.none}let s=[];for(let r of e.visibleRanges){let e=new V(n.doc,a,r.from,r.to);for(;!e.next().done;){let{from:r,to:a}=e.value;if((!o||cr(o,n,r,a))&&(i.empty&&r<=i.from&&a>=i.to?s.push(sr.range(r,a)):(r>=i.to||a<=i.from)&&s.push(or.range(r,a)),s.length>t.maxMatches))return _.none}}return _.set(s)}},{decorations:e=>e.decorations}),dr=g.baseTheme({".cm-selectionMatch":{backgroundColor:`#99ff7780`},".cm-searchMatch .cm-selectionMatch":{backgroundColor:`transparent`}}),fr=({state:e,dispatch:t})=>{let{selection:n}=e,r=a.create(n.ranges.map(t=>e.wordAt(t.head)||a.cursor(t.head)),n.mainIndex);return!r.eq(n)&&(t(e.update({selection:r})),!0)};function pr(e,t){let{main:n,ranges:r}=e.selection,i=e.wordAt(n.head),a=i&&i.from==n.from&&i.to==n.to;for(let n=!1,i=new V(e.doc,t,r[r.length-1].to);;)if(i.next(),i.done){if(n)return null;i=new V(e.doc,t,0,Math.max(0,r[r.length-1].from-1)),n=!0}else{if(n&&r.some(e=>e.from==i.value.from))continue;if(a){let t=e.wordAt(i.value.from);if(!t||t.from!=i.value.from||t.to!=i.value.to)continue}return i.value}}var mr=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(e=>e.from===e.to))return fr({state:e,dispatch:t});let r=e.sliceDoc(n[0].from,n[0].to);if(e.selection.ranges.some(t=>e.sliceDoc(t.from,t.to)!=r))return!1;let i=pr(e,r);return i?(t(e.update({selection:e.selection.addRange(a.range(i.from,i.to),!1),effects:g.scrollIntoView(i.to)})),!0):!1},U=m.define({combine(e){return n(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:e=>new Br(e),scrollToMatch:e=>g.scrollIntoView(e)})}});function hr(e){return e?[U.of(e),Gr]:Gr}var gr=class{constructor(e){this.search=e.search,this.caseSensitive=!!e.caseSensitive,this.literal=!!e.literal,this.regexp=!!e.regexp,this.replace=e.replace||``,this.valid=!!this.search&&(!this.regexp||tr(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!e.wholeWord,this.test=e.test}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,(e,t)=>t==`n`?`
2
2
  `:t==`r`?`\r`:t==`t`?` `:`\\`)}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord&&this.test==e.test}create(){return this.regexp?new Cr(this):new br(this)}getCursor(e,t=0,n){let r=e.doc?e:i.create({doc:e});return n??=r.doc.length,this.regexp?G(this,r,t,n):W(this,r,t,n)}},_r=class{constructor(e){this.spec=e}};function vr(e,t,n){return(r,i,a,o)=>n&&!n(r,i,a,o)?!1:e(r>=o&&i<=o+a.length?a.slice(r-o,i-o):t.doc.sliceString(r,i),t,r,i)}function W(e,t,n,r){let i;return e.wholeWord&&(i=yr(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(i=vr(e.test,t,i)),new V(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:e=>e.toLowerCase(),i)}function yr(e,t){return(n,r,i,a)=>((a>n||a+i.length<r)&&(a=Math.max(0,n-2),i=e.sliceString(a,Math.min(e.length,r+2))),(t(K(i,n-a))!=v.Word||t(q(i,n-a))!=v.Word)&&(t(q(i,r-a))!=v.Word||t(K(i,r-a))!=v.Word))}var br=class extends _r{constructor(e){super(e)}nextMatch(e,t,n){let r=W(this.spec,e,n,e.doc.length).nextOverlapping();if(r.done){let n=Math.min(e.doc.length,t+this.spec.unquoted.length);r=W(this.spec,e,0,n).nextOverlapping()}return r.done||r.value.from==t&&r.value.to==n?null:r.value}prevMatchInRange(e,t,n){for(let r=n;;){let n=Math.max(t,r-1e4-this.spec.unquoted.length),i=W(this.spec,e,n,r),a=null;for(;!i.nextOverlapping().done;)a=i.value;if(a)return a;if(n==t)return null;r-=1e4}}prevMatch(e,t,n){let r=this.prevMatchInRange(e,0,t);return r||=this.prevMatchInRange(e,Math.max(0,n-this.spec.unquoted.length),e.doc.length),r&&(r.from!=t||r.to!=n)?r:null}getReplacement(e){return this.spec.unquote(this.spec.replace)}matchAll(e,t){let n=W(this.spec,e,0,e.doc.length),r=[];for(;!n.next().done;){if(r.length>=t)return null;r.push(n.value)}return r}highlight(e,t,n,r){let i=W(this.spec,e,Math.max(0,t-this.spec.unquoted.length),Math.min(n+this.spec.unquoted.length,e.doc.length));for(;!i.next().done;)r(i.value.from,i.value.to)}};function xr(e,t,n){return(r,i,a)=>(!n||n(r,i,a))&&e(a[0],t,r,i)}function G(e,t,n,r){let i;return e.wholeWord&&(i=Sr(t.charCategorizer(t.selection.main.head))),e.test&&(i=xr(e.test,t,i)),new Zn(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:i},n,r)}function K(e,t){return e.slice(c(e,t,!1),t)}function q(e,t){return e.slice(t,c(e,t))}function Sr(e){return(t,n,r)=>!r[0].length||(e(K(r.input,r.index))!=v.Word||e(q(r.input,r.index))!=v.Word)&&(e(q(r.input,r.index+r[0].length))!=v.Word||e(K(r.input,r.index+r[0].length))!=v.Word)}var Cr=class extends _r{nextMatch(e,t,n){let r=G(this.spec,e,n,e.doc.length).next();return r.done&&(r=G(this.spec,e,0,t).next()),r.done?null:r.value}prevMatchInRange(e,t,n){for(let r=1;;r++){let i=Math.max(t,n-r*1e4),a=G(this.spec,e,i,n),o=null;for(;!a.next().done;)o=a.value;if(o&&(i==t||o.from>i+10))return o;if(i==t)return null}}prevMatch(e,t,n){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,n,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(t,n)=>{if(n==`&`)return e.match[0];if(n==`$`)return`$`;for(let t=n.length;t>0;t--){let r=+n.slice(0,t);if(r>0&&r<e.match.length)return e.match[r]+n.slice(t)}return t})}matchAll(e,t){let n=G(this.spec,e,0,e.doc.length),r=[];for(;!n.next().done;){if(r.length>=t)return null;r.push(n.value)}return r}highlight(e,t,n,r){let i=G(this.spec,e,Math.max(0,t-250),Math.min(n+250,e.doc.length));for(;!i.next().done;)r(i.value.from,i.value.to)}},J=h.define(),wr=h.define(),Y=o.define({create(e){return new Tr(Pr(e).create(),null)},update(e,t){for(let n of t.effects)n.is(J)?e=new Tr(n.value.create(),e.panel):n.is(wr)&&(e=new Tr(e.query,n.value?Nr:null));return e},provide:e=>xe.from(e,e=>e.panel)}),Tr=class{constructor(e,t){this.query=e,this.panel=t}},Er=_.mark({class:`cm-searchMatch`}),Dr=_.mark({class:`cm-searchMatch cm-searchMatch-selected`}),Or=le.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Y))}update(e){let t=e.state.field(Y);(t!=e.startState.field(Y)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return _.none;let{view:n}=this,r=new p;for(let t=0,i=n.visibleRanges,a=i.length;t<a;t++){let{from:o,to:s}=i[t];for(;t<a-1&&s>i[t+1].from-500;)s=i[++t].to;e.highlight(n.state,o,s,(e,t)=>{let i=n.state.selection.ranges.some(n=>n.from==e&&n.to==t);r.add(e,t,i?Dr:Er)})}return r.finish()}},{decorations:e=>e.decorations});function X(e){return t=>{let n=t.state.field(Y,!1);return n&&n.query.spec.valid?e(t,n):Lr(t)}}var Z=X((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let i=a.single(r.from,r.to),o=e.state.facet(U);return e.dispatch({selection:i,effects:[Ur(e,r),o.scrollToMatch(i.main,e)],userEvent:`select.search`}),Ir(e),!0}),Q=X((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,i=t.prevMatch(n,r,r);if(!i)return!1;let o=a.single(i.from,i.to),s=e.state.facet(U);return e.dispatch({selection:o,effects:[Ur(e,i),s.scrollToMatch(o.main,e)],userEvent:`select.search`}),Ir(e),!0}),kr=X((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:a.create(n.map(e=>a.range(e.from,e.to))),userEvent:`select.search.matches`}),!0)}),Ar=({state:e,dispatch:t})=>{let n=e.selection;if(n.ranges.length>1||n.main.empty)return!1;let{from:r,to:i}=n.main,o=[],s=0;for(let t=new V(e.doc,e.sliceDoc(r,i));!t.next().done;){if(o.length>1e3)return!1;t.value.from==r&&(s=o.length),o.push(a.range(t.value.from,t.value.to))}return t(e.update({selection:a.create(o,s),userEvent:`select.search.matches`})),!0},jr=X((e,{query:t})=>{let{state:n}=e,{from:r,to:i}=n.selection.main;if(n.readOnly)return!1;let o=t.nextMatch(n,r,r);if(!o)return!1;let s=o,c=[],l,u,d=[];s.precise?s.from==r&&s.to==i&&(u=n.toText(t.getReplacement(s)),c.push({from:s.from,to:s.to,insert:u}),s=t.nextMatch(n,s.from,s.to),d.push(g.announce.of(n.phrase(`replaced match on line $`,n.doc.lineAt(r).number)+`.`))):s=t.nextMatch(n,s.from,s.to);let f=e.state.changes(c);return s&&(l=a.single(s.from,s.to).map(f),d.push(Ur(e,s)),d.push(n.facet(U).scrollToMatch(l.main,e))),e.dispatch({changes:f,selection:l,effects:d,userEvent:`input.replace`}),!0}),Mr=X((e,{query:t})=>{if(e.state.readOnly)return!1;let n=[];for(let r of t.matchAll(e.state,1e9)){let{from:e,to:i,precise:a}=r;a&&n.push({from:e,to:i,insert:t.getReplacement(r)})}if(!n.length)return!1;let r=e.state.phrase(`replaced $ matches`,n.length)+`.`;return e.dispatch({changes:n,effects:g.announce.of(r),userEvent:`input.replace.all`}),!0});function Nr(e){return e.state.facet(U).createPanel(e)}function Pr(e,t){let n=e.selection.main,r=n.empty||n.to>n.from+100?``:e.sliceDoc(n.from,n.to);if(t&&!r)return t;let i=e.facet(U);return new gr({search:t?.literal??i.literal?r:r.replace(/\n/g,`\\n`),caseSensitive:t?.caseSensitive??i.caseSensitive,literal:t?.literal??i.literal,regexp:t?.regexp??i.regexp,wholeWord:t?.wholeWord??i.wholeWord})}function Fr(e){let t=ue(e,Nr);return t&&t.dom.querySelector(`[main-field]`)}function Ir(e){let t=Fr(e);t&&t==e.root.activeElement&&t.select()}var Lr=e=>{let t=e.state.field(Y,!1);if(t&&t.panel){let n=Fr(e);if(n&&n!=e.root.activeElement){let r=Pr(e.state,t.query.spec);r.valid&&e.dispatch({effects:J.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[wr.of(!0),t?J.of(Pr(e.state,t.query.spec)):h.appendConfig.of(Gr)]});return!0},Rr=e=>{let t=e.state.field(Y,!1);if(!t||!t.panel)return!1;let n=ue(e,Nr);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:wr.of(!1)}),!0},zr=[{key:`Mod-f`,run:Lr,scope:`editor search-panel`},{key:`F3`,run:Z,shift:Q,scope:`editor search-panel`,preventDefault:!0},{key:`Mod-g`,run:Z,shift:Q,scope:`editor search-panel`,preventDefault:!0},{key:`Escape`,run:Rr,scope:`editor search-panel`},{key:`Mod-Shift-l`,run:Ar},{key:`Mod-Alt-g`,run:nr},{key:`Mod-d`,run:mr,preventDefault:!0}],Br=class{constructor(e){this.view=e;let t=this.query=e.state.field(Y).query.spec;this.commit=this.commit.bind(this),this.searchField=y(`input`,{value:t.search,placeholder:$(e,`Find`),"aria-label":$(e,`Find`),class:`cm-textfield`,name:`search`,form:``,"main-field":`true`,onchange:this.commit,onkeyup:this.commit}),this.replaceField=y(`input`,{value:t.replace,placeholder:$(e,`Replace`),"aria-label":$(e,`Replace`),class:`cm-textfield`,name:`replace`,form:``,onchange:this.commit,onkeyup:this.commit}),this.caseField=y(`input`,{type:`checkbox`,name:`case`,form:``,checked:t.caseSensitive,onchange:this.commit}),this.reField=y(`input`,{type:`checkbox`,name:`re`,form:``,checked:t.regexp,onchange:this.commit}),this.wordField=y(`input`,{type:`checkbox`,name:`word`,form:``,checked:t.wholeWord,onchange:this.commit});function n(e,t,n){return y(`button`,{class:`cm-button`,name:e,onclick:t,type:`button`},n)}this.dom=y(`div`,{onkeydown:e=>this.keydown(e),class:`cm-search`},[this.searchField,n(`next`,()=>Z(e),[$(e,`next`)]),n(`prev`,()=>Q(e),[$(e,`previous`)]),n(`select`,()=>kr(e),[$(e,`all`)]),y(`label`,null,[this.caseField,$(e,`match case`)]),y(`label`,null,[this.reField,$(e,`regexp`)]),y(`label`,null,[this.wordField,$(e,`by word`)]),...e.state.readOnly?[]:[y(`br`),this.replaceField,n(`replace`,()=>jr(e),[$(e,`replace`)]),n(`replaceAll`,()=>Mr(e),[$(e,`replace all`)])],y(`button`,{name:`close`,onclick:()=>Rr(e),"aria-label":$(e,`close`),type:`button`},[`×`])])}commit(){let e=new gr({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});e.eq(this.query)||(this.query=e,this.view.dispatch({effects:J.of(e)}))}keydown(e){pe(this.view,e,`search-panel`)?e.preventDefault():e.keyCode==13&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?Q:Z)(this.view)):e.keyCode==13&&e.target==this.replaceField&&(e.preventDefault(),jr(this.view))}update(e){for(let t of e.transactions)for(let e of t.effects)e.is(J)&&!e.value.eq(this.query)&&this.setQuery(e.value)}setQuery(e){this.query=e,this.searchField.value=e.search,this.replaceField.value=e.replace,this.caseField.checked=e.caseSensitive,this.reField.checked=e.regexp,this.wordField.checked=e.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(U).top}};function $(e,t){return e.state.phrase(t)}var Vr=30,Hr=/[\s\.,:;?!]/;function Ur(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),i=e.state.doc.lineAt(n).to,a=Math.max(r.from,t-Vr),o=Math.min(i,n+Vr),s=e.state.sliceDoc(a,o);if(a!=r.from){for(let e=0;e<Vr;e++)if(!Hr.test(s[e+1])&&Hr.test(s[e])){s=s.slice(e);break}}if(o!=i){for(let e=s.length-1;e>s.length-Vr;e--)if(!Hr.test(s[e-1])&&Hr.test(s[e])){s=s.slice(0,e);break}}return g.announce.of(`${e.state.phrase(`current match`)}. ${s} ${e.state.phrase(`on line`)} ${r.number}.`)}var Wr=g.baseTheme({".cm-panel.cm-search":{padding:`2px 6px 4px`,position:`relative`,"& [name=close]":{position:`absolute`,top:`0`,right:`4px`,backgroundColor:`inherit`,border:`none`,font:`inherit`,padding:0,margin:0},"& input, & button, & label":{margin:`.2em .6em .2em 0`},"& input[type=checkbox]":{marginRight:`.2em`},"& label":{fontSize:`80%`,whiteSpace:`pre`}},"&light .cm-searchMatch":{backgroundColor:`#ffff0054`},"&dark .cm-searchMatch":{backgroundColor:`#00ffff8a`},"&light .cm-searchMatch-selected":{backgroundColor:`#ff6a0054`},"&dark .cm-searchMatch-selected":{backgroundColor:`#ff00ff8a`}}),Gr=[Y,t.low(Or),Wr];function Kr(e,t,n){let r=Math.min(t,n),i=Math.max(t,n);return{text:e.state.sliceDoc(r,i),from:r,to:i,startLine:e.state.doc.lineAt(r).number,endLine:e.state.doc.lineAt(i).number}}function qr(e,t){let n=e.posAtCoords({x:t.left,y:t.top}),r=e.posAtCoords({x:t.right,y:t.bottom});return n===null||r===null?null:Kr(e,n,r)}var Jr=g.theme(ae),Yr=Te.define([{tag:b.comment,...s.comment},{tag:b.keyword,...s.keyword},{tag:[b.atom,b.bool,b.null,b.self],...s.constant},{tag:b.number,...s.literal},{tag:[b.string,b.special(b.string),b.character],...s.string},{tag:b.regexp,...s.regexp},{tag:b.operator,...s.operator},{tag:b.punctuation,...s.punctuation},{tag:b.variableName,...s.variable},{tag:b.propertyName,...s.property},{tag:[b.function(b.variableName),b.function(b.propertyName)],...s.callable},{tag:[b.typeName,b.className,b.namespace],...s.type},{tag:b.tagName,...s.tag},{tag:b.attributeName,...s.attribute},{tag:[b.meta,b.processingInstruction],...s.meta},{tag:b.heading,...s.heading},{tag:[b.link,b.url],...s.link},{tag:b.emphasis,...s.emphasis},{tag:b.strong,...s.strong},{tag:b.strikethrough,...s.strikethrough},{tag:b.invalid,...s.invalid}]),Xr=h.define(),Zr=o.define({create:()=>_.none,update:(e,t)=>{let n=e.map(t.changes);for(let e of t.effects)e.is(Xr)&&(n=e.value);return n},provide:e=>g.decorations.from(e)}),Qr=h.define(),$r=o.define({create:()=>_.none,update:(e,t)=>{let n=e.map(t.changes);for(let e of t.effects)e.is(Qr)&&(n=e.value);return n},provide:e=>g.decorations.from(e)}),ei=class extends ge{label;constructor(e){super(),this.label=e}eq(e){return e.label===this.label}toDOM(){let e=document.createElement(`span`);return e.className=`cm-marked-region-label`,e.dataset.authorRegionLabel=this.label,e.textContent=this.label,e}},ti=g.baseTheme({".cm-marked-region":{backgroundColor:`var(--doom-tint-yellow)`,borderBottom:`1px solid var(--doom-edge-yellow)`},".cm-marked-region-label":{display:`inline-flex`,alignItems:`center`,justifyContent:`center`,minWidth:`16px`,height:`16px`,marginRight:`4px`,borderRadius:`999px`,backgroundColor:`var(--doom-yellow)`,color:`var(--doom-deep)`,fontSize:`9px`,fontWeight:`700`,lineHeight:`1`,verticalAlign:`text-bottom`}}),ni=[_e(),de(),Oe(),be(),ye(),me(),Me(),De(),et(),hr({top:!0}),ar(),fe.of([...Kn,...mt,...zr,...ke,qn]),Fe(Yr),Zr,$r,ti,Jr];function ri({value:e,path:t,readOnly:n=!1,lineWrapping:r=!0,className:a,onChange:o,onSelect:s,controllerRef:c,"data-testid":l}){let u=(0,C.useRef)(null),f=(0,C.useRef)(null),p=(0,C.useRef)({onChange:o,onSelect:s}),m=(0,C.useRef)(e),h=(0,C.useRef)({language:new ne,readOnly:new ne,wrapping:new ne});return(0,C.useEffect)(()=>{p.current={onChange:o,onSelect:s}}),(0,C.useLayoutEffect)(()=>{let e=u.current;if(e===null)return;let{language:t,readOnly:n,wrapping:r}=h.current,a=new g({parent:e,state:i.create({doc:m.current,extensions:[...ni,t.of([]),n.of([]),r.of([]),g.updateListener.of(e=>{if(e.docChanged&&p.current.onChange?.(e.state.doc.toString()),!e.selectionSet&&!e.docChanged)return;let t=p.current.onSelect;if(t===void 0)return;let n=e.state.selection.main;t(Kr(e.view,n.from,n.to))})]})});return f.current=a,()=>{a.destroy(),f.current=null}},[]),(0,C.useImperativeHandle)(c,()=>({focus:()=>f.current?.focus(),revealAndSelect:e=>{let t=f.current;if(t===null)return;let[n]=S(t.state.doc.length,[e]);n!==void 0&&t.dispatch({selection:{anchor:n.from,head:n.to},effects:g.scrollIntoView(n.from,{y:`center`})})},applyEdits:e=>{let t=f.current;t!==null&&e.length!==0&&t.dispatch({changes:Le(t.state.doc.length,e)})},setClosedRanges:e=>{let t=f.current;if(t===null)return;let n=S(t.state.doc.length,e).map(e=>e.from===e.to?_.line({attributes:{class:`cm-closed-tone`,"data-tone":`closed`}}).range(t.state.doc.lineAt(e.from).from):_.mark({class:`cm-closed-tone`,attributes:{"data-tone":`closed`}}).range(e.from,e.to));t.dispatch({effects:Xr.of(_.set(n))})},setMarkedRanges:e=>{let t=f.current;if(t===null)return;let n=e.flatMap(e=>{let[n]=S(t.state.doc.length,[e]);return n===void 0||n.from===n.to?[]:[_.widget({widget:new ei(e.label),side:-1}).range(n.from),_.mark({class:`cm-marked-region`,attributes:{"data-author-region":e.label}}).range(n.from,n.to)]});t.dispatch({effects:Qr.of(_.set(n,!0))})},resolveViewportRegion:e=>{let t=f.current;return t===null?null:qr(t,e)}}),[]),(0,C.useEffect)(()=>{let t=f.current;t!==null&&t.state.doc.toString()!==e&&t.dispatch({changes:{from:0,to:t.state.doc.length,insert:e}})},[e]),(0,C.useEffect)(()=>{f.current?.dispatch({effects:h.current.readOnly.reconfigure([i.readOnly.of(n),g.editable.of(!n)])})},[n]),(0,C.useEffect)(()=>{f.current?.dispatch({effects:h.current.wrapping.reconfigure(r?g.lineWrapping:[])})},[r]),(0,C.useEffect)(()=>{let e=t===void 0?void 0:ve(t),{language:n}=h.current;if(e===void 0){f.current?.dispatch({effects:n.reconfigure([])});return}let r=!1;return d(e).then(e=>{r||f.current?.dispatch({effects:n.reconfigure(e)})}).catch(()=>{r||f.current?.dispatch({effects:n.reconfigure([])})}),()=>{r=!0}},[t]),(0,Re.jsx)(`div`,{ref:u,"data-testid":l,className:se(`min-h-0 overflow-hidden`,a)})}export{ri as CodeEditorView};
3
- //# sourceMappingURL=CodeEditorView-Vcq41fvN.js.map
3
+ //# sourceMappingURL=CodeEditorView-CsSmzevS.js.map