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