@telorun/analyzer 0.67.0 → 0.69.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 (96) hide show
  1. package/dist/analysis-registry.d.ts +12 -0
  2. package/dist/analysis-registry.d.ts.map +1 -1
  3. package/dist/analysis-registry.js +26 -0
  4. package/dist/analyzer.d.ts.map +1 -1
  5. package/dist/analyzer.js +23 -0
  6. package/dist/call-graph.d.ts +80 -1
  7. package/dist/call-graph.d.ts.map +1 -1
  8. package/dist/call-graph.js +145 -12
  9. package/dist/extends-resolution.d.ts +20 -0
  10. package/dist/extends-resolution.d.ts.map +1 -1
  11. package/dist/extends-resolution.js +29 -0
  12. package/dist/import-resolution-diagnostics.d.ts.map +1 -1
  13. package/dist/import-resolution-diagnostics.js +22 -8
  14. package/dist/index.d.ts +8 -7
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +6 -6
  17. package/dist/invocation-contract.d.ts +20 -0
  18. package/dist/invocation-contract.d.ts.map +1 -1
  19. package/dist/invocation-contract.js +74 -0
  20. package/dist/loaded-types.d.ts +4 -4
  21. package/dist/loaded-types.d.ts.map +1 -1
  22. package/dist/manifest-analysis.d.ts +19 -0
  23. package/dist/manifest-analysis.d.ts.map +1 -1
  24. package/dist/manifest-analysis.js +27 -0
  25. package/dist/manifest-loader.d.ts +3 -4
  26. package/dist/manifest-loader.d.ts.map +1 -1
  27. package/dist/manifest-loader.js +4 -5
  28. package/dist/manifest-schemas.d.ts +2 -0
  29. package/dist/manifest-schemas.d.ts.map +1 -1
  30. package/dist/manifest-schemas.js +4 -0
  31. package/dist/module-graph.d.ts +500 -0
  32. package/dist/module-graph.d.ts.map +1 -0
  33. package/dist/module-graph.js +1411 -0
  34. package/dist/reconcile-module-versions.d.ts.map +1 -1
  35. package/dist/reconcile-module-versions.js +10 -11
  36. package/dist/release/release-plan.d.ts +1 -1
  37. package/dist/resolve-zone-containment.d.ts +9 -1
  38. package/dist/resolve-zone-containment.d.ts.map +1 -1
  39. package/dist/resolve-zone-containment.js +34 -6
  40. package/dist/resolve-zone-requirements.d.ts.map +1 -1
  41. package/dist/resolve-zone-requirements.js +4 -2
  42. package/dist/schema-keywords.d.ts +16 -1
  43. package/dist/schema-keywords.d.ts.map +1 -1
  44. package/dist/schema-keywords.js +20 -0
  45. package/dist/sources/default-sources.d.ts +6 -6
  46. package/dist/sources/default-sources.d.ts.map +1 -1
  47. package/dist/sources/default-sources.js +7 -8
  48. package/dist/sources/integrity.d.ts +3 -2
  49. package/dist/sources/integrity.d.ts.map +1 -1
  50. package/dist/sources/integrity.js +26 -3
  51. package/dist/sources/versioned-ref.d.ts +17 -12
  52. package/dist/sources/versioned-ref.d.ts.map +1 -1
  53. package/dist/sources/versioned-ref.js +22 -24
  54. package/dist/telo-version.d.ts +1 -1
  55. package/dist/telo-version.js +1 -1
  56. package/dist/validate-extends.d.ts.map +1 -1
  57. package/dist/validate-extends.js +42 -1
  58. package/dist/validate-sensitive-slots.d.ts +28 -0
  59. package/dist/validate-sensitive-slots.d.ts.map +1 -0
  60. package/dist/validate-sensitive-slots.js +75 -0
  61. package/dist/value-type-keyword.d.ts +1 -1
  62. package/dist/value-type-keyword.d.ts.map +1 -1
  63. package/dist/value-type-keyword.js +1 -0
  64. package/package.json +1 -1
  65. package/src/analysis-registry.ts +37 -0
  66. package/src/analyzer.ts +26 -0
  67. package/src/call-graph.ts +207 -14
  68. package/src/extends-resolution.ts +33 -0
  69. package/src/import-resolution-diagnostics.ts +24 -7
  70. package/src/index.ts +42 -5
  71. package/src/invocation-contract.ts +71 -0
  72. package/src/loaded-types.ts +4 -4
  73. package/src/manifest-analysis.ts +39 -0
  74. package/src/manifest-loader.ts +4 -5
  75. package/src/manifest-schemas.ts +4 -0
  76. package/src/module-graph.ts +2005 -0
  77. package/src/reconcile-module-versions.ts +10 -11
  78. package/src/release/release-plan.ts +1 -1
  79. package/src/resolve-zone-containment.ts +49 -9
  80. package/src/resolve-zone-requirements.ts +7 -2
  81. package/src/schema-keywords.ts +33 -1
  82. package/src/sources/default-sources.ts +7 -8
  83. package/src/sources/integrity.ts +28 -3
  84. package/src/sources/versioned-ref.ts +26 -28
  85. package/src/telo-version.ts +1 -1
  86. package/src/validate-extends.ts +51 -1
  87. package/src/validate-sensitive-slots.ts +109 -0
  88. package/src/value-type-keyword.ts +1 -0
  89. package/dist/sources/module-ref.d.ts +0 -21
  90. package/dist/sources/module-ref.d.ts.map +0 -1
  91. package/dist/sources/module-ref.js +0 -36
  92. package/dist/sources/registry-source.d.ts +0 -14
  93. package/dist/sources/registry-source.d.ts.map +0 -1
  94. package/dist/sources/registry-source.js +0 -45
  95. package/src/sources/module-ref.ts +0 -49
  96. package/src/sources/registry-source.ts +0 -52
@@ -0,0 +1,1411 @@
1
+ import { buildCelEnvironment, extractAccessChains, isRefSentinel, walkCelExpressions, } from "@telorun/templating";
2
+ import { nodeIdFor, resolveScopedName, resourceId, } from "./call-graph.js";
3
+ import { propertySchemas, resolveLocalRef } from "./manifest-navigation.js";
4
+ import { isStepSlot } from "./step-slot.js";
5
+ import { isInlineResource, resolveFieldEntries } from "./reference-field-map.js";
6
+ import { findZoneProviders } from "./resolve-zone-containment.js";
7
+ import { possibleUses, readRefSlot } from "./ref-slot.js";
8
+ /**
9
+ * Rows that are ordered entries of their array.
10
+ *
11
+ * A consumer offering reorder, removal or an index must ask — a declaration
12
+ * written at a dispatch site carries an `index` of 0 and an `array` it shares
13
+ * with its host, both of which are borrowed so it groups into the right branch,
14
+ * and neither of which means what it means on a step.
15
+ */
16
+ export function isOrderedRow(row) {
17
+ return row.kind === "step" || row.kind === "entry" || row.kind === "target";
18
+ }
19
+ /**
20
+ * A hold whose target is ambient infrastructure — the collapse candidate.
21
+ *
22
+ * Stated here rather than in the view because it is the rule the plan fixes,
23
+ * and two hosts applying it differently would disagree about which edges exist:
24
+ * a hold into a shared connection or store is fan-in that swamps a layout and
25
+ * carries no structure, while a hold BETWEEN working resources is the
26
+ * application's spine — a server holding its mounts — and demoting the second
27
+ * with the first is exactly the mistake this replaces.
28
+ */
29
+ /**
30
+ * Is anything reaching this declaration at all?
31
+ *
32
+ * "Declared, referenced by nothing, in no `targets`" — the resource a reader
33
+ * cannot otherwise tell apart from a wired one, since a manifest states no
34
+ * difference between the two. Every incoming edge counts, not only flow: a
35
+ * connection is HELD rather than called, and reading it as unwired would mark
36
+ * every provider in the module. An owned declaration is reached by its owner,
37
+ * and the root is what reaches everything else.
38
+ *
39
+ * A declaration this module did not write is NEVER unwired, however little it
40
+ * is used here. An imported library exports what it exports, and the flatten
41
+ * forwards all of it; "nothing references this" would be a true sentence about
42
+ * an unused export and a useless one, since the reader cannot act on it — the
43
+ * declaration is not theirs to remove.
44
+ */
45
+ export function isUnwired(node, graph) {
46
+ if (node.root || node.external)
47
+ return false;
48
+ if (node.ownership === "inline" || node.ownership === "scoped")
49
+ return false;
50
+ return graph.edgesTo(node.id).length === 0;
51
+ }
52
+ export function isAmbientHold(edge, graph) {
53
+ if (edge.class !== "holds" || !edge.to)
54
+ return false;
55
+ const target = graph.nodeById(edge.to);
56
+ return isAmbientCapability(target?.capability);
57
+ }
58
+ /**
59
+ * Capabilities whose resources are AMBIENT: held and read, never run, and never
60
+ * drawn as the target of a line.
61
+ *
62
+ * Exported because the view partitions on the same fact — which boxes go off
63
+ * the canvas into the drawer — and two spellings of it is how a host ends up
64
+ * collapsing a hold the other still draws an edge for.
65
+ */
66
+ export const AMBIENT_CAPABILITIES = new Set([
67
+ "Telo.Provider",
68
+ "Telo.Type",
69
+ ]);
70
+ /** Is this an ambient declaration — held and read rather than run? */
71
+ export function isAmbientCapability(capability) {
72
+ return !!capability && AMBIENT_CAPABILITIES.has(capability);
73
+ }
74
+ /** Uses that transfer control, so the site is drawn as flow. */
75
+ const FLOW_USES = new Set([
76
+ "call",
77
+ "detached",
78
+ "trigger.inbound",
79
+ "trigger.consumer",
80
+ ]);
81
+ /**
82
+ * The class a site is drawn as.
83
+ *
84
+ * A slot declaring NO use reads as flow, the same conservative direction the
85
+ * call graph takes: the cost of a false "control reaches here" is an edge drawn
86
+ * more prominently than it deserved, while the cost of a false "it never does"
87
+ * is a call the picture denies exists.
88
+ */
89
+ export function edgeClassOf(use) {
90
+ if (use.length === 0)
91
+ return "flow";
92
+ if (use.some((u) => FLOW_USES.has(u)))
93
+ return "flow";
94
+ if (use.includes("dependency"))
95
+ return "holds";
96
+ return "shape";
97
+ }
98
+ /**
99
+ * Documents that declare a TYPE or a module rather than an instance.
100
+ *
101
+ * The flattened analysis carries every imported library's definitions beside
102
+ * its instances, so without this the instance plane fills with the abstracts a
103
+ * dependency happens to declare (`Sql.Connection`, `Codec.Encoder`) — boxes for
104
+ * things that never exist at runtime, drawn among the things that do. They are
105
+ * the kind plane's, which is a separate surface. The module docs are here too:
106
+ * the entry module's is minted as the ROOT, and an imported library's is not an
107
+ * instance at all.
108
+ */
109
+ const DECLARATION_KINDS = new Set([
110
+ "Telo.Definition",
111
+ "Telo.Abstract",
112
+ "Telo.Import",
113
+ "Telo.Application",
114
+ "Telo.Library",
115
+ ]);
116
+ const moduleOf = (manifest) => manifest.metadata?.module;
117
+ /** The canonical id of a resolved kind definition — where it was declared plus
118
+ * what it is called there, which is the one spelling every module agrees on. */
119
+ const canonicalKindOf = (definition) => {
120
+ const metadata = definition?.metadata;
121
+ if (!metadata?.name)
122
+ return undefined;
123
+ return metadata.module ? `${metadata.module}.${metadata.name}` : metadata.name;
124
+ };
125
+ const originOf = (manifest) => manifest.metadata?.xTeloOrigin;
126
+ const isForwardedExport = (manifest) => manifest.metadata?.forwardedExport === true;
127
+ const isInjected = (manifest) => manifest.metadata?.["xTeloInjected"] === true;
128
+ /**
129
+ * A short, stable key over a value's shape.
130
+ *
131
+ * FNV-1a over canonical JSON: what is wanted is that the same written entry
132
+ * keeps the same identity when a sibling is inserted above it, which a hash of
133
+ * the entry's own content gives and an index cannot. Collisions are resolved by
134
+ * declaration order at the call site, so two byte-identical rows stay
135
+ * distinguishable without either one's identity depending on the other's
136
+ * position.
137
+ */
138
+ export function contentKey(value) {
139
+ const json = canonicalJson(value);
140
+ let hash = 0x811c9dc5;
141
+ for (let i = 0; i < json.length; i++) {
142
+ hash ^= json.charCodeAt(i);
143
+ hash = Math.imul(hash, 0x01000193) >>> 0;
144
+ }
145
+ return hash.toString(36);
146
+ }
147
+ function canonicalJson(value) {
148
+ if (value === null || typeof value !== "object")
149
+ return JSON.stringify(value) ?? "null";
150
+ if (Array.isArray(value))
151
+ return `[${value.map(canonicalJson).join(",")}]`;
152
+ const entries = Object.entries(value)
153
+ .filter(([, v]) => v !== undefined)
154
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
155
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
156
+ }
157
+ /** Mints ids that are unique without being positional: the name where one
158
+ * exists, a content key where none does, and a `~n` suffix only when two
159
+ * siblings are genuinely indistinguishable. */
160
+ class IdMinter {
161
+ used = new Set();
162
+ mint(base) {
163
+ if (!this.used.has(base)) {
164
+ this.used.add(base);
165
+ return base;
166
+ }
167
+ for (let n = 2;; n++) {
168
+ const candidate = `${base}~${n}`;
169
+ if (!this.used.has(candidate)) {
170
+ this.used.add(candidate);
171
+ return candidate;
172
+ }
173
+ }
174
+ }
175
+ }
176
+ /** The schema node at a field-map path, following `[]` into `items` and `{}`
177
+ * into `additionalProperties`, resolving local `$ref`s along the way. */
178
+ function schemaAt(rootSchema, slotPath) {
179
+ if (!rootSchema)
180
+ return undefined;
181
+ let current = rootSchema;
182
+ for (const segment of slotPath.split(".")) {
183
+ if (!current)
184
+ return undefined;
185
+ // A map's key step is its OWN segment (`columns.{}.type`), where an array's
186
+ // rides the field it belongs to (`mounts[].mount`). Reading only the suffix
187
+ // form walked into nothing at the first map, so every slot under one was
188
+ // left with no schema — and a slot with no schema declares no `use`, which
189
+ // classed a column's typed reference as a control transfer.
190
+ if (segment === "{}") {
191
+ current = resolveLocalRef(current.additionalProperties, rootSchema);
192
+ continue;
193
+ }
194
+ const bare = segment.replace(/(\[\]|\{\})+$/g, "");
195
+ let next = propertySchemas(current).find(([k]) => k === bare)?.[1];
196
+ for (const marker of segment.slice(bare.length).match(/\[\]|\{\}/g) ?? []) {
197
+ next = resolveLocalRef(marker === "[]"
198
+ ? next?.items
199
+ : next?.additionalProperties, rootSchema);
200
+ if (!next || typeof next !== "object")
201
+ return undefined;
202
+ }
203
+ current = resolveLocalRef(next, rootSchema);
204
+ }
205
+ return current;
206
+ }
207
+ /**
208
+ * Does this field hold the branch that DISCHARGES a raised error?
209
+ *
210
+ * Two annotations mark one, from two layers, and both are read: the shared CEL
211
+ * one (`x-telo-error-context`, which types the `error` variable inside a
212
+ * `catch:`) and the dispatch outcome vocabulary (`x-telo-outcome-list: catches`,
213
+ * which an HTTP-style router uses to render a code as a response). Neither is a
214
+ * field NAME, so a third-party composer spelling its branch differently is seen
215
+ * as long as it annotates it; recognizing only one would silently mark every
216
+ * route in the standard library as handling nothing.
217
+ */
218
+ function isErrorBranch(schema) {
219
+ return (schema?.["x-telo-error-context"] !== undefined ||
220
+ schema?.["x-telo-outcome-list"] === "catches");
221
+ }
222
+ function entryListsOf(rootSchema) {
223
+ if (!rootSchema)
224
+ return [];
225
+ const out = [];
226
+ for (const [key, propSchema] of propertySchemas(rootSchema)) {
227
+ if (propSchema?.["x-telo-topology-role"] !== "entries")
228
+ continue;
229
+ const items = resolveLocalRef(propSchema.items, rootSchema);
230
+ const matchers = [];
231
+ const handlers = [];
232
+ const errorBranches = [];
233
+ for (const [subKey, subSchema] of propertySchemas(items ?? {})) {
234
+ const role = subSchema?.["x-telo-topology-role"];
235
+ if (role === "matcher")
236
+ matchers.push(subKey);
237
+ else if (role === "handler")
238
+ handlers.push(subKey);
239
+ if (isErrorBranch(subSchema))
240
+ errorBranches.push(subKey);
241
+ }
242
+ out.push({ field: key, matchers, handlers, errorBranches });
243
+ }
244
+ return out;
245
+ }
246
+ /** A value written AT a ref slot that declares a resource rather than naming
247
+ * one — `{kind, …config}` with no `name`. */
248
+ function isInlineDeclaration(value) {
249
+ if (isRefSentinel(value) || !value || typeof value !== "object" || Array.isArray(value)) {
250
+ return false;
251
+ }
252
+ // The shape test itself is the field map's — one reader for "is this a
253
+ // declaration rather than a reference", since the extraction pass keys on the
254
+ // same answer and a second opinion here would decide differently the day the
255
+ // form gains a key.
256
+ return isInlineResource(value);
257
+ }
258
+ /** The referenced name a ref value carries, across both written forms: an
259
+ * unresolved `!ref <name>` sentinel and the `{kind, name}` object
260
+ * `resolveRefSentinels` rewrites it into. */
261
+ function refName(value) {
262
+ if (isRefSentinel(value))
263
+ return value.source;
264
+ if (!value || typeof value !== "object")
265
+ return undefined;
266
+ const name = value.name;
267
+ return typeof name === "string" ? name : undefined;
268
+ }
269
+ /**
270
+ * Fold a manifest set into the module graph.
271
+ *
272
+ * The call graph supplies what calls what — including the scoped nodes and step
273
+ * bodies it already discovers — and this pass adds what a picture needs and a
274
+ * call graph has no reason to carry: declared-but-empty ports, ownership,
275
+ * ordered rows, region membership, and the reduction of six uses to three
276
+ * classes.
277
+ */
278
+ export function buildModuleGraph(resources, callGraph, deps, options = {}) {
279
+ const nodes = [];
280
+ const edges = [];
281
+ const regions = [];
282
+ const byId = new Map();
283
+ const rowIdByPath = new Map();
284
+ /** References found inside inline declarations, resolved once every node
285
+ * exists — a declaration may name a resource declared later in the file. */
286
+ const inlineEdgeSeeds = new Map();
287
+ const add = (node) => {
288
+ nodes.push(node);
289
+ byId.set(node.id, node);
290
+ return node;
291
+ };
292
+ // --- the module root -------------------------------------------------------
293
+ // Not a resource: it owns `targets` and the module's own configuration, and
294
+ // the call graph deliberately skips it. Minting it here is what makes a boot
295
+ // target an ordinary edge rather than a fact a consumer has to fetch from
296
+ // somewhere else.
297
+ let root;
298
+ if (options.root) {
299
+ const name = options.root.metadata?.name ?? "";
300
+ const module = moduleOf(options.root);
301
+ root = add({
302
+ id: resourceId(options.root.kind, name),
303
+ kind: options.root.kind,
304
+ name,
305
+ ownership: "root",
306
+ ...(module ? { module } : {}),
307
+ ports: [],
308
+ rows: [],
309
+ // Boot targets are an ordered list the root always has, empty or not.
310
+ rowArrays: [{ field: "targets", kind: "target" }],
311
+ root: true,
312
+ });
313
+ }
314
+ // --- resource nodes --------------------------------------------------------
315
+ // Minted from the MANIFEST LIST, not from the call graph's node map.
316
+ //
317
+ // The call graph keys a resource by `(kind, name)`, which is unique within one
318
+ // module and not across a flattened set: two libraries each exporting an
319
+ // `Http.Api` named `routes` collapse onto one node there, and a picture built
320
+ // from that map draws one box for two declarations. Minting here from the
321
+ // manifests keeps both, qualified by their declaring module. What is still the
322
+ // call graph's — steps and edges — is translated through `projectedId`, and
323
+ // the collapsed twin's own edges are missing from it; its ports and rows are
324
+ // read from its manifest here, so the box is drawn and wired correctly and
325
+ // only the edges the call graph lost are absent.
326
+ // One id scheme, the call graph's — a resource name is module-scoped, so the
327
+ // module is part of the identity wherever one is stamped. Stating it here a
328
+ // second way is how the two halves would disagree about which box an edge
329
+ // arrives at.
330
+ const idOf = (manifest) => nodeIdFor(manifest);
331
+ const manifestById = new Map();
332
+ for (const manifest of resources) {
333
+ const name = manifest.metadata?.name;
334
+ if (typeof name !== "string" || !manifest.kind || DECLARATION_KINDS.has(manifest.kind))
335
+ continue;
336
+ if (root && manifest === options.root)
337
+ continue;
338
+ const id = idOf(manifest);
339
+ if (byId.has(id))
340
+ continue;
341
+ add(projectResource(id, manifest, deps, options));
342
+ manifestById.set(id, manifest);
343
+ }
344
+ // Call-graph node id → the node it designates here, so a step or an edge the
345
+ // call graph produced lands on the box this pass minted.
346
+ const projectedId = new Map();
347
+ const scopedIdByKey = new Map();
348
+ const scopedByOwner = new Map();
349
+ for (const graphNode of callGraph.nodes.values()) {
350
+ if (graphNode.type !== "resource")
351
+ continue;
352
+ if (DECLARATION_KINDS.has(graphNode.kind))
353
+ continue;
354
+ if (graphNode.scoped) {
355
+ // A `with:`-scoped resource is declared inside another's body, so it is in
356
+ // no manifest list of its own — the call graph is where it exists.
357
+ //
358
+ // One declaration, one box: the call graph keys a scoped node by the
359
+ // scope POINTER, and `x-telo-scope` lists every region a scoped name
360
+ // resolves in (`Run.Sequence` names both `/steps` and `/targets`), so one
361
+ // `with:` entry arrives once per pointer. The pointers say where the name
362
+ // is visible, not where the resource was declared.
363
+ const key = `${graphNode.scopeOwner ?? ""}#scope#${resourceId(graphNode.kind, graphNode.name)}`;
364
+ const already = scopedIdByKey.get(key);
365
+ if (already) {
366
+ projectedId.set(graphNode.id, already);
367
+ continue;
368
+ }
369
+ const node = add(projectResource(graphNode.id, graphNode.manifest, deps, options));
370
+ scopedIdByKey.set(key, node.id);
371
+ node.ownership = "scoped";
372
+ if (graphNode.scopeOwner)
373
+ node.owner = graphNode.scopeOwner;
374
+ if (graphNode.scopeSite)
375
+ node.ownerSite = graphNode.scopeSite;
376
+ manifestById.set(node.id, graphNode.manifest);
377
+ projectedId.set(graphNode.id, node.id);
378
+ const owner = graphNode.scopeOwner;
379
+ if (owner) {
380
+ const sites = scopedByOwner.get(owner) ?? new Map();
381
+ const site = graphNode.scopeSite ?? "";
382
+ sites.set(site, [...(sites.get(site) ?? []), node.id]);
383
+ scopedByOwner.set(owner, sites);
384
+ }
385
+ continue;
386
+ }
387
+ projectedId.set(graphNode.id, idOf(graphNode.manifest));
388
+ }
389
+ // A scoped node's owner is a call-graph id; translate it now that every
390
+ // resource node has one.
391
+ for (const node of nodes) {
392
+ if (node.ownership === "scoped" && node.owner) {
393
+ node.owner = projectedId.get(node.owner) ?? node.owner;
394
+ }
395
+ }
396
+ for (const [owner, sites] of [...scopedByOwner]) {
397
+ const translated = projectedId.get(owner);
398
+ if (translated && translated !== owner) {
399
+ scopedByOwner.delete(owner);
400
+ scopedByOwner.set(translated, sites);
401
+ }
402
+ }
403
+ // Inline children: the extraction stamps the parent and the path it was
404
+ // written at, so ownership is read off the declaration rather than guessed
405
+ // from a name pattern. The stamp names the parent by `(kind, name)`, so it is
406
+ // translated through the same table a call-graph id is.
407
+ const inlineByOwner = new Map();
408
+ for (const node of nodes) {
409
+ if (node.ownership !== "inline" || !node.owner)
410
+ continue;
411
+ node.owner = projectedId.get(node.owner) ?? node.owner;
412
+ const sites = inlineByOwner.get(node.owner) ?? new Map();
413
+ const site = node.ownerSite ?? "";
414
+ sites.set(site, [...(sites.get(site) ?? []), node.id]);
415
+ inlineByOwner.set(node.owner, sites);
416
+ }
417
+ for (const [owner, sites] of inlineByOwner) {
418
+ for (const [site, members] of sites) {
419
+ regions.push({ id: `${owner}#inline:${site}`, kind: "inline", owner, site, members });
420
+ }
421
+ }
422
+ for (const [owner, sites] of scopedByOwner) {
423
+ for (const [site, members] of sites) {
424
+ regions.push({ id: `${owner}#scope:${site}`, kind: "scope", owner, site, members });
425
+ }
426
+ }
427
+ // Execution zones: a region every dispatch inside runs within. Read from the
428
+ // containment walk rather than re-derived, so what the editor draws and what
429
+ // `telo check` enforces are the same region — including one declaring no
430
+ // attributes, which is still a zone.
431
+ for (const zone of findZoneProviders(callGraph, (kind, module) => deps.definition(kind, module))) {
432
+ const owner = projectedId.get(zone.provider.id) ?? zone.provider.id;
433
+ if (!byId.has(owner))
434
+ continue;
435
+ const members = [];
436
+ for (const [id, contained] of zone.contents) {
437
+ // A step is a ROW of its owner here, so a zone reaching one is a zone
438
+ // reaching the resource whose body declares it.
439
+ const memberId = contained.node.type === "step"
440
+ ? (projectedId.get(contained.node.owner) ?? contained.node.owner)
441
+ : (projectedId.get(id) ?? id);
442
+ if (memberId !== owner && byId.has(memberId) && !members.includes(memberId)) {
443
+ members.push(memberId);
444
+ }
445
+ }
446
+ const boundaries = zone.boundaries.map((b) => ({
447
+ from: projectedId.get(b.from.id) ?? b.from.id,
448
+ toName: b.edge.toName,
449
+ escaping: b.escaping,
450
+ }));
451
+ regions.push({
452
+ id: `${owner}#zone:${zone.slot}`,
453
+ kind: "zone",
454
+ owner,
455
+ site: zone.slot,
456
+ members,
457
+ attributes: zone.attributes,
458
+ ...(boundaries.length > 0 ? { boundaries } : {}),
459
+ });
460
+ }
461
+ // --- rows ------------------------------------------------------------------
462
+ // Steps come from the call graph, which owns the analyzer's only step-array
463
+ // recursion; entry lists and boot targets are read here, since neither is a
464
+ // step body and neither has a node of its own.
465
+ const callGraphIdByNode = invertProjectedIds(projectedId);
466
+ const callGraphIdOf = (nodeId) => callGraphIdByNode.get(nodeId) ?? nodeId;
467
+ for (const node of nodes) {
468
+ const manifest = node.root ? options.root : manifestById.get(node.id);
469
+ if (!manifest)
470
+ continue;
471
+ const definition = deps.definition(node.kind, node.module);
472
+ const schema = definition?.schema;
473
+ // The root's rows are its BOOT LIST and nothing else. `targets` carries the
474
+ // step grammar, so the call graph mints a step node for every entry that is
475
+ // not a bare `!ref` — and `targetRows` already renders every shape an entry
476
+ // takes, so collecting both listed an inline target twice.
477
+ node.rows = node.root
478
+ ? targetRows(node, manifest, rowIdByPath)
479
+ : [
480
+ ...stepRows(node, callGraph, callGraphIdOf(node.id), rowIdByPath),
481
+ ...entryRows(node, manifest, schema, rowIdByPath),
482
+ ];
483
+ if (!node.root)
484
+ node.rowArrays = declaredRowArrays(schema);
485
+ }
486
+ // --- ports and edges -------------------------------------------------------
487
+ for (const node of nodes) {
488
+ const manifest = node.root ? options.root : manifestById.get(node.id);
489
+ if (!manifest)
490
+ continue;
491
+ const definition = deps.definition(node.kind, node.module);
492
+ const schema = definition?.schema;
493
+ // A slot whose occupancy is DRAWN AS ROWS is not also a port: a route, a
494
+ // boot target and a step are manipulated as the ordered thing they are, and
495
+ // a second rendering of the same occupancy beside it is two controls for
496
+ // one fact. Read off the DECLARED arrays, not the rows: an empty `mounts`
497
+ // would otherwise be row-owned only once it had a mount in it, so a fresh
498
+ // server showed both a port and an add control for the same list.
499
+ const rowArrays = new Set(node.rowArrays.map((a) => a.field));
500
+ node.ports = buildPorts(manifest, deps, schema, rowArrays);
501
+ const throws = deps.throwsOf?.(manifest);
502
+ if (throws && (throws.codes.length > 0 || throws.unbounded))
503
+ node.throws = throws;
504
+ // A declaration written at a dispatch site hangs under the row that
505
+ // declares it — see `inlineRows`. After the ports, because a route's
506
+ // `handler:` is a port slot and its occupancy is what names the site; and
507
+ // woven rather than appended, so the body stays pre-order, which every
508
+ // consumer of `parent` relies on.
509
+ node.rows = weaveInlineRows(node, manifest, callGraph, callGraphIdOf(node.id), deps, rowIdByPath, inlineEdgeSeeds);
510
+ }
511
+ // Alias-qualified names, so a reference across an import boundary resolves.
512
+ // The call graph matches bare names — right for a name declared here, and the
513
+ // reason `!ref Console.writeLine` reached this pass as a dangling edge.
514
+ // Every row is known by now, so the per-owner index the longest-prefix walk
515
+ // needs is built once rather than re-scanned per edge.
516
+ const rowsByOwner = rowsByOwnerOf(rowIdByPath);
517
+ const byQualifiedName = new Map();
518
+ for (const node of nodes) {
519
+ if (!node.module)
520
+ continue;
521
+ for (const alias of deps.aliasesForModule(node.module)) {
522
+ const key = `${alias}.${node.name}`;
523
+ if (!byQualifiedName.has(key))
524
+ byQualifiedName.set(key, node.id);
525
+ }
526
+ }
527
+ // Edges come from the call graph — one per site, already resolved — re-keyed
528
+ // onto the boxes a view draws: a step's edge is attributed to the resource
529
+ // whose body declares it, with the row that declared it named, because a step
530
+ // is a row here rather than a node of its own.
531
+ for (const edge of callGraph.edges) {
532
+ const projected = projectEdge(edge, callGraph, byId, rowIdByPath, rowsByOwner, byQualifiedName, projectedId);
533
+ if (!projected)
534
+ continue;
535
+ // A reference leaving the module root IS a boot target — the root has no
536
+ // other slots — so the flag is stamped here rather than by a second pass
537
+ // over `targets`, which emitted a duplicate edge for every one of them.
538
+ if (root && projected.from === root.id)
539
+ projected.boot = true;
540
+ edges.push(projected);
541
+ }
542
+ // Data edges: one resource reading another's published state in CEL. Parsed,
543
+ // never scanned — `extractAccessChains` reads `resources.db.status.port` as a
544
+ // chain and a name inside a string literal as nothing, which a token scan
545
+ // cannot tell apart.
546
+ // A bare name resolves in the module that WROTE it — the call graph's own
547
+ // rule, shared rather than restated. Keeping a first-wins index here would
548
+ // have put every inline declaration's reference and every CEL state read back
549
+ // on whichever module happened to come first in the flattened list, which is
550
+ // the collision module-scoped identity exists to prevent.
551
+ const nodesByName = new Map();
552
+ for (const node of nodes) {
553
+ if (node.root)
554
+ continue;
555
+ nodesByName.set(node.name, [...(nodesByName.get(node.name) ?? []), node]);
556
+ }
557
+ const resolveName = (name, fromModule) => resolveScopedName(nodesByName.get(name), (node) => node.module, fromModule)?.id;
558
+ // References written INSIDE a declaration. Resolved here rather than where
559
+ // they were found, because a declaration may name a resource declared later
560
+ // in the file — and against the same name index every other edge uses, so a
561
+ // hold reached through an inline declaration counts exactly as one written at
562
+ // a named resource's own slot.
563
+ for (const [from, list] of inlineEdgeSeeds) {
564
+ const fromModule = byId.get(from)?.module;
565
+ for (const seed of list) {
566
+ const to = resolveName(seed.toName, fromModule) ?? byQualifiedName.get(seed.toName);
567
+ const edge = {
568
+ id: `${from}\0${seed.path}`,
569
+ from,
570
+ toName: seed.toName,
571
+ class: edgeClassOf(seed.uses),
572
+ use: seed.uses,
573
+ slot: seed.slot,
574
+ path: seed.path,
575
+ row: seed.rowId,
576
+ };
577
+ if (to)
578
+ edge.to = to;
579
+ edges.push(edge);
580
+ }
581
+ }
582
+ for (const node of nodes) {
583
+ const manifest = node.root ? options.root : manifestById.get(node.id);
584
+ if (!manifest)
585
+ continue;
586
+ edges.push(...dataEdges(node, manifest, node.module, resolveName, rowIdByPath, rowsByOwner));
587
+ }
588
+ // Where each row's call is WRITTEN, and what may fill it — see
589
+ // `GraphRow.dispatch`. Three shapes, because the grammar has three: a step's
590
+ // slot is declared on its item schema and reachable only through the step
591
+ // walk; an entry's is a row-owned port of the array it sits in; a boot target
592
+ // IS its own slot. All three are stated even when nothing fills them, since
593
+ // an empty site is exactly the one an editor has something to offer at.
594
+ for (const node of nodes) {
595
+ const stepSlots = new Map();
596
+ const stepSites = new Map();
597
+ for (const step of callGraph.steps(callGraphIdOf(node.id))) {
598
+ const first = step.refSlots?.[0];
599
+ if (first) {
600
+ stepSlots.set(step.path, {
601
+ path: first.path,
602
+ refs: first.kinds,
603
+ ...(first.inline ? { inline: true } : {}),
604
+ });
605
+ }
606
+ if (step.refSlots?.length) {
607
+ stepSites.set(step.path, step.refSlots.map((slot) => ({ path: slot.path, refs: slot.kinds })));
608
+ }
609
+ }
610
+ // Whether a port-derived site holds a declaration, by its concrete path.
611
+ const inlineAt = new Set(node.ports.flatMap((port) => port.slots.filter((s) => s.inline).map((s) => s.path)));
612
+ const rowOwnedPorts = node.ports.filter((port) => port.rowOwned);
613
+ for (const row of node.rows) {
614
+ if (row.kind === "step") {
615
+ const slot = stepSlots.get(row.path);
616
+ if (slot) {
617
+ row.dispatch = withAlternatives(slot, stepSites.get(row.path) ?? []);
618
+ }
619
+ continue;
620
+ }
621
+ if (row.kind === "target") {
622
+ const port = node.ports.find((p) => p.slot === `${row.array}[]`);
623
+ if (port) {
624
+ row.dispatch = withAlternatives({
625
+ path: row.path,
626
+ refs: port.refs,
627
+ ...(inlineAt.has(row.path) ? { inline: true } : {}),
628
+ },
629
+ // A boot target IS a step, and the step walk is what sees the sites
630
+ // the entry's own grammar declares — the bare reference the port
631
+ // reports is one spelling of one of them.
632
+ stepSites.get(row.path) ?? []);
633
+ }
634
+ continue;
635
+ }
636
+ if (row.kind !== "entry")
637
+ continue;
638
+ // `routes[].handler` → the handler of THIS route, whether or not one is
639
+ // written: the port's own slots list only the routes that have one.
640
+ const port = rowOwnedPorts.find((p) => containerArrayOf(p.slot) === row.array);
641
+ if (port) {
642
+ const path = `${row.path}.${port.slot.slice(port.slot.indexOf("[].") + 3)}`;
643
+ row.dispatch = {
644
+ path,
645
+ refs: port.refs,
646
+ ...(inlineAt.has(path) ? { inline: true } : {}),
647
+ };
648
+ }
649
+ }
650
+ }
651
+ // Back-fill what a row learns from the edge it declares: where its target
652
+ // resolved, and where this call's arguments are written. Both are the edge's
653
+ // to know — a row is read off the manifest, while `inputs` is a POINTER the
654
+ // slot declares and the target is a name the graph resolved — so they are
655
+ // stamped here rather than guessed twice.
656
+ const rowById = new Map();
657
+ for (const node of nodes)
658
+ for (const row of node.rows)
659
+ rowById.set(row.id, row);
660
+ for (const edge of edges) {
661
+ const row = edge.row ? rowById.get(edge.row) : undefined;
662
+ if (!row)
663
+ continue;
664
+ if (edge.to && row.targetNode === undefined)
665
+ row.targetNode = edge.to;
666
+ if (row.target === undefined)
667
+ row.target = edge.toName;
668
+ if (edge.inputs !== undefined && row.inputs === undefined) {
669
+ // The pointer is relative to the object ENCLOSING the slot, which for a
670
+ // step or an entry is the row itself.
671
+ row.inputs = `${row.path}${edge.inputs.replace(/\//g, ".")}`;
672
+ }
673
+ }
674
+ const fromIndex = new Map();
675
+ const toIndex = new Map();
676
+ for (const edge of edges) {
677
+ fromIndex.set(edge.from, [...(fromIndex.get(edge.from) ?? []), edge]);
678
+ if (edge.to)
679
+ toIndex.set(edge.to, [...(toIndex.get(edge.to) ?? []), edge]);
680
+ }
681
+ return {
682
+ root,
683
+ nodes,
684
+ edges,
685
+ regions,
686
+ kinds: buildKindPlane(resources, nodes, deps, options),
687
+ nodeById: (id) => byId.get(id),
688
+ edgesFrom: (id) => fromIndex.get(id) ?? [],
689
+ edgesTo: (id) => toIndex.get(id) ?? [],
690
+ };
691
+ }
692
+ /**
693
+ * The call-graph id a projected node came from — the reverse of `projectedId`.
694
+ *
695
+ * Built ONCE. Inverting the map per lookup was a linear scan inside three
696
+ * per-node loops, so a module of n boxes paid O(n²) three times over on every
697
+ * keystroke.
698
+ */
699
+ function invertProjectedIds(projectedId) {
700
+ const out = new Map();
701
+ for (const [callGraphId, projected] of projectedId) {
702
+ if (!out.has(projected))
703
+ out.set(projected, callGraphId);
704
+ }
705
+ return out;
706
+ }
707
+ function projectResource(id, manifest, deps, options) {
708
+ const module = moduleOf(manifest);
709
+ const kind = manifest.kind;
710
+ const definition = deps.definition(kind, module);
711
+ const origin = originOf(manifest);
712
+ const node = {
713
+ id,
714
+ kind,
715
+ name: manifest.metadata?.name,
716
+ ownership: "named",
717
+ ports: [],
718
+ rows: [],
719
+ rowArrays: [],
720
+ };
721
+ if (definition?.capability)
722
+ node.capability = definition.capability;
723
+ const canonical = canonicalKindOf(definition);
724
+ if (canonical && canonical !== kind)
725
+ node.canonicalKind = canonical;
726
+ if (!definition)
727
+ node.unknownKind = true;
728
+ if (module)
729
+ node.module = module;
730
+ if (origin) {
731
+ node.ownership = "inline";
732
+ node.owner = resourceId(origin.parentKind, origin.parentName);
733
+ node.ownerSite = origin.pathFromParent;
734
+ }
735
+ else if (isInjected(manifest)) {
736
+ node.ownership = "injected";
737
+ }
738
+ else if (isForwardedExport(manifest)) {
739
+ node.ownership = "imported";
740
+ }
741
+ // External is a fact about the DECLARING module, not about the ownership
742
+ // class: a library's own named resource forwarded into an app is `imported`,
743
+ // while a resource the app declares in an included partial is not — both are
744
+ // decided by the module stamp rather than by how the reference reached here.
745
+ if (options.entryModule && module && module !== options.entryModule) {
746
+ node.external = true;
747
+ // The alias the reference is WRITTEN with. Several may point at one module;
748
+ // the first is taken, because a boundary box needs one label and every
749
+ // alias designates the same module.
750
+ const alias = module ? deps.aliasesForModule(module)[0] : undefined;
751
+ if (alias)
752
+ node.alias = alias;
753
+ }
754
+ return node;
755
+ }
756
+ /** Step rows, from the call graph's step nodes. Depth and parent come from the
757
+ * nesting the call graph already recorded; identity is re-anchored on names. */
758
+ function stepRows(node, callGraph, callGraphId, rowIdByPath) {
759
+ const steps = callGraph.steps(callGraphId);
760
+ if (steps.length === 0)
761
+ return [];
762
+ const minter = new IdMinter();
763
+ const idByStepPath = new Map();
764
+ const rows = [];
765
+ for (const step of steps) {
766
+ const parentId = step.parent ? idByStepPath.get(step.parent) : undefined;
767
+ const anchor = parentId ? `${parentId}/` : `${node.id}#step:`;
768
+ const key = step.name ?? `@${contentKey(step.step)}`;
769
+ const id = minter.mint(`${anchor}${key}`);
770
+ idByStepPath.set(step.id, id);
771
+ rowIdByPath.set(`${node.id}\0${step.path}`, id);
772
+ const row = {
773
+ id,
774
+ kind: "step",
775
+ path: step.path,
776
+ array: step.array,
777
+ index: step.index,
778
+ depth: depthOf(step, callGraph, callGraphId),
779
+ ...(step.name !== undefined ? { name: step.name } : {}),
780
+ ...(step.variant !== undefined ? { variant: step.variant } : {}),
781
+ ...(step.variantLabel !== undefined ? { variantLabel: step.variantLabel } : {}),
782
+ ...(step.predicate !== undefined ? { predicate: step.predicate } : {}),
783
+ ...(parentId ? { parent: parentId } : {}),
784
+ };
785
+ rows.push(row);
786
+ }
787
+ return rows;
788
+ }
789
+ /**
790
+ * One dispatch, with the other ways its grammar lets it be written.
791
+ *
792
+ * Deduplicated by CONSTRAINT, not by path: two spellings accepting the same
793
+ * kinds are one site, and which of them to write is a choice a reader should
794
+ * never be asked to make (the primary is the plainer form). A spelling that
795
+ * accepts something the primary cannot is a site of its own, because it is the
796
+ * only address a reference to such a target could be written at.
797
+ */
798
+ function withAlternatives(primary, sites) {
799
+ const key = (refs) => [...refs].sort().join("\u0000");
800
+ const seen = new Set([key(primary.refs)]);
801
+ const alternatives = [];
802
+ for (const site of sites) {
803
+ if (site.path === primary.path || seen.has(key(site.refs)))
804
+ continue;
805
+ seen.add(key(site.refs));
806
+ alternatives.push(site);
807
+ }
808
+ return alternatives.length > 0 ? { ...primary, alternatives } : primary;
809
+ }
810
+ /**
811
+ * The rows and edges a DECLARATION written at a dispatch site contributes.
812
+ *
813
+ * `invoke: { kind: Sql.Command, connection: !ref chatDb }` is a resource the
814
+ * manifest genuinely declares, and until now the graph could see none of it: no
815
+ * node, no edge, and a step row identical to one that dispatches nothing. The
816
+ * hold was invisible too, so a connection reached only from inside inline
817
+ * declarations was reported as referenced by nothing.
818
+ *
819
+ * What is emitted is one row for the declaration — named by its kind, addressed
820
+ * at the site, so it can be opened and edited where it was written — and one row
821
+ * per reference it fills, each carrying a real edge. That is what puts the hold
822
+ * back on the graph, and it is why these are rows rather than a label: a
823
+ * reference needs somewhere for its line to leave from.
824
+ *
825
+ * Recursive, because a declaration may hold another; bounded by the manifest,
826
+ * which cannot contain itself.
827
+ */
828
+ function inlineRows(node, site, host, deps, rowIdByPath, out) {
829
+ const kind = site.value.kind;
830
+ const declared = deps.definition(kind, node.module);
831
+ const id = `${host.rowId}/${lastPathSegment(site.path)}`;
832
+ const row = {
833
+ id,
834
+ kind: "inline",
835
+ path: site.path,
836
+ array: host.array,
837
+ index: 0,
838
+ depth: host.depth + 1,
839
+ parent: host.rowId,
840
+ declares: kind,
841
+ ...(declared ? {} : { unknownKind: true }),
842
+ };
843
+ out.rows.push(row);
844
+ rowIdByPath.set(`${node.id}\0${site.path}`, id);
845
+ // The declaration's own reference slots, read through its kind's field map —
846
+ // the same map a named resource's ports come from, so an inline declaration
847
+ // and an extracted one describe themselves identically.
848
+ const asManifest = { ...site.value, metadata: { name: id } };
849
+ const declaredSchema = declared?.schema;
850
+ for (const field of deps.refFields(asManifest)) {
851
+ for (const entry of resolveFieldEntries(asManifest, field.path)) {
852
+ const path = `${site.path}.${entry.path}`;
853
+ if (isInlineDeclaration(entry.value)) {
854
+ inlineRows(node, { path, value: entry.value }, { rowId: id, array: host.array, depth: row.depth, slot: `${host.slot}.${field.path}` }, deps, rowIdByPath, out);
855
+ continue;
856
+ }
857
+ const target = refName(entry.value);
858
+ if (target === undefined)
859
+ continue;
860
+ const refId = `${id}/${lastPathSegment(entry.path)}`;
861
+ out.rows.push({
862
+ id: refId,
863
+ kind: "reference",
864
+ name: lastPathSegment(field.path),
865
+ path,
866
+ array: host.array,
867
+ index: 0,
868
+ depth: row.depth + 1,
869
+ parent: id,
870
+ target,
871
+ });
872
+ rowIdByPath.set(`${node.id}\0${path}`, refId);
873
+ out.edges.push({
874
+ rowId: refId,
875
+ toName: target,
876
+ // The slot the OWNER declares, so the branch this edge leaves is the
877
+ // host's own property — what decides whether it is drawn at all.
878
+ slot: `${host.slot}.${field.path}`,
879
+ path,
880
+ // Read off the DECLARED kind's own schema, exactly as a port's is —
881
+ // `use` is a property of the slot, and the slot belongs to the kind
882
+ // written here rather than to the resource hosting it.
883
+ uses: readUses(schemaAt(declaredSchema, field.path)),
884
+ });
885
+ }
886
+ }
887
+ }
888
+ /**
889
+ * The body with each declaration's rows woven in beneath the row that declares
890
+ * it, keeping the whole list pre-order.
891
+ *
892
+ * Pre-order is not a nicety: every consumer of `parent` — the tree's visibility
893
+ * walk, the geometry, the renderer — settles a parent's verdict before it asks
894
+ * about a child, and appending these at the end would silently break all three.
895
+ *
896
+ * Sites come from two places and neither is optional. A STEP's dispatch slot is
897
+ * recorded by the call graph, which is the only walk that reaches a step's item
898
+ * schema; every other slot — a route's `handler:`, a `mounts[].mount` — is an
899
+ * ordinary field-map entry and is found here.
900
+ */
901
+ function weaveInlineRows(node, manifest, callGraph, callGraphId, deps, rowIdByPath, seeds) {
902
+ /**
903
+ * Sites keyed by their concrete path, because the two walks OVERLAP: a step's
904
+ * `invoke:` is both a step dispatch slot and a row-owned port slot, so
905
+ * collecting them into a list emitted every declaration under a step twice —
906
+ * two rows sharing one id, and two copies of every edge inside it.
907
+ */
908
+ // This node's rows as they stand before any declaration is woven in — which
909
+ // is what a site can be hosted BY. Scoped to the node rather than scanning
910
+ // every row in the module, and taken once because the weave only ADDS rows
911
+ // below the ones a site could already have named.
912
+ const ownRows = rowsByOwnerOf(rowIdByPath).get(node.id) ?? [];
913
+ const sites = new Map();
914
+ const record = (rowId, path, value, slot) => {
915
+ if (!rowId || sites.has(path) || !isInlineDeclaration(value))
916
+ return;
917
+ sites.set(path, { rowId, path, value: value, slot });
918
+ };
919
+ for (const step of callGraph.steps(callGraphId)) {
920
+ for (const site of (step.refSlots ?? []).filter((slot) => slot.inline)) {
921
+ const rowId = rowIdByPath.get(`${node.id}\0${step.path}`);
922
+ if (!rowId)
923
+ continue;
924
+ record(rowId, site.path, step.step[site.key], `${step.array}[].${site.key}`);
925
+ }
926
+ }
927
+ for (const port of node.ports) {
928
+ if (!port.slots.some((slot) => slot.inline))
929
+ continue;
930
+ for (const entry of resolveFieldEntries(manifest, port.slot)) {
931
+ // A site on a slot no row owns — a plain `connection:` on a resource — is
932
+ // left to the port, which already draws it. Only a ROW can host a subtree.
933
+ const rowId = rowIdByPath.get(`${node.id}\0${entry.path}`) ??
934
+ rowAt(new Map([[node.id, ownRows]]), node.id, entry.path);
935
+ if (!rowId)
936
+ continue;
937
+ record(rowId, entry.path, entry.value, port.slot);
938
+ }
939
+ }
940
+ if (sites.size === 0)
941
+ return node.rows;
942
+ const byRow = new Map();
943
+ for (const site of sites.values()) {
944
+ byRow.set(site.rowId, [...(byRow.get(site.rowId) ?? []), site]);
945
+ }
946
+ const out = [];
947
+ for (const row of node.rows) {
948
+ out.push(row);
949
+ for (const site of byRow.get(row.id) ?? []) {
950
+ const collected = { rows: [], edges: [] };
951
+ inlineRows(node, { path: site.path, value: site.value }, { rowId: row.id, array: row.array, depth: row.depth, slot: site.slot }, deps, rowIdByPath, collected);
952
+ out.push(...collected.rows);
953
+ if (collected.edges.length > 0) {
954
+ seeds.set(node.id, [...(seeds.get(node.id) ?? []), ...collected.edges]);
955
+ }
956
+ }
957
+ }
958
+ return out;
959
+ }
960
+ /** `steps[0].invoke.connection` → `connection`; `routes[1]` → `routes`. */
961
+ function lastPathSegment(path) {
962
+ const last = path.split(".").pop() ?? path;
963
+ return last.replace(/\[\d+\]$/, "").replace(/\[\]$|\{\}$/, "");
964
+ }
965
+ /** Nesting depth of a step: how many step parents stand above it. */
966
+ function depthOf(step, callGraph, ownerId) {
967
+ let depth = 0;
968
+ let current = step;
969
+ const byId = new Map(callGraph.steps(ownerId).map((s) => [s.id, s]));
970
+ while (current?.parent) {
971
+ depth++;
972
+ current = byId.get(current.parent);
973
+ }
974
+ return depth;
975
+ }
976
+ /** Entry rows: one per item of an `x-telo-topology-role: entries` array. The
977
+ * matcher fields are what identifies an entry to a reader, so they are also
978
+ * what its identity is derived from — a route keeps its identity when a route
979
+ * is inserted above it, and loses it only when its own path or method change,
980
+ * which is what makes it a different route. */
981
+ function entryRows(node, manifest, schema, rowIdByPath) {
982
+ const rows = [];
983
+ for (const spec of entryListsOf(schema)) {
984
+ const value = manifest[spec.field];
985
+ if (!Array.isArray(value))
986
+ continue;
987
+ const minter = new IdMinter();
988
+ value.forEach((item, index) => {
989
+ const entry = (item ?? {});
990
+ // What IDENTIFIES an entry to a reader is the scalars its matcher holds —
991
+ // a path and a method — not the whole matcher, which for an HTTP route
992
+ // also carries the request schema. Taking the schema would put a row's
993
+ // identity at the mercy of an edit to a property it does not show, so a
994
+ // reader loses their selection by editing something else entirely.
995
+ const match = scalarLeaves(Object.fromEntries(spec.matchers.filter((m) => entry[m] !== undefined).map((m) => [m, entry[m]])));
996
+ const key = Object.keys(match).length > 0 ? contentKey(match) : contentKey(entry);
997
+ const path = `${spec.field}[${index}]`;
998
+ const id = minter.mint(`${node.id}#entry:${spec.field}/${key}`);
999
+ rowIdByPath.set(`${node.id}\0${path}`, id);
1000
+ const handlerField = spec.handlers.find((h) => entry[h] !== undefined);
1001
+ const target = handlerField ? refName(entry[handlerField]) : undefined;
1002
+ const catches = spec.errorBranches.some((b) => {
1003
+ const value = entry[b];
1004
+ return Array.isArray(value) ? value.length > 0 : value !== undefined;
1005
+ });
1006
+ rows.push({
1007
+ id,
1008
+ kind: "entry",
1009
+ path,
1010
+ array: spec.field,
1011
+ index,
1012
+ depth: 0,
1013
+ ...(Object.keys(match).length > 0 ? { match } : {}),
1014
+ ...(target !== undefined ? { target } : {}),
1015
+ ...(catches ? { catches: true } : {}),
1016
+ });
1017
+ });
1018
+ }
1019
+ return rows;
1020
+ }
1021
+ /**
1022
+ * The scalar leaves of a value, flattened to one map, to a bounded depth.
1023
+ *
1024
+ * A matcher is whatever the kind declared it to be: a flat `path` / `method`
1025
+ * pair on one router, a nested `request:` object on another. Reading the scalars
1026
+ * out of it works for both without naming either — and stopping at scalars is
1027
+ * what keeps a nested JSON Schema (which is an object all the way down) out of
1028
+ * something a reader is meant to recognize the row by.
1029
+ */
1030
+ function scalarLeaves(value, depth = 0) {
1031
+ const out = {};
1032
+ if (depth > 2 || !value || typeof value !== "object" || Array.isArray(value))
1033
+ return out;
1034
+ for (const [key, child] of Object.entries(value)) {
1035
+ if (child === null)
1036
+ continue;
1037
+ if (typeof child !== "object")
1038
+ out[key] = child;
1039
+ else
1040
+ Object.assign(out, scalarLeaves(child, depth + 1));
1041
+ }
1042
+ return out;
1043
+ }
1044
+ /**
1045
+ * The ordered arrays a kind declares — its entry lists and its step bodies.
1046
+ *
1047
+ * Both are found by annotation (`x-telo-topology-role: entries`, and the shared
1048
+ * step-body stamp), so a third-party composer's list is offered the same
1049
+ * affordances as `Http.Api`'s routes with no editor change.
1050
+ */
1051
+ function declaredRowArrays(schema) {
1052
+ const out = [];
1053
+ for (const spec of entryListsOf(schema))
1054
+ out.push({ field: spec.field, kind: "entry" });
1055
+ for (const [key, propSchema] of propertySchemas(schema ?? {})) {
1056
+ if (isStepSlot(propSchema))
1057
+ out.push({ field: key, kind: "step" });
1058
+ }
1059
+ return out;
1060
+ }
1061
+ /** Boot rows: the root's `targets`, which is an ordered step list — a later
1062
+ * target reads an earlier one's result — so it is rows, not a set. */
1063
+ function targetRows(node, manifest, rowIdByPath) {
1064
+ const targets = manifest.targets;
1065
+ if (!Array.isArray(targets))
1066
+ return [];
1067
+ const minter = new IdMinter();
1068
+ return targets.map((entry, index) => {
1069
+ const record = (entry ?? {});
1070
+ const target = refName(entry) ?? refName(record.ref) ?? refName(record.invoke) ?? undefined;
1071
+ const name = typeof record.name === "string" ? record.name : undefined;
1072
+ const key = name ?? target ?? `@${contentKey(entry)}`;
1073
+ const path = `targets[${index}]`;
1074
+ const id = minter.mint(`${node.id}#target:${key}`);
1075
+ rowIdByPath.set(`${node.id}\0${path}`, id);
1076
+ return {
1077
+ id,
1078
+ kind: "target",
1079
+ path,
1080
+ array: "targets",
1081
+ index,
1082
+ depth: 0,
1083
+ ...(name !== undefined ? { name } : {}),
1084
+ ...(target !== undefined ? { target } : {}),
1085
+ // A boot target's shapes carry no branch titles, so there is no variant
1086
+ // to report — but a GATED one is the same fact a step's `when:` is, and
1087
+ // a target drawn without its guard says it always runs.
1088
+ ...(guardOf(record) !== undefined ? { predicate: guardOf(record) } : {}),
1089
+ };
1090
+ });
1091
+ }
1092
+ /** The `when:` guard on a boot target, as written. */
1093
+ function guardOf(entry) {
1094
+ const written = entry.when;
1095
+ if (typeof written === "string")
1096
+ return written;
1097
+ if (written && typeof written === "object") {
1098
+ const source = written.source;
1099
+ if (typeof source === "string")
1100
+ return source;
1101
+ }
1102
+ return undefined;
1103
+ }
1104
+ /** Every declared reference slot as a port, with its occupancy read off the
1105
+ * manifest — so an empty slot is a port with no filled sites rather than an
1106
+ * absence a view has to infer. */
1107
+ function buildPorts(manifest, deps, schema, rowArrays) {
1108
+ const fields = deps.refFields(manifest);
1109
+ // The `anyOf` sub-shapes of one array-of-refs are ONE slot, not three. A boot
1110
+ // target may be written bare, as `{ref, when}` or as an inline invoke step, so
1111
+ // the field map lists `targets[]`, `targets[].ref` and `targets[].invoke` —
1112
+ // rendering each as its own port offers three sockets for one position and
1113
+ // says the module has slots it does not have.
1114
+ const arrayRefBases = new Set(fields.filter((f) => isArrayOfRefs(f.path)).map((f) => arrayBaseOf(f.path)));
1115
+ const ports = [];
1116
+ for (const field of fields) {
1117
+ if ([...arrayRefBases].some((base) => field.path.startsWith(`${base}[].`)))
1118
+ continue;
1119
+ const slotSchema = schemaAt(schema, field.path);
1120
+ const uses = readUses(slotSchema);
1121
+ const slots = [];
1122
+ for (const { value, path } of resolveFieldEntries(manifest, field.path)) {
1123
+ const target = refName(value);
1124
+ const slot = { path };
1125
+ if (target !== undefined)
1126
+ slot.target = target;
1127
+ // A slot holding a declaration rather than a reference is FILLED, and a
1128
+ // view that reads only `target` would draw it as an empty socket — the
1129
+ // one reading that is wrong in both directions, since it invites filling
1130
+ // a slot that is already occupied.
1131
+ else if (isInlineDeclaration(value))
1132
+ slot.inline = true;
1133
+ slots.push(slot);
1134
+ }
1135
+ // **An unwritten slot still has a write site.** Resolving the manifest for
1136
+ // `notFoundHandler.invoke` on a server that declares no `notFoundHandler`
1137
+ // yields nothing, so the port had no path at all — it rendered as an empty
1138
+ // socket that could not be filled, which is worse than not drawing it: it
1139
+ // offers an affordance and then refuses. The path IS the site for a slot in
1140
+ // no array, so it is synthesized here rather than left to every consumer to
1141
+ // reconstruct.
1142
+ if (slots.length === 0 && !field.path.includes("[]") && !field.path.includes("{}")) {
1143
+ slots.push({ path: field.path });
1144
+ }
1145
+ const port = {
1146
+ slot: field.path,
1147
+ refs: field.refs,
1148
+ capabilities: field.capabilities,
1149
+ array: field.isArray,
1150
+ class: edgeClassOf(uses),
1151
+ slots,
1152
+ };
1153
+ const append = appendPathFor(field.path, manifest);
1154
+ if (append)
1155
+ port.addPath = append;
1156
+ if (rowArrays.has(containerArrayOf(field.path)))
1157
+ port.rowOwned = true;
1158
+ ports.push(port);
1159
+ }
1160
+ return ports;
1161
+ }
1162
+ /** A top-level array of direct refs (`targets[]`): the trailing `[]` is the
1163
+ * path's only marker. */
1164
+ function isArrayOfRefs(path) {
1165
+ return path.endsWith("[]") && !path.slice(0, -2).match(/\[\]|\{\}/);
1166
+ }
1167
+ /** `targets[]` → `targets`. */
1168
+ function arrayBaseOf(path) {
1169
+ return path.slice(0, -2);
1170
+ }
1171
+ /**
1172
+ * Where a NEW occupancy of this slot would be written.
1173
+ *
1174
+ * Both array shapes reach here: a direct array of refs (`targets[]` →
1175
+ * `targets[2]`) and a ref inside an array of objects (`mounts[].mount` →
1176
+ * `mounts[2].mount`). The second was missing, so an `Http.Server` with no mounts
1177
+ * offered no way to add one — the port drew an empty rail and the drag had
1178
+ * nowhere to land. Undefined for a slot in no array, and for one nested past a
1179
+ * single array, where the index of the outer item is not determined by the slot
1180
+ * alone.
1181
+ */
1182
+ function appendPathFor(path, manifest) {
1183
+ const marker = path.indexOf("[]");
1184
+ if (marker === -1)
1185
+ return undefined;
1186
+ const array = path.slice(0, marker);
1187
+ const suffix = path.slice(marker + 2);
1188
+ if (array.includes("{}") || suffix.includes("[]") || suffix.includes("{}"))
1189
+ return undefined;
1190
+ const existing = manifest[array];
1191
+ return `${array}[${Array.isArray(existing) ? existing.length : 0}]${suffix}`;
1192
+ }
1193
+ /** The array a slot's occupancy sits in (`routes[].handler` → `routes`,
1194
+ * `targets[]` → `targets`), or the path itself when it is in no array. */
1195
+ function containerArrayOf(path) {
1196
+ const marker = path.indexOf("[]");
1197
+ return marker === -1 ? path : path.slice(0, marker);
1198
+ }
1199
+ /**
1200
+ * Declared uses at a slot, through the annotation's ONE reader.
1201
+ *
1202
+ * It used to hand-parse `slotSchema["x-telo-ref"]`, which sees nothing when the
1203
+ * annotation sits in a `oneOf` branch — the sanctioned shape for a slot that
1204
+ * unions a value with a reference. A column's `type:` is exactly that, so its
1205
+ * `use: schema` read as no declared use at all and the slot was classed (and
1206
+ * drawn) as a control transfer. `readRefSlot` unions the branches; `possibleUses`
1207
+ * folds a case map's arms in, which is what a PORT wants: the port describes the
1208
+ * slot, and which arm holds is decided per site by the call graph.
1209
+ */
1210
+ function readUses(slotSchema) {
1211
+ const slot = readRefSlot(slotSchema);
1212
+ return slot ? possibleUses(slot) : [];
1213
+ }
1214
+ /** Re-key one call-graph edge onto the boxes a view draws. A step's edge is
1215
+ * attributed to the resource whose body declares it — a step is a row here,
1216
+ * not a node — with the row named so the edge can dock onto it. */
1217
+ function projectEdge(edge, callGraph, byId, rowIdByPath, rowsByOwner, byQualifiedName, projectedId) {
1218
+ const source = callGraph.nodes.get(edge.from);
1219
+ const rawFrom = source?.type === "step" ? source.owner : edge.from;
1220
+ const fromId = projectedId.get(rawFrom) ?? rawFrom;
1221
+ if (!byId.has(fromId))
1222
+ return undefined;
1223
+ const projected = {
1224
+ id: `${fromId}\0${edge.slot}\0${edge.path}`,
1225
+ from: fromId,
1226
+ toName: edge.toName,
1227
+ class: edgeClassOf(edge.use),
1228
+ use: edge.use,
1229
+ slot: edge.slot,
1230
+ path: edge.path,
1231
+ };
1232
+ const to = edge.to ? (projectedId.get(edge.to) ?? edge.to) : undefined;
1233
+ if (to && byId.has(to))
1234
+ projected.to = to;
1235
+ else {
1236
+ const qualified = byQualifiedName.get(edge.toName);
1237
+ if (qualified)
1238
+ projected.to = qualified;
1239
+ }
1240
+ if (edge.inputs !== undefined)
1241
+ projected.inputs = edge.inputs;
1242
+ if (edge.scoped)
1243
+ projected.scoped = true;
1244
+ // The row an edge leaves from: the step that declares it, or the entry whose
1245
+ // handler slot holds it. Longest-prefix on the concrete path, so a site
1246
+ // nested inside a branch docks onto the row that actually declares it.
1247
+ const row = rowIdByPath.get(`${fromId}\0${edge.path}`) ?? rowAt(rowsByOwner, fromId, edge.path);
1248
+ if (row)
1249
+ projected.row = row;
1250
+ return projected;
1251
+ }
1252
+ /** The row whose path is the longest prefix of a site's path. */
1253
+ function rowAt(rowsByOwner, ownerId, path) {
1254
+ let best;
1255
+ let bestLength = -1;
1256
+ for (const row of rowsByOwner.get(ownerId) ?? []) {
1257
+ const inside = path.startsWith(`${row.path}.`) || path.startsWith(`${row.path}[`);
1258
+ if (inside && row.path.length > bestLength) {
1259
+ best = row.id;
1260
+ bestLength = row.path.length;
1261
+ }
1262
+ }
1263
+ return best;
1264
+ }
1265
+ /**
1266
+ * The rows each box owns, by owner — so finding the row a nested site sits in
1267
+ * is a scan of one box's rows rather than of every row in the module.
1268
+ *
1269
+ * The flat `<owner>\0<path>` map is the right shape for an exact hit and the
1270
+ * wrong one for the longest-prefix walk, which is the COMMON case: a step's ref
1271
+ * is nested inside the step, so the exact lookup misses and the fallback ran
1272
+ * over every row of every box, for every edge and every CEL chain.
1273
+ */
1274
+ function rowsByOwnerOf(rowIdByPath) {
1275
+ const out = new Map();
1276
+ for (const [key, id] of rowIdByPath) {
1277
+ // The LAST separator: a node id contains NULs of its own (`kind\0name`, and
1278
+ // `module\0kind\0name` across a boundary) while a concrete path contains
1279
+ // none, so splitting at the first one takes the kind for the owner and
1280
+ // leaves the name glued to the path — an index that matches nothing.
1281
+ const marker = key.lastIndexOf("\0");
1282
+ if (marker === -1)
1283
+ continue;
1284
+ const owner = key.slice(0, marker);
1285
+ out.set(owner, [...(out.get(owner) ?? []), { path: key.slice(marker + 1), id }]);
1286
+ }
1287
+ return out;
1288
+ }
1289
+ /** Kinds a definition body declares — the marks of a template rather than a
1290
+ * controller-backed kind. */
1291
+ const TEMPLATE_FIELDS = ["resources", "invoke", "run", "provide"];
1292
+ /**
1293
+ * The kind plane: every `Telo.Definition` / `Telo.Abstract` in scope, with its
1294
+ * lineage and the instances that were declared of it.
1295
+ *
1296
+ * Built from the same manifest list the instance plane skips them from, so a
1297
+ * kind-only library — one whose whole content is declarations — has a plane to
1298
+ * render rather than an empty canvas.
1299
+ */
1300
+ function buildKindPlane(resources, nodes, deps, options) {
1301
+ const exportedKinds = new Set((options.root?.exports?.kinds ?? []).filter((k) => typeof k === "string"));
1302
+ // Keyed on the CANONICAL kind, because that is what a kind's own id is: an
1303
+ // instance a library declared as `kind: Self.WriteLine` belongs to
1304
+ // `console.WriteLine`, and keying on the written spelling gave every such kind
1305
+ // an empty instance list.
1306
+ const instancesByKind = new Map();
1307
+ for (const node of nodes) {
1308
+ if (node.root)
1309
+ continue;
1310
+ const key = node.canonicalKind ?? node.kind;
1311
+ instancesByKind.set(key, [...(instancesByKind.get(key) ?? []), node.id]);
1312
+ }
1313
+ const out = [];
1314
+ for (const manifest of resources) {
1315
+ const docKind = manifest.kind;
1316
+ if (docKind !== "Telo.Definition" && docKind !== "Telo.Abstract")
1317
+ continue;
1318
+ const name = manifest.metadata?.name;
1319
+ if (!name)
1320
+ continue;
1321
+ const module = moduleOf(manifest);
1322
+ const id = module ? `${module}.${name}` : name;
1323
+ const record = manifest;
1324
+ const extendsName = typeof record.extends === "string" ? record.extends : undefined;
1325
+ const parent = extendsName ? deps.definition(extendsName, module) : undefined;
1326
+ const parentModule = parent ? moduleOf(parent) : undefined;
1327
+ const parentName = parent?.metadata?.name;
1328
+ const kind = {
1329
+ id,
1330
+ name,
1331
+ abstract: docKind === "Telo.Abstract",
1332
+ instances: instancesByKind.get(id) ?? [],
1333
+ template: TEMPLATE_FIELDS.some((f) => record[f] !== undefined),
1334
+ own: !!options.entryModule && module === options.entryModule,
1335
+ };
1336
+ if (module)
1337
+ kind.module = module;
1338
+ if (typeof record.capability === "string")
1339
+ kind.capability = record.capability;
1340
+ if (extendsName)
1341
+ kind.extendsName = extendsName;
1342
+ if (parent && parentName)
1343
+ kind.extendsId = parentModule ? `${parentModule}.${parentName}` : parentName;
1344
+ // Only the entry module's gate is in hand — an imported library's
1345
+ // `exports.kinds` is stamped on the import, not on the definition, so a
1346
+ // claim about it here would be a guess.
1347
+ if (kind.own)
1348
+ kind.exported = exportedKinds.has(name);
1349
+ out.push(kind);
1350
+ }
1351
+ return out;
1352
+ }
1353
+ /** The CEL environment used to PARSE a chain out of an expression. One per
1354
+ * process: building it is the expensive half, and nothing here evaluates. */
1355
+ let parseEnv;
1356
+ /** Access chains an expression reads, or none when it does not parse — a syntax
1357
+ * error is the engine pass's to report, not this one's. */
1358
+ function accessChains(source) {
1359
+ try {
1360
+ parseEnv ??= buildCelEnvironment();
1361
+ return extractAccessChains(parseEnv.parse(source).ast);
1362
+ }
1363
+ catch {
1364
+ return [];
1365
+ }
1366
+ }
1367
+ /**
1368
+ * Every `resources.<name>…` read in one resource's CEL, as an edge.
1369
+ *
1370
+ * This is the dependency a manifest states without a slot: a config provider
1371
+ * read by five resources has five edges the reference graph cannot show, and an
1372
+ * observed-state read is the same shape one level in. Deduplicated per
1373
+ * (target, chain), since the same read at two sites is one fact about the pair.
1374
+ */
1375
+ function dataEdges(node, manifest, fromModule, resolveName, rowIdByPath, rowsByOwner) {
1376
+ const out = [];
1377
+ const seen = new Set();
1378
+ walkCelExpressions(manifest, "", (source, path) => {
1379
+ for (const chain of accessChains(source)) {
1380
+ if (chain[0] !== "resources" || chain.length < 2)
1381
+ continue;
1382
+ const targetName = chain[1];
1383
+ // `resources.<name>` is a bare name written in THIS module's scope, so it
1384
+ // resolves the way every other bare name does.
1385
+ const to = resolveName(targetName, fromModule);
1386
+ if (!to || to === node.id)
1387
+ continue;
1388
+ const read = chain.join(".");
1389
+ const key = `${to}\0${read}`;
1390
+ if (seen.has(key))
1391
+ continue;
1392
+ seen.add(key);
1393
+ const edge = {
1394
+ id: `${node.id}\0data\0${path}\0${read}`,
1395
+ from: node.id,
1396
+ to,
1397
+ toName: targetName,
1398
+ class: "data",
1399
+ use: [],
1400
+ slot: "cel",
1401
+ path,
1402
+ read,
1403
+ };
1404
+ const row = rowIdByPath.get(`${node.id}\0${path}`) ?? rowAt(rowsByOwner, node.id, path);
1405
+ if (row)
1406
+ edge.row = row;
1407
+ out.push(edge);
1408
+ }
1409
+ });
1410
+ return out;
1411
+ }