@telorun/analyzer 0.12.1 → 0.13.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 (45) 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 +15 -0
  4. package/dist/analyzer.d.ts.map +1 -1
  5. package/dist/analyzer.js +64 -84
  6. package/dist/builtins.d.ts.map +1 -1
  7. package/dist/builtins.js +25 -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 +109 -0
  20. package/dist/manifest-visitor.d.ts.map +1 -0
  21. package/dist/manifest-visitor.js +110 -0
  22. package/dist/schema-compat.d.ts +10 -0
  23. package/dist/schema-compat.d.ts.map +1 -1
  24. package/dist/schema-compat.js +32 -0
  25. package/dist/validate-cel-context.d.ts +14 -0
  26. package/dist/validate-cel-context.d.ts.map +1 -1
  27. package/dist/validate-cel-context.js +38 -0
  28. package/dist/validate-references.d.ts.map +1 -1
  29. package/dist/validate-references.js +117 -160
  30. package/dist/validate-unused-declarations.d.ts +25 -0
  31. package/dist/validate-unused-declarations.d.ts.map +1 -0
  32. package/dist/validate-unused-declarations.js +91 -0
  33. package/package.json +2 -2
  34. package/src/analysis-registry.ts +20 -0
  35. package/src/analyzer.ts +157 -169
  36. package/src/builtins.ts +25 -0
  37. package/src/cel-environment.ts +42 -1
  38. package/src/dependency-graph.ts +37 -52
  39. package/src/index.ts +11 -0
  40. package/src/kernel-globals.ts +22 -1
  41. package/src/manifest-visitor.ts +251 -0
  42. package/src/schema-compat.ts +32 -0
  43. package/src/validate-cel-context.ts +50 -0
  44. package/src/validate-references.ts +168 -211
  45. package/src/validate-unused-declarations.ts +95 -0
@@ -1,5 +1,6 @@
1
1
  import { isRefSentinel } from "@telorun/templating";
2
- import { isRefEntry, isScopeEntry, isSchemaFromEntry, isInlineResource, resolveFieldEntries, resolveFieldValues } from "./reference-field-map.js";
2
+ import { visitManifest } from "./manifest-visitor.js";
3
+ import { isInlineResource, resolveFieldEntries, resolveFieldValues } from "./reference-field-map.js";
3
4
  import { navigateJsonPointer } from "./schema-compat.js";
4
5
  import { REF_VALIDATION_SKIP_KINDS as SYSTEM_KINDS } from "./system-kinds.js";
5
6
  import { DiagnosticSeverity } from "./types.js";
@@ -147,142 +148,36 @@ export function validateReferences(resources, context) {
147
148
  const byName = new Map();
148
149
  for (const [name, list] of byNameAll)
149
150
  byName.set(name, list[0]);
150
- for (const r of resources) {
151
- if (!r.metadata?.name || !r.kind || SYSTEM_KINDS.has(r.kind))
152
- continue;
153
- // Use the expanded map so refs nested behind x-telo-schema-from get the
154
- // same kind-check / unresolved-name validation as locally-declared refs.
155
- // Falls back to the base map when aliasesByModule isn't supplied.
156
- const fieldMap = aliasesByModule
157
- ? registry.expandedFieldMapForResource(r, aliases, aliasesByModule)
158
- : registry.getFieldMapForKind(r.kind, aliases);
159
- if (!fieldMap)
160
- continue;
161
- const resourceLabel = `${r.kind}/${r.metadata.name}`;
162
- const resourceData = { kind: r.kind, name: r.metadata.name };
163
- const filePath = r.metadata?.source;
164
- // Collect scope visibility prefixes (JSON Pointer dot prefix) and their manifests.
165
- // scope field path flat array of ResourceManifest declared in that scope.
166
- const scopeManifestsByPointer = new Map();
167
- for (const [fieldPath, entry] of fieldMap) {
168
- if (!isScopeEntry(entry))
169
- continue;
170
- const raw = resolveFieldValues(r, fieldPath)
171
- .flatMap((v) => (Array.isArray(v) ? v : [v]))
172
- .filter((v) => !!v && typeof v === "object");
173
- const pointers = Array.isArray(entry.scope) ? entry.scope : [entry.scope];
174
- for (const pointer of pointers) {
175
- scopeManifestsByPointer.set(pointer, raw);
176
- }
177
- }
178
- const scopePrefixes = Array.from(scopeManifestsByPointer.keys()).map((p) => p.replace(/^\//, "").replace(/\//g, "."));
179
- for (const [fieldPath, entry] of fieldMap) {
180
- if (!isRefEntry(entry))
181
- continue;
182
- const inScope = scopePrefixes.some((prefix) => fieldPath === prefix ||
183
- fieldPath.startsWith(prefix + ".") ||
184
- fieldPath.startsWith(prefix + "["));
185
- // Scope manifests visible to this ref path.
186
- const visibleScopeManifests = [];
187
- if (inScope) {
188
- for (const [pointer, manifests] of scopeManifestsByPointer) {
189
- const prefix = pointer.replace(/^\//, "").replace(/\//g, ".");
190
- if (fieldPath === prefix ||
191
- fieldPath.startsWith(prefix + ".") ||
192
- fieldPath.startsWith(prefix + "[")) {
193
- visibleScopeManifests.push(...manifests);
194
- }
195
- }
196
- }
197
- for (const { value: val, path: concretePath } of resolveFieldEntries(r, fieldPath)) {
198
- if (!val)
199
- continue;
200
- // `!ref <name>` sentinel — bare resource name marked at parse time as a
201
- // reference. Look it up against the slot's x-telo-ref constraint exactly
202
- // like the legacy bare-string path; the only difference is the value's
203
- // shape (a TaggedSentinel rather than a raw string), which removed the
204
- // string/inline ambiguity at the source.
205
- if (isRefSentinel(val)) {
206
- const refName = val.source;
207
- const target = byName.get(refName) ?? visibleScopeManifests.find((m) => m.metadata?.name === refName);
208
- if (!target) {
209
- diagnostics.push({
210
- severity: DiagnosticSeverity.Error,
211
- code: "UNRESOLVED_REFERENCE",
212
- source: SOURCE,
213
- message: `${resourceLabel}: reference at '${concretePath}' → resource '${refName}' not found`,
214
- data: { resource: resourceData, filePath, path: concretePath },
215
- });
216
- continue;
217
- }
218
- const kindErrors = checkKind(target.kind, entry, registry, aliases);
219
- if (kindErrors.length > 0) {
220
- diagnostics.push({
221
- severity: DiagnosticSeverity.Error,
222
- code: "REFERENCE_KIND_MISMATCH",
223
- source: SOURCE,
224
- message: `${resourceLabel}: reference at '${concretePath}' → ${kindErrors.join("; ")}`,
225
- data: { resource: resourceData, filePath, path: concretePath },
226
- });
227
- }
228
- continue;
229
- }
230
- // Name-only reference (plain string) — look up by name to validate.
231
- // Qualified references use "Kind.Name" format (e.g. "Http.Api.PaymentApi");
232
- // extract the resource name from the last dot segment.
233
- if (typeof val === "string") {
234
- const lastDot = val.lastIndexOf(".");
235
- const refName = lastDot > 0 ? val.slice(lastDot + 1) : val;
236
- const refKindPrefix = lastDot > 0 ? val.slice(0, lastDot) : undefined;
237
- const target = byName.get(refName) ?? visibleScopeManifests.find((m) => m.metadata?.name === refName);
238
- if (!target) {
239
- // Cross-module reference: "Alias.ResourceName" (single dot, bare alias prefix).
240
- // The resource lives in the imported module's scope and can't be validated here.
241
- // Multi-dot prefixes like "Alias.Kind.Name" are local resources with qualified
242
- // kinds — those must be validated.
243
- if (refKindPrefix && !refKindPrefix.includes(".") && aliases.hasAlias(refKindPrefix)) {
244
- continue;
245
- }
246
- diagnostics.push({
247
- severity: DiagnosticSeverity.Error,
248
- code: "UNRESOLVED_REFERENCE",
249
- source: SOURCE,
250
- message: `${resourceLabel}: reference at '${concretePath}' → resource '${val}' not found`,
251
- data: { resource: resourceData, filePath, path: concretePath },
252
- });
253
- continue;
254
- }
255
- const kindErrors = checkKind(target.kind, entry, registry, aliases);
256
- if (kindErrors.length > 0) {
257
- diagnostics.push({
258
- severity: DiagnosticSeverity.Error,
259
- code: "REFERENCE_KIND_MISMATCH",
260
- source: SOURCE,
261
- message: `${resourceLabel}: reference at '${concretePath}' → ${kindErrors.join("; ")}`,
262
- data: { resource: resourceData, filePath, path: concretePath },
263
- });
264
- }
265
- continue;
266
- }
267
- if (typeof val !== "object")
268
- continue;
269
- const refVal = val;
270
- // Skip inline resources — Phase 2 normalization hasn't run yet.
271
- if (isInlineResource(refVal))
272
- continue;
273
- // 1. Structural check
274
- if (typeof refVal.kind !== "string" || typeof refVal.name !== "string") {
151
+ // Phase 3 per-ref validation. The walker supplies each ref site already
152
+ // resolved against the schema-from-expanded field map, with its source
153
+ // enclosure (`inScope`) and the scope manifests visible to it — so this
154
+ // handler only validates, it does not re-walk.
155
+ visitManifest(resources, registry, {
156
+ onRef: (e) => {
157
+ const r = e.source;
158
+ const resourceLabel = `${r.kind}/${r.metadata.name}`;
159
+ const resourceData = { kind: r.kind, name: r.metadata.name };
160
+ const filePath = r.metadata?.source;
161
+ const { value: val, concretePath, entry, visibleScopeManifests } = e;
162
+ // `!ref <name>` sentinel — bare resource name marked at parse time as a
163
+ // reference. Look it up against the slot's x-telo-ref constraint exactly
164
+ // like the legacy bare-string path; the only difference is the value's
165
+ // shape (a TaggedSentinel rather than a raw string), which removed the
166
+ // string/inline ambiguity at the source.
167
+ if (isRefSentinel(val)) {
168
+ const refName = val.source;
169
+ const target = byName.get(refName) ?? visibleScopeManifests.find((m) => m.metadata?.name === refName);
170
+ if (!target) {
275
171
  diagnostics.push({
276
172
  severity: DiagnosticSeverity.Error,
277
- code: "INVALID_REFERENCE",
173
+ code: "UNRESOLVED_REFERENCE",
278
174
  source: SOURCE,
279
- message: `${resourceLabel}: reference at '${concretePath}' must have string 'kind' and 'name' fields`,
175
+ message: `${resourceLabel}: reference at '${concretePath}' resource '${refName}' not found`,
280
176
  data: { resource: resourceData, filePath, path: concretePath },
281
177
  });
282
- continue;
178
+ return;
283
179
  }
284
- // 2. Kind check
285
- const kindErrors = checkKind(refVal.kind, entry, registry, aliases);
180
+ const kindErrors = checkKind(target.kind, entry, registry, aliases);
286
181
  if (kindErrors.length > 0) {
287
182
  diagnostics.push({
288
183
  severity: DiagnosticSeverity.Error,
@@ -292,38 +187,100 @@ export function validateReferences(resources, context) {
292
187
  data: { resource: resourceData, filePath, path: concretePath },
293
188
  });
294
189
  }
295
- // 3. Resolution check — resource with this name must exist.
296
- const exists = byName.has(refVal.name) ||
297
- visibleScopeManifests.some((m) => m.metadata?.name === refVal.name);
298
- if (!exists) {
190
+ return;
191
+ }
192
+ // Name-only reference (plain string) look up by name to validate.
193
+ // Qualified references use "Kind.Name" format (e.g. "Http.Api.PaymentApi");
194
+ // extract the resource name from the last dot segment.
195
+ if (typeof val === "string") {
196
+ const lastDot = val.lastIndexOf(".");
197
+ const refName = lastDot > 0 ? val.slice(lastDot + 1) : val;
198
+ const refKindPrefix = lastDot > 0 ? val.slice(0, lastDot) : undefined;
199
+ const target = byName.get(refName) ?? visibleScopeManifests.find((m) => m.metadata?.name === refName);
200
+ if (!target) {
201
+ // Cross-module reference: "Alias.ResourceName" (single dot, bare alias prefix).
202
+ // The resource lives in the imported module's scope and can't be validated here.
203
+ // Multi-dot prefixes like "Alias.Kind.Name" are local resources with qualified
204
+ // kinds — those must be validated.
205
+ if (refKindPrefix && !refKindPrefix.includes(".") && aliases.hasAlias(refKindPrefix)) {
206
+ return;
207
+ }
299
208
  diagnostics.push({
300
209
  severity: DiagnosticSeverity.Error,
301
210
  code: "UNRESOLVED_REFERENCE",
302
211
  source: SOURCE,
303
- message: `${resourceLabel}: reference at '${concretePath}' → resource '${refVal.name}' not found`,
212
+ message: `${resourceLabel}: reference at '${concretePath}' → resource '${val}' not found`,
213
+ data: { resource: resourceData, filePath, path: concretePath },
214
+ });
215
+ return;
216
+ }
217
+ const kindErrors = checkKind(target.kind, entry, registry, aliases);
218
+ if (kindErrors.length > 0) {
219
+ diagnostics.push({
220
+ severity: DiagnosticSeverity.Error,
221
+ code: "REFERENCE_KIND_MISMATCH",
222
+ source: SOURCE,
223
+ message: `${resourceLabel}: reference at '${concretePath}' → ${kindErrors.join("; ")}`,
304
224
  data: { resource: resourceData, filePath, path: concretePath },
305
225
  });
306
226
  }
227
+ return;
307
228
  }
308
- }
309
- }
229
+ if (typeof val !== "object")
230
+ return;
231
+ const refVal = val;
232
+ // Skip inline resources — Phase 2 normalization hasn't run yet.
233
+ if (isInlineResource(refVal))
234
+ return;
235
+ // 1. Structural check
236
+ if (typeof refVal.kind !== "string" || typeof refVal.name !== "string") {
237
+ diagnostics.push({
238
+ severity: DiagnosticSeverity.Error,
239
+ code: "INVALID_REFERENCE",
240
+ source: SOURCE,
241
+ message: `${resourceLabel}: reference at '${concretePath}' must have string 'kind' and 'name' fields`,
242
+ data: { resource: resourceData, filePath, path: concretePath },
243
+ });
244
+ return;
245
+ }
246
+ // 2. Kind check
247
+ const kindErrors = checkKind(refVal.kind, entry, registry, aliases);
248
+ if (kindErrors.length > 0) {
249
+ diagnostics.push({
250
+ severity: DiagnosticSeverity.Error,
251
+ code: "REFERENCE_KIND_MISMATCH",
252
+ source: SOURCE,
253
+ message: `${resourceLabel}: reference at '${concretePath}' → ${kindErrors.join("; ")}`,
254
+ data: { resource: resourceData, filePath, path: concretePath },
255
+ });
256
+ }
257
+ // 3. Resolution check — resource with this name must exist.
258
+ const exists = byName.has(refVal.name) ||
259
+ visibleScopeManifests.some((m) => m.metadata?.name === refVal.name);
260
+ if (!exists) {
261
+ diagnostics.push({
262
+ severity: DiagnosticSeverity.Error,
263
+ code: "UNRESOLVED_REFERENCE",
264
+ source: SOURCE,
265
+ message: `${resourceLabel}: reference at '${concretePath}' → resource '${refVal.name}' not found`,
266
+ data: { resource: resourceData, filePath, path: concretePath },
267
+ });
268
+ }
269
+ },
270
+ }, { aliases, aliasesByModule, skipKinds: SYSTEM_KINDS, expand: true });
310
271
  // Phase 3b — x-telo-schema-from validation.
311
272
  // For each field with a schemaFrom path expression, resolve the anchor ref to get the
312
273
  // concrete kind, navigate the JSON Pointer into that kind's definition schema, and
313
- // validate the field value against the resulting sub-schema.
314
- for (const r of resources) {
315
- if (!r.metadata?.name || !r.kind || SYSTEM_KINDS.has(r.kind))
316
- continue;
317
- const fieldMap = registry.getFieldMapForKind(r.kind, aliases);
318
- if (!fieldMap)
319
- continue;
320
- const resourceLabel = `${r.kind}/${r.metadata.name}`;
321
- const resourceData = { kind: r.kind, name: r.metadata.name };
322
- const filePath = r.metadata?.source;
323
- for (const [fieldPath, entry] of fieldMap) {
324
- if (!isSchemaFromEntry(entry))
325
- continue;
326
- const { schemaFrom } = entry;
274
+ // validate the field value against the resulting sub-schema. Driven off the base map
275
+ // (un-expanded) so each schema-from slot is seen as its own site.
276
+ visitManifest(resources, registry, {
277
+ onSchemaFrom: (e) => {
278
+ const r = e.source;
279
+ const fieldPath = e.fieldPath;
280
+ const resourceLabel = `${r.kind}/${r.metadata.name}`;
281
+ const resourceData = { kind: r.kind, name: r.metadata.name };
282
+ const filePath = r.metadata?.source;
283
+ const { schemaFrom } = e.entry;
327
284
  const isAbsolute = schemaFrom.startsWith("/");
328
285
  const expr = isAbsolute ? schemaFrom.slice(1) : schemaFrom;
329
286
  const slashIdx = expr.indexOf("/");
@@ -335,7 +292,7 @@ export function validateReferences(resources, context) {
335
292
  message: `${resourceLabel}: x-telo-schema-from "${schemaFrom}" must contain at least one "/" to separate anchor from JSON Pointer`,
336
293
  data: { resource: resourceData, filePath, path: fieldPath },
337
294
  });
338
- continue;
295
+ return;
339
296
  }
340
297
  const anchorName = expr.slice(0, slashIdx);
341
298
  const jsonPointer = "/" + expr.slice(slashIdx + 1);
@@ -360,7 +317,7 @@ export function validateReferences(resources, context) {
360
317
  message: `${resourceLabel}: x-telo-schema-from at '${fieldPath}' → cannot resolve alias '${anchorName}'`,
361
318
  data: { resource: resourceData, filePath, path: fieldPath },
362
319
  });
363
- continue;
320
+ return;
364
321
  }
365
322
  const targetDef = registry.resolve(targetKind);
366
323
  if (!targetDef?.schema) {
@@ -371,7 +328,7 @@ export function validateReferences(resources, context) {
371
328
  message: `${resourceLabel}: x-telo-schema-from at '${fieldPath}' → kind '${targetKind}' has no schema`,
372
329
  data: { resource: resourceData, filePath, path: fieldPath },
373
330
  });
374
- continue;
331
+ return;
375
332
  }
376
333
  const subSchema = navigateJsonPointer(targetDef.schema, jsonPointer);
377
334
  if (subSchema === undefined) {
@@ -382,7 +339,7 @@ export function validateReferences(resources, context) {
382
339
  message: `${resourceLabel}: x-telo-schema-from at '${fieldPath}' → kind '${targetKind}' has no schema path '${jsonPointer}'`,
383
340
  data: { resource: resourceData, filePath, path: fieldPath },
384
341
  });
385
- continue;
342
+ return;
386
343
  }
387
344
  for (const { value: fieldValue, path: concretePath } of resolveFieldEntries(r, fieldPath)) {
388
345
  if (fieldValue == null)
@@ -398,7 +355,7 @@ export function validateReferences(resources, context) {
398
355
  });
399
356
  }
400
357
  }
401
- continue;
358
+ return;
402
359
  }
403
360
  // Derive the anchor path in the resource config.
404
361
  let anchorPath;
@@ -413,7 +370,7 @@ export function validateReferences(resources, context) {
413
370
  }
414
371
  const anchorValues = resolveFieldValues(r, anchorPath);
415
372
  if (anchorValues.length === 0)
416
- continue; // anchor field not set — nothing to validate
373
+ return; // anchor field not set — nothing to validate
417
374
  const fieldEntries = resolveFieldEntries(r, fieldPath);
418
375
  for (let i = 0; i < fieldEntries.length; i++) {
419
376
  const { value: fieldValue, path: concretePath } = fieldEntries[i];
@@ -460,7 +417,7 @@ export function validateReferences(resources, context) {
460
417
  });
461
418
  }
462
419
  }
463
- }
464
- }
420
+ },
421
+ }, { aliases, aliasesByModule, skipKinds: SYSTEM_KINDS, expand: false });
465
422
  return diagnostics;
466
423
  }
@@ -0,0 +1,25 @@
1
+ import type { Environment } from "@marcbachmann/cel-js";
2
+ import type { ResourceManifest } from "@telorun/sdk";
3
+ import { type AnalysisDiagnostic } from "./types.js";
4
+ /**
5
+ * Warn about declared `variables` / `secrets` / `ports` entries that no CEL
6
+ * expression references. A declared-but-unconsumed entry is dead weight at
7
+ * best and misleading at worst (an unbound `ports` entry makes a runner
8
+ * advertise a port the app never listens on).
9
+ *
10
+ * Generic across all three namespaces. References are collected from every CEL
11
+ * expression (both `${{ … }}` and `!cel`, via `walkCelExpressions`) by
12
+ * extracting member-access chains: a `<ns>.<name>` chain marks `<name>` used.
13
+ * Dynamic access (`<ns>[expr]`, or the namespace passed whole, e.g.
14
+ * `keys(variables)`) yields a chain that stops at the namespace root — that
15
+ * can't be attributed to a name, so the whole namespace is conservatively
16
+ * suppressed to avoid false positives.
17
+ *
18
+ * Application-only: an Application's `variables` / `secrets` / `ports` flow
19
+ * exclusively through CEL (into resource fields, or into `Telo.Import` inputs),
20
+ * so unreferenced means dead. A `Telo.Library`'s `variables` / `secrets` are a
21
+ * public input contract consumed by its controllers — invisible to CEL
22
+ * analysis — so they are deliberately not flagged.
23
+ */
24
+ export declare function validateUnusedDeclarations(manifests: ResourceManifest[], celEnv: Environment): AnalysisDiagnostic[];
25
+ //# sourceMappingURL=validate-unused-declarations.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate-unused-declarations.d.ts","sourceRoot":"","sources":["../src/validate-unused-declarations.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAErD,OAAO,EAAE,KAAK,kBAAkB,EAAsB,MAAM,YAAY,CAAC;AASzE;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,0BAA0B,CACxC,SAAS,EAAE,gBAAgB,EAAE,EAC7B,MAAM,EAAE,WAAW,GAClB,kBAAkB,EAAE,CA2DtB"}
@@ -0,0 +1,91 @@
1
+ import { extractAccessChains, INDEX_SEGMENT, walkCelExpressions } from "@telorun/templating";
2
+ import { DiagnosticSeverity } from "./types.js";
3
+ const SOURCE = "telo-analyzer";
4
+ /** Module-doc namespaces whose entries are consumed via `<ns>.<name>` CEL
5
+ * access. One table drives the whole check — adding a namespace is an entry,
6
+ * not a branch. */
7
+ const NAMESPACES = ["variables", "secrets", "ports"];
8
+ /**
9
+ * Warn about declared `variables` / `secrets` / `ports` entries that no CEL
10
+ * expression references. A declared-but-unconsumed entry is dead weight at
11
+ * best and misleading at worst (an unbound `ports` entry makes a runner
12
+ * advertise a port the app never listens on).
13
+ *
14
+ * Generic across all three namespaces. References are collected from every CEL
15
+ * expression (both `${{ … }}` and `!cel`, via `walkCelExpressions`) by
16
+ * extracting member-access chains: a `<ns>.<name>` chain marks `<name>` used.
17
+ * Dynamic access (`<ns>[expr]`, or the namespace passed whole, e.g.
18
+ * `keys(variables)`) yields a chain that stops at the namespace root — that
19
+ * can't be attributed to a name, so the whole namespace is conservatively
20
+ * suppressed to avoid false positives.
21
+ *
22
+ * Application-only: an Application's `variables` / `secrets` / `ports` flow
23
+ * exclusively through CEL (into resource fields, or into `Telo.Import` inputs),
24
+ * so unreferenced means dead. A `Telo.Library`'s `variables` / `secrets` are a
25
+ * public input contract consumed by its controllers — invisible to CEL
26
+ * analysis — so they are deliberately not flagged.
27
+ */
28
+ export function validateUnusedDeclarations(manifests, celEnv) {
29
+ const moduleManifest = manifests.find((m) => m.kind === "Telo.Application");
30
+ if (!moduleManifest)
31
+ return [];
32
+ const declared = new Map();
33
+ for (const ns of NAMESPACES) {
34
+ const block = moduleManifest[ns];
35
+ if (block && typeof block === "object" && !Array.isArray(block)) {
36
+ const names = Object.keys(block);
37
+ if (names.length > 0)
38
+ declared.set(ns, names);
39
+ }
40
+ }
41
+ if (declared.size === 0)
42
+ return [];
43
+ const used = new Map(NAMESPACES.map((ns) => [ns, new Set()]));
44
+ const suppressed = new Set();
45
+ for (const m of manifests) {
46
+ walkCelExpressions(m, "", (expr, _path, engineName) => {
47
+ if (engineName !== "cel")
48
+ return;
49
+ let ast;
50
+ try {
51
+ ast = celEnv.parse(expr).ast;
52
+ }
53
+ catch {
54
+ return; // syntax errors are reported by the CEL engine pass
55
+ }
56
+ for (const chain of extractAccessChains(ast)) {
57
+ const ns = chain[0];
58
+ if (!used.has(ns))
59
+ continue;
60
+ const member = chain[1];
61
+ // No static member after the namespace root — either the namespace is
62
+ // used whole (`keys(ports)` → ["ports"]) or accessed dynamically
63
+ // (`ports[x]` → ["ports", "[*]"]). Neither can be attributed to a
64
+ // declared name, so suppress the namespace rather than false-positive.
65
+ if (member === undefined || member === INDEX_SEGMENT)
66
+ suppressed.add(ns);
67
+ else
68
+ used.get(ns).add(member);
69
+ }
70
+ });
71
+ }
72
+ const diagnostics = [];
73
+ const filePath = moduleManifest.metadata?.source;
74
+ for (const [ns, names] of declared) {
75
+ if (suppressed.has(ns))
76
+ continue;
77
+ const seen = used.get(ns);
78
+ for (const name of names) {
79
+ if (seen.has(name))
80
+ continue;
81
+ diagnostics.push({
82
+ severity: DiagnosticSeverity.Warning,
83
+ code: "UNUSED_DECLARATION",
84
+ source: SOURCE,
85
+ message: `${ns}.${name} is declared but never referenced in any CEL expression.`,
86
+ data: { filePath, path: `${ns}.${name}` },
87
+ });
88
+ }
89
+ }
90
+ return diagnostics;
91
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@telorun/analyzer",
3
- "version": "0.12.1",
3
+ "version": "0.13.0",
4
4
  "description": "Telo Analyzer - Static manifest validator for Telo manifests.",
5
5
  "keywords": [
6
6
  "telo",
@@ -42,7 +42,7 @@
42
42
  "ajv-formats": "^3.0.1",
43
43
  "jsonpath-plus": "^10.3.0",
44
44
  "yaml": "^2.8.3",
45
- "@telorun/templating": "0.3.0"
45
+ "@telorun/templating": "0.3.1"
46
46
  },
47
47
  "devDependencies": {
48
48
  "@types/node": "^20.0.0",
@@ -3,6 +3,7 @@ import { AliasResolver } from "./alias-resolver.js";
3
3
  import { KERNEL_BUILTINS } from "./builtins.js";
4
4
  import { DefinitionRegistry } from "./definition-registry.js";
5
5
  import { computeSuggestKind, computeValidUserFacingKinds } from "./kind-suggest.js";
6
+ import { visitManifest as runVisitManifest, type ManifestVisitor } from "./manifest-visitor.js";
6
7
  import { isRefEntry, isScopeEntry } from "./reference-field-map.js";
7
8
  import type { AnalysisContext } from "./types.js";
8
9
 
@@ -62,6 +63,25 @@ export class AnalysisRegistry {
62
63
  }
63
64
  }
64
65
 
66
+ /**
67
+ * Walks a manifest's annotation sites (refs, scopes, schema-from, CEL) via
68
+ * the shared manifest visitor, bound to this registry's definitions and
69
+ * aliases. The public seam for hosts (editor overview graph, tooling) that
70
+ * need the same site discovery the analyzer's own passes use, without
71
+ * reaching into the internal DefinitionRegistry.
72
+ */
73
+ visitManifest(
74
+ resources: ResourceManifest[],
75
+ visitor: ManifestVisitor,
76
+ opts?: { skipKinds?: ReadonlySet<string>; expand?: boolean },
77
+ ): void {
78
+ runVisitManifest(resources, this.defs, visitor, {
79
+ aliases: this.aliases,
80
+ aliasesByModule: this.aliasesByModule,
81
+ ...opts,
82
+ });
83
+ }
84
+
65
85
  /**
66
86
  * Returns the built-in kernel definitions. The underlying DefinitionRegistry already
67
87
  * seeds these on construction; this method exposes them so callers (e.g. the kernel's