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
@@ -58,7 +58,9 @@ var MARKED_BLOCKS = Object.freeze({
58
58
  keys: Object.freeze(["file", "title", "caption", "loop", "tracks"]),
59
59
  anchor: Object.freeze(["file", "object"])
60
60
  }),
61
- synced: Object.freeze({ keys: Object.freeze(["ref"]), anchor: Object.freeze(["ref", "string"]) })
61
+ synced: Object.freeze({ keys: Object.freeze(["ref"]), anchor: Object.freeze(["ref", "string"]) }),
62
+ // 2.4: math block. A Settings custom block named `math` could exist before 2.4.
63
+ math: Object.freeze({ keys: Object.freeze(["tex", "display"]), anchor: Object.freeze(["tex", "string"]) })
62
64
  });
63
65
  var isBuiltInMarker = (value) => Number.isInteger(value) && /** @type {number} */
64
66
  value >= 1;
@@ -77,6 +79,10 @@ var isMarkedBuiltIn = (type, data) => {
77
79
  return hasBuiltInShape(MARKED_BLOCKS[type], data);
78
80
  };
79
81
 
82
+ // shared/field-identity.mjs
83
+ var FIELD_KEY_PATTERN = /^[A-Za-z0-9_-]{16,32}$/;
84
+ var isValidFieldKey = (value) => typeof value === "string" && FIELD_KEY_PATTERN.test(value);
85
+
80
86
  // shared/editor-data.mjs
81
87
  var EDITOR_DATA_LIMITS = Object.freeze({
82
88
  maxBlocks: 5e3,
@@ -189,8 +195,8 @@ var normalizeEditorData = (value) => {
189
195
  if (!isPlainObject2(candidate)) {
190
196
  throw new EditorDataError("Editor content must be an Editor.js object", "INVALID_SHAPE");
191
197
  }
192
- const clean = cloneJsonSafe(candidate);
193
- const rawBlocks = Array.isArray(clean.blocks) ? clean.blocks : [];
198
+ const clean2 = cloneJsonSafe(candidate);
199
+ const rawBlocks = Array.isArray(clean2.blocks) ? clean2.blocks : [];
194
200
  if (rawBlocks.length > EDITOR_DATA_LIMITS.maxBlocks) {
195
201
  throw new EditorDataError("Editor content has too many blocks", "TOO_MANY_BLOCKS");
196
202
  }
@@ -209,9 +215,10 @@ var normalizeEditorData = (value) => {
209
215
  if (isPlainObject2(block.tunes) && Object.keys(block.tunes).length > 0) normalized.tunes = block.tunes;
210
216
  blocks.push(normalized);
211
217
  });
212
- const time = Number.isFinite(clean.time) && clean.time > 0 ? Math.floor(clean.time) : 0;
213
- const version = typeof clean.version === "string" && clean.version.length <= 32 ? clean.version : "2.31.7";
218
+ const time = Number.isFinite(clean2.time) && clean2.time > 0 ? Math.floor(clean2.time) : 0;
219
+ const version = typeof clean2.version === "string" && clean2.version.length <= 32 ? clean2.version : "2.31.7";
214
220
  const result = { time, blocks, version };
221
+ if (isValidFieldKey(clean2.fieldKey)) result.fieldKey = clean2.fieldKey;
215
222
  const size = byteLength(JSON.stringify(result));
216
223
  if (size > EDITOR_DATA_LIMITS.maxBytes) {
217
224
  throw new EditorDataError("Editor content exceeds the size limit", "TOO_LARGE");
@@ -239,6 +246,95 @@ var byteLength = (text) => {
239
246
  return bytes;
240
247
  };
241
248
 
249
+ // shared/table.mjs
250
+ var TABLE_LIMITS = Object.freeze({ rows: 500, cols: 100, merges: 1e3, caption: 4e3 });
251
+ var TABLE_ALIGNS = Object.freeze(["left", "center", "right"]);
252
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
253
+ var tableWidth = (content) => Array.isArray(content) ? content.reduce((width, row) => Math.max(width, Array.isArray(row) ? row.length : 0), 0) : 0;
254
+ var cleanTableAlign = (value, cols) => {
255
+ if (!Array.isArray(value) || cols <= 0) return null;
256
+ const out = value.slice(0, Math.min(cols, TABLE_LIMITS.cols)).map((item) => typeof item === "string" && TABLE_ALIGNS.includes(item) ? item : null);
257
+ while (out.length && out[out.length - 1] === null) out.pop();
258
+ return out.length ? out : null;
259
+ };
260
+ 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;
261
+ var normalizeMerges = (merges, rows, cols, options = {}) => {
262
+ if (!Array.isArray(merges) || rows <= 0 || cols <= 0) return [];
263
+ const out = [];
264
+ for (const merge of merges.slice(0, TABLE_LIMITS.merges)) {
265
+ if (!isObject(merge)) continue;
266
+ const { row, col, rowspan, colspan } = merge;
267
+ if (![row, col, rowspan, colspan].every(Number.isInteger)) continue;
268
+ if (row < 0 || col < 0 || rowspan < 1 || colspan < 1 || rowspan * colspan < 2) continue;
269
+ if (row + rowspan > rows || col + colspan > cols) continue;
270
+ if (options.headerRow && row === 0 && rowspan > 1) continue;
271
+ const next = { row, col, rowspan, colspan };
272
+ if (out.some((other) => intersects(other, next))) continue;
273
+ out.push(next);
274
+ }
275
+ return out.sort((a, b) => a.row - b.row || a.col - b.col);
276
+ };
277
+ var mergeMap = (merges) => {
278
+ const anchors = /* @__PURE__ */ new Map();
279
+ const covered = /* @__PURE__ */ new Map();
280
+ for (const merge of merges || []) {
281
+ anchors.set(`${merge.row}:${merge.col}`, merge);
282
+ for (let r = merge.row; r < merge.row + merge.rowspan; r += 1)
283
+ for (let c = merge.col; c < merge.col + merge.colspan; c += 1)
284
+ if (r !== merge.row || c !== merge.col) covered.set(`${r}:${c}`, merge);
285
+ }
286
+ return { anchors, covered };
287
+ };
288
+ var headerKind = (data, row, col) => {
289
+ if (data.withHeadings === true && row === 0) return "col";
290
+ if (data.headerColumn === true && col === 0) return "row";
291
+ return null;
292
+ };
293
+ var tableLayout = (data) => {
294
+ const merges = Array.isArray(data.merges) ? data.merges : [];
295
+ const { anchors, covered } = mergeMap(merges);
296
+ const align = Array.isArray(data.align) ? data.align : [];
297
+ return (data.content || []).map(
298
+ (row, r) => row.map((html, c) => {
299
+ if (covered.has(`${r}:${c}`)) return null;
300
+ const merge = anchors.get(`${r}:${c}`);
301
+ return {
302
+ row: r,
303
+ col: c,
304
+ html,
305
+ rowspan: merge ? merge.rowspan : 1,
306
+ colspan: merge ? merge.colspan : 1,
307
+ header: headerKind(data, r, c),
308
+ align: typeof align[c] === "string" ? align[c] : null
309
+ };
310
+ }).filter(Boolean)
311
+ );
312
+ };
313
+ var isBlankInlineHtml = (html) => typeof html !== "string" || /^(?:\s|&nbsp;|&#160;|\u00a0|<br\s*\/?>)*$/i.test(html);
314
+ var cleanTableExtras = (out, d, inline) => {
315
+ if (d.headerColumn === true) out.headerColumn = true;
316
+ const rows = out.content.length;
317
+ const cols = tableWidth(out.content);
318
+ const align = cleanTableAlign(d.align, cols);
319
+ if (align) out.align = align;
320
+ const merges = normalizeMerges(d.merges, rows, cols, { headerRow: out.withHeadings === true });
321
+ if (merges.length) {
322
+ const { covered } = mergeMap(merges);
323
+ out.content = out.content.map(
324
+ (row, r) => Array.from(
325
+ { length: cols },
326
+ (_, c) => covered.has(`${r}:${c}`) ? "" : row[c] === void 0 ? "" : row[c]
327
+ )
328
+ );
329
+ out.merges = merges;
330
+ }
331
+ if (typeof d.caption === "string") {
332
+ const caption = inline(d.caption.slice(0, TABLE_LIMITS.caption));
333
+ if (!isBlankInlineHtml(caption)) out.caption = caption;
334
+ }
335
+ return out;
336
+ };
337
+
242
338
  // shared/sanitize-policy.mjs
243
339
  var INLINE_TAGS = Object.freeze([
244
340
  "b",
@@ -282,9 +378,16 @@ var cleanInternalLinkAttributes = (attribs) => {
282
378
  var isMentionLink = (attrs) => Boolean(
283
379
  attrs && attrs["data-mex-mention"] === "true" && attrs["data-mex-uid"] && attrs["data-mex-document-id"]
284
380
  );
381
+ var MATH_ATTRIBUTE = "data-mex-math";
382
+ var FOOTNOTE_ATTRIBUTES = Object.freeze(["data-mex-footnote", "data-mex-note"]);
383
+ var FOOTNOTE_ID = /^[A-Za-z0-9_-]{1,64}$/;
384
+ var MAX_MATH_TEX = 1e4;
385
+ var MAX_INLINE_TEX = 2e3;
386
+ var MAX_FOOTNOTE_NOTE = 4e3;
285
387
  var INLINE_ATTRIBUTES = Object.freeze({
286
388
  a: ["href", "target", "rel", "title", ...INTERNAL_LINK_ATTRIBUTES],
287
- span: ["class", "data-tooltip"],
389
+ span: ["class", "data-tooltip", MATH_ATTRIBUTE],
390
+ sup: [...FOOTNOTE_ATTRIBUTES],
288
391
  mark: ["class"],
289
392
  u: ["class"],
290
393
  s: ["class"],
@@ -367,17 +470,17 @@ var mediaTracks = (tracks) => {
367
470
  if (!isPlainObject2(track)) continue;
368
471
  const file = cleanMediaFile(track.file, { vtt: true });
369
472
  if (!file.url) continue;
370
- const clean = {
473
+ const clean2 = {
371
474
  file,
372
475
  kind: oneOf(track.kind, TRACK_KINDS, "captions"),
373
476
  srclang: typeof track.srclang === "string" && SRCLANG.test(track.srclang) ? track.srclang : "",
374
477
  label: plain(track.label, 100)
375
478
  };
376
479
  if (track.default === true && !hasDefault) {
377
- clean.default = true;
480
+ clean2.default = true;
378
481
  hasDefault = true;
379
482
  }
380
- out.push(clean);
483
+ out.push(clean2);
381
484
  }
382
485
  return out;
383
486
  };
@@ -420,6 +523,17 @@ var listItems = (items, inline, depth = 0) => {
420
523
  return out;
421
524
  });
422
525
  };
526
+ var MAX_CODE_FILENAME = 200;
527
+ var FILENAME_STRIP = (
528
+ // eslint-disable-next-line no-control-regex -- the point is to remove control characters
529
+ /[\u0000-\u001f\u007f-\u009f\u061c\u200b-\u200f\u2028-\u202e\u2060\u2066-\u2069\ufeff]/g
530
+ );
531
+ var cleanCodeFilename = (value) => {
532
+ if (typeof value !== "string") return "";
533
+ return Array.from(
534
+ value.slice(0, 4 * MAX_CODE_FILENAME).replace(/[\t\n\r\f\v]/g, " ").replace(FILENAME_STRIP, "").replace(/\s+/g, " ").trim()
535
+ ).slice(0, MAX_CODE_FILENAME).join("").trim();
536
+ };
423
537
  var BLOCK_POLICIES = {
424
538
  paragraph: (d, inline) => ({ text: inline(d.text) }),
425
539
  header: (d, inline) => ({ text: inline(d.text), level: int(d.level, 1, 6, 2) }),
@@ -474,6 +588,8 @@ var BLOCK_POLICIES = {
474
588
  language: typeof d.language === "string" && /^[a-z0-9+#-]{1,32}$/i.test(d.language) ? d.language : "plaintext"
475
589
  };
476
590
  if (typeof d.showlinenumbers === "boolean") out.showlinenumbers = d.showlinenumbers;
591
+ const filename = cleanCodeFilename(d.filename);
592
+ if (filename) out.filename = filename;
477
593
  return out;
478
594
  },
479
595
  raw: (d, _inline, ctx) => {
@@ -482,11 +598,18 @@ var BLOCK_POLICIES = {
482
598
  if (ctx.rawHtml === "disable") return { html: "" };
483
599
  return { html: ctx.rawSanitizer(html) };
484
600
  },
485
- table: (d, inline) => ({
486
- withHeadings: bool(d.withHeadings),
487
- stretched: bool(d.stretched),
488
- content: Array.isArray(d.content) ? d.content.slice(0, 500).map((row) => Array.isArray(row) ? row.slice(0, 100).map((cell) => inline(cell)) : []) : []
489
- }),
601
+ // 2.4: optional header column, column alignment, merged cells and caption (shared/table.mjs).
602
+ table: (d, inline) => cleanTableExtras(
603
+ {
604
+ withHeadings: bool(d.withHeadings),
605
+ stretched: bool(d.stretched),
606
+ content: Array.isArray(d.content) ? d.content.slice(0, TABLE_LIMITS.rows).map(
607
+ (row) => Array.isArray(row) ? row.slice(0, TABLE_LIMITS.cols).map((cell) => inline(cell)) : []
608
+ ) : []
609
+ },
610
+ d,
611
+ inline
612
+ ),
490
613
  image: (d, inline) => {
491
614
  const file = isPlainObject2(d.file) ? d.file : {};
492
615
  const cleanFile = { url: sanitizeUrl(file.url, { schemes: ["http", "https"] }) };
@@ -610,6 +733,12 @@ var BLOCK_POLICIES = {
610
733
  ref: typeof d.ref === "string" && /^[a-z0-9]{1,64}$/.test(d.ref) ? d.ref : "",
611
734
  _mex: BUILT_IN_MARKER_VERSION
612
735
  }),
736
+ // Math block (2.4): only the TeX source is stored; `display: false` renders it in text style.
737
+ math: (d) => ({
738
+ tex: plain(d.tex, MAX_MATH_TEX),
739
+ display: d.display !== false,
740
+ _mex: BUILT_IN_MARKER_VERSION
741
+ }),
613
742
  toc: (d) => {
614
743
  const minLevel = int(d.minLevel, 1, 6, 2);
615
744
  const maxLevel = int(d.maxLevel, 1, 6, 4);
@@ -673,13 +802,13 @@ var ATTRIBUTE_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
673
802
  var isSafeAttributeName = (name) => ATTRIBUTE_NAME.test(name) && !name.startsWith("on") && name !== "style" && name !== "srcdoc";
674
803
  var textNode = (value) => ({ type: "text", value: String(value ?? "") });
675
804
  var el = (tag, attrs, children) => {
676
- const clean = {};
805
+ const clean2 = {};
677
806
  for (const [name, value] of Object.entries(attrs || {})) {
678
807
  if (value === void 0 || value === null || value === false) continue;
679
808
  if (value === "" && name !== "alt") continue;
680
- clean[name] = value === true ? true : String(value);
809
+ clean2[name] = value === true ? true : String(value);
681
810
  }
682
- return { type: "element", tag, attrs: clean, children: toNodes(children) };
811
+ return { type: "element", tag, attrs: clean2, children: toNodes(children) };
683
812
  };
684
813
  var toNodes = (children) => {
685
814
  const out = [];
@@ -826,7 +955,7 @@ var findTagEnd = (html, from) => {
826
955
  }
827
956
  return -1;
828
957
  };
829
- var cleanAttributes = (tag, attribs) => {
958
+ var cleanAttributes = (tag, attribs, options = {}) => {
830
959
  const allowed = INLINE_ATTRIBUTES[tag] || [];
831
960
  const out = {};
832
961
  for (const name of allowed) {
@@ -848,10 +977,40 @@ var cleanAttributes = (tag, attribs) => {
848
977
  out[name] = String(value).slice(0, 2e3);
849
978
  }
850
979
  }
851
- if (tag === "a") Object.assign(out, cleanInternalLinkAttributes(attribs));
980
+ if (tag === "a" && !options.inNote) Object.assign(out, cleanInternalLinkAttributes(attribs));
852
981
  return out;
853
982
  };
854
- var parseInline = (input) => {
983
+ var MAX_MARKER_TEXT = 16;
984
+ var isMathNode = (node) => node.type === "element" && node.tag === "span" && node.attrs[MATH_ATTRIBUTE] === "true";
985
+ var isFootnoteNode = (node) => node.type === "element" && node.tag === "sup" && typeof node.attrs["data-mex-footnote"] === "string";
986
+ var finalizeSpecial = (nodes, depth = 0) => {
987
+ for (const node of nodes) {
988
+ if (node.type !== "element") continue;
989
+ if (isMathNode(node)) {
990
+ const tex = nodesToText(node.children, { raw: true }).replace(/\u200b/g, "").slice(0, MAX_INLINE_TEX);
991
+ node.children = tex ? [{ type: "text", value: tex }] : [];
992
+ } else if (isFootnoteNode(node)) {
993
+ const text = nodesToText(node.children, { raw: true }).slice(0, MAX_MARKER_TEXT);
994
+ node.children = text ? [{ type: "text", value: text }] : [];
995
+ } else if (depth < MAX_DEPTH) finalizeSpecial(node.children, depth + 1);
996
+ }
997
+ return nodes;
998
+ };
999
+ var specialElement = (tag, attribs, options) => {
1000
+ if (tag === "span" && Object.prototype.hasOwnProperty.call(attribs, MATH_ATTRIBUTE)) {
1001
+ if (!/^(?:|true)$/.test(attribs[MATH_ATTRIBUTE])) return null;
1002
+ return { attrs: { [MATH_ATTRIBUTE]: "true" } };
1003
+ }
1004
+ if (tag === "sup" && !options.inNote) {
1005
+ const id = attribs["data-mex-footnote"];
1006
+ if (typeof id !== "string" || !FOOTNOTE_ID.test(id)) return null;
1007
+ const source = typeof attribs["data-mex-note"] === "string" ? attribs["data-mex-note"] : "";
1008
+ const note = parseInline(source.slice(0, MAX_FOOTNOTE_NOTE), { inNote: true });
1009
+ return { attrs: { "data-mex-footnote": id }, note };
1010
+ }
1011
+ return null;
1012
+ };
1013
+ var parseInline = (input, options = {}) => {
855
1014
  const html = typeof input === "string" ? input.slice(0, MAX_INPUT) : "";
856
1015
  const root = { type: "element", tag: "#root", attrs: {}, children: [] };
857
1016
  const stack = [root];
@@ -932,18 +1091,21 @@ var parseInline = (input) => {
932
1091
  continue;
933
1092
  }
934
1093
  if (!ALLOWED.has(tag) || nodes >= MAX_NODES) continue;
1094
+ const attribs = parseAttributes(body);
1095
+ const special = specialElement(tag, attribs, options);
935
1096
  const element = {
936
1097
  type: "element",
937
1098
  tag,
938
- attrs: cleanAttributes(tag, parseAttributes(body)),
1099
+ attrs: special ? special.attrs : cleanAttributes(tag, attribs, options),
939
1100
  children: []
940
1101
  };
1102
+ if (special && special.note) element.note = special.note;
941
1103
  stack[stack.length - 1].children.push(element);
942
1104
  nodes += 1;
943
1105
  if (!VOID.has(tag) && stack.length < MAX_DEPTH) stack.push(element);
944
1106
  }
945
1107
  flush();
946
- return root.children;
1108
+ return finalizeSpecial(root.children);
947
1109
  };
948
1110
  var resolveLinkAttributes = (attrs, resolver) => {
949
1111
  if (typeof resolver !== "function" || !attrs["data-mex-uid"] || !attrs["data-mex-document-id"])
@@ -977,11 +1139,17 @@ var ATTRIBUTE_ORDER = [
977
1139
  "data-mex-uid",
978
1140
  "data-mex-document-id",
979
1141
  "data-mex-locale",
980
- "data-mex-mention"
1142
+ "data-mex-mention",
1143
+ MATH_ATTRIBUTE,
1144
+ "data-mex-footnote",
1145
+ "data-mex-note"
981
1146
  ];
1147
+ var RENDER_STATE = /* @__PURE__ */ Symbol.for("magic-editor-x.render-state");
1148
+ var storedNote = (note) => serializeNodes(inlineNodesToRender(note || [], { storage: true }));
982
1149
  var MENTION_CLASS = "mex-mention";
983
1150
  var inlineNodesToRender = (nodes, options = {}) => {
984
1151
  const out = [];
1152
+ const state = options[RENDER_STATE];
985
1153
  for (const node of nodes) {
986
1154
  if (node.type === "text") {
987
1155
  out.push({ type: "text", value: node.value });
@@ -991,6 +1159,31 @@ var inlineNodesToRender = (nodes, options = {}) => {
991
1159
  out.push({ type: "element", tag: "br", attrs: {}, children: [] });
992
1160
  continue;
993
1161
  }
1162
+ if (isMathNode(node)) {
1163
+ const tex = nodesToText(node.children);
1164
+ if (state && !options.storage) {
1165
+ if (tex.trim()) out.push(state.math(tex, false));
1166
+ continue;
1167
+ }
1168
+ out.push({
1169
+ type: "element",
1170
+ tag: "span",
1171
+ attrs: { [MATH_ATTRIBUTE]: "true" },
1172
+ children: tex ? [{ type: "text", value: tex }] : []
1173
+ });
1174
+ continue;
1175
+ }
1176
+ if (isFootnoteNode(node)) {
1177
+ if (state && !options.storage) {
1178
+ out.push(state.footnote(node));
1179
+ continue;
1180
+ }
1181
+ const attrs2 = { "data-mex-footnote": node.attrs["data-mex-footnote"] };
1182
+ const note = storedNote(node.note);
1183
+ if (note) attrs2["data-mex-note"] = note;
1184
+ out.push({ type: "element", tag: "sup", attrs: attrs2, children: inlineNodesToRender(node.children, options) });
1185
+ continue;
1186
+ }
994
1187
  let attrs = node.attrs;
995
1188
  if (node.tag === "a") {
996
1189
  attrs = resolveLinkAttributes(attrs, options.links);
@@ -1023,13 +1216,369 @@ var inlineNodesToRender = (nodes, options = {}) => {
1023
1216
  };
1024
1217
  var inlineToNodes = (html, options) => inlineNodesToRender(parseInline(html), options);
1025
1218
  var nodesToHtml = (nodes, options = {}) => serializeNodes(inlineNodesToRender(nodes, options));
1026
- var nodesToText = (nodes) => nodes.map((node) => {
1219
+ var nodesToText = (nodes, options = {}) => nodes.map((node) => {
1027
1220
  if (node.type === "text") return node.value;
1028
1221
  if (node.tag === "br") return "\n";
1029
- return nodesToText(node.children);
1222
+ if (!options.raw && isFootnoteNode(node))
1223
+ return typeof options.footnote === "function" ? options.footnote(node) : "";
1224
+ return nodesToText(node.children, options);
1030
1225
  }).join("");
1031
1226
  var inlineToHtml = (html, options) => nodesToHtml(parseInline(html), options);
1032
- var inlineToText = (html) => nodesToText(parseInline(html)).replace(/\u00a0/g, " ");
1227
+ var inlineToText = (html, options) => nodesToText(parseInline(html), options).replace(/\u00a0/g, " ");
1228
+
1229
+ // shared/render/mathml.mjs
1230
+ var MATHML_TAGS = Object.freeze([
1231
+ "math",
1232
+ "semantics",
1233
+ "annotation",
1234
+ "mrow",
1235
+ "mi",
1236
+ "mn",
1237
+ "mo",
1238
+ "ms",
1239
+ "mtext",
1240
+ "mspace",
1241
+ "msub",
1242
+ "msup",
1243
+ "msubsup",
1244
+ "munder",
1245
+ "mover",
1246
+ "munderover",
1247
+ "mfrac",
1248
+ "msqrt",
1249
+ "mroot",
1250
+ "mstyle",
1251
+ "merror",
1252
+ "mpadded",
1253
+ "mphantom",
1254
+ "mtable",
1255
+ "mtr",
1256
+ "mtd",
1257
+ "mlabeledtr",
1258
+ "mmultiscripts",
1259
+ "mprescripts",
1260
+ "none",
1261
+ "menclose"
1262
+ ]);
1263
+ var TAGS = new Set(MATHML_TAGS);
1264
+ var COMMON_ATTRIBUTES = /* @__PURE__ */ new Set([
1265
+ "dir",
1266
+ "displaystyle",
1267
+ "scriptlevel",
1268
+ "mathvariant",
1269
+ "mathsize",
1270
+ "mathcolor",
1271
+ "mathbackground"
1272
+ ]);
1273
+ var ELEMENT_ATTRIBUTES = Object.freeze({
1274
+ math: ["display"],
1275
+ mo: [
1276
+ "form",
1277
+ "fence",
1278
+ "separator",
1279
+ "stretchy",
1280
+ "symmetric",
1281
+ "largeop",
1282
+ "movablelimits",
1283
+ "lspace",
1284
+ "rspace",
1285
+ "minsize",
1286
+ "maxsize",
1287
+ "accent"
1288
+ ],
1289
+ mspace: ["width", "height", "depth"],
1290
+ mpadded: ["width", "height", "depth", "lspace", "voffset"],
1291
+ mfrac: ["linethickness"],
1292
+ mover: ["accent"],
1293
+ munder: ["accentunder"],
1294
+ munderover: ["accent", "accentunder"],
1295
+ mtable: [
1296
+ "columnalign",
1297
+ "rowalign",
1298
+ "columnspacing",
1299
+ "rowspacing",
1300
+ "columnlines",
1301
+ "rowlines",
1302
+ "frame",
1303
+ "framespacing",
1304
+ "equalrows",
1305
+ "equalcolumns",
1306
+ "side"
1307
+ ],
1308
+ mtr: ["columnalign", "rowalign"],
1309
+ mlabeledtr: ["columnalign", "rowalign"],
1310
+ mtd: ["columnalign", "rowalign", "columnspan", "rowspan"],
1311
+ menclose: ["notation"],
1312
+ annotation: ["encoding"]
1313
+ });
1314
+ var ATTRIBUTE_VALUE = /^[A-Za-z0-9 .%#+-]{0,100}$/;
1315
+ var COLOR_VALUE = /^(?:#[0-9A-Fa-f]{3,8}|[A-Za-z]{1,30})$/;
1316
+ var CLASS_TOKEN = /^tml-[a-z0-9-]{1,40}$/;
1317
+ var TEX_ENCODING = "application/x-tex";
1318
+ var MAX_INPUT2 = 2e5;
1319
+ var MAX_NODES2 = 2e4;
1320
+ var MAX_DEPTH2 = 64;
1321
+ var parseAttributes2 = (source) => {
1322
+ const out = {};
1323
+ const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
1324
+ let match;
1325
+ while (match = pattern.exec(source)) {
1326
+ const name = match[1].toLowerCase();
1327
+ if (Object.prototype.hasOwnProperty.call(out, name)) continue;
1328
+ out[name] = decodeEntities(match[2] ?? match[3] ?? match[4] ?? "");
1329
+ }
1330
+ return out;
1331
+ };
1332
+ var styleColor = (style, property) => {
1333
+ const pattern = property === "color" ? /(?:^|;)\s*color\s*:\s*([^;]+)/i : /background-color\s*:\s*([^;]+)/i;
1334
+ const match = pattern.exec(style);
1335
+ const value = match ? match[1].trim() : "";
1336
+ return COLOR_VALUE.test(value) ? value : "";
1337
+ };
1338
+ var cleanAttributes2 = (tag, attribs) => {
1339
+ const out = {};
1340
+ const allowed = ELEMENT_ATTRIBUTES[tag] || [];
1341
+ for (const [name, raw] of Object.entries(attribs)) {
1342
+ if (typeof raw !== "string" && typeof raw !== "number" && raw !== true) continue;
1343
+ const value = raw === true ? "true" : String(raw);
1344
+ if (name === "class") {
1345
+ const classes2 = value.split(/\s+/).filter((token) => CLASS_TOKEN.test(token));
1346
+ if (classes2.length) out.class = classes2.slice(0, 8).join(" ");
1347
+ continue;
1348
+ }
1349
+ if (name === "encoding") {
1350
+ if (tag === "annotation" && value === TEX_ENCODING) out.encoding = value;
1351
+ continue;
1352
+ }
1353
+ if (name === "mathcolor" || name === "mathbackground") {
1354
+ if (COLOR_VALUE.test(value)) out[name] = value;
1355
+ continue;
1356
+ }
1357
+ if (!COMMON_ATTRIBUTES.has(name) && !allowed.includes(name)) continue;
1358
+ if (ATTRIBUTE_VALUE.test(value)) out[name] = value;
1359
+ }
1360
+ if (typeof attribs.style === "string") {
1361
+ const color = styleColor(attribs.style, "color");
1362
+ const background = styleColor(attribs.style, "background-color");
1363
+ if (color && !out.mathcolor) out.mathcolor = color;
1364
+ if (background && !out.mathbackground) out.mathbackground = background;
1365
+ }
1366
+ if (tag === "annotation" && out.encoding !== TEX_ENCODING) return null;
1367
+ if (tag === "math" && out.display && out.display !== "block" && out.display !== "inline")
1368
+ delete out.display;
1369
+ return out;
1370
+ };
1371
+ var tokenize = (input) => {
1372
+ const source = input.slice(0, MAX_INPUT2);
1373
+ const root = { type: "element", tag: "#root", attrs: {}, children: [] };
1374
+ const stack = [root];
1375
+ let count = 0;
1376
+ let i = 0;
1377
+ const pushText = (text) => {
1378
+ if (!text) return;
1379
+ const parent = stack[stack.length - 1];
1380
+ const last = parent.children[parent.children.length - 1];
1381
+ const value = decodeEntities(text);
1382
+ if (last && last.type === "text") last.value += value;
1383
+ else if (count < MAX_NODES2) {
1384
+ parent.children.push({ type: "text", value });
1385
+ count += 1;
1386
+ }
1387
+ };
1388
+ while (i < source.length) {
1389
+ const lt = source.indexOf("<", i);
1390
+ if (lt === -1) {
1391
+ pushText(source.slice(i));
1392
+ break;
1393
+ }
1394
+ pushText(source.slice(i, lt));
1395
+ if (source.startsWith("<!--", lt)) {
1396
+ const end2 = source.indexOf("-->", lt + 4);
1397
+ i = end2 === -1 ? source.length : end2 + 3;
1398
+ continue;
1399
+ }
1400
+ if (source[lt + 1] === "!" || source[lt + 1] === "?") {
1401
+ const end2 = source.indexOf(">", lt + 2);
1402
+ i = end2 === -1 ? source.length : end2 + 1;
1403
+ continue;
1404
+ }
1405
+ const closing = source[lt + 1] === "/";
1406
+ const nameMatch = /^[A-Za-z][A-Za-z0-9:-]{0,40}/.exec(source.slice(lt + (closing ? 2 : 1), lt + 45));
1407
+ let end = -1;
1408
+ let quote = "";
1409
+ for (let j = lt + 1; j < source.length; j += 1) {
1410
+ const char = source[j];
1411
+ if (quote) {
1412
+ if (char === quote) quote = "";
1413
+ } else if (char === '"' || char === "'") quote = char;
1414
+ else if (char === ">") {
1415
+ end = j;
1416
+ break;
1417
+ }
1418
+ }
1419
+ if (!nameMatch || end === -1) {
1420
+ pushText(source.slice(lt, end === -1 ? source.length : lt + 1));
1421
+ i = end === -1 ? source.length : lt + 1;
1422
+ continue;
1423
+ }
1424
+ const tag = nameMatch[0].toLowerCase();
1425
+ const body = source.slice(lt + (closing ? 2 : 1) + nameMatch[0].length, end);
1426
+ i = end + 1;
1427
+ if (closing) {
1428
+ for (let s = stack.length - 1; s > 0; s -= 1) {
1429
+ if (stack[s].tag === tag) {
1430
+ stack.length = s;
1431
+ break;
1432
+ }
1433
+ }
1434
+ continue;
1435
+ }
1436
+ if (count >= MAX_NODES2) continue;
1437
+ const element = { type: "element", tag, attrs: parseAttributes2(body), children: [] };
1438
+ stack[stack.length - 1].children.push(element);
1439
+ count += 1;
1440
+ const selfClosing = /\/\s*$/.test(body);
1441
+ if (!selfClosing && stack.length < MAX_DEPTH2) stack.push(element);
1442
+ }
1443
+ return root.children;
1444
+ };
1445
+ var clean = (nodes, ctx, depth, inAnnotation) => {
1446
+ const out = [];
1447
+ if (!Array.isArray(nodes) || depth > MAX_DEPTH2) return out;
1448
+ for (const node of nodes) {
1449
+ if (ctx.budget <= 0) break;
1450
+ if (typeof node === "string") {
1451
+ ctx.budget -= 1;
1452
+ if (node) out.push({ type: "text", value: node });
1453
+ continue;
1454
+ }
1455
+ if (!node || typeof node !== "object") continue;
1456
+ ctx.budget -= 1;
1457
+ if (node.type === "text") {
1458
+ if (typeof node.value === "string" && node.value) out.push({ type: "text", value: node.value });
1459
+ continue;
1460
+ }
1461
+ if (node.type !== "element" || typeof node.tag !== "string" || inAnnotation) continue;
1462
+ const tag = node.tag.toLowerCase();
1463
+ if (!TAGS.has(tag)) continue;
1464
+ const attrs = cleanAttributes2(tag, node.attrs && typeof node.attrs === "object" ? node.attrs : {});
1465
+ if (!attrs) continue;
1466
+ const children = clean(node.children, ctx, depth + 1, tag === "annotation");
1467
+ out.push({ type: "element", tag, attrs, children });
1468
+ }
1469
+ return out;
1470
+ };
1471
+ var cleanMathResult = (result) => {
1472
+ let nodes;
1473
+ if (typeof result === "string") nodes = tokenize(result);
1474
+ else if (Array.isArray(result)) nodes = result;
1475
+ else if (result && typeof result === "object") nodes = [result];
1476
+ else return [];
1477
+ const top = nodes.filter(
1478
+ (node) => node && typeof node === "object" && node.type === "element" && String(node.tag).toLowerCase() === "math"
1479
+ );
1480
+ return clean(top, { budget: MAX_NODES2 }, 0, false);
1481
+ };
1482
+
1483
+ // shared/render/math-notes.mjs
1484
+ var DEFAULT_FOOTNOTES_LABEL = "Footnotes";
1485
+ var DEFAULT_FOOTNOTE_BACK_LABEL = "Back to reference {n}";
1486
+ var DEFAULT_FOOTNOTE_PREFIX = "mex-";
1487
+ var PREFIX = /^[A-Za-z][A-Za-z0-9_-]{0,40}$/;
1488
+ var label = (value, fallback) => {
1489
+ if (typeof value !== "string") return fallback;
1490
+ const clean2 = value.trim();
1491
+ return clean2 && clean2.length <= 80 ? clean2 : fallback;
1492
+ };
1493
+ var footnoteOptions = (options) => {
1494
+ const source = isPlainObject2(options && options.footnotes) ? options.footnotes : {};
1495
+ return {
1496
+ label: label(source.label, DEFAULT_FOOTNOTES_LABEL),
1497
+ backLabel: label(source.backLabel, DEFAULT_FOOTNOTE_BACK_LABEL),
1498
+ prefix: typeof source.prefix === "string" && PREFIX.test(source.prefix) ? source.prefix : DEFAULT_FOOTNOTE_PREFIX
1499
+ };
1500
+ };
1501
+ var createFootnoteNumbers = () => {
1502
+ const used = /* @__PURE__ */ new Map();
1503
+ let count = 0;
1504
+ return {
1505
+ add(id) {
1506
+ const seen = (used.get(id) || 0) + 1;
1507
+ used.set(id, seen);
1508
+ count += 1;
1509
+ return { n: count, anchor: seen === 1 ? id : `${id}-${seen}` };
1510
+ }
1511
+ };
1512
+ };
1513
+ var renderMathNodes = (options, tex, display) => {
1514
+ if (!options || typeof options.math !== "function" || !tex.trim()) return [];
1515
+ let result;
1516
+ try {
1517
+ result = options.math(tex, { display });
1518
+ } catch {
1519
+ return [];
1520
+ }
1521
+ return cleanMathResult(result);
1522
+ };
1523
+ var mathElement = (options, tex, kind) => {
1524
+ const math = renderMathNodes(options, tex, kind.display);
1525
+ const attrs = {
1526
+ class: kind.className || (kind.display ? "mex-math mex-math-display" : "mex-math"),
1527
+ "data-mex-math": kind.display ? "display" : "inline"
1528
+ };
1529
+ const children = math.length ? math : kind.display ? `\\[${tex}\\]` : `\\(${tex}\\)`;
1530
+ return el(kind.block ? "div" : "span", attrs, children);
1531
+ };
1532
+ var createFootnoteTree = (options, renderNote) => {
1533
+ const { label: listLabel, backLabel, prefix } = footnoteOptions(options);
1534
+ const numbers = createFootnoteNumbers();
1535
+ const items = [];
1536
+ const labelId = `${prefix}footnotes-label`;
1537
+ return {
1538
+ marker(node) {
1539
+ const { n, anchor } = numbers.add(node.attrs["data-mex-footnote"]);
1540
+ items.push({ n, anchor, note: node.note || [] });
1541
+ return el(
1542
+ "sup",
1543
+ { class: "mex-footnote-ref" },
1544
+ el(
1545
+ "a",
1546
+ {
1547
+ href: `#${prefix}fn-${anchor}`,
1548
+ id: `${prefix}fnref-${anchor}`,
1549
+ "aria-describedby": labelId
1550
+ },
1551
+ String(n)
1552
+ )
1553
+ );
1554
+ },
1555
+ section() {
1556
+ if (!items.length) return null;
1557
+ return el("section", { class: "mex-footnotes", "aria-labelledby": labelId }, [
1558
+ el("h2", { id: labelId, class: "mex-footnotes-label" }, listLabel),
1559
+ el(
1560
+ "ol",
1561
+ { class: "mex-footnotes-list" },
1562
+ items.map(
1563
+ (item) => el("li", { id: `${prefix}fn-${item.anchor}`, class: "mex-footnote" }, [
1564
+ renderNote(item.note),
1565
+ " ",
1566
+ el(
1567
+ "a",
1568
+ {
1569
+ href: `#${prefix}fnref-${item.anchor}`,
1570
+ class: "mex-footnote-back",
1571
+ "aria-label": backLabel.replace(/\{n\}/g, String(item.n))
1572
+ },
1573
+ "\u21A9"
1574
+ )
1575
+ ])
1576
+ )
1577
+ )
1578
+ ]);
1579
+ }
1580
+ };
1581
+ };
1033
1582
 
1034
1583
  // shared/blocks/define.mjs
1035
1584
  var BLOCK_FIELD_TYPES = Object.freeze([
@@ -1107,6 +1656,7 @@ var RESERVED_BLOCK_NAMES = Object.freeze([
1107
1656
  "textVariant",
1108
1657
  "indentTune"
1109
1658
  ]);
1659
+ var SDK_COMPATIBLE_NAMES = Object.freeze(["math"]);
1110
1660
  var RESERVED = new Set(RESERVED_BLOCK_NAMES.map((name) => name.toLowerCase()));
1111
1661
  var BLOCK_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{1,49}$/;
1112
1662
  var KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
@@ -1144,7 +1694,7 @@ var BlockDefinitionError = class extends Error {
1144
1694
  this.code = code;
1145
1695
  }
1146
1696
  };
1147
- var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1697
+ var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1148
1698
  var fail = (where, message) => {
1149
1699
  throw new BlockDefinitionError(`Magic Editor X block ${where}: ${message}`);
1150
1700
  };
@@ -1155,7 +1705,7 @@ var boundedInt = (value, min, max, fallback, where, key) => {
1155
1705
  return value;
1156
1706
  };
1157
1707
  var normalizeField = (input, where, depth) => {
1158
- if (!isObject(input)) fail(where, 'a field must be an object with a "type"');
1708
+ if (!isObject2(input)) fail(where, 'a field must be an object with a "type"');
1159
1709
  const type = input.type;
1160
1710
  if (!BLOCK_FIELD_TYPES.includes(type)) fail(where, `unknown field type ${JSON.stringify(type)}`);
1161
1711
  for (const key of Object.keys(input))
@@ -1248,7 +1798,7 @@ var normalizeField = (input, where, depth) => {
1248
1798
  return Object.freeze(out);
1249
1799
  };
1250
1800
  var normalizeFields = (input, where, depth) => {
1251
- if (!isObject(input)) fail(where, '"fields" must be an object of field descriptors');
1801
+ if (!isObject2(input)) fail(where, '"fields" must be an object of field descriptors');
1252
1802
  const keys = Object.keys(input);
1253
1803
  if (keys.length < 1 || keys.length > BLOCK_LIMITS.maxFields)
1254
1804
  fail(where, `an object needs 1 to ${BLOCK_LIMITS.maxFields} fields`);
@@ -1267,20 +1817,20 @@ var blockNameProblem = (name) => {
1267
1817
  return null;
1268
1818
  };
1269
1819
  var defineBlock = (definition) => {
1270
- if (!isObject(definition))
1820
+ if (!isObject2(definition))
1271
1821
  throw new BlockDefinitionError("Magic Editor X block: the definition must be an object");
1272
- const label2 = typeof definition.name === "string" ? `"${definition.name.slice(0, 50)}"` : "(no name)";
1822
+ const label3 = typeof definition.name === "string" ? `"${definition.name.slice(0, 50)}"` : "(no name)";
1273
1823
  for (const key of Object.keys(definition))
1274
- if (!DEFINITION_KEYS.has(key)) fail(label2, `unknown key "${key}"`);
1824
+ if (!DEFINITION_KEYS.has(key)) fail(label3, `unknown key "${key}"`);
1275
1825
  const problem = blockNameProblem(definition.name);
1276
1826
  if (problem)
1277
1827
  throw new BlockDefinitionError(
1278
- `Magic Editor X block ${label2}: ${problem}`,
1828
+ `Magic Editor X block ${label3}: ${problem}`,
1279
1829
  problem.includes("built-in") ? "RESERVED_NAME" : "INVALID_DEFINITION"
1280
1830
  );
1281
1831
  const out = {
1282
1832
  name: definition.name,
1283
- version: boundedInt(definition.version, 1, 1e6, 1, label2, "version")
1833
+ version: boundedInt(definition.version, 1, 1e6, 1, label3, "version")
1284
1834
  };
1285
1835
  for (const [key, max] of [
1286
1836
  ["title", 100],
@@ -1288,18 +1838,18 @@ var defineBlock = (definition) => {
1288
1838
  ]) {
1289
1839
  if (definition[key] === void 0) continue;
1290
1840
  if (typeof definition[key] !== "string" || definition[key].length > max)
1291
- fail(label2, `"${key}" must be a string of at most ${max} characters`);
1841
+ fail(label3, `"${key}" must be a string of at most ${max} characters`);
1292
1842
  out[key] = definition[key];
1293
1843
  }
1294
- out.schema = normalizeFields(definition.schema, `${label2} schema`, 0);
1844
+ out.schema = normalizeFields(definition.schema, `${label3} schema`, 0);
1295
1845
  for (const key of ["sanitize", "text", "markdown", "render"]) {
1296
1846
  if (definition[key] === void 0) continue;
1297
- if (typeof definition[key] !== "function") fail(label2, `"${key}" must be a function`);
1847
+ if (typeof definition[key] !== "function") fail(label3, `"${key}" must be a function`);
1298
1848
  out[key] = definition[key];
1299
1849
  }
1300
1850
  const presets = definition.presets === void 0 ? [] : definition.presets;
1301
1851
  if (!Array.isArray(presets) || presets.some((preset) => !BLOCK_PRESETS.includes(preset)))
1302
- fail(label2, `"presets" must list some of ${BLOCK_PRESETS.join(", ")}`);
1852
+ fail(label3, `"presets" must list some of ${BLOCK_PRESETS.join(", ")}`);
1303
1853
  out.presets = Object.freeze([...new Set(presets)]);
1304
1854
  return Object.freeze(out);
1305
1855
  };
@@ -1327,13 +1877,13 @@ var cleanValue = (field, value, inline, budget) => {
1327
1877
  for (const item of value) {
1328
1878
  if (out.length >= field.max || budget.left <= 0) break;
1329
1879
  if (!matchesType(field.items, item)) continue;
1330
- const clean = cleanValue(field.items, item, inline, budget);
1331
- if (clean !== void 0) out.push(clean);
1880
+ const clean2 = cleanValue(field.items, item, inline, budget);
1881
+ if (clean2 !== void 0) out.push(clean2);
1332
1882
  }
1333
1883
  return out;
1334
1884
  }
1335
1885
  case "object":
1336
- return cleanObject(field.fields, isObject(value) ? value : {}, inline, budget);
1886
+ return cleanObject(field.fields, isObject2(value) ? value : {}, inline, budget);
1337
1887
  default:
1338
1888
  return void 0;
1339
1889
  }
@@ -1352,15 +1902,15 @@ var matchesType = (field, item) => {
1352
1902
  case "array":
1353
1903
  return Array.isArray(item);
1354
1904
  default:
1355
- return isObject(item);
1905
+ return isObject2(item);
1356
1906
  }
1357
1907
  };
1358
1908
  var cleanObject = (fields, value, inline, budget) => {
1359
1909
  const out = {};
1360
1910
  for (const key of Object.keys(fields)) {
1361
1911
  const own = Object.prototype.hasOwnProperty.call(value, key) ? value[key] : void 0;
1362
- const clean = cleanValue(fields[key], own, inline, budget);
1363
- if (clean !== void 0) out[key] = clean;
1912
+ const clean2 = cleanValue(fields[key], own, inline, budget);
1913
+ if (clean2 !== void 0) out[key] = clean2;
1364
1914
  }
1365
1915
  return out;
1366
1916
  };
@@ -1371,13 +1921,13 @@ var eachLeaf = (fields, data, visit) => {
1371
1921
  if (!Array.isArray(value)) return;
1372
1922
  value.slice(0, field.max).forEach((item, index) => walk(field.items, item, [...path, index], depth + 1));
1373
1923
  } else if (field.type === "object") {
1374
- if (!isObject(value)) return;
1924
+ if (!isObject2(value)) return;
1375
1925
  for (const key of Object.keys(field.fields))
1376
1926
  if (Object.prototype.hasOwnProperty.call(value, key))
1377
1927
  walk(field.fields[key], value[key], [...path, key], depth + 1);
1378
1928
  } else visit(field, value, path);
1379
1929
  };
1380
- if (!isObject(data)) return;
1930
+ if (!isObject2(data)) return;
1381
1931
  for (const key of Object.keys(fields))
1382
1932
  if (Object.prototype.hasOwnProperty.call(data, key)) walk(fields[key], data[key], [key], 0);
1383
1933
  };
@@ -1403,7 +1953,7 @@ var compileBlock = (definition) => {
1403
1953
  return compiled.get(definition);
1404
1954
  const def = defineBlock(definition && typeof definition === "object" ? { ...definition } : definition);
1405
1955
  const schema = def.schema;
1406
- const run = (data, inline) => cleanObject(schema, isObject(data) ? data : {}, inline, { left: BLOCK_LIMITS.maxValues });
1956
+ const run = (data, inline) => cleanObject(schema, isObject2(data) ? data : {}, inline, { left: BLOCK_LIMITS.maxValues });
1407
1957
  const result = Object.freeze({
1408
1958
  ...def,
1409
1959
  /**
@@ -1424,7 +1974,7 @@ var compileBlock = (definition) => {
1424
1974
  } catch {
1425
1975
  return first;
1426
1976
  }
1427
- return isObject(next) ? run(next, inline) : first;
1977
+ return isObject2(next) ? run(next, inline) : first;
1428
1978
  },
1429
1979
  /**
1430
1980
  * Text fields of the data in schema order: `{ path, kind, value }`
@@ -1472,7 +2022,7 @@ var compileBlock = (definition) => {
1472
2022
  };
1473
2023
  var copyData = (value) => {
1474
2024
  if (Array.isArray(value)) return value.map(copyData);
1475
- if (isObject(value)) {
2025
+ if (isObject2(value)) {
1476
2026
  const out = {};
1477
2027
  for (const [key, child] of Object.entries(value)) out[key] = copyData(child);
1478
2028
  return out;
@@ -1716,12 +2266,12 @@ var prepareBlocks = (value, options = {}) => {
1716
2266
  const raw = isPlainObject2(block.data) ? block.data : {};
1717
2267
  const known = isBuiltInBlock({ type: block.type, data: raw });
1718
2268
  const definition = known ? null : registeredBlockOf({ type: block.type, data: raw }, explicit);
1719
- const clean = known ? BLOCK_POLICIES[block.type](raw, keepInline, ctx) : definition ? definition.clean(raw, keepInline) : raw;
1720
- for (const key of Object.keys(clean)) if (clean[key] === void 0) delete clean[key];
2269
+ const clean2 = known ? BLOCK_POLICIES[block.type](raw, keepInline, ctx) : definition ? definition.clean(raw, keepInline) : raw;
2270
+ for (const key of Object.keys(clean2)) if (clean2[key] === void 0) delete clean2[key];
1721
2271
  return {
1722
2272
  id: block.id,
1723
2273
  type: block.type,
1724
- data: clean,
2274
+ data: clean2,
1725
2275
  raw,
1726
2276
  tunes: sanitizeTunes(block.tunes),
1727
2277
  known,
@@ -1751,10 +2301,10 @@ var imageCandidates = (file) => {
1751
2301
  const out = [];
1752
2302
  const seen = /* @__PURE__ */ new Set();
1753
2303
  const push = (url, width) => {
1754
- const clean = sanitizeUrl(url, { schemes: ["http", "https"] });
1755
- if (!clean || !Number.isInteger(width) || width <= 0 || seen.has(width)) return;
2304
+ const clean2 = sanitizeUrl(url, { schemes: ["http", "https"] });
2305
+ if (!clean2 || !Number.isInteger(width) || width <= 0 || seen.has(width)) return;
1756
2306
  seen.add(width);
1757
- out.push({ url: clean, width });
2307
+ out.push({ url: clean2, width });
1758
2308
  };
1759
2309
  if (isPlainObject2(file.formats)) {
1760
2310
  const names = Object.keys(file.formats).sort(
@@ -1970,20 +2520,20 @@ var mediaFigure = (tag, b, o) => {
1970
2520
  caption.length ? el("figcaption", {}, caption) : null
1971
2521
  ]);
1972
2522
  };
1973
- var label = (value, fallback) => {
2523
+ var label2 = (value, fallback) => {
1974
2524
  if (typeof value !== "string") return fallback;
1975
- const clean = value.trim();
1976
- return clean && clean.length <= 80 ? clean : fallback;
2525
+ const clean2 = value.trim();
2526
+ return clean2 && clean2.length <= 80 ? clean2 : fallback;
1977
2527
  };
1978
- var tocLabel = (options) => label(isPlainObject2(options.toc) ? options.toc.label : void 0, "Table of contents");
2528
+ var tocLabel = (options) => label2(isPlainObject2(options.toc) ? options.toc.label : void 0, "Table of contents");
1979
2529
  var codeOptions = (options) => {
1980
2530
  const code = isPlainObject2(options.code) ? options.code : {};
1981
2531
  const lineNumbers = code.lineNumbers === true ? "all" : code.lineNumbers === "block" ? "block" : "none";
1982
2532
  const button = code.copyButton;
1983
2533
  const copy = button === true || isPlainObject2(button) ? {
1984
- label: label(isPlainObject2(button) ? button.label : void 0, "Copy code"),
1985
- copied: label(isPlainObject2(button) ? button.copiedLabel : void 0, "Copied"),
1986
- failed: label(isPlainObject2(button) ? button.failedLabel : void 0, "Copy failed")
2534
+ label: label2(isPlainObject2(button) ? button.label : void 0, "Copy code"),
2535
+ copied: label2(isPlainObject2(button) ? button.copiedLabel : void 0, "Copied"),
2536
+ failed: label2(isPlainObject2(button) ? button.failedLabel : void 0, "Copy failed")
1987
2537
  } : null;
1988
2538
  return { lineNumbers, copy };
1989
2539
  };
@@ -2012,23 +2562,29 @@ var codeBlock = (b, language, o) => {
2012
2562
  },
2013
2563
  el("code", language ? { class: `language-${language}` } : {}, numbers ? numberedLines(code) : code)
2014
2564
  );
2015
- if (!copy) return pre;
2016
- return el("div", { class: "mex-code-block", "data-mex-code": "copy" }, [
2017
- pre,
2018
- el(
2019
- "button",
2020
- {
2021
- type: "button",
2022
- class: "mex-code-copy",
2023
- "data-mex-copy": "code",
2024
- "data-mex-copied": copy.copied,
2025
- "data-mex-failed": copy.failed
2026
- },
2027
- copy.label
2028
- ),
2029
- el("span", { class: "mex-code-copy-status", role: "status", "aria-live": "polite" })
2565
+ const block = copy ? copyBlock(pre, copy) : pre;
2566
+ const filename = b.type === "codeFlask" && typeof b.data.filename === "string" ? b.data.filename : "";
2567
+ if (!filename) return block;
2568
+ return el("figure", { class: "mex-code-figure" }, [
2569
+ el("figcaption", { class: "mex-code-filename" }, filename),
2570
+ block
2030
2571
  ]);
2031
2572
  };
2573
+ var copyBlock = (pre, copy) => el("div", { class: "mex-code-block", "data-mex-code": "copy" }, [
2574
+ pre,
2575
+ el(
2576
+ "button",
2577
+ {
2578
+ type: "button",
2579
+ class: "mex-code-copy",
2580
+ "data-mex-copy": "code",
2581
+ "data-mex-copied": copy.copied,
2582
+ "data-mex-failed": copy.failed
2583
+ },
2584
+ copy.label
2585
+ ),
2586
+ el("span", { class: "mex-code-copy-status", role: "status", "aria-live": "polite" })
2587
+ ]);
2032
2588
  var RENDERERS = {
2033
2589
  paragraph: (b, o) => el("p", { class: classes(["mex-paragraph"], b.tunes) }, inlineToNodes(b.data.text, o)),
2034
2590
  header: (b, o) => el(
@@ -2103,20 +2659,29 @@ var RENDERERS = {
2103
2659
  const html = o.sanitizeRaw(String(b.raw.html || ""));
2104
2660
  return typeof html === "string" && html ? el("div", { class: classes(["mex-raw"], b.tunes) }, { type: "raw", html }) : null;
2105
2661
  },
2662
+ // Header row: <thead> with <th scope="col">; header column (2.4): <th scope="row">;
2663
+ // merged cells: colspan/rowspan (covered cells are left out); alignment: a class.
2106
2664
  table: (b, o) => {
2107
- const rows = b.data.content;
2665
+ const rows = tableLayout(b.data);
2108
2666
  if (!rows.length) return null;
2109
- const cells = (row, tag) => el(
2110
- "tr",
2111
- {},
2112
- row.map((cell) => el(tag, tag === "th" ? { scope: "col" } : {}, inlineToNodes(cell, o)))
2667
+ const cell = (item) => el(
2668
+ item.header ? "th" : "td",
2669
+ {
2670
+ ...item.header ? { scope: item.header } : {},
2671
+ ...item.colspan > 1 ? { colspan: String(item.colspan) } : {},
2672
+ ...item.rowspan > 1 ? { rowspan: String(item.rowspan) } : {},
2673
+ ...item.align ? { class: `mex-align-${item.align}` } : {}
2674
+ },
2675
+ inlineToNodes(item.html, o)
2113
2676
  );
2114
- const head = b.data.withHeadings ? el("thead", {}, cells(rows[0], "th")) : null;
2115
- const body = (b.data.withHeadings ? rows.slice(1) : rows).map((row) => cells(row, "td"));
2677
+ const tr = (row) => el("tr", {}, row.map(cell));
2678
+ const head = b.data.withHeadings ? el("thead", {}, tr(rows[0])) : null;
2679
+ const body = (b.data.withHeadings ? rows.slice(1) : rows).map(tr);
2680
+ const caption = b.data.caption ? el("caption", {}, inlineToNodes(b.data.caption, o)) : null;
2116
2681
  return el(
2117
2682
  "table",
2118
2683
  { class: classes(["mex-table", ...b.data.stretched ? ["mex-stretched"] : []], b.tunes) },
2119
- [head, body.length ? el("tbody", {}, body) : null]
2684
+ [caption, head, body.length ? el("tbody", {}, body) : null]
2120
2685
  );
2121
2686
  },
2122
2687
  image: (b, o) => {
@@ -2209,11 +2774,11 @@ var RENDERERS = {
2209
2774
  embed: (b, o) => {
2210
2775
  const hosts = Array.isArray(o.embedHosts) ? o.embedHosts.map((h) => String(h).toLowerCase()) : DEFAULT_EMBED_HOSTS;
2211
2776
  const frame = embedFrameUrl(b.data.embed, hosts);
2777
+ const href = b.data.source || b.data.embed;
2778
+ if (!frame && !href) return null;
2212
2779
  const caption = inlineToNodes(b.data.caption, o);
2213
2780
  const title = inlineToText(b.data.caption) || b.data.service || "Embedded content";
2214
2781
  if (!frame) {
2215
- const href = b.data.source || b.data.embed;
2216
- if (!href) return null;
2217
2782
  return el(
2218
2783
  "p",
2219
2784
  { class: classes(["mex-embed", "mex-embed-link"], b.tunes) },
@@ -2273,6 +2838,15 @@ var RENDERERS = {
2273
2838
  return el("p", { class: classes(["mex-button-block"], b.tunes) }, inner);
2274
2839
  },
2275
2840
  delimiter: (b) => el("hr", { class: classes(["mex-delimiter"], b.tunes) }),
2841
+ // Math block (2.4): MathML from `options.math`, else the delimited TeX source.
2842
+ math: (b, o) => b.data.tex.trim() ? mathElement(o, b.data.tex, {
2843
+ display: b.data.display !== false,
2844
+ block: true,
2845
+ className: classes(
2846
+ ["mex-math", ...b.data.display !== false ? ["mex-math-display"] : []],
2847
+ b.tunes
2848
+ )
2849
+ }) : null,
2276
2850
  toc: (b, o) => {
2277
2851
  const tree = buildTocTree(b.headings || [], b.data);
2278
2852
  if (!tree.length) return null;
@@ -2365,15 +2939,15 @@ var RESOURCE_ATTRIBUTES = /* @__PURE__ */ new Set(["src", "poster", "data", "bac
2365
2939
  var cleanUrlAttribute = (name, value) => {
2366
2940
  if (name === "srcset" || name === "imagesrcset") {
2367
2941
  const parts = value.split(",").map((part) => part.trim());
2368
- const clean = [];
2942
+ const clean2 = [];
2369
2943
  for (const part of parts) {
2370
2944
  const [url, descriptor, extra] = part.split(/\s+/);
2371
2945
  if (extra !== void 0 || descriptor && !/^\d+(?:\.\d+)?[wx]$/.test(descriptor)) return "";
2372
2946
  const safe = sanitizeUrl(url, { schemes: ["http", "https"] });
2373
2947
  if (!safe) return "";
2374
- clean.push(descriptor ? `${safe} ${descriptor}` : safe);
2948
+ clean2.push(descriptor ? `${safe} ${descriptor}` : safe);
2375
2949
  }
2376
- return clean.join(", ");
2950
+ return clean2.join(", ");
2377
2951
  }
2378
2952
  return sanitizeUrl(value, { schemes: RESOURCE_ATTRIBUTES.has(name) ? ["http", "https"] : LINK_SCHEMES });
2379
2953
  };
@@ -2431,7 +3005,13 @@ var cleanOverrideNodes = (input, trusted) => {
2431
3005
  };
2432
3006
  var rawAllowed = (options) => options.rawHtml === "allow" && typeof options.sanitizeRaw === "function";
2433
3007
  var createTreeBuilder = (value, options, mode = {}) => {
2434
- const opts = options && typeof options === "object" ? options : {};
3008
+ const base = options && typeof options === "object" ? options : {};
3009
+ const opts = { ...base };
3010
+ const footnotes = createFootnoteTree(base, (note) => inlineNodesToRender(note, opts));
3011
+ opts[RENDER_STATE] = {
3012
+ math: (tex) => mathElement(base, tex, { display: false, block: false }),
3013
+ footnote: (node) => footnotes.marker(node)
3014
+ };
2435
3015
  const publicOf = /* @__PURE__ */ new WeakMap();
2436
3016
  const preparedOf = /* @__PURE__ */ new WeakMap();
2437
3017
  const trusted = /* @__PURE__ */ new WeakSet();
@@ -2515,6 +3095,8 @@ var createTreeBuilder = (value, options, mode = {}) => {
2515
3095
  childNodes: renderBlocks
2516
3096
  };
2517
3097
  const nodes = renderList(annotateHeadings(prepareBlocks(value, opts), opts));
3098
+ const section = footnotes.section();
3099
+ if (section) nodes.push(textNode("\n"), section);
2518
3100
  return { nodes, renderBlocks, helpers };
2519
3101
  };
2520
3102