magic-editor-x 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/README.md +593 -142
  3. package/bin/magic-editor-x.mjs +190 -0
  4. package/dist/admin/{ConfigurationPage-CK2AbfGW.mjs → ConfigurationPage-BxLHIQdo.mjs} +450 -21
  5. package/dist/admin/{ConfigurationPage-CzsT_dO_.js → ConfigurationPage-C-UktL1x.js} +479 -50
  6. package/dist/admin/ConfirmAction-DuQwvRYi.mjs +125 -0
  7. package/dist/admin/ConfirmAction-zLuIFj8t.js +124 -0
  8. package/dist/admin/{CustomBlocksPage-CvLrsBds.js → CustomBlocksPage-CxcTfdOT.js} +135 -84
  9. package/dist/admin/{CustomBlocksPage-B2A8S5MV.mjs → CustomBlocksPage-D8aMbVXc.mjs} +92 -41
  10. package/dist/admin/DraftSync-BIA8cZgA.js +11 -0
  11. package/dist/admin/DraftSync-CUxOMG-E.mjs +12 -0
  12. package/dist/admin/TemplatesPage-Hn6gyu2l.js +993 -0
  13. package/dist/admin/TemplatesPage-jhYi6Zdf.mjs +993 -0
  14. package/dist/admin/de-1cFMs-4c.mjs +43 -0
  15. package/dist/admin/{de-CkUYGb7U.js → de-2Ie5jy7j.js} +86 -2
  16. package/dist/admin/de-B1X46JJZ.js +453 -0
  17. package/dist/admin/{de-rRIutpYJ.mjs → de-BMY2LBaa.mjs} +86 -2
  18. package/dist/admin/{de-Bt6pYIWi.mjs → de-BUS1hUw0.mjs} +145 -0
  19. package/dist/admin/{de-CVbi685U.js → de-C3AsGauQ.js} +145 -0
  20. package/dist/admin/de-DOiGaTNX.mjs +453 -0
  21. package/dist/admin/de-Dn8athM8.js +43 -0
  22. package/dist/admin/{en-DulOcmXb.js → en-Ah-Cw0Wd.js} +86 -2
  23. package/dist/admin/{en-BX362fTp.js → en-BkEjpC3i.js} +145 -0
  24. package/dist/admin/en-CDg_18Bt.js +453 -0
  25. package/dist/admin/en-CIZ5Ggod.js +43 -0
  26. package/dist/admin/en-CU6UzV4g.mjs +453 -0
  27. package/dist/admin/{en-Puup8TFi.mjs → en-CvFiqti2.mjs} +86 -2
  28. package/dist/admin/en-Dc9y-6n9.mjs +43 -0
  29. package/dist/admin/{en-B_HltUxZ.mjs → en-GCzgS9Aw.mjs} +145 -0
  30. package/dist/admin/es-BCpJmUEM.js +453 -0
  31. package/dist/admin/es-BmfffNM2.mjs +453 -0
  32. package/dist/admin/es-C4IRHV5d.js +43 -0
  33. package/dist/admin/{es-CHHEZi44.js → es-C4pEnDRv.js} +145 -0
  34. package/dist/admin/{es-BoQZC86B.js → es-Cr8JH85N.js} +86 -2
  35. package/dist/admin/es-D2Kw6E4N.mjs +43 -0
  36. package/dist/admin/{es-CrhwOq-5.mjs → es-DHBBZKl2.mjs} +145 -0
  37. package/dist/admin/{es-257SSB7f.mjs → es-DbKHZz5l.mjs} +86 -2
  38. package/dist/admin/fr-BOvvfEH7.mjs +43 -0
  39. package/dist/admin/{fr-B3SL0TBV.js → fr-C2aLSwEu.js} +145 -0
  40. package/dist/admin/{fr-C5rSdKU4.mjs → fr-DQJ_7aq5.mjs} +86 -2
  41. package/dist/admin/fr-DZd2XJP6.mjs +453 -0
  42. package/dist/admin/{fr-5djKfQ3s.mjs → fr-Dvq4xk2e.mjs} +145 -0
  43. package/dist/admin/{fr-HxFcPpv4.js → fr-OJ4VW1kh.js} +86 -2
  44. package/dist/admin/fr-ZcN0yM_2.js +453 -0
  45. package/dist/admin/fr-Zkb8vfjN.js +43 -0
  46. package/dist/admin/index-BHBRr562.js +1940 -0
  47. package/dist/admin/index-CQk1XeNb.mjs +1939 -0
  48. package/dist/admin/index-Cm-fFUhE.js +18908 -0
  49. package/dist/admin/index-XgfwqLfV.mjs +18873 -0
  50. package/dist/admin/index.js +1 -1
  51. package/dist/admin/index.mjs +2 -2
  52. package/dist/admin/pt-1IUyx6ae.js +43 -0
  53. package/dist/admin/{pt-D6UuEtPy.mjs → pt-BSLzA17U.mjs} +86 -2
  54. package/dist/admin/pt-C3UdeIpd.mjs +453 -0
  55. package/dist/admin/pt-CImqDnLB.js +453 -0
  56. package/dist/admin/{pt-BdnY2Cth.mjs → pt-CilDggGF.mjs} +145 -0
  57. package/dist/admin/{pt-Cjn2Sc9k.js → pt-D0I0_JYs.js} +86 -2
  58. package/dist/admin/{pt-EVwCuBUK.js → pt-DX0OAIoL.js} +145 -0
  59. package/dist/admin/pt-etwsg3G4.mjs +43 -0
  60. package/dist/admin/useBreakpoint-D30eNTkF.js +37 -0
  61. package/dist/admin/useBreakpoint-DCfn6pDG.mjs +38 -0
  62. package/dist/admin/useT-CmaeZbCr.mjs +65 -0
  63. package/dist/admin/{useT-91ruePzq.js → useT-D3sM9Zf7.js} +4 -70
  64. package/dist/blocks/index.d.mts +167 -0
  65. package/dist/blocks/index.d.ts +167 -0
  66. package/dist/blocks/index.js +631 -0
  67. package/dist/blocks/index.mjs +609 -0
  68. package/dist/react/index.d.mts +39 -0
  69. package/dist/react/index.d.ts +39 -0
  70. package/dist/react/index.js +2687 -0
  71. package/dist/react/index.mjs +2657 -0
  72. package/dist/render/index.d.mts +201 -0
  73. package/dist/render/index.d.ts +201 -0
  74. package/dist/render/index.js +2918 -0
  75. package/dist/render/index.mjs +2896 -0
  76. package/dist/server/index.js +19400 -4738
  77. package/dist/server/index.mjs +19403 -4741
  78. package/dist/vue/index.d.mts +41 -0
  79. package/dist/vue/index.d.ts +41 -0
  80. package/dist/vue/index.js +2630 -0
  81. package/dist/vue/index.mjs +2610 -0
  82. package/package.json +49 -8
  83. package/schema/magic-editor-x.schema.json +1506 -0
  84. package/types/blocks.d.ts +167 -0
  85. package/types/index.d.ts +338 -0
  86. package/types/react.d.ts +39 -0
  87. package/types/render.d.ts +201 -0
  88. package/types/vue.d.ts +41 -0
  89. package/dist/admin/EditorField-7YCdXx-v.mjs +0 -6829
  90. package/dist/admin/EditorField-BdBCW15Q.js +0 -6864
  91. package/dist/admin/api-CmccMxlN.js +0 -36
  92. package/dist/admin/api-D5CAH0nh.mjs +0 -37
  93. package/dist/admin/de-BHPyA2S-.mjs +0 -103
  94. package/dist/admin/de-DBR893G4.js +0 -13
  95. package/dist/admin/de-RMs-_SCK.js +0 -103
  96. package/dist/admin/de-fBFh09Wl.mjs +0 -13
  97. package/dist/admin/en-BluCStLw.mjs +0 -103
  98. package/dist/admin/en-C81faOHP.js +0 -103
  99. package/dist/admin/en-D9Nfccux.mjs +0 -13
  100. package/dist/admin/en-gueRT44P.js +0 -13
  101. package/dist/admin/es-B0Zy8DVg.mjs +0 -13
  102. package/dist/admin/es-CQRI2Prp.mjs +0 -103
  103. package/dist/admin/es-D1QzY0JW.js +0 -103
  104. package/dist/admin/es-DRGs7meF.js +0 -13
  105. package/dist/admin/fr-B8rdLAIL.js +0 -13
  106. package/dist/admin/fr-Di3R6gOX.mjs +0 -103
  107. package/dist/admin/fr-R3_MbzT5.js +0 -103
  108. package/dist/admin/fr-oiUb2bb_.mjs +0 -13
  109. package/dist/admin/index-0_b1iroK.mjs +0 -156
  110. package/dist/admin/index-6SZLli70.js +0 -155
  111. package/dist/admin/pt-B3Jce6uT.mjs +0 -13
  112. package/dist/admin/pt-BCW1u_Hp.js +0 -103
  113. package/dist/admin/pt-BiWuSBcH.js +0 -13
  114. package/dist/admin/pt-Cr9AL408.mjs +0 -103
  115. package/dist/admin/sanitize-DP5aeU7V.js +0 -597
  116. package/dist/admin/sanitize-jjCot5PM.mjs +0 -596
  117. package/dist/admin/useT-vgY88N_H.mjs +0 -131
@@ -0,0 +1,2918 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // shared/render/index.mjs
20
+ var index_exports = {};
21
+ __export(index_exports, {
22
+ DEFAULT_EMBED_HOSTS: () => DEFAULT_EMBED_HOSTS,
23
+ copyText: () => copyText,
24
+ enhanceCodeBlocks: () => enhanceCodeBlocks,
25
+ escapeHtml: () => escapeHtml,
26
+ escapeMarkdown: () => escapeMarkdown,
27
+ inlineToHtml: () => inlineToHtml,
28
+ inlineToText: () => inlineToText,
29
+ renderHtml: () => renderHtml,
30
+ renderMarkdown: () => renderMarkdown,
31
+ renderText: () => renderText,
32
+ renderTree: () => renderTree,
33
+ serializeNodes: () => serializeNodes
34
+ });
35
+ module.exports = __toCommonJS(index_exports);
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
+
152
+ // shared/editor-data.mjs
153
+ var EDITOR_DATA_LIMITS = Object.freeze({
154
+ maxBlocks: 5e3,
155
+ maxBytes: 5 * 1024 * 1024,
156
+ maxDepth: 24,
157
+ maxBlockIdLength: 64,
158
+ maxTypeLength: 64
159
+ });
160
+ var FORBIDDEN_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
161
+ var BLOCK_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
162
+ var BLOCK_TYPE_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
163
+ var isPlainObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
164
+ var EditorDataError = class extends Error {
165
+ /**
166
+ * @param {string} message - Fixed, non-sensitive message.
167
+ * @param {string} code - Machine-readable reason.
168
+ */
169
+ constructor(message, code) {
170
+ super(message);
171
+ this.name = "EditorDataError";
172
+ this.code = code;
173
+ }
174
+ };
175
+ var cloneJsonSafe = (value, depth = 0) => {
176
+ if (depth > EDITOR_DATA_LIMITS.maxDepth) {
177
+ throw new EditorDataError("Editor content is nested too deeply", "TOO_DEEP");
178
+ }
179
+ if (value === null) return null;
180
+ if (Array.isArray(value)) {
181
+ const out = [];
182
+ for (const item of value) {
183
+ const cloned = cloneJsonSafe(item, depth + 1);
184
+ out.push(cloned === void 0 ? null : cloned);
185
+ }
186
+ return out;
187
+ }
188
+ switch (typeof value) {
189
+ case "string":
190
+ case "boolean":
191
+ return value;
192
+ case "number":
193
+ return Number.isFinite(value) ? value : null;
194
+ case "object": {
195
+ const out = {};
196
+ for (const key of Object.keys(value)) {
197
+ if (FORBIDDEN_KEYS.has(key)) continue;
198
+ const cloned = cloneJsonSafe(value[key], depth + 1);
199
+ if (cloned !== void 0) out[key] = cloned;
200
+ }
201
+ return out;
202
+ }
203
+ default:
204
+ return void 0;
205
+ }
206
+ };
207
+ var tryParseJson = (text) => {
208
+ try {
209
+ return { ok: true, value: JSON.parse(text) };
210
+ } catch {
211
+ return { ok: false };
212
+ }
213
+ };
214
+ var escapeHtml2 = (text) => String(text).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
215
+ var hashString = (text) => {
216
+ let hash = 2166136261;
217
+ for (let i = 0; i < text.length; i += 1) {
218
+ hash ^= text.charCodeAt(i);
219
+ hash = Math.imul(hash, 16777619) >>> 0;
220
+ }
221
+ return hash.toString(16).padStart(8, "0");
222
+ };
223
+ var legacyBlockId = (index, type, data) => `mx${hashString(`${index}:${type}:${JSON.stringify(data)}`)}${index}`;
224
+ var textToBlocks = (text) => {
225
+ const trimmed = text.trim();
226
+ if (!trimmed) return [];
227
+ const looksLikeHtml = /<\/?[a-z][^>]{0,200}>/i.test(trimmed.slice(0, 2e3));
228
+ if (looksLikeHtml) {
229
+ return [{ type: "paragraph", data: { text: trimmed } }];
230
+ }
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>") } }));
232
+ };
233
+ var unwrapValue = (value) => {
234
+ let current = value;
235
+ let legacy = false;
236
+ for (let i = 0; i < 3 && typeof current === "string"; i += 1) {
237
+ const text = current.trim();
238
+ if (!text) return { candidate: null, legacy: true };
239
+ if (text.startsWith("{") || text.startsWith("[") || text.startsWith('"')) {
240
+ const parsed = tryParseJson(text);
241
+ if (parsed.ok) {
242
+ current = parsed.value;
243
+ legacy = true;
244
+ continue;
245
+ }
246
+ }
247
+ return { candidate: { blocks: textToBlocks(text) }, legacy: true };
248
+ }
249
+ if (Array.isArray(current)) {
250
+ return { candidate: { blocks: current }, legacy: true };
251
+ }
252
+ return { candidate: current, legacy };
253
+ };
254
+ var normalizeEditorData = (value) => {
255
+ if (value === null || value === void 0) return null;
256
+ if (typeof value === "string" && value.length > EDITOR_DATA_LIMITS.maxBytes) {
257
+ throw new EditorDataError("Editor content exceeds the size limit", "TOO_LARGE");
258
+ }
259
+ const { candidate } = unwrapValue(value);
260
+ if (candidate === null || candidate === void 0) return null;
261
+ if (!isPlainObject2(candidate)) {
262
+ throw new EditorDataError("Editor content must be an Editor.js object", "INVALID_SHAPE");
263
+ }
264
+ const clean = cloneJsonSafe(candidate);
265
+ const rawBlocks = Array.isArray(clean.blocks) ? clean.blocks : [];
266
+ if (rawBlocks.length > EDITOR_DATA_LIMITS.maxBlocks) {
267
+ throw new EditorDataError("Editor content has too many blocks", "TOO_MANY_BLOCKS");
268
+ }
269
+ const seen = /* @__PURE__ */ new Set();
270
+ const blocks = [];
271
+ rawBlocks.forEach((block, index) => {
272
+ if (!isPlainObject2(block)) return;
273
+ const type = typeof block.type === "string" ? block.type.trim() : "";
274
+ if (!BLOCK_TYPE_PATTERN.test(type)) return;
275
+ const data = isPlainObject2(block.data) ? block.data : {};
276
+ let id = typeof block.id === "string" && BLOCK_ID_PATTERN.test(block.id) ? block.id : "";
277
+ if (!id || seen.has(id)) id = legacyBlockId(index, type, data);
278
+ while (seen.has(id)) id = `${id}x`;
279
+ seen.add(id);
280
+ const normalized = { id, type, data };
281
+ if (isPlainObject2(block.tunes) && Object.keys(block.tunes).length > 0) normalized.tunes = block.tunes;
282
+ blocks.push(normalized);
283
+ });
284
+ const time = Number.isFinite(clean.time) && clean.time > 0 ? Math.floor(clean.time) : 0;
285
+ const version = typeof clean.version === "string" && clean.version.length <= 32 ? clean.version : "2.31.7";
286
+ const result = { time, blocks, version };
287
+ const size = byteLength(JSON.stringify(result));
288
+ if (size > EDITOR_DATA_LIMITS.maxBytes) {
289
+ throw new EditorDataError("Editor content exceeds the size limit", "TOO_LARGE");
290
+ }
291
+ return result;
292
+ };
293
+ var normalizeEditorDataSafe = (value) => {
294
+ try {
295
+ return normalizeEditorData(value);
296
+ } catch {
297
+ return null;
298
+ }
299
+ };
300
+ var byteLength = (text) => {
301
+ let bytes = 0;
302
+ for (let i = 0; i < text.length; i += 1) {
303
+ const code = text.charCodeAt(i);
304
+ if (code < 128) bytes += 1;
305
+ else if (code < 2048) bytes += 2;
306
+ else if (code >= 55296 && code <= 56319) {
307
+ bytes += 4;
308
+ i += 1;
309
+ } else bytes += 3;
310
+ }
311
+ return bytes;
312
+ };
313
+
314
+ // shared/sanitize-policy.mjs
315
+ var INLINE_TAGS = Object.freeze([
316
+ "b",
317
+ "strong",
318
+ "i",
319
+ "em",
320
+ "u",
321
+ "s",
322
+ "mark",
323
+ "code",
324
+ "a",
325
+ "br",
326
+ "span",
327
+ "sub",
328
+ "sup"
329
+ ]);
330
+ var INTERNAL_LINK_ATTRIBUTES = Object.freeze([
331
+ "data-mex-uid",
332
+ "data-mex-document-id",
333
+ "data-mex-locale",
334
+ "data-mex-mention"
335
+ ]);
336
+ var INTERNAL_LINK_RULES = Object.freeze({
337
+ "data-mex-uid": /^api::[a-z0-9-]{1,60}\.[a-z0-9-]{1,60}$/,
338
+ "data-mex-document-id": /^[a-z0-9]{1,64}$/,
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)$/
342
+ });
343
+ var cleanInternalLinkAttributes = (attribs) => {
344
+ const out = {};
345
+ if (!attribs || typeof attribs !== "object") return out;
346
+ for (const name of INTERNAL_LINK_ATTRIBUTES) {
347
+ const value = attribs[name];
348
+ if (typeof value === "string" && INTERNAL_LINK_RULES[name].test(value)) out[name] = value;
349
+ }
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";
352
+ return out;
353
+ };
354
+ var isMentionLink = (attrs) => Boolean(
355
+ attrs && attrs["data-mex-mention"] === "true" && attrs["data-mex-uid"] && attrs["data-mex-document-id"]
356
+ );
357
+ var INLINE_ATTRIBUTES = Object.freeze({
358
+ a: ["href", "target", "rel", "title", ...INTERNAL_LINK_ATTRIBUTES],
359
+ span: ["class", "data-tooltip"],
360
+ mark: ["class"],
361
+ u: ["class"],
362
+ s: ["class"],
363
+ code: ["class"]
364
+ });
365
+ var INLINE_CLASSES = Object.freeze({
366
+ span: ["cdx-tooltip"],
367
+ mark: ["cdx-marker"],
368
+ u: ["cdx-underline"],
369
+ s: ["cdx-strikethrough", "cdx-strikethroughs"],
370
+ code: ["inline-code"]
371
+ });
372
+ var LINK_SCHEMES = Object.freeze(["http", "https", "mailto", "tel"]);
373
+ var MAX_URL_LENGTH = 2048;
374
+ var TARGETS = /* @__PURE__ */ new Set(["_blank", "_self", "_parent", "_top"]);
375
+ var sanitizeUrl = (value, options = {}) => {
376
+ const schemes = options.schemes || LINK_SCHEMES;
377
+ const allowRelative = options.allowRelative !== false;
378
+ if (typeof value !== "string") return "";
379
+ const url = value.trim();
380
+ if (!url || url.length > MAX_URL_LENGTH) return "";
381
+ if (/[\u0000-\u001f\u007f\s]/.test(url) && !/^(mailto|tel):/i.test(url)) return "";
382
+ if (url.startsWith("//") || url.startsWith("\\")) return "";
383
+ const scheme = /^([a-zA-Z][a-zA-Z0-9+.-]{0,20}):/.exec(url);
384
+ if (!scheme) {
385
+ return allowRelative && /^[/#?.]/.test(url) ? url : "";
386
+ }
387
+ if (!schemes.includes(scheme[1].toLowerCase())) return "";
388
+ if (scheme[1].toLowerCase().startsWith("http")) {
389
+ try {
390
+ const parsed = new URL(url);
391
+ if (parsed.username || parsed.password) return "";
392
+ } catch {
393
+ return "";
394
+ }
395
+ }
396
+ return url;
397
+ };
398
+ var plain = (value, max = 1e5) => typeof value === "string" ? value.slice(0, max) : "";
399
+ var oneOf = (value, allowed, fallback) => typeof value === "string" && allowed.includes(value) ? value : fallback;
400
+ var int = (value, min, max, fallback) => {
401
+ const number = typeof value === "string" ? Number(value) : value;
402
+ return Number.isInteger(number) && number >= min && number <= max ? number : fallback;
403
+ };
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
+ };
456
+ var generic = (value, inline, depth = 0, key = "") => {
457
+ if (depth > 20) return null;
458
+ if (typeof value === "string") {
459
+ if (/^(url|href|link|src|photo|source|embed)$/i.test(key)) return sanitizeUrl(value);
460
+ return inline(value);
461
+ }
462
+ if (Array.isArray(value)) return value.map((item) => generic(item, inline, depth + 1, key));
463
+ if (isPlainObject2(value)) {
464
+ const out = {};
465
+ for (const [childKey, child] of Object.entries(value))
466
+ out[childKey] = generic(child, inline, depth + 1, childKey);
467
+ return out;
468
+ }
469
+ return value;
470
+ };
471
+ var listItems = (items, inline, depth = 0) => {
472
+ if (!Array.isArray(items) || depth > 12) return [];
473
+ return items.map((item) => {
474
+ if (typeof item === "string") return inline(item);
475
+ if (!isPlainObject2(item)) return { content: "", items: [] };
476
+ const out = { content: inline(typeof item.content === "string" ? item.content : plain(item.text)) };
477
+ if (isPlainObject2(item.meta)) {
478
+ const meta = {};
479
+ if (typeof item.meta.checked === "boolean") meta.checked = item.meta.checked;
480
+ const start = int(item.meta.start, 0, 1e5, void 0);
481
+ if (start !== void 0) meta.start = start;
482
+ if (typeof item.meta.counterType === "string") {
483
+ meta.counterType = oneOf(
484
+ item.meta.counterType,
485
+ ["numeric", "lower-roman", "upper-roman", "lower-alpha", "upper-alpha"],
486
+ "numeric"
487
+ );
488
+ }
489
+ out.meta = meta;
490
+ }
491
+ out.items = listItems(item.items, inline, depth + 1);
492
+ return out;
493
+ });
494
+ };
495
+ var BLOCK_POLICIES = {
496
+ paragraph: (d, inline) => ({ text: inline(d.text) }),
497
+ header: (d, inline) => ({ text: inline(d.text), level: int(d.level, 1, 6, 2) }),
498
+ quote: (d, inline) => ({
499
+ text: inline(d.text),
500
+ caption: inline(d.caption),
501
+ alignment: oneOf(d.alignment, ["left", "center"], "left")
502
+ }),
503
+ list: (d, inline) => {
504
+ const out = {
505
+ style: oneOf(d.style, ["ordered", "unordered", "checklist"], "unordered"),
506
+ items: listItems(d.items, inline)
507
+ };
508
+ if (isPlainObject2(d.meta)) {
509
+ const meta = {};
510
+ const start = int(d.meta.start, 0, 1e5, void 0);
511
+ if (start !== void 0) meta.start = start;
512
+ if (typeof d.meta.counterType === "string") {
513
+ meta.counterType = oneOf(
514
+ d.meta.counterType,
515
+ ["numeric", "lower-roman", "upper-roman", "lower-alpha", "upper-alpha"],
516
+ "numeric"
517
+ );
518
+ }
519
+ out.meta = meta;
520
+ }
521
+ return out;
522
+ },
523
+ checklist: (d, inline) => ({
524
+ items: Array.isArray(d.items) ? d.items.filter(isPlainObject2).map((item) => ({ text: inline(item.text), checked: bool(item.checked) })) : []
525
+ }),
526
+ warning: (d, inline) => ({ title: inline(d.title), message: inline(d.message) }),
527
+ alert: (d, inline) => ({
528
+ type: oneOf(
529
+ d.type,
530
+ ["primary", "secondary", "info", "success", "warning", "danger", "light", "dark"],
531
+ "info"
532
+ ),
533
+ align: oneOf(d.align, ["left", "center", "right"], "left"),
534
+ message: inline(d.message)
535
+ }),
536
+ toggle: (d, inline) => ({
537
+ text: inline(d.text),
538
+ status: oneOf(d.status, ["open", "closed"], "open"),
539
+ fk: typeof d.fk === "string" ? d.fk.slice(0, 64) : void 0,
540
+ items: int(d.items, 0, 5e3, 0)
541
+ }),
542
+ code: (d) => ({ code: plain(d.code, 5e5) }),
543
+ codeFlask: (d) => {
544
+ const out = {
545
+ code: plain(d.code, 5e5),
546
+ language: typeof d.language === "string" && /^[a-z0-9+#-]{1,32}$/i.test(d.language) ? d.language : "plaintext"
547
+ };
548
+ if (typeof d.showlinenumbers === "boolean") out.showlinenumbers = d.showlinenumbers;
549
+ return out;
550
+ },
551
+ raw: (d, _inline, ctx) => {
552
+ const html = plain(d.html, 5e5);
553
+ if (ctx.rawHtml === "allow") return { html };
554
+ if (ctx.rawHtml === "disable") return { html: "" };
555
+ return { html: ctx.rawSanitizer(html) };
556
+ },
557
+ table: (d, inline) => ({
558
+ withHeadings: bool(d.withHeadings),
559
+ stretched: bool(d.stretched),
560
+ content: Array.isArray(d.content) ? d.content.slice(0, 500).map((row) => Array.isArray(row) ? row.slice(0, 100).map((cell2) => inline(cell2)) : []) : []
561
+ }),
562
+ image: (d, inline) => {
563
+ const file = isPlainObject2(d.file) ? d.file : {};
564
+ const cleanFile = { url: sanitizeUrl(file.url, { schemes: ["http", "https"] }) };
565
+ for (const key of ["mime", "alt", "name", "hash", "ext"])
566
+ if (typeof file[key] === "string") cleanFile[key] = plain(file[key], 500);
567
+ for (const key of ["width", "height", "size"]) if (Number.isFinite(file[key])) cleanFile[key] = file[key];
568
+ if (isPlainObject2(file.formats))
569
+ cleanFile.formats = generic(file.formats, (s) => plain(s, 2048), 0, "formats");
570
+ if (file.id !== void 0 && (Number.isInteger(file.id) || typeof file.id === "string"))
571
+ cleanFile.id = file.id;
572
+ if (typeof file.documentId === "string") cleanFile.documentId = plain(file.documentId, 64);
573
+ const out = {
574
+ file: cleanFile,
575
+ caption: inline(d.caption),
576
+ withBorder: bool(d.withBorder),
577
+ withBackground: bool(d.withBackground),
578
+ stretched: bool(d.stretched)
579
+ };
580
+ if (d.decorative === true) out.decorative = true;
581
+ const focalPoint = cleanFocalPoint(d.focalPoint);
582
+ if (focalPoint) out.focalPoint = focalPoint;
583
+ return out;
584
+ },
585
+ simpleImage: (d, inline) => {
586
+ const out = {
587
+ url: sanitizeUrl(d.url, { schemes: ["http", "https"] }),
588
+ caption: inline(d.caption),
589
+ withBorder: bool(d.withBorder),
590
+ withBackground: bool(d.withBackground),
591
+ stretched: bool(d.stretched)
592
+ };
593
+ if (typeof d.alt === "string") out.alt = plain(d.alt, 500);
594
+ if (d.decorative === true) out.decorative = true;
595
+ return out;
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
+ }),
642
+ linkTool: (d) => {
643
+ const meta = isPlainObject2(d.meta) ? d.meta : {};
644
+ const image = isPlainObject2(meta.image) ? { url: sanitizeUrl(meta.image.url, { schemes: ["http", "https"] }) } : void 0;
645
+ const cleanMeta = { title: plain(meta.title, 500), description: plain(meta.description, 2e3) };
646
+ if (typeof meta.site_name === "string") cleanMeta.site_name = plain(meta.site_name, 200);
647
+ if (image && image.url) cleanMeta.image = image;
648
+ return { link: sanitizeUrl(d.link, { schemes: ["http", "https"] }), meta: cleanMeta };
649
+ },
650
+ attaches: (d) => {
651
+ const file = isPlainObject2(d.file) ? d.file : {};
652
+ const cleanFile = { url: sanitizeUrl(file.url, { schemes: ["http", "https"] }) };
653
+ if (typeof file.name === "string") cleanFile.name = plain(file.name, 255);
654
+ if (typeof file.extension === "string") cleanFile.extension = plain(file.extension, 16);
655
+ if (Number.isFinite(file.size)) cleanFile.size = file.size;
656
+ if (typeof file.title === "string") cleanFile.title = plain(file.title, 255);
657
+ return { file: cleanFile, title: plain(d.title, 255) };
658
+ },
659
+ embed: (d, inline) => ({
660
+ service: typeof d.service === "string" && /^[a-z0-9_-]{1,40}$/i.test(d.service) ? d.service : "",
661
+ source: sanitizeUrl(d.source, { schemes: ["https", "http"], allowRelative: false }),
662
+ embed: sanitizeUrl(d.embed, { schemes: ["https"], allowRelative: false }),
663
+ width: int(d.width, 1, 1e4, void 0),
664
+ height: int(d.height, 1, 1e4, void 0),
665
+ caption: inline(d.caption)
666
+ }),
667
+ personality: (d) => ({
668
+ name: plain(d.name, 500),
669
+ description: plain(d.description, 2e3),
670
+ link: sanitizeUrl(d.link, { schemes: ["http", "https", "mailto"] }),
671
+ photo: sanitizeUrl(d.photo, { schemes: ["http", "https"] })
672
+ }),
673
+ button: (d) => ({
674
+ text: plain(d.text, 200),
675
+ link: sanitizeUrl(d.link),
676
+ style: oneOf(d.style, ["primary", "secondary", "outline", "ghost", "danger", "success"], "primary"),
677
+ openInNewTab: bool(d.openInNewTab)
678
+ }),
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);
702
+ };
703
+ var sanitizeTunes = (tunes) => {
704
+ if (!isPlainObject2(tunes)) return void 0;
705
+ const out = {};
706
+ if (isPlainObject2(tunes.alignmentTune)) {
707
+ out.alignmentTune = {
708
+ alignment: oneOf(tunes.alignmentTune.alignment, ["left", "center", "right", "justify"], "left")
709
+ };
710
+ }
711
+ if (typeof tunes.textVariant === "string") {
712
+ out.textVariant = oneOf(tunes.textVariant, ["", "call-out", "citation", "details"], "");
713
+ }
714
+ if (isPlainObject2(tunes.indentTune)) {
715
+ out.indentTune = { indentLevel: int(tunes.indentTune.indentLevel, 0, 10, 0) };
716
+ }
717
+ return Object.keys(out).length ? out : void 0;
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
+ };
724
+ var sanitizeTarget = (value) => typeof value === "string" && TARGETS.has(value) ? value : null;
725
+
726
+ // shared/render/inline.mjs
727
+ var DROP_WITH_CONTENT = /* @__PURE__ */ new Set([
728
+ "script",
729
+ "style",
730
+ "textarea",
731
+ "title",
732
+ "xmp",
733
+ "noscript",
734
+ "noembed",
735
+ "noframes",
736
+ "template",
737
+ "iframe",
738
+ "object",
739
+ "embed",
740
+ "svg",
741
+ "math",
742
+ "select",
743
+ "option",
744
+ "plaintext"
745
+ ]);
746
+ var ALLOWED = new Set(INLINE_TAGS);
747
+ var VOID = /* @__PURE__ */ new Set(["br"]);
748
+ var MAX_INPUT = 5e5;
749
+ var MAX_NODES = 5e4;
750
+ var MAX_DEPTH = 64;
751
+ var NAMED_ENTITIES = Object.freeze({
752
+ amp: "&",
753
+ lt: "<",
754
+ gt: ">",
755
+ quot: '"',
756
+ apos: "'",
757
+ nbsp: "\xA0",
758
+ shy: "\xAD",
759
+ copy: "\xA9",
760
+ reg: "\xAE",
761
+ trade: "\u2122",
762
+ hellip: "\u2026",
763
+ mdash: "\u2014",
764
+ ndash: "\u2013",
765
+ lsquo: "\u2018",
766
+ rsquo: "\u2019",
767
+ ldquo: "\u201C",
768
+ rdquo: "\u201D",
769
+ laquo: "\xAB",
770
+ raquo: "\xBB",
771
+ euro: "\u20AC",
772
+ middot: "\xB7",
773
+ bull: "\u2022",
774
+ times: "\xD7",
775
+ deg: "\xB0",
776
+ tab: " ",
777
+ newline: "\n",
778
+ colon: ":",
779
+ sol: "/",
780
+ lpar: "(",
781
+ rpar: ")"
782
+ });
783
+ var decodeEntities = (text) => String(text).replace(
784
+ /&(#[xX][0-9a-fA-F]{1,8}|#[0-9]{1,10}|[A-Za-z][A-Za-z0-9]{1,31});?/g,
785
+ (match, body) => {
786
+ if (body[0] === "#") {
787
+ const code = body[1] === "x" || body[1] === "X" ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
788
+ if (!Number.isFinite(code) || code <= 0 || code > 1114111 || code >= 55296 && code <= 57343)
789
+ return "\uFFFD";
790
+ return String.fromCodePoint(code);
791
+ }
792
+ const named = NAMED_ENTITIES[body] ?? NAMED_ENTITIES[body.toLowerCase()];
793
+ return named === void 0 ? match : named;
794
+ }
795
+ );
796
+ var parseAttributes = (source) => {
797
+ const out = {};
798
+ const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
799
+ let match;
800
+ while (match = pattern.exec(source)) {
801
+ const name = match[1].toLowerCase();
802
+ if (Object.prototype.hasOwnProperty.call(out, name)) continue;
803
+ const raw = match[2] ?? match[3] ?? match[4] ?? "";
804
+ out[name] = decodeEntities(raw);
805
+ }
806
+ return out;
807
+ };
808
+ var findTagEnd = (html, from) => {
809
+ let quote = "";
810
+ for (let i = from; i < html.length; i += 1) {
811
+ const char = html[i];
812
+ if (quote) {
813
+ if (char === quote) quote = "";
814
+ } else if (char === '"' || char === "'") quote = char;
815
+ else if (char === ">") return i;
816
+ }
817
+ return -1;
818
+ };
819
+ var cleanAttributes = (tag, attribs) => {
820
+ const allowed = INLINE_ATTRIBUTES[tag] || [];
821
+ const out = {};
822
+ for (const name of allowed) {
823
+ if (!Object.prototype.hasOwnProperty.call(attribs, name) || name.startsWith("data-mex-")) continue;
824
+ const value = attribs[name];
825
+ if (name === "href") {
826
+ const url = sanitizeUrl(value);
827
+ if (url) out.href = url;
828
+ } else if (name === "target") {
829
+ const target = sanitizeTarget(value);
830
+ if (target) out.target = target;
831
+ } else if (name === "rel") {
832
+ const rel = String(value).split(/\s+/).filter((token) => /^[a-z-]{1,20}$/.test(token));
833
+ if (rel.length) out.rel = rel.join(" ");
834
+ } else if (name === "class") {
835
+ const classes2 = String(value).split(/\s+/).filter((token) => (INLINE_CLASSES[tag] || []).includes(token));
836
+ if (classes2.length) out.class = classes2.join(" ");
837
+ } else {
838
+ out[name] = String(value).slice(0, 2e3);
839
+ }
840
+ }
841
+ if (tag === "a") Object.assign(out, cleanInternalLinkAttributes(attribs));
842
+ return out;
843
+ };
844
+ var parseInline = (input) => {
845
+ const html = typeof input === "string" ? input.slice(0, MAX_INPUT) : "";
846
+ const root = { type: "element", tag: "#root", attrs: {}, children: [] };
847
+ const stack = [root];
848
+ let nodes = 0;
849
+ let text = "";
850
+ const flush = () => {
851
+ if (!text) return;
852
+ const parent = stack[stack.length - 1];
853
+ const last = parent.children[parent.children.length - 1];
854
+ const value = decodeEntities(text);
855
+ if (last && last.type === "text") last.value += value;
856
+ else if (nodes < MAX_NODES) {
857
+ parent.children.push({ type: "text", value });
858
+ nodes += 1;
859
+ }
860
+ text = "";
861
+ };
862
+ let i = 0;
863
+ while (i < html.length) {
864
+ const lt = html.indexOf("<", i);
865
+ if (lt === -1) {
866
+ text += html.slice(i);
867
+ break;
868
+ }
869
+ text += html.slice(i, lt);
870
+ i = lt;
871
+ if (html.startsWith("<!--", i)) {
872
+ const end2 = html.indexOf("-->", i + 4);
873
+ flush();
874
+ i = end2 === -1 ? html.length : end2 + 3;
875
+ continue;
876
+ }
877
+ if (html.startsWith("<![CDATA[", i)) {
878
+ const end2 = html.indexOf("]]>", i + 9);
879
+ flush();
880
+ i = end2 === -1 ? html.length : end2 + 3;
881
+ continue;
882
+ }
883
+ if (html[i + 1] === "!" || html[i + 1] === "?") {
884
+ const end2 = html.indexOf(">", i + 2);
885
+ flush();
886
+ i = end2 === -1 ? html.length : end2 + 1;
887
+ continue;
888
+ }
889
+ const closing = html[i + 1] === "/";
890
+ const nameMatch = /^[A-Za-z][A-Za-z0-9-]{0,40}/.exec(html.slice(i + (closing ? 2 : 1), i + 45));
891
+ if (!nameMatch) {
892
+ text += "<";
893
+ i += 1;
894
+ continue;
895
+ }
896
+ const end = findTagEnd(html, i + 1);
897
+ if (end === -1) {
898
+ text += html.slice(i);
899
+ break;
900
+ }
901
+ flush();
902
+ const tag = nameMatch[0].toLowerCase();
903
+ const body = html.slice(i + (closing ? 2 : 1) + nameMatch[0].length, end);
904
+ i = end + 1;
905
+ if (closing) {
906
+ if (!ALLOWED.has(tag)) continue;
907
+ for (let s = stack.length - 1; s > 0; s -= 1) {
908
+ if (stack[s].tag === tag) {
909
+ stack.length = s;
910
+ break;
911
+ }
912
+ }
913
+ continue;
914
+ }
915
+ if (DROP_WITH_CONTENT.has(tag)) {
916
+ const selfClosing = /\/\s*$/.test(body);
917
+ if (selfClosing) continue;
918
+ const closeIndex = html.slice(i).search(new RegExp(`</${tag}[\\s/>]`, "i"));
919
+ if (closeIndex === -1) break;
920
+ const closeEnd = html.indexOf(">", i + closeIndex);
921
+ i = closeEnd === -1 ? html.length : closeEnd + 1;
922
+ continue;
923
+ }
924
+ if (!ALLOWED.has(tag) || nodes >= MAX_NODES) continue;
925
+ const element = {
926
+ type: "element",
927
+ tag,
928
+ attrs: cleanAttributes(tag, parseAttributes(body)),
929
+ children: []
930
+ };
931
+ stack[stack.length - 1].children.push(element);
932
+ nodes += 1;
933
+ if (!VOID.has(tag) && stack.length < MAX_DEPTH) stack.push(element);
934
+ }
935
+ flush();
936
+ return root.children;
937
+ };
938
+ var resolveLinkAttributes = (attrs, resolver) => {
939
+ if (typeof resolver !== "function" || !attrs["data-mex-uid"] || !attrs["data-mex-document-id"])
940
+ return attrs;
941
+ let result;
942
+ try {
943
+ result = resolver({
944
+ uid: attrs["data-mex-uid"],
945
+ documentId: attrs["data-mex-document-id"],
946
+ locale: attrs["data-mex-locale"] || null,
947
+ href: attrs.href || null,
948
+ ...isMentionLink(attrs) ? { mention: true } : {}
949
+ });
950
+ } catch {
951
+ result = void 0;
952
+ }
953
+ if (result === false) return null;
954
+ if (typeof result === "string") {
955
+ const url = sanitizeUrl(result);
956
+ if (url) return { ...attrs, href: url };
957
+ }
958
+ return attrs;
959
+ };
960
+ var ATTRIBUTE_ORDER = [
961
+ "href",
962
+ "target",
963
+ "rel",
964
+ "title",
965
+ "class",
966
+ "data-tooltip",
967
+ "data-mex-uid",
968
+ "data-mex-document-id",
969
+ "data-mex-locale",
970
+ "data-mex-mention"
971
+ ];
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;
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
+ });
1011
+ }
1012
+ return out;
1013
+ };
1014
+ var inlineToNodes = (html, options) => inlineNodesToRender(parseInline(html), options);
1015
+ var nodesToHtml = (nodes, options = {}) => serializeNodes(inlineNodesToRender(nodes, options));
1016
+ var nodesToText = (nodes) => nodes.map((node) => {
1017
+ if (node.type === "text") return node.value;
1018
+ if (node.tag === "br") return "\n";
1019
+ return nodesToText(node.children);
1020
+ }).join("");
1021
+ var inlineToHtml = (html, options) => nodesToHtml(parseInline(html), options);
1022
+ var inlineToText = (html) => nodesToText(parseInline(html)).replace(/\u00a0/g, " ");
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
+
1696
+ // shared/render/common.mjs
1697
+ var keepInline = (html) => inlineToHtml(html, { storage: true });
1698
+ var prepareBlocks = (value, options = {}) => {
1699
+ const normalized = normalizeEditorDataSafe(value);
1700
+ if (!normalized) return [];
1701
+ const data = containsSynced(normalized.blocks) ? expandSynced(normalized, syncedLookup(options.synced)).data : normalized;
1702
+ const rawPolicy = options.rawHtml === "allow" && typeof options.sanitizeRaw === "function" ? "allow" : "disable";
1703
+ const ctx = { rawHtml: rawPolicy, rawSanitizer: () => "" };
1704
+ const explicit = Array.isArray(options.blocks) ? compileBlockList(options.blocks) : null;
1705
+ const flat = data.blocks.map((block) => {
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;
1710
+ for (const key of Object.keys(clean)) if (clean[key] === void 0) delete clean[key];
1711
+ return {
1712
+ id: block.id,
1713
+ type: block.type,
1714
+ data: clean,
1715
+ raw,
1716
+ tunes: sanitizeTunes(block.tunes),
1717
+ known,
1718
+ definition,
1719
+ children: []
1720
+ };
1721
+ });
1722
+ const group = (start, end, depth) => {
1723
+ const out = [];
1724
+ let i = start;
1725
+ while (i < end) {
1726
+ const block = flat[i];
1727
+ i += 1;
1728
+ if (block.type === "toggle" && depth < 16) {
1729
+ const count = Math.max(0, Math.min(Number(block.data.items) || 0, end - i));
1730
+ block.children = group(i, i + count, depth + 1);
1731
+ i += count;
1732
+ }
1733
+ out.push(block);
1734
+ }
1735
+ return out;
1736
+ };
1737
+ return group(0, flat.length, 0);
1738
+ };
1739
+ var FORMAT_ORDER = ["thumbnail", "xsmall", "small", "medium", "large", "xlarge"];
1740
+ var imageCandidates = (file) => {
1741
+ const out = [];
1742
+ const seen = /* @__PURE__ */ new Set();
1743
+ const push = (url, width) => {
1744
+ const clean = sanitizeUrl(url, { schemes: ["http", "https"] });
1745
+ if (!clean || !Number.isInteger(width) || width <= 0 || seen.has(width)) return;
1746
+ seen.add(width);
1747
+ out.push({ url: clean, width });
1748
+ };
1749
+ if (isPlainObject2(file.formats)) {
1750
+ const names = Object.keys(file.formats).sort(
1751
+ (a, b) => (FORMAT_ORDER.indexOf(a) + 1 || 99) - (FORMAT_ORDER.indexOf(b) + 1 || 99) || (a < b ? -1 : a > b ? 1 : 0)
1752
+ );
1753
+ for (const name of names) {
1754
+ const format = file.formats[name];
1755
+ if (isPlainObject2(format)) push(format.url, Number(format.width));
1756
+ }
1757
+ }
1758
+ push(file.url, Number(file.width));
1759
+ return out.sort((a, b) => a.width - b.width);
1760
+ };
1761
+ var resolveMedia = (file, block, options, kind) => {
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
+ }
1772
+ let next;
1773
+ try {
1774
+ next = options.media({ ...file }, { id: block.id, type: block.type });
1775
+ } catch {
1776
+ next = null;
1777
+ }
1778
+ if (!isPlainObject2(next)) return file;
1779
+ const policy = BLOCK_POLICIES.image({ file: next }, (s) => s, {
1780
+ rawHtml: "disable",
1781
+ rawSanitizer: () => ""
1782
+ });
1783
+ return policy.file;
1784
+ };
1785
+ var DEFAULT_EMBED_HOSTS = Object.freeze([
1786
+ "www.youtube-nocookie.com",
1787
+ "www.youtube.com",
1788
+ "youtube.com",
1789
+ "player.vimeo.com",
1790
+ "codepen.io",
1791
+ "player.twitch.tv",
1792
+ "clips.twitch.tv",
1793
+ "embed.figma.com",
1794
+ "www.figma.com",
1795
+ "miro.com"
1796
+ ]);
1797
+ var embedFrameUrl = (url, hosts) => {
1798
+ if (!url || !/^https:\/\//i.test(url)) return "";
1799
+ try {
1800
+ const parsed = new URL(url);
1801
+ return parsed.protocol === "https:" && hosts.includes(parsed.hostname.toLowerCase()) ? url : "";
1802
+ } catch {
1803
+ return "";
1804
+ }
1805
+ };
1806
+ var overrideFor = (options, type) => {
1807
+ const overrides = options && options.overrides;
1808
+ if (!overrides || typeof overrides !== "object" || !Object.prototype.hasOwnProperty.call(overrides, type))
1809
+ return null;
1810
+ return typeof overrides[type] === "function" ? overrides[type] : null;
1811
+ };
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])]);
1813
+ var formatSize = (bytes) => {
1814
+ if (!Number.isFinite(bytes) || bytes < 0) return "";
1815
+ if (bytes < 1024) return `${bytes} B`;
1816
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
1817
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
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
+ };
1850
+
1851
+ // shared/render/tree.mjs
1852
+ var COUNTER_TYPES = Object.freeze({
1853
+ "lower-roman": "i",
1854
+ "upper-roman": "I",
1855
+ "lower-alpha": "a",
1856
+ "upper-alpha": "A"
1857
+ });
1858
+ var MAX_NUMBERED_LINES = 2e4;
1859
+ var classes = (base, tunes) => {
1860
+ const list = [...base];
1861
+ if (tunes && tunes.alignmentTune && tunes.alignmentTune.alignment !== "left")
1862
+ list.push(`mex-align-${tunes.alignmentTune.alignment}`);
1863
+ if (tunes && tunes.textVariant) list.push(`mex-variant-${tunes.textVariant}`);
1864
+ if (tunes && tunes.indentTune && tunes.indentTune.indentLevel > 0)
1865
+ list.push(`mex-indent-${tunes.indentTune.indentLevel}`);
1866
+ return list.join(" ");
1867
+ };
1868
+ var listItems2 = (items, style, options, depth) => items.map((item) => {
1869
+ if (typeof item === "string") return el("li", {}, inlineToNodes(item, options));
1870
+ const checked = Boolean(item.meta && item.meta.checked);
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;
1881
+ return el(
1882
+ "li",
1883
+ style === "checklist" ? { class: "mex-checklist-item", "data-checked": String(checked) } : {},
1884
+ [check, inlineToNodes(item.content, options), nested]
1885
+ );
1886
+ });
1887
+ var listElement = (items, style, meta, options, depth, base, tunes) => {
1888
+ const tag = style === "ordered" ? "ol" : "ul";
1889
+ const attrs = {};
1890
+ if (base.length) attrs.class = classes(base, tunes);
1891
+ if (style === "ordered" && meta) {
1892
+ if (Number.isInteger(meta.start) && meta.start !== 1) attrs.start = meta.start;
1893
+ if (COUNTER_TYPES[meta.counterType]) attrs.type = COUNTER_TYPES[meta.counterType];
1894
+ }
1895
+ return el(tag, attrs, listItems2(items, style, options, depth));
1896
+ };
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
+ };
2022
+ var RENDERERS = {
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
+ ),
2029
+ quote: (b, o) => {
2030
+ const caption = inlineToNodes(b.data.caption, o);
2031
+ return el(
2032
+ "figure",
2033
+ {
2034
+ class: classes(
2035
+ ["mex-quote", ...b.data.alignment === "center" ? ["mex-align-center"] : []],
2036
+ b.tunes
2037
+ )
2038
+ },
2039
+ [
2040
+ el("blockquote", {}, inlineToNodes(b.data.text, o)),
2041
+ caption.length ? el("figcaption", {}, caption) : null
2042
+ ]
2043
+ );
2044
+ },
2045
+ list: (b, o) => listElement(
2046
+ b.data.items,
2047
+ b.data.style,
2048
+ b.data.meta,
2049
+ o,
2050
+ 0,
2051
+ b.data.style === "checklist" ? ["mex-list", "mex-checklist"] : ["mex-list"],
2052
+ b.tunes
2053
+ ),
2054
+ checklist: (b, o) => listElement(
2055
+ b.data.items.map((item) => ({ content: item.text, meta: { checked: item.checked }, items: [] })),
2056
+ "checklist",
2057
+ {},
2058
+ o,
2059
+ 0,
2060
+ ["mex-list", "mex-checklist"],
2061
+ b.tunes
2062
+ ),
2063
+ warning: (b, o) => {
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
+ ]);
2069
+ },
2070
+ alert: (b, o) => el(
2071
+ "div",
2072
+ {
2073
+ class: classes(
2074
+ [
2075
+ "mex-alert",
2076
+ `mex-alert-${b.data.type}`,
2077
+ ...b.data.align !== "left" ? [`mex-align-${b.data.align}`] : []
2078
+ ],
2079
+ b.tunes
2080
+ ),
2081
+ role: "note"
2082
+ },
2083
+ inlineToNodes(b.data.message, o)
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),
2091
+ raw: (b, o) => {
2092
+ if (o.rawHtml !== "allow" || typeof o.sanitizeRaw !== "function") return null;
2093
+ const html = o.sanitizeRaw(String(b.raw.html || ""));
2094
+ return typeof html === "string" && html ? el("div", { class: classes(["mex-raw"], b.tunes) }, { type: "raw", html }) : null;
2095
+ },
2096
+ table: (b, o) => {
2097
+ const rows = b.data.content;
2098
+ if (!rows.length) return null;
2099
+ const cells = (row, tag) => el(
2100
+ "tr",
2101
+ {},
2102
+ row.map((cell2) => el(tag, tag === "th" ? { scope: "col" } : {}, inlineToNodes(cell2, o)))
2103
+ );
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"));
2106
+ return el(
2107
+ "table",
2108
+ { class: classes(["mex-table", ...b.data.stretched ? ["mex-stretched"] : []], b.tunes) },
2109
+ [head, body.length ? el("tbody", {}, body) : null]
2110
+ );
2111
+ },
2112
+ image: (b, o) => {
2113
+ const file = resolveMedia(b.data.file, b, o);
2114
+ if (!file.url) return null;
2115
+ const img = libraryImageAttrs(file, b.raw.decorative === true, o);
2116
+ const cls = ["mex-image"];
2117
+ if (b.data.withBorder) cls.push("mex-image-border");
2118
+ if (b.data.withBackground) cls.push("mex-image-background");
2119
+ if (b.data.stretched) cls.push("mex-stretched");
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;
2123
+ },
2124
+ simpleImage: (b, o) => {
2125
+ if (!b.data.url) return null;
2126
+ const cls = ["mex-image"];
2127
+ if (b.data.withBorder) cls.push("mex-image-border");
2128
+ if (b.data.withBackground) cls.push("mex-image-background");
2129
+ if (b.data.stretched) cls.push("mex-stretched");
2130
+ return figure(
2131
+ b.data.url,
2132
+ {
2133
+ alt: b.data.decorative === true ? "" : typeof b.data.alt === "string" && b.data.alt.trim() ? b.data.alt : inlineToText(b.data.caption)
2134
+ },
2135
+ inlineToNodes(b.data.caption, o),
2136
+ classes(cls, b.tunes)
2137
+ );
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),
2175
+ linkTool: (b) => {
2176
+ if (!b.data.link) return null;
2177
+ const meta = b.data.meta;
2178
+ return el(
2179
+ "div",
2180
+ { class: classes(["mex-link-preview"], b.tunes) },
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
+ ])
2187
+ );
2188
+ },
2189
+ attaches: (b) => {
2190
+ const file = b.data.file;
2191
+ if (!file.url) return null;
2192
+ const text = b.data.title || file.title || file.name || file.url;
2193
+ const details = [file.extension ? file.extension.toUpperCase() : "", formatSize(file.size)].filter(Boolean).join(", ");
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
+ ]);
2198
+ },
2199
+ embed: (b, o) => {
2200
+ const hosts = Array.isArray(o.embedHosts) ? o.embedHosts.map((h) => String(h).toLowerCase()) : DEFAULT_EMBED_HOSTS;
2201
+ const frame = embedFrameUrl(b.data.embed, hosts);
2202
+ const caption = inlineToNodes(b.data.caption, o);
2203
+ const title = inlineToText(b.data.caption) || b.data.service || "Embedded content";
2204
+ if (!frame) {
2205
+ const href = b.data.source || b.data.embed;
2206
+ if (!href) return null;
2207
+ return el(
2208
+ "p",
2209
+ { class: classes(["mex-embed", "mex-embed-link"], b.tunes) },
2210
+ el("a", { href, rel: "nofollow noopener noreferrer" }, caption.length ? caption : href)
2211
+ );
2212
+ }
2213
+ return el(
2214
+ "figure",
2215
+ {
2216
+ class: classes(
2217
+ ["mex-embed", b.data.service ? `mex-embed-${b.data.service}` : ""].filter(Boolean),
2218
+ b.tunes
2219
+ )
2220
+ },
2221
+ [
2222
+ el("iframe", {
2223
+ src: frame,
2224
+ title,
2225
+ width: b.data.width,
2226
+ height: b.data.height,
2227
+ loading: "lazy",
2228
+ referrerpolicy: "strict-origin-when-cross-origin",
2229
+ sandbox: "allow-scripts allow-same-origin allow-popups allow-presentation",
2230
+ allow: "fullscreen; picture-in-picture; encrypted-media",
2231
+ allowfullscreen: true
2232
+ }),
2233
+ caption.length ? el("figcaption", {}, caption) : null
2234
+ ]
2235
+ );
2236
+ },
2237
+ personality: (b) => {
2238
+ const d = b.data;
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
+ ]);
2248
+ },
2249
+ button: (b) => {
2250
+ const d = b.data;
2251
+ if (!d.text) return null;
2252
+ const cls = `mex-button mex-button-${d.style}`;
2253
+ const inner = d.link ? el(
2254
+ "a",
2255
+ {
2256
+ class: cls,
2257
+ href: d.link,
2258
+ target: d.openInNewTab ? "_blank" : void 0,
2259
+ rel: d.openInNewTab ? "noopener noreferrer" : void 0
2260
+ },
2261
+ d.text
2262
+ ) : el("span", { class: cls }, d.text);
2263
+ return el("p", { class: classes(["mex-button-block"], b.tunes) }, inner);
2264
+ },
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
+ }
2290
+ };
2291
+ var neutral = (b) => el(
2292
+ "div",
2293
+ { class: classes(["mex-block", `mex-${b.type}`], b.tunes), "data-mex-block": b.type },
2294
+ scalarFields(b.data).map(
2295
+ ([key, value]) => el("div", { class: "mex-field", "data-mex-field": key }, inlineToText(value))
2296
+ )
2297
+ );
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 = {}) => {
2424
+ const opts = options && typeof options === "object" ? options : {};
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) => {
2443
+ const override = overrideFor(opts, block.type);
2444
+ if (override) {
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
+ }
2480
+ }
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 };
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);
2531
+
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
+ ]);
2537
+ var listLines = (items, style, start, depth) => {
2538
+ const lines = [];
2539
+ items.forEach((item, index) => {
2540
+ const content = typeof item === "string" ? item : item.content;
2541
+ let marker = "-";
2542
+ if (style === "ordered") marker = `${start + index}.`;
2543
+ else if (style === "checklist") marker = item.meta && item.meta.checked ? "[x]" : "[ ]";
2544
+ const indent = " ".repeat(depth);
2545
+ const text = inlineToText(content).trim().replace(/\n/g, `
2546
+ ${indent} `);
2547
+ lines.push(`${indent}${marker} ${text}`);
2548
+ if (typeof item !== "string" && Array.isArray(item.items) && item.items.length && depth < 12)
2549
+ lines.push(...listLines(item.items, style, 1, depth + 1));
2550
+ });
2551
+ return lines;
2552
+ };
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
+ };
2559
+ var RENDERERS2 = {
2560
+ paragraph: (b) => t(b.data.text),
2561
+ header: (b) => t(b.data.text),
2562
+ quote: (b) => [t(b.data.text), t(b.data.caption) ? `\u2014 ${t(b.data.caption)}` : ""].filter(Boolean).join("\n"),
2563
+ list: (b) => listLines(
2564
+ b.data.items,
2565
+ b.data.style,
2566
+ Number.isInteger(b.data.meta && b.data.meta.start) ? b.data.meta.start : 1,
2567
+ 0
2568
+ ).join("\n"),
2569
+ checklist: (b) => b.data.items.map((item) => `${item.checked ? "[x]" : "[ ]"} ${t(item.text)}`).join("\n"),
2570
+ warning: (b) => [t(b.data.title), t(b.data.message)].filter(Boolean).join("\n"),
2571
+ alert: (b) => t(b.data.message),
2572
+ toggle: (b, _o, render) => [t(b.data.text), render(b.children)].filter(Boolean).join("\n\n"),
2573
+ code: (b) => b.data.code,
2574
+ codeFlask: (b) => b.data.code,
2575
+ raw: () => "",
2576
+ table: (b) => b.data.content.map((row) => row.map((cell2) => t(cell2).replace(/\s+/g, " ")).join(" ")).join("\n"),
2577
+ image: (b) => t(b.data.caption) || (b.raw.decorative === true ? "" : (b.data.file.alt || "").trim()),
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),
2587
+ linkTool: (b) => [b.data.meta.title, b.data.link].filter(Boolean).join("\n"),
2588
+ attaches: (b) => b.data.file.url ? b.data.title || b.data.file.title || b.data.file.name || b.data.file.url : "",
2589
+ embed: (b) => [t(b.data.caption), b.data.source || b.data.embed].filter(Boolean).join("\n"),
2590
+ personality: (b) => [b.data.name, b.data.description, b.data.link].filter(Boolean).join("\n"),
2591
+ button: (b) => b.data.link ? `${b.data.text} (${b.data.link})` : b.data.text,
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");
2609
+ };
2610
+ var renderText = (value, options = {}) => {
2611
+ const opts = options && typeof options === "object" ? options : {};
2612
+ const render = (blocks) => blocks.map((block) => {
2613
+ const override = overrideFor(opts, block.type);
2614
+ if (override) {
2615
+ const out = override(
2616
+ {
2617
+ id: block.id,
2618
+ type: block.type,
2619
+ data: block.data,
2620
+ tunes: block.tunes,
2621
+ children: block.children
2622
+ },
2623
+ { text: (html) => inlineToText(html), renderChildren: render }
2624
+ );
2625
+ if (typeof out === "string") return out;
2626
+ }
2627
+ if (block.known) return RENDERERS2[block.type](block, opts, render);
2628
+ if (block.definition) return registeredText(block);
2629
+ return scalarFields(block.data).map(([, v]) => inlineToText(v).trim()).filter(Boolean).join("\n");
2630
+ }).map((text) => String(text).replace(/\u00a0/g, " ")).filter((text) => text.trim() !== "").join("\n\n");
2631
+ return render(annotateHeadings(prepareBlocks(value, opts), opts));
2632
+ };
2633
+
2634
+ // shared/render/markdown.mjs
2635
+ var escapeMarkdown = (text) => String(text).replace(/\u00a0/g, " ").replace(/[\\`*_[\]<>|~&{}]/g, (char) => `\\${char}`).replace(
2636
+ /(^|\n)(\s*)([#>+=-]|\d{1,9}[.)])/g,
2637
+ (_m, nl, space, mark) => `${nl}${space}${mark.replace(/^(\d*)([#>+=.)-])$/, "$1\\$2")}`
2638
+ );
2639
+ var linkUrl = (url) => String(url).replace(
2640
+ /[ ()<>\\]/g,
2641
+ (char) => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`
2642
+ );
2643
+ var linkTitle = (title) => {
2644
+ const clean = String(title || "").replace(/\s+/g, " ").trim();
2645
+ return clean ? ` "${clean.replace(/[\\"<>]/g, (char) => `\\${char}`)}"` : "";
2646
+ };
2647
+ var wrap = (marker, inner) => {
2648
+ const match = /^(\s*)([\s\S]*?)(\s*)$/.exec(inner);
2649
+ if (!match[2]) return inner;
2650
+ return `${match[1]}${marker}${match[2]}${marker}${match[3]}`;
2651
+ };
2652
+ var codeSpan = (code) => {
2653
+ const text = code.replace(/\n/g, " ");
2654
+ if (!text) return "";
2655
+ const longest = Math.max(0, ...(text.match(/`+/g) || []).map((run) => run.length));
2656
+ const fence2 = "`".repeat(longest + 1);
2657
+ const pad = text.startsWith("`") || text.endsWith("`") || text.startsWith(" ") && text.endsWith(" ") ? " " : "";
2658
+ return `${fence2}${pad}${text}${pad}${fence2}`;
2659
+ };
2660
+ var rawText = (nodes) => nodes.map((n) => n.type === "text" ? n.value : n.tag === "br" ? "\n" : rawText(n.children)).join("");
2661
+ var nodesToMarkdown = (nodes, options) => nodes.map((node) => {
2662
+ if (node.type === "text") return escapeMarkdown(node.value);
2663
+ const inner = () => nodesToMarkdown(node.children, options);
2664
+ switch (node.tag) {
2665
+ case "br":
2666
+ return "\\\n";
2667
+ case "b":
2668
+ case "strong":
2669
+ return wrap("**", inner());
2670
+ case "i":
2671
+ case "em":
2672
+ return wrap("_", inner());
2673
+ case "s":
2674
+ return wrap("~~", inner());
2675
+ case "code":
2676
+ return codeSpan(rawText(node.children));
2677
+ case "a": {
2678
+ const attrs = resolveLinkAttributes(node.attrs, options.links);
2679
+ const text = inner();
2680
+ if (!attrs || !attrs.href) return text;
2681
+ return `[${text || escapeMarkdown(attrs.href)}](${linkUrl(attrs.href)}${linkTitle(attrs.title)})`;
2682
+ }
2683
+ default:
2684
+ return inner();
2685
+ }
2686
+ }).join("");
2687
+ var md = (html, options) => nodesToMarkdown(parseInline(html), options).trim();
2688
+ var oneLine = (text) => text.replace(/\\\n/g, " ").replace(/\n/g, " ");
2689
+ var prefixLines = (text, prefix) => text.split("\n").map((line) => line ? `${prefix}${line}` : prefix.trimEnd()).join("\n");
2690
+ var listLines2 = (items, style, start, options, indent, depth) => {
2691
+ const lines = [];
2692
+ items.forEach((item, index) => {
2693
+ const content = typeof item === "string" ? item : item.content;
2694
+ let marker = "-";
2695
+ if (style === "ordered") marker = `${start + index}.`;
2696
+ else if (style === "checklist") marker = `- [${item.meta && item.meta.checked ? "x" : " "}]`;
2697
+ const childIndent = `${indent}${" ".repeat((style === "checklist" ? 2 : marker.length) + 1)}`;
2698
+ const text = md(content, options).replace(/\n/g, `
2699
+ ${childIndent}`);
2700
+ lines.push(`${indent}${marker} ${text}`.trimEnd());
2701
+ if (typeof item !== "string" && Array.isArray(item.items) && item.items.length && depth < 12)
2702
+ lines.push(...listLines2(item.items, style, 1, options, childIndent, depth + 1));
2703
+ });
2704
+ return lines;
2705
+ };
2706
+ var fence = (code, language) => {
2707
+ const longest = Math.max(2, ...(code.match(/`{3,}/g) || []).map((run) => run.length));
2708
+ const marks = "`".repeat(longest + 1);
2709
+ const info = language && /^[a-z0-9+#-]{1,32}$/i.test(language) && language !== "plaintext" ? language : "";
2710
+ return `${marks}${info}
2711
+ ${code.replace(/\n$/, "")}
2712
+ ${marks}`;
2713
+ };
2714
+ var cell = (html, options) => oneLine(md(html, options)) || " ";
2715
+ var RENDERERS3 = {
2716
+ paragraph: (b, o) => md(b.data.text, o),
2717
+ header: (b, o) => {
2718
+ const text = oneLine(md(b.data.text, o));
2719
+ return text ? `${"#".repeat(b.data.level)} ${text}` : "";
2720
+ },
2721
+ quote: (b, o) => {
2722
+ const text = md(b.data.text, o);
2723
+ const caption = md(b.data.caption, o);
2724
+ if (!text && !caption) return "";
2725
+ return prefixLines(caption ? `${text}
2726
+
2727
+ \u2014 ${caption}` : text, "> ");
2728
+ },
2729
+ list: (b, o) => listLines2(
2730
+ b.data.items,
2731
+ b.data.style,
2732
+ Number.isInteger(b.data.meta && b.data.meta.start) ? b.data.meta.start : 1,
2733
+ o,
2734
+ "",
2735
+ 0
2736
+ ).join("\n"),
2737
+ checklist: (b, o) => b.data.items.map((item) => `- [${item.checked ? "x" : " "}] ${oneLine(md(item.text, o))}`.trimEnd()).join("\n"),
2738
+ warning: (b, o) => {
2739
+ const title = md(b.data.title, o);
2740
+ const message = md(b.data.message, o);
2741
+ return prefixLines([title ? `**${oneLine(title)}**` : "", message].filter(Boolean).join("\n\n"), "> ");
2742
+ },
2743
+ alert: (b, o) => {
2744
+ const message = md(b.data.message, o);
2745
+ return message ? prefixLines(message, "> ") : "";
2746
+ },
2747
+ toggle: (b, o, render) => [b.data.text ? `**${oneLine(md(b.data.text, o))}**` : "", render(b.children)].filter(Boolean).join("\n\n"),
2748
+ code: (b) => b.data.code ? fence(b.data.code) : "",
2749
+ codeFlask: (b) => b.data.code ? fence(b.data.code, b.data.language) : "",
2750
+ raw: (b, o) => {
2751
+ if (o.rawHtml !== "allow" || typeof o.sanitizeRaw !== "function") return "";
2752
+ const html = o.sanitizeRaw(String(b.raw.html || ""));
2753
+ return typeof html === "string" ? html.trim() : "";
2754
+ },
2755
+ table: (b, o) => {
2756
+ const rows = b.data.content.filter((row) => row.length);
2757
+ if (!rows.length) return "";
2758
+ const width = Math.max(...rows.map((row) => row.length));
2759
+ const line = (row) => `| ${Array.from({ length: width }, (_, i) => cell(row[i] || "", o)).join(" | ")} |`;
2760
+ const head = b.data.withHeadings ? rows[0] : [];
2761
+ const body = b.data.withHeadings ? rows.slice(1) : rows;
2762
+ return [
2763
+ line(head),
2764
+ `| ${Array.from({ length: width }, () => "---").join(" | ")} |`,
2765
+ ...body.map(line)
2766
+ ].join("\n");
2767
+ },
2768
+ image: (b, o) => {
2769
+ const file = resolveMedia(b.data.file, b, o);
2770
+ if (!file.url) return "";
2771
+ const alt = b.raw.decorative === true ? "" : escapeMarkdown(oneLine(file.alt || ""));
2772
+ const caption = inlineToText(b.data.caption);
2773
+ return `![${alt}](${linkUrl(file.url)}${linkTitle(caption)})`;
2774
+ },
2775
+ simpleImage: (b) => {
2776
+ if (!b.data.url) return "";
2777
+ const text = typeof b.data.alt === "string" && b.data.alt.trim() ? b.data.alt : inlineToText(b.data.caption);
2778
+ const alt = b.data.decorative === true ? "" : escapeMarkdown(oneLine(text));
2779
+ return `![${alt}](${linkUrl(b.data.url)})`;
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),
2794
+ linkTool: (b) => b.data.link ? `[${escapeMarkdown(b.data.meta.title || b.data.link)}](${linkUrl(b.data.link)})` : "",
2795
+ attaches: (b) => {
2796
+ const file = b.data.file;
2797
+ if (!file.url) return "";
2798
+ return `[${escapeMarkdown(b.data.title || file.title || file.name || file.url)}](${linkUrl(file.url)})`;
2799
+ },
2800
+ embed: (b, o) => {
2801
+ const href = b.data.source || b.data.embed;
2802
+ if (!href) return "";
2803
+ return `[${oneLine(md(b.data.caption, o)) || escapeMarkdown(b.data.service || href)}](${linkUrl(href)})`;
2804
+ },
2805
+ personality: (b) => {
2806
+ const d = b.data;
2807
+ return [
2808
+ d.name ? `**${escapeMarkdown(d.name)}**` : "",
2809
+ d.description ? escapeMarkdown(d.description) : "",
2810
+ d.link ? `[${escapeMarkdown(d.link)}](${linkUrl(d.link)})` : ""
2811
+ ].filter(Boolean).join("\n\n");
2812
+ },
2813
+ button: (b) => {
2814
+ if (!b.data.text) return "";
2815
+ return b.data.link ? `[${escapeMarkdown(b.data.text)}](${linkUrl(b.data.link)})` : escapeMarkdown(b.data.text);
2816
+ },
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");
2856
+ };
2857
+ var renderMarkdown = (value, options = {}) => {
2858
+ const opts = options && typeof options === "object" ? options : {};
2859
+ const render = (blocks) => blocks.map((block) => {
2860
+ const override = overrideFor(opts, block.type);
2861
+ if (override) {
2862
+ const out = override(
2863
+ {
2864
+ id: block.id,
2865
+ type: block.type,
2866
+ data: block.data,
2867
+ tunes: block.tunes,
2868
+ children: block.children
2869
+ },
2870
+ { escape: escapeMarkdown, inline: (html) => md(html, opts), renderChildren: render }
2871
+ );
2872
+ if (typeof out === "string") return out;
2873
+ }
2874
+ if (block.known) return RENDERERS3[block.type](block, opts, render);
2875
+ if (block.definition) return registeredMarkdown(block, opts);
2876
+ return scalarFields(block.data).map(([, v]) => md(v, opts)).filter(Boolean).join("\n\n");
2877
+ }).filter((text) => text && text.trim() !== "").join("\n\n");
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
+ };
2918
+ };