nizel 0.1.15 → 0.1.16

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 (41) hide show
  1. package/README.md +21 -0
  2. package/dist/browser/nizel.iife.js +184 -141
  3. package/dist/browser/nizel.js +184 -141
  4. package/dist/browser-runtime.d.ts +21 -0
  5. package/dist/browser-runtime.d.ts.map +1 -0
  6. package/dist/browser-runtime.js +156 -0
  7. package/dist/browser-runtime.js.map +1 -0
  8. package/dist/browser-wasm.d.ts +14 -0
  9. package/dist/browser-wasm.d.ts.map +1 -0
  10. package/dist/browser-wasm.js +13 -0
  11. package/dist/browser-wasm.js.map +1 -0
  12. package/dist/browser.d.ts +4 -36
  13. package/dist/browser.d.ts.map +1 -1
  14. package/dist/browser.js +4 -153
  15. package/dist/browser.js.map +1 -1
  16. package/dist/parse/emphasis.d.ts.map +1 -1
  17. package/dist/parse/emphasis.js +30 -33
  18. package/dist/parse/emphasis.js.map +1 -1
  19. package/dist/parse/inline.d.ts.map +1 -1
  20. package/dist/parse/inline.js +22 -4
  21. package/dist/parse/inline.js.map +1 -1
  22. package/dist/parse.js +6 -6
  23. package/dist/parse.js.map +1 -1
  24. package/dist/use-nizel.d.ts +5 -1
  25. package/dist/use-nizel.d.ts.map +1 -1
  26. package/dist/use-nizel.js +31 -14
  27. package/dist/use-nizel.js.map +1 -1
  28. package/dist/utils.d.ts.map +1 -1
  29. package/dist/utils.js +9 -7
  30. package/dist/utils.js.map +1 -1
  31. package/dist/wasm/backend.d.ts +7 -0
  32. package/dist/wasm/backend.d.ts.map +1 -0
  33. package/dist/wasm/backend.js +65 -0
  34. package/dist/wasm/backend.js.map +1 -0
  35. package/dist/wasm/bytes.js +1 -0
  36. package/dist/wasm/renderer.wasm +0 -0
  37. package/dist/wasm.d.ts +6 -0
  38. package/dist/wasm.d.ts.map +1 -0
  39. package/dist/wasm.js +10 -0
  40. package/dist/wasm.js.map +1 -0
  41. package/package.json +13 -3
package/README.md CHANGED
@@ -110,3 +110,24 @@ For ready-to-link content styling, use `nizel-style`. It ships scoped CSS for co
110
110
  ## License
111
111
 
112
112
  MIT
113
+
114
+ ## Optional WebAssembly renderer
115
+
116
+ Import from `nizel/wasm` on Node or `nizel/browser/wasm` in a browser build. The opt-in entry points have the same exports and call signatures as the corresponding JavaScript entry points.
117
+
118
+ ```js
119
+ import { useNizel, htmlToMarkdown } from 'nizel/wasm';
120
+
121
+ const nizel = useNizel();
122
+ const html = await nizel.html('A **bold** word.');
123
+ const markdown = htmlToMarkdown(html);
124
+ ```
125
+
126
+ The module is compiled lazily on the first eligible call. The binary is included in the package, so initialization needs no network request. Standard imports keep using JavaScript. Consumers can switch imports independently in the same process. To disable Wasm, switch back to the original entry point.
127
+
128
+ - Markdown acceleration covers ASCII paragraphs, line breaks, uncomplicated ATX headings and IDs, and simple inline code and emphasis. HTML conversion covers the corresponding semantic markup, common named entities, and simple headings with matching IDs.
129
+ - The backend falls back for unsupported syntax, custom rendering rules, AST transforms, reverse plugin handlers, or inputs over 1,048,576 UTF-16 code units. It also falls back when the runtime blocks compilation or a Wasm operation fails. Before-parse and after-render hooks run in either path.
130
+ - AST, document, metadata, and text APIs continue to use the existing JS implementation. The browser wrapper accepts the same strings, nodes, ranges, and selections.
131
+ - Run `npm run build --workspace nizel` to build the optional binary from `packages/nizel/assembly/renderer.ts`. The AssemblyScript compiler is a build dependency. The package verification suite compares both entry points, both conversion directions, missing-Wasm fallback, options, and plugin behavior against the stock implementation.
132
+
133
+ For the offline WebView bundle, use `nizel-kit/wasm` or the `nizel-kit.wasm.iife.js` build from the matching `nizel-kit` release. Keep JavaScript fallback enabled and measure the HTML subset and plugin configuration you actually ship. On a site with a restrictive Content Security Policy, compilation must be permitted for the fast path to run.
@@ -2246,9 +2246,16 @@ ${trimmed}
2246
2246
  };
2247
2247
 
2248
2248
  // src/utils.ts
2249
+ var htmlEntities = {
2250
+ "&": "&",
2251
+ "<": "&lt;",
2252
+ ">": "&gt;",
2253
+ '"': "&quot;"
2254
+ };
2255
+ var replaceHtmlEntity = (character) => htmlEntities[character];
2249
2256
  var escapeHtml = (value) => {
2250
2257
  const text = String(value);
2251
- return /[&<>"]/.test(text) ? text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;") : text;
2258
+ return /[&<>"]/.test(text) ? text.replace(/[&<>"]/g, replaceHtmlEntity) : text;
2252
2259
  };
2253
2260
  var slugify = (value, style = "github") => {
2254
2261
  if (style === "classic") {
@@ -2886,34 +2893,29 @@ ${trimmed}
2886
2893
  // src/parse/emphasis.ts
2887
2894
  var resolveRemainingEmphasis = (nodes) => {
2888
2895
  const tokens = tokenizeEmphasisDelimiters(nodes);
2889
- let changed = true;
2890
- while (changed) {
2891
- changed = false;
2892
- for (let closeIndex = 0; closeIndex < tokens.length; closeIndex += 1) {
2893
- const closer = tokens[closeIndex];
2894
- if (closer.type !== "delimiter" || !closer.close || closer.length === 0) continue;
2895
- for (let openIndex = closeIndex - 1; openIndex >= 0; openIndex -= 1) {
2896
- const opener = tokens[openIndex];
2897
- if (opener.type !== "delimiter" || !opener.open || opener.char !== closer.char || opener.length === 0) {
2898
- continue;
2899
- }
2900
- if (isForbiddenDelimiterMatch(opener, closer)) continue;
2901
- const size = opener.length >= 2 && closer.length >= 2 ? 2 : 1;
2902
- const children = inlineTokensToNodes(tokens.slice(openIndex + 1, closeIndex));
2903
- const wrapped = size === 2 ? { type: "strong", children: resolveRemainingEmphasis(children) } : { type: "emphasis", children: resolveRemainingEmphasis(children) };
2904
- const replacement = [];
2905
- if (opener.length > size) {
2906
- replacement.push({ ...opener, length: opener.length - size });
2907
- }
2908
- replacement.push({ type: "node", node: wrapped });
2909
- if (closer.length > size) {
2910
- replacement.push({ ...closer, length: closer.length - size });
2911
- }
2912
- tokens.splice(openIndex, closeIndex - openIndex + 1, ...replacement);
2913
- changed = true;
2914
- closeIndex = -1;
2915
- break;
2896
+ for (let closeIndex = 0; closeIndex < tokens.length; closeIndex += 1) {
2897
+ const closer = tokens[closeIndex];
2898
+ if (closer.type !== "delimiter" || !closer.close || closer.length === 0) continue;
2899
+ for (let openIndex = closeIndex - 1; openIndex >= 0; openIndex -= 1) {
2900
+ const opener = tokens[openIndex];
2901
+ if (opener.type !== "delimiter" || !opener.open || opener.char !== closer.char || opener.length === 0) {
2902
+ continue;
2903
+ }
2904
+ if (isForbiddenDelimiterMatch(opener, closer)) continue;
2905
+ const size = opener.length >= 2 && closer.length >= 2 ? 2 : 1;
2906
+ const children = inlineTokensToNodes(tokens.slice(openIndex + 1, closeIndex));
2907
+ const wrapped = size === 2 ? { type: "strong", children: resolveRemainingEmphasis(children) } : { type: "emphasis", children: resolveRemainingEmphasis(children) };
2908
+ const replacement = [];
2909
+ if (opener.length > size) {
2910
+ replacement.push({ ...opener, length: opener.length - size });
2916
2911
  }
2912
+ replacement.push({ type: "node", node: wrapped });
2913
+ if (closer.length > size) {
2914
+ replacement.push({ ...closer, length: closer.length - size });
2915
+ }
2916
+ tokens.splice(openIndex, closeIndex - openIndex + 1, ...replacement);
2917
+ closeIndex = openIndex - 1;
2918
+ break;
2917
2919
  }
2918
2920
  }
2919
2921
  return inlineTokensToNodes(tokens);
@@ -3238,22 +3240,35 @@ ${trimmed}
3238
3240
  };
3239
3241
 
3240
3242
  // src/parse/inline.ts
3243
+ var inlineTokenPatternWithoutBareEmail = new RegExp("(?<inlineHtml><!-->|<!--->|<!--[\\s\\S]*?-->|<\\?[\\s\\S]*?\\?>|<![A-Z][^>]*>|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>|<\\/?[A-Za-z][A-Za-z0-9-]*(?:\\s+[A-Za-z_:][A-Za-z0-9_.:-]*(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'=<>`]+))?)*\\s*\\/?>)|(?<hardSpaces> {2,}\\n)|(?<hardBackslash>\\\\\\n)|(?<softBreak>\\n)|(?<!`)(?<codeTicks>`+)(?!`)(?<codeValue>[\\s\\S]*?)(?<!`)\\k<codeTicks>(?!`)|\\\\(?<escaped>[!\"#$%&'()*+,\\-./:;<=>?@[\\\\\\]^_`{|}~])|&(?<entity>[A-Za-z][A-Za-z0-9]+|#[0-9]+|#[xX][0-9A-Fa-f]+);|!\\[(?<refImageAlt>[^\\]]*)\\]\\[(?<refImageLabel>[^\\]]*)\\]|\\[(?<refLinkText>[^\\]`<\\[]+)\\]\\[(?<refLinkLabel>[^\\]]*)\\]|!\\[(?<inlineImageAlt>[^\\]`<]*)\\]\\([ \\t\\n]*(?<inlineImageHref><[^<>\\n\\\\]*>|(?!<)(?:\\\\.|[^() \\t\\n`\\\\]|\\([^()\\n]*(?:\\([^()\\n]*\\)[^()\\n]*)*\\))*)(?:[ \\t\\n]+(?:\"(?<inlineImageTitle>(?:\\\\.|[^\"`])*)\"|'(?<inlineImageTitleSingle>[^']*)'|\\((?<inlineImageTitleParen>[^)]*)\\)))?[ \\t\\n]*\\)|\\[(?<inlineLinkText>[^\\]`<]*)\\]\\([ \\t\\n]*(?<inlineLinkHref><[^<>\\n\\\\]*>|(?!<)(?:\\\\.|[^() \\t\\n`\\\\]|\\([^()\\n]*(?:\\([^()\\n]*\\)[^()\\n]*)*\\))*)(?:[ \\t\\n]+(?:\"(?<inlineLinkTitle>(?:\\\\.|[^\"`])*)\"|'(?<inlineLinkTitleSingle>[^']*)'|\\((?<inlineLinkTitleParen>[^)]*)\\)))?[ \\t\\n]*\\)|<(?<angleUrl>[A-Za-z][A-Za-z0-9+.-]{1,31}:[^<>\\s]*)>|<(?<angleEmail>[A-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?(?:\\.[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?)*)>|!\\[(?<shortcutImageAlt>(?:\\\\\\]|[^\\]`<\\[])+)\\]|\\[(?<shortcutLinkText>(?:\\\\\\]|[^\\]`<\\[])+)\\]|~~(?<deleteValue>[^~`]+)~~|(?<bareUrl>https?:\\/\\/[^\\s<`]+)", "giu");
3244
+ var bareEmailPattern = /(?<bareEmail>[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,})/giu;
3245
+ var inlineTokenPatternWithBareEmail = new RegExp(
3246
+ inlineTokenPatternWithoutBareEmail.source + "|" + bareEmailPattern.source,
3247
+ inlineTokenPatternWithoutBareEmail.flags
3248
+ );
3241
3249
  var parseInline = (source, options = { autolinks: true }) => parseInlineWithState(source, options, { references: /* @__PURE__ */ new Map() });
3242
3250
  var parseInlineWithState = (source, options = { autolinks: true }, state, extractNestedLinks = true) => {
3243
3251
  const autolinks = options.autolinks !== false && getAutolinkOptions(options.autolinks).enabled !== false;
3244
3252
  if (!hasInlineSyntax(source, autolinks)) {
3245
3253
  return source ? [{ type: "text", value: source }] : [];
3246
3254
  }
3255
+ const hasAtSign = source.includes("@");
3256
+ if (!hasAtSign && !hasNonEmphasisSyntax(source)) {
3257
+ return resolveRemainingEmphasis([{ type: "text", value: source }]);
3258
+ }
3247
3259
  if (extractNestedLinks && hasBalancedLinkCandidate(source)) {
3248
3260
  const scanned = scanBalancedInlineLinks(source, options, state);
3249
3261
  if (scanned) return resolveRemainingEmphasis(scanned);
3250
3262
  }
3251
3263
  const nodes = [];
3252
3264
  const safe = options.safe !== false;
3253
- const pattern = new RegExp("(?<inlineHtml><!-->|<!--->|<!--[\\s\\S]*?-->|<\\?[\\s\\S]*?\\?>|<![A-Z][^>]*>|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>|<\\/?[A-Za-z][A-Za-z0-9-]*(?:\\s+[A-Za-z_:][A-Za-z0-9_.:-]*(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'=<>`]+))?)*\\s*\\/?>)|(?<hardSpaces> {2,}\\n)|(?<hardBackslash>\\\\\\n)|(?<softBreak>\\n)|(?<!`)(?<codeTicks>`+)(?!`)(?<codeValue>[\\s\\S]*?)(?<!`)\\k<codeTicks>(?!`)|\\\\(?<escaped>[!\"#$%&'()*+,\\-./:;<=>?@[\\\\\\]^_`{|}~])|&(?<entity>[A-Za-z][A-Za-z0-9]+|#[0-9]+|#[xX][0-9A-Fa-f]+);|!\\[(?<refImageAlt>[^\\]]*)\\]\\[(?<refImageLabel>[^\\]]*)\\]|\\[(?<refLinkText>[^\\]`<\\[]+)\\]\\[(?<refLinkLabel>[^\\]]*)\\]|!\\[(?<inlineImageAlt>[^\\]`<]*)\\]\\([ \\t\\n]*(?<inlineImageHref><[^<>\\n\\\\]*>|(?!<)(?:\\\\.|[^() \\t\\n`\\\\]|\\([^()\\n]*(?:\\([^()\\n]*\\)[^()\\n]*)*\\))*)(?:[ \\t\\n]+(?:\"(?<inlineImageTitle>(?:\\\\.|[^\"`])*)\"|'(?<inlineImageTitleSingle>[^']*)'|\\((?<inlineImageTitleParen>[^)]*)\\)))?[ \\t\\n]*\\)|\\[(?<inlineLinkText>[^\\]`<]*)\\]\\([ \\t\\n]*(?<inlineLinkHref><[^<>\\n\\\\]*>|(?!<)(?:\\\\.|[^() \\t\\n`\\\\]|\\([^()\\n]*(?:\\([^()\\n]*\\)[^()\\n]*)*\\))*)(?:[ \\t\\n]+(?:\"(?<inlineLinkTitle>(?:\\\\.|[^\"`])*)\"|'(?<inlineLinkTitleSingle>[^']*)'|\\((?<inlineLinkTitleParen>[^)]*)\\)))?[ \\t\\n]*\\)|<(?<angleUrl>[A-Za-z][A-Za-z0-9+.-]{1,31}:[^<>\\s]*)>|<(?<angleEmail>[A-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?(?:\\.[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?)*)>|!\\[(?<shortcutImageAlt>(?:\\\\\\]|[^\\]`<\\[])+)\\]|\\[(?<shortcutLinkText>(?:\\\\\\]|[^\\]`<\\[])+)\\]|~~(?<deleteValue>[^~`]+)~~|(?<bareUrl>https?:\\/\\/[^\\s<`]+)|(?<bareEmail>[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,})", "giu");
3265
+ const pattern = hasAtSign ? inlineTokenPatternWithBareEmail : inlineTokenPatternWithoutBareEmail;
3254
3266
  let lastIndex = 0;
3255
- let match;
3256
- while (match = pattern.exec(source)) {
3267
+ while (true) {
3268
+ pattern.lastIndex = lastIndex;
3269
+ const match = pattern.exec(source);
3270
+ if (!match) break;
3271
+ const end = pattern.lastIndex;
3257
3272
  if (match.index > lastIndex) {
3258
3273
  nodes.push({ type: "text", value: source.slice(lastIndex, match.index) });
3259
3274
  }
@@ -3388,7 +3403,7 @@ ${trimmed}
3388
3403
  } else {
3389
3404
  nodes.push({ type: "text", value: match[0] });
3390
3405
  }
3391
- lastIndex = pattern.lastIndex;
3406
+ lastIndex = end;
3392
3407
  }
3393
3408
  if (lastIndex < source.length) nodes.push({ type: "text", value: source.slice(lastIndex) });
3394
3409
  return resolveRemainingEmphasis(nodes);
@@ -3398,6 +3413,9 @@ ${trimmed}
3398
3413
  if (/[\\`<&\n\[\]*_~]/.test(source)) return true;
3399
3414
  return autolinks && (source.includes("http://") || source.includes("https://") || source.includes("@"));
3400
3415
  };
3416
+ var hasNonEmphasisSyntax = (source) => {
3417
+ return /[`<&\n[~\\]|https?:\/\//i.test(source);
3418
+ };
3401
3419
  var hasBalancedLinkCandidate = (source) => {
3402
3420
  return source.includes("[");
3403
3421
  };
@@ -3791,7 +3809,7 @@ ${line}`) !== null;
3791
3809
  function parseMarkdown(markdown, options) {
3792
3810
  const normalizedMarkdown = markdown.includes("\r") ? markdown.replace(/\r\n?/g, "\n") : markdown;
3793
3811
  const lines = normalizedMarkdown.includes(" ") ? expandLeadingTabsToLines(normalizedMarkdown) : normalizedMarkdown.split("\n");
3794
- const { contentLines, references } = normalizedMarkdown.includes("[") && hasPossibleReferenceDefinitionStart(normalizedMarkdown) ? extractReferenceDefinitions(lines) : { contentLines: lines, references: /* @__PURE__ */ new Map() };
3812
+ const { contentLines, references } = normalizedMarkdown.includes("]:") && hasPossibleReferenceDefinitionStart(normalizedMarkdown) ? extractReferenceDefinitions(lines) : { contentLines: lines, references: /* @__PURE__ */ new Map() };
3795
3813
  const children = parseBlocks(contentLines, options, /* @__PURE__ */ new Map(), { references });
3796
3814
  return { type: "root", children };
3797
3815
  }
@@ -3802,7 +3820,8 @@ ${line}`) !== null;
3802
3820
  const children = [];
3803
3821
  for (let index = 0; index < lines.length; index += 1) {
3804
3822
  const line = lines[index];
3805
- if (!line.trim()) continue;
3823
+ const trimmed = line.trim();
3824
+ if (!trimmed) continue;
3806
3825
  if (!options.safe) {
3807
3826
  const htmlBlock = readHtmlBlock(lines, index);
3808
3827
  if (htmlBlock) {
@@ -3811,7 +3830,7 @@ ${line}`) !== null;
3811
3830
  continue;
3812
3831
  }
3813
3832
  }
3814
- const customBlock = /^::([A-Za-z][\w-]*)(?:\s+(.*))?$/.exec(line.trim());
3833
+ const customBlock = /^::([A-Za-z][\w-]*)(?:\s+(.*))?$/.exec(trimmed);
3815
3834
  if (customBlock) {
3816
3835
  const parsed = readCustomBlock(lines, index);
3817
3836
  const args = splitWords(customBlock[2] ?? "");
@@ -3894,9 +3913,8 @@ ${line}`) !== null;
3894
3913
  continue;
3895
3914
  }
3896
3915
  const setext = lines[index + 1] && isSetextUnderline(lines[index + 1]);
3897
- if (setext && line.trim() && !isBlockStart(line, options, lines, index)) {
3898
- const source = line.trim();
3899
- const inlineChildren = parseInlineWithState(source, options, state);
3916
+ if (setext && !isBlockStart(line, options, lines, index)) {
3917
+ const inlineChildren = parseInlineWithState(trimmed, options, state);
3900
3918
  const text = stripInlineNodes(inlineChildren);
3901
3919
  const node = {
3902
3920
  type: "heading",
@@ -4620,7 +4638,7 @@ ${" ".repeat(marker.length + 1)}${line}`).join("")}`;
4620
4638
  };
4621
4639
 
4622
4640
  // src/use-nizel.ts
4623
- function createNizel(options = {}) {
4641
+ function createNizel(options = {}, htmlBackend) {
4624
4642
  const presetOptions = options.preset ? resolvePreset(options.preset) : {};
4625
4643
  const effectiveOptions = { ...presetOptions, ...options, preset: void 0 };
4626
4644
  const baseResolved = resolveOptions(effectiveOptions, {});
@@ -4649,7 +4667,11 @@ ${" ".repeat(marker.length + 1)}${line}`).join("")}`;
4649
4667
  }
4650
4668
  const nizel = process;
4651
4669
  nizel.html = async (markdown, runtimeOptions) => {
4652
- const { ast, resolved } = prepareMarkdown(markdown, runtimeOptions);
4670
+ const prepared = prepareMeta(markdown, runtimeOptions);
4671
+ const source = prepareSource(prepared);
4672
+ const accelerated = htmlBackend?.(source, prepared.resolved);
4673
+ if (accelerated !== void 0) return applyAfterRender(accelerated, prepared.resolved);
4674
+ const { ast, resolved } = prepareMarkdown(markdown, runtimeOptions, prepared, source);
4653
4675
  return renderPreparedHtml(ast, resolved);
4654
4676
  };
4655
4677
  nizel.text = async (markdown, runtimeOptions) => {
@@ -4662,7 +4684,7 @@ ${" ".repeat(marker.length + 1)}${line}`).join("")}`;
4662
4684
  nizel.meta = async (markdown, runtimeOptions) => {
4663
4685
  return prepareMeta(markdown, runtimeOptions).meta;
4664
4686
  };
4665
- nizel.preset = (name) => createNizel(resolvePreset(name));
4687
+ nizel.preset = (name) => createNizel(resolvePreset(name), htmlBackend);
4666
4688
  nizel.parse = async (markdown, runtimeOptions) => {
4667
4689
  const resolved = resolveRuntime(runtimeOptions);
4668
4690
  const extracted = resolved.frontmatter === false ? { markdown, frontmatter: {} } : extractFrontmatter(markdown);
@@ -4691,15 +4713,7 @@ ${" ".repeat(marker.length + 1)}${line}`).join("")}`;
4691
4713
  return createNizelDocument(result);
4692
4714
  };
4693
4715
  return nizel;
4694
- function prepareMarkdown(markdown, runtimeOptions = {}) {
4695
- const preparedMeta = prepareMeta(markdown, runtimeOptions);
4696
- let preparedMarkdown = preparedMeta.markdown;
4697
- for (const plugin of preparedMeta.resolved.plugins ?? []) {
4698
- const nextMarkdown = plugin.hooks?.beforeParse?.(preparedMarkdown, preparedMeta.resolved);
4699
- if (nextMarkdown !== void 0) {
4700
- preparedMarkdown = nextMarkdown;
4701
- }
4702
- }
4716
+ function prepareMarkdown(markdown, runtimeOptions = {}, preparedMeta = prepareMeta(markdown, runtimeOptions), preparedMarkdown = prepareSource(preparedMeta)) {
4703
4717
  let ast = parseMarkdown(preparedMarkdown, {
4704
4718
  anchors: preparedMeta.resolved.anchors !== false,
4705
4719
  autolinks: preparedMeta.resolved.autolinks,
@@ -4765,6 +4779,14 @@ ${" ".repeat(marker.length + 1)}${line}`).join("")}`;
4765
4779
  };
4766
4780
  }
4767
4781
  }
4782
+ function prepareSource(prepared) {
4783
+ let markdown = prepared.markdown;
4784
+ for (const plugin of prepared.resolved.plugins ?? []) {
4785
+ const next = plugin.hooks?.beforeParse?.(markdown, prepared.resolved);
4786
+ if (next !== void 0) markdown = next;
4787
+ }
4788
+ return markdown;
4789
+ }
4768
4790
  function renderPreparedHtml(ast, resolved) {
4769
4791
  const html = renderHtml(
4770
4792
  ast,
@@ -4774,6 +4796,9 @@ ${" ".repeat(marker.length + 1)}${line}`).join("")}`;
4774
4796
  unwrapStandaloneImages: resolved.unwrapStandaloneImages === true
4775
4797
  }
4776
4798
  );
4799
+ return applyAfterRender(html, resolved);
4800
+ }
4801
+ function applyAfterRender(html, resolved) {
4777
4802
  let finalHtml = html;
4778
4803
  for (const plugin of resolved.plugins ?? []) {
4779
4804
  const modified = plugin.hooks?.afterRender?.(finalHtml, resolved);
@@ -4795,8 +4820,13 @@ ${" ".repeat(marker.length + 1)}${line}`).join("")}`;
4795
4820
  function hasRuntimeOptions(runtimeOptions) {
4796
4821
  return Boolean(runtimeOptions && Object.keys(runtimeOptions).length > 0);
4797
4822
  }
4798
- var useNizel = createNizel;
4799
- useNizel.preset = (name) => createNizel(resolvePreset(name));
4823
+ function createNizelFactory(htmlBackend) {
4824
+ const factory = (options) => createNizel(options, htmlBackend);
4825
+ return Object.assign(factory, {
4826
+ preset: (name) => createNizel(resolvePreset(name), htmlBackend)
4827
+ });
4828
+ }
4829
+ var useNizel = createNizelFactory();
4800
4830
  function stringMeta(value) {
4801
4831
  return typeof value === "string" ? value : void 0;
4802
4832
  }
@@ -4858,6 +4888,100 @@ ${" ".repeat(marker.length + 1)}${line}`).join("")}`;
4858
4888
  };
4859
4889
  }
4860
4890
 
4891
+ // src/browser-runtime.ts
4892
+ function createBrowserRuntime(useNizel2, baseHtmlToMarkdown) {
4893
+ function useBrowserNizel2(options = {}) {
4894
+ const processor = useNizel2(options);
4895
+ processor.markdownToHtml = (markdown, runtimeOptions) => processor.html(markdown, runtimeOptions);
4896
+ processor.mount = async (target, markdown, runtimeOptions) => mountMarkdown2(target, markdown, runtimeOptions, processor);
4897
+ processor.htmlToMarkdown = htmlToMarkdown3;
4898
+ processor.nodeToMarkdown = nodeToMarkdown2;
4899
+ processor.selectionToMarkdown = selectionToMarkdown2;
4900
+ return processor;
4901
+ }
4902
+ async function markdownToHtml2(markdown, runtimeOptions) {
4903
+ return useNizel2().html(markdown, runtimeOptions);
4904
+ }
4905
+ async function mountMarkdown2(target, markdown, runtimeOptions, processor = useNizel2()) {
4906
+ const element = resolveMountTarget(target);
4907
+ element.innerHTML = await processor.html(markdown, runtimeOptions);
4908
+ return element;
4909
+ }
4910
+ function htmlToMarkdown3(source, options) {
4911
+ return baseHtmlToMarkdown(sourceToHtml(source), options);
4912
+ }
4913
+ function nodeToMarkdown2(source, options) {
4914
+ return htmlToMarkdown3(source, options);
4915
+ }
4916
+ function selectionToMarkdown2(selection = currentSelection(), options) {
4917
+ if (!selection || selection.rangeCount === 0) return "";
4918
+ return htmlToMarkdown3(selection, options);
4919
+ }
4920
+ return { useBrowserNizel: useBrowserNizel2, markdownToHtml: markdownToHtml2, mountMarkdown: mountMarkdown2, htmlToMarkdown: htmlToMarkdown3, nodeToMarkdown: nodeToMarkdown2, selectionToMarkdown: selectionToMarkdown2 };
4921
+ }
4922
+ function sourceToHtml(source) {
4923
+ if (typeof source === "string") return source;
4924
+ if (isSelection(source)) return serializeSelection(source);
4925
+ if (isRange(source)) return serializeNode(source.cloneContents());
4926
+ if (isNodeList(source)) return Array.from(source, serializeNode).join("");
4927
+ return serializeNode(source);
4928
+ }
4929
+ function serializeNode(node) {
4930
+ if (isElement(node) && typeof node.outerHTML === "string") return node.outerHTML;
4931
+ switch (node.nodeType) {
4932
+ case 3:
4933
+ case 4:
4934
+ return escapeHtml2(node.nodeValue ?? "");
4935
+ case 8:
4936
+ return `<!--${node.nodeValue ?? ""}-->`;
4937
+ case 9: {
4938
+ const documentNode = node;
4939
+ return documentNode.documentElement?.outerHTML ?? serializeChildren(node);
4940
+ }
4941
+ case 11:
4942
+ return serializeChildren(node);
4943
+ default:
4944
+ return "childNodes" in node ? serializeChildren(node) : "";
4945
+ }
4946
+ }
4947
+ function serializeChildren(node) {
4948
+ return Array.from(node.childNodes, serializeNode).join("");
4949
+ }
4950
+ function serializeSelection(selection) {
4951
+ const fragments = [];
4952
+ for (let index = 0; index < selection.rangeCount; index += 1) {
4953
+ fragments.push(serializeNode(selection.getRangeAt(index).cloneContents()));
4954
+ }
4955
+ return fragments.join("");
4956
+ }
4957
+ function resolveMountTarget(target) {
4958
+ if (typeof target !== "string") return target;
4959
+ if (typeof document === "undefined") {
4960
+ throw new Error("nizel/browser mountMarkdown() needs a browser document when target is a selector.");
4961
+ }
4962
+ const element = document.querySelector(target);
4963
+ if (!element) throw new Error(`nizel/browser could not find mount target: ${target}`);
4964
+ return element;
4965
+ }
4966
+ function currentSelection() {
4967
+ return typeof globalThis.getSelection === "function" ? globalThis.getSelection() : null;
4968
+ }
4969
+ function isSelection(value) {
4970
+ return "rangeCount" in value && "getRangeAt" in value;
4971
+ }
4972
+ function isRange(value) {
4973
+ return "cloneContents" in value && "startContainer" in value && "endContainer" in value;
4974
+ }
4975
+ function isNodeList(value) {
4976
+ return "length" in value && !("nodeType" in value);
4977
+ }
4978
+ function isElement(value) {
4979
+ return value.nodeType === 1 && "outerHTML" in value;
4980
+ }
4981
+ function escapeHtml2(value) {
4982
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
4983
+ }
4984
+
4861
4985
  // src/plugins/define-nizel-plugin.ts
4862
4986
  var defineNizelPlugin = (plugin) => {
4863
4987
  return plugin;
@@ -5000,94 +5124,13 @@ ${customClosers.join("\n")}`;
5000
5124
  }
5001
5125
 
5002
5126
  // src/browser.ts
5003
- function useBrowserNizel(options = {}) {
5004
- const processor = useNizel(options);
5005
- processor.markdownToHtml = (markdown, runtimeOptions) => processor.html(markdown, runtimeOptions);
5006
- processor.mount = async (target, markdown, runtimeOptions) => mountMarkdown(target, markdown, runtimeOptions, processor);
5007
- processor.htmlToMarkdown = htmlToMarkdown2;
5008
- processor.nodeToMarkdown = nodeToMarkdown;
5009
- processor.selectionToMarkdown = selectionToMarkdown;
5010
- return processor;
5011
- }
5012
- async function markdownToHtml(markdown, runtimeOptions) {
5013
- return useNizel().html(markdown, runtimeOptions);
5014
- }
5015
- async function mountMarkdown(target, markdown, runtimeOptions, processor = useNizel()) {
5016
- const element = resolveMountTarget(target);
5017
- element.innerHTML = await processor.html(markdown, runtimeOptions);
5018
- return element;
5019
- }
5020
- function htmlToMarkdown2(source, options) {
5021
- return htmlToMarkdown(sourceToHtml(source), options);
5022
- }
5023
- function nodeToMarkdown(source, options) {
5024
- return htmlToMarkdown2(source, options);
5025
- }
5026
- function selectionToMarkdown(selection = currentSelection(), options) {
5027
- if (!selection || selection.rangeCount === 0) return "";
5028
- return htmlToMarkdown2(selection, options);
5029
- }
5030
- function sourceToHtml(source) {
5031
- if (typeof source === "string") return source;
5032
- if (isSelection(source)) return serializeSelection(source);
5033
- if (isRange(source)) return serializeNode(source.cloneContents());
5034
- if (isNodeList(source)) return Array.from(source, serializeNode).join("");
5035
- return serializeNode(source);
5036
- }
5037
- function serializeNode(node) {
5038
- if (isElement(node) && typeof node.outerHTML === "string") return node.outerHTML;
5039
- switch (node.nodeType) {
5040
- case 3:
5041
- case 4:
5042
- return escapeHtml2(node.nodeValue ?? "");
5043
- case 8:
5044
- return `<!--${node.nodeValue ?? ""}-->`;
5045
- case 9: {
5046
- const documentNode = node;
5047
- return documentNode.documentElement?.outerHTML ?? serializeChildren(node);
5048
- }
5049
- case 11:
5050
- return serializeChildren(node);
5051
- default:
5052
- return "childNodes" in node ? serializeChildren(node) : "";
5053
- }
5054
- }
5055
- function serializeChildren(node) {
5056
- return Array.from(node.childNodes, serializeNode).join("");
5057
- }
5058
- function serializeSelection(selection) {
5059
- const fragments = [];
5060
- for (let index = 0; index < selection.rangeCount; index += 1) {
5061
- fragments.push(serializeNode(selection.getRangeAt(index).cloneContents()));
5062
- }
5063
- return fragments.join("");
5064
- }
5065
- function resolveMountTarget(target) {
5066
- if (typeof target !== "string") return target;
5067
- if (typeof document === "undefined") {
5068
- throw new Error("nizel/browser mountMarkdown() needs a browser document when target is a selector.");
5069
- }
5070
- const element = document.querySelector(target);
5071
- if (!element) throw new Error(`nizel/browser could not find mount target: ${target}`);
5072
- return element;
5073
- }
5074
- function currentSelection() {
5075
- return typeof globalThis.getSelection === "function" ? globalThis.getSelection() : null;
5076
- }
5077
- function isSelection(value) {
5078
- return "rangeCount" in value && "getRangeAt" in value;
5079
- }
5080
- function isRange(value) {
5081
- return "cloneContents" in value && "startContainer" in value && "endContainer" in value;
5082
- }
5083
- function isNodeList(value) {
5084
- return "length" in value && !("nodeType" in value);
5085
- }
5086
- function isElement(value) {
5087
- return value.nodeType === 1 && "outerHTML" in value;
5088
- }
5089
- function escapeHtml2(value) {
5090
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
5091
- }
5127
+ var {
5128
+ useBrowserNizel,
5129
+ markdownToHtml,
5130
+ mountMarkdown,
5131
+ htmlToMarkdown: htmlToMarkdown2,
5132
+ nodeToMarkdown,
5133
+ selectionToMarkdown
5134
+ } = createBrowserRuntime(useNizel, htmlToMarkdown);
5092
5135
  return __toCommonJS(browser_exports);
5093
5136
  })();