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
@@ -58,7 +58,9 @@ var MARKED_BLOCKS = Object.freeze({
58
58
  keys: Object.freeze(["file", "title", "caption", "loop", "tracks"]),
59
59
  anchor: Object.freeze(["file", "object"])
60
60
  }),
61
- synced: Object.freeze({ keys: Object.freeze(["ref"]), anchor: Object.freeze(["ref", "string"]) })
61
+ synced: Object.freeze({ keys: Object.freeze(["ref"]), anchor: Object.freeze(["ref", "string"]) }),
62
+ // 2.4: math block. A Settings custom block named `math` could exist before 2.4.
63
+ math: Object.freeze({ keys: Object.freeze(["tex", "display"]), anchor: Object.freeze(["tex", "string"]) })
62
64
  });
63
65
  var isBuiltInMarker = (value) => Number.isInteger(value) && /** @type {number} */
64
66
  value >= 1;
@@ -77,6 +79,10 @@ var isMarkedBuiltIn = (type, data) => {
77
79
  return hasBuiltInShape(MARKED_BLOCKS[type], data);
78
80
  };
79
81
 
82
+ // shared/field-identity.mjs
83
+ var FIELD_KEY_PATTERN = /^[A-Za-z0-9_-]{16,32}$/;
84
+ var isValidFieldKey = (value) => typeof value === "string" && FIELD_KEY_PATTERN.test(value);
85
+
80
86
  // shared/editor-data.mjs
81
87
  var EDITOR_DATA_LIMITS = Object.freeze({
82
88
  maxBlocks: 5e3,
@@ -189,8 +195,8 @@ var normalizeEditorData = (value) => {
189
195
  if (!isPlainObject2(candidate)) {
190
196
  throw new EditorDataError("Editor content must be an Editor.js object", "INVALID_SHAPE");
191
197
  }
192
- const clean = cloneJsonSafe(candidate);
193
- const rawBlocks = Array.isArray(clean.blocks) ? clean.blocks : [];
198
+ const clean2 = cloneJsonSafe(candidate);
199
+ const rawBlocks = Array.isArray(clean2.blocks) ? clean2.blocks : [];
194
200
  if (rawBlocks.length > EDITOR_DATA_LIMITS.maxBlocks) {
195
201
  throw new EditorDataError("Editor content has too many blocks", "TOO_MANY_BLOCKS");
196
202
  }
@@ -209,9 +215,10 @@ var normalizeEditorData = (value) => {
209
215
  if (isPlainObject2(block.tunes) && Object.keys(block.tunes).length > 0) normalized.tunes = block.tunes;
210
216
  blocks.push(normalized);
211
217
  });
212
- const time = Number.isFinite(clean.time) && clean.time > 0 ? Math.floor(clean.time) : 0;
213
- const version = typeof clean.version === "string" && clean.version.length <= 32 ? clean.version : "2.31.7";
218
+ const time = Number.isFinite(clean2.time) && clean2.time > 0 ? Math.floor(clean2.time) : 0;
219
+ const version = typeof clean2.version === "string" && clean2.version.length <= 32 ? clean2.version : "2.31.7";
214
220
  const result = { time, blocks, version };
221
+ if (isValidFieldKey(clean2.fieldKey)) result.fieldKey = clean2.fieldKey;
215
222
  const size = byteLength(JSON.stringify(result));
216
223
  if (size > EDITOR_DATA_LIMITS.maxBytes) {
217
224
  throw new EditorDataError("Editor content exceeds the size limit", "TOO_LARGE");
@@ -239,6 +246,95 @@ var byteLength = (text) => {
239
246
  return bytes;
240
247
  };
241
248
 
249
+ // shared/table.mjs
250
+ var TABLE_LIMITS = Object.freeze({ rows: 500, cols: 100, merges: 1e3, caption: 4e3 });
251
+ var TABLE_ALIGNS = Object.freeze(["left", "center", "right"]);
252
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
253
+ var tableWidth = (content) => Array.isArray(content) ? content.reduce((width, row) => Math.max(width, Array.isArray(row) ? row.length : 0), 0) : 0;
254
+ var cleanTableAlign = (value, cols) => {
255
+ if (!Array.isArray(value) || cols <= 0) return null;
256
+ const out = value.slice(0, Math.min(cols, TABLE_LIMITS.cols)).map((item) => typeof item === "string" && TABLE_ALIGNS.includes(item) ? item : null);
257
+ while (out.length && out[out.length - 1] === null) out.pop();
258
+ return out.length ? out : null;
259
+ };
260
+ var intersects = (a, b) => a.row < b.row + b.rowspan && b.row < a.row + a.rowspan && a.col < b.col + b.colspan && b.col < a.col + a.colspan;
261
+ var normalizeMerges = (merges, rows, cols, options = {}) => {
262
+ if (!Array.isArray(merges) || rows <= 0 || cols <= 0) return [];
263
+ const out = [];
264
+ for (const merge of merges.slice(0, TABLE_LIMITS.merges)) {
265
+ if (!isObject(merge)) continue;
266
+ const { row, col, rowspan, colspan } = merge;
267
+ if (![row, col, rowspan, colspan].every(Number.isInteger)) continue;
268
+ if (row < 0 || col < 0 || rowspan < 1 || colspan < 1 || rowspan * colspan < 2) continue;
269
+ if (row + rowspan > rows || col + colspan > cols) continue;
270
+ if (options.headerRow && row === 0 && rowspan > 1) continue;
271
+ const next = { row, col, rowspan, colspan };
272
+ if (out.some((other) => intersects(other, next))) continue;
273
+ out.push(next);
274
+ }
275
+ return out.sort((a, b) => a.row - b.row || a.col - b.col);
276
+ };
277
+ var mergeMap = (merges) => {
278
+ const anchors = /* @__PURE__ */ new Map();
279
+ const covered = /* @__PURE__ */ new Map();
280
+ for (const merge of merges || []) {
281
+ anchors.set(`${merge.row}:${merge.col}`, merge);
282
+ for (let r = merge.row; r < merge.row + merge.rowspan; r += 1)
283
+ for (let c = merge.col; c < merge.col + merge.colspan; c += 1)
284
+ if (r !== merge.row || c !== merge.col) covered.set(`${r}:${c}`, merge);
285
+ }
286
+ return { anchors, covered };
287
+ };
288
+ var headerKind = (data, row, col) => {
289
+ if (data.withHeadings === true && row === 0) return "col";
290
+ if (data.headerColumn === true && col === 0) return "row";
291
+ return null;
292
+ };
293
+ var tableLayout = (data) => {
294
+ const merges = Array.isArray(data.merges) ? data.merges : [];
295
+ const { anchors, covered } = mergeMap(merges);
296
+ const align = Array.isArray(data.align) ? data.align : [];
297
+ return (data.content || []).map(
298
+ (row, r) => row.map((html, c) => {
299
+ if (covered.has(`${r}:${c}`)) return null;
300
+ const merge = anchors.get(`${r}:${c}`);
301
+ return {
302
+ row: r,
303
+ col: c,
304
+ html,
305
+ rowspan: merge ? merge.rowspan : 1,
306
+ colspan: merge ? merge.colspan : 1,
307
+ header: headerKind(data, r, c),
308
+ align: typeof align[c] === "string" ? align[c] : null
309
+ };
310
+ }).filter(Boolean)
311
+ );
312
+ };
313
+ var isBlankInlineHtml = (html) => typeof html !== "string" || /^(?:\s|&nbsp;|&#160;|\u00a0|<br\s*\/?>)*$/i.test(html);
314
+ var cleanTableExtras = (out, d, inline) => {
315
+ if (d.headerColumn === true) out.headerColumn = true;
316
+ const rows = out.content.length;
317
+ const cols = tableWidth(out.content);
318
+ const align = cleanTableAlign(d.align, cols);
319
+ if (align) out.align = align;
320
+ const merges = normalizeMerges(d.merges, rows, cols, { headerRow: out.withHeadings === true });
321
+ if (merges.length) {
322
+ const { covered } = mergeMap(merges);
323
+ out.content = out.content.map(
324
+ (row, r) => Array.from(
325
+ { length: cols },
326
+ (_, c) => covered.has(`${r}:${c}`) ? "" : row[c] === void 0 ? "" : row[c]
327
+ )
328
+ );
329
+ out.merges = merges;
330
+ }
331
+ if (typeof d.caption === "string") {
332
+ const caption = inline(d.caption.slice(0, TABLE_LIMITS.caption));
333
+ if (!isBlankInlineHtml(caption)) out.caption = caption;
334
+ }
335
+ return out;
336
+ };
337
+
242
338
  // shared/sanitize-policy.mjs
243
339
  var INLINE_TAGS = Object.freeze([
244
340
  "b",
@@ -282,10 +378,21 @@ var cleanInternalLinkAttributes = (attribs) => {
282
378
  var isMentionLink = (attrs) => Boolean(
283
379
  attrs && attrs["data-mex-mention"] === "true" && attrs["data-mex-uid"] && attrs["data-mex-document-id"]
284
380
  );
381
+ var MATH_ATTRIBUTE = "data-mex-math";
382
+ var FOOTNOTE_ATTRIBUTES = Object.freeze(["data-mex-footnote", "data-mex-note"]);
383
+ var FOOTNOTE_ID = /^[A-Za-z0-9_-]{1,64}$/;
384
+ var MAX_MATH_TEX = 1e4;
385
+ var MAX_INLINE_TEX = 2e3;
386
+ var MAX_FOOTNOTE_NOTE = 4e3;
387
+ var INLINE_FORMAT_ATTRIBUTES = Object.freeze({
388
+ span: ["data-mex-color", "data-mex-annotation", "data-mex-a-*"],
389
+ mark: ["data-mex-highlight"]
390
+ });
285
391
  var INLINE_ATTRIBUTES = Object.freeze({
286
392
  a: ["href", "target", "rel", "title", ...INTERNAL_LINK_ATTRIBUTES],
287
- span: ["class", "data-tooltip"],
288
- mark: ["class"],
393
+ span: ["class", "data-tooltip", MATH_ATTRIBUTE, ...INLINE_FORMAT_ATTRIBUTES.span],
394
+ sup: [...FOOTNOTE_ATTRIBUTES],
395
+ mark: ["class", ...INLINE_FORMAT_ATTRIBUTES.mark],
289
396
  u: ["class"],
290
397
  s: ["class"],
291
398
  code: ["class"]
@@ -367,17 +474,17 @@ var mediaTracks = (tracks) => {
367
474
  if (!isPlainObject2(track)) continue;
368
475
  const file = cleanMediaFile(track.file, { vtt: true });
369
476
  if (!file.url) continue;
370
- const clean = {
477
+ const clean2 = {
371
478
  file,
372
479
  kind: oneOf(track.kind, TRACK_KINDS, "captions"),
373
480
  srclang: typeof track.srclang === "string" && SRCLANG.test(track.srclang) ? track.srclang : "",
374
481
  label: plain(track.label, 100)
375
482
  };
376
483
  if (track.default === true && !hasDefault) {
377
- clean.default = true;
484
+ clean2.default = true;
378
485
  hasDefault = true;
379
486
  }
380
- out.push(clean);
487
+ out.push(clean2);
381
488
  }
382
489
  return out;
383
490
  };
@@ -420,6 +527,17 @@ var listItems = (items, inline, depth = 0) => {
420
527
  return out;
421
528
  });
422
529
  };
530
+ var MAX_CODE_FILENAME = 200;
531
+ var FILENAME_STRIP = (
532
+ // eslint-disable-next-line no-control-regex -- the point is to remove control characters
533
+ /[\u0000-\u001f\u007f-\u009f\u061c\u200b-\u200f\u2028-\u202e\u2060\u2066-\u2069\ufeff]/g
534
+ );
535
+ var cleanCodeFilename = (value) => {
536
+ if (typeof value !== "string") return "";
537
+ return Array.from(
538
+ value.slice(0, 4 * MAX_CODE_FILENAME).replace(/[\t\n\r\f\v]/g, " ").replace(FILENAME_STRIP, "").replace(/\s+/g, " ").trim()
539
+ ).slice(0, MAX_CODE_FILENAME).join("").trim();
540
+ };
423
541
  var BLOCK_POLICIES = {
424
542
  paragraph: (d, inline) => ({ text: inline(d.text) }),
425
543
  header: (d, inline) => ({ text: inline(d.text), level: int(d.level, 1, 6, 2) }),
@@ -474,6 +592,8 @@ var BLOCK_POLICIES = {
474
592
  language: typeof d.language === "string" && /^[a-z0-9+#-]{1,32}$/i.test(d.language) ? d.language : "plaintext"
475
593
  };
476
594
  if (typeof d.showlinenumbers === "boolean") out.showlinenumbers = d.showlinenumbers;
595
+ const filename = cleanCodeFilename(d.filename);
596
+ if (filename) out.filename = filename;
477
597
  return out;
478
598
  },
479
599
  raw: (d, _inline, ctx) => {
@@ -482,11 +602,18 @@ var BLOCK_POLICIES = {
482
602
  if (ctx.rawHtml === "disable") return { html: "" };
483
603
  return { html: ctx.rawSanitizer(html) };
484
604
  },
485
- table: (d, inline) => ({
486
- withHeadings: bool(d.withHeadings),
487
- stretched: bool(d.stretched),
488
- content: Array.isArray(d.content) ? d.content.slice(0, 500).map((row) => Array.isArray(row) ? row.slice(0, 100).map((cell) => inline(cell)) : []) : []
489
- }),
605
+ // 2.4: optional header column, column alignment, merged cells and caption (shared/table.mjs).
606
+ table: (d, inline) => cleanTableExtras(
607
+ {
608
+ withHeadings: bool(d.withHeadings),
609
+ stretched: bool(d.stretched),
610
+ content: Array.isArray(d.content) ? d.content.slice(0, TABLE_LIMITS.rows).map(
611
+ (row) => Array.isArray(row) ? row.slice(0, TABLE_LIMITS.cols).map((cell) => inline(cell)) : []
612
+ ) : []
613
+ },
614
+ d,
615
+ inline
616
+ ),
490
617
  image: (d, inline) => {
491
618
  const file = isPlainObject2(d.file) ? d.file : {};
492
619
  const cleanFile = { url: sanitizeUrl(file.url, { schemes: ["http", "https"] }) };
@@ -582,6 +709,9 @@ var BLOCK_POLICIES = {
582
709
  if (typeof file.extension === "string") cleanFile.extension = plain(file.extension, 16);
583
710
  if (Number.isFinite(file.size)) cleanFile.size = file.size;
584
711
  if (typeof file.title === "string") cleanFile.title = plain(file.title, 255);
712
+ if (file.id !== void 0 && (Number.isInteger(file.id) || typeof file.id === "string"))
713
+ cleanFile.id = file.id;
714
+ if (typeof file.documentId === "string") cleanFile.documentId = plain(file.documentId, 64);
585
715
  return { file: cleanFile, title: plain(d.title, 255) };
586
716
  },
587
717
  embed: (d, inline) => ({
@@ -610,6 +740,12 @@ var BLOCK_POLICIES = {
610
740
  ref: typeof d.ref === "string" && /^[a-z0-9]{1,64}$/.test(d.ref) ? d.ref : "",
611
741
  _mex: BUILT_IN_MARKER_VERSION
612
742
  }),
743
+ // Math block (2.4): only the TeX source is stored; `display: false` renders it in text style.
744
+ math: (d) => ({
745
+ tex: plain(d.tex, MAX_MATH_TEX),
746
+ display: d.display !== false,
747
+ _mex: BUILT_IN_MARKER_VERSION
748
+ }),
613
749
  toc: (d) => {
614
750
  const minLevel = int(d.minLevel, 1, 6, 2);
615
751
  const maxLevel = int(d.maxLevel, 1, 6, 4);
@@ -673,13 +809,13 @@ var ATTRIBUTE_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
673
809
  var isSafeAttributeName = (name) => ATTRIBUTE_NAME.test(name) && !name.startsWith("on") && name !== "style" && name !== "srcdoc";
674
810
  var textNode = (value) => ({ type: "text", value: String(value ?? "") });
675
811
  var el = (tag, attrs, children) => {
676
- const clean = {};
812
+ const clean2 = {};
677
813
  for (const [name, value] of Object.entries(attrs || {})) {
678
814
  if (value === void 0 || value === null || value === false) continue;
679
815
  if (value === "" && name !== "alt") continue;
680
- clean[name] = value === true ? true : String(value);
816
+ clean2[name] = value === true ? true : String(value);
681
817
  }
682
- return { type: "element", tag, attrs: clean, children: toNodes(children) };
818
+ return { type: "element", tag, attrs: clean2, children: toNodes(children) };
683
819
  };
684
820
  var toNodes = (children) => {
685
821
  const out = [];
@@ -733,763 +869,1486 @@ var nodesTextContent = (nodes) => {
733
869
  return out;
734
870
  };
735
871
 
736
- // shared/render/inline.mjs
737
- var DROP_WITH_CONTENT = /* @__PURE__ */ new Set([
738
- "script",
739
- "style",
740
- "textarea",
741
- "title",
742
- "xmp",
743
- "noscript",
744
- "noembed",
745
- "noframes",
746
- "template",
747
- "iframe",
748
- "object",
749
- "embed",
750
- "svg",
751
- "math",
752
- "select",
753
- "option",
754
- "plaintext"
872
+ // shared/inline-format.mjs
873
+ var TOKEN_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;
874
+ var COLOR_ATTRIBUTE = "data-mex-color";
875
+ var HIGHLIGHT_ATTRIBUTE = "data-mex-highlight";
876
+ var PALETTE_LIMITS = Object.freeze({ tokens: 24, label: 60, locales: 20 });
877
+ var DEFAULT_SURFACE = Object.freeze({
878
+ background: Object.freeze({ light: "#ffffff", dark: "#121212" }),
879
+ text: Object.freeze({ light: "#1f1f1f", dark: "#f2f2f2" })
880
+ });
881
+ var colorClass = (token) => `mex-color-${token}`;
882
+ var highlightClass = (token) => `mex-highlight-${token}`;
883
+
884
+ // shared/blocks/define.mjs
885
+ var BLOCK_FIELD_TYPES = Object.freeze([
886
+ "text",
887
+ "inline",
888
+ "url",
889
+ "enum",
890
+ "number",
891
+ "boolean",
892
+ "array",
893
+ "object"
755
894
  ]);
756
- var ALLOWED = new Set(INLINE_TAGS);
757
- var VOID = /* @__PURE__ */ new Set(["br"]);
758
- var MAX_INPUT = 5e5;
759
- var MAX_NODES = 5e4;
760
- var MAX_DEPTH = 64;
761
- var NAMED_ENTITIES = Object.freeze({
762
- amp: "&",
763
- lt: "<",
764
- gt: ">",
765
- quot: '"',
766
- apos: "'",
767
- nbsp: "\xA0",
768
- shy: "\xAD",
769
- copy: "\xA9",
770
- reg: "\xAE",
771
- trade: "\u2122",
772
- hellip: "\u2026",
773
- mdash: "\u2014",
774
- ndash: "\u2013",
775
- lsquo: "\u2018",
776
- rsquo: "\u2019",
777
- ldquo: "\u201C",
778
- rdquo: "\u201D",
779
- laquo: "\xAB",
780
- raquo: "\xBB",
781
- euro: "\u20AC",
782
- middot: "\xB7",
783
- bull: "\u2022",
784
- times: "\xD7",
785
- deg: "\xB0",
786
- tab: " ",
787
- newline: "\n",
788
- colon: ":",
789
- sol: "/",
790
- lpar: "(",
791
- rpar: ")"
895
+ var BLOCK_LIMITS = Object.freeze({
896
+ /** Fields per object (also the schema root). */
897
+ maxFields: 50,
898
+ /** Nesting of arrays and objects below the root. */
899
+ maxDepth: 4,
900
+ /** Largest `max` of a text or inline field. */
901
+ maxText: 1e5,
902
+ /** Default `max` of a text field. */
903
+ defaultText: 1e3,
904
+ /** Default `max` of an inline HTML field. */
905
+ defaultInline: 1e4,
906
+ /** Largest `max` of an array field. */
907
+ maxItems: 500,
908
+ /** Default `max` of an array field. */
909
+ defaultItems: 50,
910
+ /** Values of an enum field. */
911
+ maxEnumValues: 100,
912
+ /** Values cleaned per block; later array items are dropped. */
913
+ maxValues: 2e4,
914
+ /** Length of a URL value. */
915
+ maxUrl: 2048
792
916
  });
793
- var decodeEntities = (text) => String(text).replace(
794
- /&(#[xX][0-9a-fA-F]{1,8}|#[0-9]{1,10}|[A-Za-z][A-Za-z0-9]{1,31});?/g,
795
- (match, body) => {
796
- if (body[0] === "#") {
797
- const code = body[1] === "x" || body[1] === "X" ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
798
- if (!Number.isFinite(code) || code <= 0 || code > 1114111 || code >= 55296 && code <= 57343)
799
- return "\uFFFD";
800
- return String.fromCodePoint(code);
801
- }
802
- const named = NAMED_ENTITIES[body] ?? NAMED_ENTITIES[body.toLowerCase()];
803
- return named === void 0 ? match : named;
804
- }
805
- );
806
- var parseAttributes = (source) => {
807
- const out = {};
808
- const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
809
- let match;
810
- while (match = pattern.exec(source)) {
811
- const name = match[1].toLowerCase();
812
- if (Object.prototype.hasOwnProperty.call(out, name)) continue;
813
- const raw = match[2] ?? match[3] ?? match[4] ?? "";
814
- out[name] = decodeEntities(raw);
815
- }
816
- return out;
917
+ var BLOCK_PRESETS = Object.freeze(["article", "basic", "minimal"]);
918
+ var RESERVED_BLOCK_NAMES = Object.freeze([
919
+ "paragraph",
920
+ "header",
921
+ "list",
922
+ "checklist",
923
+ "quote",
924
+ "warning",
925
+ "alert",
926
+ "toggle",
927
+ "code",
928
+ "codeFlask",
929
+ "delimiter",
930
+ "toc",
931
+ "synced",
932
+ "table",
933
+ "embed",
934
+ "raw",
935
+ "image",
936
+ "simpleImage",
937
+ "gallery",
938
+ "video",
939
+ "audio",
940
+ "linkTool",
941
+ "attaches",
942
+ "personality",
943
+ "button",
944
+ "mediaLib",
945
+ "embeddedEntry",
946
+ "bold",
947
+ "italic",
948
+ "hyperlink",
949
+ "mention",
950
+ "marker",
951
+ "underline",
952
+ "strikethrough",
953
+ "inlineCode",
954
+ "tooltip",
955
+ "aiAssistant",
956
+ "alignmentTune",
957
+ "textVariant",
958
+ "indentTune"
959
+ ]);
960
+ var SDK_COMPATIBLE_NAMES = Object.freeze(["math"]);
961
+ var RESERVED = new Set(RESERVED_BLOCK_NAMES.map((name) => name.toLowerCase()));
962
+ var BLOCK_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{1,49}$/;
963
+ var KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
964
+ var FORBIDDEN_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
965
+ var DEFINITION_KEYS = /* @__PURE__ */ new Set([
966
+ "name",
967
+ "version",
968
+ "title",
969
+ "description",
970
+ "schema",
971
+ "sanitize",
972
+ "text",
973
+ "markdown",
974
+ "render",
975
+ "presets"
976
+ ]);
977
+ var FIELD_KEYS = {
978
+ text: ["max", "multiline", "default"],
979
+ inline: ["max", "default"],
980
+ url: ["schemes", "relative"],
981
+ enum: ["values", "default"],
982
+ number: ["min", "max", "integer", "default"],
983
+ boolean: ["default"],
984
+ array: ["items", "max"],
985
+ object: ["fields"]
817
986
  };
818
- var findTagEnd = (html, from) => {
819
- let quote = "";
820
- for (let i = from; i < html.length; i += 1) {
821
- const char = html[i];
822
- if (quote) {
823
- if (char === quote) quote = "";
824
- } else if (char === '"' || char === "'") quote = char;
825
- else if (char === ">") return i;
987
+ var BlockDefinitionError = class extends Error {
988
+ /**
989
+ * @param {string} message - Message naming the definition and the problem.
990
+ * @param {string} [code] - `INVALID_DEFINITION` | `RESERVED_NAME` | `NAME_TAKEN` | `REGISTRY_SEALED`.
991
+ */
992
+ constructor(message, code = "INVALID_DEFINITION") {
993
+ super(message);
994
+ this.name = "BlockDefinitionError";
995
+ this.code = code;
826
996
  }
827
- return -1;
828
997
  };
829
- var cleanAttributes = (tag, attribs) => {
830
- const allowed = INLINE_ATTRIBUTES[tag] || [];
831
- const out = {};
832
- for (const name of allowed) {
833
- if (!Object.prototype.hasOwnProperty.call(attribs, name) || name.startsWith("data-mex-")) continue;
834
- const value = attribs[name];
835
- if (name === "href") {
836
- const url = sanitizeUrl(value);
837
- if (url) out.href = url;
838
- } else if (name === "target") {
839
- const target = sanitizeTarget(value);
840
- if (target) out.target = target;
841
- } else if (name === "rel") {
842
- const rel = String(value).split(/\s+/).filter((token) => /^[a-z-]{1,20}$/.test(token));
843
- if (rel.length) out.rel = rel.join(" ");
844
- } else if (name === "class") {
845
- const classes2 = String(value).split(/\s+/).filter((token) => (INLINE_CLASSES[tag] || []).includes(token));
846
- if (classes2.length) out.class = classes2.join(" ");
847
- } else {
848
- out[name] = String(value).slice(0, 2e3);
849
- }
850
- }
851
- if (tag === "a") Object.assign(out, cleanInternalLinkAttributes(attribs));
852
- return out;
998
+ var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
999
+ var fail = (where, message) => {
1000
+ throw new BlockDefinitionError(`Magic Editor X block ${where}: ${message}`);
853
1001
  };
854
- var parseInline = (input) => {
855
- const html = typeof input === "string" ? input.slice(0, MAX_INPUT) : "";
856
- const root = { type: "element", tag: "#root", attrs: {}, children: [] };
857
- const stack = [root];
858
- let nodes = 0;
859
- let text = "";
860
- const flush = () => {
861
- if (!text) return;
862
- const parent = stack[stack.length - 1];
863
- const last = parent.children[parent.children.length - 1];
864
- const value = decodeEntities(text);
865
- if (last && last.type === "text") last.value += value;
866
- else if (nodes < MAX_NODES) {
867
- parent.children.push({ type: "text", value });
868
- nodes += 1;
869
- }
870
- text = "";
871
- };
872
- let i = 0;
873
- while (i < html.length) {
874
- const lt = html.indexOf("<", i);
875
- if (lt === -1) {
876
- text += html.slice(i);
1002
+ var boundedInt = (value, min, max, fallback, where, key) => {
1003
+ if (value === void 0) return fallback;
1004
+ if (!Number.isInteger(value) || value < min || value > max)
1005
+ fail(where, `"${key}" must be an integer from ${min} to ${max}`);
1006
+ return value;
1007
+ };
1008
+ var normalizeField = (input, where, depth) => {
1009
+ if (!isObject2(input)) fail(where, 'a field must be an object with a "type"');
1010
+ const type = input.type;
1011
+ if (!BLOCK_FIELD_TYPES.includes(type)) fail(where, `unknown field type ${JSON.stringify(type)}`);
1012
+ for (const key of Object.keys(input))
1013
+ if (key !== "type" && key !== "label" && !FIELD_KEYS[type].includes(key))
1014
+ fail(where, `unknown option "${key}" for a ${type} field`);
1015
+ const out = { type };
1016
+ if (input.label !== void 0) {
1017
+ if (typeof input.label !== "string" || input.label.length > 100)
1018
+ fail(where, '"label" must be a string of at most 100 characters');
1019
+ out.label = input.label;
1020
+ }
1021
+ switch (type) {
1022
+ case "text":
1023
+ case "inline": {
1024
+ out.max = boundedInt(
1025
+ input.max,
1026
+ 1,
1027
+ BLOCK_LIMITS.maxText,
1028
+ type === "text" ? BLOCK_LIMITS.defaultText : BLOCK_LIMITS.defaultInline,
1029
+ where,
1030
+ "max"
1031
+ );
1032
+ if (input.default !== void 0 && typeof input.default !== "string")
1033
+ fail(where, '"default" must be a string');
1034
+ out.default = (input.default || "").slice(0, out.max);
1035
+ if (type === "text") {
1036
+ if (input.multiline !== void 0 && typeof input.multiline !== "boolean")
1037
+ fail(where, '"multiline" must be a boolean');
1038
+ out.multiline = input.multiline === true;
1039
+ }
877
1040
  break;
878
1041
  }
879
- text += html.slice(i, lt);
880
- i = lt;
881
- if (html.startsWith("<!--", i)) {
882
- const end2 = html.indexOf("-->", i + 4);
883
- flush();
884
- i = end2 === -1 ? html.length : end2 + 3;
885
- continue;
886
- }
887
- if (html.startsWith("<![CDATA[", i)) {
888
- const end2 = html.indexOf("]]>", i + 9);
889
- flush();
890
- i = end2 === -1 ? html.length : end2 + 3;
891
- continue;
892
- }
893
- if (html[i + 1] === "!" || html[i + 1] === "?") {
894
- const end2 = html.indexOf(">", i + 2);
895
- flush();
896
- i = end2 === -1 ? html.length : end2 + 1;
897
- continue;
898
- }
899
- const closing = html[i + 1] === "/";
900
- const nameMatch = /^[A-Za-z][A-Za-z0-9-]{0,40}/.exec(html.slice(i + (closing ? 2 : 1), i + 45));
901
- if (!nameMatch) {
902
- text += "<";
903
- i += 1;
904
- continue;
1042
+ case "url": {
1043
+ const schemes = input.schemes === void 0 ? ["http", "https"] : input.schemes;
1044
+ if (!Array.isArray(schemes) || !schemes.length || schemes.some((scheme) => !LINK_SCHEMES.includes(scheme)))
1045
+ fail(where, `"schemes" must be a non-empty list of ${LINK_SCHEMES.join(", ")}`);
1046
+ if (input.relative !== void 0 && typeof input.relative !== "boolean")
1047
+ fail(where, '"relative" must be a boolean');
1048
+ out.schemes = Object.freeze([...new Set(schemes)]);
1049
+ out.relative = input.relative !== false;
1050
+ break;
905
1051
  }
906
- const end = findTagEnd(html, i + 1);
907
- if (end === -1) {
908
- text += html.slice(i);
1052
+ case "enum": {
1053
+ const values = input.values;
1054
+ 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)
1055
+ fail(
1056
+ where,
1057
+ `"values" must be 1 to ${BLOCK_LIMITS.maxEnumValues} distinct strings (1-100 characters)`
1058
+ );
1059
+ out.values = Object.freeze([...values]);
1060
+ if (input.default !== void 0 && !values.includes(input.default))
1061
+ fail(where, '"default" must be one of "values"');
1062
+ out.default = input.default === void 0 ? values[0] : input.default;
909
1063
  break;
910
1064
  }
911
- flush();
912
- const tag = nameMatch[0].toLowerCase();
913
- const body = html.slice(i + (closing ? 2 : 1) + nameMatch[0].length, end);
914
- i = end + 1;
915
- if (closing) {
916
- if (!ALLOWED.has(tag)) continue;
917
- for (let s = stack.length - 1; s > 0; s -= 1) {
918
- if (stack[s].tag === tag) {
919
- stack.length = s;
920
- break;
921
- }
1065
+ case "number": {
1066
+ for (const key of ["min", "max", "default"])
1067
+ if (input[key] !== void 0 && (typeof input[key] !== "number" || !Number.isFinite(input[key])))
1068
+ fail(where, `"${key}" must be a finite number`);
1069
+ if (input.integer !== void 0 && typeof input.integer !== "boolean")
1070
+ fail(where, '"integer" must be a boolean');
1071
+ out.integer = input.integer === true;
1072
+ out.min = input.min === void 0 ? -Number.MAX_SAFE_INTEGER : input.min;
1073
+ out.max = input.max === void 0 ? Number.MAX_SAFE_INTEGER : input.max;
1074
+ if (out.min > out.max) fail(where, '"min" must not be greater than "max"');
1075
+ if (input.default !== void 0) {
1076
+ if (input.default < out.min || input.default > out.max || out.integer && !Number.isInteger(input.default))
1077
+ fail(where, '"default" must be a valid value of the field');
1078
+ out.default = input.default;
922
1079
  }
923
- continue;
924
- }
925
- if (DROP_WITH_CONTENT.has(tag)) {
926
- const selfClosing = /\/\s*$/.test(body);
927
- if (selfClosing) continue;
928
- const closeIndex = html.slice(i).search(new RegExp(`</${tag}[\\s/>]`, "i"));
929
- if (closeIndex === -1) break;
930
- const closeEnd = html.indexOf(">", i + closeIndex);
931
- i = closeEnd === -1 ? html.length : closeEnd + 1;
932
- continue;
1080
+ break;
933
1081
  }
934
- if (!ALLOWED.has(tag) || nodes >= MAX_NODES) continue;
935
- const element = {
936
- type: "element",
937
- tag,
938
- attrs: cleanAttributes(tag, parseAttributes(body)),
939
- children: []
940
- };
941
- stack[stack.length - 1].children.push(element);
942
- nodes += 1;
943
- if (!VOID.has(tag) && stack.length < MAX_DEPTH) stack.push(element);
1082
+ case "boolean":
1083
+ if (input.default !== void 0 && typeof input.default !== "boolean")
1084
+ fail(where, '"default" must be a boolean');
1085
+ out.default = input.default === true;
1086
+ break;
1087
+ case "array":
1088
+ if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1089
+ out.max = boundedInt(input.max, 1, BLOCK_LIMITS.maxItems, BLOCK_LIMITS.defaultItems, where, "max");
1090
+ out.items = normalizeField(input.items, `${where}[]`, depth + 1);
1091
+ break;
1092
+ case "object":
1093
+ if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1094
+ out.fields = normalizeFields(input.fields, where, depth + 1);
1095
+ break;
1096
+ default:
1097
+ break;
944
1098
  }
945
- flush();
946
- return root.children;
1099
+ return Object.freeze(out);
947
1100
  };
948
- var resolveLinkAttributes = (attrs, resolver) => {
949
- if (typeof resolver !== "function" || !attrs["data-mex-uid"] || !attrs["data-mex-document-id"])
950
- return attrs;
951
- let result;
952
- try {
953
- result = resolver({
954
- uid: attrs["data-mex-uid"],
955
- documentId: attrs["data-mex-document-id"],
956
- locale: attrs["data-mex-locale"] || null,
957
- href: attrs.href || null,
958
- ...isMentionLink(attrs) ? { mention: true } : {}
959
- });
960
- } catch {
961
- result = void 0;
962
- }
963
- if (result === false) return null;
964
- if (typeof result === "string") {
965
- const url = sanitizeUrl(result);
966
- if (url) return { ...attrs, href: url };
1101
+ var normalizeFields = (input, where, depth) => {
1102
+ if (!isObject2(input)) fail(where, '"fields" must be an object of field descriptors');
1103
+ const keys = Object.keys(input);
1104
+ if (keys.length < 1 || keys.length > BLOCK_LIMITS.maxFields)
1105
+ fail(where, `an object needs 1 to ${BLOCK_LIMITS.maxFields} fields`);
1106
+ const out = /* @__PURE__ */ Object.create(null);
1107
+ for (const key of keys) {
1108
+ if (!KEY_PATTERN.test(key) || FORBIDDEN_KEYS2.has(key))
1109
+ fail(where, `field name ${JSON.stringify(key)} must match ${KEY_PATTERN}`);
1110
+ out[key] = normalizeField(input[key], `${where}.${key}`, depth);
967
1111
  }
968
- return attrs;
1112
+ return Object.freeze(out);
969
1113
  };
970
- var ATTRIBUTE_ORDER = [
971
- "href",
972
- "target",
973
- "rel",
974
- "title",
975
- "class",
976
- "data-tooltip",
977
- "data-mex-uid",
978
- "data-mex-document-id",
979
- "data-mex-locale",
980
- "data-mex-mention"
981
- ];
982
- var MENTION_CLASS = "mex-mention";
983
- var inlineNodesToRender = (nodes, options = {}) => {
984
- const out = [];
985
- for (const node of nodes) {
986
- if (node.type === "text") {
987
- out.push({ type: "text", value: node.value });
988
- continue;
989
- }
990
- if (node.tag === "br") {
991
- out.push({ type: "element", tag: "br", attrs: {}, children: [] });
992
- continue;
993
- }
994
- let attrs = node.attrs;
995
- if (node.tag === "a") {
996
- attrs = resolveLinkAttributes(attrs, options.links);
997
- if (!attrs || !attrs.href) {
998
- out.push(...inlineNodesToRender(node.children, options));
999
- continue;
1000
- }
1001
- if (attrs.target === "_blank") {
1002
- const rel = new Set(
1003
- String(attrs.rel || "").split(/\s+/).filter(Boolean)
1004
- );
1005
- rel.add("noopener");
1006
- rel.add("noreferrer");
1007
- attrs = { ...attrs, rel: Array.from(rel).sort().join(" ") };
1008
- }
1009
- if (!options.storage && isMentionLink(attrs)) attrs = { ...attrs, class: MENTION_CLASS };
1010
- }
1011
- const ordered = {};
1012
- for (const name of ATTRIBUTE_ORDER) {
1013
- if (attrs[name] !== void 0 && attrs[name] !== "") ordered[name] = String(attrs[name]);
1014
- }
1015
- out.push({
1016
- type: "element",
1017
- tag: node.tag,
1018
- attrs: ordered,
1019
- children: inlineNodesToRender(node.children, options)
1020
- });
1021
- }
1022
- return out;
1114
+ var blockNameProblem = (name) => {
1115
+ if (typeof name !== "string" || !BLOCK_NAME_PATTERN.test(name))
1116
+ return `the name must match ${BLOCK_NAME_PATTERN}`;
1117
+ if (RESERVED.has(name.toLowerCase())) return `"${name}" is a built-in tool name`;
1118
+ return null;
1023
1119
  };
1024
- var inlineToNodes = (html, options) => inlineNodesToRender(parseInline(html), options);
1025
- var nodesToHtml = (nodes, options = {}) => serializeNodes(inlineNodesToRender(nodes, options));
1026
- var nodesToText = (nodes) => nodes.map((node) => {
1027
- if (node.type === "text") return node.value;
1028
- if (node.tag === "br") return "\n";
1029
- return nodesToText(node.children);
1030
- }).join("");
1031
- var inlineToHtml = (html, options) => nodesToHtml(parseInline(html), options);
1032
- var inlineToText = (html) => nodesToText(parseInline(html)).replace(/\u00a0/g, " ");
1033
-
1034
- // shared/blocks/define.mjs
1035
- var BLOCK_FIELD_TYPES = Object.freeze([
1036
- "text",
1037
- "inline",
1038
- "url",
1039
- "enum",
1040
- "number",
1041
- "boolean",
1042
- "array",
1043
- "object"
1044
- ]);
1045
- var BLOCK_LIMITS = Object.freeze({
1046
- /** Fields per object (also the schema root). */
1047
- maxFields: 50,
1048
- /** Nesting of arrays and objects below the root. */
1049
- maxDepth: 4,
1050
- /** Largest `max` of a text or inline field. */
1051
- maxText: 1e5,
1052
- /** Default `max` of a text field. */
1053
- defaultText: 1e3,
1054
- /** Default `max` of an inline HTML field. */
1055
- defaultInline: 1e4,
1056
- /** Largest `max` of an array field. */
1057
- maxItems: 500,
1058
- /** Default `max` of an array field. */
1059
- defaultItems: 50,
1060
- /** Values of an enum field. */
1061
- maxEnumValues: 100,
1062
- /** Values cleaned per block; later array items are dropped. */
1063
- maxValues: 2e4,
1064
- /** Length of a URL value. */
1065
- maxUrl: 2048
1066
- });
1067
- var BLOCK_PRESETS = Object.freeze(["article", "basic", "minimal"]);
1068
- var RESERVED_BLOCK_NAMES = Object.freeze([
1069
- "paragraph",
1070
- "header",
1071
- "list",
1072
- "checklist",
1073
- "quote",
1074
- "warning",
1075
- "alert",
1076
- "toggle",
1077
- "code",
1078
- "codeFlask",
1079
- "delimiter",
1080
- "toc",
1081
- "synced",
1082
- "table",
1083
- "embed",
1084
- "raw",
1085
- "image",
1086
- "simpleImage",
1087
- "gallery",
1088
- "video",
1089
- "audio",
1090
- "linkTool",
1091
- "attaches",
1092
- "personality",
1093
- "button",
1094
- "mediaLib",
1095
- "embeddedEntry",
1096
- "bold",
1097
- "italic",
1098
- "hyperlink",
1099
- "mention",
1100
- "marker",
1101
- "underline",
1102
- "strikethrough",
1103
- "inlineCode",
1104
- "tooltip",
1105
- "aiAssistant",
1106
- "alignmentTune",
1107
- "textVariant",
1108
- "indentTune"
1120
+ var defineBlock = (definition) => {
1121
+ if (!isObject2(definition))
1122
+ throw new BlockDefinitionError("Magic Editor X block: the definition must be an object");
1123
+ const label3 = typeof definition.name === "string" ? `"${definition.name.slice(0, 50)}"` : "(no name)";
1124
+ for (const key of Object.keys(definition))
1125
+ if (!DEFINITION_KEYS.has(key)) fail(label3, `unknown key "${key}"`);
1126
+ const problem = blockNameProblem(definition.name);
1127
+ if (problem)
1128
+ throw new BlockDefinitionError(
1129
+ `Magic Editor X block ${label3}: ${problem}`,
1130
+ problem.includes("built-in") ? "RESERVED_NAME" : "INVALID_DEFINITION"
1131
+ );
1132
+ const out = {
1133
+ name: definition.name,
1134
+ version: boundedInt(definition.version, 1, 1e6, 1, label3, "version")
1135
+ };
1136
+ for (const [key, max] of [
1137
+ ["title", 100],
1138
+ ["description", 500]
1139
+ ]) {
1140
+ if (definition[key] === void 0) continue;
1141
+ if (typeof definition[key] !== "string" || definition[key].length > max)
1142
+ fail(label3, `"${key}" must be a string of at most ${max} characters`);
1143
+ out[key] = definition[key];
1144
+ }
1145
+ out.schema = normalizeFields(definition.schema, `${label3} schema`, 0);
1146
+ for (const key of ["sanitize", "text", "markdown", "render"]) {
1147
+ if (definition[key] === void 0) continue;
1148
+ if (typeof definition[key] !== "function") fail(label3, `"${key}" must be a function`);
1149
+ out[key] = definition[key];
1150
+ }
1151
+ const presets = definition.presets === void 0 ? [] : definition.presets;
1152
+ if (!Array.isArray(presets) || presets.some((preset) => !BLOCK_PRESETS.includes(preset)))
1153
+ fail(label3, `"presets" must list some of ${BLOCK_PRESETS.join(", ")}`);
1154
+ out.presets = Object.freeze([...new Set(presets)]);
1155
+ return Object.freeze(out);
1156
+ };
1157
+ var cleanValue = (field, value, inline, budget) => {
1158
+ budget.left -= 1;
1159
+ switch (field.type) {
1160
+ case "text":
1161
+ return typeof value === "string" ? value.slice(0, field.max) : field.default;
1162
+ case "inline":
1163
+ return inline(typeof value === "string" ? value.slice(0, field.max) : field.default);
1164
+ case "url":
1165
+ return typeof value === "string" ? sanitizeUrl(value.slice(0, BLOCK_LIMITS.maxUrl), {
1166
+ schemes: field.schemes,
1167
+ allowRelative: field.relative
1168
+ }) : "";
1169
+ case "enum":
1170
+ return typeof value === "string" && field.values.includes(value) ? value : field.default;
1171
+ case "number":
1172
+ return typeof value === "number" && Number.isFinite(value) && value >= field.min && value <= field.max && (!field.integer || Number.isInteger(value)) ? value : field.default;
1173
+ case "boolean":
1174
+ return typeof value === "boolean" ? value : field.default;
1175
+ case "array": {
1176
+ const out = [];
1177
+ if (!Array.isArray(value)) return out;
1178
+ for (const item of value) {
1179
+ if (out.length >= field.max || budget.left <= 0) break;
1180
+ if (!matchesType(field.items, item)) continue;
1181
+ const clean2 = cleanValue(field.items, item, inline, budget);
1182
+ if (clean2 !== void 0) out.push(clean2);
1183
+ }
1184
+ return out;
1185
+ }
1186
+ case "object":
1187
+ return cleanObject(field.fields, isObject2(value) ? value : {}, inline, budget);
1188
+ default:
1189
+ return void 0;
1190
+ }
1191
+ };
1192
+ var matchesType = (field, item) => {
1193
+ switch (field.type) {
1194
+ case "text":
1195
+ case "inline":
1196
+ case "url":
1197
+ case "enum":
1198
+ return typeof item === "string";
1199
+ case "number":
1200
+ return typeof item === "number";
1201
+ case "boolean":
1202
+ return typeof item === "boolean";
1203
+ case "array":
1204
+ return Array.isArray(item);
1205
+ default:
1206
+ return isObject2(item);
1207
+ }
1208
+ };
1209
+ var cleanObject = (fields, value, inline, budget) => {
1210
+ const out = {};
1211
+ for (const key of Object.keys(fields)) {
1212
+ const own = Object.prototype.hasOwnProperty.call(value, key) ? value[key] : void 0;
1213
+ const clean2 = cleanValue(fields[key], own, inline, budget);
1214
+ if (clean2 !== void 0) out[key] = clean2;
1215
+ }
1216
+ return out;
1217
+ };
1218
+ var eachLeaf = (fields, data, visit) => {
1219
+ const walk = (field, value, path, depth) => {
1220
+ if (depth > BLOCK_LIMITS.maxDepth + 1) return;
1221
+ if (field.type === "array") {
1222
+ if (!Array.isArray(value)) return;
1223
+ value.slice(0, field.max).forEach((item, index) => walk(field.items, item, [...path, index], depth + 1));
1224
+ } else if (field.type === "object") {
1225
+ if (!isObject2(value)) return;
1226
+ for (const key of Object.keys(field.fields))
1227
+ if (Object.prototype.hasOwnProperty.call(value, key))
1228
+ walk(field.fields[key], value[key], [...path, key], depth + 1);
1229
+ } else visit(field, value, path);
1230
+ };
1231
+ if (!isObject2(data)) return;
1232
+ for (const key of Object.keys(fields))
1233
+ if (Object.prototype.hasOwnProperty.call(data, key)) walk(fields[key], data[key], [key], 0);
1234
+ };
1235
+ var fieldAt = (fields, path) => {
1236
+ let current = { type: "object", fields };
1237
+ for (const part of String(path).split(".")) {
1238
+ if (!part) continue;
1239
+ if (current.type === "array") {
1240
+ if (/^\d+$/.test(part)) {
1241
+ current = current.items;
1242
+ continue;
1243
+ }
1244
+ return null;
1245
+ }
1246
+ if (current.type !== "object" || !Object.prototype.hasOwnProperty.call(current.fields, part)) return null;
1247
+ current = current.fields[part];
1248
+ }
1249
+ return current;
1250
+ };
1251
+ var compiled = /* @__PURE__ */ new WeakMap();
1252
+ var compileBlock = (definition) => {
1253
+ if (definition && typeof definition === "object" && compiled.has(definition))
1254
+ return compiled.get(definition);
1255
+ const def = defineBlock(definition && typeof definition === "object" ? { ...definition } : definition);
1256
+ const schema = def.schema;
1257
+ const run = (data, inline) => cleanObject(schema, isObject2(data) ? data : {}, inline, { left: BLOCK_LIMITS.maxValues });
1258
+ const result = Object.freeze({
1259
+ ...def,
1260
+ /**
1261
+ * Cleans untrusted block data (unknown keys dropped, values bounded).
1262
+ * The optional `sanitize` hook runs on the clean data; its result is
1263
+ * cleaned again, so it cannot add keys or unsafe values. A hook that
1264
+ * throws is ignored (the clean data is used).
1265
+ * @param {unknown} data - Block data.
1266
+ * @param {(html: string) => string} inline - Inline HTML sanitiser of the caller.
1267
+ * @returns {object} Clean data.
1268
+ */
1269
+ clean: (data, inline) => {
1270
+ const first = run(data, inline);
1271
+ if (!def.sanitize) return first;
1272
+ let next;
1273
+ try {
1274
+ next = def.sanitize(copyData(first), { sanitizeUrl });
1275
+ } catch {
1276
+ return first;
1277
+ }
1278
+ return isObject2(next) ? run(next, inline) : first;
1279
+ },
1280
+ /**
1281
+ * Text fields of the data in schema order: `{ path, kind, value }`
1282
+ * (`html` for inline fields, `plain` for text fields).
1283
+ * @param {unknown} data - Block data.
1284
+ * @returns {Array<{ path: Array<string|number>, kind: 'html'|'plain', value: string }>} Fields.
1285
+ */
1286
+ fields: (data) => {
1287
+ const out = [];
1288
+ eachLeaf(schema, data, (field, value, path) => {
1289
+ if (typeof value !== "string") return;
1290
+ if (field.type === "inline") out.push({ path, kind: "html", value });
1291
+ else if (field.type === "text") out.push({ path, kind: "plain", value });
1292
+ });
1293
+ return out;
1294
+ },
1295
+ /**
1296
+ * Non-empty URL values: `{ path, value }`.
1297
+ * @param {unknown} data - Block data.
1298
+ * @returns {Array<{ path: Array<string|number>, value: string }>} URLs.
1299
+ */
1300
+ urls: (data) => {
1301
+ const out = [];
1302
+ eachLeaf(schema, data, (field, value, path) => {
1303
+ if (field.type === "url" && typeof value === "string" && value) out.push({ path, value });
1304
+ });
1305
+ return out;
1306
+ },
1307
+ /**
1308
+ * Kind of the value at a dotted path, for the version diff.
1309
+ * @param {string} path - Dotted path.
1310
+ * @returns {'inline'|'plain'|'value'} Kind.
1311
+ */
1312
+ kindOf: (path) => {
1313
+ const field = fieldAt(schema, path);
1314
+ if (!field) return "value";
1315
+ if (field.type === "inline") return "inline";
1316
+ if (field.type === "text") return "plain";
1317
+ return "value";
1318
+ }
1319
+ });
1320
+ compiled.set(result, result);
1321
+ if (definition && typeof definition === "object") compiled.set(definition, result);
1322
+ return result;
1323
+ };
1324
+ var copyData = (value) => {
1325
+ if (Array.isArray(value)) return value.map(copyData);
1326
+ if (isObject2(value)) {
1327
+ const out = {};
1328
+ for (const [key, child] of Object.entries(value)) out[key] = copyData(child);
1329
+ return out;
1330
+ }
1331
+ return value;
1332
+ };
1333
+ var listCache = /* @__PURE__ */ new WeakMap();
1334
+ var compileBlockList = (list) => {
1335
+ if (!Array.isArray(list)) return /* @__PURE__ */ new Map();
1336
+ if (listCache.has(list)) return listCache.get(list);
1337
+ const map = /* @__PURE__ */ new Map();
1338
+ for (const definition of list) {
1339
+ const def = compileBlock(definition);
1340
+ map.set(def.name, def);
1341
+ }
1342
+ listCache.set(list, map);
1343
+ return map;
1344
+ };
1345
+
1346
+ // shared/blocks/annotations.mjs
1347
+ var ANNOTATION_ATTRIBUTE = "data-mex-annotation";
1348
+ var ANNOTATION_VALUE_PREFIX = "data-mex-a-";
1349
+ var ANNOTATION_NAME = /^[a-z][a-z0-9-]{1,39}$/;
1350
+ var ANNOTATION_KEY = /^[a-z][a-z0-9]{0,23}$/;
1351
+ var ANNOTATION_FIELD_TYPES = Object.freeze(["text", "enum", "url"]);
1352
+ var ANNOTATION_LIMITS = Object.freeze({
1353
+ attributes: 8,
1354
+ text: 1e3,
1355
+ textDefault: 200,
1356
+ values: 50,
1357
+ registered: 50,
1358
+ label: 100,
1359
+ resolveItems: 200
1360
+ });
1361
+ var ANNOTATION_PRESETS = Object.freeze(["full", "article", "basic", "minimal"]);
1362
+ var ANNOTATION_RENDER_TAGS = Object.freeze([
1363
+ "abbr",
1364
+ "dfn",
1365
+ "span",
1366
+ "a",
1367
+ "mark",
1368
+ "cite",
1369
+ "q",
1370
+ "small",
1371
+ "em",
1372
+ "strong",
1373
+ "b",
1374
+ "i",
1375
+ "u",
1376
+ "s",
1377
+ "time",
1378
+ "data",
1379
+ "bdi",
1380
+ "kbd",
1381
+ "var",
1382
+ "ins",
1383
+ "del"
1109
1384
  ]);
1110
- var RESERVED = new Set(RESERVED_BLOCK_NAMES.map((name) => name.toLowerCase()));
1111
- var BLOCK_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{1,49}$/;
1112
- var KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
1113
- var FORBIDDEN_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1114
- var DEFINITION_KEYS = /* @__PURE__ */ new Set([
1115
- "name",
1116
- "version",
1385
+ var ANNOTATION_SHORTCUTS = Object.freeze(["CMD+SHIFT+0", "CMD+SHIFT+1", "CMD+SHIFT+8"]);
1386
+ var ABBREVIATION = "abbreviation";
1387
+ var isObject3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1388
+ var fail2 = (name, message, code = "INVALID_DEFINITION") => {
1389
+ throw new BlockDefinitionError(`Magic Editor X inline annotation ${name}: ${message}`, code);
1390
+ };
1391
+ var defined = /* @__PURE__ */ new WeakSet();
1392
+ var cleanText = (value, max) => typeof value === "string" ? value.trim().slice(0, max).trim() : "";
1393
+ var normalizeAttribute = (where, input) => {
1394
+ if (!isObject3(input)) fail2(where, 'an attribute must be an object with a "type"');
1395
+ const { type } = input;
1396
+ if (!ANNOTATION_FIELD_TYPES.includes(type)) fail2(where, `unknown attribute type ${JSON.stringify(type)}`);
1397
+ const allowed = { text: ["max"], enum: ["values"], url: ["schemes", "relative"] }[type];
1398
+ for (const key of Object.keys(input))
1399
+ if (!["type", "label", "required", ...allowed].includes(key))
1400
+ fail2(where, `unknown option "${key}" for a ${type} attribute`);
1401
+ const out = { type, required: input.required === true };
1402
+ if (input.label !== void 0) {
1403
+ if (typeof input.label !== "string" || input.label.length > ANNOTATION_LIMITS.label)
1404
+ fail2(where, `"label" must be a string of at most ${ANNOTATION_LIMITS.label} characters`);
1405
+ out.label = input.label;
1406
+ }
1407
+ if (input.required !== void 0 && typeof input.required !== "boolean")
1408
+ fail2(where, '"required" must be a boolean');
1409
+ if (type === "text") {
1410
+ const max = input.max === void 0 ? ANNOTATION_LIMITS.textDefault : input.max;
1411
+ if (!Number.isInteger(max) || max < 1 || max > ANNOTATION_LIMITS.text)
1412
+ fail2(where, `"max" must be an integer from 1 to ${ANNOTATION_LIMITS.text}`);
1413
+ out.max = max;
1414
+ } else if (type === "enum") {
1415
+ const { values } = input;
1416
+ 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)
1417
+ fail2(where, `"values" must be 1 to ${ANNOTATION_LIMITS.values} distinct strings`);
1418
+ out.values = Object.freeze([...values]);
1419
+ } else {
1420
+ const schemes = input.schemes === void 0 ? ["http", "https"] : input.schemes;
1421
+ if (!Array.isArray(schemes) || !schemes.length || !schemes.every((scheme) => LINK_SCHEMES.includes(scheme)))
1422
+ fail2(where, `"schemes" must be a non-empty subset of ${LINK_SCHEMES.join(", ")}`);
1423
+ if (input.relative !== void 0 && typeof input.relative !== "boolean")
1424
+ fail2(where, '"relative" must be a boolean');
1425
+ out.schemes = Object.freeze([...new Set(schemes)]);
1426
+ out.relative = input.relative !== false;
1427
+ }
1428
+ return Object.freeze(out);
1429
+ };
1430
+ var defineInlineAnnotation = (definition) => {
1431
+ if (!isObject3(definition)) fail2("(unnamed)", "the definition must be an object");
1432
+ const { name } = definition;
1433
+ if (typeof name !== "string" || !ANNOTATION_NAME.test(name))
1434
+ fail2(JSON.stringify(name), "the name must match /^[a-z][a-z0-9-]{1,39}$/");
1435
+ for (const key of Object.keys(definition))
1436
+ if (!["name", "label", "description", "attributes", "presets", "resolve", "render", "shortcut"].includes(
1437
+ key
1438
+ ))
1439
+ fail2(name, `unknown key "${key}"`);
1440
+ for (const key of ["label", "description"])
1441
+ if (definition[key] !== void 0 && (typeof definition[key] !== "string" || definition[key].length > (key === "label" ? 100 : 500)))
1442
+ fail2(name, `"${key}" must be a short string`);
1443
+ if (!isObject3(definition.attributes)) fail2(name, '"attributes" must be an object');
1444
+ const keys = Object.keys(definition.attributes);
1445
+ if (keys.length > ANNOTATION_LIMITS.attributes)
1446
+ fail2(name, `at most ${ANNOTATION_LIMITS.attributes} attributes`);
1447
+ const attributes = {};
1448
+ for (const key of keys) {
1449
+ if (!ANNOTATION_KEY.test(key)) fail2(name, `attribute key "${key}" must match /^[a-z][a-z0-9]{0,23}$/`);
1450
+ attributes[key] = normalizeAttribute(`${name}.${key}`, definition.attributes[key]);
1451
+ }
1452
+ const presets = definition.presets === void 0 ? [] : definition.presets;
1453
+ if (!Array.isArray(presets) || !presets.every((preset) => ANNOTATION_PRESETS.includes(preset)))
1454
+ fail2(name, `"presets" must list only ${ANNOTATION_PRESETS.join(", ")}`);
1455
+ if (definition.shortcut !== void 0 && !ANNOTATION_SHORTCUTS.includes(definition.shortcut))
1456
+ fail2(name, `"shortcut" must be one of ${ANNOTATION_SHORTCUTS.join(", ")}`);
1457
+ for (const key of ["resolve", "render"])
1458
+ if (definition[key] !== void 0 && typeof definition[key] !== "function")
1459
+ fail2(name, `"${key}" must be a function`);
1460
+ const out = Object.freeze({
1461
+ name,
1462
+ label: definition.label || name,
1463
+ ...definition.description ? { description: definition.description } : {},
1464
+ attributes: Object.freeze(attributes),
1465
+ presets: Object.freeze([...new Set(presets)]),
1466
+ ...definition.shortcut ? { shortcut: definition.shortcut } : {},
1467
+ ...definition.resolve ? { resolve: definition.resolve } : {},
1468
+ ...definition.render ? { render: definition.render } : {}
1469
+ });
1470
+ defined.add(out);
1471
+ return out;
1472
+ };
1473
+ var cleanAnnotationAttributes = (definition, raw) => {
1474
+ const source = raw && typeof raw === "object" ? raw : {};
1475
+ const out = {};
1476
+ for (const [key, field] of Object.entries(definition.attributes)) {
1477
+ const value = Object.prototype.hasOwnProperty.call(source, key) ? source[key] : void 0;
1478
+ let clean2;
1479
+ if (field.type === "text") clean2 = cleanText(value, field.max);
1480
+ else if (field.type === "enum")
1481
+ clean2 = typeof value === "string" && field.values.includes(value) ? value : "";
1482
+ else clean2 = sanitizeUrl(value, { schemes: field.schemes, allowRelative: field.relative });
1483
+ if (clean2) out[key] = clean2;
1484
+ else if (field.required) return null;
1485
+ }
1486
+ return out;
1487
+ };
1488
+ var abbreviationAnnotation = defineInlineAnnotation({
1489
+ name: ABBREVIATION,
1490
+ label: "Abbreviation",
1491
+ description: "Short form with its full form (shown as a tooltip and read by screen readers).",
1492
+ attributes: { title: { type: "text", max: 200, required: true, label: "Full form" } },
1493
+ render: (annotation) => ({ tag: "abbr", attrs: { title: annotation.attrs.title } })
1494
+ });
1495
+ var registry2 = /* @__PURE__ */ new Map();
1496
+ var activeAnnotation = (name) => {
1497
+ if (name === ABBREVIATION) return abbreviationAnnotation;
1498
+ return typeof name === "string" && registry2.has(name) ? registry2.get(name) : null;
1499
+ };
1500
+ var CLASS_TOKEN = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;
1501
+ var RENDER_ATTRIBUTES = /* @__PURE__ */ new Set(["title", "class", "lang", "dir", "href", "datetime", "value", "cite"]);
1502
+ var cleanAnnotationWrapper = (out) => {
1503
+ if (!isObject3(out) || !ANNOTATION_RENDER_TAGS.includes(out.tag)) return null;
1504
+ const attrs = {};
1505
+ for (const [name, raw] of Object.entries(isObject3(out.attrs) ? out.attrs : {})) {
1506
+ if (raw === void 0 || raw === null || raw === false) continue;
1507
+ if (!["string", "number"].includes(typeof raw)) continue;
1508
+ const allowed = RENDER_ATTRIBUTES.has(name) || name === "aria-label" || name.startsWith("data-") && !name.startsWith("data-mex-");
1509
+ if (!allowed || !isSafeAttributeName(name)) continue;
1510
+ const text = String(raw).slice(0, 2e3);
1511
+ if (name === "href" || name === "cite") {
1512
+ if (out.tag !== "a" && name === "href") continue;
1513
+ const url = sanitizeUrl(text);
1514
+ if (url) attrs[name] = url;
1515
+ } else if (name === "class") {
1516
+ const classes2 = text.split(/\s+/).filter((token) => CLASS_TOKEN.test(token));
1517
+ if (classes2.length) attrs.class = classes2.join(" ");
1518
+ } else if (text) attrs[name] = text;
1519
+ }
1520
+ return { tag: out.tag, attrs };
1521
+ };
1522
+
1523
+ // shared/render/inline.mjs
1524
+ var DROP_WITH_CONTENT = /* @__PURE__ */ new Set([
1525
+ "script",
1526
+ "style",
1527
+ "textarea",
1117
1528
  "title",
1118
- "description",
1119
- "schema",
1120
- "sanitize",
1121
- "text",
1122
- "markdown",
1123
- "render",
1124
- "presets"
1529
+ "xmp",
1530
+ "noscript",
1531
+ "noembed",
1532
+ "noframes",
1533
+ "template",
1534
+ "iframe",
1535
+ "object",
1536
+ "embed",
1537
+ "svg",
1538
+ "math",
1539
+ "select",
1540
+ "option",
1541
+ "plaintext"
1125
1542
  ]);
1126
- var FIELD_KEYS = {
1127
- text: ["max", "multiline", "default"],
1128
- inline: ["max", "default"],
1129
- url: ["schemes", "relative"],
1130
- enum: ["values", "default"],
1131
- number: ["min", "max", "integer", "default"],
1132
- boolean: ["default"],
1133
- array: ["items", "max"],
1134
- object: ["fields"]
1543
+ var ALLOWED = new Set(INLINE_TAGS);
1544
+ var VOID = /* @__PURE__ */ new Set(["br"]);
1545
+ var MAX_INPUT = 5e5;
1546
+ var MAX_NODES = 5e4;
1547
+ var MAX_DEPTH = 64;
1548
+ var NAMED_ENTITIES = Object.freeze({
1549
+ amp: "&",
1550
+ lt: "<",
1551
+ gt: ">",
1552
+ quot: '"',
1553
+ apos: "'",
1554
+ nbsp: "\xA0",
1555
+ shy: "\xAD",
1556
+ copy: "\xA9",
1557
+ reg: "\xAE",
1558
+ trade: "\u2122",
1559
+ hellip: "\u2026",
1560
+ mdash: "\u2014",
1561
+ ndash: "\u2013",
1562
+ lsquo: "\u2018",
1563
+ rsquo: "\u2019",
1564
+ ldquo: "\u201C",
1565
+ rdquo: "\u201D",
1566
+ laquo: "\xAB",
1567
+ raquo: "\xBB",
1568
+ euro: "\u20AC",
1569
+ middot: "\xB7",
1570
+ bull: "\u2022",
1571
+ times: "\xD7",
1572
+ deg: "\xB0",
1573
+ tab: " ",
1574
+ newline: "\n",
1575
+ colon: ":",
1576
+ sol: "/",
1577
+ lpar: "(",
1578
+ rpar: ")"
1579
+ });
1580
+ var decodeEntities = (text) => String(text).replace(
1581
+ /&(#[xX][0-9a-fA-F]{1,8}|#[0-9]{1,10}|[A-Za-z][A-Za-z0-9]{1,31});?/g,
1582
+ (match, body) => {
1583
+ if (body[0] === "#") {
1584
+ const code = body[1] === "x" || body[1] === "X" ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
1585
+ if (!Number.isFinite(code) || code <= 0 || code > 1114111 || code >= 55296 && code <= 57343)
1586
+ return "\uFFFD";
1587
+ return String.fromCodePoint(code);
1588
+ }
1589
+ const named = NAMED_ENTITIES[body] ?? NAMED_ENTITIES[body.toLowerCase()];
1590
+ return named === void 0 ? match : named;
1591
+ }
1592
+ );
1593
+ var parseAttributes = (source) => {
1594
+ const out = {};
1595
+ const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
1596
+ let match;
1597
+ while (match = pattern.exec(source)) {
1598
+ const name = match[1].toLowerCase();
1599
+ if (Object.prototype.hasOwnProperty.call(out, name)) continue;
1600
+ const raw = match[2] ?? match[3] ?? match[4] ?? "";
1601
+ out[name] = decodeEntities(raw);
1602
+ }
1603
+ return out;
1135
1604
  };
1136
- var BlockDefinitionError = class extends Error {
1137
- /**
1138
- * @param {string} message - Message naming the definition and the problem.
1139
- * @param {string} [code] - `INVALID_DEFINITION` | `RESERVED_NAME` | `NAME_TAKEN` | `REGISTRY_SEALED`.
1140
- */
1141
- constructor(message, code = "INVALID_DEFINITION") {
1142
- super(message);
1143
- this.name = "BlockDefinitionError";
1144
- this.code = code;
1605
+ var findTagEnd = (html, from) => {
1606
+ let quote = "";
1607
+ for (let i = from; i < html.length; i += 1) {
1608
+ const char = html[i];
1609
+ if (quote) {
1610
+ if (char === quote) quote = "";
1611
+ } else if (char === '"' || char === "'") quote = char;
1612
+ else if (char === ">") return i;
1145
1613
  }
1614
+ return -1;
1146
1615
  };
1147
- var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1148
- var fail = (where, message) => {
1149
- throw new BlockDefinitionError(`Magic Editor X block ${where}: ${message}`);
1616
+ var cleanAttributes = (tag, attribs, options = {}) => {
1617
+ const allowed = INLINE_ATTRIBUTES[tag] || [];
1618
+ const out = {};
1619
+ for (const name of allowed) {
1620
+ if (!Object.prototype.hasOwnProperty.call(attribs, name) || name.startsWith("data-mex-")) continue;
1621
+ const value = attribs[name];
1622
+ if (name === "href") {
1623
+ const url = sanitizeUrl(value);
1624
+ if (url) out.href = url;
1625
+ } else if (name === "target") {
1626
+ const target = sanitizeTarget(value);
1627
+ if (target) out.target = target;
1628
+ } else if (name === "rel") {
1629
+ const rel = String(value).split(/\s+/).filter((token) => /^[a-z-]{1,20}$/.test(token));
1630
+ if (rel.length) out.rel = rel.join(" ");
1631
+ } else if (name === "class") {
1632
+ const classes2 = String(value).split(/\s+/).filter((token) => (INLINE_CLASSES[tag] || []).includes(token));
1633
+ if (classes2.length) out.class = classes2.join(" ");
1634
+ } else {
1635
+ out[name] = String(value).slice(0, 2e3);
1636
+ }
1637
+ }
1638
+ if (tag === "a" && !options.inNote) Object.assign(out, cleanInternalLinkAttributes(attribs));
1639
+ return out;
1150
1640
  };
1151
- var boundedInt = (value, min, max, fallback, where, key) => {
1152
- if (value === void 0) return fallback;
1153
- if (!Number.isInteger(value) || value < min || value > max)
1154
- fail(where, `"${key}" must be an integer from ${min} to ${max}`);
1155
- return value;
1641
+ var MAX_MARKER_TEXT = 16;
1642
+ var isMathNode = (node) => node.type === "element" && node.tag === "span" && node.attrs[MATH_ATTRIBUTE] === "true";
1643
+ var isFootnoteNode = (node) => node.type === "element" && node.tag === "sup" && typeof node.attrs["data-mex-footnote"] === "string";
1644
+ var isColorNode = (node) => node.type === "element" && node.tag === "span" && typeof node.attrs[COLOR_ATTRIBUTE] === "string";
1645
+ var isHighlightNode = (node) => node.type === "element" && node.tag === "mark" && typeof node.attrs[HIGHLIGHT_ATTRIBUTE] === "string";
1646
+ var isAnnotationNode = (node) => node.type === "element" && node.tag === "span" && typeof node.attrs[ANNOTATION_ATTRIBUTE] === "string";
1647
+ var annotationOf = (node) => {
1648
+ const attrs = {};
1649
+ for (const [name, value] of Object.entries(node.attrs))
1650
+ if (name.startsWith(ANNOTATION_VALUE_PREFIX)) attrs[name.slice(ANNOTATION_VALUE_PREFIX.length)] = value;
1651
+ return { name: node.attrs[ANNOTATION_ATTRIBUTE], attrs };
1156
1652
  };
1157
- var normalizeField = (input, where, depth) => {
1158
- if (!isObject(input)) fail(where, 'a field must be an object with a "type"');
1159
- const type = input.type;
1160
- if (!BLOCK_FIELD_TYPES.includes(type)) fail(where, `unknown field type ${JSON.stringify(type)}`);
1161
- for (const key of Object.keys(input))
1162
- if (key !== "type" && key !== "label" && !FIELD_KEYS[type].includes(key))
1163
- fail(where, `unknown option "${key}" for a ${type} field`);
1164
- const out = { type };
1165
- if (input.label !== void 0) {
1166
- if (typeof input.label !== "string" || input.label.length > 100)
1167
- fail(where, '"label" must be a string of at most 100 characters');
1168
- out.label = input.label;
1653
+ var annotationAttributes = (name, values) => {
1654
+ const out = { [ANNOTATION_ATTRIBUTE]: name };
1655
+ for (const key of Object.keys(values).sort()) out[`${ANNOTATION_VALUE_PREFIX}${key}`] = values[key];
1656
+ return out;
1657
+ };
1658
+ var finalizeSpecial = (nodes, depth = 0) => {
1659
+ for (const node of nodes) {
1660
+ if (node.type !== "element") continue;
1661
+ if (isMathNode(node)) {
1662
+ const tex = nodesToText(node.children, { raw: true }).replace(/\u200b/g, "").slice(0, MAX_INLINE_TEX);
1663
+ node.children = tex ? [{ type: "text", value: tex }] : [];
1664
+ } else if (isFootnoteNode(node)) {
1665
+ const text = nodesToText(node.children, { raw: true }).slice(0, MAX_MARKER_TEXT);
1666
+ node.children = text ? [{ type: "text", value: text }] : [];
1667
+ } else if (depth < MAX_DEPTH) finalizeSpecial(node.children, depth + 1);
1668
+ }
1669
+ return nodes;
1670
+ };
1671
+ var specialElement = (tag, attribs, options) => {
1672
+ if (tag === "span" && Object.prototype.hasOwnProperty.call(attribs, MATH_ATTRIBUTE)) {
1673
+ if (!/^(?:|true)$/.test(attribs[MATH_ATTRIBUTE])) return null;
1674
+ return { attrs: { [MATH_ATTRIBUTE]: "true" } };
1675
+ }
1676
+ if (tag === "span" && Object.prototype.hasOwnProperty.call(attribs, ANNOTATION_ATTRIBUTE)) {
1677
+ const name = attribs[ANNOTATION_ATTRIBUTE];
1678
+ if (!ANNOTATION_NAME.test(name)) return null;
1679
+ const values = {};
1680
+ for (const [attribute, value] of Object.entries(attribs)) {
1681
+ if (!attribute.startsWith(ANNOTATION_VALUE_PREFIX)) continue;
1682
+ const key = attribute.slice(ANNOTATION_VALUE_PREFIX.length);
1683
+ if (!ANNOTATION_KEY.test(key) || Object.keys(values).length >= ANNOTATION_LIMITS.attributes) continue;
1684
+ const text = String(value).slice(0, ANNOTATION_LIMITS.text);
1685
+ if (text) values[key] = text;
1686
+ }
1687
+ return { attrs: annotationAttributes(name, values) };
1169
1688
  }
1170
- switch (type) {
1171
- case "text":
1172
- case "inline": {
1173
- out.max = boundedInt(
1174
- input.max,
1175
- 1,
1176
- BLOCK_LIMITS.maxText,
1177
- type === "text" ? BLOCK_LIMITS.defaultText : BLOCK_LIMITS.defaultInline,
1178
- where,
1179
- "max"
1180
- );
1181
- if (input.default !== void 0 && typeof input.default !== "string")
1182
- fail(where, '"default" must be a string');
1183
- out.default = (input.default || "").slice(0, out.max);
1184
- if (type === "text") {
1185
- if (input.multiline !== void 0 && typeof input.multiline !== "boolean")
1186
- fail(where, '"multiline" must be a boolean');
1187
- out.multiline = input.multiline === true;
1188
- }
1189
- break;
1689
+ if (tag === "span" && Object.prototype.hasOwnProperty.call(attribs, COLOR_ATTRIBUTE)) {
1690
+ return TOKEN_PATTERN.test(attribs[COLOR_ATTRIBUTE]) ? { attrs: { [COLOR_ATTRIBUTE]: attribs[COLOR_ATTRIBUTE] } } : null;
1691
+ }
1692
+ if (tag === "mark" && Object.prototype.hasOwnProperty.call(attribs, HIGHLIGHT_ATTRIBUTE)) {
1693
+ return TOKEN_PATTERN.test(attribs[HIGHLIGHT_ATTRIBUTE]) ? { attrs: { [HIGHLIGHT_ATTRIBUTE]: attribs[HIGHLIGHT_ATTRIBUTE] } } : null;
1694
+ }
1695
+ if (tag === "sup" && !options.inNote) {
1696
+ const id = attribs["data-mex-footnote"];
1697
+ if (typeof id !== "string" || !FOOTNOTE_ID.test(id)) return null;
1698
+ const source = typeof attribs["data-mex-note"] === "string" ? attribs["data-mex-note"] : "";
1699
+ const note = parseInline(source.slice(0, MAX_FOOTNOTE_NOTE), { inNote: true });
1700
+ return { attrs: { "data-mex-footnote": id }, note };
1701
+ }
1702
+ return null;
1703
+ };
1704
+ var parseInline = (input, options = {}) => {
1705
+ const html = typeof input === "string" ? input.slice(0, MAX_INPUT) : "";
1706
+ const root = { type: "element", tag: "#root", attrs: {}, children: [] };
1707
+ const stack = [root];
1708
+ let nodes = 0;
1709
+ let text = "";
1710
+ const flush = () => {
1711
+ if (!text) return;
1712
+ const parent = stack[stack.length - 1];
1713
+ const last = parent.children[parent.children.length - 1];
1714
+ const value = decodeEntities(text);
1715
+ if (last && last.type === "text") last.value += value;
1716
+ else if (nodes < MAX_NODES) {
1717
+ parent.children.push({ type: "text", value });
1718
+ nodes += 1;
1190
1719
  }
1191
- case "url": {
1192
- const schemes = input.schemes === void 0 ? ["http", "https"] : input.schemes;
1193
- if (!Array.isArray(schemes) || !schemes.length || schemes.some((scheme) => !LINK_SCHEMES.includes(scheme)))
1194
- fail(where, `"schemes" must be a non-empty list of ${LINK_SCHEMES.join(", ")}`);
1195
- if (input.relative !== void 0 && typeof input.relative !== "boolean")
1196
- fail(where, '"relative" must be a boolean');
1197
- out.schemes = Object.freeze([...new Set(schemes)]);
1198
- out.relative = input.relative !== false;
1720
+ text = "";
1721
+ };
1722
+ let i = 0;
1723
+ while (i < html.length) {
1724
+ const lt = html.indexOf("<", i);
1725
+ if (lt === -1) {
1726
+ text += html.slice(i);
1199
1727
  break;
1200
1728
  }
1201
- case "enum": {
1202
- const values = input.values;
1203
- 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)
1204
- fail(
1205
- where,
1206
- `"values" must be 1 to ${BLOCK_LIMITS.maxEnumValues} distinct strings (1-100 characters)`
1207
- );
1208
- out.values = Object.freeze([...values]);
1209
- if (input.default !== void 0 && !values.includes(input.default))
1210
- fail(where, '"default" must be one of "values"');
1211
- out.default = input.default === void 0 ? values[0] : input.default;
1729
+ text += html.slice(i, lt);
1730
+ i = lt;
1731
+ if (html.startsWith("<!--", i)) {
1732
+ const end2 = html.indexOf("-->", i + 4);
1733
+ flush();
1734
+ i = end2 === -1 ? html.length : end2 + 3;
1735
+ continue;
1736
+ }
1737
+ if (html.startsWith("<![CDATA[", i)) {
1738
+ const end2 = html.indexOf("]]>", i + 9);
1739
+ flush();
1740
+ i = end2 === -1 ? html.length : end2 + 3;
1741
+ continue;
1742
+ }
1743
+ if (html[i + 1] === "!" || html[i + 1] === "?") {
1744
+ const end2 = html.indexOf(">", i + 2);
1745
+ flush();
1746
+ i = end2 === -1 ? html.length : end2 + 1;
1747
+ continue;
1748
+ }
1749
+ const closing = html[i + 1] === "/";
1750
+ const nameMatch = /^[A-Za-z][A-Za-z0-9-]{0,40}/.exec(html.slice(i + (closing ? 2 : 1), i + 45));
1751
+ if (!nameMatch) {
1752
+ text += "<";
1753
+ i += 1;
1754
+ continue;
1755
+ }
1756
+ const end = findTagEnd(html, i + 1);
1757
+ if (end === -1) {
1758
+ text += html.slice(i);
1212
1759
  break;
1213
1760
  }
1214
- case "number": {
1215
- for (const key of ["min", "max", "default"])
1216
- if (input[key] !== void 0 && (typeof input[key] !== "number" || !Number.isFinite(input[key])))
1217
- fail(where, `"${key}" must be a finite number`);
1218
- if (input.integer !== void 0 && typeof input.integer !== "boolean")
1219
- fail(where, '"integer" must be a boolean');
1220
- out.integer = input.integer === true;
1221
- out.min = input.min === void 0 ? -Number.MAX_SAFE_INTEGER : input.min;
1222
- out.max = input.max === void 0 ? Number.MAX_SAFE_INTEGER : input.max;
1223
- if (out.min > out.max) fail(where, '"min" must not be greater than "max"');
1224
- if (input.default !== void 0) {
1225
- if (input.default < out.min || input.default > out.max || out.integer && !Number.isInteger(input.default))
1226
- fail(where, '"default" must be a valid value of the field');
1227
- out.default = input.default;
1761
+ flush();
1762
+ const tag = nameMatch[0].toLowerCase();
1763
+ const body = html.slice(i + (closing ? 2 : 1) + nameMatch[0].length, end);
1764
+ i = end + 1;
1765
+ if (closing) {
1766
+ if (!ALLOWED.has(tag)) continue;
1767
+ for (let s = stack.length - 1; s > 0; s -= 1) {
1768
+ if (stack[s].tag === tag) {
1769
+ stack.length = s;
1770
+ break;
1771
+ }
1228
1772
  }
1229
- break;
1773
+ continue;
1230
1774
  }
1231
- case "boolean":
1232
- if (input.default !== void 0 && typeof input.default !== "boolean")
1233
- fail(where, '"default" must be a boolean');
1234
- out.default = input.default === true;
1235
- break;
1236
- case "array":
1237
- if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1238
- out.max = boundedInt(input.max, 1, BLOCK_LIMITS.maxItems, BLOCK_LIMITS.defaultItems, where, "max");
1239
- out.items = normalizeField(input.items, `${where}[]`, depth + 1);
1240
- break;
1241
- case "object":
1242
- if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1243
- out.fields = normalizeFields(input.fields, where, depth + 1);
1244
- break;
1245
- default:
1246
- break;
1247
- }
1248
- return Object.freeze(out);
1249
- };
1250
- var normalizeFields = (input, where, depth) => {
1251
- if (!isObject(input)) fail(where, '"fields" must be an object of field descriptors');
1252
- const keys = Object.keys(input);
1253
- if (keys.length < 1 || keys.length > BLOCK_LIMITS.maxFields)
1254
- fail(where, `an object needs 1 to ${BLOCK_LIMITS.maxFields} fields`);
1255
- const out = /* @__PURE__ */ Object.create(null);
1256
- for (const key of keys) {
1257
- if (!KEY_PATTERN.test(key) || FORBIDDEN_KEYS2.has(key))
1258
- fail(where, `field name ${JSON.stringify(key)} must match ${KEY_PATTERN}`);
1259
- out[key] = normalizeField(input[key], `${where}.${key}`, depth);
1775
+ if (DROP_WITH_CONTENT.has(tag)) {
1776
+ const selfClosing = /\/\s*$/.test(body);
1777
+ if (selfClosing) continue;
1778
+ const closeIndex = html.slice(i).search(new RegExp(`</${tag}[\\s/>]`, "i"));
1779
+ if (closeIndex === -1) break;
1780
+ const closeEnd = html.indexOf(">", i + closeIndex);
1781
+ i = closeEnd === -1 ? html.length : closeEnd + 1;
1782
+ continue;
1783
+ }
1784
+ if (!ALLOWED.has(tag) || nodes >= MAX_NODES) continue;
1785
+ const attribs = parseAttributes(body);
1786
+ const special = specialElement(tag, attribs, options);
1787
+ const element = {
1788
+ type: "element",
1789
+ tag,
1790
+ attrs: special ? special.attrs : cleanAttributes(tag, attribs, options),
1791
+ children: []
1792
+ };
1793
+ if (special && special.note) element.note = special.note;
1794
+ stack[stack.length - 1].children.push(element);
1795
+ nodes += 1;
1796
+ if (!VOID.has(tag) && stack.length < MAX_DEPTH) stack.push(element);
1260
1797
  }
1261
- return Object.freeze(out);
1262
- };
1263
- var blockNameProblem = (name) => {
1264
- if (typeof name !== "string" || !BLOCK_NAME_PATTERN.test(name))
1265
- return `the name must match ${BLOCK_NAME_PATTERN}`;
1266
- if (RESERVED.has(name.toLowerCase())) return `"${name}" is a built-in tool name`;
1267
- return null;
1798
+ flush();
1799
+ return finalizeSpecial(root.children);
1268
1800
  };
1269
- var defineBlock = (definition) => {
1270
- if (!isObject(definition))
1271
- throw new BlockDefinitionError("Magic Editor X block: the definition must be an object");
1272
- const label2 = typeof definition.name === "string" ? `"${definition.name.slice(0, 50)}"` : "(no name)";
1273
- for (const key of Object.keys(definition))
1274
- if (!DEFINITION_KEYS.has(key)) fail(label2, `unknown key "${key}"`);
1275
- const problem = blockNameProblem(definition.name);
1276
- if (problem)
1277
- throw new BlockDefinitionError(
1278
- `Magic Editor X block ${label2}: ${problem}`,
1279
- problem.includes("built-in") ? "RESERVED_NAME" : "INVALID_DEFINITION"
1280
- );
1281
- const out = {
1282
- name: definition.name,
1283
- version: boundedInt(definition.version, 1, 1e6, 1, label2, "version")
1284
- };
1285
- for (const [key, max] of [
1286
- ["title", 100],
1287
- ["description", 500]
1288
- ]) {
1289
- if (definition[key] === void 0) continue;
1290
- if (typeof definition[key] !== "string" || definition[key].length > max)
1291
- fail(label2, `"${key}" must be a string of at most ${max} characters`);
1292
- out[key] = definition[key];
1801
+ var resolveLinkAttributes = (attrs, resolver) => {
1802
+ if (typeof resolver !== "function" || !attrs["data-mex-uid"] || !attrs["data-mex-document-id"])
1803
+ return attrs;
1804
+ let result;
1805
+ try {
1806
+ result = resolver({
1807
+ uid: attrs["data-mex-uid"],
1808
+ documentId: attrs["data-mex-document-id"],
1809
+ locale: attrs["data-mex-locale"] || null,
1810
+ href: attrs.href || null,
1811
+ ...isMentionLink(attrs) ? { mention: true } : {}
1812
+ });
1813
+ } catch {
1814
+ result = void 0;
1293
1815
  }
1294
- out.schema = normalizeFields(definition.schema, `${label2} schema`, 0);
1295
- for (const key of ["sanitize", "text", "markdown", "render"]) {
1296
- if (definition[key] === void 0) continue;
1297
- if (typeof definition[key] !== "function") fail(label2, `"${key}" must be a function`);
1298
- out[key] = definition[key];
1816
+ if (result === false) return null;
1817
+ if (typeof result === "string") {
1818
+ const url = sanitizeUrl(result);
1819
+ if (url) return { ...attrs, href: url };
1299
1820
  }
1300
- const presets = definition.presets === void 0 ? [] : definition.presets;
1301
- if (!Array.isArray(presets) || presets.some((preset) => !BLOCK_PRESETS.includes(preset)))
1302
- fail(label2, `"presets" must list some of ${BLOCK_PRESETS.join(", ")}`);
1303
- out.presets = Object.freeze([...new Set(presets)]);
1304
- return Object.freeze(out);
1821
+ return attrs;
1305
1822
  };
1306
- var cleanValue = (field, value, inline, budget) => {
1307
- budget.left -= 1;
1308
- switch (field.type) {
1309
- case "text":
1310
- return typeof value === "string" ? value.slice(0, field.max) : field.default;
1311
- case "inline":
1312
- return inline(typeof value === "string" ? value.slice(0, field.max) : field.default);
1313
- case "url":
1314
- return typeof value === "string" ? sanitizeUrl(value.slice(0, BLOCK_LIMITS.maxUrl), {
1315
- schemes: field.schemes,
1316
- allowRelative: field.relative
1317
- }) : "";
1318
- case "enum":
1319
- return typeof value === "string" && field.values.includes(value) ? value : field.default;
1320
- case "number":
1321
- return typeof value === "number" && Number.isFinite(value) && value >= field.min && value <= field.max && (!field.integer || Number.isInteger(value)) ? value : field.default;
1322
- case "boolean":
1323
- return typeof value === "boolean" ? value : field.default;
1324
- case "array": {
1325
- const out = [];
1326
- if (!Array.isArray(value)) return out;
1327
- for (const item of value) {
1328
- if (out.length >= field.max || budget.left <= 0) break;
1329
- if (!matchesType(field.items, item)) continue;
1330
- const clean = cleanValue(field.items, item, inline, budget);
1331
- if (clean !== void 0) out.push(clean);
1823
+ var ATTRIBUTE_ORDER = [
1824
+ "href",
1825
+ "target",
1826
+ "rel",
1827
+ "title",
1828
+ "class",
1829
+ "data-tooltip",
1830
+ "data-mex-uid",
1831
+ "data-mex-document-id",
1832
+ "data-mex-locale",
1833
+ "data-mex-mention",
1834
+ MATH_ATTRIBUTE,
1835
+ "data-mex-footnote",
1836
+ "data-mex-note"
1837
+ ];
1838
+ var RENDER_STATE = /* @__PURE__ */ Symbol.for("magic-editor-x.render-state");
1839
+ var storedNote = (note) => serializeNodes(inlineNodesToRender(note || [], { storage: true }));
1840
+ var MENTION_CLASS = "mex-mention";
1841
+ var inlineNodesToRender = (nodes, options = {}) => {
1842
+ const out = [];
1843
+ const state = options[RENDER_STATE];
1844
+ for (const node of nodes) {
1845
+ if (node.type === "text") {
1846
+ out.push({ type: "text", value: node.value });
1847
+ continue;
1848
+ }
1849
+ if (node.tag === "br") {
1850
+ out.push({ type: "element", tag: "br", attrs: {}, children: [] });
1851
+ continue;
1852
+ }
1853
+ if (isMathNode(node)) {
1854
+ const tex = nodesToText(node.children);
1855
+ if (state && !options.storage) {
1856
+ if (tex.trim()) out.push(state.math(tex, false));
1857
+ continue;
1332
1858
  }
1333
- return out;
1859
+ out.push({
1860
+ type: "element",
1861
+ tag: "span",
1862
+ attrs: { [MATH_ATTRIBUTE]: "true" },
1863
+ children: tex ? [{ type: "text", value: tex }] : []
1864
+ });
1865
+ continue;
1866
+ }
1867
+ if (isFootnoteNode(node)) {
1868
+ if (state && !options.storage) {
1869
+ out.push(state.footnote(node));
1870
+ continue;
1871
+ }
1872
+ const attrs2 = { "data-mex-footnote": node.attrs["data-mex-footnote"] };
1873
+ const note = storedNote(node.note);
1874
+ if (note) attrs2["data-mex-note"] = note;
1875
+ out.push({ type: "element", tag: "sup", attrs: attrs2, children: inlineNodesToRender(node.children, options) });
1876
+ continue;
1877
+ }
1878
+ if (isColorNode(node) || isHighlightNode(node)) {
1879
+ const color = node.tag === "span";
1880
+ const name = color ? COLOR_ATTRIBUTE : HIGHLIGHT_ATTRIBUTE;
1881
+ const token = node.attrs[name];
1882
+ out.push({
1883
+ type: "element",
1884
+ tag: node.tag,
1885
+ attrs: options.storage ? { [name]: token } : { class: color ? colorClass(token) : highlightClass(token), [name]: token },
1886
+ children: inlineNodesToRender(node.children, options)
1887
+ });
1888
+ continue;
1889
+ }
1890
+ if (isAnnotationNode(node)) {
1891
+ const children = inlineNodesToRender(node.children, options);
1892
+ if (options.storage) out.push({ type: "element", tag: "span", attrs: { ...node.attrs }, children });
1893
+ else out.push(...renderAnnotation(node, children, options));
1894
+ continue;
1895
+ }
1896
+ let attrs = node.attrs;
1897
+ if (node.tag === "a") {
1898
+ attrs = resolveLinkAttributes(attrs, options.links);
1899
+ if (!attrs || !attrs.href) {
1900
+ out.push(...inlineNodesToRender(node.children, options));
1901
+ continue;
1902
+ }
1903
+ if (attrs.target === "_blank") {
1904
+ const rel = new Set(
1905
+ String(attrs.rel || "").split(/\s+/).filter(Boolean)
1906
+ );
1907
+ rel.add("noopener");
1908
+ rel.add("noreferrer");
1909
+ attrs = { ...attrs, rel: Array.from(rel).sort().join(" ") };
1910
+ }
1911
+ if (!options.storage && isMentionLink(attrs)) attrs = { ...attrs, class: MENTION_CLASS };
1912
+ }
1913
+ const ordered = {};
1914
+ for (const name of ATTRIBUTE_ORDER) {
1915
+ if (attrs[name] !== void 0 && attrs[name] !== "") ordered[name] = String(attrs[name]);
1334
1916
  }
1335
- case "object":
1336
- return cleanObject(field.fields, isObject(value) ? value : {}, inline, budget);
1337
- default:
1338
- return void 0;
1917
+ out.push({
1918
+ type: "element",
1919
+ tag: node.tag,
1920
+ attrs: ordered,
1921
+ children: inlineNodesToRender(node.children, options)
1922
+ });
1339
1923
  }
1924
+ return out;
1340
1925
  };
1341
- var matchesType = (field, item) => {
1342
- switch (field.type) {
1343
- case "text":
1344
- case "inline":
1345
- case "url":
1346
- case "enum":
1347
- return typeof item === "string";
1348
- case "number":
1349
- return typeof item === "number";
1350
- case "boolean":
1351
- return typeof item === "boolean";
1352
- case "array":
1353
- return Array.isArray(item);
1354
- default:
1355
- return isObject(item);
1926
+ var annotationLists = /* @__PURE__ */ new WeakMap();
1927
+ var annotationDefinition = (name, options) => {
1928
+ const list = options.annotations;
1929
+ if (Array.isArray(list)) {
1930
+ if (!annotationLists.has(list)) {
1931
+ const map = /* @__PURE__ */ new Map();
1932
+ for (const item of list.slice(0, ANNOTATION_LIMITS.registered))
1933
+ if (item && typeof item === "object" && typeof item.name === "string" && item.attributes)
1934
+ map.set(item.name, item);
1935
+ annotationLists.set(list, map);
1936
+ }
1937
+ const found = annotationLists.get(list).get(name);
1938
+ if (found) return found;
1356
1939
  }
1940
+ return activeAnnotation(name);
1357
1941
  };
1358
- var cleanObject = (fields, value, inline, budget) => {
1942
+ var resolvedValue = (options, annotation) => {
1943
+ if (typeof options.resolveAnnotation !== "function") return void 0;
1944
+ let value;
1945
+ try {
1946
+ value = options.resolveAnnotation(annotation);
1947
+ } catch {
1948
+ return void 0;
1949
+ }
1950
+ if (typeof value === "string") return value.slice(0, 2e3);
1951
+ if (value && typeof value === "object" && !Array.isArray(value)) return value;
1952
+ return void 0;
1953
+ };
1954
+ var renderAnnotation = (node, children, options) => {
1955
+ const { name, attrs } = annotationOf(node);
1956
+ const definition = annotationDefinition(name, options);
1957
+ const values = definition ? cleanAnnotationAttributes(definition, attrs) : attrs;
1958
+ if (!values) return children;
1959
+ if (definition && typeof definition.render === "function") {
1960
+ const text = nodesToText(node.children);
1961
+ let out;
1962
+ try {
1963
+ out = definition.render({
1964
+ name,
1965
+ attrs: { ...values },
1966
+ text,
1967
+ resolved: resolvedValue(options, { name, attrs: { ...values }, text })
1968
+ });
1969
+ } catch {
1970
+ out = void 0;
1971
+ }
1972
+ if (out === false) return children;
1973
+ const wrapper = cleanAnnotationWrapper(out);
1974
+ if (wrapper) return [{ type: "element", tag: wrapper.tag, attrs: wrapper.attrs, children }];
1975
+ }
1976
+ return [
1977
+ {
1978
+ type: "element",
1979
+ tag: "span",
1980
+ attrs: {
1981
+ class: `mex-annotation mex-annotation-${name}`,
1982
+ ...annotationAttributes(name, definition ? values : {})
1983
+ },
1984
+ children
1985
+ }
1986
+ ];
1987
+ };
1988
+ var inlineToNodes = (html, options) => inlineNodesToRender(parseInline(html), options);
1989
+ var nodesToHtml = (nodes, options = {}) => serializeNodes(inlineNodesToRender(nodes, options));
1990
+ var nodesToText = (nodes, options = {}) => nodes.map((node) => {
1991
+ if (node.type === "text") return node.value;
1992
+ if (node.tag === "br") return "\n";
1993
+ if (!options.raw && isFootnoteNode(node))
1994
+ return typeof options.footnote === "function" ? options.footnote(node) : "";
1995
+ return nodesToText(node.children, options);
1996
+ }).join("");
1997
+ var inlineToHtml = (html, options) => nodesToHtml(parseInline(html), options);
1998
+ var inlineToText = (html, options) => nodesToText(parseInline(html), options).replace(/\u00a0/g, " ");
1999
+
2000
+ // shared/render/mathml.mjs
2001
+ var MATHML_TAGS = Object.freeze([
2002
+ "math",
2003
+ "semantics",
2004
+ "annotation",
2005
+ "mrow",
2006
+ "mi",
2007
+ "mn",
2008
+ "mo",
2009
+ "ms",
2010
+ "mtext",
2011
+ "mspace",
2012
+ "msub",
2013
+ "msup",
2014
+ "msubsup",
2015
+ "munder",
2016
+ "mover",
2017
+ "munderover",
2018
+ "mfrac",
2019
+ "msqrt",
2020
+ "mroot",
2021
+ "mstyle",
2022
+ "merror",
2023
+ "mpadded",
2024
+ "mphantom",
2025
+ "mtable",
2026
+ "mtr",
2027
+ "mtd",
2028
+ "mlabeledtr",
2029
+ "mmultiscripts",
2030
+ "mprescripts",
2031
+ "none",
2032
+ "menclose"
2033
+ ]);
2034
+ var TAGS = new Set(MATHML_TAGS);
2035
+ var COMMON_ATTRIBUTES = /* @__PURE__ */ new Set([
2036
+ "dir",
2037
+ "displaystyle",
2038
+ "scriptlevel",
2039
+ "mathvariant",
2040
+ "mathsize",
2041
+ "mathcolor",
2042
+ "mathbackground"
2043
+ ]);
2044
+ var ELEMENT_ATTRIBUTES = Object.freeze({
2045
+ math: ["display"],
2046
+ mo: [
2047
+ "form",
2048
+ "fence",
2049
+ "separator",
2050
+ "stretchy",
2051
+ "symmetric",
2052
+ "largeop",
2053
+ "movablelimits",
2054
+ "lspace",
2055
+ "rspace",
2056
+ "minsize",
2057
+ "maxsize",
2058
+ "accent"
2059
+ ],
2060
+ mspace: ["width", "height", "depth"],
2061
+ mpadded: ["width", "height", "depth", "lspace", "voffset"],
2062
+ mfrac: ["linethickness"],
2063
+ mover: ["accent"],
2064
+ munder: ["accentunder"],
2065
+ munderover: ["accent", "accentunder"],
2066
+ mtable: [
2067
+ "columnalign",
2068
+ "rowalign",
2069
+ "columnspacing",
2070
+ "rowspacing",
2071
+ "columnlines",
2072
+ "rowlines",
2073
+ "frame",
2074
+ "framespacing",
2075
+ "equalrows",
2076
+ "equalcolumns",
2077
+ "side"
2078
+ ],
2079
+ mtr: ["columnalign", "rowalign"],
2080
+ mlabeledtr: ["columnalign", "rowalign"],
2081
+ mtd: ["columnalign", "rowalign", "columnspan", "rowspan"],
2082
+ menclose: ["notation"],
2083
+ annotation: ["encoding"]
2084
+ });
2085
+ var ATTRIBUTE_VALUE = /^[A-Za-z0-9 .%#+-]{0,100}$/;
2086
+ var COLOR_VALUE = /^(?:#[0-9A-Fa-f]{3,8}|[A-Za-z]{1,30})$/;
2087
+ var CLASS_TOKEN2 = /^tml-[a-z0-9-]{1,40}$/;
2088
+ var TEX_ENCODING = "application/x-tex";
2089
+ var MAX_INPUT2 = 2e5;
2090
+ var MAX_NODES2 = 2e4;
2091
+ var MAX_DEPTH2 = 64;
2092
+ var parseAttributes2 = (source) => {
1359
2093
  const out = {};
1360
- for (const key of Object.keys(fields)) {
1361
- const own = Object.prototype.hasOwnProperty.call(value, key) ? value[key] : void 0;
1362
- const clean = cleanValue(fields[key], own, inline, budget);
1363
- if (clean !== void 0) out[key] = clean;
2094
+ const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
2095
+ let match;
2096
+ while (match = pattern.exec(source)) {
2097
+ const name = match[1].toLowerCase();
2098
+ if (Object.prototype.hasOwnProperty.call(out, name)) continue;
2099
+ out[name] = decodeEntities(match[2] ?? match[3] ?? match[4] ?? "");
1364
2100
  }
1365
2101
  return out;
1366
2102
  };
1367
- var eachLeaf = (fields, data, visit) => {
1368
- const walk = (field, value, path, depth) => {
1369
- if (depth > BLOCK_LIMITS.maxDepth + 1) return;
1370
- if (field.type === "array") {
1371
- if (!Array.isArray(value)) return;
1372
- value.slice(0, field.max).forEach((item, index) => walk(field.items, item, [...path, index], depth + 1));
1373
- } else if (field.type === "object") {
1374
- if (!isObject(value)) return;
1375
- for (const key of Object.keys(field.fields))
1376
- if (Object.prototype.hasOwnProperty.call(value, key))
1377
- walk(field.fields[key], value[key], [...path, key], depth + 1);
1378
- } else visit(field, value, path);
1379
- };
1380
- if (!isObject(data)) return;
1381
- for (const key of Object.keys(fields))
1382
- if (Object.prototype.hasOwnProperty.call(data, key)) walk(fields[key], data[key], [key], 0);
2103
+ var styleColor = (style, property) => {
2104
+ const pattern = property === "color" ? /(?:^|;)\s*color\s*:\s*([^;]+)/i : /background-color\s*:\s*([^;]+)/i;
2105
+ const match = pattern.exec(style);
2106
+ const value = match ? match[1].trim() : "";
2107
+ return COLOR_VALUE.test(value) ? value : "";
1383
2108
  };
1384
- var fieldAt = (fields, path) => {
1385
- let current = { type: "object", fields };
1386
- for (const part of String(path).split(".")) {
1387
- if (!part) continue;
1388
- if (current.type === "array") {
1389
- if (/^\d+$/.test(part)) {
1390
- current = current.items;
1391
- continue;
1392
- }
1393
- return null;
2109
+ var cleanAttributes2 = (tag, attribs) => {
2110
+ const out = {};
2111
+ const allowed = ELEMENT_ATTRIBUTES[tag] || [];
2112
+ for (const [name, raw] of Object.entries(attribs)) {
2113
+ if (typeof raw !== "string" && typeof raw !== "number" && raw !== true) continue;
2114
+ const value = raw === true ? "true" : String(raw);
2115
+ if (name === "class") {
2116
+ const classes2 = value.split(/\s+/).filter((token) => CLASS_TOKEN2.test(token));
2117
+ if (classes2.length) out.class = classes2.slice(0, 8).join(" ");
2118
+ continue;
1394
2119
  }
1395
- if (current.type !== "object" || !Object.prototype.hasOwnProperty.call(current.fields, part)) return null;
1396
- current = current.fields[part];
1397
- }
1398
- return current;
2120
+ if (name === "encoding") {
2121
+ if (tag === "annotation" && value === TEX_ENCODING) out.encoding = value;
2122
+ continue;
2123
+ }
2124
+ if (name === "mathcolor" || name === "mathbackground") {
2125
+ if (COLOR_VALUE.test(value)) out[name] = value;
2126
+ continue;
2127
+ }
2128
+ if (!COMMON_ATTRIBUTES.has(name) && !allowed.includes(name)) continue;
2129
+ if (ATTRIBUTE_VALUE.test(value)) out[name] = value;
2130
+ }
2131
+ if (typeof attribs.style === "string") {
2132
+ const color = styleColor(attribs.style, "color");
2133
+ const background = styleColor(attribs.style, "background-color");
2134
+ if (color && !out.mathcolor) out.mathcolor = color;
2135
+ if (background && !out.mathbackground) out.mathbackground = background;
2136
+ }
2137
+ if (tag === "annotation" && out.encoding !== TEX_ENCODING) return null;
2138
+ if (tag === "math" && out.display && out.display !== "block" && out.display !== "inline")
2139
+ delete out.display;
2140
+ return out;
1399
2141
  };
1400
- var compiled = /* @__PURE__ */ new WeakMap();
1401
- var compileBlock = (definition) => {
1402
- if (definition && typeof definition === "object" && compiled.has(definition))
1403
- return compiled.get(definition);
1404
- const def = defineBlock(definition && typeof definition === "object" ? { ...definition } : definition);
1405
- const schema = def.schema;
1406
- const run = (data, inline) => cleanObject(schema, isObject(data) ? data : {}, inline, { left: BLOCK_LIMITS.maxValues });
1407
- const result = Object.freeze({
1408
- ...def,
1409
- /**
1410
- * Cleans untrusted block data (unknown keys dropped, values bounded).
1411
- * The optional `sanitize` hook runs on the clean data; its result is
1412
- * cleaned again, so it cannot add keys or unsafe values. A hook that
1413
- * throws is ignored (the clean data is used).
1414
- * @param {unknown} data - Block data.
1415
- * @param {(html: string) => string} inline - Inline HTML sanitiser of the caller.
1416
- * @returns {object} Clean data.
1417
- */
1418
- clean: (data, inline) => {
1419
- const first = run(data, inline);
1420
- if (!def.sanitize) return first;
1421
- let next;
1422
- try {
1423
- next = def.sanitize(copyData(first), { sanitizeUrl });
1424
- } catch {
1425
- return first;
2142
+ var tokenize = (input) => {
2143
+ const source = input.slice(0, MAX_INPUT2);
2144
+ const root = { type: "element", tag: "#root", attrs: {}, children: [] };
2145
+ const stack = [root];
2146
+ let count = 0;
2147
+ let i = 0;
2148
+ const pushText = (text) => {
2149
+ if (!text) return;
2150
+ const parent = stack[stack.length - 1];
2151
+ const last = parent.children[parent.children.length - 1];
2152
+ const value = decodeEntities(text);
2153
+ if (last && last.type === "text") last.value += value;
2154
+ else if (count < MAX_NODES2) {
2155
+ parent.children.push({ type: "text", value });
2156
+ count += 1;
2157
+ }
2158
+ };
2159
+ while (i < source.length) {
2160
+ const lt = source.indexOf("<", i);
2161
+ if (lt === -1) {
2162
+ pushText(source.slice(i));
2163
+ break;
2164
+ }
2165
+ pushText(source.slice(i, lt));
2166
+ if (source.startsWith("<!--", lt)) {
2167
+ const end2 = source.indexOf("-->", lt + 4);
2168
+ i = end2 === -1 ? source.length : end2 + 3;
2169
+ continue;
2170
+ }
2171
+ if (source[lt + 1] === "!" || source[lt + 1] === "?") {
2172
+ const end2 = source.indexOf(">", lt + 2);
2173
+ i = end2 === -1 ? source.length : end2 + 1;
2174
+ continue;
2175
+ }
2176
+ const closing = source[lt + 1] === "/";
2177
+ const nameMatch = /^[A-Za-z][A-Za-z0-9:-]{0,40}/.exec(source.slice(lt + (closing ? 2 : 1), lt + 45));
2178
+ let end = -1;
2179
+ let quote = "";
2180
+ for (let j = lt + 1; j < source.length; j += 1) {
2181
+ const char = source[j];
2182
+ if (quote) {
2183
+ if (char === quote) quote = "";
2184
+ } else if (char === '"' || char === "'") quote = char;
2185
+ else if (char === ">") {
2186
+ end = j;
2187
+ break;
1426
2188
  }
1427
- return isObject(next) ? run(next, inline) : first;
1428
- },
1429
- /**
1430
- * Text fields of the data in schema order: `{ path, kind, value }`
1431
- * (`html` for inline fields, `plain` for text fields).
1432
- * @param {unknown} data - Block data.
1433
- * @returns {Array<{ path: Array<string|number>, kind: 'html'|'plain', value: string }>} Fields.
1434
- */
1435
- fields: (data) => {
1436
- const out = [];
1437
- eachLeaf(schema, data, (field, value, path) => {
1438
- if (typeof value !== "string") return;
1439
- if (field.type === "inline") out.push({ path, kind: "html", value });
1440
- else if (field.type === "text") out.push({ path, kind: "plain", value });
1441
- });
1442
- return out;
1443
- },
1444
- /**
1445
- * Non-empty URL values: `{ path, value }`.
1446
- * @param {unknown} data - Block data.
1447
- * @returns {Array<{ path: Array<string|number>, value: string }>} URLs.
1448
- */
1449
- urls: (data) => {
1450
- const out = [];
1451
- eachLeaf(schema, data, (field, value, path) => {
1452
- if (field.type === "url" && typeof value === "string" && value) out.push({ path, value });
1453
- });
1454
- return out;
1455
- },
1456
- /**
1457
- * Kind of the value at a dotted path, for the version diff.
1458
- * @param {string} path - Dotted path.
1459
- * @returns {'inline'|'plain'|'value'} Kind.
1460
- */
1461
- kindOf: (path) => {
1462
- const field = fieldAt(schema, path);
1463
- if (!field) return "value";
1464
- if (field.type === "inline") return "inline";
1465
- if (field.type === "text") return "plain";
1466
- return "value";
1467
2189
  }
1468
- });
1469
- compiled.set(result, result);
1470
- if (definition && typeof definition === "object") compiled.set(definition, result);
1471
- return result;
2190
+ if (!nameMatch || end === -1) {
2191
+ pushText(source.slice(lt, end === -1 ? source.length : lt + 1));
2192
+ i = end === -1 ? source.length : lt + 1;
2193
+ continue;
2194
+ }
2195
+ const tag = nameMatch[0].toLowerCase();
2196
+ const body = source.slice(lt + (closing ? 2 : 1) + nameMatch[0].length, end);
2197
+ i = end + 1;
2198
+ if (closing) {
2199
+ for (let s = stack.length - 1; s > 0; s -= 1) {
2200
+ if (stack[s].tag === tag) {
2201
+ stack.length = s;
2202
+ break;
2203
+ }
2204
+ }
2205
+ continue;
2206
+ }
2207
+ if (count >= MAX_NODES2) continue;
2208
+ const element = { type: "element", tag, attrs: parseAttributes2(body), children: [] };
2209
+ stack[stack.length - 1].children.push(element);
2210
+ count += 1;
2211
+ const selfClosing = /\/\s*$/.test(body);
2212
+ if (!selfClosing && stack.length < MAX_DEPTH2) stack.push(element);
2213
+ }
2214
+ return root.children;
1472
2215
  };
1473
- var copyData = (value) => {
1474
- if (Array.isArray(value)) return value.map(copyData);
1475
- if (isObject(value)) {
1476
- const out = {};
1477
- for (const [key, child] of Object.entries(value)) out[key] = copyData(child);
1478
- return out;
2216
+ var clean = (nodes, ctx, depth, inAnnotation) => {
2217
+ const out = [];
2218
+ if (!Array.isArray(nodes) || depth > MAX_DEPTH2) return out;
2219
+ for (const node of nodes) {
2220
+ if (ctx.budget <= 0) break;
2221
+ if (typeof node === "string") {
2222
+ ctx.budget -= 1;
2223
+ if (node) out.push({ type: "text", value: node });
2224
+ continue;
2225
+ }
2226
+ if (!node || typeof node !== "object") continue;
2227
+ ctx.budget -= 1;
2228
+ if (node.type === "text") {
2229
+ if (typeof node.value === "string" && node.value) out.push({ type: "text", value: node.value });
2230
+ continue;
2231
+ }
2232
+ if (node.type !== "element" || typeof node.tag !== "string" || inAnnotation) continue;
2233
+ const tag = node.tag.toLowerCase();
2234
+ if (!TAGS.has(tag)) continue;
2235
+ const attrs = cleanAttributes2(tag, node.attrs && typeof node.attrs === "object" ? node.attrs : {});
2236
+ if (!attrs) continue;
2237
+ const children = clean(node.children, ctx, depth + 1, tag === "annotation");
2238
+ out.push({ type: "element", tag, attrs, children });
1479
2239
  }
1480
- return value;
2240
+ return out;
1481
2241
  };
1482
- var listCache = /* @__PURE__ */ new WeakMap();
1483
- var compileBlockList = (list) => {
1484
- if (!Array.isArray(list)) return /* @__PURE__ */ new Map();
1485
- if (listCache.has(list)) return listCache.get(list);
1486
- const map = /* @__PURE__ */ new Map();
1487
- for (const definition of list) {
1488
- const def = compileBlock(definition);
1489
- map.set(def.name, def);
2242
+ var cleanMathResult = (result) => {
2243
+ let nodes;
2244
+ if (typeof result === "string") nodes = tokenize(result);
2245
+ else if (Array.isArray(result)) nodes = result;
2246
+ else if (result && typeof result === "object") nodes = [result];
2247
+ else return [];
2248
+ const top = nodes.filter(
2249
+ (node) => node && typeof node === "object" && node.type === "element" && String(node.tag).toLowerCase() === "math"
2250
+ );
2251
+ return clean(top, { budget: MAX_NODES2 }, 0, false);
2252
+ };
2253
+
2254
+ // shared/render/math-notes.mjs
2255
+ var DEFAULT_FOOTNOTES_LABEL = "Footnotes";
2256
+ var DEFAULT_FOOTNOTE_BACK_LABEL = "Back to reference {n}";
2257
+ var DEFAULT_FOOTNOTE_PREFIX = "mex-";
2258
+ var PREFIX = /^[A-Za-z][A-Za-z0-9_-]{0,40}$/;
2259
+ var label = (value, fallback) => {
2260
+ if (typeof value !== "string") return fallback;
2261
+ const clean2 = value.trim();
2262
+ return clean2 && clean2.length <= 80 ? clean2 : fallback;
2263
+ };
2264
+ var footnoteOptions = (options) => {
2265
+ const source = isPlainObject2(options && options.footnotes) ? options.footnotes : {};
2266
+ return {
2267
+ label: label(source.label, DEFAULT_FOOTNOTES_LABEL),
2268
+ backLabel: label(source.backLabel, DEFAULT_FOOTNOTE_BACK_LABEL),
2269
+ prefix: typeof source.prefix === "string" && PREFIX.test(source.prefix) ? source.prefix : DEFAULT_FOOTNOTE_PREFIX
2270
+ };
2271
+ };
2272
+ var createFootnoteNumbers = () => {
2273
+ const used = /* @__PURE__ */ new Map();
2274
+ let count = 0;
2275
+ return {
2276
+ add(id) {
2277
+ const seen = (used.get(id) || 0) + 1;
2278
+ used.set(id, seen);
2279
+ count += 1;
2280
+ return { n: count, anchor: seen === 1 ? id : `${id}-${seen}` };
2281
+ }
2282
+ };
2283
+ };
2284
+ var renderMathNodes = (options, tex, display) => {
2285
+ if (!options || typeof options.math !== "function" || !tex.trim()) return [];
2286
+ let result;
2287
+ try {
2288
+ result = options.math(tex, { display });
2289
+ } catch {
2290
+ return [];
1490
2291
  }
1491
- listCache.set(list, map);
1492
- return map;
2292
+ return cleanMathResult(result);
2293
+ };
2294
+ var mathElement = (options, tex, kind) => {
2295
+ const math = renderMathNodes(options, tex, kind.display);
2296
+ const attrs = {
2297
+ class: kind.className || (kind.display ? "mex-math mex-math-display" : "mex-math"),
2298
+ "data-mex-math": kind.display ? "display" : "inline"
2299
+ };
2300
+ const children = math.length ? math : kind.display ? `\\[${tex}\\]` : `\\(${tex}\\)`;
2301
+ return el(kind.block ? "div" : "span", attrs, children);
2302
+ };
2303
+ var createFootnoteTree = (options, renderNote) => {
2304
+ const { label: listLabel, backLabel, prefix } = footnoteOptions(options);
2305
+ const numbers = createFootnoteNumbers();
2306
+ const items = [];
2307
+ const labelId = `${prefix}footnotes-label`;
2308
+ return {
2309
+ marker(node) {
2310
+ const { n, anchor } = numbers.add(node.attrs["data-mex-footnote"]);
2311
+ items.push({ n, anchor, note: node.note || [] });
2312
+ return el(
2313
+ "sup",
2314
+ { class: "mex-footnote-ref" },
2315
+ el(
2316
+ "a",
2317
+ {
2318
+ href: `#${prefix}fn-${anchor}`,
2319
+ id: `${prefix}fnref-${anchor}`,
2320
+ "aria-describedby": labelId
2321
+ },
2322
+ String(n)
2323
+ )
2324
+ );
2325
+ },
2326
+ section() {
2327
+ if (!items.length) return null;
2328
+ return el("section", { class: "mex-footnotes", "aria-labelledby": labelId }, [
2329
+ el("h2", { id: labelId, class: "mex-footnotes-label" }, listLabel),
2330
+ el(
2331
+ "ol",
2332
+ { class: "mex-footnotes-list" },
2333
+ items.map(
2334
+ (item) => el("li", { id: `${prefix}fn-${item.anchor}`, class: "mex-footnote" }, [
2335
+ renderNote(item.note),
2336
+ " ",
2337
+ el(
2338
+ "a",
2339
+ {
2340
+ href: `#${prefix}fnref-${item.anchor}`,
2341
+ class: "mex-footnote-back",
2342
+ "aria-label": backLabel.replace(/\{n\}/g, String(item.n))
2343
+ },
2344
+ "\u21A9"
2345
+ )
2346
+ ])
2347
+ )
2348
+ )
2349
+ ]);
2350
+ }
2351
+ };
1493
2352
  };
1494
2353
 
1495
2354
  // shared/toc.mjs
@@ -1716,12 +2575,12 @@ var prepareBlocks = (value, options = {}) => {
1716
2575
  const raw = isPlainObject2(block.data) ? block.data : {};
1717
2576
  const known = isBuiltInBlock({ type: block.type, data: raw });
1718
2577
  const definition = known ? null : registeredBlockOf({ type: block.type, data: raw }, explicit);
1719
- const clean = known ? BLOCK_POLICIES[block.type](raw, keepInline, ctx) : definition ? definition.clean(raw, keepInline) : raw;
1720
- for (const key of Object.keys(clean)) if (clean[key] === void 0) delete clean[key];
2578
+ const clean2 = known ? BLOCK_POLICIES[block.type](raw, keepInline, ctx) : definition ? definition.clean(raw, keepInline) : raw;
2579
+ for (const key of Object.keys(clean2)) if (clean2[key] === void 0) delete clean2[key];
1721
2580
  return {
1722
2581
  id: block.id,
1723
2582
  type: block.type,
1724
- data: clean,
2583
+ data: clean2,
1725
2584
  raw,
1726
2585
  tunes: sanitizeTunes(block.tunes),
1727
2586
  known,
@@ -1751,10 +2610,10 @@ var imageCandidates = (file) => {
1751
2610
  const out = [];
1752
2611
  const seen = /* @__PURE__ */ new Set();
1753
2612
  const push = (url, width) => {
1754
- const clean = sanitizeUrl(url, { schemes: ["http", "https"] });
1755
- if (!clean || !Number.isInteger(width) || width <= 0 || seen.has(width)) return;
2613
+ const clean2 = sanitizeUrl(url, { schemes: ["http", "https"] });
2614
+ if (!clean2 || !Number.isInteger(width) || width <= 0 || seen.has(width)) return;
1756
2615
  seen.add(width);
1757
- out.push({ url: clean, width });
2616
+ out.push({ url: clean2, width });
1758
2617
  };
1759
2618
  if (isPlainObject2(file.formats)) {
1760
2619
  const names = Object.keys(file.formats).sort(
@@ -1970,20 +2829,20 @@ var mediaFigure = (tag, b, o) => {
1970
2829
  caption.length ? el("figcaption", {}, caption) : null
1971
2830
  ]);
1972
2831
  };
1973
- var label = (value, fallback) => {
2832
+ var label2 = (value, fallback) => {
1974
2833
  if (typeof value !== "string") return fallback;
1975
- const clean = value.trim();
1976
- return clean && clean.length <= 80 ? clean : fallback;
2834
+ const clean2 = value.trim();
2835
+ return clean2 && clean2.length <= 80 ? clean2 : fallback;
1977
2836
  };
1978
- var tocLabel = (options) => label(isPlainObject2(options.toc) ? options.toc.label : void 0, "Table of contents");
2837
+ var tocLabel = (options) => label2(isPlainObject2(options.toc) ? options.toc.label : void 0, "Table of contents");
1979
2838
  var codeOptions = (options) => {
1980
2839
  const code = isPlainObject2(options.code) ? options.code : {};
1981
2840
  const lineNumbers = code.lineNumbers === true ? "all" : code.lineNumbers === "block" ? "block" : "none";
1982
2841
  const button = code.copyButton;
1983
2842
  const copy = button === true || isPlainObject2(button) ? {
1984
- label: label(isPlainObject2(button) ? button.label : void 0, "Copy code"),
1985
- copied: label(isPlainObject2(button) ? button.copiedLabel : void 0, "Copied"),
1986
- failed: label(isPlainObject2(button) ? button.failedLabel : void 0, "Copy failed")
2843
+ label: label2(isPlainObject2(button) ? button.label : void 0, "Copy code"),
2844
+ copied: label2(isPlainObject2(button) ? button.copiedLabel : void 0, "Copied"),
2845
+ failed: label2(isPlainObject2(button) ? button.failedLabel : void 0, "Copy failed")
1987
2846
  } : null;
1988
2847
  return { lineNumbers, copy };
1989
2848
  };
@@ -2012,23 +2871,29 @@ var codeBlock = (b, language, o) => {
2012
2871
  },
2013
2872
  el("code", language ? { class: `language-${language}` } : {}, numbers ? numberedLines(code) : code)
2014
2873
  );
2015
- if (!copy) return pre;
2016
- return el("div", { class: "mex-code-block", "data-mex-code": "copy" }, [
2017
- pre,
2018
- el(
2019
- "button",
2020
- {
2021
- type: "button",
2022
- class: "mex-code-copy",
2023
- "data-mex-copy": "code",
2024
- "data-mex-copied": copy.copied,
2025
- "data-mex-failed": copy.failed
2026
- },
2027
- copy.label
2028
- ),
2029
- el("span", { class: "mex-code-copy-status", role: "status", "aria-live": "polite" })
2874
+ const block = copy ? copyBlock(pre, copy) : pre;
2875
+ const filename = b.type === "codeFlask" && typeof b.data.filename === "string" ? b.data.filename : "";
2876
+ if (!filename) return block;
2877
+ return el("figure", { class: "mex-code-figure" }, [
2878
+ el("figcaption", { class: "mex-code-filename" }, filename),
2879
+ block
2030
2880
  ]);
2031
2881
  };
2882
+ var copyBlock = (pre, copy) => el("div", { class: "mex-code-block", "data-mex-code": "copy" }, [
2883
+ pre,
2884
+ el(
2885
+ "button",
2886
+ {
2887
+ type: "button",
2888
+ class: "mex-code-copy",
2889
+ "data-mex-copy": "code",
2890
+ "data-mex-copied": copy.copied,
2891
+ "data-mex-failed": copy.failed
2892
+ },
2893
+ copy.label
2894
+ ),
2895
+ el("span", { class: "mex-code-copy-status", role: "status", "aria-live": "polite" })
2896
+ ]);
2032
2897
  var RENDERERS = {
2033
2898
  paragraph: (b, o) => el("p", { class: classes(["mex-paragraph"], b.tunes) }, inlineToNodes(b.data.text, o)),
2034
2899
  header: (b, o) => el(
@@ -2103,20 +2968,29 @@ var RENDERERS = {
2103
2968
  const html = o.sanitizeRaw(String(b.raw.html || ""));
2104
2969
  return typeof html === "string" && html ? el("div", { class: classes(["mex-raw"], b.tunes) }, { type: "raw", html }) : null;
2105
2970
  },
2971
+ // Header row: <thead> with <th scope="col">; header column (2.4): <th scope="row">;
2972
+ // merged cells: colspan/rowspan (covered cells are left out); alignment: a class.
2106
2973
  table: (b, o) => {
2107
- const rows = b.data.content;
2974
+ const rows = tableLayout(b.data);
2108
2975
  if (!rows.length) return null;
2109
- const cells = (row, tag) => el(
2110
- "tr",
2111
- {},
2112
- row.map((cell) => el(tag, tag === "th" ? { scope: "col" } : {}, inlineToNodes(cell, o)))
2976
+ const cell = (item) => el(
2977
+ item.header ? "th" : "td",
2978
+ {
2979
+ ...item.header ? { scope: item.header } : {},
2980
+ ...item.colspan > 1 ? { colspan: String(item.colspan) } : {},
2981
+ ...item.rowspan > 1 ? { rowspan: String(item.rowspan) } : {},
2982
+ ...item.align ? { class: `mex-align-${item.align}` } : {}
2983
+ },
2984
+ inlineToNodes(item.html, o)
2113
2985
  );
2114
- const head = b.data.withHeadings ? el("thead", {}, cells(rows[0], "th")) : null;
2115
- const body = (b.data.withHeadings ? rows.slice(1) : rows).map((row) => cells(row, "td"));
2986
+ const tr = (row) => el("tr", {}, row.map(cell));
2987
+ const head = b.data.withHeadings ? el("thead", {}, tr(rows[0])) : null;
2988
+ const body = (b.data.withHeadings ? rows.slice(1) : rows).map(tr);
2989
+ const caption = b.data.caption ? el("caption", {}, inlineToNodes(b.data.caption, o)) : null;
2116
2990
  return el(
2117
2991
  "table",
2118
2992
  { class: classes(["mex-table", ...b.data.stretched ? ["mex-stretched"] : []], b.tunes) },
2119
- [head, body.length ? el("tbody", {}, body) : null]
2993
+ [caption, head, body.length ? el("tbody", {}, body) : null]
2120
2994
  );
2121
2995
  },
2122
2996
  image: (b, o) => {
@@ -2209,11 +3083,11 @@ var RENDERERS = {
2209
3083
  embed: (b, o) => {
2210
3084
  const hosts = Array.isArray(o.embedHosts) ? o.embedHosts.map((h) => String(h).toLowerCase()) : DEFAULT_EMBED_HOSTS;
2211
3085
  const frame = embedFrameUrl(b.data.embed, hosts);
3086
+ const href = b.data.source || b.data.embed;
3087
+ if (!frame && !href) return null;
2212
3088
  const caption = inlineToNodes(b.data.caption, o);
2213
3089
  const title = inlineToText(b.data.caption) || b.data.service || "Embedded content";
2214
3090
  if (!frame) {
2215
- const href = b.data.source || b.data.embed;
2216
- if (!href) return null;
2217
3091
  return el(
2218
3092
  "p",
2219
3093
  { class: classes(["mex-embed", "mex-embed-link"], b.tunes) },
@@ -2273,6 +3147,15 @@ var RENDERERS = {
2273
3147
  return el("p", { class: classes(["mex-button-block"], b.tunes) }, inner);
2274
3148
  },
2275
3149
  delimiter: (b) => el("hr", { class: classes(["mex-delimiter"], b.tunes) }),
3150
+ // Math block (2.4): MathML from `options.math`, else the delimited TeX source.
3151
+ math: (b, o) => b.data.tex.trim() ? mathElement(o, b.data.tex, {
3152
+ display: b.data.display !== false,
3153
+ block: true,
3154
+ className: classes(
3155
+ ["mex-math", ...b.data.display !== false ? ["mex-math-display"] : []],
3156
+ b.tunes
3157
+ )
3158
+ }) : null,
2276
3159
  toc: (b, o) => {
2277
3160
  const tree = buildTocTree(b.headings || [], b.data);
2278
3161
  if (!tree.length) return null;
@@ -2365,15 +3248,15 @@ var RESOURCE_ATTRIBUTES = /* @__PURE__ */ new Set(["src", "poster", "data", "bac
2365
3248
  var cleanUrlAttribute = (name, value) => {
2366
3249
  if (name === "srcset" || name === "imagesrcset") {
2367
3250
  const parts = value.split(",").map((part) => part.trim());
2368
- const clean = [];
3251
+ const clean2 = [];
2369
3252
  for (const part of parts) {
2370
3253
  const [url, descriptor, extra] = part.split(/\s+/);
2371
3254
  if (extra !== void 0 || descriptor && !/^\d+(?:\.\d+)?[wx]$/.test(descriptor)) return "";
2372
3255
  const safe = sanitizeUrl(url, { schemes: ["http", "https"] });
2373
3256
  if (!safe) return "";
2374
- clean.push(descriptor ? `${safe} ${descriptor}` : safe);
3257
+ clean2.push(descriptor ? `${safe} ${descriptor}` : safe);
2375
3258
  }
2376
- return clean.join(", ");
3259
+ return clean2.join(", ");
2377
3260
  }
2378
3261
  return sanitizeUrl(value, { schemes: RESOURCE_ATTRIBUTES.has(name) ? ["http", "https"] : LINK_SCHEMES });
2379
3262
  };
@@ -2431,7 +3314,13 @@ var cleanOverrideNodes = (input, trusted) => {
2431
3314
  };
2432
3315
  var rawAllowed = (options) => options.rawHtml === "allow" && typeof options.sanitizeRaw === "function";
2433
3316
  var createTreeBuilder = (value, options, mode = {}) => {
2434
- const opts = options && typeof options === "object" ? options : {};
3317
+ const base = options && typeof options === "object" ? options : {};
3318
+ const opts = { ...base };
3319
+ const footnotes = createFootnoteTree(base, (note) => inlineNodesToRender(note, opts));
3320
+ opts[RENDER_STATE] = {
3321
+ math: (tex) => mathElement(base, tex, { display: false, block: false }),
3322
+ footnote: (node) => footnotes.marker(node)
3323
+ };
2435
3324
  const publicOf = /* @__PURE__ */ new WeakMap();
2436
3325
  const preparedOf = /* @__PURE__ */ new WeakMap();
2437
3326
  const trusted = /* @__PURE__ */ new WeakSet();
@@ -2515,6 +3404,8 @@ var createTreeBuilder = (value, options, mode = {}) => {
2515
3404
  childNodes: renderBlocks
2516
3405
  };
2517
3406
  const nodes = renderList(annotateHeadings(prepareBlocks(value, opts), opts));
3407
+ const section = footnotes.section();
3408
+ if (section) nodes.push(textNode("\n"), section);
2518
3409
  return { nodes, renderBlocks, helpers };
2519
3410
  };
2520
3411