@telorun/kernel 0.82.1 → 0.83.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.
@@ -1,11 +1,30 @@
1
- import { AnalysisRegistry, DiagnosticSeverity, authoredModuleMetadata, foldIntegrity, parseExportEntry, StaticAnalyzer } from "@telorun/analyzer";
2
- import type { ResourceInstance } from "@telorun/sdk";
3
- import { RuntimeError } from "@telorun/sdk";
1
+ import {
2
+ AnalysisRegistry,
3
+ DiagnosticSeverity,
4
+ authoredModuleMetadata,
5
+ foldIntegrity,
6
+ isInjectedDeclaration,
7
+ parseExportEntry,
8
+ readLibraryLifecycle,
9
+ readResourceInputs,
10
+ readSuppliedResources,
11
+ StaticAnalyzer,
12
+ } from "@telorun/analyzer";
13
+ import type { ParsedExportEntry } from "@telorun/analyzer";
14
+ import type { ResourceInstance, ResourceManifest } from "@telorun/sdk";
15
+ import { RuntimeError, TEARDOWN_LAST } from "@telorun/sdk";
4
16
  import { publishedPropsOf } from "../../evaluation-context.js";
5
17
  import type { BuiltinControllerContext } from "../../internal-context.js";
6
18
  import { buildScopeConfig, type LoggingManifestBlock } from "../../logging/kernel-logging.js";
7
19
  import { ModuleContext } from "../../module-context.js";
8
20
  import { isDefaultPolicy, normalizeRuntime } from "../../runtime-registry.js";
21
+ import {
22
+ assertNoSharedOverride,
23
+ assertSharedInputsAgree,
24
+ rootContextOf,
25
+ sharedLibraries,
26
+ type SharedLibrary,
27
+ } from "./shared-libraries.js";
9
28
 
10
29
  export async function create(
11
30
  resource: any,
@@ -13,6 +32,15 @@ export async function create(
13
32
  ): Promise<ResourceInstance> {
14
33
  const alias = resource.metadata.name as string;
15
34
 
35
+ // Resolve the instances this import hands DOWN to the target library's
36
+ // declared `resources:` inputs BEFORE any loading happens. A borrowed
37
+ // instance that is registered but not yet initialized is a DEFERRAL, not a
38
+ // failure — raised as `ERR_LOCAL_REF_PENDING` so the multi-pass loop retries
39
+ // and the init-failure classifier reads it as derived rather than as a root
40
+ // cause. Resolving first is what keeps a deferral cheap: a fetch, a parse and
41
+ // a full analysis pass would otherwise be redone on every pass.
42
+ const borrowed = resolveBorrowedResources(resource, ctx);
43
+
16
44
  const rawSource: string = resource.module ?? resource.source;
17
45
  // A directly-authored Telo.Import may carry integrity as a sibling field;
18
46
  // fold it into the ref as a `#sha256-...` fragment (the desugared inline
@@ -39,6 +67,16 @@ export async function create(
39
67
  // `isImportValidatedAtLoad` silently miss.
40
68
  const resolvedUrl = ctx.resolveImportUrl(base, moduleSource);
41
69
 
70
+ // A `lifecycle: shared` library is instantiated ONCE per application. Only a
71
+ // shared library is ever registered, so the registry HIT is itself the answer
72
+ // to "is this one shared" — which is what makes a second import of it cost no
73
+ // fetch, no parse and no analysis pass at all.
74
+ const registry = sharedLibraries(ctx.moduleContext);
75
+ const alreadyShared = registry.get(resolvedUrl);
76
+ if (alreadyShared) {
77
+ return borrowSharedLibrary(alreadyShared, alias, resource, borrowed, ctx);
78
+ }
79
+
42
80
  // The analysis-flattened graph (follows Telo.Import chains, includes forwarded
43
81
  // sub-import exports) serves two purposes here: validating the imported subtree,
44
82
  // and populating a CHILD-SCOPED analysis registry whose top-level alias scope is
@@ -114,6 +152,8 @@ export async function create(
114
152
  // Validate required inputs before injecting.
115
153
  validateRequiredInputs(moduleManifest.variables ?? {}, resource.variables ?? {}, "variables");
116
154
  validateRequiredInputs(moduleManifest.secrets ?? {}, resource.secrets ?? {}, "secrets");
155
+ const declaredInputs = readResourceInputs(moduleManifest);
156
+ validateResourceInputs(declaredInputs, borrowed, targetModule);
117
157
 
118
158
  // Evaluate the import's variables/secrets ONCE against the IMPORTER's config
119
159
  // scope, instead of baking the raw compiled-value objects verbatim. Resolution
@@ -173,7 +213,19 @@ export async function create(
173
213
  authoredModuleMetadata(moduleManifest.metadata as Record<string, unknown> | undefined),
174
214
  );
175
215
 
176
- const child = ctx.moduleContext.spawnChild(childCtx);
216
+ // A singleton is spawned under the ROOT, never under whichever import reached
217
+ // it first: otherwise tearing that importer down would close a library two
218
+ // others still hold, and which importer that is depends on init order. It is
219
+ // pinned last in the root's cascade so a borrower's own inverses still find it
220
+ // alive — the context-level form of `TEARDOWN_LAST`.
221
+ const isShared = readLibraryLifecycle(moduleManifest) === "shared";
222
+ if (isShared) {
223
+ assertNoSharedOverride(resource, alias, targetModule);
224
+ childCtx.teardownPriority = TEARDOWN_LAST;
225
+ }
226
+ const child = isShared
227
+ ? rootContextOf(ctx.moduleContext).spawnChild(childCtx)
228
+ : ctx.moduleContext.spawnChild(childCtx);
177
229
 
178
230
  // A library references its own kinds via `Self.<Kind>` (e.g. when it declares an
179
231
  // instance to export). Register `Self` → the library's own module in the child context
@@ -209,7 +261,14 @@ export async function create(
209
261
  const parentScope =
210
262
  (ctx.moduleContext as unknown as ModuleContext).getLoggingConfig?.() ??
211
263
  ctx.kernelLoggingRootScope();
212
- const scopePath = parentScope.scope ? `${parentScope.scope}.${alias}` : alias;
264
+ // A singleton's scope is the LIBRARY's own name: it sits under the root rather
265
+ // than under an importer, and naming it after whichever import was created
266
+ // first would make a log line's scope depend on init order.
267
+ const scopePath = isShared
268
+ ? targetModule
269
+ : parentScope.scope
270
+ ? `${parentScope.scope}.${alias}`
271
+ : alias;
213
272
  const importLogging = resource.logging
214
273
  ? (ctx.expandValue(resource.logging, {}) as LoggingManifestBlock)
215
274
  : undefined;
@@ -220,7 +279,43 @@ export async function create(
220
279
  secretValues: child.secretValues,
221
280
  });
222
281
 
282
+ // A borrowed instance is bound under the library's own name for it BEFORE its
283
+ // resources are registered, so `!ref connection` and `resources.connection`
284
+ // resolve exactly as a locally declared resource does — and so a library
285
+ // declaring a resource that collides with an input name fails as the
286
+ // duplicate it is.
287
+ //
288
+ // An EFFECT on the create frame, not bare statements: binding a borrowed
289
+ // instance registers a publication mirror on the OWNER, and an import whose
290
+ // `init()` fails is discarded and re-created on the next pass. Left
291
+ // unregistered, each pass would append another mirror for the same pair and
292
+ // keep the abandoned child context reachable from the live owner.
293
+ if (borrowed.size > 0) {
294
+ await ctx
295
+ .effect(`borrowed resources ${alias}`, async () => {
296
+ const inverses = [...borrowed].map(([name, entry]) =>
297
+ childCtx.adoptBorrowedResource(
298
+ name,
299
+ entry.manifest,
300
+ entry.instance,
301
+ ctx.moduleContext as unknown as ModuleContext,
302
+ ),
303
+ );
304
+ return {
305
+ result: undefined,
306
+ inverse: () => {
307
+ for (const undo of inverses) undo?.();
308
+ },
309
+ };
310
+ })
311
+ .perform();
312
+ }
313
+
223
314
  for (const manifest of manifests) {
315
+ // The kind-only stand-ins the loader synthesizes behind a `resources:` entry
316
+ // are a DECLARATION for the analyzer, never an instantiation: the instance
317
+ // is the importer's, already bound above.
318
+ if (isInjectedDeclaration(manifest)) continue;
224
319
  child.registerManifest(manifest);
225
320
  }
226
321
 
@@ -297,6 +392,48 @@ export async function create(
297
392
  );
298
393
  }
299
394
  }
395
+ /** Build this library's resources and its export tables — the work an
396
+ * `init()` performs, hoisted so a SINGLETON can carry it on its registry
397
+ * entry rather than in one import's closure. Whichever import's `init()`
398
+ * runs first calls it; every other awaits the same promise. */
399
+ const buildLibrary = async (): Promise<void> => {
400
+ // Publish each borrowed reading into the child's `resources` scope before
401
+ // anything reads it: a library resource's compile-eval fields are expanded
402
+ // at CREATE time, inside `initializeResources` below.
403
+ for (const name of borrowed.keys()) await childCtx.publishSnapshot(name);
404
+ await child.initializeResources();
405
+ // Build this import's flattened export tables now that its own imports are
406
+ // registered (leaves-first), so a re-export (`!ref Alias.name` /
407
+ // `Alias.Kind`) copies the source import's terminal getter / canonical kind
408
+ // by reference — O(1) resolution at any depth.
409
+ childCtx.buildExportTable(exportEntries, kindEntries, targetModule);
410
+ };
411
+
412
+ // The singleton, registered before any alias so a second import created in
413
+ // the same pass finds it. `initialized` is filled by whichever import's
414
+ // `init()` runs first — which is NOT necessarily the one that registered it,
415
+ // so the builder travels with the entry.
416
+ const entry: SharedLibrary | undefined = isShared
417
+ ? {
418
+ build: buildLibrary,
419
+ url: resolvedUrl,
420
+ module: targetModule,
421
+ owner: alias,
422
+ context: childCtx,
423
+ child,
424
+ variables: importVariables,
425
+ secrets: importSecrets,
426
+ resources: new Map([...borrowed].map(([name, b]) => [name, b.instance])),
427
+ declaredVariables: (moduleManifest.variables ?? {}) as Record<string, any>,
428
+ declaredSecrets: (moduleManifest.secrets ?? {}) as Record<string, any>,
429
+ exportEntries,
430
+ kindEntries,
431
+ exportedResourceNames,
432
+ exportedKindSuffixes,
433
+ }
434
+ : undefined;
435
+ if (entry) registry.set(resolvedUrl, entry);
436
+
300
437
  // The alias registrations are an EFFECT on the create frame, not bare calls:
301
438
  // an import whose `init()` fails is discarded and re-created on the next pass,
302
439
  // so an alias left registered would be re-registered against a module context
@@ -329,8 +466,10 @@ export async function create(
329
466
  inverse: () => {
330
467
  (ctx.moduleContext as ModuleContext).unregisterImport(alias);
331
468
  // The child context goes with the alias: it was spawned for this
332
- // import and nothing else can reach it once the alias is gone.
333
- ctx.moduleContext.detachChild(child);
469
+ // import and nothing else can reach it once the alias is gone. A
470
+ // SINGLETON is the exception — the root owns it and other imports may
471
+ // still hold it, so only the alias is given up.
472
+ if (!isShared) ctx.moduleContext.detachChild(child);
334
473
  },
335
474
  };
336
475
  })
@@ -368,17 +507,104 @@ export async function create(
368
507
  // than an init/teardown pair the kernel had to trust were inverses.
369
508
  init: (importCtx) =>
370
509
  importCtx.effect("library resources", async () => {
371
- await child.initializeResources();
372
- // Build this import's flattened export tables now that its own imports are
373
- // registered (leaves-first), so a re-export (`!ref Alias.name` / `Alias.Kind`)
374
- // copies the source import's terminal getter / canonical kind by reference —
375
- // O(1) resolution at any depth.
376
- childCtx.buildExportTable(exportEntries, kindEntries, targetModule);
510
+ if (entry) {
511
+ // Memoized on the ENTRY, so whichever import's `init()` runs first
512
+ // does the work and every other awaits the same promise. It is not
513
+ // necessarily the import that registered it: a root import registers
514
+ // the singleton during the create sub-phase, while a nested import
515
+ // inside another library borrows it during that library's init — and
516
+ // the nested one's `init()` can then run first.
517
+ await (entry.initialized ??= entry.build());
518
+ // No inverse: the ROOT owns a singleton, and an import that gave it up
519
+ // would close a library its siblings still hold.
520
+ return { result: undefined };
521
+ }
522
+ await buildLibrary();
377
523
  return { result: undefined, inverse: () => child.teardownResources() };
378
524
  }),
379
525
  };
380
526
  }
381
527
 
528
+ /**
529
+ * A second (or third) import of a library already instantiated as a singleton.
530
+ *
531
+ * Nothing is fetched, parsed or analyzed: the registry hit means the library is
532
+ * built and shared, so this import only has to agree with it and register its
533
+ * own alias. What it must NOT do is re-register the manifests, re-initialize the
534
+ * resources, or claim any part of the teardown.
535
+ */
536
+ function borrowSharedLibrary(
537
+ entry: SharedLibrary,
538
+ alias: string,
539
+ resource: any,
540
+ borrowed: Map<string, BorrowedResource>,
541
+ ctx: BuiltinControllerContext,
542
+ ): ResourceInstance {
543
+ assertNoSharedOverride(resource, alias, entry.module);
544
+ const importVariables = applyDefaults(
545
+ (ctx.expandValue(resource.variables, {}) as Record<string, unknown>) ?? {},
546
+ entry.declaredVariables,
547
+ );
548
+ const importSecrets = applyDefaults(
549
+ (ctx.expandValue(resource.secrets, {}) as Record<string, unknown>) ?? {},
550
+ entry.declaredSecrets,
551
+ );
552
+ validateRequiredInputs(entry.declaredVariables, importVariables, "variables");
553
+ validateRequiredInputs(entry.declaredSecrets, importSecrets, "secrets");
554
+ assertSharedInputsAgree(entry, alias, importVariables, importSecrets, borrowed);
555
+
556
+ const childCtx = entry.context;
557
+ const exportedResourceNames = [...entry.exportedResourceNames];
558
+
559
+ return {
560
+ snapshot: async () => {
561
+ const exported: Record<string, unknown> = {};
562
+ for (const name of exportedResourceNames) {
563
+ const target = childCtx.getExported(name);
564
+ if (target?.instance) {
565
+ exported[name] = await publishedPropsOf(
566
+ target.kind,
567
+ name,
568
+ target.instance,
569
+ childCtx.getDefinition,
570
+ );
571
+ }
572
+ }
573
+ return { variables: importVariables, secrets: importSecrets, ...exported };
574
+ },
575
+ init: (importCtx) =>
576
+ importCtx
577
+ .effect(`import alias ${alias}`, async () => {
578
+ ctx.registerModuleImport(
579
+ alias,
580
+ entry.module,
581
+ entry.exportedKindSuffixes ? [...entry.exportedKindSuffixes] : undefined,
582
+ );
583
+ (ctx.moduleContext as ModuleContext).registerImportedScope(
584
+ alias,
585
+ exportedResourceNames,
586
+ (name) => childCtx.getTerminalExport(name),
587
+ );
588
+ (ctx.moduleContext as ModuleContext).registerImportedKindScope(alias, (suffix) =>
589
+ childCtx.getExportedKind(suffix),
590
+ );
591
+ return {
592
+ result: undefined,
593
+ // Only the alias: the root owns the library and the imports that
594
+ // instantiated it are still holding it.
595
+ inverse: () => (ctx.moduleContext as ModuleContext).unregisterImport(alias),
596
+ };
597
+ })
598
+ // The singleton may not be built yet — this import's `init()` can run
599
+ // before the one that registered it. Start it if nobody has; otherwise
600
+ // await the one promise everybody shares.
601
+ .effect("shared library", async () => {
602
+ await (entry.initialized ??= entry.build());
603
+ return { result: undefined };
604
+ }),
605
+ };
606
+ }
607
+
382
608
  /**
383
609
  * Fill in library-declared `default:` values for any input the importer left
384
610
  * unset. Mirrors the root Application's env defaulting: a provided value (incl.
@@ -412,3 +638,88 @@ function validateRequiredInputs(
412
638
  }
413
639
  }
414
640
 
641
+
642
+ /** One instance handed down to a library's declared `resources:` input, with the
643
+ * manifest it was DECLARED with — the declaration is what a projected contract
644
+ * and a `status:` reading are resolved against, so it travels with the
645
+ * instance rather than being re-derived on the far side. */
646
+ interface BorrowedResource {
647
+ manifest: ResourceManifest;
648
+ instance: ResourceInstance;
649
+ }
650
+
651
+ /**
652
+ * Resolve every `resources:` entry this import supplies to a live instance, in
653
+ * the IMPORTER's scope.
654
+ *
655
+ * A name that is registered here but not yet initialized defers
656
+ * (`ERR_LOCAL_REF_PENDING`); one that names nothing at all is a hard
657
+ * `ERR_REF_UNRESOLVED`, since no later pass will produce it. The two are kept
658
+ * apart because the init-failure classifier reads the first as derived — the
659
+ * import never ran — and the second as the root cause it is.
660
+ */
661
+ function resolveBorrowedResources(
662
+ resource: any,
663
+ ctx: BuiltinControllerContext,
664
+ ): Map<string, BorrowedResource> {
665
+ const out = new Map<string, BorrowedResource>();
666
+ const alias = resource.metadata.name as string;
667
+ for (const [name, value] of Object.entries(readSuppliedResources(resource))) {
668
+ const ref = value as { name?: unknown; alias?: unknown } | undefined;
669
+ const targetName = typeof ref?.name === "string" ? ref.name : undefined;
670
+ if (!targetName) {
671
+ throw new RuntimeError(
672
+ "ERR_REF_UNRESOLVED",
673
+ `Import '${alias}': resource input '${name}' must be a '!ref' to a resource this module declares.`,
674
+ );
675
+ }
676
+ const targetAlias = typeof ref?.alias === "string" ? ref.alias : undefined;
677
+ const instance =
678
+ targetAlias && targetAlias !== "Self"
679
+ ? ctx.moduleContext.resolveImportedInstance(targetAlias, targetName)
680
+ : ctx.moduleContext.getInstance?.(targetName);
681
+ if (!instance) {
682
+ const label = targetAlias ? `${targetAlias}.${targetName}` : targetName;
683
+ throw new RuntimeError(
684
+ targetAlias && targetAlias !== "Self"
685
+ ? "ERR_CROSS_MODULE_REF_PENDING"
686
+ : "ERR_LOCAL_REF_PENDING",
687
+ `Import '${alias}': resource input '${name}' → '${label}' is not available yet ` +
688
+ `(deferring to a later init pass).`,
689
+ );
690
+ }
691
+ const manifest =
692
+ ctx.moduleContext.resolveDeclaredManifest?.(targetName, targetAlias) ??
693
+ ({ kind: (ref as { kind?: string }).kind ?? "", metadata: { name: targetName } } as ResourceManifest);
694
+ out.set(name, { manifest, instance });
695
+ }
696
+ return out;
697
+ }
698
+
699
+ /** The runtime half of `validate-resource-inputs`: a library reached through a
700
+ * programmatic load never passed `telo check`, so the boundary is enforced
701
+ * here too. Kind acceptance is deliberately NOT re-tested — that is a static
702
+ * question about declarations, and the kernel holds instances. */
703
+ function validateResourceInputs(
704
+ declared: ReadonlyArray<{ name: string; kind: string }>,
705
+ supplied: ReadonlyMap<string, BorrowedResource>,
706
+ targetModule: string,
707
+ ): void {
708
+ for (const entry of declared) {
709
+ if (supplied.has(entry.name)) continue;
710
+ throw new RuntimeError(
711
+ "ERR_MANIFEST_VALIDATION_FAILED",
712
+ `Required resource input "${entry.name}" (kind '${entry.kind}') not provided for import of ` +
713
+ `module '${targetModule}'.`,
714
+ );
715
+ }
716
+ const names = new Set(declared.map((d) => d.name));
717
+ for (const name of supplied.keys()) {
718
+ if (names.has(name)) continue;
719
+ throw new RuntimeError(
720
+ "ERR_MANIFEST_VALIDATION_FAILED",
721
+ `Resource input "${name}" is not declared by module '${targetModule}'. Declared inputs: ` +
722
+ `${declared.map((d) => d.name).join(", ") || "(none)"}.`,
723
+ );
724
+ }
725
+ }
@@ -0,0 +1,180 @@
1
+ import type { EvaluationContext as IEvaluationContext, ResourceInstance } from "@telorun/sdk";
2
+ import { RuntimeError } from "@telorun/sdk";
3
+ import type { ModuleContext } from "../../module-context.js";
4
+ import type { ParsedExportEntry } from "@telorun/analyzer";
5
+
6
+ /**
7
+ * LIBRARY SINGLETONS — one instantiation of a `lifecycle: shared` library per
8
+ * application, borrowed by every import that names it.
9
+ *
10
+ * An import declaration otherwise builds its own child scope with its own
11
+ * instances, so two libraries importing a third get two of everything in it.
12
+ * That is right for a library whose instances are the importer's — a client
13
+ * configured per consumer — and wrong for one that owns a resource the
14
+ * application has exactly one of. `lifecycle: shared` names the second case, and
15
+ * it is what lets a set of libraries share a dependency without linearizing them
16
+ * into a chain that re-exports the union of everything beneath it.
17
+ *
18
+ * **The root owns it; every import borrows it** — the same rule an injected
19
+ * resource follows. The child context is spawned under the ROOT rather than
20
+ * under whichever import happened to reach it first, because otherwise tearing
21
+ * that importer down would close a library two others still hold, and which
22
+ * importer that is depends on init order. It is torn down after every other root
23
+ * child (`TEARDOWN_LAST` on the context), so a borrower's own inverses still
24
+ * find it alive.
25
+ *
26
+ * **Registered only when shared**, which is what makes a registry HIT the answer
27
+ * to "is this library shared" — a second import of one costs no fetch, no parse
28
+ * and no analysis pass at all.
29
+ */
30
+ export interface SharedLibrary {
31
+ /** The resolved module URL — the identity two imports must agree on. Carries
32
+ * any `#sha256-` pin, so two imports of the same source at different
33
+ * integrity are different libraries, which is the truth. */
34
+ readonly url: string;
35
+ readonly module: string;
36
+ /** The alias of the import that instantiated it, named in a conflict. */
37
+ readonly owner: string;
38
+ readonly context: ModuleContext;
39
+ readonly child: IEvaluationContext;
40
+ readonly variables: Record<string, unknown>;
41
+ readonly secrets: Record<string, unknown>;
42
+ /** The instances supplied for the library's declared `resources:` inputs,
43
+ * compared by IDENTITY: two imports handing down different instances of the
44
+ * same kind is exactly the split a singleton exists to prevent. */
45
+ readonly resources: ReadonlyMap<string, ResourceInstance>;
46
+ readonly declaredVariables: Record<string, any>;
47
+ readonly declaredSecrets: Record<string, any>;
48
+ readonly exportEntries: readonly ParsedExportEntry[];
49
+ readonly kindEntries: readonly ParsedExportEntry[];
50
+ readonly exportedResourceNames: readonly string[];
51
+ readonly exportedKindSuffixes: readonly string[] | undefined;
52
+ /** Build the library's resources and export tables. Carried on the ENTRY
53
+ * rather than in one import's closure because the import that REGISTERS a
54
+ * singleton is not necessarily the one whose `init()` runs first. */
55
+ readonly build: () => Promise<void>;
56
+ /** Memoized initialization. Whichever import's `init()` runs first starts it
57
+ * and every other awaits the same promise, so a borrower can never proceed
58
+ * against a library whose resources have not been built — an ordering the
59
+ * multi-pass loop does not otherwise guarantee. */
60
+ initialized?: Promise<void>;
61
+ }
62
+
63
+ /** Per-kernel, hung off the ROOT context rather than held in module scope, so
64
+ * two in-process kernels never share a library instance. */
65
+ const registries = new WeakMap<object, Map<string, SharedLibrary>>();
66
+
67
+ /** The root of a context's lifecycle tree — the kernel's own root context. */
68
+ export function rootContextOf(ctx: IEvaluationContext): IEvaluationContext {
69
+ let node: IEvaluationContext = ctx;
70
+ while (node.parent) node = node.parent;
71
+ return node;
72
+ }
73
+
74
+ /** The shared-library registry for the kernel `ctx` belongs to. */
75
+ export function sharedLibraries(ctx: IEvaluationContext): Map<string, SharedLibrary> {
76
+ const root = rootContextOf(ctx) as unknown as object;
77
+ let registry = registries.get(root);
78
+ if (!registry) registries.set(root, (registry = new Map()));
79
+ return registry;
80
+ }
81
+
82
+ /**
83
+ * Refuse a second import that would instantiate the library differently.
84
+ *
85
+ * A singleton has one configuration, so the only sound reading of two imports
86
+ * supplying different values is that one of them is wrong — and which one cannot
87
+ * be decided here. Resolved by init order it would be whichever import was
88
+ * created first, silently, which is the failure mode `lifecycle: shared` is
89
+ * supposed to remove rather than relocate.
90
+ *
91
+ * A secret's VALUE is never printed: the key is what the author has to look at.
92
+ */
93
+ export function assertSharedInputsAgree(
94
+ entry: SharedLibrary,
95
+ alias: string,
96
+ variables: Record<string, unknown>,
97
+ secrets: Record<string, unknown>,
98
+ resources: ReadonlyMap<string, { instance: ResourceInstance }>,
99
+ ): void {
100
+ const conflict = (block: string, key: string, detail?: string): never => {
101
+ throw new RuntimeError(
102
+ "ERR_SHARED_LIBRARY_CONFLICT",
103
+ `Import '${alias}' and import '${entry.owner}' both reach module '${entry.module}', which ` +
104
+ `declares 'lifecycle: shared' — one instantiation for the whole application — but they ` +
105
+ `supply different values for ${block}.${key}${detail ? ` (${detail})` : ""}. Make the two ` +
106
+ `imports agree, or make the library 'lifecycle: isolated'.`,
107
+ );
108
+ };
109
+
110
+ for (const key of union(Object.keys(entry.variables), Object.keys(variables))) {
111
+ if (!sameValue(entry.variables[key], variables[key])) {
112
+ conflict("variables", key, `'${render(entry.variables[key])}' vs '${render(variables[key])}'`);
113
+ }
114
+ }
115
+ // Values withheld deliberately — a diagnostic must not become a way to read a
116
+ // secret out of a running process.
117
+ for (const key of union(Object.keys(entry.secrets), Object.keys(secrets))) {
118
+ if (!sameValue(entry.secrets[key], secrets[key])) conflict("secrets", key);
119
+ }
120
+ for (const key of union([...entry.resources.keys()], [...resources.keys()])) {
121
+ if (entry.resources.get(key) !== resources.get(key)?.instance) {
122
+ conflict("resources", key, "different instances");
123
+ }
124
+ }
125
+ }
126
+
127
+ /** Reject a per-import override a singleton has no room for. The analyzer
128
+ * reports the same thing as `SHARED_LIBRARY_OVERRIDE`; this is the runtime
129
+ * half, for a library reached through a programmatic load that never passed
130
+ * `telo check`. */
131
+ export function assertNoSharedOverride(resource: any, alias: string, module: string): void {
132
+ for (const field of ["logging", "runtime"] as const) {
133
+ if (resource[field] === undefined) continue;
134
+ throw new RuntimeError(
135
+ "ERR_SHARED_LIBRARY_OVERRIDE",
136
+ `Import '${alias}' declares '${field}:', but module '${module}' is 'lifecycle: shared' — ` +
137
+ `one instantiation for the whole application, so a per-import override cannot apply to ` +
138
+ `it. Remove it, or make the library 'lifecycle: isolated'.`,
139
+ );
140
+ }
141
+ }
142
+
143
+ function union(a: readonly string[], b: readonly string[]): string[] {
144
+ return [...new Set([...a, ...b])];
145
+ }
146
+
147
+ /**
148
+ * Structural equality over the JSON-shaped values a config input carries.
149
+ * `undefined` and an absent key are the same absence.
150
+ *
151
+ * Key ORDER is not part of a value: two imports writing the same object variable
152
+ * with its keys in a different YAML order are supplying the same thing, and a
153
+ * conflict here is a hard boot failure telling the author the two imports
154
+ * disagree — a false positive is both expensive and unexplainable.
155
+ */
156
+ function sameValue(a: unknown, b: unknown): boolean {
157
+ if (a === b) return true;
158
+ if (a === undefined || b === undefined) return false;
159
+ if (a === null || b === null) return false;
160
+ if (Array.isArray(a) || Array.isArray(b)) {
161
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
162
+ return a.every((item, i) => sameValue(item, b[i]));
163
+ }
164
+ if (typeof a === "object" && typeof b === "object") {
165
+ const left = a as Record<string, unknown>;
166
+ const right = b as Record<string, unknown>;
167
+ const keys = union(Object.keys(left), Object.keys(right));
168
+ return keys.every((key) => sameValue(left[key], right[key]));
169
+ }
170
+ return false;
171
+ }
172
+
173
+ function render(value: unknown): string {
174
+ if (typeof value === "string") return value;
175
+ try {
176
+ return JSON.stringify(value) ?? String(value);
177
+ } catch {
178
+ return String(value);
179
+ }
180
+ }