@standarx/graph 0.0.0-stage → 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.
Files changed (127) hide show
  1. package/LICENSE +21 -0
  2. package/README.fr.md +436 -0
  3. package/README.md +435 -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-b4n941t8.js +1439 -0
  14. package/dist/cli-eqq7a3wz.js +1144 -0
  15. package/dist/cli-gh5166k6.js +1565 -0
  16. package/dist/cli-kzp16pt5.js +207 -0
  17. package/dist/cli-mzmjkk5v.js +11 -0
  18. package/dist/cli-njgyf690.js +1060 -0
  19. package/dist/cli-nkm2j980.js +141 -0
  20. package/dist/cli-nyckgf1t.js +4 -0
  21. package/dist/cli-sfdqkbd1.js +433 -0
  22. package/dist/cli-txrzzr2q.js +0 -0
  23. package/dist/cli-vecew2na.js +709 -0
  24. package/dist/cli-wt9dmbhm.js +560 -0
  25. package/dist/cli-xhdxp3cj.js +387 -0
  26. package/dist/cli-ywgtv1cg.js +39 -0
  27. package/dist/cli.d.ts +2 -0
  28. package/dist/cli.js +415 -0
  29. package/dist/core/index.d.ts +6 -0
  30. package/dist/core/index.js +93 -0
  31. package/dist/core/spatial.d.ts +16 -0
  32. package/dist/core/threshold.d.ts +1 -0
  33. package/dist/core/view.d.ts +80 -0
  34. package/dist/export/index.d.ts +18 -0
  35. package/dist/export/index.js +172 -0
  36. package/dist/export/pdf.d.ts +5 -0
  37. package/dist/export/png.d.ts +4 -0
  38. package/dist/format/index.d.ts +4 -0
  39. package/dist/format/index.js +71 -0
  40. package/dist/format/json-schema.d.ts +2 -0
  41. package/dist/format/schema.d.ts +787 -0
  42. package/dist/format/semantic/er.d.ts +3 -0
  43. package/dist/format/semantic/graph.d.ts +3 -0
  44. package/dist/format/semantic/sequence.d.ts +3 -0
  45. package/dist/format/semantic/shared.d.ts +14 -0
  46. package/dist/format/semantic/state.d.ts +3 -0
  47. package/dist/format/semantic/tree.d.ts +3 -0
  48. package/dist/format/transition-label.d.ts +2 -0
  49. package/dist/format/validate.d.ts +11 -0
  50. package/dist/html/index.d.ts +3 -0
  51. package/dist/html/index.js +127 -0
  52. package/dist/html/layout-worker.d.ts +1 -0
  53. package/dist/html/layout-worker.generated.d.ts +1 -0
  54. package/dist/html/mount.d.ts +12 -0
  55. package/dist/html/page.d.ts +14 -0
  56. package/dist/html/render.d.ts +7 -0
  57. package/dist/html/runtime.d.ts +1 -0
  58. package/dist/html/runtime.generated.d.ts +1 -0
  59. package/dist/html/shell.d.ts +10 -0
  60. package/dist/html/svg-adapter.d.ts +8 -0
  61. package/dist/html/ui.d.ts +34 -0
  62. package/dist/language/analysis.d.ts +38 -0
  63. package/dist/language/complete.d.ts +3 -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 +6 -0
  68. package/dist/language/index.js +1385 -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 +34 -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 +17 -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-emmvgfb1.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 +104 -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 +27 -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,1439 @@
1
+ import {
2
+ SHAPES2,
3
+ DirectionSchema2,
4
+ PSEUDO2,
5
+ TREE_LAYOUTS2
6
+ } from "./cli-kzp16pt5.js";
7
+ import {
8
+ validate2
9
+ } from "./cli-xhdxp3cj.js";
10
+ import {
11
+ STOP,
12
+ LineMap,
13
+ Sink,
14
+ normalize,
15
+ Lexer,
16
+ KINDS,
17
+ FLAGS,
18
+ OPERATOR_WORDS,
19
+ parseSyntax
20
+ } from "./cli-njgyf690.js";
21
+
22
+ // src/text/slug.ts
23
+ function slug(label) {
24
+ const base = label.normalize("NFKD").replace(/\p{M}/gu, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
25
+ return base === "" ? "node" : base;
26
+ }
27
+
28
+ // src/text/build.ts
29
+ var DIRECTIONS = DirectionSchema2.anyOf.map((literal) => literal.const);
30
+ var CONFIDENCES = ["confirmed", "inferred", "unknown"];
31
+ var META_FIELDS = {
32
+ source: "string",
33
+ confidence: CONFIDENCES,
34
+ tool: "string",
35
+ coverage: "number",
36
+ freshness: "string"
37
+ };
38
+ var PROVENANCE_KEYS = new Set(["source", "confidence", "tool"]);
39
+ var META_NAMES = [...Object.keys(META_FIELDS), "data.*"];
40
+ var NODE = {
41
+ noun: "a node",
42
+ fields: { type: "string", shape: SHAPES2, link: "string", description: "string", x: "number", y: "number" },
43
+ meta: true,
44
+ position: true
45
+ };
46
+ var GROUP = { noun: "a group", fields: {}, meta: true };
47
+ var EDGE = { noun: "an edge", fields: { id: "string", type: "string" }, meta: true };
48
+ var PARTICIPANT = { noun: "a participant", fields: { type: "string" }, meta: true };
49
+ var MESSAGE = { noun: "a message", fields: {}, meta: true };
50
+ var STATE = {
51
+ noun: "a state",
52
+ fields: { type: "string", pseudo: PSEUDO2, actions: "strings", description: "string", link: "string" },
53
+ meta: true
54
+ };
55
+ var TRANSITION = {
56
+ noun: "a transition",
57
+ fields: { id: "string", guard: "string", action: "string", type: "string" },
58
+ meta: true
59
+ };
60
+ var ENTITY = {
61
+ noun: "an entity",
62
+ fields: { type: "string", description: "string", link: "string" },
63
+ meta: true
64
+ };
65
+ var ATTRIBUTE = { noun: "an attribute", fields: { note: "string" }, meta: false };
66
+ var RELATION = { noun: "a relation", fields: { id: "string", type: "string" }, meta: true };
67
+ var TREE_NODE = {
68
+ noun: "a tree node",
69
+ fields: { id: "string", type: "string", shape: SHAPES2, description: "string", link: "string" },
70
+ meta: true
71
+ };
72
+ var HEADERS = {
73
+ graph: { noun: "the header", fields: { direction: DIRECTIONS }, meta: true },
74
+ sequence: { noun: "the header", fields: {}, meta: true },
75
+ state: { noun: "the header", fields: { direction: DIRECTIONS }, meta: true },
76
+ er: { noun: "the header", fields: { direction: DIRECTIONS }, meta: true },
77
+ tree: { noun: "the header", fields: { direction: DIRECTIONS, layout: TREE_LAYOUTS2 }, meta: true }
78
+ };
79
+ function mark(ctx, pointer, range) {
80
+ ctx.marks.set(pointer, range);
81
+ }
82
+ function describe(value) {
83
+ if (value.type === "list")
84
+ return "a list";
85
+ if (value.type === "number")
86
+ return String(value.value);
87
+ return JSON.stringify(value.value);
88
+ }
89
+ function isStringLike(value) {
90
+ return value.type === "string" || value.type === "ident";
91
+ }
92
+ function coerce(ctx, attr, field) {
93
+ const value = attr.value;
94
+ let expects;
95
+ if (field === "number") {
96
+ if (value.type === "number")
97
+ return value.value;
98
+ expects = "a number";
99
+ } else if (field === "strings") {
100
+ if (value.type === "list" && value.items.every(isStringLike)) {
101
+ return value.items.map((item) => item.value);
102
+ }
103
+ expects = "a list of strings";
104
+ } else if (field === "string") {
105
+ if (isStringLike(value))
106
+ return value.value;
107
+ expects = "a string";
108
+ } else {
109
+ if (isStringLike(value) && field.includes(value.value))
110
+ return value.value;
111
+ expects = `one of ${field.join(", ")}`;
112
+ }
113
+ ctx.sink.report("E_VALUE", value.range, `Attribute "${attr.key}" expects ${expects}; found ${describe(value)}`);
114
+ return;
115
+ }
116
+ function coerceData(ctx, attr) {
117
+ const value = attr.value;
118
+ if (value.type === "string" || value.type === "number")
119
+ return value.value;
120
+ if (value.type === "ident" && (value.value === "true" || value.value === "false")) {
121
+ return value.value === "true";
122
+ }
123
+ ctx.sink.report("E_VALUE", value.range, `Attribute "${attr.key}" expects a string, a number or a boolean; found ${describe(value)}`);
124
+ return;
125
+ }
126
+ function applyMeta(ctx, attr, target, pointer) {
127
+ const { key } = attr;
128
+ const isData = key.startsWith("data.") && key.length > 5;
129
+ if (!isData && !Object.hasOwn(META_FIELDS, key))
130
+ return false;
131
+ const value = isData ? coerceData(ctx, attr) : coerce(ctx, attr, META_FIELDS[key]);
132
+ if (value === undefined)
133
+ return true;
134
+ const meta = target.meta ??= {};
135
+ const base = `${pointer}/meta`;
136
+ mark(ctx, base, attr.range);
137
+ if (isData) {
138
+ const name = key.slice(5);
139
+ (meta.data ??= {})[name] = value;
140
+ mark(ctx, `${base}/data`, attr.range);
141
+ mark(ctx, `${base}/data/${name}`, attr.value.range);
142
+ } else if (PROVENANCE_KEYS.has(key)) {
143
+ (meta.provenance ??= {})[key] = value;
144
+ mark(ctx, `${base}/provenance`, attr.range);
145
+ mark(ctx, `${base}/provenance/${key}`, attr.value.range);
146
+ } else {
147
+ meta[key] = value;
148
+ mark(ctx, `${base}/${key}`, attr.value.range);
149
+ }
150
+ return true;
151
+ }
152
+ function applyAttrs(ctx, attrs, spec, target, pointer) {
153
+ const seen = new Set;
154
+ const coordinates = new Map;
155
+ let needsSource;
156
+ for (const attr of attrs) {
157
+ const { key } = attr;
158
+ if (seen.has(key)) {
159
+ ctx.sink.report("E_ATTR", attr.keyRange, `Attribute "${key}" is set twice`);
160
+ continue;
161
+ }
162
+ seen.add(key);
163
+ if (Object.hasOwn(spec.fields, key)) {
164
+ const value = coerce(ctx, attr, spec.fields[key]);
165
+ if (value === undefined)
166
+ continue;
167
+ if (spec.position && (key === "x" || key === "y")) {
168
+ coordinates.set(key, { value, attr });
169
+ } else {
170
+ target[key] = value;
171
+ mark(ctx, `${pointer}/${key}`, attr.value.range);
172
+ }
173
+ continue;
174
+ }
175
+ if (spec.meta && applyMeta(ctx, attr, target, pointer)) {
176
+ if (key === "confidence" || key === "tool")
177
+ needsSource ??= attr;
178
+ continue;
179
+ }
180
+ const expected = [...Object.keys(spec.fields), ...spec.meta ? META_NAMES : []];
181
+ ctx.sink.report("E_ATTR", attr.keyRange, `Unknown attribute "${key}" for ${spec.noun} (expected: ${expected.join(", ")})`);
182
+ }
183
+ if (spec.position && coordinates.size > 0) {
184
+ const x = coordinates.get("x");
185
+ const y = coordinates.get("y");
186
+ if (x && y) {
187
+ target.position = { x: x.value, y: y.value };
188
+ mark(ctx, `${pointer}/position`, { start: x.attr.range.start, end: y.attr.range.end });
189
+ mark(ctx, `${pointer}/position/x`, x.attr.value.range);
190
+ mark(ctx, `${pointer}/position/y`, y.attr.value.range);
191
+ } else {
192
+ ctx.sink.report("E_ATTR", (x ?? y).attr.keyRange, "x and y go together");
193
+ }
194
+ }
195
+ if (needsSource) {
196
+ const meta = target.meta;
197
+ const provenance = meta?.provenance;
198
+ if (provenance?.source === undefined) {
199
+ ctx.sink.report("E_ATTR", needsSource.keyRange, "confidence and tool need a source");
200
+ }
201
+ }
202
+ }
203
+ function setLabel(ctx, item, pointer, label) {
204
+ if (!label)
205
+ return;
206
+ item.label = label.value;
207
+ mark(ctx, `${pointer}/label`, label.range);
208
+ }
209
+
210
+ class Registry {
211
+ ctx;
212
+ collection;
213
+ noun;
214
+ blockField;
215
+ items = [];
216
+ entries = new Map;
217
+ constructor(ctx, collection, noun, blockField) {
218
+ this.ctx = ctx;
219
+ this.collection = collection;
220
+ this.noun = noun;
221
+ this.blockField = blockField;
222
+ }
223
+ pointer(entry) {
224
+ return `/${this.collection}/${entry.index}`;
225
+ }
226
+ item(entry) {
227
+ return this.items[entry.index];
228
+ }
229
+ mention(id, block) {
230
+ let entry = this.entries.get(id.value);
231
+ if (!entry) {
232
+ const item = { id: id.value };
233
+ if (this.blockField && block !== undefined)
234
+ item[this.blockField] = block;
235
+ entry = {
236
+ index: this.items.length,
237
+ block,
238
+ line: this.ctx.sink.lineOf(id.range.start),
239
+ declared: false
240
+ };
241
+ this.items.push(item);
242
+ this.entries.set(id.value, entry);
243
+ mark(this.ctx, this.pointer(entry), id.range);
244
+ mark(this.ctx, `${this.pointer(entry)}/id`, id.range);
245
+ }
246
+ return entry;
247
+ }
248
+ declare(id, block, range) {
249
+ const existing = this.entries.get(id.value);
250
+ if (existing?.declared) {
251
+ this.ctx.sink.report("E_DUPLICATE", id.range, `${this.noun} "${id.value}" is already declared at line ${existing.line}`);
252
+ return;
253
+ }
254
+ if (existing && existing.block !== block) {
255
+ 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`);
256
+ return;
257
+ }
258
+ const entry = this.mention(id, block);
259
+ entry.declared = true;
260
+ entry.line = this.ctx.sink.lineOf(id.range.start);
261
+ mark(this.ctx, this.pointer(entry), range);
262
+ return entry;
263
+ }
264
+ }
265
+ function buildGraph(ast, ctx) {
266
+ const nodes = new Registry(ctx, "nodes", "Node", "group");
267
+ const groups = new Registry(ctx, "groups", "Group", "parent");
268
+ const edges = [];
269
+ const walk = (statements, block) => {
270
+ for (const statement of statements) {
271
+ if (statement.t === "group") {
272
+ const entry = groups.declare(statement.id, block, statement.range);
273
+ if (entry) {
274
+ const item = groups.item(entry);
275
+ setLabel(ctx, item, groups.pointer(entry), statement.label);
276
+ applyAttrs(ctx, statement.attrs, GROUP, item, groups.pointer(entry));
277
+ }
278
+ walk(statement.body, statement.id.value);
279
+ } else if (statement.t === "node") {
280
+ const entry = nodes.declare(statement.id, block, statement.range);
281
+ if (entry) {
282
+ const item = nodes.item(entry);
283
+ setLabel(ctx, item, nodes.pointer(entry), statement.label);
284
+ applyAttrs(ctx, statement.attrs, NODE, item, nodes.pointer(entry));
285
+ }
286
+ } else {
287
+ for (const id of statement.ids)
288
+ nodes.mention(id, block);
289
+ const several = statement.ops.length > 1;
290
+ const attrs = several ? statement.attrs.filter((attr) => {
291
+ if (attr.key !== "id")
292
+ return true;
293
+ ctx.sink.report("E_ATTR", attr.keyRange, "id cannot be set on a chain of several edges");
294
+ return false;
295
+ }) : statement.attrs;
296
+ statement.ops.forEach((op, position) => {
297
+ const edge = {
298
+ from: statement.ids[position].value,
299
+ to: statement.ids[position + 1].value
300
+ };
301
+ const pointer = `/edges/${edges.length}`;
302
+ edges.push(edge);
303
+ mark(ctx, pointer, statement.range);
304
+ mark(ctx, `${pointer}/from`, statement.ids[position].range);
305
+ mark(ctx, `${pointer}/to`, statement.ids[position + 1].range);
306
+ mark(ctx, `${pointer}/directed`, op.range);
307
+ setLabel(ctx, edge, pointer, statement.label);
308
+ edge.directed = op.symbol === "->";
309
+ if (position > 0)
310
+ ctx.sink.muted++;
311
+ applyAttrs(ctx, attrs, EDGE, edge, pointer);
312
+ if (position > 0)
313
+ ctx.sink.muted--;
314
+ });
315
+ }
316
+ }
317
+ };
318
+ walk(ast.body, undefined);
319
+ const result = { nodes: nodes.items };
320
+ if (edges.length > 0)
321
+ result.edges = edges;
322
+ if (groups.items.length > 0)
323
+ result.groups = groups.items;
324
+ return result;
325
+ }
326
+ function buildSequence(ast, ctx) {
327
+ const participants = new Registry(ctx, "participants", "Participant");
328
+ const messages = [];
329
+ for (const statement of ast.body) {
330
+ if (statement.t === "participant") {
331
+ const entry = participants.declare(statement.id, undefined, statement.range);
332
+ if (entry) {
333
+ const item = participants.item(entry);
334
+ setLabel(ctx, item, participants.pointer(entry), statement.label);
335
+ applyAttrs(ctx, statement.attrs, PARTICIPANT, item, participants.pointer(entry));
336
+ }
337
+ } else {
338
+ participants.mention(statement.from, undefined);
339
+ participants.mention(statement.to, undefined);
340
+ const pointer = `/messages/${messages.length}`;
341
+ const message = { from: statement.from.value, to: statement.to.value };
342
+ messages.push(message);
343
+ mark(ctx, pointer, statement.range);
344
+ mark(ctx, `${pointer}/from`, statement.from.range);
345
+ mark(ctx, `${pointer}/to`, statement.to.range);
346
+ mark(ctx, `${pointer}/style`, statement.op.range);
347
+ setLabel(ctx, message, pointer, statement.label);
348
+ message.style = statement.op.symbol === "->" ? "sync" : statement.op.symbol === "->>" ? "async" : "reply";
349
+ applyAttrs(ctx, statement.attrs, MESSAGE, message, pointer);
350
+ }
351
+ }
352
+ return { participants: participants.items, messages };
353
+ }
354
+ function buildState(ast, ctx) {
355
+ const states = new Registry(ctx, "states", "State", "parent");
356
+ const transitions = [];
357
+ const endpoint = (target, pseudo, block) => {
358
+ if (!target.star) {
359
+ states.mention(target, block);
360
+ return target.value;
361
+ }
362
+ const id = `${block ?? ""}__${pseudo}`;
363
+ const before = states.items.length;
364
+ const entry = states.mention({ value: id, range: target.range }, block);
365
+ const item = states.item(entry);
366
+ if (states.items.length > before) {
367
+ item.pseudo = pseudo;
368
+ mark(ctx, `${states.pointer(entry)}/pseudo`, target.range);
369
+ } else if (item.pseudo !== pseudo) {
370
+ ctx.sink.report("E_VALUE", target.range, `State "${id}" already exists and is not an ${pseudo} pseudo-state, so "*" cannot stand for it`);
371
+ }
372
+ return id;
373
+ };
374
+ const walk = (statements, block) => {
375
+ for (const statement of statements) {
376
+ if (statement.t === "state") {
377
+ const entry = states.declare(statement.id, block, statement.range);
378
+ if (entry) {
379
+ const item = states.item(entry);
380
+ const pointer = states.pointer(entry);
381
+ const previous = item.pseudo;
382
+ setLabel(ctx, item, pointer, statement.label);
383
+ applyAttrs(ctx, statement.attrs, STATE, item, pointer);
384
+ if (previous !== undefined && item.pseudo !== previous) {
385
+ 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 "*"`);
386
+ }
387
+ }
388
+ if (statement.body)
389
+ walk(statement.body, statement.id.value);
390
+ } else {
391
+ const from = endpoint(statement.from, "initial", block);
392
+ const to = endpoint(statement.to, "final", block);
393
+ const pointer = `/transitions/${transitions.length}`;
394
+ const transition = { from, to };
395
+ transitions.push(transition);
396
+ mark(ctx, pointer, statement.range);
397
+ mark(ctx, `${pointer}/from`, statement.from.range);
398
+ mark(ctx, `${pointer}/to`, statement.to.range);
399
+ if (statement.label) {
400
+ transition.event = statement.label.value;
401
+ mark(ctx, `${pointer}/event`, statement.label.range);
402
+ }
403
+ applyAttrs(ctx, statement.attrs, TRANSITION, transition, pointer);
404
+ }
405
+ }
406
+ };
407
+ walk(ast.body, undefined);
408
+ const result = { states: states.items };
409
+ if (transitions.length > 0)
410
+ result.transitions = transitions;
411
+ return result;
412
+ }
413
+ function buildEr(ast, ctx) {
414
+ const entities = new Registry(ctx, "entities", "Entity");
415
+ const relations = [];
416
+ for (const statement of ast.body) {
417
+ if (statement.t === "entity") {
418
+ const entry = entities.declare(statement.id, undefined, statement.range);
419
+ if (!entry)
420
+ continue;
421
+ const item = entities.item(entry);
422
+ const pointer = entities.pointer(entry);
423
+ setLabel(ctx, item, pointer, statement.label);
424
+ applyAttrs(ctx, statement.attrs, ENTITY, item, pointer);
425
+ if (statement.attributes) {
426
+ item.attributes = statement.attributes.map((line, index) => {
427
+ const attribute = { name: line.name.value };
428
+ const at = `${pointer}/attributes/${index}`;
429
+ mark(ctx, at, line.range);
430
+ mark(ctx, `${at}/name`, line.name.range);
431
+ if (line.type) {
432
+ attribute.type = line.type.value;
433
+ mark(ctx, `${at}/type`, line.type.range);
434
+ }
435
+ const keys = [];
436
+ for (const flag of line.flags) {
437
+ if (flag.value === "null") {
438
+ attribute.nullable = true;
439
+ mark(ctx, `${at}/nullable`, flag.range);
440
+ } else {
441
+ mark(ctx, `${at}/keys/${keys.length}`, flag.range);
442
+ keys.push(flag.value);
443
+ }
444
+ }
445
+ if (keys.length > 0) {
446
+ attribute.keys = keys;
447
+ mark(ctx, `${at}/keys`, line.flags.find((flag) => flag.value !== "null").range);
448
+ }
449
+ applyAttrs(ctx, line.attrs, ATTRIBUTE, attribute, at);
450
+ return attribute;
451
+ });
452
+ }
453
+ } else {
454
+ entities.mention(statement.from, undefined);
455
+ entities.mention(statement.to, undefined);
456
+ const pointer = `/relations/${relations.length}`;
457
+ const relation = { from: statement.from.value, to: statement.to.value };
458
+ relations.push(relation);
459
+ mark(ctx, pointer, statement.range);
460
+ mark(ctx, `${pointer}/from`, statement.from.range);
461
+ mark(ctx, `${pointer}/to`, statement.to.range);
462
+ mark(ctx, `${pointer}/identifying`, statement.op.range);
463
+ if (statement.fromCard) {
464
+ relation.fromCardinality = statement.fromCard.value;
465
+ mark(ctx, `${pointer}/fromCardinality`, statement.fromCard.range);
466
+ }
467
+ if (statement.toCard) {
468
+ relation.toCardinality = statement.toCard.value;
469
+ mark(ctx, `${pointer}/toCardinality`, statement.toCard.range);
470
+ }
471
+ setLabel(ctx, relation, pointer, statement.label);
472
+ relation.identifying = statement.op.symbol === "--";
473
+ applyAttrs(ctx, statement.attrs, RELATION, relation, pointer);
474
+ }
475
+ }
476
+ const result = { entities: entities.items };
477
+ if (relations.length > 0)
478
+ result.relations = relations;
479
+ return result;
480
+ }
481
+ function buildTree(ast, ctx) {
482
+ const nodes = ast.body.map(() => ({}));
483
+ const explicit = new Map;
484
+ ast.body.forEach((line, index) => {
485
+ const node = nodes[index];
486
+ const pointer = `/nodes/${index}`;
487
+ mark(ctx, pointer, line.range);
488
+ applyAttrs(ctx, line.attrs, TREE_NODE, node, pointer);
489
+ node.label = line.label.value;
490
+ mark(ctx, `${pointer}/label`, line.label.range);
491
+ if (typeof node.id !== "string")
492
+ return;
493
+ const first = explicit.get(node.id);
494
+ if (first === undefined) {
495
+ explicit.set(node.id, index);
496
+ } else {
497
+ 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)}`);
498
+ }
499
+ });
500
+ const used = new Set(explicit.keys());
501
+ ast.body.forEach((line, index) => {
502
+ const node = nodes[index];
503
+ const pointer = `/nodes/${index}`;
504
+ if (node.id === undefined) {
505
+ const base = slug(line.label.value);
506
+ let candidate = base;
507
+ for (let suffix = 2;used.has(candidate); suffix++)
508
+ candidate = `${base}-${suffix}`;
509
+ used.add(candidate);
510
+ node.id = candidate;
511
+ mark(ctx, `${pointer}/id`, line.label.range);
512
+ }
513
+ if (line.parent >= 0) {
514
+ node.parent = nodes[line.parent].id;
515
+ mark(ctx, `${pointer}/parent`, line.label.range);
516
+ }
517
+ });
518
+ return { nodes };
519
+ }
520
+ function build(ast, ctx) {
521
+ const result = { version: 1, kind: ast.kind };
522
+ const { header } = ast;
523
+ mark(ctx, "", header.range);
524
+ mark(ctx, "/kind", header.kindRange);
525
+ if (header.title) {
526
+ result.title = header.title.value;
527
+ mark(ctx, "/title", header.title.range);
528
+ }
529
+ const attrs = header.attrs.filter((attr) => {
530
+ if (attr.key !== "version")
531
+ return true;
532
+ ctx.sink.report("E_ATTR", attr.keyRange, "version is implied (1) in the text syntax");
533
+ return false;
534
+ });
535
+ applyAttrs(ctx, attrs, HEADERS[ast.kind], result, "");
536
+ switch (ast.kind) {
537
+ case "graph":
538
+ return Object.assign(result, buildGraph(ast, ctx));
539
+ case "sequence":
540
+ return Object.assign(result, buildSequence(ast, ctx));
541
+ case "state":
542
+ return Object.assign(result, buildState(ast, ctx));
543
+ case "er":
544
+ return Object.assign(result, buildEr(ast, ctx));
545
+ case "tree":
546
+ return Object.assign(result, buildTree(ast, ctx));
547
+ }
548
+ }
549
+ // src/text/canonical.ts
550
+ function childrenOf(items) {
551
+ const children = new Map;
552
+ for (const item of items) {
553
+ const list = children.get(item.parent);
554
+ if (list)
555
+ list.push(item);
556
+ else
557
+ children.set(item.parent, [item]);
558
+ }
559
+ return children;
560
+ }
561
+ function walk(items, enter, exit) {
562
+ const children = childrenOf(items);
563
+ const stack = [];
564
+ const push = (parent, depth) => {
565
+ const list = children.get(parent);
566
+ if (!list)
567
+ return;
568
+ for (let index = list.length - 1;index >= 0; index--) {
569
+ stack.push({ item: list[index], depth, exiting: false });
570
+ }
571
+ };
572
+ push(undefined, 0);
573
+ while (stack.length > 0) {
574
+ const frame = stack.pop();
575
+ const count = children.get(frame.item.id)?.length ?? 0;
576
+ if (frame.exiting) {
577
+ exit?.(frame.item, frame.depth, count);
578
+ continue;
579
+ }
580
+ enter(frame.item, frame.depth, count);
581
+ stack.push({ ...frame, exiting: true });
582
+ push(frame.item.id, frame.depth + 1);
583
+ }
584
+ }
585
+ function preorder(items) {
586
+ const ordered = [];
587
+ walk(items, (item) => {
588
+ ordered.push(item);
589
+ });
590
+ return ordered;
591
+ }
592
+ function groupNodes(nodes) {
593
+ const byGroup = new Map;
594
+ for (const node of nodes) {
595
+ const list = byGroup.get(node.group);
596
+ if (list)
597
+ list.push(node);
598
+ else
599
+ byGroup.set(node.group, [node]);
600
+ }
601
+ return byGroup;
602
+ }
603
+ function orderedNodes(nodes, groups) {
604
+ const byGroup = groupNodes(nodes);
605
+ const ordered = [...byGroup.get(undefined) ?? []];
606
+ for (const group of preorder(groups))
607
+ ordered.push(...byGroup.get(group.id) ?? []);
608
+ return ordered;
609
+ }
610
+ function isRecord(value) {
611
+ return typeof value === "object" && value !== null && !Array.isArray(value);
612
+ }
613
+ function clean(value) {
614
+ if (Array.isArray(value)) {
615
+ for (const item of value)
616
+ clean(item);
617
+ return;
618
+ }
619
+ if (!isRecord(value))
620
+ return;
621
+ for (const [key, child] of Object.entries(value)) {
622
+ if (key === "meta" && isRecord(child)) {
623
+ if (isRecord(child.data) && Object.keys(child.data).length === 0)
624
+ delete child.data;
625
+ if (Object.keys(child).length === 0)
626
+ delete value[key];
627
+ } else {
628
+ clean(child);
629
+ }
630
+ }
631
+ }
632
+ function dropEmpty(target, key) {
633
+ if (Array.isArray(target[key]) && target[key].length === 0)
634
+ delete target[key];
635
+ }
636
+ function canonicalize2(document) {
637
+ const copy = structuredClone(document);
638
+ delete copy.$schema;
639
+ clean(copy);
640
+ switch (copy.kind) {
641
+ case "graph":
642
+ copy.nodes = orderedNodes(copy.nodes, copy.groups ?? []);
643
+ if (copy.groups)
644
+ copy.groups = preorder(copy.groups);
645
+ for (const edge of copy.edges ?? [])
646
+ edge.directed ??= true;
647
+ dropEmpty(copy, "edges");
648
+ dropEmpty(copy, "groups");
649
+ break;
650
+ case "sequence":
651
+ for (const message of copy.messages)
652
+ message.style ??= "sync";
653
+ break;
654
+ case "state":
655
+ copy.states = preorder(copy.states);
656
+ dropEmpty(copy, "transitions");
657
+ break;
658
+ case "er":
659
+ for (const entity of copy.entities) {
660
+ for (const attribute of entity.attributes ?? []) {
661
+ if (attribute.nullable === false)
662
+ delete attribute.nullable;
663
+ dropEmpty(attribute, "keys");
664
+ }
665
+ }
666
+ for (const relation of copy.relations ?? [])
667
+ relation.identifying ??= true;
668
+ dropEmpty(copy, "relations");
669
+ break;
670
+ case "tree":
671
+ copy.nodes = preorder(copy.nodes);
672
+ break;
673
+ }
674
+ return copy;
675
+ }
676
+ // src/text/highlight.ts
677
+ var SEMANTIC_TOKEN_TYPES2 = [
678
+ "namespace",
679
+ "type",
680
+ "variable",
681
+ "property",
682
+ "enumMember",
683
+ "keyword",
684
+ "comment",
685
+ "string",
686
+ "number",
687
+ "operator"
688
+ ];
689
+ var SEMANTIC_TOKEN_MODIFIERS2 = ["declaration", "defaultLibrary"];
690
+ var ENUM_KEYS = new Set(["shape", "pseudo", "confidence", "direction", "layout"]);
691
+ var SYMBOL_OPERATORS = new Set(["ARROW", "LINE", "ASYNC", "REPLY", "DOTS"]);
692
+ function isPunct(token, text) {
693
+ return token !== undefined && token.kind === "PUNCT" && token.text === text;
694
+ }
695
+ function isWord(token, word) {
696
+ return token !== undefined && token.kind === "IDENT" && token.text === word;
697
+ }
698
+ function isId(token) {
699
+ return token !== undefined && (token.kind === "IDENT" || token.kind === "QUOTED_ID");
700
+ }
701
+ function isOperator(token) {
702
+ return token !== undefined && (SYMBOL_OPERATORS.has(token.kind) || token.kind === "IDENT" && OPERATOR_WORDS.has(token.text));
703
+ }
704
+ function isCard(token) {
705
+ return token !== undefined && (token.kind === "NUMBER" || token.kind === "CARD");
706
+ }
707
+ function offsets(source) {
708
+ const bom = source.charCodeAt(0) === 65279;
709
+ if (!bom && !source.includes(`\r
710
+ `))
711
+ return;
712
+ const map = [];
713
+ for (let index = bom ? 1 : 0;index < source.length; index++) {
714
+ if (source[index] === "\r" && source[index + 1] === `
715
+ `)
716
+ continue;
717
+ map.push(index);
718
+ }
719
+ map.push(source.length);
720
+ return map;
721
+ }
722
+
723
+ class Cursor {
724
+ tokens;
725
+ index = 0;
726
+ constructor(tokens) {
727
+ this.tokens = tokens;
728
+ }
729
+ peek(offset = 0) {
730
+ return this.tokens[this.index + offset];
731
+ }
732
+ take() {
733
+ return this.tokens[this.index++];
734
+ }
735
+ get last() {
736
+ return this.index === this.tokens.length - 1;
737
+ }
738
+ get done() {
739
+ return this.index >= this.tokens.length;
740
+ }
741
+ }
742
+
743
+ class Highlighter {
744
+ source;
745
+ text;
746
+ map;
747
+ lines;
748
+ lexer;
749
+ out = [];
750
+ eof = false;
751
+ blocks = [];
752
+ constructor(source) {
753
+ this.source = source;
754
+ this.text = normalize(source);
755
+ this.map = offsets(source);
756
+ this.lines = new LineMap(this.text);
757
+ const sink = new Sink(this.lines);
758
+ sink.muted = 1;
759
+ this.lexer = new Lexer(this.text, sink);
760
+ }
761
+ emit(start, end, type, modifiers) {
762
+ if (end <= start)
763
+ return;
764
+ const position = this.lines.position(start);
765
+ const token = {
766
+ start: this.map ? this.map[start] : start,
767
+ end: this.map ? this.map[end - 1] + 1 : end,
768
+ line: position.line,
769
+ column: position.column,
770
+ type
771
+ };
772
+ if (modifiers !== undefined)
773
+ token.modifiers = modifiers;
774
+ this.out.push(token);
775
+ }
776
+ mark(token, type, modifiers) {
777
+ this.emit(token.start, token.end, type, modifiers);
778
+ }
779
+ comments(from, to) {
780
+ const gap = this.text.slice(from, Math.max(from, to));
781
+ for (const match of gap.matchAll(/#[^\n]*/g)) {
782
+ this.emit(from + match.index, from + match.index + match[0].length, "comment");
783
+ }
784
+ }
785
+ line() {
786
+ const tokens = [];
787
+ for (;; ) {
788
+ const from = this.lexer.pos;
789
+ const token = this.lexer.next();
790
+ if (token.kind === "ERROR" && token.start < from) {
791
+ this.comments(from, this.text.length);
792
+ this.eof = true;
793
+ return tokens;
794
+ }
795
+ this.comments(from, token.start);
796
+ if (token.kind === "EOF") {
797
+ this.eof = true;
798
+ return tokens;
799
+ }
800
+ if (token.kind === "NEWLINE")
801
+ return tokens;
802
+ tokens.push(token);
803
+ }
804
+ }
805
+ quotedError(token) {
806
+ if (token.kind === "ERROR" && token.text.startsWith('"'))
807
+ this.mark(token, "string");
808
+ }
809
+ label(cursor) {
810
+ const token = cursor.peek();
811
+ if (token === undefined)
812
+ return;
813
+ if (token.kind === "STRING") {
814
+ cursor.take();
815
+ this.mark(token, "string");
816
+ } else if (token.kind === "ERROR" && token.text.startsWith('"')) {
817
+ cursor.take();
818
+ this.quotedError(token);
819
+ }
820
+ }
821
+ attrs(cursor) {
822
+ if (!isPunct(cursor.peek(), "["))
823
+ return;
824
+ cursor.take();
825
+ let depth = 1;
826
+ let key = "";
827
+ while (!cursor.done) {
828
+ const token = cursor.take();
829
+ if (token.kind === "PUNCT") {
830
+ if (token.text === "[")
831
+ depth++;
832
+ else if (token.text === "]" && --depth === 0)
833
+ return;
834
+ else if (token.text === "=")
835
+ this.mark(token, "operator");
836
+ continue;
837
+ }
838
+ if ((token.kind === "IDENT" || token.kind === "QUOTED_ID") && isPunct(cursor.peek(), "=")) {
839
+ key = token.text;
840
+ this.mark(token, "property");
841
+ } else if (token.kind === "STRING") {
842
+ this.mark(token, "string");
843
+ } else if (token.kind === "NUMBER") {
844
+ this.mark(token, "number");
845
+ } else if (token.kind === "IDENT") {
846
+ if (ENUM_KEYS.has(key))
847
+ this.mark(token, "enumMember");
848
+ else if (token.text === "true" || token.text === "false")
849
+ this.mark(token, "keyword");
850
+ else
851
+ this.mark(token, "string");
852
+ } else {
853
+ this.quotedError(token);
854
+ }
855
+ }
856
+ }
857
+ rest(cursor) {
858
+ while (!cursor.done) {
859
+ const token = cursor.peek();
860
+ if (isPunct(token, "[")) {
861
+ this.attrs(cursor);
862
+ continue;
863
+ }
864
+ cursor.take();
865
+ if (token.kind === "STRING")
866
+ this.mark(token, "string");
867
+ else if (token.kind === "NUMBER" || token.kind === "CARD")
868
+ this.mark(token, "number");
869
+ else if (isOperator(token) || isPunct(token, "*"))
870
+ this.mark(token, "operator");
871
+ else if (isId(token))
872
+ this.mark(token, "variable");
873
+ else
874
+ this.quotedError(token);
875
+ }
876
+ }
877
+ opener(cursor, block) {
878
+ const token = cursor.peek();
879
+ if (isPunct(token, "{")) {
880
+ cursor.take();
881
+ this.blocks.push(block);
882
+ } else if (isWord(token, "do") && cursor.last) {
883
+ this.mark(cursor.take(), "keyword");
884
+ this.blocks.push(block);
885
+ }
886
+ }
887
+ card(cursor) {
888
+ if (isCard(cursor.peek()))
889
+ this.mark(cursor.take(), "number");
890
+ }
891
+ header(tokens) {
892
+ const cursor = new Cursor(tokens);
893
+ const kind = cursor.take();
894
+ this.mark(kind, "keyword", ["defaultLibrary"]);
895
+ this.label(cursor);
896
+ this.attrs(cursor);
897
+ this.rest(cursor);
898
+ return kind.text;
899
+ }
900
+ attributeLine(cursor) {
901
+ const name = cursor.peek();
902
+ if (isId(name)) {
903
+ cursor.take();
904
+ this.mark(name, "variable", ["declaration"]);
905
+ }
906
+ const type = cursor.peek();
907
+ if (type !== undefined && type.kind === "STRING") {
908
+ cursor.take();
909
+ this.mark(type, "string");
910
+ } else if (type !== undefined && type.kind === "IDENT" && !FLAGS.has(type.text)) {
911
+ cursor.take();
912
+ this.mark(type, "type");
913
+ if (isPunct(cursor.peek(), "(")) {
914
+ cursor.take();
915
+ while (!cursor.done && !isPunct(cursor.peek(), ")") && !isPunct(cursor.peek(), "[")) {
916
+ const arg = cursor.take();
917
+ if (arg.kind === "NUMBER")
918
+ this.mark(arg, "number");
919
+ else if (arg.kind === "IDENT")
920
+ this.mark(arg, "type");
921
+ }
922
+ if (isPunct(cursor.peek(), ")"))
923
+ cursor.take();
924
+ }
925
+ if (isPunct(cursor.peek(), "[") && isPunct(cursor.peek(1), "]")) {
926
+ cursor.take();
927
+ cursor.take();
928
+ }
929
+ }
930
+ for (;; ) {
931
+ const flag = cursor.peek();
932
+ if (flag === undefined || flag.kind !== "IDENT" || !FLAGS.has(flag.text))
933
+ break;
934
+ cursor.take();
935
+ this.mark(flag, "keyword");
936
+ }
937
+ this.attrs(cursor);
938
+ this.rest(cursor);
939
+ }
940
+ statement(kind, tokens) {
941
+ const cursor = new Cursor(tokens);
942
+ const first = cursor.peek();
943
+ if (first === undefined)
944
+ return;
945
+ if (this.blocks.length > 0 && isWord(first, "end") && tokens.length === 1) {
946
+ cursor.take();
947
+ this.mark(first, "keyword");
948
+ this.blocks.pop();
949
+ return;
950
+ }
951
+ if (isPunct(first, "}")) {
952
+ this.blocks.pop();
953
+ cursor.take();
954
+ this.rest(cursor);
955
+ return;
956
+ }
957
+ if (this.blocks[this.blocks.length - 1] === "entity") {
958
+ this.attributeLine(cursor);
959
+ return;
960
+ }
961
+ if (kind === "graph" && isWord(first, "group")) {
962
+ cursor.take();
963
+ this.mark(first, "keyword");
964
+ const id = cursor.peek();
965
+ if (isId(id)) {
966
+ cursor.take();
967
+ this.mark(id, "namespace", ["declaration"]);
968
+ }
969
+ this.label(cursor);
970
+ this.attrs(cursor);
971
+ this.opener(cursor, "other");
972
+ this.rest(cursor);
973
+ return;
974
+ }
975
+ if (kind === "state" && (isPunct(first, "*") || isWord(first, "initial") && isOperator(cursor.peek(1)))) {
976
+ cursor.take();
977
+ this.mark(first, "operator");
978
+ } else if (isId(first)) {
979
+ cursor.take();
980
+ const next = cursor.peek();
981
+ const relation = isOperator(next) || kind === "er" && isCard(next);
982
+ if (!relation) {
983
+ this.mark(first, "variable", ["declaration"]);
984
+ this.label(cursor);
985
+ this.attrs(cursor);
986
+ if (kind === "state")
987
+ this.opener(cursor, "other");
988
+ else if (kind === "er")
989
+ this.opener(cursor, "entity");
990
+ this.rest(cursor);
991
+ return;
992
+ }
993
+ this.mark(first, "variable");
994
+ } else {
995
+ this.rest(cursor);
996
+ return;
997
+ }
998
+ for (;; ) {
999
+ if (kind === "er")
1000
+ this.card(cursor);
1001
+ const operator = cursor.peek();
1002
+ if (!isOperator(operator))
1003
+ break;
1004
+ cursor.take();
1005
+ this.mark(operator, "operator");
1006
+ if (kind === "er")
1007
+ this.card(cursor);
1008
+ const target = cursor.peek();
1009
+ if (kind === "state" && (isPunct(target, "*") || isWord(target, "final"))) {
1010
+ cursor.take();
1011
+ this.mark(target, "operator");
1012
+ } else if (isId(target)) {
1013
+ cursor.take();
1014
+ this.mark(target, "variable");
1015
+ } else {
1016
+ break;
1017
+ }
1018
+ }
1019
+ this.label(cursor);
1020
+ this.attrs(cursor);
1021
+ this.rest(cursor);
1022
+ }
1023
+ tree() {
1024
+ const text = this.text;
1025
+ let pos = this.lexer.pos;
1026
+ while (pos < text.length) {
1027
+ let end = text.indexOf(`
1028
+ `, pos);
1029
+ if (end < 0)
1030
+ end = text.length;
1031
+ let start = pos;
1032
+ while (start < end && (text[start] === " " || text[start] === "\t"))
1033
+ start++;
1034
+ if (start >= end) {
1035
+ pos = end + 1;
1036
+ continue;
1037
+ }
1038
+ if (text[start] === "#") {
1039
+ this.emit(start, end, "comment");
1040
+ pos = end + 1;
1041
+ continue;
1042
+ }
1043
+ let rest = start;
1044
+ if (text[start] === '"') {
1045
+ this.lexer.seek(start);
1046
+ } else {
1047
+ while (rest < end && text[rest] !== "[" && text[rest] !== "#")
1048
+ rest++;
1049
+ const bare = text.slice(start, rest).trimEnd();
1050
+ this.emit(start, start + bare.length, "string");
1051
+ this.lexer.seek(rest);
1052
+ }
1053
+ const cursor = new Cursor(this.line());
1054
+ if (text[start] === '"')
1055
+ this.label(cursor);
1056
+ this.attrs(cursor);
1057
+ this.rest(cursor);
1058
+ pos = Math.max(this.lexer.pos, end + 1);
1059
+ if (this.eof)
1060
+ break;
1061
+ }
1062
+ }
1063
+ run() {
1064
+ let tokens = this.line();
1065
+ while (tokens.length === 0) {
1066
+ if (this.eof)
1067
+ return;
1068
+ tokens = this.line();
1069
+ }
1070
+ const first = tokens[0];
1071
+ if (!(first.kind === "IDENT" && KINDS.includes(first.text)))
1072
+ return;
1073
+ const kind = this.header(tokens);
1074
+ if (this.eof)
1075
+ return;
1076
+ if (kind === "tree") {
1077
+ this.tree();
1078
+ return;
1079
+ }
1080
+ while (!this.eof)
1081
+ this.statement(kind, this.line());
1082
+ }
1083
+ }
1084
+ function highlight2(source) {
1085
+ const highlighter = new Highlighter(source);
1086
+ try {
1087
+ highlighter.run();
1088
+ } catch {}
1089
+ const sorted = highlighter.out.sort((a, b) => a.start - b.start || a.end - b.end);
1090
+ const result = [];
1091
+ let end = 0;
1092
+ for (const token of sorted) {
1093
+ if (token.start < end)
1094
+ continue;
1095
+ result.push(token);
1096
+ end = token.end;
1097
+ }
1098
+ return result;
1099
+ }
1100
+ // src/text/print.ts
1101
+ var STYLES = {
1102
+ symbols: {
1103
+ ops: { "->": "->", "--": "--", "->>": "->>", "-->": "-->", "..": ".." },
1104
+ open: "{",
1105
+ close: "}"
1106
+ },
1107
+ words: {
1108
+ ops: { "->": "to", "--": "with", "->>": "async", "-->": "reply", "..": "via" },
1109
+ open: "do",
1110
+ close: "end"
1111
+ }
1112
+ };
1113
+ var IDENT_SOURCE = String.raw`[\p{L}_][\p{L}\p{N}_]*(?:[./-][\p{L}\p{N}_]+)*`;
1114
+ var IDENT = new RegExp(`^${IDENT_SOURCE}$`, "u");
1115
+ var NUMBER_SOURCE = String.raw`-?[0-9]+(?:\.[0-9]+)?`;
1116
+ var TYPE_ARG = `(?:${NUMBER_SOURCE}|${IDENT_SOURCE})`;
1117
+ var TYPE = new RegExp(String.raw`^${IDENT_SOURCE}(?:\(${TYPE_ARG}(?:,${TYPE_ARG})*\))?(?:\[\])?$`, "u");
1118
+ var ESCAPED = /["\\\u0000-\u001f\u007f-\u009f]/g;
1119
+ var ESCAPES = {
1120
+ '"': "\\\"",
1121
+ "\\": "\\\\",
1122
+ "\n": "\\n",
1123
+ "\t": "\\t"
1124
+ };
1125
+ var WORDS = new Set(["to", "with", "async", "reply", "via", "initial", "final", "do", "end"]);
1126
+ var GRAPH_RESERVED = new Set(["group"]);
1127
+ var ATTRIBUTE_RESERVED = new Set(["pk", "fk", "uk", "null"]);
1128
+ var FLAGS2 = new Set(["pk", "fk", "uk", "null"]);
1129
+ var CARDINALITY_TEXT = {
1130
+ one: "1",
1131
+ "zero-or-one": "0..1",
1132
+ "one-or-more": "1..*",
1133
+ "zero-or-more": "0..*"
1134
+ };
1135
+ function numberText(value) {
1136
+ return Object.is(value, -0) ? "-0" : String(value);
1137
+ }
1138
+ function quote(value) {
1139
+ return `"${value.replace(ESCAPED, (char) => ESCAPES[char] ?? `\\u{${char.charCodeAt(0).toString(16)}}`)}"`;
1140
+ }
1141
+ function backticked(value) {
1142
+ return `\`${value.replace(/[\\`]/g, "\\$&")}\``;
1143
+ }
1144
+ function ident(value, reserved) {
1145
+ return IDENT.test(value) && !WORDS.has(value) && !reserved?.has(value) ? value : backticked(value);
1146
+ }
1147
+ function pad(depth) {
1148
+ return " ".repeat(depth);
1149
+ }
1150
+ function labelText(label) {
1151
+ return label === undefined ? "" : ` ${quote(label)}`;
1152
+ }
1153
+ function attrText(pairs) {
1154
+ return pairs.length === 0 ? "" : ` [${pairs.map(([key, value]) => `${key}=${value}`).join(", ")}]`;
1155
+ }
1156
+ function metaPairs(meta) {
1157
+ const pairs = [];
1158
+ if (!meta)
1159
+ return pairs;
1160
+ const { provenance } = meta;
1161
+ if (provenance) {
1162
+ pairs.push(["source", quote(provenance.source)]);
1163
+ if (provenance.confidence !== undefined)
1164
+ pairs.push(["confidence", provenance.confidence]);
1165
+ if (provenance.tool !== undefined)
1166
+ pairs.push(["tool", quote(provenance.tool)]);
1167
+ }
1168
+ if (meta.coverage !== undefined)
1169
+ pairs.push(["coverage", numberText(meta.coverage)]);
1170
+ if (meta.freshness !== undefined)
1171
+ pairs.push(["freshness", quote(meta.freshness)]);
1172
+ for (const [name, value] of Object.entries(meta.data ?? {})) {
1173
+ const key = `data.${name}`;
1174
+ pairs.push([
1175
+ IDENT.test(key) ? key : backticked(key),
1176
+ typeof value === "string" ? quote(value) : typeof value === "number" ? numberText(value) : String(value)
1177
+ ]);
1178
+ }
1179
+ return pairs;
1180
+ }
1181
+ function fieldPairs(item, withId) {
1182
+ const pairs = [];
1183
+ if (withId && item.id !== undefined)
1184
+ pairs.push(["id", quote(item.id)]);
1185
+ if (item.type !== undefined)
1186
+ pairs.push(["type", quote(item.type)]);
1187
+ if (item.shape !== undefined)
1188
+ pairs.push(["shape", item.shape]);
1189
+ if (item.pseudo !== undefined)
1190
+ pairs.push(["pseudo", item.pseudo]);
1191
+ if (item.actions !== undefined) {
1192
+ pairs.push(["actions", `[${item.actions.map(quote).join(", ")}]`]);
1193
+ }
1194
+ if (item.guard !== undefined)
1195
+ pairs.push(["guard", quote(item.guard)]);
1196
+ if (item.action !== undefined)
1197
+ pairs.push(["action", quote(item.action)]);
1198
+ if (item.link !== undefined)
1199
+ pairs.push(["link", quote(item.link)]);
1200
+ if (item.description !== undefined)
1201
+ pairs.push(["description", quote(item.description)]);
1202
+ if (item.position !== undefined) {
1203
+ pairs.push(["x", numberText(item.position.x)], ["y", numberText(item.position.y)]);
1204
+ }
1205
+ pairs.push(...metaPairs(item.meta));
1206
+ return pairs;
1207
+ }
1208
+ function declaration(id, item, depth, reserved, suffix = "") {
1209
+ return `${pad(depth)}${ident(id, reserved)}${labelText(item.label)}${attrText(fieldPairs(item, false))}${suffix}`;
1210
+ }
1211
+ function assemble(header, sections) {
1212
+ const lines = [header];
1213
+ for (const section of sections) {
1214
+ if (section.length > 0)
1215
+ lines.push("", ...section);
1216
+ }
1217
+ return `${lines.join(`
1218
+ `)}
1219
+ `;
1220
+ }
1221
+ function headerLine(doc) {
1222
+ const pairs = [];
1223
+ if ("direction" in doc && doc.direction !== undefined) {
1224
+ pairs.push(["direction", doc.direction]);
1225
+ }
1226
+ if (doc.kind === "tree" && doc.layout !== undefined) {
1227
+ pairs.push(["layout", doc.layout]);
1228
+ }
1229
+ pairs.push(...metaPairs(doc.meta));
1230
+ return `${doc.kind}${labelText(doc.title)}${attrText(pairs)}`;
1231
+ }
1232
+ function connection(from, operator, to, item, middle) {
1233
+ const left = middle?.[0] ? ` ${middle[0]}` : "";
1234
+ const right = middle?.[1] ? ` ${middle[1]}` : "";
1235
+ return `${ident(from)}${left} ${operator}${right} ${ident(to)}${labelText(item.label)}${attrText(fieldPairs(item, true))}`;
1236
+ }
1237
+ function printGraph(doc, style) {
1238
+ const byGroup = groupNodes(doc.nodes);
1239
+ const declarations = [];
1240
+ const nodeLines = (group, depth) => {
1241
+ for (const node of byGroup.get(group) ?? []) {
1242
+ declarations.push(declaration(node.id, node, depth, GRAPH_RESERVED));
1243
+ }
1244
+ };
1245
+ nodeLines(undefined, 0);
1246
+ walk(doc.groups ?? [], (group, depth) => {
1247
+ declarations.push(`${pad(depth)}group ${ident(group.id, GRAPH_RESERVED)}${labelText(group.label)}${attrText(metaPairs(group.meta))} ${style.open}`);
1248
+ nodeLines(group.id, depth + 1);
1249
+ }, (_group, depth) => {
1250
+ declarations.push(`${pad(depth)}${style.close}`);
1251
+ });
1252
+ const edges = (doc.edges ?? []).map((edge) => connection(edge.from, style.ops[edge.directed === false ? "--" : "->"], edge.to, edge));
1253
+ return [declarations, edges];
1254
+ }
1255
+ function printSequence(doc, style) {
1256
+ const operators = { sync: "->", async: "->>", reply: "-->" };
1257
+ return [
1258
+ doc.participants.map((participant) => declaration(participant.id, participant, 0)),
1259
+ doc.messages.map((message) => connection(message.from, style.ops[operators[message.style ?? "sync"]], message.to, message))
1260
+ ];
1261
+ }
1262
+ function printState(doc, style) {
1263
+ const states = [];
1264
+ walk(doc.states, (state, depth, children) => {
1265
+ states.push(declaration(state.id, state, depth, undefined, children > 0 ? ` ${style.open}` : ""));
1266
+ }, (_state, depth, children) => {
1267
+ if (children > 0)
1268
+ states.push(`${pad(depth)}${style.close}`);
1269
+ });
1270
+ const transitions = (doc.transitions ?? []).map((transition) => connection(transition.from, style.ops["->"], transition.to, {
1271
+ ...transition,
1272
+ label: transition.event
1273
+ }));
1274
+ return [states, transitions];
1275
+ }
1276
+ function typeText(type) {
1277
+ const first = /^[^(\[]*/.exec(type)[0];
1278
+ return TYPE.test(type) && !FLAGS2.has(first) ? type : quote(type);
1279
+ }
1280
+ function entityLines(entity, style) {
1281
+ const attributes = entity.attributes;
1282
+ const lines = [
1283
+ declaration(entity.id, entity, 0, undefined, attributes === undefined ? "" : ` ${style.open}`)
1284
+ ];
1285
+ if (attributes === undefined)
1286
+ return lines;
1287
+ for (const attribute of attributes) {
1288
+ const parts = [ident(attribute.name, ATTRIBUTE_RESERVED)];
1289
+ if (attribute.type !== undefined)
1290
+ parts.push(typeText(attribute.type));
1291
+ parts.push(...attribute.keys ?? []);
1292
+ if (attribute.nullable === true)
1293
+ parts.push("null");
1294
+ const note = attribute.note === undefined ? [] : [["note", quote(attribute.note)]];
1295
+ lines.push(`${pad(1)}${parts.join(" ")}${attrText(note)}`);
1296
+ }
1297
+ lines.push(style.close);
1298
+ return lines;
1299
+ }
1300
+ function printEr(doc, style) {
1301
+ const relations = (doc.relations ?? []).map((relation) => connection(relation.from, style.ops[relation.identifying === false ? ".." : "--"], relation.to, relation, [
1302
+ relation.fromCardinality ? CARDINALITY_TEXT[relation.fromCardinality] : "",
1303
+ relation.toCardinality ? CARDINALITY_TEXT[relation.toCardinality] : ""
1304
+ ]));
1305
+ return [doc.entities.flatMap((entity) => entityLines(entity, style)), relations];
1306
+ }
1307
+ function bareLabel(label) {
1308
+ return label !== "" && label === label.trim() && !/["#\[\n\r]/.test(label);
1309
+ }
1310
+ function explicitIds(nodes) {
1311
+ let explicit = new Set;
1312
+ for (;; ) {
1313
+ const used = new Set([...explicit].map((index) => nodes[index].id));
1314
+ const next = new Set(explicit);
1315
+ nodes.forEach((node, index) => {
1316
+ if (explicit.has(index))
1317
+ return;
1318
+ const base = slug(node.label);
1319
+ let candidate = base;
1320
+ for (let suffix = 2;used.has(candidate); suffix++)
1321
+ candidate = `${base}-${suffix}`;
1322
+ used.add(candidate);
1323
+ if (candidate !== node.id)
1324
+ next.add(index);
1325
+ });
1326
+ if (next.size === explicit.size)
1327
+ return explicit;
1328
+ explicit = next;
1329
+ }
1330
+ }
1331
+ function printTree(doc) {
1332
+ const nodes = preorder(doc.nodes);
1333
+ const explicit = explicitIds(nodes);
1334
+ const index = new Map(nodes.map((node, position) => [node, position]));
1335
+ const lines = [];
1336
+ walk(doc.nodes, (node, depth) => {
1337
+ const item = { ...node, id: explicit.has(index.get(node)) ? node.id : undefined };
1338
+ const text = bareLabel(node.label) ? node.label : quote(node.label);
1339
+ lines.push(`${pad(depth)}${text}${attrText(fieldPairs(item, true))}`);
1340
+ });
1341
+ return [lines];
1342
+ }
1343
+ function print2(doc, options = {}) {
1344
+ const style = STYLES[options.style ?? "symbols"];
1345
+ const header = headerLine(doc);
1346
+ switch (doc.kind) {
1347
+ case "graph":
1348
+ return assemble(header, printGraph(doc, style));
1349
+ case "sequence":
1350
+ return assemble(header, printSequence(doc, style));
1351
+ case "state":
1352
+ return assemble(header, printState(doc, style));
1353
+ case "er":
1354
+ return assemble(header, printEr(doc, style));
1355
+ case "tree":
1356
+ return assemble(header, printTree(doc));
1357
+ }
1358
+ }
1359
+
1360
+ // src/text/index.ts
1361
+ function rangeOf(marks, path) {
1362
+ let pointer = path;
1363
+ for (;; ) {
1364
+ const range = marks.get(pointer);
1365
+ if (range)
1366
+ return range;
1367
+ if (pointer === "")
1368
+ return { start: 0, end: 0 };
1369
+ pointer = pointer.slice(0, pointer.lastIndexOf("/"));
1370
+ }
1371
+ }
1372
+ function parse2(source) {
1373
+ const text = normalize(source);
1374
+ const sink = new Sink(new LineMap(text));
1375
+ try {
1376
+ const ast = parseSyntax(text, sink);
1377
+ if (ast && sink.errors.length === 0) {
1378
+ const marks = new Map;
1379
+ const document = build(ast, { sink, marks });
1380
+ if (sink.errors.length === 0) {
1381
+ const result = validate2(document);
1382
+ if (result.ok)
1383
+ return { ok: true, document: result.document };
1384
+ for (const error of result.errors) {
1385
+ sink.report("E_VALIDATE", rangeOf(marks, error.path), error.message);
1386
+ }
1387
+ }
1388
+ }
1389
+ } catch (error) {
1390
+ if (error !== STOP)
1391
+ throw error;
1392
+ }
1393
+ return { ok: false, errors: sink.sorted() };
1394
+ }
1395
+ function sniff2(source) {
1396
+ const text = source.replace(/^/, "");
1397
+ for (const line of text.split(/\r\n|\n|\r/)) {
1398
+ const trimmed = line.trim();
1399
+ if (trimmed === "" || trimmed.startsWith("#"))
1400
+ continue;
1401
+ return trimmed.startsWith("{") ? "json" : "text";
1402
+ }
1403
+ return "text";
1404
+ }
1405
+ function loadSource2(source) {
1406
+ const format = sniff2(source);
1407
+ if (format === "text") {
1408
+ const result = parse2(source);
1409
+ if (result.ok)
1410
+ return { ok: true, format, document: result.document };
1411
+ return {
1412
+ ok: false,
1413
+ format,
1414
+ errors: result.errors.map((error) => ({
1415
+ message: error.message,
1416
+ line: error.line,
1417
+ column: error.column,
1418
+ code: error.code
1419
+ }))
1420
+ };
1421
+ }
1422
+ let value;
1423
+ try {
1424
+ value = JSON.parse(source.replace(/^/, ""));
1425
+ } catch (error) {
1426
+ const reason = error instanceof Error ? error.message : String(error);
1427
+ return { ok: false, format, errors: [{ message: `Invalid JSON: ${reason}` }] };
1428
+ }
1429
+ const result = validate2(value);
1430
+ if (result.ok)
1431
+ return { ok: true, format, document: result.document };
1432
+ return {
1433
+ ok: false,
1434
+ format,
1435
+ errors: result.errors.map((error) => ({ path: error.path, message: error.message }))
1436
+ };
1437
+ }
1438
+
1439
+ export { canonicalize2, SEMANTIC_TOKEN_TYPES2, SEMANTIC_TOKEN_MODIFIERS2, highlight2, print2, parse2, sniff2, loadSource2 };