schemasketch-render 1.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,10 @@
1
+ # Changelog
2
+
3
+ `schemasketch-render`, the SchemaSketch SVG renderer. Versions follow
4
+ [Semantic Versioning](https://semver.org).
5
+
6
+ ## 1.0.0 (2026-11-17)
7
+
8
+ - First release: `renderSvg`, `renderSvgFromDbml`, `layout`, `measureTable`, `esc` and
9
+ `RENDERER_VERSION`. Draws tables, relationships and table groups as a standalone SVG,
10
+ in light, dark or automatic colours.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Stelios Ioannides
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,81 @@
1
+ # schemasketch-render
2
+
3
+ Turn a database schema into a standalone SVG image. Give it DBML (or an already parsed
4
+ schema) and get back SVG text: tables, columns, keys, relationship lines and table
5
+ groups. It's the same drawing that [SchemaSketch](https://schemasketch.dev) serves for
6
+ shared diagrams.
7
+
8
+ No dependencies, no browser, no DOM. Needs Node 18 or newer.
9
+
10
+ ```sh
11
+ npm install schemasketch-render
12
+ ```
13
+
14
+ ## Show your schema in a GitHub README
15
+
16
+ GitHub and npm only show images, not embeds. If your diagram lives in SchemaSketch, you
17
+ don't need this package at all: open the diagram, click **Share**, set the link to
18
+ **Public**, and press **Copy Markdown** under **Show it in a GitHub README**. It stays up to date as you
19
+ edit the diagram:
20
+
21
+ ```md
22
+ [![Database schema](https://schemasketch.dev/api/public/diagrams/YOUR-TOKEN/image.svg)](https://schemasketch.dev/view.html?token=YOUR-TOKEN)
23
+ ```
24
+
25
+ Use this package when you'd rather generate the SVG yourself, for example in a build
26
+ step or a docs generator, and commit the file.
27
+
28
+ ## Usage
29
+
30
+ ```js
31
+ import { writeFileSync } from 'node:fs';
32
+ import { renderSvgFromDbml } from 'schemasketch-render';
33
+
34
+ const { svg, errors } = renderSvgFromDbml(`
35
+ Table users {
36
+ id int [pk, increment]
37
+ email varchar [unique, not null]
38
+ }
39
+
40
+ Table posts {
41
+ id int [pk, increment]
42
+ user_id int [ref: > users.id]
43
+ title varchar
44
+ }
45
+ `, {}, { title: 'Blog schema', theme: 'light' });
46
+
47
+ if (errors.length) console.warn(errors);
48
+ writeFileSync('schema.svg', svg);
49
+ ```
50
+
51
+ ## API
52
+
53
+ ### `renderSvgFromDbml(dbml, positions?, options?)`
54
+
55
+ Parses the DBML and draws it. Returns `{ svg, errors }`. `errors` is a list of parse
56
+ messages (empty when the DBML is valid); whatever parsed is still drawn.
57
+
58
+ ### `renderSvg(schema, positions?, options?)`
59
+
60
+ Draws a schema object in the shape the parser produces
61
+ (`{ tables, refs, tableGroups, enums }`). Returns the SVG string.
62
+
63
+ ### Arguments
64
+
65
+ - `positions`: `{ "table_name": { x, y } }`. Tables without a position are placed
66
+ automatically.
67
+ - `options.title`: accessible title of the image (default `"Database diagram"`).
68
+ - `options.theme`: `"light"`, `"dark"` or `"auto"` (default; follows the viewer's
69
+ colour scheme).
70
+
71
+ Table names and values are escaped, so the output is safe to embed from untrusted
72
+ schemas. Diagrams with no tables, or very large ones, return a small message image
73
+ instead.
74
+
75
+ ### Also exported
76
+
77
+ `layout(schema, positions)`, `measureTable(table)`, `esc(value)` and `RENDERER_VERSION`.
78
+
79
+ ## License
80
+
81
+ MIT. Part of [SchemaSketch](https://schemasketch.dev).
package/index.js ADDED
@@ -0,0 +1,11 @@
1
+ import { renderSvg } from './svg-render.js';
2
+ import { parseSchema } from './parser.js';
3
+
4
+ export { renderSvg, layout, measureTable, esc, RENDERER_VERSION } from './svg-render.js';
5
+
6
+ // Parses DBML and draws it. Parse errors come back in `errors`; whatever parsed
7
+ // is still drawn, so a half-written schema gives a partial picture, not nothing.
8
+ export function renderSvgFromDbml(dbml, positions = {}, options = {}) {
9
+ const schema = parseSchema(String(dbml ?? ''));
10
+ return { svg: renderSvg(schema, positions, options), errors: schema.errors ?? [] };
11
+ }
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "schemasketch-render",
3
+ "version": "1.0.0",
4
+ "description": "Render a database schema (DBML or a parsed schema) as a standalone SVG image. No dependencies, no browser, runs in Node 18+.",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "exports": {
8
+ ".": "./index.js"
9
+ },
10
+ "files": [
11
+ "index.js",
12
+ "svg-render.js",
13
+ "parser.js",
14
+ "LICENSE",
15
+ "README.md",
16
+ "CHANGELOG.md"
17
+ ],
18
+ "engines": {
19
+ "node": ">=18"
20
+ },
21
+ "scripts": {
22
+ "test": "node --test index.test.mjs",
23
+ "prepublishOnly": "npm test"
24
+ },
25
+ "license": "MIT",
26
+ "author": "Stelios Ioannides",
27
+ "homepage": "https://schemasketch.dev",
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/SchemaSketch-dev/schemasketch-render.git"
31
+ },
32
+ "bugs": {
33
+ "url": "https://github.com/SchemaSketch-dev/schemasketch-render/issues"
34
+ },
35
+ "keywords": [
36
+ "dbml",
37
+ "svg",
38
+ "erd",
39
+ "database-diagram",
40
+ "schema",
41
+ "schemasketch"
42
+ ]
43
+ }
package/parser.js ADDED
@@ -0,0 +1,443 @@
1
+ // DBML-like schema language parser.
2
+ // Supports:
3
+ // Table name [as alias] { col type [settings] ... Note: '...' }
4
+ // Enum name { value1 value2 ... }
5
+ // Ref: table1.col > table2.col (also <, -, <>)
6
+ // Ref name { table1.col > table2.col }
7
+ // inline column ref: `ref: > other.col`
8
+ // // line comments and /* block comments */
9
+ // Table settings [color: #hex] (color only, cosmetic)
10
+
11
+ // Triple-quoted strings ('''...''') can span multiple lines and contain
12
+ // anything (commas, quotes, `//`) — pull them out before any other parsing
13
+ // (including comment-stripping) so their content can't be misinterpreted,
14
+ // then swap in an ordinary single-quoted placeholder the rest of the parser
15
+ // already knows how to handle.
16
+ function extractTripleQuoted(source) {
17
+ const store = [];
18
+ const replaced = source.replace(/'''([\s\S]*?)'''/g, (_, content) => {
19
+ const idx = store.length;
20
+ store.push(content.trim());
21
+ return `'@@TQ${idx}@@'`;
22
+ });
23
+ return { replaced, store };
24
+ }
25
+
26
+ function resolvePlaceholders(value, store) {
27
+ if (typeof value !== 'string') return value;
28
+ const m = value.match(/^@@TQ(\d+)@@$/);
29
+ return m ? store[Number(m[1])] : value;
30
+ }
31
+
32
+ function stripComments(text) {
33
+ text = text.replace(/\/\*[\s\S]*?\*\//g, ' ');
34
+ return text
35
+ .split('\n')
36
+ .map((line) => {
37
+ const idx = line.indexOf('//');
38
+ return idx === -1 ? line : line.slice(0, idx);
39
+ })
40
+ .join('\n');
41
+ }
42
+
43
+ // Split a top-level comma list respecting (), [], '', "" nesting.
44
+ function splitTopLevel(str, sep = ',') {
45
+ const parts = [];
46
+ let depth = 0;
47
+ let cur = '';
48
+ let quote = null;
49
+ for (let i = 0; i < str.length; i++) {
50
+ const ch = str[i];
51
+ if (quote) {
52
+ cur += ch;
53
+ if (ch === quote && str[i - 1] !== '\\') quote = null;
54
+ continue;
55
+ }
56
+ if (ch === "'" || ch === '"') {
57
+ quote = ch;
58
+ cur += ch;
59
+ continue;
60
+ }
61
+ if (ch === '(' || ch === '[' || ch === '{') depth++;
62
+ if (ch === ')' || ch === ']' || ch === '}') depth--;
63
+ if (ch === sep && depth === 0) {
64
+ parts.push(cur);
65
+ cur = '';
66
+ } else {
67
+ cur += ch;
68
+ }
69
+ }
70
+ if (cur.trim() !== '') parts.push(cur);
71
+ return parts.map((s) => s.trim()).filter(Boolean);
72
+ }
73
+
74
+ function unquote(s) {
75
+ s = s.trim();
76
+ if ((s.startsWith("'") && s.endsWith("'")) || (s.startsWith('"') && s.endsWith('"'))) {
77
+ const quoteChar = s[0];
78
+ // Only the delimiter itself is ever backslash-escaped inside a DBML
79
+ // quoted string (e.g. default: 'O\'Brien') - unescape it so the value
80
+ // callers see is the real one, not the escape sequence.
81
+ return s.slice(1, -1).split(`\\${quoteChar}`).join(quoteChar);
82
+ }
83
+ return s;
84
+ }
85
+
86
+ function parseSettingsList(str) {
87
+ const out = {};
88
+ const flags = [];
89
+ for (const raw of splitTopLevel(str, ',')) {
90
+ const m = raw.match(/^([a-zA-Z_ ]+?)\s*:\s*(.+)$/);
91
+ if (m) {
92
+ const key = m[1].trim().toLowerCase();
93
+ const val = unquote(m[2]);
94
+ out[key] = val;
95
+ } else {
96
+ flags.push(raw.trim().toLowerCase());
97
+ }
98
+ }
99
+ out.__flags = flags;
100
+ return out;
101
+ }
102
+
103
+ function applyColumnSettings(col, settingsStr) {
104
+ if (!settingsStr) return;
105
+ const parsed = parseSettingsList(settingsStr);
106
+ for (const flag of parsed.__flags) {
107
+ if (flag === 'pk' || flag === 'primary key') col.pk = true;
108
+ else if (flag === 'not null') col.notNull = true;
109
+ else if (flag === 'null') col.notNull = false;
110
+ else if (flag === 'unique') col.unique = true;
111
+ else if (flag === 'increment') col.increment = true;
112
+ else if (flag.startsWith('ref:')) {
113
+ col.inlineRef = flag.slice(4).trim();
114
+ }
115
+ }
116
+ if (parsed.default !== undefined) col.default = parsed.default;
117
+ if (parsed.note !== undefined) col.note = parsed.note;
118
+ // handle key: value forms of ref (ref: > table.col) that split() above may have
119
+ // captured as key "ref" value "> table.col" since it contains ':'
120
+ for (const raw of splitTopLevel(settingsStr, ',')) {
121
+ const m = raw.match(/^ref\s*:\s*(.+)$/i);
122
+ if (m) col.inlineRef = m[1].trim();
123
+ }
124
+ }
125
+
126
+ function findMatchingBrace(text, openIdx) {
127
+ let depth = 0;
128
+ for (let i = openIdx; i < text.length; i++) {
129
+ if (text[i] === '{') depth++;
130
+ else if (text[i] === '}') {
131
+ depth--;
132
+ if (depth === 0) return i;
133
+ }
134
+ }
135
+ return -1;
136
+ }
137
+
138
+ function parseRefEndpoint(str) {
139
+ str = str.trim();
140
+ // schema.table.column or table.column, optionally table.(col1,col2) - composite not supported, take first
141
+ const compMatch = str.match(/^([\w."]+)\.\(([^)]+)\)$/);
142
+ if (compMatch) {
143
+ const table = compMatch[1].split('.').pop().replace(/"/g, '');
144
+ const col = splitTopLevel(compMatch[2], ',')[0].replace(/"/g, '');
145
+ return { table, column: col };
146
+ }
147
+ const parts = str.split('.').map((p) => p.replace(/"/g, ''));
148
+ const column = parts.pop();
149
+ const table = parts.pop();
150
+ return { table, column };
151
+ }
152
+
153
+ function normalizeRefAction(value) {
154
+ const s = (value || '').toLowerCase().trim();
155
+ return ['cascade', 'restrict', 'set null', 'set default', 'no action'].includes(s) ? s : null;
156
+ }
157
+
158
+ function parseRefLine(body, refs) {
159
+ // body like: table1.col > table2.col or table1.col <> table2.col
160
+ // optionally followed by a trailing [delete: cascade, update: restrict] settings bracket.
161
+ let settingsStr = null;
162
+ const bracketMatch = body.match(/^(.*?)\s*\[([^\]]*)\]\s*$/);
163
+ if (bracketMatch) {
164
+ body = bracketMatch[1];
165
+ settingsStr = bracketMatch[2];
166
+ }
167
+ const m = body.match(/^(.+?)\s*(<>|>|<|-)\s*(.+)$/);
168
+ if (!m) return;
169
+ const from = parseRefEndpoint(m[1]);
170
+ const type = m[2];
171
+ const to = parseRefEndpoint(m[3]);
172
+ const ref = { fromTable: from.table, fromColumn: from.column, toTable: to.table, toColumn: to.column, type };
173
+ if (settingsStr) {
174
+ const parsed = parseSettingsList(settingsStr);
175
+ if (parsed.delete !== undefined) ref.onDelete = normalizeRefAction(parsed.delete);
176
+ if (parsed.update !== undefined) ref.onUpdate = normalizeRefAction(parsed.update);
177
+ }
178
+ refs.push(ref);
179
+ }
180
+
181
+ export function parseSchema(source) {
182
+ const { replaced, store: tqStore } = extractTripleQuoted(source || '');
183
+ const text = stripComments(replaced);
184
+ const tables = [];
185
+ const enums = [];
186
+ const refs = [];
187
+ const tableGroups = [];
188
+ const errors = [];
189
+ const tableByLowerName = new Map();
190
+
191
+ // Find all top-level keyword blocks / statements.
192
+ const keywordRe = /\b(Table|Enum|Ref|TableGroup|Project)\b/g;
193
+ let match;
194
+ const consumedUntil = { pos: 0 };
195
+
196
+ while ((match = keywordRe.exec(text)) !== null) {
197
+ if (match.index < consumedUntil.pos) continue;
198
+ const keyword = match[1];
199
+ const afterKeyword = match.index + keyword.length;
200
+
201
+ if (keyword === 'Ref') {
202
+ // Two forms: "Ref: a.b > c.d" or "Ref name { ... }" or "Ref { ... }"
203
+ const restOfLine = text.slice(afterKeyword, text.indexOf('\n', afterKeyword) === -1 ? text.length : text.indexOf('\n', afterKeyword));
204
+ const colonInline = restOfLine.match(/^\s*:\s*(.+)$/);
205
+ const braceIdx = text.indexOf('{', afterKeyword);
206
+ const newlineIdx = text.indexOf('\n', afterKeyword);
207
+ if (colonInline && (braceIdx === -1 || (newlineIdx !== -1 && newlineIdx < braceIdx))) {
208
+ parseRefLine(colonInline[1].trim(), refs);
209
+ keywordRe.lastIndex = afterKeyword + colonInline[0].length;
210
+ continue;
211
+ }
212
+ if (braceIdx !== -1) {
213
+ const closeIdx = findMatchingBrace(text, braceIdx);
214
+ if (closeIdx === -1) {
215
+ errors.push('Unclosed Ref block');
216
+ break;
217
+ }
218
+ const inner = text.slice(braceIdx + 1, closeIdx);
219
+ for (const line of inner.split('\n')) {
220
+ const t = line.trim();
221
+ if (t) parseRefLine(t, refs);
222
+ }
223
+ keywordRe.lastIndex = closeIdx + 1;
224
+ continue;
225
+ }
226
+ continue;
227
+ }
228
+
229
+ if (keyword === 'Project') {
230
+ const braceIdx = text.indexOf('{', afterKeyword);
231
+ if (braceIdx !== -1) {
232
+ const closeIdx = findMatchingBrace(text, braceIdx);
233
+ if (closeIdx !== -1) {
234
+ keywordRe.lastIndex = closeIdx + 1;
235
+ continue;
236
+ }
237
+ }
238
+ continue;
239
+ }
240
+
241
+ if (keyword === 'TableGroup') {
242
+ // TableGroup name [color: '#hex'] { table1 \n table2 \n ... }
243
+ // Renders as a colored bounding region around its member tables — a
244
+ // subject area — purely organizational, no effect on the schema itself.
245
+ const braceIdx = text.indexOf('{', afterKeyword);
246
+ if (braceIdx === -1) { errors.push('TableGroup missing {'); continue; }
247
+ const header = text.slice(afterKeyword, braceIdx).trim();
248
+ let name = header;
249
+ let color = null;
250
+ const settingsBracket = header.match(/\[(.*)\]\s*$/);
251
+ if (settingsBracket) {
252
+ name = header.slice(0, settingsBracket.index).trim();
253
+ const s = parseSettingsList(settingsBracket[1]);
254
+ if (s.color) color = s.color;
255
+ }
256
+ name = name.replace(/"/g, '');
257
+
258
+ const closeIdx = findMatchingBrace(text, braceIdx);
259
+ if (closeIdx === -1) { errors.push(`TableGroup ${name} missing closing }`); break; }
260
+ const inner = text.slice(braceIdx + 1, closeIdx);
261
+ const memberTables = inner
262
+ .split('\n')
263
+ .map((l) => l.trim())
264
+ .filter(Boolean)
265
+ .map((l) => l.split('[')[0].trim().replace(/"/g, ''))
266
+ .filter(Boolean);
267
+
268
+ tableGroups.push({ name, color, tables: memberTables });
269
+ keywordRe.lastIndex = closeIdx + 1;
270
+ continue;
271
+ }
272
+
273
+ if (keyword === 'Enum') {
274
+ const header = text.slice(afterKeyword, text.indexOf('{', afterKeyword));
275
+ const name = header.trim().split(/\s+/)[0];
276
+ const braceIdx = text.indexOf('{', afterKeyword);
277
+ if (braceIdx === -1) { errors.push(`Enum ${name || ''} missing {`); continue; }
278
+ const closeIdx = findMatchingBrace(text, braceIdx);
279
+ if (closeIdx === -1) { errors.push(`Enum ${name} missing closing }`); break; }
280
+ const inner = text.slice(braceIdx + 1, closeIdx);
281
+ const values = inner
282
+ .split('\n')
283
+ .map((l) => l.trim())
284
+ .filter(Boolean)
285
+ .map((l) => l.split('[')[0].trim())
286
+ .filter(Boolean);
287
+ enums.push({ name, values });
288
+ keywordRe.lastIndex = closeIdx + 1;
289
+ continue;
290
+ }
291
+
292
+ if (keyword === 'Table') {
293
+ const braceIdx = text.indexOf('{', afterKeyword);
294
+ if (braceIdx === -1) { errors.push('Table missing {'); continue; }
295
+ const header = text.slice(afterKeyword, braceIdx).trim();
296
+ // name [as alias] [settings]
297
+ let name = header;
298
+ let alias = null;
299
+ let settingsStr = null;
300
+ const settingsBracket = header.match(/\[(.*)\]\s*$/);
301
+ if (settingsBracket) {
302
+ settingsStr = settingsBracket[1];
303
+ name = header.slice(0, settingsBracket.index).trim();
304
+ }
305
+ const asMatch = name.match(/^(\S+)\s+as\s+(\S+)$/i);
306
+ if (asMatch) {
307
+ name = asMatch[1];
308
+ alias = asMatch[2];
309
+ }
310
+ name = name.replace(/"/g, '');
311
+
312
+ const closeIdx = findMatchingBrace(text, braceIdx);
313
+ if (closeIdx === -1) { errors.push(`Table ${name} missing closing }`); break; }
314
+ const inner = text.slice(braceIdx + 1, closeIdx);
315
+
316
+ const table = { name, alias, columns: [], indexes: [], note: null, color: null };
317
+ if (settingsStr) {
318
+ const s = parseSettingsList(settingsStr);
319
+ if (s.headercolor) table.color = s.headercolor;
320
+ if (s.color) table.color = s.color;
321
+ }
322
+
323
+ // Walk inner line by line, but respect bracket settings that might span... generally one line per column.
324
+ const lines = inner.split('\n');
325
+ for (let li = 0; li < lines.length; li++) {
326
+ const line = lines[li].trim();
327
+ if (!line) continue;
328
+ if (/^Note\s*:/i.test(line)) {
329
+ const nm = line.match(/^Note\s*:\s*(.+)$/i);
330
+ if (nm) table.note = unquote(nm[1].trim());
331
+ continue;
332
+ }
333
+ if (/^Indexes\s*\{?/i.test(line)) {
334
+ // Entries look like "(a, b) [unique]", "col [name: 'foo']", or a
335
+ // bare "col" for a plain single-column index. Composite entries
336
+ // would otherwise fall through to the column-line parsing below
337
+ // and get misread as a bogus column named "(a,", so this block is
338
+ // consumed and parsed on its own rather than left to that path.
339
+ li++;
340
+ while (li < lines.length && lines[li].trim() !== '}') {
341
+ const idxLine = lines[li].trim();
342
+ if (idxLine) {
343
+ const bracketMatch = idxLine.match(/^(.*?)\[(.*)\]\s*$/);
344
+ const head = bracketMatch ? bracketMatch[1].trim() : idxLine;
345
+ const settingsStr = bracketMatch ? bracketMatch[2] : null;
346
+ const compMatch = head.match(/^\(([^)]+)\)$/);
347
+ const columns = compMatch
348
+ ? splitTopLevel(compMatch[1], ',').map((c) => c.replace(/"/g, '').trim())
349
+ : [head.replace(/"/g, '').trim()];
350
+ if (columns.length && columns[0]) {
351
+ const entry = { columns, unique: false, pk: false, name: null };
352
+ if (settingsStr) {
353
+ const parsedIdx = parseSettingsList(settingsStr);
354
+ for (const flag of parsedIdx.__flags) {
355
+ if (flag === 'unique') entry.unique = true;
356
+ else if (flag === 'pk' || flag === 'primary key') entry.pk = true;
357
+ }
358
+ if (parsedIdx.name !== undefined) entry.name = parsedIdx.name;
359
+ }
360
+ table.indexes.push(entry);
361
+ }
362
+ }
363
+ li++;
364
+ }
365
+ continue;
366
+ }
367
+ // column line: name type [settings]
368
+ const bracketMatch = line.match(/^(.*?)\[(.*)\]\s*$/);
369
+ let head = line;
370
+ let settings = null;
371
+ if (bracketMatch) {
372
+ head = bracketMatch[1].trim();
373
+ settings = bracketMatch[2];
374
+ }
375
+ const headParts = head.match(/^("[^"]+"|\S+)\s+([\s\S]+)$/);
376
+ if (!headParts) continue;
377
+ const colName = headParts[1].replace(/"/g, '');
378
+ // A native passthrough type ("bigint unsigned", "enum('a','b')") is
379
+ // wrapped in double quotes only because it contains whitespace/a
380
+ // comma/a quote - unquote() strips that DBML-level delimiter so the
381
+ // stored type is the real one (e.g. exporting it back to SQL), not
382
+ // a type name with literal quote characters baked into it.
383
+ const colType = unquote(headParts[2].trim());
384
+ const col = {
385
+ name: colName,
386
+ type: colType,
387
+ pk: false,
388
+ notNull: false,
389
+ unique: false,
390
+ increment: false,
391
+ default: null,
392
+ note: null,
393
+ inlineRef: null,
394
+ };
395
+ applyColumnSettings(col, settings);
396
+ table.columns.push(col);
397
+ }
398
+
399
+ tables.push(table);
400
+ tableByLowerName.set(name.toLowerCase(), table);
401
+ if (alias) tableByLowerName.set(alias.toLowerCase(), table);
402
+ keywordRe.lastIndex = closeIdx + 1;
403
+ continue;
404
+ }
405
+ }
406
+
407
+ // Resolve inline column refs (col [ref: > other.col]) into the refs array.
408
+ for (const table of tables) {
409
+ for (const col of table.columns) {
410
+ if (col.inlineRef) {
411
+ const m = col.inlineRef.match(/^(<>|>|<|-)\s*(.+)$/);
412
+ if (m) {
413
+ const to = parseRefEndpoint(m[2]);
414
+ refs.push({ fromTable: table.name, fromColumn: col.name, toTable: to.table, toColumn: to.column, type: m[1] });
415
+ }
416
+ }
417
+ }
418
+ }
419
+
420
+ // Normalize ref table names against actual table names/aliases (case-insensitive).
421
+ function resolveName(n) {
422
+ const t = tableByLowerName.get((n || '').toLowerCase());
423
+ return t ? t.name : n;
424
+ }
425
+ for (const ref of refs) {
426
+ ref.fromTable = resolveName(ref.fromTable);
427
+ ref.toTable = resolveName(ref.toTable);
428
+ }
429
+ for (const group of tableGroups) {
430
+ group.tables = group.tables.map(resolveName);
431
+ }
432
+
433
+ // Swap triple-quoted placeholders back to their real (possibly multi-line) text.
434
+ for (const table of tables) {
435
+ table.note = resolvePlaceholders(table.note, tqStore);
436
+ for (const col of table.columns) {
437
+ col.note = resolvePlaceholders(col.note, tqStore);
438
+ col.default = resolvePlaceholders(col.default, tqStore);
439
+ }
440
+ }
441
+
442
+ return { tables, enums, refs, tableGroups, errors };
443
+ }
package/svg-render.js ADDED
@@ -0,0 +1,367 @@
1
+ // Standalone SVG renderer: turns a parsed schema (parseSchema()) plus stored
2
+ // table positions into an SVG string. Pure: no DOM, no browser APIs, so it
3
+ // runs in Node 18+ and in browsers.
4
+ //
5
+ // The output is served from the app's own domain and the diagram content is
6
+ // untrusted, so every text and attribute value goes through esc(), colours
7
+ // are validated, positions are coerced to finite numbers, and no user value
8
+ // is ever used as an element/attribute name, style text, href or url().
9
+ //
10
+ // Drawing constants mirror frontend/renderer.js (the interactive editor).
11
+
12
+ export const RENDERER_VERSION = '1.0.0';
13
+
14
+ const ROW_H = 26;
15
+ const HEADER_H = 32;
16
+ const CHAR_W = 7.2;
17
+ const BOLD_EXTRA = 1.2;
18
+ const PAD_X = 14;
19
+ const MIN_TABLE_W = 160;
20
+ const TABLE_GAP_X = 90;
21
+ const TABLE_GAP_Y = 70;
22
+ const DEFAULT_HEADER_COLOR = '#5b6cf0';
23
+ // Table header presets, as in the editor.
24
+ export const PRESET_COLORS = [
25
+ '#5b6cf0', '#3b82f6', '#06b6d4', '#14b8a6', '#22c55e', '#84cc16',
26
+ '#eab308', '#f97316', '#ef4444', '#ec4899', '#a855f7', '#64748b',
27
+ ];
28
+ const BADGE_W = 20;
29
+ const BADGE_H = 14;
30
+ const BADGE_GAP = 3;
31
+ const BADGE_DEFS = {
32
+ pk: { label: 'PK', color: '#5b6cf0' },
33
+ increment: { label: 'AI', color: '#06b6d4' },
34
+ unique: { label: 'UQ', color: '#a855f7' },
35
+ notNull: { label: 'NN', color: '#f97316' },
36
+ };
37
+ const EXPORT_PAD = 30;
38
+ const AREA_PAD = 28;
39
+ const AREA_LABEL_H = 26;
40
+ const DEFAULT_AREA_COLOR = '#64748b';
41
+ const EDGE_COLOR = '#9aa0b4';
42
+ // Themed colours. Light matches the editor's export; dark follows its dark
43
+ // tokens. User-chosen header and group colours are never themed.
44
+ const PALETTES = {
45
+ light: {
46
+ bg: '#fbfbfe', card: '#ffffff', cardStroke: '#d9dce9', sep: '#eceef6', text: '#1f2330',
47
+ pk: '#4350c8', type: '#8b90a5', edge: EDGE_COLOR, msg: '#4a4f66', msgStroke: '#e1e3ee',
48
+ },
49
+ dark: {
50
+ bg: '#16171d', card: '#1f212b', cardStroke: '#343746', sep: '#2b2e3b', text: '#e6e8f0',
51
+ pk: '#a5b0ff', type: '#8f94aa', edge: '#6b7088', msg: '#c4c8d8', msgStroke: '#343746',
52
+ },
53
+ };
54
+ const MAX_TABLES = 300;
55
+ const COORD_LIMIT = 100000;
56
+ const MONO = "'JetBrains Mono', 'SF Mono', Menlo, Consolas, 'Liberation Mono', monospace";
57
+ const HEADER_ICONS_W = 74;
58
+ const FONT = "system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif";
59
+ const COLOR_RE = /^#[0-9a-f]{3}([0-9a-f]{3})?$/i;
60
+
61
+ // The single escaping point for text and attribute values.
62
+ export function esc(value) {
63
+ if (value === null || value === undefined) return '';
64
+ return String(value)
65
+ // Control characters are illegal in XML 1.0.
66
+ .replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F￾￿]/g, '')
67
+ .replace(/&/g, '&amp;')
68
+ .replace(/</g, '&lt;')
69
+ .replace(/>/g, '&gt;')
70
+ .replace(/"/g, '&quot;')
71
+ .replace(/'/g, '&#39;')
72
+ // Defence in depth: numeric references render identically, but keep
73
+ // attribute-looking and URL-looking text from appearing in the output.
74
+ .replace(/=/g, '&#61;')
75
+ .replace(/(url)\(/gi, '$1&#40;')
76
+ .replace(/(javascript):/gi, '$1&#58;');
77
+ }
78
+
79
+ function safeColor(value, fallback = DEFAULT_HEADER_COLOR) {
80
+ return typeof value === 'string' && COLOR_RE.test(value.trim()) ? value.trim() : fallback;
81
+ }
82
+
83
+ function num(n) {
84
+ return Math.round(n * 100) / 100;
85
+ }
86
+
87
+ function textWidth(str, bold = false) {
88
+ return str.length * CHAR_W + (bold ? str.length * BOLD_EXTRA : 0);
89
+ }
90
+
91
+ function truncateDefault(value) {
92
+ const s = String(value);
93
+ return s.length > 12 ? s.slice(0, 12) + '…' : s;
94
+ }
95
+
96
+ function hasDefault(col) {
97
+ return col.default !== undefined && col.default !== null && col.default !== '';
98
+ }
99
+
100
+ function badgeList(col) {
101
+ const badges = [];
102
+ if (col.pk) badges.push(BADGE_DEFS.pk);
103
+ if (col.increment) badges.push(BADGE_DEFS.increment);
104
+ if (col.unique) badges.push(BADGE_DEFS.unique);
105
+ if (col.notNull) badges.push(BADGE_DEFS.notNull);
106
+ return badges;
107
+ }
108
+
109
+ export function measureTable(table) {
110
+ const columns = table.columns || [];
111
+ let w = Math.max(MIN_TABLE_W, textWidth(String(table.name), true) + PAD_X * 2 + HEADER_ICONS_W);
112
+ for (const col of columns) {
113
+ const badgeCount = badgeList(col).length;
114
+ const badgesW = badgeCount ? badgeCount * BADGE_W + (badgeCount - 1) * BADGE_GAP + 8 : 0;
115
+ const defaultW = hasDefault(col) ? textWidth(' = ' + truncateDefault(col.default)) : 0;
116
+ const label = String(col.name) + ' ' + String(col.type);
117
+ w = Math.max(w, textWidth(label) + defaultW + badgesW + PAD_X * 2 + 54);
118
+ }
119
+ return { w: Math.round(w), h: HEADER_H + columns.length * ROW_H };
120
+ }
121
+
122
+ function coerceCoord(v) {
123
+ if (typeof v === 'string' && v.trim() === '') return null;
124
+ if (typeof v !== 'number' && typeof v !== 'string') return null;
125
+ const n = Number(v);
126
+ return Number.isFinite(n) && Math.abs(n) <= COORD_LIMIT ? n : null;
127
+ }
128
+
129
+ // Returns a new { [tableName]: {x, y} } with every table placed. Positions
130
+ // that are missing or not usable count as unplaced. Port of the editor's
131
+ // _ensureLayout, starting from the coerced copy.
132
+ export function layout(schema, positions) {
133
+ const tables = schema.tables || [];
134
+ const src = positions && typeof positions === 'object' ? positions : {};
135
+ const out = Object.create(null);
136
+ for (const t of tables) {
137
+ if (!Object.prototype.hasOwnProperty.call(src, t.name)) continue;
138
+ const p = src[t.name];
139
+ if (!p || typeof p !== 'object') continue;
140
+ const x = coerceCoord(p.x);
141
+ const y = coerceCoord(p.y);
142
+ if (x === null || y === null) continue;
143
+ out[t.name] = { x, y };
144
+ }
145
+
146
+ const unpositioned = tables.filter((t) => !out[t.name]);
147
+ if (unpositioned.length === 0) return out;
148
+
149
+ let startY = 40;
150
+ for (const t of tables) {
151
+ const pos = out[t.name];
152
+ if (!pos) continue;
153
+ startY = Math.max(startY, pos.y + measureTable(t).h + TABLE_GAP_Y);
154
+ }
155
+
156
+ const cols = Math.max(1, Math.ceil(Math.sqrt(unpositioned.length)));
157
+ let x = 40;
158
+ let y = startY;
159
+ let rowMaxH = 0;
160
+ let i = 0;
161
+ for (const t of unpositioned) {
162
+ const { w, h } = measureTable(t);
163
+ out[t.name] = { x, y };
164
+ rowMaxH = Math.max(rowMaxH, h);
165
+ x += w + TABLE_GAP_X;
166
+ i++;
167
+ if (i % cols === 0) {
168
+ x = 40;
169
+ y += rowMaxH + TABLE_GAP_Y;
170
+ rowMaxH = 0;
171
+ }
172
+ }
173
+ return out;
174
+ }
175
+
176
+ function paletteRules(p) {
177
+ return `.ss-bg{fill:${p.bg}}.ss-card{fill:${p.card};stroke:${p.cardStroke}}.ss-sep{stroke:${p.sep}}`
178
+ + `.ss-tx{fill:${p.text}}.ss-pk{fill:${p.pk}}.ss-ty{fill:${p.type}}`
179
+ + `.ss-ref-line{fill:none;stroke:${p.edge};stroke-width:1.4}.ss-mk{stroke:${p.edge}}`
180
+ + `.ss-msg-card{fill:${p.card};stroke:${p.msgStroke}}.ss-msg{fill:${p.msg}}`;
181
+ }
182
+
183
+ function themeStyle(theme) {
184
+ if (theme === 'dark') return `<style>${paletteRules(PALETTES.dark)}</style>`;
185
+ if (theme === 'light') return `<style>${paletteRules(PALETTES.light)}</style>`;
186
+ return `<style>${paletteRules(PALETTES.light)}@media (prefers-color-scheme: dark){${paletteRules(PALETTES.dark)}}</style>`;
187
+ }
188
+
189
+ function normTheme(theme) {
190
+ return theme === 'light' || theme === 'dark' ? theme : 'auto';
191
+ }
192
+
193
+ // The one place that writes the root <svg>, <title>, theme <style> and
194
+ // background. `vb` is {x, y, w, h}.
195
+ function svgOpen(vb, title, theme) {
196
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${num(vb.x)} ${num(vb.y)} ${num(vb.w)} ${num(vb.h)}" width="${num(vb.w)}" height="${num(vb.h)}" font-family="${esc(FONT)}">`
197
+ + `<title>${esc(title)}</title>`
198
+ + themeStyle(normTheme(theme))
199
+ + `<rect class="ss-bg" x="${num(vb.x)}" y="${num(vb.y)}" width="${num(vb.w)}" height="${num(vb.h)}"/>`;
200
+ }
201
+
202
+ // Small standalone card, also used for the "too large" / "can't show" fallbacks.
203
+ export function messageSvg(text, theme) {
204
+ const w = 400;
205
+ const h = 120;
206
+ return svgOpen({ x: 0, y: 0, w, h }, text, theme)
207
+ + `<rect class="ss-msg-card" x="0.5" y="0.5" width="${w - 1}" height="${h - 1}" rx="8"/>`
208
+ + `<text class="ss-msg" x="${w / 2}" y="${h / 2 + 5}" text-anchor="middle" font-size="14">${esc(text)}</text>`
209
+ + '</svg>';
210
+ }
211
+
212
+ function renderRow(col, y, w) {
213
+ const center = y + ROW_H / 2;
214
+ const badges = badgeList(col);
215
+ const clusterW = badges.length ? badges.length * BADGE_W + (badges.length - 1) * BADGE_GAP : 0;
216
+ const clusterLeft = (w - PAD_X - 4) - clusterW;
217
+ const typeRight = badges.length ? clusterLeft - 8 : w - PAD_X - 16;
218
+
219
+ let s = '<g class="ss-row">';
220
+ s += `<line class="ss-sep" x1="0" y1="${y}" x2="${w}" y2="${y}"/>`;
221
+ s += `<text class="${col.pk ? 'ss-pk' : 'ss-tx'}" x="${PAD_X}" y="${center + 4}" font-family="${esc(MONO)}" font-size="12"${col.pk ? ' font-weight="700"' : ''}>${esc(col.name)}</text>`;
222
+ s += `<text class="ss-ty" x="${num(typeRight)}" y="${center + 4}" text-anchor="end" font-family="${esc(MONO)}" font-size="11">${esc(col.type)}`;
223
+ if (hasDefault(col)) s += `<tspan font-style="italic" opacity="0.8">${esc(' = ' + truncateDefault(col.default))}</tspan>`;
224
+ s += '</text>';
225
+ badges.forEach((def, i) => {
226
+ const bx = clusterLeft + i * (BADGE_W + BADGE_GAP);
227
+ s += `<rect x="${num(bx)}" y="${num(center - BADGE_H / 2)}" width="${BADGE_W}" height="${BADGE_H}" rx="3" fill="${def.color}"/>`;
228
+ s += `<text x="${num(bx + BADGE_W / 2)}" y="${center + 3}" text-anchor="middle" font-family="${esc(MONO)}" font-size="8.5" font-weight="800" letter-spacing="0.2" fill="#ffffff">${def.label}</text>`;
229
+ });
230
+ return s + '</g>';
231
+ }
232
+
233
+ function renderTable(table, pos, size) {
234
+ const { w, h } = size;
235
+ const color = safeColor(table.color);
236
+ let s = `<g class="ss-table" transform="translate(${num(pos.x)} ${num(pos.y)})">`;
237
+ s += `<rect class="ss-card" width="${w}" height="${h}" rx="8"/>`;
238
+ s += `<path d="M0 ${HEADER_H} V8 a8 8 0 0 1 8 -8 H${w - 8} a8 8 0 0 1 8 8 V${HEADER_H} Z" fill="${color}"/>`;
239
+ s += `<text x="${PAD_X}" y="${HEADER_H / 2 + 5}" font-size="13" font-weight="700" fill="#ffffff">${esc(table.name)}</text>`;
240
+ (table.columns || []).forEach((col, i) => {
241
+ s += renderRow(col, HEADER_H + i * ROW_H, w);
242
+ });
243
+ return s + '</g>';
244
+ }
245
+
246
+ function renderTables(schema, positions, sizes) {
247
+ return schema.tables.map((t) => renderTable(t, positions[t.name], sizes.get(t))).join('');
248
+ }
249
+
250
+ // Row centre of a column; a missing table or column means a stale ref (null).
251
+ function colRowCenter(tableByName, positions, sizes, tableName, colName) {
252
+ const table = tableByName.get(tableName);
253
+ const pos = positions[tableName];
254
+ if (!table || !pos) return null;
255
+ const idx = (table.columns || []).findIndex((c) => c.name === colName);
256
+ if (idx === -1) return null;
257
+ const { w } = sizes.get(table);
258
+ return { x: pos.x, y: pos.y + HEADER_H + idx * ROW_H + ROW_H / 2, xRight: pos.x + w };
259
+ }
260
+
261
+ function renderEdges(schema, positions, sizes) {
262
+ const tableByName = new Map();
263
+ for (const t of schema.tables) if (!tableByName.has(t.name)) tableByName.set(t.name, t);
264
+ let s = '';
265
+ for (const ref of schema.refs || []) {
266
+ if (!ref) continue;
267
+ const from = colRowCenter(tableByName, positions, sizes, ref.fromTable, ref.fromColumn);
268
+ const to = colRowCenter(tableByName, positions, sizes, ref.toTable, ref.toColumn);
269
+ if (!from || !to) continue;
270
+ const fromOnRight = from.x < to.x;
271
+ const p1 = { x: fromOnRight ? from.xRight : from.x, y: from.y };
272
+ const p2 = { x: fromOnRight ? to.x : to.xRight, y: to.y };
273
+ const dx = Math.max(40, Math.abs(p2.x - p1.x) / 2);
274
+ const c1x = p1.x + (fromOnRight ? dx : -dx);
275
+ const c2x = p2.x + (fromOnRight ? -dx : dx);
276
+ const d = `M ${num(p1.x)},${num(p1.y)} C ${num(c1x)},${num(p1.y)} ${num(c2x)},${num(p2.y)} ${num(p2.x)},${num(p2.y)}`;
277
+ const isMany = ref.type === '>' || ref.type === '<>';
278
+ const otherMany = ref.type === '<' || ref.type === '<>';
279
+ s += `<path class="ss-ref-line" d="${d}" marker-start="url(#ss-${otherMany ? 'crow-many' : 'one-tick'})" marker-end="url(#ss-${isMany ? 'crow-many' : 'one-tick'})"/>`;
280
+ }
281
+ return s;
282
+ }
283
+
284
+ const MARKER_DEFS = '<defs>'
285
+ + `<marker id="ss-crow-many" markerWidth="14" markerHeight="14" refX="10" refY="6" orient="auto"><path class="ss-mk" d="M0,0 L10,6 L0,12 M0,6 L10,6" fill="none" stroke="${EDGE_COLOR}" stroke-width="1.4"/></marker>`
286
+ + `<marker id="ss-one-tick" markerWidth="12" markerHeight="12" refX="8" refY="6" orient="auto"><path class="ss-mk" d="M8,0 L8,12 M4,0 L4,12" stroke="${EDGE_COLOR}" stroke-width="1.4"/></marker>`
287
+ + '</defs>';
288
+
289
+ // Returns { svg, rects } for the table-group areas. Members that are
290
+ // missing from the schema are ignored; a group with no members is skipped.
291
+ function renderAreas(schema, positions, sizes) {
292
+ const tableByName = new Map();
293
+ for (const t of schema.tables) if (!tableByName.has(t.name)) tableByName.set(t.name, t);
294
+ let s = '';
295
+ const rects = [];
296
+ for (const group of schema.tableGroups || []) {
297
+ if (!group || !Array.isArray(group.tables)) continue;
298
+ let minX = Infinity;
299
+ let minY = Infinity;
300
+ let maxX = -Infinity;
301
+ let maxY = -Infinity;
302
+ for (const name of group.tables) {
303
+ const pos = positions[name];
304
+ const table = tableByName.get(name);
305
+ if (!pos || !table) continue;
306
+ const { w, h } = sizes.get(table);
307
+ minX = Math.min(minX, pos.x);
308
+ minY = Math.min(minY, pos.y);
309
+ maxX = Math.max(maxX, pos.x + w);
310
+ maxY = Math.max(maxY, pos.y + h);
311
+ }
312
+ if (minX === Infinity) continue;
313
+ const x = minX - AREA_PAD;
314
+ const y = minY - AREA_PAD - AREA_LABEL_H;
315
+ const w = (maxX - minX) + AREA_PAD * 2;
316
+ const h = (maxY - minY) + AREA_PAD * 2 + AREA_LABEL_H;
317
+ const color = safeColor(group.color, DEFAULT_AREA_COLOR);
318
+ rects.push({ x, y, w, h });
319
+ s += '<g class="ss-area">'
320
+ + `<rect x="${num(x)}" y="${num(y)}" width="${num(w)}" height="${num(h)}" rx="12" class="ss-area-rect" fill="${color}" fill-opacity="0.12" stroke="${color}"/>`
321
+ + `<text x="${num(x + 14)}" y="${num(y + AREA_LABEL_H / 2 + 5)}" font-size="12.5" font-weight="800" fill="${color}">${esc(group.name)}</text>`
322
+ + '</g>';
323
+ }
324
+ return { svg: s, rects };
325
+ }
326
+
327
+ export function renderSvg(schema, positions = {}, options = {}) {
328
+ const opts = options && typeof options === 'object' ? options : {};
329
+ const title = opts.title ? String(opts.title) : 'Database diagram';
330
+ const theme = normTheme(opts.theme);
331
+ const tables = schema && Array.isArray(schema.tables) ? schema.tables : [];
332
+ if (tables.length === 0) return messageSvg('Empty diagram', theme);
333
+ if (tables.length > MAX_TABLES) return messageSvg('Diagram too large to preview, open it in SchemaSketch', theme);
334
+
335
+ const full = { tables, refs: schema.refs, tableGroups: schema.tableGroups };
336
+ const pos = layout(full, positions);
337
+ const sizes = new Map(tables.map((t) => [t, measureTable(t)]));
338
+
339
+ let minX = Infinity;
340
+ let minY = Infinity;
341
+ let maxX = -Infinity;
342
+ let maxY = -Infinity;
343
+ for (const t of tables) {
344
+ const p = pos[t.name];
345
+ const { w, h } = sizes.get(t);
346
+ minX = Math.min(minX, p.x);
347
+ minY = Math.min(minY, p.y);
348
+ maxX = Math.max(maxX, p.x + w);
349
+ maxY = Math.max(maxY, p.y + h);
350
+ }
351
+ const areas = renderAreas(full, pos, sizes);
352
+ for (const r of areas.rects) {
353
+ minX = Math.min(minX, r.x);
354
+ minY = Math.min(minY, r.y);
355
+ maxX = Math.max(maxX, r.x + r.w);
356
+ maxY = Math.max(maxY, r.y + r.h);
357
+ }
358
+ const vb = { x: minX - EXPORT_PAD, y: minY - EXPORT_PAD, w: maxX - minX + EXPORT_PAD * 2, h: maxY - minY + EXPORT_PAD * 2 };
359
+
360
+ const edges = renderEdges(full, pos, sizes);
361
+ return svgOpen(vb, title, theme)
362
+ + (edges ? MARKER_DEFS : '')
363
+ + areas.svg
364
+ + edges
365
+ + renderTables(full, pos, sizes)
366
+ + '</svg>';
367
+ }