pptx-glimpse 2.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3643 @@
1
+ import {
2
+ collectUsedFonts
3
+ } from "./chunk-ZZKN4U5J.js";
4
+ import {
5
+ DEFAULT_OUTPUT_WIDTH,
6
+ addConnector,
7
+ addEmptySlideFromLayout,
8
+ addTextBox,
9
+ asEmu,
10
+ asPartPath,
11
+ asRelationshipId,
12
+ asSourceNodeId,
13
+ clearTextRunProperties,
14
+ convertPptxToSvg,
15
+ deleteShape,
16
+ deleteSlide,
17
+ duplicateSlide,
18
+ findShapeNodeBySourceHandle,
19
+ readPptx,
20
+ renderPptxSourceModelToSvg,
21
+ replaceImageBytes,
22
+ replaceParagraphPlainText,
23
+ replaceTextRunPlainText,
24
+ setTextRunProperties,
25
+ unsafeBrandAssertion,
26
+ updateShapeTransform,
27
+ writePptx
28
+ } from "./chunk-NMAO44T7.js";
29
+ import {
30
+ DEFAULT_FONT_MAPPING,
31
+ clearFontCache,
32
+ createFontMapping,
33
+ createOpentypeSetupFromBuffers,
34
+ createOpentypeTextMeasurerFromBuffers,
35
+ getMappedFont,
36
+ getWarningEntries,
37
+ getWarningSummary
38
+ } from "./chunk-PGCREQQU.js";
39
+ import {
40
+ renderSvgToPng
41
+ } from "./chunk-QPT6BMN5.js";
42
+
43
+ // ../renderer/src/png/browser-png-converter.ts
44
+ import { initWasm } from "@resvg/resvg-wasm";
45
+ var wasmInitPromise = null;
46
+ async function normalizeWasmInput(wasm) {
47
+ if (wasm instanceof ArrayBuffer || wasm instanceof Uint8Array) {
48
+ return wasm;
49
+ }
50
+ if (!wasm.ok) {
51
+ throw new Error(`Failed to load resvg WASM: HTTP ${wasm.status.toString()}`);
52
+ }
53
+ return wasm.arrayBuffer();
54
+ }
55
+ async function initResvgWasm(wasm) {
56
+ if (!wasmInitPromise) {
57
+ wasmInitPromise = normalizeWasmInput(wasm).then((wasmInput) => initWasm(wasmInput)).catch((error) => {
58
+ wasmInitPromise = null;
59
+ throw error;
60
+ });
61
+ }
62
+ await wasmInitPromise;
63
+ }
64
+ async function svgToPng(svgString, options) {
65
+ if (!wasmInitPromise) {
66
+ throw new Error("initResvgWasm(wasm) must be called before browser PNG conversion.");
67
+ }
68
+ await wasmInitPromise;
69
+ return renderSvgToPng(svgString, options);
70
+ }
71
+
72
+ // ../../node_modules/.pnpm/orderedmap@2.1.1/node_modules/orderedmap/dist/index.js
73
+ function OrderedMap(content) {
74
+ this.content = content;
75
+ }
76
+ OrderedMap.prototype = {
77
+ constructor: OrderedMap,
78
+ find: function(key) {
79
+ for (var i = 0; i < this.content.length; i += 2)
80
+ if (this.content[i] === key) return i;
81
+ return -1;
82
+ },
83
+ // :: (string) → ?any
84
+ // Retrieve the value stored under `key`, or return undefined when
85
+ // no such key exists.
86
+ get: function(key) {
87
+ var found2 = this.find(key);
88
+ return found2 == -1 ? void 0 : this.content[found2 + 1];
89
+ },
90
+ // :: (string, any, ?string) → OrderedMap
91
+ // Create a new map by replacing the value of `key` with a new
92
+ // value, or adding a binding to the end of the map. If `newKey` is
93
+ // given, the key of the binding will be replaced with that key.
94
+ update: function(key, value, newKey) {
95
+ var self = newKey && newKey != key ? this.remove(newKey) : this;
96
+ var found2 = self.find(key), content = self.content.slice();
97
+ if (found2 == -1) {
98
+ content.push(newKey || key, value);
99
+ } else {
100
+ content[found2 + 1] = value;
101
+ if (newKey) content[found2] = newKey;
102
+ }
103
+ return new OrderedMap(content);
104
+ },
105
+ // :: (string) → OrderedMap
106
+ // Return a map with the given key removed, if it existed.
107
+ remove: function(key) {
108
+ var found2 = this.find(key);
109
+ if (found2 == -1) return this;
110
+ var content = this.content.slice();
111
+ content.splice(found2, 2);
112
+ return new OrderedMap(content);
113
+ },
114
+ // :: (string, any) → OrderedMap
115
+ // Add a new key to the start of the map.
116
+ addToStart: function(key, value) {
117
+ return new OrderedMap([key, value].concat(this.remove(key).content));
118
+ },
119
+ // :: (string, any) → OrderedMap
120
+ // Add a new key to the end of the map.
121
+ addToEnd: function(key, value) {
122
+ var content = this.remove(key).content.slice();
123
+ content.push(key, value);
124
+ return new OrderedMap(content);
125
+ },
126
+ // :: (string, string, any) → OrderedMap
127
+ // Add a key after the given key. If `place` is not found, the new
128
+ // key is added to the end.
129
+ addBefore: function(place, key, value) {
130
+ var without = this.remove(key), content = without.content.slice();
131
+ var found2 = without.find(place);
132
+ content.splice(found2 == -1 ? content.length : found2, 0, key, value);
133
+ return new OrderedMap(content);
134
+ },
135
+ // :: ((key: string, value: any))
136
+ // Call the given function for each key/value pair in the map, in
137
+ // order.
138
+ forEach: function(f) {
139
+ for (var i = 0; i < this.content.length; i += 2)
140
+ f(this.content[i], this.content[i + 1]);
141
+ },
142
+ // :: (union<Object, OrderedMap>) → OrderedMap
143
+ // Create a new map by prepending the keys in this map that don't
144
+ // appear in `map` before the keys in `map`.
145
+ prepend: function(map) {
146
+ map = OrderedMap.from(map);
147
+ if (!map.size) return this;
148
+ return new OrderedMap(map.content.concat(this.subtract(map).content));
149
+ },
150
+ // :: (union<Object, OrderedMap>) → OrderedMap
151
+ // Create a new map by appending the keys in this map that don't
152
+ // appear in `map` after the keys in `map`.
153
+ append: function(map) {
154
+ map = OrderedMap.from(map);
155
+ if (!map.size) return this;
156
+ return new OrderedMap(this.subtract(map).content.concat(map.content));
157
+ },
158
+ // :: (union<Object, OrderedMap>) → OrderedMap
159
+ // Create a map containing all the keys in this map that don't
160
+ // appear in `map`.
161
+ subtract: function(map) {
162
+ var result = this;
163
+ map = OrderedMap.from(map);
164
+ for (var i = 0; i < map.content.length; i += 2)
165
+ result = result.remove(map.content[i]);
166
+ return result;
167
+ },
168
+ // :: () → Object
169
+ // Turn ordered map into a plain object.
170
+ toObject: function() {
171
+ var result = {};
172
+ this.forEach(function(key, value) {
173
+ result[key] = value;
174
+ });
175
+ return result;
176
+ },
177
+ // :: number
178
+ // The amount of keys in this map.
179
+ get size() {
180
+ return this.content.length >> 1;
181
+ }
182
+ };
183
+ OrderedMap.from = function(value) {
184
+ if (value instanceof OrderedMap) return value;
185
+ var content = [];
186
+ if (value) for (var prop in value) content.push(prop, value[prop]);
187
+ return new OrderedMap(content);
188
+ };
189
+ var dist_default = OrderedMap;
190
+
191
+ // ../../node_modules/.pnpm/prosemirror-model@1.25.9/node_modules/prosemirror-model/dist/index.js
192
+ function findDiffStart(a, b, pos) {
193
+ for (let i = 0; ; i++) {
194
+ if (i == a.childCount || i == b.childCount)
195
+ return a.childCount == b.childCount ? null : pos;
196
+ let childA = a.child(i), childB = b.child(i);
197
+ if (childA == childB) {
198
+ pos += childA.nodeSize;
199
+ continue;
200
+ }
201
+ if (!childA.sameMarkup(childB))
202
+ return pos;
203
+ if (childA.isText && childA.text != childB.text) {
204
+ let tA = childA.text, tB = childB.text, j = 0;
205
+ for (; tA[j] == tB[j]; j++)
206
+ pos++;
207
+ if (j && j < tA.length && j < tB.length && surrogateHigh(tA.charCodeAt(j - 1)) && surrogateLow(tA.charCodeAt(j)))
208
+ pos--;
209
+ return pos;
210
+ }
211
+ if (childA.content.size || childB.content.size) {
212
+ let inner = findDiffStart(childA.content, childB.content, pos + 1);
213
+ if (inner != null)
214
+ return inner;
215
+ }
216
+ pos += childA.nodeSize;
217
+ }
218
+ }
219
+ function findDiffEnd(a, b, posA, posB) {
220
+ for (let iA = a.childCount, iB = b.childCount; ; ) {
221
+ if (iA == 0 || iB == 0)
222
+ return iA == iB ? null : { a: posA, b: posB };
223
+ let childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize;
224
+ if (childA == childB) {
225
+ posA -= size;
226
+ posB -= size;
227
+ continue;
228
+ }
229
+ if (!childA.sameMarkup(childB))
230
+ return { a: posA, b: posB };
231
+ if (childA.isText && childA.text != childB.text) {
232
+ let tA = childA.text, tB = childB.text, iA2 = tA.length, iB2 = tB.length;
233
+ while (iA2 > 0 && iB2 > 0 && tA[iA2 - 1] == tB[iB2 - 1]) {
234
+ iA2--;
235
+ iB2--;
236
+ posA--;
237
+ posB--;
238
+ }
239
+ if (iA2 && iB2 && iA2 < tA.length && surrogateHigh(tA.charCodeAt(iA2 - 1)) && surrogateLow(tA.charCodeAt(iA2))) {
240
+ posA++;
241
+ posB++;
242
+ }
243
+ return { a: posA, b: posB };
244
+ }
245
+ if (childA.content.size || childB.content.size) {
246
+ let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);
247
+ if (inner)
248
+ return inner;
249
+ }
250
+ posA -= size;
251
+ posB -= size;
252
+ }
253
+ }
254
+ function surrogateLow(ch) {
255
+ return ch >= 56320 && ch < 57344;
256
+ }
257
+ function surrogateHigh(ch) {
258
+ return ch >= 55296 && ch < 56320;
259
+ }
260
+ var Fragment = class _Fragment {
261
+ /**
262
+ @internal
263
+ */
264
+ constructor(content, size) {
265
+ this.content = content;
266
+ this.size = size || 0;
267
+ if (size == null)
268
+ for (let i = 0; i < content.length; i++)
269
+ this.size += content[i].nodeSize;
270
+ }
271
+ /**
272
+ Invoke a callback for all descendant nodes between the given two
273
+ positions (relative to start of this fragment). Doesn't descend
274
+ into a node when the callback returns `false`.
275
+ */
276
+ nodesBetween(from, to, f, nodeStart = 0, parent) {
277
+ for (let i = 0, pos = 0; pos < to; i++) {
278
+ let child = this.content[i], end = pos + child.nodeSize;
279
+ if (end > from && f(child, nodeStart + pos, parent || null, i) !== false && child.content.size) {
280
+ let start = pos + 1;
281
+ child.nodesBetween(Math.max(0, from - start), Math.min(child.content.size, to - start), f, nodeStart + start);
282
+ }
283
+ pos = end;
284
+ }
285
+ }
286
+ /**
287
+ Call the given callback for every descendant node. `pos` will be
288
+ relative to the start of the fragment. The callback may return
289
+ `false` to prevent traversal of a given node's children.
290
+ */
291
+ descendants(f) {
292
+ this.nodesBetween(0, this.size, f);
293
+ }
294
+ /**
295
+ Extract the text between `from` and `to`. See the same method on
296
+ [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween).
297
+ */
298
+ textBetween(from, to, blockSeparator, leafText) {
299
+ let text = "", first = true;
300
+ this.nodesBetween(from, to, (node, pos) => {
301
+ let nodeText = node.isText ? node.text.slice(Math.max(from, pos) - pos, to - pos) : !node.isLeaf ? "" : leafText ? typeof leafText === "function" ? leafText(node) : leafText : node.type.spec.leafText ? node.type.spec.leafText(node) : "";
302
+ if (node.isBlock && (node.isLeaf && nodeText || node.isTextblock) && blockSeparator) {
303
+ if (first)
304
+ first = false;
305
+ else
306
+ text += blockSeparator;
307
+ }
308
+ text += nodeText;
309
+ }, 0);
310
+ return text;
311
+ }
312
+ /**
313
+ Create a new fragment containing the combined content of this
314
+ fragment and the other.
315
+ */
316
+ append(other) {
317
+ if (!other.size)
318
+ return this;
319
+ if (!this.size)
320
+ return other;
321
+ let last = this.lastChild, first = other.firstChild, content = this.content.slice(), i = 0;
322
+ if (last.isText && last.sameMarkup(first)) {
323
+ content[content.length - 1] = last.withText(last.text + first.text);
324
+ i = 1;
325
+ }
326
+ for (; i < other.content.length; i++)
327
+ content.push(other.content[i]);
328
+ return new _Fragment(content, this.size + other.size);
329
+ }
330
+ /**
331
+ Cut out the sub-fragment between the two given positions.
332
+ */
333
+ cut(from, to = this.size) {
334
+ if (from == 0 && to == this.size)
335
+ return this;
336
+ let result = [], size = 0;
337
+ if (to > from)
338
+ for (let i = 0, pos = 0; pos < to; i++) {
339
+ let child = this.content[i], end = pos + child.nodeSize;
340
+ if (end > from) {
341
+ if (pos < from || end > to) {
342
+ if (child.isText)
343
+ child = child.cut(Math.max(0, from - pos), Math.min(child.text.length, to - pos));
344
+ else
345
+ child = child.cut(Math.max(0, from - pos - 1), Math.min(child.content.size, to - pos - 1));
346
+ }
347
+ result.push(child);
348
+ size += child.nodeSize;
349
+ }
350
+ pos = end;
351
+ }
352
+ return new _Fragment(result, size);
353
+ }
354
+ /**
355
+ @internal
356
+ */
357
+ cutByIndex(from, to) {
358
+ if (from == to)
359
+ return _Fragment.empty;
360
+ if (from == 0 && to == this.content.length)
361
+ return this;
362
+ return new _Fragment(this.content.slice(from, to));
363
+ }
364
+ /**
365
+ Create a new fragment in which the node at the given index is
366
+ replaced by the given node.
367
+ */
368
+ replaceChild(index, node) {
369
+ let current = this.content[index];
370
+ if (current == node)
371
+ return this;
372
+ let copy = this.content.slice();
373
+ let size = this.size + node.nodeSize - current.nodeSize;
374
+ copy[index] = node;
375
+ return new _Fragment(copy, size);
376
+ }
377
+ /**
378
+ Create a new fragment by prepending the given node to this
379
+ fragment.
380
+ */
381
+ addToStart(node) {
382
+ return new _Fragment([node].concat(this.content), this.size + node.nodeSize);
383
+ }
384
+ /**
385
+ Create a new fragment by appending the given node to this
386
+ fragment.
387
+ */
388
+ addToEnd(node) {
389
+ return new _Fragment(this.content.concat(node), this.size + node.nodeSize);
390
+ }
391
+ /**
392
+ Compare this fragment to another one.
393
+ */
394
+ eq(other) {
395
+ if (this.content.length != other.content.length)
396
+ return false;
397
+ for (let i = 0; i < this.content.length; i++)
398
+ if (!this.content[i].eq(other.content[i]))
399
+ return false;
400
+ return true;
401
+ }
402
+ /**
403
+ The first child of the fragment, or `null` if it is empty.
404
+ */
405
+ get firstChild() {
406
+ return this.content.length ? this.content[0] : null;
407
+ }
408
+ /**
409
+ The last child of the fragment, or `null` if it is empty.
410
+ */
411
+ get lastChild() {
412
+ return this.content.length ? this.content[this.content.length - 1] : null;
413
+ }
414
+ /**
415
+ The number of child nodes in this fragment.
416
+ */
417
+ get childCount() {
418
+ return this.content.length;
419
+ }
420
+ /**
421
+ Get the child node at the given index. Raise an error when the
422
+ index is out of range.
423
+ */
424
+ child(index) {
425
+ let found2 = this.content[index];
426
+ if (!found2)
427
+ throw new RangeError("Index " + index + " out of range for " + this);
428
+ return found2;
429
+ }
430
+ /**
431
+ Get the child node at the given index, if it exists.
432
+ */
433
+ maybeChild(index) {
434
+ return this.content[index] || null;
435
+ }
436
+ /**
437
+ Call `f` for every child node, passing the node, its offset
438
+ into this parent node, and its index.
439
+ */
440
+ forEach(f) {
441
+ for (let i = 0, p = 0; i < this.content.length; i++) {
442
+ let child = this.content[i];
443
+ f(child, p, i);
444
+ p += child.nodeSize;
445
+ }
446
+ }
447
+ /**
448
+ Find the first position at which this fragment and another
449
+ fragment differ, or `null` if they are the same.
450
+ */
451
+ findDiffStart(other, pos = 0) {
452
+ return findDiffStart(this, other, pos);
453
+ }
454
+ /**
455
+ Find the first position, searching from the end, at which this
456
+ fragment and the given fragment differ, or `null` if they are
457
+ the same. Since this position will not be the same in both
458
+ nodes, an object with two separate positions is returned.
459
+ */
460
+ findDiffEnd(other, pos = this.size, otherPos = other.size) {
461
+ return findDiffEnd(this, other, pos, otherPos);
462
+ }
463
+ /**
464
+ Find the index and inner offset corresponding to a given relative
465
+ position in this fragment. The result object will be reused
466
+ (overwritten) the next time the function is called. @internal
467
+ */
468
+ findIndex(pos) {
469
+ if (pos == 0)
470
+ return retIndex(0, pos);
471
+ if (pos == this.size)
472
+ return retIndex(this.content.length, pos);
473
+ if (pos > this.size || pos < 0)
474
+ throw new RangeError(`Position ${pos} outside of fragment (${this})`);
475
+ for (let i = 0, curPos = 0; ; i++) {
476
+ let cur = this.child(i), end = curPos + cur.nodeSize;
477
+ if (end >= pos) {
478
+ if (end == pos)
479
+ return retIndex(i + 1, end);
480
+ return retIndex(i, curPos);
481
+ }
482
+ curPos = end;
483
+ }
484
+ }
485
+ /**
486
+ Return a debugging string that describes this fragment.
487
+ */
488
+ toString() {
489
+ return "<" + this.toStringInner() + ">";
490
+ }
491
+ /**
492
+ @internal
493
+ */
494
+ toStringInner() {
495
+ return this.content.join(", ");
496
+ }
497
+ /**
498
+ Create a JSON-serializeable representation of this fragment.
499
+ */
500
+ toJSON() {
501
+ return this.content.length ? this.content.map((n) => n.toJSON()) : null;
502
+ }
503
+ /**
504
+ Deserialize a fragment from its JSON representation.
505
+ */
506
+ static fromJSON(schema, value) {
507
+ if (!value)
508
+ return _Fragment.empty;
509
+ if (!Array.isArray(value))
510
+ throw new RangeError("Invalid input for Fragment.fromJSON");
511
+ return _Fragment.fromArray(value.map(schema.nodeFromJSON));
512
+ }
513
+ /**
514
+ Build a fragment from an array of nodes. Ensures that adjacent
515
+ text nodes with the same marks are joined together.
516
+ */
517
+ static fromArray(array) {
518
+ if (!array.length)
519
+ return _Fragment.empty;
520
+ let joined, size = 0;
521
+ for (let i = 0; i < array.length; i++) {
522
+ let node = array[i];
523
+ size += node.nodeSize;
524
+ if (i && node.isText && array[i - 1].sameMarkup(node)) {
525
+ if (!joined)
526
+ joined = array.slice(0, i);
527
+ joined[joined.length - 1] = node.withText(joined[joined.length - 1].text + node.text);
528
+ } else if (joined) {
529
+ joined.push(node);
530
+ }
531
+ }
532
+ return new _Fragment(joined || array, size);
533
+ }
534
+ /**
535
+ Create a fragment from something that can be interpreted as a
536
+ set of nodes. For `null`, it returns the empty fragment. For a
537
+ fragment, the fragment itself. For a node or array of nodes, a
538
+ fragment containing those nodes.
539
+ */
540
+ static from(nodes) {
541
+ if (!nodes)
542
+ return _Fragment.empty;
543
+ if (nodes instanceof _Fragment)
544
+ return nodes;
545
+ if (Array.isArray(nodes))
546
+ return this.fromArray(nodes);
547
+ if (nodes.attrs)
548
+ return new _Fragment([nodes], nodes.nodeSize);
549
+ throw new RangeError("Can not convert " + nodes + " to a Fragment" + (nodes.nodesBetween ? " (looks like multiple versions of prosemirror-model were loaded)" : ""));
550
+ }
551
+ };
552
+ Fragment.empty = new Fragment([], 0);
553
+ var found = { index: 0, offset: 0 };
554
+ function retIndex(index, offset) {
555
+ found.index = index;
556
+ found.offset = offset;
557
+ return found;
558
+ }
559
+ function compareDeep(a, b) {
560
+ if (a === b)
561
+ return true;
562
+ if (!(a && typeof a == "object") || !(b && typeof b == "object"))
563
+ return false;
564
+ let array = Array.isArray(a);
565
+ if (Array.isArray(b) != array)
566
+ return false;
567
+ if (array) {
568
+ if (a.length != b.length)
569
+ return false;
570
+ for (let i = 0; i < a.length; i++)
571
+ if (!compareDeep(a[i], b[i]))
572
+ return false;
573
+ } else {
574
+ for (let p in a)
575
+ if (!(p in b) || !compareDeep(a[p], b[p]))
576
+ return false;
577
+ for (let p in b)
578
+ if (!(p in a))
579
+ return false;
580
+ }
581
+ return true;
582
+ }
583
+ var Mark = class _Mark {
584
+ /**
585
+ @internal
586
+ */
587
+ constructor(type, attrs) {
588
+ this.type = type;
589
+ this.attrs = attrs;
590
+ }
591
+ /**
592
+ Given a set of marks, create a new set which contains this one as
593
+ well, in the right position. If this mark is already in the set,
594
+ the set itself is returned. If any marks that are set to be
595
+ [exclusive](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present,
596
+ those are replaced by this one.
597
+ */
598
+ addToSet(set) {
599
+ let copy, placed = false;
600
+ for (let i = 0; i < set.length; i++) {
601
+ let other = set[i];
602
+ if (this.eq(other))
603
+ return set;
604
+ if (this.type.excludes(other.type)) {
605
+ if (!copy)
606
+ copy = set.slice(0, i);
607
+ } else if (other.type.excludes(this.type)) {
608
+ return set;
609
+ } else {
610
+ if (!placed && other.type.rank > this.type.rank) {
611
+ if (!copy)
612
+ copy = set.slice(0, i);
613
+ copy.push(this);
614
+ placed = true;
615
+ }
616
+ if (copy)
617
+ copy.push(other);
618
+ }
619
+ }
620
+ if (!copy)
621
+ copy = set.slice();
622
+ if (!placed)
623
+ copy.push(this);
624
+ return copy;
625
+ }
626
+ /**
627
+ Remove this mark from the given set, returning a new set. If this
628
+ mark is not in the set, the set itself is returned.
629
+ */
630
+ removeFromSet(set) {
631
+ for (let i = 0; i < set.length; i++)
632
+ if (this.eq(set[i]))
633
+ return set.slice(0, i).concat(set.slice(i + 1));
634
+ return set;
635
+ }
636
+ /**
637
+ Test whether this mark is in the given set of marks.
638
+ */
639
+ isInSet(set) {
640
+ for (let i = 0; i < set.length; i++)
641
+ if (this.eq(set[i]))
642
+ return true;
643
+ return false;
644
+ }
645
+ /**
646
+ Test whether this mark has the same type and attributes as
647
+ another mark.
648
+ */
649
+ eq(other) {
650
+ return this == other || this.type == other.type && compareDeep(this.attrs, other.attrs);
651
+ }
652
+ /**
653
+ Convert this mark to a JSON-serializeable representation.
654
+ */
655
+ toJSON() {
656
+ let obj = { type: this.type.name };
657
+ for (let _ in this.attrs) {
658
+ obj.attrs = this.attrs;
659
+ break;
660
+ }
661
+ return obj;
662
+ }
663
+ /**
664
+ Deserialize a mark from JSON.
665
+ */
666
+ static fromJSON(schema, json) {
667
+ if (!json)
668
+ throw new RangeError("Invalid input for Mark.fromJSON");
669
+ let type = schema.marks[json.type];
670
+ if (!type)
671
+ throw new RangeError(`There is no mark type ${json.type} in this schema`);
672
+ let mark = type.create(json.attrs);
673
+ type.checkAttrs(mark.attrs);
674
+ return mark;
675
+ }
676
+ /**
677
+ Test whether two sets of marks are identical.
678
+ */
679
+ static sameSet(a, b) {
680
+ if (a == b)
681
+ return true;
682
+ if (a.length != b.length)
683
+ return false;
684
+ for (let i = 0; i < a.length; i++)
685
+ if (!a[i].eq(b[i]))
686
+ return false;
687
+ return true;
688
+ }
689
+ /**
690
+ Create a properly sorted mark set from null, a single mark, or an
691
+ unsorted array of marks.
692
+ */
693
+ static setFrom(marks) {
694
+ if (!marks || Array.isArray(marks) && marks.length == 0)
695
+ return _Mark.none;
696
+ if (marks instanceof _Mark)
697
+ return [marks];
698
+ let copy = marks.slice();
699
+ copy.sort((a, b) => a.type.rank - b.type.rank);
700
+ return copy;
701
+ }
702
+ };
703
+ Mark.none = [];
704
+ var ReplaceError = class extends Error {
705
+ };
706
+ var Slice = class _Slice {
707
+ /**
708
+ Create a slice. When specifying a non-zero open depth, you must
709
+ make sure that there are nodes of at least that depth at the
710
+ appropriate side of the fragment—i.e. if the fragment is an
711
+ empty paragraph node, `openStart` and `openEnd` can't be greater
712
+ than 1.
713
+
714
+ It is not necessary for the content of open nodes to conform to
715
+ the schema's content constraints, though it should be a valid
716
+ start/end/middle for such a node, depending on which sides are
717
+ open.
718
+ */
719
+ constructor(content, openStart, openEnd) {
720
+ this.content = content;
721
+ this.openStart = openStart;
722
+ this.openEnd = openEnd;
723
+ }
724
+ /**
725
+ The size this slice would add when inserted into a document.
726
+ */
727
+ get size() {
728
+ return this.content.size - this.openStart - this.openEnd;
729
+ }
730
+ /**
731
+ @internal
732
+ */
733
+ insertAt(pos, fragment) {
734
+ let content = insertInto(this.content, pos + this.openStart, fragment, this.openStart + 1, this.openEnd + 1);
735
+ return content && new _Slice(content, this.openStart, this.openEnd);
736
+ }
737
+ /**
738
+ @internal
739
+ */
740
+ removeBetween(from, to) {
741
+ return new _Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd);
742
+ }
743
+ /**
744
+ Tests whether this slice is equal to another slice.
745
+ */
746
+ eq(other) {
747
+ return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd;
748
+ }
749
+ /**
750
+ @internal
751
+ */
752
+ toString() {
753
+ return this.content + "(" + this.openStart + "," + this.openEnd + ")";
754
+ }
755
+ /**
756
+ Convert a slice to a JSON-serializable representation.
757
+ */
758
+ toJSON() {
759
+ if (!this.content.size)
760
+ return null;
761
+ let json = { content: this.content.toJSON() };
762
+ if (this.openStart > 0)
763
+ json.openStart = this.openStart;
764
+ if (this.openEnd > 0)
765
+ json.openEnd = this.openEnd;
766
+ return json;
767
+ }
768
+ /**
769
+ Deserialize a slice from its JSON representation.
770
+ */
771
+ static fromJSON(schema, json) {
772
+ if (!json)
773
+ return _Slice.empty;
774
+ let openStart = json.openStart || 0, openEnd = json.openEnd || 0;
775
+ if (typeof openStart != "number" || typeof openEnd != "number")
776
+ throw new RangeError("Invalid input for Slice.fromJSON");
777
+ return new _Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd);
778
+ }
779
+ /**
780
+ Create a slice from a fragment by taking the maximum possible
781
+ open value on both side of the fragment.
782
+ */
783
+ static maxOpen(fragment, openIsolating = true) {
784
+ let openStart = 0, openEnd = 0;
785
+ for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild)
786
+ openStart++;
787
+ for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild)
788
+ openEnd++;
789
+ return new _Slice(fragment, openStart, openEnd);
790
+ }
791
+ };
792
+ Slice.empty = new Slice(Fragment.empty, 0, 0);
793
+ function removeRange(content, from, to) {
794
+ let { index, offset } = content.findIndex(from), child = content.maybeChild(index);
795
+ let { index: indexTo, offset: offsetTo } = content.findIndex(to);
796
+ if (offset == from || child.isText) {
797
+ if (offsetTo != to && !content.child(indexTo).isText)
798
+ throw new RangeError("Removing non-flat range");
799
+ return content.cut(0, from).append(content.cut(to));
800
+ }
801
+ if (index != indexTo)
802
+ throw new RangeError("Removing non-flat range");
803
+ return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1)));
804
+ }
805
+ function insertInto(content, dist, insert, openStart, openEnd, parent) {
806
+ let { index, offset } = content.findIndex(dist), child = content.maybeChild(index);
807
+ if (offset == dist || child.isText) {
808
+ if (parent && openStart <= 0 && openEnd <= 0 && !parent.canReplace(index, index, insert))
809
+ return null;
810
+ return content.cut(0, dist).append(insert).append(content.cut(dist));
811
+ }
812
+ let inner = insertInto(child.content, dist - offset - 1, insert, index == 0 ? openStart - 1 : 0, index == content.childCount - 1 ? openEnd - 1 : 0, child);
813
+ return inner && content.replaceChild(index, child.copy(inner));
814
+ }
815
+ function replace($from, $to, slice) {
816
+ if (slice.openStart > $from.depth)
817
+ throw new ReplaceError("Inserted content deeper than insertion position");
818
+ if ($from.depth - slice.openStart != $to.depth - slice.openEnd)
819
+ throw new ReplaceError("Inconsistent open depths");
820
+ return replaceOuter($from, $to, slice, 0);
821
+ }
822
+ function replaceOuter($from, $to, slice, depth) {
823
+ let index = $from.index(depth), node = $from.node(depth);
824
+ if (index == $to.index(depth) && depth < $from.depth - slice.openStart) {
825
+ let inner = replaceOuter($from, $to, slice, depth + 1);
826
+ return node.copy(node.content.replaceChild(index, inner));
827
+ } else if (!slice.content.size) {
828
+ return close(node, replaceTwoWay($from, $to, depth));
829
+ } else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) {
830
+ let parent = $from.parent, content = parent.content;
831
+ return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset)));
832
+ } else {
833
+ let { start, end } = prepareSliceForReplace(slice, $from);
834
+ return close(node, replaceThreeWay($from, start, end, $to, depth));
835
+ }
836
+ }
837
+ function checkJoin(main, sub) {
838
+ if (!sub.type.compatibleContent(main.type))
839
+ throw new ReplaceError("Cannot join " + sub.type.name + " onto " + main.type.name);
840
+ }
841
+ function joinable($before, $after, depth) {
842
+ let node = $before.node(depth);
843
+ checkJoin(node, $after.node(depth));
844
+ return node;
845
+ }
846
+ function addNode(child, target) {
847
+ let last = target.length - 1;
848
+ if (last >= 0 && child.isText && child.sameMarkup(target[last]))
849
+ target[last] = child.withText(target[last].text + child.text);
850
+ else
851
+ target.push(child);
852
+ }
853
+ function addRange($start, $end, depth, target) {
854
+ let node = ($end || $start).node(depth);
855
+ let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount;
856
+ if ($start) {
857
+ startIndex = $start.index(depth);
858
+ if ($start.depth > depth) {
859
+ startIndex++;
860
+ } else if ($start.textOffset) {
861
+ addNode($start.nodeAfter, target);
862
+ startIndex++;
863
+ }
864
+ }
865
+ for (let i = startIndex; i < endIndex; i++)
866
+ addNode(node.child(i), target);
867
+ if ($end && $end.depth == depth && $end.textOffset)
868
+ addNode($end.nodeBefore, target);
869
+ }
870
+ function close(node, content) {
871
+ if (!node.type.validContent(content))
872
+ throw new ReplaceError("Invalid content for node " + node.type.name);
873
+ return node.copy(content);
874
+ }
875
+ function replaceThreeWay($from, $start, $end, $to, depth) {
876
+ let openStart = $from.depth > depth && joinable($from, $start, depth + 1);
877
+ let openEnd = $to.depth > depth && joinable($end, $to, depth + 1);
878
+ let content = [];
879
+ addRange(null, $from, depth, content);
880
+ if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {
881
+ checkJoin(openStart, openEnd);
882
+ addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content);
883
+ } else {
884
+ if (openStart)
885
+ addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content);
886
+ addRange($start, $end, depth, content);
887
+ if (openEnd)
888
+ addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content);
889
+ }
890
+ addRange($to, null, depth, content);
891
+ return new Fragment(content);
892
+ }
893
+ function replaceTwoWay($from, $to, depth) {
894
+ let content = [];
895
+ addRange(null, $from, depth, content);
896
+ if ($from.depth > depth) {
897
+ let type = joinable($from, $to, depth + 1);
898
+ addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content);
899
+ }
900
+ addRange($to, null, depth, content);
901
+ return new Fragment(content);
902
+ }
903
+ function prepareSliceForReplace(slice, $along) {
904
+ let extra = $along.depth - slice.openStart, parent = $along.node(extra);
905
+ let node = parent.copy(slice.content);
906
+ for (let i = extra - 1; i >= 0; i--)
907
+ node = $along.node(i).copy(Fragment.from(node));
908
+ return {
909
+ start: node.resolveNoCache(slice.openStart + extra),
910
+ end: node.resolveNoCache(node.content.size - slice.openEnd - extra)
911
+ };
912
+ }
913
+ var ResolvedPos = class _ResolvedPos {
914
+ /**
915
+ @internal
916
+ */
917
+ constructor(pos, path, parentOffset) {
918
+ this.pos = pos;
919
+ this.path = path;
920
+ this.parentOffset = parentOffset;
921
+ this.depth = path.length / 3 - 1;
922
+ }
923
+ /**
924
+ @internal
925
+ */
926
+ resolveDepth(val) {
927
+ if (val == null)
928
+ return this.depth;
929
+ if (val < 0)
930
+ return this.depth + val;
931
+ return val;
932
+ }
933
+ /**
934
+ The parent node that the position points into. Note that even if
935
+ a position points into a text node, that node is not considered
936
+ the parent—text nodes are ‘flat’ in this model, and have no content.
937
+ */
938
+ get parent() {
939
+ return this.node(this.depth);
940
+ }
941
+ /**
942
+ The root node in which the position was resolved.
943
+ */
944
+ get doc() {
945
+ return this.node(0);
946
+ }
947
+ /**
948
+ The ancestor node at the given level. `p.node(p.depth)` is the
949
+ same as `p.parent`.
950
+ */
951
+ node(depth) {
952
+ return this.path[this.resolveDepth(depth) * 3];
953
+ }
954
+ /**
955
+ The index into the ancestor at the given level. If this points
956
+ at the 3rd node in the 2nd paragraph on the top level, for
957
+ example, `p.index(0)` is 1 and `p.index(1)` is 2.
958
+ */
959
+ index(depth) {
960
+ return this.path[this.resolveDepth(depth) * 3 + 1];
961
+ }
962
+ /**
963
+ The index pointing after this position into the ancestor at the
964
+ given level.
965
+ */
966
+ indexAfter(depth) {
967
+ depth = this.resolveDepth(depth);
968
+ return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1);
969
+ }
970
+ /**
971
+ The (absolute) position at the start of the node at the given
972
+ level.
973
+ */
974
+ start(depth) {
975
+ depth = this.resolveDepth(depth);
976
+ return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;
977
+ }
978
+ /**
979
+ The (absolute) position at the end of the node at the given
980
+ level.
981
+ */
982
+ end(depth) {
983
+ depth = this.resolveDepth(depth);
984
+ return this.start(depth) + this.node(depth).content.size;
985
+ }
986
+ /**
987
+ The (absolute) position directly before the wrapping node at the
988
+ given level, or, when `depth` is `this.depth + 1`, the original
989
+ position.
990
+ */
991
+ before(depth) {
992
+ depth = this.resolveDepth(depth);
993
+ if (!depth)
994
+ throw new RangeError("There is no position before the top-level node");
995
+ return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1];
996
+ }
997
+ /**
998
+ The (absolute) position directly after the wrapping node at the
999
+ given level, or the original position when `depth` is `this.depth + 1`.
1000
+ */
1001
+ after(depth) {
1002
+ depth = this.resolveDepth(depth);
1003
+ if (!depth)
1004
+ throw new RangeError("There is no position after the top-level node");
1005
+ return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize;
1006
+ }
1007
+ /**
1008
+ When this position points into a text node, this returns the
1009
+ distance between the position and the start of the text node.
1010
+ Will be zero for positions that point between nodes.
1011
+ */
1012
+ get textOffset() {
1013
+ return this.pos - this.path[this.path.length - 1];
1014
+ }
1015
+ /**
1016
+ Get the node directly after the position, if any. If the position
1017
+ points into a text node, only the part of that node after the
1018
+ position is returned.
1019
+ */
1020
+ get nodeAfter() {
1021
+ let parent = this.parent, index = this.index(this.depth);
1022
+ if (index == parent.childCount)
1023
+ return null;
1024
+ let dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index);
1025
+ return dOff ? parent.child(index).cut(dOff) : child;
1026
+ }
1027
+ /**
1028
+ Get the node directly before the position, if any. If the
1029
+ position points into a text node, only the part of that node
1030
+ before the position is returned.
1031
+ */
1032
+ get nodeBefore() {
1033
+ let index = this.index(this.depth);
1034
+ let dOff = this.pos - this.path[this.path.length - 1];
1035
+ if (dOff)
1036
+ return this.parent.child(index).cut(0, dOff);
1037
+ return index == 0 ? null : this.parent.child(index - 1);
1038
+ }
1039
+ /**
1040
+ Get the position at the given index in the parent node at the
1041
+ given depth (which defaults to `this.depth`).
1042
+ */
1043
+ posAtIndex(index, depth) {
1044
+ depth = this.resolveDepth(depth);
1045
+ let node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;
1046
+ for (let i = 0; i < index; i++)
1047
+ pos += node.child(i).nodeSize;
1048
+ return pos;
1049
+ }
1050
+ /**
1051
+ Get the marks at this position, factoring in the surrounding
1052
+ marks' [`inclusive`](https://prosemirror.net/docs/ref/#model.MarkSpec.inclusive) property. If the
1053
+ position is at the start of a non-empty node, the marks of the
1054
+ node after it (if any) are returned.
1055
+ */
1056
+ marks() {
1057
+ let parent = this.parent, index = this.index();
1058
+ if (parent.content.size == 0)
1059
+ return Mark.none;
1060
+ if (this.textOffset)
1061
+ return parent.child(index).marks;
1062
+ let main = parent.maybeChild(index - 1), other = parent.maybeChild(index);
1063
+ if (!main) {
1064
+ let tmp = main;
1065
+ main = other;
1066
+ other = tmp;
1067
+ }
1068
+ let marks = main.marks;
1069
+ for (var i = 0; i < marks.length; i++)
1070
+ if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks)))
1071
+ marks = marks[i--].removeFromSet(marks);
1072
+ return marks;
1073
+ }
1074
+ /**
1075
+ Get the marks after the current position, if any, except those
1076
+ that are non-inclusive and not present at position `$end`. This
1077
+ is mostly useful for getting the set of marks to preserve after a
1078
+ deletion. Will return `null` if this position is at the end of
1079
+ its parent node or its parent node isn't a textblock (in which
1080
+ case no marks should be preserved).
1081
+ */
1082
+ marksAcross($end) {
1083
+ let after = this.parent.maybeChild(this.index());
1084
+ if (!after || !after.isInline)
1085
+ return null;
1086
+ let marks = after.marks, next = $end.parent.maybeChild($end.index());
1087
+ for (var i = 0; i < marks.length; i++)
1088
+ if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks)))
1089
+ marks = marks[i--].removeFromSet(marks);
1090
+ return marks;
1091
+ }
1092
+ /**
1093
+ The depth up to which this position and the given (non-resolved)
1094
+ position share the same parent nodes.
1095
+ */
1096
+ sharedDepth(pos) {
1097
+ for (let depth = this.depth; depth > 0; depth--)
1098
+ if (this.start(depth) <= pos && this.end(depth) >= pos)
1099
+ return depth;
1100
+ return 0;
1101
+ }
1102
+ /**
1103
+ Returns a range based on the place where this position and the
1104
+ given position diverge around block content. If both point into
1105
+ the same textblock, for example, a range around that textblock
1106
+ will be returned. If they point into different blocks, the range
1107
+ around those blocks in their shared ancestor is returned. You can
1108
+ pass in an optional predicate that will be called with a parent
1109
+ node to see if a range into that parent is acceptable.
1110
+ */
1111
+ blockRange(other = this, pred) {
1112
+ if (other.pos < this.pos)
1113
+ return other.blockRange(this);
1114
+ for (let d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--)
1115
+ if (other.pos <= this.end(d) && (!pred || pred(this.node(d))))
1116
+ return new NodeRange(this, other, d);
1117
+ return null;
1118
+ }
1119
+ /**
1120
+ Query whether the given position shares the same parent node.
1121
+ */
1122
+ sameParent(other) {
1123
+ return this.pos - this.parentOffset == other.pos - other.parentOffset;
1124
+ }
1125
+ /**
1126
+ Return the greater of this and the given position.
1127
+ */
1128
+ max(other) {
1129
+ return other.pos > this.pos ? other : this;
1130
+ }
1131
+ /**
1132
+ Return the smaller of this and the given position.
1133
+ */
1134
+ min(other) {
1135
+ return other.pos < this.pos ? other : this;
1136
+ }
1137
+ /**
1138
+ @internal
1139
+ */
1140
+ toString() {
1141
+ let str = "";
1142
+ for (let i = 1; i <= this.depth; i++)
1143
+ str += (str ? "/" : "") + this.node(i).type.name + "_" + this.index(i - 1);
1144
+ return str + ":" + this.parentOffset;
1145
+ }
1146
+ /**
1147
+ @internal
1148
+ */
1149
+ static resolve(doc, pos) {
1150
+ if (!(pos >= 0 && pos <= doc.content.size))
1151
+ throw new RangeError("Position " + pos + " out of range");
1152
+ let path = [];
1153
+ let start = 0, parentOffset = pos;
1154
+ for (let node = doc; ; ) {
1155
+ let { index, offset } = node.content.findIndex(parentOffset);
1156
+ let rem = parentOffset - offset;
1157
+ path.push(node, index, start + offset);
1158
+ if (!rem)
1159
+ break;
1160
+ node = node.child(index);
1161
+ if (node.isText)
1162
+ break;
1163
+ parentOffset = rem - 1;
1164
+ start += offset + 1;
1165
+ }
1166
+ return new _ResolvedPos(pos, path, parentOffset);
1167
+ }
1168
+ /**
1169
+ @internal
1170
+ */
1171
+ static resolveCached(doc, pos) {
1172
+ let cache = resolveCache.get(doc);
1173
+ if (cache) {
1174
+ for (let i = 0; i < cache.elts.length; i++) {
1175
+ let elt = cache.elts[i];
1176
+ if (elt.pos == pos)
1177
+ return elt;
1178
+ }
1179
+ } else {
1180
+ resolveCache.set(doc, cache = new ResolveCache());
1181
+ }
1182
+ let result = cache.elts[cache.i] = _ResolvedPos.resolve(doc, pos);
1183
+ cache.i = (cache.i + 1) % resolveCacheSize;
1184
+ return result;
1185
+ }
1186
+ };
1187
+ var ResolveCache = class {
1188
+ constructor() {
1189
+ this.elts = [];
1190
+ this.i = 0;
1191
+ }
1192
+ };
1193
+ var resolveCacheSize = 12;
1194
+ var resolveCache = /* @__PURE__ */ new WeakMap();
1195
+ var NodeRange = class {
1196
+ /**
1197
+ Construct a node range. `$from` and `$to` should point into the
1198
+ same node until at least the given `depth`, since a node range
1199
+ denotes an adjacent set of nodes in a single parent node.
1200
+ */
1201
+ constructor($from, $to, depth) {
1202
+ this.$from = $from;
1203
+ this.$to = $to;
1204
+ this.depth = depth;
1205
+ }
1206
+ /**
1207
+ The position at the start of the range.
1208
+ */
1209
+ get start() {
1210
+ return this.$from.before(this.depth + 1);
1211
+ }
1212
+ /**
1213
+ The position at the end of the range.
1214
+ */
1215
+ get end() {
1216
+ return this.$to.after(this.depth + 1);
1217
+ }
1218
+ /**
1219
+ The parent node that the range points into.
1220
+ */
1221
+ get parent() {
1222
+ return this.$from.node(this.depth);
1223
+ }
1224
+ /**
1225
+ The start index of the range in the parent node.
1226
+ */
1227
+ get startIndex() {
1228
+ return this.$from.index(this.depth);
1229
+ }
1230
+ /**
1231
+ The end index of the range in the parent node.
1232
+ */
1233
+ get endIndex() {
1234
+ return this.$to.indexAfter(this.depth);
1235
+ }
1236
+ };
1237
+ var emptyAttrs = /* @__PURE__ */ Object.create(null);
1238
+ var Node = class _Node {
1239
+ /**
1240
+ @internal
1241
+ */
1242
+ constructor(type, attrs, content, marks = Mark.none) {
1243
+ this.type = type;
1244
+ this.attrs = attrs;
1245
+ this.marks = marks;
1246
+ this.content = content || Fragment.empty;
1247
+ }
1248
+ /**
1249
+ The array of this node's child nodes.
1250
+ */
1251
+ get children() {
1252
+ return this.content.content;
1253
+ }
1254
+ /**
1255
+ The size of this node, as defined by the integer-based [indexing
1256
+ scheme](https://prosemirror.net/docs/guide/#doc.indexing). For text nodes, this is the
1257
+ amount of characters. For other leaf nodes, it is one. For
1258
+ non-leaf nodes, it is the size of the content plus two (the
1259
+ start and end token).
1260
+ */
1261
+ get nodeSize() {
1262
+ return this.isLeaf ? 1 : 2 + this.content.size;
1263
+ }
1264
+ /**
1265
+ The number of children that the node has.
1266
+ */
1267
+ get childCount() {
1268
+ return this.content.childCount;
1269
+ }
1270
+ /**
1271
+ Get the child node at the given index. Raises an error when the
1272
+ index is out of range.
1273
+ */
1274
+ child(index) {
1275
+ return this.content.child(index);
1276
+ }
1277
+ /**
1278
+ Get the child node at the given index, if it exists.
1279
+ */
1280
+ maybeChild(index) {
1281
+ return this.content.maybeChild(index);
1282
+ }
1283
+ /**
1284
+ Call `f` for every child node, passing the node, its offset
1285
+ into this parent node, and its index.
1286
+ */
1287
+ forEach(f) {
1288
+ this.content.forEach(f);
1289
+ }
1290
+ /**
1291
+ Invoke a callback for all descendant nodes recursively overlapping
1292
+ the given two positions that are relative to start of this
1293
+ node's content. This includes all ancestors of the nodes
1294
+ containing the two positions. The callback is invoked with the
1295
+ node, its position relative to the original node (method receiver),
1296
+ its parent node, and its child index. When the callback returns
1297
+ false for a given node, that node's children will not be
1298
+ recursed over. The last parameter can be used to specify a
1299
+ starting position to count from.
1300
+ */
1301
+ nodesBetween(from, to, f, startPos = 0) {
1302
+ this.content.nodesBetween(from, to, f, startPos, this);
1303
+ }
1304
+ /**
1305
+ Call the given callback for every descendant node. Doesn't
1306
+ descend into a node when the callback returns `false`.
1307
+ */
1308
+ descendants(f) {
1309
+ this.nodesBetween(0, this.content.size, f);
1310
+ }
1311
+ /**
1312
+ Concatenates all the text nodes found in this fragment and its
1313
+ children.
1314
+ */
1315
+ get textContent() {
1316
+ return this.isLeaf && this.type.spec.leafText ? this.type.spec.leafText(this) : this.textBetween(0, this.content.size, "");
1317
+ }
1318
+ /**
1319
+ Get all text between positions `from` and `to`. When
1320
+ `blockSeparator` is given, it will be inserted to separate text
1321
+ from different block nodes. If `leafText` is given, it'll be
1322
+ inserted for every non-text leaf node encountered, otherwise
1323
+ [`leafText`](https://prosemirror.net/docs/ref/#model.NodeSpec.leafText) will be used.
1324
+ */
1325
+ textBetween(from, to, blockSeparator, leafText) {
1326
+ return this.content.textBetween(from, to, blockSeparator, leafText);
1327
+ }
1328
+ /**
1329
+ Returns this node's first child, or `null` if there are no
1330
+ children.
1331
+ */
1332
+ get firstChild() {
1333
+ return this.content.firstChild;
1334
+ }
1335
+ /**
1336
+ Returns this node's last child, or `null` if there are no
1337
+ children.
1338
+ */
1339
+ get lastChild() {
1340
+ return this.content.lastChild;
1341
+ }
1342
+ /**
1343
+ Test whether two nodes represent the same piece of document.
1344
+ */
1345
+ eq(other) {
1346
+ return this == other || this.sameMarkup(other) && this.content.eq(other.content);
1347
+ }
1348
+ /**
1349
+ Compare the markup (type, attributes, and marks) of this node to
1350
+ those of another. Returns `true` if both have the same markup.
1351
+ */
1352
+ sameMarkup(other) {
1353
+ return this.hasMarkup(other.type, other.attrs, other.marks);
1354
+ }
1355
+ /**
1356
+ Check whether this node's markup correspond to the given type,
1357
+ attributes, and marks.
1358
+ */
1359
+ hasMarkup(type, attrs, marks) {
1360
+ return this.type == type && compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) && Mark.sameSet(this.marks, marks || Mark.none);
1361
+ }
1362
+ /**
1363
+ Create a new node with the same markup as this node, containing
1364
+ the given content (or empty, if no content is given).
1365
+ */
1366
+ copy(content = null) {
1367
+ if (content == this.content)
1368
+ return this;
1369
+ return new _Node(this.type, this.attrs, content, this.marks);
1370
+ }
1371
+ /**
1372
+ Create a copy of this node, with the given set of marks instead
1373
+ of the node's own marks.
1374
+ */
1375
+ mark(marks) {
1376
+ return marks == this.marks ? this : new _Node(this.type, this.attrs, this.content, marks);
1377
+ }
1378
+ /**
1379
+ Create a copy of this node with only the content between the
1380
+ given positions. If `to` is not given, it defaults to the end of
1381
+ the node.
1382
+ */
1383
+ cut(from, to = this.content.size) {
1384
+ if (from == 0 && to == this.content.size)
1385
+ return this;
1386
+ return this.copy(this.content.cut(from, to));
1387
+ }
1388
+ /**
1389
+ Cut out the part of the document between the given positions, and
1390
+ return it as a `Slice` object.
1391
+ */
1392
+ slice(from, to = this.content.size, includeParents = false) {
1393
+ if (from == to)
1394
+ return Slice.empty;
1395
+ let $from = this.resolve(from), $to = this.resolve(to);
1396
+ let depth = includeParents ? 0 : $from.sharedDepth(to);
1397
+ let start = $from.start(depth), node = $from.node(depth);
1398
+ let content = node.content.cut($from.pos - start, $to.pos - start);
1399
+ return new Slice(content, $from.depth - depth, $to.depth - depth);
1400
+ }
1401
+ /**
1402
+ Replace the part of the document between the given positions with
1403
+ the given slice. The slice must 'fit', meaning its open sides
1404
+ must be able to connect to the surrounding content, and its
1405
+ content nodes must be valid children for the node they are placed
1406
+ into. If any of this is violated, an error of type
1407
+ [`ReplaceError`](https://prosemirror.net/docs/ref/#model.ReplaceError) is thrown.
1408
+ */
1409
+ replace(from, to, slice) {
1410
+ return replace(this.resolve(from), this.resolve(to), slice);
1411
+ }
1412
+ /**
1413
+ Find the node directly after the given position.
1414
+ */
1415
+ nodeAt(pos) {
1416
+ for (let node = this; ; ) {
1417
+ let { index, offset } = node.content.findIndex(pos);
1418
+ node = node.maybeChild(index);
1419
+ if (!node)
1420
+ return null;
1421
+ if (offset == pos || node.isText)
1422
+ return node;
1423
+ pos -= offset + 1;
1424
+ }
1425
+ }
1426
+ /**
1427
+ Find the (direct) child node after the given offset, if any,
1428
+ and return it along with its index and offset relative to this
1429
+ node.
1430
+ */
1431
+ childAfter(pos) {
1432
+ let { index, offset } = this.content.findIndex(pos);
1433
+ return { node: this.content.maybeChild(index), index, offset };
1434
+ }
1435
+ /**
1436
+ Find the (direct) child node before the given offset, if any,
1437
+ and return it along with its index and offset relative to this
1438
+ node.
1439
+ */
1440
+ childBefore(pos) {
1441
+ if (pos == 0)
1442
+ return { node: null, index: 0, offset: 0 };
1443
+ let { index, offset } = this.content.findIndex(pos);
1444
+ if (offset < pos)
1445
+ return { node: this.content.child(index), index, offset };
1446
+ let node = this.content.child(index - 1);
1447
+ return { node, index: index - 1, offset: offset - node.nodeSize };
1448
+ }
1449
+ /**
1450
+ Resolve the given position in the document, returning an
1451
+ [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context.
1452
+ */
1453
+ resolve(pos) {
1454
+ return ResolvedPos.resolveCached(this, pos);
1455
+ }
1456
+ /**
1457
+ @internal
1458
+ */
1459
+ resolveNoCache(pos) {
1460
+ return ResolvedPos.resolve(this, pos);
1461
+ }
1462
+ /**
1463
+ Test whether a given mark or mark type occurs in this document
1464
+ between the two given positions.
1465
+ */
1466
+ rangeHasMark(from, to, type) {
1467
+ let found2 = false;
1468
+ if (to > from)
1469
+ this.nodesBetween(from, to, (node) => {
1470
+ if (type.isInSet(node.marks))
1471
+ found2 = true;
1472
+ return !found2;
1473
+ });
1474
+ return found2;
1475
+ }
1476
+ /**
1477
+ True when this is a block (non-inline node)
1478
+ */
1479
+ get isBlock() {
1480
+ return this.type.isBlock;
1481
+ }
1482
+ /**
1483
+ True when this is a textblock node, a block node with inline
1484
+ content.
1485
+ */
1486
+ get isTextblock() {
1487
+ return this.type.isTextblock;
1488
+ }
1489
+ /**
1490
+ True when this node allows inline content.
1491
+ */
1492
+ get inlineContent() {
1493
+ return this.type.inlineContent;
1494
+ }
1495
+ /**
1496
+ True when this is an inline node (a text node or a node that can
1497
+ appear among text).
1498
+ */
1499
+ get isInline() {
1500
+ return this.type.isInline;
1501
+ }
1502
+ /**
1503
+ True when this is a text node.
1504
+ */
1505
+ get isText() {
1506
+ return this.type.isText;
1507
+ }
1508
+ /**
1509
+ True when this is a leaf node.
1510
+ */
1511
+ get isLeaf() {
1512
+ return this.type.isLeaf;
1513
+ }
1514
+ /**
1515
+ True when this is an atom, i.e. when it does not have directly
1516
+ editable content. This is usually the same as `isLeaf`, but can
1517
+ be configured with the [`atom` property](https://prosemirror.net/docs/ref/#model.NodeSpec.atom)
1518
+ on a node's spec (typically used when the node is displayed as
1519
+ an uneditable [node view](https://prosemirror.net/docs/ref/#view.NodeView)).
1520
+ */
1521
+ get isAtom() {
1522
+ return this.type.isAtom;
1523
+ }
1524
+ /**
1525
+ Return a string representation of this node for debugging
1526
+ purposes.
1527
+ */
1528
+ toString() {
1529
+ if (this.type.spec.toDebugString)
1530
+ return this.type.spec.toDebugString(this);
1531
+ let name = this.type.name;
1532
+ if (this.content.size)
1533
+ name += "(" + this.content.toStringInner() + ")";
1534
+ return wrapMarks(this.marks, name);
1535
+ }
1536
+ /**
1537
+ Get the content match in this node at the given index.
1538
+ */
1539
+ contentMatchAt(index) {
1540
+ let match = this.type.contentMatch.matchFragment(this.content, 0, index);
1541
+ if (!match)
1542
+ throw new Error("Called contentMatchAt on a node with invalid content");
1543
+ return match;
1544
+ }
1545
+ /**
1546
+ Test whether replacing the range between `from` and `to` (by
1547
+ child index) with the given replacement fragment (which defaults
1548
+ to the empty fragment) would leave the node's content valid. You
1549
+ can optionally pass `start` and `end` indices into the
1550
+ replacement fragment.
1551
+ */
1552
+ canReplace(from, to, replacement = Fragment.empty, start = 0, end = replacement.childCount) {
1553
+ let one = this.contentMatchAt(from).matchFragment(replacement, start, end);
1554
+ let two = one && one.matchFragment(this.content, to);
1555
+ if (!two || !two.validEnd)
1556
+ return false;
1557
+ for (let i = start; i < end; i++)
1558
+ if (!this.type.allowsMarks(replacement.child(i).marks))
1559
+ return false;
1560
+ return true;
1561
+ }
1562
+ /**
1563
+ Test whether replacing the range `from` to `to` (by index) with
1564
+ a node of the given type would leave the node's content valid.
1565
+ */
1566
+ canReplaceWith(from, to, type, marks) {
1567
+ if (marks && !this.type.allowsMarks(marks))
1568
+ return false;
1569
+ let start = this.contentMatchAt(from).matchType(type);
1570
+ let end = start && start.matchFragment(this.content, to);
1571
+ return end ? end.validEnd : false;
1572
+ }
1573
+ /**
1574
+ Test whether the given node's content could be appended to this
1575
+ node. If that node is empty, this will only return true if there
1576
+ is at least one node type that can appear in both nodes (to avoid
1577
+ merging completely incompatible nodes).
1578
+ */
1579
+ canAppend(other) {
1580
+ if (other.content.size)
1581
+ return this.canReplace(this.childCount, this.childCount, other.content);
1582
+ else
1583
+ return this.type.compatibleContent(other.type);
1584
+ }
1585
+ /**
1586
+ Check whether this node and its descendants conform to the
1587
+ schema, and raise an exception when they do not.
1588
+ */
1589
+ check() {
1590
+ this.type.checkContent(this.content);
1591
+ this.type.checkAttrs(this.attrs);
1592
+ let copy = Mark.none;
1593
+ for (let i = 0; i < this.marks.length; i++) {
1594
+ let mark = this.marks[i];
1595
+ mark.type.checkAttrs(mark.attrs);
1596
+ copy = mark.addToSet(copy);
1597
+ }
1598
+ if (!Mark.sameSet(copy, this.marks))
1599
+ throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map((m) => m.type.name)}`);
1600
+ this.content.forEach((node) => node.check());
1601
+ }
1602
+ /**
1603
+ Return a JSON-serializeable representation of this node.
1604
+ */
1605
+ toJSON() {
1606
+ let obj = { type: this.type.name };
1607
+ for (let _ in this.attrs) {
1608
+ obj.attrs = this.attrs;
1609
+ break;
1610
+ }
1611
+ if (this.content.size)
1612
+ obj.content = this.content.toJSON();
1613
+ if (this.marks.length)
1614
+ obj.marks = this.marks.map((n) => n.toJSON());
1615
+ return obj;
1616
+ }
1617
+ /**
1618
+ Deserialize a node from its JSON representation.
1619
+ */
1620
+ static fromJSON(schema, json) {
1621
+ if (!json)
1622
+ throw new RangeError("Invalid input for Node.fromJSON");
1623
+ let marks = void 0;
1624
+ if (json.marks) {
1625
+ if (!Array.isArray(json.marks))
1626
+ throw new RangeError("Invalid mark data for Node.fromJSON");
1627
+ marks = json.marks.map(schema.markFromJSON);
1628
+ }
1629
+ if (json.type == "text") {
1630
+ if (typeof json.text != "string")
1631
+ throw new RangeError("Invalid text node in JSON");
1632
+ return schema.text(json.text, marks);
1633
+ }
1634
+ let content = Fragment.fromJSON(schema, json.content);
1635
+ let node = schema.nodeType(json.type).create(json.attrs, content, marks);
1636
+ node.type.checkAttrs(node.attrs);
1637
+ return node;
1638
+ }
1639
+ };
1640
+ Node.prototype.text = void 0;
1641
+ var TextNode = class _TextNode extends Node {
1642
+ /**
1643
+ @internal
1644
+ */
1645
+ constructor(type, attrs, content, marks) {
1646
+ super(type, attrs, null, marks);
1647
+ if (!content)
1648
+ throw new RangeError("Empty text nodes are not allowed");
1649
+ this.text = content;
1650
+ }
1651
+ toString() {
1652
+ if (this.type.spec.toDebugString)
1653
+ return this.type.spec.toDebugString(this);
1654
+ return wrapMarks(this.marks, JSON.stringify(this.text));
1655
+ }
1656
+ get textContent() {
1657
+ return this.text;
1658
+ }
1659
+ textBetween(from, to) {
1660
+ return this.text.slice(from, to);
1661
+ }
1662
+ get nodeSize() {
1663
+ return this.text.length;
1664
+ }
1665
+ mark(marks) {
1666
+ return marks == this.marks ? this : new _TextNode(this.type, this.attrs, this.text, marks);
1667
+ }
1668
+ withText(text) {
1669
+ if (text == this.text)
1670
+ return this;
1671
+ return new _TextNode(this.type, this.attrs, text, this.marks);
1672
+ }
1673
+ cut(from = 0, to = this.text.length) {
1674
+ if (from == 0 && to == this.text.length)
1675
+ return this;
1676
+ return this.withText(this.text.slice(from, to));
1677
+ }
1678
+ eq(other) {
1679
+ return this.sameMarkup(other) && this.text == other.text;
1680
+ }
1681
+ toJSON() {
1682
+ let base = super.toJSON();
1683
+ base.text = this.text;
1684
+ return base;
1685
+ }
1686
+ };
1687
+ function wrapMarks(marks, str) {
1688
+ for (let i = marks.length - 1; i >= 0; i--)
1689
+ str = marks[i].type.name + "(" + str + ")";
1690
+ return str;
1691
+ }
1692
+ var ContentMatch = class _ContentMatch {
1693
+ /**
1694
+ @internal
1695
+ */
1696
+ constructor(validEnd) {
1697
+ this.validEnd = validEnd;
1698
+ this.next = [];
1699
+ this.wrapCache = [];
1700
+ }
1701
+ /**
1702
+ @internal
1703
+ */
1704
+ static parse(string, nodeTypes) {
1705
+ let stream = new TokenStream(string, nodeTypes);
1706
+ if (stream.next == null)
1707
+ return _ContentMatch.empty;
1708
+ let expr = parseExpr(stream);
1709
+ if (stream.next)
1710
+ stream.err("Unexpected trailing text");
1711
+ let match = dfa(nfa(expr));
1712
+ checkForDeadEnds(match, stream);
1713
+ return match;
1714
+ }
1715
+ /**
1716
+ Match a node type, returning a match after that node if
1717
+ successful.
1718
+ */
1719
+ matchType(type) {
1720
+ for (let i = 0; i < this.next.length; i++)
1721
+ if (this.next[i].type == type)
1722
+ return this.next[i].next;
1723
+ return null;
1724
+ }
1725
+ /**
1726
+ Try to match a fragment. Returns the resulting match when
1727
+ successful.
1728
+ */
1729
+ matchFragment(frag, start = 0, end = frag.childCount) {
1730
+ let cur = this;
1731
+ for (let i = start; cur && i < end; i++)
1732
+ cur = cur.matchType(frag.child(i).type);
1733
+ return cur;
1734
+ }
1735
+ /**
1736
+ @internal
1737
+ */
1738
+ get inlineContent() {
1739
+ return this.next.length != 0 && this.next[0].type.isInline;
1740
+ }
1741
+ /**
1742
+ Get the first matching node type at this match position that can
1743
+ be generated.
1744
+ */
1745
+ get defaultType() {
1746
+ for (let i = 0; i < this.next.length; i++) {
1747
+ let { type } = this.next[i];
1748
+ if (!(type.isText || type.hasRequiredAttrs()))
1749
+ return type;
1750
+ }
1751
+ return null;
1752
+ }
1753
+ /**
1754
+ @internal
1755
+ */
1756
+ compatible(other) {
1757
+ for (let i = 0; i < this.next.length; i++)
1758
+ for (let j = 0; j < other.next.length; j++)
1759
+ if (this.next[i].type == other.next[j].type)
1760
+ return true;
1761
+ return false;
1762
+ }
1763
+ /**
1764
+ Try to match the given fragment, and if that fails, see if it can
1765
+ be made to match by inserting nodes in front of it. When
1766
+ successful, return a fragment of inserted nodes (which may be
1767
+ empty if nothing had to be inserted). When `toEnd` is true, only
1768
+ return a fragment if the resulting match goes to the end of the
1769
+ content expression.
1770
+ */
1771
+ fillBefore(after, toEnd = false, startIndex = 0) {
1772
+ let seen = [this];
1773
+ function search(match, types) {
1774
+ let finished = match.matchFragment(after, startIndex);
1775
+ if (finished && (!toEnd || finished.validEnd))
1776
+ return Fragment.from(types.map((tp) => tp.createAndFill()));
1777
+ for (let i = 0; i < match.next.length; i++) {
1778
+ let { type, next } = match.next[i];
1779
+ if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) {
1780
+ seen.push(next);
1781
+ let found2 = search(next, types.concat(type));
1782
+ if (found2)
1783
+ return found2;
1784
+ }
1785
+ }
1786
+ return null;
1787
+ }
1788
+ return search(this, []);
1789
+ }
1790
+ /**
1791
+ Find a set of wrapping node types that would allow a node of the
1792
+ given type to appear at this position. The result may be empty
1793
+ (when it fits directly) and will be null when no such wrapping
1794
+ exists.
1795
+ */
1796
+ findWrapping(target) {
1797
+ for (let i = 0; i < this.wrapCache.length; i += 2)
1798
+ if (this.wrapCache[i] == target)
1799
+ return this.wrapCache[i + 1];
1800
+ let computed = this.computeWrapping(target);
1801
+ this.wrapCache.push(target, computed);
1802
+ return computed;
1803
+ }
1804
+ /**
1805
+ @internal
1806
+ */
1807
+ computeWrapping(target) {
1808
+ let seen = /* @__PURE__ */ Object.create(null), active = [{ match: this, type: null, via: null }];
1809
+ while (active.length) {
1810
+ let current = active.shift(), match = current.match;
1811
+ if (match.matchType(target)) {
1812
+ let result = [];
1813
+ for (let obj = current; obj.type; obj = obj.via)
1814
+ result.push(obj.type);
1815
+ return result.reverse();
1816
+ }
1817
+ for (let i = 0; i < match.next.length; i++) {
1818
+ let { type, next } = match.next[i];
1819
+ if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next.validEnd)) {
1820
+ active.push({ match: type.contentMatch, type, via: current });
1821
+ seen[type.name] = true;
1822
+ }
1823
+ }
1824
+ }
1825
+ return null;
1826
+ }
1827
+ /**
1828
+ The number of outgoing edges this node has in the finite
1829
+ automaton that describes the content expression.
1830
+ */
1831
+ get edgeCount() {
1832
+ return this.next.length;
1833
+ }
1834
+ /**
1835
+ Get the _n_​th outgoing edge from this node in the finite
1836
+ automaton that describes the content expression.
1837
+ */
1838
+ edge(n) {
1839
+ if (n >= this.next.length)
1840
+ throw new RangeError(`There's no ${n}th edge in this content match`);
1841
+ return this.next[n];
1842
+ }
1843
+ /**
1844
+ @internal
1845
+ */
1846
+ toString() {
1847
+ let seen = [];
1848
+ function scan(m) {
1849
+ seen.push(m);
1850
+ for (let i = 0; i < m.next.length; i++)
1851
+ if (seen.indexOf(m.next[i].next) == -1)
1852
+ scan(m.next[i].next);
1853
+ }
1854
+ scan(this);
1855
+ return seen.map((m, i) => {
1856
+ let out = i + (m.validEnd ? "*" : " ") + " ";
1857
+ for (let i2 = 0; i2 < m.next.length; i2++)
1858
+ out += (i2 ? ", " : "") + m.next[i2].type.name + "->" + seen.indexOf(m.next[i2].next);
1859
+ return out;
1860
+ }).join("\n");
1861
+ }
1862
+ };
1863
+ ContentMatch.empty = new ContentMatch(true);
1864
+ var TokenStream = class {
1865
+ constructor(string, nodeTypes) {
1866
+ this.string = string;
1867
+ this.nodeTypes = nodeTypes;
1868
+ this.inline = null;
1869
+ this.pos = 0;
1870
+ this.tokens = string.split(/\s*(?=\b|\W|$)/);
1871
+ if (this.tokens[this.tokens.length - 1] == "")
1872
+ this.tokens.pop();
1873
+ if (this.tokens[0] == "")
1874
+ this.tokens.shift();
1875
+ }
1876
+ get next() {
1877
+ return this.tokens[this.pos];
1878
+ }
1879
+ eat(tok) {
1880
+ return this.next == tok && (this.pos++ || true);
1881
+ }
1882
+ err(str) {
1883
+ throw new SyntaxError(str + " (in content expression '" + this.string + "')");
1884
+ }
1885
+ };
1886
+ function parseExpr(stream) {
1887
+ let exprs = [];
1888
+ do {
1889
+ exprs.push(parseExprSeq(stream));
1890
+ } while (stream.eat("|"));
1891
+ return exprs.length == 1 ? exprs[0] : { type: "choice", exprs };
1892
+ }
1893
+ function parseExprSeq(stream) {
1894
+ let exprs = [];
1895
+ do {
1896
+ exprs.push(parseExprSubscript(stream));
1897
+ } while (stream.next && stream.next != ")" && stream.next != "|");
1898
+ return exprs.length == 1 ? exprs[0] : { type: "seq", exprs };
1899
+ }
1900
+ function parseExprSubscript(stream) {
1901
+ let expr = parseExprAtom(stream);
1902
+ for (; ; ) {
1903
+ if (stream.eat("+"))
1904
+ expr = { type: "plus", expr };
1905
+ else if (stream.eat("*"))
1906
+ expr = { type: "star", expr };
1907
+ else if (stream.eat("?"))
1908
+ expr = { type: "opt", expr };
1909
+ else if (stream.eat("{"))
1910
+ expr = parseExprRange(stream, expr);
1911
+ else
1912
+ break;
1913
+ }
1914
+ return expr;
1915
+ }
1916
+ function parseNum(stream) {
1917
+ if (/\D/.test(stream.next))
1918
+ stream.err("Expected number, got '" + stream.next + "'");
1919
+ let result = Number(stream.next);
1920
+ stream.pos++;
1921
+ return result;
1922
+ }
1923
+ function parseExprRange(stream, expr) {
1924
+ let min = parseNum(stream), max = min;
1925
+ if (stream.eat(",")) {
1926
+ if (stream.next != "}")
1927
+ max = parseNum(stream);
1928
+ else
1929
+ max = -1;
1930
+ }
1931
+ if (!stream.eat("}"))
1932
+ stream.err("Unclosed braced range");
1933
+ return { type: "range", min, max, expr };
1934
+ }
1935
+ function resolveName(stream, name) {
1936
+ let types = stream.nodeTypes, type = types[name];
1937
+ if (type)
1938
+ return [type];
1939
+ let result = [];
1940
+ for (let typeName in types) {
1941
+ let type2 = types[typeName];
1942
+ if (type2.isInGroup(name))
1943
+ result.push(type2);
1944
+ }
1945
+ if (result.length == 0)
1946
+ stream.err("No node type or group '" + name + "' found");
1947
+ return result;
1948
+ }
1949
+ function parseExprAtom(stream) {
1950
+ if (stream.eat("(")) {
1951
+ let expr = parseExpr(stream);
1952
+ if (!stream.eat(")"))
1953
+ stream.err("Missing closing paren");
1954
+ return expr;
1955
+ } else if (!/\W/.test(stream.next)) {
1956
+ let exprs = resolveName(stream, stream.next).map((type) => {
1957
+ if (stream.inline == null)
1958
+ stream.inline = type.isInline;
1959
+ else if (stream.inline != type.isInline)
1960
+ stream.err("Mixing inline and block content");
1961
+ return { type: "name", value: type };
1962
+ });
1963
+ stream.pos++;
1964
+ return exprs.length == 1 ? exprs[0] : { type: "choice", exprs };
1965
+ } else {
1966
+ stream.err("Unexpected token '" + stream.next + "'");
1967
+ }
1968
+ }
1969
+ function nfa(expr) {
1970
+ let nfa2 = [[]];
1971
+ connect(compile(expr, 0), node());
1972
+ return nfa2;
1973
+ function node() {
1974
+ return nfa2.push([]) - 1;
1975
+ }
1976
+ function edge(from, to, term) {
1977
+ let edge2 = { term, to };
1978
+ nfa2[from].push(edge2);
1979
+ return edge2;
1980
+ }
1981
+ function connect(edges, to) {
1982
+ edges.forEach((edge2) => edge2.to = to);
1983
+ }
1984
+ function compile(expr2, from) {
1985
+ if (expr2.type == "choice") {
1986
+ return expr2.exprs.reduce((out, expr3) => out.concat(compile(expr3, from)), []);
1987
+ } else if (expr2.type == "seq") {
1988
+ for (let i = 0; ; i++) {
1989
+ let next = compile(expr2.exprs[i], from);
1990
+ if (i == expr2.exprs.length - 1)
1991
+ return next;
1992
+ connect(next, from = node());
1993
+ }
1994
+ } else if (expr2.type == "star") {
1995
+ let loop = node();
1996
+ edge(from, loop);
1997
+ connect(compile(expr2.expr, loop), loop);
1998
+ return [edge(loop)];
1999
+ } else if (expr2.type == "plus") {
2000
+ let loop = node();
2001
+ connect(compile(expr2.expr, from), loop);
2002
+ connect(compile(expr2.expr, loop), loop);
2003
+ return [edge(loop)];
2004
+ } else if (expr2.type == "opt") {
2005
+ return [edge(from)].concat(compile(expr2.expr, from));
2006
+ } else if (expr2.type == "range") {
2007
+ let cur = from;
2008
+ for (let i = 0; i < expr2.min; i++) {
2009
+ let next = node();
2010
+ connect(compile(expr2.expr, cur), next);
2011
+ cur = next;
2012
+ }
2013
+ if (expr2.max == -1) {
2014
+ connect(compile(expr2.expr, cur), cur);
2015
+ } else {
2016
+ for (let i = expr2.min; i < expr2.max; i++) {
2017
+ let next = node();
2018
+ edge(cur, next);
2019
+ connect(compile(expr2.expr, cur), next);
2020
+ cur = next;
2021
+ }
2022
+ }
2023
+ return [edge(cur)];
2024
+ } else if (expr2.type == "name") {
2025
+ return [edge(from, void 0, expr2.value)];
2026
+ } else {
2027
+ throw new Error("Unknown expr type");
2028
+ }
2029
+ }
2030
+ }
2031
+ function cmp(a, b) {
2032
+ return b - a;
2033
+ }
2034
+ function nullFrom(nfa2, node) {
2035
+ let result = [];
2036
+ scan(node);
2037
+ return result.sort(cmp);
2038
+ function scan(node2) {
2039
+ let edges = nfa2[node2];
2040
+ if (edges.length == 1 && !edges[0].term)
2041
+ return scan(edges[0].to);
2042
+ result.push(node2);
2043
+ for (let i = 0; i < edges.length; i++) {
2044
+ let { term, to } = edges[i];
2045
+ if (!term && result.indexOf(to) == -1)
2046
+ scan(to);
2047
+ }
2048
+ }
2049
+ }
2050
+ function dfa(nfa2) {
2051
+ let labeled = /* @__PURE__ */ Object.create(null);
2052
+ return explore(nullFrom(nfa2, 0));
2053
+ function explore(states) {
2054
+ let out = [];
2055
+ states.forEach((node) => {
2056
+ nfa2[node].forEach(({ term, to }) => {
2057
+ if (!term)
2058
+ return;
2059
+ let set;
2060
+ for (let i = 0; i < out.length; i++)
2061
+ if (out[i][0] == term)
2062
+ set = out[i][1];
2063
+ nullFrom(nfa2, to).forEach((node2) => {
2064
+ if (!set)
2065
+ out.push([term, set = []]);
2066
+ if (set.indexOf(node2) == -1)
2067
+ set.push(node2);
2068
+ });
2069
+ });
2070
+ });
2071
+ let state = labeled[states.join(",")] = new ContentMatch(states.indexOf(nfa2.length - 1) > -1);
2072
+ for (let i = 0; i < out.length; i++) {
2073
+ let states2 = out[i][1].sort(cmp);
2074
+ state.next.push({ type: out[i][0], next: labeled[states2.join(",")] || explore(states2) });
2075
+ }
2076
+ return state;
2077
+ }
2078
+ }
2079
+ function checkForDeadEnds(match, stream) {
2080
+ for (let i = 0, work = [match]; i < work.length; i++) {
2081
+ let state = work[i], dead = !state.validEnd, nodes = [];
2082
+ for (let j = 0; j < state.next.length; j++) {
2083
+ let { type, next } = state.next[j];
2084
+ nodes.push(type.name);
2085
+ if (dead && !(type.isText || type.hasRequiredAttrs()))
2086
+ dead = false;
2087
+ if (work.indexOf(next) == -1)
2088
+ work.push(next);
2089
+ }
2090
+ if (dead)
2091
+ stream.err("Only non-generatable nodes (" + nodes.join(", ") + ") in a required position (see https://prosemirror.net/docs/guide/#generatable)");
2092
+ }
2093
+ }
2094
+ function defaultAttrs(attrs) {
2095
+ let defaults = /* @__PURE__ */ Object.create(null);
2096
+ for (let attrName in attrs) {
2097
+ let attr = attrs[attrName];
2098
+ if (!attr.hasDefault)
2099
+ return null;
2100
+ defaults[attrName] = attr.default;
2101
+ }
2102
+ return defaults;
2103
+ }
2104
+ function computeAttrs(attrs, value) {
2105
+ let built = /* @__PURE__ */ Object.create(null);
2106
+ for (let name in attrs) {
2107
+ let given = value && value[name];
2108
+ if (given === void 0) {
2109
+ let attr = attrs[name];
2110
+ if (attr.hasDefault)
2111
+ given = attr.default;
2112
+ else
2113
+ throw new RangeError("No value supplied for attribute " + name);
2114
+ }
2115
+ built[name] = given;
2116
+ }
2117
+ return built;
2118
+ }
2119
+ function checkAttrs(attrs, values, type, name) {
2120
+ for (let attr in values)
2121
+ if (!(attr in attrs))
2122
+ throw new RangeError(`Unsupported attribute ${attr} for ${type} of type ${name}`);
2123
+ for (let attr in attrs) {
2124
+ if (attrs[attr].validate)
2125
+ attrs[attr].validate(values[attr]);
2126
+ }
2127
+ }
2128
+ function initAttrs(typeName, attrs) {
2129
+ let result = /* @__PURE__ */ Object.create(null);
2130
+ if (attrs)
2131
+ for (let name in attrs)
2132
+ result[name] = new Attribute(typeName, name, attrs[name]);
2133
+ return result;
2134
+ }
2135
+ var NodeType = class _NodeType {
2136
+ /**
2137
+ @internal
2138
+ */
2139
+ constructor(name, schema, spec) {
2140
+ this.name = name;
2141
+ this.schema = schema;
2142
+ this.spec = spec;
2143
+ this.markSet = null;
2144
+ this.groups = spec.group ? spec.group.split(" ") : [];
2145
+ this.attrs = initAttrs(name, spec.attrs);
2146
+ this.defaultAttrs = defaultAttrs(this.attrs);
2147
+ this.contentMatch = null;
2148
+ this.inlineContent = null;
2149
+ this.isBlock = !(spec.inline || name == "text");
2150
+ this.isText = name == "text";
2151
+ }
2152
+ /**
2153
+ True if this is an inline type.
2154
+ */
2155
+ get isInline() {
2156
+ return !this.isBlock;
2157
+ }
2158
+ /**
2159
+ True if this is a textblock type, a block that contains inline
2160
+ content.
2161
+ */
2162
+ get isTextblock() {
2163
+ return this.isBlock && this.inlineContent;
2164
+ }
2165
+ /**
2166
+ True for node types that allow no content.
2167
+ */
2168
+ get isLeaf() {
2169
+ return this.contentMatch == ContentMatch.empty;
2170
+ }
2171
+ /**
2172
+ True when this node is an atom, i.e. when it does not have
2173
+ directly editable content.
2174
+ */
2175
+ get isAtom() {
2176
+ return this.isLeaf || !!this.spec.atom;
2177
+ }
2178
+ /**
2179
+ Return true when this node type is part of the given
2180
+ [group](https://prosemirror.net/docs/ref/#model.NodeSpec.group).
2181
+ */
2182
+ isInGroup(group) {
2183
+ return this.groups.indexOf(group) > -1;
2184
+ }
2185
+ /**
2186
+ The node type's [whitespace](https://prosemirror.net/docs/ref/#model.NodeSpec.whitespace) option.
2187
+ */
2188
+ get whitespace() {
2189
+ return this.spec.whitespace || (this.spec.code ? "pre" : "normal");
2190
+ }
2191
+ /**
2192
+ Tells you whether this node type has any required attributes.
2193
+ */
2194
+ hasRequiredAttrs() {
2195
+ for (let n in this.attrs)
2196
+ if (this.attrs[n].isRequired)
2197
+ return true;
2198
+ return false;
2199
+ }
2200
+ /**
2201
+ Indicates whether this node allows some of the same content as
2202
+ the given node type.
2203
+ */
2204
+ compatibleContent(other) {
2205
+ return this == other || this.contentMatch.compatible(other.contentMatch);
2206
+ }
2207
+ /**
2208
+ @internal
2209
+ */
2210
+ computeAttrs(attrs) {
2211
+ if (!attrs && this.defaultAttrs)
2212
+ return this.defaultAttrs;
2213
+ else
2214
+ return computeAttrs(this.attrs, attrs);
2215
+ }
2216
+ /**
2217
+ Create a `Node` of this type. The given attributes are
2218
+ checked and defaulted (you can pass `null` to use the type's
2219
+ defaults entirely, if no required attributes exist). `content`
2220
+ may be a `Fragment`, a node, an array of nodes, or
2221
+ `null`. Similarly `marks` may be `null` to default to the empty
2222
+ set of marks.
2223
+ */
2224
+ create(attrs = null, content, marks) {
2225
+ if (this.isText)
2226
+ throw new Error("NodeType.create can't construct text nodes");
2227
+ return new Node(this, this.computeAttrs(attrs), Fragment.from(content), Mark.setFrom(marks));
2228
+ }
2229
+ /**
2230
+ Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but check the given content
2231
+ against the node type's content restrictions, and throw an error
2232
+ if it doesn't match.
2233
+ */
2234
+ createChecked(attrs = null, content, marks) {
2235
+ content = Fragment.from(content);
2236
+ this.checkContent(content);
2237
+ return new Node(this, this.computeAttrs(attrs), content, Mark.setFrom(marks));
2238
+ }
2239
+ /**
2240
+ Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is
2241
+ necessary to add nodes to the start or end of the given fragment
2242
+ to make it fit the node. If no fitting wrapping can be found,
2243
+ return null. Note that, due to the fact that required nodes can
2244
+ always be created, this will always succeed if you pass null or
2245
+ `Fragment.empty` as content.
2246
+ */
2247
+ createAndFill(attrs = null, content, marks) {
2248
+ attrs = this.computeAttrs(attrs);
2249
+ content = Fragment.from(content);
2250
+ if (content.size) {
2251
+ let before = this.contentMatch.fillBefore(content);
2252
+ if (!before)
2253
+ return null;
2254
+ content = before.append(content);
2255
+ }
2256
+ let matched = this.contentMatch.matchFragment(content);
2257
+ let after = matched && matched.fillBefore(Fragment.empty, true);
2258
+ if (!after)
2259
+ return null;
2260
+ return new Node(this, attrs, content.append(after), Mark.setFrom(marks));
2261
+ }
2262
+ /**
2263
+ Returns true if the given fragment is valid content for this node
2264
+ type.
2265
+ */
2266
+ validContent(content) {
2267
+ let result = this.contentMatch.matchFragment(content);
2268
+ if (!result || !result.validEnd)
2269
+ return false;
2270
+ for (let i = 0; i < content.childCount; i++)
2271
+ if (!this.allowsMarks(content.child(i).marks))
2272
+ return false;
2273
+ return true;
2274
+ }
2275
+ /**
2276
+ Throws a RangeError if the given fragment is not valid content for this
2277
+ node type.
2278
+ @internal
2279
+ */
2280
+ checkContent(content) {
2281
+ if (!this.validContent(content))
2282
+ throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`);
2283
+ }
2284
+ /**
2285
+ @internal
2286
+ */
2287
+ checkAttrs(attrs) {
2288
+ checkAttrs(this.attrs, attrs, "node", this.name);
2289
+ }
2290
+ /**
2291
+ Check whether the given mark type is allowed in this node.
2292
+ */
2293
+ allowsMarkType(markType) {
2294
+ return this.markSet == null || this.markSet.indexOf(markType) > -1;
2295
+ }
2296
+ /**
2297
+ Test whether the given set of marks are allowed in this node.
2298
+ */
2299
+ allowsMarks(marks) {
2300
+ if (this.markSet == null)
2301
+ return true;
2302
+ for (let i = 0; i < marks.length; i++)
2303
+ if (!this.allowsMarkType(marks[i].type))
2304
+ return false;
2305
+ return true;
2306
+ }
2307
+ /**
2308
+ Removes the marks that are not allowed in this node from the given set.
2309
+ */
2310
+ allowedMarks(marks) {
2311
+ if (this.markSet == null)
2312
+ return marks;
2313
+ let copy;
2314
+ for (let i = 0; i < marks.length; i++) {
2315
+ if (!this.allowsMarkType(marks[i].type)) {
2316
+ if (!copy)
2317
+ copy = marks.slice(0, i);
2318
+ } else if (copy) {
2319
+ copy.push(marks[i]);
2320
+ }
2321
+ }
2322
+ return !copy ? marks : copy.length ? copy : Mark.none;
2323
+ }
2324
+ /**
2325
+ @internal
2326
+ */
2327
+ static compile(nodes, schema) {
2328
+ let result = /* @__PURE__ */ Object.create(null);
2329
+ nodes.forEach((name, spec) => result[name] = new _NodeType(name, schema, spec));
2330
+ let topType = schema.spec.topNode || "doc";
2331
+ if (!result[topType])
2332
+ throw new RangeError("Schema is missing its top node type ('" + topType + "')");
2333
+ if (!result.text)
2334
+ throw new RangeError("Every schema needs a 'text' type");
2335
+ for (let _ in result.text.attrs)
2336
+ throw new RangeError("The text node type should not have attributes");
2337
+ return result;
2338
+ }
2339
+ };
2340
+ function validateType(typeName, attrName, type) {
2341
+ let types = type.split("|");
2342
+ return (value) => {
2343
+ let name = value === null ? "null" : typeof value;
2344
+ if (types.indexOf(name) < 0)
2345
+ throw new RangeError(`Expected value of type ${types} for attribute ${attrName} on type ${typeName}, got ${name}`);
2346
+ };
2347
+ }
2348
+ var Attribute = class {
2349
+ constructor(typeName, attrName, options) {
2350
+ this.hasDefault = Object.prototype.hasOwnProperty.call(options, "default");
2351
+ this.default = options.default;
2352
+ this.validate = typeof options.validate == "string" ? validateType(typeName, attrName, options.validate) : options.validate;
2353
+ }
2354
+ get isRequired() {
2355
+ return !this.hasDefault;
2356
+ }
2357
+ };
2358
+ var MarkType = class _MarkType {
2359
+ /**
2360
+ @internal
2361
+ */
2362
+ constructor(name, rank, schema, spec) {
2363
+ this.name = name;
2364
+ this.rank = rank;
2365
+ this.schema = schema;
2366
+ this.spec = spec;
2367
+ this.attrs = initAttrs(name, spec.attrs);
2368
+ this.excluded = null;
2369
+ let defaults = defaultAttrs(this.attrs);
2370
+ this.instance = defaults ? new Mark(this, defaults) : null;
2371
+ }
2372
+ /**
2373
+ Create a mark of this type. `attrs` may be `null` or an object
2374
+ containing only some of the mark's attributes. The others, if
2375
+ they have defaults, will be added.
2376
+ */
2377
+ create(attrs = null) {
2378
+ if (!attrs && this.instance)
2379
+ return this.instance;
2380
+ return new Mark(this, computeAttrs(this.attrs, attrs));
2381
+ }
2382
+ /**
2383
+ @internal
2384
+ */
2385
+ static compile(marks, schema) {
2386
+ let result = /* @__PURE__ */ Object.create(null), rank = 0;
2387
+ marks.forEach((name, spec) => result[name] = new _MarkType(name, rank++, schema, spec));
2388
+ return result;
2389
+ }
2390
+ /**
2391
+ When there is a mark of this type in the given set, a new set
2392
+ without it is returned. Otherwise, the input set is returned.
2393
+ */
2394
+ removeFromSet(set) {
2395
+ for (var i = 0; i < set.length; i++)
2396
+ if (set[i].type == this) {
2397
+ set = set.slice(0, i).concat(set.slice(i + 1));
2398
+ i--;
2399
+ }
2400
+ return set;
2401
+ }
2402
+ /**
2403
+ Tests whether there is a mark of this type in the given set.
2404
+ */
2405
+ isInSet(set) {
2406
+ for (let i = 0; i < set.length; i++)
2407
+ if (set[i].type == this)
2408
+ return set[i];
2409
+ }
2410
+ /**
2411
+ @internal
2412
+ */
2413
+ checkAttrs(attrs) {
2414
+ checkAttrs(this.attrs, attrs, "mark", this.name);
2415
+ }
2416
+ /**
2417
+ Queries whether a given mark type is
2418
+ [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one.
2419
+ */
2420
+ excludes(other) {
2421
+ return this.excluded.indexOf(other) > -1;
2422
+ }
2423
+ };
2424
+ var Schema = class {
2425
+ /**
2426
+ Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec).
2427
+ */
2428
+ constructor(spec) {
2429
+ this.linebreakReplacement = null;
2430
+ this.cached = /* @__PURE__ */ Object.create(null);
2431
+ let instanceSpec = this.spec = {};
2432
+ for (let prop in spec)
2433
+ instanceSpec[prop] = spec[prop];
2434
+ instanceSpec.nodes = dist_default.from(spec.nodes), instanceSpec.marks = dist_default.from(spec.marks || {}), this.nodes = NodeType.compile(this.spec.nodes, this);
2435
+ this.marks = MarkType.compile(this.spec.marks, this);
2436
+ let contentExprCache = /* @__PURE__ */ Object.create(null);
2437
+ for (let prop in this.nodes) {
2438
+ if (prop in this.marks)
2439
+ throw new RangeError(prop + " can not be both a node and a mark");
2440
+ let type = this.nodes[prop], contentExpr = type.spec.content || "", markExpr = type.spec.marks;
2441
+ type.contentMatch = contentExprCache[contentExpr] || (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes));
2442
+ type.inlineContent = type.contentMatch.inlineContent;
2443
+ if (type.spec.linebreakReplacement) {
2444
+ if (this.linebreakReplacement)
2445
+ throw new RangeError("Multiple linebreak nodes defined");
2446
+ if (!type.isInline || !type.isLeaf)
2447
+ throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");
2448
+ this.linebreakReplacement = type;
2449
+ }
2450
+ type.markSet = markExpr == "_" ? null : markExpr ? gatherMarks(this, markExpr.split(" ")) : markExpr == "" || !type.inlineContent ? [] : null;
2451
+ }
2452
+ for (let prop in this.marks) {
2453
+ let type = this.marks[prop], excl = type.spec.excludes;
2454
+ type.excluded = excl == null ? [type] : excl == "" ? [] : gatherMarks(this, excl.split(" "));
2455
+ }
2456
+ this.nodeFromJSON = (json) => Node.fromJSON(this, json);
2457
+ this.markFromJSON = (json) => Mark.fromJSON(this, json);
2458
+ this.topNodeType = this.nodes[this.spec.topNode || "doc"];
2459
+ this.cached.wrappings = /* @__PURE__ */ Object.create(null);
2460
+ }
2461
+ /**
2462
+ Create a node in this schema. The `type` may be a string or a
2463
+ `NodeType` instance. Attributes will be extended with defaults,
2464
+ `content` may be a `Fragment`, `null`, a `Node`, or an array of
2465
+ nodes.
2466
+ */
2467
+ node(type, attrs = null, content, marks) {
2468
+ if (typeof type == "string")
2469
+ type = this.nodeType(type);
2470
+ else if (!(type instanceof NodeType))
2471
+ throw new RangeError("Invalid node type: " + type);
2472
+ else if (type.schema != this)
2473
+ throw new RangeError("Node type from different schema used (" + type.name + ")");
2474
+ return type.createChecked(attrs, content, marks);
2475
+ }
2476
+ /**
2477
+ Create a text node in the schema. Empty text nodes are not
2478
+ allowed.
2479
+ */
2480
+ text(text, marks) {
2481
+ let type = this.nodes.text;
2482
+ return new TextNode(type, type.defaultAttrs, text, Mark.setFrom(marks));
2483
+ }
2484
+ /**
2485
+ Create a mark with the given type and attributes.
2486
+ */
2487
+ mark(type, attrs) {
2488
+ if (typeof type == "string")
2489
+ type = this.marks[type];
2490
+ return type.create(attrs);
2491
+ }
2492
+ /**
2493
+ @internal
2494
+ */
2495
+ nodeType(name) {
2496
+ let found2 = this.nodes[name];
2497
+ if (!found2)
2498
+ throw new RangeError("Unknown node type: " + name);
2499
+ return found2;
2500
+ }
2501
+ };
2502
+ function gatherMarks(schema, marks) {
2503
+ let found2 = [];
2504
+ for (let i = 0; i < marks.length; i++) {
2505
+ let name = marks[i], mark = schema.marks[name], ok = mark;
2506
+ if (mark) {
2507
+ found2.push(mark);
2508
+ } else {
2509
+ for (let prop in schema.marks) {
2510
+ let mark2 = schema.marks[prop];
2511
+ if (name == "_" || mark2.spec.group && mark2.spec.group.split(" ").indexOf(name) > -1)
2512
+ found2.push(ok = mark2);
2513
+ }
2514
+ }
2515
+ if (!ok)
2516
+ throw new SyntaxError("Unknown mark type: '" + marks[i] + "'");
2517
+ }
2518
+ return found2;
2519
+ }
2520
+
2521
+ // ../editor-core/dist/index.js
2522
+ var pptxTextBodySchema = new Schema({
2523
+ nodes: {
2524
+ doc: { content: "paragraph*" },
2525
+ paragraph: {
2526
+ content: "text*",
2527
+ attrs: {
2528
+ handle: { default: null },
2529
+ properties: { default: null }
2530
+ },
2531
+ toDOM: () => ["p", 0]
2532
+ },
2533
+ text: { group: "inline" }
2534
+ },
2535
+ marks: {
2536
+ pptxRun: {
2537
+ attrs: {
2538
+ handle: { default: null },
2539
+ properties: { default: null }
2540
+ },
2541
+ toDOM: () => ["span", { "data-pptx-run": "" }, 0]
2542
+ }
2543
+ }
2544
+ });
2545
+ function textBodyToProseMirrorDocJson(textBody) {
2546
+ assertSupportedTextBody(textBody);
2547
+ return {
2548
+ type: "doc",
2549
+ content: textBody.paragraphs.map((paragraph) => {
2550
+ const content = paragraph.runs.map((run) => ({
2551
+ type: "text",
2552
+ text: run.text,
2553
+ marks: [
2554
+ {
2555
+ type: "pptxRun",
2556
+ attrs: {
2557
+ handle: run.handle ?? null,
2558
+ properties: run.properties ?? null
2559
+ }
2560
+ }
2561
+ ]
2562
+ }));
2563
+ return {
2564
+ type: "paragraph",
2565
+ attrs: {
2566
+ handle: paragraph.handle ?? null,
2567
+ properties: paragraph.properties ?? null
2568
+ },
2569
+ ...content.length > 0 ? { content } : {}
2570
+ };
2571
+ })
2572
+ };
2573
+ }
2574
+ function assertSupportedTextBody(textBody) {
2575
+ textBody.paragraphs.forEach((paragraph, paragraphIndex) => {
2576
+ paragraph.runs.forEach((run, runIndex) => {
2577
+ if (run.text.length === 0) {
2578
+ throw new Error(
2579
+ `textBodyToProseMirrorDocJson: empty text runs are unsupported at paragraph ${paragraphIndex}, run ${runIndex}`
2580
+ );
2581
+ }
2582
+ if (run.text.includes("\n") || (run.rawSidecars?.length ?? 0) > 0) {
2583
+ throw new Error(
2584
+ `textBodyToProseMirrorDocJson: unsupported run-like content at paragraph ${paragraphIndex}, run ${runIndex}`
2585
+ );
2586
+ }
2587
+ });
2588
+ });
2589
+ }
2590
+ function proseMirrorDocJsonToTextBody(originalTextBody, docJson) {
2591
+ const parsed = parsePptxTextBodyProseMirrorDocJson(docJson);
2592
+ validateProseMirrorDocJson(parsed);
2593
+ const paragraphs = (parsed.content ?? []).map(
2594
+ (paragraph, index) => paragraphJsonToSourceParagraph(originalTextBody.paragraphs[index], paragraph)
2595
+ );
2596
+ return {
2597
+ ...originalTextBody,
2598
+ paragraphs
2599
+ };
2600
+ }
2601
+ function proseMirrorDocJsonToEditorCommands(originalTextBody, docJson) {
2602
+ const editedTextBody = proseMirrorDocJsonToTextBody(originalTextBody, docJson);
2603
+ if (editedTextBody.paragraphs.length !== originalTextBody.paragraphs.length) {
2604
+ throw new Error("proseMirrorDocJsonToEditorCommands: paragraph count changes are unsupported");
2605
+ }
2606
+ return editedTextBody.paragraphs.flatMap(
2607
+ (editedParagraph, paragraphIndex) => {
2608
+ const originalParagraph = originalTextBody.paragraphs[paragraphIndex];
2609
+ if (originalParagraph === void 0) return [];
2610
+ if (paragraphRunHandlesMatch(originalParagraph, editedParagraph)) {
2611
+ return editedParagraph.runs.flatMap(
2612
+ (editedRun, runIndex) => {
2613
+ const originalRun = originalParagraph.runs[runIndex];
2614
+ if (originalRun === void 0 || editedRun.text === originalRun.text) return [];
2615
+ if (editedRun.handle === void 0) {
2616
+ throw new Error(
2617
+ "proseMirrorDocJsonToEditorCommands: changed text run has no source handle"
2618
+ );
2619
+ }
2620
+ return [
2621
+ {
2622
+ kind: "replaceTextRunPlainText",
2623
+ handle: editedRun.handle,
2624
+ text: editedRun.text
2625
+ }
2626
+ ];
2627
+ }
2628
+ );
2629
+ }
2630
+ if (editedParagraph.handle === void 0) {
2631
+ throw new Error(
2632
+ "proseMirrorDocJsonToEditorCommands: paragraph structure changed but paragraph has no source handle"
2633
+ );
2634
+ }
2635
+ return [
2636
+ {
2637
+ kind: "replaceParagraphPlainText",
2638
+ handle: editedParagraph.handle,
2639
+ text: paragraphPlainText(editedParagraph)
2640
+ }
2641
+ ];
2642
+ }
2643
+ );
2644
+ }
2645
+ function validateProseMirrorDocJson(docJson) {
2646
+ const doc = Node.fromJSON(pptxTextBodySchema, docJson);
2647
+ doc.check();
2648
+ }
2649
+ function paragraphJsonToSourceParagraph(originalParagraph, paragraphJson) {
2650
+ const groups = collectRunGroups(paragraphJson, originalParagraph);
2651
+ return {
2652
+ ...originalParagraph ?? {},
2653
+ runs: groups.map(sourceRunFromGroup),
2654
+ ...originalParagraph?.properties !== void 0 ? { properties: originalParagraph.properties } : {},
2655
+ ...originalParagraph?.handle !== void 0 ? { handle: originalParagraph.handle } : sourceHandleFromUnknown(paragraphJson.attrs?.handle) !== void 0 ? { handle: sourceHandleFromUnknown(paragraphJson.attrs?.handle) } : {}
2656
+ };
2657
+ }
2658
+ function collectRunGroups(paragraphJson, originalParagraph) {
2659
+ const groups = [];
2660
+ let previousHandle = originalParagraph?.runs[0]?.handle;
2661
+ for (const textNode of paragraphJson.content ?? []) {
2662
+ const mark = textNode.marks?.find((candidate) => candidate.type === "pptxRun");
2663
+ const markedHandle = sourceHandleFromUnknown(mark?.attrs?.handle);
2664
+ const handle = markedHandle ?? previousHandle;
2665
+ const originalRun = handle === void 0 ? void 0 : findOriginalRun(originalParagraph, handle);
2666
+ const properties = originalRun?.properties;
2667
+ const lastGroup = groups.at(-1);
2668
+ if (lastGroup !== void 0 && sourceHandlesEqual(lastGroup.handle, handle)) {
2669
+ groups[groups.length - 1] = {
2670
+ ...lastGroup,
2671
+ text: lastGroup.text + textNode.text
2672
+ };
2673
+ } else {
2674
+ groups.push({
2675
+ ...handle !== void 0 ? { handle } : {},
2676
+ ...properties !== void 0 ? { properties } : {},
2677
+ text: textNode.text
2678
+ });
2679
+ }
2680
+ previousHandle = handle;
2681
+ }
2682
+ return groups;
2683
+ }
2684
+ function sourceRunFromGroup(group) {
2685
+ return {
2686
+ kind: "textRun",
2687
+ text: group.text,
2688
+ ...group.properties !== void 0 ? { properties: group.properties } : {},
2689
+ ...group.handle !== void 0 ? { handle: group.handle } : {}
2690
+ };
2691
+ }
2692
+ function findOriginalRun(paragraph, handle) {
2693
+ return paragraph?.runs.find((run) => sourceHandlesEqual(run.handle, handle));
2694
+ }
2695
+ function paragraphRunHandlesMatch(originalParagraph, editedParagraph) {
2696
+ if (originalParagraph.runs.length !== editedParagraph.runs.length) return false;
2697
+ return originalParagraph.runs.every(
2698
+ (run, index) => sourceHandlesEqual(run.handle, editedParagraph.runs[index]?.handle)
2699
+ );
2700
+ }
2701
+ function paragraphPlainText(paragraph) {
2702
+ return paragraph.runs.map((run) => run.text).join("");
2703
+ }
2704
+ function parsePptxTextBodyProseMirrorDocJson(value) {
2705
+ if (!isRecord(value) || value.type !== "doc") {
2706
+ throw new Error("ProseMirror text body doc JSON must be a doc node");
2707
+ }
2708
+ if (value.content !== void 0 && readArray(value.content, isParagraphJson) === void 0) {
2709
+ throw new Error("ProseMirror text body doc JSON content must contain paragraph nodes");
2710
+ }
2711
+ const content = readArray(value.content, isParagraphJson);
2712
+ return {
2713
+ type: "doc",
2714
+ ...content !== void 0 ? { content } : {}
2715
+ };
2716
+ }
2717
+ function isParagraphJson(value) {
2718
+ if (!isRecord(value) || value.type !== "paragraph") return false;
2719
+ if (value.content !== void 0 && readArray(value.content, isTextJson) === void 0) {
2720
+ return false;
2721
+ }
2722
+ return value.attrs === void 0 || isRecord(value.attrs);
2723
+ }
2724
+ function isTextJson(value) {
2725
+ if (!isRecord(value) || value.type !== "text" || typeof value.text !== "string") return false;
2726
+ if (value.marks === void 0) return true;
2727
+ return readArray(value.marks, isRunMarkJson) !== void 0;
2728
+ }
2729
+ function isRunMarkJson(value) {
2730
+ if (!isRecord(value) || value.type !== "pptxRun") return false;
2731
+ return value.attrs === void 0 || isRecord(value.attrs);
2732
+ }
2733
+ function readArray(value, itemGuard) {
2734
+ if (value === void 0) return void 0;
2735
+ if (!Array.isArray(value)) return void 0;
2736
+ return value.every(itemGuard) ? value : void 0;
2737
+ }
2738
+ function sourceHandleFromUnknown(value) {
2739
+ if (value === null || value === void 0) return void 0;
2740
+ if (!isRecord(value) || typeof value.partPath !== "string") return void 0;
2741
+ const handle = {
2742
+ partPath: asPartPath(value.partPath),
2743
+ ...typeof value.nodeId === "string" ? { nodeId: asSourceNodeId(value.nodeId) } : {},
2744
+ ...typeof value.relationshipId === "string" ? { relationshipId: asRelationshipId(value.relationshipId) } : {},
2745
+ ...typeof value.orderingSlot === "number" ? { orderingSlot: value.orderingSlot } : {}
2746
+ };
2747
+ return handle;
2748
+ }
2749
+ function sourceHandlesEqual(left, right) {
2750
+ if (left === void 0 || right === void 0) return left === right;
2751
+ return sourceHandleKey(left) === sourceHandleKey(right);
2752
+ }
2753
+ function sourceHandleKey(handle) {
2754
+ return [
2755
+ handle.partPath,
2756
+ handle.nodeId ?? "",
2757
+ handle.relationshipId ?? "",
2758
+ handle.orderingSlot ?? ""
2759
+ ].join("\0");
2760
+ }
2761
+ function isRecord(value) {
2762
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2763
+ }
2764
+ var EditorSession = class {
2765
+ #document;
2766
+ #selection;
2767
+ #undoStack = [];
2768
+ #redoStack = [];
2769
+ constructor(document) {
2770
+ this.#document = document;
2771
+ }
2772
+ get document() {
2773
+ return this.#document;
2774
+ }
2775
+ get selection() {
2776
+ return this.#selection;
2777
+ }
2778
+ get canUndo() {
2779
+ return this.#undoStack.length > 0;
2780
+ }
2781
+ get canRedo() {
2782
+ return this.#redoStack.length > 0;
2783
+ }
2784
+ get undoDepth() {
2785
+ return this.#undoStack.length;
2786
+ }
2787
+ get redoDepth() {
2788
+ return this.#redoStack.length;
2789
+ }
2790
+ selectShape(handle) {
2791
+ if (findShapeNodeBySourceHandle(this.#document, handle) === void 0) {
2792
+ return {
2793
+ ok: false,
2794
+ code: "invalid-selection",
2795
+ message: "selectShape: shape handle was not found in PptxSourceModel source"
2796
+ };
2797
+ }
2798
+ const selection = { shapeHandle: handle };
2799
+ this.#selection = selection;
2800
+ return { ok: true, selection };
2801
+ }
2802
+ deselectShape() {
2803
+ this.#selection = void 0;
2804
+ }
2805
+ apply(command) {
2806
+ return this.applyAll([command]);
2807
+ }
2808
+ applyAll(commands) {
2809
+ const before = this.#document;
2810
+ if (commands.length === 0) return { ok: true, document: before };
2811
+ try {
2812
+ let after = before;
2813
+ const warnings = [];
2814
+ for (const command of commands) {
2815
+ after = applyCommandToDocument(after, command);
2816
+ warnings.push(...collectCommandWarnings(after, [command]));
2817
+ }
2818
+ after = normalizeEditorEdits(after);
2819
+ const dedupedWarnings = dedupeCommandWarnings(warnings);
2820
+ this.#document = after;
2821
+ this.reconcileSelectionAfterDocumentChange();
2822
+ this.#undoStack.push({ before, after });
2823
+ this.#redoStack.length = 0;
2824
+ return {
2825
+ ok: true,
2826
+ document: after,
2827
+ ...dedupedWarnings.length > 0 ? { warnings: dedupedWarnings } : {}
2828
+ };
2829
+ } catch (error) {
2830
+ return {
2831
+ ok: false,
2832
+ code: "invalid-command",
2833
+ message: error instanceof Error ? error.message : "Editor command was rejected.",
2834
+ cause: error
2835
+ };
2836
+ }
2837
+ }
2838
+ undo() {
2839
+ const entry = this.#undoStack.pop();
2840
+ if (entry === void 0) return { ok: false, reason: "empty-undo-stack" };
2841
+ this.#document = entry.before;
2842
+ this.reconcileSelectionAfterDocumentChange();
2843
+ this.#redoStack.push(entry);
2844
+ return { ok: true, document: entry.before };
2845
+ }
2846
+ redo() {
2847
+ const entry = this.#redoStack.pop();
2848
+ if (entry === void 0) return { ok: false, reason: "empty-redo-stack" };
2849
+ this.#document = entry.after;
2850
+ this.reconcileSelectionAfterDocumentChange();
2851
+ this.#undoStack.push(entry);
2852
+ return { ok: true, document: entry.after };
2853
+ }
2854
+ reconcileSelectionAfterDocumentChange() {
2855
+ if (this.#selection === void 0) return;
2856
+ if (findShapeNodeBySourceHandle(this.#document, this.#selection.shapeHandle) === void 0) {
2857
+ this.#selection = void 0;
2858
+ }
2859
+ }
2860
+ };
2861
+ function createEditorSession(document) {
2862
+ return new EditorSession(document);
2863
+ }
2864
+ function applyCommandToDocument(document, command) {
2865
+ switch (command.kind) {
2866
+ case "replaceTextRunPlainText":
2867
+ return replaceTextRunPlainText(document, command.handle, command.text);
2868
+ case "replaceParagraphPlainText":
2869
+ return replaceParagraphPlainText(document, command.handle, command.text);
2870
+ case "setTextRunProperties":
2871
+ return setTextRunPropertiesCommand(document, command);
2872
+ case "clearTextRunProperties":
2873
+ return clearTextRunPropertiesCommand(document, command);
2874
+ case "moveShape":
2875
+ return moveShape(document, command);
2876
+ case "resizeShape":
2877
+ return resizeShape(document, command);
2878
+ case "setShapeTransform":
2879
+ return setShapeTransform(document, command);
2880
+ case "addTextBox":
2881
+ return addTextBoxCommand(document, command);
2882
+ case "addConnector":
2883
+ return addConnectorCommand(document, command);
2884
+ case "deleteShape":
2885
+ return deleteShape(document, command.handle);
2886
+ case "replaceImage":
2887
+ return replaceImageBytes(document, command.handle, command.bytes);
2888
+ case "addEmptySlideFromLayout":
2889
+ return addEmptySlideFromLayout(document, command);
2890
+ case "duplicateSlide":
2891
+ return duplicateSlide(document, command.handle);
2892
+ case "deleteSlide":
2893
+ return deleteSlide(document, command.handle);
2894
+ }
2895
+ }
2896
+ function collectCommandWarnings(document, commands) {
2897
+ if (!commands.some((command) => command.kind === "replaceImage")) return [];
2898
+ const warnings = [];
2899
+ const imageEdits = document.edits?.filter((edit) => edit.kind === "replaceImage") ?? [];
2900
+ for (const command of commands) {
2901
+ if (command.kind !== "replaceImage") continue;
2902
+ let edit;
2903
+ for (let index = imageEdits.length - 1; index >= 0; index -= 1) {
2904
+ const candidate = imageEdits[index];
2905
+ if (candidate.handle.partPath === command.handle.partPath && candidate.handle.nodeId === command.handle.nodeId && candidate.handle.relationshipId === command.handle.relationshipId && candidate.handle.orderingSlot === command.handle.orderingSlot) {
2906
+ edit = candidate;
2907
+ break;
2908
+ }
2909
+ }
2910
+ if (edit === void 0 || edit.sharedReferenceCount <= 1) continue;
2911
+ warnings.push({
2912
+ code: "shared-media-part",
2913
+ mediaPartPath: edit.mediaPartPath,
2914
+ referenceCount: edit.sharedReferenceCount,
2915
+ message: `replaceImage: media part '${edit.mediaPartPath}' is referenced by ${edit.sharedReferenceCount} pic shapes; all references now use the replacement image.`
2916
+ });
2917
+ }
2918
+ return warnings;
2919
+ }
2920
+ function dedupeCommandWarnings(warnings) {
2921
+ const deduped = /* @__PURE__ */ new Map();
2922
+ for (const warning of warnings) {
2923
+ const key = `${warning.code}\0${warning.mediaPartPath}`;
2924
+ if (!deduped.has(key)) deduped.set(key, warning);
2925
+ }
2926
+ return [...deduped.values()];
2927
+ }
2928
+ function addTextBoxCommand(document, command) {
2929
+ requireFiniteEmu(command.offsetX, "addTextBox", "offsetX");
2930
+ requireFiniteEmu(command.offsetY, "addTextBox", "offsetY");
2931
+ requirePositiveFiniteEmu(command.width, "addTextBox", "width");
2932
+ requirePositiveFiniteEmu(command.height, "addTextBox", "height");
2933
+ if (typeof command.text !== "string") {
2934
+ throw new Error("addTextBox: text must be a string");
2935
+ }
2936
+ if (command.name !== void 0 && command.name.trim() === "") {
2937
+ throw new Error("addTextBox: name must be a non-empty string when provided");
2938
+ }
2939
+ return addTextBox(document, command.slideHandle, command);
2940
+ }
2941
+ function addConnectorCommand(document, command) {
2942
+ requireFiniteEmu(command.offsetX, "addConnector", "offsetX");
2943
+ requireFiniteEmu(command.offsetY, "addConnector", "offsetY");
2944
+ requirePositiveFiniteEmu(command.width, "addConnector", "width");
2945
+ requirePositiveFiniteEmu(command.height, "addConnector", "height");
2946
+ return addConnector(document, command.slideHandle, command);
2947
+ }
2948
+ function setTextRunPropertiesCommand(document, command) {
2949
+ requireNonEmptyPropertySet(command.properties, "setTextRunProperties");
2950
+ validateTextRunPropertySet(command.properties, "setTextRunProperties");
2951
+ return setTextRunProperties(document, command.handle, command.properties);
2952
+ }
2953
+ function clearTextRunPropertiesCommand(document, command) {
2954
+ if (command.properties.length === 0) {
2955
+ throw new Error("clearTextRunProperties: properties must contain at least one property name");
2956
+ }
2957
+ for (const property of command.properties) {
2958
+ if (!EDITABLE_TEXT_RUN_PROPERTY_SET.has(property)) {
2959
+ throw new Error(`clearTextRunProperties: unsupported text run property '${property}'`);
2960
+ }
2961
+ }
2962
+ return clearTextRunProperties(document, command.handle, command.properties);
2963
+ }
2964
+ function moveShape(document, command) {
2965
+ requireFiniteEmu(command.offsetX, "moveShape", "offsetX");
2966
+ requireFiniteEmu(command.offsetY, "moveShape", "offsetY");
2967
+ const current = requireEditableShapeTransform(document, command.handle, "moveShape");
2968
+ return updateShapeTransform(document, command.handle, {
2969
+ offsetX: command.offsetX,
2970
+ offsetY: command.offsetY,
2971
+ width: current.width,
2972
+ height: current.height
2973
+ });
2974
+ }
2975
+ function resizeShape(document, command) {
2976
+ requirePositiveFiniteEmu(command.width, "resizeShape", "width");
2977
+ requirePositiveFiniteEmu(command.height, "resizeShape", "height");
2978
+ const current = requireEditableShapeTransform(document, command.handle, "resizeShape");
2979
+ return updateShapeTransform(document, command.handle, {
2980
+ offsetX: current.offsetX,
2981
+ offsetY: current.offsetY,
2982
+ width: command.width,
2983
+ height: command.height
2984
+ });
2985
+ }
2986
+ function setShapeTransform(document, command) {
2987
+ requireFiniteEmu(command.offsetX, "setShapeTransform", "offsetX");
2988
+ requireFiniteEmu(command.offsetY, "setShapeTransform", "offsetY");
2989
+ requirePositiveFiniteEmu(command.width, "setShapeTransform", "width");
2990
+ requirePositiveFiniteEmu(command.height, "setShapeTransform", "height");
2991
+ requireEditableShapeTransform(document, command.handle, "setShapeTransform");
2992
+ return updateShapeTransform(document, command.handle, {
2993
+ offsetX: command.offsetX,
2994
+ offsetY: command.offsetY,
2995
+ width: command.width,
2996
+ height: command.height
2997
+ });
2998
+ }
2999
+ var EDITABLE_TEXT_RUN_PROPERTIES = [
3000
+ "bold",
3001
+ "italic",
3002
+ "underline",
3003
+ "fontSize",
3004
+ "color",
3005
+ "typeface"
3006
+ ];
3007
+ var EDITABLE_TEXT_RUN_PROPERTY_SET = new Set(EDITABLE_TEXT_RUN_PROPERTIES);
3008
+ function requireNonEmptyPropertySet(properties, commandName) {
3009
+ if (Object.values(properties).every((value) => value === void 0)) {
3010
+ throw new Error(`${commandName}: properties must contain at least one defined property`);
3011
+ }
3012
+ }
3013
+ function validateTextRunPropertySet(properties, commandName) {
3014
+ for (const property of Object.keys(properties)) {
3015
+ if (!EDITABLE_TEXT_RUN_PROPERTY_SET.has(property)) {
3016
+ throw new Error(`${commandName}: unsupported text run property '${property}'`);
3017
+ }
3018
+ }
3019
+ requireBooleanOrUndefined(properties.bold, commandName, "bold");
3020
+ requireBooleanOrUndefined(properties.italic, commandName, "italic");
3021
+ requireBooleanOrUndefined(properties.underline, commandName, "underline");
3022
+ if (properties.fontSize !== void 0 && (!Number.isFinite(properties.fontSize) || properties.fontSize <= 0)) {
3023
+ throw new Error(`${commandName}: fontSize must be a finite positive pt value`);
3024
+ }
3025
+ if (properties.typeface !== void 0 && properties.typeface.trim() === "") {
3026
+ throw new Error(`${commandName}: typeface must be a non-empty string`);
3027
+ }
3028
+ if (properties.color !== void 0) {
3029
+ if (properties.color.kind !== "srgb") {
3030
+ throw new Error(`${commandName}: only srgb text run color is supported`);
3031
+ }
3032
+ if (!/^[0-9A-Fa-f]{6}$/.test(properties.color.hex)) {
3033
+ throw new Error(`${commandName}: color.hex must be a 6-digit hex value`);
3034
+ }
3035
+ }
3036
+ }
3037
+ function requireBooleanOrUndefined(value, commandName, fieldName) {
3038
+ if (value !== void 0 && typeof value !== "boolean") {
3039
+ throw new Error(`${commandName}: ${fieldName} must be a boolean value`);
3040
+ }
3041
+ }
3042
+ function requireEditableShapeTransform(document, handle, commandName) {
3043
+ const shape = findShapeNodeBySourceHandle(document, handle);
3044
+ if (shape === void 0) {
3045
+ throw new Error(`${commandName}: shape handle was not found in PptxSourceModel source`);
3046
+ }
3047
+ if (!hasTransform(shape)) {
3048
+ throw new Error(`${commandName}: shape handle does not reference a shape with xfrm`);
3049
+ }
3050
+ return shape.transform;
3051
+ }
3052
+ function requireFiniteEmu(value, commandName, fieldName) {
3053
+ if (!Number.isFinite(value)) {
3054
+ throw new Error(`${commandName}: ${fieldName} must be a finite EMU value`);
3055
+ }
3056
+ }
3057
+ function requirePositiveFiniteEmu(value, commandName, fieldName) {
3058
+ if (!Number.isFinite(value) || value <= 0) {
3059
+ throw new Error(`${commandName}: ${fieldName} must be a finite positive EMU value`);
3060
+ }
3061
+ }
3062
+ function hasTransform(shape) {
3063
+ return shape.kind !== "raw" && shape.transform !== void 0;
3064
+ }
3065
+ function normalizeEditorEdits(document) {
3066
+ const edits = document.edits;
3067
+ if (edits === void 0) return document;
3068
+ const seenTextRuns = /* @__PURE__ */ new Set();
3069
+ const seenTextRunProperties = /* @__PURE__ */ new Map();
3070
+ const seenParagraphs = /* @__PURE__ */ new Set();
3071
+ const seenShapeTransforms = /* @__PURE__ */ new Set();
3072
+ const normalizedReversed = [];
3073
+ let changed = false;
3074
+ for (let index = edits.length - 1; index >= 0; index -= 1) {
3075
+ const edit = edits[index];
3076
+ if (edit.kind === "replaceTextRunPlainText") {
3077
+ const key = editHandleNodeKey(edit);
3078
+ const paragraphKey = textRunParagraphEditKey(edit);
3079
+ if (paragraphKey !== void 0 && seenParagraphs.has(paragraphKey)) {
3080
+ changed = true;
3081
+ continue;
3082
+ }
3083
+ if (seenTextRuns.has(key)) {
3084
+ changed = true;
3085
+ continue;
3086
+ }
3087
+ seenTextRuns.add(key);
3088
+ }
3089
+ if (edit.kind === "updateTextRunProperties") {
3090
+ const paragraphKey = textRunParagraphEditKey(edit);
3091
+ if (paragraphKey !== void 0 && seenParagraphs.has(paragraphKey)) {
3092
+ changed = true;
3093
+ continue;
3094
+ }
3095
+ const normalized = normalizeTextRunPropertiesEdit(edit, seenTextRunProperties);
3096
+ if (normalized === void 0) {
3097
+ changed = true;
3098
+ continue;
3099
+ }
3100
+ if (!editorEditsEqual(normalized, edit)) changed = true;
3101
+ normalizedReversed.push(normalized);
3102
+ continue;
3103
+ }
3104
+ if (edit.kind === "replaceParagraphPlainText") {
3105
+ const key = editHandleNodeKey(edit);
3106
+ if (seenParagraphs.has(key)) {
3107
+ changed = true;
3108
+ continue;
3109
+ }
3110
+ seenParagraphs.add(key);
3111
+ }
3112
+ if (edit.kind === "updateShapeTransform") {
3113
+ const key = editHandleNodeKey(edit);
3114
+ if (seenShapeTransforms.has(key)) {
3115
+ changed = true;
3116
+ continue;
3117
+ }
3118
+ seenShapeTransforms.add(key);
3119
+ }
3120
+ normalizedReversed.push(edit);
3121
+ }
3122
+ if (!changed && normalizedReversed.length === edits.length) return document;
3123
+ return {
3124
+ ...document,
3125
+ edits: normalizedReversed.reverse()
3126
+ };
3127
+ }
3128
+ function editorEditsEqual(left, right) {
3129
+ return JSON.stringify(left) === JSON.stringify(right);
3130
+ }
3131
+ function editHandleNodeKey(edit) {
3132
+ return [
3133
+ edit.handle.partPath,
3134
+ edit.handle.nodeId ?? "",
3135
+ edit.handle.relationshipId ?? "",
3136
+ edit.handle.orderingSlot ?? ""
3137
+ ].join("\0");
3138
+ }
3139
+ function textRunParagraphEditKey(edit) {
3140
+ const nodeId = String(edit.handle.nodeId ?? "");
3141
+ const byShapeId = /^(text:shape:.+:p:(\d+)):r:\d+$/.exec(nodeId);
3142
+ const byShapeSlot = /^(text:shapeSlot:\d+:p:(\d+)):r:\d+$/.exec(nodeId);
3143
+ const paragraphNodeId = byShapeId?.[1] ?? byShapeSlot?.[1];
3144
+ const paragraphOrderingSlot = byShapeId?.[2] ?? byShapeSlot?.[2] ?? "";
3145
+ if (paragraphNodeId === void 0) return void 0;
3146
+ return [
3147
+ edit.handle.partPath,
3148
+ paragraphNodeId,
3149
+ edit.handle.relationshipId ?? "",
3150
+ paragraphOrderingSlot
3151
+ ].join("\0");
3152
+ }
3153
+ function normalizeTextRunPropertiesEdit(edit, seenTextRunProperties) {
3154
+ const key = editHandleNodeKey(edit);
3155
+ let seenProperties = seenTextRunProperties.get(key);
3156
+ if (seenProperties === void 0) {
3157
+ seenProperties = /* @__PURE__ */ new Set();
3158
+ seenTextRunProperties.set(key, seenProperties);
3159
+ }
3160
+ const set = {};
3161
+ if (edit.set?.bold !== void 0 && !seenProperties.has("bold")) {
3162
+ seenProperties.add("bold");
3163
+ set.bold = edit.set.bold;
3164
+ }
3165
+ if (edit.set?.italic !== void 0 && !seenProperties.has("italic")) {
3166
+ seenProperties.add("italic");
3167
+ set.italic = edit.set.italic;
3168
+ }
3169
+ if (edit.set?.underline !== void 0 && !seenProperties.has("underline")) {
3170
+ seenProperties.add("underline");
3171
+ set.underline = edit.set.underline;
3172
+ }
3173
+ if (edit.set?.fontSize !== void 0 && !seenProperties.has("fontSize")) {
3174
+ seenProperties.add("fontSize");
3175
+ set.fontSize = edit.set.fontSize;
3176
+ }
3177
+ if (edit.set?.color !== void 0 && !seenProperties.has("color")) {
3178
+ seenProperties.add("color");
3179
+ set.color = edit.set.color;
3180
+ }
3181
+ if (edit.set?.typeface !== void 0 && !seenProperties.has("typeface")) {
3182
+ seenProperties.add("typeface");
3183
+ set.typeface = edit.set.typeface;
3184
+ }
3185
+ const clear = (edit.clear ?? []).filter((property) => !seenProperties.has(property));
3186
+ for (const property of clear) seenProperties.add(property);
3187
+ if (clear.length === 0 && Object.keys(set).length === 0) return void 0;
3188
+ const normalized = {
3189
+ kind: "updateTextRunProperties",
3190
+ handle: edit.handle,
3191
+ ...Object.keys(set).length > 0 ? { set } : {},
3192
+ ...clear.length > 0 ? { clear } : {}
3193
+ };
3194
+ return normalized;
3195
+ }
3196
+
3197
+ // src/browser-editor.ts
3198
+ var EMU_PER_INCH = 914400;
3199
+ var DEFAULT_DPI = 96;
3200
+ var EMU_PER_PIXEL = EMU_PER_INCH / DEFAULT_DPI;
3201
+ var DEFAULT_TEXT_BOX_BOUNDS_PX = {
3202
+ x: 96,
3203
+ y: 96,
3204
+ width: 288,
3205
+ height: 72
3206
+ };
3207
+ var DEFAULT_TEXT_BOX_TEXT = "New text box";
3208
+ var IMAGE_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
3209
+ var IMAGE_ACCEPT_BY_CONTENT_TYPE = {
3210
+ "image/png": "image/png,.png",
3211
+ "image/jpeg": "image/jpeg,.jpg,.jpeg",
3212
+ "image/gif": "image/gif,.gif",
3213
+ "image/bmp": "image/bmp,.bmp",
3214
+ "image/tiff": "image/tiff,.tif,.tiff",
3215
+ "image/webp": "image/webp,.webp"
3216
+ };
3217
+ var BrowserPptxEditorSession = class _BrowserPptxEditorSession {
3218
+ #session;
3219
+ #slides = [];
3220
+ #renderOptions;
3221
+ constructor(source, renderOptions) {
3222
+ this.#session = createEditorSession(source);
3223
+ this.#renderOptions = renderOptions;
3224
+ }
3225
+ static async create(input, renderOptions = {}) {
3226
+ const editor = new _BrowserPptxEditorSession(readPptx(input), renderOptions);
3227
+ await editor.renderCurrentSlides();
3228
+ return editor;
3229
+ }
3230
+ get document() {
3231
+ return this.#session.document;
3232
+ }
3233
+ get slides() {
3234
+ return this.#slides;
3235
+ }
3236
+ get history() {
3237
+ return {
3238
+ canUndo: this.#session.canUndo,
3239
+ canRedo: this.#session.canRedo,
3240
+ undoDepth: this.#session.undoDepth,
3241
+ redoDepth: this.#session.redoDepth
3242
+ };
3243
+ }
3244
+ get selection() {
3245
+ return this.#session.selection;
3246
+ }
3247
+ response(warnings) {
3248
+ return {
3249
+ slides: this.#slides,
3250
+ history: this.history,
3251
+ ...this.selection !== void 0 ? { selection: this.selection } : {},
3252
+ ...warnings !== void 0 && warnings.length > 0 ? { warnings } : {}
3253
+ };
3254
+ }
3255
+ shapes(slideNumber) {
3256
+ const slide = this.#session.document.slides[slideNumber - 1];
3257
+ if (slide === void 0) return [];
3258
+ return slide.shapes.flatMap(
3259
+ (shape, index) => shapeInfo(this.#session.document, shape, index, true, slide.shapes)
3260
+ );
3261
+ }
3262
+ async renderCurrentSlides() {
3263
+ const report = await renderPptxSourceModelToSvg(this.#session.document, {
3264
+ textOutput: "text",
3265
+ skipSystemFonts: true,
3266
+ ...this.#renderOptions
3267
+ });
3268
+ this.#slides = report.slides.map((slide) => ({
3269
+ ...slide,
3270
+ ...this.#session.document.slides[slide.slideNumber - 1]?.handle !== void 0 ? { handle: this.#session.document.slides[slide.slideNumber - 1]?.handle } : {}
3271
+ }));
3272
+ return this.#slides;
3273
+ }
3274
+ async apply(command) {
3275
+ const result = this.#session.apply(command);
3276
+ if (!result.ok) {
3277
+ throw new Error(result.message);
3278
+ }
3279
+ await this.renderCurrentSlides();
3280
+ return this.response(result.warnings);
3281
+ }
3282
+ async addTextBox(slideNumber = 1, options = {}) {
3283
+ const slide = this.#session.document.slides[slideNumber - 1];
3284
+ if (slide?.handle === void 0) {
3285
+ throw new Error("addTextBox: slide handle was not found in PptxSourceModel source");
3286
+ }
3287
+ const existingShapeKeys = new Set(slide.shapes.map(shapeSourceKey));
3288
+ const result = this.#session.apply({
3289
+ kind: "addTextBox",
3290
+ slideHandle: slide.handle,
3291
+ offsetX: pxToEmu(options.x ?? DEFAULT_TEXT_BOX_BOUNDS_PX.x),
3292
+ offsetY: pxToEmu(options.y ?? DEFAULT_TEXT_BOX_BOUNDS_PX.y),
3293
+ width: pxToEmu(options.width ?? DEFAULT_TEXT_BOX_BOUNDS_PX.width),
3294
+ height: pxToEmu(options.height ?? DEFAULT_TEXT_BOX_BOUNDS_PX.height),
3295
+ text: options.text ?? DEFAULT_TEXT_BOX_TEXT,
3296
+ ...options.name !== void 0 ? { name: options.name } : {}
3297
+ });
3298
+ if (!result.ok) {
3299
+ throw new Error(result.message);
3300
+ }
3301
+ this.#selectNewShape(slideNumber, existingShapeKeys);
3302
+ await this.renderCurrentSlides();
3303
+ return this.response(result.warnings);
3304
+ }
3305
+ async deleteShape(handle) {
3306
+ const result = this.#session.apply({ kind: "deleteShape", handle });
3307
+ if (!result.ok) {
3308
+ throw new Error(result.message);
3309
+ }
3310
+ await this.renderCurrentSlides();
3311
+ return this.response(result.warnings);
3312
+ }
3313
+ async deleteSelectedShape() {
3314
+ const selection = this.#session.selection;
3315
+ if (selection === void 0) {
3316
+ throw new Error("deleteShape: no selected shape");
3317
+ }
3318
+ return this.deleteShape(selection.shapeHandle);
3319
+ }
3320
+ async applyTextBodyDocJson(handle, docJson) {
3321
+ const textBody = this.#requireEditableShapeTextBody(handle);
3322
+ const commands = proseMirrorDocJsonToEditorCommands(textBody, docJson);
3323
+ if (commands.length === 0) return this.response();
3324
+ const result = this.#session.applyAll(commands);
3325
+ if (!result.ok) {
3326
+ throw new Error(result.message);
3327
+ }
3328
+ await this.renderCurrentSlides();
3329
+ return this.response(result.warnings);
3330
+ }
3331
+ selectShape(handle) {
3332
+ const result = this.#session.selectShape(handle);
3333
+ if (!result.ok) {
3334
+ throw new Error(result.message);
3335
+ }
3336
+ return this.response();
3337
+ }
3338
+ async undo() {
3339
+ const result = this.#session.undo();
3340
+ if (!result.ok) {
3341
+ throw new Error(result.reason);
3342
+ }
3343
+ await this.renderCurrentSlides();
3344
+ return this.response();
3345
+ }
3346
+ async redo() {
3347
+ const result = this.#session.redo();
3348
+ if (!result.ok) {
3349
+ throw new Error(result.reason);
3350
+ }
3351
+ await this.renderCurrentSlides();
3352
+ return this.response();
3353
+ }
3354
+ save() {
3355
+ const output = writePptx(this.#session.document);
3356
+ readPptx(output);
3357
+ return { ok: true, pptx: output, history: this.history };
3358
+ }
3359
+ #requireEditableShapeTextBody(handle) {
3360
+ const shape = findShapeNodeBySourceHandle(this.#session.document, handle);
3361
+ if (shape === void 0) {
3362
+ throw new Error("text body edit: shape handle was not found in PptxSourceModel source");
3363
+ }
3364
+ if (shape.kind !== "shape" || shape.textBody === void 0) {
3365
+ throw new Error("text body edit: shape does not have editable text body");
3366
+ }
3367
+ return shape.textBody;
3368
+ }
3369
+ #selectNewShape(slideNumber, existingShapeKeys) {
3370
+ const slide = this.#session.document.slides[slideNumber - 1];
3371
+ const addedShape = slide?.shapes.find((shape) => !existingShapeKeys.has(shapeSourceKey(shape)));
3372
+ if (addedShape?.handle === void 0) return;
3373
+ this.#session.selectShape(addedShape.handle);
3374
+ }
3375
+ };
3376
+ function createBrowserPptxEditorSession(input, renderOptions) {
3377
+ return BrowserPptxEditorSession.create(input, renderOptions);
3378
+ }
3379
+ function shapeInfo(source, shape, index, editableTransform = true, slideShapes = []) {
3380
+ const canEditTransform = shape.kind !== "raw" && shape.transform !== void 0 && editableTransform && isEditableTransformShape(shape);
3381
+ const base = {
3382
+ id: String(shape.nodeId ?? shape.handle?.nodeId ?? `${shape.kind}:${String(index)}`),
3383
+ kind: shape.kind,
3384
+ ...shapeName(shape) !== void 0 ? { name: shapeName(shape) } : {},
3385
+ ...shape.handle !== void 0 ? { handle: shape.handle } : {},
3386
+ ...canEditTransform ? {
3387
+ bounds: transformBoundsPx(shape.transform),
3388
+ editableTransform: true
3389
+ } : {},
3390
+ ...editableTransform && isDeletableShape(shape, slideShapes) ? { editableDelete: true } : {},
3391
+ ..."textBody" in shape && shape.textBody !== void 0 ? {
3392
+ textRuns: collectTextRuns(
3393
+ shape.textBody.paragraphs.flatMap((paragraph) => paragraph.runs)
3394
+ )
3395
+ } : {},
3396
+ ...shape.kind === "shape" && canEditTransform && shape.textBody !== void 0 ? editableTextBody(shape.textBody) : {},
3397
+ ...shape.kind === "image" ? editableImageReplacement(source, shape) : {}
3398
+ };
3399
+ if (shape.kind !== "group") return [base];
3400
+ return [
3401
+ base,
3402
+ ...shape.children.flatMap(
3403
+ (child, childIndex) => shapeInfo(source, child, childIndex, false, slideShapes)
3404
+ )
3405
+ ];
3406
+ }
3407
+ function shapeName(shape) {
3408
+ return "name" in shape ? shape.name : void 0;
3409
+ }
3410
+ function isEditableTransformShape(shape) {
3411
+ if (shape.kind === "raw" || shape.transform === void 0 || shape.handle?.nodeId === void 0) {
3412
+ return false;
3413
+ }
3414
+ return !shape.rawSidecars?.some((sidecar) => sidecar.node.name === "mc:AlternateContent");
3415
+ }
3416
+ function isDeletableShape(shape, slideShapes) {
3417
+ if (shape.kind !== "shape" || shape.handle?.nodeId === void 0) {
3418
+ return false;
3419
+ }
3420
+ if (isShapeReferencedByConnector(shape, slideShapes)) {
3421
+ return false;
3422
+ }
3423
+ return !shape.rawSidecars?.some((sidecar) => sidecar.node.name === "mc:AlternateContent");
3424
+ }
3425
+ function isShapeReferencedByConnector(shape, slideShapes) {
3426
+ return slideShapes.some(
3427
+ (candidate) => candidate.kind === "connector" && (candidate.connection?.start?.shapeId === shape.nodeId || candidate.connection?.end?.shapeId === shape.nodeId)
3428
+ );
3429
+ }
3430
+ function collectTextRuns(runs) {
3431
+ return runs.flatMap((run) => {
3432
+ if (run.handle === void 0) return [];
3433
+ return [{ text: run.text, handle: run.handle }];
3434
+ });
3435
+ }
3436
+ function editableTextBody(textBody) {
3437
+ try {
3438
+ return { editableTextBody: { docJson: textBodyToProseMirrorDocJson(textBody) } };
3439
+ } catch {
3440
+ return {};
3441
+ }
3442
+ }
3443
+ function editableImageReplacement(source, image) {
3444
+ const media = imageMediaPart(source, image);
3445
+ if (media === void 0) return {};
3446
+ const accept = IMAGE_ACCEPT_BY_CONTENT_TYPE[media.contentType];
3447
+ if (accept === void 0) return {};
3448
+ return {
3449
+ editableImageReplacement: {
3450
+ contentType: media.contentType,
3451
+ accept,
3452
+ mediaPartPath: media.partPath,
3453
+ sharedReferenceCount: countImageReferencesToMedia(source, media.partPath)
3454
+ }
3455
+ };
3456
+ }
3457
+ function imageMediaPart(source, image) {
3458
+ if (image.blipRelationshipId === void 0 || image.handle?.partPath === void 0) {
3459
+ return void 0;
3460
+ }
3461
+ const mediaPartPath = imageMediaPartPath(source, image.handle.partPath, image.blipRelationshipId);
3462
+ if (mediaPartPath === void 0) return void 0;
3463
+ return source.packageGraph.media.find((part) => part.partPath === mediaPartPath);
3464
+ }
3465
+ function imageMediaPartPath(source, sourcePartPath, relationshipId) {
3466
+ const relationships = source.packageGraph.relationships.find(
3467
+ (candidate) => candidate.sourcePartPath === sourcePartPath
3468
+ );
3469
+ const relationship = relationships?.relationships.find(
3470
+ (candidate) => candidate.id === relationshipId && candidate.type === IMAGE_REL_TYPE
3471
+ );
3472
+ if (relationship === void 0) return void 0;
3473
+ return resolveInternalRelationshipTarget(sourcePartPath, relationship);
3474
+ }
3475
+ function countImageReferencesToMedia(source, mediaPartPath) {
3476
+ const parsedImageRelationshipKeys = /* @__PURE__ */ new Set();
3477
+ let count = 0;
3478
+ for (const slide of source.slides) {
3479
+ count += countImageReferencesInTree(
3480
+ source,
3481
+ slide.partPath,
3482
+ slide.shapes,
3483
+ mediaPartPath,
3484
+ parsedImageRelationshipKeys
3485
+ );
3486
+ }
3487
+ for (const layout of source.slideLayouts) {
3488
+ count += countImageReferencesInTree(
3489
+ source,
3490
+ layout.partPath,
3491
+ layout.shapes,
3492
+ mediaPartPath,
3493
+ parsedImageRelationshipKeys
3494
+ );
3495
+ }
3496
+ for (const master of source.slideMasters) {
3497
+ count += countImageReferencesInTree(
3498
+ source,
3499
+ master.partPath,
3500
+ master.shapes,
3501
+ mediaPartPath,
3502
+ parsedImageRelationshipKeys
3503
+ );
3504
+ }
3505
+ for (const relationships of source.packageGraph.relationships) {
3506
+ for (const relationship of relationships.relationships) {
3507
+ if (relationship.type !== IMAGE_REL_TYPE) continue;
3508
+ if (parsedImageRelationshipKeys.has(
3509
+ imageRelationshipKey(relationships.sourcePartPath, relationship.id)
3510
+ )) {
3511
+ continue;
3512
+ }
3513
+ if (resolveInternalRelationshipTarget(relationships.sourcePartPath, relationship) === mediaPartPath) {
3514
+ count += 1;
3515
+ }
3516
+ }
3517
+ }
3518
+ return count;
3519
+ }
3520
+ function countImageReferencesInTree(source, sourcePartPath, shapes, mediaPartPath, parsedImageRelationshipKeys) {
3521
+ let count = 0;
3522
+ for (const shape of shapes) {
3523
+ if (shape.kind === "group") {
3524
+ count += countImageReferencesInTree(
3525
+ source,
3526
+ sourcePartPath,
3527
+ shape.children,
3528
+ mediaPartPath,
3529
+ parsedImageRelationshipKeys
3530
+ );
3531
+ continue;
3532
+ }
3533
+ if (shape.kind !== "image" || shape.blipRelationshipId === void 0) continue;
3534
+ if (imageMediaPartPath(source, sourcePartPath, shape.blipRelationshipId) === mediaPartPath) {
3535
+ count += 1;
3536
+ parsedImageRelationshipKeys.add(
3537
+ imageRelationshipKey(sourcePartPath, shape.blipRelationshipId)
3538
+ );
3539
+ }
3540
+ }
3541
+ return count;
3542
+ }
3543
+ function imageRelationshipKey(partPath, relationshipId) {
3544
+ return `${partPath}\0${relationshipId}`;
3545
+ }
3546
+ function resolveInternalRelationshipTarget(sourcePartPath, relationship) {
3547
+ if (relationship.targetMode === "External") return void 0;
3548
+ return unsafeBrandAssertion(
3549
+ normalizePackagePath(
3550
+ relationship.target.startsWith("/") ? relationship.target.slice(1) : joinPackageRelativeTarget(sourcePartPath, relationship.target)
3551
+ )
3552
+ );
3553
+ }
3554
+ function joinPackageRelativeTarget(sourcePartPath, target) {
3555
+ const slash = sourcePartPath.lastIndexOf("/");
3556
+ const baseDir = slash === -1 ? "" : sourcePartPath.slice(0, slash);
3557
+ return baseDir === "" ? target : `${baseDir}/${target}`;
3558
+ }
3559
+ function normalizePackagePath(path) {
3560
+ const segments = [];
3561
+ for (const segment of path.split("/")) {
3562
+ if (segment === "" || segment === ".") continue;
3563
+ if (segment === "..") {
3564
+ segments.pop();
3565
+ continue;
3566
+ }
3567
+ segments.push(segment);
3568
+ }
3569
+ return segments.join("/");
3570
+ }
3571
+ function transformBoundsPx(transform) {
3572
+ return {
3573
+ x: emuToPixels(transform.offsetX),
3574
+ y: emuToPixels(transform.offsetY),
3575
+ width: emuToPixels(transform.width),
3576
+ height: emuToPixels(transform.height)
3577
+ };
3578
+ }
3579
+ function emuToPixels(value) {
3580
+ return value / EMU_PER_INCH * DEFAULT_DPI;
3581
+ }
3582
+ function pxToEmu(value) {
3583
+ return asEmu(Math.round(value * EMU_PER_PIXEL));
3584
+ }
3585
+ function shapeSourceKey(shape) {
3586
+ const handle = shape.handle;
3587
+ return [
3588
+ shape.kind,
3589
+ handle?.partPath ?? "",
3590
+ handle?.nodeId ?? "",
3591
+ handle?.relationshipId ?? "",
3592
+ handle?.orderingSlot ?? ""
3593
+ ].join("\0");
3594
+ }
3595
+
3596
+ // src/browser.ts
3597
+ async function convertPptxToPng(input, options) {
3598
+ const svgResult = await convertPptxToSvg(input, {
3599
+ ...options,
3600
+ textOutput: "path"
3601
+ });
3602
+ const width = options?.width ?? DEFAULT_OUTPUT_WIDTH;
3603
+ const height = options?.height;
3604
+ const fontBuffers = options?.fonts?.map((font) => toUint8Array(font.data)) ?? [];
3605
+ const slides = [];
3606
+ for (const { slideNumber, svg } of svgResult.slides) {
3607
+ const pngResult = await svgToPng(svg, { width, height, fontBuffers });
3608
+ slides.push({
3609
+ slideNumber,
3610
+ png: new Uint8Array(pngResult.png),
3611
+ width: pngResult.width,
3612
+ height: pngResult.height
3613
+ });
3614
+ }
3615
+ return {
3616
+ slides,
3617
+ diagnostics: svgResult.diagnostics,
3618
+ supportCoverage: svgResult.supportCoverage
3619
+ };
3620
+ }
3621
+ function initResvgWasm2(wasm) {
3622
+ return initResvgWasm(wasm);
3623
+ }
3624
+ function toUint8Array(data) {
3625
+ return data instanceof Uint8Array ? data : new Uint8Array(data);
3626
+ }
3627
+ export {
3628
+ BrowserPptxEditorSession,
3629
+ DEFAULT_FONT_MAPPING,
3630
+ clearFontCache,
3631
+ collectUsedFonts,
3632
+ convertPptxToPng,
3633
+ convertPptxToSvg,
3634
+ createBrowserPptxEditorSession,
3635
+ createFontMapping,
3636
+ createOpentypeSetupFromBuffers,
3637
+ createOpentypeTextMeasurerFromBuffers,
3638
+ getMappedFont,
3639
+ getWarningEntries,
3640
+ getWarningSummary,
3641
+ initResvgWasm2 as initResvgWasm,
3642
+ renderPptxSourceModelToSvg
3643
+ };