magic-editor-x 2.3.1 → 2.5.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 (106) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/README.md +428 -148
  3. package/bin/magic-editor-x.mjs +55 -8
  4. package/dist/admin/AuditPage-Be78C7EC.mjs +382 -0
  5. package/dist/admin/AuditPage-iQzpjH8H.js +382 -0
  6. package/dist/admin/{ConfigurationPage-CYGDLjM7.mjs → ConfigurationPage-C9CPBfWy.mjs} +405 -10
  7. package/dist/admin/{ConfigurationPage-CFP3lp9p.js → ConfigurationPage-DefuBeYO.js} +415 -20
  8. package/dist/admin/ConfirmAction-CUhpngYU.js +71 -0
  9. package/dist/admin/ConfirmAction-CZjpduc3.mjs +72 -0
  10. package/dist/admin/Content-BttG50Mc.mjs +360 -0
  11. package/dist/admin/Content-V5MRBsI3.js +362 -0
  12. package/dist/admin/{CustomBlocksPage-B5Q33N-s.mjs → CustomBlocksPage-DB5nnCsn.mjs} +8 -5
  13. package/dist/admin/{CustomBlocksPage-DzPOSpfn.js → CustomBlocksPage-Dg2rM3F4.js} +26 -23
  14. package/dist/admin/EntryWidgets-B8YA0Zxy.mjs +199 -0
  15. package/dist/admin/EntryWidgets-BcXAAx3F.js +201 -0
  16. package/dist/admin/MentionsWidget-CJPZDk9Z.mjs +225 -0
  17. package/dist/admin/MentionsWidget-DUz6YVIG.js +227 -0
  18. package/dist/admin/{useT-Cmg1jwwG.mjs → SectionCard-8ZNHkvn9.mjs} +2 -12
  19. package/dist/admin/{useT-DNphiBQR.js → SectionCard-Bs-xiiH1.js} +0 -10
  20. package/dist/admin/{TemplatesPage-4A8JNO_Z.mjs → TemplatesPage-VsZ_Mc0R.mjs} +307 -10
  21. package/dist/admin/{TemplatesPage-BVkgafCK.js → TemplatesPage-dx4_yd_t.js} +321 -24
  22. package/dist/admin/{ConfirmAction-zLuIFj8t.js → api-4AYzwS4-.js} +28 -71
  23. package/dist/admin/{ConfirmAction-DuQwvRYi.mjs → api-CcTYyckq.mjs} +28 -71
  24. package/dist/admin/auditText-DIIYVR6k.mjs +110 -0
  25. package/dist/admin/auditText-DUhWu2Nx.js +109 -0
  26. package/dist/admin/comments-C7P41lan.js +86 -0
  27. package/dist/admin/comments-hfIbLQNO.mjs +87 -0
  28. package/dist/admin/{de-B1X46JJZ.js → de-B6rdcOqQ.js} +293 -5
  29. package/dist/admin/{de-1cFMs-4c.mjs → de-BWfR2jTg.mjs} +8 -1
  30. package/dist/admin/{de-BUS1hUw0.mjs → de-Bip0sBRT.mjs} +158 -1
  31. package/dist/admin/{de-Dn8athM8.js → de-BrPR4sUB.js} +8 -1
  32. package/dist/admin/{de-DOiGaTNX.mjs → de-CQA8hOpl.mjs} +293 -5
  33. package/dist/admin/{de-C3AsGauQ.js → de-CnnxKXj7.js} +158 -1
  34. package/dist/admin/{de-2Ie5jy7j.js → de-Dss5POqk.js} +53 -3
  35. package/dist/admin/{de-BMY2LBaa.mjs → de-zgHCYTLH.mjs} +53 -3
  36. package/dist/admin/{en-CIZ5Ggod.js → en--JjAHbpP.js} +8 -1
  37. package/dist/admin/{en-CU6UzV4g.mjs → en-BCKaVgBM.mjs} +293 -5
  38. package/dist/admin/{en-Ah-Cw0Wd.js → en-CJ17Sp_e.js} +53 -3
  39. package/dist/admin/{en-CDg_18Bt.js → en-CbGkcq0Q.js} +293 -5
  40. package/dist/admin/{en-GCzgS9Aw.mjs → en-Cd6Jk-J0.mjs} +158 -1
  41. package/dist/admin/{en-BkEjpC3i.js → en-D69Fe9ZO.js} +158 -1
  42. package/dist/admin/{en-Dc9y-6n9.mjs → en-Dr58wBAo.mjs} +8 -1
  43. package/dist/admin/{en-CvFiqti2.mjs → en-Uhm7OouM.mjs} +53 -3
  44. package/dist/admin/entry-panel-events-0msyPrAD.js +18 -0
  45. package/dist/admin/entry-panel-events-XRuUoLZ9.mjs +19 -0
  46. package/dist/admin/{es-D2Kw6E4N.mjs → es-B2Hkkbw9.mjs} +8 -1
  47. package/dist/admin/{es-DbKHZz5l.mjs → es-BMkmfH88.mjs} +53 -3
  48. package/dist/admin/{es-DHBBZKl2.mjs → es-Bz8d72Fa.mjs} +158 -1
  49. package/dist/admin/{es-BCpJmUEM.js → es-C8UotT8O.js} +293 -5
  50. package/dist/admin/{es-C4pEnDRv.js → es-CcEDZpVQ.js} +158 -1
  51. package/dist/admin/{es-Cr8JH85N.js → es-DJm3HFJt.js} +53 -3
  52. package/dist/admin/{es-C4IRHV5d.js → es-YvaTAtqY.js} +8 -1
  53. package/dist/admin/{es-BmfffNM2.mjs → es-pvPfNAld.mjs} +293 -5
  54. package/dist/admin/{fr-BOvvfEH7.mjs → fr-BvPjRiwr.mjs} +8 -1
  55. package/dist/admin/{fr-Dvq4xk2e.mjs → fr-CKHZ0xxU.mjs} +158 -1
  56. package/dist/admin/{fr-OJ4VW1kh.js → fr-CRM9VuAq.js} +53 -3
  57. package/dist/admin/{fr-DQJ_7aq5.mjs → fr-CrIHmKYX.mjs} +53 -3
  58. package/dist/admin/{fr-C2aLSwEu.js → fr-Cx29jQ_g.js} +158 -1
  59. package/dist/admin/{fr-DZd2XJP6.mjs → fr-D4tL6Ag2.mjs} +293 -5
  60. package/dist/admin/{fr-Zkb8vfjN.js → fr-Di-U-rAH.js} +8 -1
  61. package/dist/admin/{fr-ZcN0yM_2.js → fr-DrUYv2jh.js} +293 -5
  62. package/dist/admin/{index-k8_a5o1A.mjs → index-C4ksUkEm.mjs} +20059 -10130
  63. package/dist/admin/{index-DQVE0ymw.js → index-C5D3VqLq.js} +21272 -11344
  64. package/dist/admin/index-CMYCZWOh.mjs +3752 -0
  65. package/dist/admin/index-DRyctF9s.js +3753 -0
  66. package/dist/admin/index.js +2 -1
  67. package/dist/admin/index.mjs +3 -2
  68. package/dist/admin/math-D6jmskGS.js +49 -0
  69. package/dist/admin/math-DntdSWKX.mjs +47 -0
  70. package/dist/admin/{pt-CilDggGF.mjs → pt-B8x7v-Xw.mjs} +158 -1
  71. package/dist/admin/{pt-DX0OAIoL.js → pt-BYn2xx78.js} +158 -1
  72. package/dist/admin/{pt-CImqDnLB.js → pt-CojQcz-p.js} +293 -5
  73. package/dist/admin/{pt-C3UdeIpd.mjs → pt-CuoIihKx.mjs} +293 -5
  74. package/dist/admin/{pt-1IUyx6ae.js → pt-CzrN_3ui.js} +8 -1
  75. package/dist/admin/{pt-BSLzA17U.mjs → pt-DDlPJYtB.mjs} +53 -3
  76. package/dist/admin/{pt-D0I0_JYs.js → pt-DPVAycXJ.js} +53 -3
  77. package/dist/admin/{pt-etwsg3G4.mjs → pt-DdGagO99.mjs} +8 -1
  78. package/dist/admin/useT-Bpw__IXT.js +12 -0
  79. package/dist/admin/useT-Cb-R3kyA.mjs +13 -0
  80. package/dist/blocks/index.d.mts +126 -0
  81. package/dist/blocks/index.d.ts +126 -0
  82. package/dist/blocks/index.js +184 -4
  83. package/dist/blocks/index.mjs +184 -4
  84. package/dist/math/index.d.mts +27 -0
  85. package/dist/math/index.d.ts +27 -0
  86. package/dist/math/index.js +168 -0
  87. package/dist/math/index.mjs +138 -0
  88. package/dist/react/index.js +1650 -759
  89. package/dist/react/index.mjs +1650 -759
  90. package/dist/render/index.d.mts +48 -0
  91. package/dist/render/index.d.ts +48 -0
  92. package/dist/render/index.js +1755 -773
  93. package/dist/render/index.mjs +1755 -773
  94. package/dist/server/index.js +29475 -18462
  95. package/dist/server/index.mjs +29475 -18462
  96. package/dist/server/mcp-worker.js +11319 -0
  97. package/dist/vue/index.js +1650 -759
  98. package/dist/vue/index.mjs +1650 -759
  99. package/package.json +14 -8
  100. package/schema/magic-editor-x.schema.json +135 -2
  101. package/types/blocks.d.ts +126 -0
  102. package/types/index.d.ts +52 -1
  103. package/types/math.d.ts +27 -0
  104. package/types/render.d.ts +48 -0
  105. package/dist/admin/index-DR8sHkTk.js +0 -1940
  106. package/dist/admin/index-My6FjjHB.mjs +0 -1939
@@ -20,13 +20,13 @@ var ATTRIBUTE_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
20
20
  var isSafeAttributeName = (name) => ATTRIBUTE_NAME.test(name) && !name.startsWith("on") && name !== "style" && name !== "srcdoc";
21
21
  var textNode = (value) => ({ type: "text", value: String(value ?? "") });
22
22
  var el = (tag, attrs, children) => {
23
- const clean = {};
23
+ const clean2 = {};
24
24
  for (const [name, value] of Object.entries(attrs || {})) {
25
25
  if (value === void 0 || value === null || value === false) continue;
26
26
  if (value === "" && name !== "alt") continue;
27
- clean[name] = value === true ? true : String(value);
27
+ clean2[name] = value === true ? true : String(value);
28
28
  }
29
- return { type: "element", tag, attrs: clean, children: toNodes(children) };
29
+ return { type: "element", tag, attrs: clean2, children: toNodes(children) };
30
30
  };
31
31
  var toNodes = (children) => {
32
32
  const out = [];
@@ -94,7 +94,9 @@ var MARKED_BLOCKS = Object.freeze({
94
94
  keys: Object.freeze(["file", "title", "caption", "loop", "tracks"]),
95
95
  anchor: Object.freeze(["file", "object"])
96
96
  }),
97
- synced: Object.freeze({ keys: Object.freeze(["ref"]), anchor: Object.freeze(["ref", "string"]) })
97
+ synced: Object.freeze({ keys: Object.freeze(["ref"]), anchor: Object.freeze(["ref", "string"]) }),
98
+ // 2.4: math block. A Settings custom block named `math` could exist before 2.4.
99
+ math: Object.freeze({ keys: Object.freeze(["tex", "display"]), anchor: Object.freeze(["tex", "string"]) })
98
100
  });
99
101
  var isBuiltInMarker = (value) => Number.isInteger(value) && /** @type {number} */
100
102
  value >= 1;
@@ -113,6 +115,10 @@ var isMarkedBuiltIn = (type, data) => {
113
115
  return hasBuiltInShape(MARKED_BLOCKS[type], data);
114
116
  };
115
117
 
118
+ // shared/field-identity.mjs
119
+ var FIELD_KEY_PATTERN = /^[A-Za-z0-9_-]{16,32}$/;
120
+ var isValidFieldKey = (value) => typeof value === "string" && FIELD_KEY_PATTERN.test(value);
121
+
116
122
  // shared/editor-data.mjs
117
123
  var EDITOR_DATA_LIMITS = Object.freeze({
118
124
  maxBlocks: 5e3,
@@ -225,8 +231,8 @@ var normalizeEditorData = (value) => {
225
231
  if (!isPlainObject2(candidate)) {
226
232
  throw new EditorDataError("Editor content must be an Editor.js object", "INVALID_SHAPE");
227
233
  }
228
- const clean = cloneJsonSafe(candidate);
229
- const rawBlocks = Array.isArray(clean.blocks) ? clean.blocks : [];
234
+ const clean2 = cloneJsonSafe(candidate);
235
+ const rawBlocks = Array.isArray(clean2.blocks) ? clean2.blocks : [];
230
236
  if (rawBlocks.length > EDITOR_DATA_LIMITS.maxBlocks) {
231
237
  throw new EditorDataError("Editor content has too many blocks", "TOO_MANY_BLOCKS");
232
238
  }
@@ -245,9 +251,10 @@ var normalizeEditorData = (value) => {
245
251
  if (isPlainObject2(block.tunes) && Object.keys(block.tunes).length > 0) normalized.tunes = block.tunes;
246
252
  blocks.push(normalized);
247
253
  });
248
- const time = Number.isFinite(clean.time) && clean.time > 0 ? Math.floor(clean.time) : 0;
249
- const version = typeof clean.version === "string" && clean.version.length <= 32 ? clean.version : "2.31.7";
254
+ const time = Number.isFinite(clean2.time) && clean2.time > 0 ? Math.floor(clean2.time) : 0;
255
+ const version = typeof clean2.version === "string" && clean2.version.length <= 32 ? clean2.version : "2.31.7";
250
256
  const result = { time, blocks, version };
257
+ if (isValidFieldKey(clean2.fieldKey)) result.fieldKey = clean2.fieldKey;
251
258
  const size = byteLength(JSON.stringify(result));
252
259
  if (size > EDITOR_DATA_LIMITS.maxBytes) {
253
260
  throw new EditorDataError("Editor content exceeds the size limit", "TOO_LARGE");
@@ -275,6 +282,95 @@ var byteLength = (text) => {
275
282
  return bytes;
276
283
  };
277
284
 
285
+ // shared/table.mjs
286
+ var TABLE_LIMITS = Object.freeze({ rows: 500, cols: 100, merges: 1e3, caption: 4e3 });
287
+ var TABLE_ALIGNS = Object.freeze(["left", "center", "right"]);
288
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
289
+ var tableWidth = (content) => Array.isArray(content) ? content.reduce((width, row) => Math.max(width, Array.isArray(row) ? row.length : 0), 0) : 0;
290
+ var cleanTableAlign = (value, cols) => {
291
+ if (!Array.isArray(value) || cols <= 0) return null;
292
+ const out = value.slice(0, Math.min(cols, TABLE_LIMITS.cols)).map((item) => typeof item === "string" && TABLE_ALIGNS.includes(item) ? item : null);
293
+ while (out.length && out[out.length - 1] === null) out.pop();
294
+ return out.length ? out : null;
295
+ };
296
+ 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;
297
+ var normalizeMerges = (merges, rows, cols, options = {}) => {
298
+ if (!Array.isArray(merges) || rows <= 0 || cols <= 0) return [];
299
+ const out = [];
300
+ for (const merge of merges.slice(0, TABLE_LIMITS.merges)) {
301
+ if (!isObject(merge)) continue;
302
+ const { row, col, rowspan, colspan } = merge;
303
+ if (![row, col, rowspan, colspan].every(Number.isInteger)) continue;
304
+ if (row < 0 || col < 0 || rowspan < 1 || colspan < 1 || rowspan * colspan < 2) continue;
305
+ if (row + rowspan > rows || col + colspan > cols) continue;
306
+ if (options.headerRow && row === 0 && rowspan > 1) continue;
307
+ const next = { row, col, rowspan, colspan };
308
+ if (out.some((other) => intersects(other, next))) continue;
309
+ out.push(next);
310
+ }
311
+ return out.sort((a, b) => a.row - b.row || a.col - b.col);
312
+ };
313
+ var mergeMap = (merges) => {
314
+ const anchors = /* @__PURE__ */ new Map();
315
+ const covered = /* @__PURE__ */ new Map();
316
+ for (const merge of merges || []) {
317
+ anchors.set(`${merge.row}:${merge.col}`, merge);
318
+ for (let r = merge.row; r < merge.row + merge.rowspan; r += 1)
319
+ for (let c = merge.col; c < merge.col + merge.colspan; c += 1)
320
+ if (r !== merge.row || c !== merge.col) covered.set(`${r}:${c}`, merge);
321
+ }
322
+ return { anchors, covered };
323
+ };
324
+ var headerKind = (data, row, col) => {
325
+ if (data.withHeadings === true && row === 0) return "col";
326
+ if (data.headerColumn === true && col === 0) return "row";
327
+ return null;
328
+ };
329
+ var tableLayout = (data) => {
330
+ const merges = Array.isArray(data.merges) ? data.merges : [];
331
+ const { anchors, covered } = mergeMap(merges);
332
+ const align = Array.isArray(data.align) ? data.align : [];
333
+ return (data.content || []).map(
334
+ (row, r) => row.map((html, c) => {
335
+ if (covered.has(`${r}:${c}`)) return null;
336
+ const merge = anchors.get(`${r}:${c}`);
337
+ return {
338
+ row: r,
339
+ col: c,
340
+ html,
341
+ rowspan: merge ? merge.rowspan : 1,
342
+ colspan: merge ? merge.colspan : 1,
343
+ header: headerKind(data, r, c),
344
+ align: typeof align[c] === "string" ? align[c] : null
345
+ };
346
+ }).filter(Boolean)
347
+ );
348
+ };
349
+ var isBlankInlineHtml = (html) => typeof html !== "string" || /^(?:\s|&nbsp;|&#160;|\u00a0|<br\s*\/?>)*$/i.test(html);
350
+ var cleanTableExtras = (out, d, inline) => {
351
+ if (d.headerColumn === true) out.headerColumn = true;
352
+ const rows = out.content.length;
353
+ const cols = tableWidth(out.content);
354
+ const align = cleanTableAlign(d.align, cols);
355
+ if (align) out.align = align;
356
+ const merges = normalizeMerges(d.merges, rows, cols, { headerRow: out.withHeadings === true });
357
+ if (merges.length) {
358
+ const { covered } = mergeMap(merges);
359
+ out.content = out.content.map(
360
+ (row, r) => Array.from(
361
+ { length: cols },
362
+ (_, c) => covered.has(`${r}:${c}`) ? "" : row[c] === void 0 ? "" : row[c]
363
+ )
364
+ );
365
+ out.merges = merges;
366
+ }
367
+ if (typeof d.caption === "string") {
368
+ const caption = inline(d.caption.slice(0, TABLE_LIMITS.caption));
369
+ if (!isBlankInlineHtml(caption)) out.caption = caption;
370
+ }
371
+ return out;
372
+ };
373
+
278
374
  // shared/sanitize-policy.mjs
279
375
  var INLINE_TAGS = Object.freeze([
280
376
  "b",
@@ -318,10 +414,21 @@ var cleanInternalLinkAttributes = (attribs) => {
318
414
  var isMentionLink = (attrs) => Boolean(
319
415
  attrs && attrs["data-mex-mention"] === "true" && attrs["data-mex-uid"] && attrs["data-mex-document-id"]
320
416
  );
417
+ var MATH_ATTRIBUTE = "data-mex-math";
418
+ var FOOTNOTE_ATTRIBUTES = Object.freeze(["data-mex-footnote", "data-mex-note"]);
419
+ var FOOTNOTE_ID = /^[A-Za-z0-9_-]{1,64}$/;
420
+ var MAX_MATH_TEX = 1e4;
421
+ var MAX_INLINE_TEX = 2e3;
422
+ var MAX_FOOTNOTE_NOTE = 4e3;
423
+ var INLINE_FORMAT_ATTRIBUTES = Object.freeze({
424
+ span: ["data-mex-color", "data-mex-annotation", "data-mex-a-*"],
425
+ mark: ["data-mex-highlight"]
426
+ });
321
427
  var INLINE_ATTRIBUTES = Object.freeze({
322
428
  a: ["href", "target", "rel", "title", ...INTERNAL_LINK_ATTRIBUTES],
323
- span: ["class", "data-tooltip"],
324
- mark: ["class"],
429
+ span: ["class", "data-tooltip", MATH_ATTRIBUTE, ...INLINE_FORMAT_ATTRIBUTES.span],
430
+ sup: [...FOOTNOTE_ATTRIBUTES],
431
+ mark: ["class", ...INLINE_FORMAT_ATTRIBUTES.mark],
325
432
  u: ["class"],
326
433
  s: ["class"],
327
434
  code: ["class"]
@@ -403,17 +510,17 @@ var mediaTracks = (tracks) => {
403
510
  if (!isPlainObject2(track)) continue;
404
511
  const file = cleanMediaFile(track.file, { vtt: true });
405
512
  if (!file.url) continue;
406
- const clean = {
513
+ const clean2 = {
407
514
  file,
408
515
  kind: oneOf(track.kind, TRACK_KINDS, "captions"),
409
516
  srclang: typeof track.srclang === "string" && SRCLANG.test(track.srclang) ? track.srclang : "",
410
517
  label: plain(track.label, 100)
411
518
  };
412
519
  if (track.default === true && !hasDefault) {
413
- clean.default = true;
520
+ clean2.default = true;
414
521
  hasDefault = true;
415
522
  }
416
- out.push(clean);
523
+ out.push(clean2);
417
524
  }
418
525
  return out;
419
526
  };
@@ -456,6 +563,17 @@ var listItems = (items, inline, depth = 0) => {
456
563
  return out;
457
564
  });
458
565
  };
566
+ var MAX_CODE_FILENAME = 200;
567
+ var FILENAME_STRIP = (
568
+ // eslint-disable-next-line no-control-regex -- the point is to remove control characters
569
+ /[\u0000-\u001f\u007f-\u009f\u061c\u200b-\u200f\u2028-\u202e\u2060\u2066-\u2069\ufeff]/g
570
+ );
571
+ var cleanCodeFilename = (value) => {
572
+ if (typeof value !== "string") return "";
573
+ return Array.from(
574
+ value.slice(0, 4 * MAX_CODE_FILENAME).replace(/[\t\n\r\f\v]/g, " ").replace(FILENAME_STRIP, "").replace(/\s+/g, " ").trim()
575
+ ).slice(0, MAX_CODE_FILENAME).join("").trim();
576
+ };
459
577
  var BLOCK_POLICIES = {
460
578
  paragraph: (d, inline) => ({ text: inline(d.text) }),
461
579
  header: (d, inline) => ({ text: inline(d.text), level: int(d.level, 1, 6, 2) }),
@@ -510,6 +628,8 @@ var BLOCK_POLICIES = {
510
628
  language: typeof d.language === "string" && /^[a-z0-9+#-]{1,32}$/i.test(d.language) ? d.language : "plaintext"
511
629
  };
512
630
  if (typeof d.showlinenumbers === "boolean") out.showlinenumbers = d.showlinenumbers;
631
+ const filename = cleanCodeFilename(d.filename);
632
+ if (filename) out.filename = filename;
513
633
  return out;
514
634
  },
515
635
  raw: (d, _inline, ctx) => {
@@ -518,11 +638,18 @@ var BLOCK_POLICIES = {
518
638
  if (ctx.rawHtml === "disable") return { html: "" };
519
639
  return { html: ctx.rawSanitizer(html) };
520
640
  },
521
- table: (d, inline) => ({
522
- withHeadings: bool(d.withHeadings),
523
- stretched: bool(d.stretched),
524
- content: Array.isArray(d.content) ? d.content.slice(0, 500).map((row) => Array.isArray(row) ? row.slice(0, 100).map((cell2) => inline(cell2)) : []) : []
525
- }),
641
+ // 2.4: optional header column, column alignment, merged cells and caption (shared/table.mjs).
642
+ table: (d, inline) => cleanTableExtras(
643
+ {
644
+ withHeadings: bool(d.withHeadings),
645
+ stretched: bool(d.stretched),
646
+ content: Array.isArray(d.content) ? d.content.slice(0, TABLE_LIMITS.rows).map(
647
+ (row) => Array.isArray(row) ? row.slice(0, TABLE_LIMITS.cols).map((cell2) => inline(cell2)) : []
648
+ ) : []
649
+ },
650
+ d,
651
+ inline
652
+ ),
526
653
  image: (d, inline) => {
527
654
  const file = isPlainObject2(d.file) ? d.file : {};
528
655
  const cleanFile = { url: sanitizeUrl(file.url, { schemes: ["http", "https"] }) };
@@ -618,6 +745,9 @@ var BLOCK_POLICIES = {
618
745
  if (typeof file.extension === "string") cleanFile.extension = plain(file.extension, 16);
619
746
  if (Number.isFinite(file.size)) cleanFile.size = file.size;
620
747
  if (typeof file.title === "string") cleanFile.title = plain(file.title, 255);
748
+ if (file.id !== void 0 && (Number.isInteger(file.id) || typeof file.id === "string"))
749
+ cleanFile.id = file.id;
750
+ if (typeof file.documentId === "string") cleanFile.documentId = plain(file.documentId, 64);
621
751
  return { file: cleanFile, title: plain(d.title, 255) };
622
752
  },
623
753
  embed: (d, inline) => ({
@@ -646,6 +776,12 @@ var BLOCK_POLICIES = {
646
776
  ref: typeof d.ref === "string" && /^[a-z0-9]{1,64}$/.test(d.ref) ? d.ref : "",
647
777
  _mex: BUILT_IN_MARKER_VERSION
648
778
  }),
779
+ // Math block (2.4): only the TeX source is stored; `display: false` renders it in text style.
780
+ math: (d) => ({
781
+ tex: plain(d.tex, MAX_MATH_TEX),
782
+ display: d.display !== false,
783
+ _mex: BUILT_IN_MARKER_VERSION
784
+ }),
649
785
  toc: (d) => {
650
786
  const minLevel = int(d.minLevel, 1, 6, 2);
651
787
  const maxLevel = int(d.maxLevel, 1, 6, 4);
@@ -687,763 +823,1486 @@ var registeredBlockOf = (block, explicit) => {
687
823
  };
688
824
  var sanitizeTarget = (value) => typeof value === "string" && TARGETS.has(value) ? value : null;
689
825
 
690
- // shared/render/inline.mjs
691
- var DROP_WITH_CONTENT = /* @__PURE__ */ new Set([
692
- "script",
693
- "style",
694
- "textarea",
695
- "title",
696
- "xmp",
697
- "noscript",
698
- "noembed",
699
- "noframes",
700
- "template",
701
- "iframe",
702
- "object",
703
- "embed",
704
- "svg",
705
- "math",
706
- "select",
707
- "option",
708
- "plaintext"
826
+ // shared/inline-format.mjs
827
+ var TOKEN_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;
828
+ var COLOR_ATTRIBUTE = "data-mex-color";
829
+ var HIGHLIGHT_ATTRIBUTE = "data-mex-highlight";
830
+ var PALETTE_LIMITS = Object.freeze({ tokens: 24, label: 60, locales: 20 });
831
+ var DEFAULT_SURFACE = Object.freeze({
832
+ background: Object.freeze({ light: "#ffffff", dark: "#121212" }),
833
+ text: Object.freeze({ light: "#1f1f1f", dark: "#f2f2f2" })
834
+ });
835
+ var colorClass = (token) => `mex-color-${token}`;
836
+ var highlightClass = (token) => `mex-highlight-${token}`;
837
+
838
+ // shared/blocks/define.mjs
839
+ var BLOCK_FIELD_TYPES = Object.freeze([
840
+ "text",
841
+ "inline",
842
+ "url",
843
+ "enum",
844
+ "number",
845
+ "boolean",
846
+ "array",
847
+ "object"
709
848
  ]);
710
- var ALLOWED = new Set(INLINE_TAGS);
711
- var VOID = /* @__PURE__ */ new Set(["br"]);
712
- var MAX_INPUT = 5e5;
713
- var MAX_NODES = 5e4;
714
- var MAX_DEPTH = 64;
715
- var NAMED_ENTITIES = Object.freeze({
716
- amp: "&",
717
- lt: "<",
718
- gt: ">",
719
- quot: '"',
720
- apos: "'",
721
- nbsp: "\xA0",
722
- shy: "\xAD",
723
- copy: "\xA9",
724
- reg: "\xAE",
725
- trade: "\u2122",
726
- hellip: "\u2026",
727
- mdash: "\u2014",
728
- ndash: "\u2013",
729
- lsquo: "\u2018",
730
- rsquo: "\u2019",
731
- ldquo: "\u201C",
732
- rdquo: "\u201D",
733
- laquo: "\xAB",
734
- raquo: "\xBB",
735
- euro: "\u20AC",
736
- middot: "\xB7",
737
- bull: "\u2022",
738
- times: "\xD7",
739
- deg: "\xB0",
740
- tab: " ",
741
- newline: "\n",
742
- colon: ":",
743
- sol: "/",
744
- lpar: "(",
745
- rpar: ")"
849
+ var BLOCK_LIMITS = Object.freeze({
850
+ /** Fields per object (also the schema root). */
851
+ maxFields: 50,
852
+ /** Nesting of arrays and objects below the root. */
853
+ maxDepth: 4,
854
+ /** Largest `max` of a text or inline field. */
855
+ maxText: 1e5,
856
+ /** Default `max` of a text field. */
857
+ defaultText: 1e3,
858
+ /** Default `max` of an inline HTML field. */
859
+ defaultInline: 1e4,
860
+ /** Largest `max` of an array field. */
861
+ maxItems: 500,
862
+ /** Default `max` of an array field. */
863
+ defaultItems: 50,
864
+ /** Values of an enum field. */
865
+ maxEnumValues: 100,
866
+ /** Values cleaned per block; later array items are dropped. */
867
+ maxValues: 2e4,
868
+ /** Length of a URL value. */
869
+ maxUrl: 2048
746
870
  });
747
- var decodeEntities = (text) => String(text).replace(
748
- /&(#[xX][0-9a-fA-F]{1,8}|#[0-9]{1,10}|[A-Za-z][A-Za-z0-9]{1,31});?/g,
749
- (match, body) => {
750
- if (body[0] === "#") {
751
- const code = body[1] === "x" || body[1] === "X" ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
752
- if (!Number.isFinite(code) || code <= 0 || code > 1114111 || code >= 55296 && code <= 57343)
753
- return "\uFFFD";
754
- return String.fromCodePoint(code);
755
- }
756
- const named = NAMED_ENTITIES[body] ?? NAMED_ENTITIES[body.toLowerCase()];
757
- return named === void 0 ? match : named;
758
- }
759
- );
760
- var parseAttributes = (source) => {
761
- const out = {};
762
- const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
763
- let match;
764
- while (match = pattern.exec(source)) {
765
- const name = match[1].toLowerCase();
766
- if (Object.prototype.hasOwnProperty.call(out, name)) continue;
767
- const raw = match[2] ?? match[3] ?? match[4] ?? "";
768
- out[name] = decodeEntities(raw);
769
- }
770
- return out;
871
+ var BLOCK_PRESETS = Object.freeze(["article", "basic", "minimal"]);
872
+ var RESERVED_BLOCK_NAMES = Object.freeze([
873
+ "paragraph",
874
+ "header",
875
+ "list",
876
+ "checklist",
877
+ "quote",
878
+ "warning",
879
+ "alert",
880
+ "toggle",
881
+ "code",
882
+ "codeFlask",
883
+ "delimiter",
884
+ "toc",
885
+ "synced",
886
+ "table",
887
+ "embed",
888
+ "raw",
889
+ "image",
890
+ "simpleImage",
891
+ "gallery",
892
+ "video",
893
+ "audio",
894
+ "linkTool",
895
+ "attaches",
896
+ "personality",
897
+ "button",
898
+ "mediaLib",
899
+ "embeddedEntry",
900
+ "bold",
901
+ "italic",
902
+ "hyperlink",
903
+ "mention",
904
+ "marker",
905
+ "underline",
906
+ "strikethrough",
907
+ "inlineCode",
908
+ "tooltip",
909
+ "aiAssistant",
910
+ "alignmentTune",
911
+ "textVariant",
912
+ "indentTune"
913
+ ]);
914
+ var SDK_COMPATIBLE_NAMES = Object.freeze(["math"]);
915
+ var RESERVED = new Set(RESERVED_BLOCK_NAMES.map((name) => name.toLowerCase()));
916
+ var BLOCK_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{1,49}$/;
917
+ var KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
918
+ var FORBIDDEN_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
919
+ var DEFINITION_KEYS = /* @__PURE__ */ new Set([
920
+ "name",
921
+ "version",
922
+ "title",
923
+ "description",
924
+ "schema",
925
+ "sanitize",
926
+ "text",
927
+ "markdown",
928
+ "render",
929
+ "presets"
930
+ ]);
931
+ var FIELD_KEYS = {
932
+ text: ["max", "multiline", "default"],
933
+ inline: ["max", "default"],
934
+ url: ["schemes", "relative"],
935
+ enum: ["values", "default"],
936
+ number: ["min", "max", "integer", "default"],
937
+ boolean: ["default"],
938
+ array: ["items", "max"],
939
+ object: ["fields"]
771
940
  };
772
- var findTagEnd = (html, from) => {
773
- let quote = "";
774
- for (let i = from; i < html.length; i += 1) {
775
- const char = html[i];
776
- if (quote) {
777
- if (char === quote) quote = "";
778
- } else if (char === '"' || char === "'") quote = char;
779
- else if (char === ">") return i;
941
+ var BlockDefinitionError = class extends Error {
942
+ /**
943
+ * @param {string} message - Message naming the definition and the problem.
944
+ * @param {string} [code] - `INVALID_DEFINITION` | `RESERVED_NAME` | `NAME_TAKEN` | `REGISTRY_SEALED`.
945
+ */
946
+ constructor(message, code = "INVALID_DEFINITION") {
947
+ super(message);
948
+ this.name = "BlockDefinitionError";
949
+ this.code = code;
780
950
  }
781
- return -1;
782
951
  };
783
- var cleanAttributes = (tag, attribs) => {
784
- const allowed = INLINE_ATTRIBUTES[tag] || [];
785
- const out = {};
786
- for (const name of allowed) {
787
- if (!Object.prototype.hasOwnProperty.call(attribs, name) || name.startsWith("data-mex-")) continue;
788
- const value = attribs[name];
789
- if (name === "href") {
790
- const url = sanitizeUrl(value);
791
- if (url) out.href = url;
792
- } else if (name === "target") {
793
- const target = sanitizeTarget(value);
794
- if (target) out.target = target;
795
- } else if (name === "rel") {
796
- const rel = String(value).split(/\s+/).filter((token) => /^[a-z-]{1,20}$/.test(token));
797
- if (rel.length) out.rel = rel.join(" ");
798
- } else if (name === "class") {
799
- const classes2 = String(value).split(/\s+/).filter((token) => (INLINE_CLASSES[tag] || []).includes(token));
800
- if (classes2.length) out.class = classes2.join(" ");
801
- } else {
802
- out[name] = String(value).slice(0, 2e3);
803
- }
804
- }
805
- if (tag === "a") Object.assign(out, cleanInternalLinkAttributes(attribs));
806
- return out;
952
+ var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
953
+ var fail = (where, message) => {
954
+ throw new BlockDefinitionError(`Magic Editor X block ${where}: ${message}`);
807
955
  };
808
- var parseInline = (input) => {
809
- const html = typeof input === "string" ? input.slice(0, MAX_INPUT) : "";
810
- const root = { type: "element", tag: "#root", attrs: {}, children: [] };
811
- const stack = [root];
812
- let nodes = 0;
813
- let text = "";
814
- const flush = () => {
815
- if (!text) return;
816
- const parent = stack[stack.length - 1];
817
- const last = parent.children[parent.children.length - 1];
818
- const value = decodeEntities(text);
819
- if (last && last.type === "text") last.value += value;
820
- else if (nodes < MAX_NODES) {
821
- parent.children.push({ type: "text", value });
822
- nodes += 1;
823
- }
824
- text = "";
825
- };
826
- let i = 0;
827
- while (i < html.length) {
828
- const lt = html.indexOf("<", i);
829
- if (lt === -1) {
830
- text += html.slice(i);
956
+ var boundedInt = (value, min, max, fallback, where, key) => {
957
+ if (value === void 0) return fallback;
958
+ if (!Number.isInteger(value) || value < min || value > max)
959
+ fail(where, `"${key}" must be an integer from ${min} to ${max}`);
960
+ return value;
961
+ };
962
+ var normalizeField = (input, where, depth) => {
963
+ if (!isObject2(input)) fail(where, 'a field must be an object with a "type"');
964
+ const type = input.type;
965
+ if (!BLOCK_FIELD_TYPES.includes(type)) fail(where, `unknown field type ${JSON.stringify(type)}`);
966
+ for (const key of Object.keys(input))
967
+ if (key !== "type" && key !== "label" && !FIELD_KEYS[type].includes(key))
968
+ fail(where, `unknown option "${key}" for a ${type} field`);
969
+ const out = { type };
970
+ if (input.label !== void 0) {
971
+ if (typeof input.label !== "string" || input.label.length > 100)
972
+ fail(where, '"label" must be a string of at most 100 characters');
973
+ out.label = input.label;
974
+ }
975
+ switch (type) {
976
+ case "text":
977
+ case "inline": {
978
+ out.max = boundedInt(
979
+ input.max,
980
+ 1,
981
+ BLOCK_LIMITS.maxText,
982
+ type === "text" ? BLOCK_LIMITS.defaultText : BLOCK_LIMITS.defaultInline,
983
+ where,
984
+ "max"
985
+ );
986
+ if (input.default !== void 0 && typeof input.default !== "string")
987
+ fail(where, '"default" must be a string');
988
+ out.default = (input.default || "").slice(0, out.max);
989
+ if (type === "text") {
990
+ if (input.multiline !== void 0 && typeof input.multiline !== "boolean")
991
+ fail(where, '"multiline" must be a boolean');
992
+ out.multiline = input.multiline === true;
993
+ }
831
994
  break;
832
995
  }
833
- text += html.slice(i, lt);
834
- i = lt;
835
- if (html.startsWith("<!--", i)) {
836
- const end2 = html.indexOf("-->", i + 4);
837
- flush();
838
- i = end2 === -1 ? html.length : end2 + 3;
839
- continue;
840
- }
841
- if (html.startsWith("<![CDATA[", i)) {
842
- const end2 = html.indexOf("]]>", i + 9);
843
- flush();
844
- i = end2 === -1 ? html.length : end2 + 3;
845
- continue;
846
- }
847
- if (html[i + 1] === "!" || html[i + 1] === "?") {
848
- const end2 = html.indexOf(">", i + 2);
849
- flush();
850
- i = end2 === -1 ? html.length : end2 + 1;
851
- continue;
852
- }
853
- const closing = html[i + 1] === "/";
854
- const nameMatch = /^[A-Za-z][A-Za-z0-9-]{0,40}/.exec(html.slice(i + (closing ? 2 : 1), i + 45));
855
- if (!nameMatch) {
856
- text += "<";
857
- i += 1;
858
- continue;
996
+ case "url": {
997
+ const schemes = input.schemes === void 0 ? ["http", "https"] : input.schemes;
998
+ if (!Array.isArray(schemes) || !schemes.length || schemes.some((scheme) => !LINK_SCHEMES.includes(scheme)))
999
+ fail(where, `"schemes" must be a non-empty list of ${LINK_SCHEMES.join(", ")}`);
1000
+ if (input.relative !== void 0 && typeof input.relative !== "boolean")
1001
+ fail(where, '"relative" must be a boolean');
1002
+ out.schemes = Object.freeze([...new Set(schemes)]);
1003
+ out.relative = input.relative !== false;
1004
+ break;
859
1005
  }
860
- const end = findTagEnd(html, i + 1);
861
- if (end === -1) {
862
- text += html.slice(i);
1006
+ case "enum": {
1007
+ const values = input.values;
1008
+ if (!Array.isArray(values) || values.length < 1 || values.length > BLOCK_LIMITS.maxEnumValues || values.some((value) => typeof value !== "string" || value.length < 1 || value.length > 100) || new Set(values).size !== values.length)
1009
+ fail(
1010
+ where,
1011
+ `"values" must be 1 to ${BLOCK_LIMITS.maxEnumValues} distinct strings (1-100 characters)`
1012
+ );
1013
+ out.values = Object.freeze([...values]);
1014
+ if (input.default !== void 0 && !values.includes(input.default))
1015
+ fail(where, '"default" must be one of "values"');
1016
+ out.default = input.default === void 0 ? values[0] : input.default;
863
1017
  break;
864
1018
  }
865
- flush();
866
- const tag = nameMatch[0].toLowerCase();
867
- const body = html.slice(i + (closing ? 2 : 1) + nameMatch[0].length, end);
868
- i = end + 1;
869
- if (closing) {
870
- if (!ALLOWED.has(tag)) continue;
871
- for (let s = stack.length - 1; s > 0; s -= 1) {
872
- if (stack[s].tag === tag) {
873
- stack.length = s;
874
- break;
875
- }
1019
+ case "number": {
1020
+ for (const key of ["min", "max", "default"])
1021
+ if (input[key] !== void 0 && (typeof input[key] !== "number" || !Number.isFinite(input[key])))
1022
+ fail(where, `"${key}" must be a finite number`);
1023
+ if (input.integer !== void 0 && typeof input.integer !== "boolean")
1024
+ fail(where, '"integer" must be a boolean');
1025
+ out.integer = input.integer === true;
1026
+ out.min = input.min === void 0 ? -Number.MAX_SAFE_INTEGER : input.min;
1027
+ out.max = input.max === void 0 ? Number.MAX_SAFE_INTEGER : input.max;
1028
+ if (out.min > out.max) fail(where, '"min" must not be greater than "max"');
1029
+ if (input.default !== void 0) {
1030
+ if (input.default < out.min || input.default > out.max || out.integer && !Number.isInteger(input.default))
1031
+ fail(where, '"default" must be a valid value of the field');
1032
+ out.default = input.default;
876
1033
  }
877
- continue;
878
- }
879
- if (DROP_WITH_CONTENT.has(tag)) {
880
- const selfClosing = /\/\s*$/.test(body);
881
- if (selfClosing) continue;
882
- const closeIndex = html.slice(i).search(new RegExp(`</${tag}[\\s/>]`, "i"));
883
- if (closeIndex === -1) break;
884
- const closeEnd = html.indexOf(">", i + closeIndex);
885
- i = closeEnd === -1 ? html.length : closeEnd + 1;
886
- continue;
1034
+ break;
887
1035
  }
888
- if (!ALLOWED.has(tag) || nodes >= MAX_NODES) continue;
889
- const element = {
890
- type: "element",
891
- tag,
892
- attrs: cleanAttributes(tag, parseAttributes(body)),
893
- children: []
894
- };
895
- stack[stack.length - 1].children.push(element);
896
- nodes += 1;
897
- if (!VOID.has(tag) && stack.length < MAX_DEPTH) stack.push(element);
1036
+ case "boolean":
1037
+ if (input.default !== void 0 && typeof input.default !== "boolean")
1038
+ fail(where, '"default" must be a boolean');
1039
+ out.default = input.default === true;
1040
+ break;
1041
+ case "array":
1042
+ if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1043
+ out.max = boundedInt(input.max, 1, BLOCK_LIMITS.maxItems, BLOCK_LIMITS.defaultItems, where, "max");
1044
+ out.items = normalizeField(input.items, `${where}[]`, depth + 1);
1045
+ break;
1046
+ case "object":
1047
+ if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1048
+ out.fields = normalizeFields(input.fields, where, depth + 1);
1049
+ break;
1050
+ default:
1051
+ break;
898
1052
  }
899
- flush();
900
- return root.children;
1053
+ return Object.freeze(out);
901
1054
  };
902
- var resolveLinkAttributes = (attrs, resolver) => {
903
- if (typeof resolver !== "function" || !attrs["data-mex-uid"] || !attrs["data-mex-document-id"])
904
- return attrs;
905
- let result;
906
- try {
907
- result = resolver({
908
- uid: attrs["data-mex-uid"],
909
- documentId: attrs["data-mex-document-id"],
910
- locale: attrs["data-mex-locale"] || null,
911
- href: attrs.href || null,
912
- ...isMentionLink(attrs) ? { mention: true } : {}
913
- });
914
- } catch {
915
- result = void 0;
916
- }
917
- if (result === false) return null;
918
- if (typeof result === "string") {
919
- const url = sanitizeUrl(result);
920
- if (url) return { ...attrs, href: url };
1055
+ var normalizeFields = (input, where, depth) => {
1056
+ if (!isObject2(input)) fail(where, '"fields" must be an object of field descriptors');
1057
+ const keys = Object.keys(input);
1058
+ if (keys.length < 1 || keys.length > BLOCK_LIMITS.maxFields)
1059
+ fail(where, `an object needs 1 to ${BLOCK_LIMITS.maxFields} fields`);
1060
+ const out = /* @__PURE__ */ Object.create(null);
1061
+ for (const key of keys) {
1062
+ if (!KEY_PATTERN.test(key) || FORBIDDEN_KEYS2.has(key))
1063
+ fail(where, `field name ${JSON.stringify(key)} must match ${KEY_PATTERN}`);
1064
+ out[key] = normalizeField(input[key], `${where}.${key}`, depth);
921
1065
  }
922
- return attrs;
1066
+ return Object.freeze(out);
923
1067
  };
924
- var ATTRIBUTE_ORDER = [
925
- "href",
926
- "target",
927
- "rel",
928
- "title",
929
- "class",
930
- "data-tooltip",
931
- "data-mex-uid",
932
- "data-mex-document-id",
933
- "data-mex-locale",
934
- "data-mex-mention"
935
- ];
936
- var MENTION_CLASS = "mex-mention";
937
- var inlineNodesToRender = (nodes, options = {}) => {
938
- const out = [];
939
- for (const node of nodes) {
940
- if (node.type === "text") {
941
- out.push({ type: "text", value: node.value });
942
- continue;
943
- }
944
- if (node.tag === "br") {
945
- out.push({ type: "element", tag: "br", attrs: {}, children: [] });
946
- continue;
947
- }
948
- let attrs = node.attrs;
949
- if (node.tag === "a") {
950
- attrs = resolveLinkAttributes(attrs, options.links);
951
- if (!attrs || !attrs.href) {
952
- out.push(...inlineNodesToRender(node.children, options));
953
- continue;
954
- }
955
- if (attrs.target === "_blank") {
956
- const rel = new Set(
957
- String(attrs.rel || "").split(/\s+/).filter(Boolean)
958
- );
959
- rel.add("noopener");
960
- rel.add("noreferrer");
961
- attrs = { ...attrs, rel: Array.from(rel).sort().join(" ") };
962
- }
963
- if (!options.storage && isMentionLink(attrs)) attrs = { ...attrs, class: MENTION_CLASS };
964
- }
965
- const ordered = {};
966
- for (const name of ATTRIBUTE_ORDER) {
967
- if (attrs[name] !== void 0 && attrs[name] !== "") ordered[name] = String(attrs[name]);
968
- }
969
- out.push({
970
- type: "element",
971
- tag: node.tag,
972
- attrs: ordered,
973
- children: inlineNodesToRender(node.children, options)
974
- });
975
- }
976
- return out;
1068
+ var blockNameProblem = (name) => {
1069
+ if (typeof name !== "string" || !BLOCK_NAME_PATTERN.test(name))
1070
+ return `the name must match ${BLOCK_NAME_PATTERN}`;
1071
+ if (RESERVED.has(name.toLowerCase())) return `"${name}" is a built-in tool name`;
1072
+ return null;
1073
+ };
1074
+ var defineBlock = (definition) => {
1075
+ if (!isObject2(definition))
1076
+ throw new BlockDefinitionError("Magic Editor X block: the definition must be an object");
1077
+ const label3 = typeof definition.name === "string" ? `"${definition.name.slice(0, 50)}"` : "(no name)";
1078
+ for (const key of Object.keys(definition))
1079
+ if (!DEFINITION_KEYS.has(key)) fail(label3, `unknown key "${key}"`);
1080
+ const problem = blockNameProblem(definition.name);
1081
+ if (problem)
1082
+ throw new BlockDefinitionError(
1083
+ `Magic Editor X block ${label3}: ${problem}`,
1084
+ problem.includes("built-in") ? "RESERVED_NAME" : "INVALID_DEFINITION"
1085
+ );
1086
+ const out = {
1087
+ name: definition.name,
1088
+ version: boundedInt(definition.version, 1, 1e6, 1, label3, "version")
1089
+ };
1090
+ for (const [key, max] of [
1091
+ ["title", 100],
1092
+ ["description", 500]
1093
+ ]) {
1094
+ if (definition[key] === void 0) continue;
1095
+ if (typeof definition[key] !== "string" || definition[key].length > max)
1096
+ fail(label3, `"${key}" must be a string of at most ${max} characters`);
1097
+ out[key] = definition[key];
1098
+ }
1099
+ out.schema = normalizeFields(definition.schema, `${label3} schema`, 0);
1100
+ for (const key of ["sanitize", "text", "markdown", "render"]) {
1101
+ if (definition[key] === void 0) continue;
1102
+ if (typeof definition[key] !== "function") fail(label3, `"${key}" must be a function`);
1103
+ out[key] = definition[key];
1104
+ }
1105
+ const presets = definition.presets === void 0 ? [] : definition.presets;
1106
+ if (!Array.isArray(presets) || presets.some((preset) => !BLOCK_PRESETS.includes(preset)))
1107
+ fail(label3, `"presets" must list some of ${BLOCK_PRESETS.join(", ")}`);
1108
+ out.presets = Object.freeze([...new Set(presets)]);
1109
+ return Object.freeze(out);
1110
+ };
1111
+ var cleanValue = (field, value, inline, budget) => {
1112
+ budget.left -= 1;
1113
+ switch (field.type) {
1114
+ case "text":
1115
+ return typeof value === "string" ? value.slice(0, field.max) : field.default;
1116
+ case "inline":
1117
+ return inline(typeof value === "string" ? value.slice(0, field.max) : field.default);
1118
+ case "url":
1119
+ return typeof value === "string" ? sanitizeUrl(value.slice(0, BLOCK_LIMITS.maxUrl), {
1120
+ schemes: field.schemes,
1121
+ allowRelative: field.relative
1122
+ }) : "";
1123
+ case "enum":
1124
+ return typeof value === "string" && field.values.includes(value) ? value : field.default;
1125
+ case "number":
1126
+ return typeof value === "number" && Number.isFinite(value) && value >= field.min && value <= field.max && (!field.integer || Number.isInteger(value)) ? value : field.default;
1127
+ case "boolean":
1128
+ return typeof value === "boolean" ? value : field.default;
1129
+ case "array": {
1130
+ const out = [];
1131
+ if (!Array.isArray(value)) return out;
1132
+ for (const item of value) {
1133
+ if (out.length >= field.max || budget.left <= 0) break;
1134
+ if (!matchesType(field.items, item)) continue;
1135
+ const clean2 = cleanValue(field.items, item, inline, budget);
1136
+ if (clean2 !== void 0) out.push(clean2);
1137
+ }
1138
+ return out;
1139
+ }
1140
+ case "object":
1141
+ return cleanObject(field.fields, isObject2(value) ? value : {}, inline, budget);
1142
+ default:
1143
+ return void 0;
1144
+ }
1145
+ };
1146
+ var matchesType = (field, item) => {
1147
+ switch (field.type) {
1148
+ case "text":
1149
+ case "inline":
1150
+ case "url":
1151
+ case "enum":
1152
+ return typeof item === "string";
1153
+ case "number":
1154
+ return typeof item === "number";
1155
+ case "boolean":
1156
+ return typeof item === "boolean";
1157
+ case "array":
1158
+ return Array.isArray(item);
1159
+ default:
1160
+ return isObject2(item);
1161
+ }
1162
+ };
1163
+ var cleanObject = (fields, value, inline, budget) => {
1164
+ const out = {};
1165
+ for (const key of Object.keys(fields)) {
1166
+ const own = Object.prototype.hasOwnProperty.call(value, key) ? value[key] : void 0;
1167
+ const clean2 = cleanValue(fields[key], own, inline, budget);
1168
+ if (clean2 !== void 0) out[key] = clean2;
1169
+ }
1170
+ return out;
1171
+ };
1172
+ var eachLeaf = (fields, data, visit) => {
1173
+ const walk = (field, value, path, depth) => {
1174
+ if (depth > BLOCK_LIMITS.maxDepth + 1) return;
1175
+ if (field.type === "array") {
1176
+ if (!Array.isArray(value)) return;
1177
+ value.slice(0, field.max).forEach((item, index) => walk(field.items, item, [...path, index], depth + 1));
1178
+ } else if (field.type === "object") {
1179
+ if (!isObject2(value)) return;
1180
+ for (const key of Object.keys(field.fields))
1181
+ if (Object.prototype.hasOwnProperty.call(value, key))
1182
+ walk(field.fields[key], value[key], [...path, key], depth + 1);
1183
+ } else visit(field, value, path);
1184
+ };
1185
+ if (!isObject2(data)) return;
1186
+ for (const key of Object.keys(fields))
1187
+ if (Object.prototype.hasOwnProperty.call(data, key)) walk(fields[key], data[key], [key], 0);
1188
+ };
1189
+ var fieldAt = (fields, path) => {
1190
+ let current = { type: "object", fields };
1191
+ for (const part of String(path).split(".")) {
1192
+ if (!part) continue;
1193
+ if (current.type === "array") {
1194
+ if (/^\d+$/.test(part)) {
1195
+ current = current.items;
1196
+ continue;
1197
+ }
1198
+ return null;
1199
+ }
1200
+ if (current.type !== "object" || !Object.prototype.hasOwnProperty.call(current.fields, part)) return null;
1201
+ current = current.fields[part];
1202
+ }
1203
+ return current;
1204
+ };
1205
+ var compiled = /* @__PURE__ */ new WeakMap();
1206
+ var compileBlock = (definition) => {
1207
+ if (definition && typeof definition === "object" && compiled.has(definition))
1208
+ return compiled.get(definition);
1209
+ const def = defineBlock(definition && typeof definition === "object" ? { ...definition } : definition);
1210
+ const schema = def.schema;
1211
+ const run = (data, inline) => cleanObject(schema, isObject2(data) ? data : {}, inline, { left: BLOCK_LIMITS.maxValues });
1212
+ const result = Object.freeze({
1213
+ ...def,
1214
+ /**
1215
+ * Cleans untrusted block data (unknown keys dropped, values bounded).
1216
+ * The optional `sanitize` hook runs on the clean data; its result is
1217
+ * cleaned again, so it cannot add keys or unsafe values. A hook that
1218
+ * throws is ignored (the clean data is used).
1219
+ * @param {unknown} data - Block data.
1220
+ * @param {(html: string) => string} inline - Inline HTML sanitiser of the caller.
1221
+ * @returns {object} Clean data.
1222
+ */
1223
+ clean: (data, inline) => {
1224
+ const first = run(data, inline);
1225
+ if (!def.sanitize) return first;
1226
+ let next;
1227
+ try {
1228
+ next = def.sanitize(copyData(first), { sanitizeUrl });
1229
+ } catch {
1230
+ return first;
1231
+ }
1232
+ return isObject2(next) ? run(next, inline) : first;
1233
+ },
1234
+ /**
1235
+ * Text fields of the data in schema order: `{ path, kind, value }`
1236
+ * (`html` for inline fields, `plain` for text fields).
1237
+ * @param {unknown} data - Block data.
1238
+ * @returns {Array<{ path: Array<string|number>, kind: 'html'|'plain', value: string }>} Fields.
1239
+ */
1240
+ fields: (data) => {
1241
+ const out = [];
1242
+ eachLeaf(schema, data, (field, value, path) => {
1243
+ if (typeof value !== "string") return;
1244
+ if (field.type === "inline") out.push({ path, kind: "html", value });
1245
+ else if (field.type === "text") out.push({ path, kind: "plain", value });
1246
+ });
1247
+ return out;
1248
+ },
1249
+ /**
1250
+ * Non-empty URL values: `{ path, value }`.
1251
+ * @param {unknown} data - Block data.
1252
+ * @returns {Array<{ path: Array<string|number>, value: string }>} URLs.
1253
+ */
1254
+ urls: (data) => {
1255
+ const out = [];
1256
+ eachLeaf(schema, data, (field, value, path) => {
1257
+ if (field.type === "url" && typeof value === "string" && value) out.push({ path, value });
1258
+ });
1259
+ return out;
1260
+ },
1261
+ /**
1262
+ * Kind of the value at a dotted path, for the version diff.
1263
+ * @param {string} path - Dotted path.
1264
+ * @returns {'inline'|'plain'|'value'} Kind.
1265
+ */
1266
+ kindOf: (path) => {
1267
+ const field = fieldAt(schema, path);
1268
+ if (!field) return "value";
1269
+ if (field.type === "inline") return "inline";
1270
+ if (field.type === "text") return "plain";
1271
+ return "value";
1272
+ }
1273
+ });
1274
+ compiled.set(result, result);
1275
+ if (definition && typeof definition === "object") compiled.set(definition, result);
1276
+ return result;
1277
+ };
1278
+ var copyData = (value) => {
1279
+ if (Array.isArray(value)) return value.map(copyData);
1280
+ if (isObject2(value)) {
1281
+ const out = {};
1282
+ for (const [key, child] of Object.entries(value)) out[key] = copyData(child);
1283
+ return out;
1284
+ }
1285
+ return value;
1286
+ };
1287
+ var listCache = /* @__PURE__ */ new WeakMap();
1288
+ var compileBlockList = (list) => {
1289
+ if (!Array.isArray(list)) return /* @__PURE__ */ new Map();
1290
+ if (listCache.has(list)) return listCache.get(list);
1291
+ const map = /* @__PURE__ */ new Map();
1292
+ for (const definition of list) {
1293
+ const def = compileBlock(definition);
1294
+ map.set(def.name, def);
1295
+ }
1296
+ listCache.set(list, map);
1297
+ return map;
977
1298
  };
978
- var inlineToNodes = (html, options) => inlineNodesToRender(parseInline(html), options);
979
- var nodesToHtml = (nodes, options = {}) => serializeNodes(inlineNodesToRender(nodes, options));
980
- var nodesToText = (nodes) => nodes.map((node) => {
981
- if (node.type === "text") return node.value;
982
- if (node.tag === "br") return "\n";
983
- return nodesToText(node.children);
984
- }).join("");
985
- var inlineToHtml = (html, options) => nodesToHtml(parseInline(html), options);
986
- var inlineToText = (html) => nodesToText(parseInline(html)).replace(/\u00a0/g, " ");
987
1299
 
988
- // shared/blocks/define.mjs
989
- var BLOCK_FIELD_TYPES = Object.freeze([
990
- "text",
991
- "inline",
992
- "url",
993
- "enum",
994
- "number",
995
- "boolean",
996
- "array",
997
- "object"
998
- ]);
999
- var BLOCK_LIMITS = Object.freeze({
1000
- /** Fields per object (also the schema root). */
1001
- maxFields: 50,
1002
- /** Nesting of arrays and objects below the root. */
1003
- maxDepth: 4,
1004
- /** Largest `max` of a text or inline field. */
1005
- maxText: 1e5,
1006
- /** Default `max` of a text field. */
1007
- defaultText: 1e3,
1008
- /** Default `max` of an inline HTML field. */
1009
- defaultInline: 1e4,
1010
- /** Largest `max` of an array field. */
1011
- maxItems: 500,
1012
- /** Default `max` of an array field. */
1013
- defaultItems: 50,
1014
- /** Values of an enum field. */
1015
- maxEnumValues: 100,
1016
- /** Values cleaned per block; later array items are dropped. */
1017
- maxValues: 2e4,
1018
- /** Length of a URL value. */
1019
- maxUrl: 2048
1300
+ // shared/blocks/annotations.mjs
1301
+ var ANNOTATION_ATTRIBUTE = "data-mex-annotation";
1302
+ var ANNOTATION_VALUE_PREFIX = "data-mex-a-";
1303
+ var ANNOTATION_NAME = /^[a-z][a-z0-9-]{1,39}$/;
1304
+ var ANNOTATION_KEY = /^[a-z][a-z0-9]{0,23}$/;
1305
+ var ANNOTATION_FIELD_TYPES = Object.freeze(["text", "enum", "url"]);
1306
+ var ANNOTATION_LIMITS = Object.freeze({
1307
+ attributes: 8,
1308
+ text: 1e3,
1309
+ textDefault: 200,
1310
+ values: 50,
1311
+ registered: 50,
1312
+ label: 100,
1313
+ resolveItems: 200
1020
1314
  });
1021
- var BLOCK_PRESETS = Object.freeze(["article", "basic", "minimal"]);
1022
- var RESERVED_BLOCK_NAMES = Object.freeze([
1023
- "paragraph",
1024
- "header",
1025
- "list",
1026
- "checklist",
1027
- "quote",
1028
- "warning",
1029
- "alert",
1030
- "toggle",
1031
- "code",
1032
- "codeFlask",
1033
- "delimiter",
1034
- "toc",
1035
- "synced",
1036
- "table",
1037
- "embed",
1038
- "raw",
1039
- "image",
1040
- "simpleImage",
1041
- "gallery",
1042
- "video",
1043
- "audio",
1044
- "linkTool",
1045
- "attaches",
1046
- "personality",
1047
- "button",
1048
- "mediaLib",
1049
- "embeddedEntry",
1050
- "bold",
1051
- "italic",
1052
- "hyperlink",
1053
- "mention",
1054
- "marker",
1055
- "underline",
1056
- "strikethrough",
1057
- "inlineCode",
1058
- "tooltip",
1059
- "aiAssistant",
1060
- "alignmentTune",
1061
- "textVariant",
1062
- "indentTune"
1315
+ var ANNOTATION_PRESETS = Object.freeze(["full", "article", "basic", "minimal"]);
1316
+ var ANNOTATION_RENDER_TAGS = Object.freeze([
1317
+ "abbr",
1318
+ "dfn",
1319
+ "span",
1320
+ "a",
1321
+ "mark",
1322
+ "cite",
1323
+ "q",
1324
+ "small",
1325
+ "em",
1326
+ "strong",
1327
+ "b",
1328
+ "i",
1329
+ "u",
1330
+ "s",
1331
+ "time",
1332
+ "data",
1333
+ "bdi",
1334
+ "kbd",
1335
+ "var",
1336
+ "ins",
1337
+ "del"
1063
1338
  ]);
1064
- var RESERVED = new Set(RESERVED_BLOCK_NAMES.map((name) => name.toLowerCase()));
1065
- var BLOCK_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{1,49}$/;
1066
- var KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
1067
- var FORBIDDEN_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1068
- var DEFINITION_KEYS = /* @__PURE__ */ new Set([
1069
- "name",
1070
- "version",
1339
+ var ANNOTATION_SHORTCUTS = Object.freeze(["CMD+SHIFT+0", "CMD+SHIFT+1", "CMD+SHIFT+8"]);
1340
+ var ABBREVIATION = "abbreviation";
1341
+ var isObject3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1342
+ var fail2 = (name, message, code = "INVALID_DEFINITION") => {
1343
+ throw new BlockDefinitionError(`Magic Editor X inline annotation ${name}: ${message}`, code);
1344
+ };
1345
+ var defined = /* @__PURE__ */ new WeakSet();
1346
+ var cleanText = (value, max) => typeof value === "string" ? value.trim().slice(0, max).trim() : "";
1347
+ var normalizeAttribute = (where, input) => {
1348
+ if (!isObject3(input)) fail2(where, 'an attribute must be an object with a "type"');
1349
+ const { type } = input;
1350
+ if (!ANNOTATION_FIELD_TYPES.includes(type)) fail2(where, `unknown attribute type ${JSON.stringify(type)}`);
1351
+ const allowed = { text: ["max"], enum: ["values"], url: ["schemes", "relative"] }[type];
1352
+ for (const key of Object.keys(input))
1353
+ if (!["type", "label", "required", ...allowed].includes(key))
1354
+ fail2(where, `unknown option "${key}" for a ${type} attribute`);
1355
+ const out = { type, required: input.required === true };
1356
+ if (input.label !== void 0) {
1357
+ if (typeof input.label !== "string" || input.label.length > ANNOTATION_LIMITS.label)
1358
+ fail2(where, `"label" must be a string of at most ${ANNOTATION_LIMITS.label} characters`);
1359
+ out.label = input.label;
1360
+ }
1361
+ if (input.required !== void 0 && typeof input.required !== "boolean")
1362
+ fail2(where, '"required" must be a boolean');
1363
+ if (type === "text") {
1364
+ const max = input.max === void 0 ? ANNOTATION_LIMITS.textDefault : input.max;
1365
+ if (!Number.isInteger(max) || max < 1 || max > ANNOTATION_LIMITS.text)
1366
+ fail2(where, `"max" must be an integer from 1 to ${ANNOTATION_LIMITS.text}`);
1367
+ out.max = max;
1368
+ } else if (type === "enum") {
1369
+ const { values } = input;
1370
+ if (!Array.isArray(values) || !values.length || values.length > ANNOTATION_LIMITS.values || !values.every((value) => typeof value === "string" && value.length >= 1 && value.length <= 100) || new Set(values).size !== values.length)
1371
+ fail2(where, `"values" must be 1 to ${ANNOTATION_LIMITS.values} distinct strings`);
1372
+ out.values = Object.freeze([...values]);
1373
+ } else {
1374
+ const schemes = input.schemes === void 0 ? ["http", "https"] : input.schemes;
1375
+ if (!Array.isArray(schemes) || !schemes.length || !schemes.every((scheme) => LINK_SCHEMES.includes(scheme)))
1376
+ fail2(where, `"schemes" must be a non-empty subset of ${LINK_SCHEMES.join(", ")}`);
1377
+ if (input.relative !== void 0 && typeof input.relative !== "boolean")
1378
+ fail2(where, '"relative" must be a boolean');
1379
+ out.schemes = Object.freeze([...new Set(schemes)]);
1380
+ out.relative = input.relative !== false;
1381
+ }
1382
+ return Object.freeze(out);
1383
+ };
1384
+ var defineInlineAnnotation = (definition) => {
1385
+ if (!isObject3(definition)) fail2("(unnamed)", "the definition must be an object");
1386
+ const { name } = definition;
1387
+ if (typeof name !== "string" || !ANNOTATION_NAME.test(name))
1388
+ fail2(JSON.stringify(name), "the name must match /^[a-z][a-z0-9-]{1,39}$/");
1389
+ for (const key of Object.keys(definition))
1390
+ if (!["name", "label", "description", "attributes", "presets", "resolve", "render", "shortcut"].includes(
1391
+ key
1392
+ ))
1393
+ fail2(name, `unknown key "${key}"`);
1394
+ for (const key of ["label", "description"])
1395
+ if (definition[key] !== void 0 && (typeof definition[key] !== "string" || definition[key].length > (key === "label" ? 100 : 500)))
1396
+ fail2(name, `"${key}" must be a short string`);
1397
+ if (!isObject3(definition.attributes)) fail2(name, '"attributes" must be an object');
1398
+ const keys = Object.keys(definition.attributes);
1399
+ if (keys.length > ANNOTATION_LIMITS.attributes)
1400
+ fail2(name, `at most ${ANNOTATION_LIMITS.attributes} attributes`);
1401
+ const attributes = {};
1402
+ for (const key of keys) {
1403
+ if (!ANNOTATION_KEY.test(key)) fail2(name, `attribute key "${key}" must match /^[a-z][a-z0-9]{0,23}$/`);
1404
+ attributes[key] = normalizeAttribute(`${name}.${key}`, definition.attributes[key]);
1405
+ }
1406
+ const presets = definition.presets === void 0 ? [] : definition.presets;
1407
+ if (!Array.isArray(presets) || !presets.every((preset) => ANNOTATION_PRESETS.includes(preset)))
1408
+ fail2(name, `"presets" must list only ${ANNOTATION_PRESETS.join(", ")}`);
1409
+ if (definition.shortcut !== void 0 && !ANNOTATION_SHORTCUTS.includes(definition.shortcut))
1410
+ fail2(name, `"shortcut" must be one of ${ANNOTATION_SHORTCUTS.join(", ")}`);
1411
+ for (const key of ["resolve", "render"])
1412
+ if (definition[key] !== void 0 && typeof definition[key] !== "function")
1413
+ fail2(name, `"${key}" must be a function`);
1414
+ const out = Object.freeze({
1415
+ name,
1416
+ label: definition.label || name,
1417
+ ...definition.description ? { description: definition.description } : {},
1418
+ attributes: Object.freeze(attributes),
1419
+ presets: Object.freeze([...new Set(presets)]),
1420
+ ...definition.shortcut ? { shortcut: definition.shortcut } : {},
1421
+ ...definition.resolve ? { resolve: definition.resolve } : {},
1422
+ ...definition.render ? { render: definition.render } : {}
1423
+ });
1424
+ defined.add(out);
1425
+ return out;
1426
+ };
1427
+ var cleanAnnotationAttributes = (definition, raw) => {
1428
+ const source = raw && typeof raw === "object" ? raw : {};
1429
+ const out = {};
1430
+ for (const [key, field] of Object.entries(definition.attributes)) {
1431
+ const value = Object.prototype.hasOwnProperty.call(source, key) ? source[key] : void 0;
1432
+ let clean2;
1433
+ if (field.type === "text") clean2 = cleanText(value, field.max);
1434
+ else if (field.type === "enum")
1435
+ clean2 = typeof value === "string" && field.values.includes(value) ? value : "";
1436
+ else clean2 = sanitizeUrl(value, { schemes: field.schemes, allowRelative: field.relative });
1437
+ if (clean2) out[key] = clean2;
1438
+ else if (field.required) return null;
1439
+ }
1440
+ return out;
1441
+ };
1442
+ var abbreviationAnnotation = defineInlineAnnotation({
1443
+ name: ABBREVIATION,
1444
+ label: "Abbreviation",
1445
+ description: "Short form with its full form (shown as a tooltip and read by screen readers).",
1446
+ attributes: { title: { type: "text", max: 200, required: true, label: "Full form" } },
1447
+ render: (annotation) => ({ tag: "abbr", attrs: { title: annotation.attrs.title } })
1448
+ });
1449
+ var registry2 = /* @__PURE__ */ new Map();
1450
+ var activeAnnotation = (name) => {
1451
+ if (name === ABBREVIATION) return abbreviationAnnotation;
1452
+ return typeof name === "string" && registry2.has(name) ? registry2.get(name) : null;
1453
+ };
1454
+ var CLASS_TOKEN = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;
1455
+ var RENDER_ATTRIBUTES = /* @__PURE__ */ new Set(["title", "class", "lang", "dir", "href", "datetime", "value", "cite"]);
1456
+ var cleanAnnotationWrapper = (out) => {
1457
+ if (!isObject3(out) || !ANNOTATION_RENDER_TAGS.includes(out.tag)) return null;
1458
+ const attrs = {};
1459
+ for (const [name, raw] of Object.entries(isObject3(out.attrs) ? out.attrs : {})) {
1460
+ if (raw === void 0 || raw === null || raw === false) continue;
1461
+ if (!["string", "number"].includes(typeof raw)) continue;
1462
+ const allowed = RENDER_ATTRIBUTES.has(name) || name === "aria-label" || name.startsWith("data-") && !name.startsWith("data-mex-");
1463
+ if (!allowed || !isSafeAttributeName(name)) continue;
1464
+ const text = String(raw).slice(0, 2e3);
1465
+ if (name === "href" || name === "cite") {
1466
+ if (out.tag !== "a" && name === "href") continue;
1467
+ const url = sanitizeUrl(text);
1468
+ if (url) attrs[name] = url;
1469
+ } else if (name === "class") {
1470
+ const classes2 = text.split(/\s+/).filter((token) => CLASS_TOKEN.test(token));
1471
+ if (classes2.length) attrs.class = classes2.join(" ");
1472
+ } else if (text) attrs[name] = text;
1473
+ }
1474
+ return { tag: out.tag, attrs };
1475
+ };
1476
+
1477
+ // shared/render/inline.mjs
1478
+ var DROP_WITH_CONTENT = /* @__PURE__ */ new Set([
1479
+ "script",
1480
+ "style",
1481
+ "textarea",
1071
1482
  "title",
1072
- "description",
1073
- "schema",
1074
- "sanitize",
1075
- "text",
1076
- "markdown",
1077
- "render",
1078
- "presets"
1483
+ "xmp",
1484
+ "noscript",
1485
+ "noembed",
1486
+ "noframes",
1487
+ "template",
1488
+ "iframe",
1489
+ "object",
1490
+ "embed",
1491
+ "svg",
1492
+ "math",
1493
+ "select",
1494
+ "option",
1495
+ "plaintext"
1079
1496
  ]);
1080
- var FIELD_KEYS = {
1081
- text: ["max", "multiline", "default"],
1082
- inline: ["max", "default"],
1083
- url: ["schemes", "relative"],
1084
- enum: ["values", "default"],
1085
- number: ["min", "max", "integer", "default"],
1086
- boolean: ["default"],
1087
- array: ["items", "max"],
1088
- object: ["fields"]
1497
+ var ALLOWED = new Set(INLINE_TAGS);
1498
+ var VOID = /* @__PURE__ */ new Set(["br"]);
1499
+ var MAX_INPUT = 5e5;
1500
+ var MAX_NODES = 5e4;
1501
+ var MAX_DEPTH = 64;
1502
+ var NAMED_ENTITIES = Object.freeze({
1503
+ amp: "&",
1504
+ lt: "<",
1505
+ gt: ">",
1506
+ quot: '"',
1507
+ apos: "'",
1508
+ nbsp: "\xA0",
1509
+ shy: "\xAD",
1510
+ copy: "\xA9",
1511
+ reg: "\xAE",
1512
+ trade: "\u2122",
1513
+ hellip: "\u2026",
1514
+ mdash: "\u2014",
1515
+ ndash: "\u2013",
1516
+ lsquo: "\u2018",
1517
+ rsquo: "\u2019",
1518
+ ldquo: "\u201C",
1519
+ rdquo: "\u201D",
1520
+ laquo: "\xAB",
1521
+ raquo: "\xBB",
1522
+ euro: "\u20AC",
1523
+ middot: "\xB7",
1524
+ bull: "\u2022",
1525
+ times: "\xD7",
1526
+ deg: "\xB0",
1527
+ tab: " ",
1528
+ newline: "\n",
1529
+ colon: ":",
1530
+ sol: "/",
1531
+ lpar: "(",
1532
+ rpar: ")"
1533
+ });
1534
+ var decodeEntities = (text) => String(text).replace(
1535
+ /&(#[xX][0-9a-fA-F]{1,8}|#[0-9]{1,10}|[A-Za-z][A-Za-z0-9]{1,31});?/g,
1536
+ (match, body) => {
1537
+ if (body[0] === "#") {
1538
+ const code = body[1] === "x" || body[1] === "X" ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
1539
+ if (!Number.isFinite(code) || code <= 0 || code > 1114111 || code >= 55296 && code <= 57343)
1540
+ return "\uFFFD";
1541
+ return String.fromCodePoint(code);
1542
+ }
1543
+ const named = NAMED_ENTITIES[body] ?? NAMED_ENTITIES[body.toLowerCase()];
1544
+ return named === void 0 ? match : named;
1545
+ }
1546
+ );
1547
+ var parseAttributes = (source) => {
1548
+ const out = {};
1549
+ const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
1550
+ let match;
1551
+ while (match = pattern.exec(source)) {
1552
+ const name = match[1].toLowerCase();
1553
+ if (Object.prototype.hasOwnProperty.call(out, name)) continue;
1554
+ const raw = match[2] ?? match[3] ?? match[4] ?? "";
1555
+ out[name] = decodeEntities(raw);
1556
+ }
1557
+ return out;
1089
1558
  };
1090
- var BlockDefinitionError = class extends Error {
1091
- /**
1092
- * @param {string} message - Message naming the definition and the problem.
1093
- * @param {string} [code] - `INVALID_DEFINITION` | `RESERVED_NAME` | `NAME_TAKEN` | `REGISTRY_SEALED`.
1094
- */
1095
- constructor(message, code = "INVALID_DEFINITION") {
1096
- super(message);
1097
- this.name = "BlockDefinitionError";
1098
- this.code = code;
1559
+ var findTagEnd = (html, from) => {
1560
+ let quote = "";
1561
+ for (let i = from; i < html.length; i += 1) {
1562
+ const char = html[i];
1563
+ if (quote) {
1564
+ if (char === quote) quote = "";
1565
+ } else if (char === '"' || char === "'") quote = char;
1566
+ else if (char === ">") return i;
1099
1567
  }
1568
+ return -1;
1100
1569
  };
1101
- var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1102
- var fail = (where, message) => {
1103
- throw new BlockDefinitionError(`Magic Editor X block ${where}: ${message}`);
1570
+ var cleanAttributes = (tag, attribs, options = {}) => {
1571
+ const allowed = INLINE_ATTRIBUTES[tag] || [];
1572
+ const out = {};
1573
+ for (const name of allowed) {
1574
+ if (!Object.prototype.hasOwnProperty.call(attribs, name) || name.startsWith("data-mex-")) continue;
1575
+ const value = attribs[name];
1576
+ if (name === "href") {
1577
+ const url = sanitizeUrl(value);
1578
+ if (url) out.href = url;
1579
+ } else if (name === "target") {
1580
+ const target = sanitizeTarget(value);
1581
+ if (target) out.target = target;
1582
+ } else if (name === "rel") {
1583
+ const rel = String(value).split(/\s+/).filter((token) => /^[a-z-]{1,20}$/.test(token));
1584
+ if (rel.length) out.rel = rel.join(" ");
1585
+ } else if (name === "class") {
1586
+ const classes2 = String(value).split(/\s+/).filter((token) => (INLINE_CLASSES[tag] || []).includes(token));
1587
+ if (classes2.length) out.class = classes2.join(" ");
1588
+ } else {
1589
+ out[name] = String(value).slice(0, 2e3);
1590
+ }
1591
+ }
1592
+ if (tag === "a" && !options.inNote) Object.assign(out, cleanInternalLinkAttributes(attribs));
1593
+ return out;
1104
1594
  };
1105
- var boundedInt = (value, min, max, fallback, where, key) => {
1106
- if (value === void 0) return fallback;
1107
- if (!Number.isInteger(value) || value < min || value > max)
1108
- fail(where, `"${key}" must be an integer from ${min} to ${max}`);
1109
- return value;
1595
+ var MAX_MARKER_TEXT = 16;
1596
+ var isMathNode = (node) => node.type === "element" && node.tag === "span" && node.attrs[MATH_ATTRIBUTE] === "true";
1597
+ var isFootnoteNode = (node) => node.type === "element" && node.tag === "sup" && typeof node.attrs["data-mex-footnote"] === "string";
1598
+ var isColorNode = (node) => node.type === "element" && node.tag === "span" && typeof node.attrs[COLOR_ATTRIBUTE] === "string";
1599
+ var isHighlightNode = (node) => node.type === "element" && node.tag === "mark" && typeof node.attrs[HIGHLIGHT_ATTRIBUTE] === "string";
1600
+ var isAnnotationNode = (node) => node.type === "element" && node.tag === "span" && typeof node.attrs[ANNOTATION_ATTRIBUTE] === "string";
1601
+ var annotationOf = (node) => {
1602
+ const attrs = {};
1603
+ for (const [name, value] of Object.entries(node.attrs))
1604
+ if (name.startsWith(ANNOTATION_VALUE_PREFIX)) attrs[name.slice(ANNOTATION_VALUE_PREFIX.length)] = value;
1605
+ return { name: node.attrs[ANNOTATION_ATTRIBUTE], attrs };
1110
1606
  };
1111
- var normalizeField = (input, where, depth) => {
1112
- if (!isObject(input)) fail(where, 'a field must be an object with a "type"');
1113
- const type = input.type;
1114
- if (!BLOCK_FIELD_TYPES.includes(type)) fail(where, `unknown field type ${JSON.stringify(type)}`);
1115
- for (const key of Object.keys(input))
1116
- if (key !== "type" && key !== "label" && !FIELD_KEYS[type].includes(key))
1117
- fail(where, `unknown option "${key}" for a ${type} field`);
1118
- const out = { type };
1119
- if (input.label !== void 0) {
1120
- if (typeof input.label !== "string" || input.label.length > 100)
1121
- fail(where, '"label" must be a string of at most 100 characters');
1122
- out.label = input.label;
1607
+ var annotationAttributes = (name, values) => {
1608
+ const out = { [ANNOTATION_ATTRIBUTE]: name };
1609
+ for (const key of Object.keys(values).sort()) out[`${ANNOTATION_VALUE_PREFIX}${key}`] = values[key];
1610
+ return out;
1611
+ };
1612
+ var finalizeSpecial = (nodes, depth = 0) => {
1613
+ for (const node of nodes) {
1614
+ if (node.type !== "element") continue;
1615
+ if (isMathNode(node)) {
1616
+ const tex = nodesToText(node.children, { raw: true }).replace(/\u200b/g, "").slice(0, MAX_INLINE_TEX);
1617
+ node.children = tex ? [{ type: "text", value: tex }] : [];
1618
+ } else if (isFootnoteNode(node)) {
1619
+ const text = nodesToText(node.children, { raw: true }).slice(0, MAX_MARKER_TEXT);
1620
+ node.children = text ? [{ type: "text", value: text }] : [];
1621
+ } else if (depth < MAX_DEPTH) finalizeSpecial(node.children, depth + 1);
1622
+ }
1623
+ return nodes;
1624
+ };
1625
+ var specialElement = (tag, attribs, options) => {
1626
+ if (tag === "span" && Object.prototype.hasOwnProperty.call(attribs, MATH_ATTRIBUTE)) {
1627
+ if (!/^(?:|true)$/.test(attribs[MATH_ATTRIBUTE])) return null;
1628
+ return { attrs: { [MATH_ATTRIBUTE]: "true" } };
1629
+ }
1630
+ if (tag === "span" && Object.prototype.hasOwnProperty.call(attribs, ANNOTATION_ATTRIBUTE)) {
1631
+ const name = attribs[ANNOTATION_ATTRIBUTE];
1632
+ if (!ANNOTATION_NAME.test(name)) return null;
1633
+ const values = {};
1634
+ for (const [attribute, value] of Object.entries(attribs)) {
1635
+ if (!attribute.startsWith(ANNOTATION_VALUE_PREFIX)) continue;
1636
+ const key = attribute.slice(ANNOTATION_VALUE_PREFIX.length);
1637
+ if (!ANNOTATION_KEY.test(key) || Object.keys(values).length >= ANNOTATION_LIMITS.attributes) continue;
1638
+ const text = String(value).slice(0, ANNOTATION_LIMITS.text);
1639
+ if (text) values[key] = text;
1640
+ }
1641
+ return { attrs: annotationAttributes(name, values) };
1123
1642
  }
1124
- switch (type) {
1125
- case "text":
1126
- case "inline": {
1127
- out.max = boundedInt(
1128
- input.max,
1129
- 1,
1130
- BLOCK_LIMITS.maxText,
1131
- type === "text" ? BLOCK_LIMITS.defaultText : BLOCK_LIMITS.defaultInline,
1132
- where,
1133
- "max"
1134
- );
1135
- if (input.default !== void 0 && typeof input.default !== "string")
1136
- fail(where, '"default" must be a string');
1137
- out.default = (input.default || "").slice(0, out.max);
1138
- if (type === "text") {
1139
- if (input.multiline !== void 0 && typeof input.multiline !== "boolean")
1140
- fail(where, '"multiline" must be a boolean');
1141
- out.multiline = input.multiline === true;
1142
- }
1143
- break;
1643
+ if (tag === "span" && Object.prototype.hasOwnProperty.call(attribs, COLOR_ATTRIBUTE)) {
1644
+ return TOKEN_PATTERN.test(attribs[COLOR_ATTRIBUTE]) ? { attrs: { [COLOR_ATTRIBUTE]: attribs[COLOR_ATTRIBUTE] } } : null;
1645
+ }
1646
+ if (tag === "mark" && Object.prototype.hasOwnProperty.call(attribs, HIGHLIGHT_ATTRIBUTE)) {
1647
+ return TOKEN_PATTERN.test(attribs[HIGHLIGHT_ATTRIBUTE]) ? { attrs: { [HIGHLIGHT_ATTRIBUTE]: attribs[HIGHLIGHT_ATTRIBUTE] } } : null;
1648
+ }
1649
+ if (tag === "sup" && !options.inNote) {
1650
+ const id = attribs["data-mex-footnote"];
1651
+ if (typeof id !== "string" || !FOOTNOTE_ID.test(id)) return null;
1652
+ const source = typeof attribs["data-mex-note"] === "string" ? attribs["data-mex-note"] : "";
1653
+ const note = parseInline(source.slice(0, MAX_FOOTNOTE_NOTE), { inNote: true });
1654
+ return { attrs: { "data-mex-footnote": id }, note };
1655
+ }
1656
+ return null;
1657
+ };
1658
+ var parseInline = (input, options = {}) => {
1659
+ const html = typeof input === "string" ? input.slice(0, MAX_INPUT) : "";
1660
+ const root = { type: "element", tag: "#root", attrs: {}, children: [] };
1661
+ const stack = [root];
1662
+ let nodes = 0;
1663
+ let text = "";
1664
+ const flush = () => {
1665
+ if (!text) return;
1666
+ const parent = stack[stack.length - 1];
1667
+ const last = parent.children[parent.children.length - 1];
1668
+ const value = decodeEntities(text);
1669
+ if (last && last.type === "text") last.value += value;
1670
+ else if (nodes < MAX_NODES) {
1671
+ parent.children.push({ type: "text", value });
1672
+ nodes += 1;
1144
1673
  }
1145
- case "url": {
1146
- const schemes = input.schemes === void 0 ? ["http", "https"] : input.schemes;
1147
- if (!Array.isArray(schemes) || !schemes.length || schemes.some((scheme) => !LINK_SCHEMES.includes(scheme)))
1148
- fail(where, `"schemes" must be a non-empty list of ${LINK_SCHEMES.join(", ")}`);
1149
- if (input.relative !== void 0 && typeof input.relative !== "boolean")
1150
- fail(where, '"relative" must be a boolean');
1151
- out.schemes = Object.freeze([...new Set(schemes)]);
1152
- out.relative = input.relative !== false;
1674
+ text = "";
1675
+ };
1676
+ let i = 0;
1677
+ while (i < html.length) {
1678
+ const lt = html.indexOf("<", i);
1679
+ if (lt === -1) {
1680
+ text += html.slice(i);
1153
1681
  break;
1154
1682
  }
1155
- case "enum": {
1156
- const values = input.values;
1157
- if (!Array.isArray(values) || values.length < 1 || values.length > BLOCK_LIMITS.maxEnumValues || values.some((value) => typeof value !== "string" || value.length < 1 || value.length > 100) || new Set(values).size !== values.length)
1158
- fail(
1159
- where,
1160
- `"values" must be 1 to ${BLOCK_LIMITS.maxEnumValues} distinct strings (1-100 characters)`
1161
- );
1162
- out.values = Object.freeze([...values]);
1163
- if (input.default !== void 0 && !values.includes(input.default))
1164
- fail(where, '"default" must be one of "values"');
1165
- out.default = input.default === void 0 ? values[0] : input.default;
1683
+ text += html.slice(i, lt);
1684
+ i = lt;
1685
+ if (html.startsWith("<!--", i)) {
1686
+ const end2 = html.indexOf("-->", i + 4);
1687
+ flush();
1688
+ i = end2 === -1 ? html.length : end2 + 3;
1689
+ continue;
1690
+ }
1691
+ if (html.startsWith("<![CDATA[", i)) {
1692
+ const end2 = html.indexOf("]]>", i + 9);
1693
+ flush();
1694
+ i = end2 === -1 ? html.length : end2 + 3;
1695
+ continue;
1696
+ }
1697
+ if (html[i + 1] === "!" || html[i + 1] === "?") {
1698
+ const end2 = html.indexOf(">", i + 2);
1699
+ flush();
1700
+ i = end2 === -1 ? html.length : end2 + 1;
1701
+ continue;
1702
+ }
1703
+ const closing = html[i + 1] === "/";
1704
+ const nameMatch = /^[A-Za-z][A-Za-z0-9-]{0,40}/.exec(html.slice(i + (closing ? 2 : 1), i + 45));
1705
+ if (!nameMatch) {
1706
+ text += "<";
1707
+ i += 1;
1708
+ continue;
1709
+ }
1710
+ const end = findTagEnd(html, i + 1);
1711
+ if (end === -1) {
1712
+ text += html.slice(i);
1166
1713
  break;
1167
1714
  }
1168
- case "number": {
1169
- for (const key of ["min", "max", "default"])
1170
- if (input[key] !== void 0 && (typeof input[key] !== "number" || !Number.isFinite(input[key])))
1171
- fail(where, `"${key}" must be a finite number`);
1172
- if (input.integer !== void 0 && typeof input.integer !== "boolean")
1173
- fail(where, '"integer" must be a boolean');
1174
- out.integer = input.integer === true;
1175
- out.min = input.min === void 0 ? -Number.MAX_SAFE_INTEGER : input.min;
1176
- out.max = input.max === void 0 ? Number.MAX_SAFE_INTEGER : input.max;
1177
- if (out.min > out.max) fail(where, '"min" must not be greater than "max"');
1178
- if (input.default !== void 0) {
1179
- if (input.default < out.min || input.default > out.max || out.integer && !Number.isInteger(input.default))
1180
- fail(where, '"default" must be a valid value of the field');
1181
- out.default = input.default;
1715
+ flush();
1716
+ const tag = nameMatch[0].toLowerCase();
1717
+ const body = html.slice(i + (closing ? 2 : 1) + nameMatch[0].length, end);
1718
+ i = end + 1;
1719
+ if (closing) {
1720
+ if (!ALLOWED.has(tag)) continue;
1721
+ for (let s = stack.length - 1; s > 0; s -= 1) {
1722
+ if (stack[s].tag === tag) {
1723
+ stack.length = s;
1724
+ break;
1725
+ }
1182
1726
  }
1183
- break;
1727
+ continue;
1184
1728
  }
1185
- case "boolean":
1186
- if (input.default !== void 0 && typeof input.default !== "boolean")
1187
- fail(where, '"default" must be a boolean');
1188
- out.default = input.default === true;
1189
- break;
1190
- case "array":
1191
- if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1192
- out.max = boundedInt(input.max, 1, BLOCK_LIMITS.maxItems, BLOCK_LIMITS.defaultItems, where, "max");
1193
- out.items = normalizeField(input.items, `${where}[]`, depth + 1);
1194
- break;
1195
- case "object":
1196
- if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1197
- out.fields = normalizeFields(input.fields, where, depth + 1);
1198
- break;
1199
- default:
1200
- break;
1201
- }
1202
- return Object.freeze(out);
1203
- };
1204
- var normalizeFields = (input, where, depth) => {
1205
- if (!isObject(input)) fail(where, '"fields" must be an object of field descriptors');
1206
- const keys = Object.keys(input);
1207
- if (keys.length < 1 || keys.length > BLOCK_LIMITS.maxFields)
1208
- fail(where, `an object needs 1 to ${BLOCK_LIMITS.maxFields} fields`);
1209
- const out = /* @__PURE__ */ Object.create(null);
1210
- for (const key of keys) {
1211
- if (!KEY_PATTERN.test(key) || FORBIDDEN_KEYS2.has(key))
1212
- fail(where, `field name ${JSON.stringify(key)} must match ${KEY_PATTERN}`);
1213
- out[key] = normalizeField(input[key], `${where}.${key}`, depth);
1729
+ if (DROP_WITH_CONTENT.has(tag)) {
1730
+ const selfClosing = /\/\s*$/.test(body);
1731
+ if (selfClosing) continue;
1732
+ const closeIndex = html.slice(i).search(new RegExp(`</${tag}[\\s/>]`, "i"));
1733
+ if (closeIndex === -1) break;
1734
+ const closeEnd = html.indexOf(">", i + closeIndex);
1735
+ i = closeEnd === -1 ? html.length : closeEnd + 1;
1736
+ continue;
1737
+ }
1738
+ if (!ALLOWED.has(tag) || nodes >= MAX_NODES) continue;
1739
+ const attribs = parseAttributes(body);
1740
+ const special = specialElement(tag, attribs, options);
1741
+ const element = {
1742
+ type: "element",
1743
+ tag,
1744
+ attrs: special ? special.attrs : cleanAttributes(tag, attribs, options),
1745
+ children: []
1746
+ };
1747
+ if (special && special.note) element.note = special.note;
1748
+ stack[stack.length - 1].children.push(element);
1749
+ nodes += 1;
1750
+ if (!VOID.has(tag) && stack.length < MAX_DEPTH) stack.push(element);
1214
1751
  }
1215
- return Object.freeze(out);
1216
- };
1217
- var blockNameProblem = (name) => {
1218
- if (typeof name !== "string" || !BLOCK_NAME_PATTERN.test(name))
1219
- return `the name must match ${BLOCK_NAME_PATTERN}`;
1220
- if (RESERVED.has(name.toLowerCase())) return `"${name}" is a built-in tool name`;
1221
- return null;
1752
+ flush();
1753
+ return finalizeSpecial(root.children);
1222
1754
  };
1223
- var defineBlock = (definition) => {
1224
- if (!isObject(definition))
1225
- throw new BlockDefinitionError("Magic Editor X block: the definition must be an object");
1226
- const label2 = typeof definition.name === "string" ? `"${definition.name.slice(0, 50)}"` : "(no name)";
1227
- for (const key of Object.keys(definition))
1228
- if (!DEFINITION_KEYS.has(key)) fail(label2, `unknown key "${key}"`);
1229
- const problem = blockNameProblem(definition.name);
1230
- if (problem)
1231
- throw new BlockDefinitionError(
1232
- `Magic Editor X block ${label2}: ${problem}`,
1233
- problem.includes("built-in") ? "RESERVED_NAME" : "INVALID_DEFINITION"
1234
- );
1235
- const out = {
1236
- name: definition.name,
1237
- version: boundedInt(definition.version, 1, 1e6, 1, label2, "version")
1238
- };
1239
- for (const [key, max] of [
1240
- ["title", 100],
1241
- ["description", 500]
1242
- ]) {
1243
- if (definition[key] === void 0) continue;
1244
- if (typeof definition[key] !== "string" || definition[key].length > max)
1245
- fail(label2, `"${key}" must be a string of at most ${max} characters`);
1246
- out[key] = definition[key];
1755
+ var resolveLinkAttributes = (attrs, resolver) => {
1756
+ if (typeof resolver !== "function" || !attrs["data-mex-uid"] || !attrs["data-mex-document-id"])
1757
+ return attrs;
1758
+ let result;
1759
+ try {
1760
+ result = resolver({
1761
+ uid: attrs["data-mex-uid"],
1762
+ documentId: attrs["data-mex-document-id"],
1763
+ locale: attrs["data-mex-locale"] || null,
1764
+ href: attrs.href || null,
1765
+ ...isMentionLink(attrs) ? { mention: true } : {}
1766
+ });
1767
+ } catch {
1768
+ result = void 0;
1247
1769
  }
1248
- out.schema = normalizeFields(definition.schema, `${label2} schema`, 0);
1249
- for (const key of ["sanitize", "text", "markdown", "render"]) {
1250
- if (definition[key] === void 0) continue;
1251
- if (typeof definition[key] !== "function") fail(label2, `"${key}" must be a function`);
1252
- out[key] = definition[key];
1770
+ if (result === false) return null;
1771
+ if (typeof result === "string") {
1772
+ const url = sanitizeUrl(result);
1773
+ if (url) return { ...attrs, href: url };
1253
1774
  }
1254
- const presets = definition.presets === void 0 ? [] : definition.presets;
1255
- if (!Array.isArray(presets) || presets.some((preset) => !BLOCK_PRESETS.includes(preset)))
1256
- fail(label2, `"presets" must list some of ${BLOCK_PRESETS.join(", ")}`);
1257
- out.presets = Object.freeze([...new Set(presets)]);
1258
- return Object.freeze(out);
1775
+ return attrs;
1259
1776
  };
1260
- var cleanValue = (field, value, inline, budget) => {
1261
- budget.left -= 1;
1262
- switch (field.type) {
1263
- case "text":
1264
- return typeof value === "string" ? value.slice(0, field.max) : field.default;
1265
- case "inline":
1266
- return inline(typeof value === "string" ? value.slice(0, field.max) : field.default);
1267
- case "url":
1268
- return typeof value === "string" ? sanitizeUrl(value.slice(0, BLOCK_LIMITS.maxUrl), {
1269
- schemes: field.schemes,
1270
- allowRelative: field.relative
1271
- }) : "";
1272
- case "enum":
1273
- return typeof value === "string" && field.values.includes(value) ? value : field.default;
1274
- case "number":
1275
- return typeof value === "number" && Number.isFinite(value) && value >= field.min && value <= field.max && (!field.integer || Number.isInteger(value)) ? value : field.default;
1276
- case "boolean":
1277
- return typeof value === "boolean" ? value : field.default;
1278
- case "array": {
1279
- const out = [];
1280
- if (!Array.isArray(value)) return out;
1281
- for (const item of value) {
1282
- if (out.length >= field.max || budget.left <= 0) break;
1283
- if (!matchesType(field.items, item)) continue;
1284
- const clean = cleanValue(field.items, item, inline, budget);
1285
- if (clean !== void 0) out.push(clean);
1777
+ var ATTRIBUTE_ORDER = [
1778
+ "href",
1779
+ "target",
1780
+ "rel",
1781
+ "title",
1782
+ "class",
1783
+ "data-tooltip",
1784
+ "data-mex-uid",
1785
+ "data-mex-document-id",
1786
+ "data-mex-locale",
1787
+ "data-mex-mention",
1788
+ MATH_ATTRIBUTE,
1789
+ "data-mex-footnote",
1790
+ "data-mex-note"
1791
+ ];
1792
+ var RENDER_STATE = /* @__PURE__ */ Symbol.for("magic-editor-x.render-state");
1793
+ var storedNote = (note) => serializeNodes(inlineNodesToRender(note || [], { storage: true }));
1794
+ var MENTION_CLASS = "mex-mention";
1795
+ var inlineNodesToRender = (nodes, options = {}) => {
1796
+ const out = [];
1797
+ const state = options[RENDER_STATE];
1798
+ for (const node of nodes) {
1799
+ if (node.type === "text") {
1800
+ out.push({ type: "text", value: node.value });
1801
+ continue;
1802
+ }
1803
+ if (node.tag === "br") {
1804
+ out.push({ type: "element", tag: "br", attrs: {}, children: [] });
1805
+ continue;
1806
+ }
1807
+ if (isMathNode(node)) {
1808
+ const tex = nodesToText(node.children);
1809
+ if (state && !options.storage) {
1810
+ if (tex.trim()) out.push(state.math(tex, false));
1811
+ continue;
1286
1812
  }
1287
- return out;
1813
+ out.push({
1814
+ type: "element",
1815
+ tag: "span",
1816
+ attrs: { [MATH_ATTRIBUTE]: "true" },
1817
+ children: tex ? [{ type: "text", value: tex }] : []
1818
+ });
1819
+ continue;
1288
1820
  }
1289
- case "object":
1290
- return cleanObject(field.fields, isObject(value) ? value : {}, inline, budget);
1291
- default:
1292
- return void 0;
1821
+ if (isFootnoteNode(node)) {
1822
+ if (state && !options.storage) {
1823
+ out.push(state.footnote(node));
1824
+ continue;
1825
+ }
1826
+ const attrs2 = { "data-mex-footnote": node.attrs["data-mex-footnote"] };
1827
+ const note = storedNote(node.note);
1828
+ if (note) attrs2["data-mex-note"] = note;
1829
+ out.push({ type: "element", tag: "sup", attrs: attrs2, children: inlineNodesToRender(node.children, options) });
1830
+ continue;
1831
+ }
1832
+ if (isColorNode(node) || isHighlightNode(node)) {
1833
+ const color = node.tag === "span";
1834
+ const name = color ? COLOR_ATTRIBUTE : HIGHLIGHT_ATTRIBUTE;
1835
+ const token = node.attrs[name];
1836
+ out.push({
1837
+ type: "element",
1838
+ tag: node.tag,
1839
+ attrs: options.storage ? { [name]: token } : { class: color ? colorClass(token) : highlightClass(token), [name]: token },
1840
+ children: inlineNodesToRender(node.children, options)
1841
+ });
1842
+ continue;
1843
+ }
1844
+ if (isAnnotationNode(node)) {
1845
+ const children = inlineNodesToRender(node.children, options);
1846
+ if (options.storage) out.push({ type: "element", tag: "span", attrs: { ...node.attrs }, children });
1847
+ else out.push(...renderAnnotation(node, children, options));
1848
+ continue;
1849
+ }
1850
+ let attrs = node.attrs;
1851
+ if (node.tag === "a") {
1852
+ attrs = resolveLinkAttributes(attrs, options.links);
1853
+ if (!attrs || !attrs.href) {
1854
+ out.push(...inlineNodesToRender(node.children, options));
1855
+ continue;
1856
+ }
1857
+ if (attrs.target === "_blank") {
1858
+ const rel = new Set(
1859
+ String(attrs.rel || "").split(/\s+/).filter(Boolean)
1860
+ );
1861
+ rel.add("noopener");
1862
+ rel.add("noreferrer");
1863
+ attrs = { ...attrs, rel: Array.from(rel).sort().join(" ") };
1864
+ }
1865
+ if (!options.storage && isMentionLink(attrs)) attrs = { ...attrs, class: MENTION_CLASS };
1866
+ }
1867
+ const ordered = {};
1868
+ for (const name of ATTRIBUTE_ORDER) {
1869
+ if (attrs[name] !== void 0 && attrs[name] !== "") ordered[name] = String(attrs[name]);
1870
+ }
1871
+ out.push({
1872
+ type: "element",
1873
+ tag: node.tag,
1874
+ attrs: ordered,
1875
+ children: inlineNodesToRender(node.children, options)
1876
+ });
1293
1877
  }
1294
- };
1295
- var matchesType = (field, item) => {
1296
- switch (field.type) {
1297
- case "text":
1298
- case "inline":
1299
- case "url":
1300
- case "enum":
1301
- return typeof item === "string";
1302
- case "number":
1303
- return typeof item === "number";
1304
- case "boolean":
1305
- return typeof item === "boolean";
1306
- case "array":
1307
- return Array.isArray(item);
1308
- default:
1309
- return isObject(item);
1878
+ return out;
1879
+ };
1880
+ var annotationLists = /* @__PURE__ */ new WeakMap();
1881
+ var annotationDefinition = (name, options) => {
1882
+ const list = options.annotations;
1883
+ if (Array.isArray(list)) {
1884
+ if (!annotationLists.has(list)) {
1885
+ const map = /* @__PURE__ */ new Map();
1886
+ for (const item of list.slice(0, ANNOTATION_LIMITS.registered))
1887
+ if (item && typeof item === "object" && typeof item.name === "string" && item.attributes)
1888
+ map.set(item.name, item);
1889
+ annotationLists.set(list, map);
1890
+ }
1891
+ const found = annotationLists.get(list).get(name);
1892
+ if (found) return found;
1310
1893
  }
1894
+ return activeAnnotation(name);
1311
1895
  };
1312
- var cleanObject = (fields, value, inline, budget) => {
1896
+ var resolvedValue = (options, annotation) => {
1897
+ if (typeof options.resolveAnnotation !== "function") return void 0;
1898
+ let value;
1899
+ try {
1900
+ value = options.resolveAnnotation(annotation);
1901
+ } catch {
1902
+ return void 0;
1903
+ }
1904
+ if (typeof value === "string") return value.slice(0, 2e3);
1905
+ if (value && typeof value === "object" && !Array.isArray(value)) return value;
1906
+ return void 0;
1907
+ };
1908
+ var renderAnnotation = (node, children, options) => {
1909
+ const { name, attrs } = annotationOf(node);
1910
+ const definition = annotationDefinition(name, options);
1911
+ const values = definition ? cleanAnnotationAttributes(definition, attrs) : attrs;
1912
+ if (!values) return children;
1913
+ if (definition && typeof definition.render === "function") {
1914
+ const text = nodesToText(node.children);
1915
+ let out;
1916
+ try {
1917
+ out = definition.render({
1918
+ name,
1919
+ attrs: { ...values },
1920
+ text,
1921
+ resolved: resolvedValue(options, { name, attrs: { ...values }, text })
1922
+ });
1923
+ } catch {
1924
+ out = void 0;
1925
+ }
1926
+ if (out === false) return children;
1927
+ const wrapper = cleanAnnotationWrapper(out);
1928
+ if (wrapper) return [{ type: "element", tag: wrapper.tag, attrs: wrapper.attrs, children }];
1929
+ }
1930
+ return [
1931
+ {
1932
+ type: "element",
1933
+ tag: "span",
1934
+ attrs: {
1935
+ class: `mex-annotation mex-annotation-${name}`,
1936
+ ...annotationAttributes(name, definition ? values : {})
1937
+ },
1938
+ children
1939
+ }
1940
+ ];
1941
+ };
1942
+ var inlineToNodes = (html, options) => inlineNodesToRender(parseInline(html), options);
1943
+ var nodesToHtml = (nodes, options = {}) => serializeNodes(inlineNodesToRender(nodes, options));
1944
+ var nodesToText = (nodes, options = {}) => nodes.map((node) => {
1945
+ if (node.type === "text") return node.value;
1946
+ if (node.tag === "br") return "\n";
1947
+ if (!options.raw && isFootnoteNode(node))
1948
+ return typeof options.footnote === "function" ? options.footnote(node) : "";
1949
+ return nodesToText(node.children, options);
1950
+ }).join("");
1951
+ var inlineToHtml = (html, options) => nodesToHtml(parseInline(html), options);
1952
+ var inlineToText = (html, options) => nodesToText(parseInline(html), options).replace(/\u00a0/g, " ");
1953
+
1954
+ // shared/render/mathml.mjs
1955
+ var MATHML_TAGS = Object.freeze([
1956
+ "math",
1957
+ "semantics",
1958
+ "annotation",
1959
+ "mrow",
1960
+ "mi",
1961
+ "mn",
1962
+ "mo",
1963
+ "ms",
1964
+ "mtext",
1965
+ "mspace",
1966
+ "msub",
1967
+ "msup",
1968
+ "msubsup",
1969
+ "munder",
1970
+ "mover",
1971
+ "munderover",
1972
+ "mfrac",
1973
+ "msqrt",
1974
+ "mroot",
1975
+ "mstyle",
1976
+ "merror",
1977
+ "mpadded",
1978
+ "mphantom",
1979
+ "mtable",
1980
+ "mtr",
1981
+ "mtd",
1982
+ "mlabeledtr",
1983
+ "mmultiscripts",
1984
+ "mprescripts",
1985
+ "none",
1986
+ "menclose"
1987
+ ]);
1988
+ var TAGS = new Set(MATHML_TAGS);
1989
+ var COMMON_ATTRIBUTES = /* @__PURE__ */ new Set([
1990
+ "dir",
1991
+ "displaystyle",
1992
+ "scriptlevel",
1993
+ "mathvariant",
1994
+ "mathsize",
1995
+ "mathcolor",
1996
+ "mathbackground"
1997
+ ]);
1998
+ var ELEMENT_ATTRIBUTES = Object.freeze({
1999
+ math: ["display"],
2000
+ mo: [
2001
+ "form",
2002
+ "fence",
2003
+ "separator",
2004
+ "stretchy",
2005
+ "symmetric",
2006
+ "largeop",
2007
+ "movablelimits",
2008
+ "lspace",
2009
+ "rspace",
2010
+ "minsize",
2011
+ "maxsize",
2012
+ "accent"
2013
+ ],
2014
+ mspace: ["width", "height", "depth"],
2015
+ mpadded: ["width", "height", "depth", "lspace", "voffset"],
2016
+ mfrac: ["linethickness"],
2017
+ mover: ["accent"],
2018
+ munder: ["accentunder"],
2019
+ munderover: ["accent", "accentunder"],
2020
+ mtable: [
2021
+ "columnalign",
2022
+ "rowalign",
2023
+ "columnspacing",
2024
+ "rowspacing",
2025
+ "columnlines",
2026
+ "rowlines",
2027
+ "frame",
2028
+ "framespacing",
2029
+ "equalrows",
2030
+ "equalcolumns",
2031
+ "side"
2032
+ ],
2033
+ mtr: ["columnalign", "rowalign"],
2034
+ mlabeledtr: ["columnalign", "rowalign"],
2035
+ mtd: ["columnalign", "rowalign", "columnspan", "rowspan"],
2036
+ menclose: ["notation"],
2037
+ annotation: ["encoding"]
2038
+ });
2039
+ var ATTRIBUTE_VALUE = /^[A-Za-z0-9 .%#+-]{0,100}$/;
2040
+ var COLOR_VALUE = /^(?:#[0-9A-Fa-f]{3,8}|[A-Za-z]{1,30})$/;
2041
+ var CLASS_TOKEN2 = /^tml-[a-z0-9-]{1,40}$/;
2042
+ var TEX_ENCODING = "application/x-tex";
2043
+ var MAX_INPUT2 = 2e5;
2044
+ var MAX_NODES2 = 2e4;
2045
+ var MAX_DEPTH2 = 64;
2046
+ var parseAttributes2 = (source) => {
1313
2047
  const out = {};
1314
- for (const key of Object.keys(fields)) {
1315
- const own = Object.prototype.hasOwnProperty.call(value, key) ? value[key] : void 0;
1316
- const clean = cleanValue(fields[key], own, inline, budget);
1317
- if (clean !== void 0) out[key] = clean;
2048
+ const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
2049
+ let match;
2050
+ while (match = pattern.exec(source)) {
2051
+ const name = match[1].toLowerCase();
2052
+ if (Object.prototype.hasOwnProperty.call(out, name)) continue;
2053
+ out[name] = decodeEntities(match[2] ?? match[3] ?? match[4] ?? "");
1318
2054
  }
1319
2055
  return out;
1320
2056
  };
1321
- var eachLeaf = (fields, data, visit) => {
1322
- const walk = (field, value, path, depth) => {
1323
- if (depth > BLOCK_LIMITS.maxDepth + 1) return;
1324
- if (field.type === "array") {
1325
- if (!Array.isArray(value)) return;
1326
- value.slice(0, field.max).forEach((item, index) => walk(field.items, item, [...path, index], depth + 1));
1327
- } else if (field.type === "object") {
1328
- if (!isObject(value)) return;
1329
- for (const key of Object.keys(field.fields))
1330
- if (Object.prototype.hasOwnProperty.call(value, key))
1331
- walk(field.fields[key], value[key], [...path, key], depth + 1);
1332
- } else visit(field, value, path);
1333
- };
1334
- if (!isObject(data)) return;
1335
- for (const key of Object.keys(fields))
1336
- if (Object.prototype.hasOwnProperty.call(data, key)) walk(fields[key], data[key], [key], 0);
2057
+ var styleColor = (style, property) => {
2058
+ const pattern = property === "color" ? /(?:^|;)\s*color\s*:\s*([^;]+)/i : /background-color\s*:\s*([^;]+)/i;
2059
+ const match = pattern.exec(style);
2060
+ const value = match ? match[1].trim() : "";
2061
+ return COLOR_VALUE.test(value) ? value : "";
1337
2062
  };
1338
- var fieldAt = (fields, path) => {
1339
- let current = { type: "object", fields };
1340
- for (const part of String(path).split(".")) {
1341
- if (!part) continue;
1342
- if (current.type === "array") {
1343
- if (/^\d+$/.test(part)) {
1344
- current = current.items;
1345
- continue;
1346
- }
1347
- return null;
2063
+ var cleanAttributes2 = (tag, attribs) => {
2064
+ const out = {};
2065
+ const allowed = ELEMENT_ATTRIBUTES[tag] || [];
2066
+ for (const [name, raw] of Object.entries(attribs)) {
2067
+ if (typeof raw !== "string" && typeof raw !== "number" && raw !== true) continue;
2068
+ const value = raw === true ? "true" : String(raw);
2069
+ if (name === "class") {
2070
+ const classes2 = value.split(/\s+/).filter((token) => CLASS_TOKEN2.test(token));
2071
+ if (classes2.length) out.class = classes2.slice(0, 8).join(" ");
2072
+ continue;
1348
2073
  }
1349
- if (current.type !== "object" || !Object.prototype.hasOwnProperty.call(current.fields, part)) return null;
1350
- current = current.fields[part];
1351
- }
1352
- return current;
2074
+ if (name === "encoding") {
2075
+ if (tag === "annotation" && value === TEX_ENCODING) out.encoding = value;
2076
+ continue;
2077
+ }
2078
+ if (name === "mathcolor" || name === "mathbackground") {
2079
+ if (COLOR_VALUE.test(value)) out[name] = value;
2080
+ continue;
2081
+ }
2082
+ if (!COMMON_ATTRIBUTES.has(name) && !allowed.includes(name)) continue;
2083
+ if (ATTRIBUTE_VALUE.test(value)) out[name] = value;
2084
+ }
2085
+ if (typeof attribs.style === "string") {
2086
+ const color = styleColor(attribs.style, "color");
2087
+ const background = styleColor(attribs.style, "background-color");
2088
+ if (color && !out.mathcolor) out.mathcolor = color;
2089
+ if (background && !out.mathbackground) out.mathbackground = background;
2090
+ }
2091
+ if (tag === "annotation" && out.encoding !== TEX_ENCODING) return null;
2092
+ if (tag === "math" && out.display && out.display !== "block" && out.display !== "inline")
2093
+ delete out.display;
2094
+ return out;
1353
2095
  };
1354
- var compiled = /* @__PURE__ */ new WeakMap();
1355
- var compileBlock = (definition) => {
1356
- if (definition && typeof definition === "object" && compiled.has(definition))
1357
- return compiled.get(definition);
1358
- const def = defineBlock(definition && typeof definition === "object" ? { ...definition } : definition);
1359
- const schema = def.schema;
1360
- const run = (data, inline) => cleanObject(schema, isObject(data) ? data : {}, inline, { left: BLOCK_LIMITS.maxValues });
1361
- const result = Object.freeze({
1362
- ...def,
1363
- /**
1364
- * Cleans untrusted block data (unknown keys dropped, values bounded).
1365
- * The optional `sanitize` hook runs on the clean data; its result is
1366
- * cleaned again, so it cannot add keys or unsafe values. A hook that
1367
- * throws is ignored (the clean data is used).
1368
- * @param {unknown} data - Block data.
1369
- * @param {(html: string) => string} inline - Inline HTML sanitiser of the caller.
1370
- * @returns {object} Clean data.
1371
- */
1372
- clean: (data, inline) => {
1373
- const first = run(data, inline);
1374
- if (!def.sanitize) return first;
1375
- let next;
1376
- try {
1377
- next = def.sanitize(copyData(first), { sanitizeUrl });
1378
- } catch {
1379
- return first;
2096
+ var tokenize = (input) => {
2097
+ const source = input.slice(0, MAX_INPUT2);
2098
+ const root = { type: "element", tag: "#root", attrs: {}, children: [] };
2099
+ const stack = [root];
2100
+ let count = 0;
2101
+ let i = 0;
2102
+ const pushText = (text) => {
2103
+ if (!text) return;
2104
+ const parent = stack[stack.length - 1];
2105
+ const last = parent.children[parent.children.length - 1];
2106
+ const value = decodeEntities(text);
2107
+ if (last && last.type === "text") last.value += value;
2108
+ else if (count < MAX_NODES2) {
2109
+ parent.children.push({ type: "text", value });
2110
+ count += 1;
2111
+ }
2112
+ };
2113
+ while (i < source.length) {
2114
+ const lt = source.indexOf("<", i);
2115
+ if (lt === -1) {
2116
+ pushText(source.slice(i));
2117
+ break;
2118
+ }
2119
+ pushText(source.slice(i, lt));
2120
+ if (source.startsWith("<!--", lt)) {
2121
+ const end2 = source.indexOf("-->", lt + 4);
2122
+ i = end2 === -1 ? source.length : end2 + 3;
2123
+ continue;
2124
+ }
2125
+ if (source[lt + 1] === "!" || source[lt + 1] === "?") {
2126
+ const end2 = source.indexOf(">", lt + 2);
2127
+ i = end2 === -1 ? source.length : end2 + 1;
2128
+ continue;
2129
+ }
2130
+ const closing = source[lt + 1] === "/";
2131
+ const nameMatch = /^[A-Za-z][A-Za-z0-9:-]{0,40}/.exec(source.slice(lt + (closing ? 2 : 1), lt + 45));
2132
+ let end = -1;
2133
+ let quote = "";
2134
+ for (let j = lt + 1; j < source.length; j += 1) {
2135
+ const char = source[j];
2136
+ if (quote) {
2137
+ if (char === quote) quote = "";
2138
+ } else if (char === '"' || char === "'") quote = char;
2139
+ else if (char === ">") {
2140
+ end = j;
2141
+ break;
1380
2142
  }
1381
- return isObject(next) ? run(next, inline) : first;
1382
- },
1383
- /**
1384
- * Text fields of the data in schema order: `{ path, kind, value }`
1385
- * (`html` for inline fields, `plain` for text fields).
1386
- * @param {unknown} data - Block data.
1387
- * @returns {Array<{ path: Array<string|number>, kind: 'html'|'plain', value: string }>} Fields.
1388
- */
1389
- fields: (data) => {
1390
- const out = [];
1391
- eachLeaf(schema, data, (field, value, path) => {
1392
- if (typeof value !== "string") return;
1393
- if (field.type === "inline") out.push({ path, kind: "html", value });
1394
- else if (field.type === "text") out.push({ path, kind: "plain", value });
1395
- });
1396
- return out;
1397
- },
1398
- /**
1399
- * Non-empty URL values: `{ path, value }`.
1400
- * @param {unknown} data - Block data.
1401
- * @returns {Array<{ path: Array<string|number>, value: string }>} URLs.
1402
- */
1403
- urls: (data) => {
1404
- const out = [];
1405
- eachLeaf(schema, data, (field, value, path) => {
1406
- if (field.type === "url" && typeof value === "string" && value) out.push({ path, value });
1407
- });
1408
- return out;
1409
- },
1410
- /**
1411
- * Kind of the value at a dotted path, for the version diff.
1412
- * @param {string} path - Dotted path.
1413
- * @returns {'inline'|'plain'|'value'} Kind.
1414
- */
1415
- kindOf: (path) => {
1416
- const field = fieldAt(schema, path);
1417
- if (!field) return "value";
1418
- if (field.type === "inline") return "inline";
1419
- if (field.type === "text") return "plain";
1420
- return "value";
1421
2143
  }
1422
- });
1423
- compiled.set(result, result);
1424
- if (definition && typeof definition === "object") compiled.set(definition, result);
1425
- return result;
2144
+ if (!nameMatch || end === -1) {
2145
+ pushText(source.slice(lt, end === -1 ? source.length : lt + 1));
2146
+ i = end === -1 ? source.length : lt + 1;
2147
+ continue;
2148
+ }
2149
+ const tag = nameMatch[0].toLowerCase();
2150
+ const body = source.slice(lt + (closing ? 2 : 1) + nameMatch[0].length, end);
2151
+ i = end + 1;
2152
+ if (closing) {
2153
+ for (let s = stack.length - 1; s > 0; s -= 1) {
2154
+ if (stack[s].tag === tag) {
2155
+ stack.length = s;
2156
+ break;
2157
+ }
2158
+ }
2159
+ continue;
2160
+ }
2161
+ if (count >= MAX_NODES2) continue;
2162
+ const element = { type: "element", tag, attrs: parseAttributes2(body), children: [] };
2163
+ stack[stack.length - 1].children.push(element);
2164
+ count += 1;
2165
+ const selfClosing = /\/\s*$/.test(body);
2166
+ if (!selfClosing && stack.length < MAX_DEPTH2) stack.push(element);
2167
+ }
2168
+ return root.children;
1426
2169
  };
1427
- var copyData = (value) => {
1428
- if (Array.isArray(value)) return value.map(copyData);
1429
- if (isObject(value)) {
1430
- const out = {};
1431
- for (const [key, child] of Object.entries(value)) out[key] = copyData(child);
1432
- return out;
2170
+ var clean = (nodes, ctx, depth, inAnnotation) => {
2171
+ const out = [];
2172
+ if (!Array.isArray(nodes) || depth > MAX_DEPTH2) return out;
2173
+ for (const node of nodes) {
2174
+ if (ctx.budget <= 0) break;
2175
+ if (typeof node === "string") {
2176
+ ctx.budget -= 1;
2177
+ if (node) out.push({ type: "text", value: node });
2178
+ continue;
2179
+ }
2180
+ if (!node || typeof node !== "object") continue;
2181
+ ctx.budget -= 1;
2182
+ if (node.type === "text") {
2183
+ if (typeof node.value === "string" && node.value) out.push({ type: "text", value: node.value });
2184
+ continue;
2185
+ }
2186
+ if (node.type !== "element" || typeof node.tag !== "string" || inAnnotation) continue;
2187
+ const tag = node.tag.toLowerCase();
2188
+ if (!TAGS.has(tag)) continue;
2189
+ const attrs = cleanAttributes2(tag, node.attrs && typeof node.attrs === "object" ? node.attrs : {});
2190
+ if (!attrs) continue;
2191
+ const children = clean(node.children, ctx, depth + 1, tag === "annotation");
2192
+ out.push({ type: "element", tag, attrs, children });
1433
2193
  }
1434
- return value;
2194
+ return out;
1435
2195
  };
1436
- var listCache = /* @__PURE__ */ new WeakMap();
1437
- var compileBlockList = (list) => {
1438
- if (!Array.isArray(list)) return /* @__PURE__ */ new Map();
1439
- if (listCache.has(list)) return listCache.get(list);
1440
- const map = /* @__PURE__ */ new Map();
1441
- for (const definition of list) {
1442
- const def = compileBlock(definition);
1443
- map.set(def.name, def);
2196
+ var cleanMathResult = (result) => {
2197
+ let nodes;
2198
+ if (typeof result === "string") nodes = tokenize(result);
2199
+ else if (Array.isArray(result)) nodes = result;
2200
+ else if (result && typeof result === "object") nodes = [result];
2201
+ else return [];
2202
+ const top = nodes.filter(
2203
+ (node) => node && typeof node === "object" && node.type === "element" && String(node.tag).toLowerCase() === "math"
2204
+ );
2205
+ return clean(top, { budget: MAX_NODES2 }, 0, false);
2206
+ };
2207
+
2208
+ // shared/render/math-notes.mjs
2209
+ var DEFAULT_FOOTNOTES_LABEL = "Footnotes";
2210
+ var DEFAULT_FOOTNOTE_BACK_LABEL = "Back to reference {n}";
2211
+ var DEFAULT_FOOTNOTE_PREFIX = "mex-";
2212
+ var PREFIX = /^[A-Za-z][A-Za-z0-9_-]{0,40}$/;
2213
+ var label = (value, fallback) => {
2214
+ if (typeof value !== "string") return fallback;
2215
+ const clean2 = value.trim();
2216
+ return clean2 && clean2.length <= 80 ? clean2 : fallback;
2217
+ };
2218
+ var footnoteOptions = (options) => {
2219
+ const source = isPlainObject2(options && options.footnotes) ? options.footnotes : {};
2220
+ return {
2221
+ label: label(source.label, DEFAULT_FOOTNOTES_LABEL),
2222
+ backLabel: label(source.backLabel, DEFAULT_FOOTNOTE_BACK_LABEL),
2223
+ prefix: typeof source.prefix === "string" && PREFIX.test(source.prefix) ? source.prefix : DEFAULT_FOOTNOTE_PREFIX
2224
+ };
2225
+ };
2226
+ var createFootnoteNumbers = () => {
2227
+ const used = /* @__PURE__ */ new Map();
2228
+ let count = 0;
2229
+ return {
2230
+ add(id) {
2231
+ const seen = (used.get(id) || 0) + 1;
2232
+ used.set(id, seen);
2233
+ count += 1;
2234
+ return { n: count, anchor: seen === 1 ? id : `${id}-${seen}` };
2235
+ }
2236
+ };
2237
+ };
2238
+ var renderMathNodes = (options, tex, display) => {
2239
+ if (!options || typeof options.math !== "function" || !tex.trim()) return [];
2240
+ let result;
2241
+ try {
2242
+ result = options.math(tex, { display });
2243
+ } catch {
2244
+ return [];
1444
2245
  }
1445
- listCache.set(list, map);
1446
- return map;
2246
+ return cleanMathResult(result);
2247
+ };
2248
+ var mathElement = (options, tex, kind) => {
2249
+ const math = renderMathNodes(options, tex, kind.display);
2250
+ const attrs = {
2251
+ class: kind.className || (kind.display ? "mex-math mex-math-display" : "mex-math"),
2252
+ "data-mex-math": kind.display ? "display" : "inline"
2253
+ };
2254
+ const children = math.length ? math : kind.display ? `\\[${tex}\\]` : `\\(${tex}\\)`;
2255
+ return el(kind.block ? "div" : "span", attrs, children);
2256
+ };
2257
+ var createFootnoteTree = (options, renderNote) => {
2258
+ const { label: listLabel, backLabel, prefix } = footnoteOptions(options);
2259
+ const numbers = createFootnoteNumbers();
2260
+ const items = [];
2261
+ const labelId = `${prefix}footnotes-label`;
2262
+ return {
2263
+ marker(node) {
2264
+ const { n, anchor } = numbers.add(node.attrs["data-mex-footnote"]);
2265
+ items.push({ n, anchor, note: node.note || [] });
2266
+ return el(
2267
+ "sup",
2268
+ { class: "mex-footnote-ref" },
2269
+ el(
2270
+ "a",
2271
+ {
2272
+ href: `#${prefix}fn-${anchor}`,
2273
+ id: `${prefix}fnref-${anchor}`,
2274
+ "aria-describedby": labelId
2275
+ },
2276
+ String(n)
2277
+ )
2278
+ );
2279
+ },
2280
+ section() {
2281
+ if (!items.length) return null;
2282
+ return el("section", { class: "mex-footnotes", "aria-labelledby": labelId }, [
2283
+ el("h2", { id: labelId, class: "mex-footnotes-label" }, listLabel),
2284
+ el(
2285
+ "ol",
2286
+ { class: "mex-footnotes-list" },
2287
+ items.map(
2288
+ (item) => el("li", { id: `${prefix}fn-${item.anchor}`, class: "mex-footnote" }, [
2289
+ renderNote(item.note),
2290
+ " ",
2291
+ el(
2292
+ "a",
2293
+ {
2294
+ href: `#${prefix}fnref-${item.anchor}`,
2295
+ class: "mex-footnote-back",
2296
+ "aria-label": backLabel.replace(/\{n\}/g, String(item.n))
2297
+ },
2298
+ "\u21A9"
2299
+ )
2300
+ ])
2301
+ )
2302
+ )
2303
+ ]);
2304
+ }
2305
+ };
1447
2306
  };
1448
2307
 
1449
2308
  // shared/toc.mjs
@@ -1670,12 +2529,12 @@ var prepareBlocks = (value, options = {}) => {
1670
2529
  const raw = isPlainObject2(block.data) ? block.data : {};
1671
2530
  const known = isBuiltInBlock({ type: block.type, data: raw });
1672
2531
  const definition = known ? null : registeredBlockOf({ type: block.type, data: raw }, explicit);
1673
- const clean = known ? BLOCK_POLICIES[block.type](raw, keepInline, ctx) : definition ? definition.clean(raw, keepInline) : raw;
1674
- for (const key of Object.keys(clean)) if (clean[key] === void 0) delete clean[key];
2532
+ const clean2 = known ? BLOCK_POLICIES[block.type](raw, keepInline, ctx) : definition ? definition.clean(raw, keepInline) : raw;
2533
+ for (const key of Object.keys(clean2)) if (clean2[key] === void 0) delete clean2[key];
1675
2534
  return {
1676
2535
  id: block.id,
1677
2536
  type: block.type,
1678
- data: clean,
2537
+ data: clean2,
1679
2538
  raw,
1680
2539
  tunes: sanitizeTunes(block.tunes),
1681
2540
  known,
@@ -1705,10 +2564,10 @@ var imageCandidates = (file) => {
1705
2564
  const out = [];
1706
2565
  const seen = /* @__PURE__ */ new Set();
1707
2566
  const push = (url, width) => {
1708
- const clean = sanitizeUrl(url, { schemes: ["http", "https"] });
1709
- if (!clean || !Number.isInteger(width) || width <= 0 || seen.has(width)) return;
2567
+ const clean2 = sanitizeUrl(url, { schemes: ["http", "https"] });
2568
+ if (!clean2 || !Number.isInteger(width) || width <= 0 || seen.has(width)) return;
1710
2569
  seen.add(width);
1711
- out.push({ url: clean, width });
2570
+ out.push({ url: clean2, width });
1712
2571
  };
1713
2572
  if (isPlainObject2(file.formats)) {
1714
2573
  const names = Object.keys(file.formats).sort(
@@ -1924,20 +2783,20 @@ var mediaFigure = (tag, b, o) => {
1924
2783
  caption.length ? el("figcaption", {}, caption) : null
1925
2784
  ]);
1926
2785
  };
1927
- var label = (value, fallback) => {
2786
+ var label2 = (value, fallback) => {
1928
2787
  if (typeof value !== "string") return fallback;
1929
- const clean = value.trim();
1930
- return clean && clean.length <= 80 ? clean : fallback;
2788
+ const clean2 = value.trim();
2789
+ return clean2 && clean2.length <= 80 ? clean2 : fallback;
1931
2790
  };
1932
- var tocLabel = (options) => label(isPlainObject2(options.toc) ? options.toc.label : void 0, "Table of contents");
2791
+ var tocLabel = (options) => label2(isPlainObject2(options.toc) ? options.toc.label : void 0, "Table of contents");
1933
2792
  var codeOptions = (options) => {
1934
2793
  const code = isPlainObject2(options.code) ? options.code : {};
1935
2794
  const lineNumbers = code.lineNumbers === true ? "all" : code.lineNumbers === "block" ? "block" : "none";
1936
2795
  const button = code.copyButton;
1937
2796
  const copy = button === true || isPlainObject2(button) ? {
1938
- label: label(isPlainObject2(button) ? button.label : void 0, "Copy code"),
1939
- copied: label(isPlainObject2(button) ? button.copiedLabel : void 0, "Copied"),
1940
- failed: label(isPlainObject2(button) ? button.failedLabel : void 0, "Copy failed")
2797
+ label: label2(isPlainObject2(button) ? button.label : void 0, "Copy code"),
2798
+ copied: label2(isPlainObject2(button) ? button.copiedLabel : void 0, "Copied"),
2799
+ failed: label2(isPlainObject2(button) ? button.failedLabel : void 0, "Copy failed")
1941
2800
  } : null;
1942
2801
  return { lineNumbers, copy };
1943
2802
  };
@@ -1966,23 +2825,29 @@ var codeBlock = (b, language, o) => {
1966
2825
  },
1967
2826
  el("code", language ? { class: `language-${language}` } : {}, numbers ? numberedLines(code) : code)
1968
2827
  );
1969
- if (!copy) return pre;
1970
- return el("div", { class: "mex-code-block", "data-mex-code": "copy" }, [
1971
- pre,
1972
- el(
1973
- "button",
1974
- {
1975
- type: "button",
1976
- class: "mex-code-copy",
1977
- "data-mex-copy": "code",
1978
- "data-mex-copied": copy.copied,
1979
- "data-mex-failed": copy.failed
1980
- },
1981
- copy.label
1982
- ),
1983
- el("span", { class: "mex-code-copy-status", role: "status", "aria-live": "polite" })
2828
+ const block = copy ? copyBlock(pre, copy) : pre;
2829
+ const filename = b.type === "codeFlask" && typeof b.data.filename === "string" ? b.data.filename : "";
2830
+ if (!filename) return block;
2831
+ return el("figure", { class: "mex-code-figure" }, [
2832
+ el("figcaption", { class: "mex-code-filename" }, filename),
2833
+ block
1984
2834
  ]);
1985
2835
  };
2836
+ var copyBlock = (pre, copy) => el("div", { class: "mex-code-block", "data-mex-code": "copy" }, [
2837
+ pre,
2838
+ el(
2839
+ "button",
2840
+ {
2841
+ type: "button",
2842
+ class: "mex-code-copy",
2843
+ "data-mex-copy": "code",
2844
+ "data-mex-copied": copy.copied,
2845
+ "data-mex-failed": copy.failed
2846
+ },
2847
+ copy.label
2848
+ ),
2849
+ el("span", { class: "mex-code-copy-status", role: "status", "aria-live": "polite" })
2850
+ ]);
1986
2851
  var RENDERERS = {
1987
2852
  paragraph: (b, o) => el("p", { class: classes(["mex-paragraph"], b.tunes) }, inlineToNodes(b.data.text, o)),
1988
2853
  header: (b, o) => el(
@@ -2057,20 +2922,29 @@ var RENDERERS = {
2057
2922
  const html = o.sanitizeRaw(String(b.raw.html || ""));
2058
2923
  return typeof html === "string" && html ? el("div", { class: classes(["mex-raw"], b.tunes) }, { type: "raw", html }) : null;
2059
2924
  },
2925
+ // Header row: <thead> with <th scope="col">; header column (2.4): <th scope="row">;
2926
+ // merged cells: colspan/rowspan (covered cells are left out); alignment: a class.
2060
2927
  table: (b, o) => {
2061
- const rows = b.data.content;
2928
+ const rows = tableLayout(b.data);
2062
2929
  if (!rows.length) return null;
2063
- const cells = (row, tag) => el(
2064
- "tr",
2065
- {},
2066
- row.map((cell2) => el(tag, tag === "th" ? { scope: "col" } : {}, inlineToNodes(cell2, o)))
2930
+ const cell2 = (item) => el(
2931
+ item.header ? "th" : "td",
2932
+ {
2933
+ ...item.header ? { scope: item.header } : {},
2934
+ ...item.colspan > 1 ? { colspan: String(item.colspan) } : {},
2935
+ ...item.rowspan > 1 ? { rowspan: String(item.rowspan) } : {},
2936
+ ...item.align ? { class: `mex-align-${item.align}` } : {}
2937
+ },
2938
+ inlineToNodes(item.html, o)
2067
2939
  );
2068
- const head = b.data.withHeadings ? el("thead", {}, cells(rows[0], "th")) : null;
2069
- const body = (b.data.withHeadings ? rows.slice(1) : rows).map((row) => cells(row, "td"));
2940
+ const tr = (row) => el("tr", {}, row.map(cell2));
2941
+ const head = b.data.withHeadings ? el("thead", {}, tr(rows[0])) : null;
2942
+ const body = (b.data.withHeadings ? rows.slice(1) : rows).map(tr);
2943
+ const caption = b.data.caption ? el("caption", {}, inlineToNodes(b.data.caption, o)) : null;
2070
2944
  return el(
2071
2945
  "table",
2072
2946
  { class: classes(["mex-table", ...b.data.stretched ? ["mex-stretched"] : []], b.tunes) },
2073
- [head, body.length ? el("tbody", {}, body) : null]
2947
+ [caption, head, body.length ? el("tbody", {}, body) : null]
2074
2948
  );
2075
2949
  },
2076
2950
  image: (b, o) => {
@@ -2163,11 +3037,11 @@ var RENDERERS = {
2163
3037
  embed: (b, o) => {
2164
3038
  const hosts = Array.isArray(o.embedHosts) ? o.embedHosts.map((h) => String(h).toLowerCase()) : DEFAULT_EMBED_HOSTS;
2165
3039
  const frame = embedFrameUrl(b.data.embed, hosts);
3040
+ const href = b.data.source || b.data.embed;
3041
+ if (!frame && !href) return null;
2166
3042
  const caption = inlineToNodes(b.data.caption, o);
2167
3043
  const title = inlineToText(b.data.caption) || b.data.service || "Embedded content";
2168
3044
  if (!frame) {
2169
- const href = b.data.source || b.data.embed;
2170
- if (!href) return null;
2171
3045
  return el(
2172
3046
  "p",
2173
3047
  { class: classes(["mex-embed", "mex-embed-link"], b.tunes) },
@@ -2227,6 +3101,15 @@ var RENDERERS = {
2227
3101
  return el("p", { class: classes(["mex-button-block"], b.tunes) }, inner);
2228
3102
  },
2229
3103
  delimiter: (b) => el("hr", { class: classes(["mex-delimiter"], b.tunes) }),
3104
+ // Math block (2.4): MathML from `options.math`, else the delimited TeX source.
3105
+ math: (b, o) => b.data.tex.trim() ? mathElement(o, b.data.tex, {
3106
+ display: b.data.display !== false,
3107
+ block: true,
3108
+ className: classes(
3109
+ ["mex-math", ...b.data.display !== false ? ["mex-math-display"] : []],
3110
+ b.tunes
3111
+ )
3112
+ }) : null,
2230
3113
  toc: (b, o) => {
2231
3114
  const tree = buildTocTree(b.headings || [], b.data);
2232
3115
  if (!tree.length) return null;
@@ -2319,15 +3202,15 @@ var RESOURCE_ATTRIBUTES = /* @__PURE__ */ new Set(["src", "poster", "data", "bac
2319
3202
  var cleanUrlAttribute = (name, value) => {
2320
3203
  if (name === "srcset" || name === "imagesrcset") {
2321
3204
  const parts = value.split(",").map((part) => part.trim());
2322
- const clean = [];
3205
+ const clean2 = [];
2323
3206
  for (const part of parts) {
2324
3207
  const [url, descriptor, extra] = part.split(/\s+/);
2325
3208
  if (extra !== void 0 || descriptor && !/^\d+(?:\.\d+)?[wx]$/.test(descriptor)) return "";
2326
3209
  const safe = sanitizeUrl(url, { schemes: ["http", "https"] });
2327
3210
  if (!safe) return "";
2328
- clean.push(descriptor ? `${safe} ${descriptor}` : safe);
3211
+ clean2.push(descriptor ? `${safe} ${descriptor}` : safe);
2329
3212
  }
2330
- return clean.join(", ");
3213
+ return clean2.join(", ");
2331
3214
  }
2332
3215
  return sanitizeUrl(value, { schemes: RESOURCE_ATTRIBUTES.has(name) ? ["http", "https"] : LINK_SCHEMES });
2333
3216
  };
@@ -2385,7 +3268,13 @@ var cleanOverrideNodes = (input, trusted) => {
2385
3268
  };
2386
3269
  var rawAllowed = (options) => options.rawHtml === "allow" && typeof options.sanitizeRaw === "function";
2387
3270
  var createTreeBuilder = (value, options, mode = {}) => {
2388
- const opts = options && typeof options === "object" ? options : {};
3271
+ const base = options && typeof options === "object" ? options : {};
3272
+ const opts = { ...base };
3273
+ const footnotes = createFootnoteTree(base, (note) => inlineNodesToRender(note, opts));
3274
+ opts[RENDER_STATE] = {
3275
+ math: (tex) => mathElement(base, tex, { display: false, block: false }),
3276
+ footnote: (node) => footnotes.marker(node)
3277
+ };
2389
3278
  const publicOf = /* @__PURE__ */ new WeakMap();
2390
3279
  const preparedOf = /* @__PURE__ */ new WeakMap();
2391
3280
  const trusted = /* @__PURE__ */ new WeakSet();
@@ -2469,6 +3358,8 @@ var createTreeBuilder = (value, options, mode = {}) => {
2469
3358
  childNodes: renderBlocks
2470
3359
  };
2471
3360
  const nodes = renderList(annotateHeadings(prepareBlocks(value, opts), opts));
3361
+ const section = footnotes.section();
3362
+ if (section) nodes.push(textNode("\n"), section);
2472
3363
  return { nodes, renderBlocks, helpers };
2473
3364
  };
2474
3365
  var flattenBlocks = (nodes) => {
@@ -2494,6 +3385,14 @@ var renderTree = (value, options) => flattenBlocks(createTreeBuilder(value, opti
2494
3385
  var renderHtml = (value, options = {}) => serializeNodes(createTreeBuilder(value, options, { overrideHtml: true }).nodes);
2495
3386
 
2496
3387
  // shared/render/text.mjs
3388
+ var notes = null;
3389
+ var footnoteText = (node) => {
3390
+ if (!notes) return "";
3391
+ const { n } = notes.numbers.add(node.attrs["data-mex-footnote"]);
3392
+ notes.items.push({ n, note: node.note || [] });
3393
+ return `[${n}]`;
3394
+ };
3395
+ var inlineToText2 = (html) => inlineToText(html, { footnote: footnoteText });
2497
3396
  var tocLines = (nodes, ordered, depth) => nodes.flatMap((node, index) => [
2498
3397
  `${" ".repeat(depth)}${ordered ? `${index + 1}.` : "-"} ${node.text}`,
2499
3398
  ...tocLines(node.children, ordered, depth + 1)
@@ -2506,7 +3405,7 @@ var listLines = (items, style, start, depth) => {
2506
3405
  if (style === "ordered") marker = `${start + index}.`;
2507
3406
  else if (style === "checklist") marker = item.meta && item.meta.checked ? "[x]" : "[ ]";
2508
3407
  const indent = " ".repeat(depth);
2509
- const text = inlineToText(content).trim().replace(/\n/g, `
3408
+ const text = inlineToText2(content).trim().replace(/\n/g, `
2510
3409
  ${indent} `);
2511
3410
  lines.push(`${indent}${marker} ${text}`);
2512
3411
  if (typeof item !== "string" && Array.isArray(item.items) && item.items.length && depth < 12)
@@ -2514,7 +3413,7 @@ ${indent} `);
2514
3413
  });
2515
3414
  return lines;
2516
3415
  };
2517
- var t = (html) => inlineToText(html).trim();
3416
+ var t = (html) => inlineToText2(html).trim();
2518
3417
  var mediaText = (b) => {
2519
3418
  if (!b.data.file.url) return "";
2520
3419
  const parts = [b.data.title.trim(), t(b.data.caption)].filter(Boolean);
@@ -2535,9 +3434,16 @@ var RENDERERS2 = {
2535
3434
  alert: (b) => t(b.data.message),
2536
3435
  toggle: (b, _o, render) => [t(b.data.text), render(b.children)].filter(Boolean).join("\n\n"),
2537
3436
  code: (b) => b.data.code,
2538
- codeFlask: (b) => b.data.code,
3437
+ // 2.4: the file name label on its own line before the code.
3438
+ codeFlask: (b) => typeof b.data.filename === "string" && b.data.filename ? [b.data.filename, b.data.code].filter(Boolean).join("\n") : b.data.code,
2539
3439
  raw: () => "",
2540
- table: (b) => b.data.content.map((row) => row.map((cell2) => t(cell2).replace(/\s+/g, " ")).join(" ")).join("\n"),
3440
+ // Tab-separated rows; merged cells leave their covered cells empty; the caption (2.4) is the first line.
3441
+ table: (b) => {
3442
+ const rows = b.data.content.map((row) => row.map((cell2) => t(cell2).replace(/\s+/g, " ")).join(" ")).join("\n");
3443
+ const caption = b.data.caption ? t(b.data.caption).replace(/\s+/g, " ") : "";
3444
+ return caption && b.data.content.length ? `${caption}
3445
+ ${rows}` : rows;
3446
+ },
2541
3447
  image: (b) => t(b.data.caption) || (b.raw.decorative === true ? "" : (b.data.file.alt || "").trim()),
2542
3448
  simpleImage: (b) => t(b.data.caption),
2543
3449
  gallery: (b) => [
@@ -2554,6 +3460,7 @@ var RENDERERS2 = {
2554
3460
  personality: (b) => [b.data.name, b.data.description, b.data.link].filter(Boolean).join("\n"),
2555
3461
  button: (b) => b.data.link ? `${b.data.text} (${b.data.link})` : b.data.text,
2556
3462
  delimiter: () => "---",
3463
+ math: (b) => b.data.tex.trim(),
2557
3464
  toc: (b) => {
2558
3465
  const tree = buildTocTree(b.headings || [], b.data);
2559
3466
  if (!tree.length) return "";
@@ -2564,15 +3471,29 @@ var registeredText = (block) => {
2564
3471
  const { definition } = block;
2565
3472
  if (definition.text) {
2566
3473
  try {
2567
- const out = definition.text(block.data, { text: (html) => inlineToText(html) });
3474
+ const out = definition.text(block.data, { text: (html) => inlineToText2(html) });
2568
3475
  if (typeof out === "string") return out;
2569
3476
  } catch {
2570
3477
  }
2571
3478
  }
2572
- return definition.fields(block.data).map((field) => (field.kind === "html" ? inlineToText(field.value) : field.value).trim()).filter(Boolean).join("\n");
3479
+ return definition.fields(block.data).map((field) => (field.kind === "html" ? inlineToText2(field.value) : field.value).trim()).filter(Boolean).join("\n");
2573
3480
  };
2574
3481
  var renderText = (value, options = {}) => {
2575
3482
  const opts = options && typeof options === "object" ? options : {};
3483
+ const previous = notes;
3484
+ notes = { numbers: createFootnoteNumbers(), items: [] };
3485
+ try {
3486
+ const text = renderContent(value, opts);
3487
+ if (!notes.items.length) return text;
3488
+ const list = notes.items.map(
3489
+ (item) => `[${item.n}] ${nodesToText(item.note).replace(/\u00a0/g, " ").trim().replace(/\n/g, "\n ")}`.trimEnd()
3490
+ );
3491
+ return [text, [footnoteOptions(opts).label, ...list].join("\n")].filter(Boolean).join("\n\n");
3492
+ } finally {
3493
+ notes = previous;
3494
+ }
3495
+ };
3496
+ var renderContent = (value, opts) => {
2576
3497
  const render = (blocks) => blocks.map((block) => {
2577
3498
  const override = overrideFor(opts, block.type);
2578
3499
  if (override) {
@@ -2584,18 +3505,37 @@ var renderText = (value, options = {}) => {
2584
3505
  tunes: block.tunes,
2585
3506
  children: block.children
2586
3507
  },
2587
- { text: (html) => inlineToText(html), renderChildren: render }
3508
+ { text: (html) => inlineToText2(html), renderChildren: render }
2588
3509
  );
2589
3510
  if (typeof out === "string") return out;
2590
3511
  }
2591
3512
  if (block.known) return RENDERERS2[block.type](block, opts, render);
2592
3513
  if (block.definition) return registeredText(block);
2593
- return scalarFields(block.data).map(([, v]) => inlineToText(v).trim()).filter(Boolean).join("\n");
3514
+ return scalarFields(block.data).map(([, v]) => inlineToText2(v).trim()).filter(Boolean).join("\n");
2594
3515
  }).map((text) => String(text).replace(/\u00a0/g, " ")).filter((text) => text.trim() !== "").join("\n\n");
2595
3516
  return render(annotateHeadings(prepareBlocks(value, opts), opts));
2596
3517
  };
2597
3518
 
2598
3519
  // shared/render/markdown.mjs
3520
+ var notes2 = null;
3521
+ var mathSource = (tex) => tex.replace(/<(?=[A-Za-z/!?])/g, "< ");
3522
+ var dollarFence = (text, min) => "$".repeat(Math.max(min, ...(text.match(/\$+/g) || []).map((run) => run.length + 1)));
3523
+ var inlineMath = (tex) => {
3524
+ const text = mathSource(tex.replace(/\s*\n\s*/g, " ").trim());
3525
+ if (!text) return "";
3526
+ const fence2 = dollarFence(text, 1);
3527
+ return `${fence2}${text}${fence2}`;
3528
+ };
3529
+ var displayMath = (tex) => {
3530
+ const text = mathSource(
3531
+ tex.split("\n").filter((line) => line.trim()).join("\n").trim()
3532
+ );
3533
+ if (!text) return "";
3534
+ const fence2 = dollarFence(text, 2);
3535
+ return `${fence2}
3536
+ ${text}
3537
+ ${fence2}`;
3538
+ };
2599
3539
  var escapeMarkdown = (text) => String(text).replace(/\u00a0/g, " ").replace(/[\\`*_[\]<>|~&{}]/g, (char) => `\\${char}`).replace(
2600
3540
  /(^|\n)(\s*)([#>+=-]|\d{1,9}[.)])/g,
2601
3541
  (_m, nl, space, mark) => `${nl}${space}${mark.replace(/^(\d*)([#>+=.)-])$/, "$1\\$2")}`
@@ -2605,8 +3545,8 @@ var linkUrl = (url) => String(url).replace(
2605
3545
  (char) => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`
2606
3546
  );
2607
3547
  var linkTitle = (title) => {
2608
- const clean = String(title || "").replace(/\s+/g, " ").trim();
2609
- return clean ? ` "${clean.replace(/[\\"<>]/g, (char) => `\\${char}`)}"` : "";
3548
+ const clean2 = String(title || "").replace(/\s+/g, " ").trim();
3549
+ return clean2 ? ` "${clean2.replace(/[\\"<>]/g, (char) => `\\${char}`)}"` : "";
2610
3550
  };
2611
3551
  var wrap = (marker, inner) => {
2612
3552
  const match = /^(\s*)([\s\S]*?)(\s*)$/.exec(inner);
@@ -2624,6 +3564,14 @@ var codeSpan = (code) => {
2624
3564
  var rawText = (nodes) => nodes.map((n) => n.type === "text" ? n.value : n.tag === "br" ? "\n" : rawText(n.children)).join("");
2625
3565
  var nodesToMarkdown = (nodes, options) => nodes.map((node) => {
2626
3566
  if (node.type === "text") return escapeMarkdown(node.value);
3567
+ if (isMathNode(node)) return inlineMath(nodesToText(node.children));
3568
+ if (isFootnoteNode(node)) {
3569
+ if (!notes2) return "";
3570
+ const { n } = notes2.numbers.add(node.attrs["data-mex-footnote"]);
3571
+ const label3 = `${notes2.prefix}${n}`;
3572
+ notes2.items.push({ label: label3, note: node.note || [] });
3573
+ return `[^${label3}]`;
3574
+ }
2627
3575
  const inner = () => nodesToMarkdown(node.children, options);
2628
3576
  switch (node.tag) {
2629
3577
  case "br":
@@ -2667,14 +3615,26 @@ ${childIndent}`);
2667
3615
  });
2668
3616
  return lines;
2669
3617
  };
2670
- var fence = (code, language) => {
3618
+ var fence = (code, language, filename) => {
3619
+ const valid = language && /^[a-z0-9+#-]{1,32}$/i.test(language);
3620
+ if (filename) return titledFence(code, valid ? language : "plaintext", filename);
2671
3621
  const longest = Math.max(2, ...(code.match(/`{3,}/g) || []).map((run) => run.length));
2672
3622
  const marks = "`".repeat(longest + 1);
2673
- const info = language && /^[a-z0-9+#-]{1,32}$/i.test(language) && language !== "plaintext" ? language : "";
3623
+ const info = valid && language !== "plaintext" ? language : "";
2674
3624
  return `${marks}${info}
2675
3625
  ${code.replace(/\n$/, "")}
2676
3626
  ${marks}`;
2677
3627
  };
3628
+ var ALIGN_RULES = Object.freeze({ left: ":---", center: ":---:", right: "---:" });
3629
+ var titledFence = (code, language, filename) => {
3630
+ const char = filename.includes("`") ? "~" : "`";
3631
+ const runs = code.match(char === "`" ? /`{3,}/g : /~{3,}/g) || [];
3632
+ const marks = char.repeat(Math.max(2, ...runs.map((run) => run.length)) + 1);
3633
+ const title = filename.replace(/[\\"]/g, (ch) => `\\${ch}`);
3634
+ return `${marks}${language} title="${title}"
3635
+ ${code.replace(/\n$/, "")}
3636
+ ${marks}`;
3637
+ };
2678
3638
  var cell = (html, options) => oneLine(md(html, options)) || " ";
2679
3639
  var RENDERERS3 = {
2680
3640
  paragraph: (b, o) => md(b.data.text, o),
@@ -2710,7 +3670,7 @@ var RENDERERS3 = {
2710
3670
  },
2711
3671
  toggle: (b, o, render) => [b.data.text ? `**${oneLine(md(b.data.text, o))}**` : "", render(b.children)].filter(Boolean).join("\n\n"),
2712
3672
  code: (b) => b.data.code ? fence(b.data.code) : "",
2713
- codeFlask: (b) => b.data.code ? fence(b.data.code, b.data.language) : "",
3673
+ codeFlask: (b) => b.data.code || b.data.filename ? fence(b.data.code, b.data.language, b.data.filename || "") : "",
2714
3674
  raw: (b, o) => {
2715
3675
  if (o.rawHtml !== "allow" || typeof o.sanitizeRaw !== "function") return "";
2716
3676
  const html = o.sanitizeRaw(String(b.raw.html || ""));
@@ -2723,11 +3683,16 @@ var RENDERERS3 = {
2723
3683
  const line = (row) => `| ${Array.from({ length: width }, (_, i) => cell(row[i] || "", o)).join(" | ")} |`;
2724
3684
  const head = b.data.withHeadings ? rows[0] : [];
2725
3685
  const body = b.data.withHeadings ? rows.slice(1) : rows;
2726
- return [
3686
+ const align = Array.isArray(b.data.align) ? b.data.align : [];
3687
+ const table = [
2727
3688
  line(head),
2728
- `| ${Array.from({ length: width }, () => "---").join(" | ")} |`,
3689
+ `| ${Array.from({ length: width }, (_, i) => ALIGN_RULES[align[i]] || "---").join(" | ")} |`,
2729
3690
  ...body.map(line)
2730
3691
  ].join("\n");
3692
+ const caption = b.data.caption ? oneLine(md(b.data.caption, o)) : "";
3693
+ return caption ? `${caption}
3694
+
3695
+ ${table}` : table;
2731
3696
  },
2732
3697
  image: (b, o) => {
2733
3698
  const file = resolveMedia(b.data.file, b, o);
@@ -2779,6 +3744,7 @@ var RENDERERS3 = {
2779
3744
  return b.data.link ? `[${escapeMarkdown(b.data.text)}](${linkUrl(b.data.link)})` : escapeMarkdown(b.data.text);
2780
3745
  },
2781
3746
  delimiter: () => "---",
3747
+ math: (b) => b.data.display === false ? inlineMath(b.data.tex) : displayMath(b.data.tex),
2782
3748
  toc: (b) => {
2783
3749
  const tree = buildTocTree(b.headings || [], b.data);
2784
3750
  if (!tree.length) return "";
@@ -2820,6 +3786,22 @@ var registeredMarkdown = (block, opts) => {
2820
3786
  };
2821
3787
  var renderMarkdown = (value, options = {}) => {
2822
3788
  const opts = options && typeof options === "object" ? options : {};
3789
+ const previous = notes2;
3790
+ const prefix = opts.footnotes && typeof opts.footnotes === "object" && typeof opts.footnotes.prefix === "string" ? footnoteOptions(opts).prefix : "";
3791
+ notes2 = { numbers: createFootnoteNumbers(), items: [], prefix };
3792
+ try {
3793
+ const markdown = renderContent2(value, opts);
3794
+ if (!notes2.items.length) return markdown;
3795
+ const definitions = notes2.items.map((item) => {
3796
+ const body = nodesToMarkdown(item.note, opts).trim().replace(/\n/g, "\n ");
3797
+ return `[^${item.label}]: ${body}`.trimEnd();
3798
+ });
3799
+ return [markdown, definitions.join("\n")].filter(Boolean).join("\n\n");
3800
+ } finally {
3801
+ notes2 = previous;
3802
+ }
3803
+ };
3804
+ var renderContent2 = (value, opts) => {
2823
3805
  const render = (blocks) => blocks.map((block) => {
2824
3806
  const override = overrideFor(opts, block.type);
2825
3807
  if (override) {