magic-editor-x 2.4.0 → 2.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/README.md +140 -62
  3. package/bin/magic-editor-x.mjs +55 -8
  4. package/dist/admin/{AuditPage-guB0SiGS.mjs → AuditPage-Be78C7EC.mjs} +4 -3
  5. package/dist/admin/{AuditPage-C2u6z4aN.js → AuditPage-iQzpjH8H.js} +7 -6
  6. package/dist/admin/{ConfigurationPage-DiEpF1Rr.mjs → ConfigurationPage-C9CPBfWy.mjs} +186 -6
  7. package/dist/admin/{ConfigurationPage-D6uya-J1.js → ConfigurationPage-DefuBeYO.js} +191 -11
  8. package/dist/admin/Content-BttG50Mc.mjs +360 -0
  9. package/dist/admin/Content-V5MRBsI3.js +362 -0
  10. package/dist/admin/{CustomBlocksPage-Byt10-6c.mjs → CustomBlocksPage-DB5nnCsn.mjs} +5 -4
  11. package/dist/admin/{CustomBlocksPage-DP3h_wNd.js → CustomBlocksPage-Dg2rM3F4.js} +8 -7
  12. package/dist/admin/EntryWidgets-B8YA0Zxy.mjs +199 -0
  13. package/dist/admin/EntryWidgets-BcXAAx3F.js +201 -0
  14. package/dist/admin/{MentionsWidget-sMkM9mHX.mjs → MentionsWidget-CJPZDk9Z.mjs} +2 -2
  15. package/dist/admin/{MentionsWidget-C2OCAmqq.js → MentionsWidget-DUz6YVIG.js} +2 -2
  16. package/dist/admin/{useT-CLPhBmBC.mjs → SectionCard-8ZNHkvn9.mjs} +2 -12
  17. package/dist/admin/{useT-BXJLIPN4.js → SectionCard-Bs-xiiH1.js} +0 -10
  18. package/dist/admin/{TemplatesPage-Yp4OqFE2.mjs → TemplatesPage-VsZ_Mc0R.mjs} +6 -5
  19. package/dist/admin/{TemplatesPage-DrSJdteI.js → TemplatesPage-dx4_yd_t.js} +13 -12
  20. package/dist/admin/{api-bix9RLLI.js → api-4AYzwS4-.js} +9 -1
  21. package/dist/admin/{api-2ZRpHM3d.mjs → api-CcTYyckq.mjs} +9 -1
  22. package/dist/admin/{de-zcV8D7nt.js → de-B6rdcOqQ.js} +103 -1
  23. package/dist/admin/{de-1cFMs-4c.mjs → de-BWfR2jTg.mjs} +8 -1
  24. package/dist/admin/{de-DiCZrmH8.mjs → de-Bip0sBRT.mjs} +19 -1
  25. package/dist/admin/{de-Dn8athM8.js → de-BrPR4sUB.js} +8 -1
  26. package/dist/admin/{de-CKz6CG3V.mjs → de-CQA8hOpl.mjs} +103 -1
  27. package/dist/admin/{de-CbBDnXeT.js → de-CnnxKXj7.js} +19 -1
  28. package/dist/admin/{de-BhhGss1l.js → de-Dss5POqk.js} +12 -1
  29. package/dist/admin/{de-BNPIGqhs.mjs → de-zgHCYTLH.mjs} +12 -1
  30. package/dist/admin/{en-CIZ5Ggod.js → en--JjAHbpP.js} +8 -1
  31. package/dist/admin/{en-cYzqbASF.mjs → en-BCKaVgBM.mjs} +103 -1
  32. package/dist/admin/{en-B9ApE1y1.js → en-CJ17Sp_e.js} +12 -1
  33. package/dist/admin/{en-BMWhILnj.js → en-CbGkcq0Q.js} +103 -1
  34. package/dist/admin/{en-DCPMqFIa.mjs → en-Cd6Jk-J0.mjs} +19 -1
  35. package/dist/admin/{en-CpehF0Kv.js → en-D69Fe9ZO.js} +19 -1
  36. package/dist/admin/{en-Dc9y-6n9.mjs → en-Dr58wBAo.mjs} +8 -1
  37. package/dist/admin/{en-gFLeK9Ng.mjs → en-Uhm7OouM.mjs} +12 -1
  38. package/dist/admin/entry-panel-events-0msyPrAD.js +18 -0
  39. package/dist/admin/entry-panel-events-XRuUoLZ9.mjs +19 -0
  40. package/dist/admin/{es-D2Kw6E4N.mjs → es-B2Hkkbw9.mjs} +8 -1
  41. package/dist/admin/{es-BmwBgEgz.mjs → es-BMkmfH88.mjs} +12 -1
  42. package/dist/admin/{es-Chs37IBR.mjs → es-Bz8d72Fa.mjs} +19 -1
  43. package/dist/admin/{es-CQPh8PXw.js → es-C8UotT8O.js} +103 -1
  44. package/dist/admin/{es-CawpzwyC.js → es-CcEDZpVQ.js} +19 -1
  45. package/dist/admin/{es-C0W31rl8.js → es-DJm3HFJt.js} +12 -1
  46. package/dist/admin/{es-C4IRHV5d.js → es-YvaTAtqY.js} +8 -1
  47. package/dist/admin/{es-DCamt1ek.mjs → es-pvPfNAld.mjs} +103 -1
  48. package/dist/admin/{fr-BOvvfEH7.mjs → fr-BvPjRiwr.mjs} +8 -1
  49. package/dist/admin/{fr-Dp5-XP29.mjs → fr-CKHZ0xxU.mjs} +19 -1
  50. package/dist/admin/{fr-iGeIfEcU.js → fr-CRM9VuAq.js} +12 -1
  51. package/dist/admin/{fr-CMWBNE5D.mjs → fr-CrIHmKYX.mjs} +12 -1
  52. package/dist/admin/{fr-COOsqexl.js → fr-Cx29jQ_g.js} +19 -1
  53. package/dist/admin/{fr-oW0t8bT5.mjs → fr-D4tL6Ag2.mjs} +103 -1
  54. package/dist/admin/{fr-Zkb8vfjN.js → fr-Di-U-rAH.js} +8 -1
  55. package/dist/admin/{fr-DpC44Ol8.js → fr-DrUYv2jh.js} +103 -1
  56. package/dist/admin/{index-BVjf1gVC.mjs → index-C4ksUkEm.mjs} +9183 -6353
  57. package/dist/admin/{index-64wc26Bl.js → index-C5D3VqLq.js} +9170 -6340
  58. package/dist/admin/{index-D_Fv8Non.mjs → index-CMYCZWOh.mjs} +1053 -190
  59. package/dist/admin/{index-D6Z7i8ba.js → index-DRyctF9s.js} +961 -98
  60. package/dist/admin/index.js +1 -1
  61. package/dist/admin/index.mjs +2 -2
  62. package/dist/admin/{math-vsK_06ZR.js → math-D6jmskGS.js} +1 -1
  63. package/dist/admin/{math-CIQ4Z_mY.mjs → math-DntdSWKX.mjs} +1 -1
  64. package/dist/admin/{pt-DALDvfBn.mjs → pt-B8x7v-Xw.mjs} +19 -1
  65. package/dist/admin/{pt-DXy7G1x7.js → pt-BYn2xx78.js} +19 -1
  66. package/dist/admin/{pt-Bo0Pm_Pt.js → pt-CojQcz-p.js} +103 -1
  67. package/dist/admin/{pt-uGpfRQLC.mjs → pt-CuoIihKx.mjs} +103 -1
  68. package/dist/admin/{pt-1IUyx6ae.js → pt-CzrN_3ui.js} +8 -1
  69. package/dist/admin/{pt-DFNgZ5_k.mjs → pt-DDlPJYtB.mjs} +12 -1
  70. package/dist/admin/{pt-BHmXk2d9.js → pt-DPVAycXJ.js} +12 -1
  71. package/dist/admin/{pt-etwsg3G4.mjs → pt-DdGagO99.mjs} +8 -1
  72. package/dist/admin/useT-Bpw__IXT.js +12 -0
  73. package/dist/admin/useT-Cb-R3kyA.mjs +13 -0
  74. package/dist/blocks/index.d.mts +124 -0
  75. package/dist/blocks/index.d.ts +124 -0
  76. package/dist/blocks/index.js +172 -3
  77. package/dist/blocks/index.mjs +172 -3
  78. package/dist/math/index.js +6 -2
  79. package/dist/math/index.mjs +6 -2
  80. package/dist/react/index.js +1376 -1067
  81. package/dist/react/index.mjs +1376 -1067
  82. package/dist/render/index.d.mts +22 -0
  83. package/dist/render/index.d.ts +22 -0
  84. package/dist/render/index.js +1376 -1067
  85. package/dist/render/index.mjs +1376 -1067
  86. package/dist/server/index.js +28894 -24197
  87. package/dist/server/index.mjs +28893 -24196
  88. package/dist/server/mcp-worker.js +11319 -0
  89. package/dist/vue/index.js +1376 -1067
  90. package/dist/vue/index.mjs +1376 -1067
  91. package/package.json +7 -7
  92. package/schema/magic-editor-x.schema.json +9 -1
  93. package/types/blocks.d.ts +124 -0
  94. package/types/index.d.ts +10 -1
  95. package/types/render.d.ts +22 -0
package/dist/vue/index.js CHANGED
@@ -374,11 +374,15 @@ var FOOTNOTE_ID = /^[A-Za-z0-9_-]{1,64}$/;
374
374
  var MAX_MATH_TEX = 1e4;
375
375
  var MAX_INLINE_TEX = 2e3;
376
376
  var MAX_FOOTNOTE_NOTE = 4e3;
377
+ var INLINE_FORMAT_ATTRIBUTES = Object.freeze({
378
+ span: ["data-mex-color", "data-mex-annotation", "data-mex-a-*"],
379
+ mark: ["data-mex-highlight"]
380
+ });
377
381
  var INLINE_ATTRIBUTES = Object.freeze({
378
382
  a: ["href", "target", "rel", "title", ...INTERNAL_LINK_ATTRIBUTES],
379
- span: ["class", "data-tooltip", MATH_ATTRIBUTE],
383
+ span: ["class", "data-tooltip", MATH_ATTRIBUTE, ...INLINE_FORMAT_ATTRIBUTES.span],
380
384
  sup: [...FOOTNOTE_ATTRIBUTES],
381
- mark: ["class"],
385
+ mark: ["class", ...INLINE_FORMAT_ATTRIBUTES.mark],
382
386
  u: ["class"],
383
387
  s: ["class"],
384
388
  code: ["class"]
@@ -695,6 +699,9 @@ var BLOCK_POLICIES = {
695
699
  if (typeof file.extension === "string") cleanFile.extension = plain(file.extension, 16);
696
700
  if (Number.isFinite(file.size)) cleanFile.size = file.size;
697
701
  if (typeof file.title === "string") cleanFile.title = plain(file.title, 255);
702
+ if (file.id !== void 0 && (Number.isInteger(file.id) || typeof file.id === "string"))
703
+ cleanFile.id = file.id;
704
+ if (typeof file.documentId === "string") cleanFile.documentId = plain(file.documentId, 64);
698
705
  return { file: cleanFile, title: plain(d.title, 255) };
699
706
  },
700
707
  embed: (d, inline) => ({
@@ -852,569 +859,901 @@ var nodesTextContent = (nodes) => {
852
859
  return out;
853
860
  };
854
861
 
855
- // shared/render/inline.mjs
856
- var DROP_WITH_CONTENT = /* @__PURE__ */ new Set([
857
- "script",
858
- "style",
859
- "textarea",
860
- "title",
861
- "xmp",
862
- "noscript",
863
- "noembed",
864
- "noframes",
865
- "template",
866
- "iframe",
867
- "object",
868
- "embed",
869
- "svg",
870
- "math",
871
- "select",
872
- "option",
873
- "plaintext"
862
+ // shared/inline-format.mjs
863
+ var TOKEN_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;
864
+ var COLOR_ATTRIBUTE = "data-mex-color";
865
+ var HIGHLIGHT_ATTRIBUTE = "data-mex-highlight";
866
+ var PALETTE_LIMITS = Object.freeze({ tokens: 24, label: 60, locales: 20 });
867
+ var DEFAULT_SURFACE = Object.freeze({
868
+ background: Object.freeze({ light: "#ffffff", dark: "#121212" }),
869
+ text: Object.freeze({ light: "#1f1f1f", dark: "#f2f2f2" })
870
+ });
871
+ var colorClass = (token) => `mex-color-${token}`;
872
+ var highlightClass = (token) => `mex-highlight-${token}`;
873
+
874
+ // shared/blocks/define.mjs
875
+ var BLOCK_FIELD_TYPES = Object.freeze([
876
+ "text",
877
+ "inline",
878
+ "url",
879
+ "enum",
880
+ "number",
881
+ "boolean",
882
+ "array",
883
+ "object"
874
884
  ]);
875
- var ALLOWED = new Set(INLINE_TAGS);
876
- var VOID = /* @__PURE__ */ new Set(["br"]);
877
- var MAX_INPUT = 5e5;
878
- var MAX_NODES = 5e4;
879
- var MAX_DEPTH = 64;
880
- var NAMED_ENTITIES = Object.freeze({
881
- amp: "&",
882
- lt: "<",
883
- gt: ">",
884
- quot: '"',
885
- apos: "'",
886
- nbsp: "\xA0",
887
- shy: "\xAD",
888
- copy: "\xA9",
889
- reg: "\xAE",
890
- trade: "\u2122",
891
- hellip: "\u2026",
892
- mdash: "\u2014",
893
- ndash: "\u2013",
894
- lsquo: "\u2018",
895
- rsquo: "\u2019",
896
- ldquo: "\u201C",
897
- rdquo: "\u201D",
898
- laquo: "\xAB",
899
- raquo: "\xBB",
900
- euro: "\u20AC",
901
- middot: "\xB7",
902
- bull: "\u2022",
903
- times: "\xD7",
904
- deg: "\xB0",
905
- tab: " ",
906
- newline: "\n",
907
- colon: ":",
908
- sol: "/",
909
- lpar: "(",
910
- rpar: ")"
885
+ var BLOCK_LIMITS = Object.freeze({
886
+ /** Fields per object (also the schema root). */
887
+ maxFields: 50,
888
+ /** Nesting of arrays and objects below the root. */
889
+ maxDepth: 4,
890
+ /** Largest `max` of a text or inline field. */
891
+ maxText: 1e5,
892
+ /** Default `max` of a text field. */
893
+ defaultText: 1e3,
894
+ /** Default `max` of an inline HTML field. */
895
+ defaultInline: 1e4,
896
+ /** Largest `max` of an array field. */
897
+ maxItems: 500,
898
+ /** Default `max` of an array field. */
899
+ defaultItems: 50,
900
+ /** Values of an enum field. */
901
+ maxEnumValues: 100,
902
+ /** Values cleaned per block; later array items are dropped. */
903
+ maxValues: 2e4,
904
+ /** Length of a URL value. */
905
+ maxUrl: 2048
911
906
  });
912
- var decodeEntities = (text) => String(text).replace(
913
- /&(#[xX][0-9a-fA-F]{1,8}|#[0-9]{1,10}|[A-Za-z][A-Za-z0-9]{1,31});?/g,
914
- (match, body) => {
915
- if (body[0] === "#") {
916
- const code = body[1] === "x" || body[1] === "X" ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
917
- if (!Number.isFinite(code) || code <= 0 || code > 1114111 || code >= 55296 && code <= 57343)
918
- return "\uFFFD";
919
- return String.fromCodePoint(code);
920
- }
921
- const named = NAMED_ENTITIES[body] ?? NAMED_ENTITIES[body.toLowerCase()];
922
- return named === void 0 ? match : named;
923
- }
924
- );
925
- var parseAttributes = (source) => {
926
- const out = {};
927
- const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
928
- let match;
929
- while (match = pattern.exec(source)) {
930
- const name = match[1].toLowerCase();
931
- if (Object.prototype.hasOwnProperty.call(out, name)) continue;
932
- const raw = match[2] ?? match[3] ?? match[4] ?? "";
933
- out[name] = decodeEntities(raw);
934
- }
935
- return out;
907
+ var BLOCK_PRESETS = Object.freeze(["article", "basic", "minimal"]);
908
+ var RESERVED_BLOCK_NAMES = Object.freeze([
909
+ "paragraph",
910
+ "header",
911
+ "list",
912
+ "checklist",
913
+ "quote",
914
+ "warning",
915
+ "alert",
916
+ "toggle",
917
+ "code",
918
+ "codeFlask",
919
+ "delimiter",
920
+ "toc",
921
+ "synced",
922
+ "table",
923
+ "embed",
924
+ "raw",
925
+ "image",
926
+ "simpleImage",
927
+ "gallery",
928
+ "video",
929
+ "audio",
930
+ "linkTool",
931
+ "attaches",
932
+ "personality",
933
+ "button",
934
+ "mediaLib",
935
+ "embeddedEntry",
936
+ "bold",
937
+ "italic",
938
+ "hyperlink",
939
+ "mention",
940
+ "marker",
941
+ "underline",
942
+ "strikethrough",
943
+ "inlineCode",
944
+ "tooltip",
945
+ "aiAssistant",
946
+ "alignmentTune",
947
+ "textVariant",
948
+ "indentTune"
949
+ ]);
950
+ var SDK_COMPATIBLE_NAMES = Object.freeze(["math"]);
951
+ var RESERVED = new Set(RESERVED_BLOCK_NAMES.map((name) => name.toLowerCase()));
952
+ var BLOCK_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{1,49}$/;
953
+ var KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
954
+ var FORBIDDEN_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
955
+ var DEFINITION_KEYS = /* @__PURE__ */ new Set([
956
+ "name",
957
+ "version",
958
+ "title",
959
+ "description",
960
+ "schema",
961
+ "sanitize",
962
+ "text",
963
+ "markdown",
964
+ "render",
965
+ "presets"
966
+ ]);
967
+ var FIELD_KEYS = {
968
+ text: ["max", "multiline", "default"],
969
+ inline: ["max", "default"],
970
+ url: ["schemes", "relative"],
971
+ enum: ["values", "default"],
972
+ number: ["min", "max", "integer", "default"],
973
+ boolean: ["default"],
974
+ array: ["items", "max"],
975
+ object: ["fields"]
936
976
  };
937
- var findTagEnd = (html, from) => {
938
- let quote = "";
939
- for (let i = from; i < html.length; i += 1) {
940
- const char = html[i];
941
- if (quote) {
942
- if (char === quote) quote = "";
943
- } else if (char === '"' || char === "'") quote = char;
944
- else if (char === ">") return i;
977
+ var BlockDefinitionError = class extends Error {
978
+ /**
979
+ * @param {string} message - Message naming the definition and the problem.
980
+ * @param {string} [code] - `INVALID_DEFINITION` | `RESERVED_NAME` | `NAME_TAKEN` | `REGISTRY_SEALED`.
981
+ */
982
+ constructor(message, code = "INVALID_DEFINITION") {
983
+ super(message);
984
+ this.name = "BlockDefinitionError";
985
+ this.code = code;
945
986
  }
946
- return -1;
947
987
  };
948
- var cleanAttributes = (tag, attribs, options = {}) => {
949
- const allowed = INLINE_ATTRIBUTES[tag] || [];
950
- const out = {};
951
- for (const name of allowed) {
952
- if (!Object.prototype.hasOwnProperty.call(attribs, name) || name.startsWith("data-mex-")) continue;
953
- const value = attribs[name];
954
- if (name === "href") {
955
- const url = sanitizeUrl(value);
956
- if (url) out.href = url;
957
- } else if (name === "target") {
958
- const target = sanitizeTarget(value);
959
- if (target) out.target = target;
960
- } else if (name === "rel") {
961
- const rel = String(value).split(/\s+/).filter((token) => /^[a-z-]{1,20}$/.test(token));
962
- if (rel.length) out.rel = rel.join(" ");
963
- } else if (name === "class") {
964
- const classes2 = String(value).split(/\s+/).filter((token) => (INLINE_CLASSES[tag] || []).includes(token));
965
- if (classes2.length) out.class = classes2.join(" ");
966
- } else {
967
- out[name] = String(value).slice(0, 2e3);
968
- }
969
- }
970
- if (tag === "a" && !options.inNote) Object.assign(out, cleanInternalLinkAttributes(attribs));
971
- return out;
988
+ var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
989
+ var fail = (where, message) => {
990
+ throw new BlockDefinitionError(`Magic Editor X block ${where}: ${message}`);
972
991
  };
973
- var MAX_MARKER_TEXT = 16;
974
- var isMathNode = (node) => node.type === "element" && node.tag === "span" && node.attrs[MATH_ATTRIBUTE] === "true";
975
- var isFootnoteNode = (node) => node.type === "element" && node.tag === "sup" && typeof node.attrs["data-mex-footnote"] === "string";
976
- var finalizeSpecial = (nodes, depth = 0) => {
977
- for (const node of nodes) {
978
- if (node.type !== "element") continue;
979
- if (isMathNode(node)) {
980
- const tex = nodesToText(node.children, { raw: true }).replace(/\u200b/g, "").slice(0, MAX_INLINE_TEX);
981
- node.children = tex ? [{ type: "text", value: tex }] : [];
982
- } else if (isFootnoteNode(node)) {
983
- const text = nodesToText(node.children, { raw: true }).slice(0, MAX_MARKER_TEXT);
984
- node.children = text ? [{ type: "text", value: text }] : [];
985
- } else if (depth < MAX_DEPTH) finalizeSpecial(node.children, depth + 1);
986
- }
987
- return nodes;
992
+ var boundedInt = (value, min, max, fallback, where, key) => {
993
+ if (value === void 0) return fallback;
994
+ if (!Number.isInteger(value) || value < min || value > max)
995
+ fail(where, `"${key}" must be an integer from ${min} to ${max}`);
996
+ return value;
988
997
  };
989
- var specialElement = (tag, attribs, options) => {
990
- if (tag === "span" && Object.prototype.hasOwnProperty.call(attribs, MATH_ATTRIBUTE)) {
991
- if (!/^(?:|true)$/.test(attribs[MATH_ATTRIBUTE])) return null;
992
- return { attrs: { [MATH_ATTRIBUTE]: "true" } };
993
- }
994
- if (tag === "sup" && !options.inNote) {
995
- const id = attribs["data-mex-footnote"];
996
- if (typeof id !== "string" || !FOOTNOTE_ID.test(id)) return null;
997
- const source = typeof attribs["data-mex-note"] === "string" ? attribs["data-mex-note"] : "";
998
- const note = parseInline(source.slice(0, MAX_FOOTNOTE_NOTE), { inNote: true });
999
- return { attrs: { "data-mex-footnote": id }, note };
998
+ var normalizeField = (input, where, depth) => {
999
+ if (!isObject2(input)) fail(where, 'a field must be an object with a "type"');
1000
+ const type = input.type;
1001
+ if (!BLOCK_FIELD_TYPES.includes(type)) fail(where, `unknown field type ${JSON.stringify(type)}`);
1002
+ for (const key of Object.keys(input))
1003
+ if (key !== "type" && key !== "label" && !FIELD_KEYS[type].includes(key))
1004
+ fail(where, `unknown option "${key}" for a ${type} field`);
1005
+ const out = { type };
1006
+ if (input.label !== void 0) {
1007
+ if (typeof input.label !== "string" || input.label.length > 100)
1008
+ fail(where, '"label" must be a string of at most 100 characters');
1009
+ out.label = input.label;
1000
1010
  }
1001
- return null;
1002
- };
1003
- var parseInline = (input, options = {}) => {
1004
- const html = typeof input === "string" ? input.slice(0, MAX_INPUT) : "";
1005
- const root = { type: "element", tag: "#root", attrs: {}, children: [] };
1006
- const stack = [root];
1007
- let nodes = 0;
1008
- let text = "";
1009
- const flush = () => {
1010
- if (!text) return;
1011
- const parent = stack[stack.length - 1];
1012
- const last = parent.children[parent.children.length - 1];
1013
- const value = decodeEntities(text);
1014
- if (last && last.type === "text") last.value += value;
1015
- else if (nodes < MAX_NODES) {
1016
- parent.children.push({ type: "text", value });
1017
- nodes += 1;
1018
- }
1019
- text = "";
1020
- };
1021
- let i = 0;
1022
- while (i < html.length) {
1023
- const lt = html.indexOf("<", i);
1024
- if (lt === -1) {
1025
- text += html.slice(i);
1011
+ switch (type) {
1012
+ case "text":
1013
+ case "inline": {
1014
+ out.max = boundedInt(
1015
+ input.max,
1016
+ 1,
1017
+ BLOCK_LIMITS.maxText,
1018
+ type === "text" ? BLOCK_LIMITS.defaultText : BLOCK_LIMITS.defaultInline,
1019
+ where,
1020
+ "max"
1021
+ );
1022
+ if (input.default !== void 0 && typeof input.default !== "string")
1023
+ fail(where, '"default" must be a string');
1024
+ out.default = (input.default || "").slice(0, out.max);
1025
+ if (type === "text") {
1026
+ if (input.multiline !== void 0 && typeof input.multiline !== "boolean")
1027
+ fail(where, '"multiline" must be a boolean');
1028
+ out.multiline = input.multiline === true;
1029
+ }
1026
1030
  break;
1027
1031
  }
1028
- text += html.slice(i, lt);
1029
- i = lt;
1030
- if (html.startsWith("<!--", i)) {
1031
- const end2 = html.indexOf("-->", i + 4);
1032
- flush();
1033
- i = end2 === -1 ? html.length : end2 + 3;
1034
- continue;
1035
- }
1036
- if (html.startsWith("<![CDATA[", i)) {
1037
- const end2 = html.indexOf("]]>", i + 9);
1038
- flush();
1039
- i = end2 === -1 ? html.length : end2 + 3;
1040
- continue;
1041
- }
1042
- if (html[i + 1] === "!" || html[i + 1] === "?") {
1043
- const end2 = html.indexOf(">", i + 2);
1044
- flush();
1045
- i = end2 === -1 ? html.length : end2 + 1;
1046
- continue;
1047
- }
1048
- const closing = html[i + 1] === "/";
1049
- const nameMatch = /^[A-Za-z][A-Za-z0-9-]{0,40}/.exec(html.slice(i + (closing ? 2 : 1), i + 45));
1050
- if (!nameMatch) {
1051
- text += "<";
1052
- i += 1;
1053
- continue;
1032
+ case "url": {
1033
+ const schemes = input.schemes === void 0 ? ["http", "https"] : input.schemes;
1034
+ if (!Array.isArray(schemes) || !schemes.length || schemes.some((scheme) => !LINK_SCHEMES.includes(scheme)))
1035
+ fail(where, `"schemes" must be a non-empty list of ${LINK_SCHEMES.join(", ")}`);
1036
+ if (input.relative !== void 0 && typeof input.relative !== "boolean")
1037
+ fail(where, '"relative" must be a boolean');
1038
+ out.schemes = Object.freeze([...new Set(schemes)]);
1039
+ out.relative = input.relative !== false;
1040
+ break;
1054
1041
  }
1055
- const end = findTagEnd(html, i + 1);
1056
- if (end === -1) {
1057
- text += html.slice(i);
1042
+ case "enum": {
1043
+ const values = input.values;
1044
+ 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)
1045
+ fail(
1046
+ where,
1047
+ `"values" must be 1 to ${BLOCK_LIMITS.maxEnumValues} distinct strings (1-100 characters)`
1048
+ );
1049
+ out.values = Object.freeze([...values]);
1050
+ if (input.default !== void 0 && !values.includes(input.default))
1051
+ fail(where, '"default" must be one of "values"');
1052
+ out.default = input.default === void 0 ? values[0] : input.default;
1058
1053
  break;
1059
1054
  }
1060
- flush();
1061
- const tag = nameMatch[0].toLowerCase();
1062
- const body = html.slice(i + (closing ? 2 : 1) + nameMatch[0].length, end);
1063
- i = end + 1;
1064
- if (closing) {
1065
- if (!ALLOWED.has(tag)) continue;
1066
- for (let s = stack.length - 1; s > 0; s -= 1) {
1067
- if (stack[s].tag === tag) {
1068
- stack.length = s;
1069
- break;
1070
- }
1055
+ case "number": {
1056
+ for (const key of ["min", "max", "default"])
1057
+ if (input[key] !== void 0 && (typeof input[key] !== "number" || !Number.isFinite(input[key])))
1058
+ fail(where, `"${key}" must be a finite number`);
1059
+ if (input.integer !== void 0 && typeof input.integer !== "boolean")
1060
+ fail(where, '"integer" must be a boolean');
1061
+ out.integer = input.integer === true;
1062
+ out.min = input.min === void 0 ? -Number.MAX_SAFE_INTEGER : input.min;
1063
+ out.max = input.max === void 0 ? Number.MAX_SAFE_INTEGER : input.max;
1064
+ if (out.min > out.max) fail(where, '"min" must not be greater than "max"');
1065
+ if (input.default !== void 0) {
1066
+ if (input.default < out.min || input.default > out.max || out.integer && !Number.isInteger(input.default))
1067
+ fail(where, '"default" must be a valid value of the field');
1068
+ out.default = input.default;
1071
1069
  }
1072
- continue;
1073
- }
1074
- if (DROP_WITH_CONTENT.has(tag)) {
1075
- const selfClosing = /\/\s*$/.test(body);
1076
- if (selfClosing) continue;
1077
- const closeIndex = html.slice(i).search(new RegExp(`</${tag}[\\s/>]`, "i"));
1078
- if (closeIndex === -1) break;
1079
- const closeEnd = html.indexOf(">", i + closeIndex);
1080
- i = closeEnd === -1 ? html.length : closeEnd + 1;
1081
- continue;
1070
+ break;
1082
1071
  }
1083
- if (!ALLOWED.has(tag) || nodes >= MAX_NODES) continue;
1084
- const attribs = parseAttributes(body);
1085
- const special = specialElement(tag, attribs, options);
1086
- const element = {
1087
- type: "element",
1088
- tag,
1089
- attrs: special ? special.attrs : cleanAttributes(tag, attribs, options),
1090
- children: []
1091
- };
1092
- if (special && special.note) element.note = special.note;
1093
- stack[stack.length - 1].children.push(element);
1094
- nodes += 1;
1095
- if (!VOID.has(tag) && stack.length < MAX_DEPTH) stack.push(element);
1072
+ case "boolean":
1073
+ if (input.default !== void 0 && typeof input.default !== "boolean")
1074
+ fail(where, '"default" must be a boolean');
1075
+ out.default = input.default === true;
1076
+ break;
1077
+ case "array":
1078
+ if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1079
+ out.max = boundedInt(input.max, 1, BLOCK_LIMITS.maxItems, BLOCK_LIMITS.defaultItems, where, "max");
1080
+ out.items = normalizeField(input.items, `${where}[]`, depth + 1);
1081
+ break;
1082
+ case "object":
1083
+ if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1084
+ out.fields = normalizeFields(input.fields, where, depth + 1);
1085
+ break;
1086
+ default:
1087
+ break;
1096
1088
  }
1097
- flush();
1098
- return finalizeSpecial(root.children);
1089
+ return Object.freeze(out);
1099
1090
  };
1100
- var resolveLinkAttributes = (attrs, resolver) => {
1101
- if (typeof resolver !== "function" || !attrs["data-mex-uid"] || !attrs["data-mex-document-id"])
1102
- return attrs;
1103
- let result;
1104
- try {
1105
- result = resolver({
1106
- uid: attrs["data-mex-uid"],
1107
- documentId: attrs["data-mex-document-id"],
1108
- locale: attrs["data-mex-locale"] || null,
1109
- href: attrs.href || null,
1110
- ...isMentionLink(attrs) ? { mention: true } : {}
1111
- });
1112
- } catch {
1113
- result = void 0;
1091
+ var normalizeFields = (input, where, depth) => {
1092
+ if (!isObject2(input)) fail(where, '"fields" must be an object of field descriptors');
1093
+ const keys = Object.keys(input);
1094
+ if (keys.length < 1 || keys.length > BLOCK_LIMITS.maxFields)
1095
+ fail(where, `an object needs 1 to ${BLOCK_LIMITS.maxFields} fields`);
1096
+ const out = /* @__PURE__ */ Object.create(null);
1097
+ for (const key of keys) {
1098
+ if (!KEY_PATTERN.test(key) || FORBIDDEN_KEYS2.has(key))
1099
+ fail(where, `field name ${JSON.stringify(key)} must match ${KEY_PATTERN}`);
1100
+ out[key] = normalizeField(input[key], `${where}.${key}`, depth);
1114
1101
  }
1115
- if (result === false) return null;
1116
- if (typeof result === "string") {
1117
- const url = sanitizeUrl(result);
1118
- if (url) return { ...attrs, href: url };
1102
+ return Object.freeze(out);
1103
+ };
1104
+ var blockNameProblem = (name) => {
1105
+ if (typeof name !== "string" || !BLOCK_NAME_PATTERN.test(name))
1106
+ return `the name must match ${BLOCK_NAME_PATTERN}`;
1107
+ if (RESERVED.has(name.toLowerCase())) return `"${name}" is a built-in tool name`;
1108
+ return null;
1109
+ };
1110
+ var defineBlock = (definition) => {
1111
+ if (!isObject2(definition))
1112
+ throw new BlockDefinitionError("Magic Editor X block: the definition must be an object");
1113
+ const label3 = typeof definition.name === "string" ? `"${definition.name.slice(0, 50)}"` : "(no name)";
1114
+ for (const key of Object.keys(definition))
1115
+ if (!DEFINITION_KEYS.has(key)) fail(label3, `unknown key "${key}"`);
1116
+ const problem = blockNameProblem(definition.name);
1117
+ if (problem)
1118
+ throw new BlockDefinitionError(
1119
+ `Magic Editor X block ${label3}: ${problem}`,
1120
+ problem.includes("built-in") ? "RESERVED_NAME" : "INVALID_DEFINITION"
1121
+ );
1122
+ const out = {
1123
+ name: definition.name,
1124
+ version: boundedInt(definition.version, 1, 1e6, 1, label3, "version")
1125
+ };
1126
+ for (const [key, max] of [
1127
+ ["title", 100],
1128
+ ["description", 500]
1129
+ ]) {
1130
+ if (definition[key] === void 0) continue;
1131
+ if (typeof definition[key] !== "string" || definition[key].length > max)
1132
+ fail(label3, `"${key}" must be a string of at most ${max} characters`);
1133
+ out[key] = definition[key];
1119
1134
  }
1120
- return attrs;
1135
+ out.schema = normalizeFields(definition.schema, `${label3} schema`, 0);
1136
+ for (const key of ["sanitize", "text", "markdown", "render"]) {
1137
+ if (definition[key] === void 0) continue;
1138
+ if (typeof definition[key] !== "function") fail(label3, `"${key}" must be a function`);
1139
+ out[key] = definition[key];
1140
+ }
1141
+ const presets = definition.presets === void 0 ? [] : definition.presets;
1142
+ if (!Array.isArray(presets) || presets.some((preset) => !BLOCK_PRESETS.includes(preset)))
1143
+ fail(label3, `"presets" must list some of ${BLOCK_PRESETS.join(", ")}`);
1144
+ out.presets = Object.freeze([...new Set(presets)]);
1145
+ return Object.freeze(out);
1121
1146
  };
1122
- var ATTRIBUTE_ORDER = [
1123
- "href",
1124
- "target",
1125
- "rel",
1126
- "title",
1127
- "class",
1128
- "data-tooltip",
1129
- "data-mex-uid",
1130
- "data-mex-document-id",
1131
- "data-mex-locale",
1132
- "data-mex-mention",
1133
- MATH_ATTRIBUTE,
1134
- "data-mex-footnote",
1135
- "data-mex-note"
1136
- ];
1137
- var RENDER_STATE = /* @__PURE__ */ Symbol.for("magic-editor-x.render-state");
1138
- var storedNote = (note) => serializeNodes(inlineNodesToRender(note || [], { storage: true }));
1139
- var MENTION_CLASS = "mex-mention";
1140
- var inlineNodesToRender = (nodes, options = {}) => {
1141
- const out = [];
1142
- const state = options[RENDER_STATE];
1143
- for (const node of nodes) {
1144
- if (node.type === "text") {
1145
- out.push({ type: "text", value: node.value });
1146
- continue;
1147
- }
1148
- if (node.tag === "br") {
1149
- out.push({ type: "element", tag: "br", attrs: {}, children: [] });
1150
- continue;
1151
- }
1152
- if (isMathNode(node)) {
1153
- const tex = nodesToText(node.children);
1154
- if (state && !options.storage) {
1155
- if (tex.trim()) out.push(state.math(tex, false));
1156
- continue;
1147
+ var cleanValue = (field, value, inline, budget) => {
1148
+ budget.left -= 1;
1149
+ switch (field.type) {
1150
+ case "text":
1151
+ return typeof value === "string" ? value.slice(0, field.max) : field.default;
1152
+ case "inline":
1153
+ return inline(typeof value === "string" ? value.slice(0, field.max) : field.default);
1154
+ case "url":
1155
+ return typeof value === "string" ? sanitizeUrl(value.slice(0, BLOCK_LIMITS.maxUrl), {
1156
+ schemes: field.schemes,
1157
+ allowRelative: field.relative
1158
+ }) : "";
1159
+ case "enum":
1160
+ return typeof value === "string" && field.values.includes(value) ? value : field.default;
1161
+ case "number":
1162
+ return typeof value === "number" && Number.isFinite(value) && value >= field.min && value <= field.max && (!field.integer || Number.isInteger(value)) ? value : field.default;
1163
+ case "boolean":
1164
+ return typeof value === "boolean" ? value : field.default;
1165
+ case "array": {
1166
+ const out = [];
1167
+ if (!Array.isArray(value)) return out;
1168
+ for (const item of value) {
1169
+ if (out.length >= field.max || budget.left <= 0) break;
1170
+ if (!matchesType(field.items, item)) continue;
1171
+ const clean2 = cleanValue(field.items, item, inline, budget);
1172
+ if (clean2 !== void 0) out.push(clean2);
1157
1173
  }
1158
- out.push({
1159
- type: "element",
1160
- tag: "span",
1161
- attrs: { [MATH_ATTRIBUTE]: "true" },
1162
- children: tex ? [{ type: "text", value: tex }] : []
1163
- });
1164
- continue;
1174
+ return out;
1165
1175
  }
1166
- if (isFootnoteNode(node)) {
1167
- if (state && !options.storage) {
1168
- out.push(state.footnote(node));
1176
+ case "object":
1177
+ return cleanObject(field.fields, isObject2(value) ? value : {}, inline, budget);
1178
+ default:
1179
+ return void 0;
1180
+ }
1181
+ };
1182
+ var matchesType = (field, item) => {
1183
+ switch (field.type) {
1184
+ case "text":
1185
+ case "inline":
1186
+ case "url":
1187
+ case "enum":
1188
+ return typeof item === "string";
1189
+ case "number":
1190
+ return typeof item === "number";
1191
+ case "boolean":
1192
+ return typeof item === "boolean";
1193
+ case "array":
1194
+ return Array.isArray(item);
1195
+ default:
1196
+ return isObject2(item);
1197
+ }
1198
+ };
1199
+ var cleanObject = (fields, value, inline, budget) => {
1200
+ const out = {};
1201
+ for (const key of Object.keys(fields)) {
1202
+ const own = Object.prototype.hasOwnProperty.call(value, key) ? value[key] : void 0;
1203
+ const clean2 = cleanValue(fields[key], own, inline, budget);
1204
+ if (clean2 !== void 0) out[key] = clean2;
1205
+ }
1206
+ return out;
1207
+ };
1208
+ var eachLeaf = (fields, data, visit) => {
1209
+ const walk = (field, value, path, depth) => {
1210
+ if (depth > BLOCK_LIMITS.maxDepth + 1) return;
1211
+ if (field.type === "array") {
1212
+ if (!Array.isArray(value)) return;
1213
+ value.slice(0, field.max).forEach((item, index) => walk(field.items, item, [...path, index], depth + 1));
1214
+ } else if (field.type === "object") {
1215
+ if (!isObject2(value)) return;
1216
+ for (const key of Object.keys(field.fields))
1217
+ if (Object.prototype.hasOwnProperty.call(value, key))
1218
+ walk(field.fields[key], value[key], [...path, key], depth + 1);
1219
+ } else visit(field, value, path);
1220
+ };
1221
+ if (!isObject2(data)) return;
1222
+ for (const key of Object.keys(fields))
1223
+ if (Object.prototype.hasOwnProperty.call(data, key)) walk(fields[key], data[key], [key], 0);
1224
+ };
1225
+ var fieldAt = (fields, path) => {
1226
+ let current = { type: "object", fields };
1227
+ for (const part of String(path).split(".")) {
1228
+ if (!part) continue;
1229
+ if (current.type === "array") {
1230
+ if (/^\d+$/.test(part)) {
1231
+ current = current.items;
1169
1232
  continue;
1170
1233
  }
1171
- const attrs2 = { "data-mex-footnote": node.attrs["data-mex-footnote"] };
1172
- const note = storedNote(node.note);
1173
- if (note) attrs2["data-mex-note"] = note;
1174
- out.push({ type: "element", tag: "sup", attrs: attrs2, children: inlineNodesToRender(node.children, options) });
1175
- continue;
1234
+ return null;
1176
1235
  }
1177
- let attrs = node.attrs;
1178
- if (node.tag === "a") {
1179
- attrs = resolveLinkAttributes(attrs, options.links);
1180
- if (!attrs || !attrs.href) {
1181
- out.push(...inlineNodesToRender(node.children, options));
1182
- continue;
1183
- }
1184
- if (attrs.target === "_blank") {
1185
- const rel = new Set(
1186
- String(attrs.rel || "").split(/\s+/).filter(Boolean)
1187
- );
1188
- rel.add("noopener");
1189
- rel.add("noreferrer");
1190
- attrs = { ...attrs, rel: Array.from(rel).sort().join(" ") };
1236
+ if (current.type !== "object" || !Object.prototype.hasOwnProperty.call(current.fields, part)) return null;
1237
+ current = current.fields[part];
1238
+ }
1239
+ return current;
1240
+ };
1241
+ var compiled = /* @__PURE__ */ new WeakMap();
1242
+ var compileBlock = (definition) => {
1243
+ if (definition && typeof definition === "object" && compiled.has(definition))
1244
+ return compiled.get(definition);
1245
+ const def = defineBlock(definition && typeof definition === "object" ? { ...definition } : definition);
1246
+ const schema = def.schema;
1247
+ const run = (data, inline) => cleanObject(schema, isObject2(data) ? data : {}, inline, { left: BLOCK_LIMITS.maxValues });
1248
+ const result = Object.freeze({
1249
+ ...def,
1250
+ /**
1251
+ * Cleans untrusted block data (unknown keys dropped, values bounded).
1252
+ * The optional `sanitize` hook runs on the clean data; its result is
1253
+ * cleaned again, so it cannot add keys or unsafe values. A hook that
1254
+ * throws is ignored (the clean data is used).
1255
+ * @param {unknown} data - Block data.
1256
+ * @param {(html: string) => string} inline - Inline HTML sanitiser of the caller.
1257
+ * @returns {object} Clean data.
1258
+ */
1259
+ clean: (data, inline) => {
1260
+ const first = run(data, inline);
1261
+ if (!def.sanitize) return first;
1262
+ let next;
1263
+ try {
1264
+ next = def.sanitize(copyData(first), { sanitizeUrl });
1265
+ } catch {
1266
+ return first;
1191
1267
  }
1192
- if (!options.storage && isMentionLink(attrs)) attrs = { ...attrs, class: MENTION_CLASS };
1193
- }
1194
- const ordered = {};
1195
- for (const name of ATTRIBUTE_ORDER) {
1196
- if (attrs[name] !== void 0 && attrs[name] !== "") ordered[name] = String(attrs[name]);
1268
+ return isObject2(next) ? run(next, inline) : first;
1269
+ },
1270
+ /**
1271
+ * Text fields of the data in schema order: `{ path, kind, value }`
1272
+ * (`html` for inline fields, `plain` for text fields).
1273
+ * @param {unknown} data - Block data.
1274
+ * @returns {Array<{ path: Array<string|number>, kind: 'html'|'plain', value: string }>} Fields.
1275
+ */
1276
+ fields: (data) => {
1277
+ const out = [];
1278
+ eachLeaf(schema, data, (field, value, path) => {
1279
+ if (typeof value !== "string") return;
1280
+ if (field.type === "inline") out.push({ path, kind: "html", value });
1281
+ else if (field.type === "text") out.push({ path, kind: "plain", value });
1282
+ });
1283
+ return out;
1284
+ },
1285
+ /**
1286
+ * Non-empty URL values: `{ path, value }`.
1287
+ * @param {unknown} data - Block data.
1288
+ * @returns {Array<{ path: Array<string|number>, value: string }>} URLs.
1289
+ */
1290
+ urls: (data) => {
1291
+ const out = [];
1292
+ eachLeaf(schema, data, (field, value, path) => {
1293
+ if (field.type === "url" && typeof value === "string" && value) out.push({ path, value });
1294
+ });
1295
+ return out;
1296
+ },
1297
+ /**
1298
+ * Kind of the value at a dotted path, for the version diff.
1299
+ * @param {string} path - Dotted path.
1300
+ * @returns {'inline'|'plain'|'value'} Kind.
1301
+ */
1302
+ kindOf: (path) => {
1303
+ const field = fieldAt(schema, path);
1304
+ if (!field) return "value";
1305
+ if (field.type === "inline") return "inline";
1306
+ if (field.type === "text") return "plain";
1307
+ return "value";
1197
1308
  }
1198
- out.push({
1199
- type: "element",
1200
- tag: node.tag,
1201
- attrs: ordered,
1202
- children: inlineNodesToRender(node.children, options)
1203
- });
1309
+ });
1310
+ compiled.set(result, result);
1311
+ if (definition && typeof definition === "object") compiled.set(definition, result);
1312
+ return result;
1313
+ };
1314
+ var copyData = (value) => {
1315
+ if (Array.isArray(value)) return value.map(copyData);
1316
+ if (isObject2(value)) {
1317
+ const out = {};
1318
+ for (const [key, child] of Object.entries(value)) out[key] = copyData(child);
1319
+ return out;
1204
1320
  }
1205
- return out;
1321
+ return value;
1206
1322
  };
1207
- var inlineToNodes = (html, options) => inlineNodesToRender(parseInline(html), options);
1208
- var nodesToHtml = (nodes, options = {}) => serializeNodes(inlineNodesToRender(nodes, options));
1209
- var nodesToText = (nodes, options = {}) => nodes.map((node) => {
1210
- if (node.type === "text") return node.value;
1211
- if (node.tag === "br") return "\n";
1212
- if (!options.raw && isFootnoteNode(node))
1213
- return typeof options.footnote === "function" ? options.footnote(node) : "";
1214
- return nodesToText(node.children, options);
1215
- }).join("");
1216
- var inlineToHtml = (html, options) => nodesToHtml(parseInline(html), options);
1217
- var inlineToText = (html, options) => nodesToText(parseInline(html), options).replace(/\u00a0/g, " ");
1218
-
1219
- // shared/render/mathml.mjs
1220
- var MATHML_TAGS = Object.freeze([
1221
- "math",
1222
- "semantics",
1223
- "annotation",
1224
- "mrow",
1225
- "mi",
1226
- "mn",
1227
- "mo",
1228
- "ms",
1229
- "mtext",
1230
- "mspace",
1231
- "msub",
1232
- "msup",
1233
- "msubsup",
1234
- "munder",
1235
- "mover",
1236
- "munderover",
1237
- "mfrac",
1238
- "msqrt",
1239
- "mroot",
1240
- "mstyle",
1241
- "merror",
1242
- "mpadded",
1243
- "mphantom",
1244
- "mtable",
1245
- "mtr",
1246
- "mtd",
1247
- "mlabeledtr",
1248
- "mmultiscripts",
1249
- "mprescripts",
1250
- "none",
1251
- "menclose"
1323
+ var listCache = /* @__PURE__ */ new WeakMap();
1324
+ var compileBlockList = (list) => {
1325
+ if (!Array.isArray(list)) return /* @__PURE__ */ new Map();
1326
+ if (listCache.has(list)) return listCache.get(list);
1327
+ const map = /* @__PURE__ */ new Map();
1328
+ for (const definition of list) {
1329
+ const def = compileBlock(definition);
1330
+ map.set(def.name, def);
1331
+ }
1332
+ listCache.set(list, map);
1333
+ return map;
1334
+ };
1335
+
1336
+ // shared/blocks/annotations.mjs
1337
+ var ANNOTATION_ATTRIBUTE = "data-mex-annotation";
1338
+ var ANNOTATION_VALUE_PREFIX = "data-mex-a-";
1339
+ var ANNOTATION_NAME = /^[a-z][a-z0-9-]{1,39}$/;
1340
+ var ANNOTATION_KEY = /^[a-z][a-z0-9]{0,23}$/;
1341
+ var ANNOTATION_FIELD_TYPES = Object.freeze(["text", "enum", "url"]);
1342
+ var ANNOTATION_LIMITS = Object.freeze({
1343
+ attributes: 8,
1344
+ text: 1e3,
1345
+ textDefault: 200,
1346
+ values: 50,
1347
+ registered: 50,
1348
+ label: 100,
1349
+ resolveItems: 200
1350
+ });
1351
+ var ANNOTATION_PRESETS = Object.freeze(["full", "article", "basic", "minimal"]);
1352
+ var ANNOTATION_RENDER_TAGS = Object.freeze([
1353
+ "abbr",
1354
+ "dfn",
1355
+ "span",
1356
+ "a",
1357
+ "mark",
1358
+ "cite",
1359
+ "q",
1360
+ "small",
1361
+ "em",
1362
+ "strong",
1363
+ "b",
1364
+ "i",
1365
+ "u",
1366
+ "s",
1367
+ "time",
1368
+ "data",
1369
+ "bdi",
1370
+ "kbd",
1371
+ "var",
1372
+ "ins",
1373
+ "del"
1252
1374
  ]);
1253
- var TAGS = new Set(MATHML_TAGS);
1254
- var COMMON_ATTRIBUTES = /* @__PURE__ */ new Set([
1255
- "dir",
1256
- "displaystyle",
1257
- "scriptlevel",
1258
- "mathvariant",
1259
- "mathsize",
1260
- "mathcolor",
1261
- "mathbackground"
1375
+ var ANNOTATION_SHORTCUTS = Object.freeze(["CMD+SHIFT+0", "CMD+SHIFT+1", "CMD+SHIFT+8"]);
1376
+ var ABBREVIATION = "abbreviation";
1377
+ var isObject3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1378
+ var fail2 = (name, message, code = "INVALID_DEFINITION") => {
1379
+ throw new BlockDefinitionError(`Magic Editor X inline annotation ${name}: ${message}`, code);
1380
+ };
1381
+ var defined = /* @__PURE__ */ new WeakSet();
1382
+ var cleanText = (value, max) => typeof value === "string" ? value.trim().slice(0, max).trim() : "";
1383
+ var normalizeAttribute = (where, input) => {
1384
+ if (!isObject3(input)) fail2(where, 'an attribute must be an object with a "type"');
1385
+ const { type } = input;
1386
+ if (!ANNOTATION_FIELD_TYPES.includes(type)) fail2(where, `unknown attribute type ${JSON.stringify(type)}`);
1387
+ const allowed = { text: ["max"], enum: ["values"], url: ["schemes", "relative"] }[type];
1388
+ for (const key of Object.keys(input))
1389
+ if (!["type", "label", "required", ...allowed].includes(key))
1390
+ fail2(where, `unknown option "${key}" for a ${type} attribute`);
1391
+ const out = { type, required: input.required === true };
1392
+ if (input.label !== void 0) {
1393
+ if (typeof input.label !== "string" || input.label.length > ANNOTATION_LIMITS.label)
1394
+ fail2(where, `"label" must be a string of at most ${ANNOTATION_LIMITS.label} characters`);
1395
+ out.label = input.label;
1396
+ }
1397
+ if (input.required !== void 0 && typeof input.required !== "boolean")
1398
+ fail2(where, '"required" must be a boolean');
1399
+ if (type === "text") {
1400
+ const max = input.max === void 0 ? ANNOTATION_LIMITS.textDefault : input.max;
1401
+ if (!Number.isInteger(max) || max < 1 || max > ANNOTATION_LIMITS.text)
1402
+ fail2(where, `"max" must be an integer from 1 to ${ANNOTATION_LIMITS.text}`);
1403
+ out.max = max;
1404
+ } else if (type === "enum") {
1405
+ const { values } = input;
1406
+ if (!Array.isArray(values) || !values.length || values.length > ANNOTATION_LIMITS.values || !values.every((value) => typeof value === "string" && value.length >= 1 && value.length <= 100) || new Set(values).size !== values.length)
1407
+ fail2(where, `"values" must be 1 to ${ANNOTATION_LIMITS.values} distinct strings`);
1408
+ out.values = Object.freeze([...values]);
1409
+ } else {
1410
+ const schemes = input.schemes === void 0 ? ["http", "https"] : input.schemes;
1411
+ if (!Array.isArray(schemes) || !schemes.length || !schemes.every((scheme) => LINK_SCHEMES.includes(scheme)))
1412
+ fail2(where, `"schemes" must be a non-empty subset of ${LINK_SCHEMES.join(", ")}`);
1413
+ if (input.relative !== void 0 && typeof input.relative !== "boolean")
1414
+ fail2(where, '"relative" must be a boolean');
1415
+ out.schemes = Object.freeze([...new Set(schemes)]);
1416
+ out.relative = input.relative !== false;
1417
+ }
1418
+ return Object.freeze(out);
1419
+ };
1420
+ var defineInlineAnnotation = (definition) => {
1421
+ if (!isObject3(definition)) fail2("(unnamed)", "the definition must be an object");
1422
+ const { name } = definition;
1423
+ if (typeof name !== "string" || !ANNOTATION_NAME.test(name))
1424
+ fail2(JSON.stringify(name), "the name must match /^[a-z][a-z0-9-]{1,39}$/");
1425
+ for (const key of Object.keys(definition))
1426
+ if (!["name", "label", "description", "attributes", "presets", "resolve", "render", "shortcut"].includes(
1427
+ key
1428
+ ))
1429
+ fail2(name, `unknown key "${key}"`);
1430
+ for (const key of ["label", "description"])
1431
+ if (definition[key] !== void 0 && (typeof definition[key] !== "string" || definition[key].length > (key === "label" ? 100 : 500)))
1432
+ fail2(name, `"${key}" must be a short string`);
1433
+ if (!isObject3(definition.attributes)) fail2(name, '"attributes" must be an object');
1434
+ const keys = Object.keys(definition.attributes);
1435
+ if (keys.length > ANNOTATION_LIMITS.attributes)
1436
+ fail2(name, `at most ${ANNOTATION_LIMITS.attributes} attributes`);
1437
+ const attributes = {};
1438
+ for (const key of keys) {
1439
+ if (!ANNOTATION_KEY.test(key)) fail2(name, `attribute key "${key}" must match /^[a-z][a-z0-9]{0,23}$/`);
1440
+ attributes[key] = normalizeAttribute(`${name}.${key}`, definition.attributes[key]);
1441
+ }
1442
+ const presets = definition.presets === void 0 ? [] : definition.presets;
1443
+ if (!Array.isArray(presets) || !presets.every((preset) => ANNOTATION_PRESETS.includes(preset)))
1444
+ fail2(name, `"presets" must list only ${ANNOTATION_PRESETS.join(", ")}`);
1445
+ if (definition.shortcut !== void 0 && !ANNOTATION_SHORTCUTS.includes(definition.shortcut))
1446
+ fail2(name, `"shortcut" must be one of ${ANNOTATION_SHORTCUTS.join(", ")}`);
1447
+ for (const key of ["resolve", "render"])
1448
+ if (definition[key] !== void 0 && typeof definition[key] !== "function")
1449
+ fail2(name, `"${key}" must be a function`);
1450
+ const out = Object.freeze({
1451
+ name,
1452
+ label: definition.label || name,
1453
+ ...definition.description ? { description: definition.description } : {},
1454
+ attributes: Object.freeze(attributes),
1455
+ presets: Object.freeze([...new Set(presets)]),
1456
+ ...definition.shortcut ? { shortcut: definition.shortcut } : {},
1457
+ ...definition.resolve ? { resolve: definition.resolve } : {},
1458
+ ...definition.render ? { render: definition.render } : {}
1459
+ });
1460
+ defined.add(out);
1461
+ return out;
1462
+ };
1463
+ var cleanAnnotationAttributes = (definition, raw) => {
1464
+ const source = raw && typeof raw === "object" ? raw : {};
1465
+ const out = {};
1466
+ for (const [key, field] of Object.entries(definition.attributes)) {
1467
+ const value = Object.prototype.hasOwnProperty.call(source, key) ? source[key] : void 0;
1468
+ let clean2;
1469
+ if (field.type === "text") clean2 = cleanText(value, field.max);
1470
+ else if (field.type === "enum")
1471
+ clean2 = typeof value === "string" && field.values.includes(value) ? value : "";
1472
+ else clean2 = sanitizeUrl(value, { schemes: field.schemes, allowRelative: field.relative });
1473
+ if (clean2) out[key] = clean2;
1474
+ else if (field.required) return null;
1475
+ }
1476
+ return out;
1477
+ };
1478
+ var abbreviationAnnotation = defineInlineAnnotation({
1479
+ name: ABBREVIATION,
1480
+ label: "Abbreviation",
1481
+ description: "Short form with its full form (shown as a tooltip and read by screen readers).",
1482
+ attributes: { title: { type: "text", max: 200, required: true, label: "Full form" } },
1483
+ render: (annotation) => ({ tag: "abbr", attrs: { title: annotation.attrs.title } })
1484
+ });
1485
+ var registry2 = /* @__PURE__ */ new Map();
1486
+ var activeAnnotation = (name) => {
1487
+ if (name === ABBREVIATION) return abbreviationAnnotation;
1488
+ return typeof name === "string" && registry2.has(name) ? registry2.get(name) : null;
1489
+ };
1490
+ var CLASS_TOKEN = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;
1491
+ var RENDER_ATTRIBUTES = /* @__PURE__ */ new Set(["title", "class", "lang", "dir", "href", "datetime", "value", "cite"]);
1492
+ var cleanAnnotationWrapper = (out) => {
1493
+ if (!isObject3(out) || !ANNOTATION_RENDER_TAGS.includes(out.tag)) return null;
1494
+ const attrs = {};
1495
+ for (const [name, raw] of Object.entries(isObject3(out.attrs) ? out.attrs : {})) {
1496
+ if (raw === void 0 || raw === null || raw === false) continue;
1497
+ if (!["string", "number"].includes(typeof raw)) continue;
1498
+ const allowed = RENDER_ATTRIBUTES.has(name) || name === "aria-label" || name.startsWith("data-") && !name.startsWith("data-mex-");
1499
+ if (!allowed || !isSafeAttributeName(name)) continue;
1500
+ const text = String(raw).slice(0, 2e3);
1501
+ if (name === "href" || name === "cite") {
1502
+ if (out.tag !== "a" && name === "href") continue;
1503
+ const url = sanitizeUrl(text);
1504
+ if (url) attrs[name] = url;
1505
+ } else if (name === "class") {
1506
+ const classes2 = text.split(/\s+/).filter((token) => CLASS_TOKEN.test(token));
1507
+ if (classes2.length) attrs.class = classes2.join(" ");
1508
+ } else if (text) attrs[name] = text;
1509
+ }
1510
+ return { tag: out.tag, attrs };
1511
+ };
1512
+
1513
+ // shared/render/inline.mjs
1514
+ var DROP_WITH_CONTENT = /* @__PURE__ */ new Set([
1515
+ "script",
1516
+ "style",
1517
+ "textarea",
1518
+ "title",
1519
+ "xmp",
1520
+ "noscript",
1521
+ "noembed",
1522
+ "noframes",
1523
+ "template",
1524
+ "iframe",
1525
+ "object",
1526
+ "embed",
1527
+ "svg",
1528
+ "math",
1529
+ "select",
1530
+ "option",
1531
+ "plaintext"
1262
1532
  ]);
1263
- var ELEMENT_ATTRIBUTES = Object.freeze({
1264
- math: ["display"],
1265
- mo: [
1266
- "form",
1267
- "fence",
1268
- "separator",
1269
- "stretchy",
1270
- "symmetric",
1271
- "largeop",
1272
- "movablelimits",
1273
- "lspace",
1274
- "rspace",
1275
- "minsize",
1276
- "maxsize",
1277
- "accent"
1278
- ],
1279
- mspace: ["width", "height", "depth"],
1280
- mpadded: ["width", "height", "depth", "lspace", "voffset"],
1281
- mfrac: ["linethickness"],
1282
- mover: ["accent"],
1283
- munder: ["accentunder"],
1284
- munderover: ["accent", "accentunder"],
1285
- mtable: [
1286
- "columnalign",
1287
- "rowalign",
1288
- "columnspacing",
1289
- "rowspacing",
1290
- "columnlines",
1291
- "rowlines",
1292
- "frame",
1293
- "framespacing",
1294
- "equalrows",
1295
- "equalcolumns",
1296
- "side"
1297
- ],
1298
- mtr: ["columnalign", "rowalign"],
1299
- mlabeledtr: ["columnalign", "rowalign"],
1300
- mtd: ["columnalign", "rowalign", "columnspan", "rowspan"],
1301
- menclose: ["notation"],
1302
- annotation: ["encoding"]
1533
+ var ALLOWED = new Set(INLINE_TAGS);
1534
+ var VOID = /* @__PURE__ */ new Set(["br"]);
1535
+ var MAX_INPUT = 5e5;
1536
+ var MAX_NODES = 5e4;
1537
+ var MAX_DEPTH = 64;
1538
+ var NAMED_ENTITIES = Object.freeze({
1539
+ amp: "&",
1540
+ lt: "<",
1541
+ gt: ">",
1542
+ quot: '"',
1543
+ apos: "'",
1544
+ nbsp: "\xA0",
1545
+ shy: "\xAD",
1546
+ copy: "\xA9",
1547
+ reg: "\xAE",
1548
+ trade: "\u2122",
1549
+ hellip: "\u2026",
1550
+ mdash: "\u2014",
1551
+ ndash: "\u2013",
1552
+ lsquo: "\u2018",
1553
+ rsquo: "\u2019",
1554
+ ldquo: "\u201C",
1555
+ rdquo: "\u201D",
1556
+ laquo: "\xAB",
1557
+ raquo: "\xBB",
1558
+ euro: "\u20AC",
1559
+ middot: "\xB7",
1560
+ bull: "\u2022",
1561
+ times: "\xD7",
1562
+ deg: "\xB0",
1563
+ tab: " ",
1564
+ newline: "\n",
1565
+ colon: ":",
1566
+ sol: "/",
1567
+ lpar: "(",
1568
+ rpar: ")"
1303
1569
  });
1304
- var ATTRIBUTE_VALUE = /^[A-Za-z0-9 .%#+-]{0,100}$/;
1305
- var COLOR_VALUE = /^(?:#[0-9A-Fa-f]{3,8}|[A-Za-z]{1,30})$/;
1306
- var CLASS_TOKEN = /^tml-[a-z0-9-]{1,40}$/;
1307
- var TEX_ENCODING = "application/x-tex";
1308
- var MAX_INPUT2 = 2e5;
1309
- var MAX_NODES2 = 2e4;
1310
- var MAX_DEPTH2 = 64;
1311
- var parseAttributes2 = (source) => {
1570
+ var decodeEntities = (text) => String(text).replace(
1571
+ /&(#[xX][0-9a-fA-F]{1,8}|#[0-9]{1,10}|[A-Za-z][A-Za-z0-9]{1,31});?/g,
1572
+ (match, body) => {
1573
+ if (body[0] === "#") {
1574
+ const code = body[1] === "x" || body[1] === "X" ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
1575
+ if (!Number.isFinite(code) || code <= 0 || code > 1114111 || code >= 55296 && code <= 57343)
1576
+ return "\uFFFD";
1577
+ return String.fromCodePoint(code);
1578
+ }
1579
+ const named = NAMED_ENTITIES[body] ?? NAMED_ENTITIES[body.toLowerCase()];
1580
+ return named === void 0 ? match : named;
1581
+ }
1582
+ );
1583
+ var parseAttributes = (source) => {
1312
1584
  const out = {};
1313
1585
  const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
1314
1586
  let match;
1315
1587
  while (match = pattern.exec(source)) {
1316
1588
  const name = match[1].toLowerCase();
1317
1589
  if (Object.prototype.hasOwnProperty.call(out, name)) continue;
1318
- out[name] = decodeEntities(match[2] ?? match[3] ?? match[4] ?? "");
1590
+ const raw = match[2] ?? match[3] ?? match[4] ?? "";
1591
+ out[name] = decodeEntities(raw);
1319
1592
  }
1320
1593
  return out;
1321
1594
  };
1322
- var styleColor = (style, property) => {
1323
- const pattern = property === "color" ? /(?:^|;)\s*color\s*:\s*([^;]+)/i : /background-color\s*:\s*([^;]+)/i;
1324
- const match = pattern.exec(style);
1325
- const value = match ? match[1].trim() : "";
1326
- return COLOR_VALUE.test(value) ? value : "";
1595
+ var findTagEnd = (html, from) => {
1596
+ let quote = "";
1597
+ for (let i = from; i < html.length; i += 1) {
1598
+ const char = html[i];
1599
+ if (quote) {
1600
+ if (char === quote) quote = "";
1601
+ } else if (char === '"' || char === "'") quote = char;
1602
+ else if (char === ">") return i;
1603
+ }
1604
+ return -1;
1327
1605
  };
1328
- var cleanAttributes2 = (tag, attribs) => {
1606
+ var cleanAttributes = (tag, attribs, options = {}) => {
1607
+ const allowed = INLINE_ATTRIBUTES[tag] || [];
1329
1608
  const out = {};
1330
- const allowed = ELEMENT_ATTRIBUTES[tag] || [];
1331
- for (const [name, raw] of Object.entries(attribs)) {
1332
- if (typeof raw !== "string" && typeof raw !== "number" && raw !== true) continue;
1333
- const value = raw === true ? "true" : String(raw);
1334
- if (name === "class") {
1335
- const classes2 = value.split(/\s+/).filter((token) => CLASS_TOKEN.test(token));
1336
- if (classes2.length) out.class = classes2.slice(0, 8).join(" ");
1337
- continue;
1338
- }
1339
- if (name === "encoding") {
1340
- if (tag === "annotation" && value === TEX_ENCODING) out.encoding = value;
1341
- continue;
1342
- }
1343
- if (name === "mathcolor" || name === "mathbackground") {
1344
- if (COLOR_VALUE.test(value)) out[name] = value;
1345
- continue;
1609
+ for (const name of allowed) {
1610
+ if (!Object.prototype.hasOwnProperty.call(attribs, name) || name.startsWith("data-mex-")) continue;
1611
+ const value = attribs[name];
1612
+ if (name === "href") {
1613
+ const url = sanitizeUrl(value);
1614
+ if (url) out.href = url;
1615
+ } else if (name === "target") {
1616
+ const target = sanitizeTarget(value);
1617
+ if (target) out.target = target;
1618
+ } else if (name === "rel") {
1619
+ const rel = String(value).split(/\s+/).filter((token) => /^[a-z-]{1,20}$/.test(token));
1620
+ if (rel.length) out.rel = rel.join(" ");
1621
+ } else if (name === "class") {
1622
+ const classes2 = String(value).split(/\s+/).filter((token) => (INLINE_CLASSES[tag] || []).includes(token));
1623
+ if (classes2.length) out.class = classes2.join(" ");
1624
+ } else {
1625
+ out[name] = String(value).slice(0, 2e3);
1346
1626
  }
1347
- if (!COMMON_ATTRIBUTES.has(name) && !allowed.includes(name)) continue;
1348
- if (ATTRIBUTE_VALUE.test(value)) out[name] = value;
1349
1627
  }
1350
- if (typeof attribs.style === "string") {
1351
- const color = styleColor(attribs.style, "color");
1352
- const background = styleColor(attribs.style, "background-color");
1353
- if (color && !out.mathcolor) out.mathcolor = color;
1354
- if (background && !out.mathbackground) out.mathbackground = background;
1355
- }
1356
- if (tag === "annotation" && out.encoding !== TEX_ENCODING) return null;
1357
- if (tag === "math" && out.display && out.display !== "block" && out.display !== "inline")
1358
- delete out.display;
1628
+ if (tag === "a" && !options.inNote) Object.assign(out, cleanInternalLinkAttributes(attribs));
1359
1629
  return out;
1360
1630
  };
1361
- var tokenize = (input) => {
1362
- const source = input.slice(0, MAX_INPUT2);
1631
+ var MAX_MARKER_TEXT = 16;
1632
+ var isMathNode = (node) => node.type === "element" && node.tag === "span" && node.attrs[MATH_ATTRIBUTE] === "true";
1633
+ var isFootnoteNode = (node) => node.type === "element" && node.tag === "sup" && typeof node.attrs["data-mex-footnote"] === "string";
1634
+ var isColorNode = (node) => node.type === "element" && node.tag === "span" && typeof node.attrs[COLOR_ATTRIBUTE] === "string";
1635
+ var isHighlightNode = (node) => node.type === "element" && node.tag === "mark" && typeof node.attrs[HIGHLIGHT_ATTRIBUTE] === "string";
1636
+ var isAnnotationNode = (node) => node.type === "element" && node.tag === "span" && typeof node.attrs[ANNOTATION_ATTRIBUTE] === "string";
1637
+ var annotationOf = (node) => {
1638
+ const attrs = {};
1639
+ for (const [name, value] of Object.entries(node.attrs))
1640
+ if (name.startsWith(ANNOTATION_VALUE_PREFIX)) attrs[name.slice(ANNOTATION_VALUE_PREFIX.length)] = value;
1641
+ return { name: node.attrs[ANNOTATION_ATTRIBUTE], attrs };
1642
+ };
1643
+ var annotationAttributes = (name, values) => {
1644
+ const out = { [ANNOTATION_ATTRIBUTE]: name };
1645
+ for (const key of Object.keys(values).sort()) out[`${ANNOTATION_VALUE_PREFIX}${key}`] = values[key];
1646
+ return out;
1647
+ };
1648
+ var finalizeSpecial = (nodes, depth = 0) => {
1649
+ for (const node of nodes) {
1650
+ if (node.type !== "element") continue;
1651
+ if (isMathNode(node)) {
1652
+ const tex = nodesToText(node.children, { raw: true }).replace(/\u200b/g, "").slice(0, MAX_INLINE_TEX);
1653
+ node.children = tex ? [{ type: "text", value: tex }] : [];
1654
+ } else if (isFootnoteNode(node)) {
1655
+ const text = nodesToText(node.children, { raw: true }).slice(0, MAX_MARKER_TEXT);
1656
+ node.children = text ? [{ type: "text", value: text }] : [];
1657
+ } else if (depth < MAX_DEPTH) finalizeSpecial(node.children, depth + 1);
1658
+ }
1659
+ return nodes;
1660
+ };
1661
+ var specialElement = (tag, attribs, options) => {
1662
+ if (tag === "span" && Object.prototype.hasOwnProperty.call(attribs, MATH_ATTRIBUTE)) {
1663
+ if (!/^(?:|true)$/.test(attribs[MATH_ATTRIBUTE])) return null;
1664
+ return { attrs: { [MATH_ATTRIBUTE]: "true" } };
1665
+ }
1666
+ if (tag === "span" && Object.prototype.hasOwnProperty.call(attribs, ANNOTATION_ATTRIBUTE)) {
1667
+ const name = attribs[ANNOTATION_ATTRIBUTE];
1668
+ if (!ANNOTATION_NAME.test(name)) return null;
1669
+ const values = {};
1670
+ for (const [attribute, value] of Object.entries(attribs)) {
1671
+ if (!attribute.startsWith(ANNOTATION_VALUE_PREFIX)) continue;
1672
+ const key = attribute.slice(ANNOTATION_VALUE_PREFIX.length);
1673
+ if (!ANNOTATION_KEY.test(key) || Object.keys(values).length >= ANNOTATION_LIMITS.attributes) continue;
1674
+ const text = String(value).slice(0, ANNOTATION_LIMITS.text);
1675
+ if (text) values[key] = text;
1676
+ }
1677
+ return { attrs: annotationAttributes(name, values) };
1678
+ }
1679
+ if (tag === "span" && Object.prototype.hasOwnProperty.call(attribs, COLOR_ATTRIBUTE)) {
1680
+ return TOKEN_PATTERN.test(attribs[COLOR_ATTRIBUTE]) ? { attrs: { [COLOR_ATTRIBUTE]: attribs[COLOR_ATTRIBUTE] } } : null;
1681
+ }
1682
+ if (tag === "mark" && Object.prototype.hasOwnProperty.call(attribs, HIGHLIGHT_ATTRIBUTE)) {
1683
+ return TOKEN_PATTERN.test(attribs[HIGHLIGHT_ATTRIBUTE]) ? { attrs: { [HIGHLIGHT_ATTRIBUTE]: attribs[HIGHLIGHT_ATTRIBUTE] } } : null;
1684
+ }
1685
+ if (tag === "sup" && !options.inNote) {
1686
+ const id = attribs["data-mex-footnote"];
1687
+ if (typeof id !== "string" || !FOOTNOTE_ID.test(id)) return null;
1688
+ const source = typeof attribs["data-mex-note"] === "string" ? attribs["data-mex-note"] : "";
1689
+ const note = parseInline(source.slice(0, MAX_FOOTNOTE_NOTE), { inNote: true });
1690
+ return { attrs: { "data-mex-footnote": id }, note };
1691
+ }
1692
+ return null;
1693
+ };
1694
+ var parseInline = (input, options = {}) => {
1695
+ const html = typeof input === "string" ? input.slice(0, MAX_INPUT) : "";
1363
1696
  const root = { type: "element", tag: "#root", attrs: {}, children: [] };
1364
1697
  const stack = [root];
1365
- let count = 0;
1366
- let i = 0;
1367
- const pushText = (text) => {
1698
+ let nodes = 0;
1699
+ let text = "";
1700
+ const flush = () => {
1368
1701
  if (!text) return;
1369
1702
  const parent = stack[stack.length - 1];
1370
1703
  const last = parent.children[parent.children.length - 1];
1371
1704
  const value = decodeEntities(text);
1372
1705
  if (last && last.type === "text") last.value += value;
1373
- else if (count < MAX_NODES2) {
1706
+ else if (nodes < MAX_NODES) {
1374
1707
  parent.children.push({ type: "text", value });
1375
- count += 1;
1708
+ nodes += 1;
1376
1709
  }
1710
+ text = "";
1377
1711
  };
1378
- while (i < source.length) {
1379
- const lt = source.indexOf("<", i);
1712
+ let i = 0;
1713
+ while (i < html.length) {
1714
+ const lt = html.indexOf("<", i);
1380
1715
  if (lt === -1) {
1381
- pushText(source.slice(i));
1716
+ text += html.slice(i);
1382
1717
  break;
1383
1718
  }
1384
- pushText(source.slice(i, lt));
1385
- if (source.startsWith("<!--", lt)) {
1386
- const end2 = source.indexOf("-->", lt + 4);
1387
- i = end2 === -1 ? source.length : end2 + 3;
1719
+ text += html.slice(i, lt);
1720
+ i = lt;
1721
+ if (html.startsWith("<!--", i)) {
1722
+ const end2 = html.indexOf("-->", i + 4);
1723
+ flush();
1724
+ i = end2 === -1 ? html.length : end2 + 3;
1388
1725
  continue;
1389
1726
  }
1390
- if (source[lt + 1] === "!" || source[lt + 1] === "?") {
1391
- const end2 = source.indexOf(">", lt + 2);
1392
- i = end2 === -1 ? source.length : end2 + 1;
1727
+ if (html.startsWith("<![CDATA[", i)) {
1728
+ const end2 = html.indexOf("]]>", i + 9);
1729
+ flush();
1730
+ i = end2 === -1 ? html.length : end2 + 3;
1393
1731
  continue;
1394
1732
  }
1395
- const closing = source[lt + 1] === "/";
1396
- const nameMatch = /^[A-Za-z][A-Za-z0-9:-]{0,40}/.exec(source.slice(lt + (closing ? 2 : 1), lt + 45));
1397
- let end = -1;
1398
- let quote = "";
1399
- for (let j = lt + 1; j < source.length; j += 1) {
1400
- const char = source[j];
1401
- if (quote) {
1402
- if (char === quote) quote = "";
1403
- } else if (char === '"' || char === "'") quote = char;
1404
- else if (char === ">") {
1405
- end = j;
1406
- break;
1407
- }
1733
+ if (html[i + 1] === "!" || html[i + 1] === "?") {
1734
+ const end2 = html.indexOf(">", i + 2);
1735
+ flush();
1736
+ i = end2 === -1 ? html.length : end2 + 1;
1737
+ continue;
1408
1738
  }
1409
- if (!nameMatch || end === -1) {
1410
- pushText(source.slice(lt, end === -1 ? source.length : lt + 1));
1411
- i = end === -1 ? source.length : lt + 1;
1739
+ const closing = html[i + 1] === "/";
1740
+ const nameMatch = /^[A-Za-z][A-Za-z0-9-]{0,40}/.exec(html.slice(i + (closing ? 2 : 1), i + 45));
1741
+ if (!nameMatch) {
1742
+ text += "<";
1743
+ i += 1;
1412
1744
  continue;
1413
1745
  }
1746
+ const end = findTagEnd(html, i + 1);
1747
+ if (end === -1) {
1748
+ text += html.slice(i);
1749
+ break;
1750
+ }
1751
+ flush();
1414
1752
  const tag = nameMatch[0].toLowerCase();
1415
- const body = source.slice(lt + (closing ? 2 : 1) + nameMatch[0].length, end);
1753
+ const body = html.slice(i + (closing ? 2 : 1) + nameMatch[0].length, end);
1416
1754
  i = end + 1;
1417
1755
  if (closing) {
1756
+ if (!ALLOWED.has(tag)) continue;
1418
1757
  for (let s = stack.length - 1; s > 0; s -= 1) {
1419
1758
  if (stack[s].tag === tag) {
1420
1759
  stack.length = s;
@@ -1423,613 +1762,583 @@ var tokenize = (input) => {
1423
1762
  }
1424
1763
  continue;
1425
1764
  }
1426
- if (count >= MAX_NODES2) continue;
1427
- const element = { type: "element", tag, attrs: parseAttributes2(body), children: [] };
1428
- stack[stack.length - 1].children.push(element);
1429
- count += 1;
1430
- const selfClosing = /\/\s*$/.test(body);
1431
- if (!selfClosing && stack.length < MAX_DEPTH2) stack.push(element);
1432
- }
1433
- return root.children;
1434
- };
1435
- var clean = (nodes, ctx, depth, inAnnotation) => {
1436
- const out = [];
1437
- if (!Array.isArray(nodes) || depth > MAX_DEPTH2) return out;
1438
- for (const node of nodes) {
1439
- if (ctx.budget <= 0) break;
1440
- if (typeof node === "string") {
1441
- ctx.budget -= 1;
1442
- if (node) out.push({ type: "text", value: node });
1443
- continue;
1444
- }
1445
- if (!node || typeof node !== "object") continue;
1446
- ctx.budget -= 1;
1447
- if (node.type === "text") {
1448
- if (typeof node.value === "string" && node.value) out.push({ type: "text", value: node.value });
1765
+ if (DROP_WITH_CONTENT.has(tag)) {
1766
+ const selfClosing = /\/\s*$/.test(body);
1767
+ if (selfClosing) continue;
1768
+ const closeIndex = html.slice(i).search(new RegExp(`</${tag}[\\s/>]`, "i"));
1769
+ if (closeIndex === -1) break;
1770
+ const closeEnd = html.indexOf(">", i + closeIndex);
1771
+ i = closeEnd === -1 ? html.length : closeEnd + 1;
1449
1772
  continue;
1450
1773
  }
1451
- if (node.type !== "element" || typeof node.tag !== "string" || inAnnotation) continue;
1452
- const tag = node.tag.toLowerCase();
1453
- if (!TAGS.has(tag)) continue;
1454
- const attrs = cleanAttributes2(tag, node.attrs && typeof node.attrs === "object" ? node.attrs : {});
1455
- if (!attrs) continue;
1456
- const children = clean(node.children, ctx, depth + 1, tag === "annotation");
1457
- out.push({ type: "element", tag, attrs, children });
1774
+ if (!ALLOWED.has(tag) || nodes >= MAX_NODES) continue;
1775
+ const attribs = parseAttributes(body);
1776
+ const special = specialElement(tag, attribs, options);
1777
+ const element = {
1778
+ type: "element",
1779
+ tag,
1780
+ attrs: special ? special.attrs : cleanAttributes(tag, attribs, options),
1781
+ children: []
1782
+ };
1783
+ if (special && special.note) element.note = special.note;
1784
+ stack[stack.length - 1].children.push(element);
1785
+ nodes += 1;
1786
+ if (!VOID.has(tag) && stack.length < MAX_DEPTH) stack.push(element);
1458
1787
  }
1459
- return out;
1460
- };
1461
- var cleanMathResult = (result) => {
1462
- let nodes;
1463
- if (typeof result === "string") nodes = tokenize(result);
1464
- else if (Array.isArray(result)) nodes = result;
1465
- else if (result && typeof result === "object") nodes = [result];
1466
- else return [];
1467
- const top = nodes.filter(
1468
- (node) => node && typeof node === "object" && node.type === "element" && String(node.tag).toLowerCase() === "math"
1469
- );
1470
- return clean(top, { budget: MAX_NODES2 }, 0, false);
1471
- };
1472
-
1473
- // shared/render/math-notes.mjs
1474
- var DEFAULT_FOOTNOTES_LABEL = "Footnotes";
1475
- var DEFAULT_FOOTNOTE_BACK_LABEL = "Back to reference {n}";
1476
- var DEFAULT_FOOTNOTE_PREFIX = "mex-";
1477
- var PREFIX = /^[A-Za-z][A-Za-z0-9_-]{0,40}$/;
1478
- var label = (value, fallback) => {
1479
- if (typeof value !== "string") return fallback;
1480
- const clean2 = value.trim();
1481
- return clean2 && clean2.length <= 80 ? clean2 : fallback;
1482
- };
1483
- var footnoteOptions = (options) => {
1484
- const source = isPlainObject2(options && options.footnotes) ? options.footnotes : {};
1485
- return {
1486
- label: label(source.label, DEFAULT_FOOTNOTES_LABEL),
1487
- backLabel: label(source.backLabel, DEFAULT_FOOTNOTE_BACK_LABEL),
1488
- prefix: typeof source.prefix === "string" && PREFIX.test(source.prefix) ? source.prefix : DEFAULT_FOOTNOTE_PREFIX
1489
- };
1490
- };
1491
- var createFootnoteNumbers = () => {
1492
- const used = /* @__PURE__ */ new Map();
1493
- let count = 0;
1494
- return {
1495
- add(id) {
1496
- const seen = (used.get(id) || 0) + 1;
1497
- used.set(id, seen);
1498
- count += 1;
1499
- return { n: count, anchor: seen === 1 ? id : `${id}-${seen}` };
1500
- }
1501
- };
1788
+ flush();
1789
+ return finalizeSpecial(root.children);
1502
1790
  };
1503
- var renderMathNodes = (options, tex, display) => {
1504
- if (!options || typeof options.math !== "function" || !tex.trim()) return [];
1791
+ var resolveLinkAttributes = (attrs, resolver) => {
1792
+ if (typeof resolver !== "function" || !attrs["data-mex-uid"] || !attrs["data-mex-document-id"])
1793
+ return attrs;
1505
1794
  let result;
1506
1795
  try {
1507
- result = options.math(tex, { display });
1796
+ result = resolver({
1797
+ uid: attrs["data-mex-uid"],
1798
+ documentId: attrs["data-mex-document-id"],
1799
+ locale: attrs["data-mex-locale"] || null,
1800
+ href: attrs.href || null,
1801
+ ...isMentionLink(attrs) ? { mention: true } : {}
1802
+ });
1508
1803
  } catch {
1509
- return [];
1804
+ result = void 0;
1510
1805
  }
1511
- return cleanMathResult(result);
1512
- };
1513
- var mathElement = (options, tex, kind) => {
1514
- const math = renderMathNodes(options, tex, kind.display);
1515
- const attrs = {
1516
- class: kind.className || (kind.display ? "mex-math mex-math-display" : "mex-math"),
1517
- "data-mex-math": kind.display ? "display" : "inline"
1518
- };
1519
- const children = math.length ? math : kind.display ? `\\[${tex}\\]` : `\\(${tex}\\)`;
1520
- return el(kind.block ? "div" : "span", attrs, children);
1806
+ if (result === false) return null;
1807
+ if (typeof result === "string") {
1808
+ const url = sanitizeUrl(result);
1809
+ if (url) return { ...attrs, href: url };
1810
+ }
1811
+ return attrs;
1521
1812
  };
1522
- var createFootnoteTree = (options, renderNote) => {
1523
- const { label: listLabel, backLabel, prefix } = footnoteOptions(options);
1524
- const numbers = createFootnoteNumbers();
1525
- const items = [];
1526
- const labelId = `${prefix}footnotes-label`;
1527
- return {
1528
- marker(node) {
1529
- const { n, anchor } = numbers.add(node.attrs["data-mex-footnote"]);
1530
- items.push({ n, anchor, note: node.note || [] });
1531
- return el(
1532
- "sup",
1533
- { class: "mex-footnote-ref" },
1534
- el(
1535
- "a",
1536
- {
1537
- href: `#${prefix}fn-${anchor}`,
1538
- id: `${prefix}fnref-${anchor}`,
1539
- "aria-describedby": labelId
1540
- },
1541
- String(n)
1542
- )
1543
- );
1544
- },
1545
- section() {
1546
- if (!items.length) return null;
1547
- return el("section", { class: "mex-footnotes", "aria-labelledby": labelId }, [
1548
- el("h2", { id: labelId, class: "mex-footnotes-label" }, listLabel),
1549
- el(
1550
- "ol",
1551
- { class: "mex-footnotes-list" },
1552
- items.map(
1553
- (item) => el("li", { id: `${prefix}fn-${item.anchor}`, class: "mex-footnote" }, [
1554
- renderNote(item.note),
1555
- " ",
1556
- el(
1557
- "a",
1558
- {
1559
- href: `#${prefix}fnref-${item.anchor}`,
1560
- class: "mex-footnote-back",
1561
- "aria-label": backLabel.replace(/\{n\}/g, String(item.n))
1562
- },
1563
- "\u21A9"
1564
- )
1565
- ])
1566
- )
1567
- )
1568
- ]);
1569
- }
1570
- };
1571
- };
1572
-
1573
- // shared/blocks/define.mjs
1574
- var BLOCK_FIELD_TYPES = Object.freeze([
1575
- "text",
1576
- "inline",
1577
- "url",
1578
- "enum",
1579
- "number",
1580
- "boolean",
1581
- "array",
1582
- "object"
1583
- ]);
1584
- var BLOCK_LIMITS = Object.freeze({
1585
- /** Fields per object (also the schema root). */
1586
- maxFields: 50,
1587
- /** Nesting of arrays and objects below the root. */
1588
- maxDepth: 4,
1589
- /** Largest `max` of a text or inline field. */
1590
- maxText: 1e5,
1591
- /** Default `max` of a text field. */
1592
- defaultText: 1e3,
1593
- /** Default `max` of an inline HTML field. */
1594
- defaultInline: 1e4,
1595
- /** Largest `max` of an array field. */
1596
- maxItems: 500,
1597
- /** Default `max` of an array field. */
1598
- defaultItems: 50,
1599
- /** Values of an enum field. */
1600
- maxEnumValues: 100,
1601
- /** Values cleaned per block; later array items are dropped. */
1602
- maxValues: 2e4,
1603
- /** Length of a URL value. */
1604
- maxUrl: 2048
1605
- });
1606
- var BLOCK_PRESETS = Object.freeze(["article", "basic", "minimal"]);
1607
- var RESERVED_BLOCK_NAMES = Object.freeze([
1608
- "paragraph",
1609
- "header",
1610
- "list",
1611
- "checklist",
1612
- "quote",
1613
- "warning",
1614
- "alert",
1615
- "toggle",
1616
- "code",
1617
- "codeFlask",
1618
- "delimiter",
1619
- "toc",
1620
- "synced",
1621
- "table",
1622
- "embed",
1623
- "raw",
1624
- "image",
1625
- "simpleImage",
1626
- "gallery",
1627
- "video",
1628
- "audio",
1629
- "linkTool",
1630
- "attaches",
1631
- "personality",
1632
- "button",
1633
- "mediaLib",
1634
- "embeddedEntry",
1635
- "bold",
1636
- "italic",
1637
- "hyperlink",
1638
- "mention",
1639
- "marker",
1640
- "underline",
1641
- "strikethrough",
1642
- "inlineCode",
1643
- "tooltip",
1644
- "aiAssistant",
1645
- "alignmentTune",
1646
- "textVariant",
1647
- "indentTune"
1648
- ]);
1649
- var SDK_COMPATIBLE_NAMES = Object.freeze(["math"]);
1650
- var RESERVED = new Set(RESERVED_BLOCK_NAMES.map((name) => name.toLowerCase()));
1651
- var BLOCK_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{1,49}$/;
1652
- var KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
1653
- var FORBIDDEN_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1654
- var DEFINITION_KEYS = /* @__PURE__ */ new Set([
1655
- "name",
1656
- "version",
1813
+ var ATTRIBUTE_ORDER = [
1814
+ "href",
1815
+ "target",
1816
+ "rel",
1657
1817
  "title",
1658
- "description",
1659
- "schema",
1660
- "sanitize",
1661
- "text",
1662
- "markdown",
1663
- "render",
1664
- "presets"
1665
- ]);
1666
- var FIELD_KEYS = {
1667
- text: ["max", "multiline", "default"],
1668
- inline: ["max", "default"],
1669
- url: ["schemes", "relative"],
1670
- enum: ["values", "default"],
1671
- number: ["min", "max", "integer", "default"],
1672
- boolean: ["default"],
1673
- array: ["items", "max"],
1674
- object: ["fields"]
1675
- };
1676
- var BlockDefinitionError = class extends Error {
1677
- /**
1678
- * @param {string} message - Message naming the definition and the problem.
1679
- * @param {string} [code] - `INVALID_DEFINITION` | `RESERVED_NAME` | `NAME_TAKEN` | `REGISTRY_SEALED`.
1680
- */
1681
- constructor(message, code = "INVALID_DEFINITION") {
1682
- super(message);
1683
- this.name = "BlockDefinitionError";
1684
- this.code = code;
1818
+ "class",
1819
+ "data-tooltip",
1820
+ "data-mex-uid",
1821
+ "data-mex-document-id",
1822
+ "data-mex-locale",
1823
+ "data-mex-mention",
1824
+ MATH_ATTRIBUTE,
1825
+ "data-mex-footnote",
1826
+ "data-mex-note"
1827
+ ];
1828
+ var RENDER_STATE = /* @__PURE__ */ Symbol.for("magic-editor-x.render-state");
1829
+ var storedNote = (note) => serializeNodes(inlineNodesToRender(note || [], { storage: true }));
1830
+ var MENTION_CLASS = "mex-mention";
1831
+ var inlineNodesToRender = (nodes, options = {}) => {
1832
+ const out = [];
1833
+ const state = options[RENDER_STATE];
1834
+ for (const node of nodes) {
1835
+ if (node.type === "text") {
1836
+ out.push({ type: "text", value: node.value });
1837
+ continue;
1838
+ }
1839
+ if (node.tag === "br") {
1840
+ out.push({ type: "element", tag: "br", attrs: {}, children: [] });
1841
+ continue;
1842
+ }
1843
+ if (isMathNode(node)) {
1844
+ const tex = nodesToText(node.children);
1845
+ if (state && !options.storage) {
1846
+ if (tex.trim()) out.push(state.math(tex, false));
1847
+ continue;
1848
+ }
1849
+ out.push({
1850
+ type: "element",
1851
+ tag: "span",
1852
+ attrs: { [MATH_ATTRIBUTE]: "true" },
1853
+ children: tex ? [{ type: "text", value: tex }] : []
1854
+ });
1855
+ continue;
1856
+ }
1857
+ if (isFootnoteNode(node)) {
1858
+ if (state && !options.storage) {
1859
+ out.push(state.footnote(node));
1860
+ continue;
1861
+ }
1862
+ const attrs2 = { "data-mex-footnote": node.attrs["data-mex-footnote"] };
1863
+ const note = storedNote(node.note);
1864
+ if (note) attrs2["data-mex-note"] = note;
1865
+ out.push({ type: "element", tag: "sup", attrs: attrs2, children: inlineNodesToRender(node.children, options) });
1866
+ continue;
1867
+ }
1868
+ if (isColorNode(node) || isHighlightNode(node)) {
1869
+ const color = node.tag === "span";
1870
+ const name = color ? COLOR_ATTRIBUTE : HIGHLIGHT_ATTRIBUTE;
1871
+ const token = node.attrs[name];
1872
+ out.push({
1873
+ type: "element",
1874
+ tag: node.tag,
1875
+ attrs: options.storage ? { [name]: token } : { class: color ? colorClass(token) : highlightClass(token), [name]: token },
1876
+ children: inlineNodesToRender(node.children, options)
1877
+ });
1878
+ continue;
1879
+ }
1880
+ if (isAnnotationNode(node)) {
1881
+ const children = inlineNodesToRender(node.children, options);
1882
+ if (options.storage) out.push({ type: "element", tag: "span", attrs: { ...node.attrs }, children });
1883
+ else out.push(...renderAnnotation(node, children, options));
1884
+ continue;
1885
+ }
1886
+ let attrs = node.attrs;
1887
+ if (node.tag === "a") {
1888
+ attrs = resolveLinkAttributes(attrs, options.links);
1889
+ if (!attrs || !attrs.href) {
1890
+ out.push(...inlineNodesToRender(node.children, options));
1891
+ continue;
1892
+ }
1893
+ if (attrs.target === "_blank") {
1894
+ const rel = new Set(
1895
+ String(attrs.rel || "").split(/\s+/).filter(Boolean)
1896
+ );
1897
+ rel.add("noopener");
1898
+ rel.add("noreferrer");
1899
+ attrs = { ...attrs, rel: Array.from(rel).sort().join(" ") };
1900
+ }
1901
+ if (!options.storage && isMentionLink(attrs)) attrs = { ...attrs, class: MENTION_CLASS };
1902
+ }
1903
+ const ordered = {};
1904
+ for (const name of ATTRIBUTE_ORDER) {
1905
+ if (attrs[name] !== void 0 && attrs[name] !== "") ordered[name] = String(attrs[name]);
1906
+ }
1907
+ out.push({
1908
+ type: "element",
1909
+ tag: node.tag,
1910
+ attrs: ordered,
1911
+ children: inlineNodesToRender(node.children, options)
1912
+ });
1685
1913
  }
1914
+ return out;
1686
1915
  };
1687
- var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
1688
- var fail = (where, message) => {
1689
- throw new BlockDefinitionError(`Magic Editor X block ${where}: ${message}`);
1690
- };
1691
- var boundedInt = (value, min, max, fallback, where, key) => {
1692
- if (value === void 0) return fallback;
1693
- if (!Number.isInteger(value) || value < min || value > max)
1694
- fail(where, `"${key}" must be an integer from ${min} to ${max}`);
1695
- return value;
1696
- };
1697
- var normalizeField = (input, where, depth) => {
1698
- if (!isObject2(input)) fail(where, 'a field must be an object with a "type"');
1699
- const type = input.type;
1700
- if (!BLOCK_FIELD_TYPES.includes(type)) fail(where, `unknown field type ${JSON.stringify(type)}`);
1701
- for (const key of Object.keys(input))
1702
- if (key !== "type" && key !== "label" && !FIELD_KEYS[type].includes(key))
1703
- fail(where, `unknown option "${key}" for a ${type} field`);
1704
- const out = { type };
1705
- if (input.label !== void 0) {
1706
- if (typeof input.label !== "string" || input.label.length > 100)
1707
- fail(where, '"label" must be a string of at most 100 characters');
1708
- out.label = input.label;
1916
+ var annotationLists = /* @__PURE__ */ new WeakMap();
1917
+ var annotationDefinition = (name, options) => {
1918
+ const list = options.annotations;
1919
+ if (Array.isArray(list)) {
1920
+ if (!annotationLists.has(list)) {
1921
+ const map = /* @__PURE__ */ new Map();
1922
+ for (const item of list.slice(0, ANNOTATION_LIMITS.registered))
1923
+ if (item && typeof item === "object" && typeof item.name === "string" && item.attributes)
1924
+ map.set(item.name, item);
1925
+ annotationLists.set(list, map);
1926
+ }
1927
+ const found = annotationLists.get(list).get(name);
1928
+ if (found) return found;
1929
+ }
1930
+ return activeAnnotation(name);
1931
+ };
1932
+ var resolvedValue = (options, annotation) => {
1933
+ if (typeof options.resolveAnnotation !== "function") return void 0;
1934
+ let value;
1935
+ try {
1936
+ value = options.resolveAnnotation(annotation);
1937
+ } catch {
1938
+ return void 0;
1939
+ }
1940
+ if (typeof value === "string") return value.slice(0, 2e3);
1941
+ if (value && typeof value === "object" && !Array.isArray(value)) return value;
1942
+ return void 0;
1943
+ };
1944
+ var renderAnnotation = (node, children, options) => {
1945
+ const { name, attrs } = annotationOf(node);
1946
+ const definition = annotationDefinition(name, options);
1947
+ const values = definition ? cleanAnnotationAttributes(definition, attrs) : attrs;
1948
+ if (!values) return children;
1949
+ if (definition && typeof definition.render === "function") {
1950
+ const text = nodesToText(node.children);
1951
+ let out;
1952
+ try {
1953
+ out = definition.render({
1954
+ name,
1955
+ attrs: { ...values },
1956
+ text,
1957
+ resolved: resolvedValue(options, { name, attrs: { ...values }, text })
1958
+ });
1959
+ } catch {
1960
+ out = void 0;
1961
+ }
1962
+ if (out === false) return children;
1963
+ const wrapper = cleanAnnotationWrapper(out);
1964
+ if (wrapper) return [{ type: "element", tag: wrapper.tag, attrs: wrapper.attrs, children }];
1709
1965
  }
1710
- switch (type) {
1711
- case "text":
1712
- case "inline": {
1713
- out.max = boundedInt(
1714
- input.max,
1715
- 1,
1716
- BLOCK_LIMITS.maxText,
1717
- type === "text" ? BLOCK_LIMITS.defaultText : BLOCK_LIMITS.defaultInline,
1718
- where,
1719
- "max"
1720
- );
1721
- if (input.default !== void 0 && typeof input.default !== "string")
1722
- fail(where, '"default" must be a string');
1723
- out.default = (input.default || "").slice(0, out.max);
1724
- if (type === "text") {
1725
- if (input.multiline !== void 0 && typeof input.multiline !== "boolean")
1726
- fail(where, '"multiline" must be a boolean');
1727
- out.multiline = input.multiline === true;
1728
- }
1729
- break;
1966
+ return [
1967
+ {
1968
+ type: "element",
1969
+ tag: "span",
1970
+ attrs: {
1971
+ class: `mex-annotation mex-annotation-${name}`,
1972
+ ...annotationAttributes(name, definition ? values : {})
1973
+ },
1974
+ children
1730
1975
  }
1731
- case "url": {
1732
- const schemes = input.schemes === void 0 ? ["http", "https"] : input.schemes;
1733
- if (!Array.isArray(schemes) || !schemes.length || schemes.some((scheme) => !LINK_SCHEMES.includes(scheme)))
1734
- fail(where, `"schemes" must be a non-empty list of ${LINK_SCHEMES.join(", ")}`);
1735
- if (input.relative !== void 0 && typeof input.relative !== "boolean")
1736
- fail(where, '"relative" must be a boolean');
1737
- out.schemes = Object.freeze([...new Set(schemes)]);
1738
- out.relative = input.relative !== false;
1739
- break;
1976
+ ];
1977
+ };
1978
+ var inlineToNodes = (html, options) => inlineNodesToRender(parseInline(html), options);
1979
+ var nodesToHtml = (nodes, options = {}) => serializeNodes(inlineNodesToRender(nodes, options));
1980
+ var nodesToText = (nodes, options = {}) => nodes.map((node) => {
1981
+ if (node.type === "text") return node.value;
1982
+ if (node.tag === "br") return "\n";
1983
+ if (!options.raw && isFootnoteNode(node))
1984
+ return typeof options.footnote === "function" ? options.footnote(node) : "";
1985
+ return nodesToText(node.children, options);
1986
+ }).join("");
1987
+ var inlineToHtml = (html, options) => nodesToHtml(parseInline(html), options);
1988
+ var inlineToText = (html, options) => nodesToText(parseInline(html), options).replace(/\u00a0/g, " ");
1989
+
1990
+ // shared/render/mathml.mjs
1991
+ var MATHML_TAGS = Object.freeze([
1992
+ "math",
1993
+ "semantics",
1994
+ "annotation",
1995
+ "mrow",
1996
+ "mi",
1997
+ "mn",
1998
+ "mo",
1999
+ "ms",
2000
+ "mtext",
2001
+ "mspace",
2002
+ "msub",
2003
+ "msup",
2004
+ "msubsup",
2005
+ "munder",
2006
+ "mover",
2007
+ "munderover",
2008
+ "mfrac",
2009
+ "msqrt",
2010
+ "mroot",
2011
+ "mstyle",
2012
+ "merror",
2013
+ "mpadded",
2014
+ "mphantom",
2015
+ "mtable",
2016
+ "mtr",
2017
+ "mtd",
2018
+ "mlabeledtr",
2019
+ "mmultiscripts",
2020
+ "mprescripts",
2021
+ "none",
2022
+ "menclose"
2023
+ ]);
2024
+ var TAGS = new Set(MATHML_TAGS);
2025
+ var COMMON_ATTRIBUTES = /* @__PURE__ */ new Set([
2026
+ "dir",
2027
+ "displaystyle",
2028
+ "scriptlevel",
2029
+ "mathvariant",
2030
+ "mathsize",
2031
+ "mathcolor",
2032
+ "mathbackground"
2033
+ ]);
2034
+ var ELEMENT_ATTRIBUTES = Object.freeze({
2035
+ math: ["display"],
2036
+ mo: [
2037
+ "form",
2038
+ "fence",
2039
+ "separator",
2040
+ "stretchy",
2041
+ "symmetric",
2042
+ "largeop",
2043
+ "movablelimits",
2044
+ "lspace",
2045
+ "rspace",
2046
+ "minsize",
2047
+ "maxsize",
2048
+ "accent"
2049
+ ],
2050
+ mspace: ["width", "height", "depth"],
2051
+ mpadded: ["width", "height", "depth", "lspace", "voffset"],
2052
+ mfrac: ["linethickness"],
2053
+ mover: ["accent"],
2054
+ munder: ["accentunder"],
2055
+ munderover: ["accent", "accentunder"],
2056
+ mtable: [
2057
+ "columnalign",
2058
+ "rowalign",
2059
+ "columnspacing",
2060
+ "rowspacing",
2061
+ "columnlines",
2062
+ "rowlines",
2063
+ "frame",
2064
+ "framespacing",
2065
+ "equalrows",
2066
+ "equalcolumns",
2067
+ "side"
2068
+ ],
2069
+ mtr: ["columnalign", "rowalign"],
2070
+ mlabeledtr: ["columnalign", "rowalign"],
2071
+ mtd: ["columnalign", "rowalign", "columnspan", "rowspan"],
2072
+ menclose: ["notation"],
2073
+ annotation: ["encoding"]
2074
+ });
2075
+ var ATTRIBUTE_VALUE = /^[A-Za-z0-9 .%#+-]{0,100}$/;
2076
+ var COLOR_VALUE = /^(?:#[0-9A-Fa-f]{3,8}|[A-Za-z]{1,30})$/;
2077
+ var CLASS_TOKEN2 = /^tml-[a-z0-9-]{1,40}$/;
2078
+ var TEX_ENCODING = "application/x-tex";
2079
+ var MAX_INPUT2 = 2e5;
2080
+ var MAX_NODES2 = 2e4;
2081
+ var MAX_DEPTH2 = 64;
2082
+ var parseAttributes2 = (source) => {
2083
+ const out = {};
2084
+ const pattern = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
2085
+ let match;
2086
+ while (match = pattern.exec(source)) {
2087
+ const name = match[1].toLowerCase();
2088
+ if (Object.prototype.hasOwnProperty.call(out, name)) continue;
2089
+ out[name] = decodeEntities(match[2] ?? match[3] ?? match[4] ?? "");
2090
+ }
2091
+ return out;
2092
+ };
2093
+ var styleColor = (style, property) => {
2094
+ const pattern = property === "color" ? /(?:^|;)\s*color\s*:\s*([^;]+)/i : /background-color\s*:\s*([^;]+)/i;
2095
+ const match = pattern.exec(style);
2096
+ const value = match ? match[1].trim() : "";
2097
+ return COLOR_VALUE.test(value) ? value : "";
2098
+ };
2099
+ var cleanAttributes2 = (tag, attribs) => {
2100
+ const out = {};
2101
+ const allowed = ELEMENT_ATTRIBUTES[tag] || [];
2102
+ for (const [name, raw] of Object.entries(attribs)) {
2103
+ if (typeof raw !== "string" && typeof raw !== "number" && raw !== true) continue;
2104
+ const value = raw === true ? "true" : String(raw);
2105
+ if (name === "class") {
2106
+ const classes2 = value.split(/\s+/).filter((token) => CLASS_TOKEN2.test(token));
2107
+ if (classes2.length) out.class = classes2.slice(0, 8).join(" ");
2108
+ continue;
1740
2109
  }
1741
- case "enum": {
1742
- const values = input.values;
1743
- 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)
1744
- fail(
1745
- where,
1746
- `"values" must be 1 to ${BLOCK_LIMITS.maxEnumValues} distinct strings (1-100 characters)`
1747
- );
1748
- out.values = Object.freeze([...values]);
1749
- if (input.default !== void 0 && !values.includes(input.default))
1750
- fail(where, '"default" must be one of "values"');
1751
- out.default = input.default === void 0 ? values[0] : input.default;
1752
- break;
2110
+ if (name === "encoding") {
2111
+ if (tag === "annotation" && value === TEX_ENCODING) out.encoding = value;
2112
+ continue;
1753
2113
  }
1754
- case "number": {
1755
- for (const key of ["min", "max", "default"])
1756
- if (input[key] !== void 0 && (typeof input[key] !== "number" || !Number.isFinite(input[key])))
1757
- fail(where, `"${key}" must be a finite number`);
1758
- if (input.integer !== void 0 && typeof input.integer !== "boolean")
1759
- fail(where, '"integer" must be a boolean');
1760
- out.integer = input.integer === true;
1761
- out.min = input.min === void 0 ? -Number.MAX_SAFE_INTEGER : input.min;
1762
- out.max = input.max === void 0 ? Number.MAX_SAFE_INTEGER : input.max;
1763
- if (out.min > out.max) fail(where, '"min" must not be greater than "max"');
1764
- if (input.default !== void 0) {
1765
- if (input.default < out.min || input.default > out.max || out.integer && !Number.isInteger(input.default))
1766
- fail(where, '"default" must be a valid value of the field');
1767
- out.default = input.default;
1768
- }
1769
- break;
2114
+ if (name === "mathcolor" || name === "mathbackground") {
2115
+ if (COLOR_VALUE.test(value)) out[name] = value;
2116
+ continue;
1770
2117
  }
1771
- case "boolean":
1772
- if (input.default !== void 0 && typeof input.default !== "boolean")
1773
- fail(where, '"default" must be a boolean');
1774
- out.default = input.default === true;
1775
- break;
1776
- case "array":
1777
- if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1778
- out.max = boundedInt(input.max, 1, BLOCK_LIMITS.maxItems, BLOCK_LIMITS.defaultItems, where, "max");
1779
- out.items = normalizeField(input.items, `${where}[]`, depth + 1);
1780
- break;
1781
- case "object":
1782
- if (depth >= BLOCK_LIMITS.maxDepth) fail(where, `fields nest at most ${BLOCK_LIMITS.maxDepth} levels`);
1783
- out.fields = normalizeFields(input.fields, where, depth + 1);
1784
- break;
1785
- default:
1786
- break;
2118
+ if (!COMMON_ATTRIBUTES.has(name) && !allowed.includes(name)) continue;
2119
+ if (ATTRIBUTE_VALUE.test(value)) out[name] = value;
1787
2120
  }
1788
- return Object.freeze(out);
1789
- };
1790
- var normalizeFields = (input, where, depth) => {
1791
- if (!isObject2(input)) fail(where, '"fields" must be an object of field descriptors');
1792
- const keys = Object.keys(input);
1793
- if (keys.length < 1 || keys.length > BLOCK_LIMITS.maxFields)
1794
- fail(where, `an object needs 1 to ${BLOCK_LIMITS.maxFields} fields`);
1795
- const out = /* @__PURE__ */ Object.create(null);
1796
- for (const key of keys) {
1797
- if (!KEY_PATTERN.test(key) || FORBIDDEN_KEYS2.has(key))
1798
- fail(where, `field name ${JSON.stringify(key)} must match ${KEY_PATTERN}`);
1799
- out[key] = normalizeField(input[key], `${where}.${key}`, depth);
2121
+ if (typeof attribs.style === "string") {
2122
+ const color = styleColor(attribs.style, "color");
2123
+ const background = styleColor(attribs.style, "background-color");
2124
+ if (color && !out.mathcolor) out.mathcolor = color;
2125
+ if (background && !out.mathbackground) out.mathbackground = background;
1800
2126
  }
1801
- return Object.freeze(out);
1802
- };
1803
- var blockNameProblem = (name) => {
1804
- if (typeof name !== "string" || !BLOCK_NAME_PATTERN.test(name))
1805
- return `the name must match ${BLOCK_NAME_PATTERN}`;
1806
- if (RESERVED.has(name.toLowerCase())) return `"${name}" is a built-in tool name`;
1807
- return null;
2127
+ if (tag === "annotation" && out.encoding !== TEX_ENCODING) return null;
2128
+ if (tag === "math" && out.display && out.display !== "block" && out.display !== "inline")
2129
+ delete out.display;
2130
+ return out;
1808
2131
  };
1809
- var defineBlock = (definition) => {
1810
- if (!isObject2(definition))
1811
- throw new BlockDefinitionError("Magic Editor X block: the definition must be an object");
1812
- const label3 = typeof definition.name === "string" ? `"${definition.name.slice(0, 50)}"` : "(no name)";
1813
- for (const key of Object.keys(definition))
1814
- if (!DEFINITION_KEYS.has(key)) fail(label3, `unknown key "${key}"`);
1815
- const problem = blockNameProblem(definition.name);
1816
- if (problem)
1817
- throw new BlockDefinitionError(
1818
- `Magic Editor X block ${label3}: ${problem}`,
1819
- problem.includes("built-in") ? "RESERVED_NAME" : "INVALID_DEFINITION"
1820
- );
1821
- const out = {
1822
- name: definition.name,
1823
- version: boundedInt(definition.version, 1, 1e6, 1, label3, "version")
2132
+ var tokenize = (input) => {
2133
+ const source = input.slice(0, MAX_INPUT2);
2134
+ const root = { type: "element", tag: "#root", attrs: {}, children: [] };
2135
+ const stack = [root];
2136
+ let count = 0;
2137
+ let i = 0;
2138
+ const pushText = (text) => {
2139
+ if (!text) return;
2140
+ const parent = stack[stack.length - 1];
2141
+ const last = parent.children[parent.children.length - 1];
2142
+ const value = decodeEntities(text);
2143
+ if (last && last.type === "text") last.value += value;
2144
+ else if (count < MAX_NODES2) {
2145
+ parent.children.push({ type: "text", value });
2146
+ count += 1;
2147
+ }
1824
2148
  };
1825
- for (const [key, max] of [
1826
- ["title", 100],
1827
- ["description", 500]
1828
- ]) {
1829
- if (definition[key] === void 0) continue;
1830
- if (typeof definition[key] !== "string" || definition[key].length > max)
1831
- fail(label3, `"${key}" must be a string of at most ${max} characters`);
1832
- out[key] = definition[key];
1833
- }
1834
- out.schema = normalizeFields(definition.schema, `${label3} schema`, 0);
1835
- for (const key of ["sanitize", "text", "markdown", "render"]) {
1836
- if (definition[key] === void 0) continue;
1837
- if (typeof definition[key] !== "function") fail(label3, `"${key}" must be a function`);
1838
- out[key] = definition[key];
1839
- }
1840
- const presets = definition.presets === void 0 ? [] : definition.presets;
1841
- if (!Array.isArray(presets) || presets.some((preset) => !BLOCK_PRESETS.includes(preset)))
1842
- fail(label3, `"presets" must list some of ${BLOCK_PRESETS.join(", ")}`);
1843
- out.presets = Object.freeze([...new Set(presets)]);
1844
- return Object.freeze(out);
1845
- };
1846
- var cleanValue = (field, value, inline, budget) => {
1847
- budget.left -= 1;
1848
- switch (field.type) {
1849
- case "text":
1850
- return typeof value === "string" ? value.slice(0, field.max) : field.default;
1851
- case "inline":
1852
- return inline(typeof value === "string" ? value.slice(0, field.max) : field.default);
1853
- case "url":
1854
- return typeof value === "string" ? sanitizeUrl(value.slice(0, BLOCK_LIMITS.maxUrl), {
1855
- schemes: field.schemes,
1856
- allowRelative: field.relative
1857
- }) : "";
1858
- case "enum":
1859
- return typeof value === "string" && field.values.includes(value) ? value : field.default;
1860
- case "number":
1861
- return typeof value === "number" && Number.isFinite(value) && value >= field.min && value <= field.max && (!field.integer || Number.isInteger(value)) ? value : field.default;
1862
- case "boolean":
1863
- return typeof value === "boolean" ? value : field.default;
1864
- case "array": {
1865
- const out = [];
1866
- if (!Array.isArray(value)) return out;
1867
- for (const item of value) {
1868
- if (out.length >= field.max || budget.left <= 0) break;
1869
- if (!matchesType(field.items, item)) continue;
1870
- const clean2 = cleanValue(field.items, item, inline, budget);
1871
- if (clean2 !== void 0) out.push(clean2);
2149
+ while (i < source.length) {
2150
+ const lt = source.indexOf("<", i);
2151
+ if (lt === -1) {
2152
+ pushText(source.slice(i));
2153
+ break;
2154
+ }
2155
+ pushText(source.slice(i, lt));
2156
+ if (source.startsWith("<!--", lt)) {
2157
+ const end2 = source.indexOf("-->", lt + 4);
2158
+ i = end2 === -1 ? source.length : end2 + 3;
2159
+ continue;
2160
+ }
2161
+ if (source[lt + 1] === "!" || source[lt + 1] === "?") {
2162
+ const end2 = source.indexOf(">", lt + 2);
2163
+ i = end2 === -1 ? source.length : end2 + 1;
2164
+ continue;
2165
+ }
2166
+ const closing = source[lt + 1] === "/";
2167
+ const nameMatch = /^[A-Za-z][A-Za-z0-9:-]{0,40}/.exec(source.slice(lt + (closing ? 2 : 1), lt + 45));
2168
+ let end = -1;
2169
+ let quote = "";
2170
+ for (let j = lt + 1; j < source.length; j += 1) {
2171
+ const char = source[j];
2172
+ if (quote) {
2173
+ if (char === quote) quote = "";
2174
+ } else if (char === '"' || char === "'") quote = char;
2175
+ else if (char === ">") {
2176
+ end = j;
2177
+ break;
1872
2178
  }
1873
- return out;
1874
2179
  }
1875
- case "object":
1876
- return cleanObject(field.fields, isObject2(value) ? value : {}, inline, budget);
1877
- default:
1878
- return void 0;
1879
- }
1880
- };
1881
- var matchesType = (field, item) => {
1882
- switch (field.type) {
1883
- case "text":
1884
- case "inline":
1885
- case "url":
1886
- case "enum":
1887
- return typeof item === "string";
1888
- case "number":
1889
- return typeof item === "number";
1890
- case "boolean":
1891
- return typeof item === "boolean";
1892
- case "array":
1893
- return Array.isArray(item);
1894
- default:
1895
- return isObject2(item);
2180
+ if (!nameMatch || end === -1) {
2181
+ pushText(source.slice(lt, end === -1 ? source.length : lt + 1));
2182
+ i = end === -1 ? source.length : lt + 1;
2183
+ continue;
2184
+ }
2185
+ const tag = nameMatch[0].toLowerCase();
2186
+ const body = source.slice(lt + (closing ? 2 : 1) + nameMatch[0].length, end);
2187
+ i = end + 1;
2188
+ if (closing) {
2189
+ for (let s = stack.length - 1; s > 0; s -= 1) {
2190
+ if (stack[s].tag === tag) {
2191
+ stack.length = s;
2192
+ break;
2193
+ }
2194
+ }
2195
+ continue;
2196
+ }
2197
+ if (count >= MAX_NODES2) continue;
2198
+ const element = { type: "element", tag, attrs: parseAttributes2(body), children: [] };
2199
+ stack[stack.length - 1].children.push(element);
2200
+ count += 1;
2201
+ const selfClosing = /\/\s*$/.test(body);
2202
+ if (!selfClosing && stack.length < MAX_DEPTH2) stack.push(element);
1896
2203
  }
2204
+ return root.children;
1897
2205
  };
1898
- var cleanObject = (fields, value, inline, budget) => {
1899
- const out = {};
1900
- for (const key of Object.keys(fields)) {
1901
- const own = Object.prototype.hasOwnProperty.call(value, key) ? value[key] : void 0;
1902
- const clean2 = cleanValue(fields[key], own, inline, budget);
1903
- if (clean2 !== void 0) out[key] = clean2;
2206
+ var clean = (nodes, ctx, depth, inAnnotation) => {
2207
+ const out = [];
2208
+ if (!Array.isArray(nodes) || depth > MAX_DEPTH2) return out;
2209
+ for (const node of nodes) {
2210
+ if (ctx.budget <= 0) break;
2211
+ if (typeof node === "string") {
2212
+ ctx.budget -= 1;
2213
+ if (node) out.push({ type: "text", value: node });
2214
+ continue;
2215
+ }
2216
+ if (!node || typeof node !== "object") continue;
2217
+ ctx.budget -= 1;
2218
+ if (node.type === "text") {
2219
+ if (typeof node.value === "string" && node.value) out.push({ type: "text", value: node.value });
2220
+ continue;
2221
+ }
2222
+ if (node.type !== "element" || typeof node.tag !== "string" || inAnnotation) continue;
2223
+ const tag = node.tag.toLowerCase();
2224
+ if (!TAGS.has(tag)) continue;
2225
+ const attrs = cleanAttributes2(tag, node.attrs && typeof node.attrs === "object" ? node.attrs : {});
2226
+ if (!attrs) continue;
2227
+ const children = clean(node.children, ctx, depth + 1, tag === "annotation");
2228
+ out.push({ type: "element", tag, attrs, children });
1904
2229
  }
1905
2230
  return out;
1906
2231
  };
1907
- var eachLeaf = (fields, data, visit) => {
1908
- const walk = (field, value, path, depth) => {
1909
- if (depth > BLOCK_LIMITS.maxDepth + 1) return;
1910
- if (field.type === "array") {
1911
- if (!Array.isArray(value)) return;
1912
- value.slice(0, field.max).forEach((item, index) => walk(field.items, item, [...path, index], depth + 1));
1913
- } else if (field.type === "object") {
1914
- if (!isObject2(value)) return;
1915
- for (const key of Object.keys(field.fields))
1916
- if (Object.prototype.hasOwnProperty.call(value, key))
1917
- walk(field.fields[key], value[key], [...path, key], depth + 1);
1918
- } else visit(field, value, path);
2232
+ var cleanMathResult = (result) => {
2233
+ let nodes;
2234
+ if (typeof result === "string") nodes = tokenize(result);
2235
+ else if (Array.isArray(result)) nodes = result;
2236
+ else if (result && typeof result === "object") nodes = [result];
2237
+ else return [];
2238
+ const top = nodes.filter(
2239
+ (node) => node && typeof node === "object" && node.type === "element" && String(node.tag).toLowerCase() === "math"
2240
+ );
2241
+ return clean(top, { budget: MAX_NODES2 }, 0, false);
2242
+ };
2243
+
2244
+ // shared/render/math-notes.mjs
2245
+ var DEFAULT_FOOTNOTES_LABEL = "Footnotes";
2246
+ var DEFAULT_FOOTNOTE_BACK_LABEL = "Back to reference {n}";
2247
+ var DEFAULT_FOOTNOTE_PREFIX = "mex-";
2248
+ var PREFIX = /^[A-Za-z][A-Za-z0-9_-]{0,40}$/;
2249
+ var label = (value, fallback) => {
2250
+ if (typeof value !== "string") return fallback;
2251
+ const clean2 = value.trim();
2252
+ return clean2 && clean2.length <= 80 ? clean2 : fallback;
2253
+ };
2254
+ var footnoteOptions = (options) => {
2255
+ const source = isPlainObject2(options && options.footnotes) ? options.footnotes : {};
2256
+ return {
2257
+ label: label(source.label, DEFAULT_FOOTNOTES_LABEL),
2258
+ backLabel: label(source.backLabel, DEFAULT_FOOTNOTE_BACK_LABEL),
2259
+ prefix: typeof source.prefix === "string" && PREFIX.test(source.prefix) ? source.prefix : DEFAULT_FOOTNOTE_PREFIX
1919
2260
  };
1920
- if (!isObject2(data)) return;
1921
- for (const key of Object.keys(fields))
1922
- if (Object.prototype.hasOwnProperty.call(data, key)) walk(fields[key], data[key], [key], 0);
1923
2261
  };
1924
- var fieldAt = (fields, path) => {
1925
- let current = { type: "object", fields };
1926
- for (const part of String(path).split(".")) {
1927
- if (!part) continue;
1928
- if (current.type === "array") {
1929
- if (/^\d+$/.test(part)) {
1930
- current = current.items;
1931
- continue;
1932
- }
1933
- return null;
2262
+ var createFootnoteNumbers = () => {
2263
+ const used = /* @__PURE__ */ new Map();
2264
+ let count = 0;
2265
+ return {
2266
+ add(id) {
2267
+ const seen = (used.get(id) || 0) + 1;
2268
+ used.set(id, seen);
2269
+ count += 1;
2270
+ return { n: count, anchor: seen === 1 ? id : `${id}-${seen}` };
1934
2271
  }
1935
- if (current.type !== "object" || !Object.prototype.hasOwnProperty.call(current.fields, part)) return null;
1936
- current = current.fields[part];
2272
+ };
2273
+ };
2274
+ var renderMathNodes = (options, tex, display) => {
2275
+ if (!options || typeof options.math !== "function" || !tex.trim()) return [];
2276
+ let result;
2277
+ try {
2278
+ result = options.math(tex, { display });
2279
+ } catch {
2280
+ return [];
1937
2281
  }
1938
- return current;
2282
+ return cleanMathResult(result);
1939
2283
  };
1940
- var compiled = /* @__PURE__ */ new WeakMap();
1941
- var compileBlock = (definition) => {
1942
- if (definition && typeof definition === "object" && compiled.has(definition))
1943
- return compiled.get(definition);
1944
- const def = defineBlock(definition && typeof definition === "object" ? { ...definition } : definition);
1945
- const schema = def.schema;
1946
- const run = (data, inline) => cleanObject(schema, isObject2(data) ? data : {}, inline, { left: BLOCK_LIMITS.maxValues });
1947
- const result = Object.freeze({
1948
- ...def,
1949
- /**
1950
- * Cleans untrusted block data (unknown keys dropped, values bounded).
1951
- * The optional `sanitize` hook runs on the clean data; its result is
1952
- * cleaned again, so it cannot add keys or unsafe values. A hook that
1953
- * throws is ignored (the clean data is used).
1954
- * @param {unknown} data - Block data.
1955
- * @param {(html: string) => string} inline - Inline HTML sanitiser of the caller.
1956
- * @returns {object} Clean data.
1957
- */
1958
- clean: (data, inline) => {
1959
- const first = run(data, inline);
1960
- if (!def.sanitize) return first;
1961
- let next;
1962
- try {
1963
- next = def.sanitize(copyData(first), { sanitizeUrl });
1964
- } catch {
1965
- return first;
1966
- }
1967
- return isObject2(next) ? run(next, inline) : first;
1968
- },
1969
- /**
1970
- * Text fields of the data in schema order: `{ path, kind, value }`
1971
- * (`html` for inline fields, `plain` for text fields).
1972
- * @param {unknown} data - Block data.
1973
- * @returns {Array<{ path: Array<string|number>, kind: 'html'|'plain', value: string }>} Fields.
1974
- */
1975
- fields: (data) => {
1976
- const out = [];
1977
- eachLeaf(schema, data, (field, value, path) => {
1978
- if (typeof value !== "string") return;
1979
- if (field.type === "inline") out.push({ path, kind: "html", value });
1980
- else if (field.type === "text") out.push({ path, kind: "plain", value });
1981
- });
1982
- return out;
1983
- },
1984
- /**
1985
- * Non-empty URL values: `{ path, value }`.
1986
- * @param {unknown} data - Block data.
1987
- * @returns {Array<{ path: Array<string|number>, value: string }>} URLs.
1988
- */
1989
- urls: (data) => {
1990
- const out = [];
1991
- eachLeaf(schema, data, (field, value, path) => {
1992
- if (field.type === "url" && typeof value === "string" && value) out.push({ path, value });
1993
- });
1994
- return out;
2284
+ var mathElement = (options, tex, kind) => {
2285
+ const math = renderMathNodes(options, tex, kind.display);
2286
+ const attrs = {
2287
+ class: kind.className || (kind.display ? "mex-math mex-math-display" : "mex-math"),
2288
+ "data-mex-math": kind.display ? "display" : "inline"
2289
+ };
2290
+ const children = math.length ? math : kind.display ? `\\[${tex}\\]` : `\\(${tex}\\)`;
2291
+ return el(kind.block ? "div" : "span", attrs, children);
2292
+ };
2293
+ var createFootnoteTree = (options, renderNote) => {
2294
+ const { label: listLabel, backLabel, prefix } = footnoteOptions(options);
2295
+ const numbers = createFootnoteNumbers();
2296
+ const items = [];
2297
+ const labelId = `${prefix}footnotes-label`;
2298
+ return {
2299
+ marker(node) {
2300
+ const { n, anchor } = numbers.add(node.attrs["data-mex-footnote"]);
2301
+ items.push({ n, anchor, note: node.note || [] });
2302
+ return el(
2303
+ "sup",
2304
+ { class: "mex-footnote-ref" },
2305
+ el(
2306
+ "a",
2307
+ {
2308
+ href: `#${prefix}fn-${anchor}`,
2309
+ id: `${prefix}fnref-${anchor}`,
2310
+ "aria-describedby": labelId
2311
+ },
2312
+ String(n)
2313
+ )
2314
+ );
1995
2315
  },
1996
- /**
1997
- * Kind of the value at a dotted path, for the version diff.
1998
- * @param {string} path - Dotted path.
1999
- * @returns {'inline'|'plain'|'value'} Kind.
2000
- */
2001
- kindOf: (path) => {
2002
- const field = fieldAt(schema, path);
2003
- if (!field) return "value";
2004
- if (field.type === "inline") return "inline";
2005
- if (field.type === "text") return "plain";
2006
- return "value";
2316
+ section() {
2317
+ if (!items.length) return null;
2318
+ return el("section", { class: "mex-footnotes", "aria-labelledby": labelId }, [
2319
+ el("h2", { id: labelId, class: "mex-footnotes-label" }, listLabel),
2320
+ el(
2321
+ "ol",
2322
+ { class: "mex-footnotes-list" },
2323
+ items.map(
2324
+ (item) => el("li", { id: `${prefix}fn-${item.anchor}`, class: "mex-footnote" }, [
2325
+ renderNote(item.note),
2326
+ " ",
2327
+ el(
2328
+ "a",
2329
+ {
2330
+ href: `#${prefix}fnref-${item.anchor}`,
2331
+ class: "mex-footnote-back",
2332
+ "aria-label": backLabel.replace(/\{n\}/g, String(item.n))
2333
+ },
2334
+ "\u21A9"
2335
+ )
2336
+ ])
2337
+ )
2338
+ )
2339
+ ]);
2007
2340
  }
2008
- });
2009
- compiled.set(result, result);
2010
- if (definition && typeof definition === "object") compiled.set(definition, result);
2011
- return result;
2012
- };
2013
- var copyData = (value) => {
2014
- if (Array.isArray(value)) return value.map(copyData);
2015
- if (isObject2(value)) {
2016
- const out = {};
2017
- for (const [key, child] of Object.entries(value)) out[key] = copyData(child);
2018
- return out;
2019
- }
2020
- return value;
2021
- };
2022
- var listCache = /* @__PURE__ */ new WeakMap();
2023
- var compileBlockList = (list) => {
2024
- if (!Array.isArray(list)) return /* @__PURE__ */ new Map();
2025
- if (listCache.has(list)) return listCache.get(list);
2026
- const map = /* @__PURE__ */ new Map();
2027
- for (const definition of list) {
2028
- const def = compileBlock(definition);
2029
- map.set(def.name, def);
2030
- }
2031
- listCache.set(list, map);
2032
- return map;
2341
+ };
2033
2342
  };
2034
2343
 
2035
2344
  // shared/toc.mjs