magic-editor-x 2.3.1 → 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 +74 -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-CFP3lp9p.js → ConfigurationPage-D6uya-J1.js} +228 -13
  6. package/dist/admin/{ConfigurationPage-CYGDLjM7.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-B5Q33N-s.mjs → CustomBlocksPage-Byt10-6c.mjs} +6 -4
  10. package/dist/admin/{CustomBlocksPage-DzPOSpfn.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-BVkgafCK.js → TemplatesPage-DrSJdteI.js} +313 -17
  14. package/dist/admin/{TemplatesPage-4A8JNO_Z.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-DQVE0ymw.js → index-64wc26Bl.js} +17467 -10369
  46. package/dist/admin/{index-k8_a5o1A.mjs → index-BVjf1gVC.mjs} +13786 -6687
  47. package/dist/admin/{index-DR8sHkTk.js → index-D6Z7i8ba.js} +1003 -53
  48. package/dist/admin/{index-My6FjjHB.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-DNphiBQR.js → useT-BXJLIPN4.js} +1 -1
  60. package/dist/admin/{useT-Cmg1jwwG.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
@@ -56,13 +56,13 @@ var ATTRIBUTE_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
56
56
  var isSafeAttributeName = (name) => ATTRIBUTE_NAME.test(name) && !name.startsWith("on") && name !== "style" && name !== "srcdoc";
57
57
  var textNode = (value) => ({ type: "text", value: String(value ?? "") });
58
58
  var el = (tag, attrs, children) => {
59
- const clean = {};
59
+ const clean2 = {};
60
60
  for (const [name, value] of Object.entries(attrs || {})) {
61
61
  if (value === void 0 || value === null || value === false) continue;
62
62
  if (value === "" && name !== "alt") continue;
63
- clean[name] = value === true ? true : String(value);
63
+ clean2[name] = value === true ? true : String(value);
64
64
  }
65
- return { type: "element", tag, attrs: clean, children: toNodes(children) };
65
+ return { type: "element", tag, attrs: clean2, children: toNodes(children) };
66
66
  };
67
67
  var toNodes = (children) => {
68
68
  const out = [];
@@ -130,7 +130,9 @@ var MARKED_BLOCKS = Object.freeze({
130
130
  keys: Object.freeze(["file", "title", "caption", "loop", "tracks"]),
131
131
  anchor: Object.freeze(["file", "object"])
132
132
  }),
133
- synced: Object.freeze({ keys: Object.freeze(["ref"]), anchor: Object.freeze(["ref", "string"]) })
133
+ synced: Object.freeze({ keys: Object.freeze(["ref"]), anchor: Object.freeze(["ref", "string"]) }),
134
+ // 2.4: math block. A Settings custom block named `math` could exist before 2.4.
135
+ math: Object.freeze({ keys: Object.freeze(["tex", "display"]), anchor: Object.freeze(["tex", "string"]) })
134
136
  });
135
137
  var isBuiltInMarker = (value) => Number.isInteger(value) && /** @type {number} */
136
138
  value >= 1;
@@ -149,6 +151,10 @@ var isMarkedBuiltIn = (type, data) => {
149
151
  return hasBuiltInShape(MARKED_BLOCKS[type], data);
150
152
  };
151
153
 
154
+ // shared/field-identity.mjs
155
+ var FIELD_KEY_PATTERN = /^[A-Za-z0-9_-]{16,32}$/;
156
+ var isValidFieldKey = (value) => typeof value === "string" && FIELD_KEY_PATTERN.test(value);
157
+
152
158
  // shared/editor-data.mjs
153
159
  var EDITOR_DATA_LIMITS = Object.freeze({
154
160
  maxBlocks: 5e3,
@@ -261,8 +267,8 @@ var normalizeEditorData = (value) => {
261
267
  if (!isPlainObject2(candidate)) {
262
268
  throw new EditorDataError("Editor content must be an Editor.js object", "INVALID_SHAPE");
263
269
  }
264
- const clean = cloneJsonSafe(candidate);
265
- const rawBlocks = Array.isArray(clean.blocks) ? clean.blocks : [];
270
+ const clean2 = cloneJsonSafe(candidate);
271
+ const rawBlocks = Array.isArray(clean2.blocks) ? clean2.blocks : [];
266
272
  if (rawBlocks.length > EDITOR_DATA_LIMITS.maxBlocks) {
267
273
  throw new EditorDataError("Editor content has too many blocks", "TOO_MANY_BLOCKS");
268
274
  }
@@ -281,9 +287,10 @@ var normalizeEditorData = (value) => {
281
287
  if (isPlainObject2(block.tunes) && Object.keys(block.tunes).length > 0) normalized.tunes = block.tunes;
282
288
  blocks.push(normalized);
283
289
  });
284
- const time = Number.isFinite(clean.time) && clean.time > 0 ? Math.floor(clean.time) : 0;
285
- const version = typeof clean.version === "string" && clean.version.length <= 32 ? clean.version : "2.31.7";
290
+ const time = Number.isFinite(clean2.time) && clean2.time > 0 ? Math.floor(clean2.time) : 0;
291
+ const version = typeof clean2.version === "string" && clean2.version.length <= 32 ? clean2.version : "2.31.7";
286
292
  const result = { time, blocks, version };
293
+ if (isValidFieldKey(clean2.fieldKey)) result.fieldKey = clean2.fieldKey;
287
294
  const size = byteLength(JSON.stringify(result));
288
295
  if (size > EDITOR_DATA_LIMITS.maxBytes) {
289
296
  throw new EditorDataError("Editor content exceeds the size limit", "TOO_LARGE");
@@ -311,6 +318,95 @@ var byteLength = (text) => {
311
318
  return bytes;
312
319
  };
313
320
 
321
+ // shared/table.mjs
322
+ var TABLE_LIMITS = Object.freeze({ rows: 500, cols: 100, merges: 1e3, caption: 4e3 });
323
+ var TABLE_ALIGNS = Object.freeze(["left", "center", "right"]);
324
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
325
+ var tableWidth = (content) => Array.isArray(content) ? content.reduce((width, row) => Math.max(width, Array.isArray(row) ? row.length : 0), 0) : 0;
326
+ var cleanTableAlign = (value, cols) => {
327
+ if (!Array.isArray(value) || cols <= 0) return null;
328
+ const out = value.slice(0, Math.min(cols, TABLE_LIMITS.cols)).map((item) => typeof item === "string" && TABLE_ALIGNS.includes(item) ? item : null);
329
+ while (out.length && out[out.length - 1] === null) out.pop();
330
+ return out.length ? out : null;
331
+ };
332
+ 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;
333
+ var normalizeMerges = (merges, rows, cols, options = {}) => {
334
+ if (!Array.isArray(merges) || rows <= 0 || cols <= 0) return [];
335
+ const out = [];
336
+ for (const merge of merges.slice(0, TABLE_LIMITS.merges)) {
337
+ if (!isObject(merge)) continue;
338
+ const { row, col, rowspan, colspan } = merge;
339
+ if (![row, col, rowspan, colspan].every(Number.isInteger)) continue;
340
+ if (row < 0 || col < 0 || rowspan < 1 || colspan < 1 || rowspan * colspan < 2) continue;
341
+ if (row + rowspan > rows || col + colspan > cols) continue;
342
+ if (options.headerRow && row === 0 && rowspan > 1) continue;
343
+ const next = { row, col, rowspan, colspan };
344
+ if (out.some((other) => intersects(other, next))) continue;
345
+ out.push(next);
346
+ }
347
+ return out.sort((a, b) => a.row - b.row || a.col - b.col);
348
+ };
349
+ var mergeMap = (merges) => {
350
+ const anchors = /* @__PURE__ */ new Map();
351
+ const covered = /* @__PURE__ */ new Map();
352
+ for (const merge of merges || []) {
353
+ anchors.set(`${merge.row}:${merge.col}`, merge);
354
+ for (let r = merge.row; r < merge.row + merge.rowspan; r += 1)
355
+ for (let c = merge.col; c < merge.col + merge.colspan; c += 1)
356
+ if (r !== merge.row || c !== merge.col) covered.set(`${r}:${c}`, merge);
357
+ }
358
+ return { anchors, covered };
359
+ };
360
+ var headerKind = (data, row, col) => {
361
+ if (data.withHeadings === true && row === 0) return "col";
362
+ if (data.headerColumn === true && col === 0) return "row";
363
+ return null;
364
+ };
365
+ var tableLayout = (data) => {
366
+ const merges = Array.isArray(data.merges) ? data.merges : [];
367
+ const { anchors, covered } = mergeMap(merges);
368
+ const align = Array.isArray(data.align) ? data.align : [];
369
+ return (data.content || []).map(
370
+ (row, r) => row.map((html, c) => {
371
+ if (covered.has(`${r}:${c}`)) return null;
372
+ const merge = anchors.get(`${r}:${c}`);
373
+ return {
374
+ row: r,
375
+ col: c,
376
+ html,
377
+ rowspan: merge ? merge.rowspan : 1,
378
+ colspan: merge ? merge.colspan : 1,
379
+ header: headerKind(data, r, c),
380
+ align: typeof align[c] === "string" ? align[c] : null
381
+ };
382
+ }).filter(Boolean)
383
+ );
384
+ };
385
+ var isBlankInlineHtml = (html) => typeof html !== "string" || /^(?:\s|&nbsp;|&#160;|\u00a0|<br\s*\/?>)*$/i.test(html);
386
+ var cleanTableExtras = (out, d, inline) => {
387
+ if (d.headerColumn === true) out.headerColumn = true;
388
+ const rows = out.content.length;
389
+ const cols = tableWidth(out.content);
390
+ const align = cleanTableAlign(d.align, cols);
391
+ if (align) out.align = align;
392
+ const merges = normalizeMerges(d.merges, rows, cols, { headerRow: out.withHeadings === true });
393
+ if (merges.length) {
394
+ const { covered } = mergeMap(merges);
395
+ out.content = out.content.map(
396
+ (row, r) => Array.from(
397
+ { length: cols },
398
+ (_, c) => covered.has(`${r}:${c}`) ? "" : row[c] === void 0 ? "" : row[c]
399
+ )
400
+ );
401
+ out.merges = merges;
402
+ }
403
+ if (typeof d.caption === "string") {
404
+ const caption = inline(d.caption.slice(0, TABLE_LIMITS.caption));
405
+ if (!isBlankInlineHtml(caption)) out.caption = caption;
406
+ }
407
+ return out;
408
+ };
409
+
314
410
  // shared/sanitize-policy.mjs
315
411
  var INLINE_TAGS = Object.freeze([
316
412
  "b",
@@ -354,9 +450,16 @@ var cleanInternalLinkAttributes = (attribs) => {
354
450
  var isMentionLink = (attrs) => Boolean(
355
451
  attrs && attrs["data-mex-mention"] === "true" && attrs["data-mex-uid"] && attrs["data-mex-document-id"]
356
452
  );
453
+ var MATH_ATTRIBUTE = "data-mex-math";
454
+ var FOOTNOTE_ATTRIBUTES = Object.freeze(["data-mex-footnote", "data-mex-note"]);
455
+ var FOOTNOTE_ID = /^[A-Za-z0-9_-]{1,64}$/;
456
+ var MAX_MATH_TEX = 1e4;
457
+ var MAX_INLINE_TEX = 2e3;
458
+ var MAX_FOOTNOTE_NOTE = 4e3;
357
459
  var INLINE_ATTRIBUTES = Object.freeze({
358
460
  a: ["href", "target", "rel", "title", ...INTERNAL_LINK_ATTRIBUTES],
359
- span: ["class", "data-tooltip"],
461
+ span: ["class", "data-tooltip", MATH_ATTRIBUTE],
462
+ sup: [...FOOTNOTE_ATTRIBUTES],
360
463
  mark: ["class"],
361
464
  u: ["class"],
362
465
  s: ["class"],
@@ -439,17 +542,17 @@ var mediaTracks = (tracks) => {
439
542
  if (!isPlainObject2(track)) continue;
440
543
  const file = cleanMediaFile(track.file, { vtt: true });
441
544
  if (!file.url) continue;
442
- const clean = {
545
+ const clean2 = {
443
546
  file,
444
547
  kind: oneOf(track.kind, TRACK_KINDS, "captions"),
445
548
  srclang: typeof track.srclang === "string" && SRCLANG.test(track.srclang) ? track.srclang : "",
446
549
  label: plain(track.label, 100)
447
550
  };
448
551
  if (track.default === true && !hasDefault) {
449
- clean.default = true;
552
+ clean2.default = true;
450
553
  hasDefault = true;
451
554
  }
452
- out.push(clean);
555
+ out.push(clean2);
453
556
  }
454
557
  return out;
455
558
  };
@@ -492,6 +595,17 @@ var listItems = (items, inline, depth = 0) => {
492
595
  return out;
493
596
  });
494
597
  };
598
+ var MAX_CODE_FILENAME = 200;
599
+ var FILENAME_STRIP = (
600
+ // eslint-disable-next-line no-control-regex -- the point is to remove control characters
601
+ /[\u0000-\u001f\u007f-\u009f\u061c\u200b-\u200f\u2028-\u202e\u2060\u2066-\u2069\ufeff]/g
602
+ );
603
+ var cleanCodeFilename = (value) => {
604
+ if (typeof value !== "string") return "";
605
+ return Array.from(
606
+ value.slice(0, 4 * MAX_CODE_FILENAME).replace(/[\t\n\r\f\v]/g, " ").replace(FILENAME_STRIP, "").replace(/\s+/g, " ").trim()
607
+ ).slice(0, MAX_CODE_FILENAME).join("").trim();
608
+ };
495
609
  var BLOCK_POLICIES = {
496
610
  paragraph: (d, inline) => ({ text: inline(d.text) }),
497
611
  header: (d, inline) => ({ text: inline(d.text), level: int(d.level, 1, 6, 2) }),
@@ -546,6 +660,8 @@ var BLOCK_POLICIES = {
546
660
  language: typeof d.language === "string" && /^[a-z0-9+#-]{1,32}$/i.test(d.language) ? d.language : "plaintext"
547
661
  };
548
662
  if (typeof d.showlinenumbers === "boolean") out.showlinenumbers = d.showlinenumbers;
663
+ const filename = cleanCodeFilename(d.filename);
664
+ if (filename) out.filename = filename;
549
665
  return out;
550
666
  },
551
667
  raw: (d, _inline, ctx) => {
@@ -554,11 +670,18 @@ var BLOCK_POLICIES = {
554
670
  if (ctx.rawHtml === "disable") return { html: "" };
555
671
  return { html: ctx.rawSanitizer(html) };
556
672
  },
557
- table: (d, inline) => ({
558
- withHeadings: bool(d.withHeadings),
559
- stretched: bool(d.stretched),
560
- content: Array.isArray(d.content) ? d.content.slice(0, 500).map((row) => Array.isArray(row) ? row.slice(0, 100).map((cell2) => inline(cell2)) : []) : []
561
- }),
673
+ // 2.4: optional header column, column alignment, merged cells and caption (shared/table.mjs).
674
+ table: (d, inline) => cleanTableExtras(
675
+ {
676
+ withHeadings: bool(d.withHeadings),
677
+ stretched: bool(d.stretched),
678
+ content: Array.isArray(d.content) ? d.content.slice(0, TABLE_LIMITS.rows).map(
679
+ (row) => Array.isArray(row) ? row.slice(0, TABLE_LIMITS.cols).map((cell2) => inline(cell2)) : []
680
+ ) : []
681
+ },
682
+ d,
683
+ inline
684
+ ),
562
685
  image: (d, inline) => {
563
686
  const file = isPlainObject2(d.file) ? d.file : {};
564
687
  const cleanFile = { url: sanitizeUrl(file.url, { schemes: ["http", "https"] }) };
@@ -682,6 +805,12 @@ var BLOCK_POLICIES = {
682
805
  ref: typeof d.ref === "string" && /^[a-z0-9]{1,64}$/.test(d.ref) ? d.ref : "",
683
806
  _mex: BUILT_IN_MARKER_VERSION
684
807
  }),
808
+ // Math block (2.4): only the TeX source is stored; `display: false` renders it in text style.
809
+ math: (d) => ({
810
+ tex: plain(d.tex, MAX_MATH_TEX),
811
+ display: d.display !== false,
812
+ _mex: BUILT_IN_MARKER_VERSION
813
+ }),
685
814
  toc: (d) => {
686
815
  const minLevel = int(d.minLevel, 1, 6, 2);
687
816
  const maxLevel = int(d.maxLevel, 1, 6, 4);
@@ -816,7 +945,7 @@ var findTagEnd = (html, from) => {
816
945
  }
817
946
  return -1;
818
947
  };
819
- var cleanAttributes = (tag, attribs) => {
948
+ var cleanAttributes = (tag, attribs, options = {}) => {
820
949
  const allowed = INLINE_ATTRIBUTES[tag] || [];
821
950
  const out = {};
822
951
  for (const name of allowed) {
@@ -838,10 +967,40 @@ var cleanAttributes = (tag, attribs) => {
838
967
  out[name] = String(value).slice(0, 2e3);
839
968
  }
840
969
  }
841
- if (tag === "a") Object.assign(out, cleanInternalLinkAttributes(attribs));
970
+ if (tag === "a" && !options.inNote) Object.assign(out, cleanInternalLinkAttributes(attribs));
842
971
  return out;
843
972
  };
844
- var parseInline = (input) => {
973
+ var MAX_MARKER_TEXT = 16;
974
+ var isMathNode = (node) => node.type === "element" && node.tag === "span" && node.attrs[MATH_ATTRIBUTE] === "true";
975
+ var isFootnoteNode = (node) => node.type === "element" && node.tag === "sup" && typeof node.attrs["data-mex-footnote"] === "string";
976
+ var finalizeSpecial = (nodes, depth = 0) => {
977
+ for (const node of nodes) {
978
+ if (node.type !== "element") continue;
979
+ if (isMathNode(node)) {
980
+ const tex = nodesToText(node.children, { raw: true }).replace(/\u200b/g, "").slice(0, MAX_INLINE_TEX);
981
+ node.children = tex ? [{ type: "text", value: tex }] : [];
982
+ } else if (isFootnoteNode(node)) {
983
+ const text = nodesToText(node.children, { raw: true }).slice(0, MAX_MARKER_TEXT);
984
+ node.children = text ? [{ type: "text", value: text }] : [];
985
+ } else if (depth < MAX_DEPTH) finalizeSpecial(node.children, depth + 1);
986
+ }
987
+ return nodes;
988
+ };
989
+ var specialElement = (tag, attribs, options) => {
990
+ if (tag === "span" && Object.prototype.hasOwnProperty.call(attribs, MATH_ATTRIBUTE)) {
991
+ if (!/^(?:|true)$/.test(attribs[MATH_ATTRIBUTE])) return null;
992
+ return { attrs: { [MATH_ATTRIBUTE]: "true" } };
993
+ }
994
+ if (tag === "sup" && !options.inNote) {
995
+ const id = attribs["data-mex-footnote"];
996
+ if (typeof id !== "string" || !FOOTNOTE_ID.test(id)) return null;
997
+ const source = typeof attribs["data-mex-note"] === "string" ? attribs["data-mex-note"] : "";
998
+ const note = parseInline(source.slice(0, MAX_FOOTNOTE_NOTE), { inNote: true });
999
+ return { attrs: { "data-mex-footnote": id }, note };
1000
+ }
1001
+ return null;
1002
+ };
1003
+ var parseInline = (input, options = {}) => {
845
1004
  const html = typeof input === "string" ? input.slice(0, MAX_INPUT) : "";
846
1005
  const root = { type: "element", tag: "#root", attrs: {}, children: [] };
847
1006
  const stack = [root];
@@ -922,18 +1081,21 @@ var parseInline = (input) => {
922
1081
  continue;
923
1082
  }
924
1083
  if (!ALLOWED.has(tag) || nodes >= MAX_NODES) continue;
1084
+ const attribs = parseAttributes(body);
1085
+ const special = specialElement(tag, attribs, options);
925
1086
  const element = {
926
1087
  type: "element",
927
1088
  tag,
928
- attrs: cleanAttributes(tag, parseAttributes(body)),
1089
+ attrs: special ? special.attrs : cleanAttributes(tag, attribs, options),
929
1090
  children: []
930
1091
  };
1092
+ if (special && special.note) element.note = special.note;
931
1093
  stack[stack.length - 1].children.push(element);
932
1094
  nodes += 1;
933
1095
  if (!VOID.has(tag) && stack.length < MAX_DEPTH) stack.push(element);
934
1096
  }
935
1097
  flush();
936
- return root.children;
1098
+ return finalizeSpecial(root.children);
937
1099
  };
938
1100
  var resolveLinkAttributes = (attrs, resolver) => {
939
1101
  if (typeof resolver !== "function" || !attrs["data-mex-uid"] || !attrs["data-mex-document-id"])
@@ -967,11 +1129,17 @@ var ATTRIBUTE_ORDER = [
967
1129
  "data-mex-uid",
968
1130
  "data-mex-document-id",
969
1131
  "data-mex-locale",
970
- "data-mex-mention"
1132
+ "data-mex-mention",
1133
+ MATH_ATTRIBUTE,
1134
+ "data-mex-footnote",
1135
+ "data-mex-note"
971
1136
  ];
1137
+ var RENDER_STATE = /* @__PURE__ */ Symbol.for("magic-editor-x.render-state");
1138
+ var storedNote = (note) => serializeNodes(inlineNodesToRender(note || [], { storage: true }));
972
1139
  var MENTION_CLASS = "mex-mention";
973
1140
  var inlineNodesToRender = (nodes, options = {}) => {
974
1141
  const out = [];
1142
+ const state = options[RENDER_STATE];
975
1143
  for (const node of nodes) {
976
1144
  if (node.type === "text") {
977
1145
  out.push({ type: "text", value: node.value });
@@ -981,6 +1149,31 @@ var inlineNodesToRender = (nodes, options = {}) => {
981
1149
  out.push({ type: "element", tag: "br", attrs: {}, children: [] });
982
1150
  continue;
983
1151
  }
1152
+ if (isMathNode(node)) {
1153
+ const tex = nodesToText(node.children);
1154
+ if (state && !options.storage) {
1155
+ if (tex.trim()) out.push(state.math(tex, false));
1156
+ continue;
1157
+ }
1158
+ out.push({
1159
+ type: "element",
1160
+ tag: "span",
1161
+ attrs: { [MATH_ATTRIBUTE]: "true" },
1162
+ children: tex ? [{ type: "text", value: tex }] : []
1163
+ });
1164
+ continue;
1165
+ }
1166
+ if (isFootnoteNode(node)) {
1167
+ if (state && !options.storage) {
1168
+ out.push(state.footnote(node));
1169
+ continue;
1170
+ }
1171
+ const attrs2 = { "data-mex-footnote": node.attrs["data-mex-footnote"] };
1172
+ const note = storedNote(node.note);
1173
+ if (note) attrs2["data-mex-note"] = note;
1174
+ out.push({ type: "element", tag: "sup", attrs: attrs2, children: inlineNodesToRender(node.children, options) });
1175
+ continue;
1176
+ }
984
1177
  let attrs = node.attrs;
985
1178
  if (node.tag === "a") {
986
1179
  attrs = resolveLinkAttributes(attrs, options.links);
@@ -1013,13 +1206,369 @@ var inlineNodesToRender = (nodes, options = {}) => {
1013
1206
  };
1014
1207
  var inlineToNodes = (html, options) => inlineNodesToRender(parseInline(html), options);
1015
1208
  var nodesToHtml = (nodes, options = {}) => serializeNodes(inlineNodesToRender(nodes, options));
1016
- var nodesToText = (nodes) => nodes.map((node) => {
1209
+ var nodesToText = (nodes, options = {}) => nodes.map((node) => {
1017
1210
  if (node.type === "text") return node.value;
1018
1211
  if (node.tag === "br") return "\n";
1019
- return nodesToText(node.children);
1212
+ if (!options.raw && isFootnoteNode(node))
1213
+ return typeof options.footnote === "function" ? options.footnote(node) : "";
1214
+ return nodesToText(node.children, options);
1020
1215
  }).join("");
1021
1216
  var inlineToHtml = (html, options) => nodesToHtml(parseInline(html), options);
1022
- var inlineToText = (html) => nodesToText(parseInline(html)).replace(/\u00a0/g, " ");
1217
+ var inlineToText = (html, options) => nodesToText(parseInline(html), options).replace(/\u00a0/g, " ");
1218
+
1219
+ // shared/render/mathml.mjs
1220
+ var MATHML_TAGS = Object.freeze([
1221
+ "math",
1222
+ "semantics",
1223
+ "annotation",
1224
+ "mrow",
1225
+ "mi",
1226
+ "mn",
1227
+ "mo",
1228
+ "ms",
1229
+ "mtext",
1230
+ "mspace",
1231
+ "msub",
1232
+ "msup",
1233
+ "msubsup",
1234
+ "munder",
1235
+ "mover",
1236
+ "munderover",
1237
+ "mfrac",
1238
+ "msqrt",
1239
+ "mroot",
1240
+ "mstyle",
1241
+ "merror",
1242
+ "mpadded",
1243
+ "mphantom",
1244
+ "mtable",
1245
+ "mtr",
1246
+ "mtd",
1247
+ "mlabeledtr",
1248
+ "mmultiscripts",
1249
+ "mprescripts",
1250
+ "none",
1251
+ "menclose"
1252
+ ]);
1253
+ var TAGS = new Set(MATHML_TAGS);
1254
+ var COMMON_ATTRIBUTES = /* @__PURE__ */ new Set([
1255
+ "dir",
1256
+ "displaystyle",
1257
+ "scriptlevel",
1258
+ "mathvariant",
1259
+ "mathsize",
1260
+ "mathcolor",
1261
+ "mathbackground"
1262
+ ]);
1263
+ var ELEMENT_ATTRIBUTES = Object.freeze({
1264
+ math: ["display"],
1265
+ mo: [
1266
+ "form",
1267
+ "fence",
1268
+ "separator",
1269
+ "stretchy",
1270
+ "symmetric",
1271
+ "largeop",
1272
+ "movablelimits",
1273
+ "lspace",
1274
+ "rspace",
1275
+ "minsize",
1276
+ "maxsize",
1277
+ "accent"
1278
+ ],
1279
+ mspace: ["width", "height", "depth"],
1280
+ mpadded: ["width", "height", "depth", "lspace", "voffset"],
1281
+ mfrac: ["linethickness"],
1282
+ mover: ["accent"],
1283
+ munder: ["accentunder"],
1284
+ munderover: ["accent", "accentunder"],
1285
+ mtable: [
1286
+ "columnalign",
1287
+ "rowalign",
1288
+ "columnspacing",
1289
+ "rowspacing",
1290
+ "columnlines",
1291
+ "rowlines",
1292
+ "frame",
1293
+ "framespacing",
1294
+ "equalrows",
1295
+ "equalcolumns",
1296
+ "side"
1297
+ ],
1298
+ mtr: ["columnalign", "rowalign"],
1299
+ mlabeledtr: ["columnalign", "rowalign"],
1300
+ mtd: ["columnalign", "rowalign", "columnspan", "rowspan"],
1301
+ menclose: ["notation"],
1302
+ annotation: ["encoding"]
1303
+ });
1304
+ var ATTRIBUTE_VALUE = /^[A-Za-z0-9 .%#+-]{0,100}$/;
1305
+ var COLOR_VALUE = /^(?:#[0-9A-Fa-f]{3,8}|[A-Za-z]{1,30})$/;
1306
+ var CLASS_TOKEN = /^tml-[a-z0-9-]{1,40}$/;
1307
+ var TEX_ENCODING = "application/x-tex";
1308
+ var MAX_INPUT2 = 2e5;
1309
+ var MAX_NODES2 = 2e4;
1310
+ var MAX_DEPTH2 = 64;
1311
+ var parseAttributes2 = (source) => {
1312
+ const out = {};
1313
+ const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
1314
+ let match;
1315
+ while (match = pattern.exec(source)) {
1316
+ const name = match[1].toLowerCase();
1317
+ if (Object.prototype.hasOwnProperty.call(out, name)) continue;
1318
+ out[name] = decodeEntities(match[2] ?? match[3] ?? match[4] ?? "");
1319
+ }
1320
+ return out;
1321
+ };
1322
+ var styleColor = (style, property) => {
1323
+ const pattern = property === "color" ? /(?:^|;)\s*color\s*:\s*([^;]+)/i : /background-color\s*:\s*([^;]+)/i;
1324
+ const match = pattern.exec(style);
1325
+ const value = match ? match[1].trim() : "";
1326
+ return COLOR_VALUE.test(value) ? value : "";
1327
+ };
1328
+ var cleanAttributes2 = (tag, attribs) => {
1329
+ const out = {};
1330
+ const allowed = ELEMENT_ATTRIBUTES[tag] || [];
1331
+ for (const [name, raw] of Object.entries(attribs)) {
1332
+ if (typeof raw !== "string" && typeof raw !== "number" && raw !== true) continue;
1333
+ const value = raw === true ? "true" : String(raw);
1334
+ if (name === "class") {
1335
+ const classes2 = value.split(/\s+/).filter((token) => CLASS_TOKEN.test(token));
1336
+ if (classes2.length) out.class = classes2.slice(0, 8).join(" ");
1337
+ continue;
1338
+ }
1339
+ if (name === "encoding") {
1340
+ if (tag === "annotation" && value === TEX_ENCODING) out.encoding = value;
1341
+ continue;
1342
+ }
1343
+ if (name === "mathcolor" || name === "mathbackground") {
1344
+ if (COLOR_VALUE.test(value)) out[name] = value;
1345
+ continue;
1346
+ }
1347
+ if (!COMMON_ATTRIBUTES.has(name) && !allowed.includes(name)) continue;
1348
+ if (ATTRIBUTE_VALUE.test(value)) out[name] = value;
1349
+ }
1350
+ if (typeof attribs.style === "string") {
1351
+ const color = styleColor(attribs.style, "color");
1352
+ const background = styleColor(attribs.style, "background-color");
1353
+ if (color && !out.mathcolor) out.mathcolor = color;
1354
+ if (background && !out.mathbackground) out.mathbackground = background;
1355
+ }
1356
+ if (tag === "annotation" && out.encoding !== TEX_ENCODING) return null;
1357
+ if (tag === "math" && out.display && out.display !== "block" && out.display !== "inline")
1358
+ delete out.display;
1359
+ return out;
1360
+ };
1361
+ var tokenize = (input) => {
1362
+ const source = input.slice(0, MAX_INPUT2);
1363
+ const root = { type: "element", tag: "#root", attrs: {}, children: [] };
1364
+ const stack = [root];
1365
+ let count = 0;
1366
+ let i = 0;
1367
+ const pushText = (text) => {
1368
+ if (!text) return;
1369
+ const parent = stack[stack.length - 1];
1370
+ const last = parent.children[parent.children.length - 1];
1371
+ const value = decodeEntities(text);
1372
+ if (last && last.type === "text") last.value += value;
1373
+ else if (count < MAX_NODES2) {
1374
+ parent.children.push({ type: "text", value });
1375
+ count += 1;
1376
+ }
1377
+ };
1378
+ while (i < source.length) {
1379
+ const lt = source.indexOf("<", i);
1380
+ if (lt === -1) {
1381
+ pushText(source.slice(i));
1382
+ break;
1383
+ }
1384
+ pushText(source.slice(i, lt));
1385
+ if (source.startsWith("<!--", lt)) {
1386
+ const end2 = source.indexOf("-->", lt + 4);
1387
+ i = end2 === -1 ? source.length : end2 + 3;
1388
+ continue;
1389
+ }
1390
+ if (source[lt + 1] === "!" || source[lt + 1] === "?") {
1391
+ const end2 = source.indexOf(">", lt + 2);
1392
+ i = end2 === -1 ? source.length : end2 + 1;
1393
+ continue;
1394
+ }
1395
+ const closing = source[lt + 1] === "/";
1396
+ const nameMatch = /^[A-Za-z][A-Za-z0-9:-]{0,40}/.exec(source.slice(lt + (closing ? 2 : 1), lt + 45));
1397
+ let end = -1;
1398
+ let quote = "";
1399
+ for (let j = lt + 1; j < source.length; j += 1) {
1400
+ const char = source[j];
1401
+ if (quote) {
1402
+ if (char === quote) quote = "";
1403
+ } else if (char === '"' || char === "'") quote = char;
1404
+ else if (char === ">") {
1405
+ end = j;
1406
+ break;
1407
+ }
1408
+ }
1409
+ if (!nameMatch || end === -1) {
1410
+ pushText(source.slice(lt, end === -1 ? source.length : lt + 1));
1411
+ i = end === -1 ? source.length : lt + 1;
1412
+ continue;
1413
+ }
1414
+ const tag = nameMatch[0].toLowerCase();
1415
+ const body = source.slice(lt + (closing ? 2 : 1) + nameMatch[0].length, end);
1416
+ i = end + 1;
1417
+ if (closing) {
1418
+ for (let s = stack.length - 1; s > 0; s -= 1) {
1419
+ if (stack[s].tag === tag) {
1420
+ stack.length = s;
1421
+ break;
1422
+ }
1423
+ }
1424
+ continue;
1425
+ }
1426
+ if (count >= MAX_NODES2) continue;
1427
+ const element = { type: "element", tag, attrs: parseAttributes2(body), children: [] };
1428
+ stack[stack.length - 1].children.push(element);
1429
+ count += 1;
1430
+ const selfClosing = /\/\s*$/.test(body);
1431
+ if (!selfClosing && stack.length < MAX_DEPTH2) stack.push(element);
1432
+ }
1433
+ return root.children;
1434
+ };
1435
+ var clean = (nodes, ctx, depth, inAnnotation) => {
1436
+ const out = [];
1437
+ if (!Array.isArray(nodes) || depth > MAX_DEPTH2) return out;
1438
+ for (const node of nodes) {
1439
+ if (ctx.budget <= 0) break;
1440
+ if (typeof node === "string") {
1441
+ ctx.budget -= 1;
1442
+ if (node) out.push({ type: "text", value: node });
1443
+ continue;
1444
+ }
1445
+ if (!node || typeof node !== "object") continue;
1446
+ ctx.budget -= 1;
1447
+ if (node.type === "text") {
1448
+ if (typeof node.value === "string" && node.value) out.push({ type: "text", value: node.value });
1449
+ continue;
1450
+ }
1451
+ if (node.type !== "element" || typeof node.tag !== "string" || inAnnotation) continue;
1452
+ const tag = node.tag.toLowerCase();
1453
+ if (!TAGS.has(tag)) continue;
1454
+ const attrs = cleanAttributes2(tag, node.attrs && typeof node.attrs === "object" ? node.attrs : {});
1455
+ if (!attrs) continue;
1456
+ const children = clean(node.children, ctx, depth + 1, tag === "annotation");
1457
+ out.push({ type: "element", tag, attrs, children });
1458
+ }
1459
+ return out;
1460
+ };
1461
+ var cleanMathResult = (result) => {
1462
+ let nodes;
1463
+ if (typeof result === "string") nodes = tokenize(result);
1464
+ else if (Array.isArray(result)) nodes = result;
1465
+ else if (result && typeof result === "object") nodes = [result];
1466
+ else return [];
1467
+ const top = nodes.filter(
1468
+ (node) => node && typeof node === "object" && node.type === "element" && String(node.tag).toLowerCase() === "math"
1469
+ );
1470
+ return clean(top, { budget: MAX_NODES2 }, 0, false);
1471
+ };
1472
+
1473
+ // shared/render/math-notes.mjs
1474
+ var DEFAULT_FOOTNOTES_LABEL = "Footnotes";
1475
+ var DEFAULT_FOOTNOTE_BACK_LABEL = "Back to reference {n}";
1476
+ var DEFAULT_FOOTNOTE_PREFIX = "mex-";
1477
+ var PREFIX = /^[A-Za-z][A-Za-z0-9_-]{0,40}$/;
1478
+ var label = (value, fallback) => {
1479
+ if (typeof value !== "string") return fallback;
1480
+ const clean2 = value.trim();
1481
+ return clean2 && clean2.length <= 80 ? clean2 : fallback;
1482
+ };
1483
+ var footnoteOptions = (options) => {
1484
+ const source = isPlainObject2(options && options.footnotes) ? options.footnotes : {};
1485
+ return {
1486
+ label: label(source.label, DEFAULT_FOOTNOTES_LABEL),
1487
+ backLabel: label(source.backLabel, DEFAULT_FOOTNOTE_BACK_LABEL),
1488
+ prefix: typeof source.prefix === "string" && PREFIX.test(source.prefix) ? source.prefix : DEFAULT_FOOTNOTE_PREFIX
1489
+ };
1490
+ };
1491
+ var createFootnoteNumbers = () => {
1492
+ const used = /* @__PURE__ */ new Map();
1493
+ let count = 0;
1494
+ return {
1495
+ add(id) {
1496
+ const seen = (used.get(id) || 0) + 1;
1497
+ used.set(id, seen);
1498
+ count += 1;
1499
+ return { n: count, anchor: seen === 1 ? id : `${id}-${seen}` };
1500
+ }
1501
+ };
1502
+ };
1503
+ var renderMathNodes = (options, tex, display) => {
1504
+ if (!options || typeof options.math !== "function" || !tex.trim()) return [];
1505
+ let result;
1506
+ try {
1507
+ result = options.math(tex, { display });
1508
+ } catch {
1509
+ return [];
1510
+ }
1511
+ return cleanMathResult(result);
1512
+ };
1513
+ var mathElement = (options, tex, kind) => {
1514
+ const math = renderMathNodes(options, tex, kind.display);
1515
+ const attrs = {
1516
+ class: kind.className || (kind.display ? "mex-math mex-math-display" : "mex-math"),
1517
+ "data-mex-math": kind.display ? "display" : "inline"
1518
+ };
1519
+ const children = math.length ? math : kind.display ? `\\[${tex}\\]` : `\\(${tex}\\)`;
1520
+ return el(kind.block ? "div" : "span", attrs, children);
1521
+ };
1522
+ var createFootnoteTree = (options, renderNote) => {
1523
+ const { label: listLabel, backLabel, prefix } = footnoteOptions(options);
1524
+ const numbers = createFootnoteNumbers();
1525
+ const items = [];
1526
+ const labelId = `${prefix}footnotes-label`;
1527
+ return {
1528
+ marker(node) {
1529
+ const { n, anchor } = numbers.add(node.attrs["data-mex-footnote"]);
1530
+ items.push({ n, anchor, note: node.note || [] });
1531
+ return el(
1532
+ "sup",
1533
+ { class: "mex-footnote-ref" },
1534
+ el(
1535
+ "a",
1536
+ {
1537
+ href: `#${prefix}fn-${anchor}`,
1538
+ id: `${prefix}fnref-${anchor}`,
1539
+ "aria-describedby": labelId
1540
+ },
1541
+ String(n)
1542
+ )
1543
+ );
1544
+ },
1545
+ section() {
1546
+ if (!items.length) return null;
1547
+ return el("section", { class: "mex-footnotes", "aria-labelledby": labelId }, [
1548
+ el("h2", { id: labelId, class: "mex-footnotes-label" }, listLabel),
1549
+ el(
1550
+ "ol",
1551
+ { class: "mex-footnotes-list" },
1552
+ items.map(
1553
+ (item) => el("li", { id: `${prefix}fn-${item.anchor}`, class: "mex-footnote" }, [
1554
+ renderNote(item.note),
1555
+ " ",
1556
+ el(
1557
+ "a",
1558
+ {
1559
+ href: `#${prefix}fnref-${item.anchor}`,
1560
+ class: "mex-footnote-back",
1561
+ "aria-label": backLabel.replace(/\{n\}/g, String(item.n))
1562
+ },
1563
+ "\u21A9"
1564
+ )
1565
+ ])
1566
+ )
1567
+ )
1568
+ ]);
1569
+ }
1570
+ };
1571
+ };
1023
1572
 
1024
1573
  // shared/blocks/define.mjs
1025
1574
  var BLOCK_FIELD_TYPES = Object.freeze([
@@ -1097,6 +1646,7 @@ var RESERVED_BLOCK_NAMES = Object.freeze([
1097
1646
  "textVariant",
1098
1647
  "indentTune"
1099
1648
  ]);
1649
+ var SDK_COMPATIBLE_NAMES = Object.freeze(["math"]);
1100
1650
  var RESERVED = new Set(RESERVED_BLOCK_NAMES.map((name) => name.toLowerCase()));
1101
1651
  var BLOCK_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{1,49}$/;
1102
1652
  var KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
@@ -1134,7 +1684,7 @@ var BlockDefinitionError = class extends Error {
1134
1684
  this.code = code;
1135
1685
  }
1136
1686
  };
1137
- var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1687
+ var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1138
1688
  var fail = (where, message) => {
1139
1689
  throw new BlockDefinitionError(`Magic Editor X block ${where}: ${message}`);
1140
1690
  };
@@ -1145,7 +1695,7 @@ var boundedInt = (value, min, max, fallback, where, key) => {
1145
1695
  return value;
1146
1696
  };
1147
1697
  var normalizeField = (input, where, depth) => {
1148
- if (!isObject(input)) fail(where, 'a field must be an object with a "type"');
1698
+ if (!isObject2(input)) fail(where, 'a field must be an object with a "type"');
1149
1699
  const type = input.type;
1150
1700
  if (!BLOCK_FIELD_TYPES.includes(type)) fail(where, `unknown field type ${JSON.stringify(type)}`);
1151
1701
  for (const key of Object.keys(input))
@@ -1238,7 +1788,7 @@ var normalizeField = (input, where, depth) => {
1238
1788
  return Object.freeze(out);
1239
1789
  };
1240
1790
  var normalizeFields = (input, where, depth) => {
1241
- if (!isObject(input)) fail(where, '"fields" must be an object of field descriptors');
1791
+ if (!isObject2(input)) fail(where, '"fields" must be an object of field descriptors');
1242
1792
  const keys = Object.keys(input);
1243
1793
  if (keys.length < 1 || keys.length > BLOCK_LIMITS.maxFields)
1244
1794
  fail(where, `an object needs 1 to ${BLOCK_LIMITS.maxFields} fields`);
@@ -1257,20 +1807,20 @@ var blockNameProblem = (name) => {
1257
1807
  return null;
1258
1808
  };
1259
1809
  var defineBlock = (definition) => {
1260
- if (!isObject(definition))
1810
+ if (!isObject2(definition))
1261
1811
  throw new BlockDefinitionError("Magic Editor X block: the definition must be an object");
1262
- const label2 = typeof definition.name === "string" ? `"${definition.name.slice(0, 50)}"` : "(no name)";
1812
+ const label3 = typeof definition.name === "string" ? `"${definition.name.slice(0, 50)}"` : "(no name)";
1263
1813
  for (const key of Object.keys(definition))
1264
- if (!DEFINITION_KEYS.has(key)) fail(label2, `unknown key "${key}"`);
1814
+ if (!DEFINITION_KEYS.has(key)) fail(label3, `unknown key "${key}"`);
1265
1815
  const problem = blockNameProblem(definition.name);
1266
1816
  if (problem)
1267
1817
  throw new BlockDefinitionError(
1268
- `Magic Editor X block ${label2}: ${problem}`,
1818
+ `Magic Editor X block ${label3}: ${problem}`,
1269
1819
  problem.includes("built-in") ? "RESERVED_NAME" : "INVALID_DEFINITION"
1270
1820
  );
1271
1821
  const out = {
1272
1822
  name: definition.name,
1273
- version: boundedInt(definition.version, 1, 1e6, 1, label2, "version")
1823
+ version: boundedInt(definition.version, 1, 1e6, 1, label3, "version")
1274
1824
  };
1275
1825
  for (const [key, max] of [
1276
1826
  ["title", 100],
@@ -1278,18 +1828,18 @@ var defineBlock = (definition) => {
1278
1828
  ]) {
1279
1829
  if (definition[key] === void 0) continue;
1280
1830
  if (typeof definition[key] !== "string" || definition[key].length > max)
1281
- fail(label2, `"${key}" must be a string of at most ${max} characters`);
1831
+ fail(label3, `"${key}" must be a string of at most ${max} characters`);
1282
1832
  out[key] = definition[key];
1283
1833
  }
1284
- out.schema = normalizeFields(definition.schema, `${label2} schema`, 0);
1834
+ out.schema = normalizeFields(definition.schema, `${label3} schema`, 0);
1285
1835
  for (const key of ["sanitize", "text", "markdown", "render"]) {
1286
1836
  if (definition[key] === void 0) continue;
1287
- if (typeof definition[key] !== "function") fail(label2, `"${key}" must be a function`);
1837
+ if (typeof definition[key] !== "function") fail(label3, `"${key}" must be a function`);
1288
1838
  out[key] = definition[key];
1289
1839
  }
1290
1840
  const presets = definition.presets === void 0 ? [] : definition.presets;
1291
1841
  if (!Array.isArray(presets) || presets.some((preset) => !BLOCK_PRESETS.includes(preset)))
1292
- fail(label2, `"presets" must list some of ${BLOCK_PRESETS.join(", ")}`);
1842
+ fail(label3, `"presets" must list some of ${BLOCK_PRESETS.join(", ")}`);
1293
1843
  out.presets = Object.freeze([...new Set(presets)]);
1294
1844
  return Object.freeze(out);
1295
1845
  };
@@ -1317,13 +1867,13 @@ var cleanValue = (field, value, inline, budget) => {
1317
1867
  for (const item of value) {
1318
1868
  if (out.length >= field.max || budget.left <= 0) break;
1319
1869
  if (!matchesType(field.items, item)) continue;
1320
- const clean = cleanValue(field.items, item, inline, budget);
1321
- if (clean !== void 0) out.push(clean);
1870
+ const clean2 = cleanValue(field.items, item, inline, budget);
1871
+ if (clean2 !== void 0) out.push(clean2);
1322
1872
  }
1323
1873
  return out;
1324
1874
  }
1325
1875
  case "object":
1326
- return cleanObject(field.fields, isObject(value) ? value : {}, inline, budget);
1876
+ return cleanObject(field.fields, isObject2(value) ? value : {}, inline, budget);
1327
1877
  default:
1328
1878
  return void 0;
1329
1879
  }
@@ -1342,15 +1892,15 @@ var matchesType = (field, item) => {
1342
1892
  case "array":
1343
1893
  return Array.isArray(item);
1344
1894
  default:
1345
- return isObject(item);
1895
+ return isObject2(item);
1346
1896
  }
1347
1897
  };
1348
1898
  var cleanObject = (fields, value, inline, budget) => {
1349
1899
  const out = {};
1350
1900
  for (const key of Object.keys(fields)) {
1351
1901
  const own = Object.prototype.hasOwnProperty.call(value, key) ? value[key] : void 0;
1352
- const clean = cleanValue(fields[key], own, inline, budget);
1353
- if (clean !== void 0) out[key] = clean;
1902
+ const clean2 = cleanValue(fields[key], own, inline, budget);
1903
+ if (clean2 !== void 0) out[key] = clean2;
1354
1904
  }
1355
1905
  return out;
1356
1906
  };
@@ -1361,13 +1911,13 @@ var eachLeaf = (fields, data, visit) => {
1361
1911
  if (!Array.isArray(value)) return;
1362
1912
  value.slice(0, field.max).forEach((item, index) => walk(field.items, item, [...path, index], depth + 1));
1363
1913
  } else if (field.type === "object") {
1364
- if (!isObject(value)) return;
1914
+ if (!isObject2(value)) return;
1365
1915
  for (const key of Object.keys(field.fields))
1366
1916
  if (Object.prototype.hasOwnProperty.call(value, key))
1367
1917
  walk(field.fields[key], value[key], [...path, key], depth + 1);
1368
1918
  } else visit(field, value, path);
1369
1919
  };
1370
- if (!isObject(data)) return;
1920
+ if (!isObject2(data)) return;
1371
1921
  for (const key of Object.keys(fields))
1372
1922
  if (Object.prototype.hasOwnProperty.call(data, key)) walk(fields[key], data[key], [key], 0);
1373
1923
  };
@@ -1393,7 +1943,7 @@ var compileBlock = (definition) => {
1393
1943
  return compiled.get(definition);
1394
1944
  const def = defineBlock(definition && typeof definition === "object" ? { ...definition } : definition);
1395
1945
  const schema = def.schema;
1396
- const run = (data, inline) => cleanObject(schema, isObject(data) ? data : {}, inline, { left: BLOCK_LIMITS.maxValues });
1946
+ const run = (data, inline) => cleanObject(schema, isObject2(data) ? data : {}, inline, { left: BLOCK_LIMITS.maxValues });
1397
1947
  const result = Object.freeze({
1398
1948
  ...def,
1399
1949
  /**
@@ -1414,7 +1964,7 @@ var compileBlock = (definition) => {
1414
1964
  } catch {
1415
1965
  return first;
1416
1966
  }
1417
- return isObject(next) ? run(next, inline) : first;
1967
+ return isObject2(next) ? run(next, inline) : first;
1418
1968
  },
1419
1969
  /**
1420
1970
  * Text fields of the data in schema order: `{ path, kind, value }`
@@ -1462,7 +2012,7 @@ var compileBlock = (definition) => {
1462
2012
  };
1463
2013
  var copyData = (value) => {
1464
2014
  if (Array.isArray(value)) return value.map(copyData);
1465
- if (isObject(value)) {
2015
+ if (isObject2(value)) {
1466
2016
  const out = {};
1467
2017
  for (const [key, child] of Object.entries(value)) out[key] = copyData(child);
1468
2018
  return out;
@@ -1706,12 +2256,12 @@ var prepareBlocks = (value, options = {}) => {
1706
2256
  const raw = isPlainObject2(block.data) ? block.data : {};
1707
2257
  const known = isBuiltInBlock({ type: block.type, data: raw });
1708
2258
  const definition = known ? null : registeredBlockOf({ type: block.type, data: raw }, explicit);
1709
- const clean = known ? BLOCK_POLICIES[block.type](raw, keepInline, ctx) : definition ? definition.clean(raw, keepInline) : raw;
1710
- for (const key of Object.keys(clean)) if (clean[key] === void 0) delete clean[key];
2259
+ const clean2 = known ? BLOCK_POLICIES[block.type](raw, keepInline, ctx) : definition ? definition.clean(raw, keepInline) : raw;
2260
+ for (const key of Object.keys(clean2)) if (clean2[key] === void 0) delete clean2[key];
1711
2261
  return {
1712
2262
  id: block.id,
1713
2263
  type: block.type,
1714
- data: clean,
2264
+ data: clean2,
1715
2265
  raw,
1716
2266
  tunes: sanitizeTunes(block.tunes),
1717
2267
  known,
@@ -1741,10 +2291,10 @@ var imageCandidates = (file) => {
1741
2291
  const out = [];
1742
2292
  const seen = /* @__PURE__ */ new Set();
1743
2293
  const push = (url, width) => {
1744
- const clean = sanitizeUrl(url, { schemes: ["http", "https"] });
1745
- if (!clean || !Number.isInteger(width) || width <= 0 || seen.has(width)) return;
2294
+ const clean2 = sanitizeUrl(url, { schemes: ["http", "https"] });
2295
+ if (!clean2 || !Number.isInteger(width) || width <= 0 || seen.has(width)) return;
1746
2296
  seen.add(width);
1747
- out.push({ url: clean, width });
2297
+ out.push({ url: clean2, width });
1748
2298
  };
1749
2299
  if (isPlainObject2(file.formats)) {
1750
2300
  const names = Object.keys(file.formats).sort(
@@ -1960,20 +2510,20 @@ var mediaFigure = (tag, b, o) => {
1960
2510
  caption.length ? el("figcaption", {}, caption) : null
1961
2511
  ]);
1962
2512
  };
1963
- var label = (value, fallback) => {
2513
+ var label2 = (value, fallback) => {
1964
2514
  if (typeof value !== "string") return fallback;
1965
- const clean = value.trim();
1966
- return clean && clean.length <= 80 ? clean : fallback;
2515
+ const clean2 = value.trim();
2516
+ return clean2 && clean2.length <= 80 ? clean2 : fallback;
1967
2517
  };
1968
- var tocLabel = (options) => label(isPlainObject2(options.toc) ? options.toc.label : void 0, "Table of contents");
2518
+ var tocLabel = (options) => label2(isPlainObject2(options.toc) ? options.toc.label : void 0, "Table of contents");
1969
2519
  var codeOptions = (options) => {
1970
2520
  const code = isPlainObject2(options.code) ? options.code : {};
1971
2521
  const lineNumbers = code.lineNumbers === true ? "all" : code.lineNumbers === "block" ? "block" : "none";
1972
2522
  const button = code.copyButton;
1973
2523
  const copy = button === true || isPlainObject2(button) ? {
1974
- label: label(isPlainObject2(button) ? button.label : void 0, "Copy code"),
1975
- copied: label(isPlainObject2(button) ? button.copiedLabel : void 0, "Copied"),
1976
- failed: label(isPlainObject2(button) ? button.failedLabel : void 0, "Copy failed")
2524
+ label: label2(isPlainObject2(button) ? button.label : void 0, "Copy code"),
2525
+ copied: label2(isPlainObject2(button) ? button.copiedLabel : void 0, "Copied"),
2526
+ failed: label2(isPlainObject2(button) ? button.failedLabel : void 0, "Copy failed")
1977
2527
  } : null;
1978
2528
  return { lineNumbers, copy };
1979
2529
  };
@@ -2002,23 +2552,29 @@ var codeBlock = (b, language, o) => {
2002
2552
  },
2003
2553
  el("code", language ? { class: `language-${language}` } : {}, numbers ? numberedLines(code) : code)
2004
2554
  );
2005
- if (!copy) return pre;
2006
- return el("div", { class: "mex-code-block", "data-mex-code": "copy" }, [
2007
- pre,
2008
- el(
2009
- "button",
2010
- {
2011
- type: "button",
2012
- class: "mex-code-copy",
2013
- "data-mex-copy": "code",
2014
- "data-mex-copied": copy.copied,
2015
- "data-mex-failed": copy.failed
2016
- },
2017
- copy.label
2018
- ),
2019
- el("span", { class: "mex-code-copy-status", role: "status", "aria-live": "polite" })
2555
+ const block = copy ? copyBlock(pre, copy) : pre;
2556
+ const filename = b.type === "codeFlask" && typeof b.data.filename === "string" ? b.data.filename : "";
2557
+ if (!filename) return block;
2558
+ return el("figure", { class: "mex-code-figure" }, [
2559
+ el("figcaption", { class: "mex-code-filename" }, filename),
2560
+ block
2020
2561
  ]);
2021
2562
  };
2563
+ var copyBlock = (pre, copy) => el("div", { class: "mex-code-block", "data-mex-code": "copy" }, [
2564
+ pre,
2565
+ el(
2566
+ "button",
2567
+ {
2568
+ type: "button",
2569
+ class: "mex-code-copy",
2570
+ "data-mex-copy": "code",
2571
+ "data-mex-copied": copy.copied,
2572
+ "data-mex-failed": copy.failed
2573
+ },
2574
+ copy.label
2575
+ ),
2576
+ el("span", { class: "mex-code-copy-status", role: "status", "aria-live": "polite" })
2577
+ ]);
2022
2578
  var RENDERERS = {
2023
2579
  paragraph: (b, o) => el("p", { class: classes(["mex-paragraph"], b.tunes) }, inlineToNodes(b.data.text, o)),
2024
2580
  header: (b, o) => el(
@@ -2093,20 +2649,29 @@ var RENDERERS = {
2093
2649
  const html = o.sanitizeRaw(String(b.raw.html || ""));
2094
2650
  return typeof html === "string" && html ? el("div", { class: classes(["mex-raw"], b.tunes) }, { type: "raw", html }) : null;
2095
2651
  },
2652
+ // Header row: <thead> with <th scope="col">; header column (2.4): <th scope="row">;
2653
+ // merged cells: colspan/rowspan (covered cells are left out); alignment: a class.
2096
2654
  table: (b, o) => {
2097
- const rows = b.data.content;
2655
+ const rows = tableLayout(b.data);
2098
2656
  if (!rows.length) return null;
2099
- const cells = (row, tag) => el(
2100
- "tr",
2101
- {},
2102
- row.map((cell2) => el(tag, tag === "th" ? { scope: "col" } : {}, inlineToNodes(cell2, o)))
2657
+ const cell2 = (item) => el(
2658
+ item.header ? "th" : "td",
2659
+ {
2660
+ ...item.header ? { scope: item.header } : {},
2661
+ ...item.colspan > 1 ? { colspan: String(item.colspan) } : {},
2662
+ ...item.rowspan > 1 ? { rowspan: String(item.rowspan) } : {},
2663
+ ...item.align ? { class: `mex-align-${item.align}` } : {}
2664
+ },
2665
+ inlineToNodes(item.html, o)
2103
2666
  );
2104
- const head = b.data.withHeadings ? el("thead", {}, cells(rows[0], "th")) : null;
2105
- const body = (b.data.withHeadings ? rows.slice(1) : rows).map((row) => cells(row, "td"));
2667
+ const tr = (row) => el("tr", {}, row.map(cell2));
2668
+ const head = b.data.withHeadings ? el("thead", {}, tr(rows[0])) : null;
2669
+ const body = (b.data.withHeadings ? rows.slice(1) : rows).map(tr);
2670
+ const caption = b.data.caption ? el("caption", {}, inlineToNodes(b.data.caption, o)) : null;
2106
2671
  return el(
2107
2672
  "table",
2108
2673
  { class: classes(["mex-table", ...b.data.stretched ? ["mex-stretched"] : []], b.tunes) },
2109
- [head, body.length ? el("tbody", {}, body) : null]
2674
+ [caption, head, body.length ? el("tbody", {}, body) : null]
2110
2675
  );
2111
2676
  },
2112
2677
  image: (b, o) => {
@@ -2199,11 +2764,11 @@ var RENDERERS = {
2199
2764
  embed: (b, o) => {
2200
2765
  const hosts = Array.isArray(o.embedHosts) ? o.embedHosts.map((h) => String(h).toLowerCase()) : DEFAULT_EMBED_HOSTS;
2201
2766
  const frame = embedFrameUrl(b.data.embed, hosts);
2767
+ const href = b.data.source || b.data.embed;
2768
+ if (!frame && !href) return null;
2202
2769
  const caption = inlineToNodes(b.data.caption, o);
2203
2770
  const title = inlineToText(b.data.caption) || b.data.service || "Embedded content";
2204
2771
  if (!frame) {
2205
- const href = b.data.source || b.data.embed;
2206
- if (!href) return null;
2207
2772
  return el(
2208
2773
  "p",
2209
2774
  { class: classes(["mex-embed", "mex-embed-link"], b.tunes) },
@@ -2263,6 +2828,15 @@ var RENDERERS = {
2263
2828
  return el("p", { class: classes(["mex-button-block"], b.tunes) }, inner);
2264
2829
  },
2265
2830
  delimiter: (b) => el("hr", { class: classes(["mex-delimiter"], b.tunes) }),
2831
+ // Math block (2.4): MathML from `options.math`, else the delimited TeX source.
2832
+ math: (b, o) => b.data.tex.trim() ? mathElement(o, b.data.tex, {
2833
+ display: b.data.display !== false,
2834
+ block: true,
2835
+ className: classes(
2836
+ ["mex-math", ...b.data.display !== false ? ["mex-math-display"] : []],
2837
+ b.tunes
2838
+ )
2839
+ }) : null,
2266
2840
  toc: (b, o) => {
2267
2841
  const tree = buildTocTree(b.headings || [], b.data);
2268
2842
  if (!tree.length) return null;
@@ -2355,15 +2929,15 @@ var RESOURCE_ATTRIBUTES = /* @__PURE__ */ new Set(["src", "poster", "data", "bac
2355
2929
  var cleanUrlAttribute = (name, value) => {
2356
2930
  if (name === "srcset" || name === "imagesrcset") {
2357
2931
  const parts = value.split(",").map((part) => part.trim());
2358
- const clean = [];
2932
+ const clean2 = [];
2359
2933
  for (const part of parts) {
2360
2934
  const [url, descriptor, extra] = part.split(/\s+/);
2361
2935
  if (extra !== void 0 || descriptor && !/^\d+(?:\.\d+)?[wx]$/.test(descriptor)) return "";
2362
2936
  const safe = sanitizeUrl(url, { schemes: ["http", "https"] });
2363
2937
  if (!safe) return "";
2364
- clean.push(descriptor ? `${safe} ${descriptor}` : safe);
2938
+ clean2.push(descriptor ? `${safe} ${descriptor}` : safe);
2365
2939
  }
2366
- return clean.join(", ");
2940
+ return clean2.join(", ");
2367
2941
  }
2368
2942
  return sanitizeUrl(value, { schemes: RESOURCE_ATTRIBUTES.has(name) ? ["http", "https"] : LINK_SCHEMES });
2369
2943
  };
@@ -2421,7 +2995,13 @@ var cleanOverrideNodes = (input, trusted) => {
2421
2995
  };
2422
2996
  var rawAllowed = (options) => options.rawHtml === "allow" && typeof options.sanitizeRaw === "function";
2423
2997
  var createTreeBuilder = (value, options, mode = {}) => {
2424
- const opts = options && typeof options === "object" ? options : {};
2998
+ const base = options && typeof options === "object" ? options : {};
2999
+ const opts = { ...base };
3000
+ const footnotes = createFootnoteTree(base, (note) => inlineNodesToRender(note, opts));
3001
+ opts[RENDER_STATE] = {
3002
+ math: (tex) => mathElement(base, tex, { display: false, block: false }),
3003
+ footnote: (node) => footnotes.marker(node)
3004
+ };
2425
3005
  const publicOf = /* @__PURE__ */ new WeakMap();
2426
3006
  const preparedOf = /* @__PURE__ */ new WeakMap();
2427
3007
  const trusted = /* @__PURE__ */ new WeakSet();
@@ -2505,6 +3085,8 @@ var createTreeBuilder = (value, options, mode = {}) => {
2505
3085
  childNodes: renderBlocks
2506
3086
  };
2507
3087
  const nodes = renderList(annotateHeadings(prepareBlocks(value, opts), opts));
3088
+ const section = footnotes.section();
3089
+ if (section) nodes.push(textNode("\n"), section);
2508
3090
  return { nodes, renderBlocks, helpers };
2509
3091
  };
2510
3092
  var flattenBlocks = (nodes) => {
@@ -2530,6 +3112,14 @@ var renderTree = (value, options) => flattenBlocks(createTreeBuilder(value, opti
2530
3112
  var renderHtml = (value, options = {}) => serializeNodes(createTreeBuilder(value, options, { overrideHtml: true }).nodes);
2531
3113
 
2532
3114
  // shared/render/text.mjs
3115
+ var notes = null;
3116
+ var footnoteText = (node) => {
3117
+ if (!notes) return "";
3118
+ const { n } = notes.numbers.add(node.attrs["data-mex-footnote"]);
3119
+ notes.items.push({ n, note: node.note || [] });
3120
+ return `[${n}]`;
3121
+ };
3122
+ var inlineToText2 = (html) => inlineToText(html, { footnote: footnoteText });
2533
3123
  var tocLines = (nodes, ordered, depth) => nodes.flatMap((node, index) => [
2534
3124
  `${" ".repeat(depth)}${ordered ? `${index + 1}.` : "-"} ${node.text}`,
2535
3125
  ...tocLines(node.children, ordered, depth + 1)
@@ -2542,7 +3132,7 @@ var listLines = (items, style, start, depth) => {
2542
3132
  if (style === "ordered") marker = `${start + index}.`;
2543
3133
  else if (style === "checklist") marker = item.meta && item.meta.checked ? "[x]" : "[ ]";
2544
3134
  const indent = " ".repeat(depth);
2545
- const text = inlineToText(content).trim().replace(/\n/g, `
3135
+ const text = inlineToText2(content).trim().replace(/\n/g, `
2546
3136
  ${indent} `);
2547
3137
  lines.push(`${indent}${marker} ${text}`);
2548
3138
  if (typeof item !== "string" && Array.isArray(item.items) && item.items.length && depth < 12)
@@ -2550,7 +3140,7 @@ ${indent} `);
2550
3140
  });
2551
3141
  return lines;
2552
3142
  };
2553
- var t = (html) => inlineToText(html).trim();
3143
+ var t = (html) => inlineToText2(html).trim();
2554
3144
  var mediaText = (b) => {
2555
3145
  if (!b.data.file.url) return "";
2556
3146
  const parts = [b.data.title.trim(), t(b.data.caption)].filter(Boolean);
@@ -2571,9 +3161,16 @@ var RENDERERS2 = {
2571
3161
  alert: (b) => t(b.data.message),
2572
3162
  toggle: (b, _o, render) => [t(b.data.text), render(b.children)].filter(Boolean).join("\n\n"),
2573
3163
  code: (b) => b.data.code,
2574
- codeFlask: (b) => b.data.code,
3164
+ // 2.4: the file name label on its own line before the code.
3165
+ codeFlask: (b) => typeof b.data.filename === "string" && b.data.filename ? [b.data.filename, b.data.code].filter(Boolean).join("\n") : b.data.code,
2575
3166
  raw: () => "",
2576
- table: (b) => b.data.content.map((row) => row.map((cell2) => t(cell2).replace(/\s+/g, " ")).join(" ")).join("\n"),
3167
+ // Tab-separated rows; merged cells leave their covered cells empty; the caption (2.4) is the first line.
3168
+ table: (b) => {
3169
+ const rows = b.data.content.map((row) => row.map((cell2) => t(cell2).replace(/\s+/g, " ")).join(" ")).join("\n");
3170
+ const caption = b.data.caption ? t(b.data.caption).replace(/\s+/g, " ") : "";
3171
+ return caption && b.data.content.length ? `${caption}
3172
+ ${rows}` : rows;
3173
+ },
2577
3174
  image: (b) => t(b.data.caption) || (b.raw.decorative === true ? "" : (b.data.file.alt || "").trim()),
2578
3175
  simpleImage: (b) => t(b.data.caption),
2579
3176
  gallery: (b) => [
@@ -2590,6 +3187,7 @@ var RENDERERS2 = {
2590
3187
  personality: (b) => [b.data.name, b.data.description, b.data.link].filter(Boolean).join("\n"),
2591
3188
  button: (b) => b.data.link ? `${b.data.text} (${b.data.link})` : b.data.text,
2592
3189
  delimiter: () => "---",
3190
+ math: (b) => b.data.tex.trim(),
2593
3191
  toc: (b) => {
2594
3192
  const tree = buildTocTree(b.headings || [], b.data);
2595
3193
  if (!tree.length) return "";
@@ -2600,15 +3198,29 @@ var registeredText = (block) => {
2600
3198
  const { definition } = block;
2601
3199
  if (definition.text) {
2602
3200
  try {
2603
- const out = definition.text(block.data, { text: (html) => inlineToText(html) });
3201
+ const out = definition.text(block.data, { text: (html) => inlineToText2(html) });
2604
3202
  if (typeof out === "string") return out;
2605
3203
  } catch {
2606
3204
  }
2607
3205
  }
2608
- return definition.fields(block.data).map((field) => (field.kind === "html" ? inlineToText(field.value) : field.value).trim()).filter(Boolean).join("\n");
3206
+ return definition.fields(block.data).map((field) => (field.kind === "html" ? inlineToText2(field.value) : field.value).trim()).filter(Boolean).join("\n");
2609
3207
  };
2610
3208
  var renderText = (value, options = {}) => {
2611
3209
  const opts = options && typeof options === "object" ? options : {};
3210
+ const previous = notes;
3211
+ notes = { numbers: createFootnoteNumbers(), items: [] };
3212
+ try {
3213
+ const text = renderContent(value, opts);
3214
+ if (!notes.items.length) return text;
3215
+ const list = notes.items.map(
3216
+ (item) => `[${item.n}] ${nodesToText(item.note).replace(/\u00a0/g, " ").trim().replace(/\n/g, "\n ")}`.trimEnd()
3217
+ );
3218
+ return [text, [footnoteOptions(opts).label, ...list].join("\n")].filter(Boolean).join("\n\n");
3219
+ } finally {
3220
+ notes = previous;
3221
+ }
3222
+ };
3223
+ var renderContent = (value, opts) => {
2612
3224
  const render = (blocks) => blocks.map((block) => {
2613
3225
  const override = overrideFor(opts, block.type);
2614
3226
  if (override) {
@@ -2620,18 +3232,37 @@ var renderText = (value, options = {}) => {
2620
3232
  tunes: block.tunes,
2621
3233
  children: block.children
2622
3234
  },
2623
- { text: (html) => inlineToText(html), renderChildren: render }
3235
+ { text: (html) => inlineToText2(html), renderChildren: render }
2624
3236
  );
2625
3237
  if (typeof out === "string") return out;
2626
3238
  }
2627
3239
  if (block.known) return RENDERERS2[block.type](block, opts, render);
2628
3240
  if (block.definition) return registeredText(block);
2629
- return scalarFields(block.data).map(([, v]) => inlineToText(v).trim()).filter(Boolean).join("\n");
3241
+ return scalarFields(block.data).map(([, v]) => inlineToText2(v).trim()).filter(Boolean).join("\n");
2630
3242
  }).map((text) => String(text).replace(/\u00a0/g, " ")).filter((text) => text.trim() !== "").join("\n\n");
2631
3243
  return render(annotateHeadings(prepareBlocks(value, opts), opts));
2632
3244
  };
2633
3245
 
2634
3246
  // shared/render/markdown.mjs
3247
+ var notes2 = null;
3248
+ var mathSource = (tex) => tex.replace(/<(?=[A-Za-z/!?])/g, "< ");
3249
+ var dollarFence = (text, min) => "$".repeat(Math.max(min, ...(text.match(/\$+/g) || []).map((run) => run.length + 1)));
3250
+ var inlineMath = (tex) => {
3251
+ const text = mathSource(tex.replace(/\s*\n\s*/g, " ").trim());
3252
+ if (!text) return "";
3253
+ const fence2 = dollarFence(text, 1);
3254
+ return `${fence2}${text}${fence2}`;
3255
+ };
3256
+ var displayMath = (tex) => {
3257
+ const text = mathSource(
3258
+ tex.split("\n").filter((line) => line.trim()).join("\n").trim()
3259
+ );
3260
+ if (!text) return "";
3261
+ const fence2 = dollarFence(text, 2);
3262
+ return `${fence2}
3263
+ ${text}
3264
+ ${fence2}`;
3265
+ };
2635
3266
  var escapeMarkdown = (text) => String(text).replace(/\u00a0/g, " ").replace(/[\\`*_[\]<>|~&{}]/g, (char) => `\\${char}`).replace(
2636
3267
  /(^|\n)(\s*)([#>+=-]|\d{1,9}[.)])/g,
2637
3268
  (_m, nl, space, mark) => `${nl}${space}${mark.replace(/^(\d*)([#>+=.)-])$/, "$1\\$2")}`
@@ -2641,8 +3272,8 @@ var linkUrl = (url) => String(url).replace(
2641
3272
  (char) => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`
2642
3273
  );
2643
3274
  var linkTitle = (title) => {
2644
- const clean = String(title || "").replace(/\s+/g, " ").trim();
2645
- return clean ? ` "${clean.replace(/[\\"<>]/g, (char) => `\\${char}`)}"` : "";
3275
+ const clean2 = String(title || "").replace(/\s+/g, " ").trim();
3276
+ return clean2 ? ` "${clean2.replace(/[\\"<>]/g, (char) => `\\${char}`)}"` : "";
2646
3277
  };
2647
3278
  var wrap = (marker, inner) => {
2648
3279
  const match = /^(\s*)([\s\S]*?)(\s*)$/.exec(inner);
@@ -2660,6 +3291,14 @@ var codeSpan = (code) => {
2660
3291
  var rawText = (nodes) => nodes.map((n) => n.type === "text" ? n.value : n.tag === "br" ? "\n" : rawText(n.children)).join("");
2661
3292
  var nodesToMarkdown = (nodes, options) => nodes.map((node) => {
2662
3293
  if (node.type === "text") return escapeMarkdown(node.value);
3294
+ if (isMathNode(node)) return inlineMath(nodesToText(node.children));
3295
+ if (isFootnoteNode(node)) {
3296
+ if (!notes2) return "";
3297
+ const { n } = notes2.numbers.add(node.attrs["data-mex-footnote"]);
3298
+ const label3 = `${notes2.prefix}${n}`;
3299
+ notes2.items.push({ label: label3, note: node.note || [] });
3300
+ return `[^${label3}]`;
3301
+ }
2663
3302
  const inner = () => nodesToMarkdown(node.children, options);
2664
3303
  switch (node.tag) {
2665
3304
  case "br":
@@ -2703,14 +3342,26 @@ ${childIndent}`);
2703
3342
  });
2704
3343
  return lines;
2705
3344
  };
2706
- var fence = (code, language) => {
3345
+ var fence = (code, language, filename) => {
3346
+ const valid = language && /^[a-z0-9+#-]{1,32}$/i.test(language);
3347
+ if (filename) return titledFence(code, valid ? language : "plaintext", filename);
2707
3348
  const longest = Math.max(2, ...(code.match(/`{3,}/g) || []).map((run) => run.length));
2708
3349
  const marks = "`".repeat(longest + 1);
2709
- const info = language && /^[a-z0-9+#-]{1,32}$/i.test(language) && language !== "plaintext" ? language : "";
3350
+ const info = valid && language !== "plaintext" ? language : "";
2710
3351
  return `${marks}${info}
2711
3352
  ${code.replace(/\n$/, "")}
2712
3353
  ${marks}`;
2713
3354
  };
3355
+ var ALIGN_RULES = Object.freeze({ left: ":---", center: ":---:", right: "---:" });
3356
+ var titledFence = (code, language, filename) => {
3357
+ const char = filename.includes("`") ? "~" : "`";
3358
+ const runs = code.match(char === "`" ? /`{3,}/g : /~{3,}/g) || [];
3359
+ const marks = char.repeat(Math.max(2, ...runs.map((run) => run.length)) + 1);
3360
+ const title = filename.replace(/[\\"]/g, (ch) => `\\${ch}`);
3361
+ return `${marks}${language} title="${title}"
3362
+ ${code.replace(/\n$/, "")}
3363
+ ${marks}`;
3364
+ };
2714
3365
  var cell = (html, options) => oneLine(md(html, options)) || " ";
2715
3366
  var RENDERERS3 = {
2716
3367
  paragraph: (b, o) => md(b.data.text, o),
@@ -2746,7 +3397,7 @@ var RENDERERS3 = {
2746
3397
  },
2747
3398
  toggle: (b, o, render) => [b.data.text ? `**${oneLine(md(b.data.text, o))}**` : "", render(b.children)].filter(Boolean).join("\n\n"),
2748
3399
  code: (b) => b.data.code ? fence(b.data.code) : "",
2749
- codeFlask: (b) => b.data.code ? fence(b.data.code, b.data.language) : "",
3400
+ codeFlask: (b) => b.data.code || b.data.filename ? fence(b.data.code, b.data.language, b.data.filename || "") : "",
2750
3401
  raw: (b, o) => {
2751
3402
  if (o.rawHtml !== "allow" || typeof o.sanitizeRaw !== "function") return "";
2752
3403
  const html = o.sanitizeRaw(String(b.raw.html || ""));
@@ -2759,11 +3410,16 @@ var RENDERERS3 = {
2759
3410
  const line = (row) => `| ${Array.from({ length: width }, (_, i) => cell(row[i] || "", o)).join(" | ")} |`;
2760
3411
  const head = b.data.withHeadings ? rows[0] : [];
2761
3412
  const body = b.data.withHeadings ? rows.slice(1) : rows;
2762
- return [
3413
+ const align = Array.isArray(b.data.align) ? b.data.align : [];
3414
+ const table = [
2763
3415
  line(head),
2764
- `| ${Array.from({ length: width }, () => "---").join(" | ")} |`,
3416
+ `| ${Array.from({ length: width }, (_, i) => ALIGN_RULES[align[i]] || "---").join(" | ")} |`,
2765
3417
  ...body.map(line)
2766
3418
  ].join("\n");
3419
+ const caption = b.data.caption ? oneLine(md(b.data.caption, o)) : "";
3420
+ return caption ? `${caption}
3421
+
3422
+ ${table}` : table;
2767
3423
  },
2768
3424
  image: (b, o) => {
2769
3425
  const file = resolveMedia(b.data.file, b, o);
@@ -2815,6 +3471,7 @@ var RENDERERS3 = {
2815
3471
  return b.data.link ? `[${escapeMarkdown(b.data.text)}](${linkUrl(b.data.link)})` : escapeMarkdown(b.data.text);
2816
3472
  },
2817
3473
  delimiter: () => "---",
3474
+ math: (b) => b.data.display === false ? inlineMath(b.data.tex) : displayMath(b.data.tex),
2818
3475
  toc: (b) => {
2819
3476
  const tree = buildTocTree(b.headings || [], b.data);
2820
3477
  if (!tree.length) return "";
@@ -2856,6 +3513,22 @@ var registeredMarkdown = (block, opts) => {
2856
3513
  };
2857
3514
  var renderMarkdown = (value, options = {}) => {
2858
3515
  const opts = options && typeof options === "object" ? options : {};
3516
+ const previous = notes2;
3517
+ const prefix = opts.footnotes && typeof opts.footnotes === "object" && typeof opts.footnotes.prefix === "string" ? footnoteOptions(opts).prefix : "";
3518
+ notes2 = { numbers: createFootnoteNumbers(), items: [], prefix };
3519
+ try {
3520
+ const markdown = renderContent2(value, opts);
3521
+ if (!notes2.items.length) return markdown;
3522
+ const definitions = notes2.items.map((item) => {
3523
+ const body = nodesToMarkdown(item.note, opts).trim().replace(/\n/g, "\n ");
3524
+ return `[^${item.label}]: ${body}`.trimEnd();
3525
+ });
3526
+ return [markdown, definitions.join("\n")].filter(Boolean).join("\n\n");
3527
+ } finally {
3528
+ notes2 = previous;
3529
+ }
3530
+ };
3531
+ var renderContent2 = (value, opts) => {
2859
3532
  const render = (blocks) => blocks.map((block) => {
2860
3533
  const override = overrideFor(opts, block.type);
2861
3534
  if (override) {