@takazudo/zfb-md-wasm 2.7.1 → 2.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +179 -49
- package/dist/parse-browser.d.ts +12 -0
- package/dist/parse-browser.js +17 -0
- package/dist/parse-browser.js.map +1 -0
- package/dist/parse.d.ts +12 -0
- package/dist/parse.js +23 -0
- package/dist/parse.js.map +1 -0
- package/dist/render-browser.d.ts +11 -0
- package/dist/render-browser.js +16 -0
- package/dist/render-browser.js.map +1 -0
- package/dist/render.d.ts +11 -0
- package/dist/render.js +22 -0
- package/dist/render.js.map +1 -0
- package/dist/runtime.d.ts +1 -1
- package/dist/runtime.js +9 -12
- package/dist/runtime.js.map +1 -1
- package/dist/types.d.ts +6 -1
- package/dist/types.js.map +1 -1
- package/dist/wasm/zfb_md_wasm_bg.wasm +0 -0
- package/dist/wasm/zfb_md_wasm_glue.zfb-resource.d.mts +3 -1
- package/dist/wasm/zfb_md_wasm_glue.zfb-resource.mjs +3 -1
- package/dist/wasm-highlight/zfb_md_wasm_highlight_bg.wasm +0 -0
- package/dist/wasm-parse/zfb_md_wasm_parse_bg.wasm +0 -0
- package/dist/wasm-parse/zfb_md_wasm_parse_bg.wasm.d.ts +10 -0
- package/dist/wasm-parse/zfb_md_wasm_parse_glue.zfb-resource.d.mts +108 -0
- package/dist/wasm-parse/zfb_md_wasm_parse_glue.zfb-resource.mjs +300 -0
- package/dist/wasm-render/zfb_md_wasm_render_bg.wasm +0 -0
- package/dist/wasm-render/zfb_md_wasm_render_bg.wasm.d.ts +10 -0
- package/dist/wasm-render/zfb_md_wasm_render_glue.zfb-resource.d.mts +68 -0
- package/dist/wasm-render/zfb_md_wasm_render_glue.zfb-resource.mjs +260 -0
- package/package.json +11 -1
package/dist/runtime.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AA2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E,SAAS,8BAA8B;QASrC,OAAO;YACL,mBAAmB;YACnB,iBAAiB;YACjB,mBAAmB;YACnB,kBAAkB;YAClB,iBAAiB,EAAE,mBAAmB;YACtC,qBAAqB;YACrB,QAAQ,EAAE,CAAC,CAAC,yBAAyB;SACtC,CAAC;IACJ,CAAC;IAED,OAAO;QACL,IAAI;QACJ,OAAO;QACP,UAAU;QACV,UAAU;QACV,aAAa;QACb,OAAO;QACP,mBAAmB;QACnB,8BAA8B;KAC/B,CAAC;AACJ,CAAC","sourcesContent":["import type {\n CompileResult,\n HighlightCodeOptions,\n HighlightCodeResult,\n ParseToAstOptions,\n ParseToAstResult,\n RenderHtmlResult,\n ZfbMdWasmOptions,\n} from \"./types.js\";\n\ninterface WasmGlueModule {\n // Keep this deliberately structural instead of importing the generated\n // glue's declaration file. The browser entry imports that file as a *URL\n // resource*, while the direct entry imports it dynamically. Both paths\n // nevertheless use the same wasm-bindgen surface and recovery\n // implementation below.\n //\n // `compile`/`renderHtml` are optional: the highlight-only wasm artifact\n // (`./highlight` entry, zfb#1849, epic zfb#1845) is compiled with the\n // `pipeline` Cargo feature off (see crates/zfb-md-wasm/Cargo.toml), so its\n // wasm-bindgen glue never generates these exports at all. `createWasmApi`\n // below is shared by both entries; only `src/index.ts`/`src/browser.ts`\n // re-export the functions that call them.\n initSync(input?: { module: WebAssembly.Module }): unknown;\n compile?(source: string, optionsJson: string): string;\n renderHtml?(source: string, optionsJson: string): string;\n // Raw-mdast export (zfb#1857, epic zfb#1854); pipeline-gated like\n // compile/renderHtml -- the highlight-only artifact never generates it.\n parseToAst?(source: string, optionsJson: string): string;\n highlightCode(code: string, optionsJson: string): string;\n version(): string;\n __forceTrapForTests(): void;\n}\n\nexport interface WasmResourceConfig {\n glueUrl: URL;\n loadWasmBytes(): Promise<ArrayBuffer>;\n /** @internal Deterministic test seam; production uses WebAssembly.compile. */\n compileWasm?(bytes: ArrayBuffer): Promise<WebAssembly.Module>;\n /** @internal Deterministic test seam; production dynamically imports the glue URL. */\n importGlue?(specifier: string): Promise<WasmGlueModule>;\n}\n\nexport class ZfbMdWasmTrapError extends Error {\n constructor(cause: unknown) {\n super(\n \"zfb-md-wasm: the wasm instance trapped (a Rust panic or internal fault) and has been \" +\n \"automatically re-instantiated. This is always a bug in zfb-md-wasm -- please report it \" +\n \"with the input that triggered it.\",\n );\n this.name = \"ZfbMdWasmTrapError\";\n this.cause = cause;\n }\n}\n\nexport class ZfbMdWasmTrapRecoveryLimitError extends Error {\n constructor(maxRecoveries: number, cause: unknown) {\n super(\n `zfb-md-wasm: wasm trap recovery limit reached after ${maxRecoveries} ` +\n `successful re-instantiations. Further automatic recovery is disabled to avoid ` +\n `unbounded ES module record growth. Reload the JS realm before using zfb-md-wasm ` +\n `again, and please report the input that triggered the repeated traps.`,\n );\n this.name = \"ZfbMdWasmTrapRecoveryLimitError\";\n this.cause = cause;\n }\n}\n\nexport function createWasmApi({\n glueUrl,\n loadWasmBytes,\n compileWasm = (bytes) => WebAssembly.compile(bytes),\n importGlue = (specifier) => import(/* @vite-ignore */ specifier) as Promise<WasmGlueModule>,\n}: WasmResourceConfig) {\n let compiledModulePromise: Promise<WebAssembly.Module> | undefined;\n let compiledModuleLoads = 0;\n\n function getCompiledModule(): Promise<WebAssembly.Module> {\n if (!compiledModulePromise) {\n compiledModuleLoads += 1;\n const attempt = Promise.resolve().then(loadWasmBytes).then(compileWasm);\n compiledModulePromise = attempt;\n void attempt.catch(() => {\n // A rejected attempt must be retryable, but it must not erase a newer\n // attempt if its rejection cleanup runs late.\n if (compiledModulePromise === attempt) {\n compiledModulePromise = undefined;\n }\n });\n }\n return compiledModulePromise;\n }\n\n const MAX_TRAP_RECOVERIES = 16;\n\n let currentGeneration = 0;\n let trapRecoveriesStarted = 0;\n let freshInstanceStarts = 0;\n let glueImportAttempts = 0;\n let terminalTrapRecoveryError: ZfbMdWasmTrapRecoveryLimitError | undefined;\n\n interface Instance {\n generation: number;\n glue: WasmGlueModule;\n }\n\n /**\n * Every fresh instance attempt creates a new wasm-bindgen glue module\n * record. The import-attempt nonce is deliberately independent of the trap\n * generation: transient import/initSync failures need a new module record\n * without consuming the bounded trap-recovery budget.\n */\n async function freshInstance(generation: number): Promise<Instance> {\n freshInstanceStarts += 1;\n glueImportAttempts += 1;\n const glueSpecifier = new URL(glueUrl.href);\n glueSpecifier.searchParams.set(\"zfbMdWasmGen\", String(generation));\n glueSpecifier.searchParams.set(\"zfbMdWasmAttempt\", String(glueImportAttempts));\n const [module, glue] = await Promise.all([\n getCompiledModule(),\n // Deferring the injected function also converts a synchronous test-seam\n // throw into the rejection handled by the retryable instance cache.\n Promise.resolve().then(() => importGlue(glueSpecifier.href)),\n ]);\n glue.initSync({ module });\n return { generation, glue };\n }\n\n let instancePromise: Promise<Instance> | undefined;\n\n function startInstance(generation: number): Promise<Instance> {\n const attempt = freshInstance(generation);\n instancePromise = attempt;\n void attempt.catch(() => {\n // Trap recovery can replace the installed instance promise. Never let a\n // stale initialization rejection clear that newer attempt.\n if (instancePromise === attempt) {\n instancePromise = undefined;\n }\n });\n return attempt;\n }\n\n function getInstance(): Promise<Instance> {\n if (terminalTrapRecoveryError) {\n return Promise.reject(terminalTrapRecoveryError);\n }\n if (!instancePromise) {\n return startInstance(currentGeneration);\n }\n return instancePromise;\n }\n\n function isTrap(err: unknown): boolean {\n return typeof WebAssembly !== \"undefined\" && err instanceof WebAssembly.RuntimeError;\n }\n\n async function recoverAfterTrap(observedGeneration: number, cause: unknown): Promise<void> {\n if (terminalTrapRecoveryError) {\n throw terminalTrapRecoveryError;\n }\n\n // CAS-style single-flight: reporters for an already-replaced generation\n // await its replacement instead of creating another glue module record.\n if (observedGeneration !== currentGeneration) {\n await getInstance();\n return;\n }\n\n if (trapRecoveriesStarted >= MAX_TRAP_RECOVERIES) {\n terminalTrapRecoveryError = new ZfbMdWasmTrapRecoveryLimitError(MAX_TRAP_RECOVERIES, cause);\n instancePromise = undefined;\n throw terminalTrapRecoveryError;\n }\n\n trapRecoveriesStarted += 1;\n currentGeneration += 1;\n await startInstance(currentGeneration);\n }\n\n async function callWasm<T>(fn: (instance: Instance) => T): Promise<T> {\n const instance = await getInstance();\n try {\n return fn(instance);\n } catch (err) {\n if (!isTrap(err)) {\n throw err;\n }\n await recoverAfterTrap(instance.generation, err);\n throw new ZfbMdWasmTrapError(err);\n }\n }\n\n async function init(): Promise<void> {\n await getInstance();\n }\n\n // Both throw helpers below fire only if `compile`/`renderHtml` were\n // somehow invoked against the highlight-only glue -- unreachable through\n // the public API surface, since `src/highlight.ts`/`src/highlight-browser.ts`\n // never re-export these two functions. Kept as a clear runtime error\n // rather than a silent `undefined()` crash.\n function requirePipelineExport<T>(fn: T | undefined, name: string): T {\n if (!fn) {\n throw new Error(\n `zfb-md-wasm: ${name}() is not available in the highlight-only wasm artifact ` +\n `(built with the \\`pipeline\\` Cargo feature off) -- use the default \\`.\\` entry instead.`,\n );\n }\n return fn;\n }\n\n async function compile(source: string, options: ZfbMdWasmOptions = {}): Promise<CompileResult> {\n const optionsJson = JSON.stringify(options);\n const json = await callWasm(({ glue }) =>\n requirePipelineExport(glue.compile, \"compile\").call(glue, source, optionsJson),\n );\n return JSON.parse(json) as CompileResult;\n }\n\n async function renderHtml(\n source: string,\n options: ZfbMdWasmOptions = {},\n ): Promise<RenderHtmlResult> {\n const optionsJson = JSON.stringify(options);\n const json = await callWasm(({ glue }) =>\n requirePipelineExport(glue.renderHtml, \"renderHtml\").call(glue, source, optionsJson),\n );\n return JSON.parse(json) as RenderHtmlResult;\n }\n\n /**\n * Parse markdown/MDX into a raw mdast tree (zfb#1857, epic zfb#1854).\n * The `parseToAst + JSON.parse` round trip here IS the product cost the\n * epic's benchmark measures against remark-parse. See `types.ts`'s\n * `ParseToAstResult`/`MdastNode` docs for the result shape and the\n * UTF-16 position contract.\n */\n async function parseToAst(\n source: string,\n options: ParseToAstOptions = {},\n ): Promise<ParseToAstResult> {\n const optionsJson = JSON.stringify(options);\n const json = await callWasm(({ glue }) =>\n requirePipelineExport(glue.parseToAst, \"parseToAst\").call(glue, source, optionsJson),\n );\n return JSON.parse(json) as ParseToAstResult;\n }\n\n async function highlightCode(\n code: string,\n options: HighlightCodeOptions,\n ): Promise<HighlightCodeResult> {\n const optionsJson = JSON.stringify(options);\n const json = await callWasm(({ glue }) => glue.highlightCode(code, optionsJson));\n return JSON.parse(json) as HighlightCodeResult;\n }\n\n async function version(): Promise<string> {\n return callWasm(({ glue }) => glue.version());\n }\n\n /** @internal Test-only hook that forces the current instance to trap. */\n async function __forceTrapForTests(): Promise<void> {\n await callWasm(({ glue }) => glue.__forceTrapForTests());\n }\n\n /** @internal Test-only observability for the bounded recovery contract. */\n function __getTrapRecoveryStateForTests(): {\n compiledModuleLoads: number;\n currentGeneration: number;\n freshInstanceStarts: number;\n glueImportAttempts: number;\n maxTrapRecoveries: number;\n trapRecoveriesStarted: number;\n terminal: boolean;\n } {\n return {\n compiledModuleLoads,\n currentGeneration,\n freshInstanceStarts,\n glueImportAttempts,\n maxTrapRecoveries: MAX_TRAP_RECOVERIES,\n trapRecoveriesStarted,\n terminal: !!terminalTrapRecoveryError,\n };\n }\n\n return {\n init,\n compile,\n renderHtml,\n parseToAst,\n highlightCode,\n version,\n __forceTrapForTests,\n __getTrapRecoveryStateForTests,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAuCA,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IAC3C,YAAY,KAAc;QACxB,KAAK,CACH,uFAAuF;YACrF,yFAAyF;YACzF,mCAAmC,CACtC,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;QACjC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;CACF;AAED,MAAM,OAAO,+BAAgC,SAAQ,KAAK;IACxD,YAAY,aAAqB,EAAE,KAAc;QAC/C,KAAK,CACH,uDAAuD,aAAa,GAAG;YACrE,gFAAgF;YAChF,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ult,\n HighlightCodeOptions,\n HighlightCodeResult,\n ParseToAstOptions,\n ParseToAstResult,\n RenderHtmlResult,\n ZfbMdWasmOptions,\n} from \"./types.js\";\n\ninterface WasmGlueModule {\n // Keep this deliberately structural instead of importing the generated\n // glue's declaration file. The browser entry imports that file as a *URL\n // resource*, while the direct entry imports it dynamically. Both paths\n // nevertheless use the same wasm-bindgen surface and recovery\n // implementation below.\n //\n // Capability functions are structural and optional because each singleton\n // artifact's wasm-bindgen glue contains only its selected Rust export.\n // Public entries expose only the matching calls from `createWasmApi`.\n initSync(input?: { module: WebAssembly.Module }): unknown;\n compile?(source: string, optionsJson: string): string;\n renderHtml?(source: string, optionsJson: string): string;\n // Raw-mdast export (zfb#1857, epic zfb#1854).\n parseToAst?(source: string, optionsJson: string): string;\n highlightCode?(code: string, optionsJson: string): string;\n version(): string;\n __forceTrapForTests(): void;\n}\n\nexport interface WasmResourceConfig {\n glueUrl: URL;\n loadWasmBytes(): Promise<ArrayBuffer>;\n /** @internal Deterministic test seam; production uses WebAssembly.compile. */\n compileWasm?(bytes: ArrayBuffer): Promise<WebAssembly.Module>;\n /** @internal Deterministic test seam; production dynamically imports the glue URL. */\n importGlue?(specifier: string): Promise<WasmGlueModule>;\n}\n\nexport class ZfbMdWasmTrapError extends Error {\n constructor(cause: unknown) {\n super(\n \"zfb-md-wasm: the wasm instance trapped (a Rust panic or internal fault) and has been \" +\n \"automatically re-instantiated. This is always a bug in zfb-md-wasm -- please report it \" +\n \"with the input that triggered it.\",\n );\n this.name = \"ZfbMdWasmTrapError\";\n this.cause = cause;\n }\n}\n\nexport class ZfbMdWasmTrapRecoveryLimitError extends Error {\n constructor(maxRecoveries: number, cause: unknown) {\n super(\n `zfb-md-wasm: wasm trap recovery limit reached after ${maxRecoveries} ` +\n `successful re-instantiations. Further automatic recovery is disabled to avoid ` +\n `unbounded ES module record growth. Reload the JS realm before using zfb-md-wasm ` +\n `again, and please report the input that triggered the repeated traps.`,\n );\n this.name = \"ZfbMdWasmTrapRecoveryLimitError\";\n this.cause = cause;\n }\n}\n\nexport function createWasmApi({\n glueUrl,\n loadWasmBytes,\n compileWasm = (bytes) => WebAssembly.compile(bytes),\n importGlue = (specifier) => import(/* @vite-ignore */ specifier) as Promise<WasmGlueModule>,\n}: WasmResourceConfig) {\n let compiledModulePromise: Promise<WebAssembly.Module> | undefined;\n let compiledModuleLoads = 0;\n\n function getCompiledModule(): Promise<WebAssembly.Module> {\n if (!compiledModulePromise) {\n compiledModuleLoads += 1;\n const attempt = Promise.resolve().then(loadWasmBytes).then(compileWasm);\n compiledModulePromise = attempt;\n void attempt.catch(() => {\n // A rejected attempt must be retryable, but it must not erase a newer\n // attempt if its rejection cleanup runs late.\n if (compiledModulePromise === attempt) {\n compiledModulePromise = undefined;\n }\n });\n }\n return compiledModulePromise;\n }\n\n const MAX_TRAP_RECOVERIES = 16;\n\n let currentGeneration = 0;\n let trapRecoveriesStarted = 0;\n let freshInstanceStarts = 0;\n let glueImportAttempts = 0;\n let terminalTrapRecoveryError: ZfbMdWasmTrapRecoveryLimitError | undefined;\n\n interface Instance {\n generation: number;\n glue: WasmGlueModule;\n }\n\n /**\n * Every fresh instance attempt creates a new wasm-bindgen glue module\n * record. The import-attempt nonce is deliberately independent of the trap\n * generation: transient import/initSync failures need a new module record\n * without consuming the bounded trap-recovery budget.\n */\n async function freshInstance(generation: number): Promise<Instance> {\n freshInstanceStarts += 1;\n glueImportAttempts += 1;\n const glueSpecifier = new URL(glueUrl.href);\n glueSpecifier.searchParams.set(\"zfbMdWasmGen\", String(generation));\n glueSpecifier.searchParams.set(\"zfbMdWasmAttempt\", String(glueImportAttempts));\n const [module, glue] = await Promise.all([\n getCompiledModule(),\n // Deferring the injected function also converts a synchronous test-seam\n // throw into the rejection handled by the retryable instance cache.\n Promise.resolve().then(() => importGlue(glueSpecifier.href)),\n ]);\n glue.initSync({ module });\n return { generation, glue };\n }\n\n let instancePromise: Promise<Instance> | undefined;\n\n function startInstance(generation: number): Promise<Instance> {\n const attempt = freshInstance(generation);\n instancePromise = attempt;\n void attempt.catch(() => {\n // Trap recovery can replace the installed instance promise. Never let a\n // stale initialization rejection clear that newer attempt.\n if (instancePromise === attempt) {\n instancePromise = undefined;\n }\n });\n return attempt;\n }\n\n function getInstance(): Promise<Instance> {\n if (terminalTrapRecoveryError) {\n return Promise.reject(terminalTrapRecoveryError);\n }\n if (!instancePromise) {\n return startInstance(currentGeneration);\n }\n return instancePromise;\n }\n\n function isTrap(err: unknown): boolean {\n return typeof WebAssembly !== \"undefined\" && err instanceof WebAssembly.RuntimeError;\n }\n\n async function recoverAfterTrap(observedGeneration: number, cause: unknown): Promise<void> {\n if (terminalTrapRecoveryError) {\n throw terminalTrapRecoveryError;\n }\n\n // CAS-style single-flight: reporters for an already-replaced generation\n // await its replacement instead of creating another glue module record.\n if (observedGeneration !== currentGeneration) {\n await getInstance();\n return;\n }\n\n if (trapRecoveriesStarted >= MAX_TRAP_RECOVERIES) {\n terminalTrapRecoveryError = new ZfbMdWasmTrapRecoveryLimitError(MAX_TRAP_RECOVERIES, cause);\n instancePromise = undefined;\n throw terminalTrapRecoveryError;\n }\n\n trapRecoveriesStarted += 1;\n currentGeneration += 1;\n await startInstance(currentGeneration);\n }\n\n async function callWasm<T>(fn: (instance: Instance) => T): Promise<T> {\n const instance = await getInstance();\n try {\n return fn(instance);\n } catch (err) {\n if (!isTrap(err)) {\n throw err;\n }\n await recoverAfterTrap(instance.generation, err);\n throw new ZfbMdWasmTrapError(err);\n }\n }\n\n async function init(): Promise<void> {\n await getInstance();\n }\n\n // Public entry surfaces make missing calls unreachable. This guard keeps\n // structural glue mismatches artifact-neutral and actionable.\n function requireCapability<T>(fn: T | undefined, name: string): T {\n if (!fn) {\n throw new Error(\n `zfb-md-wasm: ${name}() is not available in this wasm artifact. ` +\n `Import an entry whose artifact provides that capability.`,\n );\n }\n return fn;\n }\n\n async function compile(source: string, options: ZfbMdWasmOptions = {}): Promise<CompileResult> {\n const optionsJson = JSON.stringify(options);\n const json = await callWasm(({ glue }) =>\n requireCapability(glue.compile, \"compile\").call(glue, source, optionsJson),\n );\n return JSON.parse(json) as CompileResult;\n }\n\n async function renderHtml(\n source: string,\n options: ZfbMdWasmOptions = {},\n ): Promise<RenderHtmlResult> {\n const optionsJson = JSON.stringify(options);\n const json = await callWasm(({ glue }) =>\n requireCapability(glue.renderHtml, \"renderHtml\").call(glue, source, optionsJson),\n );\n return JSON.parse(json) as RenderHtmlResult;\n }\n\n /**\n * Parse markdown/MDX into a raw mdast tree (zfb#1857, epic zfb#1854).\n * The `parseToAst + JSON.parse` round trip here IS the product cost the\n * epic's benchmark measures against remark-parse. See `types.ts`'s\n * `ParseToAstResult`/`MdastNode` docs for the result shape and the\n * UTF-16 position contract.\n */\n async function parseToAst(\n source: string,\n options: ParseToAstOptions = {},\n ): Promise<ParseToAstResult> {\n const optionsJson = JSON.stringify(options);\n const json = await callWasm(({ glue }) =>\n requireCapability(glue.parseToAst, \"parseToAst\").call(glue, source, optionsJson),\n );\n return JSON.parse(json) as ParseToAstResult;\n }\n\n async function highlightCode(\n code: string,\n options: HighlightCodeOptions,\n ): Promise<HighlightCodeResult> {\n const optionsJson = JSON.stringify(options);\n const json = await callWasm(({ glue }) =>\n requireCapability(glue.highlightCode, \"highlightCode\").call(glue, code, optionsJson),\n );\n return JSON.parse(json) as HighlightCodeResult;\n }\n\n async function version(): Promise<string> {\n return callWasm(({ glue }) => glue.version());\n }\n\n /** @internal Test-only hook that forces the current instance to trap. */\n async function __forceTrapForTests(): Promise<void> {\n await callWasm(({ glue }) => glue.__forceTrapForTests());\n }\n\n /** @internal Test-only observability for the bounded recovery contract. */\n function __getTrapRecoveryStateForTests(): {\n compiledModuleLoads: number;\n currentGeneration: number;\n freshInstanceStarts: number;\n glueImportAttempts: number;\n maxTrapRecoveries: number;\n trapRecoveriesStarted: number;\n terminal: boolean;\n } {\n return {\n compiledModuleLoads,\n currentGeneration,\n freshInstanceStarts,\n glueImportAttempts,\n maxTrapRecoveries: MAX_TRAP_RECOVERIES,\n trapRecoveriesStarted,\n terminal: !!terminalTrapRecoveryError,\n };\n }\n\n return {\n init,\n compile,\n renderHtml,\n parseToAst,\n highlightCode,\n version,\n __forceTrapForTests,\n __getTrapRecoveryStateForTests,\n };\n}\n"]}
|
package/dist/types.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ export interface GfmOptions {
|
|
|
6
6
|
taskListItem?: boolean;
|
|
7
7
|
footnoteDefinition?: boolean;
|
|
8
8
|
}
|
|
9
|
-
/** Base syntax selected by `parseToAst`. */
|
|
9
|
+
/** Base syntax selected by `parseToAst` and `renderHtml`. */
|
|
10
10
|
export type ParseDialect = "markdown" | "mdx";
|
|
11
11
|
/** How `parseToAst` handles recognized YAML frontmatter. */
|
|
12
12
|
export type FrontmatterPolicy = "extract" | "node" | "none";
|
|
@@ -109,6 +109,11 @@ export interface ZfbMdWasmOptions {
|
|
|
109
109
|
* `<anonymous>.md` for `renderHtml`.
|
|
110
110
|
*/
|
|
111
111
|
filename?: string;
|
|
112
|
+
/**
|
|
113
|
+
* Consumed only by `renderHtml`; `compile` accepts and ignores it.
|
|
114
|
+
* Without an override, `.md` selects CommonMark and `.mdx` selects MDX.
|
|
115
|
+
*/
|
|
116
|
+
dialect?: ParseDialect;
|
|
112
117
|
/** Consumed only by `compile`; `renderHtml` accepts and ignores it. */
|
|
113
118
|
jsxRuntime?: JsxRuntime;
|
|
114
119
|
/** Consumed only by `compile`; `renderHtml` accepts and ignores it. */
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,2EAA2E;AAC3E,qEAAqE;AACrE,gCAAgC","sourcesContent":["// Mirrors the JSON contracts of the `zfb-md-wasm` Rust crate (zfb#1576)\n// literally -- see that crate's `src/lib.rs` rustdoc for the authoritative\n// shape. Keep this file in lock-step with the crate when the crate's\n// options/result shapes change.\n\n/** `zfb_content::facade::PipelineOptions`'s `gfm` sub-object, verbatim. */\nexport interface GfmOptions {\n strikethrough?: boolean;\n table?: boolean;\n autolinkLiteral?: boolean;\n taskListItem?: boolean;\n footnoteDefinition?: boolean;\n}\n\n/** Base syntax selected by `parseToAst`. */\nexport type ParseDialect = \"markdown\" | \"mdx\";\n\n/** How `parseToAst` handles recognized YAML frontmatter. */\nexport type FrontmatterPolicy = \"extract\" | \"node\" | \"none\";\n\n/** Raw-parser pipeline options. Visitor/serializer options are not accepted. */\nexport interface ParsePipelineOptions {\n gfm?: GfmOptions;\n}\n\n/**\n * The distinct, closed options document consumed by `parseToAst`.\n *\n * `filename` must end in lowercase `.md` or `.mdx`. With no explicit\n * `dialect`, `.md` selects CommonMark and `.mdx` selects MDX; omitting the\n * filename uses `<anonymous>.mdx`, hence MDX. An explicit dialect overrides\n * either valid extension but does not waive that extension gate.\n */\nexport interface ParseToAstOptions {\n filename?: string;\n dialect?: ParseDialect;\n /** Parse generic remark-directive syntax. Default: `false`. */\n directives?: boolean;\n /**\n * YAML handling policy. Default: `\"extract\"`.\n *\n * - `extract`: parse the stripped body, return YAML as JSON, no YAML node;\n * - `node`: parse the full logical source, return JSON plus canonical YAML node;\n * - `none`: parse every logical-source byte as Markdown/MDX and always return null.\n *\n * Malformed/unterminated YAML fails `extract`/`node` with one\n * `frontmatter` diagnostic; `none` never produces a YAML diagnostic.\n */\n frontmatter?: FrontmatterPolicy;\n pipeline?: ParsePipelineOptions;\n}\n\n/**\n * `MarkdownFeaturesConfig` (see `crates/zfb-md-ast/src/features_config.rs`).\n * Left as an open record here -- the wasm boundary passes it through to the\n * Rust `deny_unknown_fields` deserializer verbatim, which is the\n * authoritative validator for its keys.\n */\nexport type MarkdownFeaturesConfig = Record<string, unknown>;\n\n/**\n * `zfb_content::facade::CodeHighlightOptions`'s `mode` field -- mirrors the\n * `\"inline\"` / `\"class\"` string-literal union in native `zfb.config.ts`\n * (`CodeHighlightConfig.mode`).\n */\nexport type CodeHighlightMode = \"inline\" | \"class\";\n\n/**\n * `zfb_content::facade::CodeHighlightOptions`, verbatim (Highlight Tokens\n * epic zfb#1528, wasm routing sub zfb#1852).\n */\nexport interface CodeHighlightOptions {\n /** Output mode for fenced-code highlighting. Defaults to `\"inline\"` --\n * reproduces the pre-existing per-token inline-color behaviour\n * byte-for-byte. */\n mode?: CodeHighlightMode;\n /** Class-name prefix for class-mode role classes (e.g. the default\n * `\"hi-\"` yields `hi-kw`, `hi-str`, ...). Only meaningful when `mode` is\n * `\"class\"`. */\n classPrefix?: string;\n /** Per-role class overrides for class mode. Absent or `null` uses\n * `{classPrefix}{role}` for every role. Only meaningful when `mode` is\n * `\"class\"`. */\n roleClasses?: Partial<Record<HighlightRole, string>> | null;\n}\n\n/** `zfb_content::facade::PipelineOptions`, verbatim. */\nexport interface PipelineOptions {\n /**\n * A syntect theme name. Absent, or explicit `null`, keeps the built-in\n * default theme (`base16-ocean.dark`) -- fenced code is ALWAYS\n * highlighted through this field; there is no \"no syntax highlighting\"\n * value (this comment previously claimed `null` meant no highlighting,\n * which was never true of the Rust deserializer -- corrected in\n * zfb#1852). Mutually exclusive with `codeHighlight.mode: \"class\"`.\n */\n theme?: string | null;\n gfm?: GfmOptions;\n cjkFriendly?: boolean;\n hardBreaks?: boolean;\n /**\n * Output mode + class-mode knobs for fenced-code highlighting\n * (Highlight Tokens epic zfb#1528). Absent, `null`, or\n * `{ mode: \"inline\" }` reproduce the pre-existing inline-color\n * behaviour byte-for-byte. `{ mode: \"class\" }` is mutually exclusive\n * with a top-level `theme`.\n */\n codeHighlight?: CodeHighlightOptions | null;\n features?: MarkdownFeaturesConfig;\n}\n\n/** `jsxRuntime` option values. Consumed only by `compile`. */\nexport type JsxRuntime = \"preact\" | \"react\";\n\n/**\n * The options JSON document shared by `compile` and `renderHtml`. Every\n * field is optional; `{}` selects all defaults. Unknown fields are\n * rejected by the Rust side at both nesting levels (`deny_unknown_fields`).\n */\nexport interface ZfbMdWasmOptions {\n /**\n * Must end in `.md` or `.mdx`. Drives frontmatter dispatch and\n * diagnostics display. Defaults to `<anonymous>.mdx` for `compile` and\n * `<anonymous>.md` for `renderHtml`.\n */\n filename?: string;\n /** Consumed only by `compile`; `renderHtml` accepts and ignores it. */\n jsxRuntime?: JsxRuntime;\n /** Consumed only by `compile`; `renderHtml` accepts and ignores it. */\n development?: boolean;\n pipeline?: PipelineOptions;\n}\n\n/** `source` values a `Diagnostic` can carry. */\nexport type DiagnosticSource = \"options\" | \"frontmatter\" | \"markdown\" | \"compile\";\n\n/**\n * One diagnostic entry. `line`/`column` are the sole supported diagnostic\n * location and are 1-based. For `\"markdown\"` / `\"frontmatter\"` they point\n * into the *original source* (frontmatter lines included) in JavaScript\n * UTF-16 code units. For `\"options\"` they point into the *options JSON\n * document*. They are `null` when the underlying error carries no location.\n */\nexport interface Diagnostic {\n severity: \"error\";\n source: DiagnosticSource;\n /**\n * Opaque display text from this package or an upstream dependency. Do not\n * parse or rewrite it: embedded coordinates, when present, are not public\n * API and may use the dependency's own coordinate space. Use structured\n * `line` and `column` for the supported location instead.\n */\n message: string;\n line: number | null;\n column: number | null;\n}\n\n/** Result document of `compile`. */\nexport interface CompileResult {\n /** ES-module JS source on success, `null` on failure. */\n code: string | null;\n /** Parsed YAML frontmatter as JSON, `null` when absent or unextractable. */\n frontmatter: unknown;\n diagnostics: Diagnostic[];\n}\n\n/**\n * One point in the original source (unist convention). `line` is 1-based\n * and unit-agnostic. `column` is 1-based and `offset` is 0-based, BOTH in\n * **UTF-16 code units** (zfb#1856, epic zfb#1854) — the indexing\n * `String.prototype.slice`, `mdast-util-to-hast`, and consumer mdast\n * plugins already use, and remark/unist's own convention. This is NOT\n * Unicode scalar values/code points: a scalar value outside the Basic\n * Multilingual Plane (most emoji) is 2 UTF-16 code units but 1 code point,\n * so a surrogate-pair character advances `offset`/`column` by 2, not 1.\n * Pure-ASCII sources have byte offsets == UTF-16 offsets, so this only\n * matters once the source has non-ASCII content.\n */\nexport interface AstPoint {\n line: number;\n column: number;\n offset: number;\n}\n\n/** Start/end span of two {@link AstPoint}s (unist convention). */\nexport interface AstPosition {\n start: AstPoint;\n end: AstPoint;\n}\n\n/** Optional unist data carried losslessly by known raw tree nodes. */\nexport interface RawMdastData {\n data?: Record<string, unknown>;\n}\n\n/**\n * Internal markdown-rs re-parse bookkeeping carried by MDX expression/ESM\n * nodes: `[indexInValue, absoluteSourceOffset]`. Internal, unstable, and\n * (unlike {@link AstPosition}) **UTF-8 BYTE**-based -- markdown-rs uses it\n * to re-resolve sub-positions inside an expression's own re-parse pass.\n * Never slice a string with it; it does not share `position`'s UTF-16 unit\n * contract.\n */\nexport type MarkdownRsStop = readonly [indexInValue: number, absoluteSourceOffsetBytes: number];\n\n/** GFM alignment for a table column. `null` means no explicit alignment. */\nexport type TableAlign = \"left\" | \"right\" | \"center\" | null;\n\n/** Explicitness of a `link`/`image` reference (GFM footnotes reuse it too). */\nexport type ReferenceKind = \"shortcut\" | \"collapsed\" | \"full\";\n\n// ── mdast core node set ─────────────────────────────────────────────────────\n// Mirrors `markdown::mdast::Node`'s variants (markdown-rs, `serde(tag =\n// \"type\", rename_all = \"camelCase\")`) -- see that crate's `src/mdast.rs` for\n// the authoritative field shapes. Every variant here always carries\n// `position` (requirement 2 of zfb#1828); the one documented exception,\n// `mdxJsxAttribute`/its value/expression-attribute siblings, is intentionally\n// NOT part of the `MdastNode` union below -- they are attribute records\n// embedded in `MdxJsxFlowElement`/`MdxJsxTextElement.attributes`, not\n// standalone tree nodes.\n\nexport interface Root extends RawMdastData {\n type: \"root\";\n position: AstPosition;\n children: MdastNode[];\n}\nexport interface Paragraph extends RawMdastData {\n type: \"paragraph\";\n position: AstPosition;\n children: MdastNode[];\n}\nexport interface Heading extends RawMdastData {\n type: \"heading\";\n position: AstPosition;\n depth: 1 | 2 | 3 | 4 | 5 | 6;\n children: MdastNode[];\n}\nexport interface ThematicBreak extends RawMdastData {\n type: \"thematicBreak\";\n position: AstPosition;\n}\nexport interface Blockquote extends RawMdastData {\n type: \"blockquote\";\n position: AstPosition;\n children: MdastNode[];\n}\nexport interface List extends RawMdastData {\n type: \"list\";\n position: AstPosition;\n ordered: boolean;\n /**\n * Absent for an unordered list. Rust serializes `None` here by OMITTING\n * the key (`#[serde(skip_serializing_if = \"Option::is_none\")]`), not as\n * JSON `null` -- hence `?:`, not `| null`.\n */\n start?: number;\n spread: boolean;\n children: MdastNode[];\n}\nexport interface ListItem extends RawMdastData {\n type: \"listItem\";\n position: AstPosition;\n spread: boolean;\n /** GFM task-list state; absent (not `null` -- see {@link List.start}) for a plain (non-task) item. */\n checked?: boolean;\n children: MdastNode[];\n}\nexport interface Html extends RawMdastData {\n type: \"html\";\n position: AstPosition;\n value: string;\n}\nexport interface Code extends RawMdastData {\n type: \"code\";\n position: AstPosition;\n /** Absent when the fence has no language (see {@link List.start}). */\n lang?: string;\n /** Absent when the fence has no meta string (see {@link List.start}). */\n meta?: string;\n value: string;\n}\nexport interface Definition extends RawMdastData {\n type: \"definition\";\n position: AstPosition;\n url: string;\n /** Absent when there is no title (see {@link List.start}). */\n title?: string;\n identifier: string;\n /** Absent when there is no label (see {@link List.start}). */\n label?: string;\n}\nexport interface Text extends RawMdastData {\n type: \"text\";\n position: AstPosition;\n value: string;\n}\n\n/** Shared raw shape of the three generic remark-directive node kinds. */\nexport interface DirectiveNodeBase extends RawMdastData {\n position: AstPosition;\n name: string;\n /** Always present; boolean attributes are represented by an empty string. */\n attributes: Record<string, string>;\n children: MdastNode[];\n}\nexport interface ContainerDirective extends DirectiveNodeBase {\n type: \"containerDirective\";\n}\nexport interface LeafDirective extends DirectiveNodeBase {\n type: \"leafDirective\";\n}\nexport interface TextDirective extends DirectiveNodeBase {\n type: \"textDirective\";\n}\nexport interface Emphasis extends RawMdastData {\n type: \"emphasis\";\n position: AstPosition;\n children: MdastNode[];\n}\nexport interface Strong extends RawMdastData {\n type: \"strong\";\n position: AstPosition;\n children: MdastNode[];\n}\nexport interface InlineCode extends RawMdastData {\n type: \"inlineCode\";\n position: AstPosition;\n value: string;\n}\nexport interface Break extends RawMdastData {\n type: \"break\";\n position: AstPosition;\n}\nexport interface Link extends RawMdastData {\n type: \"link\";\n position: AstPosition;\n url: string;\n /** Absent when there is no title (see {@link List.start}). */\n title?: string;\n children: MdastNode[];\n}\nexport interface Image extends RawMdastData {\n type: \"image\";\n position: AstPosition;\n alt: string;\n url: string;\n /** Absent when there is no title (see {@link List.start}). */\n title?: string;\n}\nexport interface LinkReference extends RawMdastData {\n type: \"linkReference\";\n position: AstPosition;\n referenceType: ReferenceKind;\n identifier: string;\n /** Absent when there is no label (see {@link List.start}). */\n label?: string;\n children: MdastNode[];\n}\nexport interface ImageReference extends RawMdastData {\n type: \"imageReference\";\n position: AstPosition;\n alt: string;\n referenceType: ReferenceKind;\n identifier: string;\n /** Absent when there is no label (see {@link List.start}). */\n label?: string;\n}\n/** GFM footnote definition (`[^id]: ...`). */\nexport interface FootnoteDefinition extends RawMdastData {\n type: \"footnoteDefinition\";\n position: AstPosition;\n identifier: string;\n /** Absent when there is no label (see {@link List.start}). */\n label?: string;\n children: MdastNode[];\n}\n/** GFM footnote reference (`[^id]`). */\nexport interface FootnoteReference extends RawMdastData {\n type: \"footnoteReference\";\n position: AstPosition;\n identifier: string;\n /** Absent when there is no label (see {@link List.start}). */\n label?: string;\n}\n/** GFM table. */\nexport interface Table extends RawMdastData {\n type: \"table\";\n position: AstPosition;\n align: TableAlign[];\n children: MdastNode[];\n}\nexport interface TableRow extends RawMdastData {\n type: \"tableRow\";\n position: AstPosition;\n children: MdastNode[];\n}\nexport interface TableCell extends RawMdastData {\n type: \"tableCell\";\n position: AstPosition;\n children: MdastNode[];\n}\n/** GFM strikethrough (`~~text~~`). */\nexport interface Delete extends RawMdastData {\n type: \"delete\";\n position: AstPosition;\n children: MdastNode[];\n}\n/**\n * Canonical markdown-rs YAML frontmatter node emitted by\n * `frontmatter: \"node\"`. Its value excludes fences and line endings while\n * its position covers the complete fenced block.\n */\nexport interface Yaml extends RawMdastData {\n type: \"yaml\";\n position: AstPosition;\n value: string;\n}\n\n// ── MDX node set ─────────────────────────────────────────────────────────\n\n/** MDX flow expression (`{...}` on its own line). */\nexport interface MdxFlowExpression extends RawMdastData {\n type: \"mdxFlowExpression\";\n position: AstPosition;\n value: string;\n /** Internal/unstable/byte-based -- see {@link MarkdownRsStop}. */\n _markdownRsStops: MarkdownRsStop[];\n}\n/** MDX text expression (`{...}` inline in phrasing content). */\nexport interface MdxTextExpression extends RawMdastData {\n type: \"mdxTextExpression\";\n position: AstPosition;\n value: string;\n _markdownRsStops: MarkdownRsStop[];\n}\n/** MDX JSX element as flow (block-level) content. */\nexport interface MdxJsxFlowElement extends RawMdastData {\n type: \"mdxJsxFlowElement\";\n position: AstPosition;\n /** Absent for a JSX fragment (`<>...</>`) -- see {@link List.start}. */\n name?: string;\n attributes: MdxJsxAttributeContent[];\n children: MdastNode[];\n}\n/** MDX JSX element as phrasing (inline) content. */\nexport interface MdxJsxTextElement extends RawMdastData {\n type: \"mdxJsxTextElement\";\n position: AstPosition;\n /** Absent for a JSX fragment (`<>...</>`) -- see {@link List.start}. */\n name?: string;\n attributes: MdxJsxAttributeContent[];\n children: MdastNode[];\n}\n\n/**\n * A JSX attribute's value: a plain string literal, or a `{...}` expression\n * value. Divergence: expression attribute VALUES carry no `position`\n * (mirrors the `mdxJsxAttribute`/`mdxJsxExpressionAttribute` divergence\n * below -- markdown-rs does not model attribute positions anywhere).\n */\nexport interface MdxJsxAttributeValueExpression extends RawMdastData {\n type: \"mdxJsxAttributeValueExpression\";\n value: string;\n _markdownRsStops: MarkdownRsStop[];\n}\n/**\n * One `name=\"value\"` / `name={expr}` / bare `name` JSX attribute.\n * Divergence: carries no `position` -- markdown-rs does not model attribute\n * positions (zfb#1828 requirement 2's one documented exception).\n */\nexport interface MdxJsxAttribute extends RawMdastData {\n type: \"mdxJsxAttribute\";\n name: string;\n /** Absent for a bare boolean attribute (`<a b />`) -- see {@link List.start}. */\n value?: string | MdxJsxAttributeValueExpression;\n}\n/**\n * A JSX spread attribute (`{...expr}`). Divergence: carries no `position`,\n * same reason as {@link MdxJsxAttribute}.\n */\nexport interface MdxJsxExpressionAttribute extends RawMdastData {\n type: \"mdxJsxExpressionAttribute\";\n value: string;\n _markdownRsStops: MarkdownRsStop[];\n}\n/** One entry of `MdxJsxFlowElement`/`MdxJsxTextElement.attributes`. */\nexport type MdxJsxAttributeContent = MdxJsxAttribute | MdxJsxExpressionAttribute;\n\n/**\n * Catch-all for any mdast node type not enumerated above -- keeps\n * unrecognized/future node types TYPED (requirement 3 of zfb#1828: an opaque\n * `unknown` would silently drop this contract) rather than falling back to\n * `unknown`. `type` is deliberately the general `string` here (not a\n * literal), so TypeScript's discriminated-union narrowing on `type` keeps\n * this member alongside any single literal match; disambiguate with an\n * explicit assertion once a runtime `type` check has confirmed which shape\n * you actually have (see `test/consumer-compatibility-parse-to-ast.ts` for\n * the pattern).\n */\nexport interface UnknownMdastNode {\n type: string;\n position: AstPosition;\n [key: string]: unknown;\n}\n\n/**\n * Any node markdown-rs's raw mdast serialization can produce through\n * `parseToAst` -- the documented mdast core set, the documented MDX set, or\n * {@link UnknownMdastNode} for anything else. Attribute-record shapes\n * ({@link MdxJsxAttributeContent} and its members) are intentionally NOT\n * part of this union -- see their own docs.\n */\nexport type MdastNode =\n | Root\n | Paragraph\n | Heading\n | ThematicBreak\n | Blockquote\n | List\n | ListItem\n | Html\n | Code\n | Definition\n | Text\n | Emphasis\n | Strong\n | InlineCode\n | Break\n | Link\n | Image\n | LinkReference\n | ImageReference\n | FootnoteDefinition\n | FootnoteReference\n | Table\n | TableRow\n | TableCell\n | Delete\n | Yaml\n | MdxFlowExpression\n | MdxTextExpression\n | MdxJsxFlowElement\n | MdxJsxTextElement\n | ContainerDirective\n | LeafDirective\n | TextDirective\n | UnknownMdastNode;\n\n/** The tree root `parseToAst` returns -- always a `root` node when present. */\nexport type MdastRoot = Root;\n\n/**\n * Result document of `parseToAst` (zfb#1857, epic zfb#1854). `ast` is the\n * raw markdown-rs mdast converted through its serde shape into an open\n * carrier (unist-shaped `type`, fields, and `position`) and PRE-zfb-visitors.\n * Source selection follows {@link FrontmatterPolicy}. When `directives` is\n * true the carrier can also contain the three generic directive kinds;\n * otherwise directive-looking text survives exactly as markdown-rs parsed\n * it. `position.offset` and\n * `position.column` are UTF-16 code units (see {@link AstPoint}).\n *\n * Markdown mode preserves CommonMark HTML/comments, angle autolinks,\n * indented code, and literal braces. MDX mode enables JSX/expressions and\n * keeps markdown-rs's conflicting CommonMark constructs disabled. Both\n * modes apply the same five independent {@link GfmOptions} switches.\n *\n * Documented divergences from remark-parse / remark-mdx in MDX mode:\n * - `mdxJsxAttribute` (and its value/expression-attribute siblings) carry no\n * `position` -- markdown-rs does not model attribute positions.\n * - Top-level `import`/`export` degrade to paragraphs (no `mdxjsEsm` nodes),\n * and MDX expressions carry no estree data -- the wasm boundary cannot\n * host a JS ESM/acorn parser. Consumers needing remark-mdx-equivalent\n * ESM/estree keep remark for those documents.\n * - `_markdownRsStops` is internal, unstable, and byte-based (not UTF-16) --\n * see {@link MarkdownRsStop}.\n */\nexport interface ParseToAstResult {\n /** Serialized raw mdast root on success, `null` on failure. */\n ast: MdastRoot | null;\n /** Parsed YAML frontmatter as JSON, `null` when absent or unextractable. */\n frontmatter: unknown;\n diagnostics: Diagnostic[];\n}\n\n/** Result document of `renderHtml`. */\nexport interface RenderHtmlResult {\n /** HTML fragment on success, `null` on failure. */\n html: string | null;\n frontmatter: unknown;\n diagnostics: Diagnostic[];\n}\n\n/**\n * The fixed 18-role semantic taxonomy emitted by `highlightCode`. This union\n * is mechanically checked against Rust's canonical `HiRole::FULL_NAMES` by\n * `zfb`'s role-drift guard; do not add a second unguarded role list.\n */\nexport type HighlightRole =\n | \"escape\"\n | \"operator\"\n | \"comment\"\n | \"string\"\n | \"number\"\n | \"constant\"\n | \"keyword\"\n | \"function\"\n | \"type\"\n | \"namespace\"\n | \"property\"\n | \"variable\"\n | \"tag\"\n | \"attribute\"\n | \"punctuation\"\n | \"inserted\"\n | \"deleted\"\n | \"heading\";\n\n/** Options for direct arbitrary-code semantic class highlighting. */\nexport interface HighlightCodeOptions {\n /** Required syntax token, for example `\"html\"`, `\"css\"`, or `\"javascript\"`. */\n language: string;\n /** The only supported direct output mode. Defaults to `\"class\"`. */\n mode?: \"class\";\n /** Semantic role class prefix. Defaults to `\"hi-\"`. */\n classPrefix?: string;\n /** Full-name role overrides, for example `{ keyword: \"text-violet-600\" }`. */\n roleClasses?: Partial<Record<HighlightRole, string>>;\n}\n\n/** Sources used by direct `highlightCode` diagnostics. */\nexport type HighlightDiagnosticSource = \"options\" | \"highlight\" | \"internal\";\n\n/** A structured direct-highlighting diagnostic. */\nexport interface HighlightDiagnostic {\n severity: \"error\" | \"warning\";\n source: HighlightDiagnosticSource;\n message: string;\n /** Always `null` for semantic/highlight diagnostics; JSON option parse locations are 1-based. */\n line: number | null;\n /** Always `null` for semantic/highlight diagnostics; JSON option parse locations are 1-based. */\n column: number | null;\n}\n\n/** Result document returned by {@link highlightCode}. */\nexport interface HighlightCodeResult {\n /** Complete semantic `<pre><code>` wrapper, or `null` for invalid options/internal errors. */\n html: string | null;\n diagnostics: HighlightDiagnostic[];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,2EAA2E;AAC3E,qEAAqE;AACrE,gCAAgC","sourcesContent":["// Mirrors the JSON contracts of the `zfb-md-wasm` Rust crate (zfb#1576)\n// literally -- see that crate's `src/lib.rs` rustdoc for the authoritative\n// shape. Keep this file in lock-step with the crate when the crate's\n// options/result shapes change.\n\n/** `zfb_content::facade::PipelineOptions`'s `gfm` sub-object, verbatim. */\nexport interface GfmOptions {\n strikethrough?: boolean;\n table?: boolean;\n autolinkLiteral?: boolean;\n taskListItem?: boolean;\n footnoteDefinition?: boolean;\n}\n\n/** Base syntax selected by `parseToAst` and `renderHtml`. */\nexport type ParseDialect = \"markdown\" | \"mdx\";\n\n/** How `parseToAst` handles recognized YAML frontmatter. */\nexport type FrontmatterPolicy = \"extract\" | \"node\" | \"none\";\n\n/** Raw-parser pipeline options. Visitor/serializer options are not accepted. */\nexport interface ParsePipelineOptions {\n gfm?: GfmOptions;\n}\n\n/**\n * The distinct, closed options document consumed by `parseToAst`.\n *\n * `filename` must end in lowercase `.md` or `.mdx`. With no explicit\n * `dialect`, `.md` selects CommonMark and `.mdx` selects MDX; omitting the\n * filename uses `<anonymous>.mdx`, hence MDX. An explicit dialect overrides\n * either valid extension but does not waive that extension gate.\n */\nexport interface ParseToAstOptions {\n filename?: string;\n dialect?: ParseDialect;\n /** Parse generic remark-directive syntax. Default: `false`. */\n directives?: boolean;\n /**\n * YAML handling policy. Default: `\"extract\"`.\n *\n * - `extract`: parse the stripped body, return YAML as JSON, no YAML node;\n * - `node`: parse the full logical source, return JSON plus canonical YAML node;\n * - `none`: parse every logical-source byte as Markdown/MDX and always return null.\n *\n * Malformed/unterminated YAML fails `extract`/`node` with one\n * `frontmatter` diagnostic; `none` never produces a YAML diagnostic.\n */\n frontmatter?: FrontmatterPolicy;\n pipeline?: ParsePipelineOptions;\n}\n\n/**\n * `MarkdownFeaturesConfig` (see `crates/zfb-md-ast/src/features_config.rs`).\n * Left as an open record here -- the wasm boundary passes it through to the\n * Rust `deny_unknown_fields` deserializer verbatim, which is the\n * authoritative validator for its keys.\n */\nexport type MarkdownFeaturesConfig = Record<string, unknown>;\n\n/**\n * `zfb_content::facade::CodeHighlightOptions`'s `mode` field -- mirrors the\n * `\"inline\"` / `\"class\"` string-literal union in native `zfb.config.ts`\n * (`CodeHighlightConfig.mode`).\n */\nexport type CodeHighlightMode = \"inline\" | \"class\";\n\n/**\n * `zfb_content::facade::CodeHighlightOptions`, verbatim (Highlight Tokens\n * epic zfb#1528, wasm routing sub zfb#1852).\n */\nexport interface CodeHighlightOptions {\n /** Output mode for fenced-code highlighting. Defaults to `\"inline\"` --\n * reproduces the pre-existing per-token inline-color behaviour\n * byte-for-byte. */\n mode?: CodeHighlightMode;\n /** Class-name prefix for class-mode role classes (e.g. the default\n * `\"hi-\"` yields `hi-kw`, `hi-str`, ...). Only meaningful when `mode` is\n * `\"class\"`. */\n classPrefix?: string;\n /** Per-role class overrides for class mode. Absent or `null` uses\n * `{classPrefix}{role}` for every role. Only meaningful when `mode` is\n * `\"class\"`. */\n roleClasses?: Partial<Record<HighlightRole, string>> | null;\n}\n\n/** `zfb_content::facade::PipelineOptions`, verbatim. */\nexport interface PipelineOptions {\n /**\n * A syntect theme name. Absent, or explicit `null`, keeps the built-in\n * default theme (`base16-ocean.dark`) -- fenced code is ALWAYS\n * highlighted through this field; there is no \"no syntax highlighting\"\n * value (this comment previously claimed `null` meant no highlighting,\n * which was never true of the Rust deserializer -- corrected in\n * zfb#1852). Mutually exclusive with `codeHighlight.mode: \"class\"`.\n */\n theme?: string | null;\n gfm?: GfmOptions;\n cjkFriendly?: boolean;\n hardBreaks?: boolean;\n /**\n * Output mode + class-mode knobs for fenced-code highlighting\n * (Highlight Tokens epic zfb#1528). Absent, `null`, or\n * `{ mode: \"inline\" }` reproduce the pre-existing inline-color\n * behaviour byte-for-byte. `{ mode: \"class\" }` is mutually exclusive\n * with a top-level `theme`.\n */\n codeHighlight?: CodeHighlightOptions | null;\n features?: MarkdownFeaturesConfig;\n}\n\n/** `jsxRuntime` option values. Consumed only by `compile`. */\nexport type JsxRuntime = \"preact\" | \"react\";\n\n/**\n * The options JSON document shared by `compile` and `renderHtml`. Every\n * field is optional; `{}` selects all defaults. Unknown fields are\n * rejected by the Rust side at both nesting levels (`deny_unknown_fields`).\n */\nexport interface ZfbMdWasmOptions {\n /**\n * Must end in `.md` or `.mdx`. Drives frontmatter dispatch and\n * diagnostics display. Defaults to `<anonymous>.mdx` for `compile` and\n * `<anonymous>.md` for `renderHtml`.\n */\n filename?: string;\n /**\n * Consumed only by `renderHtml`; `compile` accepts and ignores it.\n * Without an override, `.md` selects CommonMark and `.mdx` selects MDX.\n */\n dialect?: ParseDialect;\n /** Consumed only by `compile`; `renderHtml` accepts and ignores it. */\n jsxRuntime?: JsxRuntime;\n /** Consumed only by `compile`; `renderHtml` accepts and ignores it. */\n development?: boolean;\n pipeline?: PipelineOptions;\n}\n\n/** `source` values a `Diagnostic` can carry. */\nexport type DiagnosticSource = \"options\" | \"frontmatter\" | \"markdown\" | \"compile\";\n\n/**\n * One diagnostic entry. `line`/`column` are the sole supported diagnostic\n * location and are 1-based. For `\"markdown\"` / `\"frontmatter\"` they point\n * into the *original source* (frontmatter lines included) in JavaScript\n * UTF-16 code units. For `\"options\"` they point into the *options JSON\n * document*. They are `null` when the underlying error carries no location.\n */\nexport interface Diagnostic {\n severity: \"error\";\n source: DiagnosticSource;\n /**\n * Opaque display text from this package or an upstream dependency. Do not\n * parse or rewrite it: embedded coordinates, when present, are not public\n * API and may use the dependency's own coordinate space. Use structured\n * `line` and `column` for the supported location instead.\n */\n message: string;\n line: number | null;\n column: number | null;\n}\n\n/** Result document of `compile`. */\nexport interface CompileResult {\n /** ES-module JS source on success, `null` on failure. */\n code: string | null;\n /** Parsed YAML frontmatter as JSON, `null` when absent or unextractable. */\n frontmatter: unknown;\n diagnostics: Diagnostic[];\n}\n\n/**\n * One point in the original source (unist convention). `line` is 1-based\n * and unit-agnostic. `column` is 1-based and `offset` is 0-based, BOTH in\n * **UTF-16 code units** (zfb#1856, epic zfb#1854) — the indexing\n * `String.prototype.slice`, `mdast-util-to-hast`, and consumer mdast\n * plugins already use, and remark/unist's own convention. This is NOT\n * Unicode scalar values/code points: a scalar value outside the Basic\n * Multilingual Plane (most emoji) is 2 UTF-16 code units but 1 code point,\n * so a surrogate-pair character advances `offset`/`column` by 2, not 1.\n * Pure-ASCII sources have byte offsets == UTF-16 offsets, so this only\n * matters once the source has non-ASCII content.\n */\nexport interface AstPoint {\n line: number;\n column: number;\n offset: number;\n}\n\n/** Start/end span of two {@link AstPoint}s (unist convention). */\nexport interface AstPosition {\n start: AstPoint;\n end: AstPoint;\n}\n\n/** Optional unist data carried losslessly by known raw tree nodes. */\nexport interface RawMdastData {\n data?: Record<string, unknown>;\n}\n\n/**\n * Internal markdown-rs re-parse bookkeeping carried by MDX expression/ESM\n * nodes: `[indexInValue, absoluteSourceOffset]`. Internal, unstable, and\n * (unlike {@link AstPosition}) **UTF-8 BYTE**-based -- markdown-rs uses it\n * to re-resolve sub-positions inside an expression's own re-parse pass.\n * Never slice a string with it; it does not share `position`'s UTF-16 unit\n * contract.\n */\nexport type MarkdownRsStop = readonly [indexInValue: number, absoluteSourceOffsetBytes: number];\n\n/** GFM alignment for a table column. `null` means no explicit alignment. */\nexport type TableAlign = \"left\" | \"right\" | \"center\" | null;\n\n/** Explicitness of a `link`/`image` reference (GFM footnotes reuse it too). */\nexport type ReferenceKind = \"shortcut\" | \"collapsed\" | \"full\";\n\n// ── mdast core node set ─────────────────────────────────────────────────────\n// Mirrors `markdown::mdast::Node`'s variants (markdown-rs, `serde(tag =\n// \"type\", rename_all = \"camelCase\")`) -- see that crate's `src/mdast.rs` for\n// the authoritative field shapes. Every variant here always carries\n// `position` (requirement 2 of zfb#1828); the one documented exception,\n// `mdxJsxAttribute`/its value/expression-attribute siblings, is intentionally\n// NOT part of the `MdastNode` union below -- they are attribute records\n// embedded in `MdxJsxFlowElement`/`MdxJsxTextElement.attributes`, not\n// standalone tree nodes.\n\nexport interface Root extends RawMdastData {\n type: \"root\";\n position: AstPosition;\n children: MdastNode[];\n}\nexport interface Paragraph extends RawMdastData {\n type: \"paragraph\";\n position: AstPosition;\n children: MdastNode[];\n}\nexport interface Heading extends RawMdastData {\n type: \"heading\";\n position: AstPosition;\n depth: 1 | 2 | 3 | 4 | 5 | 6;\n children: MdastNode[];\n}\nexport interface ThematicBreak extends RawMdastData {\n type: \"thematicBreak\";\n position: AstPosition;\n}\nexport interface Blockquote extends RawMdastData {\n type: \"blockquote\";\n position: AstPosition;\n children: MdastNode[];\n}\nexport interface List extends RawMdastData {\n type: \"list\";\n position: AstPosition;\n ordered: boolean;\n /**\n * Absent for an unordered list. Rust serializes `None` here by OMITTING\n * the key (`#[serde(skip_serializing_if = \"Option::is_none\")]`), not as\n * JSON `null` -- hence `?:`, not `| null`.\n */\n start?: number;\n spread: boolean;\n children: MdastNode[];\n}\nexport interface ListItem extends RawMdastData {\n type: \"listItem\";\n position: AstPosition;\n spread: boolean;\n /** GFM task-list state; absent (not `null` -- see {@link List.start}) for a plain (non-task) item. */\n checked?: boolean;\n children: MdastNode[];\n}\nexport interface Html extends RawMdastData {\n type: \"html\";\n position: AstPosition;\n value: string;\n}\nexport interface Code extends RawMdastData {\n type: \"code\";\n position: AstPosition;\n /** Absent when the fence has no language (see {@link List.start}). */\n lang?: string;\n /** Absent when the fence has no meta string (see {@link List.start}). */\n meta?: string;\n value: string;\n}\nexport interface Definition extends RawMdastData {\n type: \"definition\";\n position: AstPosition;\n url: string;\n /** Absent when there is no title (see {@link List.start}). */\n title?: string;\n identifier: string;\n /** Absent when there is no label (see {@link List.start}). */\n label?: string;\n}\nexport interface Text extends RawMdastData {\n type: \"text\";\n position: AstPosition;\n value: string;\n}\n\n/** Shared raw shape of the three generic remark-directive node kinds. */\nexport interface DirectiveNodeBase extends RawMdastData {\n position: AstPosition;\n name: string;\n /** Always present; boolean attributes are represented by an empty string. */\n attributes: Record<string, string>;\n children: MdastNode[];\n}\nexport interface ContainerDirective extends DirectiveNodeBase {\n type: \"containerDirective\";\n}\nexport interface LeafDirective extends DirectiveNodeBase {\n type: \"leafDirective\";\n}\nexport interface TextDirective extends DirectiveNodeBase {\n type: \"textDirective\";\n}\nexport interface Emphasis extends RawMdastData {\n type: \"emphasis\";\n position: AstPosition;\n children: MdastNode[];\n}\nexport interface Strong extends RawMdastData {\n type: \"strong\";\n position: AstPosition;\n children: MdastNode[];\n}\nexport interface InlineCode extends RawMdastData {\n type: \"inlineCode\";\n position: AstPosition;\n value: string;\n}\nexport interface Break extends RawMdastData {\n type: \"break\";\n position: AstPosition;\n}\nexport interface Link extends RawMdastData {\n type: \"link\";\n position: AstPosition;\n url: string;\n /** Absent when there is no title (see {@link List.start}). */\n title?: string;\n children: MdastNode[];\n}\nexport interface Image extends RawMdastData {\n type: \"image\";\n position: AstPosition;\n alt: string;\n url: string;\n /** Absent when there is no title (see {@link List.start}). */\n title?: string;\n}\nexport interface LinkReference extends RawMdastData {\n type: \"linkReference\";\n position: AstPosition;\n referenceType: ReferenceKind;\n identifier: string;\n /** Absent when there is no label (see {@link List.start}). */\n label?: string;\n children: MdastNode[];\n}\nexport interface ImageReference extends RawMdastData {\n type: \"imageReference\";\n position: AstPosition;\n alt: string;\n referenceType: ReferenceKind;\n identifier: string;\n /** Absent when there is no label (see {@link List.start}). */\n label?: string;\n}\n/** GFM footnote definition (`[^id]: ...`). */\nexport interface FootnoteDefinition extends RawMdastData {\n type: \"footnoteDefinition\";\n position: AstPosition;\n identifier: string;\n /** Absent when there is no label (see {@link List.start}). */\n label?: string;\n children: MdastNode[];\n}\n/** GFM footnote reference (`[^id]`). */\nexport interface FootnoteReference extends RawMdastData {\n type: \"footnoteReference\";\n position: AstPosition;\n identifier: string;\n /** Absent when there is no label (see {@link List.start}). */\n label?: string;\n}\n/** GFM table. */\nexport interface Table extends RawMdastData {\n type: \"table\";\n position: AstPosition;\n align: TableAlign[];\n children: MdastNode[];\n}\nexport interface TableRow extends RawMdastData {\n type: \"tableRow\";\n position: AstPosition;\n children: MdastNode[];\n}\nexport interface TableCell extends RawMdastData {\n type: \"tableCell\";\n position: AstPosition;\n children: MdastNode[];\n}\n/** GFM strikethrough (`~~text~~`). */\nexport interface Delete extends RawMdastData {\n type: \"delete\";\n position: AstPosition;\n children: MdastNode[];\n}\n/**\n * Canonical markdown-rs YAML frontmatter node emitted by\n * `frontmatter: \"node\"`. Its value excludes fences and line endings while\n * its position covers the complete fenced block.\n */\nexport interface Yaml extends RawMdastData {\n type: \"yaml\";\n position: AstPosition;\n value: string;\n}\n\n// ── MDX node set ─────────────────────────────────────────────────────────\n\n/** MDX flow expression (`{...}` on its own line). */\nexport interface MdxFlowExpression extends RawMdastData {\n type: \"mdxFlowExpression\";\n position: AstPosition;\n value: string;\n /** Internal/unstable/byte-based -- see {@link MarkdownRsStop}. */\n _markdownRsStops: MarkdownRsStop[];\n}\n/** MDX text expression (`{...}` inline in phrasing content). */\nexport interface MdxTextExpression extends RawMdastData {\n type: \"mdxTextExpression\";\n position: AstPosition;\n value: string;\n _markdownRsStops: MarkdownRsStop[];\n}\n/** MDX JSX element as flow (block-level) content. */\nexport interface MdxJsxFlowElement extends RawMdastData {\n type: \"mdxJsxFlowElement\";\n position: AstPosition;\n /** Absent for a JSX fragment (`<>...</>`) -- see {@link List.start}. */\n name?: string;\n attributes: MdxJsxAttributeContent[];\n children: MdastNode[];\n}\n/** MDX JSX element as phrasing (inline) content. */\nexport interface MdxJsxTextElement extends RawMdastData {\n type: \"mdxJsxTextElement\";\n position: AstPosition;\n /** Absent for a JSX fragment (`<>...</>`) -- see {@link List.start}. */\n name?: string;\n attributes: MdxJsxAttributeContent[];\n children: MdastNode[];\n}\n\n/**\n * A JSX attribute's value: a plain string literal, or a `{...}` expression\n * value. Divergence: expression attribute VALUES carry no `position`\n * (mirrors the `mdxJsxAttribute`/`mdxJsxExpressionAttribute` divergence\n * below -- markdown-rs does not model attribute positions anywhere).\n */\nexport interface MdxJsxAttributeValueExpression extends RawMdastData {\n type: \"mdxJsxAttributeValueExpression\";\n value: string;\n _markdownRsStops: MarkdownRsStop[];\n}\n/**\n * One `name=\"value\"` / `name={expr}` / bare `name` JSX attribute.\n * Divergence: carries no `position` -- markdown-rs does not model attribute\n * positions (zfb#1828 requirement 2's one documented exception).\n */\nexport interface MdxJsxAttribute extends RawMdastData {\n type: \"mdxJsxAttribute\";\n name: string;\n /** Absent for a bare boolean attribute (`<a b />`) -- see {@link List.start}. */\n value?: string | MdxJsxAttributeValueExpression;\n}\n/**\n * A JSX spread attribute (`{...expr}`). Divergence: carries no `position`,\n * same reason as {@link MdxJsxAttribute}.\n */\nexport interface MdxJsxExpressionAttribute extends RawMdastData {\n type: \"mdxJsxExpressionAttribute\";\n value: string;\n _markdownRsStops: MarkdownRsStop[];\n}\n/** One entry of `MdxJsxFlowElement`/`MdxJsxTextElement.attributes`. */\nexport type MdxJsxAttributeContent = MdxJsxAttribute | MdxJsxExpressionAttribute;\n\n/**\n * Catch-all for any mdast node type not enumerated above -- keeps\n * unrecognized/future node types TYPED (requirement 3 of zfb#1828: an opaque\n * `unknown` would silently drop this contract) rather than falling back to\n * `unknown`. `type` is deliberately the general `string` here (not a\n * literal), so TypeScript's discriminated-union narrowing on `type` keeps\n * this member alongside any single literal match; disambiguate with an\n * explicit assertion once a runtime `type` check has confirmed which shape\n * you actually have (see `test/consumer-compatibility-parse-to-ast.ts` for\n * the pattern).\n */\nexport interface UnknownMdastNode {\n type: string;\n position: AstPosition;\n [key: string]: unknown;\n}\n\n/**\n * Any node markdown-rs's raw mdast serialization can produce through\n * `parseToAst` -- the documented mdast core set, the documented MDX set, or\n * {@link UnknownMdastNode} for anything else. Attribute-record shapes\n * ({@link MdxJsxAttributeContent} and its members) are intentionally NOT\n * part of this union -- see their own docs.\n */\nexport type MdastNode =\n | Root\n | Paragraph\n | Heading\n | ThematicBreak\n | Blockquote\n | List\n | ListItem\n | Html\n | Code\n | Definition\n | Text\n | Emphasis\n | Strong\n | InlineCode\n | Break\n | Link\n | Image\n | LinkReference\n | ImageReference\n | FootnoteDefinition\n | FootnoteReference\n | Table\n | TableRow\n | TableCell\n | Delete\n | Yaml\n | MdxFlowExpression\n | MdxTextExpression\n | MdxJsxFlowElement\n | MdxJsxTextElement\n | ContainerDirective\n | LeafDirective\n | TextDirective\n | UnknownMdastNode;\n\n/** The tree root `parseToAst` returns -- always a `root` node when present. */\nexport type MdastRoot = Root;\n\n/**\n * Result document of `parseToAst` (zfb#1857, epic zfb#1854). `ast` is the\n * raw markdown-rs mdast converted through its serde shape into an open\n * carrier (unist-shaped `type`, fields, and `position`) and PRE-zfb-visitors.\n * Source selection follows {@link FrontmatterPolicy}. When `directives` is\n * true the carrier can also contain the three generic directive kinds;\n * otherwise directive-looking text survives exactly as markdown-rs parsed\n * it. `position.offset` and\n * `position.column` are UTF-16 code units (see {@link AstPoint}).\n *\n * Markdown mode preserves CommonMark HTML/comments, angle autolinks,\n * indented code, and literal braces. MDX mode enables JSX/expressions and\n * keeps markdown-rs's conflicting CommonMark constructs disabled. Both\n * modes apply the same five independent {@link GfmOptions} switches.\n *\n * Documented divergences from remark-parse / remark-mdx in MDX mode:\n * - `mdxJsxAttribute` (and its value/expression-attribute siblings) carry no\n * `position` -- markdown-rs does not model attribute positions.\n * - Top-level `import`/`export` degrade to paragraphs (no `mdxjsEsm` nodes),\n * and MDX expressions carry no estree data -- the wasm boundary cannot\n * host a JS ESM/acorn parser. Consumers needing remark-mdx-equivalent\n * ESM/estree keep remark for those documents.\n * - `_markdownRsStops` is internal, unstable, and byte-based (not UTF-16) --\n * see {@link MarkdownRsStop}.\n */\nexport interface ParseToAstResult {\n /** Serialized raw mdast root on success, `null` on failure. */\n ast: MdastRoot | null;\n /** Parsed YAML frontmatter as JSON, `null` when absent or unextractable. */\n frontmatter: unknown;\n diagnostics: Diagnostic[];\n}\n\n/** Result document of `renderHtml`. */\nexport interface RenderHtmlResult {\n /** HTML fragment on success, `null` on failure. */\n html: string | null;\n frontmatter: unknown;\n diagnostics: Diagnostic[];\n}\n\n/**\n * The fixed 18-role semantic taxonomy emitted by `highlightCode`. This union\n * is mechanically checked against Rust's canonical `HiRole::FULL_NAMES` by\n * `zfb`'s role-drift guard; do not add a second unguarded role list.\n */\nexport type HighlightRole =\n | \"escape\"\n | \"operator\"\n | \"comment\"\n | \"string\"\n | \"number\"\n | \"constant\"\n | \"keyword\"\n | \"function\"\n | \"type\"\n | \"namespace\"\n | \"property\"\n | \"variable\"\n | \"tag\"\n | \"attribute\"\n | \"punctuation\"\n | \"inserted\"\n | \"deleted\"\n | \"heading\";\n\n/** Options for direct arbitrary-code semantic class highlighting. */\nexport interface HighlightCodeOptions {\n /** Required syntax token, for example `\"html\"`, `\"css\"`, or `\"javascript\"`. */\n language: string;\n /** The only supported direct output mode. Defaults to `\"class\"`. */\n mode?: \"class\";\n /** Semantic role class prefix. Defaults to `\"hi-\"`. */\n classPrefix?: string;\n /** Full-name role overrides, for example `{ keyword: \"text-violet-600\" }`. */\n roleClasses?: Partial<Record<HighlightRole, string>>;\n}\n\n/** Sources used by direct `highlightCode` diagnostics. */\nexport type HighlightDiagnosticSource = \"options\" | \"highlight\" | \"internal\";\n\n/** A structured direct-highlighting diagnostic. */\nexport interface HighlightDiagnostic {\n severity: \"error\" | \"warning\";\n source: HighlightDiagnosticSource;\n message: string;\n /** Always `null` for semantic/highlight diagnostics; JSON option parse locations are 1-based. */\n line: number | null;\n /** Always `null` for semantic/highlight diagnostics; JSON option parse locations are 1-based. */\n column: number | null;\n}\n\n/** Result document returned by {@link highlightCode}. */\nexport interface HighlightCodeResult {\n /** Complete semantic `<pre><code>` wrapper, or `null` for invalid options/internal errors. */\n html: string | null;\n diagnostics: HighlightDiagnostic[];\n}\n"]}
|
|
Binary file
|
|
@@ -88,7 +88,9 @@ export function parseToAst(source: string, options_json: string): string;
|
|
|
88
88
|
*
|
|
89
89
|
* Returns a JSON string: `{ "html": string|null, "frontmatter": json,
|
|
90
90
|
* "diagnostics": Diagnostic[] }` — see the crate docs for the options
|
|
91
|
-
* and diagnostics shapes.
|
|
91
|
+
* and diagnostics shapes. A `.md` filename selects CommonMark and `.mdx`
|
|
92
|
+
* selects MDX unless the top-level `dialect` option overrides it. Exported
|
|
93
|
+
* to JS as `renderHtml`.
|
|
92
94
|
*/
|
|
93
95
|
export function renderHtml(source: string, options_json: string): string;
|
|
94
96
|
|
|
@@ -155,7 +155,9 @@ export function parseToAst(source, options_json) {
|
|
|
155
155
|
*
|
|
156
156
|
* Returns a JSON string: `{ "html": string|null, "frontmatter": json,
|
|
157
157
|
* "diagnostics": Diagnostic[] }` — see the crate docs for the options
|
|
158
|
-
* and diagnostics shapes.
|
|
158
|
+
* and diagnostics shapes. A `.md` filename selects CommonMark and `.mdx`
|
|
159
|
+
* selects MDX unless the top-level `dialect` option overrides it. Exported
|
|
160
|
+
* to JS as `renderHtml`.
|
|
159
161
|
* @param {string} source
|
|
160
162
|
* @param {string} options_json
|
|
161
163
|
* @returns {string}
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/* tslint:disable */
|
|
2
|
+
/* eslint-disable */
|
|
3
|
+
export const memory: WebAssembly.Memory;
|
|
4
|
+
export const __forceTrapForTests: () => void;
|
|
5
|
+
export const parseToAst: (a: number, b: number, c: number, d: number, e: number) => void;
|
|
6
|
+
export const version: (a: number) => void;
|
|
7
|
+
export const __wbindgen_add_to_stack_pointer: (a: number) => number;
|
|
8
|
+
export const __wbindgen_export: (a: number, b: number) => number;
|
|
9
|
+
export const __wbindgen_export2: (a: number, b: number, c: number, d: number) => number;
|
|
10
|
+
export const __wbindgen_export3: (a: number, b: number, c: number) => void;
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/* tslint:disable */
|
|
2
|
+
/* eslint-disable */
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Deliberately trap the current WebAssembly instance for wrapper recovery
|
|
6
|
+
* tests. This is not part of the typed package API; the JavaScript wrapper
|
|
7
|
+
* exposes it only through its internal test hook.
|
|
8
|
+
*
|
|
9
|
+
* A Rust panic is the reliable cross-engine representation of the real
|
|
10
|
+
* failure this hook needs to exercise. Calling a generated raw C-ABI export
|
|
11
|
+
* with fabricated pointers could instead enter undefined Rust-level work and
|
|
12
|
+
* hang Chromium before reaching the wasm trap boundary.
|
|
13
|
+
*/
|
|
14
|
+
export function __forceTrapForTests(): void;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Parse markdown/MDX source into a serialized RAW mdast tree — a
|
|
18
|
+
* supported API tier (zfb#1857, decided GO by epic zfb#1854 / zfb#1828).
|
|
19
|
+
* Exported to JS as `parseToAst`.
|
|
20
|
+
*
|
|
21
|
+
* Returns a JSON string: `{ "ast": mdast|null, "frontmatter": json,
|
|
22
|
+
* "diagnostics": Diagnostic[] }`. The tree is raw markdown-rs parser output
|
|
23
|
+
* converted through its serde shape into an open carrier, optionally
|
|
24
|
+
* composed with generic directives (post-frontmatter-strip,
|
|
25
|
+
* PRE-zfb-visitors — mdast, not hast, and
|
|
26
|
+
* unrecognized/custom constructs such as MDX JSX elements survive as typed
|
|
27
|
+
* nodes rather than being dropped), serialized in the unist shape via
|
|
28
|
+
* markdown-rs's `serde` feature, with every `position` shifted back into
|
|
29
|
+
* original-source coordinates (see [`shift_interop_positions`]). Its
|
|
30
|
+
* distinct closed options document accepts only `filename`, `dialect`,
|
|
31
|
+
* `directives`, and `pipeline.gfm`; compile/visitor/serializer knobs are
|
|
32
|
+
* rejected rather than silently ignored. A missing filename defaults to
|
|
33
|
+
* `<anonymous>.mdx`.
|
|
34
|
+
* Otherwise `.md` infers Markdown and `.mdx` infers MDX; an explicit dialect
|
|
35
|
+
* overrides either valid extension without waiving the extension gate.
|
|
36
|
+
*
|
|
37
|
+
* ## Position contract: UTF-16 code units (decided zfb#1856)
|
|
38
|
+
*
|
|
39
|
+
* `position.offset` and `position.column` are UTF-16 code-unit indices —
|
|
40
|
+
* remark/unist convention, and what `String.prototype.slice`,
|
|
41
|
+
* `mdast-util-to-hast`, and consumer mdast plugins already index by.
|
|
42
|
+
* `position.line` is unit-agnostic and needs no conversion. This matters on
|
|
43
|
+
* non-ASCII sources: a scalar value outside the Basic Multilingual Plane
|
|
44
|
+
* (most emoji) is 1 UTF-16 code unit different from its UTF-8 byte width
|
|
45
|
+
* (2 UTF-16 units vs. usually 4 bytes) — see [`Utf16Positions`] for the
|
|
46
|
+
* conversion and `tests/parse_to_ast.rs`'s
|
|
47
|
+
* `utf16_code_unit_semantics_are_pinned_on_non_ascii` for the pin. Pure-
|
|
48
|
+
* ASCII sources take a fast path that skips the conversion entirely (byte
|
|
49
|
+
* units already equal UTF-16 units there).
|
|
50
|
+
*
|
|
51
|
+
* ## Documented divergences from remark-parse / remark-mdx
|
|
52
|
+
*
|
|
53
|
+
* - `mdxJsxAttribute` records carry no `position` — markdown-rs does not
|
|
54
|
+
* model attribute positions.
|
|
55
|
+
* - Top-level `import`/`export` degrade to paragraphs (no `mdxjsEsm` nodes
|
|
56
|
+
* — markdown-rs's `mdx_esm_parse` needs a JS ESM parser the wasm boundary
|
|
57
|
+
* cannot host), and MDX expressions carry no estree data (the default
|
|
58
|
+
* aggressive mode validates braces only, unlike remark-mdx's acorn pass).
|
|
59
|
+
* Consumers needing remark-mdx-equivalent ESM/estree keep remark for
|
|
60
|
+
* those documents.
|
|
61
|
+
* - `_markdownRsStops` (on MDX expression/ESM nodes) is markdown-rs-
|
|
62
|
+
* internal re-parse bookkeeping: internal, unstable, and BYTE-based (NOT
|
|
63
|
+
* UTF-16 like `position`) — never slice a string with it.
|
|
64
|
+
*/
|
|
65
|
+
export function parseToAst(source: string, options_json: string): string;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* This package's release version, stamped by CI at compile time.
|
|
69
|
+
*
|
|
70
|
+
* Development builds without `ZFB_RELEASE_VERSION` fall back to this crate's
|
|
71
|
+
* manifest version (`CARGO_PKG_VERSION`).
|
|
72
|
+
*/
|
|
73
|
+
export function version(): string;
|
|
74
|
+
|
|
75
|
+
export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
|
|
76
|
+
|
|
77
|
+
export interface InitOutput {
|
|
78
|
+
readonly memory: WebAssembly.Memory;
|
|
79
|
+
readonly __forceTrapForTests: () => void;
|
|
80
|
+
readonly parseToAst: (a: number, b: number, c: number, d: number, e: number) => void;
|
|
81
|
+
readonly version: (a: number) => void;
|
|
82
|
+
readonly __wbindgen_add_to_stack_pointer: (a: number) => number;
|
|
83
|
+
readonly __wbindgen_export: (a: number, b: number) => number;
|
|
84
|
+
readonly __wbindgen_export2: (a: number, b: number, c: number, d: number) => number;
|
|
85
|
+
readonly __wbindgen_export3: (a: number, b: number, c: number) => void;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export type SyncInitInput = BufferSource | WebAssembly.Module;
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Instantiates the given `module`, which can either be bytes or
|
|
92
|
+
* a precompiled `WebAssembly.Module`.
|
|
93
|
+
*
|
|
94
|
+
* @param {{ module: SyncInitInput }} module - Passing `SyncInitInput` directly is deprecated.
|
|
95
|
+
*
|
|
96
|
+
* @returns {InitOutput}
|
|
97
|
+
*/
|
|
98
|
+
export function initSync(module: { module: SyncInitInput } | SyncInitInput): InitOutput;
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* If `module_or_path` is {RequestInfo} or {URL}, makes a request and
|
|
102
|
+
* for everything else, calls `WebAssembly.instantiate` directly.
|
|
103
|
+
*
|
|
104
|
+
* @param {{ module_or_path: InitInput | Promise<InitInput> }} module_or_path - Passing `InitInput` directly is deprecated.
|
|
105
|
+
*
|
|
106
|
+
* @returns {Promise<InitOutput>}
|
|
107
|
+
*/
|
|
108
|
+
export default function __wbg_init (module_or_path?: { module_or_path: InitInput | Promise<InitInput> } | InitInput | Promise<InitInput>): Promise<InitOutput>;
|