mdream 1.7.1 → 2.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/napi/index.d.ts CHANGED
@@ -1,10 +1,24 @@
1
1
  /* auto-generated by NAPI-RS */
2
2
  /* eslint-disable */
3
+
4
+ /**
5
+ * Which binding artifact the generated loader actually loaded: `'native'` for
6
+ * a native addon, otherwise the `platformArchABI` of the WASI flavor. Every
7
+ * flavor napi-rs can build is listed, because `NAPI_RS_NATIVE_LIBRARY_PATH`
8
+ * can point the loader at a WASI artifact this package does not build itself.
9
+ */
10
+ export declare const __napiBindingTarget: 'native' | 'wasm32-wasi' | 'wasm32-wasip1'
11
+
3
12
  export declare class MarkdownStream {
4
13
  constructor(options?: HtmlToMarkdownOptions | undefined | null)
5
14
  processChunk(chunk: string): string
6
15
  processChunkBytes(chunk: Uint8Array): string
7
16
  finish(): string
17
+ /**
18
+ * Frontmatter and extracted elements collected so far. Call after
19
+ * `finish()` for the complete data. Extracted elements drain on each call.
20
+ */
21
+ takeData(): MdreamStreamData
8
22
  }
9
23
 
10
24
  export interface ChunkLocNapi {
@@ -77,6 +91,12 @@ export interface MdreamNapiResult {
77
91
  frontmatter?: Record<string, string>
78
92
  }
79
93
 
94
+ /** Plugin data a stream collected: frontmatter and extracted elements. */
95
+ export interface MdreamStreamData {
96
+ extracted?: Array<ExtractedElementNapi>
97
+ frontmatter?: Record<string, string>
98
+ }
99
+
80
100
  export interface PluginOptions {
81
101
  filter?: FilterOptions
82
102
  isolateMain?: boolean
package/napi/index.mjs CHANGED
@@ -1,14 +1,16 @@
1
- // prettier-ignore
2
1
  /* eslint-disable */
3
2
  // @ts-nocheck
4
3
  /* auto-generated by NAPI-RS */
5
4
 
6
5
  import { createRequire } from 'module'
7
6
  const require = createRequire(import.meta.url)
8
- const __dirname = new URL('.', import.meta.url).pathname
9
7
 
10
8
  const { readFileSync } = require('fs')
11
9
  let nativeBinding = null
10
+ // Which artifact actually loaded. The WASI fallback chain overwrites it with
11
+ // the flavor it resolved; the late native retry below leaves it alone because
12
+ // it only runs while no WASI candidate has been loaded.
13
+ let __napiLoadedBindingTarget = 'native'
12
14
  const loadErrors = []
13
15
 
14
16
  const isMusl = () => {
@@ -67,7 +69,16 @@ const isMuslFromChildProcess = () => {
67
69
  function requireNative() {
68
70
  if (process.env.NAPI_RS_NATIVE_LIBRARY_PATH) {
69
71
  try {
70
- return require(process.env.NAPI_RS_NATIVE_LIBRARY_PATH);
72
+ const overrideBinding = require(process.env.NAPI_RS_NATIVE_LIBRARY_PATH)
73
+ // The override may be a generated WASI loader, which already reports its
74
+ // own flavor. Adopt it: `module.exports` aliases this object, so claiming
75
+ // 'native' would both misreport the artifact and overwrite the loader's
76
+ // marker through the alias.
77
+ __napiLoadedBindingTarget =
78
+ overrideBinding && typeof overrideBinding.__napiBindingTarget === 'string'
79
+ ? overrideBinding.__napiBindingTarget
80
+ : 'native'
81
+ return overrideBinding
71
82
  } catch (err) {
72
83
  loadErrors.push(err)
73
84
  }
@@ -111,36 +122,36 @@ function requireNative() {
111
122
  if (process.arch === 'x64') {
112
123
  if ((process.config && process.config.variables && process.config.variables.shlib_suffix === 'dll.a') || (process.config && process.config.variables && process.config.variables.node_target_type === 'shared_library')) {
113
124
  try {
114
- return require('./rust.win32-x64-gnu.node')
115
- } catch (e) {
116
- loadErrors.push(e)
117
- }
118
- try {
119
- const binding = require('@mdream/rust-win32-x64-gnu')
120
- const bindingPackageVersion = require('@mdream/rust-win32-x64-gnu/package.json').version
121
- if (bindingPackageVersion !== '0.17.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
122
- throw new Error(`Native binding package version mismatch, expected 0.17.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
125
+ return require('./rust.win32-x64-gnu.node')
126
+ } catch (e) {
127
+ loadErrors.push(e)
128
+ }
129
+ try {
130
+ const binding = require('@mdream/rust-win32-x64-gnu')
131
+ const bindingPackageVersion = require('@mdream/rust-win32-x64-gnu/package.json').version
132
+ if (bindingPackageVersion !== '0.17.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
133
+ throw new Error(`Native binding package version mismatch, expected 0.17.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
134
+ }
135
+ return binding
136
+ } catch (e) {
137
+ loadErrors.push(e)
123
138
  }
124
- return binding
125
- } catch (e) {
126
- loadErrors.push(e)
127
- }
128
139
  } else {
129
140
  try {
130
- return require('./rust.win32-x64-msvc.node')
131
- } catch (e) {
132
- loadErrors.push(e)
133
- }
134
- try {
135
- const binding = require('@mdream/rust-win32-x64-msvc')
136
- const bindingPackageVersion = require('@mdream/rust-win32-x64-msvc/package.json').version
137
- if (bindingPackageVersion !== '0.17.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
138
- throw new Error(`Native binding package version mismatch, expected 0.17.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
141
+ return require('./rust.win32-x64-msvc.node')
142
+ } catch (e) {
143
+ loadErrors.push(e)
144
+ }
145
+ try {
146
+ const binding = require('@mdream/rust-win32-x64-msvc')
147
+ const bindingPackageVersion = require('@mdream/rust-win32-x64-msvc/package.json').version
148
+ if (bindingPackageVersion !== '0.17.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
149
+ throw new Error(`Native binding package version mismatch, expected 0.17.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
150
+ }
151
+ return binding
152
+ } catch (e) {
153
+ loadErrors.push(e)
139
154
  }
140
- return binding
141
- } catch (e) {
142
- loadErrors.push(e)
143
- }
144
155
  }
145
156
  } else if (process.arch === 'ia32') {
146
157
  try {
@@ -554,7 +565,7 @@ function createLoadErrorChain(errors) {
554
565
  //
555
566
  // NAPI_RS_WASI_FLAVOR selects one exact generated flavor and implies strict
556
567
  // WASI loading. It never crosses into another flavor or falls back to native.
557
- const __napiWasiFlavors = ["wasm32-wasi"]
568
+ const __napiWasiFlavors = ['wasm32-wasi']
558
569
  const __napiWasiFlavor = process.env.NAPI_RS_WASI_FLAVOR
559
570
  const __napiWasiFlavorRequested =
560
571
  typeof __napiWasiFlavor === 'string' && __napiWasiFlavor.length > 0
@@ -623,15 +634,16 @@ if (!nativeBinding || forceWasi) {
623
634
  }
624
635
  return null
625
636
  }
626
- if (!wasiBindingLoaded && (!__napiWasiFlavorRequested || __napiWasiFlavor === "wasm32-wasi")) {
637
+ if (!wasiBindingLoaded && (!__napiWasiFlavorRequested || __napiWasiFlavor === 'wasm32-wasi')) {
627
638
  let candidateError = null
628
639
  let candidateFailed = false
629
640
  try {
630
- candidateError = __napiWasiResolveCandidate('./rust.wasi.cjs', false, ["./rust.wasm32-wasi.debug.wasm","./rust.wasm32-wasi.wasm"])
641
+ candidateError = __napiWasiResolveCandidate('./rust.wasi.cjs', false, ['./rust.wasm32-wasi.debug.wasm', './rust.wasm32-wasi.wasm'])
631
642
  candidateFailed = candidateError !== null
632
643
  if (!candidateFailed) {
633
644
  wasiBinding = require('./rust.wasi.cjs')
634
645
  nativeBinding = wasiBinding
646
+ __napiLoadedBindingTarget = 'wasm32-wasi'
635
647
  wasiBindingLoaded = true
636
648
  }
637
649
  } catch (err) {
@@ -643,7 +655,7 @@ if (!nativeBinding || forceWasi) {
643
655
  loadErrors.push(candidateError)
644
656
  }
645
657
  }
646
- if (!wasiBindingLoaded && (!__napiWasiFlavorRequested || __napiWasiFlavor === "wasm32-wasi")) {
658
+ if (!wasiBindingLoaded && (!__napiWasiFlavorRequested || __napiWasiFlavor === 'wasm32-wasi')) {
647
659
  let candidateError = null
648
660
  let candidateFailed = false
649
661
  try {
@@ -658,6 +670,7 @@ if (!nativeBinding || forceWasi) {
658
670
  }
659
671
  wasiBinding = require('@mdream/rust-wasm32-wasi')
660
672
  nativeBinding = wasiBinding
673
+ __napiLoadedBindingTarget = 'wasm32-wasi'
661
674
  wasiBindingLoaded = true
662
675
  }
663
676
  } catch (err) {
@@ -709,3 +722,4 @@ export { htmlToMarkdown }
709
722
  export { htmlToMarkdownBytes }
710
723
  export { htmlToMarkdownChunks }
711
724
  export { splitMarkdown }
725
+ export const __napiBindingTarget = __napiLoadedBindingTarget
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mdream",
3
3
  "type": "module",
4
- "version": "1.7.1",
4
+ "version": "2.0.0-beta.1",
5
5
  "description": "Ultra-performant HTML to Markdown Convertor Optimized for LLMs and llm.txt artifacts.",
6
6
  "author": {
7
7
  "name": "Harlan Wilton",
@@ -16,10 +16,19 @@
16
16
  },
17
17
  "exports": {
18
18
  ".": {
19
+ "workerd": {
20
+ "types": "./dist/edge.d.mts",
21
+ "default": "./dist/edge.mjs"
22
+ },
23
+ "edge-light": {
24
+ "types": "./dist/edge.d.mts",
25
+ "default": "./dist/edge.mjs"
26
+ },
27
+ "browser": {
28
+ "types": "./dist/browser.d.mts",
29
+ "default": "./dist/browser.mjs"
30
+ },
19
31
  "types": "./dist/index.d.mts",
20
- "workerd": "./dist/edge.mjs",
21
- "edge-light": "./dist/edge.mjs",
22
- "browser": "./dist/browser.mjs",
23
32
  "import": {
24
33
  "types": "./dist/index.d.mts",
25
34
  "default": "./dist/index.mjs"
@@ -35,8 +44,8 @@
35
44
  "default": "./dist/worker.mjs"
36
45
  },
37
46
  "./wasm": {
38
- "types": "./wasm/mdream_edge.d.ts",
39
- "default": "./wasm/mdream_edge.js"
47
+ "types": "./dist/wasm.d.mts",
48
+ "default": "./dist/wasm.mjs"
40
49
  },
41
50
  "./wasm/*": "./wasm/*"
42
51
  },
@@ -51,28 +60,30 @@
51
60
  "bin",
52
61
  "dist",
53
62
  "napi/",
63
+ "skills",
54
64
  "wasm-bundler/",
55
65
  "wasm/"
56
66
  ],
57
67
  "browser": "./dist/browser.mjs",
58
68
  "dependencies": {},
59
69
  "optionalDependencies": {
60
- "@mdream/rust-android-arm-eabi": "1.7.1",
61
- "@mdream/rust-android-arm64": "1.7.1",
62
- "@mdream/rust-darwin-x64": "1.7.1",
63
- "@mdream/rust-freebsd-x64": "1.7.1",
64
- "@mdream/rust-linux-arm-gnueabihf": "1.7.1",
65
- "@mdream/rust-linux-arm64-gnu": "1.7.1",
66
- "@mdream/rust-darwin-arm64": "1.7.1",
67
- "@mdream/rust-linux-arm64-musl": "1.7.1",
68
- "@mdream/rust-linux-x64-musl": "1.7.1",
69
- "@mdream/rust-linux-x64-gnu": "1.7.1",
70
- "@mdream/rust-wasm32-wasi": "1.7.1",
71
- "@mdream/rust-win32-arm64-msvc": "1.7.1",
72
- "@mdream/rust-win32-x64-msvc": "1.7.1"
70
+ "@mdream/rust-android-arm-eabi": "2.0.0-beta.1",
71
+ "@mdream/rust-android-arm64": "2.0.0-beta.1",
72
+ "@mdream/rust-darwin-arm64": "2.0.0-beta.1",
73
+ "@mdream/rust-darwin-x64": "2.0.0-beta.1",
74
+ "@mdream/rust-freebsd-x64": "2.0.0-beta.1",
75
+ "@mdream/rust-linux-arm-gnueabihf": "2.0.0-beta.1",
76
+ "@mdream/rust-linux-arm64-gnu": "2.0.0-beta.1",
77
+ "@mdream/rust-linux-arm64-musl": "2.0.0-beta.1",
78
+ "@mdream/rust-linux-x64-gnu": "2.0.0-beta.1",
79
+ "@mdream/rust-linux-x64-musl": "2.0.0-beta.1",
80
+ "@mdream/rust-wasm32-wasi": "2.0.0-beta.1",
81
+ "@mdream/rust-win32-arm64-msvc": "2.0.0-beta.1",
82
+ "@mdream/rust-win32-x64-msvc": "2.0.0-beta.1"
73
83
  },
74
84
  "devDependencies": {
75
- "@mdream/js": "1.7.1"
85
+ "@mdream/js": "2.0.0-beta.1",
86
+ "@mdream/rust-build": "0.17.0"
76
87
  },
77
88
  "scripts": {
78
89
  "flame": "pnpm build && unbuild bench/bundle && clinic flame -- node bench/bundle/dist/string.mjs 10",
@@ -88,8 +99,8 @@
88
99
  "test:wiki:file": "pnpm build && cat test/fixtures/wikipedia-largest.html | node ./bin/mdream.mjs --origin https://en.wikipedia.org | tee test/wiki-markdown.md",
89
100
  "test:wiki-small:file": "cat test/fixtures/wikipedia-small.html | node ./bin/mdream.mjs --origin https://en.wikipedia.org | tee test/wiki-markdown.md",
90
101
  "build": "obuild",
91
- "build:native": "cd ../../crates/node && napi build --platform --release",
92
- "build:edge": "cd ../../crates/edge && CARGO_PROFILE_RELEASE_OPT_LEVEL=s wasm-pack build --target web --out-dir ../../packages/mdream/wasm --out-name mdream_edge && wasm-opt -O3 --converge --low-memory-unused --enable-bulk-memory --enable-nontrapping-float-to-int --strip-producers ../../packages/mdream/wasm/mdream_edge_bg.wasm -o ../../packages/mdream/wasm/mdream_edge_bg.wasm && CARGO_PROFILE_RELEASE_OPT_LEVEL=s wasm-pack build --target bundler --out-dir ../../packages/mdream/wasm-bundler --out-name mdream_edge && wasm-opt -O3 --converge --low-memory-unused --enable-bulk-memory --enable-nontrapping-float-to-int --strip-producers ../../packages/mdream/wasm-bundler/mdream_edge_bg.wasm -o ../../packages/mdream/wasm-bundler/mdream_edge_bg.wasm",
102
+ "build:native": "pnpm --dir ../../crates/node run build:platform",
103
+ "build:edge": "node ../../scripts/build-wasm-edge.mjs --target web --out-dir ../../packages/mdream/wasm --out-name mdream_edge && node ../../scripts/build-wasm-edge.mjs --target bundler --out-dir ../../packages/mdream/wasm-bundler --out-name mdream_edge",
93
104
  "typecheck": "tsc --noEmit",
94
105
  "dev:prepare": "obuild --stub",
95
106
  "test": "vitest test",
@@ -0,0 +1,124 @@
1
+ ---
2
+ name: mdream
3
+ description: Convert HTML to Markdown, plain text, or safe HTML with mdream, the Rust engine for Node, edge, and the browser. Use when a task mentions mdream, htmlToMarkdown, streamHtmlToMarkdown, the minimal preset, frontmatter or extraction callbacks, tagOverrides, clean options, the mdream CLI, or errors such as "Custom hook plugins require @mdream/js" or ERR_PACKAGE_PATH_NOT_EXPORTED for mdream/plugins.
4
+ ---
5
+
6
+ # mdream
7
+
8
+ This Skill covers `mdream` 2.0.0-beta.0. The package wraps a Rust converter: NAPI in Node, WASM on edge runtimes and in the browser.
9
+ `@mdream/js` is a separate pure JS engine. It has hook plugins, the splitter, `llms.txt` generation, and content negotiation. Its option shape differs; see [Traps](#traps).
10
+
11
+ ## Setup
12
+
13
+ ```ts
14
+ import { htmlToMarkdown } from 'mdream'
15
+
16
+ const markdown = htmlToMarkdown('<main><h1>Docs</h1></main>', {
17
+ origin: 'https://example.com',
18
+ minimal: true,
19
+ })
20
+ ```
21
+
22
+ - `htmlToMarkdown` is synchronous in Node and on edge runtimes. It returns a string.
23
+ - Set `origin` to make relative `href` and `src` values absolute. Without it, they stay relative.
24
+ - If a bundler fails on the native binding, mark `mdream` as external. In Next.js, add it to `serverExternalPackages`. `@mdream/vite` does this for you.
25
+
26
+ ## Automatic behaviour
27
+
28
+ Default output keeps everything: navigation, forms, footers, and text hidden with CSS classes.
29
+ The `<title>` text never appears in the body. Read it with `frontmatter` or `extraction`.
30
+
31
+ `minimal: true` turns on these options. Each one is off without it.
32
+
33
+ | Option | Effect under `minimal` |
34
+ |---|---|
35
+ | `frontmatter` | YAML frontmatter from `<title>` and `<meta>`. |
36
+ | `isolateMain` | Keeps `<main>`, else the content from the first heading to the first `<footer>`. |
37
+ | `tailwind` | `font-bold` becomes `**bold**`. `hidden` and `absolute` content is dropped. |
38
+ | `filter` | Excludes `form`, `fieldset`, `object`, `embed`, `footer`, `aside`, `iframe`, `input`, `textarea`, `select`, `button`, `nav`. |
39
+ | `clean` | All cleanup: tracking parameters, `#` links, images without alt, and more. |
40
+
41
+ To turn one off, pass it as `false`: `{ minimal: true, frontmatter: false, clean: false }`.
42
+ A `filter` under `minimal` adds to the excludes above: `{ minimal: true, filter: { exclude: ['h1'] } }` drops `h1` and every default tag. `filter: false` keeps forms and `nav`.
43
+
44
+ ## Common tasks
45
+
46
+ Read metadata and matched elements in one pass:
47
+
48
+ ```ts
49
+ import { htmlToMarkdown } from 'mdream'
50
+
51
+ const links: string[] = []
52
+ let title = ''
53
+ const markdown = htmlToMarkdown('<html><head><title>T</title></head><body><a href="/a">A</a></body></html>', {
54
+ frontmatter: (fm) => { title = fm.title ?? '' },
55
+ extraction: {
56
+ 'a[href]': (el) => { links.push(el.attributes.href ?? '') },
57
+ },
58
+ })
59
+ ```
60
+
61
+ Stream a large response. The stream takes the same options, and the callbacks run once, after the last chunk is read:
62
+
63
+ ```ts
64
+ import { streamHtmlToMarkdown } from 'mdream'
65
+
66
+ const response = await fetch('https://example.com')
67
+ let markdown = ''
68
+ let title = ''
69
+ for await (const chunk of streamHtmlToMarkdown(response.body, {
70
+ origin: 'https://example.com',
71
+ minimal: true,
72
+ frontmatter: (fm) => { title = fm.title ?? '' },
73
+ })) {
74
+ markdown += chunk
75
+ }
76
+ ```
77
+
78
+ Render a custom element with Markdown semantics. Unknown tags output only their text.
79
+
80
+ ```ts
81
+ import { htmlToMarkdown } from 'mdream'
82
+
83
+ htmlToMarkdown('<x-heading>Title</x-heading><callout>Read this</callout>', {
84
+ tagOverrides: {
85
+ 'x-heading': 'h2',
86
+ 'callout': { enter: '> **Note:** ', exit: '', spacing: [2, 2] },
87
+ },
88
+ })
89
+ // ## Title\n\n> **Note:** Read this
90
+ ```
91
+
92
+ Other output: `format: 'text'` gives plain text, `format: 'html'` gives allowlisted semantic HTML. `wrapWidth: 80` wraps prose only, never code, tables, or headings.
93
+
94
+ CLI: `curl -s URL | mdream --origin URL --preset minimal`. It streams stdin to stdout. Flags: `--format`, `--text`, `--wrap-width`.
95
+
96
+ ## Traps
97
+
98
+ - **Hook plugins are not in this package.** An array in `plugins` throws `Custom hook plugins require @mdream/js`. Use `@mdream/js` with `hooks: [createPlugin({...})]` from `@mdream/js/plugins`.
99
+ - **`@mdream/js` nests options under `plugins`.** It throws a `TypeError` on `minimal`, `frontmatter`, `isolateMain`, `tailwind`, `filter`, `extraction`, or `tagOverrides` at the top level. Use `withMinimalPreset()` from `@mdream/js/preset/minimal`, or `{ plugins: { frontmatter: true } }`.
100
+ - **Emphasis is `*`, not `_`.** Headings are ATX, bullets are `-`, rules are `---`. Only `tagOverrides` changes a delimiter, for example `em: { enter: '_', exit: '_', isInline: true }`.
101
+ - **Filter selectors also drop inline `position: absolute` and `position: fixed` elements.**
102
+ - **Browser and CDN entries are async.** Every entry takes the same options and produces the same string. The browser bundle and the CDN script return `Promise<string>`, so `await` them. Read [references/runtimes.md](references/runtimes.md) before you use `mdream` outside Node or a Cloudflare Worker.
103
+
104
+ ## Version limits
105
+
106
+ Code from mdream 0.x fails on 1.x and 2.x. The subpaths `mdream/plugins`, `mdream/preset/minimal`, `mdream/splitter`, `mdream/llms-txt`, and `mdream/negotiate` throw `ERR_PACKAGE_PATH_NOT_EXPORTED`.
107
+
108
+ ```ts
109
+ // Old (0.x):
110
+ // import { htmlToMarkdown } from 'mdream'
111
+ // import { withMinimalPreset } from 'mdream/preset/minimal'
112
+ // htmlToMarkdown(html, withMinimalPreset({ origin }))
113
+
114
+ import { htmlToMarkdown } from 'mdream'
115
+
116
+ // New:
117
+ htmlToMarkdown('<p>x</p>', { minimal: true, origin: 'https://example.com' })
118
+ ```
119
+
120
+ The splitter, `llms.txt` generation, and `shouldServeMarkdown` moved to `@mdream/js/splitter`, `@mdream/js/llms-txt`, and `@mdream/js/negotiate`.
121
+
122
+ ## Config
123
+
124
+ Options: `origin`, `minimal`, `clean` (`true` or per rule), `frontmatter`, `isolateMain`, `tailwind`, `filter`, `extraction`, `tagOverrides`, `wrapWidth`, `format`. Types: `MdreamOptions` in the [package README](https://github.com/harlan-zw/mdream/tree/main/packages/mdream#options).
@@ -0,0 +1,49 @@
1
+ # mdream outside Node
2
+
3
+ `mdream` picks an entry by export condition. Every entry takes the same `MdreamOptions`: `minimal`, `frontmatter`, `filter`, `extraction`, `tagOverrides`, and the callbacks work everywhere. Every entry produces a Markdown string. Some return it in a Promise.
4
+
5
+ | Import | Resolved by | Returns |
6
+ |---|---|---|
7
+ | `mdream` | Node | `string` |
8
+ | `mdream` | `workerd`, `edge-light` | `string` |
9
+ | `mdream` | `browser` | `Promise<string>` |
10
+ | `mdream/worker` | direct import | `Promise<string>` |
11
+ | `mdream/wasm` | direct import | `string`, after `init()` |
12
+ | `dist/iife.js` (CDN) | script tag | `Promise<string>` |
13
+
14
+ Each export condition ships its own types. TypeScript reads the `browser` types only when it resolves that condition, for example with `customConditions: ["browser"]` or a bundler that sets it. Otherwise it shows the Node types, a synchronous string.
15
+
16
+ ## Cloudflare Workers and Vercel Edge
17
+
18
+ The `workerd` and `edge-light` conditions load the WASM build and instantiate it at import. The API matches Node.
19
+
20
+ ```ts
21
+ import { htmlToMarkdown } from 'mdream'
22
+
23
+ export default {
24
+ async fetch(request: Request): Promise<Response> {
25
+ const html = await request.text()
26
+ return new Response(htmlToMarkdown(html, { minimal: true }))
27
+ },
28
+ }
29
+ ```
30
+
31
+ A Rust panic becomes a normal `Error` with the message `mdream WASM panic, please report this at ...`. The instance stays usable, so catch it per request.
32
+
33
+ ## Browser bundles
34
+
35
+ In a Vite, webpack, or esbuild client build, `import { htmlToMarkdown } from 'mdream'` resolves the `browser` entry. That entry fetches the WASM binary on first use and returns `Promise<string>`, so `await` it. The options and callbacks work as in Node.
36
+
37
+ ```ts
38
+ import { htmlToMarkdown } from 'mdream'
39
+
40
+ const markdown = await htmlToMarkdown(html, { minimal: true })
41
+ ```
42
+
43
+ For browser code that wants a plain string with no WASM, `@mdream/js` is synchronous. Its options nest under `plugins`.
44
+
45
+ ## Web Worker, raw WASM, and CDN
46
+
47
+ - `mdream/worker`: call `initWorker(wasmUrl)` first, then `await htmlToMarkdown(html, options)`. Call `terminateWorker()` when done. Options resolve on the main thread, and the callbacks run there.
48
+ - `mdream/wasm`: the wasm-bindgen build. Await the default export `init({ module_or_path })` before the first `htmlToMarkdown(html, options)` call. Its `MarkdownStream` runs the callbacks in `finish()`.
49
+ - `https://unpkg.com/mdream/dist/iife.js`: the WASM is inlined and ready at load. `window.mdream` has only `htmlToMarkdown`. There is no `init()`. The call returns `Promise<string>`, the same as the browser bundle.
@@ -6,7 +6,23 @@ export class MarkdownStream {
6
6
  [Symbol.dispose](): void;
7
7
  finish(): string;
8
8
  constructor(options: any);
9
+ /**
10
+ * Byte chunk in, string out, skipping the transcode per chunk. A sequence
11
+ * split across chunks carries to the next call rather than decoding early,
12
+ * matching `TextDecoder({ stream: true })`; invalid bytes become U+FFFD.
13
+ */
14
+ processChunkBytes(chunk: Uint8Array): string;
15
+ /**
16
+ * A carried byte tail cannot be completed by a string chunk, so it is
17
+ * flushed first. Byte and string chunks may be mixed freely.
18
+ */
9
19
  processChunk(chunk: string): string;
20
+ /**
21
+ * Frontmatter and extracted elements collected so far, as
22
+ * `{ frontmatter?, extracted? }`. Call after `finish()` for the complete
23
+ * data. Extracted elements drain on each call.
24
+ */
25
+ takeData(): any;
10
26
  }
11
27
 
12
28
  /**
@@ -16,6 +32,14 @@ export function __mdreamTakePanicMessage(): string | undefined;
16
32
 
17
33
  export function htmlToMarkdown(html: string, options: any): string;
18
34
 
35
+ /**
36
+ * Bytes in, string out: skips the transcode (~14% of a convert) for a
37
+ * caller already holding UTF-8 bytes. Encoding a string to get here
38
+ * measures 1-16% *slower* than [`html_to_markdown`] — only worth it when
39
+ * the bytes are already in hand.
40
+ */
41
+ export function htmlToMarkdownBytes(html: Uint8Array, options: any): string;
42
+
19
43
  export function htmlToMarkdownResult(html: string, options: any): any;
20
44
 
21
45
  export function install_panic_hook(): void;
@@ -27,11 +51,14 @@ export interface InitOutput {
27
51
  readonly __mdreamTakePanicMessage: (a: number) => void;
28
52
  readonly __wbg_markdownstream_free: (a: number, b: number) => void;
29
53
  readonly htmlToMarkdown: (a: number, b: number, c: number, d: number) => void;
54
+ readonly htmlToMarkdownBytes: (a: number, b: number, c: number, d: number) => void;
30
55
  readonly htmlToMarkdownResult: (a: number, b: number, c: number) => number;
31
56
  readonly install_panic_hook: () => void;
32
57
  readonly markdownstream_finish: (a: number, b: number) => void;
33
58
  readonly markdownstream_new: (a: number) => number;
34
59
  readonly markdownstream_processChunk: (a: number, b: number, c: number, d: number) => void;
60
+ readonly markdownstream_processChunkBytes: (a: number, b: number, c: number, d: number) => void;
61
+ readonly markdownstream_takeData: (a: number) => number;
35
62
  readonly __wbindgen_export: (a: number, b: number) => number;
36
63
  readonly __wbindgen_export2: (a: number, b: number, c: number, d: number) => number;
37
64
  readonly __wbindgen_export3: (a: number) => void;