@telorun/analyzer 0.12.1 → 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 (51) hide show
  1. package/dist/analysis-registry.d.ts +13 -0
  2. package/dist/analysis-registry.d.ts.map +1 -1
  3. package/dist/analysis-registry.js +15 -0
  4. package/dist/analyzer.d.ts.map +1 -1
  5. package/dist/analyzer.js +154 -83
  6. package/dist/builtins.d.ts.map +1 -1
  7. package/dist/builtins.js +85 -0
  8. package/dist/cel-environment.d.ts +1 -1
  9. package/dist/cel-environment.d.ts.map +1 -1
  10. package/dist/cel-environment.js +40 -2
  11. package/dist/dependency-graph.d.ts.map +1 -1
  12. package/dist/dependency-graph.js +41 -62
  13. package/dist/index.d.ts +2 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +1 -0
  16. package/dist/kernel-globals.d.ts +1 -1
  17. package/dist/kernel-globals.d.ts.map +1 -1
  18. package/dist/kernel-globals.js +19 -1
  19. package/dist/manifest-visitor.d.ts +124 -0
  20. package/dist/manifest-visitor.d.ts.map +1 -0
  21. package/dist/manifest-visitor.js +181 -0
  22. package/dist/reference-field-map.js +16 -0
  23. package/dist/resolve-throws-union.d.ts +10 -0
  24. package/dist/resolve-throws-union.d.ts.map +1 -1
  25. package/dist/resolve-throws-union.js +35 -7
  26. package/dist/schema-compat.d.ts +10 -0
  27. package/dist/schema-compat.d.ts.map +1 -1
  28. package/dist/schema-compat.js +32 -0
  29. package/dist/validate-cel-context.d.ts +14 -0
  30. package/dist/validate-cel-context.d.ts.map +1 -1
  31. package/dist/validate-cel-context.js +38 -0
  32. package/dist/validate-references.d.ts.map +1 -1
  33. package/dist/validate-references.js +124 -160
  34. package/dist/validate-unused-declarations.d.ts +25 -0
  35. package/dist/validate-unused-declarations.d.ts.map +1 -0
  36. package/dist/validate-unused-declarations.js +91 -0
  37. package/package.json +3 -3
  38. package/src/analysis-registry.ts +20 -0
  39. package/src/analyzer.ts +256 -168
  40. package/src/builtins.ts +85 -0
  41. package/src/cel-environment.ts +42 -1
  42. package/src/dependency-graph.ts +37 -52
  43. package/src/index.ts +11 -0
  44. package/src/kernel-globals.ts +22 -1
  45. package/src/manifest-visitor.ts +340 -0
  46. package/src/reference-field-map.ts +14 -0
  47. package/src/resolve-throws-union.ts +36 -8
  48. package/src/schema-compat.ts +32 -0
  49. package/src/validate-cel-context.ts +50 -0
  50. package/src/validate-references.ts +175 -211
  51. package/src/validate-unused-declarations.ts +95 -0
@@ -1,5 +1,5 @@
1
1
  import { isRefSentinel } from "@telorun/templating";
2
- import { isRefEntry, isScopeEntry, resolveFieldValues } from "./reference-field-map.js";
2
+ import { visitManifest } from "./manifest-visitor.js";
3
3
  import { DEPENDENCY_GRAPH_SKIP_KINDS as SYSTEM_KINDS } from "./system-kinds.js";
4
4
  const nodeKey = (kind, name) => `${kind}\0${name}`;
5
5
  /**
@@ -33,68 +33,47 @@ export function buildDependencyGraph(resources, registry, aliases, aliasesByModu
33
33
  const deps = new Map();
34
34
  for (const key of nodes.keys())
35
35
  deps.set(key, new Set());
36
- for (const r of resources) {
37
- if (!r.metadata?.name || !r.kind || SYSTEM_KINDS.has(r.kind))
38
- continue;
39
- const sourceKey = nodeKey(r.kind, r.metadata.name);
40
- // Use the expanded map so refs nested behind x-telo-schema-from contribute
41
- // edges to the DAG. Without these, a parent (e.g. Http.Server) can init
42
- // before its extracted encoder and Phase 5 injection fires against a
43
- // not-yet-created dependency.
44
- const fieldMap = aliases && aliasesByModule
45
- ? registry.expandedFieldMapForResource(r, aliases, aliasesByModule)
46
- : registry.getFieldMapForKind(r.kind, aliases);
47
- if (!fieldMap)
48
- continue;
49
- // Collect names of resources declared inside scope fields — these are initialized
50
- // on-demand at runtime, not at boot, so edges pointing to them are excluded from the DAG.
51
- const scopedNames = new Set();
52
- for (const [scopeFieldPath, entry] of fieldMap) {
53
- if (!isScopeEntry(entry))
54
- continue;
55
- const scopeVal = r[scopeFieldPath];
56
- if (!Array.isArray(scopeVal))
57
- continue;
58
- for (const item of scopeVal) {
59
- const name = item?.metadata?.name;
60
- if (typeof name === "string")
61
- scopedNames.add(name);
36
+ // Names of resources declared inside the *current* resource's scope fields —
37
+ // initialized on-demand at runtime, not at boot, so edges pointing to them
38
+ // are excluded. Scoping is per-source-resource: an edge A → B is dropped only
39
+ // when B is declared inside A's own scope (the visitor's ScopeBoundary fires
40
+ // before that resource's RefSites, so this is set before any edge is added).
41
+ let scopedNames = new Set();
42
+ // Expanded map so refs nested behind x-telo-schema-from contribute edges to
43
+ // the DAG. Without these, a parent (e.g. Http.Server) can init before its
44
+ // extracted encoder and Phase 5 injection fires against a not-yet-created
45
+ // dependency.
46
+ visitManifest(resources, registry, {
47
+ onScope: (e) => {
48
+ scopedNames = e.enclosedNames;
49
+ },
50
+ onRef: (e) => {
51
+ const sourceKey = nodeKey(e.source.kind, e.source.metadata.name);
52
+ const val = e.value;
53
+ // `!ref <name>` sentinel — look up the target's kind from the name
54
+ // (resources are unique by name) so the edge carries the concrete kind,
55
+ // matching the {kind, name} edge shape below.
56
+ if (isRefSentinel(val)) {
57
+ const refName = val.source;
58
+ if (scopedNames.has(refName))
59
+ return;
60
+ const node = nodesByName.get(refName);
61
+ if (node)
62
+ deps.get(sourceKey).add(nodeKey(node.kind, node.name));
63
+ return;
62
64
  }
63
- }
64
- for (const [fieldPath, entry] of fieldMap) {
65
- if (!isRefEntry(entry))
66
- continue;
67
- for (const val of resolveFieldValues(r, fieldPath)) {
68
- if (!val)
69
- continue;
70
- // `!ref <name>` sentinel — look up the target's kind from the
71
- // name (resources are unique by name) so the edge carries the
72
- // concrete kind, matching the {kind, name} edge shape below.
73
- if (isRefSentinel(val)) {
74
- const refName = val.source;
75
- if (scopedNames.has(refName))
76
- continue;
77
- const node = nodesByName.get(refName);
78
- if (node) {
79
- deps.get(sourceKey).add(nodeKey(node.kind, node.name));
80
- }
81
- continue;
82
- }
83
- if (typeof val !== "object")
84
- continue;
85
- const ref = val;
86
- if (!ref.kind || !ref.name)
87
- continue;
88
- // Edges to scoped resources are runtime deps, not boot-time deps — exclude from DAG
89
- if (scopedNames.has(ref.name))
90
- continue;
91
- const targetKey = nodeKey(ref.kind, ref.name);
92
- if (nodes.has(targetKey)) {
93
- deps.get(sourceKey).add(targetKey);
94
- }
95
- }
96
- }
97
- }
65
+ if (typeof val !== "object")
66
+ return;
67
+ const ref = val;
68
+ if (!ref.kind || !ref.name)
69
+ return;
70
+ if (scopedNames.has(ref.name))
71
+ return;
72
+ const targetKey = nodeKey(ref.kind, ref.name);
73
+ if (nodes.has(targetKey))
74
+ deps.get(sourceKey).add(targetKey);
75
+ },
76
+ }, { aliases, aliasesByModule, skipKinds: SYSTEM_KINDS, expand: true });
98
77
  // --- Kahn's topological sort ---
99
78
  // in-degree[X] = number of X's dependencies (size of deps[X])
100
79
  // reverse[dep] = set of nodes that depend on dep (for degree decrement)
package/dist/index.d.ts CHANGED
@@ -2,6 +2,8 @@ export { AnalysisRegistry } from "./analysis-registry.js";
2
2
  export { StaticAnalyzer } from "./analyzer.js";
3
3
  export type { GraphLoadError, ImportEdge, LoadedFile, LoadedGraph, LoadedModule, ParseError, } from "./loaded-types.js";
4
4
  export { flattenForAnalyzer, flattenLoadedModule } from "./flatten-for-analyzer.js";
5
+ export { visitManifest } from "./manifest-visitor.js";
6
+ export type { CelSiteEvent, ManifestVisitor, RefSiteEvent, ResourceEnterEvent, ResourceExitEvent, ScopeBoundaryEvent, SchemaFromSiteEvent, VisitOptions, } from "./manifest-visitor.js";
5
7
  export { Loader } from "./manifest-loader.js";
6
8
  export { isModuleKind, MODULE_KINDS } from "./module-kinds.js";
7
9
  export type { ModuleKind } from "./module-kinds.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAA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export { StaticAnalyzer } from "./analyzer.js";
3
3
  export { flattenForAnalyzer, flattenLoadedModule } from "./flatten-for-analyzer.js";
4
+ export { visitManifest } from "./manifest-visitor.js";
4
5
  export { Loader } from "./manifest-loader.js";
5
6
  export { isModuleKind, MODULE_KINDS } from "./module-kinds.js";
6
7
  export { parseLoadedFile } from "./parse-loaded-file.js";
@@ -10,7 +10,7 @@ import type { ResourceManifest } from "@telorun/sdk";
10
10
  * There is no `imports` namespace at runtime — import snapshots are stored
11
11
  * under `resources.<alias>`.
12
12
  */
13
- export declare const KERNEL_GLOBAL_NAMES: readonly ["variables", "secrets", "resources", "env"];
13
+ export declare const KERNEL_GLOBAL_NAMES: readonly ["variables", "secrets", "resources", "ports", "env"];
14
14
  /**
15
15
  * Build a typed JSON Schema describing the kernel globals available in the
16
16
  * given manifest set. Used to merge into `x-telo-context` schemas so that
@@ -1 +1 @@
1
- {"version":3,"file":"kernel-globals.d.ts","sourceRoot":"","sources":["../src/kernel-globals.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAGrD;;;;;;;;;;GAUG;AACH,eAAO,MAAM,mBAAmB,uDAAwD,CAAC;AASzF;;;;;;;;;;;;;GAaG;AACH,wBAAgB,wBAAwB,CACtC,SAAS,EAAE,gBAAgB,EAAE,GAC5B,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAiCrB;AAwBD;;;;;;;GAOG;AACH,wBAAgB,6BAA6B,CAC3C,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAClC,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GACjC,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CASrB"}
1
+ {"version":3,"file":"kernel-globals.d.ts","sourceRoot":"","sources":["../src/kernel-globals.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAGrD;;;;;;;;;;GAUG;AACH,eAAO,MAAM,mBAAmB,gEAAiE,CAAC;AASlG;;;;;;;;;;;;;GAaG;AACH,wBAAgB,wBAAwB,CACtC,SAAS,EAAE,gBAAgB,EAAE,GAC5B,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAkCrB;AA4CD;;;;;;;GAOG;AACH,wBAAgB,6BAA6B,CAC3C,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAClC,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GACjC,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CASrB"}
@@ -10,7 +10,7 @@ import { residualEntrySchemaMap } from "./residual-schema.js";
10
10
  * There is no `imports` namespace at runtime — import snapshots are stored
11
11
  * under `resources.<alias>`.
12
12
  */
13
- export const KERNEL_GLOBAL_NAMES = ["variables", "secrets", "resources", "env"];
13
+ export const KERNEL_GLOBAL_NAMES = ["variables", "secrets", "resources", "ports", "env"];
14
14
  const SYSTEM_KINDS = new Set([
15
15
  "Telo.Definition",
16
16
  "Telo.Application",
@@ -55,10 +55,28 @@ export function buildKernelGlobalsSchema(manifests) {
55
55
  properties: resourceProps,
56
56
  additionalProperties: false,
57
57
  },
58
+ ports: buildPortsSchema(moduleManifest?.ports),
58
59
  env: { type: "object", additionalProperties: true },
59
60
  },
60
61
  };
61
62
  }
63
+ /** Build the closed `ports` chain-access schema: each declared port is an
64
+ * integer, so `ports.<name>` resolves and `ports.typo` (or member access past
65
+ * a port, like `ports.http.foo`) is flagged. Falls back to an open map when
66
+ * the module declares no ports. */
67
+ function buildPortsSchema(ports) {
68
+ if (!ports || typeof ports !== "object" || Array.isArray(ports)) {
69
+ return { type: "object", additionalProperties: true };
70
+ }
71
+ const props = {};
72
+ for (const name of Object.keys(ports)) {
73
+ props[name] = { type: "integer" };
74
+ }
75
+ if (Object.keys(props).length === 0) {
76
+ return { type: "object", additionalProperties: true };
77
+ }
78
+ return { type: "object", properties: props, additionalProperties: false };
79
+ }
62
80
  /** Wrap a JSON Schema property map (like `Telo.Application.variables`) into a
63
81
  * closed object schema suitable for chain-access validation. For Application
64
82
  * entries the per-entry shape carries kernel-specific keys (`env`, `default`)
@@ -0,0 +1,124 @@
1
+ import type { ResourceDefinition, ResourceManifest } from "@telorun/sdk";
2
+ import type { AliasResolver } from "./alias-resolver.js";
3
+ import type { DefinitionRegistry } from "./definition-registry.js";
4
+ import { type RefFieldEntry, type SchemaFromFieldEntry } from "./reference-field-map.js";
5
+ /**
6
+ * One descent surface over a manifest's resources, emitting the annotation
7
+ * sites every analyzer pass needs. It replaces the iteration scaffolding that
8
+ * `validate-references`, `dependency-graph`, and the analyzer's CEL walk each
9
+ * reimplemented (field-map fetch, scope collection, ref/schema-from iteration,
10
+ * CEL expression walk + context matching).
11
+ *
12
+ * Two discovery mechanics ride one per-resource pass:
13
+ *
14
+ * - **Path-driven** — ref / scope / schema-from sites come from the resource's
15
+ * per-kind field map (`RefSite`, `ScopeBoundary`, `SchemaFromSite`). This is
16
+ * map iteration resolved against the resource value, not a node-by-node tree
17
+ * descent; the field map already unifies all three annotation types.
18
+ * - **Value-tree-driven** — compiled `${{...}}` / `!cel` nodes are found by
19
+ * scanning the resource value tree (`CelSite`). CEL can sit in any string
20
+ * field, including ones the field map never lists, so its discovery is
21
+ * fundamentally not path-driven; the field map only supplies the matched
22
+ * `x-telo-context` schema at the enclosing path.
23
+ *
24
+ * Handlers are optional (Babel-style): the walker computes and emits only what
25
+ * the visitor subscribes to, and skips the work behind absent handlers.
26
+ *
27
+ * **Scope is per-resource.** `ScopeBoundary` is emitted once per resource at
28
+ * enter time, before that resource's `RefSite`s, carrying both the source
29
+ * enclosure prefixes (for refs written *inside* a scope) and the enclosed
30
+ * resource-name set (for consumers that drop edges to scoped targets). No
31
+ * cross-resource ordering or global enclosed-name union is implied — every
32
+ * consumer's scope decision is local to the resource being visited, matching
33
+ * the semantics each pass had before this walker existed.
34
+ */
35
+ export interface ResourceEnterEvent {
36
+ source: ResourceManifest;
37
+ /** Resolved definition for the resource's kind, or undefined when unknown. */
38
+ definition?: ResourceDefinition;
39
+ }
40
+ export interface ResourceExitEvent {
41
+ source: ResourceManifest;
42
+ }
43
+ export interface ScopeBoundaryEvent {
44
+ source: ResourceManifest;
45
+ /** Dot-form prefixes of every `x-telo-scope` field on this resource. */
46
+ scopePrefixes: string[];
47
+ /** Scope-field JSON Pointer → manifests declared within that scope. */
48
+ manifestsByPointer: Map<string, ResourceManifest[]>;
49
+ /** Names of every resource declared inside this resource's scopes. Used by
50
+ * the dependency graph to drop boot edges to scoped (on-demand) targets. */
51
+ enclosedNames: Set<string>;
52
+ }
53
+ export interface RefSiteEvent {
54
+ source: ResourceManifest;
55
+ /** Field-map path with `[]` / `{}` markers (e.g. `steps[].invoke`). */
56
+ fieldPath: string;
57
+ /** Concrete path with `[N]` / map keys, matching `buildPositionIndex` keys. */
58
+ concretePath: string;
59
+ /** The ref value at this concrete site (sentinel, string, or `{kind,name}`). */
60
+ value: unknown;
61
+ /** The ref constraint (`refs[]`, `isArray`, optional `context`). */
62
+ entry: RefFieldEntry;
63
+ /** True when `fieldPath` falls within one of this resource's scope prefixes —
64
+ * source enclosure, used to scope a ref's candidate set. */
65
+ inScope: boolean;
66
+ /** Scope manifests visible to this ref path (non-empty only when `inScope`). */
67
+ visibleScopeManifests: ResourceManifest[];
68
+ /** True when the site was found by value-tree scanning rather than the field
69
+ * map (only when `discoverNestedRefs` is set) — a ref nested behind a `$ref`
70
+ * the field map doesn't descend (e.g. `Run.Sequence` `steps[].invoke`).
71
+ * Nested sites carry no x-telo-ref constraint (`entry.refs` is empty) and no
72
+ * scope info; `concretePath` still points at the exact location, so consumers
73
+ * can anchor to it. */
74
+ nested?: boolean;
75
+ }
76
+ export interface SchemaFromSiteEvent {
77
+ source: ResourceManifest;
78
+ /** Field-map path of the `x-telo-schema-from` slot. */
79
+ fieldPath: string;
80
+ entry: SchemaFromFieldEntry;
81
+ }
82
+ export interface CelSiteEvent {
83
+ source: ResourceManifest;
84
+ /** Concrete dotted path of the expression (from `walkCelExpressions`). */
85
+ path: string;
86
+ /** The CEL source expression. */
87
+ expr: string;
88
+ /** Engine that owns the expression (`cel`, `literal`, …). */
89
+ engineName: string;
90
+ /** Raw `x-telo-context` schema matched at the enclosing path, if any. The
91
+ * consumer resolves `x-telo-context-*` annotations and merges its own
92
+ * globals — the walker only does the path → context match. */
93
+ contextSchema?: Record<string, any>;
94
+ /** Scope of the matched context (e.g. `$.routes[*].handler`), if matched. */
95
+ matchedScope?: string;
96
+ }
97
+ export interface ManifestVisitor {
98
+ onResourceEnter?(e: ResourceEnterEvent): void;
99
+ onScope?(e: ScopeBoundaryEvent): void;
100
+ onRef?(e: RefSiteEvent): void;
101
+ onSchemaFrom?(e: SchemaFromSiteEvent): void;
102
+ onCel?(e: CelSiteEvent): void;
103
+ onResourceExit?(e: ResourceExitEvent): void;
104
+ }
105
+ export interface VisitOptions {
106
+ aliases?: AliasResolver;
107
+ aliasesByModule?: Map<string, AliasResolver>;
108
+ /** Resource kinds to skip entirely (kind blueprints, import metadata, …). */
109
+ skipKinds?: ReadonlySet<string>;
110
+ /** When true, ref / scope sites come from the schema-from-expanded field map
111
+ * so refs nested behind `x-telo-schema-from` are surfaced. `SchemaFromSite`
112
+ * events are always emitted from the base map regardless of this flag. */
113
+ expand?: boolean;
114
+ /** When true, additionally discover refs by scanning each resource's value
115
+ * tree for `!ref` sentinels and `{kind, name}` reference objects — surfacing
116
+ * refs the field map never lists because they sit behind a `$ref` it doesn't
117
+ * descend (notably `Run.Sequence` step `invoke`s). Emitted as `RefSite`s with
118
+ * `nested: true`, deduped against the field-map sites by concrete path.
119
+ * Opt-in: the validators / dependency graph must NOT enable it (those refs
120
+ * are runtime-resolved, not boot dependencies). */
121
+ discoverNestedRefs?: boolean;
122
+ }
123
+ export declare function visitManifest(resources: ResourceManifest[], registry: DefinitionRegistry, visitor: ManifestVisitor, options?: VisitOptions): void;
124
+ //# sourceMappingURL=manifest-vis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AAsDD,wBAAgB,aAAa,CAC3B,SAAS,EAAE,gBAAgB,EAAE,EAC7B,QAAQ,EAAE,kBAAkB,EAC5B,OAAO,EAAE,eAAe,EACxB,OAAO,GAAE,YAAiB,GACzB,IAAI,CA4IN"}
@@ -0,0 +1,181 @@
1
+ import { isRefSentinel, isTaggedSentinel, walkCelExpressions } from "@telorun/templating";
2
+ import { isRefEntry, isSchemaFromEntry, isScopeEntry, resolveFieldEntries, resolveFieldValues, } from "./reference-field-map.js";
3
+ import { extractContextsFromSchema, pathMatchesScope } from "./validate-cel-context.js";
4
+ /** Synthetic entry for a value-tree-discovered ref — these carry no declared
5
+ * x-telo-ref constraint. */
6
+ const NESTED_REF_ENTRY = { refs: [], isArray: false };
7
+ /** Scans a value tree for ref-shaped values, emitting each with its concrete
8
+ * path. Recognizes `!ref <name>` sentinels and named `{kind, name}` reference
9
+ * objects. Other tagged sentinels (`!cel`, `!literal`) and precompiled nodes
10
+ * are leaves. Path format matches `resolveFieldEntries` / `walkCelExpressions`
11
+ * (`a.b[0].c`).
12
+ *
13
+ * Stops at every `{kind, …}` resource boundary: a named ref is emitted, an
14
+ * inline resource (`{kind}` with no name) is left alone, and **neither is
15
+ * descended into**. A nested resource's own refs belong to its inner topology,
16
+ * not the enclosing node — e.g. an inline `Sql.Exec` step's `connection` is the
17
+ * Exec's dependency, not the surrounding `Run.Sequence`'s. The scan is started
18
+ * per top-level field (not on the resource object) so the resource's own
19
+ * `kind` doesn't trip this boundary. */
20
+ function walkRefValues(value, path, cb) {
21
+ if (isRefSentinel(value)) {
22
+ cb(value, path);
23
+ return;
24
+ }
25
+ if (isTaggedSentinel(value))
26
+ return;
27
+ if (Array.isArray(value)) {
28
+ value.forEach((v, i) => walkRefValues(v, `${path}[${i}]`, cb));
29
+ return;
30
+ }
31
+ if (value === null || typeof value !== "object")
32
+ return;
33
+ if (value.__compiled)
34
+ return;
35
+ const obj = value;
36
+ if (typeof obj.kind === "string") {
37
+ // Resource boundary — emit if it's a named ref, then stop descending.
38
+ if (typeof obj.name === "string")
39
+ cb(value, path);
40
+ return;
41
+ }
42
+ for (const [k, v] of Object.entries(obj)) {
43
+ walkRefValues(v, path ? `${path}.${k}` : k, cb);
44
+ }
45
+ }
46
+ const scopePrefixOf = (pointer) => pointer.replace(/^\//, "").replace(/\//g, ".");
47
+ const pathUnderPrefix = (fieldPath, prefix) => fieldPath === prefix ||
48
+ fieldPath.startsWith(prefix + ".") ||
49
+ fieldPath.startsWith(prefix + "[");
50
+ export function visitManifest(resources, registry, visitor, options = {}) {
51
+ const { aliases, aliasesByModule, skipKinds, expand, discoverNestedRefs } = options;
52
+ const wantsRefs = !!visitor.onRef;
53
+ const wantsScope = !!visitor.onScope;
54
+ const wantsSchemaFrom = !!visitor.onSchemaFrom;
55
+ const wantsCel = !!visitor.onCel;
56
+ const wantsNested = wantsRefs && !!discoverNestedRefs;
57
+ for (const r of resources) {
58
+ if (!r.metadata?.name || !r.kind)
59
+ continue;
60
+ if (skipKinds?.has(r.kind))
61
+ continue;
62
+ const resolvedKind = aliases?.resolveKind(r.kind);
63
+ const definition = registry.resolve(r.kind) ??
64
+ (resolvedKind ? registry.resolve(resolvedKind) : undefined);
65
+ visitor.onResourceEnter?.({ source: r, definition });
66
+ // Concrete paths emitted from the field map — so the value-tree scan below
67
+ // doesn't re-emit a ref the field map already covered.
68
+ const emittedRefPaths = wantsNested ? new Set() : null;
69
+ if (wantsRefs || wantsScope || wantsSchemaFrom) {
70
+ const baseMap = aliases
71
+ ? registry.getFieldMapForKind(r.kind, aliases)
72
+ : registry.getFieldMap(r.kind);
73
+ // Expanded map drives ref/scope sites when requested; schema-from sites
74
+ // come from the base map (expansion replaces them with nested refs).
75
+ const refScopeMap = expand && aliases && aliasesByModule
76
+ ? registry.expandedFieldMapForResource(r, aliases, aliasesByModule)
77
+ : baseMap;
78
+ if (refScopeMap && (wantsRefs || wantsScope)) {
79
+ const manifestsByPointer = new Map();
80
+ for (const [fieldPath, entry] of refScopeMap) {
81
+ if (!isScopeEntry(entry))
82
+ continue;
83
+ const raw = resolveFieldValues(r, fieldPath)
84
+ .flatMap((v) => (Array.isArray(v) ? v : [v]))
85
+ .filter((v) => !!v && typeof v === "object");
86
+ const pointers = Array.isArray(entry.scope) ? entry.scope : [entry.scope];
87
+ for (const pointer of pointers)
88
+ manifestsByPointer.set(pointer, raw);
89
+ }
90
+ const scopePrefixes = Array.from(manifestsByPointer.keys()).map(scopePrefixOf);
91
+ if (wantsScope) {
92
+ const enclosedNames = new Set();
93
+ for (const manifests of manifestsByPointer.values()) {
94
+ for (const m of manifests) {
95
+ const name = m.metadata?.name;
96
+ if (typeof name === "string")
97
+ enclosedNames.add(name);
98
+ }
99
+ }
100
+ visitor.onScope({ source: r, scopePrefixes, manifestsByPointer, enclosedNames });
101
+ }
102
+ if (wantsRefs) {
103
+ for (const [fieldPath, entry] of refScopeMap) {
104
+ if (!isRefEntry(entry))
105
+ continue;
106
+ const inScope = scopePrefixes.some((prefix) => pathUnderPrefix(fieldPath, prefix));
107
+ const visibleScopeManifests = [];
108
+ if (inScope) {
109
+ for (const [pointer, manifests] of manifestsByPointer) {
110
+ if (pathUnderPrefix(fieldPath, scopePrefixOf(pointer))) {
111
+ visibleScopeManifests.push(...manifests);
112
+ }
113
+ }
114
+ }
115
+ for (const { value, path: concretePath } of resolveFieldEntries(r, fieldPath)) {
116
+ if (!value)
117
+ continue;
118
+ emittedRefPaths?.add(concretePath);
119
+ visitor.onRef({
120
+ source: r,
121
+ fieldPath,
122
+ concretePath,
123
+ value,
124
+ entry,
125
+ inScope,
126
+ visibleScopeManifests,
127
+ });
128
+ }
129
+ }
130
+ }
131
+ }
132
+ if (wantsSchemaFrom && baseMap) {
133
+ for (const [fieldPath, entry] of baseMap) {
134
+ if (!isSchemaFromEntry(entry))
135
+ continue;
136
+ visitor.onSchemaFrom({ source: r, fieldPath, entry });
137
+ }
138
+ }
139
+ }
140
+ // Value-tree-driven nested ref discovery — refs the field map can't reach
141
+ // because they sit behind a `$ref` it doesn't descend (e.g. Run.Sequence
142
+ // step `invoke`s). Deduped against the field-map sites by concrete path.
143
+ // Scanned per top-level field so the resource's own `kind` isn't treated as
144
+ // a resource boundary by `walkRefValues`.
145
+ if (wantsNested) {
146
+ const emitNested = (value, path) => {
147
+ if (emittedRefPaths.has(path))
148
+ return;
149
+ visitor.onRef({
150
+ source: r,
151
+ fieldPath: path,
152
+ concretePath: path,
153
+ value,
154
+ entry: NESTED_REF_ENTRY,
155
+ inScope: false,
156
+ visibleScopeManifests: [],
157
+ nested: true,
158
+ });
159
+ };
160
+ for (const [key, value] of Object.entries(r)) {
161
+ walkRefValues(value, key, emitNested);
162
+ }
163
+ }
164
+ if (wantsCel) {
165
+ const contexts = definition?.schema ? extractContextsFromSchema(definition.schema) : [];
166
+ walkCelExpressions(r, "", (expr, path, engineName) => {
167
+ let contextSchema;
168
+ let matchedScope;
169
+ for (const ctx of contexts) {
170
+ if (pathMatchesScope(path, ctx.scope)) {
171
+ contextSchema = ctx.schema;
172
+ matchedScope = ctx.scope;
173
+ break;
174
+ }
175
+ }
176
+ visitor.onCel({ source: r, path, expr, engineName, contextSchema, matchedScope });
177
+ });
178
+ }
179
+ visitor.onResourceExit?.({ source: r });
180
+ }
181
+ }
@@ -157,6 +157,22 @@ function traverseNode(node, path, map, root, visitedRefs = new Set()) {
157
157
  if (node["x-telo-context"])
158
158
  entry.context = node["x-telo-context"];
159
159
  map.set(path, entry);
160
+ // A node can mix item-level ref branches (a bare string / `{kind, name}`)
161
+ // with object branches that carry their OWN nested refs — e.g. Application
162
+ // `targets`: a bare ref vs inline `{ invoke }` vs gated `{ ref }`. Descend
163
+ // into the variant objects so those nested slots register too (and their
164
+ // `!ref` sentinels resolve). Pure x-telo-ref branches have no properties
165
+ // and contribute nothing here.
166
+ for (const variantKey of ["oneOf", "anyOf", "allOf"]) {
167
+ const variants = node[variantKey];
168
+ if (!Array.isArray(variants))
169
+ continue;
170
+ for (const variant of variants) {
171
+ if (!variant || typeof variant !== "object")
172
+ continue;
173
+ traverseVariant(variant, path, map, root, visitedRefs);
174
+ }
175
+ }
160
176
  return;
161
177
  }
162
178
  // Array — recurse into items
@@ -4,6 +4,10 @@ import type { DefinitionRegistry } from "./definition-registry.js";
4
4
  export interface ThrowsCodeMeta {
5
5
  data?: Record<string, any>;
6
6
  }
7
+ /** Code a non-`InvokeError` failure surfaces as inside a `catch` block. Mirrors
8
+ * `PLAIN_ERROR_CODE` in `@telorun/run`'s `toSequenceError`: any invoke can throw
9
+ * a plain error, which the catch sees as `error.code === "INTERNAL_ERROR"`. */
10
+ export declare const PLAIN_ERROR_CODE = "INTERNAL_ERROR";
7
11
  export interface ThrowsUnion {
8
12
  /** Code → per-code metadata (data schema, etc). Keys are the declared codes. */
9
13
  codes: Map<string, ThrowsCodeMeta>;
@@ -12,6 +16,12 @@ export interface ThrowsUnion {
12
16
  * an unknown kind was encountered, or a cycle short-circuited resolution.
13
17
  * Callers must treat unbounded unions as requiring a catch-all entry. */
14
18
  unbounded: boolean;
19
+ /** True when the block can fail with a non-`InvokeError` (any `invoke:` step).
20
+ * Such a failure surfaces inside an enclosing `catch` as `PLAIN_ERROR_CODE`,
21
+ * so a `throw: { code: "${{ error.code }}" }` rethrow can propagate it. Not
22
+ * injected into `codes` — only seeds `enclosingTryCodes` at a try/catch site,
23
+ * leaving non-rethrow unions untouched. */
24
+ canThrowPlain?: boolean;
15
25
  }
16
26
  export interface ResolveCtx {
17
27
  allManifests: ResourceManifest[];
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-throws-union.d.ts","sourceRoot":"","sources":["../src/resolve-throws-union.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAsB,gBAAgB,EAAE,MAAM,cAAc,CAAC;AACzE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAEnE,MAAM,WAAW,cAAc;IAC7B,IAAI,CAAC,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