magic-editor-x 2.3.0 → 2.4.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.
Files changed (84) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/README.md +299 -142
  3. package/dist/admin/AuditPage-C2u6z4aN.js +381 -0
  4. package/dist/admin/AuditPage-guB0SiGS.mjs +381 -0
  5. package/dist/admin/{ConfigurationPage-C-UktL1x.js → ConfigurationPage-D6uya-J1.js} +228 -13
  6. package/dist/admin/{ConfigurationPage-BxLHIQdo.mjs → ConfigurationPage-DiEpF1Rr.mjs} +222 -7
  7. package/dist/admin/ConfirmAction-CUhpngYU.js +71 -0
  8. package/dist/admin/ConfirmAction-CZjpduc3.mjs +72 -0
  9. package/dist/admin/{CustomBlocksPage-D8aMbVXc.mjs → CustomBlocksPage-Byt10-6c.mjs} +6 -4
  10. package/dist/admin/{CustomBlocksPage-CxcTfdOT.js → CustomBlocksPage-DP3h_wNd.js} +21 -19
  11. package/dist/admin/MentionsWidget-C2OCAmqq.js +227 -0
  12. package/dist/admin/MentionsWidget-sMkM9mHX.mjs +225 -0
  13. package/dist/admin/{TemplatesPage-Hn6gyu2l.js → TemplatesPage-DrSJdteI.js} +313 -17
  14. package/dist/admin/{TemplatesPage-jhYi6Zdf.mjs → TemplatesPage-Yp4OqFE2.mjs} +305 -9
  15. package/dist/admin/{ConfirmAction-DuQwvRYi.mjs → api-2ZRpHM3d.mjs} +19 -70
  16. package/dist/admin/{ConfirmAction-zLuIFj8t.js → api-bix9RLLI.js} +19 -70
  17. package/dist/admin/auditText-DIIYVR6k.mjs +110 -0
  18. package/dist/admin/auditText-DUhWu2Nx.js +109 -0
  19. package/dist/admin/comments-C7P41lan.js +86 -0
  20. package/dist/admin/comments-hfIbLQNO.mjs +87 -0
  21. package/dist/admin/{de-BMY2LBaa.mjs → de-BNPIGqhs.mjs} +41 -2
  22. package/dist/admin/{de-2Ie5jy7j.js → de-BhhGss1l.js} +41 -2
  23. package/dist/admin/{de-DOiGaTNX.mjs → de-CKz6CG3V.mjs} +191 -5
  24. package/dist/admin/{de-C3AsGauQ.js → de-CbBDnXeT.js} +140 -1
  25. package/dist/admin/{de-BUS1hUw0.mjs → de-DiCZrmH8.mjs} +140 -1
  26. package/dist/admin/{de-B1X46JJZ.js → de-zcV8D7nt.js} +191 -5
  27. package/dist/admin/{en-Ah-Cw0Wd.js → en-B9ApE1y1.js} +41 -2
  28. package/dist/admin/{en-CDg_18Bt.js → en-BMWhILnj.js} +191 -5
  29. package/dist/admin/{en-BkEjpC3i.js → en-CpehF0Kv.js} +140 -1
  30. package/dist/admin/{en-GCzgS9Aw.mjs → en-DCPMqFIa.mjs} +140 -1
  31. package/dist/admin/{en-CU6UzV4g.mjs → en-cYzqbASF.mjs} +191 -5
  32. package/dist/admin/{en-CvFiqti2.mjs → en-gFLeK9Ng.mjs} +41 -2
  33. package/dist/admin/{es-DbKHZz5l.mjs → es-BmwBgEgz.mjs} +41 -2
  34. package/dist/admin/{es-Cr8JH85N.js → es-C0W31rl8.js} +41 -2
  35. package/dist/admin/{es-BCpJmUEM.js → es-CQPh8PXw.js} +191 -5
  36. package/dist/admin/{es-C4pEnDRv.js → es-CawpzwyC.js} +140 -1
  37. package/dist/admin/{es-DHBBZKl2.mjs → es-Chs37IBR.mjs} +140 -1
  38. package/dist/admin/{es-BmfffNM2.mjs → es-DCamt1ek.mjs} +191 -5
  39. package/dist/admin/{fr-DQJ_7aq5.mjs → fr-CMWBNE5D.mjs} +41 -2
  40. package/dist/admin/{fr-C2aLSwEu.js → fr-COOsqexl.js} +140 -1
  41. package/dist/admin/{fr-Dvq4xk2e.mjs → fr-Dp5-XP29.mjs} +140 -1
  42. package/dist/admin/{fr-ZcN0yM_2.js → fr-DpC44Ol8.js} +191 -5
  43. package/dist/admin/{fr-OJ4VW1kh.js → fr-iGeIfEcU.js} +41 -2
  44. package/dist/admin/{fr-DZd2XJP6.mjs → fr-oW0t8bT5.mjs} +191 -5
  45. package/dist/admin/{index-Cm-fFUhE.js → index-64wc26Bl.js} +13851 -6746
  46. package/dist/admin/{index-XgfwqLfV.mjs → index-BVjf1gVC.mjs} +13788 -6682
  47. package/dist/admin/{index-BHBRr562.js → index-D6Z7i8ba.js} +1003 -53
  48. package/dist/admin/{index-CQk1XeNb.mjs → index-D_Fv8Non.mjs} +1032 -82
  49. package/dist/admin/index.js +2 -1
  50. package/dist/admin/index.mjs +3 -2
  51. package/dist/admin/math-CIQ4Z_mY.mjs +47 -0
  52. package/dist/admin/math-vsK_06ZR.js +49 -0
  53. package/dist/admin/{pt-D0I0_JYs.js → pt-BHmXk2d9.js} +41 -2
  54. package/dist/admin/{pt-CImqDnLB.js → pt-Bo0Pm_Pt.js} +191 -5
  55. package/dist/admin/{pt-CilDggGF.mjs → pt-DALDvfBn.mjs} +140 -1
  56. package/dist/admin/{pt-BSLzA17U.mjs → pt-DFNgZ5_k.mjs} +41 -2
  57. package/dist/admin/{pt-DX0OAIoL.js → pt-DXy7G1x7.js} +140 -1
  58. package/dist/admin/{pt-C3UdeIpd.mjs → pt-uGpfRQLC.mjs} +191 -5
  59. package/dist/admin/{useT-D3sM9Zf7.js → useT-BXJLIPN4.js} +1 -1
  60. package/dist/admin/{useT-CmaeZbCr.mjs → useT-CLPhBmBC.mjs} +1 -1
  61. package/dist/blocks/index.d.mts +2 -0
  62. package/dist/blocks/index.d.ts +2 -0
  63. package/dist/blocks/index.js +13 -2
  64. package/dist/blocks/index.mjs +13 -2
  65. package/dist/math/index.d.mts +27 -0
  66. package/dist/math/index.d.ts +27 -0
  67. package/dist/math/index.js +164 -0
  68. package/dist/math/index.mjs +134 -0
  69. package/dist/react/index.js +673 -91
  70. package/dist/react/index.mjs +673 -91
  71. package/dist/render/index.d.mts +26 -0
  72. package/dist/render/index.d.ts +26 -0
  73. package/dist/render/index.js +779 -106
  74. package/dist/render/index.mjs +779 -106
  75. package/dist/server/index.js +10419 -4103
  76. package/dist/server/index.mjs +10419 -4103
  77. package/dist/vue/index.js +673 -91
  78. package/dist/vue/index.mjs +673 -91
  79. package/package.json +8 -2
  80. package/schema/magic-editor-x.schema.json +127 -2
  81. package/types/blocks.d.ts +2 -0
  82. package/types/index.d.ts +42 -0
  83. package/types/math.d.ts +27 -0
  84. package/types/render.d.ts +26 -0
@@ -23,7 +23,9 @@ var MARKED_BLOCKS = Object.freeze({
23
23
  keys: Object.freeze(["file", "title", "caption", "loop", "tracks"]),
24
24
  anchor: Object.freeze(["file", "object"])
25
25
  }),
26
- synced: Object.freeze({ keys: Object.freeze(["ref"]), anchor: Object.freeze(["ref", "string"]) })
26
+ synced: Object.freeze({ keys: Object.freeze(["ref"]), anchor: Object.freeze(["ref", "string"]) }),
27
+ // 2.4: math block. A Settings custom block named `math` could exist before 2.4.
28
+ math: Object.freeze({ keys: Object.freeze(["tex", "display"]), anchor: Object.freeze(["tex", "string"]) })
27
29
  });
28
30
  var isBuiltInMarker = (value) => Number.isInteger(value) && /** @type {number} */
29
31
  value >= 1;
@@ -42,6 +44,10 @@ var isMarkedBuiltIn = (type, data) => {
42
44
  return hasBuiltInShape(MARKED_BLOCKS[type], data);
43
45
  };
44
46
 
47
+ // shared/field-identity.mjs
48
+ var FIELD_KEY_PATTERN = /^[A-Za-z0-9_-]{16,32}$/;
49
+ var isValidFieldKey = (value) => typeof value === "string" && FIELD_KEY_PATTERN.test(value);
50
+
45
51
  // shared/editor-data.mjs
46
52
  var EDITOR_DATA_LIMITS = Object.freeze({
47
53
  maxBlocks: 5e3,
@@ -154,8 +160,8 @@ var normalizeEditorData = (value) => {
154
160
  if (!isPlainObject2(candidate)) {
155
161
  throw new EditorDataError("Editor content must be an Editor.js object", "INVALID_SHAPE");
156
162
  }
157
- const clean = cloneJsonSafe(candidate);
158
- const rawBlocks = Array.isArray(clean.blocks) ? clean.blocks : [];
163
+ const clean2 = cloneJsonSafe(candidate);
164
+ const rawBlocks = Array.isArray(clean2.blocks) ? clean2.blocks : [];
159
165
  if (rawBlocks.length > EDITOR_DATA_LIMITS.maxBlocks) {
160
166
  throw new EditorDataError("Editor content has too many blocks", "TOO_MANY_BLOCKS");
161
167
  }
@@ -174,9 +180,10 @@ var normalizeEditorData = (value) => {
174
180
  if (isPlainObject2(block.tunes) && Object.keys(block.tunes).length > 0) normalized.tunes = block.tunes;
175
181
  blocks.push(normalized);
176
182
  });
177
- const time = Number.isFinite(clean.time) && clean.time > 0 ? Math.floor(clean.time) : 0;
178
- const version = typeof clean.version === "string" && clean.version.length <= 32 ? clean.version : "2.31.7";
183
+ const time = Number.isFinite(clean2.time) && clean2.time > 0 ? Math.floor(clean2.time) : 0;
184
+ const version = typeof clean2.version === "string" && clean2.version.length <= 32 ? clean2.version : "2.31.7";
179
185
  const result = { time, blocks, version };
186
+ if (isValidFieldKey(clean2.fieldKey)) result.fieldKey = clean2.fieldKey;
180
187
  const size = byteLength(JSON.stringify(result));
181
188
  if (size > EDITOR_DATA_LIMITS.maxBytes) {
182
189
  throw new EditorDataError("Editor content exceeds the size limit", "TOO_LARGE");
@@ -204,6 +211,95 @@ var byteLength = (text) => {
204
211
  return bytes;
205
212
  };
206
213
 
214
+ // shared/table.mjs
215
+ var TABLE_LIMITS = Object.freeze({ rows: 500, cols: 100, merges: 1e3, caption: 4e3 });
216
+ var TABLE_ALIGNS = Object.freeze(["left", "center", "right"]);
217
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
218
+ var tableWidth = (content) => Array.isArray(content) ? content.reduce((width, row) => Math.max(width, Array.isArray(row) ? row.length : 0), 0) : 0;
219
+ var cleanTableAlign = (value, cols) => {
220
+ if (!Array.isArray(value) || cols <= 0) return null;
221
+ const out = value.slice(0, Math.min(cols, TABLE_LIMITS.cols)).map((item) => typeof item === "string" && TABLE_ALIGNS.includes(item) ? item : null);
222
+ while (out.length && out[out.length - 1] === null) out.pop();
223
+ return out.length ? out : null;
224
+ };
225
+ var intersects = (a, b) => a.row < b.row + b.rowspan && b.row < a.row + a.rowspan && a.col < b.col + b.colspan && b.col < a.col + a.colspan;
226
+ var normalizeMerges = (merges, rows, cols, options = {}) => {
227
+ if (!Array.isArray(merges) || rows <= 0 || cols <= 0) return [];
228
+ const out = [];
229
+ for (const merge of merges.slice(0, TABLE_LIMITS.merges)) {
230
+ if (!isObject(merge)) continue;
231
+ const { row, col, rowspan, colspan } = merge;
232
+ if (![row, col, rowspan, colspan].every(Number.isInteger)) continue;
233
+ if (row < 0 || col < 0 || rowspan < 1 || colspan < 1 || rowspan * colspan < 2) continue;
234
+ if (row + rowspan > rows || col + colspan > cols) continue;
235
+ if (options.headerRow && row === 0 && rowspan > 1) continue;
236
+ const next = { row, col, rowspan, colspan };
237
+ if (out.some((other) => intersects(other, next))) continue;
238
+ out.push(next);
239
+ }
240
+ return out.sort((a, b) => a.row - b.row || a.col - b.col);
241
+ };
242
+ var mergeMap = (merges) => {
243
+ const anchors = /* @__PURE__ */ new Map();
244
+ const covered = /* @__PURE__ */ new Map();
245
+ for (const merge of merges || []) {
246
+ anchors.set(`${merge.row}:${merge.col}`, merge);
247
+ for (let r = merge.row; r < merge.row + merge.rowspan; r += 1)
248
+ for (let c = merge.col; c < merge.col + merge.colspan; c += 1)
249
+ if (r !== merge.row || c !== merge.col) covered.set(`${r}:${c}`, merge);
250
+ }
251
+ return { anchors, covered };
252
+ };
253
+ var headerKind = (data, row, col) => {
254
+ if (data.withHeadings === true && row === 0) return "col";
255
+ if (data.headerColumn === true && col === 0) return "row";
256
+ return null;
257
+ };
258
+ var tableLayout = (data) => {
259
+ const merges = Array.isArray(data.merges) ? data.merges : [];
260
+ const { anchors, covered } = mergeMap(merges);
261
+ const align = Array.isArray(data.align) ? data.align : [];
262
+ return (data.content || []).map(
263
+ (row, r) => row.map((html, c) => {
264
+ if (covered.has(`${r}:${c}`)) return null;
265
+ const merge = anchors.get(`${r}:${c}`);
266
+ return {
267
+ row: r,
268
+ col: c,
269
+ html,
270
+ rowspan: merge ? merge.rowspan : 1,
271
+ colspan: merge ? merge.colspan : 1,
272
+ header: headerKind(data, r, c),
273
+ align: typeof align[c] === "string" ? align[c] : null
274
+ };
275
+ }).filter(Boolean)
276
+ );
277
+ };
278
+ var isBlankInlineHtml = (html) => typeof html !== "string" || /^(?:\s|&nbsp;|&#160;|\u00a0|<br\s*\/?>)*$/i.test(html);
279
+ var cleanTableExtras = (out, d, inline) => {
280
+ if (d.headerColumn === true) out.headerColumn = true;
281
+ const rows = out.content.length;
282
+ const cols = tableWidth(out.content);
283
+ const align = cleanTableAlign(d.align, cols);
284
+ if (align) out.align = align;
285
+ const merges = normalizeMerges(d.merges, rows, cols, { headerRow: out.withHeadings === true });
286
+ if (merges.length) {
287
+ const { covered } = mergeMap(merges);
288
+ out.content = out.content.map(
289
+ (row, r) => Array.from(
290
+ { length: cols },
291
+ (_, c) => covered.has(`${r}:${c}`) ? "" : row[c] === void 0 ? "" : row[c]
292
+ )
293
+ );
294
+ out.merges = merges;
295
+ }
296
+ if (typeof d.caption === "string") {
297
+ const caption = inline(d.caption.slice(0, TABLE_LIMITS.caption));
298
+ if (!isBlankInlineHtml(caption)) out.caption = caption;
299
+ }
300
+ return out;
301
+ };
302
+
207
303
  // shared/sanitize-policy.mjs
208
304
  var INLINE_TAGS = Object.freeze([
209
305
  "b",
@@ -247,9 +343,16 @@ var cleanInternalLinkAttributes = (attribs) => {
247
343
  var isMentionLink = (attrs) => Boolean(
248
344
  attrs && attrs["data-mex-mention"] === "true" && attrs["data-mex-uid"] && attrs["data-mex-document-id"]
249
345
  );
346
+ var MATH_ATTRIBUTE = "data-mex-math";
347
+ var FOOTNOTE_ATTRIBUTES = Object.freeze(["data-mex-footnote", "data-mex-note"]);
348
+ var FOOTNOTE_ID = /^[A-Za-z0-9_-]{1,64}$/;
349
+ var MAX_MATH_TEX = 1e4;
350
+ var MAX_INLINE_TEX = 2e3;
351
+ var MAX_FOOTNOTE_NOTE = 4e3;
250
352
  var INLINE_ATTRIBUTES = Object.freeze({
251
353
  a: ["href", "target", "rel", "title", ...INTERNAL_LINK_ATTRIBUTES],
252
- span: ["class", "data-tooltip"],
354
+ span: ["class", "data-tooltip", MATH_ATTRIBUTE],
355
+ sup: [...FOOTNOTE_ATTRIBUTES],
253
356
  mark: ["class"],
254
357
  u: ["class"],
255
358
  s: ["class"],
@@ -332,17 +435,17 @@ var mediaTracks = (tracks) => {
332
435
  if (!isPlainObject2(track)) continue;
333
436
  const file = cleanMediaFile(track.file, { vtt: true });
334
437
  if (!file.url) continue;
335
- const clean = {
438
+ const clean2 = {
336
439
  file,
337
440
  kind: oneOf(track.kind, TRACK_KINDS, "captions"),
338
441
  srclang: typeof track.srclang === "string" && SRCLANG.test(track.srclang) ? track.srclang : "",
339
442
  label: plain(track.label, 100)
340
443
  };
341
444
  if (track.default === true && !hasDefault) {
342
- clean.default = true;
445
+ clean2.default = true;
343
446
  hasDefault = true;
344
447
  }
345
- out.push(clean);
448
+ out.push(clean2);
346
449
  }
347
450
  return out;
348
451
  };
@@ -385,6 +488,17 @@ var listItems = (items, inline, depth = 0) => {
385
488
  return out;
386
489
  });
387
490
  };
491
+ var MAX_CODE_FILENAME = 200;
492
+ var FILENAME_STRIP = (
493
+ // eslint-disable-next-line no-control-regex -- the point is to remove control characters
494
+ /[\u0000-\u001f\u007f-\u009f\u061c\u200b-\u200f\u2028-\u202e\u2060\u2066-\u2069\ufeff]/g
495
+ );
496
+ var cleanCodeFilename = (value) => {
497
+ if (typeof value !== "string") return "";
498
+ return Array.from(
499
+ value.slice(0, 4 * MAX_CODE_FILENAME).replace(/[\t\n\r\f\v]/g, " ").replace(FILENAME_STRIP, "").replace(/\s+/g, " ").trim()
500
+ ).slice(0, MAX_CODE_FILENAME).join("").trim();
501
+ };
388
502
  var BLOCK_POLICIES = {
389
503
  paragraph: (d, inline) => ({ text: inline(d.text) }),
390
504
  header: (d, inline) => ({ text: inline(d.text), level: int(d.level, 1, 6, 2) }),
@@ -439,6 +553,8 @@ var BLOCK_POLICIES = {
439
553
  language: typeof d.language === "string" && /^[a-z0-9+#-]{1,32}$/i.test(d.language) ? d.language : "plaintext"
440
554
  };
441
555
  if (typeof d.showlinenumbers === "boolean") out.showlinenumbers = d.showlinenumbers;
556
+ const filename = cleanCodeFilename(d.filename);
557
+ if (filename) out.filename = filename;
442
558
  return out;
443
559
  },
444
560
  raw: (d, _inline, ctx) => {
@@ -447,11 +563,18 @@ var BLOCK_POLICIES = {
447
563
  if (ctx.rawHtml === "disable") return { html: "" };
448
564
  return { html: ctx.rawSanitizer(html) };
449
565
  },
450
- table: (d, inline) => ({
451
- withHeadings: bool(d.withHeadings),
452
- stretched: bool(d.stretched),
453
- content: Array.isArray(d.content) ? d.content.slice(0, 500).map((row) => Array.isArray(row) ? row.slice(0, 100).map((cell) => inline(cell)) : []) : []
454
- }),
566
+ // 2.4: optional header column, column alignment, merged cells and caption (shared/table.mjs).
567
+ table: (d, inline) => cleanTableExtras(
568
+ {
569
+ withHeadings: bool(d.withHeadings),
570
+ stretched: bool(d.stretched),
571
+ content: Array.isArray(d.content) ? d.content.slice(0, TABLE_LIMITS.rows).map(
572
+ (row) => Array.isArray(row) ? row.slice(0, TABLE_LIMITS.cols).map((cell) => inline(cell)) : []
573
+ ) : []
574
+ },
575
+ d,
576
+ inline
577
+ ),
455
578
  image: (d, inline) => {
456
579
  const file = isPlainObject2(d.file) ? d.file : {};
457
580
  const cleanFile = { url: sanitizeUrl(file.url, { schemes: ["http", "https"] }) };
@@ -575,6 +698,12 @@ var BLOCK_POLICIES = {
575
698
  ref: typeof d.ref === "string" && /^[a-z0-9]{1,64}$/.test(d.ref) ? d.ref : "",
576
699
  _mex: BUILT_IN_MARKER_VERSION
577
700
  }),
701
+ // Math block (2.4): only the TeX source is stored; `display: false` renders it in text style.
702
+ math: (d) => ({
703
+ tex: plain(d.tex, MAX_MATH_TEX),
704
+ display: d.display !== false,
705
+ _mex: BUILT_IN_MARKER_VERSION
706
+ }),
578
707
  toc: (d) => {
579
708
  const minLevel = int(d.minLevel, 1, 6, 2);
580
709
  const maxLevel = int(d.maxLevel, 1, 6, 4);
@@ -638,13 +767,13 @@ var ATTRIBUTE_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
638
767
  var isSafeAttributeName = (name) => ATTRIBUTE_NAME.test(name) && !name.startsWith("on") && name !== "style" && name !== "srcdoc";
639
768
  var textNode = (value) => ({ type: "text", value: String(value ?? "") });
640
769
  var el = (tag, attrs, children) => {
641
- const clean = {};
770
+ const clean2 = {};
642
771
  for (const [name, value] of Object.entries(attrs || {})) {
643
772
  if (value === void 0 || value === null || value === false) continue;
644
773
  if (value === "" && name !== "alt") continue;
645
- clean[name] = value === true ? true : String(value);
774
+ clean2[name] = value === true ? true : String(value);
646
775
  }
647
- return { type: "element", tag, attrs: clean, children: toNodes(children) };
776
+ return { type: "element", tag, attrs: clean2, children: toNodes(children) };
648
777
  };
649
778
  var toNodes = (children) => {
650
779
  const out = [];
@@ -791,7 +920,7 @@ var findTagEnd = (html, from) => {
791
920
  }
792
921
  return -1;
793
922
  };
794
- var cleanAttributes = (tag, attribs) => {
923
+ var cleanAttributes = (tag, attribs, options = {}) => {
795
924
  const allowed = INLINE_ATTRIBUTES[tag] || [];
796
925
  const out = {};
797
926
  for (const name of allowed) {
@@ -813,10 +942,40 @@ var cleanAttributes = (tag, attribs) => {
813
942
  out[name] = String(value).slice(0, 2e3);
814
943
  }
815
944
  }
816
- if (tag === "a") Object.assign(out, cleanInternalLinkAttributes(attribs));
945
+ if (tag === "a" && !options.inNote) Object.assign(out, cleanInternalLinkAttributes(attribs));
817
946
  return out;
818
947
  };
819
- var parseInline = (input) => {
948
+ var MAX_MARKER_TEXT = 16;
949
+ var isMathNode = (node) => node.type === "element" && node.tag === "span" && node.attrs[MATH_ATTRIBUTE] === "true";
950
+ var isFootnoteNode = (node) => node.type === "element" && node.tag === "sup" && typeof node.attrs["data-mex-footnote"] === "string";
951
+ var finalizeSpecial = (nodes, depth = 0) => {
952
+ for (const node of nodes) {
953
+ if (node.type !== "element") continue;
954
+ if (isMathNode(node)) {
955
+ const tex = nodesToText(node.children, { raw: true }).replace(/\u200b/g, "").slice(0, MAX_INLINE_TEX);
956
+ node.children = tex ? [{ type: "text", value: tex }] : [];
957
+ } else if (isFootnoteNode(node)) {
958
+ const text = nodesToText(node.children, { raw: true }).slice(0, MAX_MARKER_TEXT);
959
+ node.children = text ? [{ type: "text", value: text }] : [];
960
+ } else if (depth < MAX_DEPTH) finalizeSpecial(node.children, depth + 1);
961
+ }
962
+ return nodes;
963
+ };
964
+ var specialElement = (tag, attribs, options) => {
965
+ if (tag === "span" && Object.prototype.hasOwnProperty.call(attribs, MATH_ATTRIBUTE)) {
966
+ if (!/^(?:|true)$/.test(attribs[MATH_ATTRIBUTE])) return null;
967
+ return { attrs: { [MATH_ATTRIBUTE]: "true" } };
968
+ }
969
+ if (tag === "sup" && !options.inNote) {
970
+ const id = attribs["data-mex-footnote"];
971
+ if (typeof id !== "string" || !FOOTNOTE_ID.test(id)) return null;
972
+ const source = typeof attribs["data-mex-note"] === "string" ? attribs["data-mex-note"] : "";
973
+ const note = parseInline(source.slice(0, MAX_FOOTNOTE_NOTE), { inNote: true });
974
+ return { attrs: { "data-mex-footnote": id }, note };
975
+ }
976
+ return null;
977
+ };
978
+ var parseInline = (input, options = {}) => {
820
979
  const html = typeof input === "string" ? input.slice(0, MAX_INPUT) : "";
821
980
  const root = { type: "element", tag: "#root", attrs: {}, children: [] };
822
981
  const stack = [root];
@@ -897,18 +1056,21 @@ var parseInline = (input) => {
897
1056
  continue;
898
1057
  }
899
1058
  if (!ALLOWED.has(tag) || nodes >= MAX_NODES) continue;
1059
+ const attribs = parseAttributes(body);
1060
+ const special = specialElement(tag, attribs, options);
900
1061
  const element = {
901
1062
  type: "element",
902
1063
  tag,
903
- attrs: cleanAttributes(tag, parseAttributes(body)),
1064
+ attrs: special ? special.attrs : cleanAttributes(tag, attribs, options),
904
1065
  children: []
905
1066
  };
1067
+ if (special && special.note) element.note = special.note;
906
1068
  stack[stack.length - 1].children.push(element);
907
1069
  nodes += 1;
908
1070
  if (!VOID.has(tag) && stack.length < MAX_DEPTH) stack.push(element);
909
1071
  }
910
1072
  flush();
911
- return root.children;
1073
+ return finalizeSpecial(root.children);
912
1074
  };
913
1075
  var resolveLinkAttributes = (attrs, resolver) => {
914
1076
  if (typeof resolver !== "function" || !attrs["data-mex-uid"] || !attrs["data-mex-document-id"])
@@ -942,11 +1104,17 @@ var ATTRIBUTE_ORDER = [
942
1104
  "data-mex-uid",
943
1105
  "data-mex-document-id",
944
1106
  "data-mex-locale",
945
- "data-mex-mention"
1107
+ "data-mex-mention",
1108
+ MATH_ATTRIBUTE,
1109
+ "data-mex-footnote",
1110
+ "data-mex-note"
946
1111
  ];
1112
+ var RENDER_STATE = /* @__PURE__ */ Symbol.for("magic-editor-x.render-state");
1113
+ var storedNote = (note) => serializeNodes(inlineNodesToRender(note || [], { storage: true }));
947
1114
  var MENTION_CLASS = "mex-mention";
948
1115
  var inlineNodesToRender = (nodes, options = {}) => {
949
1116
  const out = [];
1117
+ const state = options[RENDER_STATE];
950
1118
  for (const node of nodes) {
951
1119
  if (node.type === "text") {
952
1120
  out.push({ type: "text", value: node.value });
@@ -956,6 +1124,31 @@ var inlineNodesToRender = (nodes, options = {}) => {
956
1124
  out.push({ type: "element", tag: "br", attrs: {}, children: [] });
957
1125
  continue;
958
1126
  }
1127
+ if (isMathNode(node)) {
1128
+ const tex = nodesToText(node.children);
1129
+ if (state && !options.storage) {
1130
+ if (tex.trim()) out.push(state.math(tex, false));
1131
+ continue;
1132
+ }
1133
+ out.push({
1134
+ type: "element",
1135
+ tag: "span",
1136
+ attrs: { [MATH_ATTRIBUTE]: "true" },
1137
+ children: tex ? [{ type: "text", value: tex }] : []
1138
+ });
1139
+ continue;
1140
+ }
1141
+ if (isFootnoteNode(node)) {
1142
+ if (state && !options.storage) {
1143
+ out.push(state.footnote(node));
1144
+ continue;
1145
+ }
1146
+ const attrs2 = { "data-mex-footnote": node.attrs["data-mex-footnote"] };
1147
+ const note = storedNote(node.note);
1148
+ if (note) attrs2["data-mex-note"] = note;
1149
+ out.push({ type: "element", tag: "sup", attrs: attrs2, children: inlineNodesToRender(node.children, options) });
1150
+ continue;
1151
+ }
959
1152
  let attrs = node.attrs;
960
1153
  if (node.tag === "a") {
961
1154
  attrs = resolveLinkAttributes(attrs, options.links);
@@ -988,13 +1181,369 @@ var inlineNodesToRender = (nodes, options = {}) => {
988
1181
  };
989
1182
  var inlineToNodes = (html, options) => inlineNodesToRender(parseInline(html), options);
990
1183
  var nodesToHtml = (nodes, options = {}) => serializeNodes(inlineNodesToRender(nodes, options));
991
- var nodesToText = (nodes) => nodes.map((node) => {
1184
+ var nodesToText = (nodes, options = {}) => nodes.map((node) => {
992
1185
  if (node.type === "text") return node.value;
993
1186
  if (node.tag === "br") return "\n";
994
- return nodesToText(node.children);
1187
+ if (!options.raw && isFootnoteNode(node))
1188
+ return typeof options.footnote === "function" ? options.footnote(node) : "";
1189
+ return nodesToText(node.children, options);
995
1190
  }).join("");
996
1191
  var inlineToHtml = (html, options) => nodesToHtml(parseInline(html), options);
997
- var inlineToText = (html) => nodesToText(parseInline(html)).replace(/\u00a0/g, " ");
1192
+ var inlineToText = (html, options) => nodesToText(parseInline(html), options).replace(/\u00a0/g, " ");
1193
+
1194
+ // shared/render/mathml.mjs
1195
+ var MATHML_TAGS = Object.freeze([
1196
+ "math",
1197
+ "semantics",
1198
+ "annotation",
1199
+ "mrow",
1200
+ "mi",
1201
+ "mn",
1202
+ "mo",
1203
+ "ms",
1204
+ "mtext",
1205
+ "mspace",
1206
+ "msub",
1207
+ "msup",
1208
+ "msubsup",
1209
+ "munder",
1210
+ "mover",
1211
+ "munderover",
1212
+ "mfrac",
1213
+ "msqrt",
1214
+ "mroot",
1215
+ "mstyle",
1216
+ "merror",
1217
+ "mpadded",
1218
+ "mphantom",
1219
+ "mtable",
1220
+ "mtr",
1221
+ "mtd",
1222
+ "mlabeledtr",
1223
+ "mmultiscripts",
1224
+ "mprescripts",
1225
+ "none",
1226
+ "menclose"
1227
+ ]);
1228
+ var TAGS = new Set(MATHML_TAGS);
1229
+ var COMMON_ATTRIBUTES = /* @__PURE__ */ new Set([
1230
+ "dir",
1231
+ "displaystyle",
1232
+ "scriptlevel",
1233
+ "mathvariant",
1234
+ "mathsize",
1235
+ "mathcolor",
1236
+ "mathbackground"
1237
+ ]);
1238
+ var ELEMENT_ATTRIBUTES = Object.freeze({
1239
+ math: ["display"],
1240
+ mo: [
1241
+ "form",
1242
+ "fence",
1243
+ "separator",
1244
+ "stretchy",
1245
+ "symmetric",
1246
+ "largeop",
1247
+ "movablelimits",
1248
+ "lspace",
1249
+ "rspace",
1250
+ "minsize",
1251
+ "maxsize",
1252
+ "accent"
1253
+ ],
1254
+ mspace: ["width", "height", "depth"],
1255
+ mpadded: ["width", "height", "depth", "lspace", "voffset"],
1256
+ mfrac: ["linethickness"],
1257
+ mover: ["accent"],
1258
+ munder: ["accentunder"],
1259
+ munderover: ["accent", "accentunder"],
1260
+ mtable: [
1261
+ "columnalign",
1262
+ "rowalign",
1263
+ "columnspacing",
1264
+ "rowspacing",
1265
+ "columnlines",
1266
+ "rowlines",
1267
+ "frame",
1268
+ "framespacing",
1269
+ "equalrows",
1270
+ "equalcolumns",
1271
+ "side"
1272
+ ],
1273
+ mtr: ["columnalign", "rowalign"],
1274
+ mlabeledtr: ["columnalign", "rowalign"],
1275
+ mtd: ["columnalign", "rowalign", "columnspan", "rowspan"],
1276
+ menclose: ["notation"],
1277
+ annotation: ["encoding"]
1278
+ });
1279
+ var ATTRIBUTE_VALUE = /^[A-Za-z0-9 .%#+-]{0,100}$/;
1280
+ var COLOR_VALUE = /^(?:#[0-9A-Fa-f]{3,8}|[A-Za-z]{1,30})$/;
1281
+ var CLASS_TOKEN = /^tml-[a-z0-9-]{1,40}$/;
1282
+ var TEX_ENCODING = "application/x-tex";
1283
+ var MAX_INPUT2 = 2e5;
1284
+ var MAX_NODES2 = 2e4;
1285
+ var MAX_DEPTH2 = 64;
1286
+ var parseAttributes2 = (source) => {
1287
+ const out = {};
1288
+ const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
1289
+ let match;
1290
+ while (match = pattern.exec(source)) {
1291
+ const name = match[1].toLowerCase();
1292
+ if (Object.prototype.hasOwnProperty.call(out, name)) continue;
1293
+ out[name] = decodeEntities(match[2] ?? match[3] ?? match[4] ?? "");
1294
+ }
1295
+ return out;
1296
+ };
1297
+ var styleColor = (style, property) => {
1298
+ const pattern = property === "color" ? /(?:^|;)\s*color\s*:\s*([^;]+)/i : /background-color\s*:\s*([^;]+)/i;
1299
+ const match = pattern.exec(style);
1300
+ const value = match ? match[1].trim() : "";
1301
+ return COLOR_VALUE.test(value) ? value : "";
1302
+ };
1303
+ var cleanAttributes2 = (tag, attribs) => {
1304
+ const out = {};
1305
+ const allowed = ELEMENT_ATTRIBUTES[tag] || [];
1306
+ for (const [name, raw] of Object.entries(attribs)) {
1307
+ if (typeof raw !== "string" && typeof raw !== "number" && raw !== true) continue;
1308
+ const value = raw === true ? "true" : String(raw);
1309
+ if (name === "class") {
1310
+ const classes2 = value.split(/\s+/).filter((token) => CLASS_TOKEN.test(token));
1311
+ if (classes2.length) out.class = classes2.slice(0, 8).join(" ");
1312
+ continue;
1313
+ }
1314
+ if (name === "encoding") {
1315
+ if (tag === "annotation" && value === TEX_ENCODING) out.encoding = value;
1316
+ continue;
1317
+ }
1318
+ if (name === "mathcolor" || name === "mathbackground") {
1319
+ if (COLOR_VALUE.test(value)) out[name] = value;
1320
+ continue;
1321
+ }
1322
+ if (!COMMON_ATTRIBUTES.has(name) && !allowed.includes(name)) continue;
1323
+ if (ATTRIBUTE_VALUE.test(value)) out[name] = value;
1324
+ }
1325
+ if (typeof attribs.style === "string") {
1326
+ const color = styleColor(attribs.style, "color");
1327
+ const background = styleColor(attribs.style, "background-color");
1328
+ if (color && !out.mathcolor) out.mathcolor = color;
1329
+ if (background && !out.mathbackground) out.mathbackground = background;
1330
+ }
1331
+ if (tag === "annotation" && out.encoding !== TEX_ENCODING) return null;
1332
+ if (tag === "math" && out.display && out.display !== "block" && out.display !== "inline")
1333
+ delete out.display;
1334
+ return out;
1335
+ };
1336
+ var tokenize = (input) => {
1337
+ const source = input.slice(0, MAX_INPUT2);
1338
+ const root = { type: "element", tag: "#root", attrs: {}, children: [] };
1339
+ const stack = [root];
1340
+ let count = 0;
1341
+ let i = 0;
1342
+ const pushText = (text) => {
1343
+ if (!text) return;
1344
+ const parent = stack[stack.length - 1];
1345
+ const last = parent.children[parent.children.length - 1];
1346
+ const value = decodeEntities(text);
1347
+ if (last && last.type === "text") last.value += value;
1348
+ else if (count < MAX_NODES2) {
1349
+ parent.children.push({ type: "text", value });
1350
+ count += 1;
1351
+ }
1352
+ };
1353
+ while (i < source.length) {
1354
+ const lt = source.indexOf("<", i);
1355
+ if (lt === -1) {
1356
+ pushText(source.slice(i));
1357
+ break;
1358
+ }
1359
+ pushText(source.slice(i, lt));
1360
+ if (source.startsWith("<!--", lt)) {
1361
+ const end2 = source.indexOf("-->", lt + 4);
1362
+ i = end2 === -1 ? source.length : end2 + 3;
1363
+ continue;
1364
+ }
1365
+ if (source[lt + 1] === "!" || source[lt + 1] === "?") {
1366
+ const end2 = source.indexOf(">", lt + 2);
1367
+ i = end2 === -1 ? source.length : end2 + 1;
1368
+ continue;
1369
+ }
1370
+ const closing = source[lt + 1] === "/";
1371
+ const nameMatch = /^[A-Za-z][A-Za-z0-9:-]{0,40}/.exec(source.slice(lt + (closing ? 2 : 1), lt + 45));
1372
+ let end = -1;
1373
+ let quote = "";
1374
+ for (let j = lt + 1; j < source.length; j += 1) {
1375
+ const char = source[j];
1376
+ if (quote) {
1377
+ if (char === quote) quote = "";
1378
+ } else if (char === '"' || char === "'") quote = char;
1379
+ else if (char === ">") {
1380
+ end = j;
1381
+ break;
1382
+ }
1383
+ }
1384
+ if (!nameMatch || end === -1) {
1385
+ pushText(source.slice(lt, end === -1 ? source.length : lt + 1));
1386
+ i = end === -1 ? source.length : lt + 1;
1387
+ continue;
1388
+ }
1389
+ const tag = nameMatch[0].toLowerCase();
1390
+ const body = source.slice(lt + (closing ? 2 : 1) + nameMatch[0].length, end);
1391
+ i = end + 1;
1392
+ if (closing) {
1393
+ for (let s = stack.length - 1; s > 0; s -= 1) {
1394
+ if (stack[s].tag === tag) {
1395
+ stack.length = s;
1396
+ break;
1397
+ }
1398
+ }
1399
+ continue;
1400
+ }
1401
+ if (count >= MAX_NODES2) continue;
1402
+ const element = { type: "element", tag, attrs: parseAttributes2(body), children: [] };
1403
+ stack[stack.length - 1].children.push(element);
1404
+ count += 1;
1405
+ const selfClosing = /\/\s*$/.test(body);
1406
+ if (!selfClosing && stack.length < MAX_DEPTH2) stack.push(element);
1407
+ }
1408
+ return root.children;
1409
+ };
1410
+ var clean = (nodes, ctx, depth, inAnnotation) => {
1411
+ const out = [];
1412
+ if (!Array.isArray(nodes) || depth > MAX_DEPTH2) return out;
1413
+ for (const node of nodes) {
1414
+ if (ctx.budget <= 0) break;
1415
+ if (typeof node === "string") {
1416
+ ctx.budget -= 1;
1417
+ if (node) out.push({ type: "text", value: node });
1418
+ continue;
1419
+ }
1420
+ if (!node || typeof node !== "object") continue;
1421
+ ctx.budget -= 1;
1422
+ if (node.type === "text") {
1423
+ if (typeof node.value === "string" && node.value) out.push({ type: "text", value: node.value });
1424
+ continue;
1425
+ }
1426
+ if (node.type !== "element" || typeof node.tag !== "string" || inAnnotation) continue;
1427
+ const tag = node.tag.toLowerCase();
1428
+ if (!TAGS.has(tag)) continue;
1429
+ const attrs = cleanAttributes2(tag, node.attrs && typeof node.attrs === "object" ? node.attrs : {});
1430
+ if (!attrs) continue;
1431
+ const children = clean(node.children, ctx, depth + 1, tag === "annotation");
1432
+ out.push({ type: "element", tag, attrs, children });
1433
+ }
1434
+ return out;
1435
+ };
1436
+ var cleanMathResult = (result) => {
1437
+ let nodes;
1438
+ if (typeof result === "string") nodes = tokenize(result);
1439
+ else if (Array.isArray(result)) nodes = result;
1440
+ else if (result && typeof result === "object") nodes = [result];
1441
+ else return [];
1442
+ const top = nodes.filter(
1443
+ (node) => node && typeof node === "object" && node.type === "element" && String(node.tag).toLowerCase() === "math"
1444
+ );
1445
+ return clean(top, { budget: MAX_NODES2 }, 0, false);
1446
+ };
1447
+
1448
+ // shared/render/math-notes.mjs
1449
+ var DEFAULT_FOOTNOTES_LABEL = "Footnotes";
1450
+ var DEFAULT_FOOTNOTE_BACK_LABEL = "Back to reference {n}";
1451
+ var DEFAULT_FOOTNOTE_PREFIX = "mex-";
1452
+ var PREFIX = /^[A-Za-z][A-Za-z0-9_-]{0,40}$/;
1453
+ var label = (value, fallback) => {
1454
+ if (typeof value !== "string") return fallback;
1455
+ const clean2 = value.trim();
1456
+ return clean2 && clean2.length <= 80 ? clean2 : fallback;
1457
+ };
1458
+ var footnoteOptions = (options) => {
1459
+ const source = isPlainObject2(options && options.footnotes) ? options.footnotes : {};
1460
+ return {
1461
+ label: label(source.label, DEFAULT_FOOTNOTES_LABEL),
1462
+ backLabel: label(source.backLabel, DEFAULT_FOOTNOTE_BACK_LABEL),
1463
+ prefix: typeof source.prefix === "string" && PREFIX.test(source.prefix) ? source.prefix : DEFAULT_FOOTNOTE_PREFIX
1464
+ };
1465
+ };
1466
+ var createFootnoteNumbers = () => {
1467
+ const used = /* @__PURE__ */ new Map();
1468
+ let count = 0;
1469
+ return {
1470
+ add(id) {
1471
+ const seen = (used.get(id) || 0) + 1;
1472
+ used.set(id, seen);
1473
+ count += 1;
1474
+ return { n: count, anchor: seen === 1 ? id : `${id}-${seen}` };
1475
+ }
1476
+ };
1477
+ };
1478
+ var renderMathNodes = (options, tex, display) => {
1479
+ if (!options || typeof options.math !== "function" || !tex.trim()) return [];
1480
+ let result;
1481
+ try {
1482
+ result = options.math(tex, { display });
1483
+ } catch {
1484
+ return [];
1485
+ }
1486
+ return cleanMathResult(result);
1487
+ };
1488
+ var mathElement = (options, tex, kind) => {
1489
+ const math = renderMathNodes(options, tex, kind.display);
1490
+ const attrs = {
1491
+ class: kind.className || (kind.display ? "mex-math mex-math-display" : "mex-math"),
1492
+ "data-mex-math": kind.display ? "display" : "inline"
1493
+ };
1494
+ const children = math.length ? math : kind.display ? `\\[${tex}\\]` : `\\(${tex}\\)`;
1495
+ return el(kind.block ? "div" : "span", attrs, children);
1496
+ };
1497
+ var createFootnoteTree = (options, renderNote) => {
1498
+ const { label: listLabel, backLabel, prefix } = footnoteOptions(options);
1499
+ const numbers = createFootnoteNumbers();
1500
+ const items = [];
1501
+ const labelId = `${prefix}footnotes-label`;
1502
+ return {
1503
+ marker(node) {
1504
+ const { n, anchor } = numbers.add(node.attrs["data-mex-footnote"]);
1505
+ items.push({ n, anchor, note: node.note || [] });
1506
+ return el(
1507
+ "sup",
1508
+ { class: "mex-footnote-ref" },
1509
+ el(
1510
+ "a",
1511
+ {
1512
+ href: `#${prefix}fn-${anchor}`,
1513
+ id: `${prefix}fnref-${anchor}`,
1514
+ "aria-describedby": labelId
1515
+ },
1516
+ String(n)
1517
+ )
1518
+ );
1519
+ },
1520
+ section() {
1521
+ if (!items.length) return null;
1522
+ return el("section", { class: "mex-footnotes", "aria-labelledby": labelId }, [
1523
+ el("h2", { id: labelId, class: "mex-footnotes-label" }, listLabel),
1524
+ el(
1525
+ "ol",
1526
+ { class: "mex-footnotes-list" },
1527
+ items.map(
1528
+ (item) => el("li", { id: `${prefix}fn-${item.anchor}`, class: "mex-footnote" }, [
1529
+ renderNote(item.note),
1530
+ " ",
1531
+ el(
1532
+ "a",
1533
+ {
1534
+ href: `#${prefix}fnref-${item.anchor}`,
1535
+ class: "mex-footnote-back",
1536
+ "aria-label": backLabel.replace(/\{n\}/g, String(item.n))
1537
+ },
1538
+ "\u21A9"
1539
+ )
1540
+ ])
1541
+ )
1542
+ )
1543
+ ]);
1544
+ }
1545
+ };
1546
+ };
998
1547
 
999
1548
  // shared/blocks/define.mjs
1000
1549
  var BLOCK_FIELD_TYPES = Object.freeze([
@@ -1072,6 +1621,7 @@ var RESERVED_BLOCK_NAMES = Object.freeze([
1072
1621
  "textVariant",
1073
1622
  "indentTune"
1074
1623
  ]);
1624
+ var SDK_COMPATIBLE_NAMES = Object.freeze(["math"]);
1075
1625
  var RESERVED = new Set(RESERVED_BLOCK_NAMES.map((name) => name.toLowerCase()));
1076
1626
  var BLOCK_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{1,49}$/;
1077
1627
  var KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
@@ -1109,7 +1659,7 @@ var BlockDefinitionError = class extends Error {
1109
1659
  this.code = code;
1110
1660
  }
1111
1661
  };
1112
- var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1662
+ var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1113
1663
  var fail = (where, message) => {
1114
1664
  throw new BlockDefinitionError(`Magic Editor X block ${where}: ${message}`);
1115
1665
  };
@@ -1120,7 +1670,7 @@ var boundedInt = (value, min, max, fallback, where, key) => {
1120
1670
  return value;
1121
1671
  };
1122
1672
  var normalizeField = (input, where, depth) => {
1123
- if (!isObject(input)) fail(where, 'a field must be an object with a "type"');
1673
+ if (!isObject2(input)) fail(where, 'a field must be an object with a "type"');
1124
1674
  const type = input.type;
1125
1675
  if (!BLOCK_FIELD_TYPES.includes(type)) fail(where, `unknown field type ${JSON.stringify(type)}`);
1126
1676
  for (const key of Object.keys(input))
@@ -1213,7 +1763,7 @@ var normalizeField = (input, where, depth) => {
1213
1763
  return Object.freeze(out);
1214
1764
  };
1215
1765
  var normalizeFields = (input, where, depth) => {
1216
- if (!isObject(input)) fail(where, '"fields" must be an object of field descriptors');
1766
+ if (!isObject2(input)) fail(where, '"fields" must be an object of field descriptors');
1217
1767
  const keys = Object.keys(input);
1218
1768
  if (keys.length < 1 || keys.length > BLOCK_LIMITS.maxFields)
1219
1769
  fail(where, `an object needs 1 to ${BLOCK_LIMITS.maxFields} fields`);
@@ -1232,20 +1782,20 @@ var blockNameProblem = (name) => {
1232
1782
  return null;
1233
1783
  };
1234
1784
  var defineBlock = (definition) => {
1235
- if (!isObject(definition))
1785
+ if (!isObject2(definition))
1236
1786
  throw new BlockDefinitionError("Magic Editor X block: the definition must be an object");
1237
- const label2 = typeof definition.name === "string" ? `"${definition.name.slice(0, 50)}"` : "(no name)";
1787
+ const label3 = typeof definition.name === "string" ? `"${definition.name.slice(0, 50)}"` : "(no name)";
1238
1788
  for (const key of Object.keys(definition))
1239
- if (!DEFINITION_KEYS.has(key)) fail(label2, `unknown key "${key}"`);
1789
+ if (!DEFINITION_KEYS.has(key)) fail(label3, `unknown key "${key}"`);
1240
1790
  const problem = blockNameProblem(definition.name);
1241
1791
  if (problem)
1242
1792
  throw new BlockDefinitionError(
1243
- `Magic Editor X block ${label2}: ${problem}`,
1793
+ `Magic Editor X block ${label3}: ${problem}`,
1244
1794
  problem.includes("built-in") ? "RESERVED_NAME" : "INVALID_DEFINITION"
1245
1795
  );
1246
1796
  const out = {
1247
1797
  name: definition.name,
1248
- version: boundedInt(definition.version, 1, 1e6, 1, label2, "version")
1798
+ version: boundedInt(definition.version, 1, 1e6, 1, label3, "version")
1249
1799
  };
1250
1800
  for (const [key, max] of [
1251
1801
  ["title", 100],
@@ -1253,18 +1803,18 @@ var defineBlock = (definition) => {
1253
1803
  ]) {
1254
1804
  if (definition[key] === void 0) continue;
1255
1805
  if (typeof definition[key] !== "string" || definition[key].length > max)
1256
- fail(label2, `"${key}" must be a string of at most ${max} characters`);
1806
+ fail(label3, `"${key}" must be a string of at most ${max} characters`);
1257
1807
  out[key] = definition[key];
1258
1808
  }
1259
- out.schema = normalizeFields(definition.schema, `${label2} schema`, 0);
1809
+ out.schema = normalizeFields(definition.schema, `${label3} schema`, 0);
1260
1810
  for (const key of ["sanitize", "text", "markdown", "render"]) {
1261
1811
  if (definition[key] === void 0) continue;
1262
- if (typeof definition[key] !== "function") fail(label2, `"${key}" must be a function`);
1812
+ if (typeof definition[key] !== "function") fail(label3, `"${key}" must be a function`);
1263
1813
  out[key] = definition[key];
1264
1814
  }
1265
1815
  const presets = definition.presets === void 0 ? [] : definition.presets;
1266
1816
  if (!Array.isArray(presets) || presets.some((preset) => !BLOCK_PRESETS.includes(preset)))
1267
- fail(label2, `"presets" must list some of ${BLOCK_PRESETS.join(", ")}`);
1817
+ fail(label3, `"presets" must list some of ${BLOCK_PRESETS.join(", ")}`);
1268
1818
  out.presets = Object.freeze([...new Set(presets)]);
1269
1819
  return Object.freeze(out);
1270
1820
  };
@@ -1292,13 +1842,13 @@ var cleanValue = (field, value, inline, budget) => {
1292
1842
  for (const item of value) {
1293
1843
  if (out.length >= field.max || budget.left <= 0) break;
1294
1844
  if (!matchesType(field.items, item)) continue;
1295
- const clean = cleanValue(field.items, item, inline, budget);
1296
- if (clean !== void 0) out.push(clean);
1845
+ const clean2 = cleanValue(field.items, item, inline, budget);
1846
+ if (clean2 !== void 0) out.push(clean2);
1297
1847
  }
1298
1848
  return out;
1299
1849
  }
1300
1850
  case "object":
1301
- return cleanObject(field.fields, isObject(value) ? value : {}, inline, budget);
1851
+ return cleanObject(field.fields, isObject2(value) ? value : {}, inline, budget);
1302
1852
  default:
1303
1853
  return void 0;
1304
1854
  }
@@ -1317,15 +1867,15 @@ var matchesType = (field, item) => {
1317
1867
  case "array":
1318
1868
  return Array.isArray(item);
1319
1869
  default:
1320
- return isObject(item);
1870
+ return isObject2(item);
1321
1871
  }
1322
1872
  };
1323
1873
  var cleanObject = (fields, value, inline, budget) => {
1324
1874
  const out = {};
1325
1875
  for (const key of Object.keys(fields)) {
1326
1876
  const own = Object.prototype.hasOwnProperty.call(value, key) ? value[key] : void 0;
1327
- const clean = cleanValue(fields[key], own, inline, budget);
1328
- if (clean !== void 0) out[key] = clean;
1877
+ const clean2 = cleanValue(fields[key], own, inline, budget);
1878
+ if (clean2 !== void 0) out[key] = clean2;
1329
1879
  }
1330
1880
  return out;
1331
1881
  };
@@ -1336,13 +1886,13 @@ var eachLeaf = (fields, data, visit) => {
1336
1886
  if (!Array.isArray(value)) return;
1337
1887
  value.slice(0, field.max).forEach((item, index) => walk(field.items, item, [...path, index], depth + 1));
1338
1888
  } else if (field.type === "object") {
1339
- if (!isObject(value)) return;
1889
+ if (!isObject2(value)) return;
1340
1890
  for (const key of Object.keys(field.fields))
1341
1891
  if (Object.prototype.hasOwnProperty.call(value, key))
1342
1892
  walk(field.fields[key], value[key], [...path, key], depth + 1);
1343
1893
  } else visit(field, value, path);
1344
1894
  };
1345
- if (!isObject(data)) return;
1895
+ if (!isObject2(data)) return;
1346
1896
  for (const key of Object.keys(fields))
1347
1897
  if (Object.prototype.hasOwnProperty.call(data, key)) walk(fields[key], data[key], [key], 0);
1348
1898
  };
@@ -1368,7 +1918,7 @@ var compileBlock = (definition) => {
1368
1918
  return compiled.get(definition);
1369
1919
  const def = defineBlock(definition && typeof definition === "object" ? { ...definition } : definition);
1370
1920
  const schema = def.schema;
1371
- const run = (data, inline) => cleanObject(schema, isObject(data) ? data : {}, inline, { left: BLOCK_LIMITS.maxValues });
1921
+ const run = (data, inline) => cleanObject(schema, isObject2(data) ? data : {}, inline, { left: BLOCK_LIMITS.maxValues });
1372
1922
  const result = Object.freeze({
1373
1923
  ...def,
1374
1924
  /**
@@ -1389,7 +1939,7 @@ var compileBlock = (definition) => {
1389
1939
  } catch {
1390
1940
  return first;
1391
1941
  }
1392
- return isObject(next) ? run(next, inline) : first;
1942
+ return isObject2(next) ? run(next, inline) : first;
1393
1943
  },
1394
1944
  /**
1395
1945
  * Text fields of the data in schema order: `{ path, kind, value }`
@@ -1437,7 +1987,7 @@ var compileBlock = (definition) => {
1437
1987
  };
1438
1988
  var copyData = (value) => {
1439
1989
  if (Array.isArray(value)) return value.map(copyData);
1440
- if (isObject(value)) {
1990
+ if (isObject2(value)) {
1441
1991
  const out = {};
1442
1992
  for (const [key, child] of Object.entries(value)) out[key] = copyData(child);
1443
1993
  return out;
@@ -1681,12 +2231,12 @@ var prepareBlocks = (value, options = {}) => {
1681
2231
  const raw = isPlainObject2(block.data) ? block.data : {};
1682
2232
  const known = isBuiltInBlock({ type: block.type, data: raw });
1683
2233
  const definition = known ? null : registeredBlockOf({ type: block.type, data: raw }, explicit);
1684
- const clean = known ? BLOCK_POLICIES[block.type](raw, keepInline, ctx) : definition ? definition.clean(raw, keepInline) : raw;
1685
- for (const key of Object.keys(clean)) if (clean[key] === void 0) delete clean[key];
2234
+ const clean2 = known ? BLOCK_POLICIES[block.type](raw, keepInline, ctx) : definition ? definition.clean(raw, keepInline) : raw;
2235
+ for (const key of Object.keys(clean2)) if (clean2[key] === void 0) delete clean2[key];
1686
2236
  return {
1687
2237
  id: block.id,
1688
2238
  type: block.type,
1689
- data: clean,
2239
+ data: clean2,
1690
2240
  raw,
1691
2241
  tunes: sanitizeTunes(block.tunes),
1692
2242
  known,
@@ -1716,10 +2266,10 @@ var imageCandidates = (file) => {
1716
2266
  const out = [];
1717
2267
  const seen = /* @__PURE__ */ new Set();
1718
2268
  const push = (url, width) => {
1719
- const clean = sanitizeUrl(url, { schemes: ["http", "https"] });
1720
- if (!clean || !Number.isInteger(width) || width <= 0 || seen.has(width)) return;
2269
+ const clean2 = sanitizeUrl(url, { schemes: ["http", "https"] });
2270
+ if (!clean2 || !Number.isInteger(width) || width <= 0 || seen.has(width)) return;
1721
2271
  seen.add(width);
1722
- out.push({ url: clean, width });
2272
+ out.push({ url: clean2, width });
1723
2273
  };
1724
2274
  if (isPlainObject2(file.formats)) {
1725
2275
  const names = Object.keys(file.formats).sort(
@@ -1935,20 +2485,20 @@ var mediaFigure = (tag, b, o) => {
1935
2485
  caption.length ? el("figcaption", {}, caption) : null
1936
2486
  ]);
1937
2487
  };
1938
- var label = (value, fallback) => {
2488
+ var label2 = (value, fallback) => {
1939
2489
  if (typeof value !== "string") return fallback;
1940
- const clean = value.trim();
1941
- return clean && clean.length <= 80 ? clean : fallback;
2490
+ const clean2 = value.trim();
2491
+ return clean2 && clean2.length <= 80 ? clean2 : fallback;
1942
2492
  };
1943
- var tocLabel = (options) => label(isPlainObject2(options.toc) ? options.toc.label : void 0, "Table of contents");
2493
+ var tocLabel = (options) => label2(isPlainObject2(options.toc) ? options.toc.label : void 0, "Table of contents");
1944
2494
  var codeOptions = (options) => {
1945
2495
  const code = isPlainObject2(options.code) ? options.code : {};
1946
2496
  const lineNumbers = code.lineNumbers === true ? "all" : code.lineNumbers === "block" ? "block" : "none";
1947
2497
  const button = code.copyButton;
1948
2498
  const copy = button === true || isPlainObject2(button) ? {
1949
- label: label(isPlainObject2(button) ? button.label : void 0, "Copy code"),
1950
- copied: label(isPlainObject2(button) ? button.copiedLabel : void 0, "Copied"),
1951
- failed: label(isPlainObject2(button) ? button.failedLabel : void 0, "Copy failed")
2499
+ label: label2(isPlainObject2(button) ? button.label : void 0, "Copy code"),
2500
+ copied: label2(isPlainObject2(button) ? button.copiedLabel : void 0, "Copied"),
2501
+ failed: label2(isPlainObject2(button) ? button.failedLabel : void 0, "Copy failed")
1952
2502
  } : null;
1953
2503
  return { lineNumbers, copy };
1954
2504
  };
@@ -1977,23 +2527,29 @@ var codeBlock = (b, language, o) => {
1977
2527
  },
1978
2528
  el("code", language ? { class: `language-${language}` } : {}, numbers ? numberedLines(code) : code)
1979
2529
  );
1980
- if (!copy) return pre;
1981
- return el("div", { class: "mex-code-block", "data-mex-code": "copy" }, [
1982
- pre,
1983
- el(
1984
- "button",
1985
- {
1986
- type: "button",
1987
- class: "mex-code-copy",
1988
- "data-mex-copy": "code",
1989
- "data-mex-copied": copy.copied,
1990
- "data-mex-failed": copy.failed
1991
- },
1992
- copy.label
1993
- ),
1994
- el("span", { class: "mex-code-copy-status", role: "status", "aria-live": "polite" })
2530
+ const block = copy ? copyBlock(pre, copy) : pre;
2531
+ const filename = b.type === "codeFlask" && typeof b.data.filename === "string" ? b.data.filename : "";
2532
+ if (!filename) return block;
2533
+ return el("figure", { class: "mex-code-figure" }, [
2534
+ el("figcaption", { class: "mex-code-filename" }, filename),
2535
+ block
1995
2536
  ]);
1996
2537
  };
2538
+ var copyBlock = (pre, copy) => el("div", { class: "mex-code-block", "data-mex-code": "copy" }, [
2539
+ pre,
2540
+ el(
2541
+ "button",
2542
+ {
2543
+ type: "button",
2544
+ class: "mex-code-copy",
2545
+ "data-mex-copy": "code",
2546
+ "data-mex-copied": copy.copied,
2547
+ "data-mex-failed": copy.failed
2548
+ },
2549
+ copy.label
2550
+ ),
2551
+ el("span", { class: "mex-code-copy-status", role: "status", "aria-live": "polite" })
2552
+ ]);
1997
2553
  var RENDERERS = {
1998
2554
  paragraph: (b, o) => el("p", { class: classes(["mex-paragraph"], b.tunes) }, inlineToNodes(b.data.text, o)),
1999
2555
  header: (b, o) => el(
@@ -2068,20 +2624,29 @@ var RENDERERS = {
2068
2624
  const html = o.sanitizeRaw(String(b.raw.html || ""));
2069
2625
  return typeof html === "string" && html ? el("div", { class: classes(["mex-raw"], b.tunes) }, { type: "raw", html }) : null;
2070
2626
  },
2627
+ // Header row: <thead> with <th scope="col">; header column (2.4): <th scope="row">;
2628
+ // merged cells: colspan/rowspan (covered cells are left out); alignment: a class.
2071
2629
  table: (b, o) => {
2072
- const rows = b.data.content;
2630
+ const rows = tableLayout(b.data);
2073
2631
  if (!rows.length) return null;
2074
- const cells = (row, tag) => el(
2075
- "tr",
2076
- {},
2077
- row.map((cell) => el(tag, tag === "th" ? { scope: "col" } : {}, inlineToNodes(cell, o)))
2632
+ const cell = (item) => el(
2633
+ item.header ? "th" : "td",
2634
+ {
2635
+ ...item.header ? { scope: item.header } : {},
2636
+ ...item.colspan > 1 ? { colspan: String(item.colspan) } : {},
2637
+ ...item.rowspan > 1 ? { rowspan: String(item.rowspan) } : {},
2638
+ ...item.align ? { class: `mex-align-${item.align}` } : {}
2639
+ },
2640
+ inlineToNodes(item.html, o)
2078
2641
  );
2079
- const head = b.data.withHeadings ? el("thead", {}, cells(rows[0], "th")) : null;
2080
- const body = (b.data.withHeadings ? rows.slice(1) : rows).map((row) => cells(row, "td"));
2642
+ const tr = (row) => el("tr", {}, row.map(cell));
2643
+ const head = b.data.withHeadings ? el("thead", {}, tr(rows[0])) : null;
2644
+ const body = (b.data.withHeadings ? rows.slice(1) : rows).map(tr);
2645
+ const caption = b.data.caption ? el("caption", {}, inlineToNodes(b.data.caption, o)) : null;
2081
2646
  return el(
2082
2647
  "table",
2083
2648
  { class: classes(["mex-table", ...b.data.stretched ? ["mex-stretched"] : []], b.tunes) },
2084
- [head, body.length ? el("tbody", {}, body) : null]
2649
+ [caption, head, body.length ? el("tbody", {}, body) : null]
2085
2650
  );
2086
2651
  },
2087
2652
  image: (b, o) => {
@@ -2174,11 +2739,11 @@ var RENDERERS = {
2174
2739
  embed: (b, o) => {
2175
2740
  const hosts = Array.isArray(o.embedHosts) ? o.embedHosts.map((h) => String(h).toLowerCase()) : DEFAULT_EMBED_HOSTS;
2176
2741
  const frame = embedFrameUrl(b.data.embed, hosts);
2742
+ const href = b.data.source || b.data.embed;
2743
+ if (!frame && !href) return null;
2177
2744
  const caption = inlineToNodes(b.data.caption, o);
2178
2745
  const title = inlineToText(b.data.caption) || b.data.service || "Embedded content";
2179
2746
  if (!frame) {
2180
- const href = b.data.source || b.data.embed;
2181
- if (!href) return null;
2182
2747
  return el(
2183
2748
  "p",
2184
2749
  { class: classes(["mex-embed", "mex-embed-link"], b.tunes) },
@@ -2238,6 +2803,15 @@ var RENDERERS = {
2238
2803
  return el("p", { class: classes(["mex-button-block"], b.tunes) }, inner);
2239
2804
  },
2240
2805
  delimiter: (b) => el("hr", { class: classes(["mex-delimiter"], b.tunes) }),
2806
+ // Math block (2.4): MathML from `options.math`, else the delimited TeX source.
2807
+ math: (b, o) => b.data.tex.trim() ? mathElement(o, b.data.tex, {
2808
+ display: b.data.display !== false,
2809
+ block: true,
2810
+ className: classes(
2811
+ ["mex-math", ...b.data.display !== false ? ["mex-math-display"] : []],
2812
+ b.tunes
2813
+ )
2814
+ }) : null,
2241
2815
  toc: (b, o) => {
2242
2816
  const tree = buildTocTree(b.headings || [], b.data);
2243
2817
  if (!tree.length) return null;
@@ -2330,15 +2904,15 @@ var RESOURCE_ATTRIBUTES = /* @__PURE__ */ new Set(["src", "poster", "data", "bac
2330
2904
  var cleanUrlAttribute = (name, value) => {
2331
2905
  if (name === "srcset" || name === "imagesrcset") {
2332
2906
  const parts = value.split(",").map((part) => part.trim());
2333
- const clean = [];
2907
+ const clean2 = [];
2334
2908
  for (const part of parts) {
2335
2909
  const [url, descriptor, extra] = part.split(/\s+/);
2336
2910
  if (extra !== void 0 || descriptor && !/^\d+(?:\.\d+)?[wx]$/.test(descriptor)) return "";
2337
2911
  const safe = sanitizeUrl(url, { schemes: ["http", "https"] });
2338
2912
  if (!safe) return "";
2339
- clean.push(descriptor ? `${safe} ${descriptor}` : safe);
2913
+ clean2.push(descriptor ? `${safe} ${descriptor}` : safe);
2340
2914
  }
2341
- return clean.join(", ");
2915
+ return clean2.join(", ");
2342
2916
  }
2343
2917
  return sanitizeUrl(value, { schemes: RESOURCE_ATTRIBUTES.has(name) ? ["http", "https"] : LINK_SCHEMES });
2344
2918
  };
@@ -2396,7 +2970,13 @@ var cleanOverrideNodes = (input, trusted) => {
2396
2970
  };
2397
2971
  var rawAllowed = (options) => options.rawHtml === "allow" && typeof options.sanitizeRaw === "function";
2398
2972
  var createTreeBuilder = (value, options, mode = {}) => {
2399
- const opts = options && typeof options === "object" ? options : {};
2973
+ const base = options && typeof options === "object" ? options : {};
2974
+ const opts = { ...base };
2975
+ const footnotes = createFootnoteTree(base, (note) => inlineNodesToRender(note, opts));
2976
+ opts[RENDER_STATE] = {
2977
+ math: (tex) => mathElement(base, tex, { display: false, block: false }),
2978
+ footnote: (node) => footnotes.marker(node)
2979
+ };
2400
2980
  const publicOf = /* @__PURE__ */ new WeakMap();
2401
2981
  const preparedOf = /* @__PURE__ */ new WeakMap();
2402
2982
  const trusted = /* @__PURE__ */ new WeakSet();
@@ -2480,6 +3060,8 @@ var createTreeBuilder = (value, options, mode = {}) => {
2480
3060
  childNodes: renderBlocks
2481
3061
  };
2482
3062
  const nodes = renderList(annotateHeadings(prepareBlocks(value, opts), opts));
3063
+ const section = footnotes.section();
3064
+ if (section) nodes.push(textNode("\n"), section);
2483
3065
  return { nodes, renderBlocks, helpers };
2484
3066
  };
2485
3067