@inkeep/open-knowledge 0.68.9 → 0.68.11-beta.0

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 (102) hide show
  1. package/dist/{acp-harness-probe-D4fYUyLf.mjs → acp-harness-probe-DaYXqGxg.mjs} +2 -2
  2. package/dist/assets/skills/project/SKILL.md +3 -3
  3. package/dist/{chunk-KX3P26DQ-KA7oOKfS.mjs → chunk-KX3P26DQ-Bp2m2ndV.mjs} +2 -2
  4. package/dist/cli.mjs +6 -6
  5. package/dist/constants-jyYwGmDC.mjs +2 -0
  6. package/dist/index.d.mts +1 -1
  7. package/dist/index.mjs +50 -50
  8. package/dist/init-CBEFRP85.mjs +1 -0
  9. package/dist/{init-Q6vQQIvo.mjs → init-_7R63fwz.mjs} +3 -3
  10. package/dist/{launch-json-removal-BLsICseK.mjs → launch-json-removal-B28FsoE2.mjs} +2 -2
  11. package/dist/loader-Bz5cS92c.mjs +1 -0
  12. package/dist/{loader-V75vJygF.mjs → loader-C4UW1MW5.mjs} +2 -2
  13. package/dist/{open-browser-DmtCotYQ.mjs → open-browser-H-QKQd10.mjs} +2 -2
  14. package/dist/preview-26pLGThq.mjs +1 -0
  15. package/dist/{preview-rS6YMAKu.mjs → preview-DKtYHQbM.mjs} +2 -2
  16. package/dist/public/assets/{ActivityModeContent-iAy7Htyr.js → ActivityModeContent-C9Z839EN.js} +1 -1
  17. package/dist/public/assets/{AddPropertiesButton-BKA885SM.js → AddPropertiesButton-DSQKtGW9.js} +2 -2
  18. package/dist/public/assets/{AgentDiffPane-C7KIvUPF.js → AgentDiffPane-Cu3m0Lib.js} +1 -1
  19. package/dist/public/assets/{BugReportHistoryDialog-Cdci6g1O.js → BugReportHistoryDialog-BO92hFGg.js} +1 -1
  20. package/dist/public/assets/{CodeMirrorPropInput-cqsfRNDV.js → CodeMirrorPropInput-CRa8tGX-.js} +1 -1
  21. package/dist/public/assets/{ConsentDialogBody-BHbzcNb7.js → ConsentDialogBody-Bu8u9p1a.js} +2 -2
  22. package/dist/public/assets/{DocumentContext-DOMEoUbL.js → DocumentContext-BdZiErvh.js} +1 -1
  23. package/dist/public/assets/{EditorModeToggle-cEaO7U1B.js → EditorModeToggle-DYldyVnC.js} +1 -1
  24. package/dist/public/assets/{EnableSyncConfirmDialog-CxKyhSRR.js → EnableSyncConfirmDialog-N_l5NwWg.js} +1 -1
  25. package/dist/public/assets/{ExcalidrawDocEditor-Bw1wZL5r.js → ExcalidrawDocEditor-CFg6aGVN.js} +1 -1
  26. package/dist/public/assets/FeedbackForm-CnwouVSg.js +1 -0
  27. package/dist/public/assets/{ImportSkillDialog-BHRZuf__.js → ImportSkillDialog-DOKtVFqO.js} +1 -1
  28. package/dist/public/assets/{LintConfigEditor-DaQG-dlP.js → LintConfigEditor-SzAKIf-P.js} +1 -1
  29. package/dist/public/assets/{ManagedArtifactProperties-BDuoxjvO.js → ManagedArtifactProperties-8E5SQSnI.js} +1 -1
  30. package/dist/public/assets/ManagedArtifactProperties-DyQXtUCs.js +1 -0
  31. package/dist/public/assets/{McpConsentDialogBody-CS-c374d.js → McpConsentDialogBody-D3q7WAev.js} +1 -1
  32. package/dist/public/assets/{Mermaid-mq736Zb_.js → Mermaid-Cw1EnMJu.js} +1 -1
  33. package/dist/public/assets/{MermaidDocEditor-DudmyU3i.js → MermaidDocEditor-C-qlUZje.js} +1 -1
  34. package/dist/public/assets/{PropertyDisplayRow-C9iyg7W9.js → PropertyDisplayRow-CBiQBnOL.js} +1 -1
  35. package/dist/public/assets/{ReportBugDialogBody-t1LnS7cf.js → ReportBugDialogBody-B4Ph81pw.js} +2 -2
  36. package/dist/public/assets/{ReportBugMenuTrigger-BaIKHhOn.js → ReportBugMenuTrigger-D7aC0OiR.js} +2 -2
  37. package/dist/public/assets/{SchemaConfigEditor-BLIfeCsm.js → SchemaConfigEditor-DGBRJY7Q.js} +1 -1
  38. package/dist/public/assets/{SessionsHost-DuAZF3Zj.js → SessionsHost-CrnQRViT.js} +2 -2
  39. package/dist/public/assets/{SettingsDialogBody-txHlPNWp.js → SettingsDialogBody-DnEGrTMq.js} +1 -1
  40. package/dist/public/assets/{ShareBranchSwitchDialog-CgntPdis.js → ShareBranchSwitchDialog-Cgkl3a5v.js} +1 -1
  41. package/dist/public/assets/{ShareReceiveDialog-C5Rig4O-.js → ShareReceiveDialog-6TxrHOIU.js} +1 -1
  42. package/dist/public/assets/{ShareReceiveMissDialog-D6-ck0Uu.js → ShareReceiveMissDialog-BCkm-E10.js} +1 -1
  43. package/dist/public/assets/{SkillForkDialog-D2HU42pf.js → SkillForkDialog-Bhq9zhtY.js} +1 -1
  44. package/dist/public/assets/{SkillInstallMenu-Bcy54X0U.js → SkillInstallMenu-D3KWfbhA.js} +1 -1
  45. package/dist/public/assets/{SkillOriginInline-CwgwWmps.js → SkillOriginInline-CaEMp81T.js} +2 -2
  46. package/dist/public/assets/{SkillToolbarControls-B8Ab7ngc.js → SkillToolbarControls-tpuUyOLu.js} +1 -1
  47. package/dist/public/assets/{SkillUpdateConflictDialog-AerOBYmk.js → SkillUpdateConflictDialog-Cbj5JNXp.js} +1 -1
  48. package/dist/public/assets/SlidesToolbarControls-DWqUzkgL.js +1 -0
  49. package/dist/public/assets/{SourceEditor-CrOhJB84.js → SourceEditor-D_IY9GyQ.js} +1 -1
  50. package/dist/public/assets/{TerminalWindowApp-BP8AoRew.js → TerminalWindowApp-CwExuljm.js} +1 -1
  51. package/dist/public/assets/{TextDocEditor-BOdJgOXT.js → TextDocEditor-DAcD7hS1.js} +1 -1
  52. package/dist/public/assets/{ThreadView-BsHCDmQB.js → ThreadView-Dv-MJgLn.js} +1 -1
  53. package/dist/public/assets/{TimelineDiffPane-DDVqWMSH.js → TimelineDiffPane-G1nycx_c.js} +1 -1
  54. package/dist/public/assets/{agent-diff-store-CQtqUq4i.js → agent-diff-store-Bln_lxtD.js} +1 -1
  55. package/dist/public/assets/{alert-dialog-BFfs04J5.js → alert-dialog-DLAYZZMu.js} +2 -2
  56. package/dist/public/assets/{auth-state-cache-CgquP1B2.js → auth-state-cache-BLGrQ86G.js} +4 -4
  57. package/dist/public/assets/client-version-CXZnsz8b.js +1 -0
  58. package/dist/public/assets/{comment-chips-CNyMXpWs.js → comment-chips-Bm8WWDT7.js} +1 -1
  59. package/dist/public/assets/{config-provider-qLyaitI2.js → config-provider-BvIhxk0G.js} +1 -1
  60. package/dist/public/assets/{dialog-CCHt-oLh.js → dialog-_kqu_91M.js} +1 -1
  61. package/dist/public/assets/{globals-ByagJMEb.css → globals-DeOHYo0q.css} +1 -1
  62. package/dist/public/assets/{index-r_qRX3GR.js → index-BLB78i4B.js} +9 -9
  63. package/dist/public/assets/{pending-receive-nav-store-BwS0HcBd.js → pending-receive-nav-store-BtQaH8Ow.js} +1 -1
  64. package/dist/public/assets/{progress-CzJ7mESr.js → progress-DKwbAv_d.js} +1 -1
  65. package/dist/public/assets/{selection-context-DI5wlbAC.js → selection-context-BBTm-UVn.js} +1 -1
  66. package/dist/public/assets/{src-CgbeuLkc.js → src-BBEwVksN.js} +1 -1
  67. package/dist/public/assets/{telemetry-impl-CPT6yQPK.js → telemetry-impl-B_63zFxn.js} +1 -1
  68. package/dist/public/assets/{telemetry-startup-BmgX6zXI.js → telemetry-startup-BMrCBn-y.js} +1 -1
  69. package/dist/public/assets/{typing-burst-detector-CFwuUzqv.js → typing-burst-detector-D-RxXAZt.js} +1 -1
  70. package/dist/public/assets/{uninstall-DAfbja6D.js → uninstall-C645M4Nr.js} +1 -1
  71. package/dist/public/assets/{use-activity-panel-DDXrfY-K.js → use-activity-panel-TaOc5fsr.js} +1 -1
  72. package/dist/public/assets/{use-open-skill--yVdWHLf.js → use-open-skill-BfikAHGm.js} +1 -1
  73. package/dist/public/assets/{use-terminal-enabled-DWnQ-hY2.js → use-terminal-enabled-f6uI67oZ.js} +1 -1
  74. package/dist/public/assets/{use-timeline-entry-diff-BLDu0nkY.js → use-timeline-entry-diff-DEsOnT79.js} +1 -1
  75. package/dist/public/index.html +25 -25
  76. package/dist/public/uninstall.html +3 -3
  77. package/dist/{repair-launch-json-CGyPEMBX.mjs → repair-launch-json-O0pvONvJ.mjs} +2 -2
  78. package/dist/{repair-mcp-configs-Do0L2PKW.mjs → repair-mcp-configs-BFtKKOXF.mjs} +2 -2
  79. package/dist/repair-skills-BkLHvKTk.mjs +1 -0
  80. package/dist/{repair-skills-TrS-7N9q.mjs → repair-skills-zu7vM_05.mjs} +2 -2
  81. package/dist/{resolve-project-root-CLNohNKz.mjs → resolve-project-root-dt8lYC9W.mjs} +2 -2
  82. package/dist/{skill-teardown-DvGC-0MI.mjs → skill-teardown-DUZd_juy.mjs} +2 -2
  83. package/dist/{src-C4D-_N3T.mjs → src-CT7Wk-MG.mjs} +1 -1
  84. package/dist/{src-Dim30w_Y.mjs → src-D5pqfubu.mjs} +2 -2
  85. package/dist/src-e2udu2Rw.mjs +2045 -0
  86. package/dist/src-y6vbbp7M.mjs +1 -0
  87. package/dist/start-BoiJ1XmS.mjs +1 -0
  88. package/dist/{start-CdH7_XQz.mjs → start-DET7Qj8h.mjs} +3 -3
  89. package/package.json +4 -4
  90. package/dist/constants-IMtjOwCu.mjs +0 -2
  91. package/dist/init-DCwOjemd.mjs +0 -1
  92. package/dist/loader-C2hBS-vl.mjs +0 -1
  93. package/dist/preview-gyu5corn.mjs +0 -1
  94. package/dist/public/assets/FeedbackForm-D0S2l1ev.js +0 -1
  95. package/dist/public/assets/ManagedArtifactProperties-BpjEvg_3.js +0 -1
  96. package/dist/public/assets/SlidesToolbarControls-Dz6effyN.js +0 -1
  97. package/dist/public/assets/client-version-BEh3tGFq.js +0 -1
  98. package/dist/repair-skills-zn5HSgoM.mjs +0 -1
  99. package/dist/src-BTBVMfJ4.mjs +0 -2045
  100. package/dist/src-R2F0BHsn.mjs +0 -1
  101. package/dist/start-cQx7qTAb.mjs +0 -1
  102. /package/dist/public/assets/{globals-DIT-uAXH.js → globals--7ibIAoz.js} +0 -0
package/dist/index.mjs CHANGED
@@ -462,7 +462,10 @@ caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?
462
462
  `),F().optional().describe(`Dotted config key (e.g. "appearance.theme"). Omit to return the full merged config.`),F().optional().describe(d6),f6({value:R().describe(`Resolved config value at the requested path (or full config).`),exists:L().optional().describe('Whether the requested path resolved to a value. `false` distinguishes "path absent" from "path explicitly set to null". Always emitted — `true` on a full-config read.'),key:F().optional().describe(`Echo of the requested dotted key (absent when reading the full config).`)}),["[Requires: Hocuspocus server] Read GitHub-sync merge conflicts. Dispatches on `kind`:",``,'- `kind: "list"` — enumerate every doc currently tracked in a merge-conflict state. Returns `{ list: [{ file, detectedAt, ... }] }` (empty when none). The entry point to the resolve flow.','- `kind: "content"` — fetch the three merge stages for one `file`. Returns `{ content: { file, base, ours, theirs, shape, lifecycleStatus } }`. `ours` reflects the live Y.Text (what the human sees) when the doc is loaded server-side.',``,`**Parameters:**`,"- `kind` — `list` | `content`.",'- `file` — Required for `kind: "content"`. Relative path WITH the `.md`/`.mdx` extension (e.g. `notes/sso.md`) — git stages key on the exact path, so do NOT strip the extension.',``,"The `shape` field discriminates the conflict: `both-modified` (both sides edited), `delete-modify` (you deleted, they edited — `ours` empty), or `modify-delete` (you edited, they deleted — `theirs` empty). Use it to pick the `resolve_conflict` strategy."].join(`
463
463
  `);const qSe=[`lock`],JSe=xo([zo,_o()]),YSe=xo([F(),I(),L(),z(R()),V(F(),R()),_o()]);V(F(),YSe).superRefine((e,t)=>{for(let[n,r]of Object.entries(e))JSe.safeParse(r).success||t.addIssue({code:`custom`,path:[n],message:`invalid frontmatter value — allowed: a scalar (string | number | boolean), a scalar array, a nested object, or an array of objects; a top-level key may be null to delete it, but nested null is not allowed`})}).describe(`Metadata as a key→value map. Values may be a scalar (string | number | boolean), a scalar array, a nested object, or an array of objects. Merge-patch: include a top-level key to set it, set a top-level key to null to delete it; keys you omit are unchanged. A nested object REPLACES the existing subtree at that key (send the full subtree you want). Example: { title: "Q3 Planning", tags: ["planning"], metadata: { version: "1.0", author: "Inkeep" } }.`),H([`append`,`prepend`,`replace`]).describe(`Where content lands. replace = overwrite the whole body (default for a new doc; required for an existing doc). append / prepend = add to the end / start.`),H(gu).describe("File format for a NEW doc: `.md` (default) or `.mdx` (Markdown + JSX components). Honored only on create — an existing doc keeps its on-disk extension. Takes precedence over an extension typed into `path`."),H(pu).describe(`Level: "project" (default — a Project skill: lives in this KB wherever its folder is, shared with teammates via git) or "global" (a Global skill: lives under your user home, available in every project on this machine — not shared, not version-tracked). Pass the literal value "global" for a Global skill.`),["Delete one thing. Pass EXACTLY ONE of `document`, `folder`, `template`, `skill`, or `asset`.",``,"- `document` — Doc path(s) to delete (a single path or an array). Inbound links become redlinks. Irreversible. [Requires: Hocuspocus server]","- `folder` — Folder path to delete (recursive). [Requires: Hocuspocus server]",'- `template` — `{ path: "<folder>/<name>" }` — a template to delete (server-routed, attributed; auto-cleans empty `.ok/`). [Requires: Hocuspocus server]','- `skill` — `{ name }` deletes a whole SKILL; `{ name, files: ["references/x.md"] }` deletes specific bundle files (server-routed, attributed; auto-cleans empty `.ok/`). [Requires: Hocuspocus server]','- `asset` — `{ path: "<folder>/<file.ext>" }` — a binary asset to delete. [Requires: Hocuspocus server]',``,'Call `links({ kind: "backlinks", document })` BEFORE deleting a doc to see what links here.'].join(`
464
464
  `),`${["Edit one thing in place. Pass EXACTLY ONE of `document`, `folder`, `template`, or `skill`. Within each: a body edit (`find` + `replace`) OR a metadata patch — not both in one call.",``,"- `document` — Edit a doc [Requires: Hocuspocus server]. Body: `{ path, find, replace, occurrence? }` (occurrence = which match, 1 = first). Metadata: `{ path, frontmatter }` (merge-patch; `null` deletes a key). Body find/replace is body-only; frontmatter-intersecting finds are rejected.","- `folder` — Edit a folder (folders have no body): `{ path, frontmatter }` (merge-patch).",'- `template` — Edit a template: `{ path: "<folder>/<name>", ... }`; body `find`/`replace`/`occurrence?` or metadata `frontmatter`.',"- `skill` — Edit a SKILL: `{ name, ... }`; body `find`/`replace`/`occurrence?` OR a `description` change (a skill's only metadata leaf). Every recorded copy re-syncs from the source, so there is nothing to re-install.","- `summary` — Optional one-line user-outcome (≤80 chars) recorded in the timeline for any `document`, `folder`, `template`, or `skill` edit. Avoid secrets or PII — persisted to git history.",``,'Responses may include `structuredContent.document.warnings` — advisory entries discriminated by `kind`: `content-divergence` / `disk-edit-reconciled` (write-integrity — re-read the doc with `exec("cat <path>")`) and `mermaid-parse-error` (the edit landed but that fence will not render — fix it and re-edit).'].join(`
465
- `)}${tY()}`;var Y8;(function(e){e.EOF=`EOF`,e.NEWLINE=`NEWLINE`,e.SEMICOLON=`SEMICOLON`,e.AMP=`AMP`,e.PIPE=`PIPE`,e.PIPE_AMP=`PIPE_AMP`,e.AND_AND=`AND_AND`,e.OR_OR=`OR_OR`,e.BANG=`BANG`,e.LESS=`LESS`,e.GREAT=`GREAT`,e.DLESS=`DLESS`,e.DGREAT=`DGREAT`,e.LESSAND=`LESSAND`,e.GREATAND=`GREATAND`,e.LESSGREAT=`LESSGREAT`,e.DLESSDASH=`DLESSDASH`,e.CLOBBER=`CLOBBER`,e.TLESS=`TLESS`,e.AND_GREAT=`AND_GREAT`,e.AND_DGREAT=`AND_DGREAT`,e.LPAREN=`LPAREN`,e.RPAREN=`RPAREN`,e.LBRACE=`LBRACE`,e.RBRACE=`RBRACE`,e.DSEMI=`DSEMI`,e.SEMI_AND=`SEMI_AND`,e.SEMI_SEMI_AND=`SEMI_SEMI_AND`,e.DBRACK_START=`DBRACK_START`,e.DBRACK_END=`DBRACK_END`,e.DPAREN_START=`DPAREN_START`,e.DPAREN_END=`DPAREN_END`,e.IF=`IF`,e.THEN=`THEN`,e.ELSE=`ELSE`,e.ELIF=`ELIF`,e.FI=`FI`,e.FOR=`FOR`,e.WHILE=`WHILE`,e.UNTIL=`UNTIL`,e.DO=`DO`,e.DONE=`DONE`,e.CASE=`CASE`,e.ESAC=`ESAC`,e.IN=`IN`,e.FUNCTION=`FUNCTION`,e.SELECT=`SELECT`,e.TIME=`TIME`,e.COPROC=`COPROC`,e.WORD=`WORD`,e.NAME=`NAME`,e.NUMBER=`NUMBER`,e.ASSIGNMENT_WORD=`ASSIGNMENT_WORD`,e.FD_VARIABLE=`FD_VARIABLE`,e.COMMENT=`COMMENT`,e.HEREDOC_CONTENT=`HEREDOC_CONTENT`})(Y8||={}),new Map([[`if`,Y8.IF],[`then`,Y8.THEN],[`else`,Y8.ELSE],[`elif`,Y8.ELIF],[`fi`,Y8.FI],[`for`,Y8.FOR],[`while`,Y8.WHILE],[`until`,Y8.UNTIL],[`do`,Y8.DO],[`done`,Y8.DONE],[`case`,Y8.CASE],[`esac`,Y8.ESAC],[`in`,Y8.IN],[`function`,Y8.FUNCTION],[`select`,Y8.SELECT],[`time`,Y8.TIME],[`coproc`,Y8.COPROC]]),Y8.SEMI_SEMI_AND,Y8.TLESS,Y8.AND_DGREAT,Y8.DBRACK_START,Y8.DBRACK_END,Y8.DPAREN_START,Y8.DPAREN_END,Y8.AND_AND,Y8.OR_OR,Y8.DSEMI,Y8.SEMI_AND,Y8.PIPE_AMP,Y8.DGREAT,Y8.LESSAND,Y8.GREATAND,Y8.LESSGREAT,Y8.CLOBBER,Y8.AND_GREAT,new Map([[`|`,Y8.PIPE],[`&`,Y8.AMP],[`;`,Y8.SEMICOLON],[`(`,Y8.LPAREN],[`)`,Y8.RPAREN],[`<`,Y8.LESS],[`>`,Y8.GREAT]]),new Set([Y8.LESS,Y8.GREAT,Y8.DLESS,Y8.DGREAT,Y8.LESSAND,Y8.GREATAND,Y8.LESSGREAT,Y8.DLESSDASH,Y8.CLOBBER,Y8.TLESS,Y8.AND_GREAT,Y8.AND_DGREAT]),new Set([Y8.LESS,Y8.GREAT,Y8.DLESS,Y8.DGREAT,Y8.LESSAND,Y8.GREATAND,Y8.LESSGREAT,Y8.DLESSDASH,Y8.CLOBBER,Y8.TLESS]),new Set([Y8.LESS,Y8.GREAT,Y8.DLESS,Y8.DGREAT,Y8.LESSAND,Y8.GREATAND,Y8.LESSGREAT,Y8.DLESSDASH,Y8.CLOBBER,Y8.TLESS,Y8.AND_GREAT,Y8.AND_DGREAT]),new Set([Y8.AMP,Y8.PIPE,Y8.PIPE_AMP,Y8.SEMICOLON,Y8.AND_AND,Y8.OR_OR,Y8.DSEMI,Y8.SEMI_AND,Y8.SEMI_SEMI_AND]);var X8=[{name:`echo`,load:async()=>(await import(`./echo-O45JWWI2-gk6mEMAU.mjs`)).echoCommand},{name:`cat`,load:async()=>(await import(`./cat-RDUMLXKC-D1H4LA3Z.mjs`)).catCommand},{name:`printf`,load:async()=>(await import(`./printf-CX64KX2P-B_vWcqAL.mjs`)).printfCommand},{name:`ls`,load:async()=>(await import(`./ls-KSXFZCWH-GOWXktO9.mjs`)).lsCommand},{name:`mkdir`,load:async()=>(await import(`./mkdir-TDEMSB6C-BVcgITXm.mjs`)).mkdirCommand},{name:`rmdir`,load:async()=>(await import(`./rmdir-XTQXT7RK-DZfv6Zfz.mjs`)).rmdirCommand},{name:`touch`,load:async()=>(await import(`./touch-DX2IJOQ4-CRX6GYeb.mjs`)).touchCommand},{name:`rm`,load:async()=>(await import(`./rm-RTZG23RL-sCMTtbxP.mjs`)).rmCommand},{name:`cp`,load:async()=>(await import(`./cp-XOYR4ABJ-CpnwcT2f.mjs`)).cpCommand},{name:`mv`,load:async()=>(await import(`./mv-Z6MORUFL-El0zMsEA.mjs`)).mvCommand},{name:`ln`,load:async()=>(await import(`./ln-4TRFBYAT-DGrhTL40.mjs`)).lnCommand},{name:`chmod`,load:async()=>(await import(`./chmod-SYMGL4JA-lEGJICyB.mjs`)).chmodCommand},{name:`pwd`,load:async()=>(await import(`./pwd-D4OZ7N27-NYST_A3S.mjs`)).pwdCommand},{name:`readlink`,load:async()=>(await import(`./readlink-MI4GCHJF-Dl1Uxmrf.mjs`)).readlinkCommand},{name:`head`,load:async()=>(await import(`./head-HT2B6D2J-B5ybc-my.mjs`)).headCommand},{name:`tail`,load:async()=>(await import(`./tail-S5ULNTJU-Cfa1pDQZ.mjs`)).tailCommand},{name:`wc`,load:async()=>(await import(`./wc-TQB3VNOX-DqHFY4jy.mjs`)).wcCommand},{name:`stat`,load:async()=>(await import(`./stat-BT5A227F-CEZPXJ9_.mjs`)).statCommand},{name:`grep`,load:async()=>(await import(`./grep-2HUTXO5U-9G7xEEms.mjs`)).grepCommand},{name:`fgrep`,load:async()=>(await import(`./grep-2HUTXO5U-9G7xEEms.mjs`)).fgrepCommand},{name:`egrep`,load:async()=>(await import(`./grep-2HUTXO5U-9G7xEEms.mjs`)).egrepCommand},{name:`rg`,load:async()=>(await import(`./rg-XNF3R3II-vKB7djPZ.mjs`)).rgCommand},{name:`sed`,load:async()=>(await import(`./sed-JAPPVBEU-C7wh6RxT.mjs`)).sedCommand},{name:`awk`,load:async()=>(await import(`./awk2-BBAGSFUB-ClUuupKf.mjs`)).awkCommand2},{name:`sort`,load:async()=>(await import(`./sort-DCNRDA7U-vT57Mw8o.mjs`)).sortCommand},{name:`uniq`,load:async()=>(await import(`./uniq-SUNANL47-DBRSkw7j.mjs`)).uniqCommand},{name:`comm`,load:async()=>(await import(`./comm-5SLSESQG-0igXzBnl.mjs`)).commCommand},{name:`cut`,load:async()=>(await import(`./cut-OPC3VAGB-nJAw1cEp.mjs`)).cutCommand},{name:`paste`,load:async()=>(await import(`./paste-7N6AFSDS-BnqApCW_.mjs`)).pasteCommand},{name:`tr`,load:async()=>(await import(`./tr-2HXZRDSW-ByYmbFae.mjs`)).trCommand},{name:`rev`,load:async()=>(await import(`./rev-XOSYPP45-D6eJxPKd.mjs`)).rev},{name:`nl`,load:async()=>(await import(`./nl-U5YJDM32-Y_hGSMac.mjs`)).nl},{name:`fold`,load:async()=>(await import(`./fold-LDSORVYE-Dhx0k6vg.mjs`)).fold},{name:`expand`,load:async()=>(await import(`./expand-DTNXU4LQ-D2bEx87V.mjs`)).expand},{name:`unexpand`,load:async()=>(await import(`./unexpand-RGTMIGZM-BL5sZ5_Z.mjs`)).unexpand},{name:`strings`,load:async()=>(await import(`./strings-7PLOGTPD-CiVw0Uh4.mjs`)).strings},{name:`split`,load:async()=>(await import(`./split-SITCSYCZ-Ci_IfVPT.mjs`)).split},{name:`column`,load:async()=>(await import(`./column-WLPMMSTS-Do8HgL6q.mjs`)).column},{name:`join`,load:async()=>(await import(`./join-GG2LDHE5-7k4Syl20.mjs`)).join},{name:`tee`,load:async()=>(await import(`./tee-O7VXZDCO-D95l5L5Z.mjs`)).teeCommand},{name:`find`,load:async()=>(await import(`./find-DH2ALKQS-B6bMjuwo.mjs`)).findCommand},{name:`basename`,load:async()=>(await import(`./basename-AA2KJYZQ-CEdH80GO.mjs`)).basenameCommand},{name:`dirname`,load:async()=>(await import(`./dirname-LEMTZZFS-Dg3ijqjM.mjs`)).dirnameCommand},{name:`tree`,load:async()=>(await import(`./tree-LYXBS7DC-Dq6aWetx.mjs`)).treeCommand},{name:`du`,load:async()=>(await import(`./du-WO2ENHXQ-jqWYqk_n.mjs`)).duCommand},{name:`env`,load:async()=>(await import(`./env-5EPCWSXR-BU5zTNDV.mjs`)).envCommand},{name:`printenv`,load:async()=>(await import(`./env-5EPCWSXR-BU5zTNDV.mjs`)).printenvCommand},{name:`alias`,load:async()=>(await import(`./alias-JE7RI5QX-BLuOrjl2.mjs`)).aliasCommand},{name:`unalias`,load:async()=>(await import(`./alias-JE7RI5QX-BLuOrjl2.mjs`)).unaliasCommand},{name:`history`,load:async()=>(await import(`./history-J4QRNGRO-DesXbqi2.mjs`)).historyCommand},{name:`xargs`,load:async()=>(await import(`./xargs-I6EZUCYF-C_ZtmUCd.mjs`)).xargsCommand},{name:`true`,load:async()=>(await import(`./true-WHJNXCHG-XC4ZnbBw.mjs`)).trueCommand},{name:`false`,load:async()=>(await import(`./true-WHJNXCHG-XC4ZnbBw.mjs`)).falseCommand},{name:`clear`,load:async()=>(await import(`./clear-5CZ5X4YR-9EZyt4MH.mjs`)).clearCommand},{name:`bash`,load:async()=>(await import(`./bash-IJWYRKFO-BDtU-lTC.mjs`)).bashCommand},{name:`sh`,load:async()=>(await import(`./bash-IJWYRKFO-BDtU-lTC.mjs`)).shCommand},{name:`jq`,load:async()=>(await import(`./jq-LYZFFBZB-BZ4XP29I.mjs`)).jqCommand},{name:`base64`,load:async()=>(await import(`./base64-4YMZCVJ5-CtkujsXK.mjs`)).base64Command},{name:`diff`,load:async()=>(await import(`./diff-HJF2MPDN-EjmLU95d.mjs`)).diffCommand},{name:`date`,load:async()=>(await import(`./date-DD7FVA2V-W_sbdO4n.mjs`)).dateCommand},{name:`sleep`,load:async()=>(await import(`./sleep-VZFPZFWA-CBARUnrz.mjs`)).sleepCommand},{name:`timeout`,load:async()=>(await import(`./timeout-VRKMCG72-DFU5EkCe.mjs`)).timeoutCommand},{name:`time`,load:async()=>(await import(`./time-DEUO3QV2-DwnT4FOS.mjs`)).timeCommand},{name:`seq`,load:async()=>(await import(`./seq-RN5ZUASB-R5HjEVux.mjs`)).seqCommand},{name:`expr`,load:async()=>(await import(`./expr-YYCVMXE3-wI0boF3e.mjs`)).exprCommand},{name:`md5sum`,load:async()=>(await import(`./md5sum-INMIK4DX-BlgGpdCD.mjs`)).md5sumCommand},{name:`sha1sum`,load:async()=>(await import(`./sha1sum-VJPNLNU6-DfzpfxJ-.mjs`)).sha1sumCommand},{name:`sha256sum`,load:async()=>(await import(`./sha256sum-PI32XWXY-DrKtnAPK.mjs`)).sha256sumCommand},{name:`file`,load:async()=>(await import(`./file-IGDTDPLG-DkYMcmTl.mjs`)).fileCommand},{name:`html-to-markdown`,load:async()=>(await import(`./html-to-markdown-TFCECAGV-DLUGt6pW.mjs`)).htmlToMarkdownCommand},{name:`help`,load:async()=>(await import(`./help-VVWX7SA5-Bb8T3djf.mjs`)).helpCommand},{name:`which`,load:async()=>(await import(`./which-XZHEH76L-CbmRVw8E.mjs`)).whichCommand},{name:`tac`,load:async()=>(await import(`./tac-SJGXQ4T2-BL4Xd7y6.mjs`)).tac},{name:`hostname`,load:async()=>(await import(`./hostname-BK6HG2DE-DTiGP5th.mjs`)).hostname},{name:`whoami`,load:async()=>(await import(`./whoami-DGKU3D2X-BDJh39KM.mjs`)).whoami},{name:`od`,load:async()=>(await import(`./od-VJEF2UR5-CueTpZ68.mjs`)).od},{name:`gzip`,load:async()=>(await import(`./gzip-AQXSGOVS-BcGYw5wM.mjs`)).gzipCommand},{name:`gunzip`,load:async()=>(await import(`./gzip-AQXSGOVS-BcGYw5wM.mjs`)).gunzipCommand},{name:`zcat`,load:async()=>(await import(`./gzip-AQXSGOVS-BcGYw5wM.mjs`)).zcatCommand}];(typeof __BROWSER__>`u`||!__BROWSER__)&&(X8.push({name:`tar`,load:async()=>(await import(`./tar-MZQD7NO4-HJsWmzu9.mjs`)).tarCommand}),X8.push({name:`yq`,load:async()=>(await import(`./yq-OAKYHSXH-COzSqY4J.mjs`)).yqCommand}),X8.push({name:`xan`,load:async()=>(await import(`./xan-UD7JYIL2-DQo9f-1a.mjs`)).xanCommand}),X8.push({name:`sqlite3`,load:async()=>(await import(`./sqlite3-TE5AIOTF-BhXSdz7U.mjs`)).sqlite3Command}));var Z8=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Z8.push({name:`python3`,load:async()=>(await import(`./python3-DNGS4G3E-DaBJervu.mjs`)).python3Command}),Z8.push({name:`python`,load:async()=>(await import(`./python3-DNGS4G3E-DaBJervu.mjs`)).pythonCommand}));var Q8=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Q8.push({name:`js-exec`,load:async()=>(await import(`./js-exec-VXN6TZ7U-Ds5SsewK.mjs`)).jsExecCommand}),Q8.push({name:`node`,load:async()=>(await import(`./js-exec-VXN6TZ7U-Ds5SsewK.mjs`)).nodeStubCommand})),new TextEncoder,Object.freeze({stdout:``,stderr:``,exitCode:0}),[...new Map([[`:`,[`: [arguments]`,`Null command.
465
+ `)}${tY()}`;var XSe=i(((e,t)=>{var n=[`||`,`&&`,`;;`,`|&`,`<(`,`<<<`,`>>`,`>&`,`<&`,`&`,`;`,`(`,`)`,`|`,`<`,`>`],r=/[\n\r\u2028\u2029]/,i=/[\s#!"$&'():;<=>@\\^`|]/g;t.exports=function(e){return e.map(function(e){if(e===``)return`''`;if(e&&typeof e==`object`){if(`op`in e&&e.op===`glob`){if(typeof e.pattern!=`string`)throw TypeError("glob token requires a string `pattern`");if(r.test(e.pattern))throw TypeError("glob `pattern` must not contain line terminators");return e.pattern.replace(i,`\\$&`)}if(`op`in e&&typeof e.op==`string`){if(n.indexOf(e.op)<0)throw TypeError("invalid `op` value: "+JSON.stringify(e.op));return e.op.replace(/[\s\S]/g,`\\$&`)}if(`comment`in e&&typeof e.comment==`string`){if(r.test(e.comment))throw TypeError("`comment` must not contain line terminators");return`#`+e.comment}throw TypeError(`unrecognized object token shape`)}return/["\s\\]/.test(e)&&!/'/.test(e)?`'`+e.replace(/(['])/g,`\\$1`)+`'`:/["'\s]/.test(e)?`"`+e.replace(/(["\\$`!])/g,`\\$1`)+`"`:String(e).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}~])/g,`$1\\$2`)}).join(` `)}})),ZSe=i(((e,t)=>{for(var n=`(?:`+[`\\|\\|`,`\\&\\&`,`;;`,`\\|\\&`,`\\<\\(`,`\\<\\<\\<`,`>>`,`>\\&`,`<\\&`,`[&;()|<>]`].join(`|`)+`)`,r=RegExp(`^`+n+`$`),i=`|&;()<> \\t`,a=`'([^']*?)'`,o=`"((\\\\"|[^"])*?)"`,s=/^#$/,c=`'`,l=`"`,u=`$`,d=``,f=4294967296,p=0;p<4;p++)d+=(f*Math.random()).toString(16);var m=RegExp(`^`+d);function h(e,t){for(var n=t.lastIndex,r=[],i;i=t.exec(e);)r[r.length]=i,t.lastIndex===i.index&&(t.lastIndex+=1);return t.lastIndex=n,r}function g(e,t,n){var r=typeof e==`function`?e(n):e[n];return r===void 0&&n!=``?r=``:r===void 0&&(r=`$`),typeof r==`object`?t+d+JSON.stringify(r)+d:t+r}function _(e,t,d){d||={};var f=d.escape||`\\`,p=d.splitUnquoted===!0?`
466
+ `:typeof d.splitUnquoted==`string`?d.splitUnquoted:``,m=`(\\`+f+`['"`+i+`]|[^\\s'"`+i+`])+`,_=h(e,new RegExp([`(`+n+`)`,`(`+m+`|`+o+`|`+a+`)+`].join(`|`),`g`));if(_.length===0)return[];t||={};var v=!1;return _.map(function(n){var i=n[0];if(!i||v)return;if(r.test(i))return{op:i};var a=!1,o=!1,d=``,m=[],h=!1,_=null,y=!1,b;function x(){b+=1;var e,n,r=i.charAt(b);if(r===`{`){if(b+=1,i.charAt(b)===`}`)throw Error(`Bad substitution: `+i.slice(b-2,b+1));var a=1;for(e=b;a>0&&e<i.length;)i.charAt(e)===`{`&&i.charAt(e-1)===`$`?a+=1:i.charAt(e)===`}`&&--a,e+=1;if(a!==0)throw Error(`Bad substitution: `+i.slice(b));--e,n=i.slice(b,e),b=e}else if(/[*@#?$!_-]/.test(r))n=r,b+=1;else{var o=i.slice(b);e=o.match(/[^\w\d_]/),e?(n=o.slice(0,e.index),b+=e.index-1):(n=o,b=i.length)}return g(t,``,n)}function S(){if(_!==null){if(_===0)d!==``&&(m[m.length]=d,d=``);else{m[m.length]=d,d=``;for(var e=1;e<_;e+=1)m[m.length]=``}_=null}}for(b=0;b<i.length;b++){var C=i.charAt(b);if(p&&C!==u&&S(),y||=!a&&(C===`*`||C===`?`),o)d+=C,o=!1;else if(a)C===a?a=!1:a==c?d+=C:C===f?(b+=1,C=i.charAt(b),C===l||C===f||C===u?d+=C:d+=f+C):C===u?d+=x():d+=C;else if(C===l||C===c)a=C,h=!0;else if(r.test(C))return{op:i};else if(s.test(C)){v=!0;var w={comment:e.slice(n.index+b+1)};return d.length?[d,w]:[w]}else if(C===f)o=!0;else if(C===u){var T=x();if(!p)d+=T;else for(var E=0;E<T.length;E+=1){var D=T.charAt(E);p.indexOf(D)<0?(S(),d+=D):_===null?_=D===` `||D===` `||D===`
467
+ `?0:1:D!==` `&&D!==` `&&D!==`
468
+ `&&(_+=1)}}else d+=C}if(y)return{op:`glob`,pattern:d};if(p){if(_!==null&&_>0){m[m.length]=d,d=``;for(var O=1;O<_;O+=1)m[m.length]=``}return(d!==``||h&&m.length===0)&&(m[m.length]=d),m}return d}).reduce(function(e,t){return t===void 0||[].concat(t).forEach(function(t){e[e.length]=t}),e},[])}t.exports=function(e,t,n){var r=_(e,t,n);return typeof t==`function`?r.reduce(function(e,t){if(typeof t==`object`)return e[e.length]=t,e;var n=t.split(RegExp(`(`+d+`.*?`+d+`)`,`g`));return n.length===1?(e[e.length]=n[0],e):(n.filter(Boolean).forEach(function(t){e[e.length]=m.test(t)?JSON.parse(t.split(d)[1]):t}),e)},[]):r}}));i((e=>{e.quote=XSe(),e.parse=ZSe()}))();const QSe=[`node_modules`,`.git`,`dist`,`build`,`.next`,`.turbo`,`.nuxt`,`coverage`,`.cache`,`.parcel-cache`,`.vercel`,`.ok`,`.claude`];new Set([`-m`,`-A`,`-B`,`-C`,`-e`,`-f`,`-d`,`-D`,`--regexp`,`--file`,`--max-count`,`--after-context`,`--before-context`,`--context`,`--include`,`--exclude`,`--exclude-dir`]),new Set([`-f`,`-s`,`-w`,`--skip-fields`,`--skip-chars`,`--check-chars`]),new Set([`-k`,`-t`,`-o`,`-S`,`-T`,`--key`,`--field-separator`,`--output`]),new Set([`-d`,`-f`,`-b`,`-c`,`--delimiter`,`--fields`,`--bytes`,`--characters`]),new Set([`-n`,`-c`,`--lines`,`--bytes`]),new Set([`-n`,`-c`,`--lines`,`--bytes`]),new Set([...new Set([`-name`,`-iname`,`-path`,`-ipath`,`-regex`,`-iregex`,`-lname`,`-ilname`]),`-newer`,`-anewer`,`-cnewer`,`-type`,`-maxdepth`,`-mindepth`,`-size`,`-mtime`,`-mmin`,`-atime`,`-amin`,`-ctime`,`-cmin`,`-perm`,`-links`,`-inum`,`-user`,`-group`]),new Set(QSe);var Y8;(function(e){e.EOF=`EOF`,e.NEWLINE=`NEWLINE`,e.SEMICOLON=`SEMICOLON`,e.AMP=`AMP`,e.PIPE=`PIPE`,e.PIPE_AMP=`PIPE_AMP`,e.AND_AND=`AND_AND`,e.OR_OR=`OR_OR`,e.BANG=`BANG`,e.LESS=`LESS`,e.GREAT=`GREAT`,e.DLESS=`DLESS`,e.DGREAT=`DGREAT`,e.LESSAND=`LESSAND`,e.GREATAND=`GREATAND`,e.LESSGREAT=`LESSGREAT`,e.DLESSDASH=`DLESSDASH`,e.CLOBBER=`CLOBBER`,e.TLESS=`TLESS`,e.AND_GREAT=`AND_GREAT`,e.AND_DGREAT=`AND_DGREAT`,e.LPAREN=`LPAREN`,e.RPAREN=`RPAREN`,e.LBRACE=`LBRACE`,e.RBRACE=`RBRACE`,e.DSEMI=`DSEMI`,e.SEMI_AND=`SEMI_AND`,e.SEMI_SEMI_AND=`SEMI_SEMI_AND`,e.DBRACK_START=`DBRACK_START`,e.DBRACK_END=`DBRACK_END`,e.DPAREN_START=`DPAREN_START`,e.DPAREN_END=`DPAREN_END`,e.IF=`IF`,e.THEN=`THEN`,e.ELSE=`ELSE`,e.ELIF=`ELIF`,e.FI=`FI`,e.FOR=`FOR`,e.WHILE=`WHILE`,e.UNTIL=`UNTIL`,e.DO=`DO`,e.DONE=`DONE`,e.CASE=`CASE`,e.ESAC=`ESAC`,e.IN=`IN`,e.FUNCTION=`FUNCTION`,e.SELECT=`SELECT`,e.TIME=`TIME`,e.COPROC=`COPROC`,e.WORD=`WORD`,e.NAME=`NAME`,e.NUMBER=`NUMBER`,e.ASSIGNMENT_WORD=`ASSIGNMENT_WORD`,e.FD_VARIABLE=`FD_VARIABLE`,e.COMMENT=`COMMENT`,e.HEREDOC_CONTENT=`HEREDOC_CONTENT`})(Y8||={}),new Map([[`if`,Y8.IF],[`then`,Y8.THEN],[`else`,Y8.ELSE],[`elif`,Y8.ELIF],[`fi`,Y8.FI],[`for`,Y8.FOR],[`while`,Y8.WHILE],[`until`,Y8.UNTIL],[`do`,Y8.DO],[`done`,Y8.DONE],[`case`,Y8.CASE],[`esac`,Y8.ESAC],[`in`,Y8.IN],[`function`,Y8.FUNCTION],[`select`,Y8.SELECT],[`time`,Y8.TIME],[`coproc`,Y8.COPROC]]),Y8.SEMI_SEMI_AND,Y8.TLESS,Y8.AND_DGREAT,Y8.DBRACK_START,Y8.DBRACK_END,Y8.DPAREN_START,Y8.DPAREN_END,Y8.AND_AND,Y8.OR_OR,Y8.DSEMI,Y8.SEMI_AND,Y8.PIPE_AMP,Y8.DGREAT,Y8.LESSAND,Y8.GREATAND,Y8.LESSGREAT,Y8.CLOBBER,Y8.AND_GREAT,new Map([[`|`,Y8.PIPE],[`&`,Y8.AMP],[`;`,Y8.SEMICOLON],[`(`,Y8.LPAREN],[`)`,Y8.RPAREN],[`<`,Y8.LESS],[`>`,Y8.GREAT]]),new Set([Y8.LESS,Y8.GREAT,Y8.DLESS,Y8.DGREAT,Y8.LESSAND,Y8.GREATAND,Y8.LESSGREAT,Y8.DLESSDASH,Y8.CLOBBER,Y8.TLESS,Y8.AND_GREAT,Y8.AND_DGREAT]),new Set([Y8.LESS,Y8.GREAT,Y8.DLESS,Y8.DGREAT,Y8.LESSAND,Y8.GREATAND,Y8.LESSGREAT,Y8.DLESSDASH,Y8.CLOBBER,Y8.TLESS]),new Set([Y8.LESS,Y8.GREAT,Y8.DLESS,Y8.DGREAT,Y8.LESSAND,Y8.GREATAND,Y8.LESSGREAT,Y8.DLESSDASH,Y8.CLOBBER,Y8.TLESS,Y8.AND_GREAT,Y8.AND_DGREAT]),new Set([Y8.AMP,Y8.PIPE,Y8.PIPE_AMP,Y8.SEMICOLON,Y8.AND_AND,Y8.OR_OR,Y8.DSEMI,Y8.SEMI_AND,Y8.SEMI_SEMI_AND]);var X8=[{name:`echo`,load:async()=>(await import(`./echo-O45JWWI2-gk6mEMAU.mjs`)).echoCommand},{name:`cat`,load:async()=>(await import(`./cat-RDUMLXKC-D1H4LA3Z.mjs`)).catCommand},{name:`printf`,load:async()=>(await import(`./printf-CX64KX2P-B_vWcqAL.mjs`)).printfCommand},{name:`ls`,load:async()=>(await import(`./ls-KSXFZCWH-GOWXktO9.mjs`)).lsCommand},{name:`mkdir`,load:async()=>(await import(`./mkdir-TDEMSB6C-BVcgITXm.mjs`)).mkdirCommand},{name:`rmdir`,load:async()=>(await import(`./rmdir-XTQXT7RK-DZfv6Zfz.mjs`)).rmdirCommand},{name:`touch`,load:async()=>(await import(`./touch-DX2IJOQ4-CRX6GYeb.mjs`)).touchCommand},{name:`rm`,load:async()=>(await import(`./rm-RTZG23RL-sCMTtbxP.mjs`)).rmCommand},{name:`cp`,load:async()=>(await import(`./cp-XOYR4ABJ-CpnwcT2f.mjs`)).cpCommand},{name:`mv`,load:async()=>(await import(`./mv-Z6MORUFL-El0zMsEA.mjs`)).mvCommand},{name:`ln`,load:async()=>(await import(`./ln-4TRFBYAT-DGrhTL40.mjs`)).lnCommand},{name:`chmod`,load:async()=>(await import(`./chmod-SYMGL4JA-lEGJICyB.mjs`)).chmodCommand},{name:`pwd`,load:async()=>(await import(`./pwd-D4OZ7N27-NYST_A3S.mjs`)).pwdCommand},{name:`readlink`,load:async()=>(await import(`./readlink-MI4GCHJF-Dl1Uxmrf.mjs`)).readlinkCommand},{name:`head`,load:async()=>(await import(`./head-HT2B6D2J-B5ybc-my.mjs`)).headCommand},{name:`tail`,load:async()=>(await import(`./tail-S5ULNTJU-Cfa1pDQZ.mjs`)).tailCommand},{name:`wc`,load:async()=>(await import(`./wc-TQB3VNOX-DqHFY4jy.mjs`)).wcCommand},{name:`stat`,load:async()=>(await import(`./stat-BT5A227F-CEZPXJ9_.mjs`)).statCommand},{name:`grep`,load:async()=>(await import(`./grep-2HUTXO5U-9G7xEEms.mjs`)).grepCommand},{name:`fgrep`,load:async()=>(await import(`./grep-2HUTXO5U-9G7xEEms.mjs`)).fgrepCommand},{name:`egrep`,load:async()=>(await import(`./grep-2HUTXO5U-9G7xEEms.mjs`)).egrepCommand},{name:`rg`,load:async()=>(await import(`./rg-XNF3R3II-vKB7djPZ.mjs`)).rgCommand},{name:`sed`,load:async()=>(await import(`./sed-JAPPVBEU-C7wh6RxT.mjs`)).sedCommand},{name:`awk`,load:async()=>(await import(`./awk2-BBAGSFUB-ClUuupKf.mjs`)).awkCommand2},{name:`sort`,load:async()=>(await import(`./sort-DCNRDA7U-vT57Mw8o.mjs`)).sortCommand},{name:`uniq`,load:async()=>(await import(`./uniq-SUNANL47-DBRSkw7j.mjs`)).uniqCommand},{name:`comm`,load:async()=>(await import(`./comm-5SLSESQG-0igXzBnl.mjs`)).commCommand},{name:`cut`,load:async()=>(await import(`./cut-OPC3VAGB-nJAw1cEp.mjs`)).cutCommand},{name:`paste`,load:async()=>(await import(`./paste-7N6AFSDS-BnqApCW_.mjs`)).pasteCommand},{name:`tr`,load:async()=>(await import(`./tr-2HXZRDSW-ByYmbFae.mjs`)).trCommand},{name:`rev`,load:async()=>(await import(`./rev-XOSYPP45-D6eJxPKd.mjs`)).rev},{name:`nl`,load:async()=>(await import(`./nl-U5YJDM32-Y_hGSMac.mjs`)).nl},{name:`fold`,load:async()=>(await import(`./fold-LDSORVYE-Dhx0k6vg.mjs`)).fold},{name:`expand`,load:async()=>(await import(`./expand-DTNXU4LQ-D2bEx87V.mjs`)).expand},{name:`unexpand`,load:async()=>(await import(`./unexpand-RGTMIGZM-BL5sZ5_Z.mjs`)).unexpand},{name:`strings`,load:async()=>(await import(`./strings-7PLOGTPD-CiVw0Uh4.mjs`)).strings},{name:`split`,load:async()=>(await import(`./split-SITCSYCZ-Ci_IfVPT.mjs`)).split},{name:`column`,load:async()=>(await import(`./column-WLPMMSTS-Do8HgL6q.mjs`)).column},{name:`join`,load:async()=>(await import(`./join-GG2LDHE5-7k4Syl20.mjs`)).join},{name:`tee`,load:async()=>(await import(`./tee-O7VXZDCO-D95l5L5Z.mjs`)).teeCommand},{name:`find`,load:async()=>(await import(`./find-DH2ALKQS-B6bMjuwo.mjs`)).findCommand},{name:`basename`,load:async()=>(await import(`./basename-AA2KJYZQ-CEdH80GO.mjs`)).basenameCommand},{name:`dirname`,load:async()=>(await import(`./dirname-LEMTZZFS-Dg3ijqjM.mjs`)).dirnameCommand},{name:`tree`,load:async()=>(await import(`./tree-LYXBS7DC-Dq6aWetx.mjs`)).treeCommand},{name:`du`,load:async()=>(await import(`./du-WO2ENHXQ-jqWYqk_n.mjs`)).duCommand},{name:`env`,load:async()=>(await import(`./env-5EPCWSXR-BU5zTNDV.mjs`)).envCommand},{name:`printenv`,load:async()=>(await import(`./env-5EPCWSXR-BU5zTNDV.mjs`)).printenvCommand},{name:`alias`,load:async()=>(await import(`./alias-JE7RI5QX-BLuOrjl2.mjs`)).aliasCommand},{name:`unalias`,load:async()=>(await import(`./alias-JE7RI5QX-BLuOrjl2.mjs`)).unaliasCommand},{name:`history`,load:async()=>(await import(`./history-J4QRNGRO-DesXbqi2.mjs`)).historyCommand},{name:`xargs`,load:async()=>(await import(`./xargs-I6EZUCYF-C_ZtmUCd.mjs`)).xargsCommand},{name:`true`,load:async()=>(await import(`./true-WHJNXCHG-XC4ZnbBw.mjs`)).trueCommand},{name:`false`,load:async()=>(await import(`./true-WHJNXCHG-XC4ZnbBw.mjs`)).falseCommand},{name:`clear`,load:async()=>(await import(`./clear-5CZ5X4YR-9EZyt4MH.mjs`)).clearCommand},{name:`bash`,load:async()=>(await import(`./bash-IJWYRKFO-BDtU-lTC.mjs`)).bashCommand},{name:`sh`,load:async()=>(await import(`./bash-IJWYRKFO-BDtU-lTC.mjs`)).shCommand},{name:`jq`,load:async()=>(await import(`./jq-LYZFFBZB-BZ4XP29I.mjs`)).jqCommand},{name:`base64`,load:async()=>(await import(`./base64-4YMZCVJ5-CtkujsXK.mjs`)).base64Command},{name:`diff`,load:async()=>(await import(`./diff-HJF2MPDN-EjmLU95d.mjs`)).diffCommand},{name:`date`,load:async()=>(await import(`./date-DD7FVA2V-W_sbdO4n.mjs`)).dateCommand},{name:`sleep`,load:async()=>(await import(`./sleep-VZFPZFWA-CBARUnrz.mjs`)).sleepCommand},{name:`timeout`,load:async()=>(await import(`./timeout-VRKMCG72-DFU5EkCe.mjs`)).timeoutCommand},{name:`time`,load:async()=>(await import(`./time-DEUO3QV2-DwnT4FOS.mjs`)).timeCommand},{name:`seq`,load:async()=>(await import(`./seq-RN5ZUASB-R5HjEVux.mjs`)).seqCommand},{name:`expr`,load:async()=>(await import(`./expr-YYCVMXE3-wI0boF3e.mjs`)).exprCommand},{name:`md5sum`,load:async()=>(await import(`./md5sum-INMIK4DX-BlgGpdCD.mjs`)).md5sumCommand},{name:`sha1sum`,load:async()=>(await import(`./sha1sum-VJPNLNU6-DfzpfxJ-.mjs`)).sha1sumCommand},{name:`sha256sum`,load:async()=>(await import(`./sha256sum-PI32XWXY-DrKtnAPK.mjs`)).sha256sumCommand},{name:`file`,load:async()=>(await import(`./file-IGDTDPLG-DkYMcmTl.mjs`)).fileCommand},{name:`html-to-markdown`,load:async()=>(await import(`./html-to-markdown-TFCECAGV-DLUGt6pW.mjs`)).htmlToMarkdownCommand},{name:`help`,load:async()=>(await import(`./help-VVWX7SA5-Bb8T3djf.mjs`)).helpCommand},{name:`which`,load:async()=>(await import(`./which-XZHEH76L-CbmRVw8E.mjs`)).whichCommand},{name:`tac`,load:async()=>(await import(`./tac-SJGXQ4T2-BL4Xd7y6.mjs`)).tac},{name:`hostname`,load:async()=>(await import(`./hostname-BK6HG2DE-DTiGP5th.mjs`)).hostname},{name:`whoami`,load:async()=>(await import(`./whoami-DGKU3D2X-BDJh39KM.mjs`)).whoami},{name:`od`,load:async()=>(await import(`./od-VJEF2UR5-CueTpZ68.mjs`)).od},{name:`gzip`,load:async()=>(await import(`./gzip-AQXSGOVS-BcGYw5wM.mjs`)).gzipCommand},{name:`gunzip`,load:async()=>(await import(`./gzip-AQXSGOVS-BcGYw5wM.mjs`)).gunzipCommand},{name:`zcat`,load:async()=>(await import(`./gzip-AQXSGOVS-BcGYw5wM.mjs`)).zcatCommand}];(typeof __BROWSER__>`u`||!__BROWSER__)&&(X8.push({name:`tar`,load:async()=>(await import(`./tar-MZQD7NO4-HJsWmzu9.mjs`)).tarCommand}),X8.push({name:`yq`,load:async()=>(await import(`./yq-OAKYHSXH-COzSqY4J.mjs`)).yqCommand}),X8.push({name:`xan`,load:async()=>(await import(`./xan-UD7JYIL2-DQo9f-1a.mjs`)).xanCommand}),X8.push({name:`sqlite3`,load:async()=>(await import(`./sqlite3-TE5AIOTF-BhXSdz7U.mjs`)).sqlite3Command}));var Z8=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Z8.push({name:`python3`,load:async()=>(await import(`./python3-DNGS4G3E-DaBJervu.mjs`)).python3Command}),Z8.push({name:`python`,load:async()=>(await import(`./python3-DNGS4G3E-DaBJervu.mjs`)).pythonCommand}));var Q8=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Q8.push({name:`js-exec`,load:async()=>(await import(`./js-exec-VXN6TZ7U-Ds5SsewK.mjs`)).jsExecCommand}),Q8.push({name:`node`,load:async()=>(await import(`./js-exec-VXN6TZ7U-Ds5SsewK.mjs`)).nodeStubCommand})),new TextEncoder,Object.freeze({stdout:``,stderr:``,exitCode:0}),[...new Map([[`:`,[`: [arguments]`,`Null command.
466
469
  No effect; the command does nothing.
467
470
  Exit Status:
468
471
  Always succeeds.`]],[`.`,[`. filename [arguments]`,`Execute commands from a file in the current shell.
@@ -809,10 +812,7 @@ caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?
809
812
  job specification, and reports its termination status.
810
813
  Exit Status:
811
814
  Returns the status of the last ID; fails if ID is invalid or an invalid
812
- option is given.`]]]).keys()].sort(),new TextDecoder(`utf-8`,{fatal:!0});var XSe=i(((e,t)=>{var n=[`||`,`&&`,`;;`,`|&`,`<(`,`<<<`,`>>`,`>&`,`<&`,`&`,`;`,`(`,`)`,`|`,`<`,`>`],r=/[\n\r\u2028\u2029]/,i=/[\s#!"$&'():;<=>@\\^`|]/g;t.exports=function(e){return e.map(function(e){if(e===``)return`''`;if(e&&typeof e==`object`){if(`op`in e&&e.op===`glob`){if(typeof e.pattern!=`string`)throw TypeError("glob token requires a string `pattern`");if(r.test(e.pattern))throw TypeError("glob `pattern` must not contain line terminators");return e.pattern.replace(i,`\\$&`)}if(`op`in e&&typeof e.op==`string`){if(n.indexOf(e.op)<0)throw TypeError("invalid `op` value: "+JSON.stringify(e.op));return e.op.replace(/[\s\S]/g,`\\$&`)}if(`comment`in e&&typeof e.comment==`string`){if(r.test(e.comment))throw TypeError("`comment` must not contain line terminators");return`#`+e.comment}throw TypeError(`unrecognized object token shape`)}return/["\s\\]/.test(e)&&!/'/.test(e)?`'`+e.replace(/(['])/g,`\\$1`)+`'`:/["'\s]/.test(e)?`"`+e.replace(/(["\\$`!])/g,`\\$1`)+`"`:String(e).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}~])/g,`$1\\$2`)}).join(` `)}})),ZSe=i(((e,t)=>{for(var n=`(?:`+[`\\|\\|`,`\\&\\&`,`;;`,`\\|\\&`,`\\<\\(`,`\\<\\<\\<`,`>>`,`>\\&`,`<\\&`,`[&;()|<>]`].join(`|`)+`)`,r=RegExp(`^`+n+`$`),i=`|&;()<> \\t`,a=`'([^']*?)'`,o=`"((\\\\"|[^"])*?)"`,s=/^#$/,c=`'`,l=`"`,u=`$`,d=``,f=4294967296,p=0;p<4;p++)d+=(f*Math.random()).toString(16);var m=RegExp(`^`+d);function h(e,t){for(var n=t.lastIndex,r=[],i;i=t.exec(e);)r[r.length]=i,t.lastIndex===i.index&&(t.lastIndex+=1);return t.lastIndex=n,r}function g(e,t,n){var r=typeof e==`function`?e(n):e[n];return r===void 0&&n!=``?r=``:r===void 0&&(r=`$`),typeof r==`object`?t+d+JSON.stringify(r)+d:t+r}function _(e,t,d){d||={};var f=d.escape||`\\`,p=d.splitUnquoted===!0?`
813
- `:typeof d.splitUnquoted==`string`?d.splitUnquoted:``,m=`(\\`+f+`['"`+i+`]|[^\\s'"`+i+`])+`,_=h(e,new RegExp([`(`+n+`)`,`(`+m+`|`+o+`|`+a+`)+`].join(`|`),`g`));if(_.length===0)return[];t||={};var v=!1;return _.map(function(n){var i=n[0];if(!i||v)return;if(r.test(i))return{op:i};var a=!1,o=!1,d=``,m=[],h=!1,_=null,y=!1,b;function x(){b+=1;var e,n,r=i.charAt(b);if(r===`{`){if(b+=1,i.charAt(b)===`}`)throw Error(`Bad substitution: `+i.slice(b-2,b+1));var a=1;for(e=b;a>0&&e<i.length;)i.charAt(e)===`{`&&i.charAt(e-1)===`$`?a+=1:i.charAt(e)===`}`&&--a,e+=1;if(a!==0)throw Error(`Bad substitution: `+i.slice(b));--e,n=i.slice(b,e),b=e}else if(/[*@#?$!_-]/.test(r))n=r,b+=1;else{var o=i.slice(b);e=o.match(/[^\w\d_]/),e?(n=o.slice(0,e.index),b+=e.index-1):(n=o,b=i.length)}return g(t,``,n)}function S(){if(_!==null){if(_===0)d!==``&&(m[m.length]=d,d=``);else{m[m.length]=d,d=``;for(var e=1;e<_;e+=1)m[m.length]=``}_=null}}for(b=0;b<i.length;b++){var C=i.charAt(b);if(p&&C!==u&&S(),y||=!a&&(C===`*`||C===`?`),o)d+=C,o=!1;else if(a)C===a?a=!1:a==c?d+=C:C===f?(b+=1,C=i.charAt(b),C===l||C===f||C===u?d+=C:d+=f+C):C===u?d+=x():d+=C;else if(C===l||C===c)a=C,h=!0;else if(r.test(C))return{op:i};else if(s.test(C)){v=!0;var w={comment:e.slice(n.index+b+1)};return d.length?[d,w]:[w]}else if(C===f)o=!0;else if(C===u){var T=x();if(!p)d+=T;else for(var E=0;E<T.length;E+=1){var D=T.charAt(E);p.indexOf(D)<0?(S(),d+=D):_===null?_=D===` `||D===` `||D===`
814
- `?0:1:D!==` `&&D!==` `&&D!==`
815
- `&&(_+=1)}}else d+=C}if(y)return{op:`glob`,pattern:d};if(p){if(_!==null&&_>0){m[m.length]=d,d=``;for(var O=1;O<_;O+=1)m[m.length]=``}return(d!==``||h&&m.length===0)&&(m[m.length]=d),m}return d}).reduce(function(e,t){return t===void 0||[].concat(t).forEach(function(t){e[e.length]=t}),e},[])}t.exports=function(e,t,n){var r=_(e,t,n);return typeof t==`function`?r.reduce(function(e,t){if(typeof t==`object`)return e[e.length]=t,e;var n=t.split(RegExp(`(`+d+`.*?`+d+`)`,`g`));return n.length===1?(e[e.length]=n[0],e):(n.filter(Boolean).forEach(function(t){e[e.length]=m.test(t)?JSON.parse(t.split(d)[1]):t}),e)},[]):r}}));i((e=>{e.quote=XSe(),e.parse=ZSe()}))(),["**STOP — when the project has `.ok/`, do NOT use native `Read`/`Grep`/`Glob` on in-scope `.md`/`.mdx`; use `exec` (this tool).** Native tools skip the frontmatter, backlinks, unresolved comments, shadow-repo activity, and git history `exec` returns per wiki file. Reserve native tools for source code, non-markdown, and projects without `.ok/`. (Full rule + escape hatch: the `open-knowledge` skill.)",``,`Run a read-only bash-like command against the project content directory. Returns raw stdout plus enriched metadata for every wiki file referenced (frontmatter, backlink/forward-link counts, shadow-repo activity with agent/human attribution).`,``,"`⚠ N unresolved comment(s)` = open human review requests — factor in before editing, and report them.",``,"Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut. One command or a pipe (|) per call — NOT a shell: `&&`, `;`, redirections, subshells, and writes are rejected. To do several things, make separate exec calls or pass multiple paths to one command (e.g. `ls -A a b c`, `cat a b c`).",``,"cwd: the command runs in the explicit absolute `cwd` you pass, or in the MCP client's only advertised root when there is exactly one. If the client has zero or multiple roots, pass `cwd` explicitly. Paths inside the command resolve relative to that cwd; traversal above it is rejected.",``,"Stdout provenance headers (GNU-style): `ls <dir>/` prepends `<dir>/:`, single-file `cat`/`head`/`tail` prepends `==> <path> <==`, so the subject of the command is visible in raw output. Multi-file `cat a b` emits no header — the `enrichedPaths` array still lists every file. `head`/`tail` used as pipe trimmers (no file arg) defer to the upstream producer.",``,`Examples:`,'- `exec({ command: "cat articles/auth.md" })` — file contents + full enrichment','- `exec({ command: "ls articles/" })` — listing + per-file enrichment (slim)','- `exec({ command: "grep -rn oauth articles/ | head -5" })` — pipe with enrichment on matched files','- `exec({ command: "ls", cwd: "/abs/path/to/other-repo" })` — run in a different project'].join(`
815
+ option is given.`]]]).keys()].sort(),new TextDecoder(`utf-8`,{fatal:!0}),H$(`mcp:exec`),["**STOP — when the project has `.ok/`, do NOT use native `Read`/`Grep`/`Glob` on in-scope `.md`/`.mdx`; use `exec` (this tool).** Native tools skip the frontmatter, backlinks, unresolved comments, shadow-repo activity, and git history `exec` returns per wiki file. Reserve native tools for source code, non-markdown, and projects without `.ok/`. (Full rule + escape hatch: the `open-knowledge` skill.)",``,`Run a read-only bash-like command against the project content directory. Returns raw stdout plus enriched metadata for every wiki file referenced (frontmatter, backlink/forward-link counts, shadow-repo activity with agent/human attribution).`,``,"`⚠ N unresolved comment(s)` = open human review requests — factor in before editing, and report them.",``,"Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut. One command or a pipe (|) per call — NOT a shell: `&&`, `;`, subshells, writes, and ALL redirection are rejected, `<` too (read via `cat a.md`, not `< a.md`). For several things use separate exec calls or multiple paths (`cat a b c`).",``,"cwd: the command runs in the explicit absolute `cwd` you pass, or in the MCP client's only advertised root when there is exactly one. If the client has zero or multiple roots, pass `cwd` explicitly. Paths inside the command resolve relative to that cwd; traversal above it is rejected.",``,"Stdout provenance headers (GNU-style): `ls <dir>/` prepends `<dir>/:`, single-file `cat`/`head`/`tail` prepends `==> <path> <==`. Multi-file `cat a b` emits no header — the `enrichedPaths` array still lists every file. `head`/`tail` used as pipe trimmers (no file arg) defer to the upstream producer.",``,`Examples:`,'- `exec({ command: "cat articles/auth.md" })` — file contents + full enrichment','- `exec({ command: "ls articles/" })` — listing + per-file enrichment (slim)','- `exec({ command: "grep -rn oauth articles/ | head -5" })` — pipe with enrichment on matched files','- `exec({ command: "ls", cwd: "/abs/path/to/other-repo" })` — run in a different project'].join(`
816
816
  `),["Resolve the browser-reachable preview URL for an OpenKnowledge project (optionally for a specific doc). Opening a preview counts as demand: when no OK server is running for the project, this call auto-starts one (same `OK_MCP_AUTOSTART` gate and spawn timeout as the read/write tools) and waits briefly for the preview UI to bind — a cold first call can take a few seconds; calls against a running system answer immediately.",``,"Per-response `previewUrl` fields on read/write tools are ROUTE-ONLY (`/#/<doc>`, no host:port) — they identify which doc to preview, not a URL to open by itself. Call this tool to get the full, openable URL.",``,"This is THE way to open a doc OR a loose file in a browser, and the only way to force a browser when the OK Desktop app is installed (the `ok open` CLI prefers Desktop). Use it when YOUR host opens the URL itself: navigate your in-app / embedded browser to the returned `url`, or — only on a stdio host with no browser tool — `open` it in the system browser. Do not hunt for the URL via `ok ps`/`ok status` or by guessing a port — this tool returns it. Claude Code Desktop opens its in-app Browser pane with `preview_start({url})` then `navigate({url})` to move; a pure stdio CLI with no browser uses `ok open <doc>` to open in the OK Desktop app.",``,"If you are running INSIDE an OpenKnowledge surface — the desktop app’s built-in terminal or its in-app agent panel — the response leads with an `ok open …` steer and returns it as `okOpenCommand`. Run that instead: the user is already looking at the app, so a localhost URL in your reply is noise at best and a dead link at worst. Never paste `url` into your answer in that case.",``,"Returns `{ url: null, baseUrl: null, running: false, autoOpen }` + a recovery hint only when no UI could be reached (auto-start disabled via `OK_MCP_AUTOSTART=0`, no spawn authority in this registration, or the UI did not bind in time) — the hint names the right command for the actual state.",``,"To open a single markdown file that may live OUTSIDE any Open Knowledge project (a loose file, or a doc in a different git worktree), pass `file` with an absolute path: the tool finds the running session whose content directory contains it and returns that session’s URL, then navigate your in-app browser there. `document`/`folder` are for a doc in the current project; `file` is the out-of-project form.",``,`**Parameters:**`,"- `document` (optional) — Extension-less doc path in the current project (e.g. `specs/foo/SPEC`). Omit for the UI root URL.","- `folder` (optional) — Folder path in the current project (e.g. `specs/foo`); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.","- `skill` (optional) — A skill to open in the editor: `{ name, scope? }` (scope `project` default). Returns the `…/#/__skill__/<scope>/<name>` route. Mutually exclusive with `document`/`folder`/`file`.","- `file` (optional) — Absolute path to a single markdown file, including one outside any project. Resolves to the running single-file / worktree session serving it. Mutually exclusive with `document`/`folder`/`skill`; `cwd` is ignored when set.","- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
817
817
  `),F().optional().describe(`Extension-less doc path to resolve a preview URL for (e.g. "specs/foo/SPEC"). Omit to get the UI root URL.`),F().min(1).optional().describe('Folder path to resolve a folder-route preview URL for (e.g. "specs/foo"); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.'),B({name:F().min(1).regex($Y,`Skill name must be lowercase letters, digits, and hyphens only.`).describe(`Skill name (the bundle-dir identity, wherever the skill lives).`),scope:H(pu).optional().describe("Skill scope; defaults to `project`.")}).optional().describe("Skill to resolve an editor preview URL for; returns the `…/#/__skill__/<scope>/<name>` route. Mutually exclusive with `document`/`folder`/`file`."),F().optional().describe("Absolute path to a single markdown file to open, including one OUTSIDE any Open Knowledge project. Resolves to the running single-file (or worktree) session whose content directory contains it and returns that session’s `url`. Mutually exclusive with `document` / `folder` / `skill`. When `file` is set, `cwd` is ignored."),F().optional().describe(d6),f6({url:F().nullable().describe("Browser-reachable URL — the UI base joined with the doc route when `document` is given, else the UI root. `null` when no UI is running."),baseUrl:F().nullable().describe("Browser-reachable origin of the running UI (e.g. `http://localhost:5173`). `null` when no UI is running."),running:L().describe(`Whether a UI is running for the project.`),autoOpen:L().describe("User-scoped preview-auto-open preference (`appearance.preview.autoOpen`). When `true`, the agent should route the preview using capability-based routing (in-app browser if available, system browser as fallback). When `false`, the user is managing their own preview view (OK Desktop window, a browser tab they opened, etc.) — the agent must NOT open or refresh any preview UI, and should surface this URL only on direct user ask. Resolved fresh on every call; defaults to `true`."),okOpenCommand:F().nullable().optional().describe("Machine-readable form of the hosted-agent steer: when the calling agent runs inside an OpenKnowledge surface (the desktop app’s built-in terminal, or its in-app agent panel) AND a doc/folder/skill target was given, the exact `ok open …` command to run to bring it up for the user. Run it INSTEAD of navigating `url`, and do not paste `url` into your reply — the user is already in the app it points at. `null`/absent in every other context (navigate `url` per your host instead).")}),B({version:F().describe("40-char commit SHA for this entry — pass to `restore_version({ document, version })`."),timestamp:F().describe(`ISO timestamp of the entry.`),author:F().describe(`Author display name.`),authorEmail:F().describe(`Author email.`),kind:H([`checkpoint`,`wip`,`upstream`]).describe(`Entry kind: checkpoint / wip / upstream.`),message:F().describe(`Commit subject (the checkpoint summary, when one was set).`),contributors:Ube.describe(`Per-contributor records parsed from the commit (writer id, name, docs, summaries).`),checkpoint:R().nullable().describe(`Checkpoint metadata when this entry is a checkpoint, else null.`)}),[`[Requires: Hocuspocus server] List version history for a document, or the activity timeline for a folder.`,`Returns timeline entries from the shadow repo, sorted by timestamp descending.`,"Each entry carries a `version` (40-char commit SHA) you pass straight to `restore_version({ document, version })` — same field name on both sides.",``,"**Parameters (pass EXACTLY ONE of `document` / `folder` / `skill`):**","- `document` — Document name to query history for, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.",'- `folder` — Folder path for the FOLDER timeline: attributed activity over the folder\'s `.ok/` artifacts (templates + frontmatter) — who created / edited / renamed / moved / deleted them, when. `""` = project root.',"- `skill` — Skill NAME to query version history for (the skill folder's attributed versions). PROJECT-scope skills only — global skills are unversioned. Pass an entry's `version` to `restore_version({ skill, version })`.","- `branch` (optional) — Branch name (default: current branch)","- `limit` (optional) — Maximum entries to return (default 50, max 200)","- `offset` (optional) — Number of entries to skip for pagination (default 0)",'- `kind` (optional) — Filter by entry type: "checkpoint", "upstream", or "wip"',"- `author` (optional) — Filter to entries by this author name or email","- `excludeAuthor` (optional) — Exclude entries by this author name or email"].join(`
818
818
  `),[`[Requires: Hocuspocus server] Import a skill into this project as versioned content.`,``,"Fetches an agentskills.io / skills.sh skill-dir from a `source` and writes it into the vendor-neutral `.agents/skills/<name>/` hub — where it gains history, search, attribution, and cross-harness projection (via `install`) for free. Provenance (source, commit, content hash, publisher) is recorded in `.ok/skills-lock.json`. Scripts are imported as content and are NEVER executed. `add` says where it goes — an import always places the skill somewhere, so `install` afterwards is only for changing WHERE it lives (add/remove/convert/source).",``,`**Parameters:**`,"- `source` — paste the full skills.sh skill-page URL (`https://www.skills.sh/<owner>/<repo>/<skill>`, or `https://www.skills.sh/site/<hostname>/<skill>` for a website catalog), or pass `owner/repo[/subpath]` (GitHub), a git URL, or a local / `file://` path.","- `skill` — Pick ONE skill when the source bundles several.","- `scope` — `project` (default, versioned + shared) or `global` (user-global, unversioned).",``,"On a name collision with an existing skill the import lands under `<name>-imported` (never overwrites). An identical re-import (same content hash) is a no-op."].join(`
@@ -824,20 +824,20 @@ caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?
824
824
  `),z(F().min(1)).max(32).optional().describe("Canonical ids to expand to full JSX-form detail (max 32, case-sensitive). Returns `componentDetails` + `notFound`."),F().optional().describe(d6),f6({version:U(1).describe(`Schema version stamp — bump for breaking shape changes.`),components:z(B({id:F(),displayName:F(),description:F(),authoring:H([`markdown`,`jsx`]).describe("`markdown` — write the markdown-native form OK auto-promotes; `jsx` — write the JSX tag directly (no markdown-native form exists)."),example:F().describe(`Copy-ready source for the authoring form.`),guidance:F().describe(`One line on when / how to use this construct.`)})).describe(`Canonical authoring constructs, keyed by the form an agent should write.`),embedPatterns:z(B({id:F(),title:F(),description:F(),snippet:F().describe("A complete, theme-wired ```html preview fenced block.")})).describe("Copy-ready themed `html preview` starters."),tokens:z(B({name:F().describe("CSS custom-property name, e.g. `--chart-1`."),light:F(),dark:F()})).describe("Theme tokens injected into every preview iframe — reference with `var(--name)`."),componentDetails:z(V(F(),R())).optional().describe("Full JSX-form prop schema for the requested `components` ids (when provided)."),notFound:z(F()).optional().describe("Requested `components` ids that did not match any canonical.")}),[`[Requires: Hocuspocus server] Resolve a tracked merge conflict by writing the chosen content to disk and committing.`,``,`Strategy:`,"- `mine` — runs `git checkout --ours -- <file>` then `git add` (your committed ours stage, stage 2). Fails on delete-modify (DU) conflicts where stage 2 is missing — use `delete` instead.","- `theirs` — runs `git checkout --theirs -- <file>` then `git add` (their committed stage 3). Fails on modify-delete (UD) conflicts where stage 3 is missing — use `delete` instead.",'- `content` — writes the provided `content` argument (e.g. a per-hunk merged result, or the live Y.Text bytes the user sees in the DiffView). The provided string must be non-empty — use `delete` to remove the file entirely (an agent constructing a per-hunk merge that happens to land on `""` gets a 400 at the Zod boundary rather than a misleading 500).','- `delete` — runs `git rm <file>` then commits the deletion. Honors deletion intent for delete-modify (DU: "keep deletion") and modify-delete (UD: "accept their deletion") shapes. Inspect the `shape` field on `conflicts({ kind: "content" })` to pick the right strategy for the conflict shape.',``,'Returns 200 on success. 422 (`urn:ok:error:unresolved-conflict-markers`) means the `content` you sent still contains a `<<<<<<< … >>>>>>>` block — a permanent rejection of those bytes, so resolve every region before retrying rather than re-sending. 500 indicates commit failure (re-call `conflicts({ kind: "list" })` to confirm post-state — the resolve API is best-effort, non-atomic, and the file may have been resolved by another session).',``,`**DESTRUCTIVE:** this modifies the working tree and creates a git commit.`,``,`**Parameters:**`,"- `file` — Relative-to-projectDir path WITH .md extension (e.g. `notes/sso.md`).","- `strategy` — One of `mine` | `theirs` | `content` | `delete`.",'- `content` — Required (non-empty) when `strategy === "content"`; ignored otherwise.'].join(`
825
825
  `),f6({ok:L(),file:F()}),["[Requires: Hocuspocus server] Restore a DOCUMENT (CRDT, append-only) or a SKILL (fs-direct) to a historical version. Pass EXACTLY ONE of `document` or `skill`.",``,`**Parameters:**`,"- `document` — The document to restore (path, no extension; trailing `.md`/`.mdx` is stripped). Append-only via the CRDT layer; all connected editors see the change live.","- `skill` — The skill NAME to restore (PROJECT-scope skills only — global skills are unversioned). Rewrites the skill folder to the target version (fs-direct); every recorded copy re-syncs from it, so there is nothing to re-install.","- `version` — The 40-character commit SHA to restore to. Copy it from the `history` tool (same field name there).","- `summary` — Optional one-line summary (≤80 chars). Avoid secrets or PII — persisted to git history.",``,'A response may include `structuredContent.warnings` (kind `content-divergence`) when the restored `Y.Text` does not byte-match the target-version bytes. The restore still landed; re-read the doc with `exec("cat <document>")` to see what converged.'].join(`
826
826
  `),["[Requires: Hocuspocus server] Ranked retrieval across ALL non-ignored files (markdown by title/body, other file types by name/path, plus folders) — pair with `exec` `grep` for exhaustive content search. The cmd-K engine (title boost + body BM25 + recency).",``,"NAMES/paths are indexed for all files; BODY content for markdown only. Two-tier agent model: run this fast indexed `search` (all files by name/path + markdown content) IN PARALLEL with `exec` (`grep`) for exhaustive literal-string content search across every file — instant ranked hits plus full content coverage. Reach for `exec` grep when you need to match content inside code/config/data files.",``,"When semantic search is enabled for the workspace (an opt-in setting with an API key), an embeddings signal is additionally fused into `full_text` ranking, surfacing conceptually-related pages that share no keywords. This tool opts in by default; the `semantic` block in the response reports coverage. Note: with semantic enabled, the query and matching page content are sent to the configured embeddings provider (content egress). Set `semantic: false` to force pure-lexical ranking for a call.",``,"Returns scored `page`, `folder`, and name-only `file` hits, each with a `signals` breakdown (lexical / fullText / recency / vector); markdown `page` hits also carry a body snippet (`file` hits never do — name-only).",``,'Cold start: right after the server boots, the response may carry `ready: false` with an empty `results` while the index is still building. That empty set is NOT authoritative — wait ~2-3 seconds, then retry (agents have no built-in delay, so do not retry in immediate succession). If it is still `ready: false` after 2-3 retries (e.g. a very large workspace), fall back to `exec("grep ...")` rather than polling further. Once `ready` is true/omitted the results are complete.',``,`**Parameters:**`,"- `query` — Free-form; tokenized across title, name, path segments, and (with `full_text`) body.","- `intent` (optional) — `omnibar` searches title/path/folders only (fast); `full_text` includes body. Default `full_text`.","- `scopes` (optional) — Result scope: `page` | `folder` | `file` | `content`. Defaults derive from `intent`.","- `limit` (optional) — Max rows; default 20, max 100.","- `semantic` (optional) — Set `false` to force pure-lexical ranking even when semantic search is enabled. Omit to use semantic when available.",``,'If the server is down, the tool returns a recovery hint — use `exec("grep ...")` as the server-free fallback.'].join(`
827
- `),F().describe(`Search query — title, path, or body terms.`),H([`omnibar`,`full_text`]).optional().describe(`'omnibar' for title/path/folder only (fast); 'full_text' includes body content. Default 'full_text'.`),z(H([`page`,`folder`,`content`,`file`])).optional().describe(`Override the default scope set. Members: 'page', 'folder', 'file', 'content'. Defaults derive from intent.`),I().int().min(1).max(100).optional().describe(`Max rows; default 20, max 100.`),L().optional().describe(`Set false to force pure-lexical ranking for this call even when semantic search is enabled. Omit to use semantic when available.`),F().optional().describe(d6);const QSe=B({kind:H([`page`,`folder`,`file`]),path:F(),docName:F(),title:F().nullable(),score:I(),signals:B({lexical:I(),fullText:I(),recency:I(),vector:I().optional()}),snippet:F().optional(),previewUrl:F().nullable(),previewUrlSource:H(qSe).optional()}),$Se=B({capable:L(),applied:L(),coverage:B({embedded:I().int(),total:I().int()})});f6({cwd:F(),query:F(),intent:F(),resultCount:I().int(),results:z(QSe),elapsedMs:I().nullable(),semantic:$Se.optional(),ready:U(!1).optional()}),["[Requires: Hocuspocus server] Build a shareable GitHub-substrate URL (`https://openknowledge.ai/d/...`) pinned to the project's current branch + the focused target (a doc or a folder). Read-only against the working tree — no commits, no pushes, no `git fetch`.",``,`Use this when the user asks for a share link / shareable link / URL to send to a teammate. Recipients open the link to receive the doc (or folder subtree) into their own OpenKnowledge install.`,``,"**Publishing is a user act.** Agents do NOT publish projects to GitHub from this tool. When the project has no GitHub remote, this tool returns an error pointing the user at the Share wizard (or `gh repo create` + `git push`) — it does not run those steps itself.",``,`**Parameters:**`,'- `path` — Content-dir-relative target. For a doc, extension-less (trailing `.md`/`.mdx` is stripped; the on-disk file is probed automatically). For a folder, the directory path. The empty string `""` is the content-root sentinel (folder-only).',"- `kind` (optional) — `'doc'` or `'folder'`. Omit to auto-probe disk (`.mdx` → `.md` → directory, first hit wins). REQUIRED when `path` is empty (`\"\"`), since auto-probe cannot disambiguate the root.","- `cwd` (optional) — Project root (see `cwd` description below).",``,"**Preconditions:** project on a named branch (not detached HEAD); origin set to a GitHub remote (`github.com` or a GitHub Enterprise Server host); the branch already pushed to origin."].join(`
828
- `),f6({ok:L().describe(`Success discriminator.`),shareUrl:F().optional().describe(`Marketing share URL (success only).`),sharedUrl:F().optional().describe(`Unencoded GitHub blob/tree URL (success only).`),branch:F().optional().describe(`Branch the share URL pins to (success only).`),resolvedKind:H([`doc`,`folder`]).optional().describe(`Kind the target resolved to (success only).`),freshness:Ow.optional().describe(`Whether the shared target matches origin (success only): current, stale (unpushed edits), absent (not on origin, a push fixes it), or empty (a folder holding nothing git can track, which no push fixes). Omitted when the probe could not run.`),error:H([...Dw.options,`target-not-found`,`kind-mismatch`,`unknown`]).optional().describe(`Failure code (error path only).`),message:F().optional().describe(`Agent-actionable error message (error path only).`),previewUrl:F().nullable().optional().describe("Route-only preview URL (no host:port): `/#/<doc>` for a doc, `/#/<folder>/` for a folder, `/#/` for the content root. `null` when no UI is running."),previewUrlSource:F().optional().describe(`Internal: preview-URL provenance.`)});const $8="Which level the skill lives at. `project` = lives in this KB (wherever its folder is; shared via git); `global` = user-level under your home dir (available in every project on this machine, not shared).",eCe=B({id:F().describe("Location id — editor host id, `agents`, or a custom root path. Pass to `install`."),path:F().describe('Base-relative bundle dir (e.g. ".claude/skills/x"). INFORMATIONAL — for showing a user where a location lives. Skills are addressed by `name` + `scope`: pass `id` to `install`, and read bundle files with `skills({ name, file })`, never by handing this path to `exec` or a native file tool.'),role:H([`source`,`copy`,`symlink`]).describe(`source = the REAL folder (the skill itself); copy = independent folder, auto-refreshed from the source until hand-edited (then it forks); symlink = live link to the source.`),audience:z(F()).optional().describe(`Folders that RESOLVE INTO this location (folder-level symlinks) — their agents read what lands here.`),drift:L().optional().describe(`Something outside OK rewrote this path since OK last wrote it.`)});B({name:F().describe("Skill name (its identity; pass to `edit`/`move`/`delete`/`install`)."),scope:H([`project`,`global`]).describe($8),description:F().optional().describe(`The skill's one-line description (when present).`),installed:L().describe('Always true for a managed skill — its source folder IS the skill, so it is never "not installed". Read `locations[]` for where it actually lives.'),hosts:z(F()).describe(`Flat location ids (locations[].id), SOURCE first — legacy projection.`),locations:z(eCe).describe("Everywhere the skill lives. Exactly one `source` (the skill's real folder); every other entry is a managed copy or symlink of it."),mode:H([`copy`,`link`]).describe("The form a NEW location would take, derived from the ones the skill already uses. Not a stored preference and not a claim about existing locations — read `locations[].role` for those."),conflicts:z(F()).optional().describe(`Host ids where a DIFFERENT skill with this name occupies the slot.`)});const tCe=B({path:F().describe(`Skill-relative path (e.g. "references/tiers.md").`),kind:H([`reference`,`script`]).describe("`script` for anything under scripts/; `reference` for every other bundle file.")});B({name:F().describe(`Skill name (its identity).`),scope:H([`project`,`global`]).describe($8),description:F().describe(`The skill's one-line description (empty if none).`),body:F().describe(`The SKILL.md body (markdown, frontmatter stripped).`),files:z(tCe).describe("Bundle files beside SKILL.md (path + kind, no inline text). Read one via `file`.")}),B({path:F().describe(`Skill-relative path read.`),kind:H([`reference`,`script`]).describe("`reference` or `script`."),text:F().describe(`Full text of the bundle file.`)}),B({name:F().describe("Skill name to pass as `skill` to `import`."),source:F().describe("Import-ready repository coordinates or website hostname. Pass this exact value to `import`."),description:F().describe(`Marketplace description for deciding whether the skill matches the task.`),installs:I().int().nonnegative().nullable().describe(`skills.sh install count, if known.`),publisher:F().nullable().describe(`Publisher, website, or GitHub owner, if known.`)}),["[Requires: Hocuspocus server] Read-only discovery for SKILLS — the read half of the skill vocabulary (`write`/`edit`/`delete`/`move`/`install` are the mutate half).",``,"This is how you search the marketplace, list managed skills, and read managed skill content. Managed skills are addressed by `name` + `scope`, NOT by path — do NOT `ls`/`cat` `.ok/skills/` or pass raw `.ok/...` paths; `.ok/` is opaque internal state.",``,"Marketplace rows are external candidates; they are NOT managed content until you call `import({ source, skill: name })`, and they are NOT active in editors until `install` projects them.",``,"OpenKnowledge's own built-in `open-knowledge*` skills (e.g. the `open-knowledge` project skill) are runtime skills already loaded in your skill list — they are NOT here, and you never fetch them through this tool.",``,`**Four modes:**`,"- **Marketplace search** (pass `query`): search skills.sh and return import-ready rows (`name`, `source`, `description`, `publisher`, installs). Use when a user asks to find/browse/add an external skill. Then call `import({ source, skill: name })` on the chosen row.","- **List** (omit `name`): every skill across BOTH levels — Project (this KB) and Global (user-level). Returns name, scope, description, installed/hosts.","- **Read skill** (pass `name`): that skill's description + body + a `files` list (`{ path, kind }`, no inline text) of its bundle files (`references/**`, `scripts/**`, and any other file the skill ships). `scope` optional — omitted, it resolves by name (preferring Project when a name exists at both levels).","- **Read file** (pass `name` + `file`): one bundle file's text — the universal read path for references + scripts (no native `cat`)."].join(`
827
+ `),F().describe(`Search query — title, path, or body terms.`),H([`omnibar`,`full_text`]).optional().describe(`'omnibar' for title/path/folder only (fast); 'full_text' includes body content. Default 'full_text'.`),z(H([`page`,`folder`,`content`,`file`])).optional().describe(`Override the default scope set. Members: 'page', 'folder', 'file', 'content'. Defaults derive from intent.`),I().int().min(1).max(100).optional().describe(`Max rows; default 20, max 100.`),L().optional().describe(`Set false to force pure-lexical ranking for this call even when semantic search is enabled. Omit to use semantic when available.`),F().optional().describe(d6);const $Se=B({kind:H([`page`,`folder`,`file`]),path:F(),docName:F(),title:F().nullable(),score:I(),signals:B({lexical:I(),fullText:I(),recency:I(),vector:I().optional()}),snippet:F().optional(),previewUrl:F().nullable(),previewUrlSource:H(qSe).optional()}),eCe=B({capable:L(),applied:L(),coverage:B({embedded:I().int(),total:I().int()})});f6({cwd:F(),query:F(),intent:F(),resultCount:I().int(),results:z($Se),elapsedMs:I().nullable(),semantic:eCe.optional(),ready:U(!1).optional()}),["[Requires: Hocuspocus server] Build a shareable GitHub-substrate URL (`https://openknowledge.ai/d/...`) pinned to the project's current branch + the focused target (a doc or a folder). Read-only against the working tree — no commits, no pushes, no `git fetch`.",``,`Use this when the user asks for a share link / shareable link / URL to send to a teammate. Recipients open the link to receive the doc (or folder subtree) into their own OpenKnowledge install.`,``,"**Publishing is a user act.** Agents do NOT publish projects to GitHub from this tool. When the project has no GitHub remote, this tool returns an error pointing the user at the Share wizard (or `gh repo create` + `git push`) — it does not run those steps itself.",``,`**Parameters:**`,'- `path` — Content-dir-relative target. For a doc, extension-less (trailing `.md`/`.mdx` is stripped; the on-disk file is probed automatically). For a folder, the directory path. The empty string `""` is the content-root sentinel (folder-only).',"- `kind` (optional) — `'doc'` or `'folder'`. Omit to auto-probe disk (`.mdx` → `.md` → directory, first hit wins). REQUIRED when `path` is empty (`\"\"`), since auto-probe cannot disambiguate the root.","- `cwd` (optional) — Project root (see `cwd` description below).",``,"**Preconditions:** project on a named branch (not detached HEAD); origin set to a GitHub remote (`github.com` or a GitHub Enterprise Server host); the branch already pushed to origin."].join(`
828
+ `),f6({ok:L().describe(`Success discriminator.`),shareUrl:F().optional().describe(`Marketing share URL (success only).`),sharedUrl:F().optional().describe(`Unencoded GitHub blob/tree URL (success only).`),branch:F().optional().describe(`Branch the share URL pins to (success only).`),resolvedKind:H([`doc`,`folder`]).optional().describe(`Kind the target resolved to (success only).`),freshness:Ow.optional().describe(`Whether the shared target matches origin (success only): current, stale (unpushed edits), absent (not on origin, a push fixes it), or empty (a folder holding nothing git can track, which no push fixes). Omitted when the probe could not run.`),error:H([...Dw.options,`target-not-found`,`kind-mismatch`,`unknown`]).optional().describe(`Failure code (error path only).`),message:F().optional().describe(`Agent-actionable error message (error path only).`),previewUrl:F().nullable().optional().describe("Route-only preview URL (no host:port): `/#/<doc>` for a doc, `/#/<folder>/` for a folder, `/#/` for the content root. `null` when no UI is running."),previewUrlSource:F().optional().describe(`Internal: preview-URL provenance.`)});const $8="Which level the skill lives at. `project` = lives in this KB (wherever its folder is; shared via git); `global` = user-level under your home dir (available in every project on this machine, not shared).",tCe=B({id:F().describe("Location id — editor host id, `agents`, or a custom root path. Pass to `install`."),path:F().describe('Base-relative bundle dir (e.g. ".claude/skills/x"). INFORMATIONAL — for showing a user where a location lives. Skills are addressed by `name` + `scope`: pass `id` to `install`, and read bundle files with `skills({ name, file })`, never by handing this path to `exec` or a native file tool.'),role:H([`source`,`copy`,`symlink`]).describe(`source = the REAL folder (the skill itself); copy = independent folder, auto-refreshed from the source until hand-edited (then it forks); symlink = live link to the source.`),audience:z(F()).optional().describe(`Folders that RESOLVE INTO this location (folder-level symlinks) — their agents read what lands here.`),drift:L().optional().describe(`Something outside OK rewrote this path since OK last wrote it.`)});B({name:F().describe("Skill name (its identity; pass to `edit`/`move`/`delete`/`install`)."),scope:H([`project`,`global`]).describe($8),description:F().optional().describe(`The skill's one-line description (when present).`),installed:L().describe('Always true for a managed skill — its source folder IS the skill, so it is never "not installed". Read `locations[]` for where it actually lives.'),hosts:z(F()).describe(`Flat location ids (locations[].id), SOURCE first — legacy projection.`),locations:z(tCe).describe("Everywhere the skill lives. Exactly one `source` (the skill's real folder); every other entry is a managed copy or symlink of it."),mode:H([`copy`,`link`]).describe("The form a NEW location would take, derived from the ones the skill already uses. Not a stored preference and not a claim about existing locations — read `locations[].role` for those."),conflicts:z(F()).optional().describe(`Host ids where a DIFFERENT skill with this name occupies the slot.`)});const nCe=B({path:F().describe(`Skill-relative path (e.g. "references/tiers.md").`),kind:H([`reference`,`script`]).describe("`script` for anything under scripts/; `reference` for every other bundle file.")});B({name:F().describe(`Skill name (its identity).`),scope:H([`project`,`global`]).describe($8),description:F().describe(`The skill's one-line description (empty if none).`),body:F().describe(`The SKILL.md body (markdown, frontmatter stripped).`),files:z(nCe).describe("Bundle files beside SKILL.md (path + kind, no inline text). Read one via `file`.")}),B({path:F().describe(`Skill-relative path read.`),kind:H([`reference`,`script`]).describe("`reference` or `script`."),text:F().describe(`Full text of the bundle file.`)}),B({name:F().describe("Skill name to pass as `skill` to `import`."),source:F().describe("Import-ready repository coordinates or website hostname. Pass this exact value to `import`."),description:F().describe(`Marketplace description for deciding whether the skill matches the task.`),installs:I().int().nonnegative().nullable().describe(`skills.sh install count, if known.`),publisher:F().nullable().describe(`Publisher, website, or GitHub owner, if known.`)}),["[Requires: Hocuspocus server] Read-only discovery for SKILLS — the read half of the skill vocabulary (`write`/`edit`/`delete`/`move`/`install` are the mutate half).",``,"This is how you search the marketplace, list managed skills, and read managed skill content. Managed skills are addressed by `name` + `scope`, NOT by path — do NOT `ls`/`cat` `.ok/skills/` or pass raw `.ok/...` paths; `.ok/` is opaque internal state.",``,"Marketplace rows are external candidates; they are NOT managed content until you call `import({ source, skill: name })`, and they are NOT active in editors until `install` projects them.",``,"OpenKnowledge's own built-in `open-knowledge*` skills (e.g. the `open-knowledge` project skill) are runtime skills already loaded in your skill list — they are NOT here, and you never fetch them through this tool.",``,`**Four modes:**`,"- **Marketplace search** (pass `query`): search skills.sh and return import-ready rows (`name`, `source`, `description`, `publisher`, installs). Use when a user asks to find/browse/add an external skill. Then call `import({ source, skill: name })` on the chosen row.","- **List** (omit `name`): every skill across BOTH levels — Project (this KB) and Global (user-level). Returns name, scope, description, installed/hosts.","- **Read skill** (pass `name`): that skill's description + body + a `files` list (`{ path, kind }`, no inline text) of its bundle files (`references/**`, `scripts/**`, and any other file the skill ships). `scope` optional — omitted, it resolves by name (preferring Project when a name exists at both levels).","- **Read file** (pass `name` + `file`): one bundle file's text — the universal read path for references + scripts (no native `cat`)."].join(`
829
829
  `),`${["Create or replace one thing. Pass EXACTLY ONE of `document`, `folder`, `template`, `skill`, or `asset` (or `documents` for a batch of docs).",``,'- `document` — Create or overwrite a doc via the CRDT layer [Requires: Hocuspocus server]. `{ path, content }`, or `{ path, template }` to instantiate from a folder template (mutually exclusive with `content`). Optional `frontmatter` (its own YAML) and `position` (`replace` default for a new doc; required for an existing one) — note supplying `frontmatter` alongside literal `content` forces `position: replace` (the only position that persists a YAML block), overriding an explicit `append`/`prepend`. Example: `{ document: { path: "meetings/standup", content: "# Standup\\n..." } }`.','- `folder` — Create a NEW folder (optionally with its own properties) [Requires: Hocuspocus server]. `{ path, frontmatter? }`. To change an EXISTING folder use `edit`. Example: `{ folder: { path: "ideas" } }`.','- `template` — Create a reusable starting shape for new docs in a folder. `{ path: "<folder>/<name>", content, frontmatter: { title, description?, tags? } }`.','- `skill` — Create or overwrite an agent SKILL: reusable agent guidance you author in OK and `install` into your editors. A NEW skill lands at the project\'s default skill home (e.g. `.agents/skills/<name>/`); an existing one is edited at its real folder. `{ name, description, body, scope? }`. `name` is the identity (lowercase-hyphen); `description` is the trigger (when to use it). Example: `{ skill: { name: "trip-log", description: "Use when logging a fishing trip.", body: "# Steps\\n..." } }`.','- `asset` — Upload a binary (image/file) via the media route [Requires: Hocuspocus server]. `{ path: "<folder>/<file.ext>", content(base64) | source(local path) }`.',"- `documents` — Batch: `[{ path, content?|template?, frontmatter?, position?, summary? }, ...]` written in order; the response reports each.","- `summary` — Optional one-line user-outcome (≤80 chars) for the timeline, for a single `document`/`folder`/`template`/`asset` write. For a `documents` batch, give each entry its own `summary` instead (a top-level `summary` is ignored on the batch path). Avoid secrets or PII — persisted to git history.",``,"Responses may include `structuredContent.document.warnings` (batch: per-entry under `documents[]`) — advisory entries discriminated by `kind`: `content-divergence` / `disk-edit-reconciled` (write-integrity — re-read the doc) and `mermaid-parse-error` (the write landed but that fence will not render — fix it and re-edit)."].join(`
830
- `)}${nY()}`;var e5=i(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),t5=i(((e,n)=>{let{EMPTY_BUFFER:r}=e5(),i=Buffer[Symbol.species];function a(e,t){if(e.length===0)return r;if(e.length===1)return e[0];let n=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let r=e[t];n.set(r,a),a+=r.length}return a<t?new i(n.buffer,n.byteOffset,a):n}function o(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function s(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function c(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function l(e){if(l.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new i(e):ArrayBuffer.isView(e)?t=new i(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),l.readOnly=!1),t}if(n.exports={concat:a,mask:o,toArrayBuffer:c,toBuffer:l,unmask:s},!process.env.WS_NO_BUFFER_UTIL)try{let e=t(`bufferutil`);n.exports.mask=function(t,n,r,i,a){a<48?o(t,n,r,i,a):e.mask(t,n,r,i,a)},n.exports.unmask=function(t,n){t.length<32?s(t,n):e.unmask(t,n)}}catch{}})),nCe=i(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),n5=i(((e,n)=>{let r=t(`zlib`),i=t5(),a=nCe(),{kStatusCode:o}=e5(),s=Buffer[Symbol.species],c=Buffer.from([0,0,255,255]),l=Symbol(`permessage-deflate`),u=Symbol(`total-length`),d=Symbol(`callback`),f=Symbol(`buffers`),p=Symbol(`error`),m;n.exports=class{constructor(e){this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,m||=new a(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[d];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){m.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){m.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,n){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:r.Z_DEFAULT_WINDOWBITS;this._inflate=r.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[l]=this,this._inflate[u]=0,this._inflate[f]=[],this._inflate.on(`error`,_),this._inflate.on(`data`,g)}this._inflate[d]=n,this._inflate.write(e),t&&this._inflate.write(c),this._inflate.flush(()=>{let e=this._inflate[p];if(e){this._inflate.close(),this._inflate=null,n(e);return}let r=i.concat(this._inflate[f],this._inflate[u]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[u]=0,this._inflate[f]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),n(null,r)})}_compress(e,t,n){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:r.Z_DEFAULT_WINDOWBITS;this._deflate=r.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[u]=0,this._deflate[f]=[],this._deflate.on(`data`,h)}this._deflate[d]=n,this._deflate.write(e),this._deflate.flush(r.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=i.concat(this._deflate[f],this._deflate[u]);t&&(e=new s(e.buffer,e.byteOffset,e.length-4)),this._deflate[d]=null,this._deflate[u]=0,this._deflate[f]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),n(null,e)})}};function h(e){this[f].push(e),this[u]+=e.length}function g(e){if(this[u]+=e.length,this[l]._maxPayload<1||this[u]<=this[l]._maxPayload){this[f].push(e);return}this[p]=RangeError(`Max payload size exceeded`),this[p].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[p][o]=1009,this.removeListener(`data`,g),this.reset()}function _(e){if(this[l]._inflate=null,this[p]){this[d](this[p]);return}e[o]=1007,this[d](e)}})),r5=i(((e,n)=>{let{isUtf8:r}=t(`buffer`),{hasBlob:i}=e5(),a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function o(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function s(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function c(e){return i&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(n.exports={isBlob:c,isValidStatusCode:o,isValidUTF8:s,tokenChars:a},r)n.exports.isValidUTF8=function(e){return e.length<24?s(e):r(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=t(`utf-8-validate`);n.exports.isValidUTF8=function(t){return t.length<32?s(t):e(t)}}catch{}})),i5=i(((e,n)=>{let{Writable:r}=t(`stream`),i=n5(),{BINARY_TYPES:a,EMPTY_BUFFER:o,kStatusCode:s,kWebSocket:c}=e5(),{concat:l,toArrayBuffer:u,unmask:d}=t5(),{isValidStatusCode:f,isValidUTF8:p}=r5(),m=Buffer[Symbol.species];n.exports=class extends r{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||a[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[c]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,`Too many buffered chunks`,!1,1008,`WS_ERR_TOO_MANY_BUFFERED_PARTS`));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new m(t.buffer,t.byteOffset+e,t.length-e),new m(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new m(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[i.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=o;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&d(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}if(t.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){e(this.createError(RangeError,`Too many message fragments`,!1,1008,`WS_ERR_TOO_MANY_BUFFERED_PARTS`));return}this._messageLength=this._totalPayloadLength,this._fragments.push(t)}this.dataMessage(e)}decompress(e,t){this._extensions[i.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){t(this.createError(RangeError,`Too many message fragments`,!1,1008,`WS_ERR_TOO_MANY_BUFFERED_PARTS`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?l(n,t):this._binaryType===`arraybuffer`?u(l(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=l(n,t);if(!this._skipUTF8Validation&&!p(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,o),this.end();else{let n=e.readUInt16BE(0);if(!f(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new m(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!p(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[s]=r,a}}})),a5=i(((e,n)=>{let{Duplex:r}=t(`stream`),{randomFillSync:i}=t(`crypto`),{types:{isUint8Array:a}}=t(`util`),o=n5(),{EMPTY_BUFFER:s,kWebSocket:c,NOOP:l}=e5(),{isBlob:u,isValidStatusCode:d}=r5(),{mask:f,toBuffer:p}=t5(),m=Symbol(`kByteLength`),h=Buffer.alloc(4),g=8*1024,_,v=g;n.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=l,this[c]=void 0}static frame(e,t){let n,r=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||h,t.generateMask?t.generateMask(n):(v===g&&(_===void 0&&(_=Buffer.alloc(g)),i(_,0,g),v=0),n[0]=_[v++],n[1]=_[v++],n[2]=_[v++],n[3]=_[v++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[m]!==void 0?s=t[m]:(e=Buffer.from(e),s=e.length):(s=e.length,r=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(r?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:r?(f(e,n,l,a,s),[l]):(f(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=s;else if(typeof t!=`number`||!d(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);if(o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`)o.write(n,2);else if(a(n))o.set(n,2);else throw TypeError(`Second argument must be a string or a Uint8Array`)}let c={[m]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,c),i):this.enqueue([this.dispatch,o,!1,c,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):u(t)?(i=t.size,a=!1):(t=p(t),i=t.length,a=p.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[m]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};u(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):u(t)?(i=t.size,a=!1):(t=p(t),i=t.length,a=p.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[m]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};u(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[o.extensionName],i=t.binary?2:1,a=t.compress,s,c;typeof e==`string`?(s=Buffer.byteLength(e),c=!1):u(e)?(s=e.size,c=!1):(e=p(e),s=e.length,c=p.readOnly),this._firstFragment?(this._firstFragment=!1,a&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(a=s>=r._threshold),this._compress=a):(a=!1,i=0),t.fin&&(this._firstFragment=!0);let l={[m]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:a};u(e)?this._state===0?this.getBlobData(e,this._compress,l,n):this.enqueue([this.getBlobData,e,this._compress,l,n]):this._state===0?this.dispatch(e,this._compress,l,n):this.enqueue([this.dispatch,e,this._compress,l,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[m],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(y,this,e,i);return}this._bufferedBytes-=r[m];let a=p(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(b,this,e,i)})}dispatch(t,n,r,i){if(!n){this.sendFrame(e.frame(t,r),i);return}let a=this._extensions[o.extensionName];this._bufferedBytes+=r[m],this._state=1,a.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){let e=Error(`The socket was closed while data was being compressed`);y(this,e,i);return}this._bufferedBytes-=r[m],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),i),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][m],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][m],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function y(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function b(e,t,n){y(e,t,n),e.onerror(t)}})),rCe=i(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=e5(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),o5=i(((e,t)=>{let{tokenChars:n}=r5();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),s5=i(((e,n)=>{let r=t(`events`),i=t(`https`),a=t(`http`),o=t(`net`),s=t(`tls`),{randomBytes:c,createHash:l}=t(`crypto`),{Duplex:u,Readable:d}=t(`stream`),{URL:f}=t(`url`),p=n5(),m=i5(),h=a5(),{isBlob:g}=r5(),{BINARY_TYPES:_,CLOSE_TIMEOUT:v,EMPTY_BUFFER:y,GUID:b,kForOnEventAttribute:x,kListener:S,kStatusCode:C,kWebSocket:w,NOOP:T}=e5(),{EventTarget:{addEventListener:E,removeEventListener:D}}=rCe(),{format:O,parse:ee}=o5(),{toBuffer:te}=t5(),ne=Symbol(`kAborted`),re=[8,13],ie=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],ae=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var oe=class e extends r{constructor(t,n,r){super(),this._binaryType=_[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=y,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),se(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){_.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new m({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new h(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[w]=this,a[w]=this,t[w]=this,i.on(`conclude`,j),i.on(`drain`,de),i.on(`error`,fe),i.on(`message`,me),i.on(`ping`,M),i.on(`pong`,N),a.onerror=ge,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,ve),t.on(`data`,ye),t.on(`end`,be),t.on(`error`,xe),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[p.extensionName]&&this._extensions[p.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){ue(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),_e(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){A(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||y,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){A(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||y,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){A(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[p.extensionName]||(i.compress=!1),this._sender.send(t||y,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){ue(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(oe,`CONNECTING`,{enumerable:!0,value:ie.indexOf(`CONNECTING`)}),Object.defineProperty(oe.prototype,`CONNECTING`,{enumerable:!0,value:ie.indexOf(`CONNECTING`)}),Object.defineProperty(oe,`OPEN`,{enumerable:!0,value:ie.indexOf(`OPEN`)}),Object.defineProperty(oe.prototype,`OPEN`,{enumerable:!0,value:ie.indexOf(`OPEN`)}),Object.defineProperty(oe,`CLOSING`,{enumerable:!0,value:ie.indexOf(`CLOSING`)}),Object.defineProperty(oe.prototype,`CLOSING`,{enumerable:!0,value:ie.indexOf(`CLOSING`)}),Object.defineProperty(oe,`CLOSED`,{enumerable:!0,value:ie.indexOf(`CLOSED`)}),Object.defineProperty(oe.prototype,`CLOSED`,{enumerable:!0,value:ie.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(oe.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(oe.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[x])return t[S];return null},set(t){for(let t of this.listeners(e))if(t[x]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[x]:!0})}})}),oe.prototype.addEventListener=E,oe.prototype.removeEventListener=D,n.exports=oe;function se(e,t,n,r){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:v,protocolVersion:re[1],maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!re.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${re.join(`, `)})`);let s;if(t instanceof f)s=t;else try{s=new f(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}s.protocol===`http:`?s.protocol=`ws:`:s.protocol===`https:`&&(s.protocol=`wss:`),e._url=s.href;let u=s.protocol===`wss:`,d=s.protocol===`ws+unix:`,m;if(s.protocol!==`ws:`&&!u&&!d?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:d&&!s.pathname?m=`The URL's pathname is empty`:s.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;k(e,t);return}let h=u?443:80,g=c(16).toString(`base64`),_=u?i.request:a.request,y=new Set,x;if(o.createConnection=o.createConnection||(u?le:ce),o.defaultPort=o.defaultPort||h,o.port=s.port||h,o.host=s.hostname.startsWith(`[`)?s.hostname.slice(1,-1):s.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=s.pathname+s.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new p({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers[`Sec-WebSocket-Extensions`]=O({[p.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!ae.test(e)||y.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);y.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(s.username||s.password)&&(o.auth=`${s.username}:${s.password}`),d){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=d,e._originalSecure=u,e._originalHostOrSocketPath=d?o.socketPath:s.host;let t=r&&r.headers;if(r={...r,headers:{}},t)for(let[e,n]of Object.entries(t))r.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=d?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:s.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!r.headers.authorization&&(r.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=_(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=_(o);o.timeout&&S.on(`timeout`,()=>{ue(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[ne]||(S=e._req=null,k(e,t))}),S.on(`response`,i=>{let a=i.headers.location,s=i.statusCode;if(a&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){ue(e,S,`Maximum redirects exceeded`);return}S.abort();let i;try{i=new f(a,t)}catch{k(e,SyntaxError(`Invalid URL: ${a}`));return}se(e,i,n,r)}else e.emit(`unexpected-response`,S,i)||ue(e,S,`Unexpected server response: ${i.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==oe.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){ue(e,n,`Invalid Upgrade header`);return}let a=l(`sha1`).update(g+b).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){ue(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],c;if(s===void 0?y.size&&(c=`Server sent no subprotocol`):y.size?y.has(s)||(c=`Server sent an invalid subprotocol`):c=`Server sent a subprotocol but none was requested`,c){ue(e,n,c);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){ue(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=ee(u)}catch{ue(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==p.extensionName){ue(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[p.extensionName])}catch{ue(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[p.extensionName]=x}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,e):S.end()}function k(e,t){e._readyState=oe.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function ce(e){return e.path=e.socketPath,o.connect(e)}function le(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=o.isIP(e.host)?``:e.host),s.connect(e)}function ue(e,t,n){e._readyState=oe.CLOSING;let r=Error(n);Error.captureStackTrace(r,ue),t.setHeader?(t[ne]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(k,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function A(e,t,n){if(t){let n=g(t)?t.size:te(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${ie[e.readyState]})`);process.nextTick(n,t)}}function j(e,t){let n=this[w];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[w]!==void 0&&(n._socket.removeListener(`data`,ye),process.nextTick(he,n._socket),e===1005?n.close():n.close(e,t))}function de(){let e=this[w];e.isPaused||e._socket.resume()}function fe(e){let t=this[w];t._socket[w]!==void 0&&(t._socket.removeListener(`data`,ye),process.nextTick(he,t._socket),t.close(e[C])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function pe(){this[w].emitClose()}function me(e,t){this[w].emit(`message`,e,t)}function M(e){let t=this[w];t._autoPong&&t.pong(e,!this._isServer,T),t.emit(`ping`,e)}function N(e){this[w].emit(`pong`,e)}function he(e){e.resume()}function ge(e){let t=this[w];t.readyState!==oe.CLOSED&&(t.readyState===oe.OPEN&&(t._readyState=oe.CLOSING,_e(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function _e(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function ve(){let e=this[w];if(this.removeListener(`close`,ve),this.removeListener(`data`,ye),this.removeListener(`end`,be),e._readyState=oe.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[w]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,pe),e._receiver.on(`finish`,pe))}function ye(e){this[w]._receiver.write(e)||this.pause()}function be(){let e=this[w];e._readyState=oe.CLOSING,e._receiver.end(),this.end()}function xe(){let e=this[w];this.removeListener(`error`,xe),this.on(`error`,T),e&&(e._readyState=oe.CLOSING,this.destroy())}})),iCe=i(((e,n)=>{s5();let{Duplex:r}=t(`stream`);function i(e){e.emit(`close`)}function a(){!this.destroyed&&this._writableState.finished&&this.destroy()}function o(e){this.removeListener(`error`,o),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function s(e,t){let n=!0,s=new r({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(n=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,r){if(e.readyState===e.CLOSED){r(t),process.nextTick(i,s);return}let a=!1;e.once(`error`,function(e){a=!0,r(e)}),e.once(`close`,function(){a||r(t),process.nextTick(i,s)}),n&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,a),s.on(`error`,o),s}n.exports=s})),c5=i(((e,t)=>{let{tokenChars:n}=r5();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),aCe=i(((e,n)=>{let r=t(`events`),i=t(`http`),{Duplex:a}=t(`stream`),{createHash:o}=t(`crypto`),s=o5(),c=n5(),l=c5(),u=s5(),{CLOSE_TIMEOUT:d,GUID:f,kWebSocket:p}=e5(),m=/^[+/0-9A-Za-z]{22}==$/;n.exports=class extends r{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:d,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:u,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=i.createServer((e,t)=>{let n=i.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=h(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(g,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(g,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{g(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,_);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,o=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){y(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){y(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!m.test(i)){y(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(o!==13&&o!==8){y(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){v(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=l.parse(u)}catch{y(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],p={};if(this.options.perMessageDeflate&&f!==void 0){let n=new c({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let e=s.parse(f);e[c.extensionName]&&(n.accept(e[c.extensionName]),p[c.extensionName]=n)}catch{y(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${o===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return v(t,o||401,s,c);this.completeUpgrade(p,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return v(t,401)}this.completeUpgrade(p,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,a,l){if(!i.readable||!i.writable)return i.destroy();if(i[p])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return v(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${o(`sha1`).update(t+f).digest(`base64`)}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),d._protocol=e)}if(e[c.extensionName]){let t=e[c.extensionName].params,n=s.format({[c.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),d._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
830
+ `)}${nY()}`;var e5=i(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),t5=i(((e,n)=>{let{EMPTY_BUFFER:r}=e5(),i=Buffer[Symbol.species];function a(e,t){if(e.length===0)return r;if(e.length===1)return e[0];let n=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let r=e[t];n.set(r,a),a+=r.length}return a<t?new i(n.buffer,n.byteOffset,a):n}function o(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function s(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function c(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function l(e){if(l.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new i(e):ArrayBuffer.isView(e)?t=new i(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),l.readOnly=!1),t}if(n.exports={concat:a,mask:o,toArrayBuffer:c,toBuffer:l,unmask:s},!process.env.WS_NO_BUFFER_UTIL)try{let e=t(`bufferutil`);n.exports.mask=function(t,n,r,i,a){a<48?o(t,n,r,i,a):e.mask(t,n,r,i,a)},n.exports.unmask=function(t,n){t.length<32?s(t,n):e.unmask(t,n)}}catch{}})),rCe=i(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),n5=i(((e,n)=>{let r=t(`zlib`),i=t5(),a=rCe(),{kStatusCode:o}=e5(),s=Buffer[Symbol.species],c=Buffer.from([0,0,255,255]),l=Symbol(`permessage-deflate`),u=Symbol(`total-length`),d=Symbol(`callback`),f=Symbol(`buffers`),p=Symbol(`error`),m;n.exports=class{constructor(e){this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,m||=new a(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[d];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){m.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){m.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,n){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:r.Z_DEFAULT_WINDOWBITS;this._inflate=r.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[l]=this,this._inflate[u]=0,this._inflate[f]=[],this._inflate.on(`error`,_),this._inflate.on(`data`,g)}this._inflate[d]=n,this._inflate.write(e),t&&this._inflate.write(c),this._inflate.flush(()=>{let e=this._inflate[p];if(e){this._inflate.close(),this._inflate=null,n(e);return}let r=i.concat(this._inflate[f],this._inflate[u]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[u]=0,this._inflate[f]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),n(null,r)})}_compress(e,t,n){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:r.Z_DEFAULT_WINDOWBITS;this._deflate=r.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[u]=0,this._deflate[f]=[],this._deflate.on(`data`,h)}this._deflate[d]=n,this._deflate.write(e),this._deflate.flush(r.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=i.concat(this._deflate[f],this._deflate[u]);t&&(e=new s(e.buffer,e.byteOffset,e.length-4)),this._deflate[d]=null,this._deflate[u]=0,this._deflate[f]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),n(null,e)})}};function h(e){this[f].push(e),this[u]+=e.length}function g(e){if(this[u]+=e.length,this[l]._maxPayload<1||this[u]<=this[l]._maxPayload){this[f].push(e);return}this[p]=RangeError(`Max payload size exceeded`),this[p].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[p][o]=1009,this.removeListener(`data`,g),this.reset()}function _(e){if(this[l]._inflate=null,this[p]){this[d](this[p]);return}e[o]=1007,this[d](e)}})),r5=i(((e,n)=>{let{isUtf8:r}=t(`buffer`),{hasBlob:i}=e5(),a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function o(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function s(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function c(e){return i&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(n.exports={isBlob:c,isValidStatusCode:o,isValidUTF8:s,tokenChars:a},r)n.exports.isValidUTF8=function(e){return e.length<24?s(e):r(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=t(`utf-8-validate`);n.exports.isValidUTF8=function(t){return t.length<32?s(t):e(t)}}catch{}})),i5=i(((e,n)=>{let{Writable:r}=t(`stream`),i=n5(),{BINARY_TYPES:a,EMPTY_BUFFER:o,kStatusCode:s,kWebSocket:c}=e5(),{concat:l,toArrayBuffer:u,unmask:d}=t5(),{isValidStatusCode:f,isValidUTF8:p}=r5(),m=Buffer[Symbol.species];n.exports=class extends r{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||a[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[c]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,`Too many buffered chunks`,!1,1008,`WS_ERR_TOO_MANY_BUFFERED_PARTS`));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new m(t.buffer,t.byteOffset+e,t.length-e),new m(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new m(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[i.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=o;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&d(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}if(t.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){e(this.createError(RangeError,`Too many message fragments`,!1,1008,`WS_ERR_TOO_MANY_BUFFERED_PARTS`));return}this._messageLength=this._totalPayloadLength,this._fragments.push(t)}this.dataMessage(e)}decompress(e,t){this._extensions[i.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){t(this.createError(RangeError,`Too many message fragments`,!1,1008,`WS_ERR_TOO_MANY_BUFFERED_PARTS`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?l(n,t):this._binaryType===`arraybuffer`?u(l(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=l(n,t);if(!this._skipUTF8Validation&&!p(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,o),this.end();else{let n=e.readUInt16BE(0);if(!f(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new m(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!p(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[s]=r,a}}})),a5=i(((e,n)=>{let{Duplex:r}=t(`stream`),{randomFillSync:i}=t(`crypto`),{types:{isUint8Array:a}}=t(`util`),o=n5(),{EMPTY_BUFFER:s,kWebSocket:c,NOOP:l}=e5(),{isBlob:u,isValidStatusCode:d}=r5(),{mask:f,toBuffer:p}=t5(),m=Symbol(`kByteLength`),h=Buffer.alloc(4),g=8*1024,_,v=g;n.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=l,this[c]=void 0}static frame(e,t){let n,r=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||h,t.generateMask?t.generateMask(n):(v===g&&(_===void 0&&(_=Buffer.alloc(g)),i(_,0,g),v=0),n[0]=_[v++],n[1]=_[v++],n[2]=_[v++],n[3]=_[v++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[m]!==void 0?s=t[m]:(e=Buffer.from(e),s=e.length):(s=e.length,r=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(r?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:r?(f(e,n,l,a,s),[l]):(f(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=s;else if(typeof t!=`number`||!d(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);if(o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`)o.write(n,2);else if(a(n))o.set(n,2);else throw TypeError(`Second argument must be a string or a Uint8Array`)}let c={[m]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,c),i):this.enqueue([this.dispatch,o,!1,c,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):u(t)?(i=t.size,a=!1):(t=p(t),i=t.length,a=p.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[m]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};u(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):u(t)?(i=t.size,a=!1):(t=p(t),i=t.length,a=p.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[m]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};u(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[o.extensionName],i=t.binary?2:1,a=t.compress,s,c;typeof e==`string`?(s=Buffer.byteLength(e),c=!1):u(e)?(s=e.size,c=!1):(e=p(e),s=e.length,c=p.readOnly),this._firstFragment?(this._firstFragment=!1,a&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(a=s>=r._threshold),this._compress=a):(a=!1,i=0),t.fin&&(this._firstFragment=!0);let l={[m]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:a};u(e)?this._state===0?this.getBlobData(e,this._compress,l,n):this.enqueue([this.getBlobData,e,this._compress,l,n]):this._state===0?this.dispatch(e,this._compress,l,n):this.enqueue([this.dispatch,e,this._compress,l,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[m],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(y,this,e,i);return}this._bufferedBytes-=r[m];let a=p(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(b,this,e,i)})}dispatch(t,n,r,i){if(!n){this.sendFrame(e.frame(t,r),i);return}let a=this._extensions[o.extensionName];this._bufferedBytes+=r[m],this._state=1,a.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){let e=Error(`The socket was closed while data was being compressed`);y(this,e,i);return}this._bufferedBytes-=r[m],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),i),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][m],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][m],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function y(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function b(e,t,n){y(e,t,n),e.onerror(t)}})),iCe=i(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=e5(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),o5=i(((e,t)=>{let{tokenChars:n}=r5();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),s5=i(((e,n)=>{let r=t(`events`),i=t(`https`),a=t(`http`),o=t(`net`),s=t(`tls`),{randomBytes:c,createHash:l}=t(`crypto`),{Duplex:u,Readable:d}=t(`stream`),{URL:f}=t(`url`),p=n5(),m=i5(),h=a5(),{isBlob:g}=r5(),{BINARY_TYPES:_,CLOSE_TIMEOUT:v,EMPTY_BUFFER:y,GUID:b,kForOnEventAttribute:x,kListener:S,kStatusCode:C,kWebSocket:w,NOOP:T}=e5(),{EventTarget:{addEventListener:E,removeEventListener:D}}=iCe(),{format:O,parse:ee}=o5(),{toBuffer:te}=t5(),ne=Symbol(`kAborted`),re=[8,13],ie=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],ae=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var oe=class e extends r{constructor(t,n,r){super(),this._binaryType=_[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=y,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),se(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){_.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new m({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new h(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[w]=this,a[w]=this,t[w]=this,i.on(`conclude`,j),i.on(`drain`,de),i.on(`error`,fe),i.on(`message`,me),i.on(`ping`,M),i.on(`pong`,N),a.onerror=ge,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,ve),t.on(`data`,ye),t.on(`end`,be),t.on(`error`,xe),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[p.extensionName]&&this._extensions[p.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){ue(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),_e(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){A(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||y,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){A(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||y,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){A(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[p.extensionName]||(i.compress=!1),this._sender.send(t||y,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){ue(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(oe,`CONNECTING`,{enumerable:!0,value:ie.indexOf(`CONNECTING`)}),Object.defineProperty(oe.prototype,`CONNECTING`,{enumerable:!0,value:ie.indexOf(`CONNECTING`)}),Object.defineProperty(oe,`OPEN`,{enumerable:!0,value:ie.indexOf(`OPEN`)}),Object.defineProperty(oe.prototype,`OPEN`,{enumerable:!0,value:ie.indexOf(`OPEN`)}),Object.defineProperty(oe,`CLOSING`,{enumerable:!0,value:ie.indexOf(`CLOSING`)}),Object.defineProperty(oe.prototype,`CLOSING`,{enumerable:!0,value:ie.indexOf(`CLOSING`)}),Object.defineProperty(oe,`CLOSED`,{enumerable:!0,value:ie.indexOf(`CLOSED`)}),Object.defineProperty(oe.prototype,`CLOSED`,{enumerable:!0,value:ie.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(oe.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(oe.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[x])return t[S];return null},set(t){for(let t of this.listeners(e))if(t[x]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[x]:!0})}})}),oe.prototype.addEventListener=E,oe.prototype.removeEventListener=D,n.exports=oe;function se(e,t,n,r){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:v,protocolVersion:re[1],maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!re.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${re.join(`, `)})`);let s;if(t instanceof f)s=t;else try{s=new f(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}s.protocol===`http:`?s.protocol=`ws:`:s.protocol===`https:`&&(s.protocol=`wss:`),e._url=s.href;let u=s.protocol===`wss:`,d=s.protocol===`ws+unix:`,m;if(s.protocol!==`ws:`&&!u&&!d?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:d&&!s.pathname?m=`The URL's pathname is empty`:s.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;k(e,t);return}let h=u?443:80,g=c(16).toString(`base64`),_=u?i.request:a.request,y=new Set,x;if(o.createConnection=o.createConnection||(u?le:ce),o.defaultPort=o.defaultPort||h,o.port=s.port||h,o.host=s.hostname.startsWith(`[`)?s.hostname.slice(1,-1):s.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=s.pathname+s.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new p({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers[`Sec-WebSocket-Extensions`]=O({[p.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!ae.test(e)||y.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);y.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(s.username||s.password)&&(o.auth=`${s.username}:${s.password}`),d){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=d,e._originalSecure=u,e._originalHostOrSocketPath=d?o.socketPath:s.host;let t=r&&r.headers;if(r={...r,headers:{}},t)for(let[e,n]of Object.entries(t))r.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=d?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:s.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!r.headers.authorization&&(r.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=_(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=_(o);o.timeout&&S.on(`timeout`,()=>{ue(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[ne]||(S=e._req=null,k(e,t))}),S.on(`response`,i=>{let a=i.headers.location,s=i.statusCode;if(a&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){ue(e,S,`Maximum redirects exceeded`);return}S.abort();let i;try{i=new f(a,t)}catch{k(e,SyntaxError(`Invalid URL: ${a}`));return}se(e,i,n,r)}else e.emit(`unexpected-response`,S,i)||ue(e,S,`Unexpected server response: ${i.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==oe.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){ue(e,n,`Invalid Upgrade header`);return}let a=l(`sha1`).update(g+b).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){ue(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],c;if(s===void 0?y.size&&(c=`Server sent no subprotocol`):y.size?y.has(s)||(c=`Server sent an invalid subprotocol`):c=`Server sent a subprotocol but none was requested`,c){ue(e,n,c);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){ue(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=ee(u)}catch{ue(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==p.extensionName){ue(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[p.extensionName])}catch{ue(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[p.extensionName]=x}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,e):S.end()}function k(e,t){e._readyState=oe.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function ce(e){return e.path=e.socketPath,o.connect(e)}function le(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=o.isIP(e.host)?``:e.host),s.connect(e)}function ue(e,t,n){e._readyState=oe.CLOSING;let r=Error(n);Error.captureStackTrace(r,ue),t.setHeader?(t[ne]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(k,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function A(e,t,n){if(t){let n=g(t)?t.size:te(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${ie[e.readyState]})`);process.nextTick(n,t)}}function j(e,t){let n=this[w];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[w]!==void 0&&(n._socket.removeListener(`data`,ye),process.nextTick(he,n._socket),e===1005?n.close():n.close(e,t))}function de(){let e=this[w];e.isPaused||e._socket.resume()}function fe(e){let t=this[w];t._socket[w]!==void 0&&(t._socket.removeListener(`data`,ye),process.nextTick(he,t._socket),t.close(e[C])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function pe(){this[w].emitClose()}function me(e,t){this[w].emit(`message`,e,t)}function M(e){let t=this[w];t._autoPong&&t.pong(e,!this._isServer,T),t.emit(`ping`,e)}function N(e){this[w].emit(`pong`,e)}function he(e){e.resume()}function ge(e){let t=this[w];t.readyState!==oe.CLOSED&&(t.readyState===oe.OPEN&&(t._readyState=oe.CLOSING,_e(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function _e(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function ve(){let e=this[w];if(this.removeListener(`close`,ve),this.removeListener(`data`,ye),this.removeListener(`end`,be),e._readyState=oe.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[w]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,pe),e._receiver.on(`finish`,pe))}function ye(e){this[w]._receiver.write(e)||this.pause()}function be(){let e=this[w];e._readyState=oe.CLOSING,e._receiver.end(),this.end()}function xe(){let e=this[w];this.removeListener(`error`,xe),this.on(`error`,T),e&&(e._readyState=oe.CLOSING,this.destroy())}})),aCe=i(((e,n)=>{s5();let{Duplex:r}=t(`stream`);function i(e){e.emit(`close`)}function a(){!this.destroyed&&this._writableState.finished&&this.destroy()}function o(e){this.removeListener(`error`,o),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function s(e,t){let n=!0,s=new r({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(n=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,r){if(e.readyState===e.CLOSED){r(t),process.nextTick(i,s);return}let a=!1;e.once(`error`,function(e){a=!0,r(e)}),e.once(`close`,function(){a||r(t),process.nextTick(i,s)}),n&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,a),s.on(`error`,o),s}n.exports=s})),c5=i(((e,t)=>{let{tokenChars:n}=r5();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),oCe=i(((e,n)=>{let r=t(`events`),i=t(`http`),{Duplex:a}=t(`stream`),{createHash:o}=t(`crypto`),s=o5(),c=n5(),l=c5(),u=s5(),{CLOSE_TIMEOUT:d,GUID:f,kWebSocket:p}=e5(),m=/^[+/0-9A-Za-z]{22}==$/;n.exports=class extends r{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:d,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:u,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=i.createServer((e,t)=>{let n=i.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=h(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(g,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(g,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{g(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,_);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,o=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){y(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){y(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!m.test(i)){y(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(o!==13&&o!==8){y(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){v(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=l.parse(u)}catch{y(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],p={};if(this.options.perMessageDeflate&&f!==void 0){let n=new c({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let e=s.parse(f);e[c.extensionName]&&(n.accept(e[c.extensionName]),p[c.extensionName]=n)}catch{y(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${o===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return v(t,o||401,s,c);this.completeUpgrade(p,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return v(t,401)}this.completeUpgrade(p,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,a,l){if(!i.readable||!i.writable)return i.destroy();if(i[p])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return v(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${o(`sha1`).update(t+f).digest(`base64`)}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),d._protocol=e)}if(e[c.extensionName]){let t=e[c.extensionName].params,n=s.format({[c.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),d._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
831
831
  `).join(`\r
832
832
  `)),i.removeListener(`error`,_),d.setSocket(i,a,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on(`close`,()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(g,this)})),l(d,r)}};function h(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function g(e){e._state=2,e.emit(`close`)}function _(){this.destroy()}function v(e,t,n,r){n||=i.STATUS_CODES[t],r={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...r},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${i.STATUS_CODES[t]}\r\n`+Object.keys(r).map(e=>`${e}: ${r[e]}`).join(`\r
833
833
  `)+`\r
834
834
  \r
835
- `+n)}function y(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,y),e.emit(`wsClientError`,r,n,t)}else v(n,r,i,a)}}));iCe(),o5(),n5(),i5(),a5(),c5(),s5(),aCe();let l5,u5,d5,f5,p5=!0;typeof process<`u`&&({FORCE_COLOR:l5,NODE_DISABLE_COLORS:u5,NO_COLOR:d5,TERM:f5}=process.env||{},p5=process.stdout&&process.stdout.isTTY);const m5={enabled:!u5&&d5==null&&f5!==`dumb`&&(l5!=null&&l5!==`0`||p5),reset:g5(0,0),bold:g5(1,22),dim:g5(2,22),italic:g5(3,23),underline:g5(4,24),inverse:g5(7,27),hidden:g5(8,28),strikethrough:g5(9,29),black:g5(30,39),red:g5(31,39),green:g5(32,39),yellow:g5(33,39),blue:g5(34,39),magenta:g5(35,39),cyan:g5(36,39),white:g5(37,39),gray:g5(90,39),grey:g5(90,39),bgBlack:g5(40,49),bgRed:g5(41,49),bgGreen:g5(42,49),bgYellow:g5(43,49),bgBlue:g5(44,49),bgMagenta:g5(45,49),bgCyan:g5(46,49),bgWhite:g5(47,49)};function h5(e,t){let n=0,r,i=``,a=``;for(;n<e.length;n++)r=e[n],i+=r.open,a+=r.close,~t.indexOf(r.close)&&(t=t.replace(r.rgx,r.close+r.open));return i+t+a}function oCe(e,t){let n={has:e,keys:t};return n.reset=m5.reset.bind(n),n.bold=m5.bold.bind(n),n.dim=m5.dim.bind(n),n.italic=m5.italic.bind(n),n.underline=m5.underline.bind(n),n.inverse=m5.inverse.bind(n),n.hidden=m5.hidden.bind(n),n.strikethrough=m5.strikethrough.bind(n),n.black=m5.black.bind(n),n.red=m5.red.bind(n),n.green=m5.green.bind(n),n.yellow=m5.yellow.bind(n),n.blue=m5.blue.bind(n),n.magenta=m5.magenta.bind(n),n.cyan=m5.cyan.bind(n),n.white=m5.white.bind(n),n.gray=m5.gray.bind(n),n.grey=m5.grey.bind(n),n.bgBlack=m5.bgBlack.bind(n),n.bgRed=m5.bgRed.bind(n),n.bgGreen=m5.bgGreen.bind(n),n.bgYellow=m5.bgYellow.bind(n),n.bgBlue=m5.bgBlue.bind(n),n.bgMagenta=m5.bgMagenta.bind(n),n.bgCyan=m5.bgCyan.bind(n),n.bgWhite=m5.bgWhite.bind(n),n}function g5(e,t){let n={open:`\x1b[${e}m`,close:`\x1b[${t}m`,rgx:RegExp(`\\x1b\\[${t}m`,`g`)};return function(t){return this!==void 0&&this.has!==void 0?(~this.has.indexOf(e)||(this.has.push(e),this.keys.push(n)),t===void 0?this:m5.enabled?h5(this.keys,t+``):t+``):t===void 0?oCe([e],[n]):m5.enabled?h5([n],t+``):t+``}}Number.isNaN,Number.isInteger,Number.isNaN,Number.parseInt,Array.from,Array.isArray;const sCe=String.fromCharCode;String.fromCodePoint,sCe(65535);const _5=typeof TextEncoder<`u`?new TextEncoder:null;let v5=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});v5&&v5.decode(new Uint8Array).length===1&&(v5=null);const y5=e=>Error(e);new Uint8Array(3e4).length/3,_5&&_5.encodeInto,y5(`Unexpected end of array`),y5(`Integer out of Range`),Date.now;var b5=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),x5=o(import.meta.url),S5=b5(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),C5=b5(((e,t)=>{let{EMPTY_BUFFER:n}=S5(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=x5(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),cCe=b5(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),w5=b5(((e,t)=>{let n=x5(`zlib`),r=C5(),i=cCe(),{kStatusCode:a}=S5(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,p||=new i(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),T5=b5(((e,t)=>{let{isUtf8:n}=x5(`buffer`),{hasBlob:r}=S5(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=x5(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),E5=b5(((e,t)=>{let{Writable:n}=x5(`stream`),r=w5(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=S5(),{concat:c,toArrayBuffer:l,unmask:u}=C5(),{isValidStatusCode:d,isValidUTF8:f}=T5(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),D5=b5(((e,t)=>{let{Duplex:n}=x5(`stream`),{randomFillSync:r}=x5(`crypto`),i=w5(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=S5(),{isBlob:c,isValidStatusCode:l}=T5(),{mask:u,toBuffer:d}=C5(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function _(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function v(e,t,n){_(e,t,n),e.onerror(t)}})),lCe=b5(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=S5(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),O5=b5(((e,t)=>{let{tokenChars:n}=T5();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),k5=b5(((e,t)=>{let n=x5(`events`),r=x5(`https`),i=x5(`http`),a=x5(`net`),o=x5(`tls`),{randomBytes:s,createHash:c}=x5(`crypto`),{Duplex:l,Readable:u}=x5(`stream`),{URL:d}=x5(`url`),f=w5(),p=E5(),m=D5(),{isBlob:h}=T5(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=S5(),{EventTarget:{addEventListener:T,removeEventListener:E}}=lCe(),{format:D,parse:O}=O5(),{toBuffer:ee}=C5(),te=Symbol(`kAborted`),ne=[8,13],re=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],ie=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var ae=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),oe(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[C]=this,a[C]=this,t[C]=this,i.on(`conclude`,A),i.on(`drain`,j),i.on(`error`,de),i.on(`message`,pe),i.on(`ping`,me),i.on(`pong`,M),a.onerror=he,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,_e),t.on(`data`,ve),t.on(`end`,ye),t.on(`error`,be),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){le(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ge(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ue(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ue(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ue(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||v,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){le(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(ae,`CONNECTING`,{enumerable:!0,value:re.indexOf(`CONNECTING`)}),Object.defineProperty(ae.prototype,`CONNECTING`,{enumerable:!0,value:re.indexOf(`CONNECTING`)}),Object.defineProperty(ae,`OPEN`,{enumerable:!0,value:re.indexOf(`OPEN`)}),Object.defineProperty(ae.prototype,`OPEN`,{enumerable:!0,value:re.indexOf(`OPEN`)}),Object.defineProperty(ae,`CLOSING`,{enumerable:!0,value:re.indexOf(`CLOSING`)}),Object.defineProperty(ae.prototype,`CLOSING`,{enumerable:!0,value:re.indexOf(`CLOSING`)}),Object.defineProperty(ae,`CLOSED`,{enumerable:!0,value:re.indexOf(`CLOSED`)}),Object.defineProperty(ae.prototype,`CLOSED`,{enumerable:!0,value:re.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(ae.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(ae.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[x];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[b]:!0})}})}),ae.prototype.addEventListener=T,ae.prototype.removeEventListener=E,t.exports=ae;function oe(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:ne[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!ne.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${ne.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;se(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),v=u?r.request:i.request,b=new Set,x;if(o.createConnection=o.createConnection||(u?ce:k),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=D({[f.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!ie.test(e)||b.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);b.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=v(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=v(o);o.timeout&&S.on(`timeout`,()=>{le(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[te]||(S=e._req=null,se(e,t))}),S.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){le(e,S,`Maximum redirects exceeded`);return}S.abort();let r;try{r=new d(i,t)}catch{se(e,SyntaxError(`Invalid URL: ${i}`));return}oe(e,r,n,a)}else e.emit(`unexpected-response`,S,r)||le(e,S,`Unexpected server response: ${r.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==ae.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){le(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+y).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){le(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?b.size&&(l=`Server sent no subprotocol`):b.size?b.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){le(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){le(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=O(u)}catch{le(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){le(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[f.extensionName])}catch{le(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=x}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,e):S.end()}function se(e,t){e._readyState=ae.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function k(e){return e.path=e.socketPath,a.connect(e)}function ce(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function le(e,t,n){e._readyState=ae.CLOSING;let r=Error(n);Error.captureStackTrace(r,le),t.setHeader?(t[te]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(se,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function ue(e,t,n){if(t){let n=h(t)?t.size:ee(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${re[e.readyState]})`);process.nextTick(n,t)}}function A(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,ve),process.nextTick(N,n._socket),e===1005?n.close():n.close(e,t))}function j(){let e=this[C];e.isPaused||e._socket.resume()}function de(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,ve),process.nextTick(N,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function fe(){this[C].emitClose()}function pe(e,t){this[C].emit(`message`,e,t)}function me(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function M(e){this[C].emit(`pong`,e)}function N(e){e.resume()}function he(e){let t=this[C];t.readyState!==ae.CLOSED&&(t.readyState===ae.OPEN&&(t._readyState=ae.CLOSING,ge(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function ge(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function _e(){let e=this[C];if(this.removeListener(`close`,_e),this.removeListener(`data`,ve),this.removeListener(`end`,ye),e._readyState=ae.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[C]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,fe),e._receiver.on(`finish`,fe))}function ve(e){this[C]._receiver.write(e)||this.pause()}function ye(){let e=this[C];e._readyState=ae.CLOSING,e._receiver.end(),this.end()}function be(){let e=this[C];this.removeListener(`error`,be),this.on(`error`,w),e&&(e._readyState=ae.CLOSING,this.destroy())}})),uCe=b5(((e,t)=>{k5();let{Duplex:n}=x5(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),dCe=b5(((e,t)=>{let{tokenChars:n}=T5();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),fCe=b5(((e,t)=>{let n=x5(`events`),r=x5(`http`),{Duplex:i}=x5(`stream`),{createHash:a}=x5(`crypto`),o=O5(),s=w5(),c=dCe(),l=k5(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=S5(),p=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=m(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(h,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(f);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
835
+ `+n)}function y(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,y),e.emit(`wsClientError`,r,n,t)}else v(n,r,i,a)}}));aCe(),o5(),n5(),i5(),a5(),c5(),s5(),oCe();let l5,u5,d5,f5,p5=!0;typeof process<`u`&&({FORCE_COLOR:l5,NODE_DISABLE_COLORS:u5,NO_COLOR:d5,TERM:f5}=process.env||{},p5=process.stdout&&process.stdout.isTTY);const m5={enabled:!u5&&d5==null&&f5!==`dumb`&&(l5!=null&&l5!==`0`||p5),reset:g5(0,0),bold:g5(1,22),dim:g5(2,22),italic:g5(3,23),underline:g5(4,24),inverse:g5(7,27),hidden:g5(8,28),strikethrough:g5(9,29),black:g5(30,39),red:g5(31,39),green:g5(32,39),yellow:g5(33,39),blue:g5(34,39),magenta:g5(35,39),cyan:g5(36,39),white:g5(37,39),gray:g5(90,39),grey:g5(90,39),bgBlack:g5(40,49),bgRed:g5(41,49),bgGreen:g5(42,49),bgYellow:g5(43,49),bgBlue:g5(44,49),bgMagenta:g5(45,49),bgCyan:g5(46,49),bgWhite:g5(47,49)};function h5(e,t){let n=0,r,i=``,a=``;for(;n<e.length;n++)r=e[n],i+=r.open,a+=r.close,~t.indexOf(r.close)&&(t=t.replace(r.rgx,r.close+r.open));return i+t+a}function sCe(e,t){let n={has:e,keys:t};return n.reset=m5.reset.bind(n),n.bold=m5.bold.bind(n),n.dim=m5.dim.bind(n),n.italic=m5.italic.bind(n),n.underline=m5.underline.bind(n),n.inverse=m5.inverse.bind(n),n.hidden=m5.hidden.bind(n),n.strikethrough=m5.strikethrough.bind(n),n.black=m5.black.bind(n),n.red=m5.red.bind(n),n.green=m5.green.bind(n),n.yellow=m5.yellow.bind(n),n.blue=m5.blue.bind(n),n.magenta=m5.magenta.bind(n),n.cyan=m5.cyan.bind(n),n.white=m5.white.bind(n),n.gray=m5.gray.bind(n),n.grey=m5.grey.bind(n),n.bgBlack=m5.bgBlack.bind(n),n.bgRed=m5.bgRed.bind(n),n.bgGreen=m5.bgGreen.bind(n),n.bgYellow=m5.bgYellow.bind(n),n.bgBlue=m5.bgBlue.bind(n),n.bgMagenta=m5.bgMagenta.bind(n),n.bgCyan=m5.bgCyan.bind(n),n.bgWhite=m5.bgWhite.bind(n),n}function g5(e,t){let n={open:`\x1b[${e}m`,close:`\x1b[${t}m`,rgx:RegExp(`\\x1b\\[${t}m`,`g`)};return function(t){return this!==void 0&&this.has!==void 0?(~this.has.indexOf(e)||(this.has.push(e),this.keys.push(n)),t===void 0?this:m5.enabled?h5(this.keys,t+``):t+``):t===void 0?sCe([e],[n]):m5.enabled?h5([n],t+``):t+``}}Number.isNaN,Number.isInteger,Number.isNaN,Number.parseInt,Array.from,Array.isArray;const cCe=String.fromCharCode;String.fromCodePoint,cCe(65535);const _5=typeof TextEncoder<`u`?new TextEncoder:null;let v5=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});v5&&v5.decode(new Uint8Array).length===1&&(v5=null);const y5=e=>Error(e);new Uint8Array(3e4).length/3,_5&&_5.encodeInto,y5(`Unexpected end of array`),y5(`Integer out of Range`),Date.now;var b5=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),x5=o(import.meta.url),S5=b5(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),C5=b5(((e,t)=>{let{EMPTY_BUFFER:n}=S5(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=x5(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),lCe=b5(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),w5=b5(((e,t)=>{let n=x5(`zlib`),r=C5(),i=lCe(),{kStatusCode:a}=S5(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,p||=new i(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),T5=b5(((e,t)=>{let{isUtf8:n}=x5(`buffer`),{hasBlob:r}=S5(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=x5(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),E5=b5(((e,t)=>{let{Writable:n}=x5(`stream`),r=w5(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=S5(),{concat:c,toArrayBuffer:l,unmask:u}=C5(),{isValidStatusCode:d,isValidUTF8:f}=T5(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),D5=b5(((e,t)=>{let{Duplex:n}=x5(`stream`),{randomFillSync:r}=x5(`crypto`),i=w5(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=S5(),{isBlob:c,isValidStatusCode:l}=T5(),{mask:u,toBuffer:d}=C5(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function _(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function v(e,t,n){_(e,t,n),e.onerror(t)}})),uCe=b5(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=S5(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),O5=b5(((e,t)=>{let{tokenChars:n}=T5();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),k5=b5(((e,t)=>{let n=x5(`events`),r=x5(`https`),i=x5(`http`),a=x5(`net`),o=x5(`tls`),{randomBytes:s,createHash:c}=x5(`crypto`),{Duplex:l,Readable:u}=x5(`stream`),{URL:d}=x5(`url`),f=w5(),p=E5(),m=D5(),{isBlob:h}=T5(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=S5(),{EventTarget:{addEventListener:T,removeEventListener:E}}=uCe(),{format:D,parse:O}=O5(),{toBuffer:ee}=C5(),te=Symbol(`kAborted`),ne=[8,13],re=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],ie=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var ae=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),oe(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[C]=this,a[C]=this,t[C]=this,i.on(`conclude`,A),i.on(`drain`,j),i.on(`error`,de),i.on(`message`,pe),i.on(`ping`,me),i.on(`pong`,M),a.onerror=he,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,_e),t.on(`data`,ve),t.on(`end`,ye),t.on(`error`,be),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){le(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ge(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ue(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ue(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ue(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||v,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){le(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(ae,`CONNECTING`,{enumerable:!0,value:re.indexOf(`CONNECTING`)}),Object.defineProperty(ae.prototype,`CONNECTING`,{enumerable:!0,value:re.indexOf(`CONNECTING`)}),Object.defineProperty(ae,`OPEN`,{enumerable:!0,value:re.indexOf(`OPEN`)}),Object.defineProperty(ae.prototype,`OPEN`,{enumerable:!0,value:re.indexOf(`OPEN`)}),Object.defineProperty(ae,`CLOSING`,{enumerable:!0,value:re.indexOf(`CLOSING`)}),Object.defineProperty(ae.prototype,`CLOSING`,{enumerable:!0,value:re.indexOf(`CLOSING`)}),Object.defineProperty(ae,`CLOSED`,{enumerable:!0,value:re.indexOf(`CLOSED`)}),Object.defineProperty(ae.prototype,`CLOSED`,{enumerable:!0,value:re.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(ae.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(ae.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[x];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[b]:!0})}})}),ae.prototype.addEventListener=T,ae.prototype.removeEventListener=E,t.exports=ae;function oe(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:ne[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!ne.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${ne.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;se(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),v=u?r.request:i.request,b=new Set,x;if(o.createConnection=o.createConnection||(u?ce:k),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=D({[f.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!ie.test(e)||b.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);b.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=v(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=v(o);o.timeout&&S.on(`timeout`,()=>{le(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[te]||(S=e._req=null,se(e,t))}),S.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){le(e,S,`Maximum redirects exceeded`);return}S.abort();let r;try{r=new d(i,t)}catch{se(e,SyntaxError(`Invalid URL: ${i}`));return}oe(e,r,n,a)}else e.emit(`unexpected-response`,S,r)||le(e,S,`Unexpected server response: ${r.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==ae.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){le(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+y).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){le(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?b.size&&(l=`Server sent no subprotocol`):b.size?b.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){le(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){le(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=O(u)}catch{le(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){le(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[f.extensionName])}catch{le(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=x}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,e):S.end()}function se(e,t){e._readyState=ae.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function k(e){return e.path=e.socketPath,a.connect(e)}function ce(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function le(e,t,n){e._readyState=ae.CLOSING;let r=Error(n);Error.captureStackTrace(r,le),t.setHeader?(t[te]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(se,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function ue(e,t,n){if(t){let n=h(t)?t.size:ee(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${re[e.readyState]})`);process.nextTick(n,t)}}function A(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,ve),process.nextTick(N,n._socket),e===1005?n.close():n.close(e,t))}function j(){let e=this[C];e.isPaused||e._socket.resume()}function de(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,ve),process.nextTick(N,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function fe(){this[C].emitClose()}function pe(e,t){this[C].emit(`message`,e,t)}function me(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function M(e){this[C].emit(`pong`,e)}function N(e){e.resume()}function he(e){let t=this[C];t.readyState!==ae.CLOSED&&(t.readyState===ae.OPEN&&(t._readyState=ae.CLOSING,ge(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function ge(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function _e(){let e=this[C];if(this.removeListener(`close`,_e),this.removeListener(`data`,ve),this.removeListener(`end`,ye),e._readyState=ae.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[C]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,fe),e._receiver.on(`finish`,fe))}function ve(e){this[C]._receiver.write(e)||this.pause()}function ye(){let e=this[C];e._readyState=ae.CLOSING,e._receiver.end(),this.end()}function be(){let e=this[C];this.removeListener(`error`,be),this.on(`error`,w),e&&(e._readyState=ae.CLOSING,this.destroy())}})),dCe=b5(((e,t)=>{k5();let{Duplex:n}=x5(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),fCe=b5(((e,t)=>{let{tokenChars:n}=T5();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),pCe=b5(((e,t)=>{let n=x5(`events`),r=x5(`http`),{Duplex:i}=x5(`stream`),{createHash:a}=x5(`crypto`),o=O5(),s=w5(),c=fCe(),l=k5(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=S5(),p=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=m(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(h,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(f);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
836
836
  `).join(`\r
837
837
  `)),i.removeListener(`error`,g),p.setSocket(i,c,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on(`close`,()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(h,this)})),l(p,r)}};function m(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function h(e){e._state=2,e.emit(`close`)}function g(){this.destroy()}function _(e,t,n,i){n||=r.STATUS_CODES[t],i={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...i},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${r.STATUS_CODES[t]}\r\n`+Object.keys(i).map(e=>`${e}: ${i[e]}`).join(`\r
838
838
  `)+`\r
839
839
  \r
840
- `+n)}function v(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,v),e.emit(`wsClientError`,r,n,t)}else _(n,r,i,a)}}));uCe(),E5(),D5(),k5(),fCe(),H$(`config-persistence`),H$(`generated-index-git-attributes`),H$(`head-watcher`),H$(`shadow-gc`),H$(`shadow-maintenance`),(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_DEAD_CHAIN_THRESHOLD;if(!e)return 5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:5})(),(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_CONSOLIDATION_SPACING_MS;if(!e)return 600*1e3;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:600*1e3})(),H$(`mermaid-persistence`),H$(`persistence`),H$(`persistence-staleness`),H$(`recovered-file-target`),H$(`removed-docs-journal`),H$(`server-observers`),H$(`github-permissions`),H$(`github-account`),H$(`sync-engine`),new Set([`.mcp.json`,`.cursor/mcp.json`,`.codex/config.toml`,`opencode.json`]),Fe(s),(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})(),(()=>{let e=Object.freeze({origin:`generated-index`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();let A5=null;U$(()=>{A5?.disable(),A5=null}),H$(`skill-migrate`);function j5(e){return[{host:`agents`,root:Pu},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=u3.indexOf(e.host),r=u3.indexOf(t.host);return(n===-1?u3.length:n)-(r===-1?u3.length:r)||e.host.localeCompare(t.host)})}j5(yu),j5(bu),H$(`skill-reconcile`),[...xu],Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS);const pCe=nc;N(oe(),`.ok`,`logs`),Fe(s),H$(`project-git`),H$(`project-skill-git`),Cu.map(e=>e.replace(/\/$/,``));const M5=_u,N5=vu,mCe=wu,P5=`node`,F5={MCP_DEBUG:`1`,OK_LOG_FILE:`/tmp/ok-mcp.log`},I5=`# ok-mcp-v2
840
+ `+n)}function v(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,v),e.emit(`wsClientError`,r,n,t)}else _(n,r,i,a)}}));dCe(),E5(),D5(),k5(),pCe(),H$(`config-persistence`),H$(`generated-index-git-attributes`),H$(`head-watcher`),H$(`shadow-gc`),H$(`shadow-maintenance`),(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_DEAD_CHAIN_THRESHOLD;if(!e)return 5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:5})(),(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_CONSOLIDATION_SPACING_MS;if(!e)return 600*1e3;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:600*1e3})(),H$(`mermaid-persistence`),H$(`persistence`),H$(`persistence-staleness`),H$(`recovered-file-target`),H$(`removed-docs-journal`),H$(`server-observers`),H$(`github-permissions`),H$(`github-account`),H$(`sync-engine`),new Set([`.mcp.json`,`.cursor/mcp.json`,`.codex/config.toml`,`opencode.json`]),Fe(s),(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})(),(()=>{let e=Object.freeze({origin:`generated-index`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();let A5=null;U$(()=>{A5?.disable(),A5=null}),H$(`skill-migrate`);function j5(e){return[{host:`agents`,root:Pu},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=u3.indexOf(e.host),r=u3.indexOf(t.host);return(n===-1?u3.length:n)-(r===-1?u3.length:r)||e.host.localeCompare(t.host)})}j5(yu),j5(bu),H$(`skill-reconcile`),[...xu],Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS);const mCe=nc;N(oe(),`.ok`,`logs`),Fe(s),H$(`project-git`),H$(`project-skill-git`),Cu.map(e=>e.replace(/\/$/,``));const M5=_u,N5=vu,hCe=wu,P5=`node`,F5={MCP_DEBUG:`1`,OK_LOG_FILE:`/tmp/ok-mcp.log`},I5=`# ok-mcp-v2
841
841
  USER_BUNDLE="$HOME/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh"
842
842
  [ -f "$USER_BUNDLE" ] && [ -x "$USER_BUNDLE" ] && exec "$USER_BUNDLE" mcp
843
843
  BUNDLE="/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh"
@@ -873,7 +873,7 @@ foreach ($d in $dirs) {
873
873
  if (Test-Path -LiteralPath $probe -PathType Leaf) { & $probe -y '@inkeep/open-knowledge@latest' mcp; exit $LASTEXITCODE }
874
874
  }
875
875
  [Console]::Error.WriteLine('OpenKnowledge: install Node.js 24+ (npm i -g @inkeep/open-knowledge), then restart your editor')
876
- exit 127`,R5=`// ok-pi-bridge`,z5=`${R5}-v1`;function B5(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.command===`/bin/sh`){if(!Array.isArray(t.args)||t.args[0]!==`-l`||t.args[1]!==`-c`)return!1;let e=t.args[2];return typeof e==`string`&&e.includes(`# ok-mcp-v2`)}if(t.command===`powershell`){if(!Array.isArray(t.args)||t.args[0]!==`-NoProfile`||t.args[1]!==`-NonInteractive`||t.args[2]!==`-Command`)return!1;let e=t.args[3];return typeof e==`string`&&e.includes(`# ok-mcp-win-v1`)}if(t.type===`local`&&Array.isArray(t.command)){if(t.command[0]===`/bin/sh`){if(t.command[1]!==`-l`||t.command[2]!==`-c`)return!1;let e=t.command[3];return typeof e==`string`&&e.includes(`# ok-mcp-v2`)}if(t.command[0]===`powershell`){if(t.command[1]!==`-NoProfile`||t.command[2]!==`-NonInteractive`||t.command[3]!==`-Command`)return!1;let e=t.command[4];return typeof e==`string`&&e.includes(`# ok-mcp-win-v1`)}return!1}if(t.command===`ok-pi-managed-extension`){if(!Array.isArray(t.args))return!1;let e=t.args[0];return typeof e==`string`&&e.startsWith(z5)}return!1}function V5(e=process.argv[1]){if(!e)throw Error(`Cannot infer the local CLI entry for --dev-mcp because process.argv[1] is empty.`);let t=ve(e);if(fe(t)===`cli.mjs`&&fe(pe(t))===`dist`)return t;let n=t.split(ye),r=n.lastIndexOf(`packages`);if(r===-1||n[r+1]!==`cli`)throw Error(`Cannot infer the repo root for --dev-mcp from ${t}. Run the local CLI from this repo so the built dist path can be derived.`);let i=n.slice(0,r);return N(i.length===0?ye:i.join(ye),`packages`,`cli`,`dist`,`cli.mjs`)}function H5(e={}){return e.mode===`dev`?{command:P5,args:[V5(),`mcp`],env:{...F5}}:(e.platformName??process.platform)===`win32`?{command:`powershell`,args:[`-NoProfile`,`-NonInteractive`,`-Command`,L5]}:{command:`/bin/sh`,args:[`-l`,`-c`,I5]}}function hCe(e={}){return e.mode===`dev`?{type:`local`,enabled:!0,command:[P5,V5(),`mcp`],environment:{...F5}}:(e.platformName??process.platform)===`win32`?{type:`local`,enabled:!0,command:[`powershell`,`-NoProfile`,`-NonInteractive`,`-Command`,L5]}:{type:`local`,enabled:!0,command:[`/bin/sh`,`-l`,`-c`,I5]}}function U5(e){if(typeof e!=`object`||!e)return!1;let t=e;return W5(t,H5({mode:`published`,platformName:`darwin`}))||W5(t,H5({mode:`published`,platformName:`win32`}))}function W5(e,t){return Object.keys(e).length===Object.keys(t).length?gCe(e,t):!1}function gCe(e,t){if(e.command!==t.command)return!1;let n=t.args;return!Array.isArray(n)||!Array.isArray(e.args)||e.args.length!==n.length?!1:e.args.every((e,t)=>e===n[t])}function G5(e,t){let n=e=>typeof e==`string`&&e.includes(`# ok-mcp`);return t===`/bin/sh`?e[0]===`-l`&&e[1]===`-c`&&n(e[2]):t===`powershell`?e[0]===`-NoProfile`&&e[1]===`-NonInteractive`&&e[2]===`-Command`&&n(e[3]):!1}function _Ce(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.enabled===!1||typeof t.command!=`string`||!Array.isArray(t.args)?!1:G5(t.args,t.command)}function vCe(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.type!==`local`||t.enabled===!1||!Array.isArray(t.command))return!1;let[n,...r]=t.command;return typeof n==`string`&&G5(r,n)}function K5(e){return e===`win32`?be:ge}function yCe(e={}){let t=e.platformName??process.platform,n=e.home??oe();return K5(t).join(n,`.claude.json`)}function q5(e={}){let t=e.platformName??process.platform,n=e.home??oe(),r=e.env??process.env;if(t===`darwin`)return ge.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`);if(t===`win32`){let e=r.APPDATA??be.join(n,`AppData`,`Roaming`);return be.join(e,`Claude`,`claude_desktop_config.json`)}throw Error(`Claude Desktop is not available on ${t}. Supported: macOS, Windows.`)}function J5(e={}){let t=e.platformName??process.platform,n=e.home??oe();return K5(t).join(n,`.cursor`,`mcp.json`)}function bCe(e={}){let t=e.platformName??process.platform,n=e.home??oe();return(e.env??process.env).CODEX_HOME??K5(t).join(n,`.codex`)}function Y5(e={}){return K5(e.platformName??process.platform).join(bCe(e),`config.toml`)}function X5(e={}){let t=e.platformName??process.platform,n=e.home??oe(),r=(e.env??process.env).COPILOT_HOME??K5(t).join(n,`.copilot`);return K5(t).join(r,`mcp-config.json`)}function xCe(e={}){let t=e.platformName??process.platform,n=e.home??oe(),r=e.env??process.env,i=K5(t);if(t===`win32`){let e=r.APPDATA??i.join(n,`AppData`,`Roaming`);return i.join(e,`opencode`)}let a=r.XDG_CONFIG_HOME??i.join(n,`.config`);return i.join(a,`opencode`)}function Z5(e={}){return K5(e.platformName??process.platform).join(xCe(e),`opencode.json`)}function SCe(e={}){let t=e.platformName??process.platform,n=e.home??oe();return K5(t).join(n,`.openclaw`,`openclaw.json`)}function CCe(e={}){let t=e.platformName??process.platform,n=e.home??oe();return K5(t).join(n,`.hermes`,`config.yaml`)}function Q5(e={}){let t=e.platformName??process.platform,n=e.home??oe();return(e.env??process.env).PI_CODING_AGENT_DIR??K5(t).join(n,`.pi`,`agent`)}function wCe(e={}){let t=e.platformName??process.platform,n=e.home??oe();return K5(t).join(n,`.gemini`,`config`,`mcp_config.json`)}function TCe(e,t){let n=K5(t);return[{file:n.join(e,`.lmstudio`,`mcp.json`),dir:n.join(e,`.lmstudio`)},{file:n.join(e,`.cache`,`lm-studio`,`mcp.json`),dir:n.join(e,`.cache`,`lm-studio`)}]}function ECe(e){try{return C(e).length>0}catch{return!1}}function $5(e={}){let t=e.platformName??process.platform,[n,r]=TCe(e.home??oe(),t),i=[n,r].find(e=>g(e.file));return i?i.file:ECe(r.dir)?r.file:n.file}function DCe(e){let t=e.serverName(``);return e.format===`toml`?`[${e.topLevelKey}.${t}]`:[e.topLevelKey,e.serverMapSubKey,t].filter(Boolean).join(`.`)}function OCe(e,t){let n;try{n=e.configPath(``,t)}catch{return null}return n.startsWith(`${t}/`)?`~${n.slice(t.length)}`:n}const e7={claude:{id:`claude`,label:N5.claude,configPath:(e,t)=>yCe({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>Mu,buildEntry:(e,t)=>H5(t),scope:`global`,detectPath:(e,t)=>N(t??oe(),`.claude`),projectConfigPath:e=>N(e,`.mcp.json`),projectSkillPath:e=>N(e,`.claude`,`skills`,`open-knowledge`,`SKILL.md`)},"claude-desktop":{id:`claude-desktop`,label:N5[`claude-desktop`],configPath:(e,t)=>q5({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>Mu,buildEntry:(e,t)=>H5(t),scope:`global`,detectPath:(e,t)=>pe(q5({home:t}))},cursor:{id:`cursor`,label:N5.cursor,configPath:(e,t)=>J5({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>Mu,buildEntry:(e,t)=>H5(t),scope:`global`,detectPath:(e,t)=>pe(J5({home:t})),projectConfigPath:e=>N(e,`.cursor`,`mcp.json`),projectSkillPath:e=>N(e,`.cursor`,`skills`,`open-knowledge`,`SKILL.md`)},codex:{id:`codex`,label:N5.codex,configPath:(e,t)=>Y5({home:t}),format:`toml`,topLevelKey:`mcp_servers`,serverName:()=>Mu,buildEntry:(e,t)=>H5(t),scope:`global`,detectPath:(e,t)=>pe(Y5({home:t})),projectConfigPath:e=>N(e,`.codex`,`config.toml`),projectSkillPath:e=>N(e,`.codex`,`skills`,`open-knowledge`,`SKILL.md`)},copilot:{id:`copilot`,label:N5.copilot,configPath:(e,t)=>X5({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>Mu,buildEntry:(e,t)=>H5(t),scope:`global`,detectPath:(e,t)=>pe(X5({home:t})),projectSkillPath:e=>N(e,`.github`,`skills`,`open-knowledge`,`SKILL.md`)},opencode:{id:`opencode`,label:N5.opencode,configPath:(e,t)=>Z5({home:t}),format:`json`,topLevelKey:`mcp`,serverName:()=>Mu,buildEntry:(e,t)=>hCe(t),scope:`global`,detectPath:(e,t)=>pe(Z5({home:t})),projectConfigPath:e=>N(e,`opencode.json`),projectSkillPath:e=>N(e,`.opencode`,`skills`,`open-knowledge`,`SKILL.md`)},openclaw:{id:`openclaw`,label:N5.openclaw,configPath:(e,t)=>SCe({home:t}),format:`json`,topLevelKey:`mcp`,serverMapSubKey:`servers`,serverName:()=>Mu,buildEntry:(e,t)=>H5(t),scope:`global`,detectPath:(e,t)=>N(t??oe(),`.openclaw`),offerOnlyWhenDetected:!0},pi:{id:`pi`,label:N5.pi,configPath:()=>{throw Error("Pi has no user-global MCP config; OK's integration is the project-scoped bridge extension at .pi/extensions/open-knowledge.ts (run `ok init` in the project).")},format:`file`,topLevelKey:`mcpServers`,serverName:()=>Mu,buildEntry:()=>{throw Error(`Pi has no MCP entry shape; the managed bridge file is built by buildPiExtensionSource (integrations/pi-extension.ts).`)},scope:`project`,detectPath:(e,t)=>Q5({home:t}),projectConfigPath:e=>N(e,`.pi`,`extensions`,`open-knowledge.ts`),projectSkillPath:e=>N(e,`.pi`,`skills`,`open-knowledge`,`SKILL.md`)},antigravity:{id:`antigravity`,label:N5.antigravity,configPath:(e,t)=>wCe({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>Mu,buildEntry:(e,t)=>H5(t),scope:`global`,detectPath:(e,t)=>N(t??oe(),`.gemini`),offerOnlyWhenDetected:!0},"lm-studio":{id:`lm-studio`,label:N5[`lm-studio`],configPath:(e,t)=>$5({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>Mu,buildEntry:(e,t)=>H5(t),scope:`global`,detectPath:(e,t)=>pe($5({home:t})),offerOnlyWhenDetected:!0},hermes:{id:`hermes`,label:N5.hermes,configPath:(e,t)=>CCe({home:t}),format:`yaml`,topLevelKey:`mcp_servers`,serverName:()=>Mu,buildEntry:(e,t)=>H5(t),scope:`global`,detectPath:(e,t)=>N(t??oe(),`.hermes`),offerOnlyWhenDetected:!0}};function kCe(e){let t=e.filter(e=>!Object.hasOwn(e7,e));if(t.length>0)throw Error(`Unknown editor(s): ${t.join(`, `)}. Valid options: ${M5.join(`, `)}`);return e.map(e=>e7[e])}var t7=i((e=>{var t=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},n=class extends t{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};e.CommanderError=t,e.InvalidArgumentError=n})),n7=i((e=>{let{InvalidArgumentError:t}=t7();var n=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function r(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}e.Argument=n,e.humanReadableArgName=r})),r7=i((e=>{let{humanReadableArgName:t}=n7();var n=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(e=>t(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(n?` `+n:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
876
+ exit 127`,R5=`// ok-pi-bridge`,z5=`${R5}-v1`;function B5(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.command===`/bin/sh`){if(!Array.isArray(t.args)||t.args[0]!==`-l`||t.args[1]!==`-c`)return!1;let e=t.args[2];return typeof e==`string`&&e.includes(`# ok-mcp-v2`)}if(t.command===`powershell`){if(!Array.isArray(t.args)||t.args[0]!==`-NoProfile`||t.args[1]!==`-NonInteractive`||t.args[2]!==`-Command`)return!1;let e=t.args[3];return typeof e==`string`&&e.includes(`# ok-mcp-win-v1`)}if(t.type===`local`&&Array.isArray(t.command)){if(t.command[0]===`/bin/sh`){if(t.command[1]!==`-l`||t.command[2]!==`-c`)return!1;let e=t.command[3];return typeof e==`string`&&e.includes(`# ok-mcp-v2`)}if(t.command[0]===`powershell`){if(t.command[1]!==`-NoProfile`||t.command[2]!==`-NonInteractive`||t.command[3]!==`-Command`)return!1;let e=t.command[4];return typeof e==`string`&&e.includes(`# ok-mcp-win-v1`)}return!1}if(t.command===`ok-pi-managed-extension`){if(!Array.isArray(t.args))return!1;let e=t.args[0];return typeof e==`string`&&e.startsWith(z5)}return!1}function V5(e=process.argv[1]){if(!e)throw Error(`Cannot infer the local CLI entry for --dev-mcp because process.argv[1] is empty.`);let t=ve(e);if(fe(t)===`cli.mjs`&&fe(pe(t))===`dist`)return t;let n=t.split(ye),r=n.lastIndexOf(`packages`);if(r===-1||n[r+1]!==`cli`)throw Error(`Cannot infer the repo root for --dev-mcp from ${t}. Run the local CLI from this repo so the built dist path can be derived.`);let i=n.slice(0,r);return N(i.length===0?ye:i.join(ye),`packages`,`cli`,`dist`,`cli.mjs`)}function H5(e={}){return e.mode===`dev`?{command:P5,args:[V5(),`mcp`],env:{...F5}}:(e.platformName??process.platform)===`win32`?{command:`powershell`,args:[`-NoProfile`,`-NonInteractive`,`-Command`,L5]}:{command:`/bin/sh`,args:[`-l`,`-c`,I5]}}function gCe(e={}){return e.mode===`dev`?{type:`local`,enabled:!0,command:[P5,V5(),`mcp`],environment:{...F5}}:(e.platformName??process.platform)===`win32`?{type:`local`,enabled:!0,command:[`powershell`,`-NoProfile`,`-NonInteractive`,`-Command`,L5]}:{type:`local`,enabled:!0,command:[`/bin/sh`,`-l`,`-c`,I5]}}function U5(e){if(typeof e!=`object`||!e)return!1;let t=e;return W5(t,H5({mode:`published`,platformName:`darwin`}))||W5(t,H5({mode:`published`,platformName:`win32`}))}function W5(e,t){return Object.keys(e).length===Object.keys(t).length?_Ce(e,t):!1}function _Ce(e,t){if(e.command!==t.command)return!1;let n=t.args;return!Array.isArray(n)||!Array.isArray(e.args)||e.args.length!==n.length?!1:e.args.every((e,t)=>e===n[t])}function G5(e,t){let n=e=>typeof e==`string`&&e.includes(`# ok-mcp`);return t===`/bin/sh`?e[0]===`-l`&&e[1]===`-c`&&n(e[2]):t===`powershell`?e[0]===`-NoProfile`&&e[1]===`-NonInteractive`&&e[2]===`-Command`&&n(e[3]):!1}function vCe(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.enabled===!1||typeof t.command!=`string`||!Array.isArray(t.args)?!1:G5(t.args,t.command)}function yCe(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.type!==`local`||t.enabled===!1||!Array.isArray(t.command))return!1;let[n,...r]=t.command;return typeof n==`string`&&G5(r,n)}function K5(e){return e===`win32`?be:ge}function bCe(e={}){let t=e.platformName??process.platform,n=e.home??oe();return K5(t).join(n,`.claude.json`)}function q5(e={}){let t=e.platformName??process.platform,n=e.home??oe(),r=e.env??process.env;if(t===`darwin`)return ge.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`);if(t===`win32`){let e=r.APPDATA??be.join(n,`AppData`,`Roaming`);return be.join(e,`Claude`,`claude_desktop_config.json`)}throw Error(`Claude Desktop is not available on ${t}. Supported: macOS, Windows.`)}function J5(e={}){let t=e.platformName??process.platform,n=e.home??oe();return K5(t).join(n,`.cursor`,`mcp.json`)}function xCe(e={}){let t=e.platformName??process.platform,n=e.home??oe();return(e.env??process.env).CODEX_HOME??K5(t).join(n,`.codex`)}function Y5(e={}){return K5(e.platformName??process.platform).join(xCe(e),`config.toml`)}function X5(e={}){let t=e.platformName??process.platform,n=e.home??oe(),r=(e.env??process.env).COPILOT_HOME??K5(t).join(n,`.copilot`);return K5(t).join(r,`mcp-config.json`)}function SCe(e={}){let t=e.platformName??process.platform,n=e.home??oe(),r=e.env??process.env,i=K5(t);if(t===`win32`){let e=r.APPDATA??i.join(n,`AppData`,`Roaming`);return i.join(e,`opencode`)}let a=r.XDG_CONFIG_HOME??i.join(n,`.config`);return i.join(a,`opencode`)}function Z5(e={}){return K5(e.platformName??process.platform).join(SCe(e),`opencode.json`)}function CCe(e={}){let t=e.platformName??process.platform,n=e.home??oe();return K5(t).join(n,`.openclaw`,`openclaw.json`)}function wCe(e={}){let t=e.platformName??process.platform,n=e.home??oe();return K5(t).join(n,`.hermes`,`config.yaml`)}function Q5(e={}){let t=e.platformName??process.platform,n=e.home??oe();return(e.env??process.env).PI_CODING_AGENT_DIR??K5(t).join(n,`.pi`,`agent`)}function TCe(e={}){let t=e.platformName??process.platform,n=e.home??oe();return K5(t).join(n,`.gemini`,`config`,`mcp_config.json`)}function ECe(e,t){let n=K5(t);return[{file:n.join(e,`.lmstudio`,`mcp.json`),dir:n.join(e,`.lmstudio`)},{file:n.join(e,`.cache`,`lm-studio`,`mcp.json`),dir:n.join(e,`.cache`,`lm-studio`)}]}function DCe(e){try{return C(e).length>0}catch{return!1}}function $5(e={}){let t=e.platformName??process.platform,[n,r]=ECe(e.home??oe(),t),i=[n,r].find(e=>g(e.file));return i?i.file:DCe(r.dir)?r.file:n.file}function OCe(e){let t=e.serverName(``);return e.format===`toml`?`[${e.topLevelKey}.${t}]`:[e.topLevelKey,e.serverMapSubKey,t].filter(Boolean).join(`.`)}function kCe(e,t){let n;try{n=e.configPath(``,t)}catch{return null}return n.startsWith(`${t}/`)?`~${n.slice(t.length)}`:n}const e7={claude:{id:`claude`,label:N5.claude,configPath:(e,t)=>bCe({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>Mu,buildEntry:(e,t)=>H5(t),scope:`global`,detectPath:(e,t)=>N(t??oe(),`.claude`),projectConfigPath:e=>N(e,`.mcp.json`),projectSkillPath:e=>N(e,`.claude`,`skills`,`open-knowledge`,`SKILL.md`)},"claude-desktop":{id:`claude-desktop`,label:N5[`claude-desktop`],configPath:(e,t)=>q5({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>Mu,buildEntry:(e,t)=>H5(t),scope:`global`,detectPath:(e,t)=>pe(q5({home:t}))},cursor:{id:`cursor`,label:N5.cursor,configPath:(e,t)=>J5({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>Mu,buildEntry:(e,t)=>H5(t),scope:`global`,detectPath:(e,t)=>pe(J5({home:t})),projectConfigPath:e=>N(e,`.cursor`,`mcp.json`),projectSkillPath:e=>N(e,`.cursor`,`skills`,`open-knowledge`,`SKILL.md`)},codex:{id:`codex`,label:N5.codex,configPath:(e,t)=>Y5({home:t}),format:`toml`,topLevelKey:`mcp_servers`,serverName:()=>Mu,buildEntry:(e,t)=>H5(t),scope:`global`,detectPath:(e,t)=>pe(Y5({home:t})),projectConfigPath:e=>N(e,`.codex`,`config.toml`),projectSkillPath:e=>N(e,`.codex`,`skills`,`open-knowledge`,`SKILL.md`)},copilot:{id:`copilot`,label:N5.copilot,configPath:(e,t)=>X5({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>Mu,buildEntry:(e,t)=>H5(t),scope:`global`,detectPath:(e,t)=>pe(X5({home:t})),projectSkillPath:e=>N(e,`.github`,`skills`,`open-knowledge`,`SKILL.md`)},opencode:{id:`opencode`,label:N5.opencode,configPath:(e,t)=>Z5({home:t}),format:`json`,topLevelKey:`mcp`,serverName:()=>Mu,buildEntry:(e,t)=>gCe(t),scope:`global`,detectPath:(e,t)=>pe(Z5({home:t})),projectConfigPath:e=>N(e,`opencode.json`),projectSkillPath:e=>N(e,`.opencode`,`skills`,`open-knowledge`,`SKILL.md`)},openclaw:{id:`openclaw`,label:N5.openclaw,configPath:(e,t)=>CCe({home:t}),format:`json`,topLevelKey:`mcp`,serverMapSubKey:`servers`,serverName:()=>Mu,buildEntry:(e,t)=>H5(t),scope:`global`,detectPath:(e,t)=>N(t??oe(),`.openclaw`),offerOnlyWhenDetected:!0},pi:{id:`pi`,label:N5.pi,configPath:()=>{throw Error("Pi has no user-global MCP config; OK's integration is the project-scoped bridge extension at .pi/extensions/open-knowledge.ts (run `ok init` in the project).")},format:`file`,topLevelKey:`mcpServers`,serverName:()=>Mu,buildEntry:()=>{throw Error(`Pi has no MCP entry shape; the managed bridge file is built by buildPiExtensionSource (integrations/pi-extension.ts).`)},scope:`project`,detectPath:(e,t)=>Q5({home:t}),projectConfigPath:e=>N(e,`.pi`,`extensions`,`open-knowledge.ts`),projectSkillPath:e=>N(e,`.pi`,`skills`,`open-knowledge`,`SKILL.md`)},antigravity:{id:`antigravity`,label:N5.antigravity,configPath:(e,t)=>TCe({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>Mu,buildEntry:(e,t)=>H5(t),scope:`global`,detectPath:(e,t)=>N(t??oe(),`.gemini`),offerOnlyWhenDetected:!0},"lm-studio":{id:`lm-studio`,label:N5[`lm-studio`],configPath:(e,t)=>$5({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>Mu,buildEntry:(e,t)=>H5(t),scope:`global`,detectPath:(e,t)=>pe($5({home:t})),offerOnlyWhenDetected:!0},hermes:{id:`hermes`,label:N5.hermes,configPath:(e,t)=>wCe({home:t}),format:`yaml`,topLevelKey:`mcp_servers`,serverName:()=>Mu,buildEntry:(e,t)=>H5(t),scope:`global`,detectPath:(e,t)=>N(t??oe(),`.hermes`),offerOnlyWhenDetected:!0}};function ACe(e){let t=e.filter(e=>!Object.hasOwn(e7,e));if(t.length>0)throw Error(`Unknown editor(s): ${t.join(`, `)}. Valid options: ${M5.join(`, `)}`);return e.map(e=>e7[e])}var t7=i((e=>{var t=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},n=class extends t{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};e.CommanderError=t,e.InvalidArgumentError=n})),n7=i((e=>{let{InvalidArgumentError:t}=t7();var n=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function r(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}e.Argument=n,e.humanReadableArgName=r})),r7=i((e=>{let{humanReadableArgName:t}=n7();var n=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(e=>t(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(n?` `+n:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
877
877
  `)}displayWidth(e){return r(e).length}styleTitle(e){return e}styleUsage(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e===`[command]`?this.styleSubcommandText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleCommandText(e)).join(` `)}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleSubcommandText(e)).join(` `)}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let i=` `.repeat(2);if(!n)return i+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),o=(this.helpWidth??80)-t-2-2,s;return s=o<this.minWidthToWrap||r.preformatted(n)?n:r.boxWrap(n,o).replace(/\n/g,`
878
878
  `+` `.repeat(t+2)),i+a+` `.repeat(2)+s.replace(/\n/g,`\n${i}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,i=[];return n.forEach(e=>{let n=e.match(r);if(n===null){i.push(``);return}let a=[n.shift()],o=this.displayWidth(a[0]);n.forEach(e=>{let n=this.displayWidth(e);if(o+n<=t){a.push(e),o+=n;return}i.push(a.join(``));let r=e.trimStart();a=[r],o=this.displayWidth(r)}),i.push(a.join(``))}),i.join(`
879
879
  `)}};function r(e){return e.replace(/\x1b\[\d*(;\d*)*m/g,``)}e.Help=n,e.stripColor=r})),i7=i((e=>{let{InvalidArgumentError:t}=t7();var n=class{constructor(e,t){this.flags=e,this.description=t||``,this.required=e.includes(`<`),this.optional=e.includes(`[`),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=a(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith(`--no-`)),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e==`string`&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}name(){return this.long?this.long.replace(/^--/,``):this.short.replace(/^-/,``)}attributeName(){return this.negate?i(this.name().replace(/^no-/,``)):i(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},r=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,i=r===void 0?!1:r;return t.negate===(i===e)}};function i(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function a(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,a=e.split(/[ |,]+/).concat(`guard`);if(r.test(a[0])&&(t=a.shift()),i.test(a[0])&&(n=a.shift()),!t&&r.test(a[0])&&(t=a.shift()),!t&&i.test(a[0])&&(t=n,n=a.shift()),a[0].startsWith(`-`)){let t=a[0],n=`option creation failed due to '${t}' in option flags '${e}'`;throw/^-[^-][^-]/.test(t)?Error(`${n}
@@ -882,7 +882,7 @@ exit 127`,R5=`// ok-pi-bridge`,z5=`${R5}-v1`;function B5(e){if(typeof e!=`object
882
882
  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):r.test(t)?Error(`${n}
883
883
  - too many short flags`):i.test(t)?Error(`${n}
884
884
  - too many long flags`):Error(`${n}
885
- - unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}e.Option=n,e.DualOptions=r})),ACe=i((e=>{function t(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let t=0;t<=e.length;t++)n[t]=[t];for(let e=0;e<=t.length;e++)n[0][e]=e;for(let r=1;r<=t.length;r++)for(let i=1;i<=e.length;i++){let a=1;a=e[i-1]===t[r-1]?0:1,n[i][r]=Math.min(n[i-1][r]+1,n[i][r-1]+1,n[i-1][r-1]+a),i>1&&r>1&&e[i-1]===t[r-2]&&e[i-2]===t[r-1]&&(n[i][r]=Math.min(n[i][r],n[i-2][r-2]+1))}return n[e.length][t.length]}function n(e,n){if(!n||n.length===0)return``;n=Array.from(new Set(n));let r=e.startsWith(`--`);r&&(e=e.slice(2),n=n.map(e=>e.slice(2)));let i=[],a=3;return n.forEach(n=>{if(n.length<=1)return;let r=t(e,n),o=Math.max(e.length,n.length);(o-r)/o>.4&&(r<a?(a=r,i=[n]):r===a&&i.push(n))}),i.sort((e,t)=>e.localeCompare(t)),r&&(i=i.map(e=>`--${e}`)),i.length>1?`\n(Did you mean one of ${i.join(`, `)}?)`:i.length===1?`\n(Did you mean ${i[0]}?)`:``}e.suggestSimilar=n})),jCe=i((e=>{let n=t(`node:events`).EventEmitter,r=t(`node:child_process`),i=t(`node:path`),a=t(`node:fs`),o=t(`node:process`),{Argument:s,humanReadableArgName:c}=n7(),{CommanderError:l}=t7(),{Help:u,stripColor:d}=r7(),{Option:f,DualOptions:p}=i7(),{suggestSimilar:m}=ACe();var h=class e extends n{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||``,this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description=``,this._summary=``,this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>o.stdout.write(e),writeErr:e=>o.stderr.write(e),outputError:(e,t)=>t(e),getOutHelpWidth:()=>o.stdout.isTTY?o.stdout.columns:void 0,getErrHelpWidth:()=>o.stderr.isTTY?o.stderr.columns:void 0,getOutHasColors:()=>_()??(o.stdout.isTTY&&o.stdout.hasColors?.()),getErrHasColors:()=>_()??(o.stderr.isTTY&&o.stderr.hasColors?.()),stripColor:e=>d(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,i=n;typeof r==`object`&&r&&(i=r,r=null),i||={};let[,a,o]=e.match(/([^ ]+) *(.*)/),s=this.createCommand(a);return r&&(s.description(r),s._executableHandler=!0),i.isDefault&&(this._defaultCommandName=s._name),s._hidden=!!(i.noHelp||i.hidden),s._executableFile=i.executableFile||null,o&&s.arguments(o),this._registerCommand(s),s.parent=this,s.copyInheritedSettings(this),r?this:s}createCommand(t){return new e(t)}createHelp(){return Object.assign(new u,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!=`string`&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
885
+ - unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}e.Option=n,e.DualOptions=r})),jCe=i((e=>{function t(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let t=0;t<=e.length;t++)n[t]=[t];for(let e=0;e<=t.length;e++)n[0][e]=e;for(let r=1;r<=t.length;r++)for(let i=1;i<=e.length;i++){let a=1;a=e[i-1]===t[r-1]?0:1,n[i][r]=Math.min(n[i-1][r]+1,n[i][r-1]+1,n[i-1][r-1]+a),i>1&&r>1&&e[i-1]===t[r-2]&&e[i-2]===t[r-1]&&(n[i][r]=Math.min(n[i][r],n[i-2][r-2]+1))}return n[e.length][t.length]}function n(e,n){if(!n||n.length===0)return``;n=Array.from(new Set(n));let r=e.startsWith(`--`);r&&(e=e.slice(2),n=n.map(e=>e.slice(2)));let i=[],a=3;return n.forEach(n=>{if(n.length<=1)return;let r=t(e,n),o=Math.max(e.length,n.length);(o-r)/o>.4&&(r<a?(a=r,i=[n]):r===a&&i.push(n))}),i.sort((e,t)=>e.localeCompare(t)),r&&(i=i.map(e=>`--${e}`)),i.length>1?`\n(Did you mean one of ${i.join(`, `)}?)`:i.length===1?`\n(Did you mean ${i[0]}?)`:``}e.suggestSimilar=n})),MCe=i((e=>{let n=t(`node:events`).EventEmitter,r=t(`node:child_process`),i=t(`node:path`),a=t(`node:fs`),o=t(`node:process`),{Argument:s,humanReadableArgName:c}=n7(),{CommanderError:l}=t7(),{Help:u,stripColor:d}=r7(),{Option:f,DualOptions:p}=i7(),{suggestSimilar:m}=jCe();var h=class e extends n{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||``,this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description=``,this._summary=``,this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>o.stdout.write(e),writeErr:e=>o.stderr.write(e),outputError:(e,t)=>t(e),getOutHelpWidth:()=>o.stdout.isTTY?o.stdout.columns:void 0,getErrHelpWidth:()=>o.stderr.isTTY?o.stderr.columns:void 0,getOutHasColors:()=>_()??(o.stdout.isTTY&&o.stdout.hasColors?.()),getErrHasColors:()=>_()??(o.stderr.isTTY&&o.stderr.hasColors?.()),stripColor:e=>d(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,i=n;typeof r==`object`&&r&&(i=r,r=null),i||={};let[,a,o]=e.match(/([^ ]+) *(.*)/),s=this.createCommand(a);return r&&(s.description(r),s._executableHandler=!0),i.isDefault&&(this._defaultCommandName=s._name),s._hidden=!!(i.noHelp||i.hidden),s._executableFile=i.executableFile||null,o&&s.arguments(o),this._registerCommand(s),s.parent=this,s.copyInheritedSettings(this),r?this:s}createCommand(t){return new e(t)}createHelp(){return Object.assign(new u,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!=`string`&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
886
886
  - specify the name in Command constructor or using .name()`);return t||={},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new s(e,t)}argument(e,t,n,r){let i=this.createArgument(e,t);return typeof n==`function`?i.default(r).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e==`boolean`)return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let[,n,r]=(e??`help [command]`).match(/([^ ]+) *(.*)/),i=t??`display help for command`,a=this.createCommand(n);return a.helpOption(!1),r&&a.arguments(r),i&&a.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=a,(e||t)&&this._initCommandGroup(a),this}addHelpCommand(e,t){return typeof e==`object`?(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this):(this.helpCommand(e,t),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand(`help`))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=[`preSubcommand`,`preAction`,`postAction`];if(!n.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
887
887
  Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=e=>{if(e.code!==`commander.executeSubCommandAsync`)throw e},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new l(e,t,n)),o.exit(e)}action(e){let t=t=>{let n=this.registeredArguments.length,r=t.slice(0,n);return this._storeOptionsAsProperties?r[n]=this:r[n]=this.opts(),r.push(this),e.apply(this,r)};return this._actionHandler=t,this}createOption(e,t){return new f(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(e){if(e.code===`commander.invalidArgument`){let t=`${r} ${e.message}`;this.error(t,{exitCode:e.exitCode,code:e.code})}throw e}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
888
888
  - already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=e=>[e.name()].concat(e.aliases()),n=t(e).find(e=>this._findCommand(e));if(n){let r=t(this._findCommand(n)).join(`|`),i=t(e).join(`|`);throw Error(`cannot add command '${i}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let t=e.long.replace(/^--no-/,`--`);this._findOption(t)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,`default`)}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,`default`);let r=(t,r,i)=>{t==null&&e.presetArg!==void 0&&(t=e.presetArg);let a=this.getOptionValue(n);t!==null&&e.parseArg?t=this._callParseArg(e,t,a,r):t!==null&&e.variadic&&(t=e._collectValue(t,a)),t??=e.negate?!1:e.isBoolean()||e.optional?!0:``,this.setOptionValueWithSource(n,t,i)};return this.on(`option:`+t,t=>{r(t,`error: option '${e.flags}' argument '${t}' is invalid.`,`cli`)}),e.envVar&&this.on(`optionEnv:`+t,t=>{r(t,`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`,`env`)}),this}_optionEx(e,t,n,r,i){if(typeof t==`object`&&t instanceof f)throw Error(`To add an Option object use addOption() instead of option() or requiredOption()`);let a=this.createOption(t,n);if(a.makeOptionMandatory(!!e.mandatory),typeof r==`function`)a.default(i).argParser(r);else if(r instanceof RegExp){let e=r;r=(t,n)=>{let r=e.exec(t);return r?r[0]:n},a.default(i).argParser(r)}else a.default(r);return this.addOption(a)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error(`call .storeOptionsAsProperties() before adding options`);if(Object.keys(this._optionValues).length)throw Error(`call .storeOptionsAsProperties() before setting option values`);return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error(`first parameter to parse must be array or undefined`);if(t||={},e===void 0&&t.from===void 0){o.versions?.electron&&(t.from=`electron`);let e=o.execArgv??[];(e.includes(`-e`)||e.includes(`--eval`)||e.includes(`-p`)||e.includes(`--print`))&&(t.from=`eval`)}e===void 0&&(e=o.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case`node`:this._scriptPath=e[1],n=e.slice(2);break;case`electron`:o.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case`user`:n=e.slice(0);break;case`eval`:n=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||`program`,n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
@@ -891,7 +891,7 @@ Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._life
891
891
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
892
892
  - ${t?`searched for local subcommand relative to directory '${t}'`:`no directory for search for local subcommand, use .executableDir() to supply a custom directory`}`;throw Error(r)}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function c(e,t){let n=i.resolve(e,t);if(a.existsSync(n))return n;if(s.includes(i.extname(t)))return;let r=s.find(e=>a.existsSync(`${n}${e}`));if(r)return`${n}${r}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let u=e._executableFile||`${this._name}-${e._name}`,d=this._executableDir||``;if(this._scriptPath){let e;try{e=a.realpathSync(this._scriptPath)}catch{e=this._scriptPath}d=i.resolve(i.dirname(e),d)}if(d){let t=c(d,u);if(!t&&!e._executableFile&&this._scriptPath){let n=i.basename(this._scriptPath,i.extname(this._scriptPath));n!==this._name&&(t=c(d,`${n}-${e._name}`))}u=t||u}n=s.includes(i.extname(u));let f;o.platform===`win32`?(this._checkForMissingExecutable(u,d,e._name),t.unshift(u),t=g(o.execArgv).concat(t),f=r.spawn(o.execPath,t,{stdio:`inherit`})):n?(t.unshift(u),t=g(o.execArgv).concat(t),f=r.spawn(o.argv[0],t,{stdio:`inherit`})):f=r.spawn(u,t,{stdio:`inherit`}),f.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(e=>{o.on(e,()=>{f.killed===!1&&f.exitCode===null&&f.kill(e)})});let p=this._exitCallback;f.on(`close`,e=>{e??=1,p?p(new l(e,`commander.executeSubCommandAsync`,`(close)`)):o.exit(e)}),f.on(`error`,t=>{if(t.code===`ENOENT`)this._checkForMissingExecutable(u,d,e._name);else if(t.code===`EACCES`)throw Error(`'${u}' not executable`);if(!p)o.exit(1);else{let e=new l(1,`commander.executeSubCommandAsync`,`(error)`);e.nestedError=t,p(e)}}),this.runningCommand=f}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,`preSubcommand`),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??`--help`])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(e,t,n)=>{let r=t;if(t!==null&&e.parseArg){let i=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;r=this._callParseArg(e,t,n,i)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;n.variadic?r<this.args.length?(i=this.args.slice(r),n.parseArg&&(i=i.reduce((t,r)=>e(n,r,t),n.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],n.parseArg&&(i=e(n,i,n.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&typeof e.then==`function`?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,r=[];return this._getCommandAndAncestors().reverse().filter(e=>e._lifeCycleHooks[t]!==void 0).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{r.push({hookedCommand:e,callback:t})})}),t===`postAction`&&r.reverse(),r.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(e=>{r=this._chainOrCall(r,()=>e(this,t))}),r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let n;return n=this._chainOrCallHooks(n,`preAction`),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(i,e,t)})),n=this._chainOrCallHooks(n,`postAction`),n}if(this.parent?.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand(`*`))return this._dispatchSubcommand(`*`,e,t);this.listenerCount(`command:*`)?this.emit(`command:*`,e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(e=>{let t=e.attributeName();return this.getOptionValue(t)===void 0?!1:this.getOptionValueSource(t)!==`default`});e.filter(e=>e.conflictsWith.length>0).forEach(t=>{let n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function i(e){return e.length>1&&e[0]===`-`}let a=e=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(e)?!this._getCommandAndAncestors().some(e=>e.options.map(e=>e.short).some(e=>/^-\d$/.test(e))):!1,o=null,s=null,c=0;for(;c<e.length||s;){let l=s??e[c++];if(s=null,l===`--`){r===n&&r.push(l),r.push(...e.slice(c));break}if(o&&(!i(l)||a(l))){this.emit(`option:${o.name()}`,l);continue}if(o=null,i(l)){let t=this._findOption(l);if(t){if(t.required){let n=e[c++];n===void 0&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,n)}else if(t.optional){let n=null;c<e.length&&(!i(e[c])||a(e[c]))&&(n=e[c++]),this.emit(`option:${t.name()}`,n)}else this.emit(`option:${t.name()}`);o=t.variadic?t:null;continue}}if(l.length>2&&l[0]===`-`&&l[1]!==`-`){let e=this._findOption(`-${l[1]}`);if(e){e.required||e.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${e.name()}`,l.slice(2)):(this.emit(`option:${e.name()}`),s=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){let e=l.indexOf(`=`),t=this._findOption(l.slice(0,e));if(t&&(t.required||t.optional)){this.emit(`option:${t.name()}`,l.slice(e+1));continue}}if(r===t&&i(l)&&!(this.commands.length===0&&a(l))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),n.push(...e.slice(c));break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}else if(this._defaultCommandName){n.push(l,...e.slice(c));break}}if(this._passThroughOptions){r.push(l,...e.slice(c));break}r.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==`string`?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
893
893
  `),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in o.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||[`default`,`config`,`env`].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,o.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new p(this.options),t=e=>this.getOptionValue(e)!==void 0&&![`default`,`implied`].includes(this.getOptionValueSource(e));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],`implied`)})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:`commander.missingArgument`})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:`commander.optionMissingArgument`})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:`commander.missingMandatoryOptionValue`})}_conflictingOption(e,t){let n=e=>{let t=e.attributeName(),n=this.getOptionValue(t),r=this.options.find(e=>e.negate&&t===e.attributeName()),i=this.options.find(e=>!e.negate&&t===e.attributeName());return r&&(r.presetArg===void 0&&n===!1||r.presetArg!==void 0&&n===r.presetArg)?r:i||e},r=e=>{let t=n(e),r=t.attributeName();return this.getOptionValueSource(r)===`env`?`environment variable '${t.envVar}'`:`option '${t.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:`commander.conflictingOption`})}unknownOption(e){if(this._allowUnknownOption)return;let t=``;if(e.startsWith(`--`)&&this._showSuggestionAfterError){let n=[],r=this;do{let e=r.createHelp().visibleOptions(r).filter(e=>e.long).map(e=>e.long);n=n.concat(e),r=r.parent}while(r&&!r._enablePositionalOptions);t=m(e,n)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:`commander.unknownOption`})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?``:`s`,r=`error: too many arguments${this.parent?` for '${this.name()}'`:``}. Expected ${t} argument${n} but got ${e.length}.`;this.error(r,{code:`commander.excessArguments`})}unknownCommand(){let e=this.args[0],t=``;if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=m(e,n)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:`commander.unknownCommand`})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t||=`-V, --version`,n||=`output the version number`;let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on(`option:`+r.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,`commander.version`,e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw Error(`Command alias can't be the same as its name`);let n=this.parent?._findCommand(e);if(n){let t=[n.name()].concat(n.aliases()).join(`|`);throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(e=>c(e));return[].concat(this.options.length||this._helpOption!==null?`[options]`:[],this.commands.length?`[command]`:[],this.registeredArguments.length?e:[]).join(` `)}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??``:(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??``:(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??``:(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=i.basename(e,i.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);return n.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e||={};let t=!!e.error,n,r,i;return t?(n=e=>this._outputConfiguration.writeErr(e),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=e=>this._outputConfiguration.writeOut(e),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:e=>(r||(e=this._outputConfiguration.stripColor(e)),n(e)),hasColors:r,helpWidth:i}}outputHelp(e){let t;typeof e==`function`&&(t=e,e=void 0);let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(e=>e.emit(`beforeAllHelp`,r)),this.emit(`beforeHelp`,r);let i=this.helpInformation({error:n.error});if(t&&(i=t(i),typeof i!=`string`&&!Buffer.isBuffer(i)))throw Error(`outputHelp callback must return a string or a Buffer`);n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit(`afterHelp`,r),this._getCommandAndAncestors().forEach(e=>e.emit(`afterAllHelp`,r))}helpOption(e,t){return typeof e==`boolean`?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??`-h, --help`,t??`display help for command`),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(o.exitCode??0);t===0&&e&&typeof e!=`function`&&e.error&&(t=1),this._exit(t,`commander.help`,`(outputHelp)`)}addHelpText(e,t){let n=[`beforeAll`,`before`,`after`,`afterAll`];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
894
- Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function g(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function _(){if(o.env.NO_COLOR||o.env.FORCE_COLOR===`0`||o.env.FORCE_COLOR===`false`)return!1;if(o.env.FORCE_COLOR||o.env.CLICOLOR_FORCE!==void 0)return!0}e.Command=h,e.useColor=_}));const{program:MCe,createCommand:NCe,createArgument:PCe,createOption:FCe,CommanderError:ICe,InvalidArgumentError:LCe,InvalidOptionArgumentError:RCe,Command:zCe,Argument:BCe,Option:VCe,Help:HCe}=e(i((e=>{let{Argument:t}=n7(),{Command:n}=jCe(),{CommanderError:r,InvalidArgumentError:i}=t7(),{Help:a}=r7(),{Option:o}=i7();e.program=new n,e.createCommand=e=>new n(e),e.createOption=(e,t)=>new o(e,t),e.createArgument=(e,n)=>new t(e,n),e.Command=n,e.Option=o,e.Argument=t,e.Help=a,e.CommanderError=r,e.InvalidArgumentError=i,e.InvalidOptionArgumentError=i}))(),1).default;
894
+ Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function g(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function _(){if(o.env.NO_COLOR||o.env.FORCE_COLOR===`0`||o.env.FORCE_COLOR===`false`)return!1;if(o.env.FORCE_COLOR||o.env.CLICOLOR_FORCE!==void 0)return!0}e.Command=h,e.useColor=_}));const{program:NCe,createCommand:PCe,createArgument:FCe,createOption:ICe,CommanderError:LCe,InvalidArgumentError:RCe,InvalidOptionArgumentError:zCe,Command:BCe,Argument:VCe,Option:HCe,Help:UCe}=e(i((e=>{let{Argument:t}=n7(),{Command:n}=MCe(),{CommanderError:r,InvalidArgumentError:i}=t7(),{Help:a}=r7(),{Option:o}=i7();e.program=new n,e.createCommand=e=>new n(e),e.createOption=(e,t)=>new o(e,t),e.createArgument=(e,n)=>new t(e,n),e.Command=n,e.Option=o,e.Argument=t,e.Help=a,e.CommanderError=r,e.InvalidArgumentError=i,e.InvalidOptionArgumentError=i}))(),1).default;
895
895
  /*!
896
896
  * Copyright (c) Squirrel Chat et al., All rights reserved.
897
897
  * SPDX-License-Identifier: BSD-3-Clause
@@ -919,7 +919,7 @@ Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let
919
919
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
920
920
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
921
921
  */
922
- let UCe=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i;var WCe=class e extends Date{#e=!1;#t=!1;#n=null;constructor(e){let t=!0,n=!0,r=`Z`;if(typeof e==`string`){let i=e.match(UCe);i?(i[1]||(t=!1,e=`0000-01-01T${e}`),n=!!i[2],n&&e[10]===` `&&(e=e.replace(` `,`T`)),i[2]&&+i[2]>23?e=``:(r=i[3]||null,e=e.toUpperCase(),!r&&n&&(e+=`Z`))):e=``}super(e),isNaN(this.getTime())||(this.#e=t,this.#t=n,this.#n=r)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n=`Z`){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=!1,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=!1,n.#n=null,n}};
922
+ let WCe=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i;var GCe=class e extends Date{#e=!1;#t=!1;#n=null;constructor(e){let t=!0,n=!0,r=`Z`;if(typeof e==`string`){let i=e.match(WCe);i?(i[1]||(t=!1,e=`0000-01-01T${e}`),n=!!i[2],n&&e[10]===` `&&(e=e.replace(` `,`T`)),i[2]&&+i[2]>23?e=``:(r=i[3]||null,e=e.toUpperCase(),!r&&n&&(e+=`Z`))):e=``}super(e),isNaN(this.getTime())||(this.#e=t,this.#t=n,this.#n=r)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n=`Z`){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=!1,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=!1,n.#n=null,n}};
923
923
  /*!
924
924
  * Copyright (c) Squirrel Chat et al., All rights reserved.
925
925
  * SPDX-License-Identifier: BSD-3-Clause
@@ -947,9 +947,9 @@ let UCe=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+
947
947
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
948
948
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
949
949
  */
950
- function GCe(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function KCe(e,t,n){let r=e.split(/\r\n|\n|\r/g),i=``,a=(Math.log10(t+1)|0)+1;for(let e=t-1;e<=t+1;e++){let o=r[e-1];o&&(i+=e.toString().padEnd(a,` `),i+=`: `,i+=o,i+=`
950
+ function KCe(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function qCe(e,t,n){let r=e.split(/\r\n|\n|\r/g),i=``,a=(Math.log10(t+1)|0)+1;for(let e=t-1;e<=t+1;e++){let o=r[e-1];o&&(i+=e.toString().padEnd(a,` `),i+=`: `,i+=o,i+=`
951
951
  `,e===t&&(i+=` `.repeat(a+n+2),i+=`^
952
- `))}return i}var a7=class extends Error{line;column;codeblock;constructor(e,t){let[n,r]=GCe(t.toml,t.ptr),i=KCe(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}};
952
+ `))}return i}var a7=class extends Error{line;column;codeblock;constructor(e,t){let[n,r]=KCe(t.toml,t.ptr),i=qCe(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}};
953
953
  /*!
954
954
  * Copyright (c) Squirrel Chat et al., All rights reserved.
955
955
  * SPDX-License-Identifier: BSD-3-Clause
@@ -977,12 +977,12 @@ function GCe(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop(
977
977
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
978
978
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
979
979
  */
980
- let qCe=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,JCe=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,YCe=/^[+-]?0[0-9_]/;function o7(e,t){let n=e[t++],r=n,i=n===`'`,a=n===e[t]&&n===e[t+1];a&&(e[t+=2]===`
980
+ let JCe=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,YCe=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,XCe=/^[+-]?0[0-9_]/;function o7(e,t){let n=e[t++],r=n,i=n===`'`,a=n===e[t]&&n===e[t+1];a&&(e[t+=2]===`
981
981
  `?t++:e[t]===`\r`&&e[t+1]===`
982
982
  `&&(t+=2));let o=``,s=t,c=0;for(let l=t;l<e.length;l++)if(n=e[l],a&&(n===`
983
983
  `||n===`\r`&&e[l+1]===`
984
984
  `))c&&=3;else if(n<` `&&n!==` `||n===``)throw new a7(`control characters are not allowed in strings`,{toml:e,ptr:l});else if((!c||c===3)&&n===r&&(!a||e[l+1]===r&&e[l+2]===r))return a&&(e[l+3]===r&&l++,e[l+3]===r&&l++),[c?o:o+e.slice(s,l),l+(a?3:1)];else if(!c)!i&&n===`\\`&&(o+=e.slice(s,s=l),c=1);else if(c===1)if(n===`x`||n===`u`||n===`U`){let t=0,r=n===`x`?2:n===`u`?4:8;for(let n=0;n<r;n++,l++){let n=e.charCodeAt(l+1),r=n>=48&&n<=57?n-48:n>=65&&n<=70?n-65+10:n>=97&&n<=102?n-97+10:-1;if(r<0)throw new a7(`invalid non-hex character in unicode escape`,{toml:e,ptr:l+1});t=t<<4|r}if(t<0||t>1114111||t>=55296&&t<=57343)throw new a7(`invalid unicode escape`,{toml:e,ptr:l});o+=String.fromCodePoint(t),s=l+1,c=0}else if(n===` `||n===` `)c=2;else{if(n===`b`)o+=`\b`;else if(n===`t`)o+=` `;else if(n===`n`)o+=`
985
- `;else if(n===`f`)o+=`\f`;else if(n===`r`)o+=`\r`;else if(n===`e`)o+=`\x1B`;else if(n===`"`)o+=`"`;else if(n===`\\`)o+=`\\`;else throw new a7(`unrecognized escape sequence`,{toml:e,ptr:l});s=l+1,c=0}else if(n!==` `&&n!==` `){if(c===2)throw new a7(`invalid escape: only line-ending whitespace may be escaped`,{toml:e,ptr:s});c=+(!i&&n===`\\`),s=l}throw new a7(`unfinished string`,{toml:e,ptr:t})}function XCe(e,t,n,r){if(e===`true`)return!0;if(e===`false`)return!1;if(e===`-inf`)return-1/0;if(e===`inf`||e===`+inf`)return 1/0;if(e===`nan`||e===`+nan`||e===`-nan`)return NaN;if(e===`-0`)return r?0n:0;let i=qCe.test(e);if(i||JCe.test(e)){if(YCe.test(e))throw new a7(`leading zeroes are not allowed`,{toml:t,ptr:n});e=e.replace(/_/g,``);let a=+e;if(isNaN(a))throw new a7(`invalid number`,{toml:t,ptr:n});if(i){if((i=!Number.isSafeInteger(a))&&!r)throw new a7(`integer value cannot be represented losslessly`,{toml:t,ptr:n});(i||r===!0)&&(a=BigInt(e))}return a}let a=new WCe(e);if(!a.isValid())throw new a7(`invalid value`,{toml:t,ptr:n});return a}
985
+ `;else if(n===`f`)o+=`\f`;else if(n===`r`)o+=`\r`;else if(n===`e`)o+=`\x1B`;else if(n===`"`)o+=`"`;else if(n===`\\`)o+=`\\`;else throw new a7(`unrecognized escape sequence`,{toml:e,ptr:l});s=l+1,c=0}else if(n!==` `&&n!==` `){if(c===2)throw new a7(`invalid escape: only line-ending whitespace may be escaped`,{toml:e,ptr:s});c=+(!i&&n===`\\`),s=l}throw new a7(`unfinished string`,{toml:e,ptr:t})}function ZCe(e,t,n,r){if(e===`true`)return!0;if(e===`false`)return!1;if(e===`-inf`)return-1/0;if(e===`inf`||e===`+inf`)return 1/0;if(e===`nan`||e===`+nan`||e===`-nan`)return NaN;if(e===`-0`)return r?0n:0;let i=JCe.test(e);if(i||YCe.test(e)){if(XCe.test(e))throw new a7(`leading zeroes are not allowed`,{toml:t,ptr:n});e=e.replace(/_/g,``);let a=+e;if(isNaN(a))throw new a7(`invalid number`,{toml:t,ptr:n});if(i){if((i=!Number.isSafeInteger(a))&&!r)throw new a7(`integer value cannot be represented losslessly`,{toml:t,ptr:n});(i||r===!0)&&(a=BigInt(e))}return a}let a=new GCe(e);if(!a.isValid())throw new a7(`invalid value`,{toml:t,ptr:n});return a}
986
986
  /*!
987
987
  * Copyright (c) Squirrel Chat et al., All rights reserved.
988
988
  * SPDX-License-Identifier: BSD-3-Clause
@@ -1015,7 +1015,7 @@ function s7(e,t=0,n=e.length){let r=e.indexOf(`
1015
1015
  `)return n;if(r===`\r`&&e[n+1]===`
1016
1016
  `)return n+1;if(r<` `&&r!==` `||r===``)throw new a7(`control characters are not allowed in comments`,{toml:e,ptr:t})}return e.length}function l7(e,t,n,r){let i;for(;;){for(;(i=e[t])===` `||i===` `||!n&&(i===`
1017
1017
  `||i===`\r`&&e[t+1]===`
1018
- `);)t++;if(r||i!==`#`)break;t=c7(e,t)}return t}function ZCe(e,t,n,r,i=!1){if(!r)return t=s7(e,t),t<0?e.length:t;for(let a=t;a<e.length;a++){let t=e[a];if(t===`#`)a=s7(e,a);else if(t===n)return a+1;else if(t===r||i&&(t===`
1018
+ `);)t++;if(r||i!==`#`)break;t=c7(e,t)}return t}function QCe(e,t,n,r,i=!1){if(!r)return t=s7(e,t),t<0?e.length:t;for(let a=t;a<e.length;a++){let t=e[a];if(t===`#`)a=s7(e,a);else if(t===n)return a+1;else if(t===r||i&&(t===`
1019
1019
  `||t===`\r`&&e[a+1]===`
1020
1020
  `))return a}throw new a7(`cannot find end of structure`,{toml:e,ptr:t})}
1021
1021
  /*!
@@ -1045,8 +1045,8 @@ function s7(e,t=0,n=e.length){let r=e.indexOf(`
1045
1045
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1046
1046
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1047
1047
  */
1048
- function QCe(e,t,n){let r=e.slice(t,n),i=r.indexOf(`#`);return i>-1&&(c7(e,i),r=r.slice(0,i)),[r.trimEnd(),i]}function u7(e,t,n,r,i){if(r===0)throw new a7(`document contains excessively nested structures. aborting.`,{toml:e,ptr:t});let a=e[t];if(a===`[`||a===`{`){let[o,s]=a===`[`?twe(e,t,r,i):ewe(e,t,r,i);if(n){if(s=l7(e,s),e[s]===`,`)s++;else if(e[s]!==n)throw new a7(`expected comma or end of structure`,{toml:e,ptr:s})}return[o,s]}if(a===`"`||a===`'`){let[r,i]=o7(e,t);if(n){if(i=l7(e,i),e[i]&&e[i]!==`,`&&e[i]!==n&&e[i]!==`
1049
- `&&e[i]!==`\r`)throw new a7(`unexpected character encountered`,{toml:e,ptr:i});e[i]===`,`&&i++}return[r,i]}let o=ZCe(e,t,`,`,n),s=QCe(e,t,o-+(e[o-1]===`,`));if(!s[0])throw new a7(`incomplete key-value declaration: no value specified`,{toml:e,ptr:t});return n&&s[1]>-1&&(o=l7(e,t+s[1]),e[o]===`,`&&o++),[XCe(s[0],e,t,i),o]}
1048
+ function $Ce(e,t,n){let r=e.slice(t,n),i=r.indexOf(`#`);return i>-1&&(c7(e,i),r=r.slice(0,i)),[r.trimEnd(),i]}function u7(e,t,n,r,i){if(r===0)throw new a7(`document contains excessively nested structures. aborting.`,{toml:e,ptr:t});let a=e[t];if(a===`[`||a===`{`){let[o,s]=a===`[`?nwe(e,t,r,i):twe(e,t,r,i);if(n){if(s=l7(e,s),e[s]===`,`)s++;else if(e[s]!==n)throw new a7(`expected comma or end of structure`,{toml:e,ptr:s})}return[o,s]}if(a===`"`||a===`'`){let[r,i]=o7(e,t);if(n){if(i=l7(e,i),e[i]&&e[i]!==`,`&&e[i]!==n&&e[i]!==`
1049
+ `&&e[i]!==`\r`)throw new a7(`unexpected character encountered`,{toml:e,ptr:i});e[i]===`,`&&i++}return[r,i]}let o=QCe(e,t,`,`,n),s=$Ce(e,t,o-+(e[o-1]===`,`));if(!s[0])throw new a7(`incomplete key-value declaration: no value specified`,{toml:e,ptr:t});return n&&s[1]>-1&&(o=l7(e,t+s[1]),e[o]===`,`&&o++),[ZCe(s[0],e,t,i),o]}
1050
1050
  /*!
1051
1051
  * Copyright (c) Squirrel Chat et al., All rights reserved.
1052
1052
  * SPDX-License-Identifier: BSD-3-Clause
@@ -1074,8 +1074,8 @@ function QCe(e,t,n){let r=e.slice(t,n),i=r.indexOf(`#`);return i>-1&&(c7(e,i),r=
1074
1074
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1075
1075
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1076
1076
  */
1077
- let $Ce=/^[a-zA-Z0-9-_]+[ \t]*$/;function d7(e,t,n=`=`){let r=t-1,i=[],a=e.indexOf(n,t);if(a<0)throw new a7(`incomplete key-value: cannot find end of key`,{toml:e,ptr:t});do{let o=e[t=++r];if(o!==` `&&o!==` `)if(o===`"`||o===`'`){if(o===e[t+1]&&o===e[t+2])throw new a7(`multiline strings are not allowed in keys`,{toml:e,ptr:t});let[s,c]=o7(e,t);r=e.indexOf(`.`,c);let l=e.slice(c,r<0||r>a?a:r),u=s7(l);if(u>-1)throw new a7(`newlines are not allowed in keys`,{toml:e,ptr:t+r+u});if(l.trimStart())throw new a7(`found extra tokens after the string part`,{toml:e,ptr:c});if(a<c&&(a=e.indexOf(n,c),a<0))throw new a7(`incomplete key-value: cannot find end of key`,{toml:e,ptr:t});i.push(s)}else{r=e.indexOf(`.`,t);let n=e.slice(t,r<0||r>a?a:r);if(!$Ce.test(n))throw new a7(`only letter, numbers, dashes and underscores are allowed in keys`,{toml:e,ptr:t});i.push(n.trimEnd())}}while(r+1&&r<a);return[i,l7(e,a+1,!0,!0)]}function ewe(e,t,n,r){let i={},a=new Set,o;for(t++;(o=e[t++])!==`}`&&o;)if(o===`,`)throw new a7(`expected value, found comma`,{toml:e,ptr:t-1});else if(o===`#`)t=c7(e,t);else if(o!==` `&&o!==` `&&o!==`
1078
- `&&o!==`\r`){let o,s=i,c=!1,[l,u]=d7(e,t-1);for(let n=0;n<l.length;n++){if(n&&(s=c?s[o]:s[o]={}),o=l[n],(c=Object.hasOwn(s,o))&&(typeof s[o]!=`object`||a.has(s[o])))throw new a7(`trying to redefine an already defined value`,{toml:e,ptr:t});!c&&o===`__proto__`&&Object.defineProperty(s,o,{enumerable:!0,configurable:!0,writable:!0})}if(c)throw new a7(`trying to redefine an already defined value`,{toml:e,ptr:t});let[d,f]=u7(e,u,`}`,n-1,r);a.add(d),s[o]=d,t=f}if(!o)throw new a7(`unfinished table encountered`,{toml:e,ptr:t});return[i,t]}function twe(e,t,n,r){let i=[],a;for(t++;(a=e[t++])!==`]`&&a;)if(a===`,`)throw new a7(`expected value, found comma`,{toml:e,ptr:t-1});else if(a===`#`)t=c7(e,t);else if(a!==` `&&a!==` `&&a!==`
1077
+ let ewe=/^[a-zA-Z0-9-_]+[ \t]*$/;function d7(e,t,n=`=`){let r=t-1,i=[],a=e.indexOf(n,t);if(a<0)throw new a7(`incomplete key-value: cannot find end of key`,{toml:e,ptr:t});do{let o=e[t=++r];if(o!==` `&&o!==` `)if(o===`"`||o===`'`){if(o===e[t+1]&&o===e[t+2])throw new a7(`multiline strings are not allowed in keys`,{toml:e,ptr:t});let[s,c]=o7(e,t);r=e.indexOf(`.`,c);let l=e.slice(c,r<0||r>a?a:r),u=s7(l);if(u>-1)throw new a7(`newlines are not allowed in keys`,{toml:e,ptr:t+r+u});if(l.trimStart())throw new a7(`found extra tokens after the string part`,{toml:e,ptr:c});if(a<c&&(a=e.indexOf(n,c),a<0))throw new a7(`incomplete key-value: cannot find end of key`,{toml:e,ptr:t});i.push(s)}else{r=e.indexOf(`.`,t);let n=e.slice(t,r<0||r>a?a:r);if(!ewe.test(n))throw new a7(`only letter, numbers, dashes and underscores are allowed in keys`,{toml:e,ptr:t});i.push(n.trimEnd())}}while(r+1&&r<a);return[i,l7(e,a+1,!0,!0)]}function twe(e,t,n,r){let i={},a=new Set,o;for(t++;(o=e[t++])!==`}`&&o;)if(o===`,`)throw new a7(`expected value, found comma`,{toml:e,ptr:t-1});else if(o===`#`)t=c7(e,t);else if(o!==` `&&o!==` `&&o!==`
1078
+ `&&o!==`\r`){let o,s=i,c=!1,[l,u]=d7(e,t-1);for(let n=0;n<l.length;n++){if(n&&(s=c?s[o]:s[o]={}),o=l[n],(c=Object.hasOwn(s,o))&&(typeof s[o]!=`object`||a.has(s[o])))throw new a7(`trying to redefine an already defined value`,{toml:e,ptr:t});!c&&o===`__proto__`&&Object.defineProperty(s,o,{enumerable:!0,configurable:!0,writable:!0})}if(c)throw new a7(`trying to redefine an already defined value`,{toml:e,ptr:t});let[d,f]=u7(e,u,`}`,n-1,r);a.add(d),s[o]=d,t=f}if(!o)throw new a7(`unfinished table encountered`,{toml:e,ptr:t});return[i,t]}function nwe(e,t,n,r){let i=[],a;for(t++;(a=e[t++])!==`]`&&a;)if(a===`,`)throw new a7(`expected value, found comma`,{toml:e,ptr:t-1});else if(a===`#`)t=c7(e,t);else if(a!==` `&&a!==` `&&a!==`
1079
1079
  `&&a!==`\r`){let a=u7(e,t-1,`]`,n-1,r);i.push(a[0]),t=a[1]}if(!a)throw new a7(`unfinished array encountered`,{toml:e,ptr:t});return[i,t]}
1080
1080
  /*!
1081
1081
  * Copyright (c) Squirrel Chat et al., All rights reserved.
@@ -1104,7 +1104,7 @@ let $Ce=/^[a-zA-Z0-9-_]+[ \t]*$/;function d7(e,t,n=`=`){let r=t-1,i=[],a=e.index
1104
1104
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1105
1105
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1106
1106
  */
1107
- function f7(e,t,n,r){let i=t,a=n,o,s=!1,c;for(let t=0;t<e.length;t++){if(t){if(i=s?i[o]:i[o]={},a=(c=a[o]).c,r===0&&(c.t===1||c.t===2))return null;if(c.t===2){let e=i.length-1;i=i[e],a=a[e].c}}if(o=e[t],(s=Object.hasOwn(i,o))&&a[o]?.t===0&&a[o]?.d)return null;s||(o===`__proto__`&&(Object.defineProperty(i,o,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(a,o,{enumerable:!0,configurable:!0,writable:!0})),a[o]={t:t<e.length-1&&r===2?3:r,d:!1,i:0,c:{}})}if(c=a[o],c.t!==r&&!(r===1&&c.t===3)||(r===2&&(c.d||(c.d=!0,i[o]=[]),i[o].push(i={}),c.c[c.i++]=c={t:1,d:!1,i:0,c:{}}),c.d))return null;if(c.d=!0,r===1)i=s?i[o]:i[o]={};else if(r===0&&s)return null;return[o,i,c.c]}function nwe(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={},i={},a=r,o=i;for(let s=l7(e,0);s<e.length;){if(e[s]===`[`){let t=e[++s]===`[`,n=d7(e,s+=+t,`]`);if(t){if(e[n[1]-1]!==`]`)throw new a7(`expected end of table declaration`,{toml:e,ptr:n[1]-1});n[1]++}let c=f7(n[0],r,i,t?2:1);if(!c)throw new a7(`trying to redefine an already defined table or value`,{toml:e,ptr:s});o=c[2],a=c[1],s=n[1]}else{let r=d7(e,s),i=f7(r[0],a,o,0);if(!i)throw new a7(`trying to redefine an already defined table or value`,{toml:e,ptr:s});let c=u7(e,r[1],void 0,t,n);i[1][i[0]]=c[0],s=c[1]}if(s=l7(e,s,!0),e[s]&&e[s]!==`
1107
+ function f7(e,t,n,r){let i=t,a=n,o,s=!1,c;for(let t=0;t<e.length;t++){if(t){if(i=s?i[o]:i[o]={},a=(c=a[o]).c,r===0&&(c.t===1||c.t===2))return null;if(c.t===2){let e=i.length-1;i=i[e],a=a[e].c}}if(o=e[t],(s=Object.hasOwn(i,o))&&a[o]?.t===0&&a[o]?.d)return null;s||(o===`__proto__`&&(Object.defineProperty(i,o,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(a,o,{enumerable:!0,configurable:!0,writable:!0})),a[o]={t:t<e.length-1&&r===2?3:r,d:!1,i:0,c:{}})}if(c=a[o],c.t!==r&&!(r===1&&c.t===3)||(r===2&&(c.d||(c.d=!0,i[o]=[]),i[o].push(i={}),c.c[c.i++]=c={t:1,d:!1,i:0,c:{}}),c.d))return null;if(c.d=!0,r===1)i=s?i[o]:i[o]={};else if(r===0&&s)return null;return[o,i,c.c]}function rwe(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={},i={},a=r,o=i;for(let s=l7(e,0);s<e.length;){if(e[s]===`[`){let t=e[++s]===`[`,n=d7(e,s+=+t,`]`);if(t){if(e[n[1]-1]!==`]`)throw new a7(`expected end of table declaration`,{toml:e,ptr:n[1]-1});n[1]++}let c=f7(n[0],r,i,t?2:1);if(!c)throw new a7(`trying to redefine an already defined table or value`,{toml:e,ptr:s});o=c[2],a=c[1],s=n[1]}else{let r=d7(e,s),i=f7(r[0],a,o,0);if(!i)throw new a7(`trying to redefine an already defined table or value`,{toml:e,ptr:s});let c=u7(e,r[1],void 0,t,n);i[1][i[0]]=c[0],s=c[1]}if(s=l7(e,s,!0),e[s]&&e[s]!==`
1108
1108
  `&&e[s]!==`\r`)throw new a7(`each key-value declaration must be followed by an end-of-line`,{toml:e,ptr:s});s=l7(e,s)}return r}
1109
1109
  /*!
1110
1110
  * Copyright (c) Squirrel Chat et al., All rights reserved.
@@ -1133,13 +1133,13 @@ function f7(e,t,n,r){let i=t,a=n,o,s=!1,c;for(let t=0;t<e.length;t++){if(t){if(i
1133
1133
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1134
1134
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1135
1135
  */
1136
- let p7=/^[a-z0-9-_]+$/i;function m7(e){let t=typeof e;if(t===`object`){if(Array.isArray(e))return`array`;if(e instanceof Date)return`date`}return t}function rwe(e){for(let t=0;t<e.length;t++)if(m7(e[t])!==`object`)return!1;return e.length!=0}function h7(e){return JSON.stringify(e).replace(/\x7f/g,`\\u007f`)}function g7(e,t,n,r){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);if(t===`number`)return isNaN(e)?`nan`:e===1/0?`inf`:e===-1/0?`-inf`:Number.isInteger(e)&&(r||!Number.isSafeInteger(e))?e.toFixed(1):e.toString();if(t===`bigint`||t===`boolean`)return e.toString();if(t===`string`)return h7(e);if(t===`date`){if(isNaN(e.getTime()))throw TypeError(`cannot serialize invalid date`);return e.toISOString()}if(t===`object`)return iwe(e,n,r);if(t===`array`)return awe(e,n,r)}function iwe(e,t,n){let r=Object.keys(e);if(r.length===0)return`{}`;let i=`{ `;for(let a=0;a<r.length;a++){let o=r[a];a&&(i+=`, `),i+=p7.test(o)?o:h7(o),i+=` = `,i+=g7(e[o],m7(e[o]),t-1,n)}return i+` }`}function awe(e,t,n){if(e.length===0)return`[]`;let r=`[ `;for(let i=0;i<e.length;i++){if(i&&(r+=`, `),e[i]===null||e[i]===void 0)throw TypeError(`arrays cannot contain null or undefined values`);r+=g7(e[i],m7(e[i]),t-1,n)}return r+` ]`}function owe(e,t,n,r){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let i=``;for(let a=0;a<e.length;a++)i+=`${i&&`
1137
- `}[[${t}]]\n`,i+=_7(0,e[a],t,n,r);return i}function _7(e,t,n,r,i){if(r===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let a=``,o=``,s=Object.keys(t);for(let e=0;e<s.length;e++){let c=s[e];if(t[c]!==null&&t[c]!==void 0){let e=m7(t[c]);if(e===`symbol`||e===`function`)throw TypeError(`cannot serialize values of type '${e}'`);let s=p7.test(c)?c:h7(c);if(e===`array`&&rwe(t[c]))o+=(o&&`
1138
- `)+owe(t[c],n?`${n}.${s}`:s,r-1,i);else if(e===`object`){let e=n?`${n}.${s}`:s;o+=(o&&`
1136
+ let p7=/^[a-z0-9-_]+$/i;function m7(e){let t=typeof e;if(t===`object`){if(Array.isArray(e))return`array`;if(e instanceof Date)return`date`}return t}function iwe(e){for(let t=0;t<e.length;t++)if(m7(e[t])!==`object`)return!1;return e.length!=0}function h7(e){return JSON.stringify(e).replace(/\x7f/g,`\\u007f`)}function g7(e,t,n,r){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);if(t===`number`)return isNaN(e)?`nan`:e===1/0?`inf`:e===-1/0?`-inf`:Number.isInteger(e)&&(r||!Number.isSafeInteger(e))?e.toFixed(1):e.toString();if(t===`bigint`||t===`boolean`)return e.toString();if(t===`string`)return h7(e);if(t===`date`){if(isNaN(e.getTime()))throw TypeError(`cannot serialize invalid date`);return e.toISOString()}if(t===`object`)return awe(e,n,r);if(t===`array`)return owe(e,n,r)}function awe(e,t,n){let r=Object.keys(e);if(r.length===0)return`{}`;let i=`{ `;for(let a=0;a<r.length;a++){let o=r[a];a&&(i+=`, `),i+=p7.test(o)?o:h7(o),i+=` = `,i+=g7(e[o],m7(e[o]),t-1,n)}return i+` }`}function owe(e,t,n){if(e.length===0)return`[]`;let r=`[ `;for(let i=0;i<e.length;i++){if(i&&(r+=`, `),e[i]===null||e[i]===void 0)throw TypeError(`arrays cannot contain null or undefined values`);r+=g7(e[i],m7(e[i]),t-1,n)}return r+` ]`}function swe(e,t,n,r){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let i=``;for(let a=0;a<e.length;a++)i+=`${i&&`
1137
+ `}[[${t}]]\n`,i+=_7(0,e[a],t,n,r);return i}function _7(e,t,n,r,i){if(r===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let a=``,o=``,s=Object.keys(t);for(let e=0;e<s.length;e++){let c=s[e];if(t[c]!==null&&t[c]!==void 0){let e=m7(t[c]);if(e===`symbol`||e===`function`)throw TypeError(`cannot serialize values of type '${e}'`);let s=p7.test(c)?c:h7(c);if(e===`array`&&iwe(t[c]))o+=(o&&`
1138
+ `)+swe(t[c],n?`${n}.${s}`:s,r-1,i);else if(e===`object`){let e=n?`${n}.${s}`:s;o+=(o&&`
1139
1139
  `)+_7(e,t[c],e,r-1,i)}else a+=s,a+=` = `,a+=g7(t[c],e,r,i),a+=`
1140
- `}}return e&&(a||!o)&&(a=a?`[${e}]\n${a}`:`[${e}]`),a&&o?`${a}\n${o}`:a||o}function swe(e,{maxDepth:t=1e3,numbersAsFloat:n=!1}={}){if(m7(e)!==`object`)throw TypeError(`stringify can only be called with an object`);let r=_7(0,e,``,t,n);return r[r.length-1]===`
1140
+ `}}return e&&(a||!o)&&(a=a?`[${e}]\n${a}`:`[${e}]`),a&&o?`${a}\n${o}`:a||o}function cwe(e,{maxDepth:t=1e3,numbersAsFloat:n=!1}={}){if(m7(e)!==`object`)throw TypeError(`stringify can only be called with an object`);let r=_7(0,e,``,t,n);return r[r.length-1]===`
1141
1141
  `?r:r+`
1142
- `}function cwe(e){let{projectDir:t,contentDir:n,sampleCap:r=5}=e,i=[],a=[];try{_(n)}catch(e){return{totalCount:0,sample:[],contentDir:n,warnings:[`cannot access content directory ${n}: ${e instanceof Error?e.message:String(e)}`]}}let o;try{o=_be({projectDir:t,contentDir:n})}catch(e){return{totalCount:0,sample:[],contentDir:n,warnings:[e instanceof Error?e.message:String(e)]}}function s(e){let t;try{t=C(e,{withFileTypes:!0})}catch(t){let r=t instanceof Error?t.message:String(t);i.push(`could not read directory ${_e(n,e)||`.`}: ${r}`);return}for(let r of t){let t=N(e,r.name);if(r.isSymbolicLink()){let e;try{e=T(t)}catch(e){let r=e.code;r===`ENOENT`||r===`ELOOP`?i.push(`broken or cyclic symlink: ${_e(n,t)}`):i.push(`cannot resolve symlink ${_e(n,t)}: ${r??`unknown error`}`);continue}let r;try{r=O(e)}catch{continue}if(r.isDirectory()){let e=_e(n,t);if(o.isDirExcluded(e))continue;s(t)}else if(r.isFile()){let e=_e(n,t);if(o.isExcluded(e))continue;a.push(e)}}else if(r.isDirectory()){let e=_e(n,t);if(o.isDirExcluded(e))continue;s(t)}else if(r.isFile()){let e=_e(n,t);if(o.isExcluded(e))continue;a.push(e)}}}return s(n),{totalCount:a.length,sample:a.slice(0,r),contentDir:n,warnings:i}}const lwe=`${R5}-dev`;function uwe(e){return e.startsWith(R5)}function v7(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.command!==`ok-pi-managed-extension`||!Array.isArray(t.args))return!1;let n=t.args[0];return typeof n==`string`&&uwe(n)}function dwe(e){return{command:`ok-pi-managed-extension`,args:[e]}}function y7(e={}){let t=e.mode===`dev`?lwe:z5,n={unix:H5({...e,platformName:`darwin`}),win32:H5({...e,platformName:`win32`})};return`${t}
1142
+ `}function lwe(e){let{projectDir:t,contentDir:n,sampleCap:r=5}=e,i=[],a=[];try{_(n)}catch(e){return{totalCount:0,sample:[],contentDir:n,warnings:[`cannot access content directory ${n}: ${e instanceof Error?e.message:String(e)}`]}}let o;try{o=_be({projectDir:t,contentDir:n})}catch(e){return{totalCount:0,sample:[],contentDir:n,warnings:[e instanceof Error?e.message:String(e)]}}function s(e){let t;try{t=C(e,{withFileTypes:!0})}catch(t){let r=t instanceof Error?t.message:String(t);i.push(`could not read directory ${_e(n,e)||`.`}: ${r}`);return}for(let r of t){let t=N(e,r.name);if(r.isSymbolicLink()){let e;try{e=T(t)}catch(e){let r=e.code;r===`ENOENT`||r===`ELOOP`?i.push(`broken or cyclic symlink: ${_e(n,t)}`):i.push(`cannot resolve symlink ${_e(n,t)}: ${r??`unknown error`}`);continue}let r;try{r=O(e)}catch{continue}if(r.isDirectory()){let e=_e(n,t);if(o.isDirExcluded(e))continue;s(t)}else if(r.isFile()){let e=_e(n,t);if(o.isExcluded(e))continue;a.push(e)}}else if(r.isDirectory()){let e=_e(n,t);if(o.isDirExcluded(e))continue;s(t)}else if(r.isFile()){let e=_e(n,t);if(o.isExcluded(e))continue;a.push(e)}}}return s(n),{totalCount:a.length,sample:a.slice(0,r),contentDir:n,warnings:i}}const uwe=`${R5}-dev`;function dwe(e){return e.startsWith(R5)}function v7(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.command!==`ok-pi-managed-extension`||!Array.isArray(t.args))return!1;let n=t.args[0];return typeof n==`string`&&dwe(n)}function fwe(e){return{command:`ok-pi-managed-extension`,args:[e]}}function y7(e={}){let t=e.mode===`dev`?uwe:z5,n={unix:H5({...e,platformName:`darwin`}),win32:H5({...e,platformName:`win32`})};return`${t}
1143
1143
  /**
1144
1144
  * Open Knowledge bridge for Pi — MANAGED FILE, written by \`ok init\`.
1145
1145
  * Hand edits are overwritten whenever OK re-syncs this project; remove it
@@ -1482,53 +1482,53 @@ export default function okBridge(pi: {
1482
1482
  }
1483
1483
  });
1484
1484
  }
1485
- `}function fwe(e,t){let n=_e(U6(t),U6(e));return n.length>0&&!n.startsWith(`..`)&&!M(n)}const pwe=e=>{try{let t=c(`git`,[`rev-parse`,`--show-toplevel`],l3({cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]})).trim();return t.length>0?t:null}catch{return null}};function mwe(e,t={}){let n=t.homeDir??oe(),r=t.gitTopLevel??pwe,i=ve(e),a;try{a=T(i)}catch{a=i}let o=a,s=0;for(;s<30&&!(o===n||o===`/`||o===``);){if(b3(o))return{projectRoot:o,defaultContentDir:`.`,ancestorPromoted:o!==a,gitRootPromoted:!1};let e=pe(o);if(e===o)break;o=e,s+=1}let c=r(a);return c!==null&&fwe(c,n)?c===a?{projectRoot:i,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!1}:{projectRoot:c,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!0}:{projectRoot:i,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!1}}function b7(e,t){let n;try{n=_(e)}catch(e){if(e.code!==`ENOENT`)throw e}if(n?.isSymbolicLink())throw Error(`Refusing to write through a symbolic link at ${e}. Remove the symlink and re-run project setup.`);x7(e,t)}function hwe(e,t){x7(e,t)}function x7(e,t){let n;try{n=T(t)}catch{n=ve(t)}let r=pe(e);for(;r.length>1&&r!==ye;){let t;try{t=T(r)}catch(e){if(e.code===`ENOENT`){r=pe(r);continue}throw e}let i=_e(n,t);if(i===``||!i.startsWith(`..`)&&!M(i))return;throw Error(`Refusing to write at ${e}: ancestor ${r} resolves to ${t}, which is outside the project directory ${n}. A symbolic link in the path likely escapes the project. Remove the symlink and re-run project setup.`)}}function S7(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function gwe(e,t,n){try{if(O(n).size>10485760)return!1}catch{return!1}let r;try{r=S(n,`utf-8`)}catch{return!1}let i=[],a=kbe(r.charCodeAt(0)===65279?r.slice(1):r,i,{allowTrailingComma:!0,disallowComments:!1});if(i.length>0||!S7(a))return!1;let o=a[e.topLevelKey];if(!S7(o))return!1;let s=e.serverMapSubKey?o[e.serverMapSubKey]:o;return S7(s)?S7(s[e.serverName(t)]):!1}function _we(e,t,n={}){if(!Eu.includes(e.id))return!0;try{return gwe(e,t,e.configPath(t,n.home))}catch{return!1}}function C7(e,t,n={}){let r=e.projectSkillPath?.(t);if(!r)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};if(!_we(e,t,n))return{editorId:e.id,label:e.label,action:`skipped-prerequisite`,path:r};try{let n=Uye(`project`,{checkDesktop:!0}),i=pe(r);b7(i,t);let a=g(r)?`overwritten`:`written`;return D(i,{recursive:!0,force:!0}),v(pe(i),{recursive:!0}),m(n,i,{recursive:!0}),{editorId:e.id,label:e.label,action:a,path:r}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:r,error:t instanceof Error?t.message:String(t)}}}function vwe(e,t){let n=e.projectSkillPath?.(t);if(!n)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};try{let r=pe(n);return g(n)?(hwe(r,t),D(r,{recursive:!0,force:!0}),{editorId:e.id,label:e.label,action:`removed`,path:n}):{editorId:e.id,label:e.label,action:`not-present`,path:n}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function w7(e){let t=e&&typeof e==`object`&&`code`in e?e.code:void 0;return t===`MODULE_NOT_FOUND`||t===`ERR_MODULE_NOT_FOUND`}function T7(e,t){if(!process.env.OK_DEBUG_NATIVE)return;let n=t instanceof Error?t.message:String(t);process.stderr.write(`[ok] native-config ${e}: ${n}\n`)}const ywe=[`native`,`index.js`];function E7(e={}){let t=e.moduleUrl??import.meta.url,n=e.requireModule??o(t);try{return n(N(pe(Se(t)),...ywe))}catch(e){w7(e)||T7(`bundled loader failed to load`,e)}try{return n(`@inkeep/open-knowledge-native-config`)}catch(e){return w7(e)||T7(`workspace addon failed to load`,e),null}}function bwe(){let e=E7();return e&&typeof e.resolveSymlinkWritePath==`function`?e:null}function xwe(e){let t=e,n=new Set;for(;;){let r;try{r=_(t).isSymbolicLink()}catch(n){return n.code===`ENOENT`?{readPath:t,writePath:t}:{readPath:null,writePath:e}}if(!r)return{readPath:t,writePath:t};if(n.has(t))return{readPath:null,writePath:e};n.add(t);let i;try{i=w(t)}catch(t){return T7(`readlinkSync threw during symlink walk`,t),{readPath:null,writePath:e}}t=M(i)?i:N(pe(t),i)}}let D7;function Swe(){return D7===void 0&&(D7=bwe()),D7}function Cwe(e,t=Swe){let n=t();if(n)try{let t=n.resolveSymlinkWritePath(e);return{readPath:t.readPath??null,writePath:t.writePath}}catch(e){T7(`resolveSymlinkWritePath threw`,e)}return xwe(e)}function O7(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function wwe(){let e=E7();return e&&typeof e.parseTomlToJson==`function`?e:null}function Twe(e){try{let t=e.parseTomlToJson(`probe = 1`);return typeof t==`string`&&t.includes(`probe`)}catch(e){return T7(`addon loaded but probe failed`,e),!1}}function k7(e){if(!O7(e))throw Error(`TOML root is not a table`);return e}function Ewe(e){return{backend:`native`,parseToObject(t){return k7(JSON.parse(e.parseTomlToJson(t)))},upsertEntry(t,n,r){let i=e.upsertMcpServer(t,n,JSON.stringify(r));return{text:i.text,existed:i.existed}},removeEntry(t,n){let r=e.removeMcpServer(t,n);return{text:r.text,existed:r.existed}}}}function Dwe(){return{backend:`fallback`,parseToObject(e){return k7(nwe(e))}}}function Owe(e=wwe){let t=e();return t&&Twe(t)?Ewe(t):Dwe()}let A7=null;function j7(){return A7===null&&(A7=Owe()),A7}function kwe(){let e=j7();return e.backend===`native`?e:void 0}const M7=`**/.ok/*`,N7=`!**/${hu}/`;function P7(e){let t=[`.ok/`,`.okignore`];for(let n of M5){let r=e7[n];r.projectConfigPath&&t.push(Pwe(r.projectConfigPath(e),e))}return t.push(`.claude/launch.json`),Array.from(new Set(t))}function F7(e){let t=N(e,...Yse);if(!g(t))return[];try{let e=$se(S(t,`utf-8`));if(!e)return[];let n=[];for(let[t,r]of Object.entries(e.skills))if(t!==`open-knowledge`)for(let e of r.hosts){let r=yu[e];r&&n.push(`${r}/${t}/`)}return Array.from(new Set(n))}catch{return[]}}function Awe(e,t){let n=I7(e,t).tracked;if(n.length>0)return{kind:`refused-tracked`,tracked:n,remediation:L7(n)};let r=R7(e);if(r.kind!==`ok`)return r.result;let i=g(r.path)?S(r.path,`utf-8`):``,a=new Set(F7(e)),o=[],s=a.size===0?i:i.split(`
1485
+ `}function pwe(e,t){let n=_e(U6(t),U6(e));return n.length>0&&!n.startsWith(`..`)&&!M(n)}const mwe=e=>{try{let t=c(`git`,[`rev-parse`,`--show-toplevel`],l3({cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]})).trim();return t.length>0?t:null}catch{return null}};function hwe(e,t={}){let n=t.homeDir??oe(),r=t.gitTopLevel??mwe,i=ve(e),a;try{a=T(i)}catch{a=i}let o=a,s=0;for(;s<30&&!(o===n||o===`/`||o===``);){if(b3(o))return{projectRoot:o,defaultContentDir:`.`,ancestorPromoted:o!==a,gitRootPromoted:!1};let e=pe(o);if(e===o)break;o=e,s+=1}let c=r(a);return c!==null&&pwe(c,n)?c===a?{projectRoot:i,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!1}:{projectRoot:c,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!0}:{projectRoot:i,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!1}}function b7(e,t){let n;try{n=_(e)}catch(e){if(e.code!==`ENOENT`)throw e}if(n?.isSymbolicLink())throw Error(`Refusing to write through a symbolic link at ${e}. Remove the symlink and re-run project setup.`);x7(e,t)}function gwe(e,t){x7(e,t)}function x7(e,t){let n;try{n=T(t)}catch{n=ve(t)}let r=pe(e);for(;r.length>1&&r!==ye;){let t;try{t=T(r)}catch(e){if(e.code===`ENOENT`){r=pe(r);continue}throw e}let i=_e(n,t);if(i===``||!i.startsWith(`..`)&&!M(i))return;throw Error(`Refusing to write at ${e}: ancestor ${r} resolves to ${t}, which is outside the project directory ${n}. A symbolic link in the path likely escapes the project. Remove the symlink and re-run project setup.`)}}function S7(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function _we(e,t,n){try{if(O(n).size>10485760)return!1}catch{return!1}let r;try{r=S(n,`utf-8`)}catch{return!1}let i=[],a=kbe(r.charCodeAt(0)===65279?r.slice(1):r,i,{allowTrailingComma:!0,disallowComments:!1});if(i.length>0||!S7(a))return!1;let o=a[e.topLevelKey];if(!S7(o))return!1;let s=e.serverMapSubKey?o[e.serverMapSubKey]:o;return S7(s)?S7(s[e.serverName(t)]):!1}function vwe(e,t,n={}){if(!Eu.includes(e.id))return!0;try{return _we(e,t,e.configPath(t,n.home))}catch{return!1}}function C7(e,t,n={}){let r=e.projectSkillPath?.(t);if(!r)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};if(!vwe(e,t,n))return{editorId:e.id,label:e.label,action:`skipped-prerequisite`,path:r};try{let n=Uye(`project`,{checkDesktop:!0}),i=pe(r);b7(i,t);let a=g(r)?`overwritten`:`written`;return D(i,{recursive:!0,force:!0}),v(pe(i),{recursive:!0}),m(n,i,{recursive:!0}),{editorId:e.id,label:e.label,action:a,path:r}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:r,error:t instanceof Error?t.message:String(t)}}}function ywe(e,t){let n=e.projectSkillPath?.(t);if(!n)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};try{let r=pe(n);return g(n)?(gwe(r,t),D(r,{recursive:!0,force:!0}),{editorId:e.id,label:e.label,action:`removed`,path:n}):{editorId:e.id,label:e.label,action:`not-present`,path:n}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function w7(e){let t=e&&typeof e==`object`&&`code`in e?e.code:void 0;return t===`MODULE_NOT_FOUND`||t===`ERR_MODULE_NOT_FOUND`}function T7(e,t){if(!process.env.OK_DEBUG_NATIVE)return;let n=t instanceof Error?t.message:String(t);process.stderr.write(`[ok] native-config ${e}: ${n}\n`)}const bwe=[`native`,`index.js`];function E7(e={}){let t=e.moduleUrl??import.meta.url,n=e.requireModule??o(t);try{return n(N(pe(Se(t)),...bwe))}catch(e){w7(e)||T7(`bundled loader failed to load`,e)}try{return n(`@inkeep/open-knowledge-native-config`)}catch(e){return w7(e)||T7(`workspace addon failed to load`,e),null}}function xwe(){let e=E7();return e&&typeof e.resolveSymlinkWritePath==`function`?e:null}function Swe(e){let t=e,n=new Set;for(;;){let r;try{r=_(t).isSymbolicLink()}catch(n){return n.code===`ENOENT`?{readPath:t,writePath:t}:{readPath:null,writePath:e}}if(!r)return{readPath:t,writePath:t};if(n.has(t))return{readPath:null,writePath:e};n.add(t);let i;try{i=w(t)}catch(t){return T7(`readlinkSync threw during symlink walk`,t),{readPath:null,writePath:e}}t=M(i)?i:N(pe(t),i)}}let D7;function Cwe(){return D7===void 0&&(D7=xwe()),D7}function wwe(e,t=Cwe){let n=t();if(n)try{let t=n.resolveSymlinkWritePath(e);return{readPath:t.readPath??null,writePath:t.writePath}}catch(e){T7(`resolveSymlinkWritePath threw`,e)}return Swe(e)}function O7(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Twe(){let e=E7();return e&&typeof e.parseTomlToJson==`function`?e:null}function Ewe(e){try{let t=e.parseTomlToJson(`probe = 1`);return typeof t==`string`&&t.includes(`probe`)}catch(e){return T7(`addon loaded but probe failed`,e),!1}}function k7(e){if(!O7(e))throw Error(`TOML root is not a table`);return e}function Dwe(e){return{backend:`native`,parseToObject(t){return k7(JSON.parse(e.parseTomlToJson(t)))},upsertEntry(t,n,r){let i=e.upsertMcpServer(t,n,JSON.stringify(r));return{text:i.text,existed:i.existed}},removeEntry(t,n){let r=e.removeMcpServer(t,n);return{text:r.text,existed:r.existed}}}}function Owe(){return{backend:`fallback`,parseToObject(e){return k7(rwe(e))}}}function kwe(e=Twe){let t=e();return t&&Ewe(t)?Dwe(t):Owe()}let A7=null;function j7(){return A7===null&&(A7=kwe()),A7}function Awe(){let e=j7();return e.backend===`native`?e:void 0}const M7=`**/.ok/*`,N7=`!**/${hu}/`;function P7(e){let t=[`.ok/`,`.okignore`];for(let n of M5){let r=e7[n];r.projectConfigPath&&t.push(Fwe(r.projectConfigPath(e),e))}return t.push(`.claude/launch.json`),Array.from(new Set(t))}function F7(e){let t=N(e,...Yse);if(!g(t))return[];try{let e=$se(S(t,`utf-8`));if(!e)return[];let n=[];for(let[t,r]of Object.entries(e.skills))if(t!==`open-knowledge`)for(let e of r.hosts){let r=yu[e];r&&n.push(`${r}/${t}/`)}return Array.from(new Set(n))}catch{return[]}}function jwe(e,t){let n=I7(e,t).tracked;if(n.length>0)return{kind:`refused-tracked`,tracked:n,remediation:L7(n)};let r=R7(e);if(r.kind!==`ok`)return r.result;let i=g(r.path)?S(r.path,`utf-8`):``,a=new Set(F7(e)),o=[],s=a.size===0?i:i.split(`
1486
1486
  `).filter(e=>{let t=e.trim();return a.has(t)?(o.push(t),!1):!0}).join(`
1487
1487
  `),c=V7(s),l=[],u=[];for(let e of t)B7(c,e)?u.push(e):l.push(e);if(l.length===0&&o.length===0)return{kind:`updated`,appended:l,alreadyPresent:u,removed:[]};let d=l.length===0||s.length===0||s.endsWith(`
1488
1488
  `)?``:`
1489
1489
  `,f=l.length===0?``:`${l.join(`
1490
- `)}\n`;try{te(r.path,`${s}${d}${f}`,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}return{kind:`updated`,appended:l,alreadyPresent:u,removed:o}}function jwe(e,t){let n=R7(e);if(n.kind!==`ok`)return n.result;if(!g(n.path))return{kind:`updated`,appended:[],alreadyPresent:[],removed:[]};let r=t.map(e=>z7(e)),i=new Set;for(let e of r)for(let t of e)i.add(t);i.add(M7),i.add(N7);for(let t of F7(e))i.add(t);let a;try{a=S(n.path,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}let o=a.split(`
1490
+ `)}\n`;try{te(r.path,`${s}${d}${f}`,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}return{kind:`updated`,appended:l,alreadyPresent:u,removed:o}}function Mwe(e,t){let n=R7(e);if(n.kind!==`ok`)return n.result;if(!g(n.path))return{kind:`updated`,appended:[],alreadyPresent:[],removed:[]};let r=t.map(e=>z7(e)),i=new Set;for(let e of r)for(let t of e)i.add(t);i.add(M7),i.add(N7);for(let t of F7(e))i.add(t);let a;try{a=S(n.path,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}let o=a.split(`
1491
1491
  `),s=new Set,c=[];for(let e of o){let t=e.trim();if(i.has(t)){s.add(t);continue}c.push(e)}let l=[...s];if(s.size===0)return{kind:`updated`,appended:[],alreadyPresent:[],removed:[]};let u=c.join(`
1492
- `);if(u!==a)try{te(n.path,u,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}return{kind:`updated`,appended:[],alreadyPresent:[],removed:l}}function Mwe(e){let t=R7(e);if(t.kind!==`ok`)return t.result.reason===`no-git`||t.result.reason===`malformed-pointer`||t.result.reason===`inaccessible`?`no-git`:`shared`;if(!g(t.path))return`shared`;let n;try{n=S(t.path,`utf-8`)}catch{return`shared`}let r=V7(n),i=P7(e);for(let e of i)if(B7(r,e))return`local-only`;return r.has(M7)?`local-only`:`shared`}function Nwe(e){let t=R7(e);if(t.kind!==`ok`||!g(t.path))return[];let n;try{n=S(t.path,`utf-8`)}catch{return[]}let r=V7(n),i=[...P7(e),...F7(e)].filter(e=>B7(r,e)),a=new Set(i),o=[];for(let e of Object.values(yu))e!==null&&o.push(e);let s=[];for(let e of r){if(a.has(e))continue;if(e===M7||e===N7){s.push(e);continue}let t=e.replace(/^\//,``).replace(/\/$/,``);o.some(e=>t.startsWith(`${e}/`)&&t.length>e.length+1)&&s.push(e)}return[...i,...s]}function I7(e,t){let n=[];for(let r of t)if(g(ve(e,r)))try{c(`git`,[`ls-files`,`--error-unmatch`,`--`,r],l3({cwd:e,stdio:[`ignore`,`ignore`,`ignore`]})),n.push(r)}catch{}return{tracked:n}}function L7(e){let t=[];t.push(`Cannot switch OpenKnowledge to local-only — these OK files are tracked upstream:`),t.push(``);for(let n of e)t.push(` ${n}`);t.push(``),t.push(`.git/info/exclude only hides files that git isn't already tracking. To proceed, untrack them first:`),t.push(``);for(let n of e){let e=n.replace(/\/$/,``),r=n.endsWith(`/`)?`-r `:``;t.push(` git rm --cached ${r}${e}`)}return t.push(``),t.push("Then re-run the command. Note: `git rm --cached` removes the files from the index — your teammates will see a deletion on their next pull. If you don't want that, leave sharing mode set to 'shared'."),t.join(`
1492
+ `);if(u!==a)try{te(n.path,u,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}return{kind:`updated`,appended:[],alreadyPresent:[],removed:l}}function Nwe(e){let t=R7(e);if(t.kind!==`ok`)return t.result.reason===`no-git`||t.result.reason===`malformed-pointer`||t.result.reason===`inaccessible`?`no-git`:`shared`;if(!g(t.path))return`shared`;let n;try{n=S(t.path,`utf-8`)}catch{return`shared`}let r=V7(n),i=P7(e);for(let e of i)if(B7(r,e))return`local-only`;return r.has(M7)?`local-only`:`shared`}function Pwe(e){let t=R7(e);if(t.kind!==`ok`||!g(t.path))return[];let n;try{n=S(t.path,`utf-8`)}catch{return[]}let r=V7(n),i=[...P7(e),...F7(e)].filter(e=>B7(r,e)),a=new Set(i),o=[];for(let e of Object.values(yu))e!==null&&o.push(e);let s=[];for(let e of r){if(a.has(e))continue;if(e===M7||e===N7){s.push(e);continue}let t=e.replace(/^\//,``).replace(/\/$/,``);o.some(e=>t.startsWith(`${e}/`)&&t.length>e.length+1)&&s.push(e)}return[...i,...s]}function I7(e,t){let n=[];for(let r of t)if(g(ve(e,r)))try{c(`git`,[`ls-files`,`--error-unmatch`,`--`,r],l3({cwd:e,stdio:[`ignore`,`ignore`,`ignore`]})),n.push(r)}catch{}return{tracked:n}}function L7(e){let t=[];t.push(`Cannot switch OpenKnowledge to local-only — these OK files are tracked upstream:`),t.push(``);for(let n of e)t.push(` ${n}`);t.push(``),t.push(`.git/info/exclude only hides files that git isn't already tracking. To proceed, untrack them first:`),t.push(``);for(let n of e){let e=n.replace(/\/$/,``),r=n.endsWith(`/`)?`-r `:``;t.push(` git rm --cached ${r}${e}`)}return t.push(``),t.push("Then re-run the command. Note: `git rm --cached` removes the files from the index — your teammates will see a deletion on their next pull. If you don't want that, leave sharing mode set to 'shared'."),t.join(`
1493
1493
  `)}function R7(e){let t=FX(e);switch(t.kind){case`repository`:{let e=t.repository.readCommonDir();if(e.kind===`unreadable`)return{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`inaccessible`}};let n=N(e.path,`info`);return g(n)?{kind:`ok`,path:N(n,`exclude`)}:{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`no-info-dir`}}}case`absent`:return{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`no-git`}};case`malformed-pointer`:return{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`malformed-pointer`}};case`inaccessible`:return{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`inaccessible`}}}}function z7(e){let t=e.replace(/\/$/,``);return new Set([e,t,`/${e}`,`/${t}`])}function B7(e,t){for(let n of z7(t))if(e.has(n))return!0;return!1}function V7(e){let t=new Set;for(let n of e.split(`
1494
- `)){let e=n.trim();e.length!==0&&t.add(e)}return t}function Pwe(e,t){return Fwe(_e(t,e))}function Fwe(e){return ye===`/`?e:e.split(ye).join(`/`)}function Iwe(e){for(let t of e.split(`
1495
- `)){let e=t.trimStart();if(!(e.length===0||e.length===t.length))return t.charCodeAt(0)===9?{insertSpaces:!1,tabSize:1}:{insertSpaces:!0,tabSize:t.length-e.length}}return{insertSpaces:!0,tabSize:2}}function H7(e){let t=(e.match(/\r\n/g)??[]).length;return t===0?!1:t>=(e.match(/\n/g)??[]).length-t}function U7(e){try{return O(e).mode&511}catch{return}}function Lwe(e,t){let n=e.charCodeAt(0)===65279,r=n?e.slice(1):e,i=r.includes(`\r
1494
+ `)){let e=n.trim();e.length!==0&&t.add(e)}return t}function Fwe(e,t){return Iwe(_e(t,e))}function Iwe(e){return ye===`/`?e:e.split(ye).join(`/`)}function Lwe(e){for(let t of e.split(`
1495
+ `)){let e=t.trimStart();if(!(e.length===0||e.length===t.length))return t.charCodeAt(0)===9?{insertSpaces:!1,tabSize:1}:{insertSpaces:!0,tabSize:t.length-e.length}}return{insertSpaces:!0,tabSize:2}}function H7(e){let t=(e.match(/\r\n/g)??[]).length;return t===0?!1:t>=(e.match(/\n/g)??[]).length-t}function U7(e){try{return O(e).mode&511}catch{return}}function Rwe(e,t){let n=e.charCodeAt(0)===65279,r=n?e.slice(1):e,i=r.includes(`\r
1496
1496
  `)?`\r
1497
1497
  `:`
1498
- `,a=i6(r,t,void 0,{formattingOptions:{...Iwe(r),eol:i}});if(a.length===0)return{text:e,changed:!1};let o=`${n?``:``}${a6(r,a)}`;return{text:o,changed:o!==e}}const Rwe={allowTrailingComma:!0,disallowComments:!1};function zwe(e,t){return e.error===1&&e.offset===0&&t.charCodeAt(0)===65279}function W7(e){let t=[],n=Abe(e,t,Rwe);return t.some(t=>!zwe(t,e))||!n||n.type!==`object`?null:n}function G7(e,t){let n=0;for(let r of e.children??[]){let e=r.children?.[0];e!==void 0&&r6(e)===t&&(n+=1)}return n}function K7(e,t){WQ(e,`${JSON.stringify(t,null,2)}\n`)}function Bwe(e,t){let n=swe(t);WQ(e,n.endsWith(`
1499
- `)?n:`${n}\n`)}function Vwe(e,t){let n=(0,on.stringify)(t);WQ(e,n.endsWith(`
1500
- `)?n:`${n}\n`)}const q7=10*1024*1024;function J7(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>J7(e,t[n]));if(O7(e)&&O7(t)){let n=Object.keys(e);return n.length===Object.keys(t).length?n.every(n=>Object.hasOwn(t,n)&&J7(e[n],t[n])):!1}return!1}const Hwe=[`command`,`args`],Uwe=[`type`,`command`];function Y7(e){return e.type===`local`&&Array.isArray(e.command)?Uwe:Hwe}function Wwe(e,t,n){return O7(e)&&n.every(n=>J7(e[n],t[n]))}function Gwe(e){for(let t of e.split(`
1501
- `)){let e=t.trimStart();if(!(e.length===0||e.length===t.length))return t.charCodeAt(0)===9?{insertSpaces:!1,tabSize:1}:{insertSpaces:!0,tabSize:t.length-e.length}}return{insertSpaces:!0,tabSize:2}}function X7(e,t,n){return t===void 0?[e,n]:[e,t,n]}function Z7(e,t,n,r){let i={[n]:r};return{[e]:t===void 0?i:{[t]:i}}}function Q7(e,t,n){let r=e[t];return n===void 0?r:O7(r)?r[n]:void 0}function Kwe(e,t,n,r,i){if(!g(e))return K7(e,Z7(t,i,n,r)),{kind:`written`};let a;try{a=S(e,`utf-8`)}catch(e){return T7(`json config read failed`,e),{kind:`declined`,reason:`unparseable`}}if(a.trim()===``)return K7(e,Z7(t,i,n,r)),{kind:`written`};if(Buffer.byteLength(a,`utf-8`)>q7)return{kind:`declined`,reason:`oversize`};let o=W7(a);if(!o)return{kind:`declined`,reason:`unparseable`};if(G7(o,t)>1)return{kind:`declined`,reason:`duplicate-container`};let s=Q7(r6(o),t,i),c=O7(s)?s[n]:void 0,l=c!==void 0,u=Y7(r);if(l&&Wwe(c,r,u))return{kind:`overwritten`};let d=a.charCodeAt(0)===65279,f=d?a.slice(1):a,p=f.includes(`\r
1498
+ `,a=i6(r,t,void 0,{formattingOptions:{...Lwe(r),eol:i}});if(a.length===0)return{text:e,changed:!1};let o=`${n?``:``}${a6(r,a)}`;return{text:o,changed:o!==e}}const zwe={allowTrailingComma:!0,disallowComments:!1};function Bwe(e,t){return e.error===1&&e.offset===0&&t.charCodeAt(0)===65279}function W7(e){let t=[],n=Abe(e,t,zwe);return t.some(t=>!Bwe(t,e))||!n||n.type!==`object`?null:n}function G7(e,t){let n=0;for(let r of e.children??[]){let e=r.children?.[0];e!==void 0&&r6(e)===t&&(n+=1)}return n}function K7(e,t){WQ(e,`${JSON.stringify(t,null,2)}\n`)}function Vwe(e,t){let n=cwe(t);WQ(e,n.endsWith(`
1499
+ `)?n:`${n}\n`)}function Hwe(e,t){let n=(0,on.stringify)(t);WQ(e,n.endsWith(`
1500
+ `)?n:`${n}\n`)}const q7=10*1024*1024;function J7(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>J7(e,t[n]));if(O7(e)&&O7(t)){let n=Object.keys(e);return n.length===Object.keys(t).length?n.every(n=>Object.hasOwn(t,n)&&J7(e[n],t[n])):!1}return!1}const Uwe=[`command`,`args`],Wwe=[`type`,`command`];function Y7(e){return e.type===`local`&&Array.isArray(e.command)?Wwe:Uwe}function Gwe(e,t,n){return O7(e)&&n.every(n=>J7(e[n],t[n]))}function Kwe(e){for(let t of e.split(`
1501
+ `)){let e=t.trimStart();if(!(e.length===0||e.length===t.length))return t.charCodeAt(0)===9?{insertSpaces:!1,tabSize:1}:{insertSpaces:!0,tabSize:t.length-e.length}}return{insertSpaces:!0,tabSize:2}}function X7(e,t,n){return t===void 0?[e,n]:[e,t,n]}function Z7(e,t,n,r){let i={[n]:r};return{[e]:t===void 0?i:{[t]:i}}}function Q7(e,t,n){let r=e[t];return n===void 0?r:O7(r)?r[n]:void 0}function qwe(e,t,n,r,i){if(!g(e))return K7(e,Z7(t,i,n,r)),{kind:`written`};let a;try{a=S(e,`utf-8`)}catch(e){return T7(`json config read failed`,e),{kind:`declined`,reason:`unparseable`}}if(a.trim()===``)return K7(e,Z7(t,i,n,r)),{kind:`written`};if(Buffer.byteLength(a,`utf-8`)>q7)return{kind:`declined`,reason:`oversize`};let o=W7(a);if(!o)return{kind:`declined`,reason:`unparseable`};if(G7(o,t)>1)return{kind:`declined`,reason:`duplicate-container`};let s=Q7(r6(o),t,i),c=O7(s)?s[n]:void 0,l=c!==void 0,u=Y7(r);if(l&&Gwe(c,r,u))return{kind:`overwritten`};let d=a.charCodeAt(0)===65279,f=d?a.slice(1):a,p=f.includes(`\r
1502
1502
  `)?`\r
1503
1503
  `:`
1504
- `,m={...Gwe(f),eol:p},h=X7(t,i,n),_=f;if(l&&O7(c))for(let e of u){let t=i6(_,[...h,e],r[e],{formattingOptions:m});_=a6(_,t)}else{let e=i6(_,h,r,{formattingOptions:m});_=a6(_,e)}let v=`${d?``:``}${_}`;return v!==a&&WQ(e,v,{mode:U7(e)}),{kind:l?`overwritten`:`written`}}function qwe(e,t,n,r,i){let a=``;if(g(t))try{a=S(t,`utf-8`)}catch(e){return T7(`toml config read failed`,e),{kind:`declined`,reason:`unparseable`}}let o=a.trim()===``;if(e.backend===`fallback`)return o?(Bwe(t,{[n]:{[r]:i}}),{kind:`written`}):{kind:`declined`,reason:`no-native-writer`};let s=a.charCodeAt(0)===65279,c=s?a.slice(1):a,l=H7(c),u=o||c.endsWith(`
1504
+ `,m={...Kwe(f),eol:p},h=X7(t,i,n),_=f;if(l&&O7(c))for(let e of u){let t=i6(_,[...h,e],r[e],{formattingOptions:m});_=a6(_,t)}else{let e=i6(_,h,r,{formattingOptions:m});_=a6(_,e)}let v=`${d?``:``}${_}`;return v!==a&&WQ(e,v,{mode:U7(e)}),{kind:l?`overwritten`:`written`}}function Jwe(e,t,n,r,i){let a=``;if(g(t))try{a=S(t,`utf-8`)}catch(e){return T7(`toml config read failed`,e),{kind:`declined`,reason:`unparseable`}}let o=a.trim()===``;if(e.backend===`fallback`)return o?(Vwe(t,{[n]:{[r]:i}}),{kind:`written`}):{kind:`declined`,reason:`no-native-writer`};let s=a.charCodeAt(0)===65279,c=s?a.slice(1):a,l=H7(c),u=o||c.endsWith(`
1505
1505
  `),d;try{d=e.upsertEntry(c,r,i)}catch(e){return T7(`upsertEntry failed`,e),{kind:`declined`,reason:`unparseable`}}let f=d.text;u?f.endsWith(`
1506
1506
  `)||(f=`${f}\n`):f=f.replace(/\n+$/,``),l&&(f=f.replace(/\r\n/g,`
1507
1507
  `).replace(/\n/g,`\r
1508
- `));let p=`${s?``:``}${f}`;return p!==a&&WQ(t,p,{mode:U7(t)}),{kind:d.existed?`overwritten`:`written`}}function Jwe(e,t,n,r){let i=``;if(g(e))try{i=S(e,`utf-8`)}catch(e){return T7(`yaml config read failed`,e),{kind:`declined`,reason:`unparseable`}}if(i.trim()===``)return Vwe(e,{[t]:{[n]:r}}),{kind:`written`};if(Buffer.byteLength(i,`utf-8`)>q7)return{kind:`declined`,reason:`oversize`};let a=i.charCodeAt(0)===65279,o=a?i.slice(1):i,s=(0,on.parseDocument)(o);if(s.errors.length>0)return{kind:`declined`,reason:`unparseable`};let c=[t,n],l=s.hasIn(c);s.hasIn([t])&&!(0,on.isCollection)(s.getIn([t],!0))&&s.deleteIn([t]);let u=s.getIn(c,!0);if(l&&(0,on.isCollection)(u))for(let e of Y7(r))s.setIn([...c,e],s.createNode(r[e]));else s.setIn(c,s.createNode(r));let d=s.toString(),f=H7(o);o.endsWith(`
1508
+ `));let p=`${s?``:``}${f}`;return p!==a&&WQ(t,p,{mode:U7(t)}),{kind:d.existed?`overwritten`:`written`}}function Ywe(e,t,n,r){let i=``;if(g(e))try{i=S(e,`utf-8`)}catch(e){return T7(`yaml config read failed`,e),{kind:`declined`,reason:`unparseable`}}if(i.trim()===``)return Hwe(e,{[t]:{[n]:r}}),{kind:`written`};if(Buffer.byteLength(i,`utf-8`)>q7)return{kind:`declined`,reason:`oversize`};let a=i.charCodeAt(0)===65279,o=a?i.slice(1):i,s=(0,on.parseDocument)(o);if(s.errors.length>0)return{kind:`declined`,reason:`unparseable`};let c=[t,n],l=s.hasIn(c);s.hasIn([t])&&!(0,on.isCollection)(s.getIn([t],!0))&&s.deleteIn([t]);let u=s.getIn(c,!0);if(l&&(0,on.isCollection)(u))for(let e of Y7(r))s.setIn([...c,e],s.createNode(r[e]));else s.setIn(c,s.createNode(r));let d=s.toString(),f=H7(o);o.endsWith(`
1509
1509
  `)?d.endsWith(`
1510
1510
  `)||(d=`${d}\n`):d=d.replace(/\n+$/,``),f&&(d=d.replace(/\r\n/g,`
1511
1511
  `).replace(/\n/g,`\r
1512
- `));let p=`${a?``:``}${d}`;return p!==i&&WQ(e,p,{mode:U7(e)}),{kind:l?`overwritten`:`written`}}const Ywe=`open-knowledge-ui`;function $7(e,t,n){try{return g(e.detectPath?.(t,n)??pe(e.configPath(t,n)))}catch{return!1}}function Xwe(e,t,n){try{let r=ve(pe(e.configPath(t,n))),i=ve(e.detectPath?.(t,n)??r);return i===r||r.startsWith(i+ye)}catch{return!1}}function e9(e,t,n,r,i){let a=e.serverName(t),o;try{o=i??e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:a,error:t instanceof Error?t.message:String(t)}}let s=!n.skipAvailabilityCheck||e.offerOnlyWhenDetected===!0||Xwe(e,t,r);if(!i&&s&&!$7(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{b7(o,t)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),configScope:`project`}}if(e.format===`file`)return Qwe(e,o,a,n,{isProjectScope:i!==void 0});let c;try{c=e.buildEntry(t,n)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}try{v(pe(o),{recursive:!0})}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}let l={action:`written`},u;try{KQ(`${o}.lock`,()=>{let t=Cwe(o).writePath;if(v(pe(t),{recursive:!0}),e.format===`toml`){let n=qwe(j7(),t,e.topLevelKey,a,c);l.action=n.kind,n.kind===`declined`&&(l.declineReason=n.reason);return}if(e.format===`yaml`){let n=Jwe(t,e.topLevelKey,a,c);l.action=n.kind,n.kind===`declined`&&(l.declineReason=n.reason);return}let n=Kwe(t,e.topLevelKey,a,c,e.serverMapSubKey);l.action=n.kind,n.kind===`declined`&&(l.declineReason=n.reason)},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){u=e instanceof Error?e:Error(String(e))}return u?{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:u.message,...i===void 0?{}:{configScope:`project`}}:l.action===`declined`?{editorId:e.id,label:e.label,action:`declined`,configPath:o,serverName:a,declineReason:l.declineReason,...i===void 0?{}:{configScope:`project`}}:{editorId:e.id,label:e.label,action:l.action,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}}}const Zwe={pi:y7};function Qwe(e,t,n,r,i){let a=i.isProjectScope?{configScope:`project`}:{},o=r=>({editorId:e.id,label:e.label,action:`failed`,configPath:t,serverName:n,error:r instanceof Error?r.message:String(r),...a}),s=Zwe[e.id];if(!s)return o(Error(`No managed-file builder registered for editor "${e.id}" (format: 'file' targets need a MANAGED_FILE_BUILDERS entry).`));let c;try{c=s(r)}catch(e){return o(e)}try{v(pe(t),{recursive:!0})}catch(e){return o(e)}let l={action:`written`};try{KQ(`${t}.lock`,()=>{let e=null;try{e=S(t,`utf-8`)}catch{e=null}if(e===c){l.action=`overwritten`;return}WQ(t,c,e===null?void 0:{mode:U7(t)}),l.action=e===null?`written`:`overwritten`},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){return o(e)}return{editorId:e.id,label:e.label,action:l.action,configPath:t,serverName:n,...a}}async function $we(e){let t=kCe(e.editors).filter(e=>e.scope===`global`),n={mode:`published`,skipAvailabilityCheck:!0};return t.map(t=>e9(t,``,n,e.home))}function t9(e,t,n,r){let i=r9(e,t,n,r);return i.kind===`present`?i.entry:null}function n9(e,t,n,r){let i=Q7(e,t,r);if(!O7(i))return{kind:`no-entry`};let a=i[n];return O7(a)?{kind:`present`,entry:a}:{kind:`no-entry`}}function r9(e,t,n,r){let i;try{i=r??e.configPath(t,n)}catch{return{kind:`absent`}}if(!g(i))return{kind:`absent`};try{if(O(i).size>q7)return{kind:`decline`,reason:`oversize`}}catch{return{kind:`decline`,reason:`unparseable`}}let a;try{a=S(i,`utf-8`)}catch{return{kind:`decline`,reason:`unparseable`}}if(a.trim()===``)return{kind:`absent`};if(e.format===`file`)return{kind:`present`,entry:dwe(a)};let o=e.serverName(t);if(e.format===`toml`){let t;try{t=j7().parseToObject(a)}catch{return{kind:`decline`,reason:`unparseable`}}return n9(t,e.topLevelKey,o,e.serverMapSubKey)}if(e.format===`yaml`){let t=(0,on.parseDocument)(a.charCodeAt(0)===65279?a.slice(1):a);return t.errors.length>0?{kind:`decline`,reason:`unparseable`}:n9(t.toJS()??{},e.topLevelKey,o,e.serverMapSubKey)}let s=W7(a);return s?G7(s,e.topLevelKey)>1?{kind:`decline`,reason:`duplicate-container`}:n9(r6(s),e.topLevelKey,o,e.serverMapSubKey):{kind:`decline`,reason:`unparseable`}}function eTe(e,t){let n=[];for(let r of M5)$7(e7[r],e,t)&&n.push(r);return n}function tTe(e){return e===`opencode`?vCe:_Ce}function nTe(e,t,n){let r=e7[e],i=tTe(e),a=[],o=r.projectConfigPath?.(t);o!==void 0&&a.push({scope:`project`,configPath:o});try{a.push({scope:`user`,configPath:r.configPath(t,n)})}catch{}for(let o of a){let a=t9(r,t,n,o.configPath);if(a!==null&&i(a))return{editorId:e,scope:o.scope,configPath:o.configPath}}return null}function i9(e,t){if(e.outcome===`not-present`)return`not-present (no DiagnosticReports directory)`;if(e.outcome===`unreadable-directory`)return`unreadable (${e.directoryErrorCode??`unknown`} reading DiagnosticReports)`;let n=[`${e.windowDays}d`,`${e.foreignIgnored} other-process report(s) ignored`,`${e.unparseable} unparseable`];e.droppedOverCap>0&&n.push(`${e.droppedOverCap} older dropped over cap`);let r=e.files.length-t;return r>0&&n.push(`${r} vanished before staging`),e.outcome===`none-in-window`?`none found in window (${n.join(`; `)})`:`${t} collected (${n.join(`; `)})`}function rTe(e){return e.replace(/\\+\/?/g,e=>{if(!e.endsWith(`/`))return e;let t=e.length-1;return`\\`.repeat(t-t%2)+`/`})}const iTe=RegExp(`("(?:${[`crashReporterKey`,`bootSessionUUID`].join(`|`)})"\\s*:\\s*)"[^"]*"`,`g`);function aTe(e){return e.replace(iTe,`$1"[REDACTED-DEVICE-ID]"`)}function a9(e){return aTe(rTe(e))}const oTe=/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(\.\d+)? ([+-]\d{2})(\d{2})$/;function sTe(e){if(typeof e!=`string`)return null;let t=oTe.exec(e.trim());if(t===null)return null;let[,n,r,i=``,a,o]=t,s=Date.parse(`${n}T${r}${i}${a}:${o}`);return Number.isNaN(s)?null:s}function cTe(e){try{let t=S(e,`utf-8`),n=t.indexOf(`
1513
- `),r=n===-1?t:t.slice(0,n),i=JSON.parse(r);if(typeof i!=`object`||!i)return{kind:`unreadable`};let{name:a,app_name:o,timestamp:s}=i,c=typeof a==`string`?a:typeof o==`string`?o:null;return c===null?{kind:`unreadable`}:{kind:`named`,name:c,timestampMs:sTe(s)}}catch{return{kind:`unreadable`}}}function lTe(e){return e===`OpenKnowledge`||e.startsWith(`OpenKnowledge `)}function uTe(e,t){let n={files:[],foreignIgnored:0,unparseable:0,droppedOverCap:0,windowDays:7},r;try{r=C(e,{withFileTypes:!0})}catch(e){let t=e.code;return t===`ENOENT`?{...n,outcome:`not-present`}:{...n,outcome:`unreadable-directory`,directoryErrorCode:t??`unknown`}}let i=t.getTime()-6048e5,a=[],o=0,s=0;for(let t of r){if(!t.isFile()||!t.name.endsWith(`.ips`))continue;let n=N(e,t.name),r;try{r=O(n).mtimeMs}catch{continue}if(r<i)continue;let c=cTe(n),l=c.kind===`named`&&c.timestampMs!==null?c.timestampMs:r;if(c.kind===`unreadable`){s+=1;continue}if(!lTe(c.name)){o+=1;continue}a.push({path:n,atMs:l})}a.sort((e,t)=>t.atMs-e.atMs);let c=a.slice(0,25),l={foreignIgnored:o,unparseable:s,droppedOverCap:a.length-c.length,windowDays:7};return c.length===0?{...l,files:[],outcome:`none-in-window`}:{...l,files:c.map(e=>e.path),outcome:`collected`}}function o9(){return N(oe(),`.ok`,`bug-reports`)}function dTe(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=o9(),r=`${t}-bugreport`,i=N(n,`${r}.zip`);for(let e=2;g(i);e+=1)i=N(n,`${r}-${e}.zip`);return i}function s9(e,t){let n=N(e,`.ok`,`config.yml`);if(g(n))try{let e=S(n,`utf8`).match(/^\s*name:\s*['"]?(.+?)['"]?\s*$/m);if(e?.[1])return e[1]}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml for project slug; using path-hash fallback`)}return g(N(e,`.ok`))?Ae(`sha256`).update(ve(e)).digest(`hex`).slice(0,12):null}function fTe(){let e={timestamp:new Date().toISOString(),platform:k(),osType:A(),osRelease:ce(),hostname:`[redacted]`,uptime:j(),freeMem:ae(),totalMem:ue(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=l(`sw_vers -productVersion 2>/dev/null`,l3({encoding:`utf8`})).trim()}catch{}try{let t=N(__dirname,`..`,`..`,`package.json`);g(t)&&(e.okVersion=JSON.parse(S(t,`utf8`)).version)}catch{}return e}const pTe=[{prefix:`cli`,projectTagged:!0},{prefix:`desktop`,projectTagged:!1},{prefix:`mcp`,projectTagged:!1}];function c9(e){let t=fe(e);return pTe.some(e=>e.projectTagged&&t.startsWith(`${e.prefix}.`))}function mTe(e,t){return d9(e,t).files}const hTe=[`ShipIt_stderr.log`,`ShipIt_stdout.log`];function l9(e,t=`com.inkeep.open-knowledge`){let n=N(e,`${t}.ShipIt`);if(!g(n))return[];let r;try{r=C(n)}catch{return[]}return hTe.flatMap(e=>r.map(t=>{if(t===e)return{entry:t,suffix:-1};if(!t.startsWith(`${e}.`))return null;let n=t.slice(e.length+1);return/^\d+$/.test(n)?{entry:t,suffix:Number(n)}:null}).filter(e=>e!==null).sort((e,t)=>e.suffix-t.suffix).slice(0,4).map(e=>N(n,e.entry)))}function u9(e){if(!g(e))return[];try{let t=new Map;for(let n of C(e).filter(e=>e.endsWith(`.yaml`)).sort()){let e=n.endsWith(`.sent.yaml`)?n.slice(0,-10):n.slice(0,-5),r=t.get(e);r===void 0?t.set(e,[n]):r.push(n)}return[...t.values()].slice(-25).flat().map(t=>N(e,t))}catch{return[]}}function d9(e,t){if(!g(t))return{files:[],excludedByProjectSlug:0};let n=C(t).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>N(t,e));if(!e)return{files:n,excludedByProjectSlug:0};let r=n.filter(c9),i=[],a=r.filter(t=>{try{return S(t,`utf8`).includes(`"project":"${e}"`)}catch{return i.push(t),!1}});if(a.length===0)return{files:n,excludedByProjectSlug:0};let o=new Set([...a,...i]);return{files:n.filter(e=>!c9(e)||o.has(e)),excludedByProjectSlug:r.length-o.size}}function gTe(e){let t=N(e,`.ok`,`local`);return g(t)?{files:[`server.lock`,`last-spawn-error.log`,ju].map(e=>N(t,e)).filter(e=>g(e))}:{files:[]}}function _Te(e){let t=N(e,`.ok`,`local`,`logs`);return g(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>N(t,e)).filter(e=>g(e))}:{files:[]}}function vTe(e){let t=0,n=new Map,r=e.replace(/("(?:docName|doc\.name|documentName)"\s*:\s*")((?:[^"\\]|\\.)*)"/g,(e,r,i)=>{t+=1;let a=n.get(i);return a===void 0&&(a=`doc#${Ae(`sha256`).update(i).digest(`hex`).slice(0,12)}`,n.set(i,a)),`${r}${a}"`});for(let[e,i]of[...n].sort(([e],[t])=>t.length-e.length)){if(e.length===0||!r.includes(e))continue;let n=r.split(e);t+=n.length-1,r=n.join(i)}return{text:r,count:t}}function f9(e){let t=e.revealDocNames?e.content:vTe(e.content).text;if(e.redact){let{redacted:n,patterns:r,lineCount:i}=Rw(t);e.zipfile.addBuffer(Buffer.from(n,`utf8`),e.name),e.bundleFiles.push(e.name),r.length>0&&e.redactions.push({file:e.name,lineCount:i,patterns:r})}else e.zipfile.addBuffer(Buffer.from(t,`utf8`),e.name),e.bundleFiles.push(e.name)}function p9(e){for(let t of e.files)try{let n=S(t,`utf8`);f9({zipfile:e.zipfile,name:`${e.prefix}/${fe(t)}`,content:t.endsWith(`.ips`)?a9(n):n,redact:e.redact,revealDocNames:e.revealDocNames,bundleFiles:e.bundleFiles,redactions:e.redactions})}catch(n){e.logger?.warn({file:t,prefix:e.prefix,err:n},`bug-report: skipped unreadable file`)}}async function yTe(t){let{redact:n,outputPath:r,logger:i}=t,a=t.revealDocNames??!1,o=t.userLogsDir??N(oe(),`.ok`,`logs`),s=t.projectDir?s9(t.projectDir,i):null;v(pe(r),{recursive:!0}),i?.info({projectSlug:s},`gathering diagnostic data`);let c=fTe();c.desktop=t.desktop??null,c.language=t.language??null;let{files:l,excludedByProjectSlug:u}=d9(s,o),{files:d}=t.projectDir?gTe(t.projectDir):{files:[]},{files:f}=t.projectDir?_Te(t.projectDir):{files:[]},p=t.shipItLogFiles??[],m=t.diagnosticReports?.files??[];i?.info({logFileCount:l.length,logFilesExcludedByProjectSlug:u,lockFileCount:d.length,localSinkFileCount:f.length,shipItLogFileCount:p.length,diagnosticReportCount:m.length},`files collected`);let g=[],_=[],{ZipFile:y}=await import(`./yazl-BlMyAOcT.mjs`).then(t=>e(t.t(),1)),b=new y;p9({zipfile:b,files:[...l,...p],prefix:`logs`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),p9({zipfile:b,files:d,prefix:`lockdir`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),p9({zipfile:b,files:f,prefix:`local-logs`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),p9({zipfile:b,files:t.bugReportLedgerFiles??[],prefix:us,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),p9({zipfile:b,files:m,prefix:`diagnostic-reports`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i});for(let e of t.extraFiles??[])try{let t=S(e.sourcePath),n=`extra/${e.zipName??fe(e.sourcePath)}`;b.addBuffer(t,n),_.push(n)}catch(t){i?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&f9({zipfile:b,name:`note.txt`,content:t.note,redact:n,revealDocNames:a,bundleFiles:_,redactions:g});let x=new Set(m.map(e=>`diagnostic-reports/${fe(e)}`)),C=_.filter(e=>x.has(e)),w=t.diagnosticReports===void 0?`not-collected (no collection attempted)`:i9(t.diagnosticReports,C.length);b.addBuffer(Buffer.from(`${w}\n`,`utf8`),`state/diagnostic-reports-status.txt`),_.push(`state/diagnostic-reports-status.txt`);let T=JSON.stringify(c,null,2);b.addBuffer(Buffer.from(T,`utf8`),`sysinfo.json`),_.push(`sysinfo.json`);let E={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:s,files:_,redactions:g,sysinfo:c};b.addBuffer(Buffer.from(JSON.stringify(E,null,2),`utf8`),`MANIFEST.json`);let D=g.reduce((e,t)=>e+t.lineCount,0),O=new Set(p.map(e=>`logs/${fe(e)}`)),ee=_.filter(e=>O.has(e)),te=new Set((t.bugReportLedgerFiles??[]).map(e=>`${us}/${fe(e)}`)),ne=_.filter(e=>te.has(e)),re=s?_.filter(e=>e.startsWith(`logs/`)&&!c9(e)&&!O.has(e)):[],ie=C.length>0?[`Crash reports under diagnostic-reports/ are rewritten on the way in,`,`independently of this setting: escaped path separators are normalised`,`so the scrub above can read them, and the identifiers that link this`,`machine's bundles to each other are replaced. Nothing else is changed;`,`they are not byte-identical to the files macOS wrote.`]:[],ae=ie.length>0?[`Redaction was disabled for this bundle; file contents are unmodified,`,`with one exception.`,...ie]:[`Redaction was disabled for this bundle; file contents are unmodified.`],se=[`# Bug Report Bundle`,``,`Generated: ${E.generatedAt}`,`Project: ${s??`(unscoped)`}`,`Discipline version: ${E.disciplineVersion}`,``,`## Contents`,``,..._.map(e=>`- ${e}`),``,`## Privacy`,``,...re.length>0?[`Scope: some collected logs are user-wide rather than project-scoped.`,`These are written once per machine per day and can contain activity`,`from other projects open on this machine, including captured console`,`output:`,...re.map(e=>`- ${e}`),``]:[],...ee.length>0?[`Installer logs: written by the macOS update helper rather than by`,`OpenKnowledge itself, and machine-wide rather than scoped to any one`,`project. They record the install and update history of this app on`,`this machine. Only this app is collected, never other applications`,`that use the same update mechanism:`,...ee.map(e=>`- ${e}`),``]:[],...C.length>0?[`Crash reports: written by macOS itself rather than by OpenKnowledge,`,`and machine-wide rather than scoped to any one project. They record`,`why the operating system ended a process of this app — the signal or`,`exception, the code-signing verdict, and whatever text the process`,`left behind as it died. They also carry machine details the OS puts`,`in every report: the account uid, the Mac model, and the name of the`,`process that launched this app, which on a managed machine can be`,`internal tooling. The identifiers that would link this machine's`,`bundles to each other are replaced before bundling. Only this`,`app's own reports are collected, never another application's, though`,`a report of ours still names the processes it ran alongside:`,...C.map(e=>`- ${e}`),``]:[],...ne.length>0?[`Send history: a small record for each bug report previously generated`,`on this machine — when it was generated, whether sending it`,`succeeded, and why it failed if it did. This is what makes a failed`,`send diagnosable at all. It is machine-wide rather than scoped to`,`this project, so it names the other projects reports were filed`,`from. It carries no document content:`,...ne.map(e=>`- ${e}`),``]:[],...n?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${ece.join(`, `)}`,D>0?`${D} line(s) were scrubbed across ${g.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,...ie,``,`This bundle is safe to attach to a GitHub issue.`]:ae].join(`
1512
+ `));let p=`${a?``:``}${d}`;return p!==i&&WQ(e,p,{mode:U7(e)}),{kind:l?`overwritten`:`written`}}const Xwe=`open-knowledge-ui`;function $7(e,t,n){try{return g(e.detectPath?.(t,n)??pe(e.configPath(t,n)))}catch{return!1}}function Zwe(e,t,n){try{let r=ve(pe(e.configPath(t,n))),i=ve(e.detectPath?.(t,n)??r);return i===r||r.startsWith(i+ye)}catch{return!1}}function e9(e,t,n,r,i){let a=e.serverName(t),o;try{o=i??e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:a,error:t instanceof Error?t.message:String(t)}}let s=!n.skipAvailabilityCheck||e.offerOnlyWhenDetected===!0||Zwe(e,t,r);if(!i&&s&&!$7(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{b7(o,t)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),configScope:`project`}}if(e.format===`file`)return $we(e,o,a,n,{isProjectScope:i!==void 0});let c;try{c=e.buildEntry(t,n)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}try{v(pe(o),{recursive:!0})}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}let l={action:`written`},u;try{KQ(`${o}.lock`,()=>{let t=wwe(o).writePath;if(v(pe(t),{recursive:!0}),e.format===`toml`){let n=Jwe(j7(),t,e.topLevelKey,a,c);l.action=n.kind,n.kind===`declined`&&(l.declineReason=n.reason);return}if(e.format===`yaml`){let n=Ywe(t,e.topLevelKey,a,c);l.action=n.kind,n.kind===`declined`&&(l.declineReason=n.reason);return}let n=qwe(t,e.topLevelKey,a,c,e.serverMapSubKey);l.action=n.kind,n.kind===`declined`&&(l.declineReason=n.reason)},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){u=e instanceof Error?e:Error(String(e))}return u?{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:u.message,...i===void 0?{}:{configScope:`project`}}:l.action===`declined`?{editorId:e.id,label:e.label,action:`declined`,configPath:o,serverName:a,declineReason:l.declineReason,...i===void 0?{}:{configScope:`project`}}:{editorId:e.id,label:e.label,action:l.action,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}}}const Qwe={pi:y7};function $we(e,t,n,r,i){let a=i.isProjectScope?{configScope:`project`}:{},o=r=>({editorId:e.id,label:e.label,action:`failed`,configPath:t,serverName:n,error:r instanceof Error?r.message:String(r),...a}),s=Qwe[e.id];if(!s)return o(Error(`No managed-file builder registered for editor "${e.id}" (format: 'file' targets need a MANAGED_FILE_BUILDERS entry).`));let c;try{c=s(r)}catch(e){return o(e)}try{v(pe(t),{recursive:!0})}catch(e){return o(e)}let l={action:`written`};try{KQ(`${t}.lock`,()=>{let e=null;try{e=S(t,`utf-8`)}catch{e=null}if(e===c){l.action=`overwritten`;return}WQ(t,c,e===null?void 0:{mode:U7(t)}),l.action=e===null?`written`:`overwritten`},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){return o(e)}return{editorId:e.id,label:e.label,action:l.action,configPath:t,serverName:n,...a}}async function eTe(e){let t=ACe(e.editors).filter(e=>e.scope===`global`),n={mode:`published`,skipAvailabilityCheck:!0};return t.map(t=>e9(t,``,n,e.home))}function t9(e,t,n,r){let i=r9(e,t,n,r);return i.kind===`present`?i.entry:null}function n9(e,t,n,r){let i=Q7(e,t,r);if(!O7(i))return{kind:`no-entry`};let a=i[n];return O7(a)?{kind:`present`,entry:a}:{kind:`no-entry`}}function r9(e,t,n,r){let i;try{i=r??e.configPath(t,n)}catch{return{kind:`absent`}}if(!g(i))return{kind:`absent`};try{if(O(i).size>q7)return{kind:`decline`,reason:`oversize`}}catch{return{kind:`decline`,reason:`unparseable`}}let a;try{a=S(i,`utf-8`)}catch{return{kind:`decline`,reason:`unparseable`}}if(a.trim()===``)return{kind:`absent`};if(e.format===`file`)return{kind:`present`,entry:fwe(a)};let o=e.serverName(t);if(e.format===`toml`){let t;try{t=j7().parseToObject(a)}catch{return{kind:`decline`,reason:`unparseable`}}return n9(t,e.topLevelKey,o,e.serverMapSubKey)}if(e.format===`yaml`){let t=(0,on.parseDocument)(a.charCodeAt(0)===65279?a.slice(1):a);return t.errors.length>0?{kind:`decline`,reason:`unparseable`}:n9(t.toJS()??{},e.topLevelKey,o,e.serverMapSubKey)}let s=W7(a);return s?G7(s,e.topLevelKey)>1?{kind:`decline`,reason:`duplicate-container`}:n9(r6(s),e.topLevelKey,o,e.serverMapSubKey):{kind:`decline`,reason:`unparseable`}}function tTe(e,t){let n=[];for(let r of M5)$7(e7[r],e,t)&&n.push(r);return n}function nTe(e){return e===`opencode`?yCe:vCe}function rTe(e,t,n){let r=e7[e],i=nTe(e),a=[],o=r.projectConfigPath?.(t);o!==void 0&&a.push({scope:`project`,configPath:o});try{a.push({scope:`user`,configPath:r.configPath(t,n)})}catch{}for(let o of a){let a=t9(r,t,n,o.configPath);if(a!==null&&i(a))return{editorId:e,scope:o.scope,configPath:o.configPath}}return null}function i9(e,t){if(e.outcome===`not-present`)return`not-present (no DiagnosticReports directory)`;if(e.outcome===`unreadable-directory`)return`unreadable (${e.directoryErrorCode??`unknown`} reading DiagnosticReports)`;let n=[`${e.windowDays}d`,`${e.foreignIgnored} other-process report(s) ignored`,`${e.unparseable} unparseable`];e.droppedOverCap>0&&n.push(`${e.droppedOverCap} older dropped over cap`);let r=e.files.length-t;return r>0&&n.push(`${r} vanished before staging`),e.outcome===`none-in-window`?`none found in window (${n.join(`; `)})`:`${t} collected (${n.join(`; `)})`}function iTe(e){return e.replace(/\\+\/?/g,e=>{if(!e.endsWith(`/`))return e;let t=e.length-1;return`\\`.repeat(t-t%2)+`/`})}const aTe=RegExp(`("(?:${[`crashReporterKey`,`bootSessionUUID`].join(`|`)})"\\s*:\\s*)"[^"]*"`,`g`);function oTe(e){return e.replace(aTe,`$1"[REDACTED-DEVICE-ID]"`)}function a9(e){return oTe(iTe(e))}const sTe=/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(\.\d+)? ([+-]\d{2})(\d{2})$/;function cTe(e){if(typeof e!=`string`)return null;let t=sTe.exec(e.trim());if(t===null)return null;let[,n,r,i=``,a,o]=t,s=Date.parse(`${n}T${r}${i}${a}:${o}`);return Number.isNaN(s)?null:s}function lTe(e){try{let t=S(e,`utf-8`),n=t.indexOf(`
1513
+ `),r=n===-1?t:t.slice(0,n),i=JSON.parse(r);if(typeof i!=`object`||!i)return{kind:`unreadable`};let{name:a,app_name:o,timestamp:s}=i,c=typeof a==`string`?a:typeof o==`string`?o:null;return c===null?{kind:`unreadable`}:{kind:`named`,name:c,timestampMs:cTe(s)}}catch{return{kind:`unreadable`}}}function uTe(e){return e===`OpenKnowledge`||e.startsWith(`OpenKnowledge `)}function dTe(e,t){let n={files:[],foreignIgnored:0,unparseable:0,droppedOverCap:0,windowDays:7},r;try{r=C(e,{withFileTypes:!0})}catch(e){let t=e.code;return t===`ENOENT`?{...n,outcome:`not-present`}:{...n,outcome:`unreadable-directory`,directoryErrorCode:t??`unknown`}}let i=t.getTime()-6048e5,a=[],o=0,s=0;for(let t of r){if(!t.isFile()||!t.name.endsWith(`.ips`))continue;let n=N(e,t.name),r;try{r=O(n).mtimeMs}catch{continue}if(r<i)continue;let c=lTe(n),l=c.kind===`named`&&c.timestampMs!==null?c.timestampMs:r;if(c.kind===`unreadable`){s+=1;continue}if(!uTe(c.name)){o+=1;continue}a.push({path:n,atMs:l})}a.sort((e,t)=>t.atMs-e.atMs);let c=a.slice(0,25),l={foreignIgnored:o,unparseable:s,droppedOverCap:a.length-c.length,windowDays:7};return c.length===0?{...l,files:[],outcome:`none-in-window`}:{...l,files:c.map(e=>e.path),outcome:`collected`}}function o9(){return N(oe(),`.ok`,`bug-reports`)}function fTe(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=o9(),r=`${t}-bugreport`,i=N(n,`${r}.zip`);for(let e=2;g(i);e+=1)i=N(n,`${r}-${e}.zip`);return i}function s9(e,t){let n=N(e,`.ok`,`config.yml`);if(g(n))try{let e=S(n,`utf8`).match(/^\s*name:\s*['"]?(.+?)['"]?\s*$/m);if(e?.[1])return e[1]}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml for project slug; using path-hash fallback`)}return g(N(e,`.ok`))?Ae(`sha256`).update(ve(e)).digest(`hex`).slice(0,12):null}function pTe(){let e={timestamp:new Date().toISOString(),platform:k(),osType:A(),osRelease:ce(),hostname:`[redacted]`,uptime:j(),freeMem:ae(),totalMem:ue(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=l(`sw_vers -productVersion 2>/dev/null`,l3({encoding:`utf8`})).trim()}catch{}try{let t=N(__dirname,`..`,`..`,`package.json`);g(t)&&(e.okVersion=JSON.parse(S(t,`utf8`)).version)}catch{}return e}const mTe=[{prefix:`cli`,projectTagged:!0},{prefix:`desktop`,projectTagged:!1},{prefix:`mcp`,projectTagged:!1}];function c9(e){let t=fe(e);return mTe.some(e=>e.projectTagged&&t.startsWith(`${e.prefix}.`))}function hTe(e,t){return d9(e,t).files}const gTe=[`ShipIt_stderr.log`,`ShipIt_stdout.log`];function l9(e,t=`com.inkeep.open-knowledge`){let n=N(e,`${t}.ShipIt`);if(!g(n))return[];let r;try{r=C(n)}catch{return[]}return gTe.flatMap(e=>r.map(t=>{if(t===e)return{entry:t,suffix:-1};if(!t.startsWith(`${e}.`))return null;let n=t.slice(e.length+1);return/^\d+$/.test(n)?{entry:t,suffix:Number(n)}:null}).filter(e=>e!==null).sort((e,t)=>e.suffix-t.suffix).slice(0,4).map(e=>N(n,e.entry)))}function u9(e){if(!g(e))return[];try{let t=new Map;for(let n of C(e).filter(e=>e.endsWith(`.yaml`)).sort()){let e=n.endsWith(`.sent.yaml`)?n.slice(0,-10):n.slice(0,-5),r=t.get(e);r===void 0?t.set(e,[n]):r.push(n)}return[...t.values()].slice(-25).flat().map(t=>N(e,t))}catch{return[]}}function d9(e,t){if(!g(t))return{files:[],excludedByProjectSlug:0};let n=C(t).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>N(t,e));if(!e)return{files:n,excludedByProjectSlug:0};let r=n.filter(c9),i=[],a=r.filter(t=>{try{return S(t,`utf8`).includes(`"project":"${e}"`)}catch{return i.push(t),!1}});if(a.length===0)return{files:n,excludedByProjectSlug:0};let o=new Set([...a,...i]);return{files:n.filter(e=>!c9(e)||o.has(e)),excludedByProjectSlug:r.length-o.size}}function _Te(e){let t=N(e,`.ok`,`local`);return g(t)?{files:[`server.lock`,`last-spawn-error.log`,ju].map(e=>N(t,e)).filter(e=>g(e))}:{files:[]}}function vTe(e){let t=N(e,`.ok`,`local`,`logs`);return g(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>N(t,e)).filter(e=>g(e))}:{files:[]}}function yTe(e){let t=0,n=new Map,r=e.replace(/("(?:docName|doc\.name|documentName)"\s*:\s*")((?:[^"\\]|\\.)*)"/g,(e,r,i)=>{t+=1;let a=n.get(i);return a===void 0&&(a=`doc#${Ae(`sha256`).update(i).digest(`hex`).slice(0,12)}`,n.set(i,a)),`${r}${a}"`});for(let[e,i]of[...n].sort(([e],[t])=>t.length-e.length)){if(e.length===0||!r.includes(e))continue;let n=r.split(e);t+=n.length-1,r=n.join(i)}return{text:r,count:t}}function f9(e){let t=e.revealDocNames?e.content:yTe(e.content).text;if(e.redact){let{redacted:n,patterns:r,lineCount:i}=Rw(t);e.zipfile.addBuffer(Buffer.from(n,`utf8`),e.name),e.bundleFiles.push(e.name),r.length>0&&e.redactions.push({file:e.name,lineCount:i,patterns:r})}else e.zipfile.addBuffer(Buffer.from(t,`utf8`),e.name),e.bundleFiles.push(e.name)}function p9(e){for(let t of e.files)try{let n=S(t,`utf8`);f9({zipfile:e.zipfile,name:`${e.prefix}/${fe(t)}`,content:t.endsWith(`.ips`)?a9(n):n,redact:e.redact,revealDocNames:e.revealDocNames,bundleFiles:e.bundleFiles,redactions:e.redactions})}catch(n){e.logger?.warn({file:t,prefix:e.prefix,err:n},`bug-report: skipped unreadable file`)}}async function bTe(t){let{redact:n,outputPath:r,logger:i}=t,a=t.revealDocNames??!1,o=t.userLogsDir??N(oe(),`.ok`,`logs`),s=t.projectDir?s9(t.projectDir,i):null;v(pe(r),{recursive:!0}),i?.info({projectSlug:s},`gathering diagnostic data`);let c=pTe();c.desktop=t.desktop??null,c.language=t.language??null;let{files:l,excludedByProjectSlug:u}=d9(s,o),{files:d}=t.projectDir?_Te(t.projectDir):{files:[]},{files:f}=t.projectDir?vTe(t.projectDir):{files:[]},p=t.shipItLogFiles??[],m=t.diagnosticReports?.files??[];i?.info({logFileCount:l.length,logFilesExcludedByProjectSlug:u,lockFileCount:d.length,localSinkFileCount:f.length,shipItLogFileCount:p.length,diagnosticReportCount:m.length},`files collected`);let g=[],_=[],{ZipFile:y}=await import(`./yazl-BlMyAOcT.mjs`).then(t=>e(t.t(),1)),b=new y;p9({zipfile:b,files:[...l,...p],prefix:`logs`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),p9({zipfile:b,files:d,prefix:`lockdir`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),p9({zipfile:b,files:f,prefix:`local-logs`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),p9({zipfile:b,files:t.bugReportLedgerFiles??[],prefix:us,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),p9({zipfile:b,files:m,prefix:`diagnostic-reports`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i});for(let e of t.extraFiles??[])try{let t=S(e.sourcePath),n=`extra/${e.zipName??fe(e.sourcePath)}`;b.addBuffer(t,n),_.push(n)}catch(t){i?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&f9({zipfile:b,name:`note.txt`,content:t.note,redact:n,revealDocNames:a,bundleFiles:_,redactions:g});let x=new Set(m.map(e=>`diagnostic-reports/${fe(e)}`)),C=_.filter(e=>x.has(e)),w=t.diagnosticReports===void 0?`not-collected (no collection attempted)`:i9(t.diagnosticReports,C.length);b.addBuffer(Buffer.from(`${w}\n`,`utf8`),`state/diagnostic-reports-status.txt`),_.push(`state/diagnostic-reports-status.txt`);let T=JSON.stringify(c,null,2);b.addBuffer(Buffer.from(T,`utf8`),`sysinfo.json`),_.push(`sysinfo.json`);let E={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:s,files:_,redactions:g,sysinfo:c};b.addBuffer(Buffer.from(JSON.stringify(E,null,2),`utf8`),`MANIFEST.json`);let D=g.reduce((e,t)=>e+t.lineCount,0),O=new Set(p.map(e=>`logs/${fe(e)}`)),ee=_.filter(e=>O.has(e)),te=new Set((t.bugReportLedgerFiles??[]).map(e=>`${us}/${fe(e)}`)),ne=_.filter(e=>te.has(e)),re=s?_.filter(e=>e.startsWith(`logs/`)&&!c9(e)&&!O.has(e)):[],ie=C.length>0?[`Crash reports under diagnostic-reports/ are rewritten on the way in,`,`independently of this setting: escaped path separators are normalised`,`so the scrub above can read them, and the identifiers that link this`,`machine's bundles to each other are replaced. Nothing else is changed;`,`they are not byte-identical to the files macOS wrote.`]:[],ae=ie.length>0?[`Redaction was disabled for this bundle; file contents are unmodified,`,`with one exception.`,...ie]:[`Redaction was disabled for this bundle; file contents are unmodified.`],se=[`# Bug Report Bundle`,``,`Generated: ${E.generatedAt}`,`Project: ${s??`(unscoped)`}`,`Discipline version: ${E.disciplineVersion}`,``,`## Contents`,``,..._.map(e=>`- ${e}`),``,`## Privacy`,``,...re.length>0?[`Scope: some collected logs are user-wide rather than project-scoped.`,`These are written once per machine per day and can contain activity`,`from other projects open on this machine, including captured console`,`output:`,...re.map(e=>`- ${e}`),``]:[],...ee.length>0?[`Installer logs: written by the macOS update helper rather than by`,`OpenKnowledge itself, and machine-wide rather than scoped to any one`,`project. They record the install and update history of this app on`,`this machine. Only this app is collected, never other applications`,`that use the same update mechanism:`,...ee.map(e=>`- ${e}`),``]:[],...C.length>0?[`Crash reports: written by macOS itself rather than by OpenKnowledge,`,`and machine-wide rather than scoped to any one project. They record`,`why the operating system ended a process of this app — the signal or`,`exception, the code-signing verdict, and whatever text the process`,`left behind as it died. They also carry machine details the OS puts`,`in every report: the account uid, the Mac model, and the name of the`,`process that launched this app, which on a managed machine can be`,`internal tooling. The identifiers that would link this machine's`,`bundles to each other are replaced before bundling. Only this`,`app's own reports are collected, never another application's, though`,`a report of ours still names the processes it ran alongside:`,...C.map(e=>`- ${e}`),``]:[],...ne.length>0?[`Send history: a small record for each bug report previously generated`,`on this machine — when it was generated, whether sending it`,`succeeded, and why it failed if it did. This is what makes a failed`,`send diagnosable at all. It is machine-wide rather than scoped to`,`this project, so it names the other projects reports were filed`,`from. It carries no document content:`,...ne.map(e=>`- ${e}`),``]:[],...n?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${ece.join(`, `)}`,D>0?`${D} line(s) were scrubbed across ${g.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,...ie,``,`This bundle is safe to attach to a GitHub issue.`]:ae].join(`
1514
1514
  `);b.addBuffer(Buffer.from(se,`utf8`),`README.md`),b.end();let k=h(r);return b.outputStream.pipe(k),await new Promise((e,t)=>{k.on(`close`,e),k.on(`error`,t)}),i?.info({bundlePath:r,fileCount:_.length,redactionCount:D},`bundle written`),{zipPath:r,summary:{projectSlug:s,files:_,redactions:g,redactedLineCount:D,generatedAt:E.generatedAt}}}function m9(e,t){let n=ve(e),r=t===void 0?Q5():Q5({home:t,env:{}});return{cwd:n,bridgePath:e7.pi.projectConfigPath?.(n)??``,trustPath:N(r,`trust.json`)}}function h9(e,t,n){let r=r9(e7.pi,e,n,t);if(r.kind===`absent`)return{state:`absent`,text:null};if(r.kind!==`present`)return{state:`unreadable`,text:null};let i=r.entry,a=Array.isArray(i.args)&&typeof i.args[0]==`string`?i.args[0]:null;return B5(i)?{state:`own-current`,text:a}:v7(i)?{state:`own-stale`,text:a}:{state:`foreign`,text:a}}function g9(e,t){let n;try{n=S(e,`utf-8`)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?{state:`untrusted`,entries:{},trailingNewline:!1}:{state:`unreadable`,entries:null,trailingNewline:!1}}if(n.trim()===``)return{state:`untrusted`,entries:{},trailingNewline:!1};let r;try{r=JSON.parse(n)}catch{return{state:`unreadable`,entries:null,trailingNewline:!1}}return O7(r)?{state:r[t]===!0?`trusted`:`untrusted`,entries:r,trailingNewline:n.endsWith(`
1515
- `)}:{state:`unreadable`,entries:null,trailingNewline:!1}}function bTe(e,t){let n=m9(e,t),r=h9(n.cwd,n.bridgePath,t).state,i=g9(n.trustPath,n.cwd).state;return{...n,bridge:r,trust:i,bridgeLoadable:(r===`own-current`||r===`own-stale`)&&i===`trusted`,otherExtensions:_9(n.bridgePath).names}}function _9(e){let t=pe(e),n=fe(e);try{return{names:C(t).filter(e=>e!==n&&e.endsWith(`.ts`)).sort(),verified:!0}}catch(e){let t=e.code;return{names:[],verified:t===`ENOENT`||t===`ENOTDIR`}}}async function xTe(e,t={mode:`published`},n){let r=m9(e,n),i=h9(r.cwd,r.bridgePath,n);if(i.state===`foreign`)return{...r,ok:!1,bridge:`refused-foreign`,trust:`skipped`};if(i.state===`unreadable`)return{...r,ok:!1,bridge:`refused-unreadable`,trust:`skipped`};let a;if(i.state===`absent`)a=`written`;else{let e;try{e=y7(t)}catch{e=void 0}a=e!==void 0&&i.text===e?`unchanged`:`refreshed`}if(a!==`unchanged`){let e=e9(e7.pi,r.cwd,t,n,r.bridgePath);if(e.action!==`written`&&e.action!==`overwritten`)return{...r,ok:!1,bridge:`failed`,trust:`skipped`,error:e.error??`bridge write ${e.action}`}}let o=await STe(r.trustPath,r.cwd);return{...r,ok:o.action===`already-trusted`||o.action===`added`,bridge:a,trust:o.action,...o.error===void 0?{}:{error:o.error}}}async function STe(e,t){try{v(pe(e),{recursive:!0})}catch(e){return{action:`failed`,error:e instanceof Error?e.message:String(e)}}let n={action:`added`};try{await Rhe(`${e}.lock`,async()=>{let r=g9(e,t);if(r.state===`trusted`){n.action=`already-trusted`;return}if(r.entries===null){n.action=`refused-unreadable`;return}let i={...r.entries,[t]:!0},a=JSON.stringify(i,null,2)+(r.trailingNewline?`
1516
- `:``),o=U7(e);WQ(e,a,o===void 0?void 0:{mode:o}),n.action=`added`})}catch(e){return{action:`failed`,error:e instanceof Error?e.message:String(e)}}return n.action===`refused-unreadable`?{action:`refused-unreadable`,error:`trust store is not a readable JSON object`}:{action:n.action}}function CTe(e,t){let n=m9(e,t),r=_9(n.bridgePath);if(!r.verified)return{action:`kept-unverified`,error:`could not read the Pi extensions folder`};if(r.names.length>0)return{action:`kept-shared`};if(!g(n.trustPath))return{action:`not-present`};let i={action:`removed`};try{KQ(`${n.trustPath}.lock`,()=>{let e=g9(n.trustPath,n.cwd);if(e.entries===null){i.action=e.state===`unreadable`?`refused-unreadable`:`not-present`;return}if(!(n.cwd in e.entries)){i.action=`not-present`;return}let t={...e.entries};delete t[n.cwd];let r=JSON.stringify(t,null,2)+(e.trailingNewline?`
1517
- `:``),a=U7(n.trustPath);WQ(n.trustPath,r,a===void 0?void 0:{mode:a}),i.action=`removed`})}catch(e){return{action:`failed`,error:e instanceof Error?e.message:String(e)}}return i.action===`refused-unreadable`?{action:`refused-unreadable`,error:`trust store is not a readable JSON object`}:{action:i.action}}function wTe(e){return B5(e)||U5(e)||v7(e)}const v9=10*1024*1024;function TTe(e,t,n,r){let i=r9(e,t,n,r);if(i.kind===`absent`||i.kind===`no-entry`)return{kind:`not-present`};if(i.kind===`decline`)return{kind:`declined`,reason:i.reason};if(!wTe(i.entry))return{kind:`left-foreign`};let a;try{a=r??e.configPath(t,n)}catch{return{kind:`not-present`}}let o=e.serverName(t);if(e.format===`file`){D(a,{force:!0});let e=CTe(t,n);return{kind:`removed`,trust:e.action,...e.error===void 0?{}:{trustError:e.error}}}return e.format===`toml`?OTe(a,o):e.format===`yaml`?DTe(a,e.topLevelKey,o):ETe(a,e.topLevelKey,e.serverMapSubKey,o)}function ETe(e,t,n,r){let i;try{i=S(e,`utf-8`)}catch{return{kind:`declined`,reason:`unparseable`}}if(Buffer.byteLength(i,`utf-8`)>v9)return{kind:`declined`,reason:`oversize`};let{text:a,changed:o}=Lwe(i,X7(t,n,r));return o?(WQ(e,a,{mode:U7(e)}),{kind:`removed`}):{kind:`not-present`}}function DTe(e,t,n){let r;try{r=S(e,`utf-8`)}catch{return{kind:`declined`,reason:`unparseable`}}if(Buffer.byteLength(r,`utf-8`)>v9)return{kind:`declined`,reason:`oversize`};let i=r.charCodeAt(0)===65279,a=i?r.slice(1):r,o=(0,on.parseDocument)(a);if(o.errors.length>0)return{kind:`declined`,reason:`unparseable`};let s=[t,n];if(!o.hasIn(s))return{kind:`not-present`};o.deleteIn(s);let c=o.toString(),l=H7(a);a.trim()===``||a.endsWith(`
1515
+ `)}:{state:`unreadable`,entries:null,trailingNewline:!1}}function xTe(e,t){let n=m9(e,t),r=h9(n.cwd,n.bridgePath,t).state,i=g9(n.trustPath,n.cwd).state;return{...n,bridge:r,trust:i,bridgeLoadable:(r===`own-current`||r===`own-stale`)&&i===`trusted`,otherExtensions:_9(n.bridgePath).names}}function _9(e){let t=pe(e),n=fe(e);try{return{names:C(t).filter(e=>e!==n&&e.endsWith(`.ts`)).sort(),verified:!0}}catch(e){let t=e.code;return{names:[],verified:t===`ENOENT`||t===`ENOTDIR`}}}async function STe(e,t={mode:`published`},n){let r=m9(e,n),i=h9(r.cwd,r.bridgePath,n);if(i.state===`foreign`)return{...r,ok:!1,bridge:`refused-foreign`,trust:`skipped`};if(i.state===`unreadable`)return{...r,ok:!1,bridge:`refused-unreadable`,trust:`skipped`};let a;if(i.state===`absent`)a=`written`;else{let e;try{e=y7(t)}catch{e=void 0}a=e!==void 0&&i.text===e?`unchanged`:`refreshed`}if(a!==`unchanged`){let e=e9(e7.pi,r.cwd,t,n,r.bridgePath);if(e.action!==`written`&&e.action!==`overwritten`)return{...r,ok:!1,bridge:`failed`,trust:`skipped`,error:e.error??`bridge write ${e.action}`}}let o=await CTe(r.trustPath,r.cwd);return{...r,ok:o.action===`already-trusted`||o.action===`added`,bridge:a,trust:o.action,...o.error===void 0?{}:{error:o.error}}}async function CTe(e,t){try{v(pe(e),{recursive:!0})}catch(e){return{action:`failed`,error:e instanceof Error?e.message:String(e)}}let n={action:`added`};try{await Rhe(`${e}.lock`,async()=>{let r=g9(e,t);if(r.state===`trusted`){n.action=`already-trusted`;return}if(r.entries===null){n.action=`refused-unreadable`;return}let i={...r.entries,[t]:!0},a=JSON.stringify(i,null,2)+(r.trailingNewline?`
1516
+ `:``),o=U7(e);WQ(e,a,o===void 0?void 0:{mode:o}),n.action=`added`})}catch(e){return{action:`failed`,error:e instanceof Error?e.message:String(e)}}return n.action===`refused-unreadable`?{action:`refused-unreadable`,error:`trust store is not a readable JSON object`}:{action:n.action}}function wTe(e,t){let n=m9(e,t),r=_9(n.bridgePath);if(!r.verified)return{action:`kept-unverified`,error:`could not read the Pi extensions folder`};if(r.names.length>0)return{action:`kept-shared`};if(!g(n.trustPath))return{action:`not-present`};let i={action:`removed`};try{KQ(`${n.trustPath}.lock`,()=>{let e=g9(n.trustPath,n.cwd);if(e.entries===null){i.action=e.state===`unreadable`?`refused-unreadable`:`not-present`;return}if(!(n.cwd in e.entries)){i.action=`not-present`;return}let t={...e.entries};delete t[n.cwd];let r=JSON.stringify(t,null,2)+(e.trailingNewline?`
1517
+ `:``),a=U7(n.trustPath);WQ(n.trustPath,r,a===void 0?void 0:{mode:a}),i.action=`removed`})}catch(e){return{action:`failed`,error:e instanceof Error?e.message:String(e)}}return i.action===`refused-unreadable`?{action:`refused-unreadable`,error:`trust store is not a readable JSON object`}:{action:i.action}}function TTe(e){return B5(e)||U5(e)||v7(e)}const v9=10*1024*1024;function ETe(e,t,n,r){let i=r9(e,t,n,r);if(i.kind===`absent`||i.kind===`no-entry`)return{kind:`not-present`};if(i.kind===`decline`)return{kind:`declined`,reason:i.reason};if(!TTe(i.entry))return{kind:`left-foreign`};let a;try{a=r??e.configPath(t,n)}catch{return{kind:`not-present`}}let o=e.serverName(t);if(e.format===`file`){D(a,{force:!0});let e=wTe(t,n);return{kind:`removed`,trust:e.action,...e.error===void 0?{}:{trustError:e.error}}}return e.format===`toml`?kTe(a,o):e.format===`yaml`?OTe(a,e.topLevelKey,o):DTe(a,e.topLevelKey,e.serverMapSubKey,o)}function DTe(e,t,n,r){let i;try{i=S(e,`utf-8`)}catch{return{kind:`declined`,reason:`unparseable`}}if(Buffer.byteLength(i,`utf-8`)>v9)return{kind:`declined`,reason:`oversize`};let{text:a,changed:o}=Rwe(i,X7(t,n,r));return o?(WQ(e,a,{mode:U7(e)}),{kind:`removed`}):{kind:`not-present`}}function OTe(e,t,n){let r;try{r=S(e,`utf-8`)}catch{return{kind:`declined`,reason:`unparseable`}}if(Buffer.byteLength(r,`utf-8`)>v9)return{kind:`declined`,reason:`oversize`};let i=r.charCodeAt(0)===65279,a=i?r.slice(1):r,o=(0,on.parseDocument)(a);if(o.errors.length>0)return{kind:`declined`,reason:`unparseable`};let s=[t,n];if(!o.hasIn(s))return{kind:`not-present`};o.deleteIn(s);let c=o.toString(),l=H7(a);a.trim()===``||a.endsWith(`
1518
1518
  `)?c.endsWith(`
1519
1519
  `)||(c=`${c}\n`):c=c.replace(/\n+$/,``),l&&(c=c.replace(/\r\n/g,`
1520
1520
  `).replace(/\n/g,`\r
1521
- `));let u=`${i?``:``}${c}`;return u!==r&&WQ(e,u,{mode:U7(e)}),{kind:`removed`}}function OTe(e,t){let n=j7();if(n.backend===`fallback`)return{kind:`declined`,reason:`no-native-writer`};let r;try{r=S(e,`utf-8`)}catch{return{kind:`declined`,reason:`unparseable`}}let i=r.charCodeAt(0)===65279,a=i?r.slice(1):r,o=H7(a),s=a.trim()===``||a.endsWith(`
1521
+ `));let u=`${i?``:``}${c}`;return u!==r&&WQ(e,u,{mode:U7(e)}),{kind:`removed`}}function kTe(e,t){let n=j7();if(n.backend===`fallback`)return{kind:`declined`,reason:`no-native-writer`};let r;try{r=S(e,`utf-8`)}catch{return{kind:`declined`,reason:`unparseable`}}let i=r.charCodeAt(0)===65279,a=i?r.slice(1):r,o=H7(a),s=a.trim()===``||a.endsWith(`
1522
1522
  `),c;try{c=n.removeEntry(a,t)}catch{return{kind:`declined`,reason:`unparseable`}}if(!c.existed)return{kind:`not-present`};let l=c.text;s?l.endsWith(`
1523
1523
  `)||(l=`${l}\n`):l=l.replace(/\n+$/,``),o&&(l=l.replace(/\r\n/g,`
1524
1524
  `).replace(/\n/g,`\r
1525
- `));let u=`${i?``:``}${l}`;return u!==r&&WQ(e,u,{mode:U7(e)}),{kind:`removed`}}function kTe(e){return{event:`mcp-config-decline`,scope:e.scope,surface:e.surface,editorId:e.editorId,reason:e.reason}}function ATe(e){let{priorCommand:t,priorArgs:n}=y9(e.priorEntry);return{event:`mcp-config-migrate`,scope:e.scope,surface:e.surface,editorId:e.editorId,configPath:e.configPath,priorCommand:t,priorArgs:n}}function y9(e){return{priorCommand:typeof e.command==`string`?e.command.slice(0,200):null,priorArgs:Array.isArray(e.args)?e.args.slice(0,10).map(e=>typeof e==`string`?e.slice(0,200):e):null}}function b9(e,t,n={}){let r=Ibe(e,t);if(!g(r))return{status:`missing`,lockPath:r};let i;try{i=JSON.parse(S(r,`utf-8`))}catch{return{status:`corrupt`,lockPath:r}}if(!i||typeof i!=`object`||!Oye(i.pid))return{status:`corrupt`,lockPath:r};let a=i;if(!(n.isAlive??s3)(a.pid))return{status:`dead-pid`,lockPath:r,lock:a};if(typeof a.machineId==`string`)return a.machineId===(n.machineId??Fbe())?{status:`alive`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a};let o=n.host??se();return a.hostname===o?{status:`alive`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a}}async function jTe(e,t=void 0){let n=b9(e,`server`);if(n.status!==`alive`&&n.status!==`foreign-host`)return null;let r=Rbe(n.lock);if(r===null)return null;try{let n=await fetch(`${r}/api/server-info`,{signal:AbortSignal.timeout(1500)});if(!n.ok)return t?.warn({lockDir:e,baseUrl:r,outcome:`http-error`,status:n.status},`stop client-probe failed`),null;let i=(await n.json())?.collabClients;return typeof i==`number`&&Number.isFinite(i)?i:(t?.warn({lockDir:e,baseUrl:r,outcome:`no-client-count`,received:typeof i},`stop client-probe failed`),null)}catch(n){return t?.warn({lockDir:e,baseUrl:r,outcome:`unreachable`,err:n},`stop client-probe failed`),null}}function MTe(e,t={}){return{targets:PTe(e,t.isAlive??s3)?[{name:`server`,pid:e.lock.pid,port:e.lock.port}]:[]}}async function NTe(e){let t=e.inspect??(()=>b9(e.lockDir,`server`)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=e.probeClients??jTe,o=e.logger??void 0,s=MTe(t(),{isAlive:e.isAlive});if(s.targets.length===0)return r(`No running open-knowledge processes.`),o?.info({lockDir:e.lockDir,targets:0},`stop found nothing to signal`),{stopped:[],failed:[],hadTargets:!1};if(e.force!==!0){let t=await a(e.lockDir,o);if(t!==null&&t>0)return i(`Not stopping: ${t} collaboration client${t===1?``:`s`} (editor window${t===1?``:`s`} or agents) still connected to the server at ${e.lockDir}. Close them, or re-run with --force to terminate anyway.`),o?.warn({lockDir:e.lockDir,clients:t,pids:s.targets.map(e=>e.pid)},`stop declined: live collaboration clients`),{stopped:[],failed:[],hadTargets:!0,declined:{clients:t}}}let c=[],l=[];for(let e of s.targets)try{n(e.pid,`SIGTERM`),c.push(e)}catch(t){l.push({target:e,error:t instanceof Error?t.message:String(t)})}return c.length>0&&r(`Stopped: ${c.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),o?.info({lockDir:e.lockDir,signalled:c.map(e=>({name:e.name,pid:e.pid,port:e.port})),failed:l.map(({target:e,error:t})=>({pid:e.pid,error:t})),forced:e.force===!0},`stop signalled processes`),l.length>0&&i(`Failed to stop: ${l.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:c,failed:l,hadTargets:!0}}function PTe(e,t){return e.status===`alive`?!0:e.status===`foreign-host`?t(e.lock.pid):!1}function x9(e){if(!g(e))return{value:null,path:e,source:null,doc:null};let t;try{t=S(e,`utf-8`)}catch(t){let n=t instanceof Error?t.message:String(t);return console.warn(`[config] Failed to read ${e}: ${n}`),{value:null,path:e,source:null,doc:null,diagnostic:{code:`UNREADABLE`,detail:`${e}: ${n}`}}}let n=(0,on.parseDocument)(t);if(n.errors.length>0){let r=n.errors.map(e=>e.message).join(`; `);return console.warn(`[config] Failed to parse ${e}: ${r}`),{value:null,path:e,source:t,doc:null,diagnostic:{code:`YAML_PARSE`,detail:`${e}: ${r}`}}}let r=n.toJSON();return O7(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}function FTe(e,t){return e.map(e=>{let n=e.path.map(e=>typeof e==`symbol`?String(e):e),r={path:n,message:e.message,issueCode:e.code};if(t.doc!==null&&t.source!==null){let e=Il({file:t.path,source:t.source,doc:t.doc,path:n});if(e!==void 0)return{...r,source:e}}return r})}function ITe(e){let t=e??process.cwd(),n=[],r=[],i=[],a=[],o=JQ(`user`,t),s=UQ({absPath:o});r.push(...s.diagnostics),!s.valid&&s.sidelinedTo!==void 0&&i.push({from:o,to:s.sidelinedTo}),s.valid&&s.source!==void 0&&n.push(o);let c=(e,t=!1)=>{let i=x9(e);if(i.diagnostic!==void 0&&r.push(i.diagnostic),i.value===null)return{};let o=cu({value:i.value,file:i.path,source:i.source,doc:i.doc});r.push(...o),n.push(e);let s=o.length>0?uu(i.value):i.value;return t&&a.push(...Rl({value:s,file:i.path,source:i.source,doc:i.doc})),s},l=ve(t,`.ok`,`config.yml`),u=c(l,!0),d=c(JQ(`project-local`,t)),f=eu(s.value,u,d),p=pCe.safeParse(f);if(!p.success){let e=x9(l),t={code:`SCHEMA_INVALID`,issues:FTe(p.error.issues,e)};throw Error($l(t))}return{config:p.data,sources:n,diagnostics:r,sidelined:i,ignoredCommittedKeys:a}}function S9(e){return e.replace(/:\d+$/,``)}function C9(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:S9(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:S9(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:S9(e[1]),owner:e[2],name:e[3]}}{let e=/^(?:[\w.\-~%]+@)?([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e?.[1].includes(`.`)||e&&t.startsWith(`git@`))return{protocol:`ssh`,hostname:e[1],owner:e[2],name:e[3]}}{let e=/^git:([\w.-]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:e[1],owner:e[2],name:e[3]}}if(!t.includes(`://`)&&!t.includes(`@`)&&!t.startsWith(`/`)){let e=/^([\w.-]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e)return{protocol:`https`,hostname:`github.com`,owner:e[1],name:e[2]}}return null}function w9(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=ku(t.hostname);if(n===null)return null;let r=t.pathname.split(`/`).filter(e=>e.length>0);if(r.length<5||r[2]!==`blob`)return null;let i,a,o,s;try{i=decodeURIComponent(r[0]),a=decodeURIComponent(r[1]),o=decodeURIComponent(r[3]),s=r.slice(4).map(e=>decodeURIComponent(e))}catch{return null}return!i||!a||!o||s.length===0||s.some(e=>e.length===0)?null:{host:n,owner:i,repo:a,branch:o,path:s.join(`/`)}}function T9(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=ku(t.hostname);if(n===null)return null;let r=t.pathname.split(`/`);if(r.length<5||r[0]!==``||r[3]!==`tree`)return null;let i=r.slice(5);i.length===1&&i[0]===``&&i.pop();let a,o,s,c;try{a=decodeURIComponent(r[1]),o=decodeURIComponent(r[2]),s=decodeURIComponent(r[4]),c=i.map(e=>decodeURIComponent(e))}catch{return null}return!a||!o||!s||c.some(e=>e.length===0)?null:{host:n,owner:a,repo:o,branch:s,path:c.join(`/`)}}function LTe(e){let t=w9(e);if(t)return{kind:`doc`,...t};let n=T9(e);return n?{kind:`folder`,...n}:null}async function RTe(e,t){let n,r;try{n=await Te(ve(e)),r=await Te(ve(pe(e)))}catch{return{kind:`not-git`}}if(!E9(n,r))return{kind:`symlink-escape`};let i=N(n,`.git`),a;try{a=O(i)}catch{return{kind:`not-git`}}if(a.isDirectory()){let e;try{e=await Te(i)}catch{return{kind:`not-git`}}if(!E9(e,n))return{kind:`symlink-escape`}}else if(!a.isFile())return{kind:`not-git`};let o=PX(n);if(o.kind!==`repository`)return{kind:`not-git`};let s=o.repository.readRemoteUrl(`origin`);if(s.kind===`unreadable`)return{kind:`not-git`};if(s.kind===`absent`)return s.reason===`config-missing`?{kind:`not-git`}:{kind:`no-origin`};let c=s.url,l=C9(c);if(l===null)return{kind:`non-github`};let u=ku(l.hostname);if(u===null)return{kind:`non-github`};let d=u===t.host.toLowerCase(),f=l.owner.toLowerCase()===t.owner.toLowerCase(),p=l.name.toLowerCase()===t.repo.toLowerCase();return!d&&f&&p?{kind:`wrong-host`,actualHost:u}:!d||!f||!p?{kind:`wrong-repo`,actualOwner:l.owner,actualRepo:l.name}:{kind:`ok`,gitRemoteUrl:`https://${u}/${l.owner}/${l.name}.git`}}function E9(e,t){if(e===t)return!0;let n=_e(t,e);return n.length>0&&!n.startsWith(`..`)&&!M(n)}const zTe=`# >>> open-knowledge cli >>>`,BTe=`# <<< open-knowledge cli <<<`,VTe=/^# >>> open-knowledge cli >>>\n[\s\S]*?^# <<< open-knowledge cli <<<\n?/m;function HTe(e){return N(e,`Library`,`Application Support`,`OpenKnowledge`,`path-install.json`)}[...f3.map(e=>d3[e])];function UTe(e){if(!M(e))throw Error(`skill cleanup requires an absolute home directory; got ${JSON.stringify(e)}`);let t=ve(e);if(t===ye||pe(t)===t)throw Error(`skill cleanup refuses to operate on the filesystem root (${t})`);return t}function D9(e){let t=UTe(e),n=[];for(let e of f3){let r=d3[e];n.push({path:N(t,`.agents`,`skills`,r),bundleId:e,scope:`central`});for(let i of Tu)n.push({path:N(t,i.skillsRoot,r),bundleId:e,scope:`host`,hostDir:i.hostDir})}return n}function WTe(e,t){let n=[];for(let r of D9(e))if(r.bundleId===t)try{D(r.path,{recursive:!0,force:!0})}catch(e){n.push(e instanceof Error?e:Error(String(e)))}if(n.length>0)throw AggregateError(n,`Failed to remove ${n.length} path(s) for ${t}`)}const GTe=[{id:`mcp-config`,write(e,t,n){let r=e.projectConfigPath?.(t);if(!r)return{integration:`mcp-config`,editorId:e.id,action:`skipped-unsupported`};try{let i=e9(e,t,n,void 0,r);return i.action===`written`||i.action===`overwritten`?{integration:`mcp-config`,editorId:e.id,action:i.action,path:i.configPath}:i.action===`failed`?{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:i.error??`unknown failure`}:i.action===`declined`?{integration:`mcp-config`,editorId:e.id,action:`declined`,path:i.configPath,...i.declineReason===void 0?{}:{reason:i.declineReason}}:{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:`unexpected project-scope action: ${i.action}`}}catch(t){return{integration:`mcp-config`,editorId:e.id,action:`failed`,path:r,error:t instanceof Error?t.message:String(t)}}}},{id:`project-skill`,write(e,t,n){try{let r=C7(e,t,{home:n.home});return{integration:`project-skill`,editorId:e.id,action:r.action,...r.path?{path:r.path}:{},...r.error?{error:r.error}:{}}}catch(t){return{integration:`project-skill`,editorId:e.id,action:`failed`,error:t instanceof Error?t.message:String(t)}}}}];function KTe(e,t,n={},r=GTe){let i=[];for(let a of t){let t=e7[a];for(let a of r)i.push(a.write(t,e,n))}return i}function qTe(e,t,n={}){return{integrations:KTe(e,t,n)}}function JTe(e){return UQ({absPath:JQ(`user`,e,e),sideline:!1,warn:()=>{}}).value.appearance?.language??`system`}function O9({home:e=oe(),env:t=process.env}={}){let n=JTe(e),{override:r,preferenceList:i}=Uhe(t),{locale:a,source:o}=Jse({override:r,storedPreference:n,supportedLocales:Ns,preferenceList:i,autoDetectableLocales:yre});return{preference:n,locale:a,source:o,systemLanguages:i}}function k9(e,t){return t.length===0||!e.includes(t)?e:e.split(t).join(`<CONTENT_DIR>`)}function YTe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function A9(e,t){if(typeof e==`string`)return k9(e,t.contentDir);if(Array.isArray(e))return e.map(e=>A9(e,t));if(!YTe(e))return e;let n={};for(let[r,i]of Object.entries(e))n[r]=A9(i,t);return n}function j9(e,t){let n=S(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
1525
+ `));let u=`${i?``:``}${l}`;return u!==r&&WQ(e,u,{mode:U7(e)}),{kind:`removed`}}function ATe(e){return{event:`mcp-config-decline`,scope:e.scope,surface:e.surface,editorId:e.editorId,reason:e.reason}}function jTe(e){let{priorCommand:t,priorArgs:n}=y9(e.priorEntry);return{event:`mcp-config-migrate`,scope:e.scope,surface:e.surface,editorId:e.editorId,configPath:e.configPath,priorCommand:t,priorArgs:n}}function y9(e){return{priorCommand:typeof e.command==`string`?e.command.slice(0,200):null,priorArgs:Array.isArray(e.args)?e.args.slice(0,10).map(e=>typeof e==`string`?e.slice(0,200):e):null}}function b9(e,t,n={}){let r=Ibe(e,t);if(!g(r))return{status:`missing`,lockPath:r};let i;try{i=JSON.parse(S(r,`utf-8`))}catch{return{status:`corrupt`,lockPath:r}}if(!i||typeof i!=`object`||!Oye(i.pid))return{status:`corrupt`,lockPath:r};let a=i;if(!(n.isAlive??s3)(a.pid))return{status:`dead-pid`,lockPath:r,lock:a};if(typeof a.machineId==`string`)return a.machineId===(n.machineId??Fbe())?{status:`alive`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a};let o=n.host??se();return a.hostname===o?{status:`alive`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a}}async function MTe(e,t=void 0){let n=b9(e,`server`);if(n.status!==`alive`&&n.status!==`foreign-host`)return null;let r=Rbe(n.lock);if(r===null)return null;try{let n=await fetch(`${r}/api/server-info`,{signal:AbortSignal.timeout(1500)});if(!n.ok)return t?.warn({lockDir:e,baseUrl:r,outcome:`http-error`,status:n.status},`stop client-probe failed`),null;let i=(await n.json())?.collabClients;return typeof i==`number`&&Number.isFinite(i)?i:(t?.warn({lockDir:e,baseUrl:r,outcome:`no-client-count`,received:typeof i},`stop client-probe failed`),null)}catch(n){return t?.warn({lockDir:e,baseUrl:r,outcome:`unreachable`,err:n},`stop client-probe failed`),null}}function NTe(e,t={}){return{targets:FTe(e,t.isAlive??s3)?[{name:`server`,pid:e.lock.pid,port:e.lock.port}]:[]}}async function PTe(e){let t=e.inspect??(()=>b9(e.lockDir,`server`)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=e.probeClients??MTe,o=e.logger??void 0,s=NTe(t(),{isAlive:e.isAlive});if(s.targets.length===0)return r(`No running open-knowledge processes.`),o?.info({lockDir:e.lockDir,targets:0},`stop found nothing to signal`),{stopped:[],failed:[],hadTargets:!1};if(e.force!==!0){let t=await a(e.lockDir,o);if(t!==null&&t>0)return i(`Not stopping: ${t} collaboration client${t===1?``:`s`} (editor window${t===1?``:`s`} or agents) still connected to the server at ${e.lockDir}. Close them, or re-run with --force to terminate anyway.`),o?.warn({lockDir:e.lockDir,clients:t,pids:s.targets.map(e=>e.pid)},`stop declined: live collaboration clients`),{stopped:[],failed:[],hadTargets:!0,declined:{clients:t}}}let c=[],l=[];for(let e of s.targets)try{n(e.pid,`SIGTERM`),c.push(e)}catch(t){l.push({target:e,error:t instanceof Error?t.message:String(t)})}return c.length>0&&r(`Stopped: ${c.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),o?.info({lockDir:e.lockDir,signalled:c.map(e=>({name:e.name,pid:e.pid,port:e.port})),failed:l.map(({target:e,error:t})=>({pid:e.pid,error:t})),forced:e.force===!0},`stop signalled processes`),l.length>0&&i(`Failed to stop: ${l.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:c,failed:l,hadTargets:!0}}function FTe(e,t){return e.status===`alive`?!0:e.status===`foreign-host`?t(e.lock.pid):!1}function x9(e){if(!g(e))return{value:null,path:e,source:null,doc:null};let t;try{t=S(e,`utf-8`)}catch(t){let n=t instanceof Error?t.message:String(t);return console.warn(`[config] Failed to read ${e}: ${n}`),{value:null,path:e,source:null,doc:null,diagnostic:{code:`UNREADABLE`,detail:`${e}: ${n}`}}}let n=(0,on.parseDocument)(t);if(n.errors.length>0){let r=n.errors.map(e=>e.message).join(`; `);return console.warn(`[config] Failed to parse ${e}: ${r}`),{value:null,path:e,source:t,doc:null,diagnostic:{code:`YAML_PARSE`,detail:`${e}: ${r}`}}}let r=n.toJSON();return O7(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}function ITe(e,t){return e.map(e=>{let n=e.path.map(e=>typeof e==`symbol`?String(e):e),r={path:n,message:e.message,issueCode:e.code};if(t.doc!==null&&t.source!==null){let e=Il({file:t.path,source:t.source,doc:t.doc,path:n});if(e!==void 0)return{...r,source:e}}return r})}function LTe(e){let t=e??process.cwd(),n=[],r=[],i=[],a=[],o=JQ(`user`,t),s=UQ({absPath:o});r.push(...s.diagnostics),!s.valid&&s.sidelinedTo!==void 0&&i.push({from:o,to:s.sidelinedTo}),s.valid&&s.source!==void 0&&n.push(o);let c=(e,t=!1)=>{let i=x9(e);if(i.diagnostic!==void 0&&r.push(i.diagnostic),i.value===null)return{};let o=cu({value:i.value,file:i.path,source:i.source,doc:i.doc});r.push(...o),n.push(e);let s=o.length>0?uu(i.value):i.value;return t&&a.push(...Rl({value:s,file:i.path,source:i.source,doc:i.doc})),s},l=ve(t,`.ok`,`config.yml`),u=c(l,!0),d=c(JQ(`project-local`,t)),f=eu(s.value,u,d),p=mCe.safeParse(f);if(!p.success){let e=x9(l),t={code:`SCHEMA_INVALID`,issues:ITe(p.error.issues,e)};throw Error($l(t))}return{config:p.data,sources:n,diagnostics:r,sidelined:i,ignoredCommittedKeys:a}}function S9(e){return e.replace(/:\d+$/,``)}function C9(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:S9(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:S9(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:S9(e[1]),owner:e[2],name:e[3]}}{let e=/^(?:[\w.\-~%]+@)?([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e?.[1].includes(`.`)||e&&t.startsWith(`git@`))return{protocol:`ssh`,hostname:e[1],owner:e[2],name:e[3]}}{let e=/^git:([\w.-]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:e[1],owner:e[2],name:e[3]}}if(!t.includes(`://`)&&!t.includes(`@`)&&!t.startsWith(`/`)){let e=/^([\w.-]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e)return{protocol:`https`,hostname:`github.com`,owner:e[1],name:e[2]}}return null}function w9(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=ku(t.hostname);if(n===null)return null;let r=t.pathname.split(`/`).filter(e=>e.length>0);if(r.length<5||r[2]!==`blob`)return null;let i,a,o,s;try{i=decodeURIComponent(r[0]),a=decodeURIComponent(r[1]),o=decodeURIComponent(r[3]),s=r.slice(4).map(e=>decodeURIComponent(e))}catch{return null}return!i||!a||!o||s.length===0||s.some(e=>e.length===0)?null:{host:n,owner:i,repo:a,branch:o,path:s.join(`/`)}}function T9(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=ku(t.hostname);if(n===null)return null;let r=t.pathname.split(`/`);if(r.length<5||r[0]!==``||r[3]!==`tree`)return null;let i=r.slice(5);i.length===1&&i[0]===``&&i.pop();let a,o,s,c;try{a=decodeURIComponent(r[1]),o=decodeURIComponent(r[2]),s=decodeURIComponent(r[4]),c=i.map(e=>decodeURIComponent(e))}catch{return null}return!a||!o||!s||c.some(e=>e.length===0)?null:{host:n,owner:a,repo:o,branch:s,path:c.join(`/`)}}function RTe(e){let t=w9(e);if(t)return{kind:`doc`,...t};let n=T9(e);return n?{kind:`folder`,...n}:null}async function zTe(e,t){let n,r;try{n=await Te(ve(e)),r=await Te(ve(pe(e)))}catch{return{kind:`not-git`}}if(!E9(n,r))return{kind:`symlink-escape`};let i=N(n,`.git`),a;try{a=O(i)}catch{return{kind:`not-git`}}if(a.isDirectory()){let e;try{e=await Te(i)}catch{return{kind:`not-git`}}if(!E9(e,n))return{kind:`symlink-escape`}}else if(!a.isFile())return{kind:`not-git`};let o=PX(n);if(o.kind!==`repository`)return{kind:`not-git`};let s=o.repository.readRemoteUrl(`origin`);if(s.kind===`unreadable`)return{kind:`not-git`};if(s.kind===`absent`)return s.reason===`config-missing`?{kind:`not-git`}:{kind:`no-origin`};let c=s.url,l=C9(c);if(l===null)return{kind:`non-github`};let u=ku(l.hostname);if(u===null)return{kind:`non-github`};let d=u===t.host.toLowerCase(),f=l.owner.toLowerCase()===t.owner.toLowerCase(),p=l.name.toLowerCase()===t.repo.toLowerCase();return!d&&f&&p?{kind:`wrong-host`,actualHost:u}:!d||!f||!p?{kind:`wrong-repo`,actualOwner:l.owner,actualRepo:l.name}:{kind:`ok`,gitRemoteUrl:`https://${u}/${l.owner}/${l.name}.git`}}function E9(e,t){if(e===t)return!0;let n=_e(t,e);return n.length>0&&!n.startsWith(`..`)&&!M(n)}const BTe=`# >>> open-knowledge cli >>>`,VTe=`# <<< open-knowledge cli <<<`,HTe=/^# >>> open-knowledge cli >>>\n[\s\S]*?^# <<< open-knowledge cli <<<\n?/m;function UTe(e){return N(e,`Library`,`Application Support`,`OpenKnowledge`,`path-install.json`)}[...f3.map(e=>d3[e])];function WTe(e){if(!M(e))throw Error(`skill cleanup requires an absolute home directory; got ${JSON.stringify(e)}`);let t=ve(e);if(t===ye||pe(t)===t)throw Error(`skill cleanup refuses to operate on the filesystem root (${t})`);return t}function D9(e){let t=WTe(e),n=[];for(let e of f3){let r=d3[e];n.push({path:N(t,`.agents`,`skills`,r),bundleId:e,scope:`central`});for(let i of Tu)n.push({path:N(t,i.skillsRoot,r),bundleId:e,scope:`host`,hostDir:i.hostDir})}return n}function GTe(e,t){let n=[];for(let r of D9(e))if(r.bundleId===t)try{D(r.path,{recursive:!0,force:!0})}catch(e){n.push(e instanceof Error?e:Error(String(e)))}if(n.length>0)throw AggregateError(n,`Failed to remove ${n.length} path(s) for ${t}`)}const KTe=[{id:`mcp-config`,write(e,t,n){let r=e.projectConfigPath?.(t);if(!r)return{integration:`mcp-config`,editorId:e.id,action:`skipped-unsupported`};try{let i=e9(e,t,n,void 0,r);return i.action===`written`||i.action===`overwritten`?{integration:`mcp-config`,editorId:e.id,action:i.action,path:i.configPath}:i.action===`failed`?{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:i.error??`unknown failure`}:i.action===`declined`?{integration:`mcp-config`,editorId:e.id,action:`declined`,path:i.configPath,...i.declineReason===void 0?{}:{reason:i.declineReason}}:{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:`unexpected project-scope action: ${i.action}`}}catch(t){return{integration:`mcp-config`,editorId:e.id,action:`failed`,path:r,error:t instanceof Error?t.message:String(t)}}}},{id:`project-skill`,write(e,t,n){try{let r=C7(e,t,{home:n.home});return{integration:`project-skill`,editorId:e.id,action:r.action,...r.path?{path:r.path}:{},...r.error?{error:r.error}:{}}}catch(t){return{integration:`project-skill`,editorId:e.id,action:`failed`,error:t instanceof Error?t.message:String(t)}}}}];function qTe(e,t,n={},r=KTe){let i=[];for(let a of t){let t=e7[a];for(let a of r)i.push(a.write(t,e,n))}return i}function JTe(e,t,n={}){return{integrations:qTe(e,t,n)}}function YTe(e){return UQ({absPath:JQ(`user`,e,e),sideline:!1,warn:()=>{}}).value.appearance?.language??`system`}function O9({home:e=oe(),env:t=process.env}={}){let n=YTe(e),{override:r,preferenceList:i}=Uhe(t),{locale:a,source:o}=Jse({override:r,storedPreference:n,supportedLocales:Ns,preferenceList:i,autoDetectableLocales:yre});return{preference:n,locale:a,source:o,systemLanguages:i}}function k9(e,t){return t.length===0||!e.includes(t)?e:e.split(t).join(`<CONTENT_DIR>`)}function XTe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function A9(e,t){if(typeof e==`string`)return k9(e,t.contentDir);if(Array.isArray(e))return e.map(e=>A9(e,t));if(!XTe(e))return e;let n={};for(let[r,i]of Object.entries(e))n[r]=A9(i,t);return n}function j9(e,t){let n=S(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
1526
1526
  `),i=n.split(`
1527
1527
  `),a=[];for(let e=0;e<i.length;e++){let n=i[e]??``;if(!(e===i.length-1&&n===``)){if(n.length===0){a.push(``);continue}try{let e=A9(JSON.parse(n),t);a.push(JSON.stringify(e))}catch{a.push(n)}}}te(e,r?`${a.join(`
1528
1528
  `)}\n`:a.join(`
1529
1529
  `))}function M9(e,t){let n=S(e,`utf-8`);if(n.trim().length!==0)try{let r=A9(JSON.parse(n),t),i=n.endsWith(`
1530
1530
  `)?`
1531
- `:``;te(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=k9(n,t.contentDir);r!==n&&te(e,r)}}function N9(e,t){let n=S(e,`utf-8`),r=k9(n,t.contentDir);r!==n&&te(e,r)}function P9(e){try{return C(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>N(e,t.name))}catch{return[]}}const XTe=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function F9(e){return/\.log\.\d+$/.test(e)}function ZTe(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||F9(e)}const QTe=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function $Te(e){let t={contentDir:e.contentDir};for(let n of QTe)for(let r of P9(N(e.stagingDir,n)))ZTe(r)?j9(r,t):r.endsWith(`.json`)?M9(r,t):N9(r,t);for(let n of P9(N(e.stagingDir,`state`))){let e=fe(n);n.endsWith(`.jsonl`)?j9(n,t):XTe.has(e)?M9(n,t):N9(n,t)}}const I9=[`.ok`,`local`,`telemetry`],L9=[`.ok`,`local`,`logs`],R9=[`.ok`,`local`,`loss-capture`],z9=`spans-current.jsonl`,B9=`spans-prev.jsonl`,V9=`server-current.jsonl`,H9=`server-prev.jsonl`,U9=`loss-current.jsonl`,W9=`loss-prev.jsonl`;function eEe(e){return N(e,...I9,z9)}function tEe(e){return N(e,...I9,B9)}function nEe(e){return N(e,...L9,V9)}function rEe(e){return N(e,...L9,H9)}function iEe(e){return N(e,...R9,U9)}function aEe(e){return N(e,...R9,W9)}const G9=1e3;async function oEe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-presence`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}async function sEe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-effects`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}async function cEe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/watcher-recent`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}function lEe(e){try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return null;let n=t.decisions;return Array.isArray(n)?n.length===0?``:`${n.map(e=>JSON.stringify(e)).join(`
1532
- `)}\n`:null}catch{return null}}function uEe(e){let t=N(e,`.git`,`ok`);if(!g(t))return null;let n=u(`git`,[`-C`,t,`log`,`--oneline`,`-50`],l3({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function dEe(e){let t=N(e,`.git`,`ok`);if(!g(t))return null;let n=u(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],l3({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function K9(){let e=process.env.OK_DESKTOP_VERSION,t=process.env.OK_DESKTOP_PACKAGED,n=process.env.OK_DESKTOP_CHANNEL;return e===void 0||t===void 0||n===void 0?null:{electronVersion:e,packaged:t===`1`||t.toLowerCase()===`true`,channel:n}}function fEe(){return{nodeVersion:process.version,platform:k(),arch:re()}}function pEe(){return process.env.OTEL_SDK_DISABLED===`false`}function q9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J9(e){if(!g(e))return{};let t;try{t=(0,on.parse)(S(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!q9(t))return{};let n=t.telemetry;if(!q9(n))return{};let r=n.localSink;return q9(r)?r:{}}function Y9(e){return typeof e==`boolean`?e:void 0}function mEe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return mEe(e.maxBytes)}function hEe(e){let t=J9(JQ(`project`,e)),n=J9(JQ(`project-local`,e));return{enabled:Y9(n.enabled)??Y9(t.enabled)??!0,spansMaxBytes:X9(n.spans)??X9(t.spans)??52428800,logsMaxBytes:X9(n.logs)??X9(t.logs)??26214400}}function gEe(e){return Ae(`sha256`).update(e).digest(`hex`)}function _Ee(e){let t=S(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const vEe=[`"doc.name"`,`"docName"`];function yEe(e){let t=S(e,`utf-8`),n=0;for(let e of vEe){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Z9(e,t){if(!g(e))return!1;try{return v(pe(t),{recursive:!0}),e.endsWith(`.ips`)?te(t,a9(S(e,`utf-8`))):m(e,t),!0}catch{return!1}}function Q9(e){let t=[],n=e=>{let r=C(e,{withFileTypes:!0});for(let i of r){let r=N(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const bEe=new Set([`.jsonl`]);function xEe(e){let t=e.lastIndexOf(`.`);return t===-1?!1:bEe.has(e.slice(t))}const SEe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function CEe(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t===-1?!1:SEe.has(e.slice(t))}function wEe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!CEe(r))continue;let{redacted:i,patterns:a,lineCount:o}=Rw(S(n,`utf-8`));a.length!==0&&(te(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function $9(e,t){return _e(e,t).split(ye).join(`/`)}async function TEe(e){let t=ve(e.contentDir),n=ve(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??oEe,a=r.fetchAgentEffects??sEe,o=r.fetchWatcherRecent??cEe,s=r.readShadowHead??uEe,c=r.readCheckpointRefs??dEe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.68.9`),d=r.readDesktopEnv??K9,f=r.readLanguage??O9,p=r.readRuntime??fEe,h=r.isOtlpPushEnabled??pEe,_=y(N(le(),`ok-bundle-`));try{v(N(_,`telemetry`),{recursive:!0}),v(N(_,`logs`),{recursive:!0}),v(N(_,`state`),{recursive:!0}),Z9(eEe(n),N(_,`telemetry`,z9)),Z9(tEe(n),N(_,`telemetry`,B9)),Z9(nEe(n),N(_,`logs`,V9)),Z9(rEe(n),N(_,`logs`,H9));for(let t of e.userLogFiles??[])Z9(t,N(_,`logs`,fe(t)));for(let t of e.userStateFiles??[])Z9(t,N(_,us,fe(t)));let y=0;for(let t of e.diagnosticReports?.files??[])Z9(t,N(_,`diagnostic-reports`,fe(t)))&&(y+=1);let b=N(n,`.ok`,`local`),x=N(b,`server.lock`),C=`not-running`,w=`no server.lock`,T=null;if(g(x)){Z9(x,N(_,`state`,`server.lock`));try{let e=S(x,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?T=t.port:w=`lock present but no port`}catch{w=`lock present but unparseable`}}if(T!==null){let e=await i(T);e===null?w=`agent-presence endpoint at :${T} unreachable`:(te(N(_,`state`,`agent-presence.json`),e),C=`running`,w=``);let t=await a(T);t!==null&&te(N(_,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=lEe(n);e!==null&&te(N(_,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&te(N(_,`state`,`shadow-head.txt`),E);let ee=c(t);ee!==null&&te(N(_,`state`,`checkpoint-refs.txt`),ee),Z9(iEe(n),N(_,`state`,U9)),Z9(aEe(n),N(_,`state`,W9)),Z9(N(b,`last-spawn-error.log`),N(_,`state`,`last-spawn-error.log`)),Z9(N(b,Au),N(_,`state`,Au)),Z9(N(b,ju),N(_,`state`,ju));let ne=p(),re=d(),ie=f(),ae={ok:{version:u(),nodeVersion:ne.nodeVersion,platform:ne.platform,arch:ne.arch},host:{desktop:re,language:ie}};te(N(_,`state`,`runtime.json`),`${JSON.stringify(ae,null,2)}\n`);let oe=C===`running`?`running
1533
- `:`not-running (${w})\n`;te(N(_,`state`,`server-status.txt`),oe);let se=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:i9(e.diagnosticReports,y);if(te(N(_,`state`,`diagnostic-reports-status.txt`),`${se}\n`),e.processDir&&g(e.processDir)){let t=N(_,`process`);v(t,{recursive:!0}),m(e.processDir,t,{recursive:!0})}let k=e.redact===!0;k&&$Te({stagingDir:_,contentDir:t}),e.note&&te(N(_,`note.txt`),e.note);let ce=null;e.scrubSecrets===!0&&(ce=wEe(_));for(let t of e.extraFiles??[])Z9(t.sourcePath,N(_,`extra`,t.zipName??fe(t.sourcePath)))||r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);let le=hEe(n),ue=Q9(_),A=[],j=0,de=0;for(let e of ue){let t=$9(_,e),n=O(e).size,r=xEe(t)?_Ee(e):0;A.push({path:t,bytes:n,lines:r}),j+=n,(t.startsWith(`telemetry/`)||t.startsWith(`logs/`))&&(de+=yEe(e))}let pe={applied:k};ce!==null&&(pe.secretScrub=ce);let me={schemaVersion:2,createdAt:l().toISOString(),ok:{version:u(),nodeVersion:ne.nodeVersion,platform:ne.platform,arch:ne.arch},host:{desktop:re,language:ie},contentDir:{pathSha256:gEe(t),absolutePath:k?`<CONTENT_DIR>`:t},telemetry:{localSink:le,otlpPushEnabled:h()},redaction:pe,serverStatus:C,files:A};te(N(_,`manifest.json`),`${JSON.stringify(me,null,2)}\n`);let M=ue.some(e=>{try{return S(e,`utf-8`).includes(t)}catch{return!1}}),he={stagedDiagnosticReports:y,totalBytes:j,fileCount:A.length,docNameCount:de,contentDirVisible:M,redacted:k},ge=!1;return{stagingDir:_,manifest:me,summary:he,cleanup:()=>{ge||(ge=!0,D(_,{recursive:!0,force:!0}))}}}catch(e){throw D(_,{recursive:!0,force:!0}),e}}async function EEe(e){let{collected:t,outputPath:n}=e,r=pe(n);if(!g(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);let i=new Bye.ZipFile,a=Q9(t.stagingDir);for(let e of a){let n=$9(t.stagingDir,e);i.addFile(e,n)}i.end();let o=h(n);return i.outputStream.pipe(o),await new Promise((e,t)=>{o.on(`close`,e),o.on(`error`,t),i.outputStream.on(`error`,t)}),n}function DEe(e,t){let n=N(e,`.ok`,`config.yml`);if(g(n))try{let t=(0,on.parse)(S(n,`utf-8`)),r=O7(t)?t.content:void 0,i=O7(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return ve(e,i)}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml; falling back to project root as content dir`)}return ve(e)}async function OEe(e,t,n,r,i){let a=s9(t,e.logger),o=await TEe({contentDir:DEe(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...mTe(a,e.userLogsDir??N(oe(),`.ok`,`logs`)),...l9(e.cachesDir??N(oe(),`Library`,`Caches`))],userStateFiles:u9(e.bugReportsDir??o9()),diagnosticReports:i,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{v(pe(e.outputPath),{recursive:!0}),await EEe({collected:o,outputPath:e.outputPath});let t=o.manifest.redaction.secretScrub;return{zipPath:e.outputPath,summary:{level:`full`,systemWide:!1,projectSlug:a,files:o.manifest.files.map(e=>e.path),redactions:t?.redactions??[],redactedLineCount:t?.redactedLineCount??0,generatedAt:o.manifest.createdAt}}}finally{o.cleanup()}}async function kEe(e){let{projectDir:t}=e,n=e.readDesktopEnv??K9,r=e.readLanguage??O9,i=()=>uTe(e.diagnosticReportsDir??N(oe(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return OEe(e,t,n,r,i());let{zipPath:a,summary:o}=await yTe({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:l9(e.cachesDir??N(oe(),`Library`,`Caches`)),bugReportLedgerFiles:u9(e.bugReportsDir??o9()),diagnosticReports:e.level===`full`?i():void 0,logger:e.logger,note:e.note,extraFiles:e.extraFiles,desktop:n(),language:r()});return{zipPath:a,summary:{level:e.level,systemWide:t===void 0,projectSlug:o.projectSlug,files:o.files,redactions:o.redactions,redactedLineCount:o.redactedLineCount,generatedAt:o.generatedAt}}}export{M5 as ALL_EDITOR_IDS,N5 as EDITOR_LABELS,e7 as EDITOR_TARGETS,mCe as HOSTS_WITH_USER_SKILL_DIR,Ywe as LAUNCH_CONFIG_NAME,zTe as PATH_SHIM_BEGIN,VTe as PATH_SHIM_BLOCK_RE,BTe as PATH_SHIM_END,Awe as addOkPathsToGitExclude,b7 as assertProjectPathSafe,H5 as buildManagedServerEntry,kTe as buildMcpConfigDeclineEvent,ATe as buildMcpConfigMigrateEvent,r9 as classifyExistingMcpEntry,kEe as collectReportBundle,un as createTokenStore,dTe as defaultBugReportZipPath,Be as detectGh,Ue as detectGhAccounts,eTe as detectInstalledEditors,OCe as editorConfigPathDisplay,DCe as editorEntryLocator,xTe as ensurePiBridge,L7 as formatTrackedRemediation,Nwe as getExcludedOkPaths,F7 as getInstalledSkillProjectionPaths,kwe as getNativeTomlMcpEditor,P7 as getOkArtifactPaths,B5 as isEntryUpToDate,U5 as isOwnManagedEntry,ITe as loadConfig,fee as makeLazyProbeTokenStore,o9 as okBugReportsDir,w9 as parseGitHubBlobUrl,LTe as parseGitHubShareUrl,T9 as parseGitHubTreeUrl,C9 as parseGitUrl,HTe as pathInstallMarkerPath,cwe as previewContent,nTe as probeOwnManagedEditorMcpEntry,bTe as probePiBridgeState,I7 as probeTrackedOkPaths,t9 as readExistingMcpEntry,Mwe as readSharingMode,Rw as redactContent,jwe as removeOkPathsFromGitExclude,TTe as removeOwnMcpEntry,vwe as removeProjectSkill,WTe as removeUserGlobalSkillBundle,mwe as resolveProjectRoot,NTe as runStop,y9 as truncatePriorEntry,D9 as userGlobalSkillBundleTargets,RTe as validateLocalFolderForShare,e9 as writeEditorMcpConfig,qTe as writeProjectAiIntegrations,C7 as writeProjectSkill,$we as writeUserMcpConfigs};
1531
+ `:``;te(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=k9(n,t.contentDir);r!==n&&te(e,r)}}function N9(e,t){let n=S(e,`utf-8`),r=k9(n,t.contentDir);r!==n&&te(e,r)}function P9(e){try{return C(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>N(e,t.name))}catch{return[]}}const ZTe=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function F9(e){return/\.log\.\d+$/.test(e)}function QTe(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||F9(e)}const $Te=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function eEe(e){let t={contentDir:e.contentDir};for(let n of $Te)for(let r of P9(N(e.stagingDir,n)))QTe(r)?j9(r,t):r.endsWith(`.json`)?M9(r,t):N9(r,t);for(let n of P9(N(e.stagingDir,`state`))){let e=fe(n);n.endsWith(`.jsonl`)?j9(n,t):ZTe.has(e)?M9(n,t):N9(n,t)}}const I9=[`.ok`,`local`,`telemetry`],L9=[`.ok`,`local`,`logs`],R9=[`.ok`,`local`,`loss-capture`],z9=`spans-current.jsonl`,B9=`spans-prev.jsonl`,V9=`server-current.jsonl`,H9=`server-prev.jsonl`,U9=`loss-current.jsonl`,W9=`loss-prev.jsonl`;function tEe(e){return N(e,...I9,z9)}function nEe(e){return N(e,...I9,B9)}function rEe(e){return N(e,...L9,V9)}function iEe(e){return N(e,...L9,H9)}function aEe(e){return N(e,...R9,U9)}function oEe(e){return N(e,...R9,W9)}const G9=1e3;async function sEe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-presence`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}async function cEe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-effects`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}async function lEe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/watcher-recent`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}function uEe(e){try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return null;let n=t.decisions;return Array.isArray(n)?n.length===0?``:`${n.map(e=>JSON.stringify(e)).join(`
1532
+ `)}\n`:null}catch{return null}}function dEe(e){let t=N(e,`.git`,`ok`);if(!g(t))return null;let n=u(`git`,[`-C`,t,`log`,`--oneline`,`-50`],l3({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function fEe(e){let t=N(e,`.git`,`ok`);if(!g(t))return null;let n=u(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],l3({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function K9(){let e=process.env.OK_DESKTOP_VERSION,t=process.env.OK_DESKTOP_PACKAGED,n=process.env.OK_DESKTOP_CHANNEL;return e===void 0||t===void 0||n===void 0?null:{electronVersion:e,packaged:t===`1`||t.toLowerCase()===`true`,channel:n}}function pEe(){return{nodeVersion:process.version,platform:k(),arch:re()}}function mEe(){return process.env.OTEL_SDK_DISABLED===`false`}function q9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J9(e){if(!g(e))return{};let t;try{t=(0,on.parse)(S(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!q9(t))return{};let n=t.telemetry;if(!q9(n))return{};let r=n.localSink;return q9(r)?r:{}}function Y9(e){return typeof e==`boolean`?e:void 0}function hEe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return hEe(e.maxBytes)}function gEe(e){let t=J9(JQ(`project`,e)),n=J9(JQ(`project-local`,e));return{enabled:Y9(n.enabled)??Y9(t.enabled)??!0,spansMaxBytes:X9(n.spans)??X9(t.spans)??52428800,logsMaxBytes:X9(n.logs)??X9(t.logs)??26214400}}function _Ee(e){return Ae(`sha256`).update(e).digest(`hex`)}function vEe(e){let t=S(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const yEe=[`"doc.name"`,`"docName"`];function bEe(e){let t=S(e,`utf-8`),n=0;for(let e of yEe){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Z9(e,t){if(!g(e))return!1;try{return v(pe(t),{recursive:!0}),e.endsWith(`.ips`)?te(t,a9(S(e,`utf-8`))):m(e,t),!0}catch{return!1}}function Q9(e){let t=[],n=e=>{let r=C(e,{withFileTypes:!0});for(let i of r){let r=N(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const xEe=new Set([`.jsonl`]);function SEe(e){let t=e.lastIndexOf(`.`);return t===-1?!1:xEe.has(e.slice(t))}const CEe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function wEe(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t===-1?!1:CEe.has(e.slice(t))}function TEe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!wEe(r))continue;let{redacted:i,patterns:a,lineCount:o}=Rw(S(n,`utf-8`));a.length!==0&&(te(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function $9(e,t){return _e(e,t).split(ye).join(`/`)}async function EEe(e){let t=ve(e.contentDir),n=ve(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??sEe,a=r.fetchAgentEffects??cEe,o=r.fetchWatcherRecent??lEe,s=r.readShadowHead??dEe,c=r.readCheckpointRefs??fEe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.68.11-beta.0`),d=r.readDesktopEnv??K9,f=r.readLanguage??O9,p=r.readRuntime??pEe,h=r.isOtlpPushEnabled??mEe,_=y(N(le(),`ok-bundle-`));try{v(N(_,`telemetry`),{recursive:!0}),v(N(_,`logs`),{recursive:!0}),v(N(_,`state`),{recursive:!0}),Z9(tEe(n),N(_,`telemetry`,z9)),Z9(nEe(n),N(_,`telemetry`,B9)),Z9(rEe(n),N(_,`logs`,V9)),Z9(iEe(n),N(_,`logs`,H9));for(let t of e.userLogFiles??[])Z9(t,N(_,`logs`,fe(t)));for(let t of e.userStateFiles??[])Z9(t,N(_,us,fe(t)));let y=0;for(let t of e.diagnosticReports?.files??[])Z9(t,N(_,`diagnostic-reports`,fe(t)))&&(y+=1);let b=N(n,`.ok`,`local`),x=N(b,`server.lock`),C=`not-running`,w=`no server.lock`,T=null;if(g(x)){Z9(x,N(_,`state`,`server.lock`));try{let e=S(x,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?T=t.port:w=`lock present but no port`}catch{w=`lock present but unparseable`}}if(T!==null){let e=await i(T);e===null?w=`agent-presence endpoint at :${T} unreachable`:(te(N(_,`state`,`agent-presence.json`),e),C=`running`,w=``);let t=await a(T);t!==null&&te(N(_,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=uEe(n);e!==null&&te(N(_,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&te(N(_,`state`,`shadow-head.txt`),E);let ee=c(t);ee!==null&&te(N(_,`state`,`checkpoint-refs.txt`),ee),Z9(aEe(n),N(_,`state`,U9)),Z9(oEe(n),N(_,`state`,W9)),Z9(N(b,`last-spawn-error.log`),N(_,`state`,`last-spawn-error.log`)),Z9(N(b,Au),N(_,`state`,Au)),Z9(N(b,ju),N(_,`state`,ju));let ne=p(),re=d(),ie=f(),ae={ok:{version:u(),nodeVersion:ne.nodeVersion,platform:ne.platform,arch:ne.arch},host:{desktop:re,language:ie}};te(N(_,`state`,`runtime.json`),`${JSON.stringify(ae,null,2)}\n`);let oe=C===`running`?`running
1533
+ `:`not-running (${w})\n`;te(N(_,`state`,`server-status.txt`),oe);let se=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:i9(e.diagnosticReports,y);if(te(N(_,`state`,`diagnostic-reports-status.txt`),`${se}\n`),e.processDir&&g(e.processDir)){let t=N(_,`process`);v(t,{recursive:!0}),m(e.processDir,t,{recursive:!0})}let k=e.redact===!0;k&&eEe({stagingDir:_,contentDir:t}),e.note&&te(N(_,`note.txt`),e.note);let ce=null;e.scrubSecrets===!0&&(ce=TEe(_));for(let t of e.extraFiles??[])Z9(t.sourcePath,N(_,`extra`,t.zipName??fe(t.sourcePath)))||r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);let le=gEe(n),ue=Q9(_),A=[],j=0,de=0;for(let e of ue){let t=$9(_,e),n=O(e).size,r=SEe(t)?vEe(e):0;A.push({path:t,bytes:n,lines:r}),j+=n,(t.startsWith(`telemetry/`)||t.startsWith(`logs/`))&&(de+=bEe(e))}let pe={applied:k};ce!==null&&(pe.secretScrub=ce);let me={schemaVersion:2,createdAt:l().toISOString(),ok:{version:u(),nodeVersion:ne.nodeVersion,platform:ne.platform,arch:ne.arch},host:{desktop:re,language:ie},contentDir:{pathSha256:_Ee(t),absolutePath:k?`<CONTENT_DIR>`:t},telemetry:{localSink:le,otlpPushEnabled:h()},redaction:pe,serverStatus:C,files:A};te(N(_,`manifest.json`),`${JSON.stringify(me,null,2)}\n`);let M=ue.some(e=>{try{return S(e,`utf-8`).includes(t)}catch{return!1}}),he={stagedDiagnosticReports:y,totalBytes:j,fileCount:A.length,docNameCount:de,contentDirVisible:M,redacted:k},ge=!1;return{stagingDir:_,manifest:me,summary:he,cleanup:()=>{ge||(ge=!0,D(_,{recursive:!0,force:!0}))}}}catch(e){throw D(_,{recursive:!0,force:!0}),e}}async function DEe(e){let{collected:t,outputPath:n}=e,r=pe(n);if(!g(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);let i=new Bye.ZipFile,a=Q9(t.stagingDir);for(let e of a){let n=$9(t.stagingDir,e);i.addFile(e,n)}i.end();let o=h(n);return i.outputStream.pipe(o),await new Promise((e,t)=>{o.on(`close`,e),o.on(`error`,t),i.outputStream.on(`error`,t)}),n}function OEe(e,t){let n=N(e,`.ok`,`config.yml`);if(g(n))try{let t=(0,on.parse)(S(n,`utf-8`)),r=O7(t)?t.content:void 0,i=O7(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return ve(e,i)}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml; falling back to project root as content dir`)}return ve(e)}async function kEe(e,t,n,r,i){let a=s9(t,e.logger),o=await EEe({contentDir:OEe(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...hTe(a,e.userLogsDir??N(oe(),`.ok`,`logs`)),...l9(e.cachesDir??N(oe(),`Library`,`Caches`))],userStateFiles:u9(e.bugReportsDir??o9()),diagnosticReports:i,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{v(pe(e.outputPath),{recursive:!0}),await DEe({collected:o,outputPath:e.outputPath});let t=o.manifest.redaction.secretScrub;return{zipPath:e.outputPath,summary:{level:`full`,systemWide:!1,projectSlug:a,files:o.manifest.files.map(e=>e.path),redactions:t?.redactions??[],redactedLineCount:t?.redactedLineCount??0,generatedAt:o.manifest.createdAt}}}finally{o.cleanup()}}async function AEe(e){let{projectDir:t}=e,n=e.readDesktopEnv??K9,r=e.readLanguage??O9,i=()=>dTe(e.diagnosticReportsDir??N(oe(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return kEe(e,t,n,r,i());let{zipPath:a,summary:o}=await bTe({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:l9(e.cachesDir??N(oe(),`Library`,`Caches`)),bugReportLedgerFiles:u9(e.bugReportsDir??o9()),diagnosticReports:e.level===`full`?i():void 0,logger:e.logger,note:e.note,extraFiles:e.extraFiles,desktop:n(),language:r()});return{zipPath:a,summary:{level:e.level,systemWide:t===void 0,projectSlug:o.projectSlug,files:o.files,redactions:o.redactions,redactedLineCount:o.redactedLineCount,generatedAt:o.generatedAt}}}export{M5 as ALL_EDITOR_IDS,N5 as EDITOR_LABELS,e7 as EDITOR_TARGETS,hCe as HOSTS_WITH_USER_SKILL_DIR,Xwe as LAUNCH_CONFIG_NAME,BTe as PATH_SHIM_BEGIN,HTe as PATH_SHIM_BLOCK_RE,VTe as PATH_SHIM_END,jwe as addOkPathsToGitExclude,b7 as assertProjectPathSafe,H5 as buildManagedServerEntry,ATe as buildMcpConfigDeclineEvent,jTe as buildMcpConfigMigrateEvent,r9 as classifyExistingMcpEntry,AEe as collectReportBundle,un as createTokenStore,fTe as defaultBugReportZipPath,Be as detectGh,Ue as detectGhAccounts,tTe as detectInstalledEditors,kCe as editorConfigPathDisplay,OCe as editorEntryLocator,STe as ensurePiBridge,L7 as formatTrackedRemediation,Pwe as getExcludedOkPaths,F7 as getInstalledSkillProjectionPaths,Awe as getNativeTomlMcpEditor,P7 as getOkArtifactPaths,B5 as isEntryUpToDate,U5 as isOwnManagedEntry,LTe as loadConfig,fee as makeLazyProbeTokenStore,o9 as okBugReportsDir,w9 as parseGitHubBlobUrl,RTe as parseGitHubShareUrl,T9 as parseGitHubTreeUrl,C9 as parseGitUrl,UTe as pathInstallMarkerPath,lwe as previewContent,rTe as probeOwnManagedEditorMcpEntry,xTe as probePiBridgeState,I7 as probeTrackedOkPaths,t9 as readExistingMcpEntry,Nwe as readSharingMode,Rw as redactContent,Mwe as removeOkPathsFromGitExclude,ETe as removeOwnMcpEntry,ywe as removeProjectSkill,GTe as removeUserGlobalSkillBundle,hwe as resolveProjectRoot,PTe as runStop,y9 as truncatePriorEntry,D9 as userGlobalSkillBundleTargets,zTe as validateLocalFolderForShare,e9 as writeEditorMcpConfig,JTe as writeProjectAiIntegrations,C7 as writeProjectSkill,eTe as writeUserMcpConfigs};
1534
1534
  //# sourceMappingURL=index.mjs.map