@stream-markdown/mermaid 0.7.2

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/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Jing Haihan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,68 @@
1
+ import { MaybeGetter, SharedCdnOptions } from "@stream-markdown/core";
2
+ import * as _$beautiful_mermaid0 from "beautiful-mermaid";
3
+ import { RenderOptions, ThemeName } from "beautiful-mermaid";
4
+ import * as _$mermaid from "mermaid";
5
+ import { MermaidConfig } from "mermaid";
6
+
7
+ //#region src/types.d.ts
8
+ type MermaidRendererType = 'beautiful' | 'vanilla';
9
+ interface MermaidRenderResult {
10
+ svg?: string;
11
+ error?: string;
12
+ valid: boolean;
13
+ }
14
+ interface MermaidParseResult {
15
+ valid: boolean;
16
+ error?: string;
17
+ }
18
+ interface MermaidRuntimeOptions {
19
+ renderer?: MaybeGetter<MermaidRendererType | undefined>;
20
+ theme?: MaybeGetter<[string, string] | undefined>;
21
+ beautifulTheme?: MaybeGetter<[ThemeName, ThemeName] | undefined>;
22
+ config?: MaybeGetter<MermaidConfig | undefined>;
23
+ beautifulConfig?: MaybeGetter<RenderOptions | undefined>;
24
+ cdnOptions?: MaybeGetter<SharedCdnOptions | undefined>;
25
+ isDark?: MaybeGetter<boolean | undefined>;
26
+ getThemeColors?: () => Promise<Record<string, string> | null>;
27
+ }
28
+ interface MermaidRuntime {
29
+ installed: Promise<boolean>;
30
+ preload: () => Promise<void>;
31
+ load: () => Promise<void>;
32
+ dispose: () => void;
33
+ parse: (code: string) => Promise<MermaidParseResult>;
34
+ render: (code: string) => Promise<MermaidRenderResult>;
35
+ save: (format: 'svg' | 'png', code: string) => Promise<void>;
36
+ }
37
+ //#endregion
38
+ //#region src/beautiful-cdn.d.ts
39
+ interface BeautifulMermaidCdnLoaderOptions {
40
+ cdnOptions?: MaybeGetter<SharedCdnOptions | undefined>;
41
+ }
42
+ declare function createBeautifulMermaidCdnLoader(options?: BeautifulMermaidCdnLoaderOptions): {
43
+ getCdnUrl: () => string | undefined;
44
+ loadCdn: () => Promise<typeof _$beautiful_mermaid0 | undefined>;
45
+ };
46
+ //#endregion
47
+ //#region src/constants.d.ts
48
+ declare const MERMAID_VERSION: string;
49
+ declare const BEAUTIFUL_MERMAID_VERSION: string;
50
+ declare const BEAUTIFUL_MERMAID_SUPPORTED_PATTERNS: readonly ['flowchart', 'graph', 'stateDiagram', 'sequence', 'classDiagram', 'erDiagram', 'xychart'];
51
+ declare const DEFAULT_MERMAID_THEME: readonly ['neutral', 'dark'];
52
+ declare const PRESET_BEAUTIFUL_MERMAID_CONFIG: RenderOptions;
53
+ declare const DEFAULT_BEAUTIFUL_MERMAID_THEME: [ThemeName, ThemeName];
54
+ //#endregion
55
+ //#region src/mermaid-cdn.d.ts
56
+ interface MermaidCdnLoaderOptions {
57
+ cdnOptions?: MaybeGetter<SharedCdnOptions | undefined>;
58
+ }
59
+ declare function createMermaidCdnLoader(options?: MermaidCdnLoaderOptions): {
60
+ getCdnUrl: () => string | undefined;
61
+ loadCdn: () => Promise<typeof _$mermaid | undefined>;
62
+ };
63
+ //#endregion
64
+ //#region src/runtime.d.ts
65
+ declare function resolveMermaidRendererType(options?: Pick<MermaidRuntimeOptions, 'renderer' | 'cdnOptions'>, hasBeautifulModule?: () => Promise<boolean>): Promise<MermaidRendererType>;
66
+ declare function createMermaidRuntime(options?: MermaidRuntimeOptions): MermaidRuntime;
67
+ //#endregion
68
+ export { BEAUTIFUL_MERMAID_SUPPORTED_PATTERNS, BEAUTIFUL_MERMAID_VERSION, BeautifulMermaidCdnLoaderOptions, DEFAULT_BEAUTIFUL_MERMAID_THEME, DEFAULT_MERMAID_THEME, MERMAID_VERSION, type MaybeGetter, MermaidCdnLoaderOptions, MermaidParseResult, MermaidRenderResult, MermaidRendererType, MermaidRuntime, MermaidRuntimeOptions, PRESET_BEAUTIFUL_MERMAID_CONFIG, createBeautifulMermaidCdnLoader, createMermaidCdnLoader, createMermaidRuntime, resolveMermaidRendererType };
package/dist/index.mjs ADDED
@@ -0,0 +1,365 @@
1
+ import { dynamicImport, getModuleFromImport, getModuleStrategy, isClient, isModuleEnabled, isSupportESM, removeTrailingSlash, resolveGetter, save, stripVersionRangePrefix, svgToPngBlob } from "@stream-markdown/core";
2
+ import { randomStr } from "@antfu/utils";
3
+ //#region package.json
4
+ var dependencies = {
5
+ "@antfu/utils": "catalog:inlined",
6
+ "@stream-markdown/core": "workspace:*",
7
+ "beautiful-mermaid": "^1.1.3",
8
+ "mermaid": "^11.13.0"
9
+ };
10
+ //#endregion
11
+ //#region src/constants.ts
12
+ const MERMAID_VERSION = stripVersionRangePrefix(dependencies.mermaid);
13
+ const BEAUTIFUL_MERMAID_VERSION = stripVersionRangePrefix(dependencies["beautiful-mermaid"]);
14
+ const BEAUTIFUL_MERMAID_SUPPORTED_PATTERNS = [
15
+ "flowchart",
16
+ "graph",
17
+ "stateDiagram",
18
+ "sequence",
19
+ "classDiagram",
20
+ "erDiagram",
21
+ "xychart"
22
+ ];
23
+ const DEFAULT_MERMAID_THEME = ["neutral", "dark"];
24
+ const PRESET_BEAUTIFUL_MERMAID_CONFIG = { padding: 8 };
25
+ const DEFAULT_BEAUTIFUL_MERMAID_THEME = ["github-light", "github-dark"];
26
+ //#endregion
27
+ //#region src/beautiful-cdn.ts
28
+ let beautifulMermaidModule = null;
29
+ function createBeautifulMermaidCdnLoader(options) {
30
+ function getCdnUrl() {
31
+ const cdnOptions = resolveGetter(options?.cdnOptions);
32
+ const enabled = isModuleEnabled(cdnOptions?.beautifulMermaid);
33
+ const strategy = getModuleStrategy(cdnOptions?.beautifulMermaid);
34
+ const baseUrl = cdnOptions?.baseUrl ? removeTrailingSlash(cdnOptions.baseUrl) : "";
35
+ const customGetter = !!cdnOptions?.getUrl;
36
+ if (!enabled) return void 0;
37
+ if (!baseUrl && !customGetter) return void 0;
38
+ if (customGetter) {
39
+ const url = cdnOptions?.getUrl?.("beautiful-mermaid", BEAUTIFUL_MERMAID_VERSION);
40
+ if (url) return url;
41
+ }
42
+ const umd = `${baseUrl}/beautiful-mermaid@${BEAUTIFUL_MERMAID_VERSION}/dist/beautiful-mermaid.browser.global.min.js`;
43
+ if (strategy === "umd") return umd;
44
+ return isSupportESM() ? `${baseUrl}/beautiful-mermaid@${BEAUTIFUL_MERMAID_VERSION}/+esm` : umd;
45
+ }
46
+ async function loadCdn() {
47
+ if (beautifulMermaidModule) return beautifulMermaidModule;
48
+ const url = getCdnUrl();
49
+ if (!url) return void 0;
50
+ const module = await dynamicImport(url);
51
+ beautifulMermaidModule = getModuleFromImport(module, "beautifulMermaid");
52
+ return beautifulMermaidModule ?? module;
53
+ }
54
+ return {
55
+ getCdnUrl,
56
+ loadCdn
57
+ };
58
+ }
59
+ //#endregion
60
+ //#region src/mermaid-cdn.ts
61
+ let mermaidModule = null;
62
+ function createMermaidCdnLoader(options) {
63
+ function getCdnUrl() {
64
+ const cdnOptions = resolveGetter(options?.cdnOptions);
65
+ const enabled = isModuleEnabled(cdnOptions?.mermaid);
66
+ const strategy = getModuleStrategy(cdnOptions?.mermaid);
67
+ const baseUrl = cdnOptions?.baseUrl ? removeTrailingSlash(cdnOptions.baseUrl) : "";
68
+ const customGetter = !!cdnOptions?.getUrl;
69
+ if (!enabled) return void 0;
70
+ if (!baseUrl && !customGetter) return void 0;
71
+ if (customGetter) {
72
+ const url = cdnOptions?.getUrl?.("mermaid", MERMAID_VERSION);
73
+ if (url) return url;
74
+ }
75
+ const umd = `${baseUrl}/mermaid@${MERMAID_VERSION}/dist/mermaid.min.js`;
76
+ if (strategy === "umd") return umd;
77
+ return isSupportESM() ? `${baseUrl}/mermaid@${MERMAID_VERSION}/+esm` : umd;
78
+ }
79
+ async function loadCdn() {
80
+ if (mermaidModule) return mermaidModule;
81
+ const url = getCdnUrl();
82
+ if (!url) return void 0;
83
+ const module = await dynamicImport(url);
84
+ mermaidModule = getModuleFromImport(module, "mermaid");
85
+ return mermaidModule ?? module;
86
+ }
87
+ return {
88
+ getCdnUrl,
89
+ loadCdn
90
+ };
91
+ }
92
+ //#endregion
93
+ //#region src/runtime/base.ts
94
+ var MermaidRenderer = class {
95
+ options;
96
+ loaded = false;
97
+ constructor(options = {}) {
98
+ this.options = options;
99
+ }
100
+ isLoaded() {
101
+ return this.loaded;
102
+ }
103
+ async ensureLoaded() {
104
+ if (!this.loaded) {
105
+ await this.load();
106
+ this.loaded = true;
107
+ }
108
+ }
109
+ toError(error) {
110
+ return error instanceof Error ? error.message : String(error);
111
+ }
112
+ };
113
+ //#endregion
114
+ //#region src/runtime/vanilla.ts
115
+ async function hasBundledMermaidModule() {
116
+ try {
117
+ await import("mermaid");
118
+ return true;
119
+ } catch {
120
+ return false;
121
+ }
122
+ }
123
+ var VanillaMermaidRenderer = class extends MermaidRenderer {
124
+ mermaid = null;
125
+ get currentTheme() {
126
+ const [light, dark] = resolveGetter(this.options.theme) ?? DEFAULT_MERMAID_THEME;
127
+ return resolveGetter(this.options.isDark) ? dark : light;
128
+ }
129
+ wrapThemeCode(code) {
130
+ if (code.startsWith("%%{")) return code;
131
+ return `%%{init: {"theme": "${this.currentTheme}"}}%%\n${code}`;
132
+ }
133
+ async load() {
134
+ if (this.mermaid) return;
135
+ const cdnLoader = createMermaidCdnLoader({ cdnOptions: this.options.cdnOptions });
136
+ if (!(cdnLoader.getCdnUrl() ? true : await hasBundledMermaidModule())) throw new Error("Mermaid module is not available");
137
+ const module = (await cdnLoader.loadCdn() ?? await import("mermaid")).default;
138
+ module.initialize({
139
+ startOnLoad: false,
140
+ securityLevel: "loose",
141
+ ...resolveGetter(this.options.config) ?? {}
142
+ });
143
+ this.mermaid = module;
144
+ }
145
+ isSupported() {
146
+ return true;
147
+ }
148
+ async parse(code) {
149
+ try {
150
+ await this.ensureLoaded();
151
+ await this.mermaid.parse(this.wrapThemeCode(code));
152
+ return { valid: true };
153
+ } catch (error) {
154
+ return {
155
+ valid: false,
156
+ error: this.toError(error)
157
+ };
158
+ }
159
+ }
160
+ async render(code) {
161
+ const parseResult = await this.parse(code);
162
+ if (!parseResult.valid || !isClient()) return {
163
+ error: parseResult.error,
164
+ valid: false
165
+ };
166
+ const id = `mermaid-${randomStr()}`;
167
+ try {
168
+ return {
169
+ svg: (await this.mermaid.render(id, this.wrapThemeCode(code))).svg,
170
+ valid: true
171
+ };
172
+ } catch (error) {
173
+ document.getElementById(`d${id}`)?.remove();
174
+ return {
175
+ valid: false,
176
+ error: this.toError(error)
177
+ };
178
+ }
179
+ }
180
+ async isEnabled() {
181
+ const cdnLoader = createMermaidCdnLoader({ cdnOptions: this.options.cdnOptions });
182
+ try {
183
+ if (await hasBundledMermaidModule()) return true;
184
+ return !!cdnLoader.getCdnUrl();
185
+ } catch {
186
+ return false;
187
+ }
188
+ }
189
+ };
190
+ //#endregion
191
+ //#region src/runtime/beautiful.ts
192
+ const DIAGRAM_TYPE_PATTERN = new RegExp(`^(${BEAUTIFUL_MERMAID_SUPPORTED_PATTERNS.join("|")})`);
193
+ async function hasBundledBeautifulMermaidModule$1() {
194
+ try {
195
+ await import("beautiful-mermaid");
196
+ return true;
197
+ } catch {
198
+ return false;
199
+ }
200
+ }
201
+ function extractDiagramType(code) {
202
+ const lines = code.trim().split("\n");
203
+ for (const line of lines) {
204
+ const trimmed = line.trim();
205
+ if (trimmed && !trimmed.startsWith("%%")) return trimmed.match(DIAGRAM_TYPE_PATTERN)?.[1] ?? "unknown";
206
+ }
207
+ return "unknown";
208
+ }
209
+ function mightBeSupported(diagramType) {
210
+ return BEAUTIFUL_MERMAID_SUPPORTED_PATTERNS.some((pattern) => diagramType.startsWith(pattern));
211
+ }
212
+ var BeautifulMermaidRenderer = class extends MermaidRenderer {
213
+ beautifulMermaid = null;
214
+ vanillaRenderer = null;
215
+ getVanillaRenderer() {
216
+ if (!this.vanillaRenderer) this.vanillaRenderer = new VanillaMermaidRenderer(this.options);
217
+ return this.vanillaRenderer;
218
+ }
219
+ get currentTheme() {
220
+ const [light, dark] = resolveGetter(this.options.beautifulTheme) ?? DEFAULT_BEAUTIFUL_MERMAID_THEME;
221
+ return resolveGetter(this.options.isDark) ? dark : light;
222
+ }
223
+ get mergedOptions() {
224
+ return {
225
+ ...PRESET_BEAUTIFUL_MERMAID_CONFIG,
226
+ ...resolveGetter(this.options.beautifulConfig) ?? {}
227
+ };
228
+ }
229
+ async getRenderOptions() {
230
+ const presetOptions = this.beautifulMermaid?.THEMES[this.currentTheme];
231
+ if (presetOptions) return {
232
+ ...presetOptions,
233
+ ...this.mergedOptions
234
+ };
235
+ const colors = await this.options.getThemeColors?.();
236
+ return colors ? {
237
+ ...colors,
238
+ ...this.mergedOptions
239
+ } : this.mergedOptions;
240
+ }
241
+ async load() {
242
+ if (this.beautifulMermaid) return;
243
+ const cdnLoader = createBeautifulMermaidCdnLoader({ cdnOptions: this.options.cdnOptions });
244
+ this.beautifulMermaid = await cdnLoader.loadCdn() ?? await import("beautiful-mermaid");
245
+ }
246
+ isSupported(diagramType) {
247
+ return mightBeSupported(diagramType);
248
+ }
249
+ async parse(code) {
250
+ if (!mightBeSupported(extractDiagramType(code))) return this.getVanillaRenderer().parse(code);
251
+ try {
252
+ await this.ensureLoaded();
253
+ return { valid: true };
254
+ } catch (error) {
255
+ return {
256
+ valid: false,
257
+ error: this.toError(error)
258
+ };
259
+ }
260
+ }
261
+ async render(code) {
262
+ if (!mightBeSupported(extractDiagramType(code))) return this.getVanillaRenderer().render(code);
263
+ try {
264
+ await this.ensureLoaded();
265
+ const renderOptions = await this.getRenderOptions();
266
+ return {
267
+ svg: await this.beautifulMermaid.renderMermaidSVGAsync(code, renderOptions),
268
+ valid: true
269
+ };
270
+ } catch (error) {
271
+ return {
272
+ valid: false,
273
+ error: this.toError(error)
274
+ };
275
+ }
276
+ }
277
+ async isEnabled() {
278
+ const cdnLoader = createBeautifulMermaidCdnLoader({ cdnOptions: this.options.cdnOptions });
279
+ try {
280
+ if (await hasBundledBeautifulMermaidModule$1()) return true;
281
+ return !!cdnLoader.getCdnUrl();
282
+ } catch {
283
+ return false;
284
+ }
285
+ }
286
+ };
287
+ //#endregion
288
+ //#region src/runtime.ts
289
+ async function hasBundledBeautifulMermaidModule() {
290
+ try {
291
+ await import("beautiful-mermaid");
292
+ return true;
293
+ } catch {
294
+ return false;
295
+ }
296
+ }
297
+ async function resolveMermaidRendererType(options = {}, hasBeautifulModule = hasBundledBeautifulMermaidModule) {
298
+ const cdnLoader = createBeautifulMermaidCdnLoader({ cdnOptions: options.cdnOptions });
299
+ const renderer = resolveGetter(options.renderer);
300
+ if (renderer === "beautiful") return "beautiful";
301
+ if (renderer === "vanilla") return "vanilla";
302
+ if (cdnLoader.getCdnUrl()) return "beautiful";
303
+ return await hasBeautifulModule() ? "beautiful" : "vanilla";
304
+ }
305
+ function createMermaidRuntime(options = {}) {
306
+ let beautifulRenderer = null;
307
+ let vanillaRenderer = null;
308
+ let activeRenderer = null;
309
+ let activeRendererType = null;
310
+ const createRenderer = (rendererType) => {
311
+ if (rendererType === "beautiful") {
312
+ if (!beautifulRenderer) beautifulRenderer = new BeautifulMermaidRenderer(options);
313
+ return beautifulRenderer;
314
+ }
315
+ if (!vanillaRenderer) vanillaRenderer = new VanillaMermaidRenderer(options);
316
+ return vanillaRenderer;
317
+ };
318
+ const getRenderer = async () => {
319
+ const rendererType = await resolveMermaidRendererType(options);
320
+ if (activeRenderer && activeRendererType === rendererType) return activeRenderer;
321
+ const renderer = createRenderer(rendererType);
322
+ activeRenderer = renderer;
323
+ activeRendererType = rendererType;
324
+ return renderer;
325
+ };
326
+ async function load() {
327
+ await (await getRenderer()).load();
328
+ }
329
+ async function parse(code) {
330
+ return await (await getRenderer()).parse(code);
331
+ }
332
+ async function render(code) {
333
+ return await (await getRenderer()).render(code);
334
+ }
335
+ async function saveDiagram(format, code) {
336
+ const { svg } = await render(code);
337
+ if (!svg) throw new Error("SVG not found. Please wait for the diagram to render.");
338
+ if (format === "svg") {
339
+ save("diagram.svg", svg, "image/svg+xml");
340
+ return;
341
+ }
342
+ const blob = await svgToPngBlob(svg);
343
+ if (!blob) throw new Error("Failed to export PNG image");
344
+ save("diagram.png", blob, "image/png");
345
+ }
346
+ async function preload() {
347
+ const renderer = await getRenderer();
348
+ if (!await renderer.isEnabled()) return;
349
+ if (!renderer.isLoaded()) await renderer.load();
350
+ }
351
+ return {
352
+ installed: getRenderer().then((renderer) => renderer.isEnabled()),
353
+ preload,
354
+ load,
355
+ dispose() {
356
+ activeRenderer = null;
357
+ activeRendererType = null;
358
+ },
359
+ parse,
360
+ render,
361
+ save: saveDiagram
362
+ };
363
+ }
364
+ //#endregion
365
+ export { BEAUTIFUL_MERMAID_SUPPORTED_PATTERNS, BEAUTIFUL_MERMAID_VERSION, DEFAULT_BEAUTIFUL_MERMAID_THEME, DEFAULT_MERMAID_THEME, MERMAID_VERSION, PRESET_BEAUTIFUL_MERMAID_CONFIG, createBeautifulMermaidCdnLoader, createMermaidCdnLoader, createMermaidRuntime, resolveMermaidRendererType };
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@stream-markdown/mermaid",
3
+ "type": "module",
4
+ "version": "0.7.2",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "exports": {
9
+ ".": "./dist/index.mjs",
10
+ "./package.json": "./package.json"
11
+ },
12
+ "types": "./dist/index.d.mts",
13
+ "files": [
14
+ "dist"
15
+ ],
16
+ "dependencies": {
17
+ "@antfu/utils": "^9.3.0",
18
+ "beautiful-mermaid": "^1.1.3",
19
+ "mermaid": "^11.13.0",
20
+ "@stream-markdown/core": "0.7.2"
21
+ },
22
+ "devDependencies": {
23
+ "tsdown": "^0.21.10"
24
+ },
25
+ "scripts": {
26
+ "build": "tsdown"
27
+ }
28
+ }