onionskin-cli 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/CHANGELOG.md +144 -0
  2. package/INSTALL.md +25 -0
  3. package/LICENSE +21 -0
  4. package/NOTICE +49 -0
  5. package/README.md +148 -2
  6. package/docs/contracts/batch.schema.json +839 -0
  7. package/docs/contracts/history.schema.json +126 -0
  8. package/docs/contracts/ops.schema.json +541 -0
  9. package/package.json +67 -4
  10. package/scripts/checker/check.py +411 -0
  11. package/scripts/checker/requirements.txt +5 -0
  12. package/scripts/install-check.mjs +9 -0
  13. package/scripts/requirements.txt +5 -0
  14. package/scripts/rewriter/apple/main.swift +135 -0
  15. package/scripts/rewriter/apple/onionskin-fm +0 -0
  16. package/scripts/rewriter/apple/onionskin-fm.json +6 -0
  17. package/skills/onionskin/SKILL.md +117 -0
  18. package/skills/onionskin/reference/batch.md +94 -0
  19. package/skills/onionskin/reference/formats.md +15 -0
  20. package/skills/onionskin/reference/ops.md +253 -0
  21. package/skills/onionskin/reference/troubleshooting.md +73 -0
  22. package/skills/onionskin/reference/voice-guide.md +86 -0
  23. package/skills/onionskin/voice.example.md +51 -0
  24. package/src/agent-detect.js +149 -0
  25. package/src/agent-events.js +159 -0
  26. package/src/agent-prompt.js +27 -0
  27. package/src/agent-runner.js +593 -0
  28. package/src/analyze.js +17 -0
  29. package/src/anchors.js +190 -0
  30. package/src/apply.js +387 -0
  31. package/src/auth.js +130 -0
  32. package/src/batch.js +322 -0
  33. package/src/check-worker.js +8 -0
  34. package/src/checker.js +293 -0
  35. package/src/cli.js +516 -0
  36. package/src/constants.js +20 -0
  37. package/src/diff.js +267 -0
  38. package/src/doctor.js +288 -0
  39. package/src/docx.js +438 -0
  40. package/src/fmt.js +30 -0
  41. package/src/fsutil.js +348 -0
  42. package/src/history-worker.js +16 -0
  43. package/src/history.js +576 -0
  44. package/src/lease.js +79 -0
  45. package/src/local.js +242 -0
  46. package/src/merge-pptx.js +198 -0
  47. package/src/merge-xlsx.js +453 -0
  48. package/src/merge.js +410 -0
  49. package/src/offload.js +34 -0
  50. package/src/ops/common.js +48 -0
  51. package/src/ops/docx-table.js +323 -0
  52. package/src/ops/docx.js +503 -0
  53. package/src/ops/engine.js +41 -0
  54. package/src/ops/pptx.js +336 -0
  55. package/src/ops/run.js +115 -0
  56. package/src/ops/runs.js +127 -0
  57. package/src/ops/schema.js +109 -0
  58. package/src/ops/xlsx.js +277 -0
  59. package/src/package.js +189 -0
  60. package/src/paths.js +64 -0
  61. package/src/person.js +66 -0
  62. package/src/pptx.js +194 -0
  63. package/src/question.js +47 -0
  64. package/src/quick-plan.js +107 -0
  65. package/src/quick.js +164 -0
  66. package/src/redline-check.js +251 -0
  67. package/src/redline-worker.js +29 -0
  68. package/src/redline.js +438 -0
  69. package/src/reply.js +410 -0
  70. package/src/review.js +274 -0
  71. package/src/rewrite-check.js +1014 -0
  72. package/src/rewriter-cleanup.js +105 -0
  73. package/src/rewriter-setup.js +104 -0
  74. package/src/rewriter.js +396 -0
  75. package/src/sanitize.js +42 -0
  76. package/src/sentence-span.js +25 -0
  77. package/src/server-entry.js +13 -0
  78. package/src/server.js +576 -0
  79. package/src/session.js +1912 -0
  80. package/src/settings.js +161 -0
  81. package/src/setup.js +199 -0
  82. package/src/stamp-words.js +10 -0
  83. package/src/stamps.js +59 -0
  84. package/src/style.js +110 -0
  85. package/src/suggest-reply.js +84 -0
  86. package/src/suggest.js +261 -0
  87. package/src/text.js +31 -0
  88. package/src/tracked-words.js +43 -0
  89. package/src/voice-guide.js +182 -0
  90. package/src/voice-learn.js +314 -0
  91. package/src/voice-sample-worker.js +95 -0
  92. package/src/voice-samples.js +329 -0
  93. package/src/voice-store.js +305 -0
  94. package/src/voice-worker.js +28 -0
  95. package/src/voice.js +297 -0
  96. package/src/xlsx.js +454 -0
  97. package/src/xml-tree.js +118 -0
  98. package/src/xml.js +127 -0
  99. package/src/zip-write.js +74 -0
  100. package/src/zip.js +88 -0
  101. package/vendor/engine/DocViewer-BZLXUcxJ.js +15137 -0
  102. package/vendor/engine/THIRD_PARTY_LICENSES.txt +79 -0
  103. package/vendor/engine/collab-BVynXMqc.js +2591 -0
  104. package/vendor/engine/collab.js +2 -0
  105. package/vendor/engine/core.js +4 -0
  106. package/vendor/engine/default-worker-DogNT09A.js +35625 -0
  107. package/vendor/engine/embed.js +107 -0
  108. package/vendor/engine/index.js +5 -0
  109. package/vendor/engine/office-engine.embed.js +184 -0
  110. package/vendor/engine/office-engine.worker.js +36030 -0
  111. package/vendor/engine/xlsx-ops-SYAv6V0f.js +939 -0
  112. package/vendor/engine-node/LICENSE +21 -0
  113. package/vendor/engine-node/engine-node.mjs +46618 -0
  114. package/vendor/engine.lock.json +26 -0
  115. package/web/dist/assets/index-BUtofdtr.js +197 -0
  116. package/web/dist/assets/index-Dfizlg0i.css +1 -0
  117. package/web/dist/index.html +14 -0
@@ -0,0 +1,2591 @@
1
+
2
+ import { L as e, a as t, g as n, i as r, n as i, o as a, r as o, s } from "./xlsx-ops-SYAv6V0f.js";
3
+ // src/collab/hosts.ts
4
+ var c = /* @__PURE__ */ new WeakMap(), l = /* @__PURE__ */ new WeakMap();
5
+ function u(e, t, n) {
6
+ let r = c.get(e);
7
+ r || c.set(e, r = /* @__PURE__ */ new Map()), r.set(t, n);
8
+ for (let r of l.get(e)?.get(t) ?? []) r(n);
9
+ return () => {
10
+ r.get(t) === n && r.delete(t);
11
+ };
12
+ }
13
+ function d(e, t) {
14
+ return c.get(e)?.get(t);
15
+ }
16
+ function f(e, t, n) {
17
+ let r = l.get(e);
18
+ r || l.set(e, r = /* @__PURE__ */ new Map());
19
+ let i = r.get(t);
20
+ i || r.set(t, i = /* @__PURE__ */ new Set()), i.add(n);
21
+ let a = d(e, t);
22
+ return a && n(a), () => i.delete(n);
23
+ }
24
+ var p = /* @__PURE__ */ new WeakMap();
25
+ function m(e) {
26
+ let t = p.get(e);
27
+ return t || p.set(e, t = {
28
+ peers: ee,
29
+ peerFns: /* @__PURE__ */ new Set(),
30
+ localFns: /* @__PURE__ */ new Set()
31
+ }), t;
32
+ }
33
+ function h(e, t) {
34
+ let n = m(e);
35
+ n.peers = t;
36
+ for (let e of n.peerFns) e();
37
+ }
38
+ var ee = [];
39
+ function te(e) {
40
+ return p.get(e)?.peers ?? ee;
41
+ }
42
+ function ne(e, t) {
43
+ let n = m(e);
44
+ return n.peerFns.add(t), () => n.peerFns.delete(t);
45
+ }
46
+ function re(e, t) {
47
+ for (let n of p.get(e)?.localFns ?? []) n(t);
48
+ }
49
+ function ie(e, t) {
50
+ let n = m(e);
51
+ return n.localFns.add(t), () => n.localFns.delete(t);
52
+ }
53
+ // src/react/edit/rich.ts
54
+ var g = (e) => e.t === "text" ? e.text.length : 1, _ = (e) => e.reduce((e, t) => e + g(t), 0), v = (e) => e.a.pa === e.f.pa && e.a.o === e.f.o, y = (e, t) => e.replace(/(\d+)$/, (e) => String(Number(e) + t));
55
+ function b(e) {
56
+ return e.map((e) => e.t === "text" ? e.text : "").join("");
57
+ }
58
+ function x(e, t) {
59
+ if (e === t) return !0;
60
+ if (!e || !t) return !e && !t;
61
+ let n = Object.keys(e);
62
+ if (n.length !== Object.keys(t).length) return !1;
63
+ for (let r of n) if (e[r] !== t[r]) return !1;
64
+ return !0;
65
+ }
66
+ var ae = (e, t) => (e?.length ?? 0) === (t?.length ?? 0) && (!e || e.every((e, n) => t[n] === e)), oe = (e, t) => e === t || Array.isArray(e) && Array.isArray(t) && e.length === t.length && e.every((e, n) => e === t[n]), se = (e, t) => e.t === "text" && t.t === "text" && oe(e.src, t.src) && e.href === t.href && e.lk === t.lk && x(e.s, t.s) && x(e.d, t.d) && ae(e.cm, t.cm) && x(e.tc, t.tc);
67
+ function ce(e, t) {
68
+ let n, r, i = 0;
69
+ for (let a of e) {
70
+ let e = g(a);
71
+ if (i < t && t <= i + e && (n = a.cm), i <= t && t < i + e) {
72
+ r = a.cm;
73
+ break;
74
+ }
75
+ i += e;
76
+ }
77
+ let a = n?.filter((e) => r?.includes(e));
78
+ return a?.length ? a : void 0;
79
+ }
80
+ function S(e, t) {
81
+ if (ae(e.cm, t)) return e;
82
+ let n = { ...e };
83
+ return t?.length ? n.cm = t : delete n.cm, n;
84
+ }
85
+ function C(e) {
86
+ let t = [];
87
+ for (let n of e) {
88
+ if (n.t === "text" && !n.text) continue;
89
+ let e = t[t.length - 1];
90
+ e && se(e, n) ? t[t.length - 1] = {
91
+ ...e,
92
+ text: e.text + n.text
93
+ } : t.push(n);
94
+ }
95
+ return t;
96
+ }
97
+ function w(e, t) {
98
+ let n = [], r = [], i = 0;
99
+ for (let a of e) {
100
+ let e = g(a);
101
+ if (i + e <= t) n.push(a);
102
+ else if (i >= t) r.push(a);
103
+ else {
104
+ let e = t - i;
105
+ n.push({
106
+ ...a,
107
+ text: a.text.slice(0, e)
108
+ }), r.push({
109
+ ...a,
110
+ text: a.text.slice(e)
111
+ });
112
+ }
113
+ i += e;
114
+ }
115
+ return [n, r];
116
+ }
117
+ function T(e, t) {
118
+ let [n, r] = w(e, t);
119
+ for (let e = n.length - 1; e >= 0; e--) if (n[e].t === "text") return n[e];
120
+ return r.find((e) => e.t === "text");
121
+ }
122
+ function le(e, t, n, r, i) {
123
+ if (!n) return e;
124
+ let [a, o] = w(e, t), s = T(e, t), c = {
125
+ t: "text",
126
+ ...s ?? i ?? {},
127
+ ...r ?? {},
128
+ text: n
129
+ };
130
+ return r?.tc || delete c.tc, r?.s && s?.s && (c.s = {
131
+ ...s.s,
132
+ ...r.s
133
+ }), (r?.d || s?.d) && (c.d = {
134
+ ...s?.d ?? {},
135
+ ...r?.d ?? {}
136
+ }), c.d && !Object.keys(c.d).length && delete c.d, c = S(c, ce(e, t)), C([
137
+ ...a,
138
+ c,
139
+ ...o
140
+ ]);
141
+ }
142
+ function E(e, t, n) {
143
+ return n <= t ? e : C([...w(e, t)[0], ...w(e, n)[1]]);
144
+ }
145
+ function ue(e, t, n, r, i) {
146
+ let [a, o] = w(e, t), [s, c] = w(o, n - t), l = s.map((e) => e.t !== "text" && e.t !== "img" || !!e.cm?.includes(r) === i ? e : S(e, i ? [...e.cm ?? [], r] : e.cm.filter((e) => e !== r)));
147
+ return C([
148
+ ...a,
149
+ ...l,
150
+ ...c
151
+ ]);
152
+ }
153
+ function de(e, t, n, r, i) {
154
+ let [a, o] = w(e, t), [s, c] = w(o, n - t), l = s.map((e) => e.t === "text" ? {
155
+ ...e,
156
+ s: {
157
+ ...e.s ?? {},
158
+ ...r
159
+ },
160
+ d: {
161
+ ...e.d ?? {},
162
+ ...i
163
+ }
164
+ } : e);
165
+ return C([
166
+ ...a,
167
+ ...l,
168
+ ...c
169
+ ]);
170
+ }
171
+ function fe(e, t) {
172
+ if (t <= 0) return 0;
173
+ let n = Intl.Segmenter;
174
+ if (n) {
175
+ let r = 0;
176
+ for (let i of new n(void 0, { granularity: "grapheme" }).segment(e.slice(0, t))) r = i.index;
177
+ return r;
178
+ }
179
+ let r = e.charCodeAt(t - 1);
180
+ return r >= 56320 && r <= 57343 && t >= 2 ? t - 2 : t - 1;
181
+ }
182
+ function pe(e, t) {
183
+ if (t >= e.length) return e.length;
184
+ let n = Intl.Segmenter;
185
+ if (n) for (let r of new n(void 0, { granularity: "grapheme" }).segment(e.slice(t))) return t + r.segment.length;
186
+ let r = e.charCodeAt(t);
187
+ return r >= 55296 && r <= 56319 ? t + 2 : t + 1;
188
+ }
189
+ // src/react/edit/input.ts
190
+ function me(e, t) {
191
+ let n = e.cmp(t.a.pa, t.f.pa);
192
+ return n < 0 || n === 0 && t.a.o <= t.f.o ? [t.a, t.f] : [t.f, t.a];
193
+ }
194
+ var D = (e) => ({
195
+ a: e,
196
+ f: e
197
+ }), he = (e, t) => e.a.pa === t.a.pa && e.a.o === t.a.o && e.f.pa === t.f.pa && e.f.o === t.f.o;
198
+ function O(e, t) {
199
+ let [n, r] = me(e, t);
200
+ if (n.pa === r.pa) {
201
+ let t = e.para(n.pa);
202
+ return t ? {
203
+ pas: [n.pa],
204
+ paras: [e.withRuns(t, E(t.runs, n.o, r.o))],
205
+ at: n
206
+ } : null;
207
+ }
208
+ let i = e.span(n.pa, r.pa);
209
+ if (!i) {
210
+ let t = e.deleteAcross?.(n, r), i = t && e.para(t.pa);
211
+ return t && i ? {
212
+ pas: [t.pa],
213
+ paras: [i],
214
+ at: t,
215
+ applied: !0
216
+ } : null;
217
+ }
218
+ let a = e.para(i[0]), o = e.para(i[i.length - 1]), s = C([...w(a.runs, n.o)[0], ...w(o.runs, r.o)[1]]);
219
+ return {
220
+ pas: i,
221
+ paras: [e.join(a, o, s)],
222
+ at: n
223
+ };
224
+ }
225
+ function k(e, t, n) {
226
+ let r = O(e, t);
227
+ r && !r.applied && e.replace(r.pas, r.paras, D(r.at), n);
228
+ }
229
+ function A(e, t) {
230
+ if (!v(t)) return O(e, t);
231
+ let n = e.para(t.a.pa);
232
+ return n ? {
233
+ pas: [t.a.pa],
234
+ paras: [n],
235
+ at: t.a
236
+ } : null;
237
+ }
238
+ function ge(e, t, n, r = {}, i) {
239
+ let a = A(e, t);
240
+ if (!a) return;
241
+ let o = a.paras[0], s = a.at.o, [c, l] = w(o.runs, s), u = T(o.runs, s) ?? e.defaultRun?.(o), d = u?.tc ? (({ tc: e, ...t }) => t)(u) : u, f = ce(o.runs, s), p = (e) => e.map((e) => S(e.t === "text" && !e.s && d ? {
242
+ ...d,
243
+ ...e,
244
+ s: d.s,
245
+ src: d.src
246
+ } : e, f));
247
+ if (n.length === 1) {
248
+ let t = p(n[0]), i = C([
249
+ ...c,
250
+ ...t,
251
+ ...l
252
+ ]);
253
+ e.replace(a.pas, [e.withRuns(o, i)], D({
254
+ pa: a.at.pa,
255
+ o: s + _(t)
256
+ }), {
257
+ label: "paste",
258
+ ...r
259
+ });
260
+ return;
261
+ }
262
+ let m = [], h = e.withRuns(o, C([...c, ...p(n[0])]));
263
+ i?.[0] && (h = i[0](h));
264
+ for (let t = 1; t < n.length; t++) {
265
+ let r = t === n.length - 1, a = p(n[t]), [o, s] = e.split(h, h.runs, C([...a, ...r ? l : []]), !r);
266
+ m.push(o), h = i?.[t] ? i[t](s) : s;
267
+ }
268
+ m.push(h), e.replace(a.pas, m, D({
269
+ pa: y(a.at.pa, m.length - 1),
270
+ o: _(p(n[n.length - 1]))
271
+ }), {
272
+ label: "paste",
273
+ ...r
274
+ });
275
+ }
276
+ function j(e, t, n, r) {
277
+ let i = A(e, t);
278
+ if (!i) return;
279
+ let a = e.pendingStyle?.();
280
+ e.clearPending?.();
281
+ let o = i.paras[0], s = i.at.o, c = n.replace(/\r\n?/g, "\n").split("\n");
282
+ if (c.length === 1 || r?.label === "linebreak") {
283
+ let t = le(o.runs, s, n, a, e.defaultRun?.(o));
284
+ e.replace(i.pas, [e.withRuns(o, t)], D({
285
+ pa: i.at.pa,
286
+ o: s + n.length
287
+ }), {
288
+ label: "type",
289
+ ...r
290
+ });
291
+ return;
292
+ }
293
+ let l = a ? {
294
+ ...T(o.runs, s) ?? e.defaultRun?.(o) ?? {},
295
+ ...a
296
+ } : void 0;
297
+ ge(e, t, c.map((e) => e ? [{
298
+ ...l ?? {},
299
+ t: "text",
300
+ text: e
301
+ }] : []), r);
302
+ }
303
+ function _e(e, t) {
304
+ let n = v(t) ? (() => {
305
+ let n = e.para(t.a.pa);
306
+ return n ? {
307
+ pas: [t.a.pa],
308
+ paras: [n],
309
+ at: t.a
310
+ } : null;
311
+ })() : O(e, t);
312
+ if (!n) return;
313
+ let r = n.paras[0], [i, a] = w(r.runs, n.at.o), [o, s] = e.split(r, i, a, n.at.o >= _(r.runs));
314
+ e.replace(n.pas, [o, s], D({
315
+ pa: y(n.at.pa, 1),
316
+ o: 0
317
+ }), { label: "enter" });
318
+ }
319
+ function ve(e, t, n = !1) {
320
+ if (!v(t)) return k(e, t);
321
+ let { pa: r, o: i } = t.a, a = e.para(r);
322
+ if (!a) return;
323
+ if (i > 0) {
324
+ let t = b(a.runs), o = fe(t, i);
325
+ if (n) {
326
+ let e = /(\S+\s*|\s+)$/.exec(t.slice(0, i));
327
+ e && (o = i - e[0].length);
328
+ }
329
+ e.replace([r], [e.withRuns(a, E(a.runs, o, i))], D({
330
+ pa: r,
331
+ o
332
+ }), { label: "delete" });
333
+ return;
334
+ }
335
+ if (e.backspaceAtStart?.(r, a)) return;
336
+ let o = e.prev(r), s = o ? e.para(o) : void 0;
337
+ if (!o || !s) return;
338
+ let c = e.join(s, a, C([...s.runs, ...a.runs]));
339
+ e.replace([o, r], [c], D({
340
+ pa: o,
341
+ o: _(s.runs)
342
+ }), { label: "merge" });
343
+ }
344
+ function ye(e, t, n = !1) {
345
+ if (!v(t)) return k(e, t);
346
+ let { pa: r, o: i } = t.a, a = e.para(r);
347
+ if (!a) return;
348
+ if (i < _(a.runs)) {
349
+ let t = b(a.runs), o = pe(t, i);
350
+ if (n) {
351
+ let e = /^(\s*\S+|\s+)/.exec(t.slice(i));
352
+ e && (o = i + e[0].length);
353
+ }
354
+ e.replace([r], [e.withRuns(a, E(a.runs, i, o))], D({
355
+ pa: r,
356
+ o: i
357
+ }), { label: "delete" });
358
+ return;
359
+ }
360
+ let o = e.next(r), s = o ? e.para(o) : void 0;
361
+ if (!o || !s) return;
362
+ let c = e.join(a, s, C([...a.runs, ...s.runs]));
363
+ e.replace([r, o], [c], D({
364
+ pa: r,
365
+ o: i
366
+ }), { label: "merge" });
367
+ }
368
+ function be(e, t) {
369
+ let n = (e && (e.nodeType === 1 ? e : e.parentElement))?.closest("[data-o]");
370
+ return n && t.contains(n) ? n : null;
371
+ }
372
+ function xe(e) {
373
+ let t = Number(e.dataset.o);
374
+ return e.hasAttribute("data-obj") ? t + 1 : e.hasAttribute("data-empty") ? t : t + (e.textContent?.length ?? 0);
375
+ }
376
+ function M(e, t, n) {
377
+ let r = (t.nodeType === 1 ? t : t.parentElement)?.closest("[data-pa]");
378
+ if (!r || !e.contains(r)) return null;
379
+ let i = r.dataset.pa;
380
+ if (!be(t, r)) {
381
+ let e = document.createRange();
382
+ e.setStart(t, n), e.collapse(!0);
383
+ let a = 0;
384
+ for (let t of Array.from(r.querySelectorAll("[data-o]"))) if (e.comparePoint(t, t.childNodes.length) < 0) a = xe(t);
385
+ else break;
386
+ return {
387
+ pa: i,
388
+ o: a
389
+ };
390
+ }
391
+ let a = be(t, r), o = Number(a.dataset.o);
392
+ if (a.hasAttribute("data-empty")) return {
393
+ pa: i,
394
+ o
395
+ };
396
+ if (a.hasAttribute("data-obj")) return {
397
+ pa: i,
398
+ o: n > 0 || t !== a ? o + 1 : o
399
+ };
400
+ if (t.nodeType === 3) {
401
+ let e = 0, r = document.createTreeWalker(a, NodeFilter.SHOW_TEXT);
402
+ for (let a = r.nextNode(); a; a = r.nextNode()) {
403
+ if (a === t) return {
404
+ pa: i,
405
+ o: o + e + Math.min(n, (a.textContent ?? "").length)
406
+ };
407
+ e += a.textContent?.length ?? 0;
408
+ }
409
+ return {
410
+ pa: i,
411
+ o: o + e
412
+ };
413
+ }
414
+ let s = 0;
415
+ for (let e = 0; e < Math.min(n, a.childNodes.length); e++) s += a.childNodes[e].textContent?.length ?? 0;
416
+ return {
417
+ pa: i,
418
+ o: o + s
419
+ };
420
+ }
421
+ function N(e, t) {
422
+ let n = e.querySelector(`[data-pa="${t.pa}"]`);
423
+ if (!n) return null;
424
+ let r = Array.from(n.querySelectorAll("[data-o]"));
425
+ if (!r.length) return [n, n.childNodes.length];
426
+ let i;
427
+ for (let e of r) {
428
+ let n = Number(e.dataset.o), r = xe(e);
429
+ if (t.o >= n && t.o <= r && (i = e, t.o < r || !e.hasAttribute("data-obj"))) break;
430
+ }
431
+ i ??= r[r.length - 1];
432
+ let a = Number(i.dataset.o);
433
+ if (i.hasAttribute("data-obj") || i.hasAttribute("data-empty")) {
434
+ let e = i.parentNode, n = Array.prototype.indexOf.call(e.childNodes, i);
435
+ if (i.hasAttribute("data-empty")) {
436
+ let t = i.firstChild;
437
+ return t ? [t, 0] : [e, n];
438
+ }
439
+ return [e, t.o > a ? n + 1 : n];
440
+ }
441
+ let o = Math.max(0, t.o - a), s = document.createTreeWalker(i, NodeFilter.SHOW_TEXT), c = null;
442
+ for (let e = s.nextNode(); e; e = s.nextNode()) {
443
+ let t = e.textContent?.length ?? 0;
444
+ if (o <= t) return [e, o];
445
+ o -= t, c = e;
446
+ }
447
+ return c ? [c, c.textContent?.length ?? 0] : [i, 0];
448
+ }
449
+ function P(e) {
450
+ let t = e.getRootNode();
451
+ return typeof ShadowRoot < "u" && t instanceof ShadowRoot && typeof t.getSelection == "function" ? t.getSelection() : (e.ownerDocument ?? document).getSelection();
452
+ }
453
+ function Se(e) {
454
+ let t = e.getRootNode(), n = P(e);
455
+ if (!n) return null;
456
+ if (typeof ShadowRoot < "u" && t instanceof ShadowRoot && n.anchorNode && !e.contains(n.anchorNode)) {
457
+ let e = n.getComposedRanges?.call(n, { shadowRoots: [t] })[0];
458
+ if (e) return {
459
+ anchorNode: e.startContainer,
460
+ anchorOffset: e.startOffset,
461
+ focusNode: e.endContainer,
462
+ focusOffset: e.endOffset
463
+ };
464
+ }
465
+ return n;
466
+ }
467
+ var Ce = class {
468
+ host;
469
+ root = null;
470
+ composing = null;
471
+ justComposed = "";
472
+ raf = 0;
473
+ lastSel = null;
474
+ override = null;
475
+ constructor(e) {
476
+ this.host = e;
477
+ }
478
+ attach(e) {
479
+ this.root !== e && (this.detach(), this.root = e, e.addEventListener("beforeinput", this.onBeforeInput), e.addEventListener("compositionstart", this.onCompStart), e.addEventListener("compositionend", this.onCompEnd), e.addEventListener("keydown", this.onKeyDown), document.addEventListener("selectionchange", this.onSelChange));
480
+ }
481
+ detach() {
482
+ let e = this.root;
483
+ e && (e.removeEventListener("beforeinput", this.onBeforeInput), e.removeEventListener("compositionstart", this.onCompStart), e.removeEventListener("compositionend", this.onCompEnd), e.removeEventListener("keydown", this.onKeyDown), document.removeEventListener("selectionchange", this.onSelChange), cancelAnimationFrame(this.raf), this.raf = 0, this.root = null, this.override = null);
484
+ }
485
+ get isComposing() {
486
+ return !!this.composing;
487
+ }
488
+ readSel() {
489
+ let e = this.root, t = e ? Se(e) : null;
490
+ if (!e || !t || !t.anchorNode || !t.focusNode || !e.contains(t.anchorNode) || !e.contains(t.focusNode)) return null;
491
+ let n = M(e, t.anchorNode, t.anchorOffset), r = M(e, t.focusNode, t.focusOffset);
492
+ return n && r ? {
493
+ a: n,
494
+ f: r
495
+ } : null;
496
+ }
497
+ sel() {
498
+ return this.override?.model ?? this.readSel() ?? this.lastSel;
499
+ }
500
+ selectAll() {
501
+ let e = this.root, t = this.host.all?.();
502
+ if (!e || !t) return !1;
503
+ let n = Array.from(e.querySelectorAll("[data-pa]")).filter((t) => {
504
+ let n = t.closest("[contenteditable=\"false\"]");
505
+ return this.host.para(t.dataset.pa) && !(n && e.contains(n));
506
+ }), r = n[0], i = n[n.length - 1], a = r && i ? {
507
+ a: {
508
+ pa: r.dataset.pa,
509
+ o: 0
510
+ },
511
+ f: {
512
+ pa: i.dataset.pa,
513
+ o: _(this.host.para(i.dataset.pa).runs)
514
+ }
515
+ } : t;
516
+ return this.restore(a), this.override = {
517
+ model: t,
518
+ dom: this.readSel() ?? a
519
+ }, this.host.onSelection?.(t), !0;
520
+ }
521
+ restore(e, t = !0) {
522
+ let n = this.root;
523
+ if (!n || !e) return !1;
524
+ this.override = null;
525
+ let r = N(n, e.a), i = N(n, e.f);
526
+ if (!r || !i) return this.lastSel = e, !1;
527
+ let a = n.getRootNode().activeElement;
528
+ t && a !== n && !n.contains(a) && n.focus({ preventScroll: !0 });
529
+ let o = P(n);
530
+ try {
531
+ o?.setBaseAndExtent(r[0], r[1], i[0], i[1]);
532
+ } catch {}
533
+ return this.lastSel = e, !0;
534
+ }
535
+ rangeSel(e) {
536
+ if (!e || !this.root) return null;
537
+ let t = M(this.root, e.startContainer, e.startOffset), n = M(this.root, e.endContainer, e.endOffset);
538
+ return t && n ? {
539
+ a: t,
540
+ f: n
541
+ } : null;
542
+ }
543
+ onBeforeInput = (e) => {
544
+ let t = e.inputType;
545
+ if (this.composing || t === "insertCompositionText") return;
546
+ if (t === "deleteCompositionText" || t === "insertFromComposition") {
547
+ if (e.cancelable && e.preventDefault(), t === "insertFromComposition" && e.data && e.data !== this.justComposed) {
548
+ let t = this.sel();
549
+ t && j(this.host, t, e.data, { remount: !0 });
550
+ }
551
+ this.justComposed = "";
552
+ return;
553
+ }
554
+ e.preventDefault();
555
+ let n = this.rangeSel(e.getTargetRanges?.()[0]), r = this.sel();
556
+ if (!r) return;
557
+ let i = this.host;
558
+ switch (t) {
559
+ case "insertText":
560
+ case "insertReplacementText": {
561
+ let a = e.data ?? e.dataTransfer?.getData("text/plain") ?? "";
562
+ j(i, t === "insertReplacementText" && n ? n : r, a);
563
+ break;
564
+ }
565
+ case "insertParagraph":
566
+ _e(i, r);
567
+ break;
568
+ case "insertLineBreak":
569
+ j(i, r, "\n", { label: "linebreak" });
570
+ break;
571
+ case "insertFromPaste":
572
+ case "insertFromDrop":
573
+ case "insertFromYank": {
574
+ if (e.dataTransfer && i.pasteRich?.(t === "insertFromDrop" && n ? n : r, e.dataTransfer)) break;
575
+ let a = e.dataTransfer?.getData("text/plain") ?? e.data ?? "";
576
+ a && j(i, r, a);
577
+ break;
578
+ }
579
+ case "deleteContentBackward":
580
+ ve(i, r);
581
+ break;
582
+ case "deleteWordBackward":
583
+ ve(i, r, !0);
584
+ break;
585
+ case "deleteContentForward":
586
+ ye(i, r);
587
+ break;
588
+ case "deleteWordForward":
589
+ ye(i, r, !0);
590
+ break;
591
+ case "deleteSoftLineBackward":
592
+ case "deleteHardLineBackward":
593
+ case "deleteSoftLineForward":
594
+ case "deleteHardLineForward":
595
+ case "deleteByCut":
596
+ case "deleteByDrag":
597
+ case "deleteContent":
598
+ case "deleteEntireSoftLine":
599
+ v(r) ? n && !v(n) && k(i, n) : k(i, r);
600
+ break;
601
+ case "historyUndo":
602
+ i.undo();
603
+ break;
604
+ case "historyRedo":
605
+ i.redo();
606
+ break;
607
+ case "formatBold":
608
+ i.toggle?.("b");
609
+ break;
610
+ case "formatItalic":
611
+ i.toggle?.("i");
612
+ break;
613
+ case "formatUnderline": i.toggle?.("u");
614
+ }
615
+ };
616
+ onCompStart = () => {
617
+ this.composing = this.sel();
618
+ };
619
+ onCompEnd = (e) => {
620
+ let t = this.composing;
621
+ this.composing = null, t && (this.justComposed = e.data ?? "", e.data ? j(this.host, t, e.data, { remount: !0 }) : j(this.host, t, "", { remount: !0 }), setTimeout(() => this.justComposed = "", 0));
622
+ };
623
+ onKeyDown = (e) => {
624
+ if (e.isComposing || this.composing) return;
625
+ let t = e.metaKey || e.ctrlKey, n = e.key.toLowerCase();
626
+ if (this.host.shortcut?.(e)) e.preventDefault();
627
+ else {
628
+ if (t && !e.altKey) {
629
+ if (n === "z") {
630
+ e.preventDefault(), e.shiftKey ? this.host.redo() : this.host.undo();
631
+ return;
632
+ }
633
+ if (n === "y") {
634
+ e.preventDefault(), this.host.redo();
635
+ return;
636
+ }
637
+ if (n === "a" && !e.shiftKey) {
638
+ this.selectAll() && e.preventDefault();
639
+ return;
640
+ }
641
+ if (n === "b" || n === "i" || n === "u") {
642
+ e.preventDefault(), this.host.toggle?.(n);
643
+ return;
644
+ }
645
+ }
646
+ if (e.key === "Tab" && !t) {
647
+ e.preventDefault();
648
+ let t = this.sel();
649
+ if (!t) return;
650
+ !this.host.tab?.(t, e.shiftKey) && !e.shiftKey && j(this.host, t, " ");
651
+ }
652
+ }
653
+ };
654
+ onSelChange = () => {
655
+ this.raf ||= requestAnimationFrame(() => {
656
+ this.raf = 0;
657
+ let e = this.readSel(), t = this.override;
658
+ if (t && e && !he(e, t.dom)) this.override = null;
659
+ else if (t) {
660
+ this.host.onSelection?.(t.model);
661
+ return;
662
+ }
663
+ e && (this.lastSel = e), this.host.onSelection?.(e);
664
+ });
665
+ };
666
+ }, F = [
667
+ "#1a73e8",
668
+ "#e8710a",
669
+ "#188038",
670
+ "#d93025",
671
+ "#9334e6",
672
+ "#c5221f",
673
+ "#007b83",
674
+ "#b06000",
675
+ "#3f51b5",
676
+ "#e52592"
677
+ ], we = (e) => !!e && typeof e == "object" && "cid" in e && "prev" in e;
678
+ async function I(e, t) {
679
+ let n = await e.direct("comments.set", t.cid, t.c);
680
+ return {
681
+ undo: {
682
+ cid: t.cid,
683
+ prev: n
684
+ },
685
+ result: n
686
+ };
687
+ }
688
+ function L(e, t) {
689
+ return we(t) ? e.direct("comments.set", t.cid, t.prev).then(() => void 0) : !1;
690
+ }
691
+ // src/collab/docx.ts
692
+ var Te = /* @__PURE__ */ new Set([
693
+ "open",
694
+ "part",
695
+ "docx.start",
696
+ "docx.convert",
697
+ "save",
698
+ "dirty"
699
+ ]), Ee = (e) => typeof e == "object" && !!e && !Array.isArray(e), R = (e, t) => Ee(e) && Object.keys(e).every((e) => t.includes(e)), z = (e, t) => typeof e == "string" && e.length <= t, De = (e) => e === null || typeof e == "boolean" || typeof e == "number" && Number.isFinite(e) || z(e, 255), Oe = [
700
+ "normal",
701
+ "title",
702
+ "subtitle",
703
+ "h1",
704
+ "h2",
705
+ "h3",
706
+ "h4",
707
+ "h5",
708
+ "h6"
709
+ ], ke = [
710
+ "b",
711
+ "i",
712
+ "u",
713
+ "strike",
714
+ "color",
715
+ "sz",
716
+ "font",
717
+ "align",
718
+ "line",
719
+ "lineRule",
720
+ "before",
721
+ "after"
722
+ ], Ae = [
723
+ "w",
724
+ "h",
725
+ "mt",
726
+ "mr",
727
+ "mb",
728
+ "ml",
729
+ "cols",
730
+ "colGap"
731
+ ], je = [
732
+ "header",
733
+ "footer",
734
+ "firstHeader",
735
+ "firstFooter"
736
+ ], Me = 4194304, Ne = (e) => R(e, [
737
+ "text",
738
+ "align",
739
+ "b",
740
+ "sz"
741
+ ]) && z(e.text, 2e3) && (e.align === void 0 || z(e.align, 10)) && (e.b === void 0 || typeof e.b == "boolean") && (e.sz === void 0 || typeof e.sz == "number");
742
+ function Pe(e) {
743
+ return !R(e, [
744
+ "parts",
745
+ "raw",
746
+ "titlePg"
747
+ ]) || e.titlePg !== void 0 && typeof e.titlePg != "boolean" || e.parts !== void 0 && !(R(e.parts, je) && Object.values(e.parts).every((e) => Array.isArray(e) && e.length <= 20 && e.every(Ne))) ? !1 : e.raw === void 0 || R(e.raw, je) && Object.values(e.raw).every((e) => z(e, Me));
748
+ }
749
+ var Fe = e({
750
+ "docx.style": (e) => e.length === 1 && Oe.includes(e[0]),
751
+ "docx.styleSet": (e) => e.length === 2 && z(e[0], 255) && R(e[1], ke) && Object.values(e[1]).every(De),
752
+ "docx.page": (e) => e.length === 1 && R(e[0], Ae) && Object.values(e[0]).every((e) => typeof e == "number" && Number.isFinite(e)),
753
+ "docx.hf": (e) => e.length === 1 && Pe(e[0])
754
+ });
755
+ function Ie(e, t) {
756
+ let n = typeof e == "string" ? Fe[e] : void 0;
757
+ return !!n && Array.isArray(t) && n(t);
758
+ }
759
+ var Le = /^[a-z0-9]{1,8}$/i;
760
+ function Re(e) {
761
+ let t = () => /* @__PURE__ */ Error(`Collaboration: operation refused (${String(e.method ?? e.t).slice(0, 40)})`);
762
+ if (e.t === "call") {
763
+ if (!Ie(e.method, e.args)) throw t();
764
+ } else if (e.t === "image") {
765
+ if (!z(e.key, 200) || !(e.bytes instanceof Uint8Array) || typeof e.ext != "string" || !Le.test(e.ext)) throw t();
766
+ } else if (e.t === "link" && (!z(e.key, 200) || !z(e.url, 8192))) throw t();
767
+ }
768
+ var B = (e) => e.t === "p" ? e.pid === void 0 ? null : { p: e.pid } : e.t === "tbl" ? {
769
+ tid: e.tid,
770
+ item: e.item
771
+ } : null;
772
+ function ze(e, t) {
773
+ return e ? "p" in t ? e.t === "p" && e.pid === t.p : e.t === "tbl" && (t.tid !== void 0 && e.tid === t.tid || t.item !== void 0 && e.item === t.item) : !1;
774
+ }
775
+ var Be = (e) => [...new Set(e)];
776
+ function V(e, t = []) {
777
+ for (let n of e) if (n.t === "p" && n.pid !== void 0) t.push(n.pid);
778
+ else if (n.t === "tbl") for (let e of n.rows) for (let n of e.cells) V(n.blocks, t);
779
+ return t;
780
+ }
781
+ function Ve(e) {
782
+ if (e.t !== "text") return JSON.stringify(e);
783
+ let { text: t, ...n } = e;
784
+ return JSON.stringify(n);
785
+ }
786
+ function He(e, t) {
787
+ let n = (e) => {
788
+ let t = [];
789
+ for (let n of e) {
790
+ let e = Ve(n);
791
+ if (n.t === "text") for (let r = 0; r < n.text.length; r++) t.push(e + "\0" + n.text[r]);
792
+ else t.push(e);
793
+ }
794
+ return t;
795
+ }, r = n(e), i = n(t), a = 0;
796
+ for (; a < r.length && a < i.length && r[a] === i[a];) a++;
797
+ let o = 0;
798
+ for (; o < r.length - a && o < i.length - a && r[r.length - 1 - o] === i[i.length - 1 - o];) o++;
799
+ if (a === r.length && a === i.length) return null;
800
+ let [, s] = w(t, a), [c] = w(s, i.length - a - o);
801
+ return {
802
+ at: a,
803
+ del: r.length - a - o,
804
+ ins: c
805
+ };
806
+ }
807
+ function Ue(e, t, n, r) {
808
+ let i = _(e), a = Math.max(0, Math.min(t, i)), o = Math.max(0, Math.min(n, i - a)), [s, c] = w(e, a), [, l] = w(c, o);
809
+ return [
810
+ ...s,
811
+ ...r,
812
+ ...l
813
+ ];
814
+ }
815
+ function We(e, t, n, r, i) {
816
+ return e < t || e === t && (n > 0 || i) ? e : e >= t + n ? e - n + r : t + r;
817
+ }
818
+ function Ge(e, t, n) {
819
+ if (t === n) return e;
820
+ let r = 0;
821
+ for (; r < t.length && r < n.length && t[r] === n[r];) r++;
822
+ let i = 0;
823
+ for (; i < t.length - r && i < n.length - r && t[t.length - 1 - i] === n[n.length - 1 - i];) i++;
824
+ return e <= r ? e : e >= t.length - i ? n.length - (t.length - e) : n.length - i;
825
+ }
826
+ var Ke = (e, t) => e.pid === t.pid && e.from === t.from && e.sid === t.sid && !!e.pb == !!t.pb && e.keepSect === t.keepSect && JSON.stringify(e.pd ?? null) === JSON.stringify(t.pd ?? null) && JSON.stringify(e.ps) === JSON.stringify(t.ps) && JSON.stringify(e.orig ?? null) === JSON.stringify(t.orig ?? null), qe = class {
827
+ client;
828
+ host;
829
+ suppress = 0;
830
+ res = /* @__PURE__ */ new Map();
831
+ resKey = /* @__PURE__ */ new Map();
832
+ results = /* @__PURE__ */ new WeakMap();
833
+ snap = null;
834
+ touchedModel = !1;
835
+ site = 0;
836
+ counter = 0;
837
+ offHost;
838
+ onPresence;
839
+ lastPresence = "";
840
+ raf = 0;
841
+ push;
842
+ submit;
843
+ constructor(e) {
844
+ this.client = e;
845
+ }
846
+ ready() {
847
+ return new Promise((e) => {
848
+ this.offHost = f(this.client, "docx", (t) => {
849
+ this.host?.editor !== t.editor && (this.host && (this.host.editor.onCommit = void 0), this.host = t, t.editor.onCommit = (e) => this.onCommit(e), this.allocPids(), e());
850
+ }), typeof document < "u" && document.addEventListener("selectionchange", this.onSel);
851
+ });
852
+ }
853
+ setSite(e) {
854
+ this.site = e, this.allocPids();
855
+ }
856
+ allocPids() {
857
+ let e = this.host?.editor;
858
+ if (!e || !this.site) return;
859
+ let t = 2e9 + this.site * 1e7;
860
+ (e.nextPid < t || e.nextPid >= t + 1e7) && (e.nextPid = t);
861
+ }
862
+ dispose() {
863
+ this.offHost?.(), this.host && (this.host.editor.onCommit = void 0), typeof document < "u" && document.removeEventListener("selectionchange", this.onSel), this.raf && cancelAnimationFrame(this.raf);
864
+ }
865
+ captures(e) {
866
+ return e === "comments.set" || !this.suppress && !Te.has(e) && e !== "docx.edit" && e !== "docx.table" && e.startsWith("docx.");
867
+ }
868
+ intercept(e, t) {
869
+ if (this.submit && this.captures(e)) {
870
+ switch (e) {
871
+ case "comments.set": return this.submit({
872
+ t: "comment",
873
+ cid: t[0],
874
+ c: t[1]
875
+ });
876
+ case "docx.image": {
877
+ let e = new Uint8Array(t[0].slice(0));
878
+ return this.submit({
879
+ t: "image",
880
+ key: this.key(),
881
+ bytes: e,
882
+ ext: t[1]
883
+ });
884
+ }
885
+ case "docx.link": return this.submit({
886
+ t: "link",
887
+ key: this.key(),
888
+ url: t[0]
889
+ });
890
+ }
891
+ return this.submit({
892
+ t: "call",
893
+ method: e,
894
+ args: t
895
+ });
896
+ }
897
+ }
898
+ key() {
899
+ return `${this.site}:${++this.counter}:${Math.random().toString(36).slice(2, 7)}`;
900
+ }
901
+ get st() {
902
+ return this.host.st;
903
+ }
904
+ get ed() {
905
+ return this.host.editor;
906
+ }
907
+ locate(e) {
908
+ let t = [];
909
+ return this.st.blocks.forEach((n, r) => {
910
+ n.t === "p" ? n.pid === e && t.push({
911
+ list: this.st.blocks,
912
+ index: r,
913
+ pa: String(r),
914
+ p: n
915
+ }) : n.t === "tbl" && n.rows.forEach((n, i) => n.cells.forEach((n, a) => n.blocks.forEach((o, s) => {
916
+ o.t === "p" && o.pid === e && t.push({
917
+ list: n.blocks,
918
+ index: s,
919
+ pa: `${r}.${i}.${a}.${s}`,
920
+ p: o
921
+ });
922
+ })));
923
+ }), t;
924
+ }
925
+ topIndex(e) {
926
+ return this.st.blocks.findIndex((t) => ze(t, e));
927
+ }
928
+ region(e) {
929
+ let t = new Set(e);
930
+ for (let n of e) {
931
+ let e = this.locate(n)[0];
932
+ if (!e) continue;
933
+ let r = [];
934
+ for (let n = e.index; n < e.list.length; n++) {
935
+ let i = e.list[n];
936
+ if (i.t !== "p" || i.pid === void 0 || !t.has(i.pid)) break;
937
+ r.push(e.pa.replace(/\d+$/, String(n)));
938
+ }
939
+ return r;
940
+ }
941
+ return null;
942
+ }
943
+ remap(e) {
944
+ if (e.t === "img") {
945
+ let t = e.ck, n = t ? this.res.get(t) : void 0;
946
+ return n && typeof n == "object" ? {
947
+ ...e,
948
+ rid: n.rid,
949
+ target: n.path
950
+ } : e;
951
+ }
952
+ if (e.t === "text") {
953
+ let t = e.lck, n = t ? this.res.get(t) : void 0;
954
+ return typeof n == "string" ? {
955
+ ...e,
956
+ lk: n
957
+ } : e;
958
+ }
959
+ return e.t === "p" ? {
960
+ ...e,
961
+ runs: e.runs.map((e) => this.remap(e))
962
+ } : e.t === "tbl" ? {
963
+ ...e,
964
+ rows: e.rows.map((e) => ({
965
+ ...e,
966
+ cells: e.cells.map((e) => ({
967
+ ...e,
968
+ blocks: e.blocks.map((e) => this.remap(e))
969
+ }))
970
+ }))
971
+ } : e;
972
+ }
973
+ tag(e) {
974
+ return e.t === "img" && e.rid && this.resKey.has(e.rid) && !e.ck ? {
975
+ ...e,
976
+ ck: this.resKey.get(e.rid)
977
+ } : e.t === "text" && e.lk && this.resKey.has(e.lk) && !e.lck ? {
978
+ ...e,
979
+ lck: this.resKey.get(e.lk)
980
+ } : e.t === "p" ? {
981
+ ...e,
982
+ runs: e.runs.map((e) => this.tag(e)),
983
+ caret: void 0
984
+ } : e.t === "tbl" ? {
985
+ ...e,
986
+ rows: e.rows.map((e) => ({
987
+ ...e,
988
+ cells: e.cells.map((e) => ({
989
+ ...e,
990
+ blocks: e.blocks.map((e) => this.tag(e))
991
+ }))
992
+ }))
993
+ } : e;
994
+ }
995
+ async fetchRes(e) {
996
+ if (Re(e), e.t === "image" && !this.res.has(e.key)) {
997
+ let t = await this.client.direct("docx.image", e.bytes.slice().buffer, e.ext);
998
+ this.res.set(e.key, t), this.resKey.set(t.rid, e.key);
999
+ } else if (e.t === "link" && !this.res.has(e.key)) {
1000
+ let t = await this.client.direct("docx.link", e.url);
1001
+ this.res.set(e.key, t), this.resKey.set(t, e.key);
1002
+ } else if (e.t === "call" && !this.results.has(e)) {
1003
+ let t = this.client.direct.bind(this.client);
1004
+ this.results.set(e, await t(e.method, ...e.args));
1005
+ }
1006
+ }
1007
+ onCommit(e) {
1008
+ if (this.suppress || !this.push) return;
1009
+ if (e.kind === "paras") {
1010
+ let t = e.before, n = e.next;
1011
+ if (t.length === 1 && n.length === 1 && t[0].pid !== void 0 && Ke(t[0], n[0]) && this.locate(t[0].pid).length === 1) {
1012
+ let e = He(t[0].runs, n[0].runs);
1013
+ if (!e) return;
1014
+ this.push({
1015
+ t: "text",
1016
+ pid: t[0].pid,
1017
+ at: e.at,
1018
+ del: e.del,
1019
+ ins: e.ins.map((e) => this.tag(e))
1020
+ }, [{
1021
+ t: "paras",
1022
+ before: t,
1023
+ next: n
1024
+ }]);
1025
+ return;
1026
+ }
1027
+ this.push({
1028
+ t: "paras",
1029
+ before: t.map((e) => e.pid),
1030
+ next: n.map((e) => this.tag(e))
1031
+ }, [{
1032
+ t: "paras",
1033
+ before: t,
1034
+ next: n
1035
+ }]);
1036
+ return;
1037
+ }
1038
+ let t = e.bi > 0 ? B(this.st.blocks[e.bi - 1]) : null;
1039
+ this.push({
1040
+ t: "blocks",
1041
+ before: e.before.map(B).filter((e) => !!e),
1042
+ prev: t,
1043
+ next: e.next.map((e) => this.tag(e))
1044
+ }, [{
1045
+ t: "blocks",
1046
+ before: e.before,
1047
+ next: e.next,
1048
+ prev: t
1049
+ }]);
1050
+ }
1051
+ transform(e, t) {
1052
+ if (e.t !== "text") return e;
1053
+ if (t.t === "text" && t.pid === e.pid) {
1054
+ let n = _(t.ins), r = We(e.at, t.at, t.del, n, !1), i = e.del ? Math.max(r, We(e.at + e.del, t.at, t.del, n, !0)) : r;
1055
+ return r === e.at && i - r === e.del ? e : {
1056
+ ...e,
1057
+ at: r,
1058
+ del: i - r
1059
+ };
1060
+ }
1061
+ return t.t === "paras" && (t.before.includes(e.pid) || t.next.some((t) => t.pid === e.pid)) ? t.next.some((t) => t.pid === e.pid) ? e : null : t.t === "blocks" && t.before.some((t) => "p" in t && t.p === e.pid) && !V(t.next).includes(e.pid) ? null : e;
1062
+ }
1063
+ touched(e) {
1064
+ switch (e.t) {
1065
+ case "text": return ["p" + e.pid];
1066
+ case "paras": return [...e.before, ...e.next.map((e) => e.pid)].map((e) => "p" + e);
1067
+ case "comment": return ["c" + e.cid];
1068
+ case "blocks": {
1069
+ let t = [
1070
+ ...e.before,
1071
+ ...e.prev ? [e.prev] : [],
1072
+ ...e.next.map(B).filter((e) => !!e)
1073
+ ].map((e) => "p" in e ? "p" + e.p : "t" + (e.item ?? "n" + e.tid));
1074
+ for (let n of V(e.next)) t.push("p" + n);
1075
+ return t;
1076
+ }
1077
+ default: return [];
1078
+ }
1079
+ }
1080
+ conflicts(e, t) {
1081
+ let n = new Set(e.flatMap((e) => this.touched(e)));
1082
+ return t.some((e) => this.touched(e).some((e) => n.has(e)));
1083
+ }
1084
+ validate(e) {
1085
+ return t(e);
1086
+ }
1087
+ pessimistic(e) {
1088
+ return e.t === "call";
1089
+ }
1090
+ async prepare(e) {
1091
+ for (; this.host?.editor.input.isComposing;) await new Promise((e) => setTimeout(e, 50));
1092
+ for (let t of e) await this.fetchRes(t);
1093
+ this.capture();
1094
+ }
1095
+ async apply(e, t) {
1096
+ switch (e.t) {
1097
+ case "comment": return I(this.client, e);
1098
+ case "image":
1099
+ case "link": return await this.fetchRes(e), { result: this.res.get(e.key) };
1100
+ case "call": {
1101
+ await this.fetchRes(e);
1102
+ let t = this.results.get(e);
1103
+ return (e.method === "docx.style" || e.method === "docx.styleSet") && t && typeof t == "object" && this.host && this.ed.styled(t), e.method === "docx.page" && t && typeof t == "object" && this.host && this.ed.paged(t), e.method === "docx.hf" && t && typeof t == "object" && this.host && this.ed.hfed(t), { result: t };
1104
+ }
1105
+ }
1106
+ if (!this.host) throw Error("Document editor not ready");
1107
+ (t === "remote" || t === "replay") && this.capture(), this.touchedModel = !0, this.suppress++;
1108
+ try {
1109
+ return { undo: this.run(e) };
1110
+ } finally {
1111
+ this.suppress--;
1112
+ }
1113
+ }
1114
+ home(e) {
1115
+ let t = (t) => {
1116
+ let n = e.list[t];
1117
+ return n?.t === "tbl" ? B(n) ?? void 0 : void 0;
1118
+ };
1119
+ if (e.list === this.st.blocks) return {
1120
+ index: e.index,
1121
+ prevT: t(e.index - 1),
1122
+ nextT: t(e.index + 1)
1123
+ };
1124
+ let [n, r, i] = e.pa.split(".").map(Number), a = B(this.st.blocks[n]);
1125
+ return a ? {
1126
+ index: e.index,
1127
+ cell: {
1128
+ tbl: a,
1129
+ ri: r,
1130
+ ci: i
1131
+ }
1132
+ } : { index: e.index };
1133
+ }
1134
+ homePa(e) {
1135
+ if (e.cell) {
1136
+ let t = this.topIndex(e.cell.tbl), n = this.st.blocks[t], r = n?.t === "tbl" ? n.rows[e.cell.ri]?.cells[e.cell.ci] : void 0;
1137
+ return r ? `${t}.${e.cell.ri}.${e.cell.ci}.${Math.min(e.index, r.blocks.length)}` : void 0;
1138
+ }
1139
+ let t = e.prevT ? this.topIndex(e.prevT) : -1;
1140
+ if (t >= 0) return String(t + 1);
1141
+ let n = e.nextT ? this.topIndex(e.nextT) : -1;
1142
+ return String(n >= 0 ? n : Math.min(e.index, this.st.blocks.length));
1143
+ }
1144
+ run(e) {
1145
+ let t = this.ed;
1146
+ if (e.t === "text") {
1147
+ let n = this.locate(e.pid);
1148
+ if (n.length !== 1 || !t.para(n[0].pa)) return null;
1149
+ let r = n[0].p, i = {
1150
+ ...r,
1151
+ runs: Ue(r.runs, e.at, e.del, e.ins.map((e) => this.remap(e))),
1152
+ edited: !0
1153
+ };
1154
+ return t.replace([n[0].pa], [i], this.sel(), {
1155
+ history: !1,
1156
+ label: "collab"
1157
+ }), [{
1158
+ t: "paras",
1159
+ before: [r],
1160
+ next: [i]
1161
+ }];
1162
+ }
1163
+ if (e.t === "paras") {
1164
+ let n = e.next.map((e) => this.remap(e)), r = new Set(n.map((e) => e.pid)), i = this.region(e.before);
1165
+ if (!i || !i.length) return null;
1166
+ let a = [], o = new Set(i.map((e) => t.para(e)?.pid ?? -1));
1167
+ for (let n of Be([...e.before, ...r])) if (!o.has(n)) for (let e of this.locate(n).reverse()) {
1168
+ if (!t.para(e.pa)) continue;
1169
+ let n = (t) => {
1170
+ let n = e.list[t];
1171
+ return n?.t === "p" && n.pid !== void 0 ? {
1172
+ pid: n.pid,
1173
+ k: this.locate(n.pid).findIndex((n) => n.list === e.list && n.index === t)
1174
+ } : void 0;
1175
+ }, r = {
1176
+ t: "paras",
1177
+ before: [e.p],
1178
+ next: [],
1179
+ prev: n(e.index - 1),
1180
+ after: n(e.index + 1),
1181
+ home: this.home(e)
1182
+ };
1183
+ t.replace([e.pa], [], this.sel(), {
1184
+ history: !1,
1185
+ label: "collab"
1186
+ }), a.push(r);
1187
+ }
1188
+ let s = this.region(e.before);
1189
+ if (!s?.length) return a;
1190
+ let c = s.map((e) => t.para(e)).filter(Boolean);
1191
+ return c.length === s.length && (t.replace(s, n, this.sel(), {
1192
+ history: !1,
1193
+ label: "collab"
1194
+ }), a.push({
1195
+ t: "paras",
1196
+ before: c,
1197
+ next: n
1198
+ })), a;
1199
+ }
1200
+ if (e.t === "blocks") {
1201
+ let n = e.next.map((e) => this.remap(e)), r, i = 0;
1202
+ if (e.before.length) {
1203
+ if (r = this.topIndex(e.before[0]), r < 0) {
1204
+ let t = e.before.find((e) => this.topIndex(e) >= 0);
1205
+ if (!t) return null;
1206
+ r = this.topIndex(t);
1207
+ }
1208
+ for (; r + i < this.st.blocks.length && e.before.some((e) => ze(this.st.blocks[r + i], e));) i++;
1209
+ } else if (r = e.prev ? this.topIndex(e.prev) + 1 : 0, e.prev && r === 0) return null;
1210
+ let a = this.st.blocks.slice(r, r + i), o = new Map(a.flatMap((e) => e.t === "p" && e.pid !== void 0 ? [[e.pid, e]] : [])), s = new Set(e.before.flatMap((e) => "p" in e ? [e.p] : []));
1211
+ return n = n.flatMap((e) => e.t === "p" && e.pid !== void 0 && s.has(e.pid) ? o.has(e.pid) ? [o.get(e.pid)] : [] : [e]), t.replaceBlocks(r, i, n, null, !1), [{
1212
+ t: "blocks",
1213
+ before: a,
1214
+ next: n,
1215
+ prev: r > 0 ? B(this.st.blocks[r - 1]) : null
1216
+ }];
1217
+ }
1218
+ return null;
1219
+ }
1220
+ revert(e) {
1221
+ let t = L(this.client, e);
1222
+ if (t) return t;
1223
+ let n = e;
1224
+ if (n && this.host) {
1225
+ this.capture(), this.touchedModel = !0, this.suppress++;
1226
+ try {
1227
+ for (let e = n.length - 1; e >= 0; e--) this.undoStep(n[e]);
1228
+ } finally {
1229
+ this.suppress--;
1230
+ }
1231
+ }
1232
+ }
1233
+ undoStep(e) {
1234
+ let t = this.ed;
1235
+ if (e.t === "paras") {
1236
+ if (!e.next.length) {
1237
+ let n = (e) => e ? this.locate(e.pid)[e.k] : void 0, r = n(e.prev);
1238
+ if (r && t.para(r.pa)) return t.replace([r.pa], [r.p, ...e.before], this.sel(), {
1239
+ history: !1,
1240
+ label: "collab"
1241
+ });
1242
+ let i = n(e.after);
1243
+ if (i && t.para(i.pa)) return t.replace([i.pa], [...e.before, i.p], this.sel(), {
1244
+ history: !1,
1245
+ label: "collab"
1246
+ });
1247
+ let a = e.home && this.homePa(e.home);
1248
+ if (a !== void 0) for (let n of [...e.before].reverse()) t.restore(a, n);
1249
+ return;
1250
+ }
1251
+ let n = this.locate(e.next[0].pid)[0];
1252
+ if (!n) return;
1253
+ let r = e.next.map((e, t) => n.pa.replace(/\d+$/, String(n.index + t)));
1254
+ if (r.some((n, r) => t.para(n)?.pid !== e.next[r].pid)) return;
1255
+ t.replace(r, e.before, this.sel(), {
1256
+ history: !1,
1257
+ label: "collab"
1258
+ });
1259
+ return;
1260
+ }
1261
+ let n = e.next.length ? B(e.next[0]) : null, r = n ? this.topIndex(n) : e.prev ? this.topIndex(e.prev) + 1 : 0;
1262
+ if (r < 0) return;
1263
+ let i = new Map(this.st.blocks.slice(r, r + e.next.length).flatMap((e) => e.t === "p" && e.pid !== void 0 ? [[e.pid, e]] : []));
1264
+ t.replaceBlocks(r, e.next.length, e.before.map((e) => e.t === "p" && e.pid !== void 0 && i.has(e.pid) ? i.get(e.pid) : e), null, !1);
1265
+ }
1266
+ toD(e) {
1267
+ let t = this.ed.para(e.pa);
1268
+ if (!t || t.pid === void 0) return null;
1269
+ let n = this.locate(t.pid);
1270
+ return {
1271
+ pid: t.pid,
1272
+ k: Math.max(0, n.findIndex((t) => t.pa === e.pa)),
1273
+ o: e.o
1274
+ };
1275
+ }
1276
+ fromD(e) {
1277
+ let t = this.locate(e.pid), n = t[Math.min(e.k, t.length - 1)];
1278
+ return n ? {
1279
+ pa: n.pa,
1280
+ o: Math.min(e.o, _(n.p.runs))
1281
+ } : null;
1282
+ }
1283
+ capture() {
1284
+ if (this.snap || !this.host) return;
1285
+ let e = !!this.ed.input.readSel(), t = this.ed.input.sel(), n = t && this.toD(t.a), r = t && this.toD(t.f);
1286
+ if (!n || !r) return;
1287
+ let i = /* @__PURE__ */ new Map();
1288
+ for (let e of [n, r]) {
1289
+ let t = this.locate(e.pid)[e.k];
1290
+ t && i.set(`${e.pid}:${e.k}`, b(t.p.runs));
1291
+ }
1292
+ this.snap = {
1293
+ a: n,
1294
+ f: r,
1295
+ text: i,
1296
+ focused: e
1297
+ };
1298
+ }
1299
+ sel() {
1300
+ let e = this.snap, t = {
1301
+ pa: "0",
1302
+ o: 0
1303
+ };
1304
+ if (!e) return this.ed.input.lastSel ?? {
1305
+ a: t,
1306
+ f: t
1307
+ };
1308
+ let n = (n) => {
1309
+ let r = this.locate(n.pid)[n.k] ?? this.locate(n.pid)[0];
1310
+ if (!r) return this.ed.input.lastSel?.f ?? t;
1311
+ let i = e.text.get(`${n.pid}:${n.k}`), a = b(r.p.runs);
1312
+ return {
1313
+ pa: r.pa,
1314
+ o: i === void 0 ? Math.min(n.o, a.length) : Ge(n.o, i, a)
1315
+ };
1316
+ };
1317
+ return {
1318
+ a: n(e.a),
1319
+ f: n(e.f)
1320
+ };
1321
+ }
1322
+ settled() {
1323
+ let e = this.snap, t = this.touchedModel;
1324
+ if (this.touchedModel = !1, !this.host) return;
1325
+ if (!e) {
1326
+ t && (this.ed.pendingSel = null);
1327
+ return;
1328
+ }
1329
+ let n = this.sel();
1330
+ this.snap = null, this.ed.pendingSel = e.focused ? n : null, e.focused || (this.ed.input.lastSel = n);
1331
+ }
1332
+ onSel = () => {
1333
+ !this.raf && this.host && (this.raf = requestAnimationFrame(() => {
1334
+ this.raf = 0;
1335
+ let e = this.host && this.ed.input.readSel();
1336
+ if (!e) return;
1337
+ let t = this.toD(e.a), n = this.toD(e.f);
1338
+ if (!t || !n) return;
1339
+ let r = {
1340
+ k: "docx",
1341
+ a: t,
1342
+ f: n
1343
+ }, i = JSON.stringify(r);
1344
+ i !== this.lastPresence && (this.lastPresence = i, this.onPresence?.(r));
1345
+ }));
1346
+ };
1347
+ rects(e, t) {
1348
+ if (!this.host) return {
1349
+ caret: null,
1350
+ sel: []
1351
+ };
1352
+ let n = e.querySelector(".de-pages"), r = this.fromD(t.a), i = this.fromD(t.f);
1353
+ if (!n || !r || !i) return {
1354
+ caret: null,
1355
+ sel: []
1356
+ };
1357
+ let a = N(n, i), o = null;
1358
+ if (a) {
1359
+ let e = document.createRange();
1360
+ try {
1361
+ e.setStart(a[0], a[1]), e.collapse(!0), o = e.getClientRects()[0] ?? (a[0].nodeType === 1 ? a[0].getBoundingClientRect() : e.getBoundingClientRect());
1362
+ } catch {
1363
+ o = null;
1364
+ }
1365
+ }
1366
+ let s = [], c = N(n, r);
1367
+ if (c && a && (r.pa !== i.pa || r.o !== i.o)) {
1368
+ let e = document.createRange();
1369
+ try {
1370
+ this.ed.cmp(r.pa, i.pa) < 0 || r.pa === i.pa && r.o < i.o ? (e.setStart(c[0], c[1]), e.setEnd(a[0], a[1])) : (e.setStart(a[0], a[1]), e.setEnd(c[0], c[1]));
1371
+ for (let t of Array.from(e.getClientRects())) t.width > .5 && s.push(t);
1372
+ } catch {}
1373
+ }
1374
+ return {
1375
+ caret: o,
1376
+ sel: s
1377
+ };
1378
+ }
1379
+ }, H = (e) => e !== null;
1380
+ function Je(e) {
1381
+ let t = Number.isFinite(e.site) ? e.site : 0;
1382
+ return {
1383
+ ...e,
1384
+ name: typeof e.name == "string" ? e.name.slice(0, 200) : "",
1385
+ color: n(e.color) ?? F[Math.abs(Math.trunc(t)) % F.length]
1386
+ };
1387
+ }
1388
+ var Ye = class {
1389
+ transport;
1390
+ adapter;
1391
+ opts;
1392
+ site = 0;
1393
+ rev = 0;
1394
+ status = "connecting";
1395
+ error;
1396
+ peers = /* @__PURE__ */ new Map();
1397
+ log = [];
1398
+ inflight = null;
1399
+ buffer = [];
1400
+ queue;
1401
+ joined = !1;
1402
+ online = !1;
1403
+ counter = 0;
1404
+ listeners = /* @__PURE__ */ new Map();
1405
+ presence;
1406
+ presenceTimer;
1407
+ presenceAt = 0;
1408
+ closed = !1;
1409
+ constructor(e, t, n) {
1410
+ this.transport = e, this.adapter = t, this.opts = n, this.rev = n.base ?? 0, this.queue = Promise.resolve(t.ready?.()).catch((e) => this.fail(e.message)), e.onMessage = (e) => this.enqueue(() => this.onMessage(e)), e.onStatus = (t) => {
1411
+ t === "open" ? (this.online = !0, e.send(this.joined ? {
1412
+ t: "hello",
1413
+ room: n.room,
1414
+ user: n.user,
1415
+ have: this.rev,
1416
+ site: this.site
1417
+ } : {
1418
+ t: "hello",
1419
+ room: n.room,
1420
+ user: n.user,
1421
+ base: n.base || void 0
1422
+ })) : t === "closed" && (this.online = !1, this.peers.clear(), this.emit("peers", []), this.status !== "error" && this.setStatus(this.joined ? "offline" : "connecting"));
1423
+ }, e.connect();
1424
+ }
1425
+ get pending() {
1426
+ return (this.inflight?.items.length ?? 0) + this.buffer.length;
1427
+ }
1428
+ nextId() {
1429
+ return `${this.site}.${++this.counter}.${Math.random().toString(36).slice(2, 6)}`;
1430
+ }
1431
+ submit(e) {
1432
+ return new Promise((t, n) => this.enqueue(async () => {
1433
+ if (this.status === "error") return n(Error(this.error ?? "Collaboration stopped"));
1434
+ if (this.adapter.pessimistic?.(e)) this.buffer.push({
1435
+ op: e,
1436
+ applied: !1,
1437
+ done: t
1438
+ });
1439
+ else {
1440
+ let r;
1441
+ try {
1442
+ r = await this.adapter.apply(e, "local");
1443
+ } catch (e) {
1444
+ return n(e);
1445
+ }
1446
+ this.buffer.push({
1447
+ op: e,
1448
+ applied: !0,
1449
+ undo: r.undo
1450
+ }), t(r.result);
1451
+ }
1452
+ this.flush();
1453
+ }));
1454
+ }
1455
+ push(e, t) {
1456
+ this.buffer.push({
1457
+ op: e,
1458
+ applied: !0,
1459
+ undo: t
1460
+ }), this.enqueue(async () => this.flush());
1461
+ }
1462
+ setPresence(e) {
1463
+ if (this.presence = e, this.presenceTimer) return;
1464
+ let t = Math.max(0, 80 - (Date.now() - this.presenceAt));
1465
+ this.presenceTimer = setTimeout(() => {
1466
+ this.presenceTimer = void 0, this.presenceAt = Date.now(), this.online && this.joined && this.transport.send({
1467
+ t: "presence",
1468
+ data: this.presence
1469
+ });
1470
+ }, t);
1471
+ }
1472
+ on(e, t) {
1473
+ let n = this.listeners.get(e);
1474
+ return n || this.listeners.set(e, n = /* @__PURE__ */ new Set()), n.add(t), () => n.delete(t);
1475
+ }
1476
+ context(e = this.opts.logWindow ?? 5e3) {
1477
+ return e > 0 ? this.log.slice(-e) : [];
1478
+ }
1479
+ idle() {
1480
+ return this.queue;
1481
+ }
1482
+ close() {
1483
+ this.closed = !0, clearTimeout(this.presenceTimer), this.transport.close(), this.listeners.clear();
1484
+ }
1485
+ emit(e, t) {
1486
+ for (let n of this.listeners.get(e) ?? []) n(t);
1487
+ }
1488
+ setStatus(e) {
1489
+ this.status !== e && (this.status = e, this.emit("status", e));
1490
+ }
1491
+ fail(e) {
1492
+ this.error = e, this.setStatus("error"), this.emit("error", Error(e));
1493
+ }
1494
+ enqueue(e) {
1495
+ this.queue = this.queue.then(e).catch((e) => {
1496
+ console.error("[office-engine collab]", e), this.emit("error", e);
1497
+ });
1498
+ }
1499
+ async onMessage(e) {
1500
+ if (!(this.closed || this.status === "error")) switch (e.t) {
1501
+ case "welcome": {
1502
+ if (e.reset) return this.fail("The shared document history was reset; reopen the document");
1503
+ let t = !this.joined;
1504
+ this.site = e.site, this.joined = !0, t && (this.log = e.ctx ?? [], this.setStatus("syncing")), this.peers.clear();
1505
+ for (let t of e.peers) this.peers.set(t.site, Je(t));
1506
+ this.emit("peers", [...this.peers.values()]);
1507
+ for (let t of e.log) await this.onBatch(t);
1508
+ this.inflight && (this.inflight.base = this.rev, this.transport.send({
1509
+ t: "ops",
1510
+ id: this.inflight.id,
1511
+ base: this.rev,
1512
+ ops: this.inflight.items.map((e) => e.op).filter(H)
1513
+ })), this.flush(), this.presence !== void 0 && this.transport.send({
1514
+ t: "presence",
1515
+ data: this.presence
1516
+ }), this.setStatus("live");
1517
+ return;
1518
+ }
1519
+ case "batch": return this.onBatch(e.b);
1520
+ case "presence": {
1521
+ let t = this.peers.get(e.site);
1522
+ t && (this.peers.set(e.site, {
1523
+ ...t,
1524
+ presence: e.data
1525
+ }), this.emit("peers", [...this.peers.values()]));
1526
+ return;
1527
+ }
1528
+ case "join":
1529
+ this.peers.set(e.peer.site, Je(e.peer)), this.emit("peers", [...this.peers.values()]);
1530
+ return;
1531
+ case "leave":
1532
+ this.peers.delete(e.site), this.emit("peers", [...this.peers.values()]);
1533
+ return;
1534
+ case "error": return this.fail(e.message);
1535
+ }
1536
+ }
1537
+ async onBatch(e) {
1538
+ if (e.seq <= this.rev) return;
1539
+ if (e.seq !== this.rev + 1) return this.fail(`Missed operations (${this.rev + 1}…${e.seq - 1})`);
1540
+ if (this.inflight && e.id === this.inflight.id) await this.ack(e);
1541
+ else {
1542
+ let t = this.canonical(e);
1543
+ if (t === null) return;
1544
+ await this.remote(t), this.log.push({
1545
+ seq: e.seq,
1546
+ site: e.site,
1547
+ ops: t
1548
+ });
1549
+ }
1550
+ this.rev = e.seq;
1551
+ let t = this.opts.logWindow ?? 5e3;
1552
+ this.log.length > t && this.log.splice(0, this.log.length - t), this.flush(), this.adapter.settled?.(), this.emit("change", void 0);
1553
+ }
1554
+ canonical(e) {
1555
+ if (!Array.isArray(e.ops)) return [];
1556
+ let t = e.ops.map((t) => !this.adapter.validate || this.adapter.validate(t) ? t : (console.warn(`[office-engine collab] rejected an invalid operation from site ${e.site} (batch ${e.seq})`), null));
1557
+ if (e.base < e.seq - 1 && (this.log[0]?.seq ?? Infinity) > e.base + 1 && this.rev > e.base) return this.fail("Operation is too old to merge; reopen the document"), null;
1558
+ for (let n of this.log) if (!(n.seq <= e.base || n.site === e.site)) for (let e of n.ops) t = t.map((t) => t === null ? null : this.adapter.transform(t, e));
1559
+ return t.filter(H);
1560
+ }
1561
+ async revertAll(e) {
1562
+ for (let t = e.length - 1; t >= 0; t--) {
1563
+ let n = e[t];
1564
+ if (n.applied) {
1565
+ try {
1566
+ await this.adapter.revert(n.undo);
1567
+ } catch (e) {
1568
+ console.error("[office-engine collab] revert failed", e);
1569
+ }
1570
+ n.applied = !1, n.undo = void 0;
1571
+ }
1572
+ }
1573
+ }
1574
+ async replay(e, t, n) {
1575
+ if (e.op) try {
1576
+ let r = await this.adapter.apply(e.op, t);
1577
+ if (e.undo = r.undo, e.applied = !0, e.done) {
1578
+ let t = e.done;
1579
+ e.done = void 0, n ? n.push(() => t(r.result)) : t(r.result);
1580
+ }
1581
+ } catch (e) {
1582
+ console.error("[office-engine collab] replay failed", e);
1583
+ }
1584
+ }
1585
+ async prepare(e) {
1586
+ try {
1587
+ await this.adapter.prepare?.(e);
1588
+ } catch (e) {
1589
+ console.error("[office-engine collab] prepare failed", e);
1590
+ }
1591
+ }
1592
+ async remote(e) {
1593
+ await this.prepare(e);
1594
+ let t = [...this.inflight?.items ?? [], ...this.buffer];
1595
+ if (!t.length) {
1596
+ for (let t of e) await this.applyRemote(t);
1597
+ return;
1598
+ }
1599
+ let n = t.map((t) => {
1600
+ let n = t.op;
1601
+ for (let t of e) n !== null && (n = this.adapter.transform(n, t));
1602
+ return n;
1603
+ }), r = t.filter((e) => e.applied && e.op).map((e) => e.op), i = n.some((e, n) => e !== t[n].op) || r.length > 0 && (this.adapter.conflicts?.(r, e) ?? !0);
1604
+ i && await this.revertAll(t);
1605
+ for (let t of e) await this.applyRemote(t);
1606
+ if (t.forEach((e, t) => e.op = n[t]), i) for (let e of t) !e.op || this.adapter.pessimistic?.(e.op) && !e.applied && e.done || await this.replay(e, "replay");
1607
+ }
1608
+ async applyRemote(e) {
1609
+ try {
1610
+ await this.adapter.apply(e, "remote");
1611
+ } catch (t) {
1612
+ console.error("[office-engine collab] remote op failed", t, e), this.emit("error", t);
1613
+ }
1614
+ }
1615
+ async ack(e) {
1616
+ let t = this.inflight.items;
1617
+ this.inflight = null;
1618
+ let n = t.findIndex((e) => e.op && !e.applied), r = [];
1619
+ if (n >= 0) {
1620
+ await this.prepare(t.slice(n).filter((e) => e.op && !e.applied).map((e) => e.op));
1621
+ let e = [...t.slice(n), ...this.buffer];
1622
+ await this.revertAll(e);
1623
+ for (let n of e) !t.includes(n) && n.op && this.adapter.pessimistic?.(n.op) && n.done || await this.replay(n, n.done ? "local" : "replay", r);
1624
+ }
1625
+ for (let e of r) e();
1626
+ for (let e of t) e.done && e.done(null);
1627
+ this.log.push({
1628
+ seq: e.seq,
1629
+ site: e.site,
1630
+ ops: t.map((e) => e.op).filter(H)
1631
+ });
1632
+ }
1633
+ flush() {
1634
+ if (this.inflight || !this.buffer.length || !this.online || !this.joined || this.status === "error") return;
1635
+ let e = this.buffer;
1636
+ this.buffer = [];
1637
+ let t = `${this.site}-${Date.now().toString(36)}-${++this.counter}`;
1638
+ this.inflight = {
1639
+ id: t,
1640
+ base: this.rev,
1641
+ items: e
1642
+ }, this.transport.send({
1643
+ t: "ops",
1644
+ id: t,
1645
+ base: this.rev,
1646
+ ops: e.map((e) => e.op).filter(H)
1647
+ });
1648
+ }
1649
+ }, U = "$b64";
1650
+ function Xe(e) {
1651
+ let t = "";
1652
+ for (let n = 0; n < e.length; n += 32768) t += String.fromCharCode(...e.subarray(n, n + 32768));
1653
+ return btoa(t);
1654
+ }
1655
+ function Ze(e) {
1656
+ let t = atob(e), n = new Uint8Array(t.length);
1657
+ for (let e = 0; e < t.length; e++) n[e] = t.charCodeAt(e);
1658
+ return n;
1659
+ }
1660
+ function W(e) {
1661
+ return JSON.stringify(e, (e, t) => t instanceof Uint8Array ? { [U]: Xe(t) } : t instanceof ArrayBuffer ? { [U]: Xe(new Uint8Array(t)) } : t);
1662
+ }
1663
+ function G(e) {
1664
+ return JSON.parse(e, (e, t) => t && typeof t == "object" && typeof t[U] == "string" && Object.keys(t).length === 1 ? Ze(t[U]) : t);
1665
+ }
1666
+ // src/collab/transport.ts
1667
+ var Qe = class {
1668
+ url;
1669
+ protocols;
1670
+ onMessage;
1671
+ onStatus;
1672
+ ws;
1673
+ closed = !1;
1674
+ retry = 0;
1675
+ timer;
1676
+ constructor(e, t) {
1677
+ this.url = e, this.protocols = t;
1678
+ }
1679
+ connect() {
1680
+ this.closed = !1, this.open();
1681
+ }
1682
+ open() {
1683
+ if (this.closed) return;
1684
+ this.onStatus?.("connecting");
1685
+ let e = this.ws = new WebSocket(this.url, this.protocols);
1686
+ e.onopen = () => {
1687
+ this.retry = 0, this.onStatus?.("open");
1688
+ }, e.onmessage = (e) => {
1689
+ typeof e.data == "string" && this.onMessage?.(G(e.data));
1690
+ }, e.onclose = () => {
1691
+ if (this.ws !== e || (this.ws = void 0, this.onStatus?.("closed"), this.closed)) return;
1692
+ let t = Math.min(1e4, 300 * 2 ** this.retry++) * (.75 + Math.random() * .5);
1693
+ this.timer = setTimeout(() => this.open(), t);
1694
+ }, e.onerror = () => e.close();
1695
+ }
1696
+ send(e) {
1697
+ this.ws?.readyState === WebSocket.OPEN && this.ws.send(W(e));
1698
+ }
1699
+ close() {
1700
+ this.closed = !0, clearTimeout(this.timer);
1701
+ let e = this.ws;
1702
+ this.ws = void 0, e?.close(), this.onStatus?.("closed");
1703
+ }
1704
+ }, $e = class {
1705
+ hub;
1706
+ latency;
1707
+ onMessage;
1708
+ onStatus;
1709
+ conn;
1710
+ up = Promise.resolve();
1711
+ down = Promise.resolve();
1712
+ constructor(e, t = 0) {
1713
+ this.hub = e, this.latency = t;
1714
+ }
1715
+ delay() {
1716
+ let e = typeof this.latency == "function" ? this.latency() : this.latency;
1717
+ return new Promise((t) => e > 0 ? setTimeout(t, e) : queueMicrotask(t));
1718
+ }
1719
+ connect() {
1720
+ if (this.conn) return;
1721
+ this.onStatus?.("connecting");
1722
+ let e = this.conn = this.hub.connect((t) => {
1723
+ let n = W(t);
1724
+ this.down = this.down.then(() => this.delay()).then(() => {
1725
+ this.conn === e && this.onMessage?.(G(n));
1726
+ });
1727
+ });
1728
+ queueMicrotask(() => this.onStatus?.("open"));
1729
+ }
1730
+ send(e) {
1731
+ let t = this.conn;
1732
+ if (!t) return;
1733
+ let n = W(e);
1734
+ this.up = this.up.then(() => this.delay()).then(() => {
1735
+ this.conn === t && t.receive(G(n));
1736
+ });
1737
+ }
1738
+ drop() {
1739
+ let e = this.conn;
1740
+ this.conn = void 0, e?.close(), this.onStatus?.("closed");
1741
+ }
1742
+ close() {
1743
+ this.drop();
1744
+ }
1745
+ }, et = /* @__PURE__ */ new Set([
1746
+ "comments.set",
1747
+ "xlsx.set",
1748
+ "xlsx.format",
1749
+ "xlsx.sheetOp",
1750
+ "xlsx.replace",
1751
+ "xlsx.bookOp",
1752
+ "xlsx.undo",
1753
+ "xlsx.redo"
1754
+ ]), tt = class {
1755
+ client;
1756
+ submit;
1757
+ nextId;
1758
+ onPresence;
1759
+ undoStack = [];
1760
+ redoStack = [];
1761
+ offLocal;
1762
+ constructor(e) {
1763
+ this.client = e, this.offLocal = ie(e, (e) => {
1764
+ let t = e, n = this.path(t.sheet);
1765
+ n && this.onPresence?.({
1766
+ k: "xlsx",
1767
+ sheet: n,
1768
+ range: t.range,
1769
+ ar: t.ar,
1770
+ ac: t.ac
1771
+ });
1772
+ });
1773
+ }
1774
+ dispose() {
1775
+ this.offLocal();
1776
+ }
1777
+ get meta() {
1778
+ return this.client.info.xlsx;
1779
+ }
1780
+ path(e) {
1781
+ return this.meta.sheets[e]?.path ?? "";
1782
+ }
1783
+ id() {
1784
+ return this.nextId();
1785
+ }
1786
+ captures(e) {
1787
+ return et.has(e);
1788
+ }
1789
+ intercept(e, t) {
1790
+ if (!this.submit) return;
1791
+ let n = t;
1792
+ switch (e) {
1793
+ case "comments.set": return this.submit({
1794
+ t: "comment",
1795
+ id: this.id(),
1796
+ cid: n[0],
1797
+ c: n[1]
1798
+ });
1799
+ case "xlsx.set": return this.local({
1800
+ t: "set",
1801
+ id: this.id(),
1802
+ sheet: this.path(n[0]),
1803
+ cells: n[1]
1804
+ });
1805
+ case "xlsx.format": return this.local({
1806
+ t: "fmt",
1807
+ id: this.id(),
1808
+ sheet: this.path(n[0]),
1809
+ range: n[1],
1810
+ patch: n[2]
1811
+ });
1812
+ case "xlsx.sheetOp": return this.local({
1813
+ t: "sheet",
1814
+ id: this.id(),
1815
+ sheet: this.path(n[0]),
1816
+ op: n[1]
1817
+ });
1818
+ case "xlsx.replace": return this.local({
1819
+ t: "replace",
1820
+ id: this.id(),
1821
+ sheet: this.path(n[0]),
1822
+ query: n[1],
1823
+ by: n[2],
1824
+ opts: n[3],
1825
+ at: n[4]
1826
+ });
1827
+ case "xlsx.bookOp": return this.local({
1828
+ t: "book",
1829
+ id: this.id(),
1830
+ op: this.pbook(n[0])
1831
+ });
1832
+ case "xlsx.undo": return this.history(this.undoStack, this.redoStack, "prev");
1833
+ case "xlsx.redo": return this.history(this.redoStack, this.undoStack, "next");
1834
+ }
1835
+ }
1836
+ pbook(e) {
1837
+ switch (e.op) {
1838
+ case "add": return {
1839
+ op: "add",
1840
+ name: e.name,
1841
+ after: e.after === void 0 ? void 0 : this.path(e.after)
1842
+ };
1843
+ case "rename": return {
1844
+ op: "rename",
1845
+ path: this.path(e.index),
1846
+ name: e.name
1847
+ };
1848
+ case "delete": return {
1849
+ op: "delete",
1850
+ path: this.path(e.index)
1851
+ };
1852
+ case "move": return {
1853
+ op: "move",
1854
+ path: this.path(e.from),
1855
+ to: e.to
1856
+ };
1857
+ }
1858
+ }
1859
+ local(e) {
1860
+ if (e.t === "sheet" && (e.op.op === "insertRows" || e.op.op === "insertCols")) {
1861
+ let t = {
1862
+ op: e.op.op === "insertRows" ? "deleteRows" : "deleteCols",
1863
+ at: e.op.at,
1864
+ n: e.op.n
1865
+ };
1866
+ this.undoStack.push({
1867
+ kind: "inverse",
1868
+ sheet: e.sheet,
1869
+ undo: t,
1870
+ redo: e.op
1871
+ });
1872
+ } else o(e) || this.undoStack.push({
1873
+ kind: "op",
1874
+ id: e.id
1875
+ });
1876
+ return this.undoStack.length > 200 && this.undoStack.shift(), this.redoStack = [], this.submit(e);
1877
+ }
1878
+ history(e, t, n) {
1879
+ let r = e.pop();
1880
+ return r ? (t.push(r), r.kind === "op" ? this.submit({
1881
+ t: "revert",
1882
+ id: this.id(),
1883
+ target: r.id,
1884
+ which: n
1885
+ }) : this.submit({
1886
+ t: "sheet",
1887
+ id: this.id(),
1888
+ sheet: r.sheet,
1889
+ op: n === "prev" ? r.undo : r.redo
1890
+ })) : Promise.resolve(null);
1891
+ }
1892
+ transform(e, t) {
1893
+ return r(e, t);
1894
+ }
1895
+ conflicts(e, t) {
1896
+ return i(e, t);
1897
+ }
1898
+ validate(e) {
1899
+ return s(e);
1900
+ }
1901
+ pessimistic(e) {
1902
+ return o(e);
1903
+ }
1904
+ async apply(e, t) {
1905
+ if (e.t === "comment") return I(this.client, e);
1906
+ let { res: n, rec: r } = await this.client.direct("collab.xlsx.apply", e);
1907
+ if (o(e)) {
1908
+ let e = (e) => e.kind === "inverse" && t === "local";
1909
+ this.undoStack = this.undoStack.filter(e), this.redoStack = this.redoStack.filter(e);
1910
+ }
1911
+ return t !== "local" && n && this.client.notify("collab:xlsx", n), {
1912
+ result: n,
1913
+ undo: r
1914
+ };
1915
+ }
1916
+ async revert(e) {
1917
+ let t = L(this.client, e);
1918
+ if (t) return t;
1919
+ if (typeof e != "number") return;
1920
+ let n = await this.client.direct("collab.xlsx.revert", e);
1921
+ n && this.client.notify("collab:xlsx", n);
1922
+ }
1923
+ };
1924
+ // src/collab/pptx-ops.ts
1925
+ function nt(e, t) {
1926
+ return t.t === "slides" && t.op.op === "delete" && "slide" in e && e.slide === t.op.path ? null : e;
1927
+ }
1928
+ function rt(e, t) {
1929
+ if (t.some((e) => e.t === "slides" || e.t === "revert") || e.some((e) => e.t === "revert")) return !0;
1930
+ let n = new Set(e.flatMap((e) => e.t === "comment" ? [e.cid] : []));
1931
+ if (t.some((e) => e.t === "comment" && n.has(e.cid))) return !0;
1932
+ let r = new Set(e.flatMap((e) => "slide" in e && e.t !== "image" ? [e.slide] : []));
1933
+ return t.some((e) => "slide" in e && e.t !== "image" && r.has(e.slide));
1934
+ }
1935
+ // src/collab/pptx.ts
1936
+ var it = /* @__PURE__ */ new Set([
1937
+ "pptx.setText",
1938
+ "pptx.shapes",
1939
+ "pptx.slides",
1940
+ "pptx.image",
1941
+ "pptx.undo"
1942
+ ]), at = class {
1943
+ client;
1944
+ submit;
1945
+ nextId;
1946
+ onPresence;
1947
+ undoStack = [];
1948
+ redoStack = [];
1949
+ ridKey = /* @__PURE__ */ new Map();
1950
+ offLocal;
1951
+ constructor(e) {
1952
+ this.client = e, this.offLocal = ie(e, (e) => {
1953
+ let t = e, n = this.path(t.slide);
1954
+ n && this.onPresence?.({
1955
+ k: "pptx",
1956
+ slide: n,
1957
+ top: t.top
1958
+ });
1959
+ });
1960
+ }
1961
+ dispose() {
1962
+ this.offLocal();
1963
+ }
1964
+ get meta() {
1965
+ return this.client.info.pptx;
1966
+ }
1967
+ path(e) {
1968
+ return this.meta.slides[e]?.path ?? "";
1969
+ }
1970
+ id() {
1971
+ return this.nextId();
1972
+ }
1973
+ captures(e) {
1974
+ return e === "comments.set" || it.has(e);
1975
+ }
1976
+ intercept(e, t) {
1977
+ if (!this.submit) return;
1978
+ let n = t;
1979
+ switch (e) {
1980
+ case "comments.set": return this.submit({
1981
+ t: "comment",
1982
+ id: this.id(),
1983
+ cid: n[0],
1984
+ c: n[1]
1985
+ });
1986
+ case "pptx.setText": return this.local({
1987
+ t: "text",
1988
+ id: this.id(),
1989
+ slide: this.path(n[0]),
1990
+ sid: n[1],
1991
+ paras: n[2]
1992
+ }).then((e) => e.model);
1993
+ case "pptx.shapes": {
1994
+ let e = n[1].map((e) => e.op === "insert" && e.rid && this.ridKey.has(e.rid) ? {
1995
+ ...e,
1996
+ rid: void 0,
1997
+ key: this.ridKey.get(e.rid)
1998
+ } : e);
1999
+ return this.local({
2000
+ t: "shapes",
2001
+ id: this.id(),
2002
+ slide: this.path(n[0]),
2003
+ ops: e
2004
+ }).then((e) => e.model);
2005
+ }
2006
+ case "pptx.image": {
2007
+ let e = `${this.id()}`, t = new Uint8Array(n[1].slice(0));
2008
+ return this.submit({
2009
+ t: "image",
2010
+ id: e,
2011
+ key: e,
2012
+ slide: this.path(n[0]),
2013
+ bytes: t,
2014
+ ext: n[2]
2015
+ }).then((t) => {
2016
+ let n = t.rid;
2017
+ return n && this.ridKey.set(n, e), n;
2018
+ });
2019
+ }
2020
+ case "pptx.slides": return this.submit({
2021
+ t: "slides",
2022
+ id: this.id(),
2023
+ op: this.pslide(n[0])
2024
+ }).then((e) => e?.meta ?? this.meta);
2025
+ case "pptx.undo": return this.history(n[0] ? this.redoStack : this.undoStack, n[0] ? this.undoStack : this.redoStack, n[0] ? "next" : "prev");
2026
+ }
2027
+ }
2028
+ pslide(e) {
2029
+ switch (e.op) {
2030
+ case "add": return {
2031
+ op: "add",
2032
+ after: e.after >= 0 && this.path(e.after) || null,
2033
+ layout: e.layout
2034
+ };
2035
+ case "duplicate": return {
2036
+ op: "duplicate",
2037
+ path: this.path(e.index)
2038
+ };
2039
+ case "delete": return {
2040
+ op: "delete",
2041
+ path: this.path(e.index)
2042
+ };
2043
+ case "move": return {
2044
+ op: "move",
2045
+ path: this.path(e.from),
2046
+ to: e.to
2047
+ };
2048
+ case "hide": return {
2049
+ op: "hide",
2050
+ path: this.path(e.index),
2051
+ hidden: e.hidden
2052
+ };
2053
+ }
2054
+ }
2055
+ local(e) {
2056
+ return this.undoStack.push(e.id), this.undoStack.length > 200 && this.undoStack.shift(), this.redoStack = [], this.submit(e);
2057
+ }
2058
+ async history(e, t, n) {
2059
+ let r = e.pop();
2060
+ if (!r) return null;
2061
+ t.push(r);
2062
+ let i = await this.submit({
2063
+ t: "revert",
2064
+ id: this.id(),
2065
+ target: r,
2066
+ which: n
2067
+ });
2068
+ return i.model && i.slide !== void 0 ? {
2069
+ index: i.slide,
2070
+ model: i.model
2071
+ } : null;
2072
+ }
2073
+ transform(e, t) {
2074
+ return nt(e, t);
2075
+ }
2076
+ conflicts(e, t) {
2077
+ return rt(e, t);
2078
+ }
2079
+ validate(e) {
2080
+ return a(e);
2081
+ }
2082
+ pessimistic(e) {
2083
+ return e.t === "slides";
2084
+ }
2085
+ prepare(e) {
2086
+ e.some((e) => e.t === "slides") && d(this.client, "pptx")?.endEditing();
2087
+ }
2088
+ async apply(e, t) {
2089
+ if (e.t === "comment") return I(this.client, e);
2090
+ let { res: n, rec: r } = await this.client.direct("collab.pptx.apply", e);
2091
+ return e.t === "slides" && (this.undoStack = [], this.redoStack = [], n.meta && Object.assign(this.meta, n.meta)), t !== "local" && this.client.notify("collab:pptx", n), {
2092
+ result: n,
2093
+ undo: r
2094
+ };
2095
+ }
2096
+ async revert(e) {
2097
+ let t = L(this.client, e);
2098
+ if (t) return t;
2099
+ typeof e == "number" && this.client.notify("collab:pptx", await this.client.direct("collab.pptx.revert", e));
2100
+ }
2101
+ }, K = (e) => !!e && typeof e == "object" && !Array.isArray(e) && !(e instanceof Uint8Array), q = (e) => Number.isInteger(e) && e >= 0 && e <= 2 ** 31, J = (e, t, n) => typeof e == "string" && e.length >= t && e.length <= n && !/[\u0000-\u001f]/.test(e);
2102
+ function ot(e, t) {
2103
+ let n = 0, r = [e];
2104
+ for (; r.length;) {
2105
+ let e = r.pop();
2106
+ if (e == null || typeof e == "boolean" || typeof e == "number") n += 8;
2107
+ else if (typeof e == "string") n += e.length + 2;
2108
+ else if (e instanceof Uint8Array) n += e.length;
2109
+ else if (Array.isArray(e)) {
2110
+ n += 2;
2111
+ for (let t of e) r.push(t);
2112
+ } else if (K(e)) for (let t of Object.keys(e)) {
2113
+ if (t === "__proto__") return Infinity;
2114
+ n += t.length + 4, r.push(e[t]);
2115
+ }
2116
+ else return Infinity;
2117
+ if (n > t) return Infinity;
2118
+ }
2119
+ return n;
2120
+ }
2121
+ var st = class {
2122
+ opts;
2123
+ rooms = /* @__PURE__ */ new Map();
2124
+ loading = /* @__PURE__ */ new Map();
2125
+ constructor(e = {}) {
2126
+ this.opts = e;
2127
+ }
2128
+ room(e) {
2129
+ let t = this.rooms.get(e);
2130
+ if (t) return Promise.resolve(t);
2131
+ let n = this.loading.get(e);
2132
+ return n || (n = Promise.resolve(this.opts.loadLog?.(e)).then((t) => {
2133
+ if (this.loading.get(e) !== n) return this.room(e);
2134
+ let r = this.rooms.get(e) ?? ct(e, t);
2135
+ return this.rooms.set(e, r), r;
2136
+ }), n.finally(() => this.loading.get(e) === n && this.loading.delete(e)).catch(() => {}), this.loading.set(e, n)), n;
2137
+ }
2138
+ reset(e) {
2139
+ let t = this.rooms.get(e);
2140
+ if (t) for (let e of t.peers.values()) e.send({
2141
+ t: "error",
2142
+ message: "Room was reset"
2143
+ });
2144
+ this.rooms.delete(e), this.loading.delete(e);
2145
+ }
2146
+ unload(e) {
2147
+ return !this.rooms.get(e)?.peers.size && (this.rooms.delete(e), !0);
2148
+ }
2149
+ snapshot(e, t) {
2150
+ let n = this.rooms.get(e);
2151
+ if (!n || t.seq > n.seq || t.seq < n.start) return !1;
2152
+ n.snaps.set(t.seq, t.ctx);
2153
+ let r = [...n.snaps.keys()].sort((e, t) => e - t);
2154
+ for (let e of r.splice(0, Math.max(0, r.length - (this.opts.keep ?? 3)))) n.snaps.delete(e);
2155
+ let i = Math.min(r[0], r[r.length - 1] - (this.opts.retain ?? 1e3));
2156
+ if (i > n.start) {
2157
+ let e = 0;
2158
+ for (; e < n.log.length && n.log[e].seq <= i;) n.ids.delete(n.log[e++].id);
2159
+ n.log.splice(0, e), n.start = i;
2160
+ }
2161
+ return !0;
2162
+ }
2163
+ connect(e) {
2164
+ let t, r = 0, i = !1, a = null, o = this.opts.rate ?? {
2165
+ perSecond: 300,
2166
+ burst: 1500
2167
+ }, s = this.opts.now ?? Date.now, c = o.burst, l = s(), u = (e) => void this.opts.onReject?.(t?.id, e), d = (e) => {
2168
+ if (!K(e)) return "not an object";
2169
+ let t = this.opts.maxMessageBytes ?? 16777216;
2170
+ switch (e.t) {
2171
+ case "hello": {
2172
+ let t = e.user;
2173
+ if (!J(e.room, 1, 200) || !K(t) || !J(t.name, 1, 100) || t.id !== void 0 && !J(t.id, 1, 200) || e.have !== void 0 && !q(e.have) || e.site !== void 0 && !q(e.site) || e.base !== void 0 && !q(e.base)) return "bad hello";
2174
+ let n = {
2175
+ name: t.name,
2176
+ ...t.id === void 0 ? {} : { id: t.id },
2177
+ ...typeof t.color == "string" ? { color: t.color } : {}
2178
+ };
2179
+ return {
2180
+ t: "hello",
2181
+ room: e.room,
2182
+ user: n,
2183
+ have: e.have,
2184
+ site: e.site,
2185
+ base: e.base
2186
+ };
2187
+ }
2188
+ case "ops": {
2189
+ if (!J(e.id, 1, 100) || !q(e.base) || !Array.isArray(e.ops)) return "bad ops";
2190
+ if (e.ops.length > (this.opts.maxOps ?? 1e3)) return "bad ops: batch size";
2191
+ let n = this.opts.opTypes;
2192
+ return n && !e.ops.every((e) => K(e) && typeof e.t == "string" && n.includes(e.t)) ? "bad ops: unknown operation type" : ot(e.ops, t) === Infinity ? "bad ops: too large" : {
2193
+ t: "ops",
2194
+ id: e.id,
2195
+ base: e.base,
2196
+ ops: e.ops
2197
+ };
2198
+ }
2199
+ case "presence": return ot(e.data, 16384) === Infinity ? "bad presence" : {
2200
+ t: "presence",
2201
+ data: e.data
2202
+ };
2203
+ }
2204
+ return "unknown message type";
2205
+ }, f = (e, n) => {
2206
+ if (t) for (let [r, i] of t.peers) r !== n && i.send(e);
2207
+ }, p = (i, a) => {
2208
+ t = i, r = a.site && a.site < i.nextSite && !i.peers.has(a.site) ? a.site : i.nextSite++;
2209
+ let o = new Set([...i.peers.values()].map((e) => e.info.color)), s = n(a.user.color) || F.find((e) => !o.has(e)) || F[r % F.length], c = {
2210
+ ...a.user,
2211
+ site: r,
2212
+ color: s
2213
+ }, l, u, d;
2214
+ a.have === void 0 ? (l = a.base ?? 0, u = l === 0 ? void 0 : i.snaps.get(l), d = l > i.seq || l < i.start || l > 0 && !u) : (l = a.have, d = l > i.seq || l < i.start), e({
2215
+ t: "welcome",
2216
+ site: r,
2217
+ seq: i.seq,
2218
+ from: l,
2219
+ reset: d,
2220
+ log: d ? [] : i.log.filter((e) => e.seq > l),
2221
+ peers: [...i.peers.values()].map((e) => e.info),
2222
+ ...u && !d ? { ctx: u } : {}
2223
+ }), i.peers.set(r, {
2224
+ info: c,
2225
+ send: e
2226
+ }), f({
2227
+ t: "join",
2228
+ peer: c
2229
+ }, r);
2230
+ }, m = (n) => {
2231
+ if (!i) {
2232
+ if (a) return void a.push(n);
2233
+ if (n.t === "hello") {
2234
+ if (t) return;
2235
+ a = [], this.room(n.room).then((e) => {
2236
+ let t = a;
2237
+ a = null, i || (p(e, n), t.forEach(m));
2238
+ }, (t) => {
2239
+ a = null, e({
2240
+ t: "error",
2241
+ message: `Room failed to load: ${t.message}`
2242
+ });
2243
+ });
2244
+ } else {
2245
+ if (!t) return e({
2246
+ t: "error",
2247
+ message: "Not joined"
2248
+ });
2249
+ if (n.t === "ops") {
2250
+ if (t.ids.has(n.id)) return;
2251
+ let e = t.peers.get(r), i = {
2252
+ seq: ++t.seq,
2253
+ site: r,
2254
+ base: Math.min(n.base, t.seq - 1),
2255
+ id: n.id,
2256
+ ops: n.ops,
2257
+ time: Date.now(),
2258
+ user: e?.info.id ?? e?.info.name
2259
+ };
2260
+ t.log.push(i), t.ids.add(i.id), this.opts.onBatch?.(t.id, i), f({
2261
+ t: "batch",
2262
+ b: i
2263
+ });
2264
+ } else if (n.t === "presence") {
2265
+ let e = t.peers.get(r);
2266
+ e && (e.info.presence = n.data), f({
2267
+ t: "presence",
2268
+ site: r,
2269
+ data: n.data
2270
+ }, r);
2271
+ }
2272
+ }
2273
+ }
2274
+ };
2275
+ return {
2276
+ receive: (e) => {
2277
+ if (i) return;
2278
+ let t = s();
2279
+ if (c = Math.min(o.burst, c + (t - l) / 1e3 * o.perSecond), l = t, c < 1) return u("rate limit");
2280
+ c--;
2281
+ let n = d(e);
2282
+ if (typeof n == "string") return u(n);
2283
+ m(n);
2284
+ },
2285
+ close: () => {
2286
+ i = !0, t && t.peers.has(r) && (t.peers.delete(r), f({
2287
+ t: "leave",
2288
+ site: r
2289
+ }), t.peers.size || this.opts.onIdle?.(t.id));
2290
+ }
2291
+ };
2292
+ }
2293
+ };
2294
+ function ct(e, t) {
2295
+ let n = Array.isArray(t) ? { log: t } : t ?? { log: [] }, r = n.snapshot, i = [...n.log].sort((e, t) => e.seq - t.seq);
2296
+ for (let e = i.length - 1; e > 0; e--) if (i[e - 1].seq !== i[e].seq - 1) {
2297
+ i = i.slice(e);
2298
+ break;
2299
+ }
2300
+ let a = i.length ? i[i.length - 1].seq : 0, o = i.length ? i[0].seq - 1 : 0;
2301
+ r && (r.seq > a || r.seq < o) && (a = o = r.seq, i = []);
2302
+ let s = Math.max(1, r?.sites ?? 1);
2303
+ for (let e of i) s = Math.max(s, e.site + 1);
2304
+ for (let e of r?.ctx ?? []) s = Math.max(s, e.site + 1);
2305
+ return {
2306
+ id: e,
2307
+ seq: a,
2308
+ log: i,
2309
+ start: o,
2310
+ nextSite: s,
2311
+ ids: new Set(i.map((e) => e.id)),
2312
+ peers: /* @__PURE__ */ new Map(),
2313
+ snaps: new Map(r ? [[r.seq, r.ctx]] : [])
2314
+ };
2315
+ }
2316
+ // src/collab/compact.ts
2317
+ var lt = class {
2318
+ welcome;
2319
+ onMessage;
2320
+ onStatus;
2321
+ constructor(e) {
2322
+ this.welcome = e;
2323
+ }
2324
+ connect() {
2325
+ queueMicrotask(() => this.onStatus?.("open"));
2326
+ }
2327
+ send(e) {
2328
+ e.t === "hello" && queueMicrotask(() => this.onMessage?.(this.welcome));
2329
+ }
2330
+ close() {}
2331
+ };
2332
+ async function ut(e, t) {
2333
+ if (e.kind === "docx" && !d(e, "docx")) throw Error("compact: DOCX needs its editor host registered (registerHost)");
2334
+ let n = t.from ?? {
2335
+ seq: 0,
2336
+ ctx: []
2337
+ }, r = t.batches.filter((e) => e.seq > n.seq).sort((e, t) => e.seq - t.seq);
2338
+ r.forEach((e, t) => {
2339
+ if (e.seq !== n.seq + t + 1) throw Error(`compact: batch ${n.seq + t + 1} is missing`);
2340
+ });
2341
+ let i = n.seq + r.length, a = pt(e, {
2342
+ transport: new lt({
2343
+ t: "welcome",
2344
+ site: 0,
2345
+ seq: i,
2346
+ from: n.seq,
2347
+ log: r,
2348
+ peers: [],
2349
+ ctx: n.ctx
2350
+ }),
2351
+ room: "",
2352
+ user: { name: "compact" },
2353
+ base: n.seq
2354
+ });
2355
+ try {
2356
+ if (await new Promise((e, t) => {
2357
+ let n = () => {
2358
+ a.status === "live" ? e() : a.status === "error" && t(Error(a.session.error ?? "compact failed"));
2359
+ };
2360
+ a.on("status", n), n();
2361
+ }), await a.session.idle(), a.session.rev !== i) throw Error(`compact: stopped at ${a.session.rev} of ${i}`);
2362
+ return {
2363
+ seq: i,
2364
+ ctx: a.session.context(t.window ?? 1e3)
2365
+ };
2366
+ } finally {
2367
+ a.close();
2368
+ }
2369
+ }
2370
+ // src/collab/store.ts
2371
+ var dt = class {
2372
+ data = /* @__PURE__ */ new Map();
2373
+ async get(e) {
2374
+ return this.data.get(e) ?? null;
2375
+ }
2376
+ async put(e, t) {
2377
+ this.data.set(e, t.slice());
2378
+ }
2379
+ async list(e) {
2380
+ return [...this.data.keys()].filter((t) => t.startsWith(e));
2381
+ }
2382
+ async delete(e) {
2383
+ this.data.delete(e);
2384
+ }
2385
+ }, Y = (e) => String(e).padStart(12, "0"), X = new TextEncoder(), Z = new TextDecoder(), Q = (e) => X.encode(JSON.stringify(e)), $ = (e) => e ? JSON.parse(Z.decode(e)) : null, ft = class {
2386
+ blobs;
2387
+ opts;
2388
+ heads = /* @__PURE__ */ new Map();
2389
+ buffers = /* @__PURE__ */ new Map();
2390
+ queues = /* @__PURE__ */ new Map();
2391
+ constructor(e, t = {}) {
2392
+ this.blobs = e, this.opts = t;
2393
+ }
2394
+ dir(e) {
2395
+ return `${this.opts.prefix ?? ""}${encodeURIComponent(e).replace(/\./g, "%2E")}/`;
2396
+ }
2397
+ epochDir(e, t) {
2398
+ return `${this.dir(e)}${t}/`;
2399
+ }
2400
+ run(e, t) {
2401
+ let n = (this.queues.get(e) ?? Promise.resolve()).then(t, t), r = n.catch(() => {});
2402
+ return this.queues.set(e, r), r.then(() => this.queues.get(e) === r && this.queues.delete(e)), n;
2403
+ }
2404
+ async readHead(e) {
2405
+ if (this.heads.has(e)) return this.heads.get(e);
2406
+ let t = $(await this.blobs.get(this.dir(e) + "head.json"));
2407
+ return this.heads.set(e, t), t;
2408
+ }
2409
+ create(e, t, n) {
2410
+ let r = this.buffers.get(e);
2411
+ return r && (clearTimeout(r.timer), this.buffers.delete(e)), this.run(e, async () => {
2412
+ let r = await this.readHead(e), i = {
2413
+ epoch: Date.now().toString(36) + Math.random().toString(36).slice(2, 6),
2414
+ seq: 0,
2415
+ size: t.length,
2416
+ time: Date.now(),
2417
+ ...n
2418
+ }, a = this.epochDir(e, i.epoch);
2419
+ if (await this.blobs.put(`${a}snap/${Y(0)}.bin`, t), await this.blobs.put(`${a}snap/${Y(0)}.json`, Q({
2420
+ seq: 0,
2421
+ size: t.length,
2422
+ time: i.time
2423
+ })), await this.blobs.put(this.dir(e) + "head.json", Q(i)), this.heads.set(e, i), r) for (let t of await this.blobs.list(this.epochDir(e, r.epoch))) await this.blobs.delete(t);
2424
+ return i;
2425
+ });
2426
+ }
2427
+ head(e) {
2428
+ return this.run(e, () => this.readHead(e));
2429
+ }
2430
+ async file(e, t, n) {
2431
+ return n ??= (await this.head(e))?.epoch, n ? this.blobs.get(`${this.epochDir(e, n)}snap/${Y(t)}.bin`) : null;
2432
+ }
2433
+ async snapshot(e, t, n) {
2434
+ if (n ??= (await this.head(e))?.epoch, !n) return null;
2435
+ let r = `${this.epochDir(e, n)}snap/${Y(t)}`, i = $(await this.blobs.get(r + ".json"));
2436
+ if (!i) return null;
2437
+ let a = await this.blobs.get(r + ".ctx");
2438
+ return {
2439
+ ...i,
2440
+ ctx: a ? G(Z.decode(a)) : []
2441
+ };
2442
+ }
2443
+ async versions(e, t) {
2444
+ if (t ??= (await this.head(e))?.epoch, !t) return [];
2445
+ let n = `${this.epochDir(e, t)}snap/`, r = (await this.blobs.list(n)).filter((e) => e.endsWith(".json")).sort(), i = [];
2446
+ for (let e of r) {
2447
+ let t = $(await this.blobs.get(e));
2448
+ t && i.push({
2449
+ seq: t.seq,
2450
+ size: t.size,
2451
+ time: t.time
2452
+ });
2453
+ }
2454
+ return i;
2455
+ }
2456
+ async batches(e, t, n = Infinity, r) {
2457
+ if (r ??= (await this.head(e))?.epoch, !r) return [];
2458
+ let i = (await this.blobs.list(`${this.epochDir(e, r)}ops/`)).map((e) => {
2459
+ let t = /(\d+)-(\d+)\.jsonl$/.exec(e);
2460
+ return t ? {
2461
+ k: e,
2462
+ first: Number(t[1]),
2463
+ last: Number(t[2])
2464
+ } : null;
2465
+ }).filter((e) => e !== null && e.last > t && e.first <= n).sort((e, t) => e.first - t.first), a = /* @__PURE__ */ new Set(), o = [];
2466
+ for (let e of i) {
2467
+ let r = Z.decode(await this.blobs.get(e.k) ?? /* @__PURE__ */ new Uint8Array());
2468
+ for (let e of r.split("\n")) {
2469
+ if (!e) continue;
2470
+ let r = G(e);
2471
+ r.seq > t && r.seq <= n && !a.has(r.seq) && (a.add(r.seq), o.push(r));
2472
+ }
2473
+ }
2474
+ return o.sort((e, t) => e.seq - t.seq);
2475
+ }
2476
+ append(e, t) {
2477
+ let n = this.buffers.get(e);
2478
+ n || this.buffers.set(e, n = {
2479
+ batches: [],
2480
+ retry: 0
2481
+ }), n.batches.push(t), n.timer || (n.timer = setTimeout(() => void this.flushRoom(e), this.opts.flushMs ?? 250));
2482
+ }
2483
+ async flush(e) {
2484
+ let t = e === void 0 ? [...this.buffers.keys()] : [e];
2485
+ await Promise.all(t.map((e) => this.flushRoom(e)));
2486
+ }
2487
+ flushRoom(e) {
2488
+ let t = this.buffers.get(e);
2489
+ return t && (clearTimeout(t.timer), t.timer = void 0), this.run(e, async () => {
2490
+ let t = this.buffers.get(e);
2491
+ if (!t?.batches.length) return;
2492
+ let n = t.batches;
2493
+ t.batches = [];
2494
+ let r = await this.readHead(e);
2495
+ if (!r) return;
2496
+ let i = `${this.epochDir(e, r.epoch)}ops/${Y(n[0].seq)}-${Y(n[n.length - 1].seq)}.jsonl`;
2497
+ try {
2498
+ await this.blobs.put(i, X.encode(n.map((e) => W(e)).join("\n") + "\n")), t.retry = 0;
2499
+ } catch (r) {
2500
+ if (this.opts.onError?.(r, e), this.buffers.get(e) !== t) return;
2501
+ t.batches.unshift(...n), t.timer ||= setTimeout(() => void this.flushRoom(e), Math.min(3e4, 500 * 2 ** t.retry++));
2502
+ }
2503
+ });
2504
+ }
2505
+ load(e) {
2506
+ return this.flushRoom(e).then(() => this.run(e, async () => {
2507
+ this.heads.delete(e);
2508
+ let t = await this.readHead(e);
2509
+ if (!t) return;
2510
+ let n = await this.snapshot(e, t.seq, t.epoch);
2511
+ return {
2512
+ log: await this.batches(e, Math.max(0, t.seq - (this.opts.retain ?? 1e3)), Infinity, t.epoch),
2513
+ snapshot: n ?? {
2514
+ seq: t.seq,
2515
+ ctx: []
2516
+ }
2517
+ };
2518
+ }));
2519
+ }
2520
+ save(e, t, n, r) {
2521
+ return this.run(e, async () => {
2522
+ let i = await this.readHead(e);
2523
+ if (!i || i.epoch !== t.epoch || n.seq <= i.seq) return null;
2524
+ let a = this.epochDir(e, i.epoch), o = Date.now();
2525
+ await Promise.all([
2526
+ this.blobs.put(`${a}snap/${Y(n.seq)}.bin`, r),
2527
+ this.blobs.put(`${a}snap/${Y(n.seq)}.ctx`, X.encode(W(n.ctx))),
2528
+ this.blobs.put(`${a}snap/${Y(n.seq)}.json`, Q({
2529
+ seq: n.seq,
2530
+ size: r.length,
2531
+ time: o,
2532
+ sites: n.sites
2533
+ }))
2534
+ ]);
2535
+ let s = {
2536
+ ...i,
2537
+ seq: n.seq,
2538
+ size: r.length,
2539
+ time: o
2540
+ };
2541
+ return await this.blobs.put(this.dir(e) + "head.json", Q(s)), this.heads.set(e, s), this.opts.keep && await this.prune(e, s), s;
2542
+ });
2543
+ }
2544
+ async prune(e, t) {
2545
+ let n = `${this.epochDir(e, t.epoch)}snap/`, r = [...new Set((await this.blobs.list(n)).map((e) => Number(/(\d+)\.\w+$/.exec(e)?.[1])).filter((e) => !Number.isNaN(e)))].sort((e, t) => e - t), i = r.slice(0, Math.max(0, r.length - this.opts.keep));
2546
+ for (let e of i) for (let t of [
2547
+ "bin",
2548
+ "json",
2549
+ "ctx"
2550
+ ]) await this.blobs.delete(`${n}${Y(e)}.${t}`);
2551
+ let a = r[i.length], o = Math.min(a, t.seq - (this.opts.retain ?? 1e3));
2552
+ for (let n of await this.blobs.list(`${this.epochDir(e, t.epoch)}ops/`)) Number(/-(\d+)\.jsonl$/.exec(n)?.[1]) <= o && await this.blobs.delete(n);
2553
+ }
2554
+ };
2555
+ // src/collab/index.ts
2556
+ function pt(e, t) {
2557
+ let n = typeof t.transport == "string" ? new Qe(t.transport) : t.transport, r = e.kind === "docx" ? new qe(e) : void 0, i = r ?? (e.kind === "xlsx" ? new tt(e) : new at(e)), a = new Ye(n, i, {
2558
+ room: t.room,
2559
+ user: t.user,
2560
+ base: t.base
2561
+ });
2562
+ i.submit = (e) => a.submit(e), i.push = (e, t) => a.push(e, t), i.nextId = () => a.nextId(), i.onPresence = (e) => a.setPresence(e), e.interceptor = (e, t) => {
2563
+ if (i.captures(e)) return a.status === "connecting" || a.status === "syncing" || a.status === "error" ? Promise.reject(Error(a.status === "error" ? a.error ?? "Collaboration stopped" : "Document is still syncing")) : i.intercept(e, t);
2564
+ };
2565
+ let o = [a.on("peers", (t) => h(e, t)), a.on("status", (e) => {
2566
+ e === "live" && i.setSite?.(a.site);
2567
+ })];
2568
+ return {
2569
+ session: a,
2570
+ get status() {
2571
+ return a.status;
2572
+ },
2573
+ get peers() {
2574
+ return [...a.peers.values()];
2575
+ },
2576
+ get pending() {
2577
+ return a.pending;
2578
+ },
2579
+ on: (e, t) => a.on(e, t),
2580
+ rects: (e, t) => {
2581
+ let n = t.presence;
2582
+ return r && n?.k === "docx" ? r.rects(e, n) : null;
2583
+ },
2584
+ close() {
2585
+ o.forEach((e) => e()), a.close(), e.interceptor &&= void 0, i.dispose?.(), h(e, []);
2586
+ }
2587
+ };
2588
+ }
2589
+ export { re as A, _ as C, y as D, b as E, ne as M, w as O, C as S, T, me as _, st as a, de as b, G as c, F as d, Ce as f, ge as g, j as h, ut as i, u as j, te as k, W as l, P as m, dt as n, $e as o, N as p, ft as r, Qe as s, pt as t, Ye as u, M as v, g as w, ue as x, v as y };
2590
+
2591
+ //# sourceMappingURL=collab-BVynXMqc.js.map