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