@kitionstage/sdk 0.0.0-stage → 0.5.2-stage.2

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 (259) hide show
  1. package/README.md +73 -2
  2. package/dist/LICENSE +177 -0
  3. package/dist/THIRD_PARTY_NOTICES +28 -0
  4. package/dist/lib/assets/kitEngine.worker-3iMvwtlI.js +12732 -0
  5. package/dist/lib/assets/loro_wasm_bg-Gulzks_0.wasm +0 -0
  6. package/dist/lib/chunks/batch-BWpAyHvP.js +789 -0
  7. package/dist/lib/chunks/canonical-BIWfVCL-.js +87 -0
  8. package/dist/lib/chunks/envelope-D6MGY-ZN.js +61 -0
  9. package/dist/lib/chunks/replica-D8w3I4sn.js +2472 -0
  10. package/dist/lib/chunks/runtime-BVJHE1Pg.js +997 -0
  11. package/dist/lib/chunks/session-BqXC9a1-.js +281 -0
  12. package/dist/lib/chunks/toolIds-BCeSGHpV.js +821 -0
  13. package/dist/lib/chunks/workspaceTree-Destqupf.js +23 -0
  14. package/dist/lib/convergence/index.js +1035 -0
  15. package/dist/lib/convergence/node.js +8 -0
  16. package/dist/lib/embed-server/callbacks.js +37 -0
  17. package/dist/lib/embed-server/cli.js +19 -0
  18. package/dist/lib/embed-server/index.js +272 -0
  19. package/dist/lib/extensions/index.js +439 -0
  20. package/dist/lib/extensions/panel.html +208 -0
  21. package/dist/lib/extensions/runtime.js +198 -0
  22. package/dist/lib/extensions/sandbox.html +35 -0
  23. package/dist/lib/kdm/index.js +437 -0
  24. package/dist/lib/kit-dev-host/checkUiIds.mjs +44 -0
  25. package/dist/lib/kit-dev-host/index.js +308 -0
  26. package/dist/lib/kit-dev-host/lineRow.mjs +47 -0
  27. package/dist/lib/kit-dev-host/modeSmoke.mjs +178 -0
  28. package/dist/lib/kit-editor/index.js +6481 -0
  29. package/dist/lib/kit-editor/styles.css +807 -0
  30. package/dist/lib/kit-editor/workspaceTree.js +1 -0
  31. package/dist/lib/kit-engine/index.js +7 -0
  32. package/dist/lib/kit-host/index.js +530 -0
  33. package/dist/lib/kit-ui-protocol/index.js +336 -0
  34. package/dist/lib/node-only/embed-server-callbacks.js +2 -0
  35. package/dist/lib/node-only/embed-server.js +2 -0
  36. package/dist/lib/sync/index.js +1008 -0
  37. package/dist/lib/sync/openToken.js +201 -0
  38. package/dist/lib/sync/replicaVersions.js +51 -0
  39. package/dist/standalone/chunks/batch-CAGYk6m4.js +789 -0
  40. package/dist/standalone/chunks/client-B9xkOcvf.js +772 -0
  41. package/dist/standalone/chunks/collab-CTQZ9h7J.js +1022 -0
  42. package/dist/standalone/chunks/comment-Ds9t8xSE.js +94 -0
  43. package/dist/standalone/chunks/comments-uVDS8Wxp.js +41 -0
  44. package/dist/standalone/chunks/document-B5MMuYyN.js +324 -0
  45. package/dist/standalone/chunks/envelope-GX4Cynkx.js +7612 -0
  46. package/dist/standalone/chunks/index-BEgEEnhU.js +287 -0
  47. package/dist/standalone/chunks/index-EEl8hGbP.js +1967 -0
  48. package/dist/standalone/chunks/kits-Cp51mDlw.js +9 -0
  49. package/dist/standalone/chunks/replica-Di2iCPiD.js +3281 -0
  50. package/dist/standalone/chunks/replicaVersions-C3rJxnk9.js +50 -0
  51. package/dist/standalone/chunks/touched-T9jKJjxn.js +78 -0
  52. package/dist/standalone/index.js +12 -0
  53. package/dist/standalone/script/index.js +339 -0
  54. package/dist/standalone/script/kits/board.js +5 -0
  55. package/dist/standalone/script/kits/cad.js +5 -0
  56. package/dist/standalone/script/kits/design.js +5 -0
  57. package/dist/standalone/script/kits/doc.js +5 -0
  58. package/dist/standalone/script/kits/film.js +5 -0
  59. package/dist/standalone/script/kits/html.js +5 -0
  60. package/dist/standalone/script/kits/index.js +38 -0
  61. package/dist/standalone/script/kits/layout.js +5 -0
  62. package/dist/standalone/script/kits/motion.js +5 -0
  63. package/dist/standalone/script/kits/note.js +5 -0
  64. package/dist/standalone/script/kits/pdf.js +5 -0
  65. package/dist/standalone/script/kits/photo.js +5 -0
  66. package/dist/standalone/script/kits/scene.js +5 -0
  67. package/dist/standalone/script/kits/sheet.js +5 -0
  68. package/dist/standalone/script/kits/slide.js +5 -0
  69. package/dist/standalone/script/kits/table.js +5 -0
  70. package/dist/standalone/script/kits/vector.js +5 -0
  71. package/dist/standalone/script/node.js +401 -0
  72. package/dist/standalone/script/proxy.js +254 -0
  73. package/dist/types/convergence/src/adapter.d.ts +131 -0
  74. package/dist/types/convergence/src/engine.d.ts +66 -0
  75. package/dist/types/convergence/src/index.d.ts +21 -0
  76. package/dist/types/convergence/src/net.d.ts +52 -0
  77. package/dist/types/convergence/src/node.d.ts +6 -0
  78. package/dist/types/convergence/src/report.d.ts +56 -0
  79. package/dist/types/convergence/src/rng.d.ts +12 -0
  80. package/dist/types/convergence/src/scenarios.d.ts +15 -0
  81. package/dist/types/convergence/src/state.d.ts +67 -0
  82. package/dist/types/embed/src/agent.d.ts +88 -0
  83. package/dist/types/embed/src/blobs.d.ts +2 -0
  84. package/dist/types/embed/src/collab.d.ts +250 -0
  85. package/dist/types/embed/src/comments.d.ts +30 -0
  86. package/dist/types/embed/src/errors.d.ts +24 -0
  87. package/dist/types/embed/src/handlers.d.ts +92 -0
  88. package/dist/types/embed/src/index.d.ts +20 -0
  89. package/dist/types/embed/src/mount.d.ts +39 -0
  90. package/dist/types/embed/src/replicaStore.d.ts +3 -0
  91. package/dist/types/embed/src/rooms.d.ts +40 -0
  92. package/dist/types/embed/src/schemas.d.ts +7 -0
  93. package/dist/types/embed/src/syncClients.d.ts +28 -0
  94. package/dist/types/embed/src/theme.d.ts +7 -0
  95. package/dist/types/embed/src/types.d.ts +596 -0
  96. package/dist/types/embed/src/ui.d.ts +33 -0
  97. package/dist/types/embed/src/version.d.ts +2 -0
  98. package/dist/types/embed-server/src/callbacks.d.ts +30 -0
  99. package/dist/types/embed-server/src/cli.d.ts +1 -0
  100. package/dist/types/embed-server/src/index.d.ts +19 -0
  101. package/dist/types/embed-server/src/page.d.ts +15 -0
  102. package/dist/types/embed-server/src/server.d.ts +39 -0
  103. package/dist/types/embed-server/src/session.d.ts +22 -0
  104. package/dist/types/extensions/src/gate.d.ts +17 -0
  105. package/dist/types/extensions/src/generated/runtime.d.ts +8 -0
  106. package/dist/types/extensions/src/host.d.ts +135 -0
  107. package/dist/types/extensions/src/index.d.ts +13 -0
  108. package/dist/types/extensions/src/manifest.d.ts +82 -0
  109. package/dist/types/extensions/src/protocol.d.ts +159 -0
  110. package/dist/types/extensions/src/rpc.d.ts +52 -0
  111. package/dist/types/extensions/src/runtime/document.d.ts +40 -0
  112. package/dist/types/extensions/src/runtime/index.d.ts +10 -0
  113. package/dist/types/extensions/src/runtime/panel.d.ts +19 -0
  114. package/dist/types/extensions/src/runtime/runtime.d.ts +54 -0
  115. package/dist/types/extensions/src/runtime/worker.d.ts +1 -0
  116. package/dist/types/extensions/src/sandbox.d.ts +41 -0
  117. package/dist/types/kdm/src/args.d.ts +12 -0
  118. package/dist/types/kdm/src/batch.d.ts +118 -0
  119. package/dist/types/kdm/src/canonical.d.ts +25 -0
  120. package/dist/types/kdm/src/comment.d.ts +114 -0
  121. package/dist/types/kdm/src/diff.d.ts +125 -0
  122. package/dist/types/kdm/src/envelope.d.ts +27 -0
  123. package/dist/types/kdm/src/errors.d.ts +28 -0
  124. package/dist/types/kdm/src/footprint.d.ts +21 -0
  125. package/dist/types/kdm/src/ids.d.ts +57 -0
  126. package/dist/types/kdm/src/index.d.ts +18 -0
  127. package/dist/types/kdm/src/marks.d.ts +32 -0
  128. package/dist/types/kdm/src/op.d.ts +124 -0
  129. package/dist/types/kdm/src/origin.d.ts +41 -0
  130. package/dist/types/kdm/src/overlay.d.ts +92 -0
  131. package/dist/types/kdm/src/projection.d.ts +29 -0
  132. package/dist/types/kdm/src/read.d.ts +90 -0
  133. package/dist/types/kdm/src/replica.d.ts +403 -0
  134. package/dist/types/kdm/src/schema.d.ts +185 -0
  135. package/dist/types/kdm/src/testing.d.ts +28 -0
  136. package/dist/types/kdm/src/toolIds.d.ts +61 -0
  137. package/dist/types/kdm/src/touched.d.ts +24 -0
  138. package/dist/types/kdm/src/tx.d.ts +215 -0
  139. package/dist/types/kdm/src/value.d.ts +23 -0
  140. package/dist/types/kit-dev-host/src/checkNoPaths.d.ts +19 -0
  141. package/dist/types/kit-dev-host/src/checkUiIds.d.mts +2 -0
  142. package/dist/types/kit-dev-host/src/index.d.ts +179 -0
  143. package/dist/types/kit-dev-host/src/lineRow.d.mts +14 -0
  144. package/dist/types/kit-dev-host/src/memoryFiles.d.ts +15 -0
  145. package/dist/types/kit-dev-host/src/modeSmoke.d.mts +8 -0
  146. package/dist/types/kit-editor/src/CommandDialog.d.ts +22 -0
  147. package/dist/types/kit-editor/src/CommentsPanel.d.ts +45 -0
  148. package/dist/types/kit-editor/src/CustomizeDialog.d.ts +32 -0
  149. package/dist/types/kit-editor/src/HostButtons.d.ts +11 -0
  150. package/dist/types/kit-editor/src/RenderFailure.d.ts +7 -0
  151. package/dist/types/kit-editor/src/TextSink.d.ts +6 -0
  152. package/dist/types/kit-editor/src/brand.d.ts +2 -0
  153. package/dist/types/kit-editor/src/catalogMenus.d.ts +27 -0
  154. package/dist/types/kit-editor/src/chart.d.ts +138 -0
  155. package/dist/types/kit-editor/src/conflicts.d.ts +12 -0
  156. package/dist/types/kit-editor/src/drawing.d.ts +83 -0
  157. package/dist/types/kit-editor/src/editor.d.ts +544 -0
  158. package/dist/types/kit-editor/src/engine/KitCanvas.d.ts +70 -0
  159. package/dist/types/kit-editor/src/engine/backdrop.d.ts +32 -0
  160. package/dist/types/kit-editor/src/engine/createKitFile.d.ts +12 -0
  161. package/dist/types/kit-editor/src/engine/decorations.d.ts +14 -0
  162. package/dist/types/kit-editor/src/engine/engineOverlays.d.ts +197 -0
  163. package/dist/types/kit-editor/src/engine/engineTools.d.ts +116 -0
  164. package/dist/types/kit-editor/src/engine/kitDraft.d.ts +70 -0
  165. package/dist/types/kit-editor/src/engine/kitEngine.d.ts +390 -0
  166. package/dist/types/kit-editor/src/engine/kitEngine.worker.d.ts +30 -0
  167. package/dist/types/kit-editor/src/engine/kitHost.d.ts +41 -0
  168. package/dist/types/kit-editor/src/engine/kitModel.d.ts +32 -0
  169. package/dist/types/kit-editor/src/engine/kitModelRunner.d.ts +99 -0
  170. package/dist/types/kit-editor/src/engine/kitModule.d.ts +185 -0
  171. package/dist/types/kit-editor/src/engine/kitShortcuts.d.ts +32 -0
  172. package/dist/types/kit-editor/src/engine/kitTools.d.ts +79 -0
  173. package/dist/types/kit-editor/src/engine/lazyFonts.d.ts +34 -0
  174. package/dist/types/kit-editor/src/engine/lentFiles.d.ts +29 -0
  175. package/dist/types/kit-editor/src/engine/rasterViewport.d.ts +178 -0
  176. package/dist/types/kit-editor/src/engine/readOnly.d.ts +78 -0
  177. package/dist/types/kit-editor/src/engine/refusal.d.ts +39 -0
  178. package/dist/types/kit-editor/src/engine/replica.d.ts +23 -0
  179. package/dist/types/kit-editor/src/engine/useKitDocument.d.ts +154 -0
  180. package/dist/types/kit-editor/src/engine/workerRelay.d.ts +62 -0
  181. package/dist/types/kit-editor/src/files.d.ts +74 -0
  182. package/dist/types/kit-editor/src/frame/EditorFrame.d.ts +74 -0
  183. package/dist/types/kit-editor/src/frame/FocusBar.d.ts +10 -0
  184. package/dist/types/kit-editor/src/frame/MenuNodes.d.ts +20 -0
  185. package/dist/types/kit-editor/src/frame/MenuRibbon.d.ts +8 -0
  186. package/dist/types/kit-editor/src/frame/ModeButton.d.ts +7 -0
  187. package/dist/types/kit-editor/src/frame/menus.d.ts +64 -0
  188. package/dist/types/kit-editor/src/frame/modes.d.ts +51 -0
  189. package/dist/types/kit-editor/src/frame/useFrameLayout.d.ts +34 -0
  190. package/dist/types/kit-editor/src/host.d.ts +127 -0
  191. package/dist/types/kit-editor/src/index.d.ts +85 -0
  192. package/dist/types/kit-editor/src/ink.d.ts +26 -0
  193. package/dist/types/kit-editor/src/lease.d.ts +53 -0
  194. package/dist/types/kit-editor/src/oneInFlight.d.ts +7 -0
  195. package/dist/types/kit-editor/src/phrases.d.ts +25 -0
  196. package/dist/types/kit-editor/src/presence.d.ts +79 -0
  197. package/dist/types/kit-editor/src/strings.d.ts +6 -0
  198. package/dist/types/kit-editor/src/toolIcons.d.ts +32 -0
  199. package/dist/types/kit-editor/src/uiCatalog.d.ts +59 -0
  200. package/dist/types/kit-editor/src/uiConfig.d.ts +53 -0
  201. package/dist/types/kit-editor/src/uiContext.d.ts +65 -0
  202. package/dist/types/kit-editor/src/uiStore.d.ts +20 -0
  203. package/dist/types/kit-editor/src/useCommentAnchors.d.ts +29 -0
  204. package/dist/types/kit-editor/src/useKitSession.d.ts +115 -0
  205. package/dist/types/kit-editor/src/workspaceTree.d.ts +5 -0
  206. package/dist/types/kit-engine/src/contract.d.ts +154 -0
  207. package/dist/types/kit-engine/src/index.d.ts +2 -0
  208. package/dist/types/kit-engine/src/session.d.ts +133 -0
  209. package/dist/types/kit-host/src/files.d.ts +163 -0
  210. package/dist/types/kit-host/src/index.d.ts +315 -0
  211. package/dist/types/kit-ui-protocol/src/index.d.ts +1145 -0
  212. package/dist/types/loro-crdt.d.ts +9 -0
  213. package/dist/types/script/kits/board.d.ts +534 -0
  214. package/dist/types/script/kits/cad.d.ts +2937 -0
  215. package/dist/types/script/kits/design.d.ts +3213 -0
  216. package/dist/types/script/kits/doc.d.ts +2575 -0
  217. package/dist/types/script/kits/film.d.ts +4067 -0
  218. package/dist/types/script/kits/html.d.ts +38 -0
  219. package/dist/types/script/kits/index.d.ts +20 -0
  220. package/dist/types/script/kits/layout.d.ts +3483 -0
  221. package/dist/types/script/kits/motion.d.ts +4826 -0
  222. package/dist/types/script/kits/note.d.ts +631 -0
  223. package/dist/types/script/kits/pdf.d.ts +829 -0
  224. package/dist/types/script/kits/photo.d.ts +7574 -0
  225. package/dist/types/script/kits/scene.d.ts +2962 -0
  226. package/dist/types/script/kits/sheet.d.ts +2419 -0
  227. package/dist/types/script/kits/slide.d.ts +1894 -0
  228. package/dist/types/script/kits/table.d.ts +654 -0
  229. package/dist/types/script/kits/vector.d.ts +5167 -0
  230. package/dist/types/script/src/agentRelay.d.ts +48 -0
  231. package/dist/types/script/src/capabilities.d.ts +21 -0
  232. package/dist/types/script/src/document.d.ts +87 -0
  233. package/dist/types/script/src/drafts.d.ts +141 -0
  234. package/dist/types/script/src/exchange.d.ts +30 -0
  235. package/dist/types/script/src/headless.d.ts +190 -0
  236. package/dist/types/script/src/index.d.ts +15 -0
  237. package/dist/types/script/src/kitModel.d.ts +17 -0
  238. package/dist/types/script/src/kits.d.ts +8 -0
  239. package/dist/types/script/src/node.d.ts +42 -0
  240. package/dist/types/script/src/port.d.ts +89 -0
  241. package/dist/types/script/src/proxy.d.ts +132 -0
  242. package/dist/types/script/src/room.d.ts +162 -0
  243. package/dist/types/script/src/sources.d.ts +73 -0
  244. package/dist/types/sync/src/backoff.d.ts +9 -0
  245. package/dist/types/sync/src/blobSection.d.ts +23 -0
  246. package/dist/types/sync/src/capabilities.d.ts +20 -0
  247. package/dist/types/sync/src/client.d.ts +253 -0
  248. package/dist/types/sync/src/framing.d.ts +35 -0
  249. package/dist/types/sync/src/hash.d.ts +2 -0
  250. package/dist/types/sync/src/index.d.ts +19 -0
  251. package/dist/types/sync/src/leases.d.ts +82 -0
  252. package/dist/types/sync/src/openToken.d.ts +104 -0
  253. package/dist/types/sync/src/protocol.d.ts +484 -0
  254. package/dist/types/sync/src/relay.d.ts +52 -0
  255. package/dist/types/sync/src/replicaVersions.d.ts +17 -0
  256. package/dist/types/sync/src/saveMachine.d.ts +83 -0
  257. package/dist/types/sync/src/saveRun.d.ts +52 -0
  258. package/dist/types/sync/src/transport.d.ts +19 -0
  259. package/package.json +229 -4
@@ -0,0 +1,1967 @@
1
+ const ye = "kition-kit-ui/1", St = (e) => typeof e == "object" && e !== null && e.kitionKitUi === 1;
2
+ function Et(e) {
3
+ return St(e) && typeof e.ready == "string" && typeof e.id == "string";
4
+ }
5
+ function $t(e) {
6
+ if (!e || typeof e != "object" || Array.isArray(e)) return null;
7
+ const t = e, n = {};
8
+ for (const r of ["objectId", "path", "sheet", "cell", "blockId"])
9
+ typeof t[r] == "string" && t[r] && (n[r] = t[r]);
10
+ for (const r of ["page", "slide"])
11
+ Number.isInteger(t[r]) && t[r] >= 1 && (n[r] = t[r]);
12
+ return typeof t.time == "number" && Number.isFinite(t.time) && t.time >= 0 && (n.time = t.time), Array.isArray(t.heading) && t.heading.length && t.heading.every((r) => typeof r == "string") && (n.heading = [...t.heading]), Object.keys(n).length ? n : null;
13
+ }
14
+ function xt(e) {
15
+ if (e == null) return { download: !0, export: !0, share: !0 };
16
+ const t = typeof e == "object" && !Array.isArray(e) ? e : {};
17
+ return { download: t.download === !0, export: t.export === !0, share: t.share === !0 };
18
+ }
19
+ const Wn = "held", jt = 256, ae = (e) => typeof e == "object" && e !== null && !Array.isArray(e);
20
+ function Lt(e) {
21
+ if (!ae(e)) return null;
22
+ const { object: t, field: n, offset: r } = e;
23
+ return typeof t == "string" && typeof n == "string" && typeof r == "number" && Number.isInteger(r) && r >= 0 ? { object: t, field: n, offset: r } : null;
24
+ }
25
+ function ct(e) {
26
+ if (!ae(e)) return null;
27
+ const t = Array.isArray(e.selection) ? e.selection.filter((i) => typeof i == "string").slice(0, jt) : [], n = Lt(e.caret), r = ae(e.viewport) ? e.viewport : null;
28
+ return { selection: t, ...n ? { caret: n } : {}, ...r ? { viewport: r } : {} };
29
+ }
30
+ function Rt(e) {
31
+ if (!e || typeof e != "object") return null;
32
+ const { reads: t, newestAuthor: n } = e;
33
+ return !Number.isSafeInteger(t) || !Number.isSafeInteger(n) || n <= t || t < 0 ? null : { reads: t, newestAuthor: n };
34
+ }
35
+ const lt = "fh_", It = ["ai-field", "rewrite"], Ct = /^[a-z][a-z0-9-]{0,62}$/;
36
+ function Ot(e, t) {
37
+ if (typeof e != "string") return !1;
38
+ if (It.includes(e)) return !0;
39
+ if (!t) return !1;
40
+ const n = t.startsWith("kit.") ? t.slice(4) : t;
41
+ return e.startsWith(`${n}.`) && Ct.test(e.slice(n.length + 1));
42
+ }
43
+ const Tt = "action:", Pt = "service:", dt = ["file.pick", "image.insert", "people.mention", "people.notify", "share.open", "file.rename", "file.saveAs", "access.request", "editor.close", "comment.create"], _t = ["not-allowed", "no-gesture", "cancelled", "not-found", "failed"];
44
+ function qt(e, t) {
45
+ const n = t.readOnly !== !0, r = n || t.comments?.canComment === !0, i = xt(t.permissions);
46
+ switch (e) {
47
+ case "comment.create":
48
+ case "people.mention":
49
+ case "people.notify":
50
+ return r;
51
+ case "file.pick":
52
+ case "image.insert":
53
+ case "file.rename":
54
+ return n;
55
+ case "file.saveAs":
56
+ return i.download || i.export;
57
+ case "share.open":
58
+ return i.share;
59
+ case "access.request":
60
+ case "editor.close":
61
+ return !0;
62
+ }
63
+ }
64
+ const Ke = 2e3, Ut = 256, Nt = 256, Mt = 500, Dt = /[\u0000-\u001f\u007f-\u009f]/, Kt = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/, ft = /[\u202a-\u202e\u2066-\u2069\u200e\u200f\u061c]/, de = (e) => !Dt.test(e) && !ft.test(e), Ce = (e) => !Kt.test(e) && !ft.test(e);
65
+ function Oe(e) {
66
+ if (!e || typeof e != "object" || Array.isArray(e)) return null;
67
+ const t = e, n = Array.isArray(t.ids) ? t.ids.filter((o) => typeof o == "string" && o.length > 0 && o.length <= 256 && de(o)) : [];
68
+ if (!n.length || n.length > Nt || n.length !== t.ids.length) return null;
69
+ const r = { ids: n }, i = t.range;
70
+ if (i !== void 0) {
71
+ const { start: o, end: a } = i ?? {};
72
+ if (!Number.isSafeInteger(o) || !Number.isSafeInteger(a) || o < 0 || a < o) return null;
73
+ r.range = { start: o, end: a };
74
+ }
75
+ for (const o of ["quote", "label"]) {
76
+ const a = t[o];
77
+ if (a !== void 0) {
78
+ if (typeof a != "string" || a.length > Mt || !(o === "label" ? de(a) : Ce(a))) return null;
79
+ r[o] = a;
80
+ }
81
+ }
82
+ if (t.page !== void 0) {
83
+ if (!Number.isSafeInteger(t.page) || t.page < 0) return null;
84
+ r.page = t.page;
85
+ }
86
+ return r;
87
+ }
88
+ function zt(e) {
89
+ const t = e;
90
+ if (!t || typeof t != "object" || !dt.includes(t.service)) return null;
91
+ const n = t.service, r = t.params ?? {};
92
+ if (typeof r != "object" || Array.isArray(r)) return null;
93
+ const i = (o, a = 256, h = !1) => r[o] === void 0 || typeof r[o] == "string" && r[o].length <= a && (h ? Ce : de)(r[o]);
94
+ switch (n) {
95
+ case "file.pick":
96
+ return typeof r.purpose == "string" && Array.isArray(r.accept) && r.accept.every((o) => typeof o == "string") ? { service: n, params: r } : null;
97
+ case "image.insert":
98
+ return r.accept === void 0 || Array.isArray(r.accept) && r.accept.every((o) => typeof o == "string") ? { service: n, params: r } : null;
99
+ case "people.mention":
100
+ return typeof r.query == "string" && r.query.length <= 256 && de(r.query) && (r.limit === void 0 || Number.isSafeInteger(r.limit) && r.limit > 0 && r.limit <= 100) ? { service: n, params: r } : null;
101
+ case "people.notify": {
102
+ const o = r.people;
103
+ if (!(Array.isArray(o) && o.length > 0 && o.length <= Ut && o.every((C) => typeof C == "string" && C.length > 0 && C.length <= 256 && de(C)) && typeof r.message == "string" && r.message.length <= Ke && Ce(r.message))) return null;
104
+ if (r.anchor === void 0) return { service: n, params: r };
105
+ const h = Oe(r.anchor);
106
+ return h ? { service: n, params: { ...r, anchor: h } } : null;
107
+ }
108
+ case "share.open":
109
+ case "editor.close":
110
+ return { service: n, params: {} };
111
+ case "file.rename":
112
+ return i("name") ? { service: n, params: r } : null;
113
+ case "file.saveAs":
114
+ return r.bytes instanceof ArrayBuffer && i("name") && i("format", 32) ? { service: n, params: r } : null;
115
+ case "access.request":
116
+ return r.perm === "edit" || r.perm === "comment" ? { service: n, params: r } : null;
117
+ case "comment.create": {
118
+ const o = Oe(r.anchor);
119
+ return o && i("text", Ke, !0) ? { service: n, params: { ...r, anchor: o } } : null;
120
+ }
121
+ }
122
+ }
123
+ const Bt = ["https:", "http:", "mailto:"];
124
+ function ut(e) {
125
+ if (typeof e != "string" || !e) return !1;
126
+ try {
127
+ return Bt.includes(new URL(e).protocol);
128
+ } catch {
129
+ return !1;
130
+ }
131
+ }
132
+ function Ht(e) {
133
+ if (!ae(e)) return null;
134
+ const t = {};
135
+ for (const n of ["path", "name", "docId"])
136
+ typeof e[n] == "string" && e[n] && (t[n] = e[n]);
137
+ return Object.keys(t).length ? t : null;
138
+ }
139
+ function Ft(e) {
140
+ if (!ae(e)) return null;
141
+ const t = Ht(e.link);
142
+ if (!t) return null;
143
+ const n = $t(e.view), r = ae(e.create) ? typeof e.create.kit == "string" && e.create.kit ? { kit: e.create.kit } : {} : null;
144
+ return { link: t, ...n ? { view: n } : {}, placement: e.placement === "beside" ? "beside" : "tab", ...r ? { create: r } : {} };
145
+ }
146
+ function Vt(e) {
147
+ if (!ae(e) || typeof e.purpose != "string" || !Array.isArray(e.accept)) return null;
148
+ const t = [];
149
+ for (const n of e.accept) {
150
+ if (typeof n != "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,15}$/.test(n)) return null;
151
+ t.includes(n.toLowerCase()) || t.push(n.toLowerCase());
152
+ }
153
+ return !t.length || t.length > 64 ? null : { purpose: e.purpose.slice(0, 200), accept: t, multiple: e.multiple === !0 };
154
+ }
155
+ function Wt(e, t) {
156
+ const n = (a) => a.replace(/\\/g, "/").split("/").filter((h) => h && h !== "."), r = n(e).slice(0, -1), i = n(t);
157
+ let o = 0;
158
+ for (; o < r.length && o < i.length - 1 && r[o] === i[o]; ) o += 1;
159
+ return [...r.slice(o).map(() => ".."), ...i.slice(o)].join("/");
160
+ }
161
+ const Gt = ["image/png", "image/jpeg", "image/gif", "image/webp", "image/svg+xml", "image/avif"];
162
+ function Xt(e) {
163
+ if (typeof e != "string" || !e) return !1;
164
+ try {
165
+ return ["https:", "http:"].includes(new URL(e).protocol);
166
+ } catch {
167
+ return !1;
168
+ }
169
+ }
170
+ class z extends Error {
171
+ constructor(t, n, r) {
172
+ super(n), this.code = t, this.data = r;
173
+ }
174
+ }
175
+ function ht(e, t = [], n = 0) {
176
+ if (e instanceof ArrayBuffer) t.push(e);
177
+ else if (ArrayBuffer.isView(e) && e.buffer instanceof ArrayBuffer) t.push(e.buffer);
178
+ else if (e && typeof e == "object" && n < 4) for (const r of Object.values(e)) ht(r, t, n + 1);
179
+ return t;
180
+ }
181
+ class Yt {
182
+ constructor(t, n) {
183
+ this.port = t, this.prefix = n, t.onmessage = (r) => void this.receive(r.data), t.start();
184
+ }
185
+ next = 1;
186
+ pending = /* @__PURE__ */ new Map();
187
+ handlers = /* @__PURE__ */ new Map();
188
+ listeners = /* @__PURE__ */ new Map();
189
+ closed = !1;
190
+ /** Answers requests for `method`; a thrown error becomes a JSON-RPC error. */
191
+ handle(t, n) {
192
+ this.handlers.set(t, n);
193
+ }
194
+ on(t, n) {
195
+ let r = this.listeners.get(t);
196
+ return r || this.listeners.set(t, r = /* @__PURE__ */ new Set()), r.add(n), () => r.delete(n);
197
+ }
198
+ /** `transfer` hands the params' ArrayBuffers over instead of copying them (the sender loses them). */
199
+ request(t, n, r = {}) {
200
+ if (this.closed) return Promise.reject(new z(-32e3, "the connection is closed"));
201
+ const i = `${this.prefix}${this.next++}`;
202
+ return new Promise((o, a) => {
203
+ this.pending.set(i, { resolve: o, reject: a }), this.post({ jsonrpc: "2.0", id: i, method: t, params: n }, r.transfer);
204
+ });
205
+ }
206
+ notify(t, n) {
207
+ this.closed || this.post({ jsonrpc: "2.0", method: t, params: n });
208
+ }
209
+ close() {
210
+ this.closed = !0;
211
+ for (const t of this.pending.values()) t.reject(new z(-32e3, "the connection is closed"));
212
+ this.pending.clear(), this.port.close();
213
+ }
214
+ post(t, n = !1) {
215
+ this.port.postMessage(t, n ? ht(t.params ?? t.result) : []);
216
+ }
217
+ async receive(t) {
218
+ if (!t || t.jsonrpc !== "2.0") return;
219
+ if (t.method && t.id !== void 0) {
220
+ const r = this.handlers.get(t.method);
221
+ if (!r) return this.post({ jsonrpc: "2.0", id: t.id, error: { code: -32601, message: `${t.method} is not supported` } });
222
+ try {
223
+ const i = await r(t.params);
224
+ this.post({ jsonrpc: "2.0", id: t.id, result: i === void 0 ? {} : i });
225
+ } catch (i) {
226
+ const o = i instanceof z ? i : new z(-32e3, i instanceof Error ? i.message : String(i));
227
+ this.post({ jsonrpc: "2.0", id: t.id, error: { code: o.code, message: o.message, data: o.data } });
228
+ }
229
+ return;
230
+ }
231
+ if (t.method) {
232
+ for (const r of this.listeners.get(t.method) ?? []) r(t.params);
233
+ return;
234
+ }
235
+ if (t.id === void 0) return;
236
+ const n = this.pending.get(t.id);
237
+ n && (this.pending.delete(t.id), t.error ? n.reject(new z(t.error.code, t.error.message, t.error.data)) : n.resolve(t.result));
238
+ }
239
+ }
240
+ function N(e, t) {
241
+ return new z(-32e3, t, { reason: e });
242
+ }
243
+ const oe = (e) => new z(-32602, e), ze = (e) => Object.prototype.toString.call(e) === "[object ArrayBuffer]";
244
+ function ne(e) {
245
+ const t = e.lastIndexOf(".");
246
+ return t > 0 ? e.slice(t + 1).toLowerCase() : "";
247
+ }
248
+ const Jt = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;
249
+ function Be(e) {
250
+ let n = (e.split(/[\\/]/).pop() ?? "").replace(/[\u0000-\u001f\u007f<>:"|?*]/g, "").trim().replace(/^\.+/, "").replace(/[. ]+$/, "");
251
+ const r = n.indexOf("."), i = r < 0 ? n : n.slice(0, r);
252
+ if (Jt.test(i) && (n = `${i}_${n.slice(i.length)}`), n.length > 255) {
253
+ const o = ne(n);
254
+ n = o ? `${n.slice(0, 254 - o.length)}.${o}` : n.slice(0, 255);
255
+ }
256
+ return n || "Untitled";
257
+ }
258
+ async function Zt(e, t) {
259
+ const n = e.lastIndexOf("."), [r, i] = n > 0 ? [e.slice(0, n), e.slice(n)] : [e, ""];
260
+ for (let o = 1; o < 1e4; o += 1) {
261
+ const a = o === 1 ? e : `${r} ${o}${i}`;
262
+ if (!await t(a)) return a;
263
+ }
264
+ throw N("io-error", "no unused name is left for this file");
265
+ }
266
+ function He() {
267
+ const e = new Uint8Array(16);
268
+ return crypto.getRandomValues(e), lt + Array.from(e, (t) => t.toString(16).padStart(2, "0")).join("");
269
+ }
270
+ const Qt = (e) => e.split(/[\\/]/).filter(Boolean).pop() ?? e, en = () => globalThis.navigator?.userActivation?.isActive ?? !0, Ee = (e) => (e ?? []).map((t) => t.replace(/^\./, "").toLowerCase());
271
+ function tn(e, t, n) {
272
+ let r = [];
273
+ return {
274
+ append: async (i) => void r.push(i),
275
+ commit: async () => {
276
+ const i = new Uint8Array(r.reduce((h, C) => h + C.byteLength, 0));
277
+ let o = 0;
278
+ for (const h of r)
279
+ i.set(h, o), o += h.byteLength;
280
+ const a = await e.commit(t(), i, n());
281
+ return r = [], a;
282
+ },
283
+ abort: async () => {
284
+ r = [];
285
+ }
286
+ };
287
+ }
288
+ const nn = ["files/pick", "files/create", "files/stat", "files/read", "files/list", "files/write", "files/release", "files/print"];
289
+ function rn(e) {
290
+ const { storage: t } = e, n = He().slice(lt.length), r = { read: Ee(e.manifest?.read), create: Ee(e.manifest?.create), folders: e.manifest?.folders === !0, print: e.manifest?.print === !0 }, i = t.name ?? Qt, o = e.gesture ?? en, a = /* @__PURE__ */ new Map();
291
+ let h = !1, C = 0;
292
+ const F = ["files", ...e.pick ? ["files-pick"] : [], ...e.print ? ["print"] : []], E = (c) => ({
293
+ handle: c.handle,
294
+ name: c.name,
295
+ kind: c.kind,
296
+ ...c.size !== void 0 ? { size: c.size } : {},
297
+ ...c.mime !== void 0 ? { mime: c.mime } : {},
298
+ version: c.version,
299
+ rights: [...c.rights]
300
+ }), j = (c, d, m, v, k = {}) => {
301
+ const y = {
302
+ handle: He(),
303
+ session: n,
304
+ kit: e.kit,
305
+ principal: e.principal,
306
+ flow: v,
307
+ rights: m,
308
+ kind: d?.kind ?? "file",
309
+ name: k.name ?? i(c),
310
+ ref: c,
311
+ folder: k.folder ?? null,
312
+ accept: k.accept ?? [],
313
+ mime: k.mime ?? d?.mime,
314
+ version: d?.version ?? null,
315
+ size: d?.size,
316
+ committed: !1,
317
+ staging: null,
318
+ staged: 0,
319
+ written: 0,
320
+ expected: null
321
+ };
322
+ a.set(y.handle, y);
323
+ const { handle: H, session: Q, kit: ee, principal: re, kind: ce, name: ue } = y;
324
+ return e.log?.({ handle: H, session: Q, kit: ee, principal: re, flow: v, rights: [...m], kind: ce, name: ue }), y;
325
+ }, q = (c, d, m) => {
326
+ if (h) throw N("file-not-granted", "the session has ended");
327
+ const v = typeof c == "string" ? a.get(c) : void 0;
328
+ if (!v) throw N("file-not-granted", "this handle was not granted to this session");
329
+ if (d && !v.rights.includes(d)) throw N("file-not-granted", `this handle has no ${d} right`);
330
+ if (m && v.kind !== m) throw N("file-not-granted", `this handle is not a ${m}`);
331
+ return v;
332
+ }, w = async (c) => {
333
+ try {
334
+ return await c();
335
+ } catch (d) {
336
+ throw d instanceof z ? d : N("io-error", "the host could not reach the file");
337
+ }
338
+ }, _ = async (c) => {
339
+ a.delete(c.handle);
340
+ const d = c.staging;
341
+ c.staging = null, d && await d.abort().catch(() => {
342
+ });
343
+ }, B = (c) => {
344
+ if (!o()) throw N("no-gesture", `${c} needs a person's gesture in the kit`);
345
+ }, g = async (c, d) => {
346
+ const m = new Set([...a.values()].filter((k) => k.rights.includes("create") && k.kind === "file" && !k.committed).map((k) => k.ref)), v = await Zt(d, async (k) => {
347
+ const y = t.child(c, k);
348
+ return m.has(y) || await t.stat(y) !== null;
349
+ });
350
+ return { name: v, ref: t.child(c, v) };
351
+ }, I = (c, d = r.read) => {
352
+ const m = ne(c);
353
+ if (!r.read.includes(m) || !d.includes(m)) throw N("not-allowed", `the kit may not read .${m || "(none)"} files`);
354
+ }, $ = (c) => {
355
+ const d = ne(c);
356
+ if (!r.create.includes(d)) throw N("not-allowed", `the kit may not create .${d || "(none)"} files`);
357
+ }, T = (c, d) => {
358
+ const m = Ee(c);
359
+ if (m.some((v) => !d.includes(v))) throw N("not-allowed", "the kit asked for a file type its manifest does not declare");
360
+ return m.length ? m : d;
361
+ }, l = async (c) => {
362
+ if (!e.pick) throw N("unsupported", "this host has no picker");
363
+ if (c?.mode !== "open" && c?.mode !== "folder" && c?.mode !== "save") throw oe("mode is open, folder, or save");
364
+ if (B("files/pick"), c.mode === "folder" && !r.folders) throw N("not-allowed", "the kit may not ask for folders");
365
+ const d = T(c.accept, c.mode === "save" ? r.create : r.read);
366
+ c.mode === "save" && c.suggestedName != null && $(Be(c.suggestedName));
367
+ const m = await w(() => e.pick(c)), v = [];
368
+ for (const k of c.mode === "open" && !c.multiple ? m.slice(0, 1) : m) {
369
+ const y = await w(() => t.stat(k));
370
+ if (c.mode === "folder") {
371
+ if (y?.kind !== "folder") continue;
372
+ const H = r.create.length ? ["read", "create"] : ["read"];
373
+ v.push(E(j(k, y, H, "pick", { accept: d })));
374
+ } else if (c.mode === "open") {
375
+ if (y?.kind !== "file" || !d.includes(ne(i(k)))) continue;
376
+ v.push(E(j(k, y, ["read"], "pick")));
377
+ } else {
378
+ if (!d.includes(ne(i(k)))) throw N("not-allowed", "the kit may not create this file type");
379
+ if (y?.kind === "folder") continue;
380
+ if (y && e.readOnly) throw N("not-allowed", "a read-only session replaces no file");
381
+ v.push(E(j(k, y, y ? ["write"] : ["create"], "pick")));
382
+ break;
383
+ }
384
+ }
385
+ return { files: v };
386
+ }, s = async (c) => {
387
+ if (typeof c?.suggestedName != "string") throw oe("suggestedName is a string");
388
+ const d = c.folder === void 0 ? null : q(c.folder, "create", "folder"), m = Be(c.suggestedName);
389
+ $(m);
390
+ const { name: v, ref: k } = await w(() => g(d?.ref ?? null, m));
391
+ return E(j(k, null, ["create"], "create", { name: v, folder: d?.ref ?? null, mime: typeof c.mime == "string" ? c.mime : void 0 }));
392
+ }, u = async ({ handle: c, offset: d, length: m }) => {
393
+ const v = q(c, "read", "file"), k = d ?? 0;
394
+ if (!Number.isSafeInteger(k) || k < 0 || m !== void 0 && (!Number.isSafeInteger(m) || m < 0)) throw oe("offset and length are whole numbers");
395
+ const y = await w(() => t.read(v.ref, k, m));
396
+ return v.version = y.version, v.size = y.size, y;
397
+ }, f = async ({ handle: c }) => {
398
+ const d = q(c, "read", "folder"), m = await w(() => t.list(d.ref)), v = [];
399
+ for (const k of m) {
400
+ if (!d.accept.includes(ne(i(k))) || !r.read.includes(ne(i(k)))) continue;
401
+ const y = await w(() => t.stat(k));
402
+ y?.kind === "file" && v.push(E(j(k, y, ["read"], "list")));
403
+ }
404
+ return { files: v };
405
+ }, b = async (c) => {
406
+ const d = q(c?.handle, void 0, "file"), m = d.rights.includes("create");
407
+ if (!m && !d.rights.includes("write")) throw N("file-not-granted", "this handle has no create or write right");
408
+ if (m && d.committed) throw N("already-committed", "this file was already committed");
409
+ if (!ze(c.bytes)) throw oe("bytes is an ArrayBuffer");
410
+ if (c.offset !== d.staged) throw oe(`offset is ${d.staged}, the bytes staged so far`);
411
+ const v = c.bytes.byteLength;
412
+ if (e.quota?.perGrant !== void 0 && d.written + v > e.quota.perGrant || e.quota?.perSession !== void 0 && C + v > e.quota.perSession)
413
+ throw N("quota", "this write passes the host's cap");
414
+ if (c.final && !m) {
415
+ if (typeof c.expected != "string") throw N("conflict", "the final chunk carries the version it replaces");
416
+ if (await w(() => t.unsaved?.(d.ref) ?? !1)) throw N("unsaved-edits", "the file is open with unsaved edits");
417
+ d.expected = c.expected;
418
+ }
419
+ if (!d.staging) {
420
+ const H = () => m ? { mode: "create" } : { mode: "replace", expected: d.expected ?? "" };
421
+ d.staging = t.stage ? t.stage(d.ref, H) : tn(t, () => d.ref, H);
422
+ }
423
+ const k = d.staging;
424
+ if (await w(() => k.append(new Uint8Array(c.bytes.slice(0)))), d.staged += v, d.written += v, C += v, !c.final) return {};
425
+ const y = await x(d, k, m);
426
+ return d.staging = null, d.staged = 0, d.expected = null, d.version = y.version, m && (d.committed = !0), { version: y.version };
427
+ }, x = async (c, d, m) => {
428
+ for (let v = 0; ; v += 1)
429
+ try {
430
+ return await w(() => d.commit());
431
+ } catch (k) {
432
+ const y = k instanceof z && k.data?.reason === "conflict";
433
+ if (!m || !y || c.flow !== "create" || t.stage || v >= 8) throw k;
434
+ const H = await w(() => g(c.folder, c.name));
435
+ c.ref = H.ref, c.name = H.name;
436
+ }
437
+ }, S = async ({ handles: c }) => {
438
+ for (const d of Array.isArray(c) ? c : []) {
439
+ const m = typeof d == "string" ? a.get(d) : void 0;
440
+ m && await _(m);
441
+ }
442
+ return {};
443
+ }, P = async (c) => {
444
+ if (!e.print) throw N("unsupported", "this host does not print");
445
+ if (!r.print) throw N("not-allowed", "the kit may not print");
446
+ B("files/print");
447
+ let d;
448
+ if (!c || typeof c != "object") throw oe("a print takes PDF bytes or a handle");
449
+ if ("handle" in c) {
450
+ const v = q(c.handle, "read", "file");
451
+ if (ne(v.name) !== "pdf" && v.mime !== "application/pdf") throw N("not-allowed", "only a PDF prints");
452
+ d = await O(v.ref);
453
+ } else {
454
+ if (c.mime !== "application/pdf" || !ze(c.bytes)) throw oe("a print takes PDF bytes or a handle");
455
+ d = new Uint8Array(c.bytes.slice(0));
456
+ }
457
+ const m = typeof c.title == "string" ? c.title : "";
458
+ return { printed: await w(() => e.print({ bytes: d, title: m })) === !0 };
459
+ }, O = async (c) => {
460
+ const d = [];
461
+ let m = 0;
462
+ for (; ; ) {
463
+ const { bytes: y, size: H } = await w(() => t.read(c, m, void 0));
464
+ if (d.push(new Uint8Array(y)), m += y.byteLength, m >= H || y.byteLength === 0) break;
465
+ }
466
+ const v = new Uint8Array(m);
467
+ let k = 0;
468
+ for (const y of d)
469
+ v.set(y, k), k += y.byteLength;
470
+ return v;
471
+ }, M = {
472
+ "files/pick": l,
473
+ "files/create": s,
474
+ "files/stat": async ({ handle: c }) => {
475
+ const d = q(c);
476
+ if (d.rights.includes("create") && !d.committed && d.kind === "file") return E(d);
477
+ const m = await w(() => t.stat(d.ref));
478
+ if (!m) throw N("file-not-granted", "the file is gone");
479
+ return Object.assign(d, { version: m.version, size: m.size, mime: m.mime ?? d.mime }), E(d);
480
+ },
481
+ "files/read": u,
482
+ "files/list": f,
483
+ "files/write": b,
484
+ "files/release": S,
485
+ "files/print": P
486
+ };
487
+ return {
488
+ id: n,
489
+ capabilities: F,
490
+ grant: async (c, d, { flow: m, approved: v }) => {
491
+ if (h) throw N("file-not-granted", "the session has ended");
492
+ const k = await w(() => t.stat(c)), y = i(c);
493
+ if (d.includes("write")) {
494
+ if (e.readOnly) throw N("not-allowed", "a read-only session replaces no file");
495
+ if (m === "agent" && v !== !0) throw N("not-allowed", "an agent replaces a file only through a draft or the person's approval");
496
+ if (k?.kind !== "file") throw N("not-allowed", "there is no such file to replace");
497
+ $(y);
498
+ }
499
+ if (d.includes("read")) {
500
+ if (!k) throw N("not-allowed", "there is no such file");
501
+ if (k.kind === "file") I(y);
502
+ else if (!r.folders) throw N("not-allowed", "the kit may not read folders");
503
+ }
504
+ if (d.includes("create") && (!k || k.kind === "file")) {
505
+ if (k) throw N("not-allowed", "a create grant never names an existing file");
506
+ $(y);
507
+ }
508
+ return E(j(c, k, [...new Set(d)], m, k?.kind === "folder" ? { accept: r.read } : {}));
509
+ },
510
+ revoke: async (c) => {
511
+ const d = [];
512
+ for (const m of c) {
513
+ const v = a.get(m);
514
+ v && (await _(v), d.push(m));
515
+ }
516
+ d.length && e.revoked?.(d);
517
+ },
518
+ grants: () => [...a.values()].map(({ handle: c, session: d, kit: m, principal: v, flow: k, rights: y, kind: H, name: Q }) => ({ handle: c, session: d, kit: m, principal: v, flow: k, rights: [...y], kind: H, name: Q })),
519
+ serve: async (c, d) => {
520
+ if (e.trace?.(c, d), h) throw N("file-not-granted", "the session has ended");
521
+ return M[c](d);
522
+ },
523
+ end: async () => {
524
+ h = !0;
525
+ for (const c of [...a.values()]) await _(c);
526
+ }
527
+ };
528
+ }
529
+ function Fe(e) {
530
+ if (/^([A-Za-z]:)?[\\/]/.test(e)) return null;
531
+ const t = [];
532
+ for (const n of e.replace(/\\/g, "/").split("/"))
533
+ if (!(!n || n === "."))
534
+ if (n === "..") {
535
+ if (!t.length) return null;
536
+ t.pop();
537
+ } else t.push(n);
538
+ return t.length ? t.join("/") : null;
539
+ }
540
+ function on(e, t, n) {
541
+ const r = Fe(e), i = [];
542
+ for (const o of n) {
543
+ const a = typeof o?.path == "string" ? Fe(o.path) : null;
544
+ if (!a || a === r || a.split("/").some((E) => E.startsWith("."))) continue;
545
+ const h = a.split("/").pop(), C = h.includes(".") ? h.slice(h.lastIndexOf(".") + 1).toLowerCase() : "";
546
+ if (!t.accept.includes(C)) continue;
547
+ const F = { path: Wt(e, a), name: h, version: typeof o.version == "string" ? o.version : null };
548
+ if (i.some((E) => E.path === F.path) || i.push(F), !t.multiple) break;
549
+ }
550
+ return i;
551
+ }
552
+ function Y(e) {
553
+ throw new z(-32601, `${e} is not supported by this host`);
554
+ }
555
+ function sn(e, t) {
556
+ const { handlers: n } = t, r = { agent: n.openAgent, "pick-file": n.pick, replica: n.replicaRead && n.replicaWrite, customize: n.customize, lease: n.leases, presence: n.presence }, i = Object.entries(r).filter(([, E]) => E).map(([E]) => E);
557
+ n.generate && i.push("generate"), n.open && i.push("open-file"), n.openUrl && i.push("open-url");
558
+ const o = t.document.readOnly === !0;
559
+ n.pickLinks && !o && i.push("links-pick"), n.fetchImage && !o && i.push("fetch-image");
560
+ const a = Object.entries(n.actions ?? {}).filter(([, E]) => typeof E == "function");
561
+ i.push(...a.map(([E]) => `${Tt}${E}`));
562
+ const h = Object.entries(n.services ?? {}).filter(([E, j]) => typeof j == "function" && dt.includes(E) && qt(E, t.document));
563
+ i.push(...h.map(([E]) => `${Pt}${E}`)), n.comments && i.push("comment-anchors"), t.files && i.push("files", ...t.files.pick ? ["files-pick"] : [], ...t.files.print ? ["print"] : []);
564
+ const C = t.timeoutMs ?? 12e4, F = (E, j) => {
565
+ const q = new MessageChannel(), w = new Yt(q.port1, "h");
566
+ let _ = null;
567
+ w.handle("host/read", (l) => n.read(l)), w.handle("host/stamp", (l) => n.stamp(l)), w.handle("host/write", (l) => n.write(l)), w.handle("host/pick", (l) => n.pick ? n.pick(l) : Y("host/pick")), w.handle("host/openAgent", async (l) => (n.openAgent || Y("host/openAgent"), await n.openAgent(l), {}));
568
+ const { replicaRead: B, replicaWrite: g } = n;
569
+ w.handle("host/replicaRead", (l) => B && g ? B(l) : Y("host/replicaRead")), w.handle("host/replicaWrite", async (l) => ((!B || !g) && Y("host/replicaWrite"), await g(l), {})), w.handle("host/customize", async (l) => (n.customize || Y("host/customize"), await n.customize(l), {})), w.handle("host/leaseAcquire", (l) => n.leases ? n.leases.acquire(l) : Y("host/leaseAcquire")), w.handle("host/leaseRelease", async (l) => (n.leases || Y("host/leaseRelease"), await n.leases.release(l), {})), w.handle("host/leases", async () => (n.leases || Y("host/leases"), { leases: await n.leases.list() })), w.handle("host/generate", (l) => {
570
+ if (n.generate || Y("host/generate"), !Ot(l?.purpose, _)) throw new z(-32e3, `a kit may not generate for ${JSON.stringify(l?.purpose)}`, { reason: "not-allowed" });
571
+ return n.generate(l);
572
+ }), w.handle("host/action", (l) => {
573
+ const s = typeof l?.id == "string" ? a.find(([u]) => u === l.id)?.[1] : void 0;
574
+ if (!s) throw new z(-32e3, `this host does not serve the action ${String(l?.id)}`, { reason: "not-allowed" });
575
+ return s(l.params && typeof l.params == "object" ? l.params : {});
576
+ }), w.handle("host/open", async (l) => {
577
+ n.open || Y("host/open");
578
+ const s = Ft(l);
579
+ if (!s) throw new z(-32602, "host/open needs a link with a path, a name, or a docId");
580
+ return { opened: (await n.open(s))?.opened !== !1 };
581
+ }), w.handle("host/openUrl", async (l) => {
582
+ if (n.openUrl || Y("host/openUrl"), !ut(l?.url)) throw new z(-32e3, "a host opens only https:, http:, and mailto: addresses", { reason: "not-allowed" });
583
+ return { opened: (await n.openUrl({ url: l.url }))?.opened !== !1 };
584
+ }), w.handle("host/fetchImage", async (l) => {
585
+ if (n.fetchImage || Y("host/fetchImage"), o) throw new z(-32e3, "a read-only document fetches no pictures", { reason: "read-only" });
586
+ if (!Xt(l?.url)) throw new z(-32e3, "a host fetches only https: and http: addresses", { reason: "not-allowed" });
587
+ const s = await n.fetchImage({ url: l.url });
588
+ if (!(s?.bytes instanceof ArrayBuffer) || !Gt.includes(s.mime)) throw new z(-32e3, `${l.url} is not a picture`, { reason: "unsupported" });
589
+ return { bytes: s.bytes, mime: s.mime };
590
+ }), w.handle("links/pick", async (l) => {
591
+ if (n.pickLinks || Y("links/pick"), o) throw new z(-32e3, "a read-only document links no files", { reason: "read-only" });
592
+ const s = Vt(l);
593
+ if (!s) throw new z(-32602, "links/pick needs a purpose and at least one extension without the dot");
594
+ return { links: on(t.document.path, s, await n.pickLinks(s) ?? []) };
595
+ });
596
+ const I = t.files ? rn({ ...t.files, readOnly: o, revoked: (l) => w.notify("files/revoked", { handles: l }) }) : null;
597
+ if (I) for (const l of nn) w.handle(l, (s) => I.serve(l, s));
598
+ w.on("document/conflicts", (l) => n.conflicts?.(l)), w.on("document/schema", (l) => {
599
+ const s = Rt(l);
600
+ s && n.schema?.(s);
601
+ }), w.on("draft/changed", (l) => n.draftChanged?.(l)), w.on("presence/set", (l) => {
602
+ const s = ct(l);
603
+ s && n.presence?.(s);
604
+ }), w.on("document/changed", (l) => n.changed(l)), w.on("replica/changed", (l) => n.replicaChanged?.(l)), w.on("host/notify", (l) => n.notify?.(l)), w.on("host/shortcut", (l) => n.shortcut?.(l)), w.on("ui/action", (l) => n.action?.(l)), w.handle("host/service", (l) => {
605
+ const s = l?.service, u = h.find(([b]) => b === s)?.[1];
606
+ if (!u) throw new z(-32e3, `this host does not serve ${String(s)}`, { reason: "not-allowed" });
607
+ const f = zt(l);
608
+ if (!f) throw new z(-32602, `bad params for ${String(s)}`);
609
+ return u(f.params);
610
+ }), w.on("comments/activated", (l) => {
611
+ typeof l?.id == "string" && l.id && n.comments?.activated(l.id);
612
+ }), E.postMessage({ kitionKitUi: 1, protocol: ye, id: j }, t.origin, [q.port2]);
613
+ const $ = { ...t.document, bytes: t.document.bytes?.slice(0) }, T = w.request(
614
+ "ui/initialize",
615
+ { protocol: ye, host: t.host, document: $, theme: t.theme, locale: t.locale, shortcuts: t.shortcuts, capabilities: i, capabilitySets: t.capabilitySets ?? [], ui: t.ui },
616
+ { transfer: !0 }
617
+ );
618
+ return T.then(
619
+ (l) => {
620
+ _ = typeof l?.kit?.id == "string" ? l.kit.id : null;
621
+ },
622
+ () => {
623
+ }
624
+ ), { peer: w, files: I, initialized: T };
625
+ };
626
+ return new Promise((E, j) => {
627
+ let q = null;
628
+ const w = ($) => {
629
+ $?.peer.close(), $?.files?.end();
630
+ }, _ = () => {
631
+ clearTimeout(g), window.removeEventListener("message", I), t.signal?.removeEventListener("abort", B);
632
+ }, B = () => {
633
+ _(), w(q), j(new Error("the kit mount was abandoned"));
634
+ };
635
+ if (t.signal?.aborted) {
636
+ j(new Error("the kit mount was abandoned"));
637
+ return;
638
+ }
639
+ t.signal?.addEventListener("abort", B);
640
+ const g = setTimeout(() => {
641
+ _(), w(q), j(new Error("the kit did not open the document in time"));
642
+ }, C), I = ($) => {
643
+ if ($.source !== e.contentWindow || !Et($.data) || $.data.ready !== ye || t.origin !== "*" && $.origin !== t.origin || q?.id === $.data.id) return;
644
+ w(q);
645
+ const { peer: T, files: l, initialized: s } = F($.source, $.data.id);
646
+ q = { peer: T, files: l, id: $.data.id }, s.then(
647
+ (u) => {
648
+ q?.peer === T && (_(), E(an(T, u, l)));
649
+ },
650
+ (u) => {
651
+ q?.peer === T && (_(), l?.end(), j(u instanceof Error ? u : new Error(String(u))));
652
+ }
653
+ );
654
+ };
655
+ window.addEventListener("message", I), e.contentWindow?.postMessage({ kitionKitUi: 1, hello: ye }, t.origin);
656
+ });
657
+ }
658
+ function an(e, t, n) {
659
+ return {
660
+ kit: t.kit,
661
+ capabilities: t.capabilities,
662
+ state: () => e.request("document/state", {}),
663
+ save: () => e.request("document/save", {}),
664
+ fileChanged: (r) => e.notify("document/fileChanged", { version: r }),
665
+ fileHeld: (r) => e.notify("document/held", { version: r }),
666
+ setTheme: (r) => e.notify("ui/theme", { theme: r }),
667
+ setLocale: (r) => e.notify("ui/locale", { locale: r }),
668
+ focus: () => e.notify("ui/focus", {}),
669
+ configure: (r) => e.notify("ui/configure", { ui: r }),
670
+ leasesChanged: (r) => e.notify("lease/changed", { leases: r }),
671
+ peersChanged: (r) => e.notify("presence/peers", { peers: r }),
672
+ reveal: (r) => e.notify("document/reveal", { view: r }),
673
+ showComments: (r) => {
674
+ const i = r.flatMap((o) => {
675
+ const a = Oe(o.anchor);
676
+ return a && typeof o.id == "string" ? [{ id: o.id, anchor: a, resolved: o.resolved === !0, count: Number.isSafeInteger(o.count) ? o.count : 0 }] : [];
677
+ });
678
+ e.notify("comments/show", { threads: i });
679
+ },
680
+ locateComments: async (r) => {
681
+ if (!t.capabilities.includes("comment-anchors")) return r.map(() => !1);
682
+ const { found: i } = await e.request("comments/locate", { anchors: r });
683
+ return r.map((o, a) => i?.[a] === !0);
684
+ },
685
+ onPresence: (r) => e.on("presence/set", (i) => {
686
+ const o = ct(i);
687
+ o && r(o);
688
+ }),
689
+ elements: () => e.request("ui/elements", {}),
690
+ check: async (r) => t.capabilities.includes("check") ? (await e.request("document/check", r?.draft ? { draft: !0 } : {})).diagnostics : [],
691
+ ai: {
692
+ inspect: (r) => e.request("ai/inspect", r ?? {}),
693
+ commands: (r) => e.request("ai/commands", { query: r }),
694
+ run: (r, i, o) => e.request("ai/run", {
695
+ steps: r,
696
+ save: i,
697
+ ...o?.draft ? { draft: !0 } : {},
698
+ ...o?.origin ? { origin: o.origin } : {},
699
+ ...o?.originLabel != null ? { originLabel: o.originLabel } : {}
700
+ }),
701
+ preview: (r, i) => e.request("ai/preview", i?.draft ? { maxSize: r, draft: !0 } : { maxSize: r }),
702
+ version: async () => (await e.request("ai/version", {})).version,
703
+ premise: (r, i) => e.request("ai/premise", { method: r, params: i }),
704
+ changes: (r, i) => e.request("ai/changes", i ? { since: r, schema: i } : { since: r })
705
+ },
706
+ draft: {
707
+ state: () => e.request("draft/state", {}),
708
+ ready: () => e.request("draft/ready", {}),
709
+ reopen: () => e.request("draft/reopen", {}),
710
+ compare: (r) => e.request("draft/compare", r ?? {}),
711
+ merge: (r, i) => e.request("draft/merge", i ? { origin: r, schema: i } : { origin: r }),
712
+ discard: () => e.request("draft/discard", {})
713
+ },
714
+ replica: {
715
+ version: async () => (await e.request("replica/version", {})).version,
716
+ exportChanges: (r) => e.request("replica/export", { since: r }),
717
+ importChanges: (r, i) => e.request("replica/import", { changes: r, blobs: i }),
718
+ info: async () => (await e.request("replica/info", {})).docId,
719
+ onChanged: (r) => e.on("replica/changed", (i) => r(i.version))
720
+ },
721
+ model: {
722
+ describe: (r) => e.request("model/describe", r ? { schema: r } : {}),
723
+ batch: (r) => e.request("model/batch", r)
724
+ },
725
+ files: n && { grant: n.grant, revoke: n.revoke, grants: n.grants },
726
+ close: () => {
727
+ e.close(), n?.end();
728
+ }
729
+ };
730
+ }
731
+ const cn = /* @__PURE__ */ new Set(["invalid-op", "not-found", "invalid-value", "read-only", "command-failed", "invalid-params", "not-open", "draft-required", "unknown-command", "not-allowed", "unsupported", "unavailable", "conflict", "failed"]), Ve = ["2025-06-18", "2025-03-26", "2024-11-05"], ln = 1024, dn = 40, We = 50, Ge = 200, $e = 50, fn = ["create", "set", "delete", "text.insert", "text.delete", "text.set", "text.mark", "text.unmark", "list.insert", "list.move", "list.remove", "map.set", "map.delete", "tree.insert", "tree.move", "command"];
732
+ class D extends Error {
733
+ constructor(t, n, r = null, i = null) {
734
+ super(n), this.code = t, this.index = r, this.output = i;
735
+ }
736
+ }
737
+ function J(e, t, n = "failed") {
738
+ if (e instanceof D) return e;
739
+ const r = e instanceof Error ? e.message : String(e), i = e instanceof z && e.data && typeof e.data == "object" ? e.data : {}, a = [i.code, i.reason].find((h) => typeof h == "string" && cn.has(h)) ?? (e instanceof z && e.code === -32601 ? "unsupported" : /no draft/i.test(r) ? "draft-required" : n);
740
+ return new D(a, `${t}${r}`, typeof i.index == "number" ? i.index : null);
741
+ }
742
+ function un(e, t) {
743
+ if (!t.length) return `Checked ${e}: the kit found nothing wrong.`;
744
+ const n = (i) => t.filter((o) => o.severity === i).length, r = (i, o, a) => i === 0 ? `no ${a}` : i === 1 ? `1 ${o}` : `${i} ${a}`;
745
+ return `Checked ${e}: ${r(n("error"), "error", "errors")}, ${r(n("warning"), "warning", "warnings")}, ${r(n("info"), "note", "notes")}.`;
746
+ }
747
+ function hn(e) {
748
+ if (typeof e == "string") return [e];
749
+ if (!Array.isArray(e)) return null;
750
+ const t = e.map((n) => typeof n == "string" ? n : n && typeof n == "object" && typeof n.object == "string" ? n.object : null);
751
+ return t.every((n) => n !== null) ? t : null;
752
+ }
753
+ function mn(e, t = {}) {
754
+ const n = e.kitId.replace(/^kit\./, ""), r = { kind: "agent", principal: t.principal ?? "agent", label: t.label ?? "Agent" }, i = t.draft !== !1;
755
+ let o = !1;
756
+ const a = (s) => `${n}_${s}`, h = () => ({ type: "string", enum: [e.path()], description: `The document open in the page: \`${e.path()}\`.` }), C = { type: "boolean", description: "Work on your draft of the file instead of the live document: the person reviews it and merges or discards it. Defaults to the run's mode." };
757
+ async function F() {
758
+ const s = await e.opened(), u = (x) => s.capabilities.includes(x), f = (x, S, P, O, M, c) => ({
759
+ name: a(x),
760
+ title: S,
761
+ description: P,
762
+ inputSchema: { type: "object", properties: { path: h(), ...O }, required: ["path", ...M] },
763
+ annotations: { readOnlyHint: !c, destructiveHint: !1, openWorldHint: !1 }
764
+ }), b = [
765
+ f("inspect", "Inspect", `Open the document in the page's ${n} editor and report what it holds; attaches a rendered preview. Use it before and after editing.`, { preview: { type: "boolean", description: "Attach a rendered preview image. Defaults to true." }, draft: C }, [], !1),
766
+ f("commands", "Find commands", `Search the ${n} editor's commands by keywords; pass an id to ${a("run")}.`, { query: { type: "string", description: "Keywords to match in the command id, title, or description." } }, ["query"], !1),
767
+ f(
768
+ "run",
769
+ "Run commands",
770
+ `Edit the document by running commands in order; each step is one undoable command. With \`draft\`, the steps edit your draft (never saved); call ${a("draft_ready")} when it is done.`,
771
+ {
772
+ steps: { type: "array", minItems: 1, maxItems: $e, items: { type: "object", properties: { command: { type: "string", description: `A command id from ${a("commands")}.` }, params: { type: "object", description: "Command parameters." } }, required: ["command"] } },
773
+ save: { type: "boolean", description: "Save the file after the steps. Defaults to true; a draft is never saved." },
774
+ draft: C
775
+ },
776
+ ["steps"],
777
+ !0
778
+ )
779
+ ];
780
+ return u("draft") && b.push(
781
+ f("draft_ready", "Ask for review", "Ask the person to review your draft: they see a comparison and merge it or discard it. Do not merge or discard it yourself.", {}, [], !1),
782
+ f("draft_reopen", "Reopen draft", `Take your draft back from review to keep editing it (after ${a("draft_ready")}).`, {}, [], !1)
783
+ ), u("model") && b.push(
784
+ f(
785
+ "query",
786
+ "Query objects",
787
+ `Read the document's objects from its object model: by id (\`objects\`, \`root\` for the document), or by following fields from the root (\`follow\`). Use the ids with ${a("batch")}.`,
788
+ {
789
+ objects: { type: "array", items: { type: "string" }, description: "Object ids to read; `root` is the document's root object. Defaults to the root." },
790
+ follow: { type: "string", description: "A field path from the first object (the root by default), joined with dots." },
791
+ fields: { type: "array", items: { type: "string" }, description: "Only these fields of each object. Defaults to all." },
792
+ limit: { type: "integer", minimum: 1, maximum: Ge, description: `At most this many objects. Defaults to ${We}.` },
793
+ describe: { type: "boolean", description: "Also answer the kit's object types (model.describe)." },
794
+ draft: C
795
+ },
796
+ [],
797
+ !1
798
+ ),
799
+ f(
800
+ "batch",
801
+ "Edit objects",
802
+ "Edit the document through its object model: one model/batch of `ops` as one undoable step, then `load` reads objects back. Failures answer `error.code` and the op's `index`.",
803
+ {
804
+ ops: { type: "array", maxItems: 200, items: { type: "object", properties: { op: { type: "string", enum: fn } }, required: ["op"] } },
805
+ load: { type: "array", items: { type: "object", properties: { target: { type: "string" }, fields: { type: "array", items: { type: "string" } } }, required: ["target"] } },
806
+ save: { type: "boolean", description: "Save the file after the batch. Defaults to true; a draft is never saved." },
807
+ draft: C
808
+ },
809
+ ["ops"],
810
+ !0
811
+ )
812
+ ), u("check") && b.push(f("check", "Check", `List what the kit finds wrong with the document, each with a stable \`code\`, a \`severity\`, its \`target\`, a message, and sometimes a \`fix\` command for ${a("run")}. Changes nothing.`, { draft: C }, [], !1)), b;
813
+ }
814
+ function E(s) {
815
+ const u = String(s.path ?? "").trim();
816
+ if (!u) throw new D("invalid-params", "a `path` is required");
817
+ if (u !== e.path()) throw new D("not-open", `\`${u}\` is not open in this page; the open document is \`${e.path()}\``);
818
+ return u;
819
+ }
820
+ function j(s) {
821
+ return typeof s.draft == "boolean" ? s.draft : i;
822
+ }
823
+ async function q(s) {
824
+ if (!s.capabilities.includes("draft")) throw new D("unsupported", `the ${n} editor keeps no drafts; edit live with \`draft: false\` if the page allows it`);
825
+ if (!e.editable()) throw new D("read-only", "the document is open read-only here, so it has no draft");
826
+ return s;
827
+ }
828
+ async function w(s) {
829
+ return s.capabilities.includes("draft") ? s.draft.state() : { state: "none", revision: null };
830
+ }
831
+ function _() {
832
+ if (!e.editable()) throw new D("read-only", "the document is open read-only here: it cannot be edited");
833
+ }
834
+ async function B(s, u, f) {
835
+ try {
836
+ const { png: b } = await s.ai.preview(ln, u ? { draft: !0 } : void 0);
837
+ return b ? [{ caption: u ? `Preview of your draft of \`${f}\`.` : `Preview of \`${f}\`.`, png: b }] : [];
838
+ } catch {
839
+ return [];
840
+ }
841
+ }
842
+ async function g(s, u) {
843
+ if (!s.capabilities.includes("model")) throw new D("unsupported", `the ${n} editor has no object model; use ${a("run")}`);
844
+ if (u && !s.capabilities.includes("draft-model")) throw new D("unsupported", `the ${n} editor cannot run object-model batches on a draft; edit the draft with ${a("run")}`);
845
+ return s;
846
+ }
847
+ async function I(s, u, f) {
848
+ try {
849
+ const b = await e.schema?.();
850
+ return (await s.model.batch({ origin: r, ops: [], load: f, ...u ? { draft: !0 } : {}, ...b ? { schema: b } : {} })).loaded;
851
+ } catch (b) {
852
+ throw J(b, "");
853
+ }
854
+ }
855
+ const $ = {
856
+ async inspect(s) {
857
+ const u = E(s), f = await e.opened(), b = s.draft === !0;
858
+ let x = j(s) && f.capabilities.includes("draft");
859
+ if (x && (await w(f)).state === "none") {
860
+ if (b) throw new D("draft-required", `\`${u}\` has no draft yet: edit it with \`draft: true\` first.`);
861
+ x = !1;
862
+ }
863
+ const S = await f.ai.inspect({
864
+ ...x ? { draft: !0 } : {},
865
+ ...s.context ? { context: s.context } : {},
866
+ ...typeof s.part == "number" ? { part: s.part } : {}
867
+ }).catch((M) => Promise.reject(J(M, ""))), P = s.preview === !1 ? [] : await B(f, x, u), O = typeof S.summary == "string" ? S.summary : "";
868
+ return { summary: x ? `Opened your draft of \`${u}\`: ${O}` : `Opened \`${u}\` in the page's editor: ${O}`, output: { document: S, live: !0, ...x ? { draft: !0 } : {} }, previews: P };
869
+ },
870
+ async commands(s) {
871
+ E(s);
872
+ const u = String(s.query ?? ""), f = await (await e.opened()).ai.commands(u).catch((S) => Promise.reject(J(S, ""))), b = f.slice(0, dn);
873
+ return { summary: f.length > b.length ? `${f.length} commands match \`${u}\`; showing ${b.length}. Use more specific keywords.` : `${f.length} commands match \`${u}\``, output: { commands: b, total: f.length } };
874
+ },
875
+ async run(s) {
876
+ const u = E(s), f = Array.isArray(s.steps) ? s.steps : [];
877
+ if (!f.length) throw new D("invalid-params", "`steps` must be a non-empty array");
878
+ if (f.length > $e) throw new D("invalid-params", `at most ${$e} steps`);
879
+ const b = f.findIndex((M) => typeof M?.command != "string" || !M.command);
880
+ if (b >= 0) throw new D("invalid-params", `step ${b} has no \`command\``, b);
881
+ const x = f.map((M) => ({ command: String(M.command), ...M.params && typeof M.params == "object" ? { params: M.params } : {} })), S = await e.opened();
882
+ if (j(s)) {
883
+ await q(S);
884
+ const M = await S.ai.run(x, !1, { draft: !0 }).catch((c) => Promise.reject(J(c, "on the draft: ", "command-failed")));
885
+ return {
886
+ summary: `Ran ${M.completed.length} commands on your draft of \`${u}\`; the document is unchanged until the person merges the draft. Call ${a("draft_ready")} when it is done.`,
887
+ output: { ...M, live: !0, draft: !0 },
888
+ previews: await B(S, !0, u)
889
+ };
890
+ }
891
+ _();
892
+ const P = s.save !== !1, O = await S.ai.run(x, P).catch((M) => Promise.reject(J(M, "in the page's editor: ", "command-failed")));
893
+ return { summary: `Ran ${O.completed.length} commands on \`${u}\` in the page's editor (${O.saved ? "saved" : "not saved"}).`, output: { ...O, live: !0 }, previews: await B(S, !1, u) };
894
+ },
895
+ async draft_ready(s) {
896
+ const u = E(s), b = await (await q(await e.opened())).draft.ready().catch((x) => Promise.reject(J(x, "")));
897
+ return { summary: `Your draft of \`${u}\` is ready for review; the person will merge or discard it.`, output: b };
898
+ },
899
+ async draft_reopen(s) {
900
+ const u = E(s), b = await (await q(await e.opened())).draft.reopen().catch((x) => Promise.reject(J(x, "")));
901
+ return { summary: `Your draft of \`${u}\` is back with you to keep editing.`, output: b };
902
+ },
903
+ async query(s) {
904
+ const u = E(s), f = await e.opened(), b = s.draft === !0, x = (await w(f)).state !== "none";
905
+ if (b && !x) throw new D("draft-required", `\`${u}\` has no draft yet: edit it with \`draft: true\` first.`);
906
+ const S = b || j(s) && x && f.capabilities.includes("draft-model");
907
+ await g(f, S);
908
+ let P = Array.isArray(s.objects) ? s.objects : ["root"];
909
+ if (!P.every((y) => typeof y == "string")) throw new D("invalid-params", "`objects` lists object ids");
910
+ P.length || (P = ["root"]);
911
+ const O = Math.min(Ge, Math.max(1, Number.isInteger(s.limit) ? s.limit : We)), M = s.fields == null ? null : Array.isArray(s.fields) && s.fields.every((y) => typeof y == "string") ? s.fields : null;
912
+ if (s.fields != null && !M) throw new D("invalid-params", "`fields` lists field names");
913
+ let c = P;
914
+ const d = typeof s.follow == "string" ? s.follow.trim() : "";
915
+ if (d) {
916
+ let y = [c[0]];
917
+ for (const H of d.split(".").map((Q) => Q.trim()).filter(Boolean)) {
918
+ if (/^\d+$/.test(H)) {
919
+ const re = y[Number(H)];
920
+ if (re === void 0) throw new D("not-found", `\`${d}\`: there is no item ${H} (there are ${y.length})`);
921
+ y = [re];
922
+ continue;
923
+ }
924
+ if (y.length !== 1) throw new D("invalid-params", `\`${d}\`: \`${H}\` follows ${y.length} objects; pick one by position first`);
925
+ const Q = await I(f, S, [{ target: y[0], fields: [H] }]), ee = hn(Q[0]?.fields?.[H]);
926
+ if (!ee) throw new D("invalid-params", `\`${d}\`: \`${H}\` is not a list, a tree, or a ref, so it names no objects`);
927
+ y = ee;
928
+ }
929
+ c = y;
930
+ }
931
+ const m = await I(f, S, c.slice(0, O).map((y) => ({ target: y, fields: M }))), v = { objects: m, total: c.length, live: !0, ...S ? { draft: !0 } : {} };
932
+ c.length > O && (v.truncated = !0), s.describe === !0 && (v.describe = await f.model.describe(await e.schema?.()).catch((y) => Promise.reject(J(y, ""))));
933
+ const k = m.length;
934
+ return { summary: c.length > k ? `Read ${k} of ${c.length} objects of \`${u}\`; raise \`limit\` or narrow \`follow\` for the rest.` : `Read ${k} objects of \`${u}\`.`, output: v };
935
+ },
936
+ async batch(s) {
937
+ const u = E(s), f = s.ops == null ? [] : Array.isArray(s.ops) ? s.ops : null, b = s.load == null ? [] : Array.isArray(s.load) ? s.load : null;
938
+ if (!f) throw new D("invalid-params", "`ops` is an array of operations");
939
+ if (!b) throw new D("invalid-params", "`load` is an array of `{ target, fields? }`");
940
+ if (!f.length && !b.length) throw new D("invalid-params", `\`ops\` is empty: give at least one operation (to only read, use ${a("query")})`);
941
+ if (f.length > 1 && f.some((d) => d?.op === "command"))
942
+ throw new D(
943
+ "unsupported",
944
+ `this batch runs a command among other operations, and \`${u}\` is open in its editor, where only undo could take the command back; a batch is one change, so nothing was run. Run the command with ${a("run")} (its steps are all or nothing) and the other operations in their own ${a("batch")}.`
945
+ );
946
+ const x = await e.opened(), S = j(s);
947
+ S ? await q(x) : f.length && _(), await g(x, S);
948
+ let P;
949
+ try {
950
+ const d = await e.schema?.();
951
+ P = await x.model.batch({ origin: r, ops: f, load: b, ...S ? { draft: !0 } : {}, ...d ? { schema: d } : {} });
952
+ } catch (d) {
953
+ const m = J(d, "");
954
+ throw m.index !== null ? new D(m.code, `op ${m.index}: ${m.message}`, m.index) : m;
955
+ }
956
+ const O = { refs: P.refs, results: P.results, loaded: P.loaded }, c = !S && f.length > 0 && s.save !== !1 ? (await x.save().catch((d) => Promise.reject(J(d, "the batch was applied but saving failed: ")))).saved : !1;
957
+ return {
958
+ summary: S ? `Ran ${f.length} operations on your draft of \`${u}\`; call ${a("draft_ready")} when it is done.` : `Ran ${f.length} operations on \`${u}\` in the page's editor (${c ? "saved" : "not saved"}).`,
959
+ output: { ...O, live: !0, ...S ? { draft: !0 } : { saved: c } }
960
+ };
961
+ },
962
+ async check(s) {
963
+ const u = E(s), f = await e.opened();
964
+ if (!f.capabilities.includes("check")) throw new D("unsupported", `this version of the ${n} editor cannot check documents yet; inspect the preview instead`);
965
+ const b = s.draft === !0;
966
+ let x = j(s) && f.capabilities.includes("draft") && (await w(f)).state !== "none";
967
+ if (b && !x) throw new D("draft-required", `\`${u}\` has no draft yet: edit it with \`draft: true\` first.`);
968
+ s.draft === !1 && (x = !1);
969
+ const S = await f.check(x ? { draft: !0 } : void 0).catch((P) => Promise.reject(J(P, "")));
970
+ return { summary: un(x ? `your draft of \`${u}\`` : `\`${u}\``, S), output: { diagnostics: S } };
971
+ }
972
+ };
973
+ function T(s) {
974
+ if ("ok" in s) {
975
+ const { summary: b, output: x, previews: S = [] } = s.ok, P = [{ type: "text", text: `${b}
976
+ ${JSON.stringify(x)}` }];
977
+ for (const O of S) P.push({ type: "text", text: O.caption }, { type: "image", mimeType: "image/png", data: O.png });
978
+ return { content: P, structuredContent: x, isError: !1 };
979
+ }
980
+ const { error: u } = s, f = { code: u.code, message: u.message, ...u.index !== null ? { index: u.index } : {} };
981
+ return { content: [{ type: "text", text: `${u.message}
982
+ error: ${JSON.stringify(f)}` }], structuredContent: { ...u.output ?? {}, error: f }, isError: !0 };
983
+ }
984
+ async function l(s) {
985
+ if (!s || typeof s.method != "string" || s.id === void 0) return null;
986
+ const u = s.id, f = (S) => ({ jsonrpc: "2.0", id: u, result: S }), b = (S, P) => ({ jsonrpc: "2.0", id: u, error: { code: S, message: P } });
987
+ if (o) return b(-32e3, "the editor was closed");
988
+ const x = s.params && typeof s.params == "object" ? s.params : {};
989
+ switch (s.method) {
990
+ case "initialize": {
991
+ const S = String(x.protocolVersion ?? "");
992
+ return f({
993
+ protocolVersion: Ve.includes(S) ? S : Ve[0],
994
+ capabilities: { tools: { listChanged: !1 } },
995
+ serverInfo: { name: "kition-embed", title: "Kition editor in the page", version: e.version },
996
+ instructions: `The person has \`${e.path()}\` open in a ${n} editor in their page. Call ${a("inspect")} first, find commands with ${a("commands")}, then edit with ${a("run")}${i ? " (your edits go to a draft: call " + a("draft_ready") + " when it is done; the person merges it)" : ""}. After editing, call ${a("check")} and fix the errors it reports. Failed calls answer \`error.code\`.`
997
+ });
998
+ }
999
+ case "ping":
1000
+ return f({});
1001
+ case "tools/list":
1002
+ try {
1003
+ return f({ tools: await F() });
1004
+ } catch (S) {
1005
+ return b(-32e3, S instanceof Error ? S.message : String(S));
1006
+ }
1007
+ case "tools/call": {
1008
+ const S = String(x.name ?? ""), P = S.startsWith(`${n}_`) ? S.slice(n.length + 1) : "", O = Object.hasOwn($, P) ? $[P] : void 0;
1009
+ if (!O || !(await F()).some((c) => c.name === S)) return b(-32602, `unknown tool \`${S}\``);
1010
+ const M = x.arguments && typeof x.arguments == "object" ? x.arguments : {};
1011
+ try {
1012
+ return f(T({ ok: await O(M) }));
1013
+ } catch (c) {
1014
+ return f(T({ error: J(c, "") }));
1015
+ }
1016
+ }
1017
+ default:
1018
+ return b(-32601, `unknown method \`${s.method}\``);
1019
+ }
1020
+ }
1021
+ return {
1022
+ handle: l,
1023
+ tools: F,
1024
+ close: () => {
1025
+ o = !0;
1026
+ }
1027
+ };
1028
+ }
1029
+ async function Gn(e, t, n) {
1030
+ for (; !n?.aborted; ) {
1031
+ let r;
1032
+ try {
1033
+ r = await t.next();
1034
+ } catch {
1035
+ return;
1036
+ }
1037
+ if (n?.aborted) return;
1038
+ if (!r) continue;
1039
+ const i = await e.handle(r);
1040
+ i && await t.reply(i).catch(() => {
1041
+ });
1042
+ }
1043
+ }
1044
+ const se = 64, fe = se + 8;
1045
+ function Xe(e) {
1046
+ const t = [], n = new DataView(e.buffer, e.byteOffset, e.byteLength), r = new TextDecoder();
1047
+ let i = 0;
1048
+ for (; i < e.length; ) {
1049
+ if (i + fe > e.length) throw new Error("a blob section ends inside a blob header");
1050
+ const o = r.decode(e.subarray(i, i + se)), a = Number(n.getBigUint64(i + se, !0)), h = i + fe;
1051
+ if (h + a > e.length) throw new Error("a blob section ends inside a blob");
1052
+ t.push({ hash: o, data: e.slice(h, h + a) }), i = h + a;
1053
+ }
1054
+ return t;
1055
+ }
1056
+ function Ye(e) {
1057
+ const t = new Uint8Array(e.reduce((o, a) => o + fe + a.data.length, 0)), n = new DataView(t.buffer), r = new TextEncoder();
1058
+ let i = 0;
1059
+ for (const o of e)
1060
+ t.set(r.encode(o.hash), i), n.setBigUint64(i + se, BigInt(o.data.length), !0), t.set(o.data, i + fe), i += fe + o.data.length;
1061
+ return t;
1062
+ }
1063
+ const pn = 1024;
1064
+ function wn(e) {
1065
+ return e >= 48 && e <= 57 || e >= 97 && e <= 102;
1066
+ }
1067
+ function Xn(e) {
1068
+ const t = /* @__PURE__ */ new Set(), n = new TextDecoder();
1069
+ let r = -1;
1070
+ for (let i = 0; i <= e.length; i += 1) {
1071
+ if (i < e.length && wn(e[i])) {
1072
+ r < 0 && (r = i);
1073
+ continue;
1074
+ }
1075
+ if (r >= 0) {
1076
+ const o = i - r;
1077
+ if (o >= se && o <= pn)
1078
+ for (let a = r; a + se <= i; a += 1) t.add(n.decode(e.subarray(a, a + se)));
1079
+ r = -1;
1080
+ }
1081
+ }
1082
+ return [...t];
1083
+ }
1084
+ class be extends Error {
1085
+ constructor(t, n) {
1086
+ super(n), this.code = t, this.name = "EmbedError";
1087
+ }
1088
+ }
1089
+ class xe extends be {
1090
+ constructor(t, n = null) {
1091
+ super("conflict", `${t} changed elsewhere since it was opened`), this.fileId = t, this.currentVersion = n, this.name = "EmbedConflictError";
1092
+ }
1093
+ }
1094
+ const yn = () => globalThis.navigator?.userActivation?.isActive ?? !0;
1095
+ function Je(e, t) {
1096
+ if (e.byteLength !== t.byteLength) return !1;
1097
+ for (let n = 0; n < e.byteLength; n += 1) if (e[n] !== t[n]) return !1;
1098
+ return !0;
1099
+ }
1100
+ function je(e) {
1101
+ return e.replace(/\\/g, "/").split("/").filter((t) => t && t !== ".").join("/");
1102
+ }
1103
+ const gn = 10 * 6e4, bn = 5e3;
1104
+ function Z(e, t) {
1105
+ throw new z(-32e3, t, { reason: e });
1106
+ }
1107
+ function te(e) {
1108
+ return e instanceof ArrayBuffer ? e : e.slice().buffer;
1109
+ }
1110
+ async function ge(e, t) {
1111
+ if (e.stamp) return e.stamp(t);
1112
+ if (e.info) return (await e.info(t))?.version ?? null;
1113
+ throw new Error("the storage answers neither stamp nor info");
1114
+ }
1115
+ function Ze(e) {
1116
+ return { snapshot: te(e.snapshot), blobs: te(e.blobs), fileStamp: e.fileStamp };
1117
+ }
1118
+ function vn(e) {
1119
+ const { file: t, storage: n, replicas: r, version: i } = e, o = je(t.name), a = (g) => je(g) === o, h = (g) => {
1120
+ a(g) || Z("not-allowed", `${g} is not this editor's document`);
1121
+ };
1122
+ async function C(g, I, $) {
1123
+ const T = await ge(n, t.id);
1124
+ if (($ === void 0 ? i.current : $) !== T) {
1125
+ const f = new xe(t.id, T);
1126
+ e.onConflict?.(f), Z("conflict", f.message);
1127
+ }
1128
+ await g.occupied() && Z("conflict", `${t.name} is being edited in its new version; open it again to edit it there`);
1129
+ const s = g.docKey(), u = await n.write(t.id, I, { expectedVersion: T });
1130
+ return i.current = u.version, i.written = { version: u.version, bytes: I }, i.known = I, i.carriedOver = u.version, e.onSaved(u.version), g.moved(s), u.version;
1131
+ }
1132
+ async function F(g, I) {
1133
+ const $ = e.moving?.();
1134
+ $ && (await $.catch(() => {
1135
+ }), Z("conflict", `${t.name} opened again in its new version; save again`));
1136
+ const T = e.nextGeneration?.() ?? null;
1137
+ if (T) return C(T, g, I);
1138
+ const l = e.coordinate?.() ?? null;
1139
+ if (l) return E(l, g);
1140
+ if (e.managedRoom?.()) {
1141
+ const b = (async () => {
1142
+ const S = Date.now() + gn;
1143
+ for (; Date.now() < S && e.managedRoom?.(); ) {
1144
+ const P = e.coordinate?.();
1145
+ if (P) return E(P, g);
1146
+ await new Promise((O) => setTimeout(O, 100));
1147
+ }
1148
+ })().catch(() => {
1149
+ });
1150
+ i.pending = b.finally(() => {
1151
+ i.pending === x && (i.pending = null);
1152
+ });
1153
+ const x = i.pending;
1154
+ return i.current ?? "";
1155
+ }
1156
+ const s = I === void 0 ? i.current : I, u = i.written;
1157
+ if (u && s === u.version && i.current === u.version && Je(u.bytes, g) && await ge(n, t.id).catch(() => null) === u.version)
1158
+ return e.onSaved(u.version), u.version;
1159
+ let f;
1160
+ try {
1161
+ f = await n.write(t.id, g, { expectedVersion: s });
1162
+ } catch (b) {
1163
+ throw b instanceof xe && (e.onConflict?.(b), Z("conflict", b.message)), b;
1164
+ }
1165
+ return i.current = f.version, i.written = { version: f.version, bytes: g }, i.known = g, e.onSaved(f.version), f.version;
1166
+ }
1167
+ async function E(g, I) {
1168
+ try {
1169
+ const $ = Date.now() + bn;
1170
+ for (; ; ) {
1171
+ let T = !1;
1172
+ const l = await g(async (s) => {
1173
+ T = !0;
1174
+ const u = await n.write(t.id, I, { expectedVersion: i.current, save: s });
1175
+ return i.current = u.version, i.written = { version: u.version, bytes: I }, i.known = I, u.version;
1176
+ });
1177
+ if (!T && i.known && !Je(i.known, I) && Date.now() < $) {
1178
+ await new Promise((s) => setTimeout(s, 100));
1179
+ continue;
1180
+ }
1181
+ return e.onSaved(l), l;
1182
+ }
1183
+ } catch ($) {
1184
+ throw $ instanceof xe && (e.onConflict?.($), Z("conflict", $.message)), $;
1185
+ }
1186
+ }
1187
+ const j = {
1188
+ read: async ({ path: g, offset: I, length: $ }) => {
1189
+ h(g);
1190
+ const T = await n.read(t.id);
1191
+ i.current = T.version, i.known = T.bytes instanceof Uint8Array ? T.bytes : new Uint8Array(T.bytes);
1192
+ const l = te(T.bytes), s = I ?? 0;
1193
+ return { bytes: I != null || $ != null ? l.slice(s, $ != null ? s + $ : void 0) : l, version: T.version, size: l.byteLength };
1194
+ },
1195
+ stamp: async ({ path: g }) => ({ version: a(g) ? await ge(n, t.id) : null }),
1196
+ write: async ({ path: g, bytes: I, mode: $, expected: T }) => {
1197
+ const l = new Uint8Array(I);
1198
+ if ($ === "save") {
1199
+ h(g), e.readOnly && Z("not-allowed", `${t.name} is open read-only`);
1200
+ const f = (i.saving ?? Promise.resolve()).then(() => i.pending).then(() => F(l, T));
1201
+ return i.saving = f.catch(() => {
1202
+ }), { path: t.name, version: await f };
1203
+ }
1204
+ n.create || Z("not-allowed", "this page does not take new files");
1205
+ const s = je(g).split("/").pop() || t.name, u = await n.create(s, l);
1206
+ return { path: u.name ?? s, version: u.version ?? "" };
1207
+ },
1208
+ changed: (g) => e.onChanged(g),
1209
+ notify: ({ level: g, title: I, description: $ }) => e.onNotify?.({ level: g, message: I, ...$ ? { description: $ } : {} })
1210
+ }, q = e.gesture ?? yn, { resolveLink: w, open: _, openUrl: B } = n;
1211
+ return w && _ && (j.open = async ({ link: g, view: I }) => {
1212
+ q() || Z("no-gesture", "opening a linked file needs a person’s gesture in the kit");
1213
+ const $ = await w(t.id, g);
1214
+ return $ || Z("not-found", `${g.path ?? g.name ?? g.docId} is not a file this page opens`), _($.fileId, I);
1215
+ }), B && (j.openUrl = async ({ url: g }) => (ut(g) || Z("not-allowed", "only https:, http:, and mailto: addresses open"), q() || Z("no-gesture", "opening an address needs a person’s gesture in the kit"), B(g))), r && (j.replicaRead = async ({ path: g }) => {
1216
+ h(g);
1217
+ const I = await r.read(t.id);
1218
+ return !I || e.managedRoom?.() && I.fileStamp !== await ge(n, t.id) ? null : Ze(I);
1219
+ }, j.replicaWrite = async ({ path: g, ...I }) => {
1220
+ h(g), !(i.carriedOver && I.fileStamp === i.carriedOver) && await r.write(t.id, Ze(I));
1221
+ }), j;
1222
+ }
1223
+ const Qe = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", et = /^[0-9a-f]{64}$/;
1224
+ function kn(e) {
1225
+ return Array.from(new Uint8Array(e), (t) => t.toString(16).padStart(2, "0")).join("");
1226
+ }
1227
+ async function An(e, t) {
1228
+ const n = globalThis.crypto?.subtle;
1229
+ return n ? kn(await n.digest("SHA-256", t.slice().buffer)) === e : !0;
1230
+ }
1231
+ function Sn(e, t) {
1232
+ const n = /* @__PURE__ */ new Set();
1233
+ return {
1234
+ read: async (r) => {
1235
+ const i = await e.read(r);
1236
+ if (!i) return null;
1237
+ const o = Xe(new Uint8Array(te(i.blobs)));
1238
+ if (!o.some((h) => !h.data.length && h.hash !== Qe)) return i;
1239
+ const a = [];
1240
+ for (const h of o) {
1241
+ if (h.data.length || h.hash === Qe) {
1242
+ a.push(h);
1243
+ continue;
1244
+ }
1245
+ const C = await t.read(h.hash), F = C ? new Uint8Array(te(C)) : null;
1246
+ if (!F || !await An(h.hash, F)) {
1247
+ console.warn(`[kition-embed] the blob store ${F ? "answered other bytes for" : "lacks"} blob ${h.hash}`);
1248
+ continue;
1249
+ }
1250
+ n.add(h.hash), a.push({ hash: h.hash, data: F });
1251
+ }
1252
+ return { ...i, blobs: te(Ye(a)) };
1253
+ },
1254
+ write: async (r, i) => {
1255
+ const o = Xe(new Uint8Array(te(i.blobs)));
1256
+ for (const h of o)
1257
+ !h.data.length || n.has(h.hash) || !et.test(h.hash) || (await t.write(h.hash, h.data), n.add(h.hash));
1258
+ const a = o.map((h) => et.test(h.hash) ? { hash: h.hash, data: new Uint8Array() } : h);
1259
+ await e.write(r, { ...i, blobs: te(Ye(a)) });
1260
+ }
1261
+ };
1262
+ }
1263
+ const En = {
1264
+ "kit.board": async () => (await import("../script/kits/board.js")).boardKit,
1265
+ "kit.cad": async () => (await import("../script/kits/cad.js")).cadKit,
1266
+ "kit.design": async () => (await import("../script/kits/design.js")).designKit,
1267
+ "kit.doc": async () => (await import("../script/kits/doc.js")).docKit,
1268
+ "kit.film": async () => (await import("../script/kits/film.js")).filmKit,
1269
+ "kit.html": async () => (await import("../script/kits/html.js")).htmlKit,
1270
+ "kit.layout": async () => (await import("../script/kits/layout.js")).layoutKit,
1271
+ "kit.motion": async () => (await import("../script/kits/motion.js")).motionKit,
1272
+ "kit.note": async () => (await import("../script/kits/note.js")).noteKit,
1273
+ "kit.pdf": async () => (await import("../script/kits/pdf.js")).pdfKit,
1274
+ "kit.photo": async () => (await import("../script/kits/photo.js")).photoKit,
1275
+ "kit.scene": async () => (await import("../script/kits/scene.js")).sceneKit,
1276
+ "kit.sheet": async () => (await import("../script/kits/sheet.js")).sheetKit,
1277
+ "kit.slide": async () => (await import("../script/kits/slide.js")).slideKit,
1278
+ "kit.table": async () => (await import("../script/kits/table.js")).tableKit,
1279
+ "kit.vector": async () => (await import("../script/kits/vector.js")).vectorKit
1280
+ };
1281
+ async function $n(e) {
1282
+ try {
1283
+ const t = await fetch(e, { credentials: "omit" });
1284
+ if (!t.ok) return;
1285
+ const n = await t.json();
1286
+ return n && typeof n == "object" ? n : void 0;
1287
+ } catch {
1288
+ return;
1289
+ }
1290
+ }
1291
+ function xn(e, t, n) {
1292
+ let r = null;
1293
+ const i = () => {
1294
+ const a = En[e];
1295
+ return a ? a().then((h) => h.schema, () => {
1296
+ }) : Promise.resolve(void 0);
1297
+ }, o = async () => {
1298
+ const a = await n?.().catch(() => {
1299
+ });
1300
+ return a && a.kit === e ? a : i();
1301
+ };
1302
+ return () => t ? Promise.resolve(t) : (r ??= o(), r);
1303
+ }
1304
+ const jn = "kition.embed", Le = "replicas";
1305
+ function mt() {
1306
+ const e = /* @__PURE__ */ new Map();
1307
+ return {
1308
+ read: async (t) => e.get(t) ?? null,
1309
+ write: async (t, n) => {
1310
+ e.set(t, n);
1311
+ }
1312
+ };
1313
+ }
1314
+ function tt(e) {
1315
+ return new Promise((t, n) => {
1316
+ const r = e();
1317
+ r.onsuccess = () => t(r.result), r.onerror = () => n(r.error ?? new Error("IndexedDB failed"));
1318
+ });
1319
+ }
1320
+ function Ln(e = globalThis.indexedDB) {
1321
+ if (!e) return mt();
1322
+ let t = null;
1323
+ const n = () => (t ??= new Promise((i, o) => {
1324
+ const a = e.open(jn, 1);
1325
+ a.onupgradeneeded = () => a.result.createObjectStore(Le), a.onsuccess = () => i(a.result), a.onerror = () => o(a.error ?? new Error("IndexedDB failed"));
1326
+ }).catch((i) => {
1327
+ throw t = null, i;
1328
+ }), t), r = async (i) => (await n()).transaction(Le, i).objectStore(Le);
1329
+ return {
1330
+ read: async (i) => {
1331
+ const o = await r("readonly");
1332
+ return await tt(() => o.get(i)) ?? null;
1333
+ },
1334
+ write: async (i, o) => {
1335
+ const a = await r("readwrite");
1336
+ await tt(() => a.put(o, i));
1337
+ }
1338
+ };
1339
+ }
1340
+ const nt = {
1341
+ "--kit-font-sans": 'system-ui, -apple-system, "Segoe UI", Roboto, sans-serif',
1342
+ "--kit-font-mono": "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",
1343
+ "--kit-primary-text": "#ffffff",
1344
+ "--kit-danger": "#e03131",
1345
+ "--kit-radius-control": "8px",
1346
+ "--kit-radius-card": "12px"
1347
+ }, Rn = {
1348
+ light: {
1349
+ ...nt,
1350
+ "--kit-surface": "#ffffff",
1351
+ "--kit-surface-muted": "#fafaf9",
1352
+ "--kit-canvas": "#f6f5f4",
1353
+ "--kit-text": "#1a1a1a",
1354
+ "--kit-text-muted": "#5d5b54",
1355
+ "--kit-border": "#e5e3df",
1356
+ "--kit-primary": "#5645d4",
1357
+ "--kit-primary-soft": "rgba(86, 69, 212, 0.1)",
1358
+ "--kit-shadow-card": "0 1px 2px rgba(15, 15, 15, 0.06), 0 4px 16px rgba(15, 15, 15, 0.06)"
1359
+ },
1360
+ dark: {
1361
+ ...nt,
1362
+ "--kit-surface": "#1b1e23",
1363
+ "--kit-surface-muted": "#22262c",
1364
+ "--kit-canvas": "#15171b",
1365
+ "--kit-text": "#eceff1",
1366
+ "--kit-text-muted": "#a9b0ba",
1367
+ "--kit-border": "#33373e",
1368
+ "--kit-primary": "#8b7ff0",
1369
+ "--kit-primary-soft": "rgba(139, 127, 240, 0.16)",
1370
+ "--kit-shadow-card": "0 1px 2px rgba(0, 0, 0, 0.3), 0 4px 16px rgba(0, 0, 0, 0.3)"
1371
+ }
1372
+ };
1373
+ function rt(e) {
1374
+ const t = e?.colorScheme === "dark" ? "dark" : "light";
1375
+ return { colorScheme: t, tokens: { ...Rn[t], ...e?.tokens }, ...e?.brand ? { brand: e.brand } : {} };
1376
+ }
1377
+ const Re = { view: 0, comment: 1, edit: 2 };
1378
+ function le(...e) {
1379
+ let t = "edit";
1380
+ for (const n of e) n && n in Re && Re[n] < Re[t] && (t = n);
1381
+ return t;
1382
+ }
1383
+ const In = (e) => e.startsWith("panel:") ? e : `panel:${e}`;
1384
+ function it(e, t, n) {
1385
+ if (!e && !n) return;
1386
+ const r = [...e?.hide ?? []];
1387
+ if (e?.toolbar === "none" && r.push("tab:*"), e?.panels && t) {
1388
+ const a = new Set(e.panels.map(In));
1389
+ for (const h of t) h.kind === "panel" && !a.has(h.id) && r.push(h.id);
1390
+ }
1391
+ const i = {};
1392
+ r.length && (i.hide = [...new Set(r)]), e?.disable?.length && (i.disable = [...e.disable]), e?.add?.length && (i.add = e.add), e?.modes && (i.modes = { ...e.modes });
1393
+ const o = n ?? e?.personal;
1394
+ return o?.hide && (i.personal = { hide: [...o.hide] }), i;
1395
+ }
1396
+ class Cn {
1397
+ constructor(t) {
1398
+ this.identity = t;
1399
+ }
1400
+ known = /* @__PURE__ */ new Map();
1401
+ get serves() {
1402
+ return !!this.identity?.users;
1403
+ }
1404
+ /** The people `identity.users` knows among `ids`. */
1405
+ async lookup(t) {
1406
+ const n = this.identity?.users, r = /* @__PURE__ */ new Map();
1407
+ if (!n) return r;
1408
+ const i = [...new Set(t.filter((o) => o && !this.known.has(o)))];
1409
+ if (i.length) {
1410
+ const o = Promise.resolve().then(() => n(i)).then(
1411
+ (a) => new Map((Array.isArray(a) ? a : []).filter((h) => h && typeof h.id == "string").map((h) => [h.id, h])),
1412
+ (a) => (console.warn("[kition-embed] identity.users failed", a), /* @__PURE__ */ new Map())
1413
+ );
1414
+ for (const a of i) this.known.set(a, o.then((h) => h.get(a) ?? null));
1415
+ }
1416
+ for (const o of new Set(t)) {
1417
+ const a = await this.known.get(o);
1418
+ a && r.set(o, a);
1419
+ }
1420
+ return r;
1421
+ }
1422
+ /** The room's peers with the page's names and avatars for them: by the user their presence names, else their principal. */
1423
+ async presence(t) {
1424
+ return yt(t, this.serves ? await this.lookup(t.map(wt)) : /* @__PURE__ */ new Map());
1425
+ }
1426
+ /** The threads with each comment's author as the page names them. */
1427
+ async threads(t) {
1428
+ const n = await this.lookup(t.flatMap((r) => r.comments.map((i) => i.author)));
1429
+ return t.map((r) => ({
1430
+ ...r,
1431
+ comments: r.comments.map((i) => {
1432
+ const o = n.get(i.author);
1433
+ return o ? { ...i, user: o } : { ...i };
1434
+ })
1435
+ }));
1436
+ }
1437
+ }
1438
+ function pt(e) {
1439
+ const t = e.state?.user;
1440
+ return t && typeof t.id == "string" && typeof t.name == "string" ? t : void 0;
1441
+ }
1442
+ const wt = (e) => pt(e)?.id ?? e.principalId;
1443
+ function yt(e, t) {
1444
+ return e.map((n) => {
1445
+ const r = t.get(wt(n)) ?? t.get(n.principalId), i = r ?? pt(n);
1446
+ return i ? { ...n, name: r?.name || n.name, user: i } : { ...n };
1447
+ });
1448
+ }
1449
+ const ot = "0.5.2", On = ["KitModel 1.1", "KitObjectModel 1.0", "KitEmbed 1.3"], Tn = "allow-scripts allow-same-origin allow-forms allow-downloads allow-popups", Pn = "clipboard-read; clipboard-write; fullscreen", _n = { mountKit: sn, replicaStore: () => Ln(), packageSchema: $n };
1450
+ function Ie(e) {
1451
+ return e instanceof Error ? e : new Error(String(e));
1452
+ }
1453
+ function qn(e, t = globalThis.location?.href) {
1454
+ const n = new URL(e.url, t);
1455
+ if (n.protocol !== "https:" && n.protocol !== "http:") throw new Error(`the kit URL ${e.url} is not http(s)`);
1456
+ return n.search = "", n.hash = "", n.pathname.endsWith("/") || (n.pathname += "/"), { origin: n.origin, base: n.href, entry: new URL(e.entry ?? "index.html", n).href };
1457
+ }
1458
+ const Un = (e) => e.replace(/-/g, "").toLowerCase();
1459
+ async function Nn(e, t, n) {
1460
+ const [{ openEnvelope: r }, i] = await Promise.all([import("./index-BEgEEnhU.js"), n ?? import("./replicaVersions-C3rJxnk9.js").then((E) => E.LORO_REPLICA_VERSIONS)]), o = new Uint8Array(e.changes), a = i.endOf(o), h = new Uint8Array(await t.replica.version());
1461
+ if (!a || !h.length || !i.includes(a, h)) return !1;
1462
+ const C = await t.replica.info().catch(() => null), F = [...r(o).docId].map((E) => E.toString(16).padStart(2, "0")).join("");
1463
+ return !C || Un(C) === F;
1464
+ }
1465
+ function Mn(e, t) {
1466
+ let n = t;
1467
+ return {
1468
+ read: async (r) => {
1469
+ const i = n;
1470
+ return n = null, i ?? e.read(r);
1471
+ },
1472
+ write: (r, i) => e.write(r, i)
1473
+ };
1474
+ }
1475
+ function Dn(e, t = globalThis.location?.href) {
1476
+ if (e == null || e === "") return;
1477
+ const n = new URL(String(e), t);
1478
+ if (n.protocol !== "https:" && n.protocol !== "http:") throw new Error(`the lend URL ${String(e)} is not http(s)`);
1479
+ return n.search = "", n.hash = "", n.pathname.endsWith("/") || (n.pathname += "/"), { root: n.href, folder: "" };
1480
+ }
1481
+ function Kn(e, t) {
1482
+ const n = document.createElement("iframe");
1483
+ return n.title = t, n.setAttribute("sandbox", Tn), n.setAttribute("allow", Pn), n.style.cssText = "display:block;width:100%;height:100%;border:0", n.src = e, n;
1484
+ }
1485
+ function zn(e) {
1486
+ return e ? { ...e.permissions ? { permissions: { ...e.permissions } } : {}, ...e.watermark !== void 0 ? { watermark: e.watermark ? { text: e.watermark.text } : null } : {} } : {};
1487
+ }
1488
+ async function Bn(e, t, n = _n) {
1489
+ const { kit: r } = t, { origin: i, base: o, entry: a } = qn(r);
1490
+ if (t.collaboration && (!t.identity?.token || !t.identity.user)) throw new Error("collaboration needs an identity provider with token and user");
1491
+ if (!t.storage.stamp && !t.storage.info) throw new Error("the storage needs stamp or info");
1492
+ if (!t.file.name && !t.storage.info) throw new Error("the file needs a name, or the storage info to name it");
1493
+ const h = t.storage;
1494
+ let C = { id: t.file.id, name: t.file.name ?? "" };
1495
+ const F = new Cn(t.identity), E = /* @__PURE__ */ new Map(), j = (p, A) => {
1496
+ for (const L of [...E.get(p) ?? []])
1497
+ try {
1498
+ L(A);
1499
+ } catch (R) {
1500
+ console.error("[kition-embed] a listener failed", R);
1501
+ }
1502
+ };
1503
+ let q = rt(t.theme), w = t.locale ?? globalThis.navigator?.language ?? "en-US", _ = le(t.permissions?.mode), B = t.ui, g = null, I = null, $, T = null, l = null, s = null, u = null, f = null, b = null;
1504
+ const x = () => b ?? T?.id ?? "agent";
1505
+ let S;
1506
+ const P = /* @__PURE__ */ new Set();
1507
+ let O = !1;
1508
+ const M = new AbortController(), c = { current: null }, d = h.replica ?? (t.collaboration ? n.replicaStore() : t.model ? mt() : null), m = d && h.blob ? Sn(d, h.blob) : d, v = /* @__PURE__ */ new Set();
1509
+ function k() {
1510
+ s?.remove(), s = null;
1511
+ }
1512
+ async function y(p, A = null, L = !1) {
1513
+ const R = p !== "edit";
1514
+ u?.abort();
1515
+ const K = new AbortController();
1516
+ u = K, s?.remove();
1517
+ const X = Kn(a, C.name);
1518
+ s = X, e.append(X);
1519
+ const V = await h.read(C.id);
1520
+ if (O || K.signal.aborted) throw new Error("the editor was closed");
1521
+ c.current = V.version;
1522
+ const ie = L && A && m && V.version ? { snapshot: A.changes, blobs: A.blobs, fileStamp: V.version } : null;
1523
+ L && !ie && console.warn("[kition-embed] could not open the kit again with its edits");
1524
+ const Ne = q, Me = w, Ae = B, De = t.identity || p === "comment" ? { me: T?.id ?? null, ...T?.name ? { name: T.name } : {}, canComment: p !== "view", othersReadOnly: !t.collaboration } : void 0, W = await n.mountKit(X, {
1525
+ signal: K.signal,
1526
+ origin: i,
1527
+ host: { name: "Kition Embed", version: ot },
1528
+ document: {
1529
+ path: C.name,
1530
+ name: C.name,
1531
+ bytes: ie ? new ArrayBuffer(0) : te(V.bytes),
1532
+ version: V.version,
1533
+ ...R ? { readOnly: !0 } : {},
1534
+ ...$ ? { lend: $ } : {},
1535
+ ...De ? { comments: De } : {},
1536
+ // What a managed room's open token lets the person take out, and the watermark.
1537
+ ...f?.openDocument ?? zn(t.display)
1538
+ },
1539
+ theme: Ne,
1540
+ locale: Me,
1541
+ shortcuts: [...t.shortcuts ?? []],
1542
+ ui: it(Ae, I, g),
1543
+ capabilitySets: [...On, ...t.collaboration ? ["KitCollab 1.0"] : []],
1544
+ timeoutMs: t.timeoutMs,
1545
+ handlers: {
1546
+ ...vn({
1547
+ file: C,
1548
+ storage: h,
1549
+ replicas: ie && m ? Mn(m, ie) : m,
1550
+ readOnly: R,
1551
+ version: c,
1552
+ onSaved: (U) => j("saved", { version: U }),
1553
+ onChanged: (U) => j("changed", U),
1554
+ onNotify: (U) => j("notify", U),
1555
+ onConflict: (U) => j("conflict", U),
1556
+ // A managed room's saves go through its save state machine (KitCollab 1.4, D3).
1557
+ coordinate: () => f?.coordinator() ?? null,
1558
+ // A save in a managed room goes through the room, never to the file directly (SV1).
1559
+ managedRoom: () => f?.isManaged() ?? !1,
1560
+ // The file moved to a later generation since the room was joined (1.3, SV5).
1561
+ moving: () => f?.moving() ?? null,
1562
+ nextGeneration: () => f?.generationMoved() ? { occupied: () => f.nextGenerationHasRoom(), moved: (U) => void f.moveToNextGeneration(U).catch((Se) => j("error", Ie(Se))), docKey: () => f.currentDocKey() } : null
1563
+ }),
1564
+ // Leases on the room's scopes (Kit UI protocol section 7b), when co-editing.
1565
+ ...t.collaboration ? {
1566
+ leases: {
1567
+ acquire: (U) => f ? f.acquireLease(U) : { lease: null },
1568
+ release: async (U) => {
1569
+ await f?.releaseLease(U);
1570
+ },
1571
+ list: () => f?.listLeases() ?? []
1572
+ }
1573
+ } : {},
1574
+ // The page's services and the comment threads it keeps (KitEmbed 1.7, EM29 and EM30).
1575
+ ...t.services ? { services: Hn(t.services) } : {},
1576
+ ...t.comments ? { comments: { activated: (U) => t.comments?.activated(U) } } : {},
1577
+ conflicts: ({ conflicts: U }) => j("mergeConflicts", U),
1578
+ schema: (U) => j("newerKit", U),
1579
+ draftChanged: (U) => j("draft", U),
1580
+ action: (U) => j("action", U),
1581
+ shortcut: (U) => j("shortcut", U),
1582
+ // The person's own hides go to the page (`ui.customize`), which passes them back later.
1583
+ ...Ae?.customize ? {
1584
+ customize: async ({ personal: U }) => {
1585
+ g = { hide: [...U?.hide ?? []] }, j("customize", g), await B?.customize?.(g);
1586
+ }
1587
+ } : {}
1588
+ }
1589
+ });
1590
+ if (O || K.signal.aborted)
1591
+ throw W.close(), new Error("the editor was closed");
1592
+ if (W.kit.id !== r.id)
1593
+ throw W.close(), new Error(`the kit at ${r.url} is ${W.kit.id}, not ${r.id}`);
1594
+ if (A && !L && W.capabilities.includes("replica")) {
1595
+ const U = await Nn(A, W, n.versions).catch(() => !1);
1596
+ if (O || K.signal.aborted)
1597
+ throw W.close(), new Error("the editor was closed");
1598
+ if (!U)
1599
+ return W.close(), y(p, A, !0);
1600
+ await W.replica.importChanges(A.changes, A.blobs);
1601
+ }
1602
+ return W.capabilities.includes("replica") && W.replica.onChanged((U) => {
1603
+ for (const Se of [...v]) Se(new Uint8Array(U));
1604
+ ve();
1605
+ }), q !== Ne && W.setTheme(q), w !== Me && W.setLocale(w), l = W, he && W.showComments(he), Q?.reset(), (B !== Ae || B?.panels) && H(W), ve(), W;
1606
+ }
1607
+ async function H(p) {
1608
+ B?.panels && (I = await p.elements().catch(() => [])), l === p && p.configure(it(B, I, g) ?? {});
1609
+ }
1610
+ let Q = null, ee = null, re = Promise.resolve(), ce = null, ue = !1;
1611
+ function ve() {
1612
+ O || !E.get("comments")?.size || ee || (ee = setTimeout(() => {
1613
+ ee = null, re = re.then(gt);
1614
+ }, 100));
1615
+ }
1616
+ async function gt() {
1617
+ const p = l;
1618
+ if (!(O || !p || !m || !p.capabilities.includes("replica") || !E.get("comments")?.size))
1619
+ try {
1620
+ const { CommentReader: A } = await import("./comments-uVDS8Wxp.js");
1621
+ Q ??= new A(r.id);
1622
+ const L = await F.threads(await Q.threads(p.replica)), R = JSON.stringify(L);
1623
+ if (O || R === ce?.text) return;
1624
+ ce = { text: R, threads: L }, j("comments", L);
1625
+ } catch (A) {
1626
+ ue || console.warn("[kition-embed] could not read the comment threads", A), ue = !0;
1627
+ }
1628
+ }
1629
+ function bt(p) {
1630
+ O || le(_, p) === _ || (_ = le(_, p), (async () => {
1631
+ f?.detach();
1632
+ const A = l;
1633
+ l = null;
1634
+ let L = null;
1635
+ A?.capabilities.includes("replica") && (L = await A.replica.exportChanges(new ArrayBuffer(0)).catch((K) => (console.warn("[kition-embed] could not keep the replica before opening the kit again", K), null))), A?.close();
1636
+ const R = await y(_, L);
1637
+ f?.attach(R, _);
1638
+ })().catch((A) => {
1639
+ O || j("error", Ie(A));
1640
+ }));
1641
+ }
1642
+ let he = null, me = null;
1643
+ function vt() {
1644
+ if (O) return;
1645
+ const p = me = (async () => {
1646
+ f?.detach(), l?.close(), l = null;
1647
+ const A = await y(_);
1648
+ f?.attach(A, _);
1649
+ })().catch((A) => {
1650
+ O || j("error", Ie(A));
1651
+ }).finally(() => {
1652
+ me === p && (me = null);
1653
+ });
1654
+ }
1655
+ let Te = 0;
1656
+ const kt = (p, A) => {
1657
+ if (p !== "presence") return j(p, A);
1658
+ const L = A;
1659
+ if (!F.serves) return j("presence", yt(L, /* @__PURE__ */ new Map()));
1660
+ const R = Te += 1;
1661
+ F.presence(L).then((K) => {
1662
+ R === Te && !O && j("presence", K);
1663
+ });
1664
+ }, pe = (async () => {
1665
+ if (!t.file.name) {
1666
+ const A = await h.info(C.id);
1667
+ if (!A?.name) throw new Error(`the storage has no file ${C.id}`);
1668
+ C = { id: C.id, name: A.name };
1669
+ }
1670
+ if (t.identity?.permissions && (_ = le(_, (await t.identity.permissions(C.id))?.mode)), t.identity?.user && (T = await t.identity.user()), h.lend && ($ = Dn(await h.lend(C.id))), t.collaboration) {
1671
+ const { openCollabSession: A } = await import("./collab-CTQZ9h7J.js"), L = await A({
1672
+ kit: r,
1673
+ file: C,
1674
+ storage: h,
1675
+ identity: t.identity,
1676
+ collaboration: t.collaboration,
1677
+ replicas: m,
1678
+ emit: kt,
1679
+ reopenReadOnly: bt,
1680
+ reopen: vt,
1681
+ onVersion: (R) => {
1682
+ c.current = R;
1683
+ },
1684
+ signal: M.signal,
1685
+ createTransport: n.createTransport,
1686
+ versions: n.versions
1687
+ });
1688
+ if (O)
1689
+ throw L.close(), new Error("the editor was closed");
1690
+ f = L, P.size > 0 && L.setAgent({ name: S ?? "Agent" }), _ = le(_, L.roleMode);
1691
+ }
1692
+ const p = await y(_);
1693
+ if (f)
1694
+ try {
1695
+ await f.claimOpened(p);
1696
+ } catch (A) {
1697
+ throw f.close(), f = null, p.close(), l = null, k(), A;
1698
+ }
1699
+ f?.attach(p, _);
1700
+ })();
1701
+ pe.catch(() => {
1702
+ });
1703
+ const G = async () => {
1704
+ if (await pe, await f?.moving(), await me, !l) throw new Error(O ? "the editor was closed" : "the kit is opening again");
1705
+ return l;
1706
+ }, At = { status: "off", docId: null, role: null }, Pe = n.packageSchema, ke = xn(r.id, r.schema, Pe && (() => Pe(new URL("model/schema.json", o).href))), _e = async () => {
1707
+ const p = await G();
1708
+ if (!p.capabilities.includes("draft")) throw new be("unsupported", `the ${r.id} editor keeps no drafts`);
1709
+ return p;
1710
+ }, qe = async () => {
1711
+ const p = await _e();
1712
+ if (_ !== "edit") throw new be("read-only", "the person may not change this document, so they cannot merge or discard a draft");
1713
+ if ((await p.draft.state()).state === "none") throw new be("no-draft", "there is no draft to merge or discard");
1714
+ return p;
1715
+ }, we = (p, A) => {
1716
+ let L = E.get(p);
1717
+ if (L || E.set(p, L = /* @__PURE__ */ new Set()), L.add(A), p === "comments") {
1718
+ const R = ce;
1719
+ R && queueMicrotask(() => L.has(A) && A(R.threads)), ve();
1720
+ }
1721
+ return () => {
1722
+ L.delete(A);
1723
+ };
1724
+ }, Ue = {
1725
+ ready: () => pe,
1726
+ save: async () => (await G()).save(),
1727
+ on: we,
1728
+ setTheme: (p) => {
1729
+ q = rt(p), l?.setTheme(q);
1730
+ },
1731
+ setLocale: (p) => {
1732
+ w = p, l?.setLocale(p);
1733
+ },
1734
+ comments: {
1735
+ show: (p) => {
1736
+ he = [...p], l?.showComments(he);
1737
+ },
1738
+ locate: async (p) => (await G()).locateComments(p)
1739
+ },
1740
+ collab: {
1741
+ get state() {
1742
+ return f?.state ?? At;
1743
+ },
1744
+ shareLink: async (p) => {
1745
+ if (await pe, !f) throw new Error("this editor does not co-edit");
1746
+ return f.shareLink(p);
1747
+ }
1748
+ },
1749
+ commands: {
1750
+ list: async (p = "") => await (await G()).ai.commands(p),
1751
+ run: async (p, A, L) => {
1752
+ const R = [{ command: p, ...A ? { params: A } : {} }], K = L?.save ?? !1, X = L?.origin ? { origin: L.origin, ...L.originLabel != null ? { originLabel: L.originLabel } : {} } : null, V = await G();
1753
+ return (await (X ? V.ai.run(R, K, X) : V.ai.run(R, K))).completed[0] ?? { command: p, changed: !1, result: null };
1754
+ }
1755
+ },
1756
+ check: async (p) => (await G()).check(p?.draft ? { draft: !0 } : void 0),
1757
+ draft: {
1758
+ state: async () => {
1759
+ const p = await G();
1760
+ return p.capabilities.includes("draft") ? p.draft.state() : { state: "none", revision: null };
1761
+ },
1762
+ compare: async (p) => {
1763
+ const A = await _e(), L = await ke();
1764
+ return A.draft.compare({ ...p?.maxSize ? { maxSize: p.maxSize } : {}, ...L ? { schema: L } : {} });
1765
+ },
1766
+ merge: async (p) => {
1767
+ const A = await qe(), L = p?.label ?? S;
1768
+ return A.draft.merge({ kind: "agent", principal: x(), ...L ? { label: L } : {} }, await ke());
1769
+ },
1770
+ discard: async () => (await qe()).draft.discard()
1771
+ },
1772
+ agentPort: (p) => {
1773
+ b = p?.principal ?? T?.id ?? b, S = p?.label ?? S;
1774
+ const A = mn({ kitId: r.id, path: () => C.name, opened: G, editable: () => _ === "edit", version: ot, schema: ke }, { ...p, principal: x() });
1775
+ P.add(A), f?.setAgent({ name: S ?? "Agent" });
1776
+ const L = A.close;
1777
+ return A.close = () => {
1778
+ L(), P.delete(A), P.size === 0 && f?.setAgent(null);
1779
+ }, A;
1780
+ },
1781
+ replicaVersion: async () => {
1782
+ const p = await G();
1783
+ return !m || !p.capabilities.includes("replica") ? null : new Uint8Array(await p.replica.version());
1784
+ },
1785
+ modelPort: () => {
1786
+ const p = () => {
1787
+ const R = async () => {
1788
+ const K = await G();
1789
+ if (!K.capabilities.includes("model")) throw new Error(`the ${r.id} editor no longer answers the object model`);
1790
+ return K;
1791
+ };
1792
+ return {
1793
+ describe: async (K) => (await R()).model.describe(K),
1794
+ batch: async (K, X) => {
1795
+ const { version: V, ...ie } = await (await R()).model.batch({ ...K, schema: X });
1796
+ return { ...ie, version: V ? new Uint8Array(V) : null };
1797
+ }
1798
+ };
1799
+ }, A = async () => {
1800
+ const R = await G();
1801
+ if (!m || !R.capabilities.includes("replica")) throw new Error(`the ${r.id} editor keeps no replica: mount it with model: true`);
1802
+ return R;
1803
+ }, L = (R) => R.buffer.slice(R.byteOffset, R.byteOffset + R.byteLength);
1804
+ return {
1805
+ kitId: r.id,
1806
+ exportChanges: async (R) => new Uint8Array((await (await A()).replica.exportChanges(L(R))).changes),
1807
+ importChanges: async (R) => {
1808
+ await (await A()).replica.importChanges(L(R), new ArrayBuffer(0));
1809
+ },
1810
+ command: async (R, K) => {
1811
+ const X = [{ command: R, ...K && typeof K == "object" ? { params: K } : {} }];
1812
+ return (await (await G()).ai.run(X, !1)).completed[0]?.result ?? null;
1813
+ },
1814
+ commands: async () => await (await G()).ai.commands(""),
1815
+ readOnly: () => _ !== "edit",
1816
+ // What the object model's documents hear from this editor (`@kition/sdk/script` `doc.on`).
1817
+ events: t.collaboration ? ["saved", "conflict", "presence"] : ["saved", "conflict"],
1818
+ on: (R, K) => {
1819
+ const X = K;
1820
+ return R === "saved" ? we("saved", ({ version: V }) => X({ version: V })) : R === "conflict" ? we("conflict", (V) => X({ message: V.message })) : R === "presence" ? we("presence", (V) => X({ peers: V })) : () => {
1821
+ };
1822
+ },
1823
+ onChanged: (R) => (v.add(R), () => {
1824
+ v.delete(R);
1825
+ }),
1826
+ // The kit answers the object model itself when its editor (open now) lists `model`.
1827
+ ...l?.capabilities.includes("model") ? { model: p() } : {}
1828
+ };
1829
+ },
1830
+ document: async (p, A) => {
1831
+ if (!p?.schema || p.id !== r.id) throw new Error(`document() takes ${r.id}'s typings, not ${p?.id ?? "none"}`);
1832
+ await G();
1833
+ const { openDocument: L } = await import("./document-B5MMuYyN.js").then((R) => R.d);
1834
+ return L(Ue.modelPort(), { schema: p.schema, ...A?.origin ? { origin: A.origin } : {} });
1835
+ },
1836
+ configure: (p) => {
1837
+ B = p, l && H(l);
1838
+ },
1839
+ get mode() {
1840
+ return _;
1841
+ },
1842
+ destroy: () => {
1843
+ if (!O) {
1844
+ O = !0, ee && clearTimeout(ee), M.abort(), u?.abort();
1845
+ for (const p of P) p.close();
1846
+ P.clear(), f?.close(), l?.close(), l = null, k(), E.clear(), v.clear();
1847
+ }
1848
+ }
1849
+ };
1850
+ return Ue;
1851
+ }
1852
+ function Hn(e) {
1853
+ const t = {};
1854
+ for (const [n, r] of Object.entries(e))
1855
+ typeof r == "function" && (t[n] = async (i) => {
1856
+ try {
1857
+ return await r(i);
1858
+ } catch (o) {
1859
+ const a = o?.reason, h = _t.includes(a) ? a : "failed";
1860
+ throw new z(-32e3, o instanceof Error ? o.message : `the page could not serve ${n}`, { reason: h });
1861
+ }
1862
+ });
1863
+ return t;
1864
+ }
1865
+ const st = "kition.embed.rooms.v1", Fn = ["owner", "editor", "viewer"];
1866
+ function at(e, t) {
1867
+ const n = e;
1868
+ return !!n && typeof n == "object" && n.docId === t && typeof n.fileId == "string" && typeof n.kit == "string" && Fn.includes(n.role);
1869
+ }
1870
+ function Yn(e = Vn()) {
1871
+ const t = {}, n = () => {
1872
+ if (!e) return t;
1873
+ try {
1874
+ const r = JSON.parse(e.getItem(st) || "{}");
1875
+ return r && typeof r == "object" ? r : {};
1876
+ } catch {
1877
+ return {};
1878
+ }
1879
+ };
1880
+ return {
1881
+ get: (r) => n()[r] ?? null,
1882
+ set: (r, i) => {
1883
+ if (!e) {
1884
+ t[r] = i;
1885
+ return;
1886
+ }
1887
+ e.setItem(st, JSON.stringify({ ...n(), [r]: i }));
1888
+ }
1889
+ };
1890
+ }
1891
+ function Vn() {
1892
+ try {
1893
+ return typeof localStorage > "u" ? null : localStorage;
1894
+ } catch {
1895
+ return null;
1896
+ }
1897
+ }
1898
+ class Jn {
1899
+ constructor(t) {
1900
+ this.state = t;
1901
+ }
1902
+ queue = Promise.resolve();
1903
+ async read(t) {
1904
+ await this.queue.catch(() => {
1905
+ });
1906
+ const n = await this.state.get(t);
1907
+ return at(n, t) ? n : null;
1908
+ }
1909
+ write(t) {
1910
+ return this.run(async () => {
1911
+ await this.state.set(t.docId, t);
1912
+ });
1913
+ }
1914
+ /** Changes the record of `docId`, if there is one. */
1915
+ update(t, n) {
1916
+ return this.run(async () => {
1917
+ const r = await this.state.get(t);
1918
+ at(r, t) && await this.state.set(t, { ...r, ...n });
1919
+ });
1920
+ }
1921
+ run(t) {
1922
+ const n = this.queue.catch(() => {
1923
+ }).then(t);
1924
+ return this.queue = n, n;
1925
+ }
1926
+ }
1927
+ function Zn(e) {
1928
+ return Array.from(e, (t) => t.toString(16).padStart(2, "0")).join("");
1929
+ }
1930
+ function Qn(e) {
1931
+ return !e || e.length % 2 || /[^0-9a-f]/i.test(e) ? new Uint8Array() : Uint8Array.from(e.match(/../g) ?? [], (t) => Number.parseInt(t, 16));
1932
+ }
1933
+ const er = {
1934
+ /**
1935
+ * Mounts the kit's editor for `options.file` in `element` (which it fills); `ready()` tells when
1936
+ * it shows the document.
1937
+ *
1938
+ * Co-editing editors with sync tokens on one page share one connection per sync server, which
1939
+ * the first of them opens with its `identity`; an editor with an open token (KitCollab 1.4) has
1940
+ * its own. Every editor asks its identity for a token before it connects. One document
1941
+ * (one room) co-edits in one editor per page: another editor of the same document fails
1942
+ * `ready()` with an `EmbedError` whose `code` is `document-open`.
1943
+ */
1944
+ mount: (e, t) => Bn(e, t)
1945
+ };
1946
+ export {
1947
+ ot as E,
1948
+ Pn as F,
1949
+ z as K,
1950
+ Wn as L,
1951
+ Jn as R,
1952
+ be as a,
1953
+ Xn as b,
1954
+ Zn as c,
1955
+ Xe as d,
1956
+ Ye as e,
1957
+ Qn as f,
1958
+ On as g,
1959
+ xe as h,
1960
+ Tn as i,
1961
+ er as j,
1962
+ st as k,
1963
+ Yn as l,
1964
+ Gn as r,
1965
+ ge as s,
1966
+ te as t
1967
+ };