astro-dgmo 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Demian Neidetcher
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.
package/README.md ADDED
@@ -0,0 +1,169 @@
1
+ # astro-dgmo
2
+
3
+ Render [DGMO](https://diagrammo.app) diagrams from fenced code blocks in your Astro site at build time. Powered by [`@diagrammo/dgmo`](https://www.npmjs.com/package/@diagrammo/dgmo). Zero client JavaScript by default.
4
+
5
+ ```dgmo
6
+ chart: sequence
7
+ Client -POST /login-> API
8
+ API -validate-> Auth
9
+ Auth -JWT-> API
10
+ API -200 OK-> Client
11
+ ```
12
+
13
+ …in any `.md` or `.mdx` file becomes a beautifully rendered SVG, inlined into the page.
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ pnpm add astro-dgmo @diagrammo/dgmo
19
+ # or
20
+ npm install astro-dgmo @diagrammo/dgmo
21
+ ```
22
+
23
+ `@diagrammo/dgmo` is a peer dependency.
24
+
25
+ ## Use
26
+
27
+ Add the integration to `astro.config.mjs`:
28
+
29
+ ```js
30
+ import { defineConfig } from 'astro/config';
31
+ import dgmo from 'astro-dgmo';
32
+
33
+ export default defineConfig({
34
+ integrations: [dgmo()],
35
+ });
36
+ ```
37
+
38
+ That's it. Anywhere in your Markdown or MDX content, write a fenced block with the language `dgmo`:
39
+
40
+ ````markdown
41
+ ```dgmo
42
+ chart: pie
43
+ TypeScript: 45
44
+ Python: 30
45
+ Rust: 25
46
+ ```
47
+ ````
48
+
49
+ At build time, the block is replaced with an inline `<svg>` wrapped in a `<figure class="astro-dgmo astro-dgmo--diagram">`. No client JavaScript is shipped unless you opt into showcase mode.
50
+
51
+ ## Options
52
+
53
+ ```js
54
+ dgmo({
55
+ // Output mode for `dgmo` blocks. 'diagram' (default) renders just the SVG.
56
+ // 'showcase' renders syntax-highlighted source + diagram + copy + open-in-editor.
57
+ mode: 'diagram',
58
+
59
+ // Defaults for the `render()` call from @diagrammo/dgmo.
60
+ palette: 'nord', // any registered palette
61
+ theme: 'dark', // 'light' | 'dark' | 'transparent'
62
+
63
+ // Showcase chrome — enabled automatically in showcase mode.
64
+ showSource: undefined, // boolean; default = (mode === 'showcase')
65
+ showCopy: undefined, // boolean; default = (mode === 'showcase')
66
+ showOpenInEditor: undefined, // boolean; default = (mode === 'showcase')
67
+
68
+ // Where the "Open in editor" link points.
69
+ editorBaseUrl: 'https://online.diagrammo.app',
70
+
71
+ // Outer wrapper element + class hook.
72
+ wrapper: 'figure', // 'figure' | 'div'
73
+ className: 'astro-dgmo',
74
+ });
75
+ ```
76
+
77
+ ## Per-block overrides
78
+
79
+ Append options to the fence info string. Tokens are space-separated; values may be quoted.
80
+
81
+ ````markdown
82
+ ```dgmo showcase title="Login flow" palette=catppuccin theme=light
83
+ chart: sequence
84
+ A -> B
85
+ ```
86
+ ````
87
+
88
+ Recognized tokens:
89
+
90
+ | Token | Effect |
91
+ |---|---|
92
+ | `diagram` / `showcase` | Set `mode` for this block |
93
+ | `palette=<name>` | Override palette |
94
+ | `theme=light` / `theme=dark` / `theme=transparent` | Override theme |
95
+ | `title="…"` | Add a caption (`<figcaption>`) |
96
+ | `source` / `noSource` | Force source listing on/off |
97
+ | `copy` / `noCopy` | Force copy button on/off |
98
+ | `openInEditor` / `noOpenInEditor` | Force editor link on/off |
99
+
100
+ ## Showcase mode
101
+
102
+ For docs sites and tutorials where you want the source visible alongside the rendered diagram (with copy and "Open in online editor" affordances), set `mode: 'showcase'` globally — every `dgmo` block becomes a rich showcase:
103
+
104
+ ```js
105
+ dgmo({ mode: 'showcase' });
106
+ ```
107
+
108
+ Or opt-in per block:
109
+
110
+ ````markdown
111
+ ```dgmo showcase
112
+ chart: kanban
113
+ Backlog: Item 1, Item 2
114
+ Doing: Item 3
115
+ Done: Item 4
116
+ ```
117
+ ````
118
+
119
+ ## Styling
120
+
121
+ The plugin emits semantic class names and inline syntax-highlight styles only. Bring your own CSS to skin the showcase chrome — recommended hooks:
122
+
123
+ ```css
124
+ .astro-dgmo { /* outer wrapper */ }
125
+ .astro-dgmo--diagram { /* simple mode */ }
126
+ .astro-dgmo--showcase { /* showcase mode */ }
127
+ .astro-dgmo-caption { /* title/caption */ }
128
+ .astro-dgmo-svg { /* svg container */ }
129
+ .astro-dgmo-card { /* showcase card */ }
130
+ .astro-dgmo-source-wrap, .astro-dgmo-source-inner { /* source block */ }
131
+ .astro-dgmo-toolbar { /* "dgmo" label + open link */ }
132
+ .astro-dgmo-toolbar-label { /* "dgmo" tag */ }
133
+ .astro-dgmo-open-link { /* "Open in online editor" link */ }
134
+ .astro-dgmo-pre, .astro-dgmo-code { /* highlighted source */ }
135
+ .astro-dgmo-copy { /* copy button */ }
136
+ .astro-dgmo-copy--success { /* copy button after a successful copy */ }
137
+ ```
138
+
139
+ The SVG output also includes a small inline script (~600 bytes) that tightens each diagram's `viewBox` to its content bounds and wires up copy buttons. If your site forbids inline scripts via CSP, ignore this script — diagrams still render, but layout may have extra whitespace and copy buttons won't function.
140
+
141
+ ## Direct remark plugin
142
+
143
+ For fine-grained control (or to use outside Astro), import the remark plugin directly:
144
+
145
+ ```js
146
+ import remarkDgmo from 'astro-dgmo/remark';
147
+
148
+ // e.g. in any remark/rehype pipeline:
149
+ unified()
150
+ .use(remarkParse)
151
+ .use(remarkDgmo, { mode: 'showcase', palette: 'dracula' })
152
+ .use(remarkRehype)
153
+ .use(rehypeStringify)
154
+ .process(source);
155
+ ```
156
+
157
+ ## How it works
158
+
159
+ 1. The Astro integration registers a remark plugin via `astro:config:setup`.
160
+ 2. The remark plugin walks `.md`/`.mdx` ASTs after parse, finding `code` nodes whose `lang === 'dgmo'`.
161
+ 3. Each block is rendered to an SVG string by calling `render()` from `@diagrammo/dgmo`. SVG width/height are stripped and a `viewBox` is added so the diagram scales responsively.
162
+ 4. The original `code` node is replaced with an `html` node containing the rendered output.
163
+ 5. A small inline page script tightens viewBoxes to actual content bounds and binds copy-button click handlers.
164
+
165
+ All rendering happens at build time. No diagram source is shipped to the browser unless you enable showcase mode (which inlines a syntax-highlighted copy of the source for display).
166
+
167
+ ## License
168
+
169
+ MIT
@@ -0,0 +1,261 @@
1
+ // src/remark-plugin.ts
2
+ import { visit } from "unist-util-visit";
3
+
4
+ // src/render-block.ts
5
+ import { render, encodeDiagramUrl } from "@diagrammo/dgmo";
6
+ import { highlightDgmo, NORD_ROLE_STYLES } from "@diagrammo/dgmo/highlight";
7
+
8
+ // src/options.ts
9
+ function resolveOptions(opts = {}) {
10
+ const mode = opts.mode ?? "diagram";
11
+ const showcase = mode === "showcase";
12
+ return {
13
+ mode,
14
+ palette: opts.palette ?? "nord",
15
+ theme: opts.theme ?? "dark",
16
+ showSource: opts.showSource ?? showcase,
17
+ showCopy: opts.showCopy ?? showcase,
18
+ showOpenInEditor: opts.showOpenInEditor ?? showcase,
19
+ editorBaseUrl: opts.editorBaseUrl ?? "https://online.diagrammo.app",
20
+ wrapper: opts.wrapper ?? "figure",
21
+ className: opts.className ?? "astro-dgmo"
22
+ };
23
+ }
24
+
25
+ // src/fence-meta.ts
26
+ var BARE_FLAGS = {
27
+ diagram: { mode: "diagram" },
28
+ showcase: { mode: "showcase" },
29
+ noSource: { showSource: false },
30
+ source: { showSource: true },
31
+ noCopy: { showCopy: false },
32
+ copy: { showCopy: true },
33
+ noOpenInEditor: { showOpenInEditor: false },
34
+ openInEditor: { showOpenInEditor: true }
35
+ };
36
+ var VALID_THEMES = /* @__PURE__ */ new Set(["light", "dark", "transparent"]);
37
+ function parseFenceMeta(meta) {
38
+ if (!meta) return {};
39
+ const out = {};
40
+ const tokens = tokenize(meta);
41
+ for (const tok of tokens) {
42
+ if (BARE_FLAGS[tok]) {
43
+ Object.assign(out, BARE_FLAGS[tok]);
44
+ continue;
45
+ }
46
+ const eq = tok.indexOf("=");
47
+ if (eq < 0) continue;
48
+ const key = tok.slice(0, eq).trim();
49
+ const rawVal = tok.slice(eq + 1).trim();
50
+ const val = unquote(rawVal);
51
+ switch (key) {
52
+ case "palette":
53
+ if (val) out.palette = val;
54
+ break;
55
+ case "theme":
56
+ if (VALID_THEMES.has(val)) out.theme = val;
57
+ break;
58
+ case "mode":
59
+ if (val === "diagram" || val === "showcase") out.mode = val;
60
+ break;
61
+ case "showSource":
62
+ out.showSource = parseBool(val);
63
+ break;
64
+ case "showCopy":
65
+ out.showCopy = parseBool(val);
66
+ break;
67
+ case "showOpenInEditor":
68
+ out.showOpenInEditor = parseBool(val);
69
+ break;
70
+ case "title":
71
+ if (val) out.title = val;
72
+ break;
73
+ }
74
+ }
75
+ return out;
76
+ }
77
+ function parseBool(s) {
78
+ return s === "true" || s === "1" || s === "yes";
79
+ }
80
+ function unquote(s) {
81
+ if (s.length >= 2 && s.startsWith('"') && s.endsWith('"')) {
82
+ return s.slice(1, -1);
83
+ }
84
+ return s;
85
+ }
86
+ function tokenize(input) {
87
+ const out = [];
88
+ let buf = "";
89
+ let inQuotes = false;
90
+ for (let i = 0; i < input.length; i++) {
91
+ const ch = input[i];
92
+ if (ch === '"') {
93
+ inQuotes = !inQuotes;
94
+ buf += ch;
95
+ continue;
96
+ }
97
+ if (!inQuotes && /\s/.test(ch)) {
98
+ if (buf) {
99
+ out.push(buf);
100
+ buf = "";
101
+ }
102
+ continue;
103
+ }
104
+ buf += ch;
105
+ }
106
+ if (buf) out.push(buf);
107
+ return out;
108
+ }
109
+
110
+ // src/svg-normalize.ts
111
+ function normalizeSvg(input) {
112
+ let svg = input;
113
+ const rootMatch = svg.match(/<svg[^>]*>/);
114
+ const rootTag = rootMatch?.[0] ?? "";
115
+ if (rootTag && !rootTag.includes("viewBox")) {
116
+ const wh = rootTag.match(/width="(\d+)"[^>]*height="(\d+)"/);
117
+ if (wh) {
118
+ svg = svg.replace(/<svg/, `<svg viewBox="0 0 ${wh[1]} ${wh[2]}"`);
119
+ }
120
+ }
121
+ svg = svg.replace(/(<svg[^>]*?) width="[^"]*"/g, "$1");
122
+ svg = svg.replace(/(<svg[^>]*?) height="[^"]*"/g, "$1");
123
+ svg = svg.replace(/(<svg[^>]*?style="[^"]*?)background:[^;"]*;?\s*/g, "$1");
124
+ svg = svg.replace(/<svg\s{2,}/g, "<svg ");
125
+ return svg;
126
+ }
127
+
128
+ // src/escape.ts
129
+ var HTML_ENTITIES = {
130
+ "&": "&amp;",
131
+ "<": "&lt;",
132
+ ">": "&gt;",
133
+ '"': "&quot;",
134
+ "'": "&#39;"
135
+ };
136
+ function escapeHtml(s) {
137
+ return s.replace(/[&<>"']/g, (ch) => HTML_ENTITIES[ch]);
138
+ }
139
+ function escapeAttr(s) {
140
+ return s.replace(/[&<>"']/g, (ch) => HTML_ENTITIES[ch]);
141
+ }
142
+
143
+ // src/render-block.ts
144
+ async function renderDgmoBlock(source, meta, integrationOptions = {}) {
145
+ const block = parseFenceMeta(meta);
146
+ const base = resolveOptions(integrationOptions);
147
+ const effectiveMode = block.mode ?? base.mode;
148
+ const showcase = effectiveMode === "showcase";
149
+ const opts = {
150
+ ...base,
151
+ mode: effectiveMode,
152
+ palette: block.palette ?? base.palette,
153
+ theme: block.theme ?? base.theme,
154
+ showSource: block.showSource ?? (block.mode ? showcase : base.showSource),
155
+ showCopy: block.showCopy ?? (block.mode ? showcase : base.showCopy),
156
+ showOpenInEditor: block.showOpenInEditor ?? (block.mode ? showcase : base.showOpenInEditor)
157
+ };
158
+ const trimmed = source.trim();
159
+ const { svg: rawSvg, diagnostics } = await render(trimmed, {
160
+ palette: opts.palette,
161
+ theme: opts.theme === "transparent" ? "transparent" : opts.theme
162
+ });
163
+ const svg = normalizeSvg(rawSvg);
164
+ let editorUrl;
165
+ if (opts.showOpenInEditor) {
166
+ const encoded = encodeDiagramUrl(trimmed, { baseUrl: opts.editorBaseUrl });
167
+ editorUrl = encoded.url ?? opts.editorBaseUrl;
168
+ }
169
+ const html = opts.mode === "showcase" ? renderShowcase(trimmed, svg, editorUrl, opts, block.title) : renderSimple(svg, opts, block.title);
170
+ return { html, diagnostics };
171
+ }
172
+ function renderSimple(svg, opts, title) {
173
+ const Wrapper = opts.wrapper;
174
+ const captionHtml = title ? `<figcaption class="astro-dgmo-caption">${escapeHtml(title)}</figcaption>` : "";
175
+ const captionFallback = title && Wrapper !== "figure" ? `<div class="astro-dgmo-caption">${escapeHtml(title)}</div>` : "";
176
+ return `<${Wrapper} class="${escapeAttr(opts.className)} astro-dgmo--diagram">` + (Wrapper === "figure" ? captionHtml : captionFallback) + `<div class="astro-dgmo-svg">${svg}</div></${Wrapper}>`;
177
+ }
178
+ function renderShowcase(source, svg, editorUrl, opts, title) {
179
+ const Wrapper = opts.wrapper;
180
+ const captionHtml = title ? Wrapper === "figure" ? `<figcaption class="astro-dgmo-caption">${escapeHtml(title)}</figcaption>` : `<div class="astro-dgmo-caption">${escapeHtml(title)}</div>` : "";
181
+ const sourceHtml = opts.showSource ? renderSource(source) : "";
182
+ const toolbarParts = [];
183
+ toolbarParts.push(
184
+ `<span class="astro-dgmo-toolbar-label">dgmo</span>`
185
+ );
186
+ if (opts.showOpenInEditor && editorUrl) {
187
+ toolbarParts.push(
188
+ `<a href="${escapeAttr(editorUrl)}" target="_blank" rel="noopener noreferrer" class="astro-dgmo-open-link">Open in online editor \u2192</a>`
189
+ );
190
+ }
191
+ const toolbar = opts.showSource ? `<div class="astro-dgmo-toolbar">${toolbarParts.join("")}</div>` : "";
192
+ const copyButton = opts.showCopy && opts.showSource ? `<button type="button" class="astro-dgmo-copy" aria-label="Copy to clipboard" data-astro-dgmo-source="${escapeAttr(source)}">
193
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
194
+ <rect x="5.5" y="5.5" width="8" height="8" rx="1.5"/>
195
+ <path d="M10.5 5.5V3a1.5 1.5 0 0 0-1.5-1.5H3A1.5 1.5 0 0 0 1.5 3v6A1.5 1.5 0 0 0 3 10.5h2.5"/>
196
+ </svg>
197
+ </button>` : "";
198
+ return `<${Wrapper} class="${escapeAttr(opts.className)} astro-dgmo--showcase">` + captionHtml + `<div class="astro-dgmo-card">` + (opts.showSource ? `<div class="astro-dgmo-source-wrap">${toolbar}<div class="astro-dgmo-source-inner">${sourceHtml}${copyButton}</div></div>` : "") + `<div class="astro-dgmo-svg">${svg}</div></div></${Wrapper}>`;
199
+ }
200
+ function renderSource(source) {
201
+ const tokens = highlightDgmo(source);
202
+ const inner = tokens.map((t) => {
203
+ const styles = NORD_ROLE_STYLES[t.role];
204
+ const text = escapeHtml(t.text);
205
+ if (!styles || Object.keys(styles).length === 0) return text;
206
+ const styleStr = Object.entries(styles).map(
207
+ ([k, v]) => `${k.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase())}:${v}`
208
+ ).join(";");
209
+ return `<span style="${escapeAttr(styleStr)}">${text}</span>`;
210
+ }).join("");
211
+ return `<pre class="astro-dgmo-pre"><span class="astro-dgmo-code">${inner}</span></pre>`;
212
+ }
213
+
214
+ // src/remark-plugin.ts
215
+ function remarkDgmo(options = {}) {
216
+ return async function transformer(tree) {
217
+ const targets = [];
218
+ visit(tree, "code", (node, index, parent) => {
219
+ if (node.lang !== "dgmo") return;
220
+ if (!parent || index === void 0) return;
221
+ targets.push({
222
+ parent,
223
+ index,
224
+ payload: { source: node.value, meta: node.meta ?? null }
225
+ });
226
+ });
227
+ if (targets.length === 0) return;
228
+ const rendered = await Promise.all(
229
+ targets.map(
230
+ (t) => renderDgmoBlock(t.payload.source, t.payload.meta, options).catch(
231
+ (err) => ({
232
+ html: errorHtml(err, t.payload.source),
233
+ diagnostics: []
234
+ })
235
+ )
236
+ )
237
+ );
238
+ for (let i = targets.length - 1; i >= 0; i--) {
239
+ const t = targets[i];
240
+ const html = { type: "html", value: rendered[i].html };
241
+ t.parent.children[t.index] = html;
242
+ }
243
+ };
244
+ }
245
+ function errorHtml(err, source) {
246
+ const msg = err instanceof Error ? err.message : "Failed to render dgmo block.";
247
+ const safeMsg = msg.replace(
248
+ /[<>&]/g,
249
+ (ch) => ch === "<" ? "&lt;" : ch === ">" ? "&gt;" : "&amp;"
250
+ );
251
+ const safeSrc = source.replace(
252
+ /[<>&]/g,
253
+ (ch) => ch === "<" ? "&lt;" : ch === ">" ? "&gt;" : "&amp;"
254
+ );
255
+ return `<div class="astro-dgmo astro-dgmo--error" role="alert"><strong>dgmo render error:</strong> ${safeMsg}<pre>${safeSrc}</pre></div>`;
256
+ }
257
+
258
+ export {
259
+ remarkDgmo
260
+ };
261
+ //# sourceMappingURL=chunk-GAAZG3OV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/remark-plugin.ts","../src/render-block.ts","../src/options.ts","../src/fence-meta.ts","../src/svg-normalize.ts","../src/escape.ts"],"sourcesContent":["import { visit } from 'unist-util-visit';\nimport type { Root, Code, Html, Parent } from 'mdast';\nimport { renderDgmoBlock } from './render-block.js';\nimport type { DgmoIntegrationOptions } from './options.js';\n\nexport type RemarkDgmoOptions = DgmoIntegrationOptions;\n\ninterface FencePayload {\n source: string;\n meta: string | null;\n}\n\ninterface Target {\n parent: Parent;\n index: number;\n payload: FencePayload;\n}\n\n/**\n * Remark plugin that finds ```dgmo fenced code blocks and replaces them with\n * an HTML node containing the rendered SVG (and optional showcase chrome).\n *\n * The `lang` field on the code node is the fence language (the word after the\n * backticks). The `meta` field is everything that follows on the same line,\n * which we use to allow per-block options like ```dgmo showcase palette=catppuccin.\n *\n * Replaces the code node entirely (parent.children[index] = newNode) rather\n * than mutating it in place — otherwise downstream rehype/Shiki plugins still\n * see the lingering `lang: 'dgmo'` and `value: '...source...'` properties and\n * may re-process the block as a plaintext code listing, clobbering our\n * syntax-highlighted output.\n *\n * Async-safe: replacement is collected first, applied after parsing finishes.\n */\nexport default function remarkDgmo(options: RemarkDgmoOptions = {}) {\n return async function transformer(tree: Root): Promise<void> {\n const targets: Target[] = [];\n visit(tree, 'code', (node: Code, index, parent) => {\n if (node.lang !== 'dgmo') return;\n if (!parent || index === undefined) return;\n targets.push({\n parent: parent as Parent,\n index,\n payload: { source: node.value, meta: node.meta ?? null },\n });\n });\n if (targets.length === 0) return;\n\n const rendered = await Promise.all(\n targets.map(t =>\n renderDgmoBlock(t.payload.source, t.payload.meta, options).catch(\n err => ({\n html: errorHtml(err, t.payload.source),\n diagnostics: [],\n })\n )\n )\n );\n\n // Replace in reverse index order per parent so earlier replacements don't\n // shift indices of later targets in the same parent. (Visit walks in tree\n // order, so within a single parent's children targets are also ordered;\n // reversing is sufficient.)\n for (let i = targets.length - 1; i >= 0; i--) {\n const t = targets[i];\n const html: Html = { type: 'html', value: rendered[i].html };\n t.parent.children[t.index] = html;\n }\n };\n}\n\nfunction errorHtml(err: unknown, source: string): string {\n const msg =\n err instanceof Error ? err.message : 'Failed to render dgmo block.';\n const safeMsg = msg.replace(/[<>&]/g, ch =>\n ch === '<' ? '&lt;' : ch === '>' ? '&gt;' : '&amp;'\n );\n const safeSrc = source.replace(/[<>&]/g, ch =>\n ch === '<' ? '&lt;' : ch === '>' ? '&gt;' : '&amp;'\n );\n return (\n `<div class=\"astro-dgmo astro-dgmo--error\" role=\"alert\">` +\n `<strong>dgmo render error:</strong> ${safeMsg}` +\n `<pre>${safeSrc}</pre></div>`\n );\n}\n","import { render, encodeDiagramUrl } from '@diagrammo/dgmo';\nimport { highlightDgmo, NORD_ROLE_STYLES } from '@diagrammo/dgmo/highlight';\nimport { resolveOptions, type DgmoIntegrationOptions } from './options.js';\nimport { parseFenceMeta } from './fence-meta.js';\nimport { normalizeSvg } from './svg-normalize.js';\nimport { escapeHtml, escapeAttr } from './escape.js';\n\nexport interface RenderBlockResult {\n html: string;\n diagnostics: Array<{ message: string; line?: number; severity?: string }>;\n}\n\n/**\n * Render a single ```dgmo block to inline HTML. Pure function: takes source +\n * options and returns the HTML string and any diagnostics from the parser.\n *\n * The remark plugin calls this for every matched code node.\n */\nexport async function renderDgmoBlock(\n source: string,\n meta: string | null | undefined,\n integrationOptions: DgmoIntegrationOptions = {}\n): Promise<RenderBlockResult> {\n const block = parseFenceMeta(meta);\n const base = resolveOptions(integrationOptions);\n // Apply per-block overrides on top of integration defaults. If the block\n // changes mode, we re-resolve mode-dependent defaults from that mode unless\n // the block explicitly overrode them too.\n const effectiveMode = block.mode ?? base.mode;\n const showcase = effectiveMode === 'showcase';\n const opts = {\n ...base,\n mode: effectiveMode,\n palette: block.palette ?? base.palette,\n theme: block.theme ?? base.theme,\n showSource:\n block.showSource ??\n (block.mode ? showcase : base.showSource),\n showCopy:\n block.showCopy ??\n (block.mode ? showcase : base.showCopy),\n showOpenInEditor:\n block.showOpenInEditor ??\n (block.mode ? showcase : base.showOpenInEditor),\n };\n\n const trimmed = source.trim();\n const { svg: rawSvg, diagnostics } = await render(trimmed, {\n palette: opts.palette,\n theme: opts.theme === 'transparent' ? 'transparent' : opts.theme,\n });\n const svg = normalizeSvg(rawSvg);\n\n let editorUrl: string | undefined;\n if (opts.showOpenInEditor) {\n const encoded = encodeDiagramUrl(trimmed, { baseUrl: opts.editorBaseUrl });\n editorUrl = encoded.url ?? opts.editorBaseUrl;\n }\n\n const html = opts.mode === 'showcase'\n ? renderShowcase(trimmed, svg, editorUrl, opts, block.title)\n : renderSimple(svg, opts, block.title);\n\n return { html, diagnostics };\n}\n\nfunction renderSimple(\n svg: string,\n opts: { wrapper: 'figure' | 'div'; className: string },\n title?: string\n): string {\n const Wrapper = opts.wrapper;\n const captionHtml = title\n ? `<figcaption class=\"astro-dgmo-caption\">${escapeHtml(title)}</figcaption>`\n : '';\n // For non-figure wrappers we still emit a caption div if a title was given.\n const captionFallback = title && Wrapper !== 'figure'\n ? `<div class=\"astro-dgmo-caption\">${escapeHtml(title)}</div>`\n : '';\n return (\n `<${Wrapper} class=\"${escapeAttr(opts.className)} astro-dgmo--diagram\">` +\n (Wrapper === 'figure' ? captionHtml : captionFallback) +\n `<div class=\"astro-dgmo-svg\">${svg}</div>` +\n `</${Wrapper}>`\n );\n}\n\nfunction renderShowcase(\n source: string,\n svg: string,\n editorUrl: string | undefined,\n opts: {\n wrapper: 'figure' | 'div';\n className: string;\n showSource: boolean;\n showCopy: boolean;\n showOpenInEditor: boolean;\n },\n title?: string\n): string {\n const Wrapper = opts.wrapper;\n const captionHtml = title\n ? Wrapper === 'figure'\n ? `<figcaption class=\"astro-dgmo-caption\">${escapeHtml(title)}</figcaption>`\n : `<div class=\"astro-dgmo-caption\">${escapeHtml(title)}</div>`\n : '';\n\n const sourceHtml = opts.showSource ? renderSource(source) : '';\n\n const toolbarParts: string[] = [];\n toolbarParts.push(\n `<span class=\"astro-dgmo-toolbar-label\">dgmo</span>`\n );\n if (opts.showOpenInEditor && editorUrl) {\n toolbarParts.push(\n `<a href=\"${escapeAttr(editorUrl)}\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"astro-dgmo-open-link\">Open in online editor →</a>`\n );\n }\n const toolbar = opts.showSource\n ? `<div class=\"astro-dgmo-toolbar\">${toolbarParts.join('')}</div>`\n : '';\n\n const copyButton = opts.showCopy && opts.showSource\n ? `<button type=\"button\" class=\"astro-dgmo-copy\" aria-label=\"Copy to clipboard\" data-astro-dgmo-source=\"${escapeAttr(source)}\">\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\">\n <rect x=\"5.5\" y=\"5.5\" width=\"8\" height=\"8\" rx=\"1.5\"/>\n <path d=\"M10.5 5.5V3a1.5 1.5 0 0 0-1.5-1.5H3A1.5 1.5 0 0 0 1.5 3v6A1.5 1.5 0 0 0 3 10.5h2.5\"/>\n </svg>\n </button>`\n : '';\n\n return (\n `<${Wrapper} class=\"${escapeAttr(opts.className)} astro-dgmo--showcase\">` +\n captionHtml +\n `<div class=\"astro-dgmo-card\">` +\n (opts.showSource\n ? `<div class=\"astro-dgmo-source-wrap\">${toolbar}<div class=\"astro-dgmo-source-inner\">${sourceHtml}${copyButton}</div></div>`\n : '') +\n `<div class=\"astro-dgmo-svg\">${svg}</div>` +\n `</div>` +\n `</${Wrapper}>`\n );\n}\n\nfunction renderSource(source: string): string {\n const tokens = highlightDgmo(source);\n const inner = tokens\n .map(t => {\n const styles = NORD_ROLE_STYLES[t.role];\n const text = escapeHtml(t.text);\n if (!styles || Object.keys(styles).length === 0) return text;\n const styleStr = Object.entries(styles)\n .map(\n ([k, v]) =>\n `${k.replace(/[A-Z]/g, m => '-' + m.toLowerCase())}:${v}`\n )\n .join(';');\n return `<span style=\"${escapeAttr(styleStr)}\">${text}</span>`;\n })\n .join('');\n // NOTE: We deliberately use <pre><span> rather than <pre><code> here.\n // Astro's Shiki rehype plugin walks the hast and post-processes any\n // <pre><code> pair (even ones we emit from a remark plugin via raw HTML),\n // which clobbers our pre-rendered highlight spans with a plaintext\n // listing. Using a <span> as the inner element bypasses Shiki's matcher\n // while preserving preformatted-text semantics on the outer <pre>.\n return `<pre class=\"astro-dgmo-pre\"><span class=\"astro-dgmo-code\">${inner}</span></pre>`;\n}\n","export type Mode = 'diagram' | 'showcase';\n\nexport type Theme = 'light' | 'dark' | 'transparent';\n\nexport interface DgmoIntegrationOptions {\n /**\n * Output mode for `dgmo` fenced blocks.\n * - `diagram` (default): render the SVG only, in a `<figure>`.\n * - `showcase`: render syntax-highlighted source + SVG + copy + open-in-editor.\n *\n * Override per-block via the fence info string: ```dgmo showcase\n */\n mode?: Mode;\n\n /** Default palette name. Default: `nord`. */\n palette?: string;\n\n /** Default theme. Default: `dark`. */\n theme?: Theme;\n\n /**\n * Show source code above the diagram. Defaults to `true` in showcase mode,\n * `false` in diagram mode.\n */\n showSource?: boolean;\n\n /**\n * Show a copy-to-clipboard button. Defaults to `true` in showcase mode,\n * `false` in diagram mode.\n */\n showCopy?: boolean;\n\n /**\n * Show an \"Open in online editor\" link. Defaults to `true` in showcase mode,\n * `false` in diagram mode.\n */\n showOpenInEditor?: boolean;\n\n /**\n * Base URL for the \"Open in editor\" link. Default: `https://online.diagrammo.app`.\n * The plugin appends `?dgmo=...` (compressed source) to the base.\n */\n editorBaseUrl?: string;\n\n /**\n * Wrapper element. Default: `figure`.\n */\n wrapper?: 'figure' | 'div';\n\n /**\n * Class added to the outer wrapper. Defaults to `astro-dgmo`.\n * Useful as a styling hook.\n */\n className?: string;\n}\n\nexport type ResolvedOptions = Required<\n Omit<DgmoIntegrationOptions, 'showSource' | 'showCopy' | 'showOpenInEditor'>\n> & {\n showSource: boolean;\n showCopy: boolean;\n showOpenInEditor: boolean;\n};\n\n/**\n * Apply defaults, including mode-dependent defaults for showSource/showCopy/showOpenInEditor.\n */\nexport function resolveOptions(\n opts: DgmoIntegrationOptions = {}\n): ResolvedOptions {\n const mode: Mode = opts.mode ?? 'diagram';\n const showcase = mode === 'showcase';\n return {\n mode,\n palette: opts.palette ?? 'nord',\n theme: opts.theme ?? 'dark',\n showSource: opts.showSource ?? showcase,\n showCopy: opts.showCopy ?? showcase,\n showOpenInEditor: opts.showOpenInEditor ?? showcase,\n editorBaseUrl: opts.editorBaseUrl ?? 'https://online.diagrammo.app',\n wrapper: opts.wrapper ?? 'figure',\n className: opts.className ?? 'astro-dgmo',\n };\n}\n","import type { Mode, Theme } from './options.js';\n\n/**\n * Per-block options that can be set via the fence info string, e.g.\n *\n * ```dgmo showcase palette=catppuccin theme=light title=\"Login flow\"\n *\n * Tokens are space-separated. Boolean tokens are bare words (`showcase`,\n * `diagram`, `noSource`). Key=value pairs use `=`; values may be quoted with\n * double quotes to include spaces.\n */\nexport interface BlockOptions {\n mode?: Mode;\n palette?: string;\n theme?: Theme;\n showSource?: boolean;\n showCopy?: boolean;\n showOpenInEditor?: boolean;\n title?: string;\n}\n\nconst BARE_FLAGS: Record<string, Partial<BlockOptions>> = {\n diagram: { mode: 'diagram' },\n showcase: { mode: 'showcase' },\n noSource: { showSource: false },\n source: { showSource: true },\n noCopy: { showCopy: false },\n copy: { showCopy: true },\n noOpenInEditor: { showOpenInEditor: false },\n openInEditor: { showOpenInEditor: true },\n};\n\nconst VALID_THEMES = new Set<Theme>(['light', 'dark', 'transparent']);\n\n/**\n * Parse the meta string that follows ```dgmo on the fence line.\n * Robust to: empty, missing, malformed input.\n */\nexport function parseFenceMeta(meta: string | null | undefined): BlockOptions {\n if (!meta) return {};\n const out: BlockOptions = {};\n const tokens = tokenize(meta);\n for (const tok of tokens) {\n if (BARE_FLAGS[tok]) {\n Object.assign(out, BARE_FLAGS[tok]);\n continue;\n }\n const eq = tok.indexOf('=');\n if (eq < 0) continue;\n const key = tok.slice(0, eq).trim();\n const rawVal = tok.slice(eq + 1).trim();\n const val = unquote(rawVal);\n switch (key) {\n case 'palette':\n if (val) out.palette = val;\n break;\n case 'theme':\n if (VALID_THEMES.has(val as Theme)) out.theme = val as Theme;\n break;\n case 'mode':\n if (val === 'diagram' || val === 'showcase') out.mode = val;\n break;\n case 'showSource':\n out.showSource = parseBool(val);\n break;\n case 'showCopy':\n out.showCopy = parseBool(val);\n break;\n case 'showOpenInEditor':\n out.showOpenInEditor = parseBool(val);\n break;\n case 'title':\n if (val) out.title = val;\n break;\n }\n }\n return out;\n}\n\nfunction parseBool(s: string): boolean {\n return s === 'true' || s === '1' || s === 'yes';\n}\n\nfunction unquote(s: string): string {\n if (s.length >= 2 && s.startsWith('\"') && s.endsWith('\"')) {\n return s.slice(1, -1);\n }\n return s;\n}\n\n/**\n * Split on whitespace, respecting double-quoted segments so a value like\n * `title=\"Login flow\"` survives intact.\n */\nfunction tokenize(input: string): string[] {\n const out: string[] = [];\n let buf = '';\n let inQuotes = false;\n for (let i = 0; i < input.length; i++) {\n const ch = input[i];\n if (ch === '\"') {\n inQuotes = !inQuotes;\n buf += ch;\n continue;\n }\n if (!inQuotes && /\\s/.test(ch)) {\n if (buf) {\n out.push(buf);\n buf = '';\n }\n continue;\n }\n buf += ch;\n }\n if (buf) out.push(buf);\n return out;\n}\n","/**\n * Normalize an SVG produced by `@diagrammo/dgmo` for inline embedding:\n *\n * - Ensure the root `<svg>` has a `viewBox` so it scales responsively.\n * - Strip fixed `width=\"N\"` / `height=\"N\"` so CSS controls sizing.\n * - Remove any inline `background:` from the root style so the page background\n * shows through.\n *\n * Mirrors the post-processing previously inlined in `Diagram.astro` on the\n * marketing site.\n */\nexport function normalizeSvg(input: string): string {\n let svg = input;\n const rootMatch = svg.match(/<svg[^>]*>/);\n const rootTag = rootMatch?.[0] ?? '';\n if (rootTag && !rootTag.includes('viewBox')) {\n const wh = rootTag.match(/width=\"(\\d+)\"[^>]*height=\"(\\d+)\"/);\n if (wh) {\n svg = svg.replace(/<svg/, `<svg viewBox=\"0 0 ${wh[1]} ${wh[2]}\"`);\n }\n }\n svg = svg.replace(/(<svg[^>]*?) width=\"[^\"]*\"/g, '$1');\n svg = svg.replace(/(<svg[^>]*?) height=\"[^\"]*\"/g, '$1');\n svg = svg.replace(/(<svg[^>]*?style=\"[^\"]*?)background:[^;\"]*;?\\s*/g, '$1');\n svg = svg.replace(/<svg\\s{2,}/g, '<svg ');\n return svg;\n}\n","const HTML_ENTITIES: Record<string, string> = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#39;',\n};\n\nexport function escapeHtml(s: string): string {\n return s.replace(/[&<>\"']/g, ch => HTML_ENTITIES[ch]);\n}\n\nexport function escapeAttr(s: string): string {\n return s.replace(/[&<>\"']/g, ch => HTML_ENTITIES[ch]);\n}\n"],"mappings":";AAAA,SAAS,aAAa;;;ACAtB,SAAS,QAAQ,wBAAwB;AACzC,SAAS,eAAe,wBAAwB;;;ACkEzC,SAAS,eACd,OAA+B,CAAC,GACf;AACjB,QAAM,OAAa,KAAK,QAAQ;AAChC,QAAM,WAAW,SAAS;AAC1B,SAAO;AAAA,IACL;AAAA,IACA,SAAS,KAAK,WAAW;AAAA,IACzB,OAAO,KAAK,SAAS;AAAA,IACrB,YAAY,KAAK,cAAc;AAAA,IAC/B,UAAU,KAAK,YAAY;AAAA,IAC3B,kBAAkB,KAAK,oBAAoB;AAAA,IAC3C,eAAe,KAAK,iBAAiB;AAAA,IACrC,SAAS,KAAK,WAAW;AAAA,IACzB,WAAW,KAAK,aAAa;AAAA,EAC/B;AACF;;;AC9DA,IAAM,aAAoD;AAAA,EACxD,SAAS,EAAE,MAAM,UAAU;AAAA,EAC3B,UAAU,EAAE,MAAM,WAAW;AAAA,EAC7B,UAAU,EAAE,YAAY,MAAM;AAAA,EAC9B,QAAQ,EAAE,YAAY,KAAK;AAAA,EAC3B,QAAQ,EAAE,UAAU,MAAM;AAAA,EAC1B,MAAM,EAAE,UAAU,KAAK;AAAA,EACvB,gBAAgB,EAAE,kBAAkB,MAAM;AAAA,EAC1C,cAAc,EAAE,kBAAkB,KAAK;AACzC;AAEA,IAAM,eAAe,oBAAI,IAAW,CAAC,SAAS,QAAQ,aAAa,CAAC;AAM7D,SAAS,eAAe,MAA+C;AAC5E,MAAI,CAAC,KAAM,QAAO,CAAC;AACnB,Q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DgmoIntegrationOptions } from './remark-plugin-Dx6DW6jN.js';
3
+ export { M as Mode, T as Theme, r as remarkDgmo } from './remark-plugin-Dx6DW6jN.js';
4
+ import 'mdast';
5
+
6
+ /**
7
+ * Astro integration that renders DGMO fenced code blocks at build time.
8
+ *
9
+ * @example
10
+ * ```js
11
+ * // astro.config.mjs
12
+ * import dgmo from 'astro-dgmo';
13
+ *
14
+ * export default defineConfig({
15
+ * integrations: [dgmo()],
16
+ * });
17
+ * ```
18
+ */
19
+ declare function dgmoIntegration(options?: DgmoIntegrationOptions): AstroIntegration;
20
+
21
+ export { DgmoIntegrationOptions, dgmoIntegration as default };
package/dist/index.js ADDED
@@ -0,0 +1,58 @@
1
+ import {
2
+ remarkDgmo
3
+ } from "./chunk-GAAZG3OV.js";
4
+
5
+ // src/index.ts
6
+ var CLIENT_SCRIPT = `
7
+ (() => {
8
+ if (typeof document === 'undefined') return;
9
+ const COPY_SEL = 'button.astro-dgmo-copy';
10
+ function bindCopy() {
11
+ document.addEventListener('click', async (e) => {
12
+ const btn = e.target.closest && e.target.closest(COPY_SEL);
13
+ if (!btn) return;
14
+ const src = btn.dataset.astroDgmoSource || '';
15
+ try { await navigator.clipboard.writeText(src); } catch { return; }
16
+ btn.classList.add('astro-dgmo-copy--success');
17
+ setTimeout(() => btn.classList.remove('astro-dgmo-copy--success'), 1500);
18
+ });
19
+ }
20
+ function tighten() {
21
+ document.querySelectorAll('.astro-dgmo-svg svg').forEach((svg) => {
22
+ try {
23
+ const bbox = svg.getBBox();
24
+ if (bbox.width > 0 && bbox.height > 0) {
25
+ const pad = 16;
26
+ svg.setAttribute('viewBox',
27
+ (bbox.x - pad) + ' ' + (bbox.y - pad) + ' ' +
28
+ (bbox.width + pad * 2) + ' ' + (bbox.height + pad * 2)
29
+ );
30
+ }
31
+ } catch (_) {}
32
+ });
33
+ }
34
+ if (document.readyState === 'loading') {
35
+ document.addEventListener('DOMContentLoaded', () => { bindCopy(); tighten(); });
36
+ } else { bindCopy(); tighten(); }
37
+ })();
38
+ `.trim();
39
+ function dgmoIntegration(options = {}) {
40
+ return {
41
+ name: "astro-dgmo",
42
+ hooks: {
43
+ "astro:config:setup"({ updateConfig, injectScript }) {
44
+ updateConfig({
45
+ markdown: {
46
+ remarkPlugins: [[remarkDgmo, options]]
47
+ }
48
+ });
49
+ injectScript("page", CLIENT_SCRIPT);
50
+ }
51
+ }
52
+ };
53
+ }
54
+ export {
55
+ dgmoIntegration as default,
56
+ remarkDgmo
57
+ };
58
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { AstroIntegration } from 'astro';\nimport remarkDgmo from './remark-plugin.js';\nimport type { DgmoIntegrationOptions } from './options.js';\n\nexport type { DgmoIntegrationOptions, Mode, Theme } from './options.js';\nexport { default as remarkDgmo } from './remark-plugin.js';\n\nconst CLIENT_SCRIPT = `\n(() => {\n if (typeof document === 'undefined') return;\n const COPY_SEL = 'button.astro-dgmo-copy';\n function bindCopy() {\n document.addEventListener('click', async (e) => {\n const btn = e.target.closest && e.target.closest(COPY_SEL);\n if (!btn) return;\n const src = btn.dataset.astroDgmoSource || '';\n try { await navigator.clipboard.writeText(src); } catch { return; }\n btn.classList.add('astro-dgmo-copy--success');\n setTimeout(() => btn.classList.remove('astro-dgmo-copy--success'), 1500);\n });\n }\n function tighten() {\n document.querySelectorAll('.astro-dgmo-svg svg').forEach((svg) => {\n try {\n const bbox = svg.getBBox();\n if (bbox.width > 0 && bbox.height > 0) {\n const pad = 16;\n svg.setAttribute('viewBox',\n (bbox.x - pad) + ' ' + (bbox.y - pad) + ' ' +\n (bbox.width + pad * 2) + ' ' + (bbox.height + pad * 2)\n );\n }\n } catch (_) {}\n });\n }\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', () => { bindCopy(); tighten(); });\n } else { bindCopy(); tighten(); }\n})();\n`.trim();\n\n/**\n * Astro integration that renders DGMO fenced code blocks at build time.\n *\n * @example\n * ```js\n * // astro.config.mjs\n * import dgmo from 'astro-dgmo';\n *\n * export default defineConfig({\n * integrations: [dgmo()],\n * });\n * ```\n */\nexport default function dgmoIntegration(\n options: DgmoIntegrationOptions = {}\n): AstroIntegration {\n return {\n name: 'astro-dgmo',\n hooks: {\n 'astro:config:setup'({ updateConfig, injectScript }) {\n updateConfig({\n markdown: {\n remarkPlugins: [[remarkDgmo, options]],\n },\n });\n injectScript('page', CLIENT_SCRIPT);\n },\n },\n };\n}\n"],"mappings":";;;;;AAOA,IAAM,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgCpB,KAAK;AAeQ,SAAR,gBACL,UAAkC,CAAC,GACjB;AAClB,SAAO;AAAA,IACL,MAAM;AAAA,IACN,OAAO;AAAA,MACL,qBAAqB,EAAE,cAAc,aAAa,GAAG;AACnD,qBAAa;AAAA,UACX,UAAU;AAAA,YACR,eAAe,CAAC,CAAC,YAAY,OAAO,CAAC;AAAA,UACvC;AAAA,QACF,CAAC;AACD,qBAAa,QAAQ,aAAa;AAAA,MACpC;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,68 @@
1
+ import { Root } from 'mdast';
2
+
3
+ type Mode = 'diagram' | 'showcase';
4
+ type Theme = 'light' | 'dark' | 'transparent';
5
+ interface DgmoIntegrationOptions {
6
+ /**
7
+ * Output mode for `dgmo` fenced blocks.
8
+ * - `diagram` (default): render the SVG only, in a `<figure>`.
9
+ * - `showcase`: render syntax-highlighted source + SVG + copy + open-in-editor.
10
+ *
11
+ * Override per-block via the fence info string: ```dgmo showcase
12
+ */
13
+ mode?: Mode;
14
+ /** Default palette name. Default: `nord`. */
15
+ palette?: string;
16
+ /** Default theme. Default: `dark`. */
17
+ theme?: Theme;
18
+ /**
19
+ * Show source code above the diagram. Defaults to `true` in showcase mode,
20
+ * `false` in diagram mode.
21
+ */
22
+ showSource?: boolean;
23
+ /**
24
+ * Show a copy-to-clipboard button. Defaults to `true` in showcase mode,
25
+ * `false` in diagram mode.
26
+ */
27
+ showCopy?: boolean;
28
+ /**
29
+ * Show an "Open in online editor" link. Defaults to `true` in showcase mode,
30
+ * `false` in diagram mode.
31
+ */
32
+ showOpenInEditor?: boolean;
33
+ /**
34
+ * Base URL for the "Open in editor" link. Default: `https://online.diagrammo.app`.
35
+ * The plugin appends `?dgmo=...` (compressed source) to the base.
36
+ */
37
+ editorBaseUrl?: string;
38
+ /**
39
+ * Wrapper element. Default: `figure`.
40
+ */
41
+ wrapper?: 'figure' | 'div';
42
+ /**
43
+ * Class added to the outer wrapper. Defaults to `astro-dgmo`.
44
+ * Useful as a styling hook.
45
+ */
46
+ className?: string;
47
+ }
48
+
49
+ type RemarkDgmoOptions = DgmoIntegrationOptions;
50
+ /**
51
+ * Remark plugin that finds ```dgmo fenced code blocks and replaces them with
52
+ * an HTML node containing the rendered SVG (and optional showcase chrome).
53
+ *
54
+ * The `lang` field on the code node is the fence language (the word after the
55
+ * backticks). The `meta` field is everything that follows on the same line,
56
+ * which we use to allow per-block options like ```dgmo showcase palette=catppuccin.
57
+ *
58
+ * Replaces the code node entirely (parent.children[index] = newNode) rather
59
+ * than mutating it in place — otherwise downstream rehype/Shiki plugins still
60
+ * see the lingering `lang: 'dgmo'` and `value: '...source...'` properties and
61
+ * may re-process the block as a plaintext code listing, clobbering our
62
+ * syntax-highlighted output.
63
+ *
64
+ * Async-safe: replacement is collected first, applied after parsing finishes.
65
+ */
66
+ declare function remarkDgmo(options?: RemarkDgmoOptions): (tree: Root) => Promise<void>;
67
+
68
+ export { type DgmoIntegrationOptions as D, type Mode as M, type RemarkDgmoOptions as R, type Theme as T, remarkDgmo as r };
@@ -0,0 +1,2 @@
1
+ import 'mdast';
2
+ export { R as RemarkDgmoOptions, r as default } from './remark-plugin-Dx6DW6jN.js';
package/dist/remark.js ADDED
@@ -0,0 +1,7 @@
1
+ import {
2
+ remarkDgmo
3
+ } from "./chunk-GAAZG3OV.js";
4
+ export {
5
+ remarkDgmo as default
6
+ };
7
+ //# sourceMappingURL=remark.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/package.json ADDED
@@ -0,0 +1,73 @@
1
+ {
2
+ "name": "astro-dgmo",
3
+ "version": "0.1.0",
4
+ "description": "Astro integration to render DGMO diagrams from fenced code blocks at build time. Powered by @diagrammo/dgmo.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/diagrammo/astro-dgmo.git"
9
+ },
10
+ "homepage": "https://github.com/diagrammo/astro-dgmo#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/diagrammo/astro-dgmo/issues"
13
+ },
14
+ "keywords": [
15
+ "astro",
16
+ "astro-integration",
17
+ "astro-component",
18
+ "withastro",
19
+ "dgmo",
20
+ "diagrammo",
21
+ "diagram",
22
+ "diagrams",
23
+ "mdx",
24
+ "markdown",
25
+ "remark"
26
+ ],
27
+ "type": "module",
28
+ "main": "./dist/index.js",
29
+ "module": "./dist/index.js",
30
+ "types": "./dist/index.d.ts",
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.ts",
34
+ "import": "./dist/index.js"
35
+ },
36
+ "./remark": {
37
+ "types": "./dist/remark.d.ts",
38
+ "import": "./dist/remark.js"
39
+ }
40
+ },
41
+ "files": [
42
+ "dist",
43
+ "README.md",
44
+ "LICENSE"
45
+ ],
46
+ "sideEffects": false,
47
+ "peerDependencies": {
48
+ "@diagrammo/dgmo": ">=0.8.25",
49
+ "astro": ">=4.0.0"
50
+ },
51
+ "dependencies": {
52
+ "@lezer/common": "^1.5.1",
53
+ "@lezer/highlight": "^1.2.3",
54
+ "@lezer/lr": "^1.4.8",
55
+ "unist-util-visit": "^5.0.0"
56
+ },
57
+ "devDependencies": {
58
+ "@diagrammo/dgmo": "^0.8.26",
59
+ "@types/mdast": "^4.0.4",
60
+ "@types/node": "^22.10.0",
61
+ "astro": "^6.1.5",
62
+ "tsup": "^8.5.1",
63
+ "typescript": "^6.0.2",
64
+ "vitest": "^4.1.4"
65
+ },
66
+ "scripts": {
67
+ "build": "tsup",
68
+ "dev": "tsup --watch",
69
+ "typecheck": "tsc --noEmit",
70
+ "test": "vitest run",
71
+ "test:watch": "vitest"
72
+ }
73
+ }