@standarx/graph 0.0.0-stage → 1.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.
Files changed (127) hide show
  1. package/LICENSE +21 -0
  2. package/README.fr.md +438 -0
  3. package/README.md +437 -2
  4. package/THIRD_PARTY_NOTICES.md +22 -0
  5. package/assets/fonts/Inter-Regular.ttf +0 -0
  6. package/assets/fonts/Inter-SemiBold.ttf +0 -0
  7. package/assets/fonts/OFL.txt +92 -0
  8. package/dist/adapter-0bggwh8x.js +393 -0
  9. package/dist/cli-4m00785g.js +20 -0
  10. package/dist/cli-5v9761s9.js +330 -0
  11. package/dist/cli-9f1pdw5q.js +462 -0
  12. package/dist/cli-a4ax1vkc.js +172 -0
  13. package/dist/cli-abzdy8pn.js +1144 -0
  14. package/dist/cli-gh5166k6.js +1565 -0
  15. package/dist/cli-m29a3wgx.js +579 -0
  16. package/dist/cli-mzmjkk5v.js +11 -0
  17. package/dist/cli-nhmh6yxk.js +2485 -0
  18. package/dist/cli-nyckgf1t.js +4 -0
  19. package/dist/cli-sfdqkbd1.js +433 -0
  20. package/dist/cli-txrzzr2q.js +0 -0
  21. package/dist/cli-vecew2na.js +709 -0
  22. package/dist/cli-wt9dmbhm.js +560 -0
  23. package/dist/cli-ywgtv1cg.js +39 -0
  24. package/dist/cli-z3ccx2y4.js +141 -0
  25. package/dist/cli.d.ts +2 -0
  26. package/dist/cli.js +413 -0
  27. package/dist/core/index.d.ts +6 -0
  28. package/dist/core/index.js +91 -0
  29. package/dist/core/spatial.d.ts +16 -0
  30. package/dist/core/threshold.d.ts +1 -0
  31. package/dist/core/view.d.ts +80 -0
  32. package/dist/export/index.d.ts +18 -0
  33. package/dist/export/index.js +170 -0
  34. package/dist/export/pdf.d.ts +5 -0
  35. package/dist/export/png.d.ts +4 -0
  36. package/dist/format/index.d.ts +4 -0
  37. package/dist/format/index.js +69 -0
  38. package/dist/format/json-schema.d.ts +2 -0
  39. package/dist/format/schema.d.ts +787 -0
  40. package/dist/format/semantic/er.d.ts +3 -0
  41. package/dist/format/semantic/graph.d.ts +3 -0
  42. package/dist/format/semantic/sequence.d.ts +3 -0
  43. package/dist/format/semantic/shared.d.ts +14 -0
  44. package/dist/format/semantic/state.d.ts +3 -0
  45. package/dist/format/semantic/tree.d.ts +3 -0
  46. package/dist/format/transition-label.d.ts +2 -0
  47. package/dist/format/validate.d.ts +11 -0
  48. package/dist/html/index.d.ts +3 -0
  49. package/dist/html/index.js +125 -0
  50. package/dist/html/layout-worker.d.ts +1 -0
  51. package/dist/html/layout-worker.generated.d.ts +1 -0
  52. package/dist/html/mount.d.ts +12 -0
  53. package/dist/html/page.d.ts +14 -0
  54. package/dist/html/render.d.ts +7 -0
  55. package/dist/html/runtime.d.ts +1 -0
  56. package/dist/html/runtime.generated.d.ts +1 -0
  57. package/dist/html/shell.d.ts +10 -0
  58. package/dist/html/svg-adapter.d.ts +8 -0
  59. package/dist/html/ui.d.ts +34 -0
  60. package/dist/language/actions.d.ts +3 -0
  61. package/dist/language/analysis.d.ts +38 -0
  62. package/dist/language/complete.d.ts +3 -0
  63. package/dist/language/diagnostics.d.ts +14 -0
  64. package/dist/language/docs.d.ts +11 -0
  65. package/dist/language/format.d.ts +17 -0
  66. package/dist/language/hover.d.ts +3 -0
  67. package/dist/language/index.d.ts +8 -0
  68. package/dist/language/index.js +1560 -0
  69. package/dist/language/navigation.d.ts +9 -0
  70. package/dist/language/positions.d.ts +7 -0
  71. package/dist/language/symbols.d.ts +3 -0
  72. package/dist/language/types.d.ts +46 -0
  73. package/dist/layout/elk.d.ts +35 -0
  74. package/dist/layout/er.d.ts +3 -0
  75. package/dist/layout/font-metrics.d.ts +9 -0
  76. package/dist/layout/graph.d.ts +3 -0
  77. package/dist/layout/index.d.ts +5 -0
  78. package/dist/layout/index.js +16 -0
  79. package/dist/layout/measure.d.ts +10 -0
  80. package/dist/layout/sequence.d.ts +3 -0
  81. package/dist/layout/shapes.d.ts +16 -0
  82. package/dist/layout/shared.d.ts +31 -0
  83. package/dist/layout/state.d.ts +3 -0
  84. package/dist/layout/tree.d.ts +3 -0
  85. package/dist/layout/types.d.ts +198 -0
  86. package/dist/layout-worker.generated-xsmtzrfj.js +34 -0
  87. package/dist/mermaid/common.d.ts +36 -0
  88. package/dist/mermaid/er.d.ts +3 -0
  89. package/dist/mermaid/graph.d.ts +4 -0
  90. package/dist/mermaid/index.d.ts +6 -0
  91. package/dist/mermaid/index.js +6 -0
  92. package/dist/mermaid/mindmap.d.ts +3 -0
  93. package/dist/mermaid/sequence.d.ts +3 -0
  94. package/dist/mermaid/state.d.ts +3 -0
  95. package/dist/remark/index.d.ts +9 -0
  96. package/dist/remark/index.js +102 -0
  97. package/dist/shared/errors.d.ts +6 -0
  98. package/dist/shared/package-root.d.ts +5 -0
  99. package/dist/svg/escape.d.ts +1 -0
  100. package/dist/svg/index.d.ts +3 -0
  101. package/dist/svg/index.js +25 -0
  102. package/dist/svg/render.d.ts +9 -0
  103. package/dist/svg/theme.d.ts +62 -0
  104. package/dist/svg-adapter-gq5vmp6q.js +227 -0
  105. package/dist/text/build.d.ts +10 -0
  106. package/dist/text/canonical.d.ts +10 -0
  107. package/dist/text/errors.d.ts +33 -0
  108. package/dist/text/highlight.d.ts +13 -0
  109. package/dist/text/index.d.ts +33 -0
  110. package/dist/text/index.js +25 -0
  111. package/dist/text/lexer.d.ts +29 -0
  112. package/dist/text/parser.d.ts +160 -0
  113. package/dist/text/print.d.ts +6 -0
  114. package/dist/text/slug.d.ts +1 -0
  115. package/dist/text/syntax.d.ts +8 -0
  116. package/dist/version.d.ts +1 -0
  117. package/dist/webgl/adapter.d.ts +4 -0
  118. package/dist/webgl/index.d.ts +7 -0
  119. package/dist/webgl/index.js +15 -0
  120. package/dist/webgl/runtime.d.ts +1 -0
  121. package/dist/webgl/runtime.generated.d.ts +1 -0
  122. package/grammars/standargraph.tmLanguage.json +599 -0
  123. package/language-configuration.json +35 -0
  124. package/licenses/EPL-2.0.txt +277 -0
  125. package/licenses/MPL-2.0.txt +373 -0
  126. package/package.json +133 -4
  127. package/schema/graph-document.v1.json +1737 -0
@@ -0,0 +1,2485 @@
1
+ import {
2
+ SHAPES2,
3
+ DirectionSchema2,
4
+ PSEUDO2,
5
+ TREE_LAYOUTS2,
6
+ validate2
7
+ } from "./cli-m29a3wgx.js";
8
+
9
+ // src/text/slug.ts
10
+ function slug(label) {
11
+ const base = label.normalize("NFKD").replace(/\p{M}/gu, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
12
+ return base === "" ? "node" : base;
13
+ }
14
+
15
+ // src/text/build.ts
16
+ var DIRECTIONS = DirectionSchema2.anyOf.map((literal) => literal.const);
17
+ var CONFIDENCES = ["confirmed", "inferred", "unknown"];
18
+ var META_FIELDS = {
19
+ source: "string",
20
+ confidence: CONFIDENCES,
21
+ tool: "string",
22
+ coverage: "number",
23
+ freshness: "string"
24
+ };
25
+ var PROVENANCE_KEYS = new Set(["source", "confidence", "tool"]);
26
+ var META_NAMES = [...Object.keys(META_FIELDS), "data.*"];
27
+ var NODE = {
28
+ noun: "a node",
29
+ fields: { type: "string", shape: SHAPES2, link: "string", description: "string", x: "number", y: "number" },
30
+ meta: true,
31
+ position: true
32
+ };
33
+ var GROUP = { noun: "a group", fields: {}, meta: true };
34
+ var EDGE = { noun: "an edge", fields: { id: "string", type: "string" }, meta: true };
35
+ var PARTICIPANT = { noun: "a participant", fields: { type: "string" }, meta: true };
36
+ var MESSAGE = { noun: "a message", fields: {}, meta: true };
37
+ var STATE = {
38
+ noun: "a state",
39
+ fields: { type: "string", pseudo: PSEUDO2, actions: "strings", description: "string", link: "string" },
40
+ meta: true
41
+ };
42
+ var TRANSITION = {
43
+ noun: "a transition",
44
+ fields: { id: "string", guard: "string", action: "string", type: "string" },
45
+ meta: true
46
+ };
47
+ var ENTITY = {
48
+ noun: "an entity",
49
+ fields: { type: "string", description: "string", link: "string" },
50
+ meta: true
51
+ };
52
+ var ATTRIBUTE = { noun: "an attribute", fields: { note: "string" }, meta: false };
53
+ var RELATION = { noun: "a relation", fields: { id: "string", type: "string" }, meta: true };
54
+ var TREE_NODE = {
55
+ noun: "a tree node",
56
+ fields: { id: "string", type: "string", shape: SHAPES2, description: "string", link: "string" },
57
+ meta: true
58
+ };
59
+ var HEADERS = {
60
+ graph: { noun: "the header", fields: { direction: DIRECTIONS }, meta: true },
61
+ sequence: { noun: "the header", fields: {}, meta: true },
62
+ state: { noun: "the header", fields: { direction: DIRECTIONS }, meta: true },
63
+ er: { noun: "the header", fields: { direction: DIRECTIONS }, meta: true },
64
+ tree: { noun: "the header", fields: { direction: DIRECTIONS, layout: TREE_LAYOUTS2 }, meta: true }
65
+ };
66
+ function mark(ctx, pointer, range) {
67
+ ctx.marks.set(pointer, range);
68
+ }
69
+ function describe(value) {
70
+ if (value.type === "list")
71
+ return "a list";
72
+ if (value.type === "number")
73
+ return String(value.value);
74
+ return JSON.stringify(value.value);
75
+ }
76
+ function isStringLike(value) {
77
+ return value.type === "string" || value.type === "ident";
78
+ }
79
+ function coerce(ctx, attr, field) {
80
+ const value = attr.value;
81
+ let expects;
82
+ if (field === "number") {
83
+ if (value.type === "number")
84
+ return value.value;
85
+ expects = "a number";
86
+ } else if (field === "strings") {
87
+ if (value.type === "list" && value.items.every(isStringLike)) {
88
+ return value.items.map((item) => item.value);
89
+ }
90
+ expects = "a list of strings";
91
+ } else if (field === "string") {
92
+ if (isStringLike(value))
93
+ return value.value;
94
+ expects = "a string";
95
+ } else {
96
+ if (isStringLike(value) && field.includes(value.value))
97
+ return value.value;
98
+ expects = `one of ${field.join(", ")}`;
99
+ }
100
+ ctx.sink.report("E_VALUE", value.range, `Attribute "${attr.key}" expects ${expects}; found ${describe(value)}`);
101
+ return;
102
+ }
103
+ function coerceData(ctx, attr) {
104
+ const value = attr.value;
105
+ if (value.type === "string" || value.type === "number")
106
+ return value.value;
107
+ if (value.type === "ident" && (value.value === "true" || value.value === "false")) {
108
+ return value.value === "true";
109
+ }
110
+ ctx.sink.report("E_VALUE", value.range, `Attribute "${attr.key}" expects a string, a number or a boolean; found ${describe(value)}`);
111
+ return;
112
+ }
113
+ function applyMeta(ctx, attr, target, pointer) {
114
+ const { key } = attr;
115
+ const isData = key.startsWith("data.") && key.length > 5;
116
+ if (!isData && !Object.hasOwn(META_FIELDS, key))
117
+ return false;
118
+ const value = isData ? coerceData(ctx, attr) : coerce(ctx, attr, META_FIELDS[key]);
119
+ if (value === undefined)
120
+ return true;
121
+ const meta = target.meta ??= {};
122
+ const base = `${pointer}/meta`;
123
+ mark(ctx, base, attr.range);
124
+ if (isData) {
125
+ const name = key.slice(5);
126
+ (meta.data ??= {})[name] = value;
127
+ mark(ctx, `${base}/data`, attr.range);
128
+ mark(ctx, `${base}/data/${name}`, attr.value.range);
129
+ } else if (PROVENANCE_KEYS.has(key)) {
130
+ (meta.provenance ??= {})[key] = value;
131
+ mark(ctx, `${base}/provenance`, attr.range);
132
+ mark(ctx, `${base}/provenance/${key}`, attr.value.range);
133
+ } else {
134
+ meta[key] = value;
135
+ mark(ctx, `${base}/${key}`, attr.value.range);
136
+ }
137
+ return true;
138
+ }
139
+ function applyAttrs(ctx, attrs, spec, target, pointer) {
140
+ const seen = new Set;
141
+ const coordinates = new Map;
142
+ let needsSource;
143
+ for (const attr of attrs) {
144
+ const { key } = attr;
145
+ if (seen.has(key)) {
146
+ ctx.sink.report("E_ATTR", attr.keyRange, `Attribute "${key}" is set twice`);
147
+ continue;
148
+ }
149
+ seen.add(key);
150
+ if (Object.hasOwn(spec.fields, key)) {
151
+ const value = coerce(ctx, attr, spec.fields[key]);
152
+ if (value === undefined)
153
+ continue;
154
+ if (spec.position && (key === "x" || key === "y")) {
155
+ coordinates.set(key, { value, attr });
156
+ } else {
157
+ target[key] = value;
158
+ mark(ctx, `${pointer}/${key}`, attr.value.range);
159
+ }
160
+ continue;
161
+ }
162
+ if (spec.meta && applyMeta(ctx, attr, target, pointer)) {
163
+ if (key === "confidence" || key === "tool")
164
+ needsSource ??= attr;
165
+ continue;
166
+ }
167
+ const expected = [...Object.keys(spec.fields), ...spec.meta ? META_NAMES : []];
168
+ ctx.sink.report("E_ATTR", attr.keyRange, `Unknown attribute "${key}" for ${spec.noun} (expected: ${expected.join(", ")})`);
169
+ }
170
+ if (spec.position && coordinates.size > 0) {
171
+ const x = coordinates.get("x");
172
+ const y = coordinates.get("y");
173
+ if (x && y) {
174
+ target.position = { x: x.value, y: y.value };
175
+ mark(ctx, `${pointer}/position`, { start: x.attr.range.start, end: y.attr.range.end });
176
+ mark(ctx, `${pointer}/position/x`, x.attr.value.range);
177
+ mark(ctx, `${pointer}/position/y`, y.attr.value.range);
178
+ } else {
179
+ ctx.sink.report("E_ATTR", (x ?? y).attr.keyRange, "x and y go together");
180
+ }
181
+ }
182
+ if (needsSource) {
183
+ const meta = target.meta;
184
+ const provenance = meta?.provenance;
185
+ if (provenance?.source === undefined) {
186
+ ctx.sink.report("E_ATTR", needsSource.keyRange, "confidence and tool need a source");
187
+ }
188
+ }
189
+ }
190
+ function setLabel(ctx, item, pointer, label) {
191
+ if (!label)
192
+ return;
193
+ item.label = label.value;
194
+ mark(ctx, `${pointer}/label`, label.range);
195
+ }
196
+
197
+ class Registry {
198
+ ctx;
199
+ collection;
200
+ noun;
201
+ blockField;
202
+ items = [];
203
+ entries = new Map;
204
+ constructor(ctx, collection, noun, blockField) {
205
+ this.ctx = ctx;
206
+ this.collection = collection;
207
+ this.noun = noun;
208
+ this.blockField = blockField;
209
+ }
210
+ pointer(entry) {
211
+ return `/${this.collection}/${entry.index}`;
212
+ }
213
+ item(entry) {
214
+ return this.items[entry.index];
215
+ }
216
+ mention(id, block) {
217
+ let entry = this.entries.get(id.value);
218
+ if (!entry) {
219
+ const item = { id: id.value };
220
+ if (this.blockField && block !== undefined)
221
+ item[this.blockField] = block;
222
+ entry = {
223
+ index: this.items.length,
224
+ block,
225
+ line: this.ctx.sink.lineOf(id.range.start),
226
+ declared: false
227
+ };
228
+ this.items.push(item);
229
+ this.entries.set(id.value, entry);
230
+ mark(this.ctx, this.pointer(entry), id.range);
231
+ mark(this.ctx, `${this.pointer(entry)}/id`, id.range);
232
+ }
233
+ return entry;
234
+ }
235
+ declare(id, block, range) {
236
+ const existing = this.entries.get(id.value);
237
+ if (existing?.declared) {
238
+ this.ctx.sink.report("E_DUPLICATE", id.range, `${this.noun} "${id.value}" is already declared at line ${existing.line}`);
239
+ return;
240
+ }
241
+ if (existing && existing.block !== block) {
242
+ this.ctx.sink.report("E_REGION", id.range, `${this.noun} "${id.value}" was first used in "${existing.block ?? "root"}" at line ${existing.line} and cannot be declared in another block`);
243
+ return;
244
+ }
245
+ const entry = this.mention(id, block);
246
+ entry.declared = true;
247
+ entry.line = this.ctx.sink.lineOf(id.range.start);
248
+ mark(this.ctx, this.pointer(entry), range);
249
+ return entry;
250
+ }
251
+ }
252
+ function buildGraph(ast, ctx) {
253
+ const nodes = new Registry(ctx, "nodes", "Node", "group");
254
+ const groups = new Registry(ctx, "groups", "Group", "parent");
255
+ const edges = [];
256
+ const walk = (statements, block) => {
257
+ for (const statement of statements) {
258
+ if (statement.t === "group") {
259
+ const entry = groups.declare(statement.id, block, statement.range);
260
+ if (entry) {
261
+ const item = groups.item(entry);
262
+ setLabel(ctx, item, groups.pointer(entry), statement.label);
263
+ applyAttrs(ctx, statement.attrs, GROUP, item, groups.pointer(entry));
264
+ }
265
+ walk(statement.body, statement.id.value);
266
+ } else if (statement.t === "node") {
267
+ const entry = nodes.declare(statement.id, block, statement.range);
268
+ if (entry) {
269
+ const item = nodes.item(entry);
270
+ setLabel(ctx, item, nodes.pointer(entry), statement.label);
271
+ applyAttrs(ctx, statement.attrs, NODE, item, nodes.pointer(entry));
272
+ }
273
+ } else {
274
+ for (const id of statement.ids)
275
+ nodes.mention(id, block);
276
+ const several = statement.ops.length > 1;
277
+ const attrs = several ? statement.attrs.filter((attr) => {
278
+ if (attr.key !== "id")
279
+ return true;
280
+ ctx.sink.report("E_ATTR", attr.keyRange, "id cannot be set on a chain of several edges");
281
+ return false;
282
+ }) : statement.attrs;
283
+ statement.ops.forEach((op, position) => {
284
+ const edge = {
285
+ from: statement.ids[position].value,
286
+ to: statement.ids[position + 1].value
287
+ };
288
+ const pointer = `/edges/${edges.length}`;
289
+ edges.push(edge);
290
+ mark(ctx, pointer, statement.range);
291
+ mark(ctx, `${pointer}/from`, statement.ids[position].range);
292
+ mark(ctx, `${pointer}/to`, statement.ids[position + 1].range);
293
+ mark(ctx, `${pointer}/directed`, op.range);
294
+ setLabel(ctx, edge, pointer, statement.label);
295
+ edge.directed = op.symbol === "->";
296
+ if (position > 0)
297
+ ctx.sink.muted++;
298
+ applyAttrs(ctx, attrs, EDGE, edge, pointer);
299
+ if (position > 0)
300
+ ctx.sink.muted--;
301
+ });
302
+ }
303
+ }
304
+ };
305
+ walk(ast.body, undefined);
306
+ const result = { nodes: nodes.items };
307
+ if (edges.length > 0)
308
+ result.edges = edges;
309
+ if (groups.items.length > 0)
310
+ result.groups = groups.items;
311
+ return result;
312
+ }
313
+ function buildSequence(ast, ctx) {
314
+ const participants = new Registry(ctx, "participants", "Participant");
315
+ const messages = [];
316
+ for (const statement of ast.body) {
317
+ if (statement.t === "participant") {
318
+ const entry = participants.declare(statement.id, undefined, statement.range);
319
+ if (entry) {
320
+ const item = participants.item(entry);
321
+ setLabel(ctx, item, participants.pointer(entry), statement.label);
322
+ applyAttrs(ctx, statement.attrs, PARTICIPANT, item, participants.pointer(entry));
323
+ }
324
+ } else {
325
+ participants.mention(statement.from, undefined);
326
+ participants.mention(statement.to, undefined);
327
+ const pointer = `/messages/${messages.length}`;
328
+ const message = { from: statement.from.value, to: statement.to.value };
329
+ messages.push(message);
330
+ mark(ctx, pointer, statement.range);
331
+ mark(ctx, `${pointer}/from`, statement.from.range);
332
+ mark(ctx, `${pointer}/to`, statement.to.range);
333
+ mark(ctx, `${pointer}/style`, statement.op.range);
334
+ setLabel(ctx, message, pointer, statement.label);
335
+ message.style = statement.op.symbol === "->" ? "sync" : statement.op.symbol === "->>" ? "async" : "reply";
336
+ applyAttrs(ctx, statement.attrs, MESSAGE, message, pointer);
337
+ }
338
+ }
339
+ return { participants: participants.items, messages };
340
+ }
341
+ function buildState(ast, ctx) {
342
+ const states = new Registry(ctx, "states", "State", "parent");
343
+ const transitions = [];
344
+ const endpoint = (target, pseudo, block) => {
345
+ if (!target.star) {
346
+ states.mention(target, block);
347
+ return target.value;
348
+ }
349
+ const id = `${block ?? ""}__${pseudo}`;
350
+ const before = states.items.length;
351
+ const entry = states.mention({ value: id, range: target.range }, block);
352
+ const item = states.item(entry);
353
+ if (states.items.length > before) {
354
+ item.pseudo = pseudo;
355
+ mark(ctx, `${states.pointer(entry)}/pseudo`, target.range);
356
+ } else if (item.pseudo !== pseudo) {
357
+ ctx.sink.report("E_VALUE", target.range, `State "${id}" already exists and is not an ${pseudo} pseudo-state, so "*" cannot stand for it`);
358
+ }
359
+ return id;
360
+ };
361
+ const walk = (statements, block) => {
362
+ for (const statement of statements) {
363
+ if (statement.t === "state") {
364
+ const entry = states.declare(statement.id, block, statement.range);
365
+ if (entry) {
366
+ const item = states.item(entry);
367
+ const pointer = states.pointer(entry);
368
+ const previous = item.pseudo;
369
+ setLabel(ctx, item, pointer, statement.label);
370
+ applyAttrs(ctx, statement.attrs, STATE, item, pointer);
371
+ if (previous !== undefined && item.pseudo !== previous) {
372
+ ctx.sink.report("E_VALUE", ctx.marks.get(`${pointer}/pseudo`) ?? statement.id.range, `State "${statement.id.value}" is already the ${String(previous)} pseudo-state used by "*"`);
373
+ }
374
+ }
375
+ if (statement.body)
376
+ walk(statement.body, statement.id.value);
377
+ } else {
378
+ const from = endpoint(statement.from, "initial", block);
379
+ const to = endpoint(statement.to, "final", block);
380
+ const pointer = `/transitions/${transitions.length}`;
381
+ const transition = { from, to };
382
+ transitions.push(transition);
383
+ mark(ctx, pointer, statement.range);
384
+ mark(ctx, `${pointer}/from`, statement.from.range);
385
+ mark(ctx, `${pointer}/to`, statement.to.range);
386
+ if (statement.label) {
387
+ transition.event = statement.label.value;
388
+ mark(ctx, `${pointer}/event`, statement.label.range);
389
+ }
390
+ applyAttrs(ctx, statement.attrs, TRANSITION, transition, pointer);
391
+ }
392
+ }
393
+ };
394
+ walk(ast.body, undefined);
395
+ const result = { states: states.items };
396
+ if (transitions.length > 0)
397
+ result.transitions = transitions;
398
+ return result;
399
+ }
400
+ function buildEr(ast, ctx) {
401
+ const entities = new Registry(ctx, "entities", "Entity");
402
+ const relations = [];
403
+ for (const statement of ast.body) {
404
+ if (statement.t === "entity") {
405
+ const entry = entities.declare(statement.id, undefined, statement.range);
406
+ if (!entry)
407
+ continue;
408
+ const item = entities.item(entry);
409
+ const pointer = entities.pointer(entry);
410
+ setLabel(ctx, item, pointer, statement.label);
411
+ applyAttrs(ctx, statement.attrs, ENTITY, item, pointer);
412
+ if (statement.attributes) {
413
+ item.attributes = statement.attributes.map((line, index) => {
414
+ const attribute = { name: line.name.value };
415
+ const at = `${pointer}/attributes/${index}`;
416
+ mark(ctx, at, line.range);
417
+ mark(ctx, `${at}/name`, line.name.range);
418
+ if (line.type) {
419
+ attribute.type = line.type.value;
420
+ mark(ctx, `${at}/type`, line.type.range);
421
+ }
422
+ const keys = [];
423
+ for (const flag of line.flags) {
424
+ if (flag.value === "null") {
425
+ attribute.nullable = true;
426
+ mark(ctx, `${at}/nullable`, flag.range);
427
+ } else {
428
+ mark(ctx, `${at}/keys/${keys.length}`, flag.range);
429
+ keys.push(flag.value);
430
+ }
431
+ }
432
+ if (keys.length > 0) {
433
+ attribute.keys = keys;
434
+ mark(ctx, `${at}/keys`, line.flags.find((flag) => flag.value !== "null").range);
435
+ }
436
+ applyAttrs(ctx, line.attrs, ATTRIBUTE, attribute, at);
437
+ return attribute;
438
+ });
439
+ }
440
+ } else {
441
+ entities.mention(statement.from, undefined);
442
+ entities.mention(statement.to, undefined);
443
+ const pointer = `/relations/${relations.length}`;
444
+ const relation = { from: statement.from.value, to: statement.to.value };
445
+ relations.push(relation);
446
+ mark(ctx, pointer, statement.range);
447
+ mark(ctx, `${pointer}/from`, statement.from.range);
448
+ mark(ctx, `${pointer}/to`, statement.to.range);
449
+ mark(ctx, `${pointer}/identifying`, statement.op.range);
450
+ if (statement.fromCard) {
451
+ relation.fromCardinality = statement.fromCard.value;
452
+ mark(ctx, `${pointer}/fromCardinality`, statement.fromCard.range);
453
+ }
454
+ if (statement.toCard) {
455
+ relation.toCardinality = statement.toCard.value;
456
+ mark(ctx, `${pointer}/toCardinality`, statement.toCard.range);
457
+ }
458
+ setLabel(ctx, relation, pointer, statement.label);
459
+ relation.identifying = statement.op.symbol === "--";
460
+ applyAttrs(ctx, statement.attrs, RELATION, relation, pointer);
461
+ }
462
+ }
463
+ const result = { entities: entities.items };
464
+ if (relations.length > 0)
465
+ result.relations = relations;
466
+ return result;
467
+ }
468
+ function buildTree(ast, ctx) {
469
+ const nodes = ast.body.map(() => ({}));
470
+ const explicit = new Map;
471
+ ast.body.forEach((line, index) => {
472
+ const node = nodes[index];
473
+ const pointer = `/nodes/${index}`;
474
+ mark(ctx, pointer, line.range);
475
+ applyAttrs(ctx, line.attrs, TREE_NODE, node, pointer);
476
+ node.label = line.label.value;
477
+ mark(ctx, `${pointer}/label`, line.label.range);
478
+ if (typeof node.id !== "string")
479
+ return;
480
+ const first = explicit.get(node.id);
481
+ if (first === undefined) {
482
+ explicit.set(node.id, index);
483
+ } else {
484
+ ctx.sink.report("E_DUPLICATE", ctx.marks.get(`${pointer}/id`) ?? line.label.range, `Node "${node.id}" is already declared at line ${ctx.sink.lineOf(ast.body[first].range.start)}`);
485
+ }
486
+ });
487
+ const used = new Set(explicit.keys());
488
+ ast.body.forEach((line, index) => {
489
+ const node = nodes[index];
490
+ const pointer = `/nodes/${index}`;
491
+ if (node.id === undefined) {
492
+ const base = slug(line.label.value);
493
+ let candidate = base;
494
+ for (let suffix = 2;used.has(candidate); suffix++)
495
+ candidate = `${base}-${suffix}`;
496
+ used.add(candidate);
497
+ node.id = candidate;
498
+ mark(ctx, `${pointer}/id`, line.label.range);
499
+ }
500
+ if (line.parent >= 0) {
501
+ node.parent = nodes[line.parent].id;
502
+ mark(ctx, `${pointer}/parent`, line.label.range);
503
+ }
504
+ });
505
+ return { nodes };
506
+ }
507
+ function build(ast, ctx) {
508
+ const result = { version: 1, kind: ast.kind };
509
+ const { header } = ast;
510
+ mark(ctx, "", header.range);
511
+ mark(ctx, "/kind", header.kindRange);
512
+ if (header.title) {
513
+ result.title = header.title.value;
514
+ mark(ctx, "/title", header.title.range);
515
+ }
516
+ const attrs = header.attrs.filter((attr) => {
517
+ if (attr.key !== "version")
518
+ return true;
519
+ ctx.sink.report("E_ATTR", attr.keyRange, "version is implied (1) in the text syntax");
520
+ return false;
521
+ });
522
+ applyAttrs(ctx, attrs, HEADERS[ast.kind], result, "");
523
+ switch (ast.kind) {
524
+ case "graph":
525
+ return Object.assign(result, buildGraph(ast, ctx));
526
+ case "sequence":
527
+ return Object.assign(result, buildSequence(ast, ctx));
528
+ case "state":
529
+ return Object.assign(result, buildState(ast, ctx));
530
+ case "er":
531
+ return Object.assign(result, buildEr(ast, ctx));
532
+ case "tree":
533
+ return Object.assign(result, buildTree(ast, ctx));
534
+ }
535
+ }
536
+
537
+ // src/text/errors.ts
538
+ var STOP = Symbol("too many errors");
539
+ var MAX_ERRORS = 50;
540
+
541
+ class LineMap {
542
+ starts = [0];
543
+ constructor(source) {
544
+ for (let index = 0;index < source.length; index++) {
545
+ if (source.charCodeAt(index) === 10)
546
+ this.starts.push(index + 1);
547
+ }
548
+ }
549
+ line(offset) {
550
+ let low = 0;
551
+ let high = this.starts.length - 1;
552
+ while (low < high) {
553
+ const middle = low + high + 1 >> 1;
554
+ if (this.starts[middle] <= offset)
555
+ low = middle;
556
+ else
557
+ high = middle - 1;
558
+ }
559
+ return low + 1;
560
+ }
561
+ position(offset) {
562
+ const line = this.line(offset);
563
+ return { line, column: offset - this.starts[line - 1] + 1 };
564
+ }
565
+ error(code, range, message) {
566
+ const start = this.position(range.start);
567
+ const end = this.position(range.end);
568
+ return {
569
+ line: start.line,
570
+ column: start.column,
571
+ endLine: end.line,
572
+ endColumn: end.column,
573
+ code,
574
+ message
575
+ };
576
+ }
577
+ }
578
+
579
+ class Sink {
580
+ lines;
581
+ errors = [];
582
+ muted = 0;
583
+ constructor(lines) {
584
+ this.lines = lines;
585
+ }
586
+ lineOf(offset) {
587
+ return this.lines.line(offset);
588
+ }
589
+ report(code, range, message) {
590
+ if (this.muted > 0)
591
+ return;
592
+ if (this.errors.length >= MAX_ERRORS) {
593
+ this.errors.push(this.lines.error("E_TOKEN", range, "Too many errors"));
594
+ throw STOP;
595
+ }
596
+ this.errors.push(this.lines.error(code, range, message));
597
+ }
598
+ sorted() {
599
+ return this.errors.map((error, order) => ({ error, order })).sort((a, b) => a.error.line - b.error.line || a.error.column - b.error.column || a.order - b.order).map(({ error }) => error);
600
+ }
601
+ }
602
+
603
+ // src/text/lexer.ts
604
+ var OPERATORS = [
605
+ ["-->", "REPLY"],
606
+ ["->>", "ASYNC"],
607
+ ["->", "ARROW"],
608
+ ["--", "LINE"]
609
+ ];
610
+ var CARD = /0\.\.1|1\.\.\*|0\.\.\*/y;
611
+ var NUMBER = /-?[0-9]+(?:\.[0-9]+)?(?:[eE][-+]?[0-9]+)?/y;
612
+ var IDENT = /[\p{L}_][\p{L}\p{N}_]*(?:[./-][\p{L}\p{N}_]+)*/uy;
613
+ var UNICODE_ESCAPE = /^\{([0-9a-fA-F]{1,6})\}/;
614
+ var SIMPLE_ESCAPES = { n: `
615
+ `, t: "\t" };
616
+ var PUNCTUATION = "{}[]()=,*";
617
+ function normalize(source) {
618
+ return source.replace(/^/, "").replace(/\r\n/g, `
619
+ `);
620
+ }
621
+
622
+ class Lexer {
623
+ source;
624
+ sink;
625
+ comments;
626
+ pos = 0;
627
+ depth = 0;
628
+ openAt = 0;
629
+ constructor(source, sink, comments) {
630
+ this.source = source;
631
+ this.sink = sink;
632
+ this.comments = comments;
633
+ }
634
+ seek(pos) {
635
+ this.pos = pos;
636
+ this.depth = 0;
637
+ }
638
+ next() {
639
+ const source = this.source;
640
+ let char;
641
+ for (;; ) {
642
+ char = source[this.pos];
643
+ while (char === " " || char === "\t")
644
+ char = source[++this.pos];
645
+ if (char === "#") {
646
+ const commentStart = this.pos;
647
+ while (char !== undefined && char !== `
648
+ `)
649
+ char = source[++this.pos];
650
+ this.comments?.push({ start: commentStart, end: this.pos });
651
+ }
652
+ if (char === `
653
+ `) {
654
+ const start = this.pos++;
655
+ if (this.depth > 0)
656
+ continue;
657
+ return this.token("NEWLINE", start, this.pos);
658
+ }
659
+ break;
660
+ }
661
+ if (char === undefined) {
662
+ if (this.depth === 0)
663
+ return this.token("EOF", this.pos, this.pos);
664
+ const at = this.openAt;
665
+ this.depth = 0;
666
+ this.sink.report("E_EXPECTED", { start: at, end: at + 1 }, `Expected "]" before the end of the file: the "[" opened at line ${this.sink.lineOf(at)} is never closed`);
667
+ return this.token("ERROR", at, at + 1);
668
+ }
669
+ const start = this.pos;
670
+ if (char === '"')
671
+ return this.quoted(start, '"', "STRING");
672
+ if (char === "`")
673
+ return this.quoted(start, "`", "QUOTED_ID");
674
+ for (const [text, kind] of OPERATORS) {
675
+ if (source.startsWith(text, start))
676
+ return this.advance(kind, start, text.length);
677
+ }
678
+ CARD.lastIndex = start;
679
+ const card = CARD.exec(source);
680
+ if (card)
681
+ return this.advance("CARD", start, card[0].length);
682
+ if (source.startsWith("..", start))
683
+ return this.advance("DOTS", start, 2);
684
+ if (PUNCTUATION.includes(char)) {
685
+ if (char === "[") {
686
+ if (this.depth === 0)
687
+ this.openAt = start;
688
+ this.depth++;
689
+ } else if (char === "]" && this.depth > 0) {
690
+ this.depth--;
691
+ }
692
+ return this.advance("PUNCT", start, 1);
693
+ }
694
+ NUMBER.lastIndex = start;
695
+ const number = NUMBER.exec(source);
696
+ if (number)
697
+ return this.advance("NUMBER", start, number[0].length);
698
+ IDENT.lastIndex = start;
699
+ const ident = IDENT.exec(source);
700
+ if (ident)
701
+ return this.advance("IDENT", start, ident[0].length);
702
+ const unexpected = String.fromCodePoint(source.codePointAt(start));
703
+ const end = start + unexpected.length;
704
+ this.sink.report("E_TOKEN", { start, end }, `Unexpected character "${unexpected}"`);
705
+ this.pos = end;
706
+ return this.token("ERROR", start, end);
707
+ }
708
+ token(kind, start, end, value) {
709
+ const text = this.source.slice(start, end);
710
+ return { kind, text, value: value ?? text, start, end };
711
+ }
712
+ advance(kind, start, length) {
713
+ this.pos = start + length;
714
+ return this.token(kind, start, this.pos);
715
+ }
716
+ quoted(start, quote, kind) {
717
+ const source = this.source;
718
+ const what = kind === "STRING" ? "string" : "quoted id";
719
+ let index = start + 1;
720
+ let value = "";
721
+ let bad = false;
722
+ for (;; ) {
723
+ const char = source[index];
724
+ if (char === undefined || char === `
725
+ `) {
726
+ this.sink.report("E_STRING", { start, end: index }, `Unterminated ${what}`);
727
+ this.pos = index;
728
+ return this.token("ERROR", start, index);
729
+ }
730
+ if (char === quote) {
731
+ index++;
732
+ break;
733
+ }
734
+ if (char !== "\\") {
735
+ value += char;
736
+ index++;
737
+ continue;
738
+ }
739
+ const escape = source[index + 1];
740
+ if (escape === undefined || escape === `
741
+ `) {
742
+ index++;
743
+ continue;
744
+ }
745
+ if (escape === quote || escape === "\\") {
746
+ value += escape;
747
+ index += 2;
748
+ continue;
749
+ }
750
+ if (kind === "STRING" && Object.hasOwn(SIMPLE_ESCAPES, escape)) {
751
+ value += SIMPLE_ESCAPES[escape];
752
+ index += 2;
753
+ continue;
754
+ }
755
+ if (kind === "STRING" && escape === "u") {
756
+ const match = UNICODE_ESCAPE.exec(source.slice(index + 2, index + 10));
757
+ const code = match ? Number.parseInt(match[1], 16) : -1;
758
+ if (match && code <= 1114111 && (code < 55296 || code > 57343)) {
759
+ value += String.fromCodePoint(code);
760
+ index += 2 + match[0].length;
761
+ continue;
762
+ }
763
+ const length = match ? 2 + match[0].length : 2;
764
+ this.sink.report("E_ESCAPE", { start: index, end: index + length }, `Invalid unicode escape in string: expected \\u{ followed by 1 to 6 hexadecimal digits of a code point, then }`);
765
+ bad = true;
766
+ index += length;
767
+ continue;
768
+ }
769
+ const unknown = String.fromCodePoint(source.codePointAt(index + 1));
770
+ this.sink.report("E_ESCAPE", { start: index, end: index + 1 + unknown.length }, `Unknown escape "\\${unknown}" in ${what}`);
771
+ bad = true;
772
+ index += 1 + unknown.length;
773
+ }
774
+ this.pos = index;
775
+ return bad ? this.token("ERROR", start, index) : this.token(kind, start, index, value);
776
+ }
777
+ }
778
+
779
+ // src/text/parser.ts
780
+ var KINDS = ["graph", "sequence", "state", "er", "tree"];
781
+ var FLAGS = new Set(["pk", "fk", "uk", "null"]);
782
+ var CARDINALITIES2 = new Map([
783
+ ["1", "one"],
784
+ ["0..1", "zero-or-one"],
785
+ ["1..*", "one-or-more"],
786
+ ["0..*", "zero-or-more"]
787
+ ]);
788
+ var OPERATOR_TOKENS = new Map([
789
+ ["ARROW", "->"],
790
+ ["LINE", "--"],
791
+ ["ASYNC", "->>"],
792
+ ["REPLY", "-->"],
793
+ ["DOTS", ".."]
794
+ ]);
795
+ var OPERATOR_WORDS = new Map([
796
+ ["to", "->"],
797
+ ["with", "--"],
798
+ ["async", "->>"],
799
+ ["reply", "-->"],
800
+ ["via", ".."]
801
+ ]);
802
+ var WORD_OF = {
803
+ "->": "to",
804
+ "--": "with",
805
+ "->>": "async",
806
+ "-->": "reply",
807
+ "..": "via"
808
+ };
809
+ var OPERATOR_RULES = {
810
+ graph: { noun: "a graph", allowed: ["->", "--"] },
811
+ sequence: { noun: "a sequence diagram", allowed: ["->", "->>", "-->"] },
812
+ state: { noun: "a state machine", allowed: ["->"] },
813
+ er: { noun: "an entity-relation diagram", allowed: ["--", ".."] },
814
+ tree: { noun: "a tree", allowed: [] }
815
+ };
816
+ var ABORT = Symbol("abort statement");
817
+ function operatorOf(token) {
818
+ return token.kind === "IDENT" ? OPERATOR_WORDS.get(token.text) : OPERATOR_TOKENS.get(token.kind);
819
+ }
820
+ function isPunct(token, text) {
821
+ return token.kind === "PUNCT" && token.text === text;
822
+ }
823
+ function isWord(token, word) {
824
+ return token.kind === "IDENT" && token.text === word;
825
+ }
826
+ function isLineEnd(token) {
827
+ return token.kind === "NEWLINE" || token.kind === "EOF";
828
+ }
829
+ function joinChoices(items) {
830
+ return items.length < 2 ? items.join("") : `${items.slice(0, -1).join(", ")} or ${items[items.length - 1]}`;
831
+ }
832
+
833
+ class Parser {
834
+ source;
835
+ lexer;
836
+ sink;
837
+ lenient;
838
+ buffer = [];
839
+ lastEnd = 0;
840
+ kind = "graph";
841
+ draft;
842
+ partial;
843
+ constructor(source, lexer, sink, lenient = false) {
844
+ this.source = source;
845
+ this.lexer = lexer;
846
+ this.sink = sink;
847
+ this.lenient = lenient;
848
+ }
849
+ keep(error, node, start) {
850
+ if (error !== ABORT && error !== STOP)
851
+ return;
852
+ node.range = this.from(start);
853
+ node.incomplete = true;
854
+ this.draft = node;
855
+ }
856
+ peek(offset = 0) {
857
+ while (this.buffer.length <= offset)
858
+ this.buffer.push(this.lexer.next());
859
+ return this.buffer[offset];
860
+ }
861
+ next() {
862
+ const token = this.peek();
863
+ this.buffer.shift();
864
+ if (token.kind !== "NEWLINE" && token.kind !== "EOF")
865
+ this.lastEnd = token.end;
866
+ return token;
867
+ }
868
+ seek(pos) {
869
+ this.lexer.seek(pos);
870
+ this.buffer.length = 0;
871
+ }
872
+ from(start) {
873
+ return { start, end: Math.max(start, this.lastEnd) };
874
+ }
875
+ describe(token) {
876
+ if (token.kind === "NEWLINE")
877
+ return "end of line";
878
+ if (token.kind === "EOF")
879
+ return "end of file";
880
+ return `"${token.text}"`;
881
+ }
882
+ unexpected(token, expected) {
883
+ if (token.kind !== "ERROR") {
884
+ this.sink.report("E_EXPECTED", token, `${expected}, found ${this.describe(token)}`);
885
+ }
886
+ throw ABORT;
887
+ }
888
+ fail(code, range, message) {
889
+ this.sink.report(code, range, message);
890
+ throw ABORT;
891
+ }
892
+ skipNewlines() {
893
+ while (this.peek().kind === "NEWLINE")
894
+ this.next();
895
+ }
896
+ endLine() {
897
+ const token = this.peek();
898
+ if (!isLineEnd(token))
899
+ this.unexpected(token, "Expected end of line");
900
+ this.next();
901
+ }
902
+ recover() {
903
+ let last;
904
+ let count = 0;
905
+ for (;; ) {
906
+ const token = this.peek();
907
+ if (token.kind === "EOF")
908
+ break;
909
+ this.next();
910
+ if (token.kind === "NEWLINE")
911
+ break;
912
+ last = token;
913
+ count++;
914
+ }
915
+ if (last && (isPunct(last, "{") || isWord(last, "do") && count > 1)) {
916
+ return { text: last.text, range: last };
917
+ }
918
+ return;
919
+ }
920
+ id() {
921
+ const token = this.peek();
922
+ if (token.kind === "IDENT" || token.kind === "QUOTED_ID") {
923
+ this.next();
924
+ return { value: token.value, range: token };
925
+ }
926
+ return this.unexpected(token, "Expected an id");
927
+ }
928
+ label() {
929
+ const token = this.peek();
930
+ if (token.kind !== "STRING")
931
+ return;
932
+ this.next();
933
+ return { value: token.value, range: token };
934
+ }
935
+ value() {
936
+ const token = this.peek();
937
+ if (token.kind === "STRING") {
938
+ this.next();
939
+ return { type: "string", value: token.value, range: token };
940
+ }
941
+ if (token.kind === "NUMBER") {
942
+ this.next();
943
+ return { type: "number", value: Number(token.text), range: token };
944
+ }
945
+ if (token.kind === "IDENT") {
946
+ this.next();
947
+ return { type: "ident", value: token.text, range: token };
948
+ }
949
+ if (isPunct(token, "[")) {
950
+ this.next();
951
+ const items = [];
952
+ for (;; ) {
953
+ if (isPunct(this.peek(), "]"))
954
+ break;
955
+ items.push(this.value());
956
+ const separator = this.peek();
957
+ if (isPunct(separator, ","))
958
+ this.next();
959
+ else if (!isPunct(separator, "]"))
960
+ this.unexpected(separator, 'Expected "," or "]"');
961
+ }
962
+ const close = this.next();
963
+ return { type: "list", items, range: { start: token.start, end: close.end } };
964
+ }
965
+ return this.unexpected(token, "Expected a value");
966
+ }
967
+ attrs() {
968
+ if (!isPunct(this.peek(), "["))
969
+ return [];
970
+ this.next();
971
+ const attrs = [];
972
+ for (;; ) {
973
+ const key = this.peek();
974
+ if (isPunct(key, "]")) {
975
+ this.next();
976
+ return attrs;
977
+ }
978
+ if (key.kind !== "IDENT" && key.kind !== "QUOTED_ID") {
979
+ this.unexpected(key, "Expected an attribute name");
980
+ }
981
+ this.next();
982
+ const equals = this.peek();
983
+ if (!isPunct(equals, "="))
984
+ this.unexpected(equals, `Expected "=" after attribute "${key.value}"`);
985
+ this.next();
986
+ const value = this.value();
987
+ attrs.push({
988
+ key: key.value,
989
+ keyRange: key,
990
+ value,
991
+ range: { start: key.start, end: value.range.end }
992
+ });
993
+ const separator = this.peek();
994
+ if (isPunct(separator, ","))
995
+ this.next();
996
+ else if (!isPunct(separator, "]"))
997
+ this.unexpected(separator, 'Expected "," or "]"');
998
+ }
999
+ }
1000
+ operator() {
1001
+ const token = this.peek();
1002
+ const symbol = operatorOf(token);
1003
+ if (symbol === undefined)
1004
+ return;
1005
+ const rules = OPERATOR_RULES[this.kind];
1006
+ if (!rules.allowed.includes(symbol)) {
1007
+ const words = token.kind === "IDENT";
1008
+ const allowed = rules.allowed.map((item) => words ? WORD_OF[item] : item);
1009
+ this.fail("E_OPERATOR", token, `Operator "${token.text}" does not exist in ${rules.noun} (use ${joinChoices(allowed)})`);
1010
+ }
1011
+ this.next();
1012
+ return { symbol, range: token };
1013
+ }
1014
+ opener(required) {
1015
+ const token = this.peek();
1016
+ const brace = isPunct(token, "{");
1017
+ if (brace || isWord(token, "do") && isLineEnd(this.peek(1))) {
1018
+ this.next();
1019
+ this.endLine();
1020
+ return { text: brace ? "{" : "do", range: token };
1021
+ }
1022
+ if (required)
1023
+ this.unexpected(token, 'Expected "{" or "do" to open a block');
1024
+ return;
1025
+ }
1026
+ body(opener, statement, out = []) {
1027
+ for (;; ) {
1028
+ this.skipNewlines();
1029
+ const token = this.peek();
1030
+ if (token.kind === "EOF") {
1031
+ if (opener) {
1032
+ this.sink.report("E_BLOCK", opener.range, `Block opened at line ${this.sink.lineOf(opener.range.start)} is never closed`);
1033
+ }
1034
+ return out;
1035
+ }
1036
+ const brace = isPunct(token, "}");
1037
+ const end = isWord(token, "end") && isLineEnd(this.peek(1)) && opener !== undefined;
1038
+ if (brace || end) {
1039
+ const expected = opener?.text === "do" ? "end" : "}";
1040
+ if (opener === undefined) {
1041
+ this.sink.report("E_BLOCK", token, 'Unexpected "}"');
1042
+ } else if (token.text !== expected) {
1043
+ this.sink.report("E_BLOCK", token, `block opened with "${opener.text}" must close with "${expected}"`);
1044
+ }
1045
+ this.next();
1046
+ try {
1047
+ this.endLine();
1048
+ } catch (error) {
1049
+ if (error !== ABORT)
1050
+ throw error;
1051
+ this.recover();
1052
+ }
1053
+ if (opener)
1054
+ return out;
1055
+ continue;
1056
+ }
1057
+ try {
1058
+ out.push(statement());
1059
+ } catch (error) {
1060
+ const draft = this.draft;
1061
+ this.draft = undefined;
1062
+ if (error === STOP) {
1063
+ if (draft)
1064
+ out.push(draft);
1065
+ throw error;
1066
+ }
1067
+ if (error !== ABORT)
1068
+ throw error;
1069
+ const nested = this.recover();
1070
+ const inner = [];
1071
+ if (draft) {
1072
+ if (draft.t === "group" && Array.isArray(draft.body))
1073
+ draft.body = inner;
1074
+ out.push(draft);
1075
+ }
1076
+ if (nested)
1077
+ this.body(nested, statement, inner);
1078
+ }
1079
+ }
1080
+ }
1081
+ header() {
1082
+ this.skipNewlines();
1083
+ const token = this.peek();
1084
+ const absent = () => this.lenient ? {
1085
+ kindRange: { start: token.start, end: token.start },
1086
+ attrs: [],
1087
+ range: { start: token.start, end: token.start },
1088
+ missing: true
1089
+ } : undefined;
1090
+ if (token.kind === "ERROR")
1091
+ return absent();
1092
+ if (!(token.kind === "IDENT" && KINDS.includes(token.text))) {
1093
+ this.sink.report("E_HEADER", token, `Expected a header such as graph "Title" (kinds: ${KINDS.join(", ")})`);
1094
+ return absent();
1095
+ }
1096
+ this.next();
1097
+ this.kind = token.text;
1098
+ const header = { kindRange: token, attrs: [], range: token };
1099
+ try {
1100
+ header.title = this.label();
1101
+ header.attrs = this.attrs();
1102
+ header.range = this.from(token.start);
1103
+ this.endLine();
1104
+ } catch (error) {
1105
+ if (error !== ABORT)
1106
+ throw error;
1107
+ header.range = this.from(token.start);
1108
+ this.recover();
1109
+ }
1110
+ return header;
1111
+ }
1112
+ graphStatement() {
1113
+ const first = this.peek();
1114
+ const start = first.start;
1115
+ if (isWord(first, "group")) {
1116
+ this.next();
1117
+ const group = {
1118
+ t: "group",
1119
+ id: this.id(),
1120
+ label: undefined,
1121
+ attrs: [],
1122
+ range: this.from(start),
1123
+ body: []
1124
+ };
1125
+ try {
1126
+ group.label = this.label();
1127
+ group.attrs = this.attrs();
1128
+ group.range = this.from(start);
1129
+ const opener = this.opener(true);
1130
+ this.body(opener, () => this.graphStatement(), group.body);
1131
+ return group;
1132
+ } catch (error) {
1133
+ this.keep(error, group, start);
1134
+ throw error;
1135
+ }
1136
+ }
1137
+ const ids = [this.id()];
1138
+ const ops = [];
1139
+ let label;
1140
+ let attrs = [];
1141
+ try {
1142
+ for (;; ) {
1143
+ const op = this.operator();
1144
+ if (!op)
1145
+ break;
1146
+ ops.push(op);
1147
+ ids.push(this.id());
1148
+ }
1149
+ label = this.label();
1150
+ attrs = this.attrs();
1151
+ const range = this.from(start);
1152
+ this.endLine();
1153
+ if (ops.length === 0)
1154
+ return { t: "node", id: ids[0], label, attrs, range };
1155
+ return { t: "chain", ids, ops, label, attrs, range };
1156
+ } catch (error) {
1157
+ const range = { start, end: start };
1158
+ this.keep(error, ops.length === 0 ? { t: "node", id: ids[0], label, attrs, range } : { t: "chain", ids, ops, label, attrs, range }, start);
1159
+ throw error;
1160
+ }
1161
+ }
1162
+ sequenceStatement() {
1163
+ const start = this.peek().start;
1164
+ const id = this.id();
1165
+ const participant = {
1166
+ t: "participant",
1167
+ id,
1168
+ label: undefined,
1169
+ attrs: [],
1170
+ range: this.from(start)
1171
+ };
1172
+ let node = participant;
1173
+ try {
1174
+ const op = this.operator();
1175
+ if (!op) {
1176
+ participant.label = this.label();
1177
+ participant.attrs = this.attrs();
1178
+ participant.range = this.from(start);
1179
+ this.endLine();
1180
+ return participant;
1181
+ }
1182
+ const message = {
1183
+ t: "message",
1184
+ from: id,
1185
+ to: this.id(),
1186
+ op,
1187
+ label: undefined,
1188
+ attrs: [],
1189
+ range: this.from(start)
1190
+ };
1191
+ node = message;
1192
+ message.label = this.label();
1193
+ message.attrs = this.attrs();
1194
+ message.range = this.from(start);
1195
+ this.endLine();
1196
+ return message;
1197
+ } catch (error) {
1198
+ this.keep(error, node, start);
1199
+ throw error;
1200
+ }
1201
+ }
1202
+ stateStatement() {
1203
+ const first = this.peek();
1204
+ const start = first.start;
1205
+ let from;
1206
+ let fallback;
1207
+ if (isPunct(first, "*")) {
1208
+ this.next();
1209
+ from = { star: true, value: "*", range: first };
1210
+ } else if (isWord(first, "initial") && operatorOf(this.peek(1)) !== undefined) {
1211
+ this.next();
1212
+ from = { star: true, value: "*", range: first };
1213
+ } else {
1214
+ const id = this.id();
1215
+ const state = {
1216
+ t: "state",
1217
+ id,
1218
+ label: undefined,
1219
+ attrs: [],
1220
+ range: this.from(start)
1221
+ };
1222
+ if (operatorOf(this.peek()) === undefined) {
1223
+ try {
1224
+ state.label = this.label();
1225
+ state.attrs = this.attrs();
1226
+ state.range = this.from(start);
1227
+ const opener = this.opener(false);
1228
+ if (!opener) {
1229
+ this.endLine();
1230
+ return state;
1231
+ }
1232
+ state.body = [];
1233
+ this.body(opener, () => this.stateStatement(), state.body);
1234
+ return state;
1235
+ } catch (error) {
1236
+ this.keep(error, state, start);
1237
+ throw error;
1238
+ }
1239
+ }
1240
+ from = { star: false, ...id };
1241
+ fallback = state;
1242
+ }
1243
+ let node = fallback;
1244
+ try {
1245
+ const op = this.operator();
1246
+ if (!op)
1247
+ this.unexpected(this.peek(), 'Expected "->"');
1248
+ const target = this.peek();
1249
+ let to;
1250
+ if (isPunct(target, "*") || isWord(target, "final")) {
1251
+ this.next();
1252
+ to = { star: true, value: "*", range: target };
1253
+ } else {
1254
+ to = { star: false, ...this.id() };
1255
+ }
1256
+ const transition = {
1257
+ t: "transition",
1258
+ from,
1259
+ to,
1260
+ op,
1261
+ label: undefined,
1262
+ attrs: [],
1263
+ range: this.from(start)
1264
+ };
1265
+ node = transition;
1266
+ transition.label = this.label();
1267
+ transition.attrs = this.attrs();
1268
+ transition.range = this.from(start);
1269
+ this.endLine();
1270
+ return transition;
1271
+ } catch (error) {
1272
+ if (node)
1273
+ this.keep(error, node, start);
1274
+ throw error;
1275
+ }
1276
+ }
1277
+ card() {
1278
+ const token = this.peek();
1279
+ if (token.kind !== "NUMBER" && token.kind !== "CARD")
1280
+ return;
1281
+ const value = CARDINALITIES2.get(token.text);
1282
+ if (value === undefined) {
1283
+ this.fail("E_VALUE", token, `Cardinality must be 1, 0..1, 1..* or 0..*; found "${token.text}"`);
1284
+ }
1285
+ this.next();
1286
+ return { value, range: token };
1287
+ }
1288
+ typeExpression() {
1289
+ const first = this.next();
1290
+ let text = first.text;
1291
+ if (isPunct(this.peek(), "(")) {
1292
+ this.next();
1293
+ text += "(";
1294
+ for (;; ) {
1295
+ const arg = this.peek();
1296
+ if (arg.kind !== "NUMBER" && arg.kind !== "IDENT")
1297
+ this.unexpected(arg, "Expected a type argument");
1298
+ this.next();
1299
+ text += arg.text;
1300
+ const separator = this.peek();
1301
+ if (isPunct(separator, ",")) {
1302
+ this.next();
1303
+ text += ",";
1304
+ } else if (isPunct(separator, ")")) {
1305
+ this.next();
1306
+ text += ")";
1307
+ break;
1308
+ } else {
1309
+ this.unexpected(separator, 'Expected "," or ")"');
1310
+ }
1311
+ }
1312
+ }
1313
+ if (isPunct(this.peek(), "[") && isPunct(this.peek(1), "]")) {
1314
+ this.next();
1315
+ this.next();
1316
+ text += "[]";
1317
+ }
1318
+ return { value: text, range: { start: first.start, end: this.lastEnd } };
1319
+ }
1320
+ attributeLine() {
1321
+ const start = this.peek().start;
1322
+ const line = {
1323
+ name: this.id(),
1324
+ type: undefined,
1325
+ flags: [],
1326
+ attrs: [],
1327
+ range: this.from(start)
1328
+ };
1329
+ try {
1330
+ const token = this.peek();
1331
+ if (token.kind === "STRING") {
1332
+ this.next();
1333
+ line.type = { value: token.value, range: token };
1334
+ } else if (token.kind === "IDENT" && !FLAGS.has(token.text)) {
1335
+ line.type = this.typeExpression();
1336
+ }
1337
+ for (;; ) {
1338
+ const flag = this.peek();
1339
+ if (flag.kind !== "IDENT" || !FLAGS.has(flag.text))
1340
+ break;
1341
+ this.next();
1342
+ line.flags.push({ value: flag.text, range: flag });
1343
+ }
1344
+ line.attrs = this.attrs();
1345
+ line.range = this.from(start);
1346
+ this.endLine();
1347
+ return line;
1348
+ } catch (error) {
1349
+ this.keep(error, line, start);
1350
+ throw error;
1351
+ }
1352
+ }
1353
+ erStatement() {
1354
+ const start = this.peek().start;
1355
+ const id = this.id();
1356
+ const entity = {
1357
+ t: "entity",
1358
+ id,
1359
+ label: undefined,
1360
+ attrs: [],
1361
+ range: this.from(start)
1362
+ };
1363
+ let node = entity;
1364
+ try {
1365
+ const next = this.peek();
1366
+ if (next.kind === "NUMBER" || next.kind === "CARD" || operatorOf(next) !== undefined) {
1367
+ const fromCard = this.card();
1368
+ const op = this.operator();
1369
+ if (!op)
1370
+ this.unexpected(this.peek(), 'Expected "--" or ".."');
1371
+ const toCard = this.card();
1372
+ const relation = {
1373
+ t: "relation",
1374
+ from: id,
1375
+ fromCard,
1376
+ op,
1377
+ toCard,
1378
+ to: this.id(),
1379
+ label: undefined,
1380
+ attrs: [],
1381
+ range: this.from(start)
1382
+ };
1383
+ node = relation;
1384
+ relation.label = this.label();
1385
+ relation.attrs = this.attrs();
1386
+ relation.range = this.from(start);
1387
+ this.endLine();
1388
+ return relation;
1389
+ }
1390
+ entity.label = this.label();
1391
+ entity.attrs = this.attrs();
1392
+ entity.range = this.from(start);
1393
+ const opener = this.opener(false);
1394
+ if (!opener) {
1395
+ this.endLine();
1396
+ return entity;
1397
+ }
1398
+ entity.attributes = [];
1399
+ this.body(opener, () => this.attributeLine(), entity.attributes);
1400
+ return entity;
1401
+ } catch (error) {
1402
+ this.keep(error, node, start);
1403
+ throw error;
1404
+ }
1405
+ }
1406
+ treeBody(lines) {
1407
+ const source = this.source;
1408
+ const levels = [];
1409
+ let indentChar;
1410
+ let firstRoot = 0;
1411
+ let pos = this.lexer.pos;
1412
+ while (pos < source.length) {
1413
+ let end = source.indexOf(`
1414
+ `, pos);
1415
+ if (end < 0)
1416
+ end = source.length;
1417
+ const nextLine = end + 1;
1418
+ let text = pos;
1419
+ while (text < end && (source[text] === " " || source[text] === "\t"))
1420
+ text++;
1421
+ if (text >= end || source[text] === "#") {
1422
+ pos = nextLine;
1423
+ continue;
1424
+ }
1425
+ const indent = { start: pos, end: text };
1426
+ const width = text - pos;
1427
+ const indentation = source.slice(pos, text);
1428
+ if (indentation.includes(" ") && indentation.includes("\t") || width > 0 && indentChar !== undefined && indentation[0] !== indentChar) {
1429
+ this.sink.report("E_INDENT", indent, "Tabs and spaces are mixed in indentation");
1430
+ pos = nextLine;
1431
+ continue;
1432
+ }
1433
+ if (width > 0)
1434
+ indentChar ??= indentation[0];
1435
+ let parent = -1;
1436
+ let keep = levels.length;
1437
+ if (levels.length === 0) {
1438
+ if (width !== 0) {
1439
+ this.sink.report("E_INDENT", indent, "The first line of a tree must not be indented");
1440
+ pos = nextLine;
1441
+ continue;
1442
+ }
1443
+ firstRoot = text;
1444
+ } else if (width === 0) {
1445
+ this.sink.report("E_ROOT", { start: text, end }, `A tree has one root; this line starts a second one (first root at line ${this.sink.lineOf(firstRoot)})`);
1446
+ pos = nextLine;
1447
+ continue;
1448
+ } else if (width > levels[levels.length - 1].width) {
1449
+ parent = levels[levels.length - 1].index;
1450
+ } else {
1451
+ const level = levels.findIndex((item) => item.width === width);
1452
+ if (level < 0) {
1453
+ this.sink.report("E_INDENT", indent, `Indentation of ${width} does not match an open level (${levels.map((item) => item.width).join(", ")})`);
1454
+ pos = nextLine;
1455
+ continue;
1456
+ }
1457
+ parent = levels[level].parent;
1458
+ keep = level;
1459
+ }
1460
+ let label;
1461
+ let attrs = [];
1462
+ let incomplete = false;
1463
+ if (source[text] === '"') {
1464
+ this.seek(text);
1465
+ try {
1466
+ const token = this.next();
1467
+ if (token.kind !== "STRING")
1468
+ throw ABORT;
1469
+ label = { value: token.value, range: token };
1470
+ attrs = this.attrs();
1471
+ this.endLine();
1472
+ } catch (error) {
1473
+ if (error !== ABORT)
1474
+ throw error;
1475
+ incomplete = true;
1476
+ this.recover();
1477
+ }
1478
+ } else {
1479
+ let rest = text;
1480
+ while (rest < end && source[rest] !== "[" && source[rest] !== "#")
1481
+ rest++;
1482
+ const bare = source.slice(text, rest).trimEnd();
1483
+ if (bare === "") {
1484
+ this.sink.report("E_EXPECTED", { start: rest, end: rest + 1 }, 'Expected a label, found "["');
1485
+ pos = nextLine;
1486
+ continue;
1487
+ }
1488
+ const quote = bare.indexOf('"');
1489
+ if (quote >= 0) {
1490
+ this.sink.report("E_TOKEN", { start: text + quote, end: text + quote + 1 }, 'Bare text cannot contain """; write the whole label as a string');
1491
+ pos = nextLine;
1492
+ continue;
1493
+ }
1494
+ label = { value: bare, range: { start: text, end: text + bare.length } };
1495
+ this.seek(rest);
1496
+ try {
1497
+ attrs = this.attrs();
1498
+ this.endLine();
1499
+ } catch (error) {
1500
+ if (error !== ABORT)
1501
+ throw error;
1502
+ incomplete = true;
1503
+ this.recover();
1504
+ }
1505
+ }
1506
+ pos = this.lexer.pos;
1507
+ if (!label)
1508
+ continue;
1509
+ levels.length = keep;
1510
+ levels.push({ width, parent, index: lines.length });
1511
+ const line = {
1512
+ label,
1513
+ attrs,
1514
+ parent,
1515
+ range: { start: text, end: Math.max(label.range.end, this.lastEnd) }
1516
+ };
1517
+ if (incomplete)
1518
+ line.incomplete = true;
1519
+ lines.push(line);
1520
+ }
1521
+ return lines;
1522
+ }
1523
+ document() {
1524
+ const header = this.header();
1525
+ if (!header)
1526
+ return;
1527
+ const kind = this.kind;
1528
+ switch (kind) {
1529
+ case "graph": {
1530
+ const ast = { kind, header, body: [] };
1531
+ this.partial = ast;
1532
+ this.body(undefined, () => this.graphStatement(), ast.body);
1533
+ return ast;
1534
+ }
1535
+ case "sequence": {
1536
+ const ast = { kind, header, body: [] };
1537
+ this.partial = ast;
1538
+ this.body(undefined, () => this.sequenceStatement(), ast.body);
1539
+ return ast;
1540
+ }
1541
+ case "state": {
1542
+ const ast = { kind, header, body: [] };
1543
+ this.partial = ast;
1544
+ this.body(undefined, () => this.stateStatement(), ast.body);
1545
+ return ast;
1546
+ }
1547
+ case "er": {
1548
+ const ast = { kind, header, body: [] };
1549
+ this.partial = ast;
1550
+ this.body(undefined, () => this.erStatement(), ast.body);
1551
+ return ast;
1552
+ }
1553
+ case "tree": {
1554
+ const ast = { kind, header, body: [] };
1555
+ this.partial = ast;
1556
+ this.treeBody(ast.body);
1557
+ return ast;
1558
+ }
1559
+ }
1560
+ }
1561
+ }
1562
+ function parseSyntax(source, sink) {
1563
+ const lexer = new Lexer(source, sink);
1564
+ const parser = new Parser(source, lexer, sink);
1565
+ try {
1566
+ return parser.document();
1567
+ } catch (error) {
1568
+ if (error === STOP)
1569
+ return;
1570
+ throw error;
1571
+ }
1572
+ }
1573
+ function parseSyntaxPartial(source, sink) {
1574
+ const lexer = new Lexer(source, sink);
1575
+ const parser = new Parser(source, lexer, sink, true);
1576
+ try {
1577
+ const ast = parser.document();
1578
+ if (ast)
1579
+ return ast;
1580
+ } catch (error) {
1581
+ if (error !== STOP)
1582
+ throw error;
1583
+ }
1584
+ return parser.partial ?? {
1585
+ kind: "graph",
1586
+ header: {
1587
+ kindRange: { start: 0, end: 0 },
1588
+ attrs: [],
1589
+ range: { start: 0, end: 0 },
1590
+ missing: true
1591
+ },
1592
+ body: []
1593
+ };
1594
+ }
1595
+ // src/text/canonical.ts
1596
+ function childrenOf(items) {
1597
+ const children = new Map;
1598
+ for (const item of items) {
1599
+ const list = children.get(item.parent);
1600
+ if (list)
1601
+ list.push(item);
1602
+ else
1603
+ children.set(item.parent, [item]);
1604
+ }
1605
+ return children;
1606
+ }
1607
+ function walk(items, enter, exit) {
1608
+ const children = childrenOf(items);
1609
+ const stack = [];
1610
+ const push = (parent, depth) => {
1611
+ const list = children.get(parent);
1612
+ if (!list)
1613
+ return;
1614
+ for (let index = list.length - 1;index >= 0; index--) {
1615
+ stack.push({ item: list[index], depth, exiting: false });
1616
+ }
1617
+ };
1618
+ push(undefined, 0);
1619
+ while (stack.length > 0) {
1620
+ const frame = stack.pop();
1621
+ const count = children.get(frame.item.id)?.length ?? 0;
1622
+ if (frame.exiting) {
1623
+ exit?.(frame.item, frame.depth, count);
1624
+ continue;
1625
+ }
1626
+ enter(frame.item, frame.depth, count);
1627
+ stack.push({ ...frame, exiting: true });
1628
+ push(frame.item.id, frame.depth + 1);
1629
+ }
1630
+ }
1631
+ function preorder(items) {
1632
+ const ordered = [];
1633
+ walk(items, (item) => {
1634
+ ordered.push(item);
1635
+ });
1636
+ return ordered;
1637
+ }
1638
+ function groupNodes(nodes) {
1639
+ const byGroup = new Map;
1640
+ for (const node of nodes) {
1641
+ const list = byGroup.get(node.group);
1642
+ if (list)
1643
+ list.push(node);
1644
+ else
1645
+ byGroup.set(node.group, [node]);
1646
+ }
1647
+ return byGroup;
1648
+ }
1649
+ function orderedNodes(nodes, groups) {
1650
+ const byGroup = groupNodes(nodes);
1651
+ const ordered = [...byGroup.get(undefined) ?? []];
1652
+ for (const group of preorder(groups))
1653
+ ordered.push(...byGroup.get(group.id) ?? []);
1654
+ return ordered;
1655
+ }
1656
+ function isRecord(value) {
1657
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1658
+ }
1659
+ function clean(value) {
1660
+ if (Array.isArray(value)) {
1661
+ for (const item of value)
1662
+ clean(item);
1663
+ return;
1664
+ }
1665
+ if (!isRecord(value))
1666
+ return;
1667
+ for (const [key, child] of Object.entries(value)) {
1668
+ if (key === "meta" && isRecord(child)) {
1669
+ if (isRecord(child.data) && Object.keys(child.data).length === 0)
1670
+ delete child.data;
1671
+ if (Object.keys(child).length === 0)
1672
+ delete value[key];
1673
+ } else {
1674
+ clean(child);
1675
+ }
1676
+ }
1677
+ }
1678
+ function dropEmpty(target, key) {
1679
+ if (Array.isArray(target[key]) && target[key].length === 0)
1680
+ delete target[key];
1681
+ }
1682
+ function canonicalize2(document) {
1683
+ const copy = structuredClone(document);
1684
+ delete copy.$schema;
1685
+ clean(copy);
1686
+ switch (copy.kind) {
1687
+ case "graph":
1688
+ copy.nodes = orderedNodes(copy.nodes, copy.groups ?? []);
1689
+ if (copy.groups)
1690
+ copy.groups = preorder(copy.groups);
1691
+ for (const edge of copy.edges ?? [])
1692
+ edge.directed ??= true;
1693
+ dropEmpty(copy, "edges");
1694
+ dropEmpty(copy, "groups");
1695
+ break;
1696
+ case "sequence":
1697
+ for (const message of copy.messages)
1698
+ message.style ??= "sync";
1699
+ break;
1700
+ case "state":
1701
+ copy.states = preorder(copy.states);
1702
+ dropEmpty(copy, "transitions");
1703
+ break;
1704
+ case "er":
1705
+ for (const entity of copy.entities) {
1706
+ for (const attribute of entity.attributes ?? []) {
1707
+ if (attribute.nullable === false)
1708
+ delete attribute.nullable;
1709
+ dropEmpty(attribute, "keys");
1710
+ }
1711
+ }
1712
+ for (const relation of copy.relations ?? [])
1713
+ relation.identifying ??= true;
1714
+ dropEmpty(copy, "relations");
1715
+ break;
1716
+ case "tree":
1717
+ copy.nodes = preorder(copy.nodes);
1718
+ break;
1719
+ }
1720
+ return copy;
1721
+ }
1722
+ // src/text/highlight.ts
1723
+ var SEMANTIC_TOKEN_TYPES2 = [
1724
+ "namespace",
1725
+ "type",
1726
+ "variable",
1727
+ "property",
1728
+ "enumMember",
1729
+ "keyword",
1730
+ "comment",
1731
+ "string",
1732
+ "number",
1733
+ "operator"
1734
+ ];
1735
+ var SEMANTIC_TOKEN_MODIFIERS2 = ["declaration", "defaultLibrary"];
1736
+ var ENUM_KEYS = new Set(["shape", "pseudo", "confidence", "direction", "layout"]);
1737
+ var SYMBOL_OPERATORS = new Set(["ARROW", "LINE", "ASYNC", "REPLY", "DOTS"]);
1738
+ function isPunct2(token, text) {
1739
+ return token !== undefined && token.kind === "PUNCT" && token.text === text;
1740
+ }
1741
+ function isWord2(token, word) {
1742
+ return token !== undefined && token.kind === "IDENT" && token.text === word;
1743
+ }
1744
+ function isId(token) {
1745
+ return token !== undefined && (token.kind === "IDENT" || token.kind === "QUOTED_ID");
1746
+ }
1747
+ function isOperator(token) {
1748
+ return token !== undefined && (SYMBOL_OPERATORS.has(token.kind) || token.kind === "IDENT" && OPERATOR_WORDS.has(token.text));
1749
+ }
1750
+ function isCard(token) {
1751
+ return token !== undefined && (token.kind === "NUMBER" || token.kind === "CARD");
1752
+ }
1753
+ function offsets(source) {
1754
+ const bom = source.charCodeAt(0) === 65279;
1755
+ if (!bom && !source.includes(`\r
1756
+ `))
1757
+ return;
1758
+ const map = [];
1759
+ for (let index = bom ? 1 : 0;index < source.length; index++) {
1760
+ if (source[index] === "\r" && source[index + 1] === `
1761
+ `)
1762
+ continue;
1763
+ map.push(index);
1764
+ }
1765
+ map.push(source.length);
1766
+ return map;
1767
+ }
1768
+
1769
+ class Cursor {
1770
+ tokens;
1771
+ index = 0;
1772
+ constructor(tokens) {
1773
+ this.tokens = tokens;
1774
+ }
1775
+ peek(offset = 0) {
1776
+ return this.tokens[this.index + offset];
1777
+ }
1778
+ take() {
1779
+ return this.tokens[this.index++];
1780
+ }
1781
+ get last() {
1782
+ return this.index === this.tokens.length - 1;
1783
+ }
1784
+ get done() {
1785
+ return this.index >= this.tokens.length;
1786
+ }
1787
+ }
1788
+
1789
+ class Highlighter {
1790
+ source;
1791
+ text;
1792
+ map;
1793
+ lines;
1794
+ lexer;
1795
+ out = [];
1796
+ eof = false;
1797
+ blocks = [];
1798
+ constructor(source) {
1799
+ this.source = source;
1800
+ this.text = normalize(source);
1801
+ this.map = offsets(source);
1802
+ this.lines = new LineMap(this.text);
1803
+ const sink = new Sink(this.lines);
1804
+ sink.muted = 1;
1805
+ this.lexer = new Lexer(this.text, sink);
1806
+ }
1807
+ emit(start, end, type, modifiers) {
1808
+ if (end <= start)
1809
+ return;
1810
+ const position = this.lines.position(start);
1811
+ const token = {
1812
+ start: this.map ? this.map[start] : start,
1813
+ end: this.map ? this.map[end - 1] + 1 : end,
1814
+ line: position.line,
1815
+ column: position.column,
1816
+ type
1817
+ };
1818
+ if (modifiers !== undefined)
1819
+ token.modifiers = modifiers;
1820
+ this.out.push(token);
1821
+ }
1822
+ mark(token, type, modifiers) {
1823
+ this.emit(token.start, token.end, type, modifiers);
1824
+ }
1825
+ comments(from, to) {
1826
+ const gap = this.text.slice(from, Math.max(from, to));
1827
+ for (const match of gap.matchAll(/#[^\n]*/g)) {
1828
+ this.emit(from + match.index, from + match.index + match[0].length, "comment");
1829
+ }
1830
+ }
1831
+ line() {
1832
+ const tokens = [];
1833
+ for (;; ) {
1834
+ const from = this.lexer.pos;
1835
+ const token = this.lexer.next();
1836
+ if (token.kind === "ERROR" && token.start < from) {
1837
+ this.comments(from, this.text.length);
1838
+ this.eof = true;
1839
+ return tokens;
1840
+ }
1841
+ this.comments(from, token.start);
1842
+ if (token.kind === "EOF") {
1843
+ this.eof = true;
1844
+ return tokens;
1845
+ }
1846
+ if (token.kind === "NEWLINE")
1847
+ return tokens;
1848
+ tokens.push(token);
1849
+ }
1850
+ }
1851
+ quotedError(token) {
1852
+ if (token.kind === "ERROR" && token.text.startsWith('"'))
1853
+ this.mark(token, "string");
1854
+ }
1855
+ label(cursor) {
1856
+ const token = cursor.peek();
1857
+ if (token === undefined)
1858
+ return;
1859
+ if (token.kind === "STRING") {
1860
+ cursor.take();
1861
+ this.mark(token, "string");
1862
+ } else if (token.kind === "ERROR" && token.text.startsWith('"')) {
1863
+ cursor.take();
1864
+ this.quotedError(token);
1865
+ }
1866
+ }
1867
+ attrs(cursor) {
1868
+ if (!isPunct2(cursor.peek(), "["))
1869
+ return;
1870
+ cursor.take();
1871
+ let depth = 1;
1872
+ let key = "";
1873
+ while (!cursor.done) {
1874
+ const token = cursor.take();
1875
+ if (token.kind === "PUNCT") {
1876
+ if (token.text === "[")
1877
+ depth++;
1878
+ else if (token.text === "]" && --depth === 0)
1879
+ return;
1880
+ else if (token.text === "=")
1881
+ this.mark(token, "operator");
1882
+ continue;
1883
+ }
1884
+ if ((token.kind === "IDENT" || token.kind === "QUOTED_ID") && isPunct2(cursor.peek(), "=")) {
1885
+ key = token.text;
1886
+ this.mark(token, "property");
1887
+ } else if (token.kind === "STRING") {
1888
+ this.mark(token, "string");
1889
+ } else if (token.kind === "NUMBER") {
1890
+ this.mark(token, "number");
1891
+ } else if (token.kind === "IDENT") {
1892
+ if (ENUM_KEYS.has(key))
1893
+ this.mark(token, "enumMember");
1894
+ else if (token.text === "true" || token.text === "false")
1895
+ this.mark(token, "keyword");
1896
+ else
1897
+ this.mark(token, "string");
1898
+ } else {
1899
+ this.quotedError(token);
1900
+ }
1901
+ }
1902
+ }
1903
+ rest(cursor) {
1904
+ while (!cursor.done) {
1905
+ const token = cursor.peek();
1906
+ if (isPunct2(token, "[")) {
1907
+ this.attrs(cursor);
1908
+ continue;
1909
+ }
1910
+ cursor.take();
1911
+ if (token.kind === "STRING")
1912
+ this.mark(token, "string");
1913
+ else if (token.kind === "NUMBER" || token.kind === "CARD")
1914
+ this.mark(token, "number");
1915
+ else if (isOperator(token) || isPunct2(token, "*"))
1916
+ this.mark(token, "operator");
1917
+ else if (isId(token))
1918
+ this.mark(token, "variable");
1919
+ else
1920
+ this.quotedError(token);
1921
+ }
1922
+ }
1923
+ opener(cursor, block) {
1924
+ const token = cursor.peek();
1925
+ if (isPunct2(token, "{")) {
1926
+ cursor.take();
1927
+ this.blocks.push(block);
1928
+ } else if (isWord2(token, "do") && cursor.last) {
1929
+ this.mark(cursor.take(), "keyword");
1930
+ this.blocks.push(block);
1931
+ }
1932
+ }
1933
+ card(cursor) {
1934
+ if (isCard(cursor.peek()))
1935
+ this.mark(cursor.take(), "number");
1936
+ }
1937
+ header(tokens) {
1938
+ const cursor = new Cursor(tokens);
1939
+ const kind = cursor.take();
1940
+ this.mark(kind, "keyword", ["defaultLibrary"]);
1941
+ this.label(cursor);
1942
+ this.attrs(cursor);
1943
+ this.rest(cursor);
1944
+ return kind.text;
1945
+ }
1946
+ attributeLine(cursor) {
1947
+ const name = cursor.peek();
1948
+ if (isId(name)) {
1949
+ cursor.take();
1950
+ this.mark(name, "variable", ["declaration"]);
1951
+ }
1952
+ const type = cursor.peek();
1953
+ if (type !== undefined && type.kind === "STRING") {
1954
+ cursor.take();
1955
+ this.mark(type, "string");
1956
+ } else if (type !== undefined && type.kind === "IDENT" && !FLAGS.has(type.text)) {
1957
+ cursor.take();
1958
+ this.mark(type, "type");
1959
+ if (isPunct2(cursor.peek(), "(")) {
1960
+ cursor.take();
1961
+ while (!cursor.done && !isPunct2(cursor.peek(), ")") && !isPunct2(cursor.peek(), "[")) {
1962
+ const arg = cursor.take();
1963
+ if (arg.kind === "NUMBER")
1964
+ this.mark(arg, "number");
1965
+ else if (arg.kind === "IDENT")
1966
+ this.mark(arg, "type");
1967
+ }
1968
+ if (isPunct2(cursor.peek(), ")"))
1969
+ cursor.take();
1970
+ }
1971
+ if (isPunct2(cursor.peek(), "[") && isPunct2(cursor.peek(1), "]")) {
1972
+ cursor.take();
1973
+ cursor.take();
1974
+ }
1975
+ }
1976
+ for (;; ) {
1977
+ const flag = cursor.peek();
1978
+ if (flag === undefined || flag.kind !== "IDENT" || !FLAGS.has(flag.text))
1979
+ break;
1980
+ cursor.take();
1981
+ this.mark(flag, "keyword");
1982
+ }
1983
+ this.attrs(cursor);
1984
+ this.rest(cursor);
1985
+ }
1986
+ statement(kind, tokens) {
1987
+ const cursor = new Cursor(tokens);
1988
+ const first = cursor.peek();
1989
+ if (first === undefined)
1990
+ return;
1991
+ if (this.blocks.length > 0 && isWord2(first, "end") && tokens.length === 1) {
1992
+ cursor.take();
1993
+ this.mark(first, "keyword");
1994
+ this.blocks.pop();
1995
+ return;
1996
+ }
1997
+ if (isPunct2(first, "}")) {
1998
+ this.blocks.pop();
1999
+ cursor.take();
2000
+ this.rest(cursor);
2001
+ return;
2002
+ }
2003
+ if (this.blocks[this.blocks.length - 1] === "entity") {
2004
+ this.attributeLine(cursor);
2005
+ return;
2006
+ }
2007
+ if (kind === "graph" && isWord2(first, "group")) {
2008
+ cursor.take();
2009
+ this.mark(first, "keyword");
2010
+ const id = cursor.peek();
2011
+ if (isId(id)) {
2012
+ cursor.take();
2013
+ this.mark(id, "namespace", ["declaration"]);
2014
+ }
2015
+ this.label(cursor);
2016
+ this.attrs(cursor);
2017
+ this.opener(cursor, "other");
2018
+ this.rest(cursor);
2019
+ return;
2020
+ }
2021
+ if (kind === "state" && (isPunct2(first, "*") || isWord2(first, "initial") && isOperator(cursor.peek(1)))) {
2022
+ cursor.take();
2023
+ this.mark(first, "operator");
2024
+ } else if (isId(first)) {
2025
+ cursor.take();
2026
+ const next = cursor.peek();
2027
+ const relation = isOperator(next) || kind === "er" && isCard(next);
2028
+ if (!relation) {
2029
+ this.mark(first, "variable", ["declaration"]);
2030
+ this.label(cursor);
2031
+ this.attrs(cursor);
2032
+ if (kind === "state")
2033
+ this.opener(cursor, "other");
2034
+ else if (kind === "er")
2035
+ this.opener(cursor, "entity");
2036
+ this.rest(cursor);
2037
+ return;
2038
+ }
2039
+ this.mark(first, "variable");
2040
+ } else {
2041
+ this.rest(cursor);
2042
+ return;
2043
+ }
2044
+ for (;; ) {
2045
+ if (kind === "er")
2046
+ this.card(cursor);
2047
+ const operator = cursor.peek();
2048
+ if (!isOperator(operator))
2049
+ break;
2050
+ cursor.take();
2051
+ this.mark(operator, "operator");
2052
+ if (kind === "er")
2053
+ this.card(cursor);
2054
+ const target = cursor.peek();
2055
+ if (kind === "state" && (isPunct2(target, "*") || isWord2(target, "final"))) {
2056
+ cursor.take();
2057
+ this.mark(target, "operator");
2058
+ } else if (isId(target)) {
2059
+ cursor.take();
2060
+ this.mark(target, "variable");
2061
+ } else {
2062
+ break;
2063
+ }
2064
+ }
2065
+ this.label(cursor);
2066
+ this.attrs(cursor);
2067
+ this.rest(cursor);
2068
+ }
2069
+ tree() {
2070
+ const text = this.text;
2071
+ let pos = this.lexer.pos;
2072
+ while (pos < text.length) {
2073
+ let end = text.indexOf(`
2074
+ `, pos);
2075
+ if (end < 0)
2076
+ end = text.length;
2077
+ let start = pos;
2078
+ while (start < end && (text[start] === " " || text[start] === "\t"))
2079
+ start++;
2080
+ if (start >= end) {
2081
+ pos = end + 1;
2082
+ continue;
2083
+ }
2084
+ if (text[start] === "#") {
2085
+ this.emit(start, end, "comment");
2086
+ pos = end + 1;
2087
+ continue;
2088
+ }
2089
+ let rest = start;
2090
+ if (text[start] === '"') {
2091
+ this.lexer.seek(start);
2092
+ } else {
2093
+ while (rest < end && text[rest] !== "[" && text[rest] !== "#")
2094
+ rest++;
2095
+ const bare = text.slice(start, rest).trimEnd();
2096
+ this.emit(start, start + bare.length, "string");
2097
+ this.lexer.seek(rest);
2098
+ }
2099
+ const cursor = new Cursor(this.line());
2100
+ if (text[start] === '"')
2101
+ this.label(cursor);
2102
+ this.attrs(cursor);
2103
+ this.rest(cursor);
2104
+ pos = Math.max(this.lexer.pos, end + 1);
2105
+ if (this.eof)
2106
+ break;
2107
+ }
2108
+ }
2109
+ run() {
2110
+ let tokens = this.line();
2111
+ while (tokens.length === 0) {
2112
+ if (this.eof)
2113
+ return;
2114
+ tokens = this.line();
2115
+ }
2116
+ const first = tokens[0];
2117
+ if (!(first.kind === "IDENT" && KINDS.includes(first.text)))
2118
+ return;
2119
+ const kind = this.header(tokens);
2120
+ if (this.eof)
2121
+ return;
2122
+ if (kind === "tree") {
2123
+ this.tree();
2124
+ return;
2125
+ }
2126
+ while (!this.eof)
2127
+ this.statement(kind, this.line());
2128
+ }
2129
+ }
2130
+ function highlight2(source) {
2131
+ const highlighter = new Highlighter(source);
2132
+ try {
2133
+ highlighter.run();
2134
+ } catch {}
2135
+ const sorted = highlighter.out.sort((a, b) => a.start - b.start || a.end - b.end);
2136
+ const result = [];
2137
+ let end = 0;
2138
+ for (const token of sorted) {
2139
+ if (token.start < end)
2140
+ continue;
2141
+ result.push(token);
2142
+ end = token.end;
2143
+ }
2144
+ return result;
2145
+ }
2146
+ // src/text/print.ts
2147
+ var STYLES = {
2148
+ symbols: {
2149
+ ops: { "->": "->", "--": "--", "->>": "->>", "-->": "-->", "..": ".." },
2150
+ open: "{",
2151
+ close: "}"
2152
+ },
2153
+ words: {
2154
+ ops: { "->": "to", "--": "with", "->>": "async", "-->": "reply", "..": "via" },
2155
+ open: "do",
2156
+ close: "end"
2157
+ }
2158
+ };
2159
+ var IDENT_SOURCE = String.raw`[\p{L}_][\p{L}\p{N}_]*(?:[./-][\p{L}\p{N}_]+)*`;
2160
+ var IDENT2 = new RegExp(`^${IDENT_SOURCE}$`, "u");
2161
+ var NUMBER_SOURCE = String.raw`-?[0-9]+(?:\.[0-9]+)?`;
2162
+ var TYPE_ARG = `(?:${NUMBER_SOURCE}|${IDENT_SOURCE})`;
2163
+ var TYPE = new RegExp(String.raw`^${IDENT_SOURCE}(?:\(${TYPE_ARG}(?:,${TYPE_ARG})*\))?(?:\[\])?$`, "u");
2164
+ var ESCAPED = /["\\\u0000-\u001f\u007f-\u009f]/g;
2165
+ var ESCAPES = {
2166
+ '"': "\\\"",
2167
+ "\\": "\\\\",
2168
+ "\n": "\\n",
2169
+ "\t": "\\t"
2170
+ };
2171
+ var WORDS = new Set(["to", "with", "async", "reply", "via", "initial", "final", "do", "end"]);
2172
+ var GRAPH_RESERVED = new Set(["group"]);
2173
+ var ATTRIBUTE_RESERVED = new Set(["pk", "fk", "uk", "null"]);
2174
+ var FLAGS2 = new Set(["pk", "fk", "uk", "null"]);
2175
+ var CARDINALITY_TEXT = {
2176
+ one: "1",
2177
+ "zero-or-one": "0..1",
2178
+ "one-or-more": "1..*",
2179
+ "zero-or-more": "0..*"
2180
+ };
2181
+ function numberText(value) {
2182
+ return Object.is(value, -0) ? "-0" : String(value);
2183
+ }
2184
+ function quote(value) {
2185
+ return `"${value.replace(ESCAPED, (char) => ESCAPES[char] ?? `\\u{${char.charCodeAt(0).toString(16)}}`)}"`;
2186
+ }
2187
+ function backticked(value) {
2188
+ return `\`${value.replace(/[\\`]/g, "\\$&")}\``;
2189
+ }
2190
+ function ident(value, reserved) {
2191
+ return IDENT2.test(value) && !WORDS.has(value) && !reserved?.has(value) ? value : backticked(value);
2192
+ }
2193
+ function pad(depth) {
2194
+ return " ".repeat(depth);
2195
+ }
2196
+ function labelText(label) {
2197
+ return label === undefined ? "" : ` ${quote(label)}`;
2198
+ }
2199
+ function attrText(pairs) {
2200
+ return pairs.length === 0 ? "" : ` [${pairs.map(([key, value]) => `${key}=${value}`).join(", ")}]`;
2201
+ }
2202
+ function metaPairs(meta) {
2203
+ const pairs = [];
2204
+ if (!meta)
2205
+ return pairs;
2206
+ const { provenance } = meta;
2207
+ if (provenance) {
2208
+ pairs.push(["source", quote(provenance.source)]);
2209
+ if (provenance.confidence !== undefined)
2210
+ pairs.push(["confidence", provenance.confidence]);
2211
+ if (provenance.tool !== undefined)
2212
+ pairs.push(["tool", quote(provenance.tool)]);
2213
+ }
2214
+ if (meta.coverage !== undefined)
2215
+ pairs.push(["coverage", numberText(meta.coverage)]);
2216
+ if (meta.freshness !== undefined)
2217
+ pairs.push(["freshness", quote(meta.freshness)]);
2218
+ for (const [name, value] of Object.entries(meta.data ?? {})) {
2219
+ const key = `data.${name}`;
2220
+ pairs.push([
2221
+ IDENT2.test(key) ? key : backticked(key),
2222
+ typeof value === "string" ? quote(value) : typeof value === "number" ? numberText(value) : String(value)
2223
+ ]);
2224
+ }
2225
+ return pairs;
2226
+ }
2227
+ function fieldPairs(item, withId) {
2228
+ const pairs = [];
2229
+ if (withId && item.id !== undefined)
2230
+ pairs.push(["id", quote(item.id)]);
2231
+ if (item.type !== undefined)
2232
+ pairs.push(["type", quote(item.type)]);
2233
+ if (item.shape !== undefined)
2234
+ pairs.push(["shape", item.shape]);
2235
+ if (item.pseudo !== undefined)
2236
+ pairs.push(["pseudo", item.pseudo]);
2237
+ if (item.actions !== undefined) {
2238
+ pairs.push(["actions", `[${item.actions.map(quote).join(", ")}]`]);
2239
+ }
2240
+ if (item.guard !== undefined)
2241
+ pairs.push(["guard", quote(item.guard)]);
2242
+ if (item.action !== undefined)
2243
+ pairs.push(["action", quote(item.action)]);
2244
+ if (item.link !== undefined)
2245
+ pairs.push(["link", quote(item.link)]);
2246
+ if (item.description !== undefined)
2247
+ pairs.push(["description", quote(item.description)]);
2248
+ if (item.position !== undefined) {
2249
+ pairs.push(["x", numberText(item.position.x)], ["y", numberText(item.position.y)]);
2250
+ }
2251
+ pairs.push(...metaPairs(item.meta));
2252
+ return pairs;
2253
+ }
2254
+ function declaration(id, item, depth, reserved, suffix = "") {
2255
+ return `${pad(depth)}${ident(id, reserved)}${labelText(item.label)}${attrText(fieldPairs(item, false))}${suffix}`;
2256
+ }
2257
+ function assemble(header, sections) {
2258
+ const lines = [header];
2259
+ for (const section of sections) {
2260
+ if (section.length > 0)
2261
+ lines.push("", ...section);
2262
+ }
2263
+ return `${lines.join(`
2264
+ `)}
2265
+ `;
2266
+ }
2267
+ function headerLine(doc) {
2268
+ const pairs = [];
2269
+ if ("direction" in doc && doc.direction !== undefined) {
2270
+ pairs.push(["direction", doc.direction]);
2271
+ }
2272
+ if (doc.kind === "tree" && doc.layout !== undefined) {
2273
+ pairs.push(["layout", doc.layout]);
2274
+ }
2275
+ pairs.push(...metaPairs(doc.meta));
2276
+ return `${doc.kind}${labelText(doc.title)}${attrText(pairs)}`;
2277
+ }
2278
+ function connection(from, operator, to, item, middle) {
2279
+ const left = middle?.[0] ? ` ${middle[0]}` : "";
2280
+ const right = middle?.[1] ? ` ${middle[1]}` : "";
2281
+ return `${ident(from)}${left} ${operator}${right} ${ident(to)}${labelText(item.label)}${attrText(fieldPairs(item, true))}`;
2282
+ }
2283
+ function printGraph(doc, style) {
2284
+ const byGroup = groupNodes(doc.nodes);
2285
+ const declarations = [];
2286
+ const nodeLines = (group, depth) => {
2287
+ for (const node of byGroup.get(group) ?? []) {
2288
+ declarations.push(declaration(node.id, node, depth, GRAPH_RESERVED));
2289
+ }
2290
+ };
2291
+ nodeLines(undefined, 0);
2292
+ walk(doc.groups ?? [], (group, depth) => {
2293
+ declarations.push(`${pad(depth)}group ${ident(group.id, GRAPH_RESERVED)}${labelText(group.label)}${attrText(metaPairs(group.meta))} ${style.open}`);
2294
+ nodeLines(group.id, depth + 1);
2295
+ }, (_group, depth) => {
2296
+ declarations.push(`${pad(depth)}${style.close}`);
2297
+ });
2298
+ const edges = (doc.edges ?? []).map((edge) => connection(edge.from, style.ops[edge.directed === false ? "--" : "->"], edge.to, edge));
2299
+ return [declarations, edges];
2300
+ }
2301
+ function printSequence(doc, style) {
2302
+ const operators = { sync: "->", async: "->>", reply: "-->" };
2303
+ return [
2304
+ doc.participants.map((participant) => declaration(participant.id, participant, 0)),
2305
+ doc.messages.map((message) => connection(message.from, style.ops[operators[message.style ?? "sync"]], message.to, message))
2306
+ ];
2307
+ }
2308
+ function printState(doc, style) {
2309
+ const states = [];
2310
+ walk(doc.states, (state, depth, children) => {
2311
+ states.push(declaration(state.id, state, depth, undefined, children > 0 ? ` ${style.open}` : ""));
2312
+ }, (_state, depth, children) => {
2313
+ if (children > 0)
2314
+ states.push(`${pad(depth)}${style.close}`);
2315
+ });
2316
+ const transitions = (doc.transitions ?? []).map((transition) => connection(transition.from, style.ops["->"], transition.to, {
2317
+ ...transition,
2318
+ label: transition.event
2319
+ }));
2320
+ return [states, transitions];
2321
+ }
2322
+ function typeText(type) {
2323
+ const first = /^[^(\[]*/.exec(type)[0];
2324
+ return TYPE.test(type) && !FLAGS2.has(first) ? type : quote(type);
2325
+ }
2326
+ function entityLines(entity, style) {
2327
+ const attributes = entity.attributes;
2328
+ const lines = [
2329
+ declaration(entity.id, entity, 0, undefined, attributes === undefined ? "" : ` ${style.open}`)
2330
+ ];
2331
+ if (attributes === undefined)
2332
+ return lines;
2333
+ for (const attribute of attributes) {
2334
+ const parts = [ident(attribute.name, ATTRIBUTE_RESERVED)];
2335
+ if (attribute.type !== undefined)
2336
+ parts.push(typeText(attribute.type));
2337
+ parts.push(...attribute.keys ?? []);
2338
+ if (attribute.nullable === true)
2339
+ parts.push("null");
2340
+ const note = attribute.note === undefined ? [] : [["note", quote(attribute.note)]];
2341
+ lines.push(`${pad(1)}${parts.join(" ")}${attrText(note)}`);
2342
+ }
2343
+ lines.push(style.close);
2344
+ return lines;
2345
+ }
2346
+ function printEr(doc, style) {
2347
+ const relations = (doc.relations ?? []).map((relation) => connection(relation.from, style.ops[relation.identifying === false ? ".." : "--"], relation.to, relation, [
2348
+ relation.fromCardinality ? CARDINALITY_TEXT[relation.fromCardinality] : "",
2349
+ relation.toCardinality ? CARDINALITY_TEXT[relation.toCardinality] : ""
2350
+ ]));
2351
+ return [doc.entities.flatMap((entity) => entityLines(entity, style)), relations];
2352
+ }
2353
+ function bareLabel(label) {
2354
+ return label !== "" && label === label.trim() && !/["#\[\n\r]/.test(label);
2355
+ }
2356
+ function explicitIds(nodes) {
2357
+ let explicit = new Set;
2358
+ for (;; ) {
2359
+ const used = new Set([...explicit].map((index) => nodes[index].id));
2360
+ const next = new Set(explicit);
2361
+ nodes.forEach((node, index) => {
2362
+ if (explicit.has(index))
2363
+ return;
2364
+ const base = slug(node.label);
2365
+ let candidate = base;
2366
+ for (let suffix = 2;used.has(candidate); suffix++)
2367
+ candidate = `${base}-${suffix}`;
2368
+ used.add(candidate);
2369
+ if (candidate !== node.id)
2370
+ next.add(index);
2371
+ });
2372
+ if (next.size === explicit.size)
2373
+ return explicit;
2374
+ explicit = next;
2375
+ }
2376
+ }
2377
+ function printTree(doc) {
2378
+ const nodes = preorder(doc.nodes);
2379
+ const explicit = explicitIds(nodes);
2380
+ const index = new Map(nodes.map((node, position) => [node, position]));
2381
+ const lines = [];
2382
+ walk(doc.nodes, (node, depth) => {
2383
+ const item = { ...node, id: explicit.has(index.get(node)) ? node.id : undefined };
2384
+ const text = bareLabel(node.label) ? node.label : quote(node.label);
2385
+ lines.push(`${pad(depth)}${text}${attrText(fieldPairs(item, true))}`);
2386
+ });
2387
+ return [lines];
2388
+ }
2389
+ function print2(doc, options = {}) {
2390
+ const style = STYLES[options.style ?? "symbols"];
2391
+ const header = headerLine(doc);
2392
+ switch (doc.kind) {
2393
+ case "graph":
2394
+ return assemble(header, printGraph(doc, style));
2395
+ case "sequence":
2396
+ return assemble(header, printSequence(doc, style));
2397
+ case "state":
2398
+ return assemble(header, printState(doc, style));
2399
+ case "er":
2400
+ return assemble(header, printEr(doc, style));
2401
+ case "tree":
2402
+ return assemble(header, printTree(doc));
2403
+ }
2404
+ }
2405
+
2406
+ // src/text/index.ts
2407
+ function rangeOf(marks, path) {
2408
+ let pointer = path;
2409
+ for (;; ) {
2410
+ const range = marks.get(pointer);
2411
+ if (range)
2412
+ return range;
2413
+ if (pointer === "")
2414
+ return { start: 0, end: 0 };
2415
+ pointer = pointer.slice(0, pointer.lastIndexOf("/"));
2416
+ }
2417
+ }
2418
+ function parse2(source) {
2419
+ const text = normalize(source);
2420
+ const sink = new Sink(new LineMap(text));
2421
+ try {
2422
+ const ast = parseSyntax(text, sink);
2423
+ if (ast && sink.errors.length === 0) {
2424
+ const marks = new Map;
2425
+ const document = build(ast, { sink, marks });
2426
+ if (sink.errors.length === 0) {
2427
+ const result = validate2(document);
2428
+ if (result.ok)
2429
+ return { ok: true, document: result.document };
2430
+ for (const error of result.errors) {
2431
+ sink.report("E_VALIDATE", rangeOf(marks, error.path), error.message);
2432
+ }
2433
+ }
2434
+ }
2435
+ } catch (error) {
2436
+ if (error !== STOP)
2437
+ throw error;
2438
+ }
2439
+ return { ok: false, errors: sink.sorted() };
2440
+ }
2441
+ function sniff2(source) {
2442
+ const text = source.replace(/^/, "");
2443
+ for (const line of text.split(/\r\n|\n|\r/)) {
2444
+ const trimmed = line.trim();
2445
+ if (trimmed === "" || trimmed.startsWith("#"))
2446
+ continue;
2447
+ return trimmed.startsWith("{") ? "json" : "text";
2448
+ }
2449
+ return "text";
2450
+ }
2451
+ function loadSource2(source) {
2452
+ const format = sniff2(source);
2453
+ if (format === "text") {
2454
+ const result = parse2(source);
2455
+ if (result.ok)
2456
+ return { ok: true, format, document: result.document };
2457
+ return {
2458
+ ok: false,
2459
+ format,
2460
+ errors: result.errors.map((error) => ({
2461
+ message: error.message,
2462
+ line: error.line,
2463
+ column: error.column,
2464
+ code: error.code
2465
+ }))
2466
+ };
2467
+ }
2468
+ let value;
2469
+ try {
2470
+ value = JSON.parse(source.replace(/^/, ""));
2471
+ } catch (error) {
2472
+ const reason = error instanceof Error ? error.message : String(error);
2473
+ return { ok: false, format, errors: [{ message: `Invalid JSON: ${reason}` }] };
2474
+ }
2475
+ const result = validate2(value);
2476
+ if (result.ok)
2477
+ return { ok: true, format, document: result.document };
2478
+ return {
2479
+ ok: false,
2480
+ format,
2481
+ errors: result.errors.map((error) => ({ path: error.path, message: error.message }))
2482
+ };
2483
+ }
2484
+
2485
+ export { STOP, LineMap, Sink, IDENT, normalize, Lexer, KINDS, FLAGS, CARDINALITIES2, OPERATOR_WORDS, OPERATOR_RULES, operatorOf, parseSyntaxPartial, canonicalize2, SEMANTIC_TOKEN_TYPES2, SEMANTIC_TOKEN_MODIFIERS2, highlight2, print2, parse2, sniff2, loadSource2 };