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

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,2472 @@
1
+ import { isContainer as tt, LoroMap as at, LoroTree as We, LoroMovableList as _e, LoroText as ze, LoroDoc as It, decodeImportBlobMeta as gs, VersionVector as ms, UndoManager as ys } from "loro-crdt";
2
+ import { s as ht, c as M, b as z, e as f, a as D, K as L } from "./canonical-BIWfVCL-.js";
3
+ import { o as yt, s as wt, V as X, w as Vt } from "./envelope-D6MGY-ZN.js";
4
+ import { v as ws, r as ee, f as Jt, e as le, b as Ot, T as Dt, w as be, x as ve, y as Rt, z as ke, A as bs, s as bt, a as zt, K as Gt, n as ot, l as vs, u as Nt } from "./toolIds-BCeSGHpV.js";
5
+ function dt(o, t) {
6
+ const e = {};
7
+ for (const [s, n] of ws(t)) ht(e, s, { expand: n });
8
+ o.configTextStyle(e);
9
+ }
10
+ const ks = (o, t) => {
11
+ const e = o ? Object.keys(o).sort(M) : [], s = t ? Object.keys(t).sort(M) : [];
12
+ return e.length !== s.length ? !1 : e.every((n, r) => n === s[r] && JSON.stringify(z(o[n])) === JSON.stringify(z(t[n])));
13
+ };
14
+ function Ge(o, t, e) {
15
+ if (t === "") return;
16
+ const s = o[o.length - 1];
17
+ if (s && ks(s.attributes, e)) {
18
+ s.insert += t;
19
+ return;
20
+ }
21
+ o.push(e && Object.keys(e).length > 0 ? { insert: t, attributes: e } : { insert: t });
22
+ }
23
+ function de(o, t) {
24
+ const e = t.marks ?? {}, s = [];
25
+ for (const n of o.toDelta()) {
26
+ const r = n.insert;
27
+ if (typeof r != "string" || r === "") continue;
28
+ const i = n.attributes ?? {};
29
+ let c;
30
+ for (const h of Object.keys(i).sort(M)) {
31
+ if (!Object.hasOwn(e, h)) continue;
32
+ const a = i[h];
33
+ a != null && (c ??= {}, ht(c, h, z(a)));
34
+ }
35
+ Ge(s, r, c);
36
+ }
37
+ return s;
38
+ }
39
+ const ct = "meta", G = "objects", et = "$type", ue = "object", St = "schemaVersion", He = "schemaRaises", qe = "birth", Ye = "root", Oe = (o) => typeof o == "number" && Number.isSafeInteger(o) && o >= 0;
40
+ function it(o) {
41
+ const t = o.getMap(ct).get(St);
42
+ if (!Oe(t)) return null;
43
+ let e = t;
44
+ for (const s of o.getMap(He).keys()) {
45
+ const n = Number(s);
46
+ Oe(n) && String(n) === s && n > e && (e = n);
47
+ }
48
+ return e;
49
+ }
50
+ const Os = { text: ze, list: _e, tree: We, map: at };
51
+ function P(o, t) {
52
+ const e = o.getMap(G).get(t);
53
+ if (!(e instanceof at)) throw f.notFound(t);
54
+ return e;
55
+ }
56
+ function $t(o, t) {
57
+ const e = o.get(et);
58
+ if (typeof e != "string") throw f.notFound(t);
59
+ return e;
60
+ }
61
+ const jt = (o, t) => $t(P(o, t), t), Xe = (o, t) => f.engine(`${o}.${t} holds the wrong container`), Ze = (o, t, e) => f.invalidValue(o, t, `is not a ${e} field`);
62
+ function _(o, t, e, s) {
63
+ if (o === void 0) return null;
64
+ if (o instanceof Os[t]) return o;
65
+ throw Xe(e, s);
66
+ }
67
+ function F(o, t, e, s, n) {
68
+ const r = P(o, e), i = $t(r, e);
69
+ if (Jt(t, i, s).kind !== n) throw Ze(i, s, n);
70
+ return _(r.get(s), n, e, s);
71
+ }
72
+ function Ss(o, t, e, s) {
73
+ const n = F(o, t, e, s, "text");
74
+ if (!n) return [];
75
+ const r = Jt(t, jt(o, e), s);
76
+ if (le(r)) return de(n, r);
77
+ const i = [];
78
+ return Ge(i, n.toString(), void 0), i;
79
+ }
80
+ function fe(o, t, e, s) {
81
+ const n = P(o, e), r = $t(n, e);
82
+ if (ee(Jt(t, r, s).kind)) throw f.invalidValue(r, s, "is a container; read it with its accessor");
83
+ return Wt(n.get(s));
84
+ }
85
+ const Wt = (o) => o === void 0 || tt(o) ? null : z(o);
86
+ function Qe(o) {
87
+ return o.keys().sort(M).map((t) => [t, Wt(o.get(t))]);
88
+ }
89
+ function Ht(o, t) {
90
+ if (Object.values(t.types).some((e) => e.projected))
91
+ for (const e of Ms(o)) {
92
+ const s = $t(P(o, e), e), n = t.types[s];
93
+ if (n) {
94
+ if (n.projected) throw f.invalidValue(s, "$type", "projected objects are computed by the kit, never stored");
95
+ for (const [r, i] of Object.entries(n.fields)) {
96
+ if (!i.of || !t.types[i.of]?.projected) continue;
97
+ const c = P(o, e).get(r), h = tt(c) ? c.toJSON() : c;
98
+ if (h != null && !(Array.isArray(h) && !h.length) && !(typeof h == "object" && !Object.keys(h).length))
99
+ throw f.invalidValue(s, r, "projected membership is computed by the kit, never stored");
100
+ }
101
+ }
102
+ }
103
+ }
104
+ function ts(o, t) {
105
+ const e = [];
106
+ for (const [s, n] of o.getMap(G).entries())
107
+ n instanceof at && n.get(et) === t && e.push(s);
108
+ return e.sort(M);
109
+ }
110
+ function _t(o) {
111
+ return o.forEach((t, e) => {
112
+ if (typeof t != "string") throw f.encoding(`list item ${e} is ${js(t)}, not an object id`);
113
+ }), o;
114
+ }
115
+ const js = (o) => tt(o) ? "a container" : JSON.stringify(o) ?? String(o);
116
+ function Bt(o) {
117
+ const t = o.data.get(ue);
118
+ return typeof t == "string" ? t : null;
119
+ }
120
+ function Ms(o) {
121
+ return o.getMap(G).keys().sort(M);
122
+ }
123
+ const ut = (o) => o !== null && typeof o == "object" && !Array.isArray(o), ft = "__proto__", es = (o) => tt(o) ? o.toJSON() : o;
124
+ function ss(o) {
125
+ const t = [];
126
+ for (const e of o ?? []) {
127
+ const s = e.meta?.[ue];
128
+ typeof s == "string" && t.push({ children: ss(e.children), object: s });
129
+ }
130
+ return t;
131
+ }
132
+ function ns(o) {
133
+ const t = [];
134
+ for (const e of o ?? []) {
135
+ const s = Bt(e);
136
+ s !== null && t.push({ children: ns(e.children()), object: s });
137
+ }
138
+ return t;
139
+ }
140
+ function xs(o) {
141
+ const t = {};
142
+ for (const e of o.keys()) ht(t, e, es(o.get(e)));
143
+ return t;
144
+ }
145
+ function os(o, t, e) {
146
+ const s = P(o, e), n = $t(s, e), r = { [et]: n };
147
+ if (!Object.hasOwn(t.types, n)) return r;
148
+ const i = t.types[n].fields;
149
+ for (const c of Ot(i)) {
150
+ const h = i[c].kind;
151
+ let a;
152
+ if (h === "text" && le(i[c])) {
153
+ const p = F(o, t, e, c, "text");
154
+ a = p ? de(p, i[c]) : [];
155
+ } else if (h === "text") a = F(o, t, e, c, "text")?.toString() ?? "";
156
+ else if (h === "list") a = _t(F(o, t, e, c, "list")?.toArray() ?? []);
157
+ else if (h === "tree") a = ns(F(o, t, e, c, "tree")?.roots());
158
+ else if (h === "map") {
159
+ const p = F(o, t, e, c, "map");
160
+ a = p ? xs(p) : {};
161
+ } else a = fe(o, t, e, c);
162
+ ht(r, c, a);
163
+ }
164
+ return r;
165
+ }
166
+ const Se = /* @__PURE__ */ new WeakMap();
167
+ function $s(o, t) {
168
+ let e = Se.get(o);
169
+ e || Se.set(o, e = /* @__PURE__ */ new Map());
170
+ let s = e.get(t);
171
+ return s || e.set(t, s = [et, ...Object.keys(o.types[t].fields)].sort(M)), s;
172
+ }
173
+ const Is = (o) => o !== null && typeof o == "object" ? z(o) : o;
174
+ function je(o, t) {
175
+ const e = o.toJSON(), s = ut(e[G]) ? e[G] : {}, n = o.getMap(G), r = Object.keys(s);
176
+ n.get(ft) !== void 0 && r.push(ft), r.sort(M);
177
+ const i = {};
178
+ for (const a of r) {
179
+ const p = s[a], g = ut(p) ? p[et] : void 0, d = typeof g == "string" && Object.hasOwn(t.types, g);
180
+ if (a === ft || d && Object.hasOwn(t.types[g].fields, ft)) {
181
+ ht(i, a, z(os(o, t, a)));
182
+ continue;
183
+ }
184
+ if (!ut(p) || typeof g != "string") throw f.notFound(a);
185
+ if (!d) {
186
+ i[a] = { [et]: g };
187
+ continue;
188
+ }
189
+ const y = {};
190
+ i[a] = y;
191
+ const v = t.types[g].fields;
192
+ for (const k of $s(t, g)) {
193
+ if (k === et) {
194
+ y[k] = g;
195
+ continue;
196
+ }
197
+ const m = p[k], O = () => Xe(a, k);
198
+ switch (v[k].kind) {
199
+ case "text":
200
+ if (m !== void 0 && typeof m != "string") throw O();
201
+ if (le(v[k])) {
202
+ const S = m === void 0 ? null : _(P(o, a).get(k), "text", a, k);
203
+ y[k] = S ? de(S, v[k]) : [];
204
+ } else y[k] = m ?? "";
205
+ break;
206
+ case "list":
207
+ if (m !== void 0 && !Array.isArray(m)) throw O();
208
+ y[k] = Array.isArray(m) ? _t(m) : [];
209
+ break;
210
+ case "tree":
211
+ if (m !== void 0 && !Array.isArray(m)) throw O();
212
+ y[k] = ss(m);
213
+ break;
214
+ case "map": {
215
+ if (m !== void 0 && !ut(m)) throw O();
216
+ const S = ut(m) ? { ...m } : {}, j = P(o, a).get(k), R = j instanceof at ? j.get(ft) : void 0;
217
+ R !== void 0 && ht(S, ft, es(R)), y[k] = z(S);
218
+ break;
219
+ }
220
+ default:
221
+ y[k] = m === void 0 ? null : Is(m);
222
+ }
223
+ }
224
+ }
225
+ const c = ut(e[ct]) ? { ...e[ct] } : {}, h = it(o);
226
+ return h !== null && (c[St] = h), { meta: z(c), objects: i };
227
+ }
228
+ const se = 80;
229
+ function Vs(o, t) {
230
+ const e = Array.from(o), s = Array.from(t);
231
+ if (o === t || e.length <= se) return;
232
+ let n = 0, r = 0;
233
+ for (; n < Math.min(e.length, s.length) && e[n] === s[n]; ) n++;
234
+ for (; r < Math.min(e.length, s.length) - n && e[e.length - 1 - r] === s[s.length - 1 - r]; ) r++;
235
+ const i = e.length - n - r, c = s.length - n - r;
236
+ return {
237
+ offset: n,
238
+ removed: e.slice(n, n + Math.min(i, 80)).join(""),
239
+ inserted: s.slice(n, n + Math.min(c, 80)).join(""),
240
+ removedLength: i,
241
+ insertedLength: c,
242
+ before: e.slice(Math.max(0, n - 20), n).join(""),
243
+ after: e.slice(e.length - r, e.length - r + 20).join(""),
244
+ complete: i <= 80 && c <= 80
245
+ };
246
+ }
247
+ function rs(o, t, e) {
248
+ let s = 0;
249
+ const n = (c, h, a) => a.split(".").reduce((p, g) => N(p) ? p[g] : Array.isArray(p) ? p[Number(g)] : void 0, Mt(c)[h]), r = { ...o, changed: o.changed.map((c) => ({ ...c, edits: c.edits?.map((h) => {
250
+ const a = n(t, c.id, h.field), p = n(e, c.id, h.field), g = a == null ? "" : lt(a), d = p == null ? "" : lt(p), y = g === null || d === null ? void 0 : Vs(g, d);
251
+ if (!y) return h;
252
+ const v = new TextEncoder().encode(JSON.stringify(y)).length;
253
+ return s + v > 65536 ? { ...h, spansTruncated: !0 } : (s += v, { ...h, span: y });
254
+ }) })) }, i = Z.get(o);
255
+ return i && Z.set(r, i), r;
256
+ }
257
+ const Rs = 20, Me = "…", ne = "$type", N = (o) => typeof o == "object" && o !== null && !Array.isArray(o);
258
+ function Mt(o) {
259
+ const t = N(o) ? o.objects : void 0;
260
+ return N(t) ? t : {};
261
+ }
262
+ const H = (o) => N(o) && typeof o[ne] == "string" ? o[ne] : "";
263
+ function gt(o) {
264
+ const t = N(o) ? { ...o } : {};
265
+ return delete t[ne], t;
266
+ }
267
+ function xe(o) {
268
+ return o == null ? !1 : typeof o == "string" || Array.isArray(o) ? o.length > 0 : N(o) ? Object.keys(o).length > 0 : !0;
269
+ }
270
+ function lt(o) {
271
+ return typeof o == "string" ? o : Array.isArray(o) && o.length > 0 && o.every((t) => N(t) && typeof t.insert == "string") ? o.map((t) => t.insert).join("") : null;
272
+ }
273
+ const oe = (o, t) => JSON.stringify(o) === JSON.stringify(t), is = (o, t) => D(o) === D(t), mt = (...o) => [...new Set(o.flatMap((t) => Object.keys(t)))].sort(M), Es = (o) => Array.isArray(o) && o.length > 0 && o.every((t) => N(t) && typeof t.object == "string" && Array.isArray(t.children)), As = (o, t) => Array.isArray(o) && o.length > 0 && o.every((e) => typeof e == "string" && t(e)), $e = (o) => o == null || Array.isArray(o) && o.length === 0;
274
+ function qt(o, t, e) {
275
+ const s = (n) => (n(o) || n(t)) && (n(o) || $e(o)) && (n(t) || $e(t));
276
+ return s(Es) ? "tree" : s((n) => As(n, e)) ? "list" : "value";
277
+ }
278
+ function pe(o) {
279
+ return !N(o) || typeof o.hash != "string" || typeof o.mime != "string" ? null : typeof o.size == "number" && Number.isInteger(o.size) && o.size >= 0 ? o.size : null;
280
+ }
281
+ function Ts(o, t) {
282
+ const e = Array.from(o);
283
+ if (e.length <= se) return o;
284
+ const s = Math.min(Math.max(t - Rs, 0), e.length);
285
+ let n = se, r = "";
286
+ s > 0 && (r += Me, n -= 1);
287
+ const i = e.slice(s);
288
+ return r += i.length <= n ? i.join("") : i.slice(0, n - 1).join("") + Me, { excerpt: r, length: e.length };
289
+ }
290
+ function xt(o, t) {
291
+ const e = pe(o);
292
+ if (e !== null) return { size: e };
293
+ const s = lt(o);
294
+ return s === null ? o : Ts(s, t);
295
+ }
296
+ function Pt(o, t) {
297
+ return pe(o) === null ? xt(o, t) : o;
298
+ }
299
+ function Cs(o, t) {
300
+ const [e, s] = [Array.from(o), Array.from(t)];
301
+ let n = 0;
302
+ for (; n < e.length && n < s.length && e[n] === s[n]; ) n += 1;
303
+ return n;
304
+ }
305
+ const Yt = (o) => JSON.stringify(o);
306
+ class Ie {
307
+ at = /* @__PURE__ */ new Map();
308
+ add(t, e, s, n) {
309
+ if (n === "list") {
310
+ const r = [t, e, t];
311
+ s.filter((c) => typeof c == "string").forEach((c, h) => {
312
+ this.at.has(c) || this.at.set(c, { group: r, index: h });
313
+ });
314
+ } else n === "tree" && this.addNodes(t, e, t, s);
315
+ }
316
+ addNodes(t, e, s, n) {
317
+ const r = [t, e, s];
318
+ (Array.isArray(n) ? n : []).forEach((i, c) => {
319
+ !N(i) || typeof i.object != "string" || (this.at.has(i.object) || this.at.set(i.object, { group: r, index: c }), this.addNodes(t, e, i.object, i.children));
320
+ });
321
+ }
322
+ position(t) {
323
+ const e = this.at.get(t);
324
+ return e ? { parent: e.group[2], field: e.group[1], index: e.index } : null;
325
+ }
326
+ }
327
+ const Z = /* @__PURE__ */ new WeakMap();
328
+ function pn(o, t) {
329
+ const e = Z.get(o), s = { ...o, deleted: o.deleted.map((n) => {
330
+ const r = e?.get(n.id), i = t.types[n.type]?.fields, c = Object.fromEntries(Object.entries(r ?? {}).filter(([h]) => h.startsWith("~") || i && Object.hasOwn(i, h)));
331
+ return Object.keys(c).length ? { ...n, $was: c } : { ...n };
332
+ }) };
333
+ return e && Z.set(s, e), s;
334
+ }
335
+ function Ns(o) {
336
+ const t = [], e = o.map(() => null);
337
+ o.forEach((r, i) => {
338
+ let c = 0, h = t.length;
339
+ for (; c < h; ) {
340
+ const a = c + h >> 1;
341
+ o[t[a]] < r ? c = a + 1 : h = a;
342
+ }
343
+ c > 0 && (e[i] = t[c - 1]), c === t.length ? t.push(i) : t[c] = i;
344
+ });
345
+ const s = /* @__PURE__ */ new Set();
346
+ let n = t.length > 0 ? t[t.length - 1] : null;
347
+ for (; n !== null; )
348
+ s.add(n), n = e[n];
349
+ return s;
350
+ }
351
+ const Fs = 16;
352
+ function Ve(o) {
353
+ if (pe(o) !== null) return !0;
354
+ if (!N(o)) return !1;
355
+ const t = Object.keys(o).sort(M).join(",");
356
+ return t === "excerpt,length" || t === "size";
357
+ }
358
+ const re = (o, t) => D(o) === D(t);
359
+ function ie(o, t, e, s) {
360
+ if (N(t) && N(e) && !Ve(t) && !Ve(e)) {
361
+ const n = [.../* @__PURE__ */ new Set([...Object.keys(t), ...Object.keys(e)])].sort(M);
362
+ for (const r of n) {
363
+ const [i, c] = [t[r] ?? null, e[r] ?? null];
364
+ re(i, c) || ie(`${o}.${r}`, i, c, s);
365
+ }
366
+ return;
367
+ }
368
+ if (Array.isArray(t) && Array.isArray(e) && t.length === e.length) {
369
+ t.forEach((n, r) => {
370
+ re(n, e[r]) || ie(`${o}.${r}`, n, e[r], s);
371
+ });
372
+ return;
373
+ }
374
+ s.push({ field: o, before: Pt(t, 0), after: xt(e, 0) });
375
+ }
376
+ const Re = (o) => o.reduce((t, e) => t + e.field.length + D(e.before).length + D(e.after).length, 0);
377
+ function cs(o, t, e) {
378
+ const s = [{ field: o, before: Pt(t, 0), after: xt(e, 0) }], n = [];
379
+ return ie(o, t, e, n), n.length <= Fs && Re(n) < Re(s) ? n : s;
380
+ }
381
+ function Ds(o, t, e) {
382
+ const s = t === null ? {} : t, n = e === null ? {} : e;
383
+ if (!N(s) || !N(n)) return [{ field: o, before: t, after: e }];
384
+ const r = [];
385
+ for (const i of [.../* @__PURE__ */ new Set([...Object.keys(s), ...Object.keys(n)])].sort(M)) {
386
+ const [c, h] = [s[i] ?? null, n[i] ?? null];
387
+ re(c, h) || r.push(...cs(`${o}.${i}`, c, h));
388
+ }
389
+ return r;
390
+ }
391
+ function Bs(o, t) {
392
+ for (const e of o.changed) {
393
+ if (!e.edits) continue;
394
+ const s = /* @__PURE__ */ new Map();
395
+ for (const i of e.edits) {
396
+ let c;
397
+ try {
398
+ c = Jt(t, e.type, i.field);
399
+ } catch {
400
+ continue;
401
+ }
402
+ const h = c.kind === "map" && !c.owns ? Ds(i.field, i.before, i.after) : c.kind === "json" ? cs(i.field, i.before, i.after) : null;
403
+ h && (h.length !== 1 || h[0].field !== i.field) && s.set(i.field, h);
404
+ }
405
+ if (s.size === 0) continue;
406
+ const n = [];
407
+ let r = [...e.fields];
408
+ for (const i of e.edits) {
409
+ const c = s.get(i.field);
410
+ if (!c) {
411
+ n.push(i);
412
+ continue;
413
+ }
414
+ r = r.filter((h) => h !== i.field), r.push(...c.map((h) => h.field)), n.push(...c);
415
+ }
416
+ e.edits = n.sort((i, c) => M(i.field, c.field)), e.fields = [...new Set(r)].sort(M);
417
+ }
418
+ return o;
419
+ }
420
+ function ce(o, t, e, s, n) {
421
+ const r = (m) => s(m) !== null, i = { created: [], changed: [], moved: [], deleted: [] }, c = [], [h, a] = [new Ie(), new Ie()], p = /* @__PURE__ */ new Set(), g = /* @__PURE__ */ new Set(), d = /* @__PURE__ */ new Map();
422
+ Z.set(i, d);
423
+ for (const m of o) {
424
+ const O = Object.hasOwn(t, m) ? t[m] : void 0, S = Object.hasOwn(e, m) ? e[m] : void 0;
425
+ if (O === void 0 && S !== void 0) {
426
+ p.add(m);
427
+ const j = gt(S), R = mt(j).filter((I) => xe(j[I])), E = {};
428
+ for (const I of R) {
429
+ const A = I.startsWith("~") ? "value" : qt(null, j[I], r);
430
+ A === "value" ? E[I] = xt(j[I], 0) : a.add(m, I, j[I], A);
431
+ const U = lt(j[I]);
432
+ n && U && c.push({ id: m, field: I, before: "", after: U });
433
+ }
434
+ i.created.push({ id: m, type: H(S), fields: R, values: E });
435
+ } else if (O !== void 0 && S === void 0) {
436
+ g.add(m);
437
+ const j = gt(O), R = {};
438
+ for (const E of mt(j)) {
439
+ const I = E.startsWith("~") ? "value" : qt(j[E], null, r);
440
+ I === "value" && xe(j[E]) && (R[E] = Pt(j[E], 0)), h.add(m, E, j[E], I);
441
+ }
442
+ d.set(m, R), i.deleted.push({ id: m, type: H(O), fields: [] });
443
+ } else if (O !== void 0 && S !== void 0 && !oe(O, S)) {
444
+ const [j, R] = [gt(O), gt(S)], E = [], I = [];
445
+ H(O) !== H(S) && (E.push("$type"), I.push({ field: "$type", before: H(O), after: H(S) }));
446
+ for (const A of mt(j, R)) {
447
+ const U = j[A] ?? null, T = R[A] ?? null;
448
+ if (oe(U, T)) continue;
449
+ const st = A.startsWith("~") ? "value" : qt(U, T, r);
450
+ if (st !== "tree" && E.push(A), st !== "value") {
451
+ h.add(m, A, U, st), a.add(m, A, T, st);
452
+ continue;
453
+ }
454
+ const l = (x) => x === null ? "" : lt(x), [u, b] = [l(U), l(T)];
455
+ let w = 0;
456
+ u !== null && b !== null && (w = Cs(u, b), n && u !== b && c.push({ id: m, field: A, before: u, after: b })), I.push({ field: A, before: Pt(U, w), after: xt(T, w) });
457
+ }
458
+ E.length && i.changed.push({ id: m, type: H(S) || H(O), fields: E, edits: I });
459
+ }
460
+ }
461
+ for (const m of i.created) {
462
+ const O = a.position(m.id);
463
+ O && (m.at = O);
464
+ }
465
+ for (const m of i.deleted) {
466
+ const O = h.position(m.id);
467
+ O && (m.at = O);
468
+ }
469
+ const y = /* @__PURE__ */ new Map();
470
+ for (const [m, { group: O, index: S }] of a.at) {
471
+ const j = h.at.get(m);
472
+ if (j && Yt(j.group) === Yt(O)) {
473
+ const R = Yt(O);
474
+ y.has(R) || y.set(R, []), y.get(R).push({ id: m, was: j.index, now: S });
475
+ }
476
+ }
477
+ const v = /* @__PURE__ */ new Set();
478
+ for (const m of y.values()) {
479
+ m.sort((O, S) => O.now - S.now);
480
+ for (const O of Ns(m.map((S) => S.was))) v.add(m[O].id);
481
+ }
482
+ const k = [.../* @__PURE__ */ new Set([...h.at.keys(), ...a.at.keys()])].sort(M);
483
+ for (const m of k)
484
+ p.has(m) || g.has(m) || v.has(m) || i.moved.push({ id: m, type: s(m) ?? "", from: h.position(m), to: a.position(m) });
485
+ return n && (i.texts = c), i;
486
+ }
487
+ function gn(o, t) {
488
+ const [e, s] = [Mt(o), Mt(t)], n = (r) => Object.hasOwn(s, r) ? H(s[r]) : Object.hasOwn(e, r) ? H(e[r]) : null;
489
+ return ce(mt(e, s), e, s, n, !0);
490
+ }
491
+ function mn(o, t, e, s) {
492
+ o = rs(o, e, s);
493
+ const n = Mt(e), r = Mt(s), i = Dt.ofState(t, s), c = Dt.ofState(t, e), h = {};
494
+ let a = 0;
495
+ for (const d of mt(n, r)) {
496
+ if (!Object.hasOwn(n, d) || !Object.hasOwn(r, d)) continue;
497
+ const y = gt(n[d]), v = gt(r[d]);
498
+ for (const k of mt(y, v)) {
499
+ if (oe(y[k], v[k]) || lt(y[k]) === null || lt(v[k]) === null) continue;
500
+ const m = new TextEncoder().encode(JSON.stringify(y[k])).length;
501
+ if (m > 1048576 || a + m > 4194304) continue;
502
+ const O = i.attributed(d), S = O?.holder ?? i.show(d), j = O ? `${O.path}.${k}` : k;
503
+ (h[S] ??= {})[j] = c.showText(y[k]), a += m;
504
+ }
505
+ }
506
+ if (!Object.keys(h).length) return o;
507
+ const p = { ...o, $text: h }, g = Z.get(o);
508
+ return g && Z.set(p, g), p;
509
+ }
510
+ const yn = (o) => !o.created.length && !o.changed.length && !o.moved.length && !o.deleted.length;
511
+ function Ps(o, t, e, s) {
512
+ if (!e.isActive() && !s.isActive()) return o;
513
+ const n = Z.get(o) ?? /* @__PURE__ */ new Map(), r = (l, u) => {
514
+ const b = l.toolId(u) === null ? l.attributed(u) : null;
515
+ return b !== null ? `${b.holder}.${b.path}` : l.show(u);
516
+ }, i = (l, u, b) => typeof u != "string" || u === "" ? u : l.toolId(u) === null && l.attributed(u) === null ? { unnamed: b ?? "object" } : r(l, u), c = (l, u) => Object.hasOwn(t.types, l) && Object.hasOwn(t.types[l].fields, u) ? t.types[l].fields[u].of ?? void 0 : void 0, h = (l, u) => {
517
+ const b = l.toolId(u.parent) === null ? l.attributed(u.parent) : null;
518
+ return b !== null ? { parent: b.holder, field: `${b.path}.${u.field}`, index: u.index } : { ...u, parent: l.show(u.parent) };
519
+ }, a = new Map([...o.created, ...o.changed].map((l) => [l.id, l.type])), p = (l, u) => l !== void 0 && Object.hasOwn(t.types, l) && Object.hasOwn(t.types[l].fields, u) && t.types[l].fields[u].kind === "ref", g = (l, u) => p(a.get(l), u), d = (l, u) => ["json", "map"].includes(t.types[l]?.fields[u.split(".")[0]]?.kind ?? ""), y = (l) => l.sort((u, b) => M(u.id, b.id)), v = o.created.map((l) => {
520
+ const u = { ...l };
521
+ return l.values && (u.values = Object.fromEntries(Object.entries(l.values).map(([b, w]) => [b, p(l.type, b) ? i(s, w, c(l.type, b)) : d(l.type, b) ? s.showJson(w) : w]))), l.at && (u.at = h(s, l.at)), u;
522
+ }), k = o.changed.map((l) => {
523
+ const u = { ...l };
524
+ if (l.edits) {
525
+ u.edits = l.edits.map(
526
+ (w) => p(l.type, w.field) ? { ...w, before: i(e, w.before, c(l.type, w.field)), after: i(s, w.after, c(l.type, w.field)) } : d(l.type, w.field) ? { ...w, before: e.showJson(w.before), after: s.showJson(w.after) } : w
527
+ );
528
+ const b = new Set(u.edits.filter((w) => p(l.type, w.field) && typeof w.before == "string" && is(w.before, w.after)).map((w) => w.field));
529
+ b.size > 0 && (u.edits = u.edits.filter((w) => !b.has(w.field)), u.fields = u.fields.filter((w) => !b.has(w)));
530
+ }
531
+ return u;
532
+ }).filter((l) => l.fields.length > 0), m = /* @__PURE__ */ new Map(), O = (l, u) => {
533
+ const b = m.get(l) ?? { type: "", fields: [], edits: [], values: {} };
534
+ return b.type = u.typeOf(l) ?? "", m.set(l, b), b;
535
+ }, S = new Set(o.created.map((l) => s.show(l.id))), j = new Set(o.deleted.map((l) => e.show(l.id))), R = [];
536
+ for (const l of k) {
537
+ const u = s.attributed(l.id);
538
+ if (u === null) {
539
+ R.push(l);
540
+ continue;
541
+ }
542
+ const { holder: b, path: w } = u, x = O(b, s);
543
+ if (x.fields.push(...l.fields.map((B) => `${w}.${B}`)), S.has(b)) {
544
+ for (const B of l.edits ?? []) x.values[`${w}.${B.field}`] = B.after;
545
+ continue;
546
+ }
547
+ const q = s.namedPath(l.id);
548
+ x.edits.push(...(l.edits ?? []).map((B) => ({ ...B, field: `${w}.${B.field}`, ...q === null ? {} : { named: `${q}.${B.field}` } })));
549
+ }
550
+ const E = [];
551
+ for (const l of v) {
552
+ const u = s.attributed(l.id);
553
+ if (u === null) {
554
+ E.push(l);
555
+ continue;
556
+ }
557
+ const { holder: b, path: w } = u, x = O(b, s), q = l.values ?? {};
558
+ if (S.has(b)) {
559
+ x.fields.push(...l.fields.map((nt) => `${w}.${nt}`));
560
+ for (const [nt, ps] of Object.entries(q)) x.values[`${w}.${nt}`] = ps;
561
+ continue;
562
+ }
563
+ x.fields.push(w);
564
+ const B = s.namedPath(l.id);
565
+ x.edits.push({ field: w, before: null, after: q, ...B === null ? {} : { named: B } });
566
+ }
567
+ const I = [];
568
+ for (const l of o.deleted) {
569
+ const u = e.attributed(l.id);
570
+ if (u === null) {
571
+ I.push({ ...l });
572
+ continue;
573
+ }
574
+ if (j.has(u.holder)) continue;
575
+ const b = O(u.holder, e);
576
+ b.fields.push(u.path);
577
+ const w = e.namedPath(l.id);
578
+ b.edits.push({ field: u.path, before: n.get(l.id) ?? {}, after: null, ...w === null ? {} : { named: w } });
579
+ }
580
+ const A = (l) => {
581
+ const u = l.lastIndexOf(".");
582
+ return u >= 0 && /^\d+$/.test(l.slice(u + 1)) ? l.slice(0, u) : l;
583
+ }, U = [];
584
+ for (const l of o.moved) {
585
+ const [u, b] = [e.attributed(l.id), s.attributed(l.id)];
586
+ if (u === null && b === null) {
587
+ U.push(l);
588
+ continue;
589
+ }
590
+ if (u !== null && b !== null && u.holder === b.holder) {
591
+ if (!S.has(b.holder)) {
592
+ const w = O(b.holder, s);
593
+ w.fields.push(A(b.path)), w.edits.push({ field: A(b.path), before: u.path, after: b.path });
594
+ }
595
+ continue;
596
+ }
597
+ if (u !== null && !j.has(u.holder)) {
598
+ const w = O(u.holder, e);
599
+ w.fields.push(A(u.path)), w.edits.push({ field: A(u.path), before: u.path, after: null });
600
+ }
601
+ if (b !== null && !S.has(b.holder)) {
602
+ const w = O(b.holder, s);
603
+ w.fields.push(A(b.path)), w.edits.push({ field: A(b.path), before: null, after: b.path });
604
+ }
605
+ }
606
+ for (const l of m.values()) Ks(l);
607
+ const T = {
608
+ created: E.map((l) => ({ ...l, id: s.show(l.id) })),
609
+ changed: R.map((l) => ({ ...l, id: s.show(l.id) })),
610
+ moved: U.map((l) => ({ ...l, id: s.show(l.id), from: l.from ? h(e, l.from) : null, to: l.to ? h(s, l.to) : null })),
611
+ deleted: I.map((l) => {
612
+ const u = { ...l, id: e.show(l.id) };
613
+ return l.at && (u.at = h(e, l.at)), u;
614
+ })
615
+ }, st = (l) => [...new Set(l)].sort(M);
616
+ for (const l of [...m.keys()].sort(M)) {
617
+ const u = m.get(l), b = T.created.find((x) => x.id === l);
618
+ if (b !== void 0) {
619
+ b.fields = st([...b.fields, ...u.fields]), b.values = { ...b.values ?? {}, ...u.values };
620
+ continue;
621
+ }
622
+ if (u.fields.length === 0 && u.edits.length === 0) continue;
623
+ let w = T.changed.find((x) => x.id === l);
624
+ w === void 0 && (w = { id: l, type: u.type, fields: [], edits: [] }, T.changed.push(w)), w.fields = st([...w.fields, ...u.fields]), w.edits = [...w.edits ?? [], ...u.edits].sort((x, q) => M(x.field, q.field));
625
+ }
626
+ return y(T.created), y(T.changed), y(T.deleted), y(T.moved), o.texts && (T.texts = o.texts.map((l) => {
627
+ const u = g(l.id, l.field), b = (B, nt) => u && nt !== "" ? r(B, nt) : nt, w = s.attributed(l.id), [x, q] = w !== null ? [w.holder, `${w.path}.${l.field}`] : [r(s, l.id), l.field];
628
+ return { ...l, id: x, field: q, before: b(e, l.before), after: b(s, l.after) };
629
+ }).sort((l, u) => M(l.id, u.id) || M(l.field, u.field))), o.footprint !== void 0 && (T.footprint = o.footprint), Z.set(T, new Map([...n].map(([l, u]) => {
630
+ const b = e.typeOf(l) ?? "";
631
+ return [e.show(l), Object.fromEntries(Object.entries(u).map(([w, x]) => [
632
+ w,
633
+ p(b, w) ? i(e, x, c(b, w)) : d(b, w) ? e.showJson(x) : x
634
+ ]))];
635
+ }))), T;
636
+ }
637
+ function Ks(o) {
638
+ const t = /* @__PURE__ */ new Map(), e = /* @__PURE__ */ new Map();
639
+ for (const r of o.edits)
640
+ r.before === null && N(r.after) && t.set(r.field, r.after), r.after === null && N(r.before) && e.set(r.field, r.before);
641
+ const s = new Set([...t.keys()].filter((r) => e.has(r)));
642
+ if (s.size === 0) return;
643
+ const n = new Map(o.edits.filter((r) => s.has(r.field) && r.named !== void 0).map((r) => [r.field, r.named]));
644
+ o.edits = o.edits.filter((r) => !s.has(r.field)), o.fields = o.fields.filter((r) => !s.has(r));
645
+ for (const r of [...s].sort(M)) {
646
+ const i = e.get(r), c = t.get(r);
647
+ for (const h of [.../* @__PURE__ */ new Set([...Object.keys(i), ...Object.keys(c)])].sort(M)) {
648
+ const a = Object.hasOwn(i, h) ? i[h] : null, p = Object.hasOwn(c, h) ? c[h] : null;
649
+ if (!is(a, p)) {
650
+ o.fields.push(`${r}.${h}`);
651
+ const g = n.get(r);
652
+ o.edits.push({ field: `${r}.${h}`, before: a, after: p, ...g === void 0 ? {} : { named: `${g}.${h}` } });
653
+ }
654
+ }
655
+ }
656
+ }
657
+ function as(o) {
658
+ return Array.from(o, (t) => t.toString(16).padStart(2, "0")).join("");
659
+ }
660
+ function Q(o) {
661
+ const t = as(o);
662
+ return `${t.slice(0, 8)}-${t.slice(8, 12)}-${t.slice(12, 16)}-${t.slice(16, 20)}-${t.slice(20)}`;
663
+ }
664
+ const Ls = [
665
+ /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i,
666
+ /^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i,
667
+ /^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i,
668
+ /^([0-9a-f]{32})$/i
669
+ ];
670
+ function Xt(o) {
671
+ if (typeof o != "string") throw f.encoding("a UUID is a string");
672
+ for (const t of Ls) {
673
+ const e = t.exec(o);
674
+ if (!e) continue;
675
+ const s = e.slice(1).join(""), n = new Uint8Array(16);
676
+ for (let r = 0; r < 16; r += 1) n[r] = parseInt(s.slice(r * 2, r * 2 + 2), 16);
677
+ return n;
678
+ }
679
+ throw f.encoding(`\`${o}\` is not a UUID`);
680
+ }
681
+ function hs(o = Date.now()) {
682
+ const t = new Uint8Array(16);
683
+ crypto.getRandomValues(t);
684
+ let e = BigInt(o);
685
+ for (let s = 5; s >= 0; s -= 1)
686
+ t[s] = Number(e & 0xffn), e >>= 8n;
687
+ return t[6] = t[6] & 15 | 112, t[8] = t[8] & 63 | 128, Q(t);
688
+ }
689
+ const Us = () => hs(), wn = () => hs(), Ee = (1n << 64n) - 1n;
690
+ function Et(o) {
691
+ if (typeof o != "bigint") throw f.encoding("an actor id is a bigint");
692
+ if (o === Ee) throw f.encoding("actor id u64::MAX is reserved");
693
+ if (o < 0n || o > Ee) throw f.encoding(`actor id ${o} is not an unsigned 64-bit integer`);
694
+ return o;
695
+ }
696
+ function bn() {
697
+ const o = new Uint8Array(8);
698
+ return crypto.getRandomValues(o), BigInt(`0x${as(o)}`) >> 1n;
699
+ }
700
+ const ge = /* @__PURE__ */ new WeakMap(), me = Symbol("NodeRef");
701
+ class ls {
702
+ /** @internal */
703
+ constructor(t, e) {
704
+ if (t !== me) throw new TypeError("NodeRef handles come from Tx.treeCreate and Replica.tree");
705
+ ge.set(this, e), Object.defineProperty(this, "id", { value: e.id, enumerable: !0, writable: !1, configurable: e.id === null });
706
+ }
707
+ equals(t) {
708
+ return this.id !== null || t.id !== null ? this.id === t.id : this === t;
709
+ }
710
+ }
711
+ const ds = (o) => new ls(me, { id: o }), Js = (o, t) => new ls(me, { id: null, pending: { tx: o, index: t } }), Ws = (o) => ge.get(o);
712
+ function _s(o, t) {
713
+ const e = ge.get(o);
714
+ !e || e.id !== null || (e.id = t, Object.defineProperty(o, "id", { value: t, enumerable: !0, writable: !1, configurable: !1 }));
715
+ }
716
+ function ye(o) {
717
+ return typeof o == "string" ? JSON.stringify(o) : o == null || typeof o == "number" || typeof o == "boolean" ? String(o) : typeof o == "bigint" ? `${o}n` : Array.isArray(o) ? "an array" : `a ${typeof o}`;
718
+ }
719
+ function $(o, t) {
720
+ if (typeof t != "string") throw new L("invalid-value", `${o} must be a string, not ${ye(t)}`);
721
+ }
722
+ function J(o, t) {
723
+ if (typeof t != "number" || !Number.isSafeInteger(t) || t < 0)
724
+ throw new L("out-of-range", `${o} ${ye(t)} is out of range: it must be a whole number from 0`);
725
+ }
726
+ function Ae(o, t) {
727
+ const e = t !== null && typeof t == "object" ? Object.getPrototypeOf(t) : void 0;
728
+ if (e !== Object.prototype && e !== null || Object.getOwnPropertySymbols(t).length > 0)
729
+ throw new L("invalid-value", `${o} must be a plain object, not ${ye(t)}`);
730
+ }
731
+ const us = "[A-Za-z0-9][A-Za-z0-9:_-]{0,127}", zs = new RegExp(`^${us}$`);
732
+ function Gs(o, t) {
733
+ if (!zs.test(t)) throw f.invalidValue(o, "$id", `cannot be \`${t}\`: an object id matches \`${us}\``);
734
+ }
735
+ const ae = (o) => `c:${o}`, Zt = (o) => `p:${o}`, Kt = (o) => o.startsWith("p:") ? Number(o.slice(2)) : null, Lt = (o) => o.slice(2), Hs = 4;
736
+ class qs {
737
+ constructor(t, e) {
738
+ this.committed = t, this.len = e, this.after = e > 0 ? [{ text: null, start: 0, length: e }] : [];
739
+ }
740
+ /** The pieces before the cursor, in order, and their total length (the cursor's position). */
741
+ before = [];
742
+ beforeLength = 0;
743
+ /** The pieces after the cursor, last first: the piece right after the cursor is the last element. */
744
+ after;
745
+ /** The committed text, once read. */
746
+ committedString = null;
747
+ engineChecks = 0;
748
+ /**
749
+ * Whether `position` falls between the two halves of a surrogate pair. Every stored string is
750
+ * well formed, so that is when the code unit at `position` is a low surrogate, in an inserted
751
+ * string or in the committed text.
752
+ */
753
+ splits(t) {
754
+ if (t <= 0 || t >= this.len) return !1;
755
+ this.seek(t);
756
+ const e = this.after[this.after.length - 1], s = e.start + t - this.beforeLength;
757
+ return e.text !== null ? be(e.text.charCodeAt(s)) : this.committedSplits(s);
758
+ }
759
+ /** Inserts `content` (well formed) at `index`. */
760
+ insert(t, e) {
761
+ e && (this.cut(t), this.before.push({ text: e, start: 0, length: e.length }), this.beforeLength += e.length, this.len += e.length);
762
+ }
763
+ /** Deletes `count` code units from `index`. */
764
+ delete(t, e) {
765
+ if (e !== 0) {
766
+ this.cut(t);
767
+ for (let s = e; s > 0; ) {
768
+ const n = this.after.pop();
769
+ if (n.length > s) {
770
+ this.after.push({ text: n.text, start: n.start + s, length: n.length - s });
771
+ break;
772
+ }
773
+ s -= n.length;
774
+ }
775
+ this.len -= e;
776
+ }
777
+ }
778
+ /** The text with the pending edits applied. */
779
+ text() {
780
+ const t = this.before.some((n) => n.text === null) || this.after.some((n) => n.text === null) ? this.committedText() : "", e = (n) => (n.text ?? t).slice(n.start, n.start + n.length);
781
+ let s = "";
782
+ for (const n of this.before) s += e(n);
783
+ for (let n = this.after.length - 1; n >= 0; n -= 1) s += e(this.after[n]);
784
+ return s;
785
+ }
786
+ committedText() {
787
+ return this.committedString ??= this.committed?.toString() ?? "", this.committedString;
788
+ }
789
+ /** Whether position `at` of the committed text falls inside a surrogate pair. */
790
+ committedSplits(t) {
791
+ const e = this.committed;
792
+ if (!e || t <= 0 || t >= e.length) return !1;
793
+ if (this.committedString === null && this.engineChecks < Hs) {
794
+ this.engineChecks += 1;
795
+ const s = e.convertPos(t, "utf16", "unicode");
796
+ return s === void 0 || e.convertPos(s, "unicode", "utf16") !== t;
797
+ }
798
+ return be(this.committedText().charCodeAt(t));
799
+ }
800
+ /**
801
+ * Moves the cursor to the start of the piece holding `position` (`position` < `len`), or to the
802
+ * end when `position` is the length.
803
+ */
804
+ seek(t) {
805
+ const { before: e, after: s } = this;
806
+ for (; this.beforeLength > t; ) {
807
+ const n = e.pop();
808
+ this.beforeLength -= n.length, s.push(n);
809
+ }
810
+ for (; s.length > 0 && this.beforeLength + s[s.length - 1].length <= t; ) {
811
+ const n = s.pop();
812
+ this.beforeLength += n.length, e.push(n);
813
+ }
814
+ }
815
+ /** Moves the cursor to `position`, splitting the piece there if `position` falls inside it. */
816
+ cut(t) {
817
+ this.seek(t);
818
+ const e = t - this.beforeLength;
819
+ if (e === 0) return;
820
+ const s = this.after.pop();
821
+ this.before.push({ text: s.text, start: s.start, length: e }), this.after.push({ text: s.text, start: s.start + e, length: s.length - e }), this.beforeLength = t;
822
+ }
823
+ }
824
+ class Ys {
825
+ constructor(t) {
826
+ this.len = t;
827
+ }
828
+ edits = [];
829
+ replay(t) {
830
+ const e = [...t], s = () => f.engine("a staged list edit does not fit the list");
831
+ for (const n of this.edits)
832
+ if ("insert" in n) {
833
+ if (n.insert > e.length) throw s();
834
+ e.splice(n.insert, 0, n.item);
835
+ } else if ("move" in n) {
836
+ if (n.move >= e.length || n.to >= e.length) throw s();
837
+ e.splice(n.to, 0, ...e.splice(n.move, 1));
838
+ } else {
839
+ if (n.remove >= e.length) throw s();
840
+ e.splice(n.remove, 1);
841
+ }
842
+ return e;
843
+ }
844
+ }
845
+ class Xs {
846
+ constructor(t) {
847
+ this.committed = t;
848
+ }
849
+ /** `null` as a value: the node is a root. */
850
+ parents = /* @__PURE__ */ new Map();
851
+ /** Nodes this transaction deleted (M10b). */
852
+ deleted = /* @__PURE__ */ new Set();
853
+ /** The node's parent (`null`: a root), or `undefined` if the tree has no such live node. */
854
+ parent(t) {
855
+ if (this.deleted.has(t)) return;
856
+ if (this.parents.has(t)) return this.parents.get(t);
857
+ if (Kt(t) !== null || !this.committed) return;
858
+ const e = this.committed.getNodeByID(Lt(t));
859
+ if (!e || e.isDeleted()) return;
860
+ const s = e.parent();
861
+ return s ? ae(s.id) : null;
862
+ }
863
+ contains(t) {
864
+ return this.parent(t) !== void 0;
865
+ }
866
+ /** Whether making `parent` the parent of `node` makes `node` its own ancestor. A looping chain (a corrupt tree) counts as a cycle. */
867
+ wouldCycle(t, e) {
868
+ const s = /* @__PURE__ */ new Set();
869
+ let n = e;
870
+ for (; n != null; ) {
871
+ if (n === t || s.has(n)) return !0;
872
+ s.add(n), n = this.parent(n);
873
+ }
874
+ return !1;
875
+ }
876
+ }
877
+ function Zs(o, t, e, s, n) {
878
+ const r = new Array(s.length);
879
+ for (const i of e) {
880
+ i.op !== "raiseSchema" && n(i.id);
881
+ try {
882
+ tn(o, t, i, r);
883
+ } catch (c) {
884
+ throw c instanceof L ? c : f.engine(c instanceof Error ? c.message : String(c));
885
+ }
886
+ }
887
+ s.forEach((i, c) => {
888
+ const h = r[c];
889
+ h !== void 0 && _s(i, h);
890
+ });
891
+ }
892
+ const Te = 1024;
893
+ function Qs(o, t, e) {
894
+ if (e.length <= Te) {
895
+ o.insert(t, e);
896
+ return;
897
+ }
898
+ const s = [];
899
+ for (let r = 0; r < e.length; ) {
900
+ s.push(r);
901
+ let i = r + Te;
902
+ const c = e.charCodeAt(i);
903
+ i < e.length && c >= 56320 && c <= 57343 && (i += 1), r = i;
904
+ }
905
+ let n = e.length;
906
+ for (let r = s.length - 1; r >= 0; r -= 1)
907
+ o.insert(t, e.slice(s[r], n)), n = s[r];
908
+ }
909
+ function tn(o, t, e, s) {
910
+ switch (e.op) {
911
+ case "create": {
912
+ const n = o.getMap(G).setContainer(e.id, new at());
913
+ n.set(et, e.ty);
914
+ for (const i of Ot(e.fields)) n.set(i, e.fields[i]);
915
+ const r = t.types[e.ty].fields;
916
+ for (const i of Ot(r)) {
917
+ const c = r[i].kind;
918
+ c === "text" ? n.setContainer(i, new ze()) : c === "list" ? n.setContainer(i, new _e()) : c === "tree" ? n.setContainer(i, new We()) : c === "map" && n.setContainer(i, new at());
919
+ }
920
+ return;
921
+ }
922
+ case "set":
923
+ return P(o, e.id).set(e.field, e.value);
924
+ case "delete":
925
+ return o.getMap(G).delete(e.id);
926
+ case "textInsert":
927
+ return Qs(K(o, e.id, e.field, "text"), e.index, e.content);
928
+ case "textDelete":
929
+ return K(o, e.id, e.field, "text").delete(e.index, e.count);
930
+ case "textMark":
931
+ return K(o, e.id, e.field, "text").mark({ start: e.start, end: e.end }, e.key, e.value);
932
+ case "textUnmark":
933
+ return K(o, e.id, e.field, "text").unmark({ start: e.start, end: e.end }, e.key);
934
+ case "listInsert":
935
+ return K(o, e.id, e.field, "list").insert(e.index, e.item);
936
+ case "listMove":
937
+ return K(o, e.id, e.field, "list").move(e.from, e.to);
938
+ case "listRemove":
939
+ return K(o, e.id, e.field, "list").delete(e.index, 1);
940
+ case "mapSet":
941
+ return K(o, e.id, e.field, "map").set(e.key, e.value);
942
+ case "mapDelete":
943
+ return K(o, e.id, e.field, "map").delete(e.key);
944
+ case "treeCreate": {
945
+ const n = K(o, e.id, e.field, "tree").createNode(At(s, e.parent));
946
+ n.data.set(ue, e.object), s[e.node] = n.id;
947
+ return;
948
+ }
949
+ case "treeMove": {
950
+ const n = At(s, e.node);
951
+ if (n === void 0) throw f.engine("a staged tree move has no node");
952
+ return K(o, e.id, e.field, "tree").move(n, At(s, e.parent));
953
+ }
954
+ case "treeDelete": {
955
+ const n = At(s, e.node);
956
+ if (n === void 0) throw f.engine("a staged tree delete has no node");
957
+ return K(o, e.id, e.field, "tree").delete(n);
958
+ }
959
+ case "raiseSchema": {
960
+ const n = it(o);
961
+ if (n !== null && n >= e.version) return;
962
+ o.getMap(ct).set(St, e.version), o.getMap(He).set(String(e.version), !0);
963
+ return;
964
+ }
965
+ }
966
+ }
967
+ function K(o, t, e, s) {
968
+ const n = _(P(o, t).get(e), s, t, e);
969
+ if (!n) throw f.notFound(`${t}.${e}`);
970
+ return n;
971
+ }
972
+ function At(o, t) {
973
+ if (t === null) return;
974
+ const e = Kt(t);
975
+ if (e === null) return Lt(t);
976
+ const s = o[e];
977
+ if (s === void 0) throw f.engine(`tree node ${e} is used before it exists`);
978
+ return s;
979
+ }
980
+ function V(o, t) {
981
+ $("an object id", o), $("a field name", t);
982
+ }
983
+ const W = (o, t) => JSON.stringify([o, t]);
984
+ let en = 1;
985
+ class Ut {
986
+ constructor(t, e) {
987
+ this.doc = t, this.schema = e;
988
+ }
989
+ serial = en++;
990
+ ops = [];
991
+ /** Objects this transaction created: their type and the index of their `create` operation. */
992
+ created = /* @__PURE__ */ new Map();
993
+ deleted = /* @__PURE__ */ new Set();
994
+ /** Register writes: the index of the latest `set` operation of each field. */
995
+ registers = /* @__PURE__ */ new Map();
996
+ texts = /* @__PURE__ */ new Map();
997
+ lists = /* @__PURE__ */ new Map();
998
+ trees = /* @__PURE__ */ new Map();
999
+ /** Map writes by field: for each key written, the index of its latest `mapSet` operation, or `null` when the latest write deleted it. */
1000
+ maps = /* @__PURE__ */ new Map();
1001
+ /** The ids of `created` by type, in creation order (deleted ones included). */
1002
+ createdByType = /* @__PURE__ */ new Map();
1003
+ nodes = [];
1004
+ /** The largest schema version this transaction raised the document to. */
1005
+ raised = null;
1006
+ ended = !1;
1007
+ /** @internal Runs `build` on a new transaction; answers its result and its staged operations. */
1008
+ static stage(t, e, s) {
1009
+ const n = new Ut(t, e);
1010
+ let r;
1011
+ try {
1012
+ r = s(n);
1013
+ } finally {
1014
+ n.ended = !0;
1015
+ }
1016
+ if (typeof r?.then == "function")
1017
+ throw f.engine("a transaction runs synchronously; its function returned a promise");
1018
+ const { ops: i, nodes: c } = n, h = new Set(i.flatMap((a) => a.op === "create" ? [a.id] : []));
1019
+ return {
1020
+ result: r,
1021
+ staged: {
1022
+ empty: i.length === 0,
1023
+ raisesSchema: i.some((a) => a.op === "raiseSchema"),
1024
+ undoTouches: i.flatMap((a, p) => {
1025
+ if (a.op === "raiseSchema") return [];
1026
+ const g = [{ id: a.id, fields: "field" in a ? [a.field] : null }];
1027
+ let d;
1028
+ if (a.op === "listInsert") d = a.item;
1029
+ else if (a.op === "treeCreate") d = a.object;
1030
+ else if (a.op === "listMove" || a.op === "listRemove")
1031
+ d = n.undoListItem(a.id, a.field, a.op === "listMove" ? a.from : a.index, p);
1032
+ else if ((a.op === "treeMove" || a.op === "treeDelete") && Kt(a.node) === null) {
1033
+ const v = F(t, e, a.id, a.field, "tree")?.getNodeByID(Lt(a.node));
1034
+ d = v ? Bt(v) ?? void 0 : void 0;
1035
+ }
1036
+ return d && g.push({ id: d, fields: [] }), g;
1037
+ }),
1038
+ apply: (a, p, g) => Zs(a, p, i, c, g),
1039
+ // Writes to an object the same operations create are left out, as its creation's own
1040
+ // fields are: no undo reaches such a register before a later write replaces it (undoing
1041
+ // the creation removes the whole object), so the replica keeps no note of them.
1042
+ registerWrites: i.flatMap((a) => (a.op === "set" || a.op === "mapSet" || a.op === "mapDelete") && h.has(a.id) ? [] : a.op === "set" ? [{ id: a.id, field: null, key: a.field, value: a.value }] : a.op === "mapSet" ? [{ id: a.id, field: a.field, key: a.key, value: a.value }] : a.op === "mapDelete" ? [{ id: a.id, field: a.field, key: a.key, value: void 0 }] : [])
1043
+ }
1044
+ };
1045
+ }
1046
+ undoListItem(t, e, s, n) {
1047
+ for (let i = n - 1; i >= 0; i -= 1) {
1048
+ const c = this.ops[i];
1049
+ if (!(!("id" in c) || c.id !== t || !("field" in c) || c.field !== e))
1050
+ if (c.op === "listInsert") {
1051
+ if (s === c.index) return c.item;
1052
+ s > c.index && (s -= 1);
1053
+ } else c.op === "listRemove" ? s >= c.index && (s += 1) : c.op === "listMove" && (s === c.to ? s = c.from : c.from < c.to && s >= c.from && s < c.to ? s += 1 : c.to < c.from && s > c.to && s <= c.from && (s -= 1));
1054
+ }
1055
+ if (this.created.has(t)) return;
1056
+ const r = F(this.doc, this.schema, t, e, "list")?.get(s);
1057
+ return typeof r == "string" ? r : void 0;
1058
+ }
1059
+ /**
1060
+ * Raises the document's minimum schema version to `version` (rule M20): replicas whose schema is
1061
+ * older then refuse to load the document or import its changes (`newer-schema`). A migration
1062
+ * raises the version in the transaction that rewrites the document into the new form. Answers
1063
+ * whether the version rose: raising to a version the document already has, or a lower one,
1064
+ * changes nothing. Concurrent raises keep the largest.
1065
+ *
1066
+ * Only a `system` transaction raises the version, so it is never an undo step (`transact`
1067
+ * refuses others as `invalid-value`). `version` is at most the transaction's schema version: a
1068
+ * build cannot require a schema it does not read.
1069
+ */
1070
+ raiseSchemaVersion(t) {
1071
+ if (this.live(), !(typeof t == "number" && Number.isInteger(t) && t >= 0))
1072
+ throw f.invalidValue("$meta", "schemaVersion", "cannot be raised to a value that is not a non-negative integer");
1073
+ if (t > this.schema.schemaVersion)
1074
+ throw f.invalidValue("$meta", "schemaVersion", `cannot be raised to ${t}: this kit reads schema versions up to ${this.schema.schemaVersion}`);
1075
+ return t <= this.minSchemaVersion() ? !1 : (this.raised = t, this.ops.push({ op: "raiseSchema", version: t }), !0);
1076
+ }
1077
+ /** The document's minimum schema version (rule M20), including this transaction's raises. */
1078
+ minSchemaVersion() {
1079
+ return Math.max(it(this.doc) ?? 0, this.raised ?? 0);
1080
+ }
1081
+ /**
1082
+ * Creates an object of type `ty` with its register fields; container fields start empty. Its id
1083
+ * is a new UUID v7, or `options.id`: an id the host chose, matching
1084
+ * `[A-Za-z0-9][A-Za-z0-9:_-]{0,127}` and naming no object of the document or of this
1085
+ * transaction (one it deleted included); otherwise `invalid-value`. Replicas that create one id
1086
+ * concurrently keep one of the objects.
1087
+ */
1088
+ create(t, e, s) {
1089
+ this.live(), $("a type name", t), Ae("the fields", e);
1090
+ let n;
1091
+ if (s !== void 0) {
1092
+ Ae("the options", s);
1093
+ const p = Object.keys(s).find((g) => g !== "id");
1094
+ if (p !== void 0) throw new L("invalid-value", `the options take only \`id\`, not \`${p}\``);
1095
+ n = s.id, n !== void 0 && $("an object id", n);
1096
+ }
1097
+ if (!Object.hasOwn(this.schema.types, t)) throw f.unknownType(t);
1098
+ const r = this.schema.types[t];
1099
+ if (r.projected) throw f.invalidValue(t, "$type", "projected objects are computed by the kit, never stored");
1100
+ const i = Ot(e), c = {};
1101
+ for (const p of i) {
1102
+ const g = ve(this.schema, t, p, e[p]);
1103
+ typeof g == "string" && this.checkOf(t, p, r.fields[p], g), ht(c, p, g);
1104
+ }
1105
+ for (const p of Ot(r.fields)) {
1106
+ const g = r.fields[p];
1107
+ if (!ee(g.kind) && !g.optional && !Object.hasOwn(e, p)) throw f.invalidValue(t, p, "is required");
1108
+ }
1109
+ const h = n === void 0 ? Us() : this.freeId(t, n);
1110
+ this.created.set(h, { ty: t, op: this.ops.length });
1111
+ const a = this.createdByType.get(t);
1112
+ return a ? a.push(h) : this.createdByType.set(t, [h]), this.ops.push({ op: "create", id: h, ty: t, fields: c }), h;
1113
+ }
1114
+ /** Sets one register field. Concurrent sets of one field resolve to one winner; sets of different fields both survive. */
1115
+ set(t, e, s) {
1116
+ this.live(), V(t, e);
1117
+ const { ty: n, def: r } = this.field(t, e), i = ve(this.schema, n, e, s);
1118
+ typeof i == "string" && this.checkOf(n, e, r, i), this.registers.set(W(t, e), this.ops.length), this.ops.push({ op: "set", id: t, field: e, value: i });
1119
+ }
1120
+ /** Deletes an object. References to it dangle; kits treat that as a validation state. */
1121
+ delete(t) {
1122
+ if (!this.exists(t)) throw f.notFound(t);
1123
+ this.deleted.add(t), this.ops.push({ op: "delete", id: t });
1124
+ }
1125
+ exists(t) {
1126
+ return this.live(), $("an object id", t), !this.deleted.has(t) && (this.created.has(t) || this.doc.getMap(G).get(t) instanceof at);
1127
+ }
1128
+ /** Whether this transaction already removed the object, including an ownership cascade. */
1129
+ wasDeleted(t) {
1130
+ return this.deleted.has(t);
1131
+ }
1132
+ /** The type of a live object, including one this transaction created; not-found for an object it deleted. */
1133
+ objectType(t) {
1134
+ return this.live(), $("an object id", t), this.typeOf(t);
1135
+ }
1136
+ get(t, e) {
1137
+ this.live(), V(t, e);
1138
+ const { ty: s, def: n } = this.field(t, e);
1139
+ if (ee(n.kind)) throw f.invalidValue(s, e, "is a container; read it with its accessor");
1140
+ const r = this.pendingRegister(t, e);
1141
+ return r !== void 0 ? r : fe(this.doc, this.schema, t, e);
1142
+ }
1143
+ /** Inserts `content` at `index`, counted in UTF-16 code units. */
1144
+ textInsert(t, e, s, n) {
1145
+ this.live(), V(t, e), J("index", s), $("the content", n), this.containerField(t, e, "text");
1146
+ const r = this.textState(t, e, !0);
1147
+ if (s > r.len) throw f.outOfRange(s, r.len);
1148
+ if (r.splits(s)) throw vt(s);
1149
+ const i = Rt(n);
1150
+ this.texts.set(W(t, e), r), r.insert(s, i), this.ops.push({ op: "textInsert", id: t, field: e, index: s, content: i });
1151
+ }
1152
+ /** Deletes `count` UTF-16 code units starting at `index`. */
1153
+ textDelete(t, e, s, n) {
1154
+ this.live(), V(t, e), J("index", s), J("count", n), this.containerField(t, e, "text");
1155
+ const r = this.textState(t, e, !0), i = s + n;
1156
+ if (i > r.len) throw f.outOfRange(i, r.len);
1157
+ if (r.splits(s)) throw vt(s);
1158
+ if (r.splits(i)) throw vt(i);
1159
+ this.texts.set(W(t, e), r), r.delete(s, n), this.ops.push({ op: "textDelete", id: t, field: e, index: s, count: n });
1160
+ }
1161
+ /** The length of a text field in UTF-16 code units, including this transaction's edits. */
1162
+ textLength(t, e) {
1163
+ return this.live(), V(t, e), this.containerField(t, e, "text"), this.textState(t, e, !1).len;
1164
+ }
1165
+ /** A text field including this transaction's edits. Reads the whole text. */
1166
+ text(t, e) {
1167
+ return this.live(), V(t, e), this.containerField(t, e, "text"), this.textState(t, e, !1).text();
1168
+ }
1169
+ /**
1170
+ * Sets mark `key` to `value` over the code units `start..end` of a text field (rule M19). The
1171
+ * field declares `key` in its schema `marks`; `value` is plain JSON and not `null` (remove a
1172
+ * mark with `textUnmark`). An empty range changes nothing. Concurrent marks of one key over
1173
+ * overlapping ranges resolve to one value per character; marks of different keys all apply.
1174
+ */
1175
+ textMark(t, e, s, n, r, i) {
1176
+ this.live(), V(t, e), J("index", s), J("index", n), $("a mark key", r);
1177
+ const c = this.markKey(t, e, r);
1178
+ if (i == null) throw f.invalidValue(c, e, `mark \`${r}\` takes a value; remove a mark with textUnmark`);
1179
+ const h = ke(i, (a) => f.invalidValue(c, e, `mark \`${r}\` ${a}`));
1180
+ this.markRange(t, e, s, n) && this.ops.push({ op: "textMark", id: t, field: e, start: s, end: n, key: r, value: h });
1181
+ }
1182
+ /** Removes mark `key` from the code units `start..end` of a text field. Characters without the mark are left as they are; an empty range changes nothing. */
1183
+ textUnmark(t, e, s, n, r) {
1184
+ this.live(), V(t, e), J("index", s), J("index", n), $("a mark key", r), this.markKey(t, e, r), this.markRange(t, e, s, n) && this.ops.push({ op: "textUnmark", id: t, field: e, start: s, end: n, key: r });
1185
+ }
1186
+ listInsert(t, e, s, n) {
1187
+ this.live(), V(t, e), J("index", s), $("a list item", n);
1188
+ const { ty: r, def: i } = this.containerField(t, e, "list");
1189
+ this.checkOf(r, e, i, n);
1190
+ const c = this.listState(t, e);
1191
+ if (s > c.len) throw f.outOfRange(s, c.len);
1192
+ c.len += 1, c.edits.push({ insert: s, item: n }), this.ops.push({ op: "listInsert", id: t, field: e, index: s, item: n });
1193
+ }
1194
+ /** Moves the item at `from` so that it ends at index `to`. */
1195
+ listMove(t, e, s, n) {
1196
+ this.live(), V(t, e), J("index", s), J("index", n), this.containerField(t, e, "list");
1197
+ const r = this.listState(t, e);
1198
+ if (s >= r.len || n >= r.len) throw f.outOfRange(Math.max(s, n), r.len);
1199
+ r.edits.push({ move: s, to: n }), this.ops.push({ op: "listMove", id: t, field: e, from: s, to: n });
1200
+ }
1201
+ listRemove(t, e, s) {
1202
+ this.live(), V(t, e), J("index", s), this.containerField(t, e, "list");
1203
+ const n = this.listState(t, e);
1204
+ if (s >= n.len) throw f.outOfRange(s, n.len);
1205
+ n.len -= 1, n.edits.push({ remove: s }), this.ops.push({ op: "listRemove", id: t, field: e, index: s });
1206
+ }
1207
+ /** The list's items including this transaction's edits. Reads the whole list: call it only when the items themselves are wanted. */
1208
+ listItems(t, e) {
1209
+ this.live(), V(t, e), this.containerField(t, e, "list");
1210
+ const s = _(this.stored(t, e, !1), "list", t, e), n = s ? _t(s.toArray()) : [];
1211
+ return this.lists.get(W(t, e))?.replay(n) ?? n;
1212
+ }
1213
+ /** `listItems` under the name `Replica` uses. */
1214
+ list(t, e) {
1215
+ return this.listItems(t, e);
1216
+ }
1217
+ /** Sets `key` of a map field. Concurrent sets of one key resolve to one winner. */
1218
+ mapSet(t, e, s, n) {
1219
+ this.live(), V(t, e), $("a map key", s);
1220
+ const r = this.writableMap(t, e), i = ke(n, (h) => f.invalidValue(r, e, h));
1221
+ bs(this.schema, r, e, s, i), typeof i == "string" && this.checkOf(r, e, this.schema.types[r].fields[e], i);
1222
+ const c = Rt(s);
1223
+ this.mapWrites(t, e).set(c, this.ops.length), this.ops.push({ op: "mapSet", id: t, field: e, key: c, value: i });
1224
+ }
1225
+ mapDelete(t, e, s) {
1226
+ this.live(), V(t, e), $("a map key", s), this.writableMap(t, e);
1227
+ const n = Rt(s);
1228
+ this.mapWrites(t, e).set(n, null), this.ops.push({ op: "mapDelete", id: t, field: e, key: n });
1229
+ }
1230
+ /**
1231
+ * One key of a map field including this transaction's writes, or `null`, as `Replica.mapGet`
1232
+ * reads it. Costs one lookup in the transaction's writes of the field and at most one in the
1233
+ * document, however large the transaction.
1234
+ */
1235
+ mapGet(t, e, s) {
1236
+ this.live(), V(t, e), $("a map key", s), this.containerField(t, e, "map");
1237
+ const n = Rt(s), r = this.maps.get(W(t, e))?.get(n);
1238
+ if (r !== void 0) return this.pendingMapValue(r);
1239
+ const i = _(this.stored(t, e, !1), "map", t, e);
1240
+ return i ? Wt(i.get(n)) : null;
1241
+ }
1242
+ /**
1243
+ * A map field's keys and values including this transaction's writes, sorted by key (code point
1244
+ * order, as in the canonical state), each as `mapGet` reads it. Reads the whole map and sorts
1245
+ * the result on every call, O(n log n) in its keys: call it only when every entry is wanted.
1246
+ */
1247
+ mapEntries(t, e) {
1248
+ this.live(), V(t, e), this.containerField(t, e, "map");
1249
+ const s = _(this.stored(t, e, !1), "map", t, e), n = s ? Qe(s) : [], r = this.maps.get(W(t, e));
1250
+ if (!r) return n;
1251
+ const i = new Map(n);
1252
+ for (const [c, h] of r)
1253
+ h === null ? i.delete(c) : i.set(c, this.pendingMapValue(h));
1254
+ return [...i].sort((c, h) => M(c[0], h[0]));
1255
+ }
1256
+ /**
1257
+ * Ids of the live objects of type `ty`, including those this transaction created and without
1258
+ * those it deleted, sorted as `Replica.objectsOfType` sorts them. One pass over every object of
1259
+ * the document, O(objects) per call, plus this transaction's creations of `ty`; when it created
1260
+ * any, the whole result is sorted again, O(n log n) per call.
1261
+ */
1262
+ objectsOfType(t) {
1263
+ this.live(), $("a type name", t);
1264
+ const e = (r) => !this.deleted.has(r);
1265
+ let s = ts(this.doc, t);
1266
+ this.deleted.size > 0 && (s = s.filter(e));
1267
+ const n = this.createdByType.get(t);
1268
+ return n ? s.concat(n.filter(e)).sort(M) : s;
1269
+ }
1270
+ /** Adds a node naming `object` under `parent` (`null`: a root), last among its siblings. The handle resolves when the transaction commits. */
1271
+ treeCreate(t, e, s, n) {
1272
+ this.live(), V(t, e), $("a tree node object", n);
1273
+ const { ty: r, def: i } = this.containerField(t, e, "tree");
1274
+ this.checkOf(r, e, i, n);
1275
+ const c = s == null ? null : this.nodeKey(s), h = this.nodes.length, a = this.treeState(t, e);
1276
+ if (c !== null && !a.contains(c)) throw f.notFound(`parent node in ${t}.${e}`);
1277
+ a.parents.set(Zt(h), c);
1278
+ const p = Js(this.serial, h);
1279
+ return this.nodes.push(p), this.ops.push({ op: "treeCreate", id: t, field: e, parent: c, object: n, node: h }), p;
1280
+ }
1281
+ /**
1282
+ * Moves `node` under `parent` (`null`: a root), last among its siblings. A move that would make a
1283
+ * node its own ancestor (counting this transaction's earlier moves) is a `cycle` error; concurrent
1284
+ * moves that would form a cycle are resolved by the engine.
1285
+ */
1286
+ treeMove(t, e, s, n) {
1287
+ this.live(), V(t, e), this.containerField(t, e, "tree");
1288
+ const r = this.nodeKey(s), i = n == null ? null : this.nodeKey(n), c = this.treeState(t, e);
1289
+ if (!c.contains(r) || i !== null && !c.contains(i)) throw f.notFound(`node in ${t}.${e}`);
1290
+ if (i !== null && c.wouldCycle(r, i)) throw f.cycle();
1291
+ c.parents.set(r, i), this.ops.push({ op: "treeMove", id: t, field: e, node: r, parent: i });
1292
+ }
1293
+ /**
1294
+ * Rule M10b: leaves every object of the tree named by one node. For each object that several of
1295
+ * the document's nodes name (a redo made a new node for it while another replica's concurrent
1296
+ * move kept the old one alive), the node kept is the least by engine id (peer, then counter)
1297
+ * among those with no ancestor naming the same object; every other node naming it has its
1298
+ * children moved, in order, to the end of the kept node's children, and is then deleted. The
1299
+ * choice depends on the state alone, so replicas that repair one state concurrently make the
1300
+ * same moves and deletes. Nodes this transaction created are not considered. Answers how many
1301
+ * nodes it deleted; 0 writes nothing. Run it in a kit's repair (engine contract E14, a `system`
1302
+ * transaction) for every tree field.
1303
+ */
1304
+ treeDedupe(t, e) {
1305
+ this.live(), V(t, e), this.containerField(t, e, "tree");
1306
+ let s = 0;
1307
+ for (let n = this.treeDuplicate(t, e); n; n = this.treeDuplicate(t, e)) {
1308
+ const [r, i] = n;
1309
+ for (const a of this.tree(t, e))
1310
+ a.parent?.id === i.id && this.treeMove(t, e, a.node, r);
1311
+ const c = this.nodeKey(i), h = this.treeState(t, e);
1312
+ h.parents.delete(c), h.deleted.add(c), this.ops.push({ op: "treeDelete", id: t, field: e, node: c }), s += 1;
1313
+ }
1314
+ return s;
1315
+ }
1316
+ /** The first object in pre-order that several of the document's nodes name (M10b): the node to keep and the first other one in pre-order. */
1317
+ treeDuplicate(t, e) {
1318
+ const s = this.tree(t, e).filter((d) => d.node.id !== null), n = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new Map();
1319
+ let i = null;
1320
+ for (const d of s) {
1321
+ n.set(d.node.id, d.parent?.id ?? null);
1322
+ const y = r.get(d.object) ?? [];
1323
+ y.push(d.node), r.set(d.object, y), y.length === 2 && i === null && (i = d.object);
1324
+ }
1325
+ const c = i === null ? void 0 : r.get(i);
1326
+ if (!c) return null;
1327
+ const h = new Set(c.map((d) => d.id)), a = (d) => {
1328
+ for (let y = n.get(d.id) ?? null; y !== null; y = n.get(y) ?? null)
1329
+ if (h.has(y)) return !1;
1330
+ return !0;
1331
+ }, p = c.filter(a).sort((d, y) => sn(d.id, y.id))[0], g = p && c.find((d) => d.id !== p.id);
1332
+ return p && g ? [p, g] : null;
1333
+ }
1334
+ /**
1335
+ * The tree's nodes in pre-order as this transaction sees it: the document's nodes plus the nodes
1336
+ * it created, each node it created or moved last among its new siblings, as they will be once it
1337
+ * applies. A node that names no object is skipped with its subtree, as in `Replica.tree`. Reads
1338
+ * the whole tree: O(nodes + this transaction's operations).
1339
+ */
1340
+ tree(t, e) {
1341
+ this.live(), V(t, e), this.containerField(t, e, "tree");
1342
+ const s = _(this.stored(t, e, !1), "tree", t, e), n = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Map(), c = (d, y) => {
1343
+ const v = n.get(d);
1344
+ v ? v.push(y) : n.set(d, [y]), r.set(y, d);
1345
+ }, h = (d, y) => {
1346
+ for (const v of d ?? []) {
1347
+ const k = ae(v.id);
1348
+ c(y, k), i.set(k, Bt(v)), h(v.children(), k);
1349
+ }
1350
+ };
1351
+ s && h(s.roots(), null);
1352
+ for (const d of this.ops)
1353
+ if (d.op === "treeCreate" && d.id === t && d.field === e) {
1354
+ const y = Zt(d.node);
1355
+ c(d.parent, y), i.set(y, d.object);
1356
+ } else if (d.op === "treeMove" && d.id === t && d.field === e) {
1357
+ const y = r.get(d.node);
1358
+ y !== void 0 && n.set(y, (n.get(y) ?? []).filter((v) => v !== d.node)), c(d.parent, d.node);
1359
+ } else if (d.op === "treeDelete" && d.id === t && d.field === e) {
1360
+ const y = r.get(d.node);
1361
+ y !== void 0 && n.set(y, (n.get(y) ?? []).filter((v) => v !== d.node)), r.delete(d.node);
1362
+ }
1363
+ const a = (d) => {
1364
+ const y = Kt(d);
1365
+ if (y === null) return ds(Lt(d));
1366
+ const v = this.nodes[y];
1367
+ if (!v) throw f.engine(`tree node ${y} was not staged`);
1368
+ return v;
1369
+ }, p = [], g = (d, y) => {
1370
+ for (const v of n.get(d) ?? []) {
1371
+ const k = i.get(v);
1372
+ if (k == null) continue;
1373
+ const m = a(v);
1374
+ p.push({ node: m, object: k, parent: y }), g(v, m);
1375
+ }
1376
+ };
1377
+ return g(null, null), p;
1378
+ }
1379
+ /** Checks an id the host chose for a new object of type `ty`. */
1380
+ freeId(t, e) {
1381
+ if (Gs(t, e), this.created.has(e) || this.deleted.has(e) || this.doc.getMap(G).get(e) !== void 0)
1382
+ throw f.invalidValue(t, "$id", `cannot be \`${e}\`: that object id is taken`);
1383
+ return e;
1384
+ }
1385
+ live() {
1386
+ if (this.ended) throw f.engine("the transaction has ended");
1387
+ }
1388
+ /** The type of a live object, declared by the schema. */
1389
+ typeOf(t) {
1390
+ if (this.deleted.has(t)) throw f.notFound(t);
1391
+ const e = this.created.get(t);
1392
+ if (e) return e.ty;
1393
+ const s = jt(this.doc, t);
1394
+ if (!Object.hasOwn(this.schema.types, s)) throw f.unknownType(s);
1395
+ return s;
1396
+ }
1397
+ /** The object's type and the definition of `field`. */
1398
+ field(t, e) {
1399
+ const s = this.typeOf(t), n = this.schema.types[s].fields;
1400
+ if (!Object.hasOwn(n, e)) throw f.unknownField(s, e, Object.keys(n).sort());
1401
+ return { ty: s, def: n[e] };
1402
+ }
1403
+ containerField(t, e, s) {
1404
+ const n = this.field(t, e);
1405
+ if (n.def.kind !== s) throw Ze(n.ty, e, s);
1406
+ return n;
1407
+ }
1408
+ /** Refuses a target that exists but is not of the field's `of` type. A missing target is accepted: a dangling reference is a validation state. */
1409
+ checkOf(t, e, s, n) {
1410
+ const r = s?.of;
1411
+ if (r === void 0) return;
1412
+ let i = null;
1413
+ if (!this.deleted.has(n) && (i = this.created.get(n)?.ty ?? null, i === null))
1414
+ try {
1415
+ i = jt(this.doc, n);
1416
+ } catch {
1417
+ i = null;
1418
+ }
1419
+ if (i !== null && i !== r) throw f.invalidValue(t, e, `expects an object of type \`${r}\`, and \`${n}\` is a \`${i}\``);
1420
+ }
1421
+ /**
1422
+ * The document's container for a field, or `null` when it starts empty: the object was created
1423
+ * by this transaction, or (for reads) it predates the field. Writes to a field the stored object
1424
+ * lacks are `not-found`.
1425
+ */
1426
+ stored(t, e, s) {
1427
+ if (this.created.has(t)) return;
1428
+ const n = P(this.doc, t).get(e);
1429
+ if (n === void 0 && s) throw f.notFound(`${t}.${e}`);
1430
+ return n;
1431
+ }
1432
+ /** The pending writes of a map field, made on first use. */
1433
+ mapWrites(t, e) {
1434
+ const s = W(t, e);
1435
+ let n = this.maps.get(s);
1436
+ return n || this.maps.set(s, n = /* @__PURE__ */ new Map()), n;
1437
+ }
1438
+ /** The value of the `mapSet` operation at `index` (`null`: a deletion), as the engine will store it. */
1439
+ pendingMapValue(t) {
1440
+ if (t === null) return null;
1441
+ const e = this.ops[t];
1442
+ return e.op === "mapSet" ? z(e.value) : null;
1443
+ }
1444
+ pendingRegister(t, e) {
1445
+ const s = this.registers.get(W(t, e));
1446
+ if (s !== void 0) {
1447
+ const i = this.ops[s];
1448
+ if (i.op === "set") return z(i.value);
1449
+ }
1450
+ const n = this.created.get(t);
1451
+ if (!n) return;
1452
+ const r = this.ops[n.op];
1453
+ return r.op === "create" ? z(r.fields[e] ?? null) : void 0;
1454
+ }
1455
+ /** The text's state: this transaction's, or a fresh one over the document's text (not recorded until an edit succeeds). */
1456
+ textState(t, e, s) {
1457
+ const n = this.texts.get(W(t, e));
1458
+ if (n) return n;
1459
+ const r = _(this.stored(t, e, s), "text", t, e);
1460
+ return new qs(r, r?.length ?? 0);
1461
+ }
1462
+ /** Checks that `field` is a text field declaring mark `key`; answers the object's type. */
1463
+ markKey(t, e, s) {
1464
+ const { ty: n, def: r } = this.containerField(t, e, "text");
1465
+ if (!r.marks || !Object.hasOwn(r.marks, s)) throw f.invalidValue(n, e, `declares no mark \`${s}\``);
1466
+ return n;
1467
+ }
1468
+ /** Checks a mark's range against the text including this transaction's edits; answers whether it holds any character. */
1469
+ markRange(t, e, s, n) {
1470
+ const r = this.textState(t, e, !0);
1471
+ if (n > r.len) throw f.outOfRange(n, r.len);
1472
+ if (s > n) throw f.outOfRange(s, n);
1473
+ if (r.splits(s)) throw vt(s);
1474
+ if (r.splits(n)) throw vt(n);
1475
+ return s < n;
1476
+ }
1477
+ listState(t, e) {
1478
+ const s = W(t, e);
1479
+ let n = this.lists.get(s);
1480
+ if (!n) {
1481
+ const r = _(this.stored(t, e, !0), "list", t, e);
1482
+ n = new Ys(r?.length ?? 0), this.lists.set(s, n);
1483
+ }
1484
+ return n;
1485
+ }
1486
+ /** Checks a map field for writing; answers the object's type. */
1487
+ writableMap(t, e) {
1488
+ const { ty: s } = this.containerField(t, e, "map");
1489
+ return _(this.stored(t, e, !0), "map", t, e), s;
1490
+ }
1491
+ treeState(t, e) {
1492
+ const s = W(t, e);
1493
+ let n = this.trees.get(s);
1494
+ return n || (n = new Xs(_(this.stored(t, e, !0), "tree", t, e)), this.trees.set(s, n)), n;
1495
+ }
1496
+ /** A handle as this transaction sees it. A handle of another transaction that never applied (it failed) names no node. */
1497
+ nodeKey(t) {
1498
+ const e = Ws(t);
1499
+ if (!e) throw f.notFound("a tree node the KDM did not make");
1500
+ if (e.id !== null) return ae(e.id);
1501
+ if (e.pending?.tx === this.serial) return Zt(e.pending.index);
1502
+ throw f.notFound("a tree node from a transaction that did not commit");
1503
+ }
1504
+ }
1505
+ function sn(o, t) {
1506
+ const e = (c) => {
1507
+ const h = c.indexOf("@");
1508
+ return [BigInt(c.slice(h + 1)), Number(c.slice(0, h))];
1509
+ }, [s, n] = e(o), [r, i] = e(t);
1510
+ return s !== r ? s < r ? -1 : 1 : n - i;
1511
+ }
1512
+ const vt = (o) => new L("out-of-range", `index ${o} splits a character`), kt = "kdm-rollback", Ft = "system", nn = "import", Ce = (o) => f.engine(`applying a validated transaction failed: ${o instanceof Error ? o.message : String(o)}`), C = (o) => o instanceof Error ? o.message : String(o), on = "the changes depend on history before this shallow replica's root; rebase it on a newer snapshot", rn = "the version is not in this replica's history (another document's, or the document was replaced since)", cn = "a shallow replica forks only at its current version; read earlier versions from the server", an = "the snapshot is older than this shallow replica's root; rebase it on a newer one", Ne = (o) => C(o).includes("not included in the shallow history") ? f.historyMissing(on) : f.encoding(C(o));
1513
+ function Qt(o, t) {
1514
+ const e = /* @__PURE__ */ new Set(), s = [], n = o.subscribe((r) => {
1515
+ for (const i of r.events)
1516
+ if (i.path[0] === G) {
1517
+ if (i.path.length >= 2) {
1518
+ if (e.add(String(i.path[1])), i.diff.type === "map")
1519
+ for (const [c, h] of Object.entries(i.diff.updated)) tt(h) || s.push(he(i.target, c));
1520
+ } else if (i.diff.type === "map") for (const c of Object.keys(i.diff.updated)) e.add(c);
1521
+ }
1522
+ });
1523
+ try {
1524
+ return { value: t(), changed: e, registers: s };
1525
+ } finally {
1526
+ n();
1527
+ }
1528
+ }
1529
+ const he = (o, t) => `${o}\0${t}`, Fe = (o) => {
1530
+ const t = o.indexOf("\0");
1531
+ return [o.slice(0, t), o.slice(t + 1)];
1532
+ }, Tt = (o) => new Set([...o].sort(M));
1533
+ function Y(o, t) {
1534
+ $("an object id", o), $("a field name", t);
1535
+ }
1536
+ function De(o) {
1537
+ if (typeof o != "function") throw new L("invalid-value", "a transaction needs a function");
1538
+ }
1539
+ function Be(o) {
1540
+ if (!o.isShallow()) return !0;
1541
+ const t = X.fromEngine(o.shallowSinceVV()), e = o.fork();
1542
+ try {
1543
+ e.checkout(o.shallowSinceFrontiers());
1544
+ const s = e.getMap(qe).get(Ye);
1545
+ return s instanceof Uint8Array && X.decode(s).equals(t);
1546
+ } catch {
1547
+ return !1;
1548
+ } finally {
1549
+ e.free();
1550
+ }
1551
+ }
1552
+ class rt {
1553
+ constructor(t, e, s, n) {
1554
+ this.doc = t, this.schema = s, this.actor = n, Ht(t, s), this.docIdBytes = e.slice(), t.setPeerId(n), this.undoManagers = Ue(t, this.runs);
1555
+ }
1556
+ docIdBytes;
1557
+ undoManagers;
1558
+ changed = /* @__PURE__ */ new Set();
1559
+ /** Set while a transaction's function runs: nothing else may change the document then. */
1560
+ busy = !1;
1561
+ /** Set between `beginUndoGroup` and `endUndoGroup`. */
1562
+ grouping = !1;
1563
+ /** The open undo group's run, which its undo steps carry (rule M12b). */
1564
+ runs = { current: null, next: 1, replaying: !1, popped: null, pending: [], groups: /* @__PURE__ */ new Map() };
1565
+ /**
1566
+ * Set when a shallow replica refused an import (`newer-schema`) after the engine applied it: the
1567
+ * engine cannot rebuild a shallow document at an earlier version, so the replica refuses every
1568
+ * later change and export with the same error (standard 2.0 rule M16a).
1569
+ */
1570
+ closedBy = null;
1571
+ /**
1572
+ * For each replica whose changes an import could not apply yet, the counter just past the last
1573
+ * of them. They are applied (and no longer pending) once `version` reaches it.
1574
+ */
1575
+ pending = /* @__PURE__ */ new Map();
1576
+ /**
1577
+ * Registers an import changed: the candidates for another replica's later write, which an undo
1578
+ * or redo must keep (M12). Pruned at each undo and redo.
1579
+ */
1580
+ importedRegisters = /* @__PURE__ */ new Set();
1581
+ /**
1582
+ * Registers an undo or redo put back to another replica's value, with that value: still that
1583
+ * replica's write for the next undo or redo, though this replica wrote it last.
1584
+ */
1585
+ keptRegisters = /* @__PURE__ */ new Map();
1586
+ /**
1587
+ * The value this replica last wrote to each register (`undefined`: deleted it). Another
1588
+ * replica's later write of the same value is not a change an undo must keep (a script's own undo
1589
+ * that puts back this replica's value, for instance).
1590
+ */
1591
+ ownRegisters = /* @__PURE__ */ new Map();
1592
+ /**
1593
+ * The undo scope of this replica's last write to each register (`null`: a `system` or `import`
1594
+ * transaction), with the value written. An undo in one scope keeps the value another scope wrote
1595
+ * later, as it keeps another replica's (M12a). Pruned at each undo and redo.
1596
+ */
1597
+ localWrites = /* @__PURE__ */ new Map();
1598
+ /** A new, empty document. Only one replica creates a document; others `load` it. */
1599
+ static create(t, e, s) {
1600
+ return rt.createWith(t, e, s, bt("create"), () => {
1601
+ }).replica;
1602
+ }
1603
+ /**
1604
+ * A new document whose initial content `build` writes in the creating commit, before undo
1605
+ * history starts: file imports and other bulk builds. Undo bookkeeping grows faster than
1606
+ * linearly with a transaction's size, so bulk content must not go through `transact`.
1607
+ * `build` is staged like a transaction; if it throws, no document is made.
1608
+ */
1609
+ static createWith(t, e, s, n, r) {
1610
+ zt(n), De(r);
1611
+ const i = Xt(e);
1612
+ Et(s);
1613
+ const c = new It();
1614
+ c.setPeerId(s), dt(c, t);
1615
+ const h = c.getMap(ct);
1616
+ h.set("docId", Q(i)), h.set("kit", t.kit), h.set(St, t.schemaVersion), h.set("kdm", Gt);
1617
+ const { result: a, staged: p } = Ut.stage(c, t, r);
1618
+ try {
1619
+ p.apply(c, t, () => {
1620
+ });
1621
+ } catch (g) {
1622
+ throw Ce(g);
1623
+ }
1624
+ return c.commit({ origin: Pe(n.kind), message: ot(n, t.schemaVersion) }), { replica: new rt(c, i, t, s), result: a };
1625
+ }
1626
+ /**
1627
+ * Opens a snapshot (or a full change export) as a new writable replica of `actor`. Refuses
1628
+ * (`schema`) a document of another kit or of another KDM version, and (`newer-schema`) one whose
1629
+ * minimum schema version (rule M20) is newer than `schema`'s; bytes that are not a KDM snapshot
1630
+ * are `encoding` errors.
1631
+ *
1632
+ * A snapshot holds the changes its replica applied, not those still pending on it (see
1633
+ * `hasPendingChanges`): the loaded replica has none pending, and fetches those changes again
1634
+ * when it syncs.
1635
+ */
1636
+ static load(t, e, s) {
1637
+ Et(s);
1638
+ const { docId: n, engine: r } = yt(e), i = new It();
1639
+ dt(i, t);
1640
+ let c;
1641
+ try {
1642
+ c = i.import(r);
1643
+ } catch (m) {
1644
+ throw f.encoding(C(m));
1645
+ }
1646
+ const h = i.getMap(ct), a = (m) => {
1647
+ const O = h.get(m);
1648
+ return O === void 0 || tt(O) ? null : O;
1649
+ }, p = a("kit");
1650
+ if (p === null) throw f.encoding("not a snapshot: meta.kit is missing (load a snapshot or a full export, not changes only)");
1651
+ if (p !== t.kit) throw f.schema(`the document belongs to ${D(p)}, not \`${t.kit}\``);
1652
+ const g = a("kdm");
1653
+ if (g !== Gt) throw f.schema(`the document uses kdm ${D(g)}; this build reads ${Gt}`);
1654
+ const d = it(i);
1655
+ if (d === null)
1656
+ throw f.schema(`the document has schema version ${D(a(St))}; this kit reads schema versions up to ${t.schemaVersion}`);
1657
+ if (d > t.schemaVersion) throw f.newerSchema(d, t.schemaVersion);
1658
+ const y = a("docId");
1659
+ let v = null;
1660
+ try {
1661
+ v = typeof y == "string" ? Xt(y) : null;
1662
+ } catch {
1663
+ v = null;
1664
+ }
1665
+ if (!v || !wt(v, n)) throw f.encoding(`the bytes are labelled as document ${Q(n)}, but hold another`);
1666
+ const k = new rt(i, n, t, s);
1667
+ return k.notePending(c), k;
1668
+ }
1669
+ /** The document's durable identity, as a lowercase hyphenated UUID. */
1670
+ get docId() {
1671
+ return Q(this.docIdBytes);
1672
+ }
1673
+ version() {
1674
+ return X.fromEngine(this.doc.oplogVersion());
1675
+ }
1676
+ /**
1677
+ * The document's minimum schema version (rule M20): the version it was created with, or the
1678
+ * largest one a transaction raised it to (`Tx.raiseSchemaVersion`). Never more than this
1679
+ * replica's schema version: loads and imports refuse such documents.
1680
+ */
1681
+ minSchemaVersion() {
1682
+ return it(this.doc) ?? 0;
1683
+ }
1684
+ /**
1685
+ * The newest schema version any change of this replica was written under (rule M5a: every
1686
+ * commit records its author's schema version), or `null` when no change records one (they all
1687
+ * predate the rule). A version above this replica's schema means someone edits the document
1688
+ * with a newer kit: objects of types this schema lacks read as their `$type` only and refuse
1689
+ * edits here (`unknown-type`), and a host asks the person to update the kit. A shallow replica
1690
+ * (rule M16a) sees only the changes after its root.
1691
+ */
1692
+ authorSchemaVersion() {
1693
+ let t = null;
1694
+ for (const e of this.doc.getAllChanges().values())
1695
+ for (const s of e) {
1696
+ const n = s.message ? vs(s.message)?.schemaVersion ?? null : null;
1697
+ n !== null && (t === null || n > t) && (t = n);
1698
+ }
1699
+ return t;
1700
+ }
1701
+ /**
1702
+ * Runs `f` as one transaction: one commit, one undo step, one origin. Operations are staged while
1703
+ * `f` runs and applied only if it returns: if `f` throws, the document, its version, and its
1704
+ * exports are unchanged and the error propagates. `f` must be synchronous.
1705
+ */
1706
+ transact(t, e) {
1707
+ this.idle(), this.checkOpen(), zt(t), De(e), this.busy = !0;
1708
+ let s;
1709
+ try {
1710
+ s = Ut.stage(this.doc, this.schema, e);
1711
+ } finally {
1712
+ this.busy = !1;
1713
+ }
1714
+ const { result: n, staged: r } = s;
1715
+ if (r.empty) return n;
1716
+ if (r.raisesSchema && t.kind !== Ft)
1717
+ throw f.invalidValue("$meta", "schemaVersion", `is raised only in a \`system\` transaction, not \`${t.kind}\``);
1718
+ const i = this.doc.frontiers(), c = /* @__PURE__ */ new Set();
1719
+ try {
1720
+ r.apply(this.doc, this.schema, (a) => c.add(a));
1721
+ } catch (a) {
1722
+ if (this.doc.commit({ origin: kt }), !te(this.doc.frontiers(), i)) {
1723
+ try {
1724
+ this.doc.revertTo(i);
1725
+ } catch (p) {
1726
+ throw f.engine(C(p));
1727
+ }
1728
+ this.doc.commit({ origin: kt, message: ot(bt("rollback"), this.schema.schemaVersion) });
1729
+ }
1730
+ throw Ce(a);
1731
+ }
1732
+ this.runs.pending = r.undoTouches;
1733
+ const h = Nt(t.kind);
1734
+ if (this.runs.current !== null && h !== null) {
1735
+ const a = `${h}:${this.runs.current}`;
1736
+ this.runs.groups.set(a, fs(this.runs.groups.get(a) ?? [], r.undoTouches));
1737
+ }
1738
+ this.doc.commit({ origin: Pe(t.kind), message: ot(t, this.schema.schemaVersion) });
1739
+ for (const a of c) this.changed.add(a);
1740
+ return this.noteOwnWrites(r.registerWrites, Nt(t.kind)), n;
1741
+ }
1742
+ exists(t) {
1743
+ $("an object id", t);
1744
+ try {
1745
+ return P(this.doc, t), !0;
1746
+ } catch {
1747
+ return !1;
1748
+ }
1749
+ }
1750
+ objectType(t) {
1751
+ return $("an object id", t), jt(this.doc, t);
1752
+ }
1753
+ get(t, e) {
1754
+ return Y(t, e), fe(this.doc, this.schema, t, e);
1755
+ }
1756
+ text(t, e) {
1757
+ return Y(t, e), F(this.doc, this.schema, t, e, "text")?.toString() ?? "";
1758
+ }
1759
+ /**
1760
+ * A text field as runs of characters with equal marks (rule M19), in order: adjacent runs differ
1761
+ * in their marks, no run is empty, and only the field's declared marks appear. A field that
1762
+ * declares no marks reads as one unmarked run (none when empty). Positions are counted in UTF-16
1763
+ * code units (`insert.length`).
1764
+ */
1765
+ textDelta(t, e) {
1766
+ return Y(t, e), Ss(this.doc, this.schema, t, e);
1767
+ }
1768
+ /** The length of a text field in UTF-16 code units. */
1769
+ textLength(t, e) {
1770
+ return Y(t, e), F(this.doc, this.schema, t, e, "text")?.length ?? 0;
1771
+ }
1772
+ list(t, e) {
1773
+ Y(t, e);
1774
+ const s = F(this.doc, this.schema, t, e, "list");
1775
+ return s ? _t(s.toArray()) : [];
1776
+ }
1777
+ /** One key of a map field, or `null`. */
1778
+ mapGet(t, e, s) {
1779
+ Y(t, e), $("a map key", s);
1780
+ const n = F(this.doc, this.schema, t, e, "map");
1781
+ return n ? Wt(n.get(s)) : null;
1782
+ }
1783
+ /**
1784
+ * A map field's keys and values, sorted by key (code point order, as in the canonical state),
1785
+ * each as `mapGet` reads it. Reads the whole map.
1786
+ */
1787
+ mapEntries(t, e) {
1788
+ Y(t, e);
1789
+ const s = F(this.doc, this.schema, t, e, "map");
1790
+ return s ? Qe(s) : [];
1791
+ }
1792
+ /**
1793
+ * The tree's nodes in pre-order (each parent before its children, siblings in order). A node
1794
+ * that names no object is skipped with its subtree, as in `stateJson`.
1795
+ */
1796
+ tree(t, e) {
1797
+ Y(t, e);
1798
+ const s = [], n = F(this.doc, this.schema, t, e, "tree"), r = (i, c) => {
1799
+ for (const h of i ?? []) {
1800
+ const a = Bt(h);
1801
+ if (a === null) continue;
1802
+ const p = ds(h.id);
1803
+ s.push({ node: p, object: a, parent: c }), r(h.children(), p);
1804
+ }
1805
+ };
1806
+ return n && r(n.roots(), null), s;
1807
+ }
1808
+ /**
1809
+ * Ids of the objects of type `ty`, sorted. One pass over the objects, so it suits large
1810
+ * documents; it costs O(objects) per call.
1811
+ */
1812
+ objectsOfType(t) {
1813
+ return $("a type name", t), ts(this.doc, t);
1814
+ }
1815
+ /**
1816
+ * The changes this replica has that a replica at `since` lacks, labelled with this document's id.
1817
+ *
1818
+ * With `Version.empty()` (every change) the bytes always `load` as this document. A shallow
1819
+ * replica (rule M16a) has no changes before its root, so for a `since` that does not reach its
1820
+ * root (the empty version above all) it answers its snapshot: its state at the root with every
1821
+ * change after it, which loads as a shallow replica with the same root and imports into any
1822
+ * replica that has the root, as these changes would. On a full replica, and for a `since` at or
1823
+ * after the root, the bytes are the changes alone.
1824
+ */
1825
+ exportChanges(t = X.empty()) {
1826
+ if (this.checkOpen(), !(t instanceof X)) throw new L("invalid-value", "a version must be a `Version`");
1827
+ if (!this.reaches(t)) return this.snapshot();
1828
+ let e;
1829
+ try {
1830
+ e = this.doc.export({ mode: "update", from: t.toEngine() });
1831
+ } catch (s) {
1832
+ throw f.encoding(C(s));
1833
+ }
1834
+ return Vt(this.docIdBytes, e);
1835
+ }
1836
+ /**
1837
+ * Applies changes from another replica or from storage, in any order, any number of times.
1838
+ * Answers the objects whose state changed. Bytes that are not a KDM export are `encoding`
1839
+ * errors; changes of another document are `wrong-document` errors and change nothing.
1840
+ *
1841
+ * Changes that raise the document's minimum schema version (rule M20) above this replica's
1842
+ * schema are `newer-schema` errors and change nothing: the state, the version, the exports, and
1843
+ * the changes still pending are as before the import. The engine cannot check changes without
1844
+ * applying them, so the replica is rebuilt from its history before the import; that clears its
1845
+ * undo and redo history, and `subscribeText` listeners stop receiving changes. A build that
1846
+ * meets this error is too old for the document: the host stops syncing and asks for an update.
1847
+ * A shallow replica cannot be rebuilt so: it keeps the changes and refuses every later change
1848
+ * and export with this error, and the host reopens the document from what it stored.
1849
+ *
1850
+ * On a shallow replica, changes that depend on history before its root (made by a replica that
1851
+ * had not seen the root yet) are `history-missing` errors and change nothing; see `rebase`.
1852
+ */
1853
+ importChanges(t) {
1854
+ this.idle(), this.checkOpen();
1855
+ const { docId: e, engine: s } = yt(t);
1856
+ if (!wt(e, this.docIdBytes)) throw f.wrongDocument(this.docId, Q(e));
1857
+ const n = this.doc.oplogFrontiers();
1858
+ let r = null;
1859
+ const { value: i, changed: c, registers: h } = Qt(this.doc, () => {
1860
+ try {
1861
+ return this.doc.import(s);
1862
+ } catch (g) {
1863
+ return r = g, null;
1864
+ }
1865
+ });
1866
+ try {
1867
+ Ht(this.doc, this.schema);
1868
+ } catch (g) {
1869
+ throw this.doc.isShallow() ? this.closedBy = g : this.restore(n), g;
1870
+ }
1871
+ const a = it(this.doc);
1872
+ if (a !== null && a > this.schema.schemaVersion) {
1873
+ const g = f.newerSchema(a, this.schema.schemaVersion);
1874
+ throw this.doc.isShallow() ? (this.closedBy = g, g) : (this.restore(n), g);
1875
+ }
1876
+ if (i === null) throw Ne(r);
1877
+ if (["person", "agent"].some((g) => this.undoManagers[g].canUndo() || this.undoManagers[g].canRedo())) for (const g of h) this.importedRegisters.add(g);
1878
+ this.notePending(i);
1879
+ for (const g of c) this.changed.add(g);
1880
+ return this.reopenUndoGroup(), Tt(c);
1881
+ }
1882
+ /**
1883
+ * Whether this replica holds imported changes it could not apply yet, because they depend on
1884
+ * changes it has not received. Importing changes out of order is legitimate (they are applied as
1885
+ * soon as what they depend on arrives); a replica that stays in this state is missing changes,
1886
+ * which a sync from `version` fetches. Pending changes are not in `version`, the state, or the
1887
+ * exports.
1888
+ */
1889
+ hasPendingChanges() {
1890
+ const t = this.doc.oplogVersion();
1891
+ for (const [e, s] of this.pending) if ((t.get(e) ?? 0) < s) return !0;
1892
+ return !1;
1893
+ }
1894
+ /** The objects changed since the last call, by local transactions, imports, undo, and redo. */
1895
+ takeChanged() {
1896
+ const t = Tt(this.changed);
1897
+ return this.changed = /* @__PURE__ */ new Set(), t;
1898
+ }
1899
+ /** A compacted copy of the whole document, for fast loading and new replicas. */
1900
+ snapshot() {
1901
+ this.checkOpen();
1902
+ let t;
1903
+ try {
1904
+ t = this.doc.export({ mode: "snapshot" });
1905
+ } catch (e) {
1906
+ throw f.encoding(C(e));
1907
+ }
1908
+ return Vt(this.docIdBytes, t);
1909
+ }
1910
+ /**
1911
+ * A **shallow snapshot** (standard 2.0 rule M16a): the document's current state with only the
1912
+ * history after `at`, for a device that holds a large document without its whole history. `load`
1913
+ * opens it as a shallow replica, which edits, exports, imports, and merges like a full one;
1914
+ * history before its root stays with whoever holds it (the sync server).
1915
+ *
1916
+ * The root is the latest version at or before `at` that every later change descends from (the
1917
+ * engine moves it back past changes made concurrently with `at`, so they stay in the retained
1918
+ * history); `Version.empty()` keeps the whole history. `at` must be a version this replica has
1919
+ * (`invalid-value` otherwise); on a shallow replica, an `at` before its own root is its root.
1920
+ */
1921
+ shallowSnapshot(t) {
1922
+ if (this.checkOpen(), !(t instanceof X)) throw new L("invalid-value", "a version must be a `Version`");
1923
+ if (!this.version().includes(t)) throw f.invalidValue("$shallow", "version", "names changes this replica does not have");
1924
+ const e = this.reaches(t) ? this.doc.vvToFrontiers(t.toEngine()) : this.doc.shallowSinceFrontiers();
1925
+ let s;
1926
+ try {
1927
+ s = this.doc.export({ mode: "shallow-snapshot", frontiers: e });
1928
+ } catch (n) {
1929
+ throw f.encoding(C(n));
1930
+ }
1931
+ return Vt(this.docIdBytes, s);
1932
+ }
1933
+ /** Whether this replica holds only part of the document's history: it was loaded from a `shallowSnapshot` (or a snapshot of a shallow replica). */
1934
+ isShallow() {
1935
+ return this.doc.isShallow();
1936
+ }
1937
+ /**
1938
+ * The version a shallow replica's retained history starts at (its root): it has every change
1939
+ * after it, and none of the history it summarizes. `null` for a full replica.
1940
+ */
1941
+ shallowRoot() {
1942
+ return this.doc.isShallow() ? X.fromEngine(this.doc.shallowSinceVV()) : null;
1943
+ }
1944
+ /**
1945
+ * Whether this replica carries the **document's whole history** (sync protocol S20): it is full,
1946
+ * or it is shallow and its root is the document's birth, so no replica of the document can hold
1947
+ * changes before it. A copy made by `copyAsNewDocument` is born at its root, and every replica
1948
+ * loaded from it, its snapshots and its drafts keep that root; a shallow snapshot taken later
1949
+ * (`shallowSnapshot` after more changes) does not.
1950
+ *
1951
+ * The birth is the version the copy recorded in the change that made it, read from this
1952
+ * replica's state **at its root**: a change after the root, which any client may make, never
1953
+ * counts, and a value written in such a change could only name a version before the root it is
1954
+ * part of. A server that trusts no client decides from the bytes alone. Shallow documents that
1955
+ * record no birth (copies made before it was recorded) do not carry it. As the Rust
1956
+ * `Replica::carries_whole_history`.
1957
+ */
1958
+ carriesWholeHistory() {
1959
+ return this.checkOpen(), Be(this.doc);
1960
+ }
1961
+ /**
1962
+ * `carriesWholeHistory` of the document `bytes` (a snapshot or a full export) hold, read without
1963
+ * a schema, as a sync server reads a room's first state (rule S20). Bytes that are not a KDM
1964
+ * export, or that do not decode, are `encoding` errors. As the Rust
1965
+ * `Replica::snapshot_carries_whole_history`.
1966
+ */
1967
+ static snapshotCarriesWholeHistory(t) {
1968
+ const { engine: e } = yt(t), s = new It();
1969
+ try {
1970
+ if (gs(e, !0).mode !== "shallow-snapshot") return !0;
1971
+ s.import(e);
1972
+ } catch (n) {
1973
+ throw s.free(), f.encoding(C(n));
1974
+ }
1975
+ try {
1976
+ return Be(s);
1977
+ } finally {
1978
+ s.free();
1979
+ }
1980
+ }
1981
+ /** Whether `version` is at or after this replica's shallow root: always, on a full replica. */
1982
+ reaches(t) {
1983
+ const e = this.shallowRoot();
1984
+ return e === null || t.includes(e);
1985
+ }
1986
+ /**
1987
+ * Replaces this replica's document with `snapshot` (a full or shallow snapshot of the same
1988
+ * document, as a server answers it) plus every change this replica has that `snapshot` lacks,
1989
+ * and answers the objects whose state changed. For a shallow replica whose import failed with
1990
+ * `history-missing`: a newer snapshot from the server holds the changes it could not take,
1991
+ * rooted early enough for them, and this replica's own changes (pushed or not) are kept on top.
1992
+ * The state is what importing every change of both would give.
1993
+ *
1994
+ * Refuses (`wrong-document`) a snapshot of another document, what `load` refuses, and
1995
+ * (`history-missing`) a shallow snapshot whose root is after changes of this replica it lacks; a
1996
+ * refused rebase changes nothing. Clears the undo and redo history, like any load, and
1997
+ * `subscribeText` listeners stop receiving changes.
1998
+ */
1999
+ rebase(t) {
2000
+ this.idle(), this.checkOpen();
2001
+ const { docId: e } = yt(t);
2002
+ if (!wt(e, this.docIdBytes)) throw f.wrongDocument(this.docId, Q(e));
2003
+ const s = rt.load(this.schema, t, this.actor);
2004
+ if (!s.version().includes(this.version()) && (s.importChanges(this.exportChanges(s.version())), !s.version().includes(this.version())))
2005
+ throw f.historyMissing(an);
2006
+ const n = (h) => h.objects ?? {}, r = n(this.stateJson()), i = n(s.stateJson()), c = /* @__PURE__ */ new Set();
2007
+ for (const h of /* @__PURE__ */ new Set([...Object.keys(r), ...Object.keys(i)]))
2008
+ (D(r[h] ?? null) !== D(i[h] ?? null) || h in r != h in i) && c.add(h);
2009
+ Je(this.undoManagers), this.doc = s.doc, this.undoManagers = s.undoManagers, this.importedRegisters.clear(), this.keptRegisters.clear(), this.ownRegisters.clear(), this.localWrites.clear();
2010
+ for (const [h, a] of s.pending) this.pending.set(h, Math.max(a, this.pending.get(h) ?? 0));
2011
+ this.prunePending(), this.reopenUndoGroup();
2012
+ for (const h of c) this.changed.add(h);
2013
+ return Tt(c);
2014
+ }
2015
+ /**
2016
+ * Undoes the person's last transaction on this replica (the `person` scope, M12a). Changes from
2017
+ * other replicas and from other scopes (an agent's) are kept, including later changes to the
2018
+ * same object and to the same field: a register another replica or scope wrote after the undone
2019
+ * transaction keeps that value (M12). The objects it changes are reported by `takeChanged`.
2020
+ */
2021
+ undo() {
2022
+ return this.undoIn("person");
2023
+ }
2024
+ /** Redoes the person's last undone transaction, keeping other replicas' and scopes' later changes and reporting what it changes like `undo`. */
2025
+ redo() {
2026
+ return this.redoIn("person");
2027
+ }
2028
+ /** Undoes the last transaction of `scope` on this replica, like `undo` for the person. */
2029
+ undoIn(t) {
2030
+ const e = () => this.undoManagers[pt(t)];
2031
+ return this.history(t, () => this.replayRun(() => e().topUndoValue(), () => e().undo()));
2032
+ }
2033
+ /** Redoes the last undone transaction of `scope`, like `redo` for the person. */
2034
+ redoIn(t) {
2035
+ const e = () => this.undoManagers[pt(t)];
2036
+ return this.history(t, () => this.replayRun(() => e().topRedoValue(), () => e().redo()));
2037
+ }
2038
+ /**
2039
+ * One undo (or redo) of a run (rule M12b): the top step, and every step under it of the same undo
2040
+ * group, which an import split. Each undo or redo step it makes carries the run on.
2041
+ */
2042
+ replayRun(t, e) {
2043
+ this.runs.replaying = !0;
2044
+ try {
2045
+ const s = Ke(t()), n = e();
2046
+ let r = n;
2047
+ for (; r && s !== null && Ke(t()) === s; ) r = e();
2048
+ return n;
2049
+ } finally {
2050
+ this.runs.replaying = !1, this.runs.popped = null;
2051
+ }
2052
+ }
2053
+ /** Whether `undo` has a transaction of the person to undo. */
2054
+ canUndo() {
2055
+ return this.canUndoIn("person");
2056
+ }
2057
+ /** Whether `redo` has an undone transaction of the person to redo. */
2058
+ canRedo() {
2059
+ return this.canRedoIn("person");
2060
+ }
2061
+ /** Whether `undoIn(scope)` has a transaction to undo. */
2062
+ canUndoIn(t) {
2063
+ return this.idle(), this.undoManagers[pt(t)].canUndo();
2064
+ }
2065
+ /** Whether `redoIn(scope)` has an undone transaction to redo. */
2066
+ canRedoIn(t) {
2067
+ return this.idle(), this.undoManagers[pt(t)].canRedo();
2068
+ }
2069
+ /** The original objects and fields of the next undo step, including its whole group. */
2070
+ undoTouchesIn(t) {
2071
+ return this.idle(), this.historyTouches(t, this.undoManagers[pt(t)].topUndoValue());
2072
+ }
2073
+ /** The original objects and fields of the next redo step. Reading leaves both histories intact. */
2074
+ redoTouchesIn(t) {
2075
+ return this.idle(), this.historyTouches(t, this.undoManagers[pt(t)].topRedoValue());
2076
+ }
2077
+ historyTouches(t, e) {
2078
+ const s = we(e);
2079
+ return structuredClone(s?.run != null ? this.runs.groups.get(`${t}:${s.run}`) ?? s.touches : s?.touches ?? []);
2080
+ }
2081
+ /**
2082
+ * Starts an undo group: the transactions until `endUndoGroup` undo and redo as one step. Groups
2083
+ * do not nest (`invalid-value`). An undo or a redo ends the open group first, so undo while
2084
+ * grouping reverts the group as one step. It stays one undo step when other replicas' changes
2085
+ * arrive while it is open, also when they touch what the group changed (rule M12b): one undo
2086
+ * takes back all of it and keeps their changes. A group spans
2087
+ * both undo scopes (M12a): the person's transactions in it are one person step, and an agent's
2088
+ * are one agent step.
2089
+ */
2090
+ beginUndoGroup() {
2091
+ if (this.idle(), this.grouping) throw f.invalidValue("$undo", "group", "is already open");
2092
+ try {
2093
+ this.undoManagers.person.groupStart();
2094
+ } catch (t) {
2095
+ throw f.engine(C(t));
2096
+ }
2097
+ try {
2098
+ this.undoManagers.agent.groupStart();
2099
+ } catch (t) {
2100
+ throw this.undoManagers.person.groupEnd(), f.engine(C(t));
2101
+ }
2102
+ this.grouping = !0, this.runs.current = this.runs.next, this.runs.next += 1;
2103
+ }
2104
+ /** Ends the open undo group; does nothing when none is open. */
2105
+ endUndoGroup() {
2106
+ this.idle(), this.closeUndoGroup();
2107
+ }
2108
+ /** Drops the person's redo stack, keeping the undo stack. */
2109
+ clearRedo() {
2110
+ this.idle(), this.undoManagers.person.clearRedo();
2111
+ }
2112
+ /** Follows one text field: `listener` gets each change with whether this replica made it. */
2113
+ subscribeText(t, e, s) {
2114
+ Y(t, e);
2115
+ const n = F(this.doc, this.schema, t, e, "text");
2116
+ if (!n) throw f.notFound(`${t}.${e}`);
2117
+ return n.subscribe((r) => {
2118
+ for (const i of r.events)
2119
+ i.diff.type === "text" && s(i.diff.diff, r.by === "local");
2120
+ });
2121
+ }
2122
+ /**
2123
+ * A draft of this document (standard 2.0 A12): a new writable replica of `actor` holding every
2124
+ * change this one has, with no undo history. Edits made on it stay there until `mergeChanges`
2125
+ * takes them into another replica of the document.
2126
+ */
2127
+ fork(t) {
2128
+ return this.forkAt(this.version(), t);
2129
+ }
2130
+ /** A draft of this document as it was at `version` (see `fork`); `version` must be one this replica has reached. */
2131
+ forkAt(t, e) {
2132
+ if (this.idle(), this.checkOpen(), Et(e), !(t instanceof X)) throw new L("invalid-value", "a version must be a `Version`");
2133
+ if (!this.version().includes(t)) throw f.invalidValue("$draft", "version", "names changes this replica does not have");
2134
+ if (this.doc.isShallow() && !t.equals(this.version())) throw f.historyMissing(cn);
2135
+ let s;
2136
+ try {
2137
+ s = this.doc.isShallow() ? this.doc.fork() : this.doc.forkAt(this.doc.vvToFrontiers(t.toEngine()));
2138
+ } catch (n) {
2139
+ throw f.engine(C(n));
2140
+ }
2141
+ return dt(s, this.schema), new rt(s, this.docIdBytes, this.schema, e);
2142
+ }
2143
+ /**
2144
+ * A copy of this document as a **new document** (data model, "A copy is a new document"): the
2145
+ * same objects, ids and content under the new permanent `docId`, as a writable replica of
2146
+ * `actor`. For a template instantiated twice, a copied file, or the same bytes stored twice: each
2147
+ * copy is its own document, with its own co-editing room. Unlike `fork` (a draft of the same
2148
+ * document, merged back), a copy never merges with its source or another copy: `importChanges`,
2149
+ * `mergeChanges` and `rebase` refuse each other's bytes (`wrong-document`).
2150
+ *
2151
+ * Answers a replica, as `fork` does, so a host edits it or stores its `snapshot`. The copy is a
2152
+ * shallow replica (rule M16a) rooted at its own first change: it holds the current state and no
2153
+ * history, so no deleted content, no earlier version and not the source's `docId` travel with
2154
+ * it; it forks only at its current version, and `changesSince` a version before the copy is
2155
+ * `history-missing`. Its undo and redo histories are empty. Object ids, tree node ids and every
2156
+ * value are kept; a blob is its content-addressed reference, so it resolves wherever the
2157
+ * source's blobs do (a host whose blob store is per document copies the referenced blobs too).
2158
+ *
2159
+ * There is no option to keep the history: the copy would share the source's change ids with
2160
+ * another document's, every earlier version of it would name the source's `docId`, and deleted
2161
+ * content would travel. Refuses (`invalid-value`) a `docId` equal to this document's. The
2162
+ * changes still pending on this replica are not in the copy. The Rust crate's
2163
+ * `Replica::copy_as_new_document` does the same.
2164
+ */
2165
+ copyAsNewDocument(t, e) {
2166
+ this.idle(), this.checkOpen();
2167
+ const s = Xt(t);
2168
+ if (Et(e), wt(s, this.docIdBytes)) throw f.invalidValue("$copy", "docId", "is this document's; a copy needs a new one");
2169
+ let n;
2170
+ try {
2171
+ const i = new It();
2172
+ dt(i, this.schema), i.import(this.doc.export({ mode: "shallow-snapshot", frontiers: this.doc.oplogFrontiers() })), i.setPeerId(e);
2173
+ const c = new Map(i.oplogVersion().toJSON()), h = e.toString();
2174
+ c.set(h, (c.get(h) ?? 0) + 1), i.getMap(ct).set("docId", Q(s)), i.getMap(qe).set(Ye, ms.parseJSON(c).encode()), i.commit({ origin: Ft, message: ot(bt("new-document"), this.schema.schemaVersion) }), n = i.export({ mode: "shallow-snapshot", frontiers: i.oplogFrontiers() });
2175
+ } catch (i) {
2176
+ throw f.encoding(C(i));
2177
+ }
2178
+ const r = rt.load(this.schema, Vt(s, n), e);
2179
+ if (!r.carriesWholeHistory()) throw f.engine("the copy is not rooted at the birth it records");
2180
+ return r;
2181
+ }
2182
+ /**
2183
+ * The canonical state this replica would have after importing `changes`, without changing it:
2184
+ * the "after" of a draft's comparison (`diffStates`). Refuses what `mergeChanges` refuses.
2185
+ */
2186
+ mergedState(t) {
2187
+ return this.idle(), this.checkOpen(), je(this.mergedDoc(t), this.schema);
2188
+ }
2189
+ /**
2190
+ * Takes another replica's changes (a draft's, made on a `fork`) into this one as one transaction
2191
+ * of its own, with `origin`: one undo step of the person (unless `origin` is `system` or `import`; M12a). The result
2192
+ * is the state a CRDT import would give, so edits made here (or imported) since the draft was
2193
+ * forked are kept; only the operations that turn this state into the merged one are written,
2194
+ * under this replica's actor. Answers the objects that changed.
2195
+ *
2196
+ * The draft's changes themselves are not imported: merging the same changes twice writes their
2197
+ * effect twice, so a host merges a draft once. Refuses (`invalid-value`) changes that depend on
2198
+ * changes this replica lacks, changes of another document (`wrong-document`), and changes that
2199
+ * raise the minimum schema version beyond this replica's (`newer-schema`); a refused merge
2200
+ * changes nothing.
2201
+ */
2202
+ mergeChanges(t, e) {
2203
+ this.idle(), this.checkOpen(), zt(e);
2204
+ const s = Nt(e.kind), n = this.mergedDoc(t), r = this.doc.oplogFrontiers(), i = n.oplogFrontiers();
2205
+ if (te(r, i)) return /* @__PURE__ */ new Set();
2206
+ let c;
2207
+ try {
2208
+ c = n.diff(r, i);
2209
+ } catch (g) {
2210
+ throw f.engine(C(g));
2211
+ }
2212
+ let h = null;
2213
+ const { changed: a, registers: p } = Qt(this.doc, () => {
2214
+ try {
2215
+ this.doc.applyDiff(c);
2216
+ } catch (g) {
2217
+ h = g;
2218
+ return;
2219
+ }
2220
+ this.doc.commit({ origin: s === null ? e.kind : "person", message: ot(e, this.schema.schemaVersion) });
2221
+ });
2222
+ if (h !== null)
2223
+ throw this.doc.commit({ origin: kt }), te(this.doc.oplogFrontiers(), r) || (this.doc.revertTo(r), this.doc.commit({ origin: kt, message: ot(bt("rollback"), this.schema.schemaVersion) })), f.engine(C(h));
2224
+ for (const g of p) {
2225
+ const d = this.registerValue(g);
2226
+ d.container || (this.ownRegisters.set(g, d.value), this.localWrites.set(g, { by: s === null ? null : "person", value: d.value }));
2227
+ }
2228
+ for (const g of a) this.changed.add(g);
2229
+ return Tt(a);
2230
+ }
2231
+ /** A copy of this document with `changes` imported, checked as `mergeChanges` checks them. */
2232
+ mergedDoc(t) {
2233
+ const { docId: e, engine: s } = yt(t);
2234
+ if (!wt(e, this.docIdBytes)) throw f.wrongDocument(this.docId, Q(e));
2235
+ const n = this.doc.fork();
2236
+ dt(n, this.schema);
2237
+ let r;
2238
+ try {
2239
+ r = n.import(s);
2240
+ } catch (c) {
2241
+ throw Ne(c);
2242
+ }
2243
+ if (r.pending && r.pending.size > 0) throw f.invalidValue("$draft", "changes", "depend on changes this replica does not have");
2244
+ Ht(n, this.schema);
2245
+ const i = it(n);
2246
+ if (i !== null && i > this.schema.schemaVersion) throw f.newerSchema(i, this.schema.schemaVersion);
2247
+ return n;
2248
+ }
2249
+ /**
2250
+ * What changed since `since` (a version this replica reached), as a write's receipt: a
2251
+ * `StateDiff` without `texts`, values cut to excerpts, objects named by their tool ids where the
2252
+ * schema declares them (OM9). Only the objects the changes since then touched are read, here and
2253
+ * in a fork at `since`; the answer equals `diffStates` of the two whole states. A version this
2254
+ * replica's history does not hold is a `history-missing` error. As the Rust `changes_since`.
2255
+ */
2256
+ changesSince(t, e = {}) {
2257
+ if (this.idle(), this.checkOpen(), !(t instanceof X)) throw new L("invalid-value", "a version must be a `Version`");
2258
+ if (!this.version().includes(t)) throw f.historyMissing(rn);
2259
+ if (t.equals(this.version())) return ce([], {}, {}, () => null, !1);
2260
+ const s = this.forkAt(t, this.actor), r = [...this.forkAt(t, this.actor).importChanges(this.exportChanges(t))].sort(M), i = (d, y) => {
2261
+ try {
2262
+ return jt(d, y);
2263
+ } catch {
2264
+ return null;
2265
+ }
2266
+ }, c = (d) => {
2267
+ const y = {};
2268
+ for (const v of r) i(d, v) !== null && (y[v] = os(d, this.schema, v));
2269
+ return y;
2270
+ }, h = (d) => i(this.doc, d) ?? i(s.doc, d), a = { objects: c(s.doc) }, p = { objects: c(this.doc) };
2271
+ let g = Bs(ce(r, a.objects, p.objects, h, !1), this.schema);
2272
+ return e.textSpans && (g = rs(g, a, p)), Ps(g, this.schema, Dt.ofReplica(s), Dt.ofReplica(this));
2273
+ }
2274
+ /** The whole document in canonical form; see `stateText`. */
2275
+ stateJson() {
2276
+ return je(this.doc, this.schema);
2277
+ }
2278
+ /** The canonical state as text; equal to the Rust `state_json().to_string()` for the same changes. */
2279
+ stateText() {
2280
+ return D(this.stateJson());
2281
+ }
2282
+ /**
2283
+ * Replaces the document with its history up to `frontiers`, dropping every change applied since.
2284
+ * Changes still pending stay recorded in `pending`: they are missing again, and a sync fetches
2285
+ * them.
2286
+ */
2287
+ restore(t) {
2288
+ let e;
2289
+ try {
2290
+ e = this.doc.forkAt(t);
2291
+ } catch (s) {
2292
+ throw f.engine(C(s));
2293
+ }
2294
+ dt(e, this.schema), e.setPeerId(this.actor), Je(this.undoManagers), this.doc = e, this.undoManagers = Ue(e, this.runs), this.importedRegisters.clear(), this.keptRegisters.clear(), this.ownRegisters.clear(), this.localWrites.clear(), this.reopenUndoGroup();
2295
+ }
2296
+ /** Records the changes an import left pending, and forgets those applied since. */
2297
+ notePending(t) {
2298
+ for (const [e, { end: s }] of t.pending ?? []) this.pending.set(e, Math.max(s, this.pending.get(e) ?? 0));
2299
+ this.prunePending();
2300
+ }
2301
+ /** Forgets the pending changes applied since they were recorded. */
2302
+ prunePending() {
2303
+ if (this.pending.size === 0) return;
2304
+ const t = this.doc.oplogVersion();
2305
+ for (const [e, s] of this.pending) (t.get(e) ?? 0) >= s && this.pending.delete(e);
2306
+ }
2307
+ /** Throws the error that closed this shallow replica, if one did (see `importChanges`). */
2308
+ checkOpen() {
2309
+ if (this.closedBy) throw this.closedBy;
2310
+ }
2311
+ idle() {
2312
+ if (this.busy) throw f.engine("the document cannot change while a transaction runs; transactions do not nest");
2313
+ }
2314
+ closeUndoGroup() {
2315
+ this.grouping && (this.undoManagers.person.groupEnd(), this.undoManagers.agent.groupEnd(), this.grouping = !1, this.runs.current = null);
2316
+ }
2317
+ /**
2318
+ * After an import, makes sure the open group is still open in the engine: the engine ends it
2319
+ * when the import changes what the group changed, and then the group goes on as a new one.
2320
+ * Starting a group the engine still has open changes nothing; if the engine can start none, no
2321
+ * group is open any more.
2322
+ */
2323
+ reopenUndoGroup() {
2324
+ if (!this.grouping) return;
2325
+ const t = (e) => {
2326
+ try {
2327
+ return e.groupStart(), !0;
2328
+ } catch (s) {
2329
+ return C(s).includes("already an active undo group");
2330
+ }
2331
+ };
2332
+ t(this.undoManagers.person) && t(this.undoManagers.agent) || (this.undoManagers.person.groupEnd(), this.undoManagers.agent.groupEnd(), this.grouping = !1);
2333
+ }
2334
+ history(t, e) {
2335
+ this.idle(), this.checkOpen(), this.closeUndoGroup();
2336
+ const s = this.othersRegisters().map(([a, p]) => [a, p, void 0]);
2337
+ for (const [a, p, g] of this.otherScopesRegisters(t)) s.push([a, p, g]);
2338
+ const { value: n, changed: r, registers: i } = Qt(this.doc, () => {
2339
+ try {
2340
+ return e();
2341
+ } catch (a) {
2342
+ throw f.engine(C(a));
2343
+ }
2344
+ });
2345
+ for (const a of r) this.changed.add(a);
2346
+ for (const a of i) {
2347
+ const p = this.registerValue(a);
2348
+ p.container || (this.ownRegisters.set(a, p.value), this.localWrites.set(a, { by: t, value: p.value }));
2349
+ }
2350
+ const c = new Set(i);
2351
+ let h = !1;
2352
+ for (const [a, p, g] of s) {
2353
+ if (!c.has(a)) continue;
2354
+ const d = this.registerValue(a);
2355
+ if (d.container || Ct(d.value, p)) continue;
2356
+ const [y, v] = Fe(a), k = this.doc.getContainerById(y);
2357
+ p === void 0 ? k.delete(v) : k.set(v, p), g !== void 0 ? this.localWrites.set(a, { by: g, value: p }) : (this.localWrites.delete(a), this.keptRegisters.set(a, p)), h = !0;
2358
+ }
2359
+ return h && this.doc.commit({ origin: Ft, message: ot(bt("keep-later-changes"), this.schema.schemaVersion) }), n;
2360
+ }
2361
+ /**
2362
+ * The registers whose current value this replica wrote in another scope than `scope` (or in a
2363
+ * `system` or `import` transaction), with that value and its scope. Forgets the writes whose value
2364
+ * was changed since by anyone.
2365
+ */
2366
+ otherScopesRegisters(t) {
2367
+ const e = [], s = String(this.actor);
2368
+ for (const [n, r] of this.localWrites) {
2369
+ const i = this.registerValue(n);
2370
+ i.container || !Ct(i.value, r.value) || i.lastEditor !== s ? this.localWrites.delete(n) : r.by !== t && e.push([n, i.value, r.by]);
2371
+ }
2372
+ return e;
2373
+ }
2374
+ /** A register's value now (`undefined`: absent), and whether it holds a container instead. */
2375
+ registerValue(t) {
2376
+ const [e, s] = Fe(t), n = this.doc.getContainerById(e);
2377
+ if (!n) return { value: void 0, container: !1, lastEditor: void 0 };
2378
+ const r = n.get(s);
2379
+ return { value: r, container: tt(r), lastEditor: n.getLastEditor(s) };
2380
+ }
2381
+ /**
2382
+ * The registers whose current value another replica wrote, with that value (`undefined`:
2383
+ * deleted there): an import changed them and another peer wrote them last, or an earlier undo or
2384
+ * redo kept them for another replica and nothing changed them since. Prunes both candidate sets
2385
+ * of registers that are this replica's own again.
2386
+ */
2387
+ othersRegisters() {
2388
+ const t = [], e = String(this.actor);
2389
+ for (const [s, n] of this.keptRegisters) {
2390
+ const r = this.registerValue(s);
2391
+ !r.container && Ct(r.value, n) ? t.push([s, n]) : this.keptRegisters.delete(s);
2392
+ }
2393
+ for (const s of this.importedRegisters) {
2394
+ if (this.keptRegisters.has(s)) continue;
2395
+ const n = this.registerValue(s);
2396
+ n.container || n.lastEditor === void 0 || n.lastEditor === e ? this.importedRegisters.delete(s) : this.ownRegisters.has(s) && Ct(this.ownRegisters.get(s), n.value) || t.push([s, n.value]);
2397
+ }
2398
+ return t;
2399
+ }
2400
+ /** Records the registers a local transaction of `scope` wrote, with their values. */
2401
+ noteOwnWrites(t, e) {
2402
+ for (const { id: s, field: n, key: r, value: i } of t) {
2403
+ let c;
2404
+ try {
2405
+ const h = P(this.doc, s);
2406
+ if (n === null) c = h.id;
2407
+ else {
2408
+ const a = h.get(n);
2409
+ if (!tt(a) || a.kind() !== "Map") continue;
2410
+ c = a.id;
2411
+ }
2412
+ } catch {
2413
+ continue;
2414
+ }
2415
+ this.ownRegisters.set(he(c, r), i), this.localWrites.set(he(c, r), { by: e, value: i });
2416
+ }
2417
+ }
2418
+ }
2419
+ const Ct = (o, t) => o === t || o !== void 0 && t !== void 0 && D(o) === D(t), hn = "undo", Pe = (o) => Nt(o) ?? o, we = (o) => o && typeof o == "object" && "touches" in o ? o : null, Ke = (o) => we(o)?.run ?? null;
2420
+ function fs(o, t) {
2421
+ const e = /* @__PURE__ */ new Map();
2422
+ for (const s of [...o, ...t]) {
2423
+ const n = e.get(s.id);
2424
+ e.set(s.id, n === null || s.fields === null ? null : /* @__PURE__ */ new Set([...n ?? [], ...s.fields]));
2425
+ }
2426
+ return [...e].sort(([s], [n]) => s < n ? -1 : s > n ? 1 : 0).map(([s, n]) => ({ id: s, fields: n === null ? null : [...n].sort() }));
2427
+ }
2428
+ const Le = (o, t, e) => new ys(o, {
2429
+ mergeInterval: 0,
2430
+ excludeOriginPrefixes: [kt, Ft, nn, t === "person" ? "agent" : "person", hn],
2431
+ onPush: () => {
2432
+ if (e.replaying) return { value: e.popped, cursors: [] };
2433
+ const s = e.current === null ? fs([], e.pending) : e.groups.get(`${t}:${e.current}`) ?? e.pending;
2434
+ return { value: { run: e.current, touches: s }, cursors: [] };
2435
+ },
2436
+ onPop: (s, n) => {
2437
+ e.popped = we(n?.value);
2438
+ }
2439
+ }), Ue = (o, t) => ({ person: Le(o, "person", t), agent: Le(o, "agent", t) }), Je = (o) => {
2440
+ o.person.free(), o.agent.free();
2441
+ };
2442
+ function pt(o) {
2443
+ if (o !== "person" && o !== "agent") throw new L("invalid-value", 'an undo scope is "person" or "agent"');
2444
+ return o;
2445
+ }
2446
+ const te = (o, t) => {
2447
+ const e = (s) => s.map((n) => `${n.counter}@${n.peer}`).sort().join(",");
2448
+ return e(o) === e(t);
2449
+ };
2450
+ export {
2451
+ se as E,
2452
+ Fs as L,
2453
+ ls as N,
2454
+ G as O,
2455
+ rt as R,
2456
+ et as T,
2457
+ Ut as a,
2458
+ gn as b,
2459
+ Ps as c,
2460
+ yn as d,
2461
+ Us as e,
2462
+ Xt as f,
2463
+ hs as g,
2464
+ Bs as h,
2465
+ mn as i,
2466
+ rs as j,
2467
+ wn as n,
2468
+ bn as r,
2469
+ Vs as t,
2470
+ Q as u,
2471
+ pn as w
2472
+ };