@theokit/di 0.1.1 → 0.2.1

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.
package/CHANGELOG.md CHANGED
@@ -1,12 +1,32 @@
1
1
  # Changelog
2
2
 
3
- ## 0.1.1
3
+ ## 0.2.1
4
4
 
5
5
  ### Patch Changes
6
6
 
7
- - 461c020: Add `METADATA_KEYS.SQUAD` (`"usetheo:di:squad"`) and `METADATA_KEYS.STEP` (`"usetheo:di:step"`) — new metadata keys backing the `@Squad()` and `@Step()` decorators in `@theokit/di-agent`. Shipped as a patch (additive values on the existing exported `METADATA_KEYS`) to keep `@theokit/di-agent` and the in-progress `@theokit/orm` (prerelease `0.1.0-next.1`) inside their `^0.1.0` peer range — a `minor` (`0.2.0`) would fall outside `^0.1.x` and force both dependents to `1.0.0`.
7
+ - 8e59fec: Name an anonymous class `<anonymous>` in diagnostics instead of rendering nothing.
8
+
9
+ Four call sites wrote a class name as `target.name ?? "<anonymous>"`, and that fallback could never
10
+ fire: an anonymous class has `name === ""`, not an absent one, and `"" ?? x` is `""`. A consumer who
11
+ passed a class expression read `Class has no @Module() decorator.` — two spaces where the identity
12
+ belongs, and nothing to search the codebase for. `MissingInjectableError`, `InvalidModuleError`, the
13
+ `emitted as ...` hint in constructor-parameter diagnostics and the cycle labels in `analyze()` are
14
+ all affected.
15
+
16
+ `describeToken` in the same file had the check right all along (`name.length > 0`); the other sites
17
+ had drifted from it. The knowledge now lives in one exported helper, `describeClassName`.
18
+
19
+ - 452d6ba: `analyze()` no longer drops a cycle when two classes share a name.
20
+
21
+ `findCycles` de-duplicated cycles by the token's RENDERING rather than by the token, so two different
22
+ classes with the same `name` produced the same key and the second cycle was discarded as a duplicate
23
+ of the first. Two files each declaring `class Logger` and `class Service` was enough to trigger it, as
24
+ was any two anonymous classes or any two symbol tokens: `analyze()` reported one cycle, and nothing
25
+ said the other had been dropped. A consumer debugging a cyclic dependency fixed the loop they were
26
+ shown and met the next one on the following run.
8
27
 
9
- Also: broke the `container.ts ↔ internal/module-loader.ts` type-only cycle (arch-review ADR 0001) — `loadModule` now depends on a narrow `ModuleRegistrar` interface from the leaf `types.ts` instead of the concrete `Container`. No behavior change; `Container` satisfies it structurally.
28
+ Cycles are now keyed on an identity table. The rotation that makes the key independent of which node
29
+ the walk entered on is unchanged.
10
30
 
11
31
  All notable changes to `@theokit/di` are documented in this file.
12
32
 
@@ -15,29 +35,82 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
15
35
 
16
36
  ## [Unreleased]
17
37
 
38
+ ### Fixed
39
+
40
+ - `analyze()` no longer drops a cycle when two classes share a name. Cycles were de-duplicated by the
41
+ token's rendering rather than by the token, so two different classes called `Logger` keyed
42
+ identically and the second cycle was discarded as a duplicate of the first — one cycle reported,
43
+ and nothing to say the other existed. Two anonymous classes and two symbol tokens collided the same
44
+ way. The key is built from an identity table now (#59).
45
+
46
+ - An anonymous class in an error message is now named `<anonymous>` instead of nothing at all.
47
+ Four diagnostics rendered a class name as `target.name ?? "<anonymous>"`, and that fallback can
48
+ never fire — an anonymous class has `name === ""`, not an absent one, so `??` passes the empty
49
+ string straight through. A consumer who passed a class expression read `Class has no @Module()
50
+ decorator.`, with two spaces where the identity belongs and nothing to search for. Affects
51
+ `MissingInjectableError`, `InvalidModuleError`, the `emitted as ...` hint in the container's
52
+ parameter diagnostics, and cycle labels in `analyze()` (#57).
53
+
18
54
  ### Added
19
55
 
20
- - `METADATA_KEYS.SQUAD` (`"usetheo:di:squad"`) — metadata key backing the `@Squad()` decorator in `@theokit/di-agent`.
21
- - `METADATA_KEYS.STEP` (`"usetheo:di:step"`) — metadata key backing the `@Step()` decorator in `@theokit/di-agent`.
56
+ - `describeClassName(target, fallback)` is exported alongside `describeToken`. The four sites above
57
+ had each written their own version of "a class's display name, with a fallback"; `describeToken`
58
+ was the only one that got it right, and now it is the only one that states it (#57).
22
59
 
23
- ### Changed
60
+ ## [0.2.0] - 2026-08-21
24
61
 
25
- - Broke the `container.ts ↔ internal/module-loader.ts` type-only dependency cycle (arch-review ADR 0001). `loadModule` now takes a narrow `ModuleRegistrar` interface (just `register(...)`) from the leaf `types.ts` instead of importing the concrete `Container`. No behavior change — `Container` satisfies it structurally; all 69 tests GREEN, `madge --circular` clean.
62
+ ### Added
63
+
64
+ - Every published export now carries documentation an editor can show. Measured on the emitted
65
+ declarations, 33/37 to 37/37. (#24)
66
+
67
+ - npm provenance is enabled again. It was switched off because npm refuses attestation for packages built from a private source repository; this one is public now, so published tarballs carry a sigstore attestation linking them to the commit and workflow that produced them.
68
+ - `@PostConstruct` is now called. The container invokes the marked method once the instance is built and every constructor dependency is injected — once per instance, so a SINGLETON initialises once however often it is resolved. An async hook is awaited by `resolveAsync`; `resolve()` cannot await one and throws `AsyncPostConstructInSyncResolveError` rather than return an object whose initialiser is still running (#5).
69
+ - `@PreDestroy` is now called, before `dispose()` when a class has both, and awaited if it returns a Promise. A class no longer needs a `dispose()` method to be torn down — declaring the hook is enough for the container to track it. A failing hook no longer stops the others; the failures arrive together as an `AggregateError` (#5).
70
+ - `AsyncPostConstructInSyncResolveError`, exported so consumers can catch it by type.
26
71
 
27
72
  ### Changed
28
73
 
29
- - **Documentation only:** expanded JSDoc header on `Container` class (`src/container.ts:87`) acknowledging auditor finding PV#10 from the 2026-06-06 architecture audit. The 812 LOC class size is above the 500 LOC heuristic file budget but justified as the Single-Point-of-Truth for DI resolution (registry lookup, lifecycle SINGLETON/TRANSIENT/REQUEST, `@Injectable` metadata read, alias resolution, request-scope ALS propagation, dispose chain). Splitting would fragment cohesion per `rules/architecture.md § 3` + KISS / YAGNI. ADR D422 tracks ongoing Extract-Method refactor at the method level. No code change. Plan `arch-review-fixes-2026-06-06` T11.2 records the trade-off.
74
+ - `repository`, `homepage` and `bugs` now point at `usetheokit/theokit-di`. They pointed at `usetheo/theokit-sdk`, so every "Repository" and "Report issues" link on npm led to a project that does not host this package.
75
+ - The package description no longer names `@theokit/http-decorators`, which does not exist. The package is `@theokit/http`.
76
+ - The README no longer carries a Portuguese clause, and says plainly where `@theokit/http` ships from.
77
+ - JSDoc on the public surface no longer cites ADRs, audit findings, plan tasks or edge-case identifiers that exist in no repository a reader can reach. The rationale each citation stood for is now written inline, so it survives into the published type declarations.
78
+ - `Primary` now declares its parameter as a constructor type rather than `Function`. `Function` is the widest callable type there is, so it documented nothing and admitted values that are not classes. Any class you could already decorate still type-checks.
79
+
80
+ ### Fixed
81
+
82
+ - **Breaking:** `container.dispose()` no longer tears down a value it was handed rather than built.
83
+ A `useValue` with a `dispose()` method was being closed by the container even though the caller
84
+ constructed it and still holds the reference — so a caller who closed their own pool, as every
85
+ convention says they should, closed it twice. The rule is now ownership: the container tears down
86
+ what it constructed (`useClass`, `useFactory`) and leaves alone what it was given. (#23)
87
+ - **Breaking:** an instance reached through `useExisting` is disposed once, not once per token that
88
+ names it. An alias resolves to the same object by definition, and the container was tracking it
89
+ again under the alias, so a resource behind two tokens was closed twice.
90
+ Both were found while documenting the disposal contract: the docblock stated the ownership rule
91
+ and the code did not implement it. Neither shape appeared in any of the eight disposal tests;
92
+ five now cover them. (#23)
93
+ - `@Primary` and `@Qualifier` documented a resolution priority the container has never had. They record metadata and nothing else, and their JSDoc now says exactly that, with the working alternative alongside. Implementing them means holding several registrations per token — which is the cache key, the cycle-detection node identity and the disposal order — so it is a design decision rather than a missing branch, and it has not been made (#5).
94
+ - The English-only lint gate could not fail on an accented word. It split identifiers with an ASCII-only pattern before testing them for diacritics, so `não` became `n` and `o` and the diacritic tier was unreachable. Both tiers now work, verified by planting an accented identifier and watching the sweep turn red (#7).
95
+
96
+ ## 0.1.1
97
+
98
+ ### Patch Changes
99
+
100
+ - Add `METADATA_KEYS.SQUAD` (`"usetheo:di:squad"`) and `METADATA_KEYS.STEP` (`"usetheo:di:step"`) — new metadata keys backing the `@Squad()` and `@Step()` decorators in `@theokit/di-agent`. Shipped as a patch (additive values on the existing exported `METADATA_KEYS`) to keep `@theokit/di-agent` and the in-progress `@theokit/orm` (prerelease `0.1.0-next.1`) inside their `^0.1.0` peer range — a `minor` (`0.2.0`) would fall outside `^0.1.x` and force both dependents to `1.0.0`.
101
+
102
+ Also: broke the `container.ts ↔ internal/module-loader.ts` type-only cycle — `loadModule` now depends on a narrow `ModuleRegistrar` interface from the leaf `types.ts` instead of the concrete `Container`. No behavior change; `Container` satisfies it structurally.
30
103
 
31
104
  ## [0.1.0] - 2026-05-31
32
105
 
33
- > First GA release. Promotes `0.1.0-next.0` to stable with the EC-R3-1 single-flight Promise cache fix (shipped in `0.1.0-next.0` commit `520fe7d`) plus the biome-cleanup refactors below. API contract preserved — no breaking changes from `0.1.0-next.0`.
106
+ > First GA release. Promotes `0.1.0-next.0` to stable with the single-flight Promise cache fix (shipped in `0.1.0-next.0`) plus the complexity refactors below. API contract preserved — no breaking changes from `0.1.0-next.0`.
34
107
 
35
108
  ### Changed
36
109
 
37
- - Refactored `Container.constructClassWithAsyncFallback<T>` (complexity 18 → ≤10) via Extract Method: introduced 4 private helpers (`validateMetadata`, `handlePrimitiveParam`, `tryResolveSync`, `resolveAllAsync`). Behavior preserved; reflect-metadata error ordering + async-fallback semantics unchanged. (theokit-sdk-biome-cleanup)
38
- - Refactored `Container.fromFactoryProvider` (complexity 11 → ≤10) via Extract Method: introduced `tryResolveSyncDeps` private helper returning a discriminated union for sync/async dispatch. (theokit-sdk-biome-cleanup)
39
- - Removed redundant `export` on `MODULE_METADATA_KEY` (internal-only — never part of public surface). (theokit-sdk-biome-cleanup)
40
- - See ADR D422 for the consolidated rationale (parameter decorators enabled in biome + container Extract Method refactor).
110
+ - Refactored `Container.constructClassWithAsyncFallback<T>` (complexity 18 → ≤10) via Extract Method: introduced 4 private helpers (`validateMetadata`, `handlePrimitiveParam`, `tryResolveSync`, `resolveAllAsync`). Behavior preserved; reflect-metadata error ordering + async-fallback semantics unchanged.
111
+ - Refactored `Container.fromFactoryProvider` (complexity 11 → ≤10) via Extract Method: introduced `tryResolveSyncDeps` private helper returning a discriminated union for sync/async dispatch.
112
+ - Removed redundant `export` on `MODULE_METADATA_KEY` (internal-only — never part of public surface).
113
+ - Parameter decorators were enabled in biome in the same pass, which is what let the container tests keep their `@Inject` annotations.
41
114
 
42
115
  ## [0.1.0-next.0] - 2026-05-29
43
116
 
@@ -48,15 +121,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
48
121
  - 5 decorators: `@Injectable()`, `@Inject(token)`, `@Optional()`, `@Module({...})` — NestJS-compatible API.
49
122
  - 4 provider types: `useClass`, `useFactory`, `useValue`, `useExisting`.
50
123
  - 3 lifecycle scopes: `SINGLETON` (default), `TRANSIENT`, `REQUEST` (via `AsyncLocalStorage`).
51
- - Cycle detection at resolve-time (Promise-lock cache with cycle-first ordering per v1.2 EC-R2-1 prevents async deadlocks).
52
- - Cache cleanup on Promise rejection (v1.2 EC-R2-2) — transient factory failures do NOT poison the REQUEST cache.
53
- - `runInRequest()` try/finally guarantees REQUEST instances are disposed even on callback throw (v1.1 EC-3).
54
- - `validateClassProvider()` centralized validation — both declarative `providers: []` and imperative `register()` reject undecorated classes (v1.1 EC-1).
55
- - Container freezes after first `resolve()`; `allowDynamicRegistration: true` opt-out for tests (v1.2 EC-R2-5).
124
+ - Cycle detection at resolve-time the Promise-lock cache checks for a cycle before consulting the cache, which is what prevents an async deadlock.
125
+ - Cache cleanup on Promise rejection — transient factory failures do NOT poison the REQUEST cache.
126
+ - `runInRequest()` try/finally guarantees REQUEST instances are disposed even on callback throw.
127
+ - `validateClassProvider()` centralized validation — both declarative `providers: []` and imperative `register()` reject undecorated classes.
128
+ - Container freezes after first `resolve()`; `allowDynamicRegistration: true` opt-out for tests.
56
129
  - Module loading with cycle detection (DFS), export validation at register-time, BFS-style transitive provider import.
57
130
  - Typed errors: `TokenNotFoundError`, `CyclicDependencyError`, `AsyncProviderInSyncResolveError`, `ScopeViolationError`, `MissingInjectableError`, `ContainerDisposedError`, `ContainerFrozenError`, `InvalidModuleError`, `InvalidExportError`, `CyclicModuleImportError`, `ReflectMetadataMissingError`.
58
131
  - Disposal lifecycle: `dispose()` calls `Symbol.asyncDispose` (preferred) or `dispose()` on each instance in reverse construction order; aggregates errors via `AggregateError`.
59
- - Foundation for `@theokit/orm` (P2) and `@theokit/http-decorators` (P3). Agent-first integration ships as separate `@theokit/di-agent` package (zero coupling per ADR D8).
132
+ - Foundation for `@theokit/orm` and `@theokit/http`. Agent-first integration ships as the separate `@theokit/di-agent` package, with zero coupling.
60
133
 
61
134
  ### Bundle / Coverage
62
135
 
@@ -64,6 +137,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
64
137
  - Bundle: ESM 11.55 KB / CJS 11.32 KB (gzipped est.).
65
138
  - Dual ESM + CJS, target Node 22.12+, dts emitted.
66
139
 
67
- ### Polyglot strategy (read ADR D11)
140
+ ### Polyglot strategy
68
141
 
69
- `@theokit/di` is **intentionally TS-only**. DI containers are intrinsically language-specific runtime constructs. The polyglot story for the theokit ecosystem lives in the contract layer — `@theokit/orm` (P2, schema export to JSON Schema + SQL migrations) and `@theokit/http-decorators` (P3, OpenAPI 3.x emit from `@Controller` decorators). Python/Go SDKs will be generated from those specs (Supabase/Appwrite pattern), NOT by porting the DI container.
142
+ `@theokit/di` is **intentionally TS-only**. DI containers are intrinsically language-specific runtime constructs. The polyglot story for the theokit ecosystem lives in the contract layer — `@theokit/orm` (schema export to JSON Schema and SQL migrations) and `@theokit/http` (OpenAPI 3.x emitted from `@Controller` decorators). Python/Go SDKs will be generated from those specs (Supabase/Appwrite pattern), NOT by porting the DI container.
package/LICENSE CHANGED
@@ -137,8 +137,8 @@
137
137
 
138
138
  6. Trademarks. This License does not grant permission to use the trade
139
139
  names, trademarks, service marks, or product names of the Licensor,
140
- except as required for describing the origin of the Work and
141
- reproducing the content of the NOTICE file.
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
142
 
143
143
  7. Disclaimer of Warranty. Unless required by applicable law or
144
144
  agreed to in writing, Licensor provides the Work (and each
package/README.md CHANGED
@@ -2,9 +2,9 @@
2
2
 
3
3
  > Lightweight TypeScript dependency injection container for the theokit ecosystem.
4
4
 
5
- NestJS-compatible API (`@Injectable`, `@Inject`, `@Module`, `providers: []`) with three lifecycle scopes (SINGLETON, TRANSIENT, REQUEST via AsyncLocalStorage). Foundation for [`@theokit/orm`](../orm) and [`@theokit/http-decorators`](../http-decorators). Agent-aware integration via the companion [`@theokit/di-agent`](../di-agent) package.
5
+ NestJS-compatible API (`@Injectable`, `@Inject`, `@Module`, `providers: []`) with three lifecycle scopes (SINGLETON, TRANSIENT, REQUEST via AsyncLocalStorage). Foundation for [`@theokit/orm`](../orm) and `@theokit/http`, which ships from the sibling `theokit` repository under `packages/http`. An earlier name, `@theokit/http-decorators`, no longer exists. Agent-aware integration via the companion [`@theokit/di-agent`](../di-agent) package.
6
6
 
7
- **Status:** initial release (`0.1.0-next.0` on npm `next` tag — promote to `latest` after 1-2 weeks dogfood).
7
+ **Status:** `0.1.1` on npm `latest`.
8
8
 
9
9
  ## Install
10
10
 
@@ -58,7 +58,7 @@ console.log(greeter.greet("world")); // Hello, world!
58
58
 
59
59
  ## Polyglot strategy
60
60
 
61
- `@theokit/di` is **intentionally TS-only**. DI containers are language-specific runtime constructs — Python uses `inspect`/`typing.get_type_hints`, Go uses `reflect`, etc. The cross-language story for the theokit ecosystem lives in the **contract layer** (OpenAPI from `@theokit/http-decorators`, SQL migrations + JSON schemas from `@theokit/orm`), not in the container. See ADR D11 of the implementation plan.
61
+ `@theokit/di` is **intentionally TS-only**. DI containers are language-specific runtime constructs — Python uses `inspect`/`typing.get_type_hints`, Go uses `reflect`, etc. The cross-language story for the theokit ecosystem lives in the **contract layer** (OpenAPI from `@theokit/http`, SQL migrations + JSON schemas from `@theokit/orm`), not in the container.
62
62
 
63
63
  ## License
64
64
 
package/dist/index.cjs CHANGED
@@ -16,6 +16,11 @@ function describeToken(token) {
16
16
  return "<unknown token>";
17
17
  }
18
18
  __name(describeToken, "describeToken");
19
+ function describeClassName(target, fallback) {
20
+ const name = target?.name;
21
+ return typeof name === "string" && name.length > 0 ? name : fallback;
22
+ }
23
+ __name(describeClassName, "describeClassName");
19
24
  var TokenNotFoundError = class extends Error {
20
25
  static {
21
26
  __name(this, "TokenNotFoundError");
@@ -49,6 +54,17 @@ var AsyncProviderInSyncResolveError = class extends Error {
49
54
  super(`Provider for token ${describeToken(token)} is async (factory returned a Promise). Use container.resolveAsync() instead of container.resolve().`), this.token = token;
50
55
  }
51
56
  };
57
+ var AsyncPostConstructInSyncResolveError = class extends Error {
58
+ static {
59
+ __name(this, "AsyncPostConstructInSyncResolveError");
60
+ }
61
+ className;
62
+ methodName;
63
+ name = "AsyncPostConstructInSyncResolveError";
64
+ constructor(className, methodName) {
65
+ super(`@PostConstruct ${className}.${methodName}() returned a Promise, and container.resolve() cannot await it. Use container.resolveAsync() instead, or make ${methodName}() synchronous.`), this.className = className, this.methodName = methodName;
66
+ }
67
+ };
52
68
  var ScopeViolationError = class extends Error {
53
69
  static {
54
70
  __name(this, "ScopeViolationError");
@@ -66,7 +82,7 @@ var MissingInjectableError = class extends Error {
66
82
  target;
67
83
  name = "MissingInjectableError";
68
84
  constructor(target) {
69
- super(`Class ${target.name ?? "<anonymous>"} has no @Injectable() decorator. Add @Injectable() above the class declaration before registering it.`), this.target = target;
85
+ super(`Class ${describeClassName(target, "<anonymous>")} has no @Injectable() decorator. Add @Injectable() above the class declaration before registering it.`), this.target = target;
70
86
  }
71
87
  };
72
88
  var ContainerDisposedError = class extends Error {
@@ -109,14 +125,15 @@ function findCycles(snapshot) {
109
125
  const cycles = [];
110
126
  const seenCycles = /* @__PURE__ */ new Set();
111
127
  const visited = /* @__PURE__ */ new Set();
128
+ const tokenIds = /* @__PURE__ */ new Map();
112
129
  for (const node of snapshot.nodes) {
113
130
  if (visited.has(node.token)) continue;
114
- iterativeDfs(node.token, adjacency, visited, cycles, seenCycles);
131
+ iterativeDfs(node.token, adjacency, visited, cycles, seenCycles, tokenIds);
115
132
  }
116
133
  return cycles;
117
134
  }
118
135
  __name(findCycles, "findCycles");
119
- function iterativeDfs(root, adjacency, visited, out, seenCycles) {
136
+ function iterativeDfs(root, adjacency, visited, out, seenCycles, tokenIds) {
120
137
  const stack = [];
121
138
  const onPath = /* @__PURE__ */ new Set();
122
139
  const pathOrder = [];
@@ -149,7 +166,7 @@ function iterativeDfs(root, adjacency, visited, out, seenCycles) {
149
166
  ...pathOrder.slice(cycleStart),
150
167
  neighbor
151
168
  ];
152
- const key = canonicalCycleKey(cycle);
169
+ const key = canonicalCycleKey(cycle, tokenIds);
153
170
  if (!seenCycles.has(key)) {
154
171
  seenCycles.add(key);
155
172
  out.push(cycle);
@@ -160,26 +177,27 @@ function iterativeDfs(root, adjacency, visited, out, seenCycles) {
160
177
  }
161
178
  }
162
179
  __name(iterativeDfs, "iterativeDfs");
163
- function canonicalCycleKey(cycle) {
164
- const strs = cycle.map(stringifyToken);
180
+ function canonicalCycleKey(cycle, tokenIds) {
181
+ const ids = cycle.map((token) => {
182
+ let id = tokenIds.get(token);
183
+ if (id === void 0) {
184
+ id = tokenIds.size;
185
+ tokenIds.set(token, id);
186
+ }
187
+ return id;
188
+ });
165
189
  let minIndex = 0;
166
- for (let i = 1; i < strs.length; i += 1) {
167
- if (strs[i] < strs[minIndex]) {
190
+ for (let i = 1; i < ids.length; i += 1) {
191
+ if (ids[i] < ids[minIndex]) {
168
192
  minIndex = i;
169
193
  }
170
194
  }
171
195
  return [
172
- ...strs.slice(minIndex),
173
- ...strs.slice(0, minIndex)
196
+ ...ids.slice(minIndex),
197
+ ...ids.slice(0, minIndex)
174
198
  ].join("\u2192");
175
199
  }
176
200
  __name(canonicalCycleKey, "canonicalCycleKey");
177
- function stringifyToken(token) {
178
- if (typeof token === "string") return `s:${token}`;
179
- if (typeof token === "function") return `c:${token.name ?? "<anon>"}`;
180
- return "u:<unknown>";
181
- }
182
- __name(stringifyToken, "stringifyToken");
183
201
 
184
202
  // src/internal/metadata.ts
185
203
  var METADATA_KEYS = {
@@ -207,7 +225,7 @@ var METADATA_KEYS = {
207
225
  SQUAD: "usetheo:di:squad",
208
226
  /** Map<string|symbol, StepMetadata> from `@Step()` method decorator. */
209
227
  STEP: "usetheo:di:step",
210
- /** HitlOptions from `@Hitl()` method decorator. */
228
+ /** Map<string|symbol, HitlMetadata> from `@Hitl()` method decorator. */
211
229
  HITL: "usetheo:di:hitl",
212
230
  /** AutoSummarizeConfig from `@AutoSummarize()` class decorator. */
213
231
  AUTO_SUMMARIZE: "usetheo:di:auto-summarize",
@@ -217,7 +235,7 @@ var METADATA_KEYS = {
217
235
  WORKFLOW: "usetheo:di:workflow",
218
236
  /** EvalOptions from `@Eval()` class decorator. */
219
237
  EVAL: "usetheo:di:eval",
220
- /** CronMetadata from `@Cron()` method decorator. */
238
+ /** Map<string|symbol, CronMetadata> from `@Cron()` method decorator. */
221
239
  CRON: "usetheo:di:cron",
222
240
  /** Map<string|symbol, SubscriptionOptions> from `@Subscription()` property decorator. */
223
241
  SUBSCRIPTION: "usetheo:di:subscription",
@@ -269,6 +287,21 @@ function isInjectable(target) {
269
287
  return readInjectableMetadata(target) !== void 0;
270
288
  }
271
289
  __name(isInjectable, "isInjectable");
290
+ function readPostConstruct(target) {
291
+ return readLifecycleHook(target, METADATA_KEYS.POST_CONSTRUCT);
292
+ }
293
+ __name(readPostConstruct, "readPostConstruct");
294
+ function readPreDestroy(target) {
295
+ return readLifecycleHook(target, METADATA_KEYS.PRE_DESTROY);
296
+ }
297
+ __name(readPreDestroy, "readPreDestroy");
298
+ function readLifecycleHook(target, key) {
299
+ if (!hasReflectMetadata()) return void 0;
300
+ const out = Reflect.getMetadata(key, target);
301
+ if (typeof out === "string" || typeof out === "symbol") return out;
302
+ return void 0;
303
+ }
304
+ __name(readLifecycleHook, "readLifecycleHook");
272
305
  var PRIMITIVE_WRAPPERS = /* @__PURE__ */ new Set([
273
306
  Number,
274
307
  String,
@@ -309,7 +342,7 @@ var InvalidModuleError = class extends Error {
309
342
  target;
310
343
  name = "InvalidModuleError";
311
344
  constructor(target) {
312
- super(`Class ${target.name ?? "<anonymous>"} has no @Module() decorator. Add @Module({ providers: [...], imports: [...], exports: [...] }) above the class declaration.`), this.target = target;
345
+ super(`Class ${describeClassName(target, "<anonymous>")} has no @Module() decorator. Add @Module({ providers: [...], imports: [...], exports: [...] }) above the class declaration.`), this.target = target;
313
346
  }
314
347
  };
315
348
  var InvalidExportError = class extends Error {
@@ -399,6 +432,11 @@ var Scope = {
399
432
  };
400
433
 
401
434
  // src/container.ts
435
+ var ASYNC_CONTEXT = /* @__PURE__ */ Symbol("theokit.di.asyncContext");
436
+ function isAsyncContext(ctx) {
437
+ return ctx[ASYNC_CONTEXT] === true;
438
+ }
439
+ __name(isAsyncContext, "isAsyncContext");
402
440
  var Container = class {
403
441
  static {
404
442
  __name(this, "Container");
@@ -424,7 +462,7 @@ var Container = class {
424
462
  * - A full Provider (useClass / useFactory / useValue / useExisting)
425
463
  * - A bare class (shorthand expands to ClassProvider { provide: X, useClass: X })
426
464
  *
427
- * Per v1.1 EC-1, ClassProvider validation runs via `validateClassProvider()`
465
+ * ClassProvider validation runs via `validateClassProvider()`
428
466
  * regardless of which API path was used.
429
467
  */
430
468
  register(providerOrClass) {
@@ -444,9 +482,9 @@ var Container = class {
444
482
  * modules. Walks imports BFS, registers every provider, validates
445
483
  * exports.
446
484
  *
447
- * Per v1.1 EC-4: undecorated class throws `InvalidModuleError`.
448
- * Per v1.2 EC-R2-5: respects the freeze-after-first-resolve guarantee
449
- * (each child `register()` checks `assertNotFrozen`).
485
+ * An undecorated class throws `InvalidModuleError`. Respects the
486
+ * freeze-after-first-resolve guarantee — each child `register()` checks
487
+ * `assertNotFrozen`.
450
488
  */
451
489
  registerModule(moduleClass) {
452
490
  this.assertNotDisposed();
@@ -483,7 +521,7 @@ var Container = class {
483
521
  * providers resolved within `callback` (or any async continuation) share
484
522
  * a single per-request cache.
485
523
  *
486
- * v1.1 EC-3: try/finally guarantees REQUEST-scoped instances are disposed
524
+ * try/finally guarantees REQUEST-scoped instances are disposed
487
525
  * even if the callback throws.
488
526
  */
489
527
  async runInRequest(callback) {
@@ -501,7 +539,7 @@ var Container = class {
501
539
  /**
502
540
  * Debug helper — returns a snapshot of the dependency graph.
503
541
  *
504
- * Per ADR D7: detects cycles in unused providers too (resolve-time
542
+ * Detects cycles in unused providers too (resolve-time
505
543
  * detection only fires for resolves that actually traverse the cycle).
506
544
  * Use this proactively in tests / dev mode to surface latent cycles.
507
545
  */
@@ -602,7 +640,7 @@ var Container = class {
602
640
  }
603
641
  }
604
642
  /**
605
- * v1.1 EC-1: shared by both declarative providers: [] AND imperative
643
+ * Shared by both declarative providers: [] AND imperative
606
644
  * register() — every class provider must have @Injectable().
607
645
  */
608
646
  validateClassProvider(provider) {
@@ -617,7 +655,7 @@ var Container = class {
617
655
  if (this.disposed) throw new ContainerDisposedError();
618
656
  }
619
657
  /**
620
- * v1.2 EC-R2-5: container freezes on first resolve. Late registrations
658
+ * The container freezes on first resolve. Late registrations
621
659
  * require explicit `allowDynamicRegistration: true` (testing escape hatch).
622
660
  */
623
661
  assertNotFrozen(token) {
@@ -648,7 +686,8 @@ var Container = class {
648
686
  token: provider.provide,
649
687
  scope,
650
688
  factory: /* @__PURE__ */ __name((ctx) => this.constructClassWithAsyncFallback(target, ctx), "factory"),
651
- classTarget: target
689
+ classTarget: target,
690
+ containerOwned: true
652
691
  };
653
692
  }
654
693
  fromFactoryProvider(provider) {
@@ -663,7 +702,8 @@ var Container = class {
663
702
  }
664
703
  return Promise.all(injectTokens.map((dep) => ctx.resolveAsync(dep))).then((asyncArgs) => provider.useFactory(...asyncArgs));
665
704
  }, "factory"),
666
- injectTokens
705
+ injectTokens,
706
+ containerOwned: true
667
707
  };
668
708
  }
669
709
  /**
@@ -694,7 +734,8 @@ var Container = class {
694
734
  return {
695
735
  token: provider.provide,
696
736
  scope: Scope.SINGLETON,
697
- factory: /* @__PURE__ */ __name(() => provider.useValue, "factory")
737
+ factory: /* @__PURE__ */ __name(() => provider.useValue, "factory"),
738
+ containerOwned: false
698
739
  };
699
740
  }
700
741
  fromExistingProvider(provider) {
@@ -702,15 +743,16 @@ var Container = class {
702
743
  token: provider.provide,
703
744
  scope: Scope.SINGLETON,
704
745
  factory: /* @__PURE__ */ __name((ctx) => ctx.resolve(provider.useExisting), "factory"),
705
- aliasTarget: provider.useExisting
746
+ aliasTarget: provider.useExisting,
747
+ containerOwned: false
706
748
  };
707
749
  }
708
750
  /**
709
751
  * Resolve constructor params + build instance. Tries sync first; if any
710
752
  * dep is async, falls back to awaiting via `resolveAsync`.
711
753
  *
712
- * Refactored via Extract Method (ADR D422): orchestrates 3 helpers:
713
- * - validateMetadata: EC-12 detect emitDecoratorMetadata off
754
+ * Refactored via Extract Method: orchestrates 3 helpers:
755
+ * - validateMetadata: detect emitDecoratorMetadata off
714
756
  * - tryResolveSync: sync resolution loop with AsyncProvider bailout
715
757
  * - resolveAllAsync: Promise.all fallback when any dep is async
716
758
  */
@@ -724,12 +766,13 @@ var Container = class {
724
766
  this.validateMetadata(target, paramTypes);
725
767
  const syncResult = this.tryResolveSync(target, paramTypes, injectTokens, optionalFlags, ctx);
726
768
  if ("args" in syncResult) {
727
- return new target(...syncResult.args);
769
+ const instance = new target(...syncResult.args);
770
+ return isAsyncContext(ctx) ? runPostConstructAsync(target, instance) : runPostConstructSync(target, instance);
728
771
  }
729
- return this.resolveAllAsync(target, paramTypes, injectTokens, optionalFlags, ctx);
772
+ return this.resolveAllAsync(target, paramTypes, injectTokens, optionalFlags, ctx).then((instance) => runPostConstructAsync(target, instance));
730
773
  }
731
774
  /**
732
- * EC-12 detection: zero paramTypes for a class that declares a non-empty
775
+ * Detection: zero paramTypes for a class that declares a non-empty
733
776
  * constructor strongly suggests emitDecoratorMetadata is off.
734
777
  */
735
778
  validateMetadata(target, paramTypes) {
@@ -744,7 +787,7 @@ var Container = class {
744
787
  */
745
788
  handlePrimitiveParam(target, paramType, index, isOptional) {
746
789
  if (isOptional) return void 0;
747
- throw new TypeError(`Class ${target.name} has a primitive/interface constructor parameter at index ${index} (emitted as ${paramType.name ?? "<unknown>"}). Primitives and interfaces cannot be auto-resolved \u2014 use \`@Inject('SOME_STRING_TOKEN')\` to provide an explicit token.`);
790
+ throw new TypeError(`Class ${target.name} has a primitive/interface constructor parameter at index ${index} (emitted as ${describeClassName(paramType, "<unknown>")}). Primitives and interfaces cannot be auto-resolved \u2014 use \`@Inject('SOME_STRING_TOKEN')\` to provide an explicit token.`);
748
791
  }
749
792
  /**
750
793
  * Attempt sync resolution. Returns `{ args }` on success, `{ needsAsync: true }`
@@ -836,14 +879,14 @@ var Container = class {
836
879
  this.storeInCache(token, value, registration.scope);
837
880
  value.then((resolved) => {
838
881
  this.storeInCache(token, resolved, registration.scope);
839
- this.trackInstance(resolved, registration.scope);
882
+ this.trackInstance(resolved, registration);
840
883
  }, () => {
841
884
  this.deleteFromCache(token, registration.scope);
842
885
  });
843
886
  throw new AsyncProviderInSyncResolveError(token);
844
887
  }
845
888
  this.storeInCache(token, value, registration.scope);
846
- this.trackInstance(value, registration.scope);
889
+ this.trackInstance(value, registration);
847
890
  return value;
848
891
  }
849
892
  // ─────────────────────────────────────────────────────────────────────
@@ -876,14 +919,14 @@ var Container = class {
876
919
  this.storeInCache(token, result, registration.scope);
877
920
  result.then((value) => {
878
921
  this.storeInCache(token, value, registration.scope);
879
- this.trackInstance(value, registration.scope);
922
+ this.trackInstance(value, registration);
880
923
  }, () => {
881
924
  this.deleteFromCache(token, registration.scope);
882
925
  });
883
926
  return result;
884
927
  }
885
928
  this.storeInCache(token, result, registration.scope);
886
- this.trackInstance(result, registration.scope);
929
+ this.trackInstance(result, registration);
887
930
  return result;
888
931
  }
889
932
  // ─────────────────────────────────────────────────────────────────────
@@ -918,8 +961,18 @@ var Container = class {
918
961
  store?.cache.delete(token);
919
962
  }
920
963
  }
921
- trackInstance(value, scope) {
922
- if (!isDisposable(value)) return;
964
+ /**
965
+ * Record an instance for teardown, when this container is the one that should tear it down.
966
+ *
967
+ * Two questions, in this order. Does the container OWN it — see `containerOwned`; a value the
968
+ * caller handed in and an instance reached through an alias are both refused here. And does it
969
+ * have any teardown at all: a class whose only teardown is `@PreDestroy` has no `dispose()`, so
970
+ * testing `isDisposable` alone would silently skip it.
971
+ */
972
+ trackInstance(value, registration) {
973
+ if (!registration.containerOwned) return;
974
+ const { scope } = registration;
975
+ if (!isDisposable(value) && !hasPreDestroy(value)) return;
923
976
  if (scope === Scope.SINGLETON) {
924
977
  this.singletonInstances.push(value);
925
978
  return;
@@ -945,11 +998,14 @@ var Container = class {
945
998
  };
946
999
  }
947
1000
  createContextAsync(path) {
948
- return {
1001
+ const ctx = {
949
1002
  path,
950
1003
  resolve: /* @__PURE__ */ __name((t) => this.resolveInContext(t, this.createContext(path)), "resolve"),
951
1004
  resolveAsync: /* @__PURE__ */ __name((t) => this.resolveAsyncInContext(t, this.createContextAsync(path)), "resolveAsync")
952
1005
  };
1006
+ return Object.assign(ctx, {
1007
+ [ASYNC_CONTEXT]: true
1008
+ });
953
1009
  }
954
1010
  // ─────────────────────────────────────────────────────────────────────
955
1011
  // Internal: disposal
@@ -960,10 +1016,11 @@ var Container = class {
960
1016
  const instance = instances[i];
961
1017
  if (instance === void 0) continue;
962
1018
  try {
1019
+ await callPreDestroy(instance);
963
1020
  const asAsync = instance[Symbol.asyncDispose];
964
1021
  if (typeof asAsync === "function") {
965
1022
  await asAsync.call(instance);
966
- } else {
1023
+ } else if (isDisposable(instance)) {
967
1024
  await instance.dispose();
968
1025
  }
969
1026
  } catch (err) {
@@ -984,6 +1041,49 @@ function isDisposable(value) {
984
1041
  return false;
985
1042
  }
986
1043
  __name(isDisposable, "isDisposable");
1044
+ function callPostConstruct(target, instance) {
1045
+ const hook = readPostConstruct(target);
1046
+ if (hook === void 0) return void 0;
1047
+ const method = instance[hook];
1048
+ if (typeof method !== "function") return void 0;
1049
+ return method.call(instance);
1050
+ }
1051
+ __name(callPostConstruct, "callPostConstruct");
1052
+ function runPostConstructSync(target, instance) {
1053
+ const returned = callPostConstruct(target, instance);
1054
+ if (isThenable(returned)) {
1055
+ throw new AsyncPostConstructInSyncResolveError(target.name, String(readPostConstruct(target)));
1056
+ }
1057
+ return instance;
1058
+ }
1059
+ __name(runPostConstructSync, "runPostConstructSync");
1060
+ async function runPostConstructAsync(target, instance) {
1061
+ const returned = callPostConstruct(target, instance);
1062
+ if (isThenable(returned)) await returned;
1063
+ return instance;
1064
+ }
1065
+ __name(runPostConstructAsync, "runPostConstructAsync");
1066
+ async function callPreDestroy(instance) {
1067
+ const ctor = instance.constructor;
1068
+ if (typeof ctor !== "function") return;
1069
+ const hook = readPreDestroy(ctor);
1070
+ if (hook === void 0) return;
1071
+ const method = instance[hook];
1072
+ if (typeof method !== "function") return;
1073
+ await method.call(instance);
1074
+ }
1075
+ __name(callPreDestroy, "callPreDestroy");
1076
+ function hasPreDestroy(value) {
1077
+ if (value === null || typeof value !== "object") return false;
1078
+ const ctor = value.constructor;
1079
+ if (typeof ctor !== "function") return false;
1080
+ return readPreDestroy(ctor) !== void 0;
1081
+ }
1082
+ __name(hasPreDestroy, "hasPreDestroy");
1083
+ function isThenable(value) {
1084
+ return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
1085
+ }
1086
+ __name(isThenable, "isThenable");
987
1087
 
988
1088
  // src/decorators/inject.ts
989
1089
  function Inject(token) {
@@ -1044,6 +1144,7 @@ function Qualifier(name) {
1044
1144
  }
1045
1145
  __name(Qualifier, "Qualifier");
1046
1146
 
1147
+ exports.AsyncPostConstructInSyncResolveError = AsyncPostConstructInSyncResolveError;
1047
1148
  exports.AsyncProviderInSyncResolveError = AsyncProviderInSyncResolveError;
1048
1149
  exports.Container = Container;
1049
1150
  exports.ContainerDisposedError = ContainerDisposedError;
@@ -1066,6 +1167,7 @@ exports.ReflectMetadataMissingError = ReflectMetadataMissingError;
1066
1167
  exports.Scope = Scope;
1067
1168
  exports.ScopeViolationError = ScopeViolationError;
1068
1169
  exports.TokenNotFoundError = TokenNotFoundError;
1170
+ exports.describeClassName = describeClassName;
1069
1171
  exports.describeToken = describeToken;
1070
1172
  //# sourceMappingURL=index.cjs.map
1071
1173
  //# sourceMappingURL=index.cjs.map