mdream 2.0.0-beta.1 → 2.0.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.
@@ -1,6 +1,9 @@
1
1
  /* @ts-self-types="./mdream_edge.d.ts" */
2
2
 
3
3
  export class MarkdownStream {
4
+ [Symbol.dispose]() {
5
+ this.free();
6
+ }
4
7
  __destroy_into_raw() {
5
8
  const ptr = this.__wbg_ptr;
6
9
  this.__wbg_ptr = 0;
@@ -99,7 +102,6 @@ export class MarkdownStream {
99
102
  return takeObject(ret);
100
103
  }
101
104
  }
102
- if (Symbol.dispose) MarkdownStream.prototype[Symbol.dispose] = MarkdownStream.prototype.free;
103
105
 
104
106
  /**
105
107
  * Consumes the message of the panic that aborted the last export call.
Binary file
package/wasm/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "mdream-edge",
3
3
  "type": "module",
4
4
  "description": "WebAssembly edge runtime bindings for mdream HTML-to-Markdown converter",
5
- "version": "2.0.0-beta.1",
5
+ "version": "2.0.0",
6
6
  "license": "MIT",
7
7
  "files": [
8
8
  "mdream_edge_bg.wasm",
@@ -1,4 +1,7 @@
1
1
  export class MarkdownStream {
2
+ [Symbol.dispose]() {
3
+ this.free();
4
+ }
2
5
  __destroy_into_raw() {
3
6
  const ptr = this.__wbg_ptr;
4
7
  this.__wbg_ptr = 0;
@@ -97,7 +100,6 @@ export class MarkdownStream {
97
100
  return takeObject(ret);
98
101
  }
99
102
  }
100
- if (Symbol.dispose) MarkdownStream.prototype[Symbol.dispose] = MarkdownStream.prototype.free;
101
103
 
102
104
  /**
103
105
  * Consumes the message of the panic that aborted the last export call.
Binary file
@@ -2,7 +2,7 @@
2
2
  "name": "mdream-edge",
3
3
  "type": "module",
4
4
  "description": "WebAssembly edge runtime bindings for mdream HTML-to-Markdown converter",
5
- "version": "2.0.0-beta.1",
5
+ "version": "2.0.0",
6
6
  "license": "MIT",
7
7
  "files": [
8
8
  "mdream_edge_bg.wasm",
package/dist/worker.d.mts DELETED
@@ -1,101 +0,0 @@
1
- interface CleanOptions {
2
- /** Strip tracking query parameters (utm_*, fbclid, gclid, etc.) from URLs */
3
- urls?: boolean;
4
- /** Strip fragment-only links that don't match any heading in the output */
5
- fragments?: boolean;
6
- /** Strip links with meaningless hrefs (#, javascript:void(0)) → plain text */
7
- emptyLinks?: boolean;
8
- /** Collapse 3+ consecutive blank lines to 2 */
9
- blankLines?: boolean;
10
- /** Strip links where text equals URL: [https://x.com](https://x.com) → https://x.com */
11
- redundantLinks?: boolean;
12
- /** Strip self-referencing heading anchors: ## [Title](#title) → ## Title */
13
- selfLinkHeadings?: boolean;
14
- /** Strip images with no alt text (decorative/tracking pixels) */
15
- emptyImages?: boolean;
16
- /** Drop links that produce no visible text: [](url) → nothing */
17
- emptyLinkText?: boolean;
18
- }
19
- interface ExtractedElement {
20
- selector: string;
21
- tagName: string;
22
- textContent: string;
23
- attributes: Record<string, string>;
24
- }
25
- interface FrontmatterConfig {
26
- additionalFields?: Record<string, string>;
27
- metaFields?: string[];
28
- /** Callback to receive structured frontmatter data after conversion */
29
- onExtract?: (frontmatter: Record<string, string>) => void;
30
- }
31
- interface TagOverride {
32
- enter?: string;
33
- exit?: string;
34
- spacing?: number[];
35
- isInline?: boolean;
36
- isSelfClosing?: boolean;
37
- collapsesInnerWhiteSpace?: boolean;
38
- alias?: string;
39
- }
40
- interface MdreamOptions {
41
- /** Origin URL for resolving relative image paths and internal links. */
42
- origin?: string;
43
- /**
44
- * Clean up the markdown output. Pass `true` for all cleanup or an object
45
- * to enable specific features. Both `htmlToMarkdown` and
46
- * `streamHtmlToMarkdown` apply it.
47
- */
48
- clean?: boolean | CleanOptions;
49
- /** Enable minimal preset (frontmatter, isolateMain, tailwind, filter). Default: false */
50
- minimal?: boolean;
51
- /**
52
- * Extract frontmatter from HTML head.
53
- * - `true`: enable with defaults
54
- * - `(fm) => void`: enable and receive structured data via callback
55
- * - `FrontmatterConfig`: enable with config options and optional callback
56
- */
57
- frontmatter?: boolean | ((frontmatter: Record<string, string>) => void) | FrontmatterConfig;
58
- /** Isolate main content area. Default when minimal: true */
59
- isolateMain?: boolean;
60
- /** Convert Tailwind utility classes. Default when minimal: true */
61
- tailwind?: boolean;
62
- /**
63
- * Filter elements by CSS selector. `minimal` excludes form, nav, footer, and
64
- * similar; a filter passed with `minimal` adds to those excludes. `false`
65
- * turns filtering off, including the `minimal` one.
66
- */
67
- filter?: false | {
68
- include?: string[];
69
- exclude?: string[];
70
- processChildren?: boolean;
71
- };
72
- /** Extract elements matching CSS selectors */
73
- extraction?: Record<string, (element: ExtractedElement) => void>;
74
- /** Tag overrides. String values act as aliases */
75
- tagOverrides?: Record<string, TagOverride | string>;
76
- /**
77
- * Hard-wrap prose at this many characters, breaking on word boundaries.
78
- * Applied inline during conversion (zero-cost when unset). Code blocks,
79
- * tables, and headings are never wrapped. `0` disables wrapping.
80
- */
81
- wrapWidth?: number;
82
- /**
83
- * Output format. Defaults to `markdown`; use `text` for readable plain text,
84
- * or `html` for allowlisted semantic HTML.
85
- */
86
- format?: 'markdown' | 'text' | 'html';
87
- }
88
- /**
89
- * Initialize the mdream web worker. Must be called before htmlToMarkdown.
90
- * @param wasmUrl - URL to the mdream_edge_bg.wasm file
91
- */
92
- export declare function initWorker(wasmUrl: string): Promise<void>;
93
- /**
94
- * Convert HTML to markdown using the web worker.
95
- * Call initWorker() first.
96
- */
97
- export declare function htmlToMarkdown(html: string, options?: Partial<MdreamOptions>): Promise<string>;
98
- /**
99
- * Terminate the web worker and free resources.
100
- */
101
- export declare function terminateWorker(): void;
package/dist/worker.mjs DELETED
@@ -1,217 +0,0 @@
1
- const MINIMAL_FILTER_EXCLUDE = [
2
- "form",
3
- "fieldset",
4
- "object",
5
- "embed",
6
- "footer",
7
- "aside",
8
- "iframe",
9
- "input",
10
- "textarea",
11
- "select",
12
- "button",
13
- "nav"
14
- ];
15
- const CLEAN_ALL = {
16
- urls: true,
17
- fragments: true,
18
- emptyLinks: true,
19
- redundantLinks: true,
20
- selfLinkHeadings: true,
21
- emptyImages: true,
22
- emptyLinkText: true
23
- };
24
- function resolveCleanConfig(options, minimal) {
25
- const cleanUrls = options.cleanUrls === true;
26
- let cleanOpt = options.clean;
27
- if (cleanOpt === void 0) {
28
- if (!minimal) return { cleanUrls };
29
- cleanOpt = true;
30
- }
31
- if (!cleanOpt) return { cleanUrls };
32
- const resolved = cleanOpt === true ? CLEAN_ALL : cleanOpt;
33
- return {
34
- cleanUrls: cleanUrls || resolved.urls === true,
35
- clean: resolved
36
- };
37
- }
38
- function resolveFrontmatter(opt) {
39
- if (typeof opt === "function") return {
40
- config: {},
41
- callback: opt
42
- };
43
- if (opt && typeof opt === "object") {
44
- const { onExtract, ...config } = opt;
45
- return {
46
- config,
47
- callback: onExtract
48
- };
49
- }
50
- return { config: {} };
51
- }
52
- function resolveOptions(options) {
53
- if (Array.isArray(options.plugins)) throw new TypeError("Custom hook plugins require @mdream/js. Pass declarative config (e.g. { frontmatter: true }) to the Rust engine, or import { htmlToMarkdown } from '@mdream/js' for hook-based plugins. See https://mdream.dev/v1-migration#custom-plugins");
54
- const minimal = options.minimal === true;
55
- const plugins = options.plugins ? { ...options.plugins } : {};
56
- let frontmatterCallback;
57
- const frontmatterDisabled = options.frontmatter === false;
58
- if (minimal ? !frontmatterDisabled : !!options.frontmatter) {
59
- const fm = resolveFrontmatter(options.frontmatter);
60
- plugins.frontmatter = fm.config;
61
- frontmatterCallback = fm.callback;
62
- } else if (frontmatterDisabled) delete plugins.frontmatter;
63
- const isolateMainDisabled = options.isolateMain === false;
64
- if (minimal ? !isolateMainDisabled : options.isolateMain) plugins.isolateMain = true;
65
- else if (isolateMainDisabled) delete plugins.isolateMain;
66
- const tailwindDisabled = options.tailwind === false;
67
- if (minimal ? !tailwindDisabled : options.tailwind) plugins.tailwind = true;
68
- else if (tailwindDisabled) delete plugins.tailwind;
69
- if (options.filter === false) delete plugins.filter;
70
- else if (minimal) plugins.filter = {
71
- ...options.filter,
72
- exclude: [...MINIMAL_FILTER_EXCLUDE, ...options.filter?.exclude ?? []]
73
- };
74
- else if (options.filter) plugins.filter = options.filter;
75
- const extraction = options.extraction;
76
- let extractionHandlers;
77
- if (extraction) {
78
- plugins.extraction = { selectors: Object.keys(extraction) };
79
- extractionHandlers = extraction;
80
- }
81
- const tagOverrides = options.tagOverrides;
82
- if (tagOverrides) {
83
- const overrides = {};
84
- for (const tag in tagOverrides) {
85
- const value = tagOverrides[tag];
86
- if (value) overrides[tag] = typeof value === "string" ? { alias: value } : value;
87
- }
88
- plugins.tagOverrides = overrides;
89
- }
90
- const { cleanUrls, clean } = resolveCleanConfig(options, minimal);
91
- return {
92
- napiOpts: {
93
- origin: options.origin,
94
- cleanUrls,
95
- clean,
96
- plugins,
97
- wrapWidth: options.wrapWidth,
98
- format: options.format
99
- },
100
- extractionHandlers,
101
- frontmatterCallback
102
- };
103
- }
104
- function deliverPluginData(data, { frontmatterCallback, extractionHandlers }) {
105
- if (data.frontmatter && frontmatterCallback) frontmatterCallback(data.frontmatter);
106
- if (data.extracted?.length && extractionHandlers) for (const element of data.extracted) extractionHandlers[element.selector]?.(element);
107
- }
108
- let _worker = null;
109
- let _ready = null;
110
- let _idCounter = 0;
111
- const _pending = /* @__PURE__ */ new Map();
112
- const WASM_RE = /\.wasm$/;
113
- function getWorkerBlob(wasmUrl) {
114
- const code = `
115
- // namespace import: the URL is caller-supplied and may point at an older build
116
- import init, * as engine from '${wasmUrl.replace(WASM_RE, ".js")}';
117
- const { htmlToMarkdownResult } = engine;
118
-
119
- let ready = false;
120
-
121
- async function initialize() {
122
- await init('${wasmUrl}');
123
- ready = true;
124
- self.postMessage({ type: 'ready' });
125
- }
126
-
127
- initialize().catch(e => {
128
- self.postMessage({ type: 'error', id: -1, message: 'WASM init failed: ' + e.message });
129
- });
130
-
131
- self.onmessage = function(e) {
132
- const msg = e.data;
133
- if (msg.type === 'convert') {
134
- if (!ready) {
135
- self.postMessage({ id: msg.id, type: 'error', message: 'Worker not ready' });
136
- return;
137
- }
138
- try {
139
- const result = htmlToMarkdownResult(msg.html, msg.options || {});
140
- self.postMessage({ id: msg.id, type: 'result', data: result });
141
- } catch (err) {
142
- // WASM aborts on panic (#195): the message is stashed by the panic hook
143
- const panic = engine.__mdreamTakePanicMessage?.();
144
- self.postMessage({ id: msg.id, type: 'error', message: panic || err.message });
145
- }
146
- }
147
- };`;
148
- return new Blob([code], { type: "application/javascript" });
149
- }
150
- function onMessage(e) {
151
- const msg = e.data;
152
- if (msg.type === "ready") return;
153
- if ("id" in msg) {
154
- const pending = _pending.get(msg.id);
155
- if (!pending) return;
156
- _pending.delete(msg.id);
157
- if (msg.type === "result") try {
158
- deliverPluginData(msg.data, pending.callbacks);
159
- pending.resolve(msg.data.markdown || "");
160
- } catch (error) {
161
- pending.reject(error);
162
- }
163
- else pending.reject(new Error(msg.message));
164
- }
165
- }
166
- function initWorker(wasmUrl) {
167
- if (_ready) return _ready;
168
- _ready = new Promise((resolve, reject) => {
169
- const blob = getWorkerBlob(wasmUrl);
170
- const url = URL.createObjectURL(blob);
171
- _worker = new Worker(url, { type: "module" });
172
- _worker.onmessage = (e) => {
173
- if (e.data.type === "ready") {
174
- _worker.onmessage = onMessage;
175
- URL.revokeObjectURL(url);
176
- resolve();
177
- } else if (e.data.type === "error") reject(new Error(e.data.message));
178
- };
179
- _worker.onerror = (e) => {
180
- reject(/* @__PURE__ */ new Error(`Worker error: ${e.message}`));
181
- };
182
- });
183
- return _ready;
184
- }
185
- function htmlToMarkdown(html, options) {
186
- if (!_worker || !_ready) return Promise.reject(/* @__PURE__ */ new Error("Call initWorker() before htmlToMarkdown()"));
187
- return _ready.then(() => {
188
- const { napiOpts, frontmatterCallback, extractionHandlers } = resolveOptions(options ?? {});
189
- const id = _idCounter++;
190
- return new Promise((resolve, reject) => {
191
- _pending.set(id, {
192
- resolve,
193
- reject,
194
- callbacks: {
195
- frontmatterCallback,
196
- extractionHandlers
197
- }
198
- });
199
- _worker.postMessage({
200
- id,
201
- type: "convert",
202
- html,
203
- options: napiOpts
204
- });
205
- });
206
- });
207
- }
208
- function terminateWorker() {
209
- if (_worker) {
210
- _worker.terminate();
211
- _worker = null;
212
- }
213
- _ready = null;
214
- for (const [, pending] of _pending) pending.reject(/* @__PURE__ */ new Error("Worker terminated"));
215
- _pending.clear();
216
- }
217
- export { htmlToMarkdown, initWorker, terminateWorker };