magic-editor-x 2.2.0 → 2.3.1

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 +85 -0
  2. package/README.md +493 -168
  3. package/dist/admin/{ConfigurationPage-YvnPnna6.js → ConfigurationPage-CFP3lp9p.js} +479 -50
  4. package/dist/admin/{ConfigurationPage-3Dir3dAf.mjs → ConfigurationPage-CYGDLjM7.mjs} +450 -21
  5. package/dist/admin/ConfirmAction-DuQwvRYi.mjs +125 -0
  6. package/dist/admin/ConfirmAction-zLuIFj8t.js +124 -0
  7. package/dist/admin/{CustomBlocksPage-CR2BaP9O.mjs → CustomBlocksPage-B5Q33N-s.mjs} +92 -41
  8. package/dist/admin/{CustomBlocksPage-BiiL2ORG.js → CustomBlocksPage-DzPOSpfn.js} +135 -84
  9. package/dist/admin/DraftSync-BIA8cZgA.js +11 -0
  10. package/dist/admin/DraftSync-CUxOMG-E.mjs +12 -0
  11. package/dist/admin/TemplatesPage-4A8JNO_Z.mjs +993 -0
  12. package/dist/admin/TemplatesPage-BVkgafCK.js +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/{EditorField-Diq1j8kc.js → index-DQVE0ymw.js} +13712 -6767
  46. package/dist/admin/index-DR8sHkTk.js +1940 -0
  47. package/dist/admin/index-My6FjjHB.mjs +1939 -0
  48. package/dist/admin/{EditorField-B8pyAxPE.mjs → index-k8_a5o1A.mjs} +10223 -3278
  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-Cmg1jwwG.mjs +65 -0
  62. package/dist/admin/{useT-BWZ_-Hel.js → useT-DNphiBQR.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
@@ -20,16 +20,135 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  var index_exports = {};
21
21
  __export(index_exports, {
22
22
  DEFAULT_EMBED_HOSTS: () => DEFAULT_EMBED_HOSTS,
23
- escapeHtml: () => escapeHtml2,
23
+ copyText: () => copyText,
24
+ enhanceCodeBlocks: () => enhanceCodeBlocks,
25
+ escapeHtml: () => escapeHtml,
24
26
  escapeMarkdown: () => escapeMarkdown,
25
27
  inlineToHtml: () => inlineToHtml,
26
28
  inlineToText: () => inlineToText,
27
29
  renderHtml: () => renderHtml,
28
30
  renderMarkdown: () => renderMarkdown,
29
- renderText: () => renderText
31
+ renderText: () => renderText,
32
+ renderTree: () => renderTree,
33
+ serializeNodes: () => serializeNodes
30
34
  });
31
35
  module.exports = __toCommonJS(index_exports);
32
36
 
37
+ // shared/render/nodes.mjs
38
+ var VOID_TAGS = /* @__PURE__ */ new Set([
39
+ "area",
40
+ "base",
41
+ "br",
42
+ "col",
43
+ "embed",
44
+ "hr",
45
+ "img",
46
+ "input",
47
+ "link",
48
+ "meta",
49
+ "source",
50
+ "track",
51
+ "wbr"
52
+ ]);
53
+ var escapeHtml = (text) => String(text ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
54
+ var TAG_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
55
+ var ATTRIBUTE_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
56
+ var isSafeAttributeName = (name) => ATTRIBUTE_NAME.test(name) && !name.startsWith("on") && name !== "style" && name !== "srcdoc";
57
+ var textNode = (value) => ({ type: "text", value: String(value ?? "") });
58
+ var el = (tag, attrs, children) => {
59
+ const clean = {};
60
+ for (const [name, value] of Object.entries(attrs || {})) {
61
+ if (value === void 0 || value === null || value === false) continue;
62
+ if (value === "" && name !== "alt") continue;
63
+ clean[name] = value === true ? true : String(value);
64
+ }
65
+ return { type: "element", tag, attrs: clean, children: toNodes(children) };
66
+ };
67
+ var toNodes = (children) => {
68
+ const out = [];
69
+ const visit = (child) => {
70
+ if (child === void 0 || child === null || child === false || child === "") return;
71
+ if (Array.isArray(child)) {
72
+ for (const item of child) visit(item);
73
+ } else if (typeof child === "string" || typeof child === "number") {
74
+ out.push(textNode(child));
75
+ } else if (typeof child === "object") {
76
+ out.push(
77
+ /** @type {RenderNode} */
78
+ child
79
+ );
80
+ }
81
+ };
82
+ visit(children);
83
+ return out;
84
+ };
85
+ var STYLE_PROPERTIES = Object.freeze(["object-position"]);
86
+ var STYLE_VALUE = /^[0-9]{1,3}(?:\.[0-9]{1,2})?% [0-9]{1,3}(?:\.[0-9]{1,2})?%$/;
87
+ var safeStyle = (style) => style && typeof style === "object" ? Object.entries(style).filter(
88
+ ([name, value]) => STYLE_PROPERTIES.includes(name) && typeof value === "string" && STYLE_VALUE.test(value)
89
+ ) : [];
90
+ var serializeNodes = (nodes) => {
91
+ let out = "";
92
+ for (const node of nodes) {
93
+ if (!node || typeof node !== "object") continue;
94
+ if (node.type === "text") out += escapeHtml(node.value);
95
+ else if (node.type === "raw") out += node.html;
96
+ else if (node.type === "block") out += serializeNodes(node.children);
97
+ else if (node.type === "element") {
98
+ let attributes = "";
99
+ for (const [name, value] of Object.entries(node.attrs)) {
100
+ attributes += value === true ? ` ${name}` : ` ${name}="${escapeHtml(value)}"`;
101
+ }
102
+ const style = safeStyle(node.style);
103
+ if (style.length)
104
+ attributes += ` style="${escapeHtml(style.map(([name, value]) => `${name}:${value}`).join(";"))}"`;
105
+ out += VOID_TAGS.has(node.tag) ? `<${node.tag}${attributes}>` : `<${node.tag}${attributes}>${serializeNodes(node.children)}</${node.tag}>`;
106
+ }
107
+ }
108
+ return out;
109
+ };
110
+
111
+ // shared/blocks/active.mjs
112
+ var registry = /* @__PURE__ */ new Map();
113
+ var activeBlock = (type) => typeof type === "string" && registry.has(type) ? registry.get(type) : null;
114
+
115
+ // shared/built-in-marker.mjs
116
+ var isPlainObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
117
+ var BUILT_IN_MARKER = "_mex";
118
+ var BUILT_IN_MARKER_VERSION = 1;
119
+ var MARKED_BLOCKS = Object.freeze({
120
+ toc: Object.freeze({ keys: Object.freeze(["title", "minLevel", "maxLevel", "style"]), anchor: null }),
121
+ gallery: Object.freeze({
122
+ keys: Object.freeze(["images", "layout", "columns", "caption"]),
123
+ anchor: Object.freeze(["images", "array"])
124
+ }),
125
+ video: Object.freeze({
126
+ keys: Object.freeze(["file", "poster", "title", "caption", "loop", "muted", "tracks"]),
127
+ anchor: Object.freeze(["file", "object"])
128
+ }),
129
+ audio: Object.freeze({
130
+ keys: Object.freeze(["file", "title", "caption", "loop", "tracks"]),
131
+ anchor: Object.freeze(["file", "object"])
132
+ }),
133
+ synced: Object.freeze({ keys: Object.freeze(["ref"]), anchor: Object.freeze(["ref", "string"]) })
134
+ });
135
+ var isBuiltInMarker = (value) => Number.isInteger(value) && /** @type {number} */
136
+ value >= 1;
137
+ var hasBuiltInShape = (shape, data) => {
138
+ if (!Object.keys(data).every((key2) => shape.keys.includes(key2))) return false;
139
+ if (!shape.anchor) return true;
140
+ const [key, kind] = shape.anchor;
141
+ const value = data[key];
142
+ if (kind === "array") return Array.isArray(value);
143
+ if (kind === "object") return isPlainObject(value);
144
+ return typeof value === kind;
145
+ };
146
+ var isMarkedBuiltIn = (type, data) => {
147
+ if (!Object.prototype.hasOwnProperty.call(MARKED_BLOCKS, type) || !isPlainObject(data)) return false;
148
+ if (isBuiltInMarker(data[BUILT_IN_MARKER])) return true;
149
+ return hasBuiltInShape(MARKED_BLOCKS[type], data);
150
+ };
151
+
33
152
  // shared/editor-data.mjs
34
153
  var EDITOR_DATA_LIMITS = Object.freeze({
35
154
  maxBlocks: 5e3,
@@ -41,7 +160,7 @@ var EDITOR_DATA_LIMITS = Object.freeze({
41
160
  var FORBIDDEN_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
42
161
  var BLOCK_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
43
162
  var BLOCK_TYPE_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
44
- var isPlainObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
163
+ var isPlainObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
45
164
  var EditorDataError = class extends Error {
46
165
  /**
47
166
  * @param {string} message - Fixed, non-sensitive message.
@@ -92,7 +211,7 @@ var tryParseJson = (text) => {
92
211
  return { ok: false };
93
212
  }
94
213
  };
95
- var escapeHtml = (text) => String(text).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
214
+ var escapeHtml2 = (text) => String(text).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
96
215
  var hashString = (text) => {
97
216
  let hash = 2166136261;
98
217
  for (let i = 0; i < text.length; i += 1) {
@@ -109,7 +228,7 @@ var textToBlocks = (text) => {
109
228
  if (looksLikeHtml) {
110
229
  return [{ type: "paragraph", data: { text: trimmed } }];
111
230
  }
112
- 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>") } }));
231
+ 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>") } }));
113
232
  };
114
233
  var unwrapValue = (value) => {
115
234
  let current = value;
@@ -139,7 +258,7 @@ var normalizeEditorData = (value) => {
139
258
  }
140
259
  const { candidate } = unwrapValue(value);
141
260
  if (candidate === null || candidate === void 0) return null;
142
- if (!isPlainObject(candidate)) {
261
+ if (!isPlainObject2(candidate)) {
143
262
  throw new EditorDataError("Editor content must be an Editor.js object", "INVALID_SHAPE");
144
263
  }
145
264
  const clean = cloneJsonSafe(candidate);
@@ -150,16 +269,16 @@ var normalizeEditorData = (value) => {
150
269
  const seen = /* @__PURE__ */ new Set();
151
270
  const blocks = [];
152
271
  rawBlocks.forEach((block, index) => {
153
- if (!isPlainObject(block)) return;
272
+ if (!isPlainObject2(block)) return;
154
273
  const type = typeof block.type === "string" ? block.type.trim() : "";
155
274
  if (!BLOCK_TYPE_PATTERN.test(type)) return;
156
- const data = isPlainObject(block.data) ? block.data : {};
275
+ const data = isPlainObject2(block.data) ? block.data : {};
157
276
  let id = typeof block.id === "string" && BLOCK_ID_PATTERN.test(block.id) ? block.id : "";
158
277
  if (!id || seen.has(id)) id = legacyBlockId(index, type, data);
159
278
  while (seen.has(id)) id = `${id}x`;
160
279
  seen.add(id);
161
280
  const normalized = { id, type, data };
162
- if (isPlainObject(block.tunes) && Object.keys(block.tunes).length > 0) normalized.tunes = block.tunes;
281
+ if (isPlainObject2(block.tunes) && Object.keys(block.tunes).length > 0) normalized.tunes = block.tunes;
163
282
  blocks.push(normalized);
164
283
  });
165
284
  const time = Number.isFinite(clean.time) && clean.time > 0 ? Math.floor(clean.time) : 0;
@@ -211,12 +330,15 @@ var INLINE_TAGS = Object.freeze([
211
330
  var INTERNAL_LINK_ATTRIBUTES = Object.freeze([
212
331
  "data-mex-uid",
213
332
  "data-mex-document-id",
214
- "data-mex-locale"
333
+ "data-mex-locale",
334
+ "data-mex-mention"
215
335
  ]);
216
336
  var INTERNAL_LINK_RULES = Object.freeze({
217
337
  "data-mex-uid": /^api::[a-z0-9-]{1,60}\.[a-z0-9-]{1,60}$/,
218
338
  "data-mex-document-id": /^[a-z0-9]{1,64}$/,
219
- "data-mex-locale": /^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8}){0,3}$/
339
+ "data-mex-locale": /^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8}){0,3}$/,
340
+ // Boolean flag: written as "true"; an empty value (`<a data-mex-mention>`) is accepted and normalised.
341
+ "data-mex-mention": /^(?:|true)$/
220
342
  });
221
343
  var cleanInternalLinkAttributes = (attribs) => {
222
344
  const out = {};
@@ -226,8 +348,12 @@ var cleanInternalLinkAttributes = (attribs) => {
226
348
  if (typeof value === "string" && INTERNAL_LINK_RULES[name].test(value)) out[name] = value;
227
349
  }
228
350
  if (!out["data-mex-uid"] || !out["data-mex-document-id"]) return {};
351
+ if (out["data-mex-mention"] !== void 0) out["data-mex-mention"] = "true";
229
352
  return out;
230
353
  };
354
+ var isMentionLink = (attrs) => Boolean(
355
+ attrs && attrs["data-mex-mention"] === "true" && attrs["data-mex-uid"] && attrs["data-mex-document-id"]
356
+ );
231
357
  var INLINE_ATTRIBUTES = Object.freeze({
232
358
  a: ["href", "target", "rel", "title", ...INTERNAL_LINK_ATTRIBUTES],
233
359
  span: ["class", "data-tooltip"],
@@ -276,6 +402,57 @@ var int = (value, min, max, fallback) => {
276
402
  return Number.isInteger(number) && number >= min && number <= max ? number : fallback;
277
403
  };
278
404
  var bool = (value) => value === true;
405
+ var MAX_GALLERY_IMAGES = 50;
406
+ var MAX_MEDIA_TRACKS = 8;
407
+ var TRACK_KINDS = Object.freeze(["captions", "subtitles", "descriptions", "chapters"]);
408
+ var SRCLANG = /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{1,8}){0,3}$/;
409
+ var cleanFocalPoint = (value) => {
410
+ if (!isPlainObject2(value)) return void 0;
411
+ const { x, y } = value;
412
+ if (![x, y].every((n) => typeof n === "number" && Number.isFinite(n) && n >= 0 && n <= 1)) return void 0;
413
+ return { x: Math.round(x * 100) / 100, y: Math.round(y * 100) / 100 };
414
+ };
415
+ var cleanMediaFile = (value, kind = {}) => {
416
+ const file = isPlainObject2(value) ? value : {};
417
+ const out = { url: sanitizeUrl(file.url, { schemes: ["http", "https"] }) };
418
+ for (const key of ["mime", ...kind.image ? ["alt"] : [], "name", "hash", "ext"])
419
+ if (typeof file[key] === "string") out[key] = plain(file[key], 500);
420
+ for (const key of ["width", "height", "size"]) if (Number.isFinite(file[key])) out[key] = file[key];
421
+ if (kind.image && isPlainObject2(file.formats))
422
+ out.formats = generic(file.formats, (s) => plain(s, 2048), 0, "formats");
423
+ if (file.id !== void 0 && (Number.isInteger(file.id) || typeof file.id === "string")) out.id = file.id;
424
+ if (typeof file.documentId === "string") out.documentId = plain(file.documentId, 64);
425
+ const mime = typeof out.mime === "string" ? out.mime.toLowerCase() : "";
426
+ if (kind.mimePrefix && mime && !mime.startsWith(kind.mimePrefix)) out.url = "";
427
+ if (kind.vtt && out.url) {
428
+ const path = out.url.split(/[?#]/)[0].toLowerCase();
429
+ const ext = typeof out.ext === "string" ? out.ext.toLowerCase() : "";
430
+ if (mime !== "text/vtt" && ext !== ".vtt" && !path.endsWith(".vtt")) out.url = "";
431
+ }
432
+ return out;
433
+ };
434
+ var mediaTracks = (tracks) => {
435
+ if (!Array.isArray(tracks)) return [];
436
+ const out = [];
437
+ let hasDefault = false;
438
+ for (const track of tracks.slice(0, MAX_MEDIA_TRACKS)) {
439
+ if (!isPlainObject2(track)) continue;
440
+ const file = cleanMediaFile(track.file, { vtt: true });
441
+ if (!file.url) continue;
442
+ const clean = {
443
+ file,
444
+ kind: oneOf(track.kind, TRACK_KINDS, "captions"),
445
+ srclang: typeof track.srclang === "string" && SRCLANG.test(track.srclang) ? track.srclang : "",
446
+ label: plain(track.label, 100)
447
+ };
448
+ if (track.default === true && !hasDefault) {
449
+ clean.default = true;
450
+ hasDefault = true;
451
+ }
452
+ out.push(clean);
453
+ }
454
+ return out;
455
+ };
279
456
  var generic = (value, inline, depth = 0, key = "") => {
280
457
  if (depth > 20) return null;
281
458
  if (typeof value === "string") {
@@ -283,7 +460,7 @@ var generic = (value, inline, depth = 0, key = "") => {
283
460
  return inline(value);
284
461
  }
285
462
  if (Array.isArray(value)) return value.map((item) => generic(item, inline, depth + 1, key));
286
- if (isPlainObject(value)) {
463
+ if (isPlainObject2(value)) {
287
464
  const out = {};
288
465
  for (const [childKey, child] of Object.entries(value))
289
466
  out[childKey] = generic(child, inline, depth + 1, childKey);
@@ -295,9 +472,9 @@ var listItems = (items, inline, depth = 0) => {
295
472
  if (!Array.isArray(items) || depth > 12) return [];
296
473
  return items.map((item) => {
297
474
  if (typeof item === "string") return inline(item);
298
- if (!isPlainObject(item)) return { content: "", items: [] };
475
+ if (!isPlainObject2(item)) return { content: "", items: [] };
299
476
  const out = { content: inline(typeof item.content === "string" ? item.content : plain(item.text)) };
300
- if (isPlainObject(item.meta)) {
477
+ if (isPlainObject2(item.meta)) {
301
478
  const meta = {};
302
479
  if (typeof item.meta.checked === "boolean") meta.checked = item.meta.checked;
303
480
  const start = int(item.meta.start, 0, 1e5, void 0);
@@ -328,7 +505,7 @@ var BLOCK_POLICIES = {
328
505
  style: oneOf(d.style, ["ordered", "unordered", "checklist"], "unordered"),
329
506
  items: listItems(d.items, inline)
330
507
  };
331
- if (isPlainObject(d.meta)) {
508
+ if (isPlainObject2(d.meta)) {
332
509
  const meta = {};
333
510
  const start = int(d.meta.start, 0, 1e5, void 0);
334
511
  if (start !== void 0) meta.start = start;
@@ -344,7 +521,7 @@ var BLOCK_POLICIES = {
344
521
  return out;
345
522
  },
346
523
  checklist: (d, inline) => ({
347
- items: Array.isArray(d.items) ? d.items.filter(isPlainObject).map((item) => ({ text: inline(item.text), checked: bool(item.checked) })) : []
524
+ items: Array.isArray(d.items) ? d.items.filter(isPlainObject2).map((item) => ({ text: inline(item.text), checked: bool(item.checked) })) : []
348
525
  }),
349
526
  warning: (d, inline) => ({ title: inline(d.title), message: inline(d.message) }),
350
527
  alert: (d, inline) => ({
@@ -383,12 +560,12 @@ var BLOCK_POLICIES = {
383
560
  content: Array.isArray(d.content) ? d.content.slice(0, 500).map((row) => Array.isArray(row) ? row.slice(0, 100).map((cell2) => inline(cell2)) : []) : []
384
561
  }),
385
562
  image: (d, inline) => {
386
- const file = isPlainObject(d.file) ? d.file : {};
563
+ const file = isPlainObject2(d.file) ? d.file : {};
387
564
  const cleanFile = { url: sanitizeUrl(file.url, { schemes: ["http", "https"] }) };
388
565
  for (const key of ["mime", "alt", "name", "hash", "ext"])
389
566
  if (typeof file[key] === "string") cleanFile[key] = plain(file[key], 500);
390
567
  for (const key of ["width", "height", "size"]) if (Number.isFinite(file[key])) cleanFile[key] = file[key];
391
- if (isPlainObject(file.formats))
568
+ if (isPlainObject2(file.formats))
392
569
  cleanFile.formats = generic(file.formats, (s) => plain(s, 2048), 0, "formats");
393
570
  if (file.id !== void 0 && (Number.isInteger(file.id) || typeof file.id === "string"))
394
571
  cleanFile.id = file.id;
@@ -401,6 +578,8 @@ var BLOCK_POLICIES = {
401
578
  stretched: bool(d.stretched)
402
579
  };
403
580
  if (d.decorative === true) out.decorative = true;
581
+ const focalPoint = cleanFocalPoint(d.focalPoint);
582
+ if (focalPoint) out.focalPoint = focalPoint;
404
583
  return out;
405
584
  },
406
585
  simpleImage: (d, inline) => {
@@ -415,16 +594,61 @@ var BLOCK_POLICIES = {
415
594
  if (d.decorative === true) out.decorative = true;
416
595
  return out;
417
596
  },
597
+ gallery: (d, inline) => {
598
+ const images = [];
599
+ for (const item of Array.isArray(d.images) ? d.images : []) {
600
+ if (images.length >= MAX_GALLERY_IMAGES) break;
601
+ if (!isPlainObject2(item)) continue;
602
+ const file = cleanMediaFile(item.file, { image: true, mimePrefix: "image/" });
603
+ if (!file.url) continue;
604
+ const image = { file, caption: inline(item.caption) };
605
+ if (item.decorative === true) image.decorative = true;
606
+ const focalPoint = cleanFocalPoint(item.focalPoint);
607
+ if (focalPoint) image.focalPoint = focalPoint;
608
+ images.push(image);
609
+ }
610
+ return {
611
+ images,
612
+ layout: oneOf(d.layout, ["grid", "carousel"], "grid"),
613
+ columns: int(d.columns, 1, 6, 3),
614
+ caption: inline(d.caption),
615
+ _mex: BUILT_IN_MARKER_VERSION
616
+ };
617
+ },
618
+ video: (d, inline) => {
619
+ const out = {
620
+ file: cleanMediaFile(d.file, { mimePrefix: "video/" }),
621
+ title: plain(d.title, 200),
622
+ caption: inline(d.caption),
623
+ loop: bool(d.loop),
624
+ muted: bool(d.muted),
625
+ tracks: mediaTracks(d.tracks)
626
+ };
627
+ if (isPlainObject2(d.poster)) {
628
+ const poster = cleanMediaFile(d.poster, { image: true, mimePrefix: "image/" });
629
+ if (poster.url) out.poster = poster;
630
+ }
631
+ out._mex = BUILT_IN_MARKER_VERSION;
632
+ return out;
633
+ },
634
+ audio: (d, inline) => ({
635
+ file: cleanMediaFile(d.file, { mimePrefix: "audio/" }),
636
+ title: plain(d.title, 200),
637
+ caption: inline(d.caption),
638
+ loop: bool(d.loop),
639
+ tracks: mediaTracks(d.tracks),
640
+ _mex: BUILT_IN_MARKER_VERSION
641
+ }),
418
642
  linkTool: (d) => {
419
- const meta = isPlainObject(d.meta) ? d.meta : {};
420
- const image = isPlainObject(meta.image) ? { url: sanitizeUrl(meta.image.url, { schemes: ["http", "https"] }) } : void 0;
643
+ const meta = isPlainObject2(d.meta) ? d.meta : {};
644
+ const image = isPlainObject2(meta.image) ? { url: sanitizeUrl(meta.image.url, { schemes: ["http", "https"] }) } : void 0;
421
645
  const cleanMeta = { title: plain(meta.title, 500), description: plain(meta.description, 2e3) };
422
646
  if (typeof meta.site_name === "string") cleanMeta.site_name = plain(meta.site_name, 200);
423
647
  if (image && image.url) cleanMeta.image = image;
424
648
  return { link: sanitizeUrl(d.link, { schemes: ["http", "https"] }), meta: cleanMeta };
425
649
  },
426
650
  attaches: (d) => {
427
- const file = isPlainObject(d.file) ? d.file : {};
651
+ const file = isPlainObject2(d.file) ? d.file : {};
428
652
  const cleanFile = { url: sanitizeUrl(file.url, { schemes: ["http", "https"] }) };
429
653
  if (typeof file.name === "string") cleanFile.name = plain(file.name, 255);
430
654
  if (typeof file.extension === "string") cleanFile.extension = plain(file.extension, 16);
@@ -452,12 +676,34 @@ var BLOCK_POLICIES = {
452
676
  style: oneOf(d.style, ["primary", "secondary", "outline", "ghost", "danger", "success"], "primary"),
453
677
  openInNewTab: bool(d.openInNewTab)
454
678
  }),
455
- delimiter: () => ({})
679
+ delimiter: () => ({}),
680
+ // Synced block (2.3): only the reference to its source is stored; an invalid reference becomes ''.
681
+ synced: (d) => ({
682
+ ref: typeof d.ref === "string" && /^[a-z0-9]{1,64}$/.test(d.ref) ? d.ref : "",
683
+ _mex: BUILT_IN_MARKER_VERSION
684
+ }),
685
+ toc: (d) => {
686
+ const minLevel = int(d.minLevel, 1, 6, 2);
687
+ const maxLevel = int(d.maxLevel, 1, 6, 4);
688
+ return {
689
+ title: plain(d.title, 200),
690
+ minLevel: Math.min(minLevel, maxLevel),
691
+ maxLevel: Math.max(minLevel, maxLevel),
692
+ style: oneOf(d.style, ["ordered", "unordered"], "unordered"),
693
+ _mex: BUILT_IN_MARKER_VERSION
694
+ };
695
+ }
696
+ };
697
+ var isBuiltInBlock = (block) => {
698
+ if (!block || typeof block.type !== "string") return false;
699
+ if (!Object.prototype.hasOwnProperty.call(BLOCK_POLICIES, block.type)) return false;
700
+ if (!Object.prototype.hasOwnProperty.call(MARKED_BLOCKS, block.type)) return true;
701
+ return isMarkedBuiltIn(block.type, block.data);
456
702
  };
457
703
  var sanitizeTunes = (tunes) => {
458
- if (!isPlainObject(tunes)) return void 0;
704
+ if (!isPlainObject2(tunes)) return void 0;
459
705
  const out = {};
460
- if (isPlainObject(tunes.alignmentTune)) {
706
+ if (isPlainObject2(tunes.alignmentTune)) {
461
707
  out.alignmentTune = {
462
708
  alignment: oneOf(tunes.alignmentTune.alignment, ["left", "center", "right", "justify"], "left")
463
709
  };
@@ -465,11 +711,16 @@ var sanitizeTunes = (tunes) => {
465
711
  if (typeof tunes.textVariant === "string") {
466
712
  out.textVariant = oneOf(tunes.textVariant, ["", "call-out", "citation", "details"], "");
467
713
  }
468
- if (isPlainObject(tunes.indentTune)) {
714
+ if (isPlainObject2(tunes.indentTune)) {
469
715
  out.indentTune = { indentLevel: int(tunes.indentTune.indentLevel, 0, 10, 0) };
470
716
  }
471
717
  return Object.keys(out).length ? out : void 0;
472
718
  };
719
+ var registeredBlockOf = (block, explicit) => {
720
+ if (!block || typeof block.type !== "string" || isBuiltInBlock(block)) return null;
721
+ if (explicit instanceof Map) return explicit.get(block.type) || null;
722
+ return activeBlock(block.type);
723
+ };
473
724
  var sanitizeTarget = (value) => typeof value === "string" && TARGETS.has(value) ? value : null;
474
725
 
475
726
  // shared/render/inline.mjs
@@ -542,7 +793,6 @@ var decodeEntities = (text) => String(text).replace(
542
793
  return named === void 0 ? match : named;
543
794
  }
544
795
  );
545
- var escapeHtml2 = (text) => String(text ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
546
796
  var parseAttributes = (source) => {
547
797
  const out = {};
548
798
  const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
@@ -694,7 +944,8 @@ var resolveLinkAttributes = (attrs, resolver) => {
694
944
  uid: attrs["data-mex-uid"],
695
945
  documentId: attrs["data-mex-document-id"],
696
946
  locale: attrs["data-mex-locale"] || null,
697
- href: attrs.href || null
947
+ href: attrs.href || null,
948
+ ...isMentionLink(attrs) ? { mention: true } : {}
698
949
  });
699
950
  } catch {
700
951
  result = void 0;
@@ -715,27 +966,53 @@ var ATTRIBUTE_ORDER = [
715
966
  "data-tooltip",
716
967
  "data-mex-uid",
717
968
  "data-mex-document-id",
718
- "data-mex-locale"
969
+ "data-mex-locale",
970
+ "data-mex-mention"
719
971
  ];
720
- var serializeAttributes = (attrs) => ATTRIBUTE_ORDER.filter((name) => attrs[name] !== void 0 && attrs[name] !== "").map((name) => ` ${name}="${escapeHtml2(attrs[name])}"`).join("");
721
- var nodesToHtml = (nodes, options = {}) => nodes.map((node) => {
722
- if (node.type === "text") return escapeHtml2(node.value);
723
- if (node.tag === "br") return "<br>";
724
- let attrs = node.attrs;
725
- if (node.tag === "a") {
726
- attrs = resolveLinkAttributes(attrs, options.links);
727
- if (!attrs || !attrs.href) return nodesToHtml(node.children, options);
728
- if (attrs.target === "_blank") {
729
- const rel = new Set(
730
- String(attrs.rel || "").split(/\s+/).filter(Boolean)
731
- );
732
- rel.add("noopener");
733
- rel.add("noreferrer");
734
- attrs = { ...attrs, rel: Array.from(rel).sort().join(" ") };
972
+ var MENTION_CLASS = "mex-mention";
973
+ var inlineNodesToRender = (nodes, options = {}) => {
974
+ const out = [];
975
+ for (const node of nodes) {
976
+ if (node.type === "text") {
977
+ out.push({ type: "text", value: node.value });
978
+ continue;
735
979
  }
980
+ if (node.tag === "br") {
981
+ out.push({ type: "element", tag: "br", attrs: {}, children: [] });
982
+ continue;
983
+ }
984
+ let attrs = node.attrs;
985
+ if (node.tag === "a") {
986
+ attrs = resolveLinkAttributes(attrs, options.links);
987
+ if (!attrs || !attrs.href) {
988
+ out.push(...inlineNodesToRender(node.children, options));
989
+ continue;
990
+ }
991
+ if (attrs.target === "_blank") {
992
+ const rel = new Set(
993
+ String(attrs.rel || "").split(/\s+/).filter(Boolean)
994
+ );
995
+ rel.add("noopener");
996
+ rel.add("noreferrer");
997
+ attrs = { ...attrs, rel: Array.from(rel).sort().join(" ") };
998
+ }
999
+ if (!options.storage && isMentionLink(attrs)) attrs = { ...attrs, class: MENTION_CLASS };
1000
+ }
1001
+ const ordered = {};
1002
+ for (const name of ATTRIBUTE_ORDER) {
1003
+ if (attrs[name] !== void 0 && attrs[name] !== "") ordered[name] = String(attrs[name]);
1004
+ }
1005
+ out.push({
1006
+ type: "element",
1007
+ tag: node.tag,
1008
+ attrs: ordered,
1009
+ children: inlineNodesToRender(node.children, options)
1010
+ });
736
1011
  }
737
- return `<${node.tag}${serializeAttributes(attrs)}>${nodesToHtml(node.children, options)}</${node.tag}>`;
738
- }).join("");
1012
+ return out;
1013
+ };
1014
+ var inlineToNodes = (html, options) => inlineNodesToRender(parseInline(html), options);
1015
+ var nodesToHtml = (nodes, options = {}) => serializeNodes(inlineNodesToRender(nodes, options));
739
1016
  var nodesToText = (nodes) => nodes.map((node) => {
740
1017
  if (node.type === "text") return node.value;
741
1018
  if (node.tag === "br") return "\n";
@@ -744,17 +1021,692 @@ var nodesToText = (nodes) => nodes.map((node) => {
744
1021
  var inlineToHtml = (html, options) => nodesToHtml(parseInline(html), options);
745
1022
  var inlineToText = (html) => nodesToText(parseInline(html)).replace(/\u00a0/g, " ");
746
1023
 
1024
+ // shared/blocks/define.mjs
1025
+ var BLOCK_FIELD_TYPES = Object.freeze([
1026
+ "text",
1027
+ "inline",
1028
+ "url",
1029
+ "enum",
1030
+ "number",
1031
+ "boolean",
1032
+ "array",
1033
+ "object"
1034
+ ]);
1035
+ var BLOCK_LIMITS = Object.freeze({
1036
+ /** Fields per object (also the schema root). */
1037
+ maxFields: 50,
1038
+ /** Nesting of arrays and objects below the root. */
1039
+ maxDepth: 4,
1040
+ /** Largest `max` of a text or inline field. */
1041
+ maxText: 1e5,
1042
+ /** Default `max` of a text field. */
1043
+ defaultText: 1e3,
1044
+ /** Default `max` of an inline HTML field. */
1045
+ defaultInline: 1e4,
1046
+ /** Largest `max` of an array field. */
1047
+ maxItems: 500,
1048
+ /** Default `max` of an array field. */
1049
+ defaultItems: 50,
1050
+ /** Values of an enum field. */
1051
+ maxEnumValues: 100,
1052
+ /** Values cleaned per block; later array items are dropped. */
1053
+ maxValues: 2e4,
1054
+ /** Length of a URL value. */
1055
+ maxUrl: 2048
1056
+ });
1057
+ var BLOCK_PRESETS = Object.freeze(["article", "basic", "minimal"]);
1058
+ var RESERVED_BLOCK_NAMES = Object.freeze([
1059
+ "paragraph",
1060
+ "header",
1061
+ "list",
1062
+ "checklist",
1063
+ "quote",
1064
+ "warning",
1065
+ "alert",
1066
+ "toggle",
1067
+ "code",
1068
+ "codeFlask",
1069
+ "delimiter",
1070
+ "toc",
1071
+ "synced",
1072
+ "table",
1073
+ "embed",
1074
+ "raw",
1075
+ "image",
1076
+ "simpleImage",
1077
+ "gallery",
1078
+ "video",
1079
+ "audio",
1080
+ "linkTool",
1081
+ "attaches",
1082
+ "personality",
1083
+ "button",
1084
+ "mediaLib",
1085
+ "embeddedEntry",
1086
+ "bold",
1087
+ "italic",
1088
+ "hyperlink",
1089
+ "mention",
1090
+ "marker",
1091
+ "underline",
1092
+ "strikethrough",
1093
+ "inlineCode",
1094
+ "tooltip",
1095
+ "aiAssistant",
1096
+ "alignmentTune",
1097
+ "textVariant",
1098
+ "indentTune"
1099
+ ]);
1100
+ var RESERVED = new Set(RESERVED_BLOCK_NAMES.map((name) => name.toLowerCase()));
1101
+ var BLOCK_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{1,49}$/;
1102
+ var KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
1103
+ var FORBIDDEN_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1104
+ var DEFINITION_KEYS = /* @__PURE__ */ new Set([
1105
+ "name",
1106
+ "version",
1107
+ "title",
1108
+ "description",
1109
+ "schema",
1110
+ "sanitize",
1111
+ "text",
1112
+ "markdown",
1113
+ "render",
1114
+ "presets"
1115
+ ]);
1116
+ var FIELD_KEYS = {
1117
+ text: ["max", "multiline", "default"],
1118
+ inline: ["max", "default"],
1119
+ url: ["schemes", "relative"],
1120
+ enum: ["values", "default"],
1121
+ number: ["min", "max", "integer", "default"],
1122
+ boolean: ["default"],
1123
+ array: ["items", "max"],
1124
+ object: ["fields"]
1125
+ };
1126
+ var BlockDefinitionError = class extends Error {
1127
+ /**
1128
+ * @param {string} message - Message naming the definition and the problem.
1129
+ * @param {string} [code] - `INVALID_DEFINITION` | `RESERVED_NAME` | `NAME_TAKEN` | `REGISTRY_SEALED`.
1130
+ */
1131
+ constructor(message, code = "INVALID_DEFINITION") {
1132
+ super(message);
1133
+ this.name = "BlockDefinitionError";
1134
+ this.code = code;
1135
+ }
1136
+ };
1137
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1138
+ var fail = (where, message) => {
1139
+ throw new BlockDefinitionError(`Magic Editor X block ${where}: ${message}`);
1140
+ };
1141
+ var boundedInt = (value, min, max, fallback, where, key) => {
1142
+ if (value === void 0) return fallback;
1143
+ if (!Number.isInteger(value) || value < min || value > max)
1144
+ fail(where, `"${key}" must be an integer from ${min} to ${max}`);
1145
+ return value;
1146
+ };
1147
+ var normalizeField = (input, where, depth) => {
1148
+ if (!isObject(input)) fail(where, 'a field must be an object with a "type"');
1149
+ const type = input.type;
1150
+ if (!BLOCK_FIELD_TYPES.includes(type)) fail(where, `unknown field type ${JSON.stringify(type)}`);
1151
+ for (const key of Object.keys(input))
1152
+ if (key !== "type" && key !== "label" && !FIELD_KEYS[type].includes(key))
1153
+ fail(where, `unknown option "${key}" for a ${type} field`);
1154
+ const out = { type };
1155
+ if (input.label !== void 0) {
1156
+ if (typeof input.label !== "string" || input.label.length > 100)
1157
+ fail(where, '"label" must be a string of at most 100 characters');
1158
+ out.label = input.label;
1159
+ }
1160
+ switch (type) {
1161
+ case "text":
1162
+ case "inline": {
1163
+ out.max = boundedInt(
1164
+ input.max,
1165
+ 1,
1166
+ BLOCK_LIMITS.maxText,
1167
+ type === "text" ? BLOCK_LIMITS.defaultText : BLOCK_LIMITS.defaultInline,
1168
+ where,
1169
+ "max"
1170
+ );
1171
+ if (input.default !== void 0 && typeof input.default !== "string")
1172
+ fail(where, '"default" must be a string');
1173
+ out.default = (input.default || "").slice(0, out.max);
1174
+ if (type === "text") {
1175
+ if (input.multiline !== void 0 && typeof input.multiline !== "boolean")
1176
+ fail(where, '"multiline" must be a boolean');
1177
+ out.multiline = input.multiline === true;
1178
+ }
1179
+ break;
1180
+ }
1181
+ case "url": {
1182
+ const schemes = input.schemes === void 0 ? ["http", "https"] : input.schemes;
1183
+ if (!Array.isArray(schemes) || !schemes.length || schemes.some((scheme) => !LINK_SCHEMES.includes(scheme)))
1184
+ fail(where, `"schemes" must be a non-empty list of ${LINK_SCHEMES.join(", ")}`);
1185
+ if (input.relative !== void 0 && typeof input.relative !== "boolean")
1186
+ fail(where, '"relative" must be a boolean');
1187
+ out.schemes = Object.freeze([...new Set(schemes)]);
1188
+ out.relative = input.relative !== false;
1189
+ break;
1190
+ }
1191
+ case "enum": {
1192
+ const values = input.values;
1193
+ 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)
1194
+ fail(
1195
+ where,
1196
+ `"values" must be 1 to ${BLOCK_LIMITS.maxEnumValues} distinct strings (1-100 characters)`
1197
+ );
1198
+ out.values = Object.freeze([...values]);
1199
+ if (input.default !== void 0 && !values.includes(input.default))
1200
+ fail(where, '"default" must be one of "values"');
1201
+ out.default = input.default === void 0 ? values[0] : input.default;
1202
+ break;
1203
+ }
1204
+ case "number": {
1205
+ for (const key of ["min", "max", "default"])
1206
+ if (input[key] !== void 0 && (typeof input[key] !== "number" || !Number.isFinite(input[key])))
1207
+ fail(where, `"${key}" must be a finite number`);
1208
+ if (input.integer !== void 0 && typeof input.integer !== "boolean")
1209
+ fail(where, '"integer" must be a boolean');
1210
+ out.integer = input.integer === true;
1211
+ out.min = input.min === void 0 ? -Number.MAX_SAFE_INTEGER : input.min;
1212
+ out.max = input.max === void 0 ? Number.MAX_SAFE_INTEGER : input.max;
1213
+ if (out.min > out.max) fail(where, '"min" must not be greater than "max"');
1214
+ if (input.default !== void 0) {
1215
+ if (input.default < out.min || input.default > out.max || out.integer && !Number.isInteger(input.default))
1216
+ fail(where, '"default" must be a valid value of the field');
1217
+ out.default = input.default;
1218
+ }
1219
+ break;
1220
+ }
1221
+ case "boolean":
1222
+ if (input.default !== void 0 && typeof input.default !== "boolean")
1223
+ fail(where, '"default" must be a boolean');
1224
+ out.default = input.default === true;
1225
+ break;
1226
+ case "array":
1227
+ if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1228
+ out.max = boundedInt(input.max, 1, BLOCK_LIMITS.maxItems, BLOCK_LIMITS.defaultItems, where, "max");
1229
+ out.items = normalizeField(input.items, `${where}[]`, depth + 1);
1230
+ break;
1231
+ case "object":
1232
+ if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1233
+ out.fields = normalizeFields(input.fields, where, depth + 1);
1234
+ break;
1235
+ default:
1236
+ break;
1237
+ }
1238
+ return Object.freeze(out);
1239
+ };
1240
+ var normalizeFields = (input, where, depth) => {
1241
+ if (!isObject(input)) fail(where, '"fields" must be an object of field descriptors');
1242
+ const keys = Object.keys(input);
1243
+ if (keys.length < 1 || keys.length > BLOCK_LIMITS.maxFields)
1244
+ fail(where, `an object needs 1 to ${BLOCK_LIMITS.maxFields} fields`);
1245
+ const out = /* @__PURE__ */ Object.create(null);
1246
+ for (const key of keys) {
1247
+ if (!KEY_PATTERN.test(key) || FORBIDDEN_KEYS2.has(key))
1248
+ fail(where, `field name ${JSON.stringify(key)} must match ${KEY_PATTERN}`);
1249
+ out[key] = normalizeField(input[key], `${where}.${key}`, depth);
1250
+ }
1251
+ return Object.freeze(out);
1252
+ };
1253
+ var blockNameProblem = (name) => {
1254
+ if (typeof name !== "string" || !BLOCK_NAME_PATTERN.test(name))
1255
+ return `the name must match ${BLOCK_NAME_PATTERN}`;
1256
+ if (RESERVED.has(name.toLowerCase())) return `"${name}" is a built-in tool name`;
1257
+ return null;
1258
+ };
1259
+ var defineBlock = (definition) => {
1260
+ if (!isObject(definition))
1261
+ throw new BlockDefinitionError("Magic Editor X block: the definition must be an object");
1262
+ const label2 = typeof definition.name === "string" ? `"${definition.name.slice(0, 50)}"` : "(no name)";
1263
+ for (const key of Object.keys(definition))
1264
+ if (!DEFINITION_KEYS.has(key)) fail(label2, `unknown key "${key}"`);
1265
+ const problem = blockNameProblem(definition.name);
1266
+ if (problem)
1267
+ throw new BlockDefinitionError(
1268
+ `Magic Editor X block ${label2}: ${problem}`,
1269
+ problem.includes("built-in") ? "RESERVED_NAME" : "INVALID_DEFINITION"
1270
+ );
1271
+ const out = {
1272
+ name: definition.name,
1273
+ version: boundedInt(definition.version, 1, 1e6, 1, label2, "version")
1274
+ };
1275
+ for (const [key, max] of [
1276
+ ["title", 100],
1277
+ ["description", 500]
1278
+ ]) {
1279
+ if (definition[key] === void 0) continue;
1280
+ if (typeof definition[key] !== "string" || definition[key].length > max)
1281
+ fail(label2, `"${key}" must be a string of at most ${max} characters`);
1282
+ out[key] = definition[key];
1283
+ }
1284
+ out.schema = normalizeFields(definition.schema, `${label2} schema`, 0);
1285
+ for (const key of ["sanitize", "text", "markdown", "render"]) {
1286
+ if (definition[key] === void 0) continue;
1287
+ if (typeof definition[key] !== "function") fail(label2, `"${key}" must be a function`);
1288
+ out[key] = definition[key];
1289
+ }
1290
+ const presets = definition.presets === void 0 ? [] : definition.presets;
1291
+ if (!Array.isArray(presets) || presets.some((preset) => !BLOCK_PRESETS.includes(preset)))
1292
+ fail(label2, `"presets" must list some of ${BLOCK_PRESETS.join(", ")}`);
1293
+ out.presets = Object.freeze([...new Set(presets)]);
1294
+ return Object.freeze(out);
1295
+ };
1296
+ var cleanValue = (field, value, inline, budget) => {
1297
+ budget.left -= 1;
1298
+ switch (field.type) {
1299
+ case "text":
1300
+ return typeof value === "string" ? value.slice(0, field.max) : field.default;
1301
+ case "inline":
1302
+ return inline(typeof value === "string" ? value.slice(0, field.max) : field.default);
1303
+ case "url":
1304
+ return typeof value === "string" ? sanitizeUrl(value.slice(0, BLOCK_LIMITS.maxUrl), {
1305
+ schemes: field.schemes,
1306
+ allowRelative: field.relative
1307
+ }) : "";
1308
+ case "enum":
1309
+ return typeof value === "string" && field.values.includes(value) ? value : field.default;
1310
+ case "number":
1311
+ return typeof value === "number" && Number.isFinite(value) && value >= field.min && value <= field.max && (!field.integer || Number.isInteger(value)) ? value : field.default;
1312
+ case "boolean":
1313
+ return typeof value === "boolean" ? value : field.default;
1314
+ case "array": {
1315
+ const out = [];
1316
+ if (!Array.isArray(value)) return out;
1317
+ for (const item of value) {
1318
+ if (out.length >= field.max || budget.left <= 0) break;
1319
+ if (!matchesType(field.items, item)) continue;
1320
+ const clean = cleanValue(field.items, item, inline, budget);
1321
+ if (clean !== void 0) out.push(clean);
1322
+ }
1323
+ return out;
1324
+ }
1325
+ case "object":
1326
+ return cleanObject(field.fields, isObject(value) ? value : {}, inline, budget);
1327
+ default:
1328
+ return void 0;
1329
+ }
1330
+ };
1331
+ var matchesType = (field, item) => {
1332
+ switch (field.type) {
1333
+ case "text":
1334
+ case "inline":
1335
+ case "url":
1336
+ case "enum":
1337
+ return typeof item === "string";
1338
+ case "number":
1339
+ return typeof item === "number";
1340
+ case "boolean":
1341
+ return typeof item === "boolean";
1342
+ case "array":
1343
+ return Array.isArray(item);
1344
+ default:
1345
+ return isObject(item);
1346
+ }
1347
+ };
1348
+ var cleanObject = (fields, value, inline, budget) => {
1349
+ const out = {};
1350
+ for (const key of Object.keys(fields)) {
1351
+ const own = Object.prototype.hasOwnProperty.call(value, key) ? value[key] : void 0;
1352
+ const clean = cleanValue(fields[key], own, inline, budget);
1353
+ if (clean !== void 0) out[key] = clean;
1354
+ }
1355
+ return out;
1356
+ };
1357
+ var eachLeaf = (fields, data, visit) => {
1358
+ const walk = (field, value, path, depth) => {
1359
+ if (depth > BLOCK_LIMITS.maxDepth + 1) return;
1360
+ if (field.type === "array") {
1361
+ if (!Array.isArray(value)) return;
1362
+ value.slice(0, field.max).forEach((item, index) => walk(field.items, item, [...path, index], depth + 1));
1363
+ } else if (field.type === "object") {
1364
+ if (!isObject(value)) return;
1365
+ for (const key of Object.keys(field.fields))
1366
+ if (Object.prototype.hasOwnProperty.call(value, key))
1367
+ walk(field.fields[key], value[key], [...path, key], depth + 1);
1368
+ } else visit(field, value, path);
1369
+ };
1370
+ if (!isObject(data)) return;
1371
+ for (const key of Object.keys(fields))
1372
+ if (Object.prototype.hasOwnProperty.call(data, key)) walk(fields[key], data[key], [key], 0);
1373
+ };
1374
+ var fieldAt = (fields, path) => {
1375
+ let current = { type: "object", fields };
1376
+ for (const part of String(path).split(".")) {
1377
+ if (!part) continue;
1378
+ if (current.type === "array") {
1379
+ if (/^\d+$/.test(part)) {
1380
+ current = current.items;
1381
+ continue;
1382
+ }
1383
+ return null;
1384
+ }
1385
+ if (current.type !== "object" || !Object.prototype.hasOwnProperty.call(current.fields, part)) return null;
1386
+ current = current.fields[part];
1387
+ }
1388
+ return current;
1389
+ };
1390
+ var compiled = /* @__PURE__ */ new WeakMap();
1391
+ var compileBlock = (definition) => {
1392
+ if (definition && typeof definition === "object" && compiled.has(definition))
1393
+ return compiled.get(definition);
1394
+ const def = defineBlock(definition && typeof definition === "object" ? { ...definition } : definition);
1395
+ const schema = def.schema;
1396
+ const run = (data, inline) => cleanObject(schema, isObject(data) ? data : {}, inline, { left: BLOCK_LIMITS.maxValues });
1397
+ const result = Object.freeze({
1398
+ ...def,
1399
+ /**
1400
+ * Cleans untrusted block data (unknown keys dropped, values bounded).
1401
+ * The optional `sanitize` hook runs on the clean data; its result is
1402
+ * cleaned again, so it cannot add keys or unsafe values. A hook that
1403
+ * throws is ignored (the clean data is used).
1404
+ * @param {unknown} data - Block data.
1405
+ * @param {(html: string) => string} inline - Inline HTML sanitiser of the caller.
1406
+ * @returns {object} Clean data.
1407
+ */
1408
+ clean: (data, inline) => {
1409
+ const first = run(data, inline);
1410
+ if (!def.sanitize) return first;
1411
+ let next;
1412
+ try {
1413
+ next = def.sanitize(copyData(first), { sanitizeUrl });
1414
+ } catch {
1415
+ return first;
1416
+ }
1417
+ return isObject(next) ? run(next, inline) : first;
1418
+ },
1419
+ /**
1420
+ * Text fields of the data in schema order: `{ path, kind, value }`
1421
+ * (`html` for inline fields, `plain` for text fields).
1422
+ * @param {unknown} data - Block data.
1423
+ * @returns {Array<{ path: Array<string|number>, kind: 'html'|'plain', value: string }>} Fields.
1424
+ */
1425
+ fields: (data) => {
1426
+ const out = [];
1427
+ eachLeaf(schema, data, (field, value, path) => {
1428
+ if (typeof value !== "string") return;
1429
+ if (field.type === "inline") out.push({ path, kind: "html", value });
1430
+ else if (field.type === "text") out.push({ path, kind: "plain", value });
1431
+ });
1432
+ return out;
1433
+ },
1434
+ /**
1435
+ * Non-empty URL values: `{ path, value }`.
1436
+ * @param {unknown} data - Block data.
1437
+ * @returns {Array<{ path: Array<string|number>, value: string }>} URLs.
1438
+ */
1439
+ urls: (data) => {
1440
+ const out = [];
1441
+ eachLeaf(schema, data, (field, value, path) => {
1442
+ if (field.type === "url" && typeof value === "string" && value) out.push({ path, value });
1443
+ });
1444
+ return out;
1445
+ },
1446
+ /**
1447
+ * Kind of the value at a dotted path, for the version diff.
1448
+ * @param {string} path - Dotted path.
1449
+ * @returns {'inline'|'plain'|'value'} Kind.
1450
+ */
1451
+ kindOf: (path) => {
1452
+ const field = fieldAt(schema, path);
1453
+ if (!field) return "value";
1454
+ if (field.type === "inline") return "inline";
1455
+ if (field.type === "text") return "plain";
1456
+ return "value";
1457
+ }
1458
+ });
1459
+ compiled.set(result, result);
1460
+ if (definition && typeof definition === "object") compiled.set(definition, result);
1461
+ return result;
1462
+ };
1463
+ var copyData = (value) => {
1464
+ if (Array.isArray(value)) return value.map(copyData);
1465
+ if (isObject(value)) {
1466
+ const out = {};
1467
+ for (const [key, child] of Object.entries(value)) out[key] = copyData(child);
1468
+ return out;
1469
+ }
1470
+ return value;
1471
+ };
1472
+ var listCache = /* @__PURE__ */ new WeakMap();
1473
+ var compileBlockList = (list) => {
1474
+ if (!Array.isArray(list)) return /* @__PURE__ */ new Map();
1475
+ if (listCache.has(list)) return listCache.get(list);
1476
+ const map = /* @__PURE__ */ new Map();
1477
+ for (const definition of list) {
1478
+ const def = compileBlock(definition);
1479
+ map.set(def.name, def);
1480
+ }
1481
+ listCache.set(list, map);
1482
+ return map;
1483
+ };
1484
+
1485
+ // shared/toc.mjs
1486
+ var HEADING_ID_PREFIX = "mex-h-";
1487
+ var TOC_DEFAULTS = Object.freeze({ title: "", minLevel: 2, maxLevel: 4, style: "unordered" });
1488
+ var TOC_STYLES = Object.freeze(["unordered", "ordered"]);
1489
+ var SAFE_ID = /^[A-Za-z0-9_-]{1,64}$/;
1490
+ var createAnchorAllocator = () => {
1491
+ const used = /* @__PURE__ */ new Set();
1492
+ let position = 0;
1493
+ return (blockId) => {
1494
+ position += 1;
1495
+ const base = `${HEADING_ID_PREFIX}${typeof blockId === "string" && SAFE_ID.test(blockId) ? blockId : position}`;
1496
+ let id = base;
1497
+ for (let n = 2; used.has(id); n += 1) id = `${base}-${n}`;
1498
+ used.add(id);
1499
+ return id;
1500
+ };
1501
+ };
1502
+ var githubSlug = (text) => String(text || "").toLowerCase().trim().replace(/[^\p{L}\p{M}\p{N}\p{Pc} -]/gu, "").replace(/ /g, "-");
1503
+ var createSlugAllocator = () => {
1504
+ const seen = /* @__PURE__ */ new Map();
1505
+ return (text) => {
1506
+ const base = githubSlug(text);
1507
+ let slug = base;
1508
+ if (seen.has(base)) {
1509
+ let n = seen.get(base);
1510
+ do {
1511
+ n += 1;
1512
+ slug = `${base}-${n}`;
1513
+ } while (seen.has(slug));
1514
+ seen.set(base, n);
1515
+ }
1516
+ seen.set(slug, 0);
1517
+ return slug;
1518
+ };
1519
+ };
1520
+ var tocRange = (data) => {
1521
+ const pick = (value, fallback) => Number.isInteger(value) && value >= 1 && value <= 6 ? value : fallback;
1522
+ const a = pick(data && data.minLevel, TOC_DEFAULTS.minLevel);
1523
+ const b = pick(data && data.maxLevel, TOC_DEFAULTS.maxLevel);
1524
+ return { minLevel: Math.min(a, b), maxLevel: Math.max(a, b) };
1525
+ };
1526
+ var buildTocTree = (headings, data) => {
1527
+ const { minLevel, maxLevel } = tocRange(data);
1528
+ const root = { level: 0, children: [] };
1529
+ const stack = [root];
1530
+ for (const heading of headings || []) {
1531
+ if (!heading || heading.level < minLevel || heading.level > maxLevel) continue;
1532
+ const text = String(heading.text || "").replace(/\s+/g, " ").trim();
1533
+ if (!text) continue;
1534
+ while (stack.length > 1 && stack[stack.length - 1].level >= heading.level) stack.pop();
1535
+ const node = {
1536
+ id: heading.id || null,
1537
+ slug: heading.slug || null,
1538
+ level: heading.level,
1539
+ text: text.slice(0, 500),
1540
+ children: []
1541
+ };
1542
+ stack[stack.length - 1].children.push(node);
1543
+ stack.push(node);
1544
+ }
1545
+ return root.children;
1546
+ };
1547
+
1548
+ // shared/synced.mjs
1549
+ var SYNCED_TYPE = "synced";
1550
+ var SYNCED_REF_PATTERN = /^[a-z0-9]{1,64}$/;
1551
+ var SYNCED_LIMITS = Object.freeze({ refsPerResponse: 100 });
1552
+ var BLOCK_ID = /^[A-Za-z0-9_-]{1,64}$/;
1553
+ var MAX_TOGGLE_DEPTH = 16;
1554
+ var isSyncedBlock = (block) => Boolean(block) && block.type === SYNCED_TYPE && isBuiltInBlock(
1555
+ /** @type {any} */
1556
+ block
1557
+ );
1558
+ var syncedRefOf = (block) => {
1559
+ if (!isSyncedBlock(block)) return null;
1560
+ const ref = (
1561
+ /** @type {any} */
1562
+ block.data.ref
1563
+ );
1564
+ return typeof ref === "string" && SYNCED_REF_PATTERN.test(ref) ? ref : null;
1565
+ };
1566
+ var containsSynced = (blocks) => Array.isArray(blocks) && blocks.some(isSyncedBlock);
1567
+ var toBlockTree = (blocks) => {
1568
+ const build = (start, end, depth) => {
1569
+ const out = [];
1570
+ let i = start;
1571
+ while (i < end) {
1572
+ const block = blocks[i];
1573
+ i += 1;
1574
+ const node = { block, children: [], toggle: false };
1575
+ if (block && block.type === "toggle" && depth < MAX_TOGGLE_DEPTH && isPlainObject2(block.data)) {
1576
+ const count = Math.max(0, Math.min(Number(block.data.items) || 0, end - i));
1577
+ node.children = build(i, i + count, depth + 1);
1578
+ node.toggle = true;
1579
+ i += count;
1580
+ }
1581
+ out.push(node);
1582
+ }
1583
+ return out;
1584
+ };
1585
+ return build(0, Array.isArray(blocks) ? blocks.length : 0, 0);
1586
+ };
1587
+ var fromBlockTree = (nodes) => {
1588
+ const out = [];
1589
+ const walk = (list) => {
1590
+ for (const node of list) {
1591
+ const at = out.length;
1592
+ out.push(node.block);
1593
+ if (!node.toggle) continue;
1594
+ walk(node.children);
1595
+ const count = out.length - at - 1;
1596
+ if (Number(node.block.data.items) !== count)
1597
+ out[at] = { ...node.block, data: { ...node.block.data, items: count } };
1598
+ }
1599
+ };
1600
+ walk(nodes);
1601
+ return out;
1602
+ };
1603
+ var replaceBlocks = (blocks, replace) => {
1604
+ const map = (nodes) => {
1605
+ const out = [];
1606
+ for (const node of nodes) {
1607
+ const next = replace(node.block);
1608
+ const children = node.toggle ? map(node.children) : [];
1609
+ if (next === null || next === void 0) {
1610
+ out.push(node.toggle ? { ...node, children } : node);
1611
+ } else if (node.toggle && next.length === 1 && next[0] && next[0].type === "toggle") {
1612
+ out.push({ block: next[0], children, toggle: true });
1613
+ } else {
1614
+ out.push(...toBlockTree(next), ...children);
1615
+ }
1616
+ }
1617
+ return out;
1618
+ };
1619
+ return fromBlockTree(map(toBlockTree(blocks)));
1620
+ };
1621
+ var sourceBlocksOf = (source) => {
1622
+ const data = normalizeEditorDataSafe(source);
1623
+ if (!data || !data.blocks.length) return [];
1624
+ return containsSynced(data.blocks) ? replaceBlocks(data.blocks, (block) => isSyncedBlock(block) ? [] : null) : data.blocks;
1625
+ };
1626
+ var derivedId = (parentId, sourceId, taken) => {
1627
+ const joined = `${parentId}-${sourceId}`;
1628
+ let id = BLOCK_ID.test(joined) ? joined : `sx${hashString(joined)}${hashString(`${sourceId}|${parentId}`)}`;
1629
+ for (let n = 2; taken.has(id); n += 1) id = `sx${hashString(`${joined}|${n}`)}${n}`;
1630
+ taken.add(id);
1631
+ return id;
1632
+ };
1633
+ var expandSynced = (data, lookup, options = {}) => {
1634
+ const origins = /* @__PURE__ */ new Map();
1635
+ if (!data || !Array.isArray(data.blocks) || !containsSynced(data.blocks))
1636
+ return { data, origins, expanded: 0, unresolved: 0 };
1637
+ const maxBlocks = options.maxBlocks || EDITOR_DATA_LIMITS.maxBlocks;
1638
+ const maxBytes = options.maxBytes || EDITOR_DATA_LIMITS.maxBytes - 64 * 1024;
1639
+ const taken = new Set(data.blocks.map((block) => block.id));
1640
+ let total = data.blocks.filter((block) => !isSyncedBlock(block)).length;
1641
+ let bytes = byteLength(JSON.stringify(data));
1642
+ let expanded = 0;
1643
+ let unresolved = 0;
1644
+ const cache = /* @__PURE__ */ new Map();
1645
+ const sourceFor = (ref) => {
1646
+ if (!cache.has(ref)) {
1647
+ let blocks2;
1648
+ try {
1649
+ blocks2 = sourceBlocksOf(typeof lookup === "function" ? lookup(ref) : null);
1650
+ if (blocks2.length && typeof options.filter === "function") {
1651
+ const filtered = options.filter(blocks2);
1652
+ blocks2 = Array.isArray(filtered) ? filtered.filter((block) => !isSyncedBlock(block)) : [];
1653
+ }
1654
+ } catch {
1655
+ blocks2 = [];
1656
+ }
1657
+ cache.set(ref, { blocks: blocks2, size: blocks2.length ? byteLength(JSON.stringify(blocks2)) : 0 });
1658
+ }
1659
+ return cache.get(ref);
1660
+ };
1661
+ const blocks = replaceBlocks(data.blocks, (block) => {
1662
+ if (!isSyncedBlock(block)) return null;
1663
+ const ref = syncedRefOf(block);
1664
+ const source = ref ? sourceFor(ref) : { blocks: [], size: 0 };
1665
+ if (!source.blocks.length || total + source.blocks.length > maxBlocks || bytes + source.size > maxBytes) {
1666
+ unresolved += 1;
1667
+ return [];
1668
+ }
1669
+ total += source.blocks.length;
1670
+ bytes += source.size;
1671
+ expanded += 1;
1672
+ return source.blocks.map((item) => {
1673
+ const id = derivedId(block.id, item.id, taken);
1674
+ origins.set(id, ref);
1675
+ const copy = { id, type: item.type, data: JSON.parse(JSON.stringify(item.data || {})) };
1676
+ if (isPlainObject2(item.tunes) && Object.keys(item.tunes).length)
1677
+ copy.tunes = JSON.parse(JSON.stringify(item.tunes));
1678
+ return copy;
1679
+ });
1680
+ });
1681
+ return {
1682
+ data: { time: data.time || 0, version: data.version || "2.31.7", blocks },
1683
+ origins,
1684
+ expanded,
1685
+ unresolved
1686
+ };
1687
+ };
1688
+ var syncedLookup = (option) => {
1689
+ if (typeof option === "function") return (ref) => option(ref);
1690
+ if (option instanceof Map) return (ref) => option.get(ref);
1691
+ if (isPlainObject2(option))
1692
+ return (ref) => Object.prototype.hasOwnProperty.call(option, ref) ? option[ref] : null;
1693
+ return () => null;
1694
+ };
1695
+
747
1696
  // shared/render/common.mjs
748
- var keepInline = (html) => inlineToHtml(html);
1697
+ var keepInline = (html) => inlineToHtml(html, { storage: true });
749
1698
  var prepareBlocks = (value, options = {}) => {
750
- const data = normalizeEditorDataSafe(value);
751
- if (!data) return [];
1699
+ const normalized = normalizeEditorDataSafe(value);
1700
+ if (!normalized) return [];
1701
+ const data = containsSynced(normalized.blocks) ? expandSynced(normalized, syncedLookup(options.synced)).data : normalized;
752
1702
  const rawPolicy = options.rawHtml === "allow" && typeof options.sanitizeRaw === "function" ? "allow" : "disable";
753
1703
  const ctx = { rawHtml: rawPolicy, rawSanitizer: () => "" };
1704
+ const explicit = Array.isArray(options.blocks) ? compileBlockList(options.blocks) : null;
754
1705
  const flat = data.blocks.map((block) => {
755
- const known = Object.prototype.hasOwnProperty.call(BLOCK_POLICIES, block.type);
756
- const raw = isPlainObject(block.data) ? block.data : {};
757
- const clean = known ? BLOCK_POLICIES[block.type](raw, keepInline, ctx) : raw;
1706
+ const raw = isPlainObject2(block.data) ? block.data : {};
1707
+ const known = isBuiltInBlock({ type: block.type, data: raw });
1708
+ const definition = known ? null : registeredBlockOf({ type: block.type, data: raw }, explicit);
1709
+ const clean = known ? BLOCK_POLICIES[block.type](raw, keepInline, ctx) : definition ? definition.clean(raw, keepInline) : raw;
758
1710
  for (const key of Object.keys(clean)) if (clean[key] === void 0) delete clean[key];
759
1711
  return {
760
1712
  id: block.id,
@@ -763,6 +1715,7 @@ var prepareBlocks = (value, options = {}) => {
763
1715
  raw,
764
1716
  tunes: sanitizeTunes(block.tunes),
765
1717
  known,
1718
+ definition,
766
1719
  children: []
767
1720
  };
768
1721
  });
@@ -793,27 +1746,36 @@ var imageCandidates = (file) => {
793
1746
  seen.add(width);
794
1747
  out.push({ url: clean, width });
795
1748
  };
796
- if (isPlainObject(file.formats)) {
1749
+ if (isPlainObject2(file.formats)) {
797
1750
  const names = Object.keys(file.formats).sort(
798
1751
  (a, b) => (FORMAT_ORDER.indexOf(a) + 1 || 99) - (FORMAT_ORDER.indexOf(b) + 1 || 99) || (a < b ? -1 : a > b ? 1 : 0)
799
1752
  );
800
1753
  for (const name of names) {
801
1754
  const format = file.formats[name];
802
- if (isPlainObject(format)) push(format.url, Number(format.width));
1755
+ if (isPlainObject2(format)) push(format.url, Number(format.width));
803
1756
  }
804
1757
  }
805
1758
  push(file.url, Number(file.width));
806
1759
  return out.sort((a, b) => a.width - b.width);
807
1760
  };
808
- var resolveMedia = (file, block, options) => {
1761
+ var resolveMedia = (file, block, options, kind) => {
809
1762
  if (typeof options.media !== "function") return file;
1763
+ if (kind) {
1764
+ let other;
1765
+ try {
1766
+ other = options.media({ ...file }, { id: block.id, type: block.type });
1767
+ } catch {
1768
+ other = null;
1769
+ }
1770
+ return isPlainObject2(other) ? cleanMediaFile(other, kind) : file;
1771
+ }
810
1772
  let next;
811
1773
  try {
812
1774
  next = options.media({ ...file }, { id: block.id, type: block.type });
813
1775
  } catch {
814
1776
  next = null;
815
1777
  }
816
- if (!isPlainObject(next)) return file;
1778
+ if (!isPlainObject2(next)) return file;
817
1779
  const policy = BLOCK_POLICIES.image({ file: next }, (s) => s, {
818
1780
  rawHtml: "disable",
819
1781
  rawSanitizer: () => ""
@@ -847,27 +1809,53 @@ var overrideFor = (options, type) => {
847
1809
  return null;
848
1810
  return typeof overrides[type] === "function" ? overrides[type] : null;
849
1811
  };
850
- 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])]);
1812
+ 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])]);
851
1813
  var formatSize = (bytes) => {
852
1814
  if (!Number.isFinite(bytes) || bytes < 0) return "";
853
1815
  if (bytes < 1024) return `${bytes} B`;
854
1816
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
855
1817
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
856
1818
  };
1819
+ var eachBlock = (blocks, fn, depth = 0) => {
1820
+ if (depth > 16) return;
1821
+ for (const block of blocks) {
1822
+ fn(block);
1823
+ if (block.children.length) eachBlock(block.children, fn, depth + 1);
1824
+ }
1825
+ };
1826
+ var annotateHeadings = (blocks, options = {}) => {
1827
+ const tocs = [];
1828
+ const headers = [];
1829
+ eachBlock(blocks, (block) => {
1830
+ if (!block.known) return;
1831
+ if (block.type === "toc") tocs.push(block);
1832
+ else if (block.type === "header") headers.push(block);
1833
+ });
1834
+ const enabled = options.headingIds === true || options.headingIds !== false && tocs.length > 0;
1835
+ if (!enabled && !tocs.length) return blocks;
1836
+ const allocate = createAnchorAllocator();
1837
+ const slugOf = createSlugAllocator();
1838
+ const headings = headers.map((block) => {
1839
+ const id = allocate(block.id);
1840
+ const text = inlineToText(block.data.text);
1841
+ if (enabled) block.anchor = id;
1842
+ return { id: enabled ? id : null, slug: slugOf(text.trim()), level: block.data.level, text };
1843
+ });
1844
+ for (const toc of tocs) {
1845
+ toc.headings = headings;
1846
+ toc.linkHeadings = enabled;
1847
+ }
1848
+ return blocks;
1849
+ };
857
1850
 
858
- // shared/render/html.mjs
1851
+ // shared/render/tree.mjs
859
1852
  var COUNTER_TYPES = Object.freeze({
860
1853
  "lower-roman": "i",
861
1854
  "upper-roman": "I",
862
1855
  "lower-alpha": "a",
863
1856
  "upper-alpha": "A"
864
1857
  });
865
- var el = (tag, attrs, inner) => {
866
- const attributes = Object.entries(attrs || {}).filter(
867
- ([name, value]) => value !== void 0 && value !== null && value !== false && (value !== "" || name === "alt")
868
- ).map(([name, value]) => value === true ? ` ${name}` : ` ${name}="${escapeHtml2(value)}"`).join("");
869
- return inner === void 0 ? `<${tag}${attributes}>` : `<${tag}${attributes}>${inner}</${tag}>`;
870
- };
1858
+ var MAX_NUMBERED_LINES = 2e4;
871
1859
  var classes = (base, tunes) => {
872
1860
  const list = [...base];
873
1861
  if (tunes && tunes.alignmentTune && tunes.alignmentTune.alignment !== "left")
@@ -878,16 +1866,24 @@ var classes = (base, tunes) => {
878
1866
  return list.join(" ");
879
1867
  };
880
1868
  var listItems2 = (items, style, options, depth) => items.map((item) => {
881
- if (typeof item === "string") return el("li", {}, inlineToHtml(item, options));
1869
+ if (typeof item === "string") return el("li", {}, inlineToNodes(item, options));
882
1870
  const checked = Boolean(item.meta && item.meta.checked);
883
- const check = style === "checklist" ? `${el("input", { type: "checkbox", disabled: true, checked, "aria-label": checked ? "done" : "open" })} ` : "";
884
- const nested = Array.isArray(item.items) && item.items.length && depth < 12 ? listElement(item.items, style, {}, options, depth + 1, []) : "";
1871
+ const check = style === "checklist" ? [
1872
+ el("input", {
1873
+ type: "checkbox",
1874
+ disabled: true,
1875
+ checked,
1876
+ "aria-label": checked ? "done" : "open"
1877
+ }),
1878
+ " "
1879
+ ] : [];
1880
+ const nested = Array.isArray(item.items) && item.items.length && depth < 12 ? listElement(item.items, style, {}, options, depth + 1, []) : null;
885
1881
  return el(
886
1882
  "li",
887
1883
  style === "checklist" ? { class: "mex-checklist-item", "data-checked": String(checked) } : {},
888
- check + inlineToHtml(item.content, options) + nested
1884
+ [check, inlineToNodes(item.content, options), nested]
889
1885
  );
890
- }).join("");
1886
+ });
891
1887
  var listElement = (items, style, meta, options, depth, base, tunes) => {
892
1888
  const tag = style === "ordered" ? "ol" : "ul";
893
1889
  const attrs = {};
@@ -898,16 +1894,140 @@ var listElement = (items, style, meta, options, depth, base, tunes) => {
898
1894
  }
899
1895
  return el(tag, attrs, listItems2(items, style, options, depth));
900
1896
  };
901
- var figure = (url, img, caption, cls) => el(
902
- "figure",
903
- { class: cls },
904
- el("img", { src: url, ...img, loading: "lazy", decoding: "async" }) + (caption ? el("figcaption", {}, caption) : "")
905
- );
1897
+ var figure = (url, img, caption, cls) => el("figure", { class: cls }, [
1898
+ el("img", { src: url, ...img, loading: "lazy", decoding: "async" }),
1899
+ caption.length ? el("figcaption", {}, caption) : null
1900
+ ]);
1901
+ var withFocalPoint = (img, point, o) => {
1902
+ if (!point || img.type !== "element") return img;
1903
+ img.attrs["data-mex-focal-x"] = String(point.x);
1904
+ img.attrs["data-mex-focal-y"] = String(point.y);
1905
+ if (o.focalPoint === "style")
1906
+ img.style = { "object-position": `${Math.round(point.x * 100)}% ${Math.round(point.y * 100)}%` };
1907
+ return img;
1908
+ };
1909
+ var libraryImageAttrs = (file, decorative, o) => {
1910
+ const candidates = imageCandidates(file);
1911
+ const img = {
1912
+ alt: decorative ? "" : file.alt || "",
1913
+ width: Number.isInteger(file.width) && file.width > 0 ? file.width : void 0,
1914
+ height: Number.isInteger(file.height) && file.height > 0 ? file.height : void 0
1915
+ };
1916
+ if (candidates.length > 1) {
1917
+ img.srcset = candidates.map((c) => `${c.url} ${c.width}w`).join(", ");
1918
+ img.sizes = typeof o.imageSizes === "string" && /^[\w\s(),.:%-]{1,200}$/.test(o.imageSizes) ? o.imageSizes : "100vw";
1919
+ }
1920
+ return img;
1921
+ };
1922
+ var trackNodes = (b, o) => b.data.tracks.map((track) => {
1923
+ const file = resolveMedia(track.file, b, o, { vtt: true });
1924
+ if (!file.url) return null;
1925
+ return el("track", {
1926
+ kind: track.kind,
1927
+ src: file.url,
1928
+ srclang: track.srclang || void 0,
1929
+ label: track.label || void 0,
1930
+ default: track.default === true
1931
+ });
1932
+ }).filter(Boolean);
1933
+ var mediaFigure = (tag, b, o) => {
1934
+ const file = resolveMedia(b.data.file, b, o, { mimePrefix: `${tag}/` });
1935
+ if (!file.url) return null;
1936
+ const caption = inlineToNodes(b.data.caption, o);
1937
+ const attrs = {
1938
+ src: file.url,
1939
+ controls: true,
1940
+ preload: "metadata",
1941
+ "aria-label": b.data.title || void 0,
1942
+ loop: b.data.loop === true
1943
+ };
1944
+ if (tag === "video") {
1945
+ const poster = b.data.poster ? resolveMedia(b.data.poster, b, o) : null;
1946
+ Object.assign(attrs, {
1947
+ playsinline: true,
1948
+ muted: b.data.muted === true,
1949
+ poster: poster && poster.url ? poster.url : void 0,
1950
+ width: Number.isInteger(file.width) && file.width > 0 ? file.width : void 0,
1951
+ height: Number.isInteger(file.height) && file.height > 0 ? file.height : void 0
1952
+ });
1953
+ }
1954
+ return el("figure", { class: classes([`mex-${tag}`], b.tunes) }, [
1955
+ el(tag, attrs, [
1956
+ trackNodes(b, o),
1957
+ // Fallback for browsers without media support.
1958
+ el("a", { href: file.url }, b.data.title || file.name || file.url)
1959
+ ]),
1960
+ caption.length ? el("figcaption", {}, caption) : null
1961
+ ]);
1962
+ };
1963
+ var label = (value, fallback) => {
1964
+ if (typeof value !== "string") return fallback;
1965
+ const clean = value.trim();
1966
+ return clean && clean.length <= 80 ? clean : fallback;
1967
+ };
1968
+ var tocLabel = (options) => label(isPlainObject2(options.toc) ? options.toc.label : void 0, "Table of contents");
1969
+ var codeOptions = (options) => {
1970
+ const code = isPlainObject2(options.code) ? options.code : {};
1971
+ const lineNumbers = code.lineNumbers === true ? "all" : code.lineNumbers === "block" ? "block" : "none";
1972
+ const button = code.copyButton;
1973
+ const copy = button === true || isPlainObject2(button) ? {
1974
+ label: label(isPlainObject2(button) ? button.label : void 0, "Copy code"),
1975
+ copied: label(isPlainObject2(button) ? button.copiedLabel : void 0, "Copied"),
1976
+ failed: label(isPlainObject2(button) ? button.failedLabel : void 0, "Copy failed")
1977
+ } : null;
1978
+ return { lineNumbers, copy };
1979
+ };
1980
+ var numberedLines = (code) => {
1981
+ const parts = code.split("\n");
1982
+ const trailing = parts.length > 1 && parts[parts.length - 1] === "";
1983
+ if (trailing) parts.pop();
1984
+ const out = [];
1985
+ parts.forEach((line, index) => {
1986
+ if (index) out.push("\n");
1987
+ out.push(el("span", { class: "mex-code-line" }, line));
1988
+ });
1989
+ if (trailing) out.push("\n");
1990
+ return out;
1991
+ };
1992
+ var codeBlock = (b, language, o) => {
1993
+ const { lineNumbers, copy } = codeOptions(o);
1994
+ const code = String(b.data.code);
1995
+ const wantNumbers = lineNumbers === "all" || lineNumbers === "block" && b.type === "codeFlask" && b.data.showlinenumbers !== false;
1996
+ const numbers = wantNumbers && code.split("\n").length <= MAX_NUMBERED_LINES;
1997
+ const pre = el(
1998
+ "pre",
1999
+ {
2000
+ class: classes(["mex-code", ...numbers ? ["mex-code-lines"] : []], b.tunes),
2001
+ "data-language": language
2002
+ },
2003
+ el("code", language ? { class: `language-${language}` } : {}, numbers ? numberedLines(code) : code)
2004
+ );
2005
+ if (!copy) return pre;
2006
+ return el("div", { class: "mex-code-block", "data-mex-code": "copy" }, [
2007
+ pre,
2008
+ el(
2009
+ "button",
2010
+ {
2011
+ type: "button",
2012
+ class: "mex-code-copy",
2013
+ "data-mex-copy": "code",
2014
+ "data-mex-copied": copy.copied,
2015
+ "data-mex-failed": copy.failed
2016
+ },
2017
+ copy.label
2018
+ ),
2019
+ el("span", { class: "mex-code-copy-status", role: "status", "aria-live": "polite" })
2020
+ ]);
2021
+ };
906
2022
  var RENDERERS = {
907
- paragraph: (b, o) => el("p", { class: classes(["mex-paragraph"], b.tunes) }, inlineToHtml(b.data.text, o)),
908
- header: (b, o) => el(`h${b.data.level}`, { class: classes(["mex-header"], b.tunes) }, inlineToHtml(b.data.text, o)),
2023
+ paragraph: (b, o) => el("p", { class: classes(["mex-paragraph"], b.tunes) }, inlineToNodes(b.data.text, o)),
2024
+ header: (b, o) => el(
2025
+ `h${b.data.level}`,
2026
+ { id: b.anchor, class: classes(["mex-header"], b.tunes) },
2027
+ inlineToNodes(b.data.text, o)
2028
+ ),
909
2029
  quote: (b, o) => {
910
- const caption = inlineToHtml(b.data.caption, o);
2030
+ const caption = inlineToNodes(b.data.caption, o);
911
2031
  return el(
912
2032
  "figure",
913
2033
  {
@@ -916,7 +2036,10 @@ var RENDERERS = {
916
2036
  b.tunes
917
2037
  )
918
2038
  },
919
- el("blockquote", {}, inlineToHtml(b.data.text, o)) + (caption ? el("figcaption", {}, caption) : "")
2039
+ [
2040
+ el("blockquote", {}, inlineToNodes(b.data.text, o)),
2041
+ caption.length ? el("figcaption", {}, caption) : null
2042
+ ]
920
2043
  );
921
2044
  },
922
2045
  list: (b, o) => listElement(
@@ -938,12 +2061,11 @@ var RENDERERS = {
938
2061
  b.tunes
939
2062
  ),
940
2063
  warning: (b, o) => {
941
- const title = inlineToHtml(b.data.title, o);
942
- return el(
943
- "aside",
944
- { class: classes(["mex-warning"], b.tunes), role: "note" },
945
- (title ? el("p", { class: "mex-warning-title" }, el("strong", {}, title)) : "") + el("p", { class: "mex-warning-message" }, inlineToHtml(b.data.message, o))
946
- );
2064
+ const title = inlineToNodes(b.data.title, o);
2065
+ return el("aside", { class: classes(["mex-warning"], b.tunes), role: "note" }, [
2066
+ title.length ? el("p", { class: "mex-warning-title" }, el("strong", {}, title)) : null,
2067
+ el("p", { class: "mex-warning-message" }, inlineToNodes(b.data.message, o))
2068
+ ]);
947
2069
  },
948
2070
  alert: (b, o) => el(
949
2071
  "div",
@@ -958,62 +2080,49 @@ var RENDERERS = {
958
2080
  ),
959
2081
  role: "note"
960
2082
  },
961
- inlineToHtml(b.data.message, o)
962
- ),
963
- toggle: (b, o, render) => el(
964
- "details",
965
- { class: classes(["mex-toggle"], b.tunes), open: b.data.status !== "closed" },
966
- el("summary", {}, inlineToHtml(b.data.text, o)) + render(b.children)
967
- ),
968
- code: (b) => el("pre", { class: classes(["mex-code"], b.tunes) }, el("code", {}, escapeHtml2(b.data.code))),
969
- codeFlask: (b) => el(
970
- "pre",
971
- { class: classes(["mex-code"], b.tunes), "data-language": b.data.language },
972
- el("code", { class: `language-${b.data.language}` }, escapeHtml2(b.data.code))
2083
+ inlineToNodes(b.data.message, o)
973
2084
  ),
2085
+ toggle: (b, o, renderList) => el("details", { class: classes(["mex-toggle"], b.tunes), open: b.data.status !== "closed" }, [
2086
+ el("summary", {}, inlineToNodes(b.data.text, o)),
2087
+ renderList(b.children)
2088
+ ]),
2089
+ code: (b, o) => codeBlock(b, void 0, o),
2090
+ codeFlask: (b, o) => codeBlock(b, b.data.language, o),
974
2091
  raw: (b, o) => {
975
- if (o.rawHtml !== "allow" || typeof o.sanitizeRaw !== "function") return "";
2092
+ if (o.rawHtml !== "allow" || typeof o.sanitizeRaw !== "function") return null;
976
2093
  const html = o.sanitizeRaw(String(b.raw.html || ""));
977
- return typeof html === "string" && html ? el("div", { class: classes(["mex-raw"], b.tunes) }, html) : "";
2094
+ return typeof html === "string" && html ? el("div", { class: classes(["mex-raw"], b.tunes) }, { type: "raw", html }) : null;
978
2095
  },
979
2096
  table: (b, o) => {
980
2097
  const rows = b.data.content;
981
- if (!rows.length) return "";
2098
+ if (!rows.length) return null;
982
2099
  const cells = (row, tag) => el(
983
2100
  "tr",
984
2101
  {},
985
- row.map((cell2) => el(tag, tag === "th" ? { scope: "col" } : {}, inlineToHtml(cell2, o))).join("")
2102
+ row.map((cell2) => el(tag, tag === "th" ? { scope: "col" } : {}, inlineToNodes(cell2, o)))
986
2103
  );
987
- const head = b.data.withHeadings ? el("thead", {}, cells(rows[0], "th")) : "";
988
- const body = (b.data.withHeadings ? rows.slice(1) : rows).map((row) => cells(row, "td")).join("");
2104
+ const head = b.data.withHeadings ? el("thead", {}, cells(rows[0], "th")) : null;
2105
+ const body = (b.data.withHeadings ? rows.slice(1) : rows).map((row) => cells(row, "td"));
989
2106
  return el(
990
2107
  "table",
991
2108
  { class: classes(["mex-table", ...b.data.stretched ? ["mex-stretched"] : []], b.tunes) },
992
- head + (body ? el("tbody", {}, body) : "")
2109
+ [head, body.length ? el("tbody", {}, body) : null]
993
2110
  );
994
2111
  },
995
2112
  image: (b, o) => {
996
2113
  const file = resolveMedia(b.data.file, b, o);
997
- if (!file.url) return "";
998
- const decorative = b.raw.decorative === true;
999
- const candidates = imageCandidates(file);
1000
- const img = {
1001
- alt: decorative ? "" : file.alt || "",
1002
- width: Number.isInteger(file.width) && file.width > 0 ? file.width : void 0,
1003
- height: Number.isInteger(file.height) && file.height > 0 ? file.height : void 0
1004
- };
1005
- if (candidates.length > 1) {
1006
- img.srcset = candidates.map((c) => `${c.url} ${c.width}w`).join(", ");
1007
- img.sizes = typeof o.imageSizes === "string" && /^[\w\s(),.:%-]{1,200}$/.test(o.imageSizes) ? o.imageSizes : "100vw";
1008
- }
2114
+ if (!file.url) return null;
2115
+ const img = libraryImageAttrs(file, b.raw.decorative === true, o);
1009
2116
  const cls = ["mex-image"];
1010
2117
  if (b.data.withBorder) cls.push("mex-image-border");
1011
2118
  if (b.data.withBackground) cls.push("mex-image-background");
1012
2119
  if (b.data.stretched) cls.push("mex-stretched");
1013
- return figure(file.url, img, inlineToHtml(b.data.caption, o), classes(cls, b.tunes));
2120
+ const node = figure(file.url, img, inlineToNodes(b.data.caption, o), classes(cls, b.tunes));
2121
+ withFocalPoint(node.children[0], b.data.focalPoint, o);
2122
+ return node;
1014
2123
  },
1015
2124
  simpleImage: (b, o) => {
1016
- if (!b.data.url) return "";
2125
+ if (!b.data.url) return null;
1017
2126
  const cls = ["mex-image"];
1018
2127
  if (b.data.withBorder) cls.push("mex-image-border");
1019
2128
  if (b.data.withBackground) cls.push("mex-image-background");
@@ -1023,44 +2132,82 @@ var RENDERERS = {
1023
2132
  {
1024
2133
  alt: b.data.decorative === true ? "" : typeof b.data.alt === "string" && b.data.alt.trim() ? b.data.alt : inlineToText(b.data.caption)
1025
2134
  },
1026
- inlineToHtml(b.data.caption, o),
2135
+ inlineToNodes(b.data.caption, o),
1027
2136
  classes(cls, b.tunes)
1028
2137
  );
1029
2138
  },
2139
+ gallery: (b, o) => {
2140
+ const items = b.data.images.map((image) => {
2141
+ const file = resolveMedia(image.file, b, o);
2142
+ if (!file.url) return null;
2143
+ const caption2 = inlineToNodes(image.caption, o);
2144
+ const img = el("img", {
2145
+ src: file.url,
2146
+ ...libraryImageAttrs(file, image.decorative === true, o),
2147
+ loading: "lazy",
2148
+ decoding: "async"
2149
+ });
2150
+ withFocalPoint(img, image.focalPoint, o);
2151
+ return el(
2152
+ "li",
2153
+ { class: "mex-gallery-item" },
2154
+ el("figure", { class: "mex-gallery-figure" }, [
2155
+ img,
2156
+ caption2.length ? el("figcaption", {}, caption2) : null
2157
+ ])
2158
+ );
2159
+ }).filter(Boolean);
2160
+ if (!items.length) return null;
2161
+ const { layout, columns } = b.data;
2162
+ const caption = inlineToNodes(b.data.caption, o);
2163
+ return el(
2164
+ "figure",
2165
+ {
2166
+ class: classes(["mex-gallery", `mex-gallery-${layout}`, `mex-gallery-cols-${columns}`], b.tunes),
2167
+ "data-mex-layout": layout,
2168
+ "data-mex-columns": String(columns)
2169
+ },
2170
+ [el("ul", { class: "mex-gallery-items" }, items), caption.length ? el("figcaption", {}, caption) : null]
2171
+ );
2172
+ },
2173
+ video: (b, o) => mediaFigure("video", b, o),
2174
+ audio: (b, o) => mediaFigure("audio", b, o),
1030
2175
  linkTool: (b) => {
1031
- if (!b.data.link) return "";
2176
+ if (!b.data.link) return null;
1032
2177
  const meta = b.data.meta;
1033
- const image = meta.image && meta.image.url ? el("img", { class: "mex-link-image", src: meta.image.url, alt: "", loading: "lazy" }) : "";
1034
- 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)) : "");
1035
2178
  return el(
1036
2179
  "div",
1037
2180
  { class: classes(["mex-link-preview"], b.tunes) },
1038
- el("a", { href: b.data.link, rel: "nofollow noopener noreferrer" }, inner)
2181
+ el("a", { href: b.data.link, rel: "nofollow noopener noreferrer" }, [
2182
+ meta.image && meta.image.url ? el("img", { class: "mex-link-image", src: meta.image.url, alt: "", loading: "lazy" }) : null,
2183
+ el("span", { class: "mex-link-title" }, meta.title || b.data.link),
2184
+ meta.description ? el("span", { class: "mex-link-description" }, meta.description) : null,
2185
+ meta.site_name ? el("span", { class: "mex-link-site" }, meta.site_name) : null
2186
+ ])
1039
2187
  );
1040
2188
  },
1041
2189
  attaches: (b) => {
1042
2190
  const file = b.data.file;
1043
- if (!file.url) return "";
1044
- const label = b.data.title || file.title || file.name || file.url;
2191
+ if (!file.url) return null;
2192
+ const text = b.data.title || file.title || file.name || file.url;
1045
2193
  const details = [file.extension ? file.extension.toUpperCase() : "", formatSize(file.size)].filter(Boolean).join(", ");
1046
- return el(
1047
- "p",
1048
- { class: classes(["mex-attachment"], b.tunes) },
1049
- el("a", { href: file.url, download: true }, escapeHtml2(label)) + (details ? ` ${el("span", { class: "mex-attachment-meta" }, `(${escapeHtml2(details)})`)}` : "")
1050
- );
2194
+ return el("p", { class: classes(["mex-attachment"], b.tunes) }, [
2195
+ el("a", { href: file.url, download: true }, text),
2196
+ details ? [" ", el("span", { class: "mex-attachment-meta" }, `(${details})`)] : null
2197
+ ]);
1051
2198
  },
1052
2199
  embed: (b, o) => {
1053
2200
  const hosts = Array.isArray(o.embedHosts) ? o.embedHosts.map((h) => String(h).toLowerCase()) : DEFAULT_EMBED_HOSTS;
1054
2201
  const frame = embedFrameUrl(b.data.embed, hosts);
1055
- const caption = inlineToHtml(b.data.caption, o);
2202
+ const caption = inlineToNodes(b.data.caption, o);
1056
2203
  const title = inlineToText(b.data.caption) || b.data.service || "Embedded content";
1057
2204
  if (!frame) {
1058
2205
  const href = b.data.source || b.data.embed;
1059
- if (!href) return "";
2206
+ if (!href) return null;
1060
2207
  return el(
1061
2208
  "p",
1062
2209
  { class: classes(["mex-embed", "mex-embed-link"], b.tunes) },
1063
- el("a", { href, rel: "nofollow noopener noreferrer" }, caption || escapeHtml2(href))
2210
+ el("a", { href, rel: "nofollow noopener noreferrer" }, caption.length ? caption : href)
1064
2211
  );
1065
2212
  }
1066
2213
  return el(
@@ -1071,9 +2218,8 @@ var RENDERERS = {
1071
2218
  b.tunes
1072
2219
  )
1073
2220
  },
1074
- el(
1075
- "iframe",
1076
- {
2221
+ [
2222
+ el("iframe", {
1077
2223
  src: frame,
1078
2224
  title,
1079
2225
  width: b.data.width,
@@ -1083,27 +2229,26 @@ var RENDERERS = {
1083
2229
  sandbox: "allow-scripts allow-same-origin allow-popups allow-presentation",
1084
2230
  allow: "fullscreen; picture-in-picture; encrypted-media",
1085
2231
  allowfullscreen: true
1086
- },
1087
- ""
1088
- ) + (caption ? el("figcaption", {}, caption) : "")
2232
+ }),
2233
+ caption.length ? el("figcaption", {}, caption) : null
2234
+ ]
1089
2235
  );
1090
2236
  },
1091
2237
  personality: (b) => {
1092
2238
  const d = b.data;
1093
- if (!d.name && !d.description) return "";
1094
- return el(
1095
- "div",
1096
- { class: classes(["mex-personality"], b.tunes) },
1097
- (d.photo ? el("img", { class: "mex-personality-photo", src: d.photo, alt: "", loading: "lazy" }) : "") + el(
1098
- "div",
1099
- { class: "mex-personality-body" },
1100
- (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)) : "")
1101
- )
1102
- );
2239
+ if (!d.name && !d.description) return null;
2240
+ return el("div", { class: classes(["mex-personality"], b.tunes) }, [
2241
+ d.photo ? el("img", { class: "mex-personality-photo", src: d.photo, alt: "", loading: "lazy" }) : null,
2242
+ el("div", { class: "mex-personality-body" }, [
2243
+ d.name ? el("p", { class: "mex-personality-name" }, d.name) : null,
2244
+ d.description ? el("p", { class: "mex-personality-description" }, d.description) : null,
2245
+ d.link ? el("a", { class: "mex-personality-link", href: d.link }, d.link) : null
2246
+ ])
2247
+ ]);
1103
2248
  },
1104
2249
  button: (b) => {
1105
2250
  const d = b.data;
1106
- if (!d.text) return "";
2251
+ if (!d.text) return null;
1107
2252
  const cls = `mex-button mex-button-${d.style}`;
1108
2253
  const inner = d.link ? el(
1109
2254
  "a",
@@ -1113,50 +2258,282 @@ var RENDERERS = {
1113
2258
  target: d.openInNewTab ? "_blank" : void 0,
1114
2259
  rel: d.openInNewTab ? "noopener noreferrer" : void 0
1115
2260
  },
1116
- escapeHtml2(d.text)
1117
- ) : el("span", { class: cls }, escapeHtml2(d.text));
2261
+ d.text
2262
+ ) : el("span", { class: cls }, d.text);
1118
2263
  return el("p", { class: classes(["mex-button-block"], b.tunes) }, inner);
1119
2264
  },
1120
- delimiter: (b) => el("hr", { class: classes(["mex-delimiter"], b.tunes) })
2265
+ delimiter: (b) => el("hr", { class: classes(["mex-delimiter"], b.tunes) }),
2266
+ toc: (b, o) => {
2267
+ const tree = buildTocTree(b.headings || [], b.data);
2268
+ if (!tree.length) return null;
2269
+ const tag = b.data.style === "ordered" ? "ol" : "ul";
2270
+ const list = (nodes) => el(
2271
+ tag,
2272
+ { class: "mex-toc-list" },
2273
+ nodes.map(
2274
+ (node) => el("li", { class: "mex-toc-item" }, [
2275
+ b.linkHeadings && node.id ? el("a", { href: `#${node.id}` }, node.text) : node.text,
2276
+ node.children.length ? list(node.children) : null
2277
+ ])
2278
+ )
2279
+ );
2280
+ const title = b.data.title.trim();
2281
+ return el(
2282
+ "nav",
2283
+ {
2284
+ class: classes(["mex-toc", `mex-toc-${b.data.style}`], b.tunes),
2285
+ "aria-label": title || tocLabel(o)
2286
+ },
2287
+ [title ? el("p", { class: "mex-toc-title" }, title) : null, list(tree)]
2288
+ );
2289
+ }
1121
2290
  };
1122
2291
  var neutral = (b) => el(
1123
2292
  "div",
1124
2293
  { class: classes(["mex-block", `mex-${b.type}`], b.tunes), "data-mex-block": b.type },
1125
2294
  scalarFields(b.data).map(
1126
- ([key, value]) => el("div", { class: "mex-field", "data-mex-field": key }, escapeHtml2(inlineToText(value)))
1127
- ).join("")
2295
+ ([key, value]) => el("div", { class: "mex-field", "data-mex-field": key }, inlineToText(value))
2296
+ )
1128
2297
  );
1129
- var helpersFor = (options, render) => ({
1130
- escape: escapeHtml2,
1131
- inline: (html) => inlineToHtml(html, options),
1132
- text: (html) => inlineToText(html),
1133
- url: (value, schemes) => sanitizeUrl(value, schemes ? { schemes } : void 0),
1134
- renderChildren: (blocks) => render(blocks)
1135
- });
1136
- var renderHtml = (value, options = {}) => {
2298
+ var registeredDefault = (b, o) => {
2299
+ const children = [];
2300
+ for (const [key, field] of Object.entries(b.definition.schema)) {
2301
+ const value = b.data[key];
2302
+ if (value === void 0 || value === null || value === "") continue;
2303
+ const attrs = { class: "mex-field", "data-mex-field": key };
2304
+ if (field.type === "inline") children.push(el("div", attrs, inlineToNodes(value, o)));
2305
+ else if (field.type === "url") children.push(el("div", attrs, el("a", { href: value }, value)));
2306
+ else if (["text", "enum", "number", "boolean"].includes(field.type))
2307
+ children.push(el("div", attrs, String(value)));
2308
+ }
2309
+ return el(
2310
+ "div",
2311
+ { class: classes(["mex-block", `mex-${b.type}`], b.tunes), "data-mex-block": b.type },
2312
+ children
2313
+ );
2314
+ };
2315
+ var DENIED_TAGS = /* @__PURE__ */ new Set([
2316
+ "script",
2317
+ "style",
2318
+ "base",
2319
+ "meta",
2320
+ "link",
2321
+ "head",
2322
+ "html",
2323
+ "body",
2324
+ "title",
2325
+ "object",
2326
+ "embed",
2327
+ "applet",
2328
+ "frame",
2329
+ "frameset",
2330
+ "template",
2331
+ "noscript",
2332
+ "noembed",
2333
+ "noframes",
2334
+ "svg",
2335
+ "math",
2336
+ "xmp",
2337
+ "plaintext",
2338
+ "form"
2339
+ ]);
2340
+ var URL_ATTRIBUTES = /* @__PURE__ */ new Set([
2341
+ "href",
2342
+ "src",
2343
+ "action",
2344
+ "formaction",
2345
+ "poster",
2346
+ "cite",
2347
+ "data",
2348
+ "background",
2349
+ "longdesc",
2350
+ "manifest",
2351
+ "ping",
2352
+ "xmlns"
2353
+ ]);
2354
+ var RESOURCE_ATTRIBUTES = /* @__PURE__ */ new Set(["src", "poster", "data", "background", "manifest", "ping"]);
2355
+ var cleanUrlAttribute = (name, value) => {
2356
+ if (name === "srcset" || name === "imagesrcset") {
2357
+ const parts = value.split(",").map((part) => part.trim());
2358
+ const clean = [];
2359
+ for (const part of parts) {
2360
+ const [url, descriptor, extra] = part.split(/\s+/);
2361
+ if (extra !== void 0 || descriptor && !/^\d+(?:\.\d+)?[wx]$/.test(descriptor)) return "";
2362
+ const safe = sanitizeUrl(url, { schemes: ["http", "https"] });
2363
+ if (!safe) return "";
2364
+ clean.push(descriptor ? `${safe} ${descriptor}` : safe);
2365
+ }
2366
+ return clean.join(", ");
2367
+ }
2368
+ return sanitizeUrl(value, { schemes: RESOURCE_ATTRIBUTES.has(name) ? ["http", "https"] : LINK_SCHEMES });
2369
+ };
2370
+ var MAX_OVERRIDE_DEPTH = 64;
2371
+ var MAX_OVERRIDE_NODES = 5e4;
2372
+ var cleanOverrideNodes = (input, trusted) => {
2373
+ let budget = MAX_OVERRIDE_NODES;
2374
+ const visit = (value, depth) => {
2375
+ const list = Array.isArray(value) ? value.flat(Infinity) : [value];
2376
+ const out = [];
2377
+ for (const node of list) {
2378
+ if (budget <= 0 || depth > MAX_OVERRIDE_DEPTH) break;
2379
+ if (typeof node === "string" || typeof node === "number") {
2380
+ if (node !== "") out.push(textNode(node));
2381
+ continue;
2382
+ }
2383
+ if (!isPlainObject2(node)) continue;
2384
+ if (trusted.has(node)) {
2385
+ out.push(node);
2386
+ continue;
2387
+ }
2388
+ budget -= 1;
2389
+ if (node.type === "text") {
2390
+ out.push(textNode(typeof node.value === "string" ? node.value : ""));
2391
+ continue;
2392
+ }
2393
+ if (node.type !== "element" || typeof node.tag !== "string") continue;
2394
+ const tag = node.tag;
2395
+ if (!TAG_NAME.test(tag) || DENIED_TAGS.has(tag)) continue;
2396
+ const attrs = {};
2397
+ for (const [name, raw] of Object.entries(isPlainObject2(node.attrs) ? node.attrs : {})) {
2398
+ if (!isSafeAttributeName(name)) continue;
2399
+ if (raw === true) {
2400
+ if (!URL_ATTRIBUTES.has(name)) attrs[name] = true;
2401
+ continue;
2402
+ }
2403
+ if (!["string", "number"].includes(typeof raw)) continue;
2404
+ const text = String(raw).slice(0, 1e4);
2405
+ if (URL_ATTRIBUTES.has(name) || name === "srcset" || name === "imagesrcset") {
2406
+ const url = cleanUrlAttribute(name, text);
2407
+ if (url) attrs[name] = url;
2408
+ } else if (text !== "" || name === "alt") attrs[name] = text;
2409
+ }
2410
+ if (tag === "iframe" && !attrs.src) continue;
2411
+ out.push({
2412
+ type: "element",
2413
+ tag,
2414
+ attrs,
2415
+ children: visit(Array.isArray(node.children) ? node.children : [], depth + 1)
2416
+ });
2417
+ }
2418
+ return out;
2419
+ };
2420
+ return visit(input, 0);
2421
+ };
2422
+ var rawAllowed = (options) => options.rawHtml === "allow" && typeof options.sanitizeRaw === "function";
2423
+ var createTreeBuilder = (value, options, mode = {}) => {
1137
2424
  const opts = options && typeof options === "object" ? options : {};
1138
- const render = (blocks) => blocks.map((block) => {
2425
+ const publicOf = /* @__PURE__ */ new WeakMap();
2426
+ const preparedOf = /* @__PURE__ */ new WeakMap();
2427
+ const trusted = /* @__PURE__ */ new WeakSet();
2428
+ const toPublic = (block) => {
2429
+ const known = publicOf.get(block);
2430
+ if (known) return known;
2431
+ const pub = {
2432
+ id: block.id,
2433
+ type: block.type,
2434
+ data: block.data,
2435
+ tunes: block.tunes,
2436
+ children: block.children.map(toPublic)
2437
+ };
2438
+ publicOf.set(block, pub);
2439
+ preparedOf.set(pub, block);
2440
+ return pub;
2441
+ };
2442
+ const blockContent = (block) => {
1139
2443
  const override = overrideFor(opts, block.type);
1140
2444
  if (override) {
1141
- const out = override(
1142
- {
1143
- id: block.id,
1144
- type: block.type,
1145
- data: block.data,
1146
- tunes: block.tunes,
1147
- children: block.children
1148
- },
1149
- helpersFor(opts, render)
1150
- );
1151
- if (typeof out === "string") return out;
2445
+ const out = override(toPublic(block), helpers);
2446
+ if (typeof out === "string") {
2447
+ if (mode.overrideHtml) return out ? [{ type: "raw", html: out }] : [];
2448
+ if (rawAllowed(opts)) {
2449
+ const html = opts.sanitizeRaw(out);
2450
+ return typeof html === "string" && html ? [el("div", { class: "mex-override", "data-mex-block": block.type }, { type: "raw", html })] : [];
2451
+ }
2452
+ } else if (out && typeof out === "object") {
2453
+ return cleanOverrideNodes(out, trusted);
2454
+ }
2455
+ }
2456
+ if (block.known) return toNodes(RENDERERS[block.type](block, opts, renderList));
2457
+ if (block.definition) return registeredContent(block);
2458
+ return [neutral(block)];
2459
+ };
2460
+ const registeredContent = (block) => {
2461
+ const render = block.definition.render;
2462
+ if (render) {
2463
+ let out;
2464
+ try {
2465
+ out = render(toPublic(block), helpers);
2466
+ } catch {
2467
+ out = void 0;
2468
+ }
2469
+ if (typeof out === "string") {
2470
+ if (rawAllowed(opts)) {
2471
+ const html = opts.sanitizeRaw(out);
2472
+ if (typeof html === "string" && html)
2473
+ return [
2474
+ el("div", { class: "mex-override", "data-mex-block": block.type }, { type: "raw", html })
2475
+ ];
2476
+ }
2477
+ } else if (out && typeof out === "object") {
2478
+ return cleanOverrideNodes(out, trusted);
2479
+ }
1152
2480
  }
1153
- if (block.known) return RENDERERS[block.type](block, opts, render);
1154
- return neutral(block);
1155
- }).filter(Boolean).join("\n");
1156
- return render(prepareBlocks(value, opts));
2481
+ return [registeredDefault(block, opts)];
2482
+ };
2483
+ function renderList(blocks) {
2484
+ const out = [];
2485
+ for (const block of blocks) {
2486
+ const children = blockContent(block);
2487
+ if (!children.length) continue;
2488
+ const node = { type: "block", block: toPublic(block), children };
2489
+ trusted.add(node);
2490
+ if (out.length) out.push(textNode("\n"));
2491
+ out.push(node);
2492
+ }
2493
+ return out;
2494
+ }
2495
+ const renderBlocks = (blocks) => renderList((Array.isArray(blocks) ? blocks : []).map((b) => preparedOf.get(b)).filter(Boolean));
2496
+ const helpers = {
2497
+ escape: escapeHtml,
2498
+ inline: (html) => inlineToHtml(html, opts),
2499
+ text: (html) => inlineToText(html),
2500
+ url: (input, schemes) => sanitizeUrl(input, schemes ? { schemes } : void 0),
2501
+ renderChildren: (blocks) => serializeNodes(renderBlocks(blocks)),
2502
+ h: (tag, attrs, children) => el(String(tag), attrs, children),
2503
+ textNode,
2504
+ inlineNodes: (html) => inlineToNodes(html, opts),
2505
+ childNodes: renderBlocks
2506
+ };
2507
+ const nodes = renderList(annotateHeadings(prepareBlocks(value, opts), opts));
2508
+ return { nodes, renderBlocks, helpers };
1157
2509
  };
2510
+ var flattenBlocks = (nodes) => {
2511
+ const out = [];
2512
+ for (const node of nodes) {
2513
+ if (node.type === "block") out.push(...flattenBlocks(node.children));
2514
+ else if (node.type === "element") {
2515
+ const element = {
2516
+ type: "element",
2517
+ tag: node.tag,
2518
+ attrs: node.attrs,
2519
+ children: flattenBlocks(node.children)
2520
+ };
2521
+ if (node.style) element.style = node.style;
2522
+ out.push(element);
2523
+ } else out.push(node);
2524
+ }
2525
+ return out;
2526
+ };
2527
+ var renderTree = (value, options) => flattenBlocks(createTreeBuilder(value, options).nodes);
2528
+
2529
+ // shared/render/html.mjs
2530
+ var renderHtml = (value, options = {}) => serializeNodes(createTreeBuilder(value, options, { overrideHtml: true }).nodes);
1158
2531
 
1159
2532
  // shared/render/text.mjs
2533
+ var tocLines = (nodes, ordered, depth) => nodes.flatMap((node, index) => [
2534
+ `${" ".repeat(depth)}${ordered ? `${index + 1}.` : "-"} ${node.text}`,
2535
+ ...tocLines(node.children, ordered, depth + 1)
2536
+ ]);
1160
2537
  var listLines = (items, style, start, depth) => {
1161
2538
  const lines = [];
1162
2539
  items.forEach((item, index) => {
@@ -1174,6 +2551,11 @@ ${indent} `);
1174
2551
  return lines;
1175
2552
  };
1176
2553
  var t = (html) => inlineToText(html).trim();
2554
+ var mediaText = (b) => {
2555
+ if (!b.data.file.url) return "";
2556
+ const parts = [b.data.title.trim(), t(b.data.caption)].filter(Boolean);
2557
+ return parts.length ? parts.join("\n") : b.data.file.url;
2558
+ };
1177
2559
  var RENDERERS2 = {
1178
2560
  paragraph: (b) => t(b.data.text),
1179
2561
  header: (b) => t(b.data.text),
@@ -1194,12 +2576,36 @@ var RENDERERS2 = {
1194
2576
  table: (b) => b.data.content.map((row) => row.map((cell2) => t(cell2).replace(/\s+/g, " ")).join(" ")).join("\n"),
1195
2577
  image: (b) => t(b.data.caption) || (b.raw.decorative === true ? "" : (b.data.file.alt || "").trim()),
1196
2578
  simpleImage: (b) => t(b.data.caption),
2579
+ gallery: (b) => [
2580
+ ...b.data.images.map(
2581
+ (image) => image.file.url ? t(image.caption) || (image.decorative ? "" : (image.file.alt || "").trim()) : ""
2582
+ ),
2583
+ t(b.data.caption)
2584
+ ].filter(Boolean).join("\n"),
2585
+ video: (b) => mediaText(b),
2586
+ audio: (b) => mediaText(b),
1197
2587
  linkTool: (b) => [b.data.meta.title, b.data.link].filter(Boolean).join("\n"),
1198
2588
  attaches: (b) => b.data.file.url ? b.data.title || b.data.file.title || b.data.file.name || b.data.file.url : "",
1199
2589
  embed: (b) => [t(b.data.caption), b.data.source || b.data.embed].filter(Boolean).join("\n"),
1200
2590
  personality: (b) => [b.data.name, b.data.description, b.data.link].filter(Boolean).join("\n"),
1201
2591
  button: (b) => b.data.link ? `${b.data.text} (${b.data.link})` : b.data.text,
1202
- delimiter: () => "---"
2592
+ delimiter: () => "---",
2593
+ toc: (b) => {
2594
+ const tree = buildTocTree(b.headings || [], b.data);
2595
+ if (!tree.length) return "";
2596
+ return [b.data.title.trim(), ...tocLines(tree, b.data.style === "ordered", 0)].filter(Boolean).join("\n");
2597
+ }
2598
+ };
2599
+ var registeredText = (block) => {
2600
+ const { definition } = block;
2601
+ if (definition.text) {
2602
+ try {
2603
+ const out = definition.text(block.data, { text: (html) => inlineToText(html) });
2604
+ if (typeof out === "string") return out;
2605
+ } catch {
2606
+ }
2607
+ }
2608
+ return definition.fields(block.data).map((field) => (field.kind === "html" ? inlineToText(field.value) : field.value).trim()).filter(Boolean).join("\n");
1203
2609
  };
1204
2610
  var renderText = (value, options = {}) => {
1205
2611
  const opts = options && typeof options === "object" ? options : {};
@@ -1219,9 +2625,10 @@ var renderText = (value, options = {}) => {
1219
2625
  if (typeof out === "string") return out;
1220
2626
  }
1221
2627
  if (block.known) return RENDERERS2[block.type](block, opts, render);
2628
+ if (block.definition) return registeredText(block);
1222
2629
  return scalarFields(block.data).map(([, v]) => inlineToText(v).trim()).filter(Boolean).join("\n");
1223
2630
  }).map((text) => String(text).replace(/\u00a0/g, " ")).filter((text) => text.trim() !== "").join("\n\n");
1224
- return render(prepareBlocks(value, opts));
2631
+ return render(annotateHeadings(prepareBlocks(value, opts), opts));
1225
2632
  };
1226
2633
 
1227
2634
  // shared/render/markdown.mjs
@@ -1371,6 +2778,19 @@ var RENDERERS3 = {
1371
2778
  const alt = b.data.decorative === true ? "" : escapeMarkdown(oneLine(text));
1372
2779
  return `![${alt}](${linkUrl(b.data.url)})`;
1373
2780
  },
2781
+ gallery: (b, o) => {
2782
+ const lines = b.data.images.map((image) => {
2783
+ const file = resolveMedia(image.file, b, o);
2784
+ if (!file.url) return "";
2785
+ const alt = image.decorative ? "" : escapeMarkdown(oneLine(file.alt || ""));
2786
+ return `![${alt}](${linkUrl(file.url)}${linkTitle(inlineToText(image.caption))})`;
2787
+ }).filter(Boolean);
2788
+ if (!lines.length) return "";
2789
+ const caption = oneLine(md(b.data.caption, o));
2790
+ return [lines.join("\n"), caption].filter(Boolean).join("\n\n");
2791
+ },
2792
+ video: (b, o) => mediaLink("video", b, o),
2793
+ audio: (b, o) => mediaLink("audio", b, o),
1374
2794
  linkTool: (b) => b.data.link ? `[${escapeMarkdown(b.data.meta.title || b.data.link)}](${linkUrl(b.data.link)})` : "",
1375
2795
  attaches: (b) => {
1376
2796
  const file = b.data.file;
@@ -1394,7 +2814,45 @@ var RENDERERS3 = {
1394
2814
  if (!b.data.text) return "";
1395
2815
  return b.data.link ? `[${escapeMarkdown(b.data.text)}](${linkUrl(b.data.link)})` : escapeMarkdown(b.data.text);
1396
2816
  },
1397
- delimiter: () => "---"
2817
+ delimiter: () => "---",
2818
+ toc: (b) => {
2819
+ const tree = buildTocTree(b.headings || [], b.data);
2820
+ if (!tree.length) return "";
2821
+ const ordered = b.data.style === "ordered";
2822
+ const lines = (nodes, indent) => nodes.flatMap((node, index) => {
2823
+ const marker = ordered ? `${index + 1}.` : "-";
2824
+ const text = escapeMarkdown(node.text);
2825
+ const entry = b.linkHeadings && node.slug ? `[${text}](#${linkUrl(node.slug)})` : text;
2826
+ return [
2827
+ `${indent}${marker} ${entry}`,
2828
+ ...lines(node.children, `${indent}${" ".repeat(marker.length + 1)}`)
2829
+ ];
2830
+ });
2831
+ const title = b.data.title.trim();
2832
+ return [title ? `**${escapeMarkdown(title)}**` : "", lines(tree, "").join("\n")].filter(Boolean).join("\n\n");
2833
+ }
2834
+ };
2835
+ function mediaLink(kind, b, o) {
2836
+ const file = resolveMedia(b.data.file, b, o, { mimePrefix: `${kind}/` });
2837
+ if (!file.url) return "";
2838
+ const caption = oneLine(md(b.data.caption, o));
2839
+ const link = `[${escapeMarkdown(oneLine(b.data.title || file.name || file.url))}](${linkUrl(file.url)})`;
2840
+ return [link, caption].filter(Boolean).join("\n\n");
2841
+ }
2842
+ var registeredMarkdown = (block, opts) => {
2843
+ const { definition } = block;
2844
+ if (definition.markdown) {
2845
+ try {
2846
+ const out = definition.markdown(block.data, {
2847
+ escape: escapeMarkdown,
2848
+ inline: (html) => md(html, opts),
2849
+ text: (html) => inlineToText(html)
2850
+ });
2851
+ if (typeof out === "string") return out;
2852
+ } catch {
2853
+ }
2854
+ }
2855
+ return definition.fields(block.data).map((field) => field.kind === "html" ? md(field.value, opts) : escapeMarkdown(field.value.trim())).filter(Boolean).join("\n\n");
1398
2856
  };
1399
2857
  var renderMarkdown = (value, options = {}) => {
1400
2858
  const opts = options && typeof options === "object" ? options : {};
@@ -1414,7 +2872,47 @@ var renderMarkdown = (value, options = {}) => {
1414
2872
  if (typeof out === "string") return out;
1415
2873
  }
1416
2874
  if (block.known) return RENDERERS3[block.type](block, opts, render);
2875
+ if (block.definition) return registeredMarkdown(block, opts);
1417
2876
  return scalarFields(block.data).map(([, v]) => md(v, opts)).filter(Boolean).join("\n\n");
1418
2877
  }).filter((text) => text && text.trim() !== "").join("\n\n");
1419
- return render(prepareBlocks(value, opts));
2878
+ return render(annotateHeadings(prepareBlocks(value, opts), opts));
2879
+ };
2880
+
2881
+ // shared/render/dom.mjs
2882
+ var copyText = async (text) => {
2883
+ try {
2884
+ if (typeof navigator === "undefined" || !navigator.clipboard || !navigator.clipboard.writeText)
2885
+ return false;
2886
+ await navigator.clipboard.writeText(text);
2887
+ return true;
2888
+ } catch {
2889
+ return false;
2890
+ }
2891
+ };
2892
+ var enhanceCodeBlocks = (root) => {
2893
+ const scope = root || (typeof document === "undefined" ? null : document);
2894
+ if (!scope || typeof scope.querySelectorAll !== "function") return () => {
2895
+ };
2896
+ const cleanups = [];
2897
+ for (const button of scope.querySelectorAll('[data-mex-code="copy"] button[data-mex-copy]')) {
2898
+ if (button.hasAttribute("data-mex-enhanced")) continue;
2899
+ const block = button.closest('[data-mex-code="copy"]');
2900
+ const code = block && block.querySelector("pre code");
2901
+ const status = block && block.querySelector('[role="status"]');
2902
+ if (!code) continue;
2903
+ const onClick = async () => {
2904
+ const ok = await copyText(code.textContent || "");
2905
+ if (status)
2906
+ status.textContent = ok ? button.getAttribute("data-mex-copied") || "Copied" : button.getAttribute("data-mex-failed") || "Copy failed";
2907
+ };
2908
+ button.addEventListener("click", onClick);
2909
+ button.setAttribute("data-mex-enhanced", "");
2910
+ cleanups.push(() => {
2911
+ button.removeEventListener("click", onClick);
2912
+ button.removeAttribute("data-mex-enhanced");
2913
+ });
2914
+ }
2915
+ return () => {
2916
+ for (const cleanup of cleanups) cleanup();
2917
+ };
1420
2918
  };