magic-editor-x 2.2.0 → 2.3.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 (94) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/README.md +493 -168
  3. package/dist/admin/{ConfigurationPage-3Dir3dAf.mjs → ConfigurationPage-BxLHIQdo.mjs} +450 -21
  4. package/dist/admin/{ConfigurationPage-YvnPnna6.js → ConfigurationPage-C-UktL1x.js} +479 -50
  5. package/dist/admin/ConfirmAction-DuQwvRYi.mjs +125 -0
  6. package/dist/admin/ConfirmAction-zLuIFj8t.js +124 -0
  7. package/dist/admin/{CustomBlocksPage-BiiL2ORG.js → CustomBlocksPage-CxcTfdOT.js} +135 -84
  8. package/dist/admin/{CustomBlocksPage-CR2BaP9O.mjs → CustomBlocksPage-D8aMbVXc.mjs} +92 -41
  9. package/dist/admin/DraftSync-BIA8cZgA.js +11 -0
  10. package/dist/admin/DraftSync-CUxOMG-E.mjs +12 -0
  11. package/dist/admin/TemplatesPage-Hn6gyu2l.js +993 -0
  12. package/dist/admin/TemplatesPage-jhYi6Zdf.mjs +993 -0
  13. package/dist/admin/{de-BmmLBJli.mjs → de-1cFMs-4c.mjs} +2 -0
  14. package/dist/admin/{de-BteRx2iA.js → de-2Ie5jy7j.js} +79 -1
  15. package/dist/admin/{de-62Vxb2iw.js → de-B1X46JJZ.js} +205 -2
  16. package/dist/admin/{de-CFX5atOk.mjs → de-BMY2LBaa.mjs} +79 -1
  17. package/dist/admin/{de-Bt6pYIWi.mjs → de-BUS1hUw0.mjs} +145 -0
  18. package/dist/admin/{de-CVbi685U.js → de-C3AsGauQ.js} +145 -0
  19. package/dist/admin/{de-BVvwSYYO.mjs → de-DOiGaTNX.mjs} +205 -2
  20. package/dist/admin/{de-DaJwN6nk.js → de-Dn8athM8.js} +2 -0
  21. package/dist/admin/{en-CyjAcccB.js → en-Ah-Cw0Wd.js} +79 -1
  22. package/dist/admin/{en-BX362fTp.js → en-BkEjpC3i.js} +145 -0
  23. package/dist/admin/{en-VlkaIzrM.js → en-CDg_18Bt.js} +205 -2
  24. package/dist/admin/{en-Cn78RZs-.js → en-CIZ5Ggod.js} +2 -0
  25. package/dist/admin/{en-Cg2Ak5Cr.mjs → en-CU6UzV4g.mjs} +205 -2
  26. package/dist/admin/{en-ea0tfA5i.mjs → en-CvFiqti2.mjs} +79 -1
  27. package/dist/admin/{en-D7mZWLGp.mjs → en-Dc9y-6n9.mjs} +2 -0
  28. package/dist/admin/{en-B_HltUxZ.mjs → en-GCzgS9Aw.mjs} +145 -0
  29. package/dist/admin/{es-BT9oAcHf.js → es-BCpJmUEM.js} +205 -2
  30. package/dist/admin/{es-C9-cXdb6.mjs → es-BmfffNM2.mjs} +205 -2
  31. package/dist/admin/{es-BmGtLkJD.js → es-C4IRHV5d.js} +2 -0
  32. package/dist/admin/{es-CHHEZi44.js → es-C4pEnDRv.js} +145 -0
  33. package/dist/admin/{es-C8GZFGjv.js → es-Cr8JH85N.js} +79 -1
  34. package/dist/admin/{es-joykG5I9.mjs → es-D2Kw6E4N.mjs} +2 -0
  35. package/dist/admin/{es-CrhwOq-5.mjs → es-DHBBZKl2.mjs} +145 -0
  36. package/dist/admin/{es-CEi_ycX8.mjs → es-DbKHZz5l.mjs} +79 -1
  37. package/dist/admin/{fr-CrzxGe5e.mjs → fr-BOvvfEH7.mjs} +2 -0
  38. package/dist/admin/{fr-B3SL0TBV.js → fr-C2aLSwEu.js} +145 -0
  39. package/dist/admin/{fr-BAMSvQbR.mjs → fr-DQJ_7aq5.mjs} +79 -1
  40. package/dist/admin/{fr-DpU_qiXR.mjs → fr-DZd2XJP6.mjs} +205 -2
  41. package/dist/admin/{fr-5djKfQ3s.mjs → fr-Dvq4xk2e.mjs} +145 -0
  42. package/dist/admin/{fr-oRCJNdeJ.js → fr-OJ4VW1kh.js} +79 -1
  43. package/dist/admin/{fr-D6KJqPWi.js → fr-ZcN0yM_2.js} +205 -2
  44. package/dist/admin/{fr-Ct_uPqxV.js → fr-Zkb8vfjN.js} +2 -0
  45. package/dist/admin/index-BHBRr562.js +1940 -0
  46. package/dist/admin/index-CQk1XeNb.mjs +1939 -0
  47. package/dist/admin/{EditorField-Diq1j8kc.js → index-Cm-fFUhE.js} +13704 -6766
  48. package/dist/admin/{EditorField-B8pyAxPE.mjs → index-XgfwqLfV.mjs} +10203 -3265
  49. package/dist/admin/index.js +1 -1
  50. package/dist/admin/index.mjs +2 -2
  51. package/dist/admin/{pt-chN2jrXl.js → pt-1IUyx6ae.js} +2 -0
  52. package/dist/admin/{pt-CQrfqsCN.mjs → pt-BSLzA17U.mjs} +79 -1
  53. package/dist/admin/{pt-jUqOR7Xh.mjs → pt-C3UdeIpd.mjs} +205 -2
  54. package/dist/admin/{pt-BOrl6x-r.js → pt-CImqDnLB.js} +205 -2
  55. package/dist/admin/{pt-BdnY2Cth.mjs → pt-CilDggGF.mjs} +145 -0
  56. package/dist/admin/{pt-tUeJ2Ywd.js → pt-D0I0_JYs.js} +79 -1
  57. package/dist/admin/{pt-EVwCuBUK.js → pt-DX0OAIoL.js} +145 -0
  58. package/dist/admin/{pt-Ga-4Hsv0.mjs → pt-etwsg3G4.mjs} +2 -0
  59. package/dist/admin/useBreakpoint-D30eNTkF.js +37 -0
  60. package/dist/admin/useBreakpoint-DCfn6pDG.mjs +38 -0
  61. package/dist/admin/useT-CmaeZbCr.mjs +65 -0
  62. package/dist/admin/{useT-BWZ_-Hel.js → useT-D3sM9Zf7.js} +4 -70
  63. package/dist/blocks/index.d.mts +167 -0
  64. package/dist/blocks/index.d.ts +167 -0
  65. package/dist/blocks/index.js +631 -0
  66. package/dist/blocks/index.mjs +609 -0
  67. package/dist/react/index.d.mts +39 -0
  68. package/dist/react/index.d.ts +39 -0
  69. package/dist/react/index.js +2687 -0
  70. package/dist/react/index.mjs +2657 -0
  71. package/dist/render/index.d.mts +131 -5
  72. package/dist/render/index.d.ts +131 -5
  73. package/dist/render/index.js +1679 -181
  74. package/dist/render/index.mjs +1679 -181
  75. package/dist/server/index.js +10645 -3716
  76. package/dist/server/index.mjs +10645 -3716
  77. package/dist/vue/index.d.mts +41 -0
  78. package/dist/vue/index.d.ts +41 -0
  79. package/dist/vue/index.js +2630 -0
  80. package/dist/vue/index.mjs +2610 -0
  81. package/package.json +30 -6
  82. package/schema/magic-editor-x.schema.json +540 -1
  83. package/types/blocks.d.ts +167 -0
  84. package/types/index.d.ts +127 -0
  85. package/types/react.d.ts +39 -0
  86. package/types/render.d.ts +131 -5
  87. package/types/vue.d.ts +41 -0
  88. package/dist/admin/api-Dsq53giv.js +0 -37
  89. package/dist/admin/api-RZ0Fz0BD.mjs +0 -38
  90. package/dist/admin/index-C-lyON1B.mjs +0 -303
  91. package/dist/admin/index-iA0lued_.js +0 -302
  92. package/dist/admin/sanitize-Cb4jvBhj.js +0 -628
  93. package/dist/admin/sanitize-ClkX823p.mjs +0 -627
  94. package/dist/admin/useT-pvHmgBFj.mjs +0 -131
@@ -1,3 +1,118 @@
1
+ // shared/render/nodes.mjs
2
+ var VOID_TAGS = /* @__PURE__ */ new Set([
3
+ "area",
4
+ "base",
5
+ "br",
6
+ "col",
7
+ "embed",
8
+ "hr",
9
+ "img",
10
+ "input",
11
+ "link",
12
+ "meta",
13
+ "source",
14
+ "track",
15
+ "wbr"
16
+ ]);
17
+ var escapeHtml = (text) => String(text ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
18
+ var TAG_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
19
+ var ATTRIBUTE_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
20
+ var isSafeAttributeName = (name) => ATTRIBUTE_NAME.test(name) && !name.startsWith("on") && name !== "style" && name !== "srcdoc";
21
+ var textNode = (value) => ({ type: "text", value: String(value ?? "") });
22
+ var el = (tag, attrs, children) => {
23
+ const clean = {};
24
+ for (const [name, value] of Object.entries(attrs || {})) {
25
+ if (value === void 0 || value === null || value === false) continue;
26
+ if (value === "" && name !== "alt") continue;
27
+ clean[name] = value === true ? true : String(value);
28
+ }
29
+ return { type: "element", tag, attrs: clean, children: toNodes(children) };
30
+ };
31
+ var toNodes = (children) => {
32
+ const out = [];
33
+ const visit = (child) => {
34
+ if (child === void 0 || child === null || child === false || child === "") return;
35
+ if (Array.isArray(child)) {
36
+ for (const item of child) visit(item);
37
+ } else if (typeof child === "string" || typeof child === "number") {
38
+ out.push(textNode(child));
39
+ } else if (typeof child === "object") {
40
+ out.push(
41
+ /** @type {RenderNode} */
42
+ child
43
+ );
44
+ }
45
+ };
46
+ visit(children);
47
+ return out;
48
+ };
49
+ var STYLE_PROPERTIES = Object.freeze(["object-position"]);
50
+ var STYLE_VALUE = /^[0-9]{1,3}(?:\.[0-9]{1,2})?% [0-9]{1,3}(?:\.[0-9]{1,2})?%$/;
51
+ var safeStyle = (style) => style && typeof style === "object" ? Object.entries(style).filter(
52
+ ([name, value]) => STYLE_PROPERTIES.includes(name) && typeof value === "string" && STYLE_VALUE.test(value)
53
+ ) : [];
54
+ var serializeNodes = (nodes) => {
55
+ let out = "";
56
+ for (const node of nodes) {
57
+ if (!node || typeof node !== "object") continue;
58
+ if (node.type === "text") out += escapeHtml(node.value);
59
+ else if (node.type === "raw") out += node.html;
60
+ else if (node.type === "block") out += serializeNodes(node.children);
61
+ else if (node.type === "element") {
62
+ let attributes = "";
63
+ for (const [name, value] of Object.entries(node.attrs)) {
64
+ attributes += value === true ? ` ${name}` : ` ${name}="${escapeHtml(value)}"`;
65
+ }
66
+ const style = safeStyle(node.style);
67
+ if (style.length)
68
+ attributes += ` style="${escapeHtml(style.map(([name, value]) => `${name}:${value}`).join(";"))}"`;
69
+ out += VOID_TAGS.has(node.tag) ? `<${node.tag}${attributes}>` : `<${node.tag}${attributes}>${serializeNodes(node.children)}</${node.tag}>`;
70
+ }
71
+ }
72
+ return out;
73
+ };
74
+
75
+ // shared/blocks/active.mjs
76
+ var registry = /* @__PURE__ */ new Map();
77
+ var activeBlock = (type) => typeof type === "string" && registry.has(type) ? registry.get(type) : null;
78
+
79
+ // shared/built-in-marker.mjs
80
+ var isPlainObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
81
+ var BUILT_IN_MARKER = "_mex";
82
+ var BUILT_IN_MARKER_VERSION = 1;
83
+ var MARKED_BLOCKS = Object.freeze({
84
+ toc: Object.freeze({ keys: Object.freeze(["title", "minLevel", "maxLevel", "style"]), anchor: null }),
85
+ gallery: Object.freeze({
86
+ keys: Object.freeze(["images", "layout", "columns", "caption"]),
87
+ anchor: Object.freeze(["images", "array"])
88
+ }),
89
+ video: Object.freeze({
90
+ keys: Object.freeze(["file", "poster", "title", "caption", "loop", "muted", "tracks"]),
91
+ anchor: Object.freeze(["file", "object"])
92
+ }),
93
+ audio: Object.freeze({
94
+ keys: Object.freeze(["file", "title", "caption", "loop", "tracks"]),
95
+ anchor: Object.freeze(["file", "object"])
96
+ }),
97
+ synced: Object.freeze({ keys: Object.freeze(["ref"]), anchor: Object.freeze(["ref", "string"]) })
98
+ });
99
+ var isBuiltInMarker = (value) => Number.isInteger(value) && /** @type {number} */
100
+ value >= 1;
101
+ var hasBuiltInShape = (shape, data) => {
102
+ if (!Object.keys(data).every((key2) => shape.keys.includes(key2))) return false;
103
+ if (!shape.anchor) return true;
104
+ const [key, kind] = shape.anchor;
105
+ const value = data[key];
106
+ if (kind === "array") return Array.isArray(value);
107
+ if (kind === "object") return isPlainObject(value);
108
+ return typeof value === kind;
109
+ };
110
+ var isMarkedBuiltIn = (type, data) => {
111
+ if (!Object.prototype.hasOwnProperty.call(MARKED_BLOCKS, type) || !isPlainObject(data)) return false;
112
+ if (isBuiltInMarker(data[BUILT_IN_MARKER])) return true;
113
+ return hasBuiltInShape(MARKED_BLOCKS[type], data);
114
+ };
115
+
1
116
  // shared/editor-data.mjs
2
117
  var EDITOR_DATA_LIMITS = Object.freeze({
3
118
  maxBlocks: 5e3,
@@ -9,7 +124,7 @@ var EDITOR_DATA_LIMITS = Object.freeze({
9
124
  var FORBIDDEN_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
10
125
  var BLOCK_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
11
126
  var BLOCK_TYPE_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
12
- var isPlainObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
127
+ var isPlainObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
13
128
  var EditorDataError = class extends Error {
14
129
  /**
15
130
  * @param {string} message - Fixed, non-sensitive message.
@@ -60,7 +175,7 @@ var tryParseJson = (text) => {
60
175
  return { ok: false };
61
176
  }
62
177
  };
63
- var escapeHtml = (text) => String(text).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
178
+ var escapeHtml2 = (text) => String(text).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
64
179
  var hashString = (text) => {
65
180
  let hash = 2166136261;
66
181
  for (let i = 0; i < text.length; i += 1) {
@@ -77,7 +192,7 @@ var textToBlocks = (text) => {
77
192
  if (looksLikeHtml) {
78
193
  return [{ type: "paragraph", data: { text: trimmed } }];
79
194
  }
80
- return trimmed.split(/\r?\n\s*\r?\n/).map((part) => part.trim()).filter(Boolean).map((part) => ({ type: "paragraph", data: { text: escapeHtml(part).replace(/\r?\n/g, "<br>") } }));
195
+ return trimmed.split(/\r?\n\s*\r?\n/).map((part) => part.trim()).filter(Boolean).map((part) => ({ type: "paragraph", data: { text: escapeHtml2(part).replace(/\r?\n/g, "<br>") } }));
81
196
  };
82
197
  var unwrapValue = (value) => {
83
198
  let current = value;
@@ -107,7 +222,7 @@ var normalizeEditorData = (value) => {
107
222
  }
108
223
  const { candidate } = unwrapValue(value);
109
224
  if (candidate === null || candidate === void 0) return null;
110
- if (!isPlainObject(candidate)) {
225
+ if (!isPlainObject2(candidate)) {
111
226
  throw new EditorDataError("Editor content must be an Editor.js object", "INVALID_SHAPE");
112
227
  }
113
228
  const clean = cloneJsonSafe(candidate);
@@ -118,16 +233,16 @@ var normalizeEditorData = (value) => {
118
233
  const seen = /* @__PURE__ */ new Set();
119
234
  const blocks = [];
120
235
  rawBlocks.forEach((block, index) => {
121
- if (!isPlainObject(block)) return;
236
+ if (!isPlainObject2(block)) return;
122
237
  const type = typeof block.type === "string" ? block.type.trim() : "";
123
238
  if (!BLOCK_TYPE_PATTERN.test(type)) return;
124
- const data = isPlainObject(block.data) ? block.data : {};
239
+ const data = isPlainObject2(block.data) ? block.data : {};
125
240
  let id = typeof block.id === "string" && BLOCK_ID_PATTERN.test(block.id) ? block.id : "";
126
241
  if (!id || seen.has(id)) id = legacyBlockId(index, type, data);
127
242
  while (seen.has(id)) id = `${id}x`;
128
243
  seen.add(id);
129
244
  const normalized = { id, type, data };
130
- if (isPlainObject(block.tunes) && Object.keys(block.tunes).length > 0) normalized.tunes = block.tunes;
245
+ if (isPlainObject2(block.tunes) && Object.keys(block.tunes).length > 0) normalized.tunes = block.tunes;
131
246
  blocks.push(normalized);
132
247
  });
133
248
  const time = Number.isFinite(clean.time) && clean.time > 0 ? Math.floor(clean.time) : 0;
@@ -179,12 +294,15 @@ var INLINE_TAGS = Object.freeze([
179
294
  var INTERNAL_LINK_ATTRIBUTES = Object.freeze([
180
295
  "data-mex-uid",
181
296
  "data-mex-document-id",
182
- "data-mex-locale"
297
+ "data-mex-locale",
298
+ "data-mex-mention"
183
299
  ]);
184
300
  var INTERNAL_LINK_RULES = Object.freeze({
185
301
  "data-mex-uid": /^api::[a-z0-9-]{1,60}\.[a-z0-9-]{1,60}$/,
186
302
  "data-mex-document-id": /^[a-z0-9]{1,64}$/,
187
- "data-mex-locale": /^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8}){0,3}$/
303
+ "data-mex-locale": /^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8}){0,3}$/,
304
+ // Boolean flag: written as "true"; an empty value (`<a data-mex-mention>`) is accepted and normalised.
305
+ "data-mex-mention": /^(?:|true)$/
188
306
  });
189
307
  var cleanInternalLinkAttributes = (attribs) => {
190
308
  const out = {};
@@ -194,8 +312,12 @@ var cleanInternalLinkAttributes = (attribs) => {
194
312
  if (typeof value === "string" && INTERNAL_LINK_RULES[name].test(value)) out[name] = value;
195
313
  }
196
314
  if (!out["data-mex-uid"] || !out["data-mex-document-id"]) return {};
315
+ if (out["data-mex-mention"] !== void 0) out["data-mex-mention"] = "true";
197
316
  return out;
198
317
  };
318
+ var isMentionLink = (attrs) => Boolean(
319
+ attrs && attrs["data-mex-mention"] === "true" && attrs["data-mex-uid"] && attrs["data-mex-document-id"]
320
+ );
199
321
  var INLINE_ATTRIBUTES = Object.freeze({
200
322
  a: ["href", "target", "rel", "title", ...INTERNAL_LINK_ATTRIBUTES],
201
323
  span: ["class", "data-tooltip"],
@@ -244,6 +366,57 @@ var int = (value, min, max, fallback) => {
244
366
  return Number.isInteger(number) && number >= min && number <= max ? number : fallback;
245
367
  };
246
368
  var bool = (value) => value === true;
369
+ var MAX_GALLERY_IMAGES = 50;
370
+ var MAX_MEDIA_TRACKS = 8;
371
+ var TRACK_KINDS = Object.freeze(["captions", "subtitles", "descriptions", "chapters"]);
372
+ var SRCLANG = /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{1,8}){0,3}$/;
373
+ var cleanFocalPoint = (value) => {
374
+ if (!isPlainObject2(value)) return void 0;
375
+ const { x, y } = value;
376
+ if (![x, y].every((n) => typeof n === "number" && Number.isFinite(n) && n >= 0 && n <= 1)) return void 0;
377
+ return { x: Math.round(x * 100) / 100, y: Math.round(y * 100) / 100 };
378
+ };
379
+ var cleanMediaFile = (value, kind = {}) => {
380
+ const file = isPlainObject2(value) ? value : {};
381
+ const out = { url: sanitizeUrl(file.url, { schemes: ["http", "https"] }) };
382
+ for (const key of ["mime", ...kind.image ? ["alt"] : [], "name", "hash", "ext"])
383
+ if (typeof file[key] === "string") out[key] = plain(file[key], 500);
384
+ for (const key of ["width", "height", "size"]) if (Number.isFinite(file[key])) out[key] = file[key];
385
+ if (kind.image && isPlainObject2(file.formats))
386
+ out.formats = generic(file.formats, (s) => plain(s, 2048), 0, "formats");
387
+ if (file.id !== void 0 && (Number.isInteger(file.id) || typeof file.id === "string")) out.id = file.id;
388
+ if (typeof file.documentId === "string") out.documentId = plain(file.documentId, 64);
389
+ const mime = typeof out.mime === "string" ? out.mime.toLowerCase() : "";
390
+ if (kind.mimePrefix && mime && !mime.startsWith(kind.mimePrefix)) out.url = "";
391
+ if (kind.vtt && out.url) {
392
+ const path = out.url.split(/[?#]/)[0].toLowerCase();
393
+ const ext = typeof out.ext === "string" ? out.ext.toLowerCase() : "";
394
+ if (mime !== "text/vtt" && ext !== ".vtt" && !path.endsWith(".vtt")) out.url = "";
395
+ }
396
+ return out;
397
+ };
398
+ var mediaTracks = (tracks) => {
399
+ if (!Array.isArray(tracks)) return [];
400
+ const out = [];
401
+ let hasDefault = false;
402
+ for (const track of tracks.slice(0, MAX_MEDIA_TRACKS)) {
403
+ if (!isPlainObject2(track)) continue;
404
+ const file = cleanMediaFile(track.file, { vtt: true });
405
+ if (!file.url) continue;
406
+ const clean = {
407
+ file,
408
+ kind: oneOf(track.kind, TRACK_KINDS, "captions"),
409
+ srclang: typeof track.srclang === "string" && SRCLANG.test(track.srclang) ? track.srclang : "",
410
+ label: plain(track.label, 100)
411
+ };
412
+ if (track.default === true && !hasDefault) {
413
+ clean.default = true;
414
+ hasDefault = true;
415
+ }
416
+ out.push(clean);
417
+ }
418
+ return out;
419
+ };
247
420
  var generic = (value, inline, depth = 0, key = "") => {
248
421
  if (depth > 20) return null;
249
422
  if (typeof value === "string") {
@@ -251,7 +424,7 @@ var generic = (value, inline, depth = 0, key = "") => {
251
424
  return inline(value);
252
425
  }
253
426
  if (Array.isArray(value)) return value.map((item) => generic(item, inline, depth + 1, key));
254
- if (isPlainObject(value)) {
427
+ if (isPlainObject2(value)) {
255
428
  const out = {};
256
429
  for (const [childKey, child] of Object.entries(value))
257
430
  out[childKey] = generic(child, inline, depth + 1, childKey);
@@ -263,9 +436,9 @@ var listItems = (items, inline, depth = 0) => {
263
436
  if (!Array.isArray(items) || depth > 12) return [];
264
437
  return items.map((item) => {
265
438
  if (typeof item === "string") return inline(item);
266
- if (!isPlainObject(item)) return { content: "", items: [] };
439
+ if (!isPlainObject2(item)) return { content: "", items: [] };
267
440
  const out = { content: inline(typeof item.content === "string" ? item.content : plain(item.text)) };
268
- if (isPlainObject(item.meta)) {
441
+ if (isPlainObject2(item.meta)) {
269
442
  const meta = {};
270
443
  if (typeof item.meta.checked === "boolean") meta.checked = item.meta.checked;
271
444
  const start = int(item.meta.start, 0, 1e5, void 0);
@@ -296,7 +469,7 @@ var BLOCK_POLICIES = {
296
469
  style: oneOf(d.style, ["ordered", "unordered", "checklist"], "unordered"),
297
470
  items: listItems(d.items, inline)
298
471
  };
299
- if (isPlainObject(d.meta)) {
472
+ if (isPlainObject2(d.meta)) {
300
473
  const meta = {};
301
474
  const start = int(d.meta.start, 0, 1e5, void 0);
302
475
  if (start !== void 0) meta.start = start;
@@ -312,7 +485,7 @@ var BLOCK_POLICIES = {
312
485
  return out;
313
486
  },
314
487
  checklist: (d, inline) => ({
315
- items: Array.isArray(d.items) ? d.items.filter(isPlainObject).map((item) => ({ text: inline(item.text), checked: bool(item.checked) })) : []
488
+ items: Array.isArray(d.items) ? d.items.filter(isPlainObject2).map((item) => ({ text: inline(item.text), checked: bool(item.checked) })) : []
316
489
  }),
317
490
  warning: (d, inline) => ({ title: inline(d.title), message: inline(d.message) }),
318
491
  alert: (d, inline) => ({
@@ -351,12 +524,12 @@ var BLOCK_POLICIES = {
351
524
  content: Array.isArray(d.content) ? d.content.slice(0, 500).map((row) => Array.isArray(row) ? row.slice(0, 100).map((cell2) => inline(cell2)) : []) : []
352
525
  }),
353
526
  image: (d, inline) => {
354
- const file = isPlainObject(d.file) ? d.file : {};
527
+ const file = isPlainObject2(d.file) ? d.file : {};
355
528
  const cleanFile = { url: sanitizeUrl(file.url, { schemes: ["http", "https"] }) };
356
529
  for (const key of ["mime", "alt", "name", "hash", "ext"])
357
530
  if (typeof file[key] === "string") cleanFile[key] = plain(file[key], 500);
358
531
  for (const key of ["width", "height", "size"]) if (Number.isFinite(file[key])) cleanFile[key] = file[key];
359
- if (isPlainObject(file.formats))
532
+ if (isPlainObject2(file.formats))
360
533
  cleanFile.formats = generic(file.formats, (s) => plain(s, 2048), 0, "formats");
361
534
  if (file.id !== void 0 && (Number.isInteger(file.id) || typeof file.id === "string"))
362
535
  cleanFile.id = file.id;
@@ -369,6 +542,8 @@ var BLOCK_POLICIES = {
369
542
  stretched: bool(d.stretched)
370
543
  };
371
544
  if (d.decorative === true) out.decorative = true;
545
+ const focalPoint = cleanFocalPoint(d.focalPoint);
546
+ if (focalPoint) out.focalPoint = focalPoint;
372
547
  return out;
373
548
  },
374
549
  simpleImage: (d, inline) => {
@@ -383,16 +558,61 @@ var BLOCK_POLICIES = {
383
558
  if (d.decorative === true) out.decorative = true;
384
559
  return out;
385
560
  },
561
+ gallery: (d, inline) => {
562
+ const images = [];
563
+ for (const item of Array.isArray(d.images) ? d.images : []) {
564
+ if (images.length >= MAX_GALLERY_IMAGES) break;
565
+ if (!isPlainObject2(item)) continue;
566
+ const file = cleanMediaFile(item.file, { image: true, mimePrefix: "image/" });
567
+ if (!file.url) continue;
568
+ const image = { file, caption: inline(item.caption) };
569
+ if (item.decorative === true) image.decorative = true;
570
+ const focalPoint = cleanFocalPoint(item.focalPoint);
571
+ if (focalPoint) image.focalPoint = focalPoint;
572
+ images.push(image);
573
+ }
574
+ return {
575
+ images,
576
+ layout: oneOf(d.layout, ["grid", "carousel"], "grid"),
577
+ columns: int(d.columns, 1, 6, 3),
578
+ caption: inline(d.caption),
579
+ _mex: BUILT_IN_MARKER_VERSION
580
+ };
581
+ },
582
+ video: (d, inline) => {
583
+ const out = {
584
+ file: cleanMediaFile(d.file, { mimePrefix: "video/" }),
585
+ title: plain(d.title, 200),
586
+ caption: inline(d.caption),
587
+ loop: bool(d.loop),
588
+ muted: bool(d.muted),
589
+ tracks: mediaTracks(d.tracks)
590
+ };
591
+ if (isPlainObject2(d.poster)) {
592
+ const poster = cleanMediaFile(d.poster, { image: true, mimePrefix: "image/" });
593
+ if (poster.url) out.poster = poster;
594
+ }
595
+ out._mex = BUILT_IN_MARKER_VERSION;
596
+ return out;
597
+ },
598
+ audio: (d, inline) => ({
599
+ file: cleanMediaFile(d.file, { mimePrefix: "audio/" }),
600
+ title: plain(d.title, 200),
601
+ caption: inline(d.caption),
602
+ loop: bool(d.loop),
603
+ tracks: mediaTracks(d.tracks),
604
+ _mex: BUILT_IN_MARKER_VERSION
605
+ }),
386
606
  linkTool: (d) => {
387
- const meta = isPlainObject(d.meta) ? d.meta : {};
388
- const image = isPlainObject(meta.image) ? { url: sanitizeUrl(meta.image.url, { schemes: ["http", "https"] }) } : void 0;
607
+ const meta = isPlainObject2(d.meta) ? d.meta : {};
608
+ const image = isPlainObject2(meta.image) ? { url: sanitizeUrl(meta.image.url, { schemes: ["http", "https"] }) } : void 0;
389
609
  const cleanMeta = { title: plain(meta.title, 500), description: plain(meta.description, 2e3) };
390
610
  if (typeof meta.site_name === "string") cleanMeta.site_name = plain(meta.site_name, 200);
391
611
  if (image && image.url) cleanMeta.image = image;
392
612
  return { link: sanitizeUrl(d.link, { schemes: ["http", "https"] }), meta: cleanMeta };
393
613
  },
394
614
  attaches: (d) => {
395
- const file = isPlainObject(d.file) ? d.file : {};
615
+ const file = isPlainObject2(d.file) ? d.file : {};
396
616
  const cleanFile = { url: sanitizeUrl(file.url, { schemes: ["http", "https"] }) };
397
617
  if (typeof file.name === "string") cleanFile.name = plain(file.name, 255);
398
618
  if (typeof file.extension === "string") cleanFile.extension = plain(file.extension, 16);
@@ -420,12 +640,34 @@ var BLOCK_POLICIES = {
420
640
  style: oneOf(d.style, ["primary", "secondary", "outline", "ghost", "danger", "success"], "primary"),
421
641
  openInNewTab: bool(d.openInNewTab)
422
642
  }),
423
- delimiter: () => ({})
643
+ delimiter: () => ({}),
644
+ // Synced block (2.3): only the reference to its source is stored; an invalid reference becomes ''.
645
+ synced: (d) => ({
646
+ ref: typeof d.ref === "string" && /^[a-z0-9]{1,64}$/.test(d.ref) ? d.ref : "",
647
+ _mex: BUILT_IN_MARKER_VERSION
648
+ }),
649
+ toc: (d) => {
650
+ const minLevel = int(d.minLevel, 1, 6, 2);
651
+ const maxLevel = int(d.maxLevel, 1, 6, 4);
652
+ return {
653
+ title: plain(d.title, 200),
654
+ minLevel: Math.min(minLevel, maxLevel),
655
+ maxLevel: Math.max(minLevel, maxLevel),
656
+ style: oneOf(d.style, ["ordered", "unordered"], "unordered"),
657
+ _mex: BUILT_IN_MARKER_VERSION
658
+ };
659
+ }
660
+ };
661
+ var isBuiltInBlock = (block) => {
662
+ if (!block || typeof block.type !== "string") return false;
663
+ if (!Object.prototype.hasOwnProperty.call(BLOCK_POLICIES, block.type)) return false;
664
+ if (!Object.prototype.hasOwnProperty.call(MARKED_BLOCKS, block.type)) return true;
665
+ return isMarkedBuiltIn(block.type, block.data);
424
666
  };
425
667
  var sanitizeTunes = (tunes) => {
426
- if (!isPlainObject(tunes)) return void 0;
668
+ if (!isPlainObject2(tunes)) return void 0;
427
669
  const out = {};
428
- if (isPlainObject(tunes.alignmentTune)) {
670
+ if (isPlainObject2(tunes.alignmentTune)) {
429
671
  out.alignmentTune = {
430
672
  alignment: oneOf(tunes.alignmentTune.alignment, ["left", "center", "right", "justify"], "left")
431
673
  };
@@ -433,11 +675,16 @@ var sanitizeTunes = (tunes) => {
433
675
  if (typeof tunes.textVariant === "string") {
434
676
  out.textVariant = oneOf(tunes.textVariant, ["", "call-out", "citation", "details"], "");
435
677
  }
436
- if (isPlainObject(tunes.indentTune)) {
678
+ if (isPlainObject2(tunes.indentTune)) {
437
679
  out.indentTune = { indentLevel: int(tunes.indentTune.indentLevel, 0, 10, 0) };
438
680
  }
439
681
  return Object.keys(out).length ? out : void 0;
440
682
  };
683
+ var registeredBlockOf = (block, explicit) => {
684
+ if (!block || typeof block.type !== "string" || isBuiltInBlock(block)) return null;
685
+ if (explicit instanceof Map) return explicit.get(block.type) || null;
686
+ return activeBlock(block.type);
687
+ };
441
688
  var sanitizeTarget = (value) => typeof value === "string" && TARGETS.has(value) ? value : null;
442
689
 
443
690
  // shared/render/inline.mjs
@@ -510,7 +757,6 @@ var decodeEntities = (text) => String(text).replace(
510
757
  return named === void 0 ? match : named;
511
758
  }
512
759
  );
513
- var escapeHtml2 = (text) => String(text ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
514
760
  var parseAttributes = (source) => {
515
761
  const out = {};
516
762
  const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
@@ -662,7 +908,8 @@ var resolveLinkAttributes = (attrs, resolver) => {
662
908
  uid: attrs["data-mex-uid"],
663
909
  documentId: attrs["data-mex-document-id"],
664
910
  locale: attrs["data-mex-locale"] || null,
665
- href: attrs.href || null
911
+ href: attrs.href || null,
912
+ ...isMentionLink(attrs) ? { mention: true } : {}
666
913
  });
667
914
  } catch {
668
915
  result = void 0;
@@ -683,27 +930,53 @@ var ATTRIBUTE_ORDER = [
683
930
  "data-tooltip",
684
931
  "data-mex-uid",
685
932
  "data-mex-document-id",
686
- "data-mex-locale"
933
+ "data-mex-locale",
934
+ "data-mex-mention"
687
935
  ];
688
- var serializeAttributes = (attrs) => ATTRIBUTE_ORDER.filter((name) => attrs[name] !== void 0 && attrs[name] !== "").map((name) => ` ${name}="${escapeHtml2(attrs[name])}"`).join("");
689
- var nodesToHtml = (nodes, options = {}) => nodes.map((node) => {
690
- if (node.type === "text") return escapeHtml2(node.value);
691
- if (node.tag === "br") return "<br>";
692
- let attrs = node.attrs;
693
- if (node.tag === "a") {
694
- attrs = resolveLinkAttributes(attrs, options.links);
695
- if (!attrs || !attrs.href) return nodesToHtml(node.children, options);
696
- if (attrs.target === "_blank") {
697
- const rel = new Set(
698
- String(attrs.rel || "").split(/\s+/).filter(Boolean)
699
- );
700
- rel.add("noopener");
701
- rel.add("noreferrer");
702
- attrs = { ...attrs, rel: Array.from(rel).sort().join(" ") };
936
+ var MENTION_CLASS = "mex-mention";
937
+ var inlineNodesToRender = (nodes, options = {}) => {
938
+ const out = [];
939
+ for (const node of nodes) {
940
+ if (node.type === "text") {
941
+ out.push({ type: "text", value: node.value });
942
+ continue;
703
943
  }
944
+ if (node.tag === "br") {
945
+ out.push({ type: "element", tag: "br", attrs: {}, children: [] });
946
+ continue;
947
+ }
948
+ let attrs = node.attrs;
949
+ if (node.tag === "a") {
950
+ attrs = resolveLinkAttributes(attrs, options.links);
951
+ if (!attrs || !attrs.href) {
952
+ out.push(...inlineNodesToRender(node.children, options));
953
+ continue;
954
+ }
955
+ if (attrs.target === "_blank") {
956
+ const rel = new Set(
957
+ String(attrs.rel || "").split(/\s+/).filter(Boolean)
958
+ );
959
+ rel.add("noopener");
960
+ rel.add("noreferrer");
961
+ attrs = { ...attrs, rel: Array.from(rel).sort().join(" ") };
962
+ }
963
+ if (!options.storage && isMentionLink(attrs)) attrs = { ...attrs, class: MENTION_CLASS };
964
+ }
965
+ const ordered = {};
966
+ for (const name of ATTRIBUTE_ORDER) {
967
+ if (attrs[name] !== void 0 && attrs[name] !== "") ordered[name] = String(attrs[name]);
968
+ }
969
+ out.push({
970
+ type: "element",
971
+ tag: node.tag,
972
+ attrs: ordered,
973
+ children: inlineNodesToRender(node.children, options)
974
+ });
704
975
  }
705
- return `<${node.tag}${serializeAttributes(attrs)}>${nodesToHtml(node.children, options)}</${node.tag}>`;
706
- }).join("");
976
+ return out;
977
+ };
978
+ var inlineToNodes = (html, options) => inlineNodesToRender(parseInline(html), options);
979
+ var nodesToHtml = (nodes, options = {}) => serializeNodes(inlineNodesToRender(nodes, options));
707
980
  var nodesToText = (nodes) => nodes.map((node) => {
708
981
  if (node.type === "text") return node.value;
709
982
  if (node.tag === "br") return "\n";
@@ -712,17 +985,692 @@ var nodesToText = (nodes) => nodes.map((node) => {
712
985
  var inlineToHtml = (html, options) => nodesToHtml(parseInline(html), options);
713
986
  var inlineToText = (html) => nodesToText(parseInline(html)).replace(/\u00a0/g, " ");
714
987
 
988
+ // shared/blocks/define.mjs
989
+ var BLOCK_FIELD_TYPES = Object.freeze([
990
+ "text",
991
+ "inline",
992
+ "url",
993
+ "enum",
994
+ "number",
995
+ "boolean",
996
+ "array",
997
+ "object"
998
+ ]);
999
+ var BLOCK_LIMITS = Object.freeze({
1000
+ /** Fields per object (also the schema root). */
1001
+ maxFields: 50,
1002
+ /** Nesting of arrays and objects below the root. */
1003
+ maxDepth: 4,
1004
+ /** Largest `max` of a text or inline field. */
1005
+ maxText: 1e5,
1006
+ /** Default `max` of a text field. */
1007
+ defaultText: 1e3,
1008
+ /** Default `max` of an inline HTML field. */
1009
+ defaultInline: 1e4,
1010
+ /** Largest `max` of an array field. */
1011
+ maxItems: 500,
1012
+ /** Default `max` of an array field. */
1013
+ defaultItems: 50,
1014
+ /** Values of an enum field. */
1015
+ maxEnumValues: 100,
1016
+ /** Values cleaned per block; later array items are dropped. */
1017
+ maxValues: 2e4,
1018
+ /** Length of a URL value. */
1019
+ maxUrl: 2048
1020
+ });
1021
+ var BLOCK_PRESETS = Object.freeze(["article", "basic", "minimal"]);
1022
+ var RESERVED_BLOCK_NAMES = Object.freeze([
1023
+ "paragraph",
1024
+ "header",
1025
+ "list",
1026
+ "checklist",
1027
+ "quote",
1028
+ "warning",
1029
+ "alert",
1030
+ "toggle",
1031
+ "code",
1032
+ "codeFlask",
1033
+ "delimiter",
1034
+ "toc",
1035
+ "synced",
1036
+ "table",
1037
+ "embed",
1038
+ "raw",
1039
+ "image",
1040
+ "simpleImage",
1041
+ "gallery",
1042
+ "video",
1043
+ "audio",
1044
+ "linkTool",
1045
+ "attaches",
1046
+ "personality",
1047
+ "button",
1048
+ "mediaLib",
1049
+ "embeddedEntry",
1050
+ "bold",
1051
+ "italic",
1052
+ "hyperlink",
1053
+ "mention",
1054
+ "marker",
1055
+ "underline",
1056
+ "strikethrough",
1057
+ "inlineCode",
1058
+ "tooltip",
1059
+ "aiAssistant",
1060
+ "alignmentTune",
1061
+ "textVariant",
1062
+ "indentTune"
1063
+ ]);
1064
+ var RESERVED = new Set(RESERVED_BLOCK_NAMES.map((name) => name.toLowerCase()));
1065
+ var BLOCK_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{1,49}$/;
1066
+ var KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
1067
+ var FORBIDDEN_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1068
+ var DEFINITION_KEYS = /* @__PURE__ */ new Set([
1069
+ "name",
1070
+ "version",
1071
+ "title",
1072
+ "description",
1073
+ "schema",
1074
+ "sanitize",
1075
+ "text",
1076
+ "markdown",
1077
+ "render",
1078
+ "presets"
1079
+ ]);
1080
+ var FIELD_KEYS = {
1081
+ text: ["max", "multiline", "default"],
1082
+ inline: ["max", "default"],
1083
+ url: ["schemes", "relative"],
1084
+ enum: ["values", "default"],
1085
+ number: ["min", "max", "integer", "default"],
1086
+ boolean: ["default"],
1087
+ array: ["items", "max"],
1088
+ object: ["fields"]
1089
+ };
1090
+ var BlockDefinitionError = class extends Error {
1091
+ /**
1092
+ * @param {string} message - Message naming the definition and the problem.
1093
+ * @param {string} [code] - `INVALID_DEFINITION` | `RESERVED_NAME` | `NAME_TAKEN` | `REGISTRY_SEALED`.
1094
+ */
1095
+ constructor(message, code = "INVALID_DEFINITION") {
1096
+ super(message);
1097
+ this.name = "BlockDefinitionError";
1098
+ this.code = code;
1099
+ }
1100
+ };
1101
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1102
+ var fail = (where, message) => {
1103
+ throw new BlockDefinitionError(`Magic Editor X block ${where}: ${message}`);
1104
+ };
1105
+ var boundedInt = (value, min, max, fallback, where, key) => {
1106
+ if (value === void 0) return fallback;
1107
+ if (!Number.isInteger(value) || value < min || value > max)
1108
+ fail(where, `"${key}" must be an integer from ${min} to ${max}`);
1109
+ return value;
1110
+ };
1111
+ var normalizeField = (input, where, depth) => {
1112
+ if (!isObject(input)) fail(where, 'a field must be an object with a "type"');
1113
+ const type = input.type;
1114
+ if (!BLOCK_FIELD_TYPES.includes(type)) fail(where, `unknown field type ${JSON.stringify(type)}`);
1115
+ for (const key of Object.keys(input))
1116
+ if (key !== "type" && key !== "label" && !FIELD_KEYS[type].includes(key))
1117
+ fail(where, `unknown option "${key}" for a ${type} field`);
1118
+ const out = { type };
1119
+ if (input.label !== void 0) {
1120
+ if (typeof input.label !== "string" || input.label.length > 100)
1121
+ fail(where, '"label" must be a string of at most 100 characters');
1122
+ out.label = input.label;
1123
+ }
1124
+ switch (type) {
1125
+ case "text":
1126
+ case "inline": {
1127
+ out.max = boundedInt(
1128
+ input.max,
1129
+ 1,
1130
+ BLOCK_LIMITS.maxText,
1131
+ type === "text" ? BLOCK_LIMITS.defaultText : BLOCK_LIMITS.defaultInline,
1132
+ where,
1133
+ "max"
1134
+ );
1135
+ if (input.default !== void 0 && typeof input.default !== "string")
1136
+ fail(where, '"default" must be a string');
1137
+ out.default = (input.default || "").slice(0, out.max);
1138
+ if (type === "text") {
1139
+ if (input.multiline !== void 0 && typeof input.multiline !== "boolean")
1140
+ fail(where, '"multiline" must be a boolean');
1141
+ out.multiline = input.multiline === true;
1142
+ }
1143
+ break;
1144
+ }
1145
+ case "url": {
1146
+ const schemes = input.schemes === void 0 ? ["http", "https"] : input.schemes;
1147
+ if (!Array.isArray(schemes) || !schemes.length || schemes.some((scheme) => !LINK_SCHEMES.includes(scheme)))
1148
+ fail(where, `"schemes" must be a non-empty list of ${LINK_SCHEMES.join(", ")}`);
1149
+ if (input.relative !== void 0 && typeof input.relative !== "boolean")
1150
+ fail(where, '"relative" must be a boolean');
1151
+ out.schemes = Object.freeze([...new Set(schemes)]);
1152
+ out.relative = input.relative !== false;
1153
+ break;
1154
+ }
1155
+ case "enum": {
1156
+ const values = input.values;
1157
+ if (!Array.isArray(values) || values.length < 1 || values.length > BLOCK_LIMITS.maxEnumValues || values.some((value) => typeof value !== "string" || value.length < 1 || value.length > 100) || new Set(values).size !== values.length)
1158
+ fail(
1159
+ where,
1160
+ `"values" must be 1 to ${BLOCK_LIMITS.maxEnumValues} distinct strings (1-100 characters)`
1161
+ );
1162
+ out.values = Object.freeze([...values]);
1163
+ if (input.default !== void 0 && !values.includes(input.default))
1164
+ fail(where, '"default" must be one of "values"');
1165
+ out.default = input.default === void 0 ? values[0] : input.default;
1166
+ break;
1167
+ }
1168
+ case "number": {
1169
+ for (const key of ["min", "max", "default"])
1170
+ if (input[key] !== void 0 && (typeof input[key] !== "number" || !Number.isFinite(input[key])))
1171
+ fail(where, `"${key}" must be a finite number`);
1172
+ if (input.integer !== void 0 && typeof input.integer !== "boolean")
1173
+ fail(where, '"integer" must be a boolean');
1174
+ out.integer = input.integer === true;
1175
+ out.min = input.min === void 0 ? -Number.MAX_SAFE_INTEGER : input.min;
1176
+ out.max = input.max === void 0 ? Number.MAX_SAFE_INTEGER : input.max;
1177
+ if (out.min > out.max) fail(where, '"min" must not be greater than "max"');
1178
+ if (input.default !== void 0) {
1179
+ if (input.default < out.min || input.default > out.max || out.integer && !Number.isInteger(input.default))
1180
+ fail(where, '"default" must be a valid value of the field');
1181
+ out.default = input.default;
1182
+ }
1183
+ break;
1184
+ }
1185
+ case "boolean":
1186
+ if (input.default !== void 0 && typeof input.default !== "boolean")
1187
+ fail(where, '"default" must be a boolean');
1188
+ out.default = input.default === true;
1189
+ break;
1190
+ case "array":
1191
+ if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1192
+ out.max = boundedInt(input.max, 1, BLOCK_LIMITS.maxItems, BLOCK_LIMITS.defaultItems, where, "max");
1193
+ out.items = normalizeField(input.items, `${where}[]`, depth + 1);
1194
+ break;
1195
+ case "object":
1196
+ if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1197
+ out.fields = normalizeFields(input.fields, where, depth + 1);
1198
+ break;
1199
+ default:
1200
+ break;
1201
+ }
1202
+ return Object.freeze(out);
1203
+ };
1204
+ var normalizeFields = (input, where, depth) => {
1205
+ if (!isObject(input)) fail(where, '"fields" must be an object of field descriptors');
1206
+ const keys = Object.keys(input);
1207
+ if (keys.length < 1 || keys.length > BLOCK_LIMITS.maxFields)
1208
+ fail(where, `an object needs 1 to ${BLOCK_LIMITS.maxFields} fields`);
1209
+ const out = /* @__PURE__ */ Object.create(null);
1210
+ for (const key of keys) {
1211
+ if (!KEY_PATTERN.test(key) || FORBIDDEN_KEYS2.has(key))
1212
+ fail(where, `field name ${JSON.stringify(key)} must match ${KEY_PATTERN}`);
1213
+ out[key] = normalizeField(input[key], `${where}.${key}`, depth);
1214
+ }
1215
+ return Object.freeze(out);
1216
+ };
1217
+ var blockNameProblem = (name) => {
1218
+ if (typeof name !== "string" || !BLOCK_NAME_PATTERN.test(name))
1219
+ return `the name must match ${BLOCK_NAME_PATTERN}`;
1220
+ if (RESERVED.has(name.toLowerCase())) return `"${name}" is a built-in tool name`;
1221
+ return null;
1222
+ };
1223
+ var defineBlock = (definition) => {
1224
+ if (!isObject(definition))
1225
+ throw new BlockDefinitionError("Magic Editor X block: the definition must be an object");
1226
+ const label2 = typeof definition.name === "string" ? `"${definition.name.slice(0, 50)}"` : "(no name)";
1227
+ for (const key of Object.keys(definition))
1228
+ if (!DEFINITION_KEYS.has(key)) fail(label2, `unknown key "${key}"`);
1229
+ const problem = blockNameProblem(definition.name);
1230
+ if (problem)
1231
+ throw new BlockDefinitionError(
1232
+ `Magic Editor X block ${label2}: ${problem}`,
1233
+ problem.includes("built-in") ? "RESERVED_NAME" : "INVALID_DEFINITION"
1234
+ );
1235
+ const out = {
1236
+ name: definition.name,
1237
+ version: boundedInt(definition.version, 1, 1e6, 1, label2, "version")
1238
+ };
1239
+ for (const [key, max] of [
1240
+ ["title", 100],
1241
+ ["description", 500]
1242
+ ]) {
1243
+ if (definition[key] === void 0) continue;
1244
+ if (typeof definition[key] !== "string" || definition[key].length > max)
1245
+ fail(label2, `"${key}" must be a string of at most ${max} characters`);
1246
+ out[key] = definition[key];
1247
+ }
1248
+ out.schema = normalizeFields(definition.schema, `${label2} schema`, 0);
1249
+ for (const key of ["sanitize", "text", "markdown", "render"]) {
1250
+ if (definition[key] === void 0) continue;
1251
+ if (typeof definition[key] !== "function") fail(label2, `"${key}" must be a function`);
1252
+ out[key] = definition[key];
1253
+ }
1254
+ const presets = definition.presets === void 0 ? [] : definition.presets;
1255
+ if (!Array.isArray(presets) || presets.some((preset) => !BLOCK_PRESETS.includes(preset)))
1256
+ fail(label2, `"presets" must list some of ${BLOCK_PRESETS.join(", ")}`);
1257
+ out.presets = Object.freeze([...new Set(presets)]);
1258
+ return Object.freeze(out);
1259
+ };
1260
+ var cleanValue = (field, value, inline, budget) => {
1261
+ budget.left -= 1;
1262
+ switch (field.type) {
1263
+ case "text":
1264
+ return typeof value === "string" ? value.slice(0, field.max) : field.default;
1265
+ case "inline":
1266
+ return inline(typeof value === "string" ? value.slice(0, field.max) : field.default);
1267
+ case "url":
1268
+ return typeof value === "string" ? sanitizeUrl(value.slice(0, BLOCK_LIMITS.maxUrl), {
1269
+ schemes: field.schemes,
1270
+ allowRelative: field.relative
1271
+ }) : "";
1272
+ case "enum":
1273
+ return typeof value === "string" && field.values.includes(value) ? value : field.default;
1274
+ case "number":
1275
+ return typeof value === "number" && Number.isFinite(value) && value >= field.min && value <= field.max && (!field.integer || Number.isInteger(value)) ? value : field.default;
1276
+ case "boolean":
1277
+ return typeof value === "boolean" ? value : field.default;
1278
+ case "array": {
1279
+ const out = [];
1280
+ if (!Array.isArray(value)) return out;
1281
+ for (const item of value) {
1282
+ if (out.length >= field.max || budget.left <= 0) break;
1283
+ if (!matchesType(field.items, item)) continue;
1284
+ const clean = cleanValue(field.items, item, inline, budget);
1285
+ if (clean !== void 0) out.push(clean);
1286
+ }
1287
+ return out;
1288
+ }
1289
+ case "object":
1290
+ return cleanObject(field.fields, isObject(value) ? value : {}, inline, budget);
1291
+ default:
1292
+ return void 0;
1293
+ }
1294
+ };
1295
+ var matchesType = (field, item) => {
1296
+ switch (field.type) {
1297
+ case "text":
1298
+ case "inline":
1299
+ case "url":
1300
+ case "enum":
1301
+ return typeof item === "string";
1302
+ case "number":
1303
+ return typeof item === "number";
1304
+ case "boolean":
1305
+ return typeof item === "boolean";
1306
+ case "array":
1307
+ return Array.isArray(item);
1308
+ default:
1309
+ return isObject(item);
1310
+ }
1311
+ };
1312
+ var cleanObject = (fields, value, inline, budget) => {
1313
+ const out = {};
1314
+ for (const key of Object.keys(fields)) {
1315
+ const own = Object.prototype.hasOwnProperty.call(value, key) ? value[key] : void 0;
1316
+ const clean = cleanValue(fields[key], own, inline, budget);
1317
+ if (clean !== void 0) out[key] = clean;
1318
+ }
1319
+ return out;
1320
+ };
1321
+ var eachLeaf = (fields, data, visit) => {
1322
+ const walk = (field, value, path, depth) => {
1323
+ if (depth > BLOCK_LIMITS.maxDepth + 1) return;
1324
+ if (field.type === "array") {
1325
+ if (!Array.isArray(value)) return;
1326
+ value.slice(0, field.max).forEach((item, index) => walk(field.items, item, [...path, index], depth + 1));
1327
+ } else if (field.type === "object") {
1328
+ if (!isObject(value)) return;
1329
+ for (const key of Object.keys(field.fields))
1330
+ if (Object.prototype.hasOwnProperty.call(value, key))
1331
+ walk(field.fields[key], value[key], [...path, key], depth + 1);
1332
+ } else visit(field, value, path);
1333
+ };
1334
+ if (!isObject(data)) return;
1335
+ for (const key of Object.keys(fields))
1336
+ if (Object.prototype.hasOwnProperty.call(data, key)) walk(fields[key], data[key], [key], 0);
1337
+ };
1338
+ var fieldAt = (fields, path) => {
1339
+ let current = { type: "object", fields };
1340
+ for (const part of String(path).split(".")) {
1341
+ if (!part) continue;
1342
+ if (current.type === "array") {
1343
+ if (/^\d+$/.test(part)) {
1344
+ current = current.items;
1345
+ continue;
1346
+ }
1347
+ return null;
1348
+ }
1349
+ if (current.type !== "object" || !Object.prototype.hasOwnProperty.call(current.fields, part)) return null;
1350
+ current = current.fields[part];
1351
+ }
1352
+ return current;
1353
+ };
1354
+ var compiled = /* @__PURE__ */ new WeakMap();
1355
+ var compileBlock = (definition) => {
1356
+ if (definition && typeof definition === "object" && compiled.has(definition))
1357
+ return compiled.get(definition);
1358
+ const def = defineBlock(definition && typeof definition === "object" ? { ...definition } : definition);
1359
+ const schema = def.schema;
1360
+ const run = (data, inline) => cleanObject(schema, isObject(data) ? data : {}, inline, { left: BLOCK_LIMITS.maxValues });
1361
+ const result = Object.freeze({
1362
+ ...def,
1363
+ /**
1364
+ * Cleans untrusted block data (unknown keys dropped, values bounded).
1365
+ * The optional `sanitize` hook runs on the clean data; its result is
1366
+ * cleaned again, so it cannot add keys or unsafe values. A hook that
1367
+ * throws is ignored (the clean data is used).
1368
+ * @param {unknown} data - Block data.
1369
+ * @param {(html: string) => string} inline - Inline HTML sanitiser of the caller.
1370
+ * @returns {object} Clean data.
1371
+ */
1372
+ clean: (data, inline) => {
1373
+ const first = run(data, inline);
1374
+ if (!def.sanitize) return first;
1375
+ let next;
1376
+ try {
1377
+ next = def.sanitize(copyData(first), { sanitizeUrl });
1378
+ } catch {
1379
+ return first;
1380
+ }
1381
+ return isObject(next) ? run(next, inline) : first;
1382
+ },
1383
+ /**
1384
+ * Text fields of the data in schema order: `{ path, kind, value }`
1385
+ * (`html` for inline fields, `plain` for text fields).
1386
+ * @param {unknown} data - Block data.
1387
+ * @returns {Array<{ path: Array<string|number>, kind: 'html'|'plain', value: string }>} Fields.
1388
+ */
1389
+ fields: (data) => {
1390
+ const out = [];
1391
+ eachLeaf(schema, data, (field, value, path) => {
1392
+ if (typeof value !== "string") return;
1393
+ if (field.type === "inline") out.push({ path, kind: "html", value });
1394
+ else if (field.type === "text") out.push({ path, kind: "plain", value });
1395
+ });
1396
+ return out;
1397
+ },
1398
+ /**
1399
+ * Non-empty URL values: `{ path, value }`.
1400
+ * @param {unknown} data - Block data.
1401
+ * @returns {Array<{ path: Array<string|number>, value: string }>} URLs.
1402
+ */
1403
+ urls: (data) => {
1404
+ const out = [];
1405
+ eachLeaf(schema, data, (field, value, path) => {
1406
+ if (field.type === "url" && typeof value === "string" && value) out.push({ path, value });
1407
+ });
1408
+ return out;
1409
+ },
1410
+ /**
1411
+ * Kind of the value at a dotted path, for the version diff.
1412
+ * @param {string} path - Dotted path.
1413
+ * @returns {'inline'|'plain'|'value'} Kind.
1414
+ */
1415
+ kindOf: (path) => {
1416
+ const field = fieldAt(schema, path);
1417
+ if (!field) return "value";
1418
+ if (field.type === "inline") return "inline";
1419
+ if (field.type === "text") return "plain";
1420
+ return "value";
1421
+ }
1422
+ });
1423
+ compiled.set(result, result);
1424
+ if (definition && typeof definition === "object") compiled.set(definition, result);
1425
+ return result;
1426
+ };
1427
+ var copyData = (value) => {
1428
+ if (Array.isArray(value)) return value.map(copyData);
1429
+ if (isObject(value)) {
1430
+ const out = {};
1431
+ for (const [key, child] of Object.entries(value)) out[key] = copyData(child);
1432
+ return out;
1433
+ }
1434
+ return value;
1435
+ };
1436
+ var listCache = /* @__PURE__ */ new WeakMap();
1437
+ var compileBlockList = (list) => {
1438
+ if (!Array.isArray(list)) return /* @__PURE__ */ new Map();
1439
+ if (listCache.has(list)) return listCache.get(list);
1440
+ const map = /* @__PURE__ */ new Map();
1441
+ for (const definition of list) {
1442
+ const def = compileBlock(definition);
1443
+ map.set(def.name, def);
1444
+ }
1445
+ listCache.set(list, map);
1446
+ return map;
1447
+ };
1448
+
1449
+ // shared/toc.mjs
1450
+ var HEADING_ID_PREFIX = "mex-h-";
1451
+ var TOC_DEFAULTS = Object.freeze({ title: "", minLevel: 2, maxLevel: 4, style: "unordered" });
1452
+ var TOC_STYLES = Object.freeze(["unordered", "ordered"]);
1453
+ var SAFE_ID = /^[A-Za-z0-9_-]{1,64}$/;
1454
+ var createAnchorAllocator = () => {
1455
+ const used = /* @__PURE__ */ new Set();
1456
+ let position = 0;
1457
+ return (blockId) => {
1458
+ position += 1;
1459
+ const base = `${HEADING_ID_PREFIX}${typeof blockId === "string" && SAFE_ID.test(blockId) ? blockId : position}`;
1460
+ let id = base;
1461
+ for (let n = 2; used.has(id); n += 1) id = `${base}-${n}`;
1462
+ used.add(id);
1463
+ return id;
1464
+ };
1465
+ };
1466
+ var githubSlug = (text) => String(text || "").toLowerCase().trim().replace(/[^\p{L}\p{M}\p{N}\p{Pc} -]/gu, "").replace(/ /g, "-");
1467
+ var createSlugAllocator = () => {
1468
+ const seen = /* @__PURE__ */ new Map();
1469
+ return (text) => {
1470
+ const base = githubSlug(text);
1471
+ let slug = base;
1472
+ if (seen.has(base)) {
1473
+ let n = seen.get(base);
1474
+ do {
1475
+ n += 1;
1476
+ slug = `${base}-${n}`;
1477
+ } while (seen.has(slug));
1478
+ seen.set(base, n);
1479
+ }
1480
+ seen.set(slug, 0);
1481
+ return slug;
1482
+ };
1483
+ };
1484
+ var tocRange = (data) => {
1485
+ const pick = (value, fallback) => Number.isInteger(value) && value >= 1 && value <= 6 ? value : fallback;
1486
+ const a = pick(data && data.minLevel, TOC_DEFAULTS.minLevel);
1487
+ const b = pick(data && data.maxLevel, TOC_DEFAULTS.maxLevel);
1488
+ return { minLevel: Math.min(a, b), maxLevel: Math.max(a, b) };
1489
+ };
1490
+ var buildTocTree = (headings, data) => {
1491
+ const { minLevel, maxLevel } = tocRange(data);
1492
+ const root = { level: 0, children: [] };
1493
+ const stack = [root];
1494
+ for (const heading of headings || []) {
1495
+ if (!heading || heading.level < minLevel || heading.level > maxLevel) continue;
1496
+ const text = String(heading.text || "").replace(/\s+/g, " ").trim();
1497
+ if (!text) continue;
1498
+ while (stack.length > 1 && stack[stack.length - 1].level >= heading.level) stack.pop();
1499
+ const node = {
1500
+ id: heading.id || null,
1501
+ slug: heading.slug || null,
1502
+ level: heading.level,
1503
+ text: text.slice(0, 500),
1504
+ children: []
1505
+ };
1506
+ stack[stack.length - 1].children.push(node);
1507
+ stack.push(node);
1508
+ }
1509
+ return root.children;
1510
+ };
1511
+
1512
+ // shared/synced.mjs
1513
+ var SYNCED_TYPE = "synced";
1514
+ var SYNCED_REF_PATTERN = /^[a-z0-9]{1,64}$/;
1515
+ var SYNCED_LIMITS = Object.freeze({ refsPerResponse: 100 });
1516
+ var BLOCK_ID = /^[A-Za-z0-9_-]{1,64}$/;
1517
+ var MAX_TOGGLE_DEPTH = 16;
1518
+ var isSyncedBlock = (block) => Boolean(block) && block.type === SYNCED_TYPE && isBuiltInBlock(
1519
+ /** @type {any} */
1520
+ block
1521
+ );
1522
+ var syncedRefOf = (block) => {
1523
+ if (!isSyncedBlock(block)) return null;
1524
+ const ref = (
1525
+ /** @type {any} */
1526
+ block.data.ref
1527
+ );
1528
+ return typeof ref === "string" && SYNCED_REF_PATTERN.test(ref) ? ref : null;
1529
+ };
1530
+ var containsSynced = (blocks) => Array.isArray(blocks) && blocks.some(isSyncedBlock);
1531
+ var toBlockTree = (blocks) => {
1532
+ const build = (start, end, depth) => {
1533
+ const out = [];
1534
+ let i = start;
1535
+ while (i < end) {
1536
+ const block = blocks[i];
1537
+ i += 1;
1538
+ const node = { block, children: [], toggle: false };
1539
+ if (block && block.type === "toggle" && depth < MAX_TOGGLE_DEPTH && isPlainObject2(block.data)) {
1540
+ const count = Math.max(0, Math.min(Number(block.data.items) || 0, end - i));
1541
+ node.children = build(i, i + count, depth + 1);
1542
+ node.toggle = true;
1543
+ i += count;
1544
+ }
1545
+ out.push(node);
1546
+ }
1547
+ return out;
1548
+ };
1549
+ return build(0, Array.isArray(blocks) ? blocks.length : 0, 0);
1550
+ };
1551
+ var fromBlockTree = (nodes) => {
1552
+ const out = [];
1553
+ const walk = (list) => {
1554
+ for (const node of list) {
1555
+ const at = out.length;
1556
+ out.push(node.block);
1557
+ if (!node.toggle) continue;
1558
+ walk(node.children);
1559
+ const count = out.length - at - 1;
1560
+ if (Number(node.block.data.items) !== count)
1561
+ out[at] = { ...node.block, data: { ...node.block.data, items: count } };
1562
+ }
1563
+ };
1564
+ walk(nodes);
1565
+ return out;
1566
+ };
1567
+ var replaceBlocks = (blocks, replace) => {
1568
+ const map = (nodes) => {
1569
+ const out = [];
1570
+ for (const node of nodes) {
1571
+ const next = replace(node.block);
1572
+ const children = node.toggle ? map(node.children) : [];
1573
+ if (next === null || next === void 0) {
1574
+ out.push(node.toggle ? { ...node, children } : node);
1575
+ } else if (node.toggle && next.length === 1 && next[0] && next[0].type === "toggle") {
1576
+ out.push({ block: next[0], children, toggle: true });
1577
+ } else {
1578
+ out.push(...toBlockTree(next), ...children);
1579
+ }
1580
+ }
1581
+ return out;
1582
+ };
1583
+ return fromBlockTree(map(toBlockTree(blocks)));
1584
+ };
1585
+ var sourceBlocksOf = (source) => {
1586
+ const data = normalizeEditorDataSafe(source);
1587
+ if (!data || !data.blocks.length) return [];
1588
+ return containsSynced(data.blocks) ? replaceBlocks(data.blocks, (block) => isSyncedBlock(block) ? [] : null) : data.blocks;
1589
+ };
1590
+ var derivedId = (parentId, sourceId, taken) => {
1591
+ const joined = `${parentId}-${sourceId}`;
1592
+ let id = BLOCK_ID.test(joined) ? joined : `sx${hashString(joined)}${hashString(`${sourceId}|${parentId}`)}`;
1593
+ for (let n = 2; taken.has(id); n += 1) id = `sx${hashString(`${joined}|${n}`)}${n}`;
1594
+ taken.add(id);
1595
+ return id;
1596
+ };
1597
+ var expandSynced = (data, lookup, options = {}) => {
1598
+ const origins = /* @__PURE__ */ new Map();
1599
+ if (!data || !Array.isArray(data.blocks) || !containsSynced(data.blocks))
1600
+ return { data, origins, expanded: 0, unresolved: 0 };
1601
+ const maxBlocks = options.maxBlocks || EDITOR_DATA_LIMITS.maxBlocks;
1602
+ const maxBytes = options.maxBytes || EDITOR_DATA_LIMITS.maxBytes - 64 * 1024;
1603
+ const taken = new Set(data.blocks.map((block) => block.id));
1604
+ let total = data.blocks.filter((block) => !isSyncedBlock(block)).length;
1605
+ let bytes = byteLength(JSON.stringify(data));
1606
+ let expanded = 0;
1607
+ let unresolved = 0;
1608
+ const cache = /* @__PURE__ */ new Map();
1609
+ const sourceFor = (ref) => {
1610
+ if (!cache.has(ref)) {
1611
+ let blocks2;
1612
+ try {
1613
+ blocks2 = sourceBlocksOf(typeof lookup === "function" ? lookup(ref) : null);
1614
+ if (blocks2.length && typeof options.filter === "function") {
1615
+ const filtered = options.filter(blocks2);
1616
+ blocks2 = Array.isArray(filtered) ? filtered.filter((block) => !isSyncedBlock(block)) : [];
1617
+ }
1618
+ } catch {
1619
+ blocks2 = [];
1620
+ }
1621
+ cache.set(ref, { blocks: blocks2, size: blocks2.length ? byteLength(JSON.stringify(blocks2)) : 0 });
1622
+ }
1623
+ return cache.get(ref);
1624
+ };
1625
+ const blocks = replaceBlocks(data.blocks, (block) => {
1626
+ if (!isSyncedBlock(block)) return null;
1627
+ const ref = syncedRefOf(block);
1628
+ const source = ref ? sourceFor(ref) : { blocks: [], size: 0 };
1629
+ if (!source.blocks.length || total + source.blocks.length > maxBlocks || bytes + source.size > maxBytes) {
1630
+ unresolved += 1;
1631
+ return [];
1632
+ }
1633
+ total += source.blocks.length;
1634
+ bytes += source.size;
1635
+ expanded += 1;
1636
+ return source.blocks.map((item) => {
1637
+ const id = derivedId(block.id, item.id, taken);
1638
+ origins.set(id, ref);
1639
+ const copy = { id, type: item.type, data: JSON.parse(JSON.stringify(item.data || {})) };
1640
+ if (isPlainObject2(item.tunes) && Object.keys(item.tunes).length)
1641
+ copy.tunes = JSON.parse(JSON.stringify(item.tunes));
1642
+ return copy;
1643
+ });
1644
+ });
1645
+ return {
1646
+ data: { time: data.time || 0, version: data.version || "2.31.7", blocks },
1647
+ origins,
1648
+ expanded,
1649
+ unresolved
1650
+ };
1651
+ };
1652
+ var syncedLookup = (option) => {
1653
+ if (typeof option === "function") return (ref) => option(ref);
1654
+ if (option instanceof Map) return (ref) => option.get(ref);
1655
+ if (isPlainObject2(option))
1656
+ return (ref) => Object.prototype.hasOwnProperty.call(option, ref) ? option[ref] : null;
1657
+ return () => null;
1658
+ };
1659
+
715
1660
  // shared/render/common.mjs
716
- var keepInline = (html) => inlineToHtml(html);
1661
+ var keepInline = (html) => inlineToHtml(html, { storage: true });
717
1662
  var prepareBlocks = (value, options = {}) => {
718
- const data = normalizeEditorDataSafe(value);
719
- if (!data) return [];
1663
+ const normalized = normalizeEditorDataSafe(value);
1664
+ if (!normalized) return [];
1665
+ const data = containsSynced(normalized.blocks) ? expandSynced(normalized, syncedLookup(options.synced)).data : normalized;
720
1666
  const rawPolicy = options.rawHtml === "allow" && typeof options.sanitizeRaw === "function" ? "allow" : "disable";
721
1667
  const ctx = { rawHtml: rawPolicy, rawSanitizer: () => "" };
1668
+ const explicit = Array.isArray(options.blocks) ? compileBlockList(options.blocks) : null;
722
1669
  const flat = data.blocks.map((block) => {
723
- const known = Object.prototype.hasOwnProperty.call(BLOCK_POLICIES, block.type);
724
- const raw = isPlainObject(block.data) ? block.data : {};
725
- const clean = known ? BLOCK_POLICIES[block.type](raw, keepInline, ctx) : raw;
1670
+ const raw = isPlainObject2(block.data) ? block.data : {};
1671
+ const known = isBuiltInBlock({ type: block.type, data: raw });
1672
+ const definition = known ? null : registeredBlockOf({ type: block.type, data: raw }, explicit);
1673
+ const clean = known ? BLOCK_POLICIES[block.type](raw, keepInline, ctx) : definition ? definition.clean(raw, keepInline) : raw;
726
1674
  for (const key of Object.keys(clean)) if (clean[key] === void 0) delete clean[key];
727
1675
  return {
728
1676
  id: block.id,
@@ -731,6 +1679,7 @@ var prepareBlocks = (value, options = {}) => {
731
1679
  raw,
732
1680
  tunes: sanitizeTunes(block.tunes),
733
1681
  known,
1682
+ definition,
734
1683
  children: []
735
1684
  };
736
1685
  });
@@ -761,27 +1710,36 @@ var imageCandidates = (file) => {
761
1710
  seen.add(width);
762
1711
  out.push({ url: clean, width });
763
1712
  };
764
- if (isPlainObject(file.formats)) {
1713
+ if (isPlainObject2(file.formats)) {
765
1714
  const names = Object.keys(file.formats).sort(
766
1715
  (a, b) => (FORMAT_ORDER.indexOf(a) + 1 || 99) - (FORMAT_ORDER.indexOf(b) + 1 || 99) || (a < b ? -1 : a > b ? 1 : 0)
767
1716
  );
768
1717
  for (const name of names) {
769
1718
  const format = file.formats[name];
770
- if (isPlainObject(format)) push(format.url, Number(format.width));
1719
+ if (isPlainObject2(format)) push(format.url, Number(format.width));
771
1720
  }
772
1721
  }
773
1722
  push(file.url, Number(file.width));
774
1723
  return out.sort((a, b) => a.width - b.width);
775
1724
  };
776
- var resolveMedia = (file, block, options) => {
1725
+ var resolveMedia = (file, block, options, kind) => {
777
1726
  if (typeof options.media !== "function") return file;
1727
+ if (kind) {
1728
+ let other;
1729
+ try {
1730
+ other = options.media({ ...file }, { id: block.id, type: block.type });
1731
+ } catch {
1732
+ other = null;
1733
+ }
1734
+ return isPlainObject2(other) ? cleanMediaFile(other, kind) : file;
1735
+ }
778
1736
  let next;
779
1737
  try {
780
1738
  next = options.media({ ...file }, { id: block.id, type: block.type });
781
1739
  } catch {
782
1740
  next = null;
783
1741
  }
784
- if (!isPlainObject(next)) return file;
1742
+ if (!isPlainObject2(next)) return file;
785
1743
  const policy = BLOCK_POLICIES.image({ file: next }, (s) => s, {
786
1744
  rawHtml: "disable",
787
1745
  rawSanitizer: () => ""
@@ -815,27 +1773,53 @@ var overrideFor = (options, type) => {
815
1773
  return null;
816
1774
  return typeof overrides[type] === "function" ? overrides[type] : null;
817
1775
  };
818
- var scalarFields = (data) => Object.keys(isPlainObject(data) ? data : {}).filter((key) => /^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(key)).filter((key) => ["string", "number", "boolean"].includes(typeof data[key])).map((key) => [key, String(data[key])]);
1776
+ var scalarFields = (data) => Object.keys(isPlainObject2(data) ? data : {}).filter((key) => /^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(key)).filter((key) => ["string", "number", "boolean"].includes(typeof data[key])).map((key) => [key, String(data[key])]);
819
1777
  var formatSize = (bytes) => {
820
1778
  if (!Number.isFinite(bytes) || bytes < 0) return "";
821
1779
  if (bytes < 1024) return `${bytes} B`;
822
1780
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
823
1781
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
824
1782
  };
1783
+ var eachBlock = (blocks, fn, depth = 0) => {
1784
+ if (depth > 16) return;
1785
+ for (const block of blocks) {
1786
+ fn(block);
1787
+ if (block.children.length) eachBlock(block.children, fn, depth + 1);
1788
+ }
1789
+ };
1790
+ var annotateHeadings = (blocks, options = {}) => {
1791
+ const tocs = [];
1792
+ const headers = [];
1793
+ eachBlock(blocks, (block) => {
1794
+ if (!block.known) return;
1795
+ if (block.type === "toc") tocs.push(block);
1796
+ else if (block.type === "header") headers.push(block);
1797
+ });
1798
+ const enabled = options.headingIds === true || options.headingIds !== false && tocs.length > 0;
1799
+ if (!enabled && !tocs.length) return blocks;
1800
+ const allocate = createAnchorAllocator();
1801
+ const slugOf = createSlugAllocator();
1802
+ const headings = headers.map((block) => {
1803
+ const id = allocate(block.id);
1804
+ const text = inlineToText(block.data.text);
1805
+ if (enabled) block.anchor = id;
1806
+ return { id: enabled ? id : null, slug: slugOf(text.trim()), level: block.data.level, text };
1807
+ });
1808
+ for (const toc of tocs) {
1809
+ toc.headings = headings;
1810
+ toc.linkHeadings = enabled;
1811
+ }
1812
+ return blocks;
1813
+ };
825
1814
 
826
- // shared/render/html.mjs
1815
+ // shared/render/tree.mjs
827
1816
  var COUNTER_TYPES = Object.freeze({
828
1817
  "lower-roman": "i",
829
1818
  "upper-roman": "I",
830
1819
  "lower-alpha": "a",
831
1820
  "upper-alpha": "A"
832
1821
  });
833
- var el = (tag, attrs, inner) => {
834
- const attributes = Object.entries(attrs || {}).filter(
835
- ([name, value]) => value !== void 0 && value !== null && value !== false && (value !== "" || name === "alt")
836
- ).map(([name, value]) => value === true ? ` ${name}` : ` ${name}="${escapeHtml2(value)}"`).join("");
837
- return inner === void 0 ? `<${tag}${attributes}>` : `<${tag}${attributes}>${inner}</${tag}>`;
838
- };
1822
+ var MAX_NUMBERED_LINES = 2e4;
839
1823
  var classes = (base, tunes) => {
840
1824
  const list = [...base];
841
1825
  if (tunes && tunes.alignmentTune && tunes.alignmentTune.alignment !== "left")
@@ -846,16 +1830,24 @@ var classes = (base, tunes) => {
846
1830
  return list.join(" ");
847
1831
  };
848
1832
  var listItems2 = (items, style, options, depth) => items.map((item) => {
849
- if (typeof item === "string") return el("li", {}, inlineToHtml(item, options));
1833
+ if (typeof item === "string") return el("li", {}, inlineToNodes(item, options));
850
1834
  const checked = Boolean(item.meta && item.meta.checked);
851
- const check = style === "checklist" ? `${el("input", { type: "checkbox", disabled: true, checked, "aria-label": checked ? "done" : "open" })} ` : "";
852
- const nested = Array.isArray(item.items) && item.items.length && depth < 12 ? listElement(item.items, style, {}, options, depth + 1, []) : "";
1835
+ const check = style === "checklist" ? [
1836
+ el("input", {
1837
+ type: "checkbox",
1838
+ disabled: true,
1839
+ checked,
1840
+ "aria-label": checked ? "done" : "open"
1841
+ }),
1842
+ " "
1843
+ ] : [];
1844
+ const nested = Array.isArray(item.items) && item.items.length && depth < 12 ? listElement(item.items, style, {}, options, depth + 1, []) : null;
853
1845
  return el(
854
1846
  "li",
855
1847
  style === "checklist" ? { class: "mex-checklist-item", "data-checked": String(checked) } : {},
856
- check + inlineToHtml(item.content, options) + nested
1848
+ [check, inlineToNodes(item.content, options), nested]
857
1849
  );
858
- }).join("");
1850
+ });
859
1851
  var listElement = (items, style, meta, options, depth, base, tunes) => {
860
1852
  const tag = style === "ordered" ? "ol" : "ul";
861
1853
  const attrs = {};
@@ -866,16 +1858,140 @@ var listElement = (items, style, meta, options, depth, base, tunes) => {
866
1858
  }
867
1859
  return el(tag, attrs, listItems2(items, style, options, depth));
868
1860
  };
869
- var figure = (url, img, caption, cls) => el(
870
- "figure",
871
- { class: cls },
872
- el("img", { src: url, ...img, loading: "lazy", decoding: "async" }) + (caption ? el("figcaption", {}, caption) : "")
873
- );
1861
+ var figure = (url, img, caption, cls) => el("figure", { class: cls }, [
1862
+ el("img", { src: url, ...img, loading: "lazy", decoding: "async" }),
1863
+ caption.length ? el("figcaption", {}, caption) : null
1864
+ ]);
1865
+ var withFocalPoint = (img, point, o) => {
1866
+ if (!point || img.type !== "element") return img;
1867
+ img.attrs["data-mex-focal-x"] = String(point.x);
1868
+ img.attrs["data-mex-focal-y"] = String(point.y);
1869
+ if (o.focalPoint === "style")
1870
+ img.style = { "object-position": `${Math.round(point.x * 100)}% ${Math.round(point.y * 100)}%` };
1871
+ return img;
1872
+ };
1873
+ var libraryImageAttrs = (file, decorative, o) => {
1874
+ const candidates = imageCandidates(file);
1875
+ const img = {
1876
+ alt: decorative ? "" : file.alt || "",
1877
+ width: Number.isInteger(file.width) && file.width > 0 ? file.width : void 0,
1878
+ height: Number.isInteger(file.height) && file.height > 0 ? file.height : void 0
1879
+ };
1880
+ if (candidates.length > 1) {
1881
+ img.srcset = candidates.map((c) => `${c.url} ${c.width}w`).join(", ");
1882
+ img.sizes = typeof o.imageSizes === "string" && /^[\w\s(),.:%-]{1,200}$/.test(o.imageSizes) ? o.imageSizes : "100vw";
1883
+ }
1884
+ return img;
1885
+ };
1886
+ var trackNodes = (b, o) => b.data.tracks.map((track) => {
1887
+ const file = resolveMedia(track.file, b, o, { vtt: true });
1888
+ if (!file.url) return null;
1889
+ return el("track", {
1890
+ kind: track.kind,
1891
+ src: file.url,
1892
+ srclang: track.srclang || void 0,
1893
+ label: track.label || void 0,
1894
+ default: track.default === true
1895
+ });
1896
+ }).filter(Boolean);
1897
+ var mediaFigure = (tag, b, o) => {
1898
+ const file = resolveMedia(b.data.file, b, o, { mimePrefix: `${tag}/` });
1899
+ if (!file.url) return null;
1900
+ const caption = inlineToNodes(b.data.caption, o);
1901
+ const attrs = {
1902
+ src: file.url,
1903
+ controls: true,
1904
+ preload: "metadata",
1905
+ "aria-label": b.data.title || void 0,
1906
+ loop: b.data.loop === true
1907
+ };
1908
+ if (tag === "video") {
1909
+ const poster = b.data.poster ? resolveMedia(b.data.poster, b, o) : null;
1910
+ Object.assign(attrs, {
1911
+ playsinline: true,
1912
+ muted: b.data.muted === true,
1913
+ poster: poster && poster.url ? poster.url : void 0,
1914
+ width: Number.isInteger(file.width) && file.width > 0 ? file.width : void 0,
1915
+ height: Number.isInteger(file.height) && file.height > 0 ? file.height : void 0
1916
+ });
1917
+ }
1918
+ return el("figure", { class: classes([`mex-${tag}`], b.tunes) }, [
1919
+ el(tag, attrs, [
1920
+ trackNodes(b, o),
1921
+ // Fallback for browsers without media support.
1922
+ el("a", { href: file.url }, b.data.title || file.name || file.url)
1923
+ ]),
1924
+ caption.length ? el("figcaption", {}, caption) : null
1925
+ ]);
1926
+ };
1927
+ var label = (value, fallback) => {
1928
+ if (typeof value !== "string") return fallback;
1929
+ const clean = value.trim();
1930
+ return clean && clean.length <= 80 ? clean : fallback;
1931
+ };
1932
+ var tocLabel = (options) => label(isPlainObject2(options.toc) ? options.toc.label : void 0, "Table of contents");
1933
+ var codeOptions = (options) => {
1934
+ const code = isPlainObject2(options.code) ? options.code : {};
1935
+ const lineNumbers = code.lineNumbers === true ? "all" : code.lineNumbers === "block" ? "block" : "none";
1936
+ const button = code.copyButton;
1937
+ const copy = button === true || isPlainObject2(button) ? {
1938
+ label: label(isPlainObject2(button) ? button.label : void 0, "Copy code"),
1939
+ copied: label(isPlainObject2(button) ? button.copiedLabel : void 0, "Copied"),
1940
+ failed: label(isPlainObject2(button) ? button.failedLabel : void 0, "Copy failed")
1941
+ } : null;
1942
+ return { lineNumbers, copy };
1943
+ };
1944
+ var numberedLines = (code) => {
1945
+ const parts = code.split("\n");
1946
+ const trailing = parts.length > 1 && parts[parts.length - 1] === "";
1947
+ if (trailing) parts.pop();
1948
+ const out = [];
1949
+ parts.forEach((line, index) => {
1950
+ if (index) out.push("\n");
1951
+ out.push(el("span", { class: "mex-code-line" }, line));
1952
+ });
1953
+ if (trailing) out.push("\n");
1954
+ return out;
1955
+ };
1956
+ var codeBlock = (b, language, o) => {
1957
+ const { lineNumbers, copy } = codeOptions(o);
1958
+ const code = String(b.data.code);
1959
+ const wantNumbers = lineNumbers === "all" || lineNumbers === "block" && b.type === "codeFlask" && b.data.showlinenumbers !== false;
1960
+ const numbers = wantNumbers && code.split("\n").length <= MAX_NUMBERED_LINES;
1961
+ const pre = el(
1962
+ "pre",
1963
+ {
1964
+ class: classes(["mex-code", ...numbers ? ["mex-code-lines"] : []], b.tunes),
1965
+ "data-language": language
1966
+ },
1967
+ el("code", language ? { class: `language-${language}` } : {}, numbers ? numberedLines(code) : code)
1968
+ );
1969
+ if (!copy) return pre;
1970
+ return el("div", { class: "mex-code-block", "data-mex-code": "copy" }, [
1971
+ pre,
1972
+ el(
1973
+ "button",
1974
+ {
1975
+ type: "button",
1976
+ class: "mex-code-copy",
1977
+ "data-mex-copy": "code",
1978
+ "data-mex-copied": copy.copied,
1979
+ "data-mex-failed": copy.failed
1980
+ },
1981
+ copy.label
1982
+ ),
1983
+ el("span", { class: "mex-code-copy-status", role: "status", "aria-live": "polite" })
1984
+ ]);
1985
+ };
874
1986
  var RENDERERS = {
875
- paragraph: (b, o) => el("p", { class: classes(["mex-paragraph"], b.tunes) }, inlineToHtml(b.data.text, o)),
876
- header: (b, o) => el(`h${b.data.level}`, { class: classes(["mex-header"], b.tunes) }, inlineToHtml(b.data.text, o)),
1987
+ paragraph: (b, o) => el("p", { class: classes(["mex-paragraph"], b.tunes) }, inlineToNodes(b.data.text, o)),
1988
+ header: (b, o) => el(
1989
+ `h${b.data.level}`,
1990
+ { id: b.anchor, class: classes(["mex-header"], b.tunes) },
1991
+ inlineToNodes(b.data.text, o)
1992
+ ),
877
1993
  quote: (b, o) => {
878
- const caption = inlineToHtml(b.data.caption, o);
1994
+ const caption = inlineToNodes(b.data.caption, o);
879
1995
  return el(
880
1996
  "figure",
881
1997
  {
@@ -884,7 +2000,10 @@ var RENDERERS = {
884
2000
  b.tunes
885
2001
  )
886
2002
  },
887
- el("blockquote", {}, inlineToHtml(b.data.text, o)) + (caption ? el("figcaption", {}, caption) : "")
2003
+ [
2004
+ el("blockquote", {}, inlineToNodes(b.data.text, o)),
2005
+ caption.length ? el("figcaption", {}, caption) : null
2006
+ ]
888
2007
  );
889
2008
  },
890
2009
  list: (b, o) => listElement(
@@ -906,12 +2025,11 @@ var RENDERERS = {
906
2025
  b.tunes
907
2026
  ),
908
2027
  warning: (b, o) => {
909
- const title = inlineToHtml(b.data.title, o);
910
- return el(
911
- "aside",
912
- { class: classes(["mex-warning"], b.tunes), role: "note" },
913
- (title ? el("p", { class: "mex-warning-title" }, el("strong", {}, title)) : "") + el("p", { class: "mex-warning-message" }, inlineToHtml(b.data.message, o))
914
- );
2028
+ const title = inlineToNodes(b.data.title, o);
2029
+ return el("aside", { class: classes(["mex-warning"], b.tunes), role: "note" }, [
2030
+ title.length ? el("p", { class: "mex-warning-title" }, el("strong", {}, title)) : null,
2031
+ el("p", { class: "mex-warning-message" }, inlineToNodes(b.data.message, o))
2032
+ ]);
915
2033
  },
916
2034
  alert: (b, o) => el(
917
2035
  "div",
@@ -926,62 +2044,49 @@ var RENDERERS = {
926
2044
  ),
927
2045
  role: "note"
928
2046
  },
929
- inlineToHtml(b.data.message, o)
930
- ),
931
- toggle: (b, o, render) => el(
932
- "details",
933
- { class: classes(["mex-toggle"], b.tunes), open: b.data.status !== "closed" },
934
- el("summary", {}, inlineToHtml(b.data.text, o)) + render(b.children)
935
- ),
936
- code: (b) => el("pre", { class: classes(["mex-code"], b.tunes) }, el("code", {}, escapeHtml2(b.data.code))),
937
- codeFlask: (b) => el(
938
- "pre",
939
- { class: classes(["mex-code"], b.tunes), "data-language": b.data.language },
940
- el("code", { class: `language-${b.data.language}` }, escapeHtml2(b.data.code))
2047
+ inlineToNodes(b.data.message, o)
941
2048
  ),
2049
+ toggle: (b, o, renderList) => el("details", { class: classes(["mex-toggle"], b.tunes), open: b.data.status !== "closed" }, [
2050
+ el("summary", {}, inlineToNodes(b.data.text, o)),
2051
+ renderList(b.children)
2052
+ ]),
2053
+ code: (b, o) => codeBlock(b, void 0, o),
2054
+ codeFlask: (b, o) => codeBlock(b, b.data.language, o),
942
2055
  raw: (b, o) => {
943
- if (o.rawHtml !== "allow" || typeof o.sanitizeRaw !== "function") return "";
2056
+ if (o.rawHtml !== "allow" || typeof o.sanitizeRaw !== "function") return null;
944
2057
  const html = o.sanitizeRaw(String(b.raw.html || ""));
945
- return typeof html === "string" && html ? el("div", { class: classes(["mex-raw"], b.tunes) }, html) : "";
2058
+ return typeof html === "string" && html ? el("div", { class: classes(["mex-raw"], b.tunes) }, { type: "raw", html }) : null;
946
2059
  },
947
2060
  table: (b, o) => {
948
2061
  const rows = b.data.content;
949
- if (!rows.length) return "";
2062
+ if (!rows.length) return null;
950
2063
  const cells = (row, tag) => el(
951
2064
  "tr",
952
2065
  {},
953
- row.map((cell2) => el(tag, tag === "th" ? { scope: "col" } : {}, inlineToHtml(cell2, o))).join("")
2066
+ row.map((cell2) => el(tag, tag === "th" ? { scope: "col" } : {}, inlineToNodes(cell2, o)))
954
2067
  );
955
- const head = b.data.withHeadings ? el("thead", {}, cells(rows[0], "th")) : "";
956
- const body = (b.data.withHeadings ? rows.slice(1) : rows).map((row) => cells(row, "td")).join("");
2068
+ const head = b.data.withHeadings ? el("thead", {}, cells(rows[0], "th")) : null;
2069
+ const body = (b.data.withHeadings ? rows.slice(1) : rows).map((row) => cells(row, "td"));
957
2070
  return el(
958
2071
  "table",
959
2072
  { class: classes(["mex-table", ...b.data.stretched ? ["mex-stretched"] : []], b.tunes) },
960
- head + (body ? el("tbody", {}, body) : "")
2073
+ [head, body.length ? el("tbody", {}, body) : null]
961
2074
  );
962
2075
  },
963
2076
  image: (b, o) => {
964
2077
  const file = resolveMedia(b.data.file, b, o);
965
- if (!file.url) return "";
966
- const decorative = b.raw.decorative === true;
967
- const candidates = imageCandidates(file);
968
- const img = {
969
- alt: decorative ? "" : file.alt || "",
970
- width: Number.isInteger(file.width) && file.width > 0 ? file.width : void 0,
971
- height: Number.isInteger(file.height) && file.height > 0 ? file.height : void 0
972
- };
973
- if (candidates.length > 1) {
974
- img.srcset = candidates.map((c) => `${c.url} ${c.width}w`).join(", ");
975
- img.sizes = typeof o.imageSizes === "string" && /^[\w\s(),.:%-]{1,200}$/.test(o.imageSizes) ? o.imageSizes : "100vw";
976
- }
2078
+ if (!file.url) return null;
2079
+ const img = libraryImageAttrs(file, b.raw.decorative === true, o);
977
2080
  const cls = ["mex-image"];
978
2081
  if (b.data.withBorder) cls.push("mex-image-border");
979
2082
  if (b.data.withBackground) cls.push("mex-image-background");
980
2083
  if (b.data.stretched) cls.push("mex-stretched");
981
- return figure(file.url, img, inlineToHtml(b.data.caption, o), classes(cls, b.tunes));
2084
+ const node = figure(file.url, img, inlineToNodes(b.data.caption, o), classes(cls, b.tunes));
2085
+ withFocalPoint(node.children[0], b.data.focalPoint, o);
2086
+ return node;
982
2087
  },
983
2088
  simpleImage: (b, o) => {
984
- if (!b.data.url) return "";
2089
+ if (!b.data.url) return null;
985
2090
  const cls = ["mex-image"];
986
2091
  if (b.data.withBorder) cls.push("mex-image-border");
987
2092
  if (b.data.withBackground) cls.push("mex-image-background");
@@ -991,44 +2096,82 @@ var RENDERERS = {
991
2096
  {
992
2097
  alt: b.data.decorative === true ? "" : typeof b.data.alt === "string" && b.data.alt.trim() ? b.data.alt : inlineToText(b.data.caption)
993
2098
  },
994
- inlineToHtml(b.data.caption, o),
2099
+ inlineToNodes(b.data.caption, o),
995
2100
  classes(cls, b.tunes)
996
2101
  );
997
2102
  },
2103
+ gallery: (b, o) => {
2104
+ const items = b.data.images.map((image) => {
2105
+ const file = resolveMedia(image.file, b, o);
2106
+ if (!file.url) return null;
2107
+ const caption2 = inlineToNodes(image.caption, o);
2108
+ const img = el("img", {
2109
+ src: file.url,
2110
+ ...libraryImageAttrs(file, image.decorative === true, o),
2111
+ loading: "lazy",
2112
+ decoding: "async"
2113
+ });
2114
+ withFocalPoint(img, image.focalPoint, o);
2115
+ return el(
2116
+ "li",
2117
+ { class: "mex-gallery-item" },
2118
+ el("figure", { class: "mex-gallery-figure" }, [
2119
+ img,
2120
+ caption2.length ? el("figcaption", {}, caption2) : null
2121
+ ])
2122
+ );
2123
+ }).filter(Boolean);
2124
+ if (!items.length) return null;
2125
+ const { layout, columns } = b.data;
2126
+ const caption = inlineToNodes(b.data.caption, o);
2127
+ return el(
2128
+ "figure",
2129
+ {
2130
+ class: classes(["mex-gallery", `mex-gallery-${layout}`, `mex-gallery-cols-${columns}`], b.tunes),
2131
+ "data-mex-layout": layout,
2132
+ "data-mex-columns": String(columns)
2133
+ },
2134
+ [el("ul", { class: "mex-gallery-items" }, items), caption.length ? el("figcaption", {}, caption) : null]
2135
+ );
2136
+ },
2137
+ video: (b, o) => mediaFigure("video", b, o),
2138
+ audio: (b, o) => mediaFigure("audio", b, o),
998
2139
  linkTool: (b) => {
999
- if (!b.data.link) return "";
2140
+ if (!b.data.link) return null;
1000
2141
  const meta = b.data.meta;
1001
- const image = meta.image && meta.image.url ? el("img", { class: "mex-link-image", src: meta.image.url, alt: "", loading: "lazy" }) : "";
1002
- const inner = image + el("span", { class: "mex-link-title" }, escapeHtml2(meta.title || b.data.link)) + (meta.description ? el("span", { class: "mex-link-description" }, escapeHtml2(meta.description)) : "") + (meta.site_name ? el("span", { class: "mex-link-site" }, escapeHtml2(meta.site_name)) : "");
1003
2142
  return el(
1004
2143
  "div",
1005
2144
  { class: classes(["mex-link-preview"], b.tunes) },
1006
- el("a", { href: b.data.link, rel: "nofollow noopener noreferrer" }, inner)
2145
+ el("a", { href: b.data.link, rel: "nofollow noopener noreferrer" }, [
2146
+ meta.image && meta.image.url ? el("img", { class: "mex-link-image", src: meta.image.url, alt: "", loading: "lazy" }) : null,
2147
+ el("span", { class: "mex-link-title" }, meta.title || b.data.link),
2148
+ meta.description ? el("span", { class: "mex-link-description" }, meta.description) : null,
2149
+ meta.site_name ? el("span", { class: "mex-link-site" }, meta.site_name) : null
2150
+ ])
1007
2151
  );
1008
2152
  },
1009
2153
  attaches: (b) => {
1010
2154
  const file = b.data.file;
1011
- if (!file.url) return "";
1012
- const label = b.data.title || file.title || file.name || file.url;
2155
+ if (!file.url) return null;
2156
+ const text = b.data.title || file.title || file.name || file.url;
1013
2157
  const details = [file.extension ? file.extension.toUpperCase() : "", formatSize(file.size)].filter(Boolean).join(", ");
1014
- return el(
1015
- "p",
1016
- { class: classes(["mex-attachment"], b.tunes) },
1017
- el("a", { href: file.url, download: true }, escapeHtml2(label)) + (details ? ` ${el("span", { class: "mex-attachment-meta" }, `(${escapeHtml2(details)})`)}` : "")
1018
- );
2158
+ return el("p", { class: classes(["mex-attachment"], b.tunes) }, [
2159
+ el("a", { href: file.url, download: true }, text),
2160
+ details ? [" ", el("span", { class: "mex-attachment-meta" }, `(${details})`)] : null
2161
+ ]);
1019
2162
  },
1020
2163
  embed: (b, o) => {
1021
2164
  const hosts = Array.isArray(o.embedHosts) ? o.embedHosts.map((h) => String(h).toLowerCase()) : DEFAULT_EMBED_HOSTS;
1022
2165
  const frame = embedFrameUrl(b.data.embed, hosts);
1023
- const caption = inlineToHtml(b.data.caption, o);
2166
+ const caption = inlineToNodes(b.data.caption, o);
1024
2167
  const title = inlineToText(b.data.caption) || b.data.service || "Embedded content";
1025
2168
  if (!frame) {
1026
2169
  const href = b.data.source || b.data.embed;
1027
- if (!href) return "";
2170
+ if (!href) return null;
1028
2171
  return el(
1029
2172
  "p",
1030
2173
  { class: classes(["mex-embed", "mex-embed-link"], b.tunes) },
1031
- el("a", { href, rel: "nofollow noopener noreferrer" }, caption || escapeHtml2(href))
2174
+ el("a", { href, rel: "nofollow noopener noreferrer" }, caption.length ? caption : href)
1032
2175
  );
1033
2176
  }
1034
2177
  return el(
@@ -1039,9 +2182,8 @@ var RENDERERS = {
1039
2182
  b.tunes
1040
2183
  )
1041
2184
  },
1042
- el(
1043
- "iframe",
1044
- {
2185
+ [
2186
+ el("iframe", {
1045
2187
  src: frame,
1046
2188
  title,
1047
2189
  width: b.data.width,
@@ -1051,27 +2193,26 @@ var RENDERERS = {
1051
2193
  sandbox: "allow-scripts allow-same-origin allow-popups allow-presentation",
1052
2194
  allow: "fullscreen; picture-in-picture; encrypted-media",
1053
2195
  allowfullscreen: true
1054
- },
1055
- ""
1056
- ) + (caption ? el("figcaption", {}, caption) : "")
2196
+ }),
2197
+ caption.length ? el("figcaption", {}, caption) : null
2198
+ ]
1057
2199
  );
1058
2200
  },
1059
2201
  personality: (b) => {
1060
2202
  const d = b.data;
1061
- if (!d.name && !d.description) return "";
1062
- return el(
1063
- "div",
1064
- { class: classes(["mex-personality"], b.tunes) },
1065
- (d.photo ? el("img", { class: "mex-personality-photo", src: d.photo, alt: "", loading: "lazy" }) : "") + el(
1066
- "div",
1067
- { class: "mex-personality-body" },
1068
- (d.name ? el("p", { class: "mex-personality-name" }, escapeHtml2(d.name)) : "") + (d.description ? el("p", { class: "mex-personality-description" }, escapeHtml2(d.description)) : "") + (d.link ? el("a", { class: "mex-personality-link", href: d.link }, escapeHtml2(d.link)) : "")
1069
- )
1070
- );
2203
+ if (!d.name && !d.description) return null;
2204
+ return el("div", { class: classes(["mex-personality"], b.tunes) }, [
2205
+ d.photo ? el("img", { class: "mex-personality-photo", src: d.photo, alt: "", loading: "lazy" }) : null,
2206
+ el("div", { class: "mex-personality-body" }, [
2207
+ d.name ? el("p", { class: "mex-personality-name" }, d.name) : null,
2208
+ d.description ? el("p", { class: "mex-personality-description" }, d.description) : null,
2209
+ d.link ? el("a", { class: "mex-personality-link", href: d.link }, d.link) : null
2210
+ ])
2211
+ ]);
1071
2212
  },
1072
2213
  button: (b) => {
1073
2214
  const d = b.data;
1074
- if (!d.text) return "";
2215
+ if (!d.text) return null;
1075
2216
  const cls = `mex-button mex-button-${d.style}`;
1076
2217
  const inner = d.link ? el(
1077
2218
  "a",
@@ -1081,50 +2222,282 @@ var RENDERERS = {
1081
2222
  target: d.openInNewTab ? "_blank" : void 0,
1082
2223
  rel: d.openInNewTab ? "noopener noreferrer" : void 0
1083
2224
  },
1084
- escapeHtml2(d.text)
1085
- ) : el("span", { class: cls }, escapeHtml2(d.text));
2225
+ d.text
2226
+ ) : el("span", { class: cls }, d.text);
1086
2227
  return el("p", { class: classes(["mex-button-block"], b.tunes) }, inner);
1087
2228
  },
1088
- delimiter: (b) => el("hr", { class: classes(["mex-delimiter"], b.tunes) })
2229
+ delimiter: (b) => el("hr", { class: classes(["mex-delimiter"], b.tunes) }),
2230
+ toc: (b, o) => {
2231
+ const tree = buildTocTree(b.headings || [], b.data);
2232
+ if (!tree.length) return null;
2233
+ const tag = b.data.style === "ordered" ? "ol" : "ul";
2234
+ const list = (nodes) => el(
2235
+ tag,
2236
+ { class: "mex-toc-list" },
2237
+ nodes.map(
2238
+ (node) => el("li", { class: "mex-toc-item" }, [
2239
+ b.linkHeadings && node.id ? el("a", { href: `#${node.id}` }, node.text) : node.text,
2240
+ node.children.length ? list(node.children) : null
2241
+ ])
2242
+ )
2243
+ );
2244
+ const title = b.data.title.trim();
2245
+ return el(
2246
+ "nav",
2247
+ {
2248
+ class: classes(["mex-toc", `mex-toc-${b.data.style}`], b.tunes),
2249
+ "aria-label": title || tocLabel(o)
2250
+ },
2251
+ [title ? el("p", { class: "mex-toc-title" }, title) : null, list(tree)]
2252
+ );
2253
+ }
1089
2254
  };
1090
2255
  var neutral = (b) => el(
1091
2256
  "div",
1092
2257
  { class: classes(["mex-block", `mex-${b.type}`], b.tunes), "data-mex-block": b.type },
1093
2258
  scalarFields(b.data).map(
1094
- ([key, value]) => el("div", { class: "mex-field", "data-mex-field": key }, escapeHtml2(inlineToText(value)))
1095
- ).join("")
2259
+ ([key, value]) => el("div", { class: "mex-field", "data-mex-field": key }, inlineToText(value))
2260
+ )
1096
2261
  );
1097
- var helpersFor = (options, render) => ({
1098
- escape: escapeHtml2,
1099
- inline: (html) => inlineToHtml(html, options),
1100
- text: (html) => inlineToText(html),
1101
- url: (value, schemes) => sanitizeUrl(value, schemes ? { schemes } : void 0),
1102
- renderChildren: (blocks) => render(blocks)
1103
- });
1104
- var renderHtml = (value, options = {}) => {
2262
+ var registeredDefault = (b, o) => {
2263
+ const children = [];
2264
+ for (const [key, field] of Object.entries(b.definition.schema)) {
2265
+ const value = b.data[key];
2266
+ if (value === void 0 || value === null || value === "") continue;
2267
+ const attrs = { class: "mex-field", "data-mex-field": key };
2268
+ if (field.type === "inline") children.push(el("div", attrs, inlineToNodes(value, o)));
2269
+ else if (field.type === "url") children.push(el("div", attrs, el("a", { href: value }, value)));
2270
+ else if (["text", "enum", "number", "boolean"].includes(field.type))
2271
+ children.push(el("div", attrs, String(value)));
2272
+ }
2273
+ return el(
2274
+ "div",
2275
+ { class: classes(["mex-block", `mex-${b.type}`], b.tunes), "data-mex-block": b.type },
2276
+ children
2277
+ );
2278
+ };
2279
+ var DENIED_TAGS = /* @__PURE__ */ new Set([
2280
+ "script",
2281
+ "style",
2282
+ "base",
2283
+ "meta",
2284
+ "link",
2285
+ "head",
2286
+ "html",
2287
+ "body",
2288
+ "title",
2289
+ "object",
2290
+ "embed",
2291
+ "applet",
2292
+ "frame",
2293
+ "frameset",
2294
+ "template",
2295
+ "noscript",
2296
+ "noembed",
2297
+ "noframes",
2298
+ "svg",
2299
+ "math",
2300
+ "xmp",
2301
+ "plaintext",
2302
+ "form"
2303
+ ]);
2304
+ var URL_ATTRIBUTES = /* @__PURE__ */ new Set([
2305
+ "href",
2306
+ "src",
2307
+ "action",
2308
+ "formaction",
2309
+ "poster",
2310
+ "cite",
2311
+ "data",
2312
+ "background",
2313
+ "longdesc",
2314
+ "manifest",
2315
+ "ping",
2316
+ "xmlns"
2317
+ ]);
2318
+ var RESOURCE_ATTRIBUTES = /* @__PURE__ */ new Set(["src", "poster", "data", "background", "manifest", "ping"]);
2319
+ var cleanUrlAttribute = (name, value) => {
2320
+ if (name === "srcset" || name === "imagesrcset") {
2321
+ const parts = value.split(",").map((part) => part.trim());
2322
+ const clean = [];
2323
+ for (const part of parts) {
2324
+ const [url, descriptor, extra] = part.split(/\s+/);
2325
+ if (extra !== void 0 || descriptor && !/^\d+(?:\.\d+)?[wx]$/.test(descriptor)) return "";
2326
+ const safe = sanitizeUrl(url, { schemes: ["http", "https"] });
2327
+ if (!safe) return "";
2328
+ clean.push(descriptor ? `${safe} ${descriptor}` : safe);
2329
+ }
2330
+ return clean.join(", ");
2331
+ }
2332
+ return sanitizeUrl(value, { schemes: RESOURCE_ATTRIBUTES.has(name) ? ["http", "https"] : LINK_SCHEMES });
2333
+ };
2334
+ var MAX_OVERRIDE_DEPTH = 64;
2335
+ var MAX_OVERRIDE_NODES = 5e4;
2336
+ var cleanOverrideNodes = (input, trusted) => {
2337
+ let budget = MAX_OVERRIDE_NODES;
2338
+ const visit = (value, depth) => {
2339
+ const list = Array.isArray(value) ? value.flat(Infinity) : [value];
2340
+ const out = [];
2341
+ for (const node of list) {
2342
+ if (budget <= 0 || depth > MAX_OVERRIDE_DEPTH) break;
2343
+ if (typeof node === "string" || typeof node === "number") {
2344
+ if (node !== "") out.push(textNode(node));
2345
+ continue;
2346
+ }
2347
+ if (!isPlainObject2(node)) continue;
2348
+ if (trusted.has(node)) {
2349
+ out.push(node);
2350
+ continue;
2351
+ }
2352
+ budget -= 1;
2353
+ if (node.type === "text") {
2354
+ out.push(textNode(typeof node.value === "string" ? node.value : ""));
2355
+ continue;
2356
+ }
2357
+ if (node.type !== "element" || typeof node.tag !== "string") continue;
2358
+ const tag = node.tag;
2359
+ if (!TAG_NAME.test(tag) || DENIED_TAGS.has(tag)) continue;
2360
+ const attrs = {};
2361
+ for (const [name, raw] of Object.entries(isPlainObject2(node.attrs) ? node.attrs : {})) {
2362
+ if (!isSafeAttributeName(name)) continue;
2363
+ if (raw === true) {
2364
+ if (!URL_ATTRIBUTES.has(name)) attrs[name] = true;
2365
+ continue;
2366
+ }
2367
+ if (!["string", "number"].includes(typeof raw)) continue;
2368
+ const text = String(raw).slice(0, 1e4);
2369
+ if (URL_ATTRIBUTES.has(name) || name === "srcset" || name === "imagesrcset") {
2370
+ const url = cleanUrlAttribute(name, text);
2371
+ if (url) attrs[name] = url;
2372
+ } else if (text !== "" || name === "alt") attrs[name] = text;
2373
+ }
2374
+ if (tag === "iframe" && !attrs.src) continue;
2375
+ out.push({
2376
+ type: "element",
2377
+ tag,
2378
+ attrs,
2379
+ children: visit(Array.isArray(node.children) ? node.children : [], depth + 1)
2380
+ });
2381
+ }
2382
+ return out;
2383
+ };
2384
+ return visit(input, 0);
2385
+ };
2386
+ var rawAllowed = (options) => options.rawHtml === "allow" && typeof options.sanitizeRaw === "function";
2387
+ var createTreeBuilder = (value, options, mode = {}) => {
1105
2388
  const opts = options && typeof options === "object" ? options : {};
1106
- const render = (blocks) => blocks.map((block) => {
2389
+ const publicOf = /* @__PURE__ */ new WeakMap();
2390
+ const preparedOf = /* @__PURE__ */ new WeakMap();
2391
+ const trusted = /* @__PURE__ */ new WeakSet();
2392
+ const toPublic = (block) => {
2393
+ const known = publicOf.get(block);
2394
+ if (known) return known;
2395
+ const pub = {
2396
+ id: block.id,
2397
+ type: block.type,
2398
+ data: block.data,
2399
+ tunes: block.tunes,
2400
+ children: block.children.map(toPublic)
2401
+ };
2402
+ publicOf.set(block, pub);
2403
+ preparedOf.set(pub, block);
2404
+ return pub;
2405
+ };
2406
+ const blockContent = (block) => {
1107
2407
  const override = overrideFor(opts, block.type);
1108
2408
  if (override) {
1109
- const out = override(
1110
- {
1111
- id: block.id,
1112
- type: block.type,
1113
- data: block.data,
1114
- tunes: block.tunes,
1115
- children: block.children
1116
- },
1117
- helpersFor(opts, render)
1118
- );
1119
- if (typeof out === "string") return out;
2409
+ const out = override(toPublic(block), helpers);
2410
+ if (typeof out === "string") {
2411
+ if (mode.overrideHtml) return out ? [{ type: "raw", html: out }] : [];
2412
+ if (rawAllowed(opts)) {
2413
+ const html = opts.sanitizeRaw(out);
2414
+ return typeof html === "string" && html ? [el("div", { class: "mex-override", "data-mex-block": block.type }, { type: "raw", html })] : [];
2415
+ }
2416
+ } else if (out && typeof out === "object") {
2417
+ return cleanOverrideNodes(out, trusted);
2418
+ }
2419
+ }
2420
+ if (block.known) return toNodes(RENDERERS[block.type](block, opts, renderList));
2421
+ if (block.definition) return registeredContent(block);
2422
+ return [neutral(block)];
2423
+ };
2424
+ const registeredContent = (block) => {
2425
+ const render = block.definition.render;
2426
+ if (render) {
2427
+ let out;
2428
+ try {
2429
+ out = render(toPublic(block), helpers);
2430
+ } catch {
2431
+ out = void 0;
2432
+ }
2433
+ if (typeof out === "string") {
2434
+ if (rawAllowed(opts)) {
2435
+ const html = opts.sanitizeRaw(out);
2436
+ if (typeof html === "string" && html)
2437
+ return [
2438
+ el("div", { class: "mex-override", "data-mex-block": block.type }, { type: "raw", html })
2439
+ ];
2440
+ }
2441
+ } else if (out && typeof out === "object") {
2442
+ return cleanOverrideNodes(out, trusted);
2443
+ }
1120
2444
  }
1121
- if (block.known) return RENDERERS[block.type](block, opts, render);
1122
- return neutral(block);
1123
- }).filter(Boolean).join("\n");
1124
- return render(prepareBlocks(value, opts));
2445
+ return [registeredDefault(block, opts)];
2446
+ };
2447
+ function renderList(blocks) {
2448
+ const out = [];
2449
+ for (const block of blocks) {
2450
+ const children = blockContent(block);
2451
+ if (!children.length) continue;
2452
+ const node = { type: "block", block: toPublic(block), children };
2453
+ trusted.add(node);
2454
+ if (out.length) out.push(textNode("\n"));
2455
+ out.push(node);
2456
+ }
2457
+ return out;
2458
+ }
2459
+ const renderBlocks = (blocks) => renderList((Array.isArray(blocks) ? blocks : []).map((b) => preparedOf.get(b)).filter(Boolean));
2460
+ const helpers = {
2461
+ escape: escapeHtml,
2462
+ inline: (html) => inlineToHtml(html, opts),
2463
+ text: (html) => inlineToText(html),
2464
+ url: (input, schemes) => sanitizeUrl(input, schemes ? { schemes } : void 0),
2465
+ renderChildren: (blocks) => serializeNodes(renderBlocks(blocks)),
2466
+ h: (tag, attrs, children) => el(String(tag), attrs, children),
2467
+ textNode,
2468
+ inlineNodes: (html) => inlineToNodes(html, opts),
2469
+ childNodes: renderBlocks
2470
+ };
2471
+ const nodes = renderList(annotateHeadings(prepareBlocks(value, opts), opts));
2472
+ return { nodes, renderBlocks, helpers };
1125
2473
  };
2474
+ var flattenBlocks = (nodes) => {
2475
+ const out = [];
2476
+ for (const node of nodes) {
2477
+ if (node.type === "block") out.push(...flattenBlocks(node.children));
2478
+ else if (node.type === "element") {
2479
+ const element = {
2480
+ type: "element",
2481
+ tag: node.tag,
2482
+ attrs: node.attrs,
2483
+ children: flattenBlocks(node.children)
2484
+ };
2485
+ if (node.style) element.style = node.style;
2486
+ out.push(element);
2487
+ } else out.push(node);
2488
+ }
2489
+ return out;
2490
+ };
2491
+ var renderTree = (value, options) => flattenBlocks(createTreeBuilder(value, options).nodes);
2492
+
2493
+ // shared/render/html.mjs
2494
+ var renderHtml = (value, options = {}) => serializeNodes(createTreeBuilder(value, options, { overrideHtml: true }).nodes);
1126
2495
 
1127
2496
  // shared/render/text.mjs
2497
+ var tocLines = (nodes, ordered, depth) => nodes.flatMap((node, index) => [
2498
+ `${" ".repeat(depth)}${ordered ? `${index + 1}.` : "-"} ${node.text}`,
2499
+ ...tocLines(node.children, ordered, depth + 1)
2500
+ ]);
1128
2501
  var listLines = (items, style, start, depth) => {
1129
2502
  const lines = [];
1130
2503
  items.forEach((item, index) => {
@@ -1142,6 +2515,11 @@ ${indent} `);
1142
2515
  return lines;
1143
2516
  };
1144
2517
  var t = (html) => inlineToText(html).trim();
2518
+ var mediaText = (b) => {
2519
+ if (!b.data.file.url) return "";
2520
+ const parts = [b.data.title.trim(), t(b.data.caption)].filter(Boolean);
2521
+ return parts.length ? parts.join("\n") : b.data.file.url;
2522
+ };
1145
2523
  var RENDERERS2 = {
1146
2524
  paragraph: (b) => t(b.data.text),
1147
2525
  header: (b) => t(b.data.text),
@@ -1162,12 +2540,36 @@ var RENDERERS2 = {
1162
2540
  table: (b) => b.data.content.map((row) => row.map((cell2) => t(cell2).replace(/\s+/g, " ")).join(" ")).join("\n"),
1163
2541
  image: (b) => t(b.data.caption) || (b.raw.decorative === true ? "" : (b.data.file.alt || "").trim()),
1164
2542
  simpleImage: (b) => t(b.data.caption),
2543
+ gallery: (b) => [
2544
+ ...b.data.images.map(
2545
+ (image) => image.file.url ? t(image.caption) || (image.decorative ? "" : (image.file.alt || "").trim()) : ""
2546
+ ),
2547
+ t(b.data.caption)
2548
+ ].filter(Boolean).join("\n"),
2549
+ video: (b) => mediaText(b),
2550
+ audio: (b) => mediaText(b),
1165
2551
  linkTool: (b) => [b.data.meta.title, b.data.link].filter(Boolean).join("\n"),
1166
2552
  attaches: (b) => b.data.file.url ? b.data.title || b.data.file.title || b.data.file.name || b.data.file.url : "",
1167
2553
  embed: (b) => [t(b.data.caption), b.data.source || b.data.embed].filter(Boolean).join("\n"),
1168
2554
  personality: (b) => [b.data.name, b.data.description, b.data.link].filter(Boolean).join("\n"),
1169
2555
  button: (b) => b.data.link ? `${b.data.text} (${b.data.link})` : b.data.text,
1170
- delimiter: () => "---"
2556
+ delimiter: () => "---",
2557
+ toc: (b) => {
2558
+ const tree = buildTocTree(b.headings || [], b.data);
2559
+ if (!tree.length) return "";
2560
+ return [b.data.title.trim(), ...tocLines(tree, b.data.style === "ordered", 0)].filter(Boolean).join("\n");
2561
+ }
2562
+ };
2563
+ var registeredText = (block) => {
2564
+ const { definition } = block;
2565
+ if (definition.text) {
2566
+ try {
2567
+ const out = definition.text(block.data, { text: (html) => inlineToText(html) });
2568
+ if (typeof out === "string") return out;
2569
+ } catch {
2570
+ }
2571
+ }
2572
+ return definition.fields(block.data).map((field) => (field.kind === "html" ? inlineToText(field.value) : field.value).trim()).filter(Boolean).join("\n");
1171
2573
  };
1172
2574
  var renderText = (value, options = {}) => {
1173
2575
  const opts = options && typeof options === "object" ? options : {};
@@ -1187,9 +2589,10 @@ var renderText = (value, options = {}) => {
1187
2589
  if (typeof out === "string") return out;
1188
2590
  }
1189
2591
  if (block.known) return RENDERERS2[block.type](block, opts, render);
2592
+ if (block.definition) return registeredText(block);
1190
2593
  return scalarFields(block.data).map(([, v]) => inlineToText(v).trim()).filter(Boolean).join("\n");
1191
2594
  }).map((text) => String(text).replace(/\u00a0/g, " ")).filter((text) => text.trim() !== "").join("\n\n");
1192
- return render(prepareBlocks(value, opts));
2595
+ return render(annotateHeadings(prepareBlocks(value, opts), opts));
1193
2596
  };
1194
2597
 
1195
2598
  // shared/render/markdown.mjs
@@ -1339,6 +2742,19 @@ var RENDERERS3 = {
1339
2742
  const alt = b.data.decorative === true ? "" : escapeMarkdown(oneLine(text));
1340
2743
  return `![${alt}](${linkUrl(b.data.url)})`;
1341
2744
  },
2745
+ gallery: (b, o) => {
2746
+ const lines = b.data.images.map((image) => {
2747
+ const file = resolveMedia(image.file, b, o);
2748
+ if (!file.url) return "";
2749
+ const alt = image.decorative ? "" : escapeMarkdown(oneLine(file.alt || ""));
2750
+ return `![${alt}](${linkUrl(file.url)}${linkTitle(inlineToText(image.caption))})`;
2751
+ }).filter(Boolean);
2752
+ if (!lines.length) return "";
2753
+ const caption = oneLine(md(b.data.caption, o));
2754
+ return [lines.join("\n"), caption].filter(Boolean).join("\n\n");
2755
+ },
2756
+ video: (b, o) => mediaLink("video", b, o),
2757
+ audio: (b, o) => mediaLink("audio", b, o),
1342
2758
  linkTool: (b) => b.data.link ? `[${escapeMarkdown(b.data.meta.title || b.data.link)}](${linkUrl(b.data.link)})` : "",
1343
2759
  attaches: (b) => {
1344
2760
  const file = b.data.file;
@@ -1362,7 +2778,45 @@ var RENDERERS3 = {
1362
2778
  if (!b.data.text) return "";
1363
2779
  return b.data.link ? `[${escapeMarkdown(b.data.text)}](${linkUrl(b.data.link)})` : escapeMarkdown(b.data.text);
1364
2780
  },
1365
- delimiter: () => "---"
2781
+ delimiter: () => "---",
2782
+ toc: (b) => {
2783
+ const tree = buildTocTree(b.headings || [], b.data);
2784
+ if (!tree.length) return "";
2785
+ const ordered = b.data.style === "ordered";
2786
+ const lines = (nodes, indent) => nodes.flatMap((node, index) => {
2787
+ const marker = ordered ? `${index + 1}.` : "-";
2788
+ const text = escapeMarkdown(node.text);
2789
+ const entry = b.linkHeadings && node.slug ? `[${text}](#${linkUrl(node.slug)})` : text;
2790
+ return [
2791
+ `${indent}${marker} ${entry}`,
2792
+ ...lines(node.children, `${indent}${" ".repeat(marker.length + 1)}`)
2793
+ ];
2794
+ });
2795
+ const title = b.data.title.trim();
2796
+ return [title ? `**${escapeMarkdown(title)}**` : "", lines(tree, "").join("\n")].filter(Boolean).join("\n\n");
2797
+ }
2798
+ };
2799
+ function mediaLink(kind, b, o) {
2800
+ const file = resolveMedia(b.data.file, b, o, { mimePrefix: `${kind}/` });
2801
+ if (!file.url) return "";
2802
+ const caption = oneLine(md(b.data.caption, o));
2803
+ const link = `[${escapeMarkdown(oneLine(b.data.title || file.name || file.url))}](${linkUrl(file.url)})`;
2804
+ return [link, caption].filter(Boolean).join("\n\n");
2805
+ }
2806
+ var registeredMarkdown = (block, opts) => {
2807
+ const { definition } = block;
2808
+ if (definition.markdown) {
2809
+ try {
2810
+ const out = definition.markdown(block.data, {
2811
+ escape: escapeMarkdown,
2812
+ inline: (html) => md(html, opts),
2813
+ text: (html) => inlineToText(html)
2814
+ });
2815
+ if (typeof out === "string") return out;
2816
+ } catch {
2817
+ }
2818
+ }
2819
+ return definition.fields(block.data).map((field) => field.kind === "html" ? md(field.value, opts) : escapeMarkdown(field.value.trim())).filter(Boolean).join("\n\n");
1366
2820
  };
1367
2821
  var renderMarkdown = (value, options = {}) => {
1368
2822
  const opts = options && typeof options === "object" ? options : {};
@@ -1382,17 +2836,61 @@ var renderMarkdown = (value, options = {}) => {
1382
2836
  if (typeof out === "string") return out;
1383
2837
  }
1384
2838
  if (block.known) return RENDERERS3[block.type](block, opts, render);
2839
+ if (block.definition) return registeredMarkdown(block, opts);
1385
2840
  return scalarFields(block.data).map(([, v]) => md(v, opts)).filter(Boolean).join("\n\n");
1386
2841
  }).filter((text) => text && text.trim() !== "").join("\n\n");
1387
- return render(prepareBlocks(value, opts));
2842
+ return render(annotateHeadings(prepareBlocks(value, opts), opts));
2843
+ };
2844
+
2845
+ // shared/render/dom.mjs
2846
+ var copyText = async (text) => {
2847
+ try {
2848
+ if (typeof navigator === "undefined" || !navigator.clipboard || !navigator.clipboard.writeText)
2849
+ return false;
2850
+ await navigator.clipboard.writeText(text);
2851
+ return true;
2852
+ } catch {
2853
+ return false;
2854
+ }
2855
+ };
2856
+ var enhanceCodeBlocks = (root) => {
2857
+ const scope = root || (typeof document === "undefined" ? null : document);
2858
+ if (!scope || typeof scope.querySelectorAll !== "function") return () => {
2859
+ };
2860
+ const cleanups = [];
2861
+ for (const button of scope.querySelectorAll('[data-mex-code="copy"] button[data-mex-copy]')) {
2862
+ if (button.hasAttribute("data-mex-enhanced")) continue;
2863
+ const block = button.closest('[data-mex-code="copy"]');
2864
+ const code = block && block.querySelector("pre code");
2865
+ const status = block && block.querySelector('[role="status"]');
2866
+ if (!code) continue;
2867
+ const onClick = async () => {
2868
+ const ok = await copyText(code.textContent || "");
2869
+ if (status)
2870
+ status.textContent = ok ? button.getAttribute("data-mex-copied") || "Copied" : button.getAttribute("data-mex-failed") || "Copy failed";
2871
+ };
2872
+ button.addEventListener("click", onClick);
2873
+ button.setAttribute("data-mex-enhanced", "");
2874
+ cleanups.push(() => {
2875
+ button.removeEventListener("click", onClick);
2876
+ button.removeAttribute("data-mex-enhanced");
2877
+ });
2878
+ }
2879
+ return () => {
2880
+ for (const cleanup of cleanups) cleanup();
2881
+ };
1388
2882
  };
1389
2883
  export {
1390
2884
  DEFAULT_EMBED_HOSTS,
1391
- escapeHtml2 as escapeHtml,
2885
+ copyText,
2886
+ enhanceCodeBlocks,
2887
+ escapeHtml,
1392
2888
  escapeMarkdown,
1393
2889
  inlineToHtml,
1394
2890
  inlineToText,
1395
2891
  renderHtml,
1396
2892
  renderMarkdown,
1397
- renderText
2893
+ renderText,
2894
+ renderTree,
2895
+ serializeNodes
1398
2896
  };