From 21bc81f2a025e1bc332e49717f6b1a24e1e8493e Mon Sep 17 00:00:00 2001 From: omermorad Date: Fri, 27 Nov 2026 19:33:07 +0200 Subject: [PATCH 1/4] test(e2e): cover the ER31 undefined token contract (#1064) --- e2e/jest/nestjs/package.json | 1 + .../nestjs/undefined-token-error.e2e.test.ts | 34 +++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 e2e/jest/nestjs/undefined-token-error.e2e.test.ts diff --git a/e2e/jest/nestjs/package.json b/e2e/jest/nestjs/package.json index 01729c07..98697f37 100644 --- a/e2e/jest/nestjs/package.json +++ b/e2e/jest/nestjs/package.json @@ -23,6 +23,7 @@ "@jest/globals": "^30.5.2", "@types/node": "^26.6.6", "@suites/types.common": "e2e", + "@suites/types.di": "e2e", "jest-jasmine2": "^30.5.2", "jest-environment-node": "^30.5.2" }, diff --git a/e2e/jest/nestjs/undefined-token-error.e2e.test.ts b/e2e/jest/nestjs/undefined-token-error.e2e.test.ts new file mode 100644 index 00000000..8c452926 --- /dev/null +++ b/e2e/jest/nestjs/undefined-token-error.e2e.test.ts @@ -0,0 +1,34 @@ +import 'reflect-metadata'; +import { Inject, Injectable } from '@nestjs/common'; +import { UndefinedTokenError } from '@suites/types.di'; +import { TestBed } from '@suites/unit'; + +@Injectable() +class ServiceWithMissingToken { + constructor(@Inject(undefined) readonly dependency: unknown) {} +} + +describe('UndefinedTokenError', () => { + it('exposes ER31 when constructed from the public package', () => { + const error = new UndefinedTokenError('A constructor dependency needs a token.'); + + expect(error).toMatchObject({ + name: 'UndefinedTokenError', + code: 'ER31', + message: 'Undefined token (code ER31)\nA constructor dependency needs a token.', + }); + }); + + it('reports ER31 when NestJS cannot detect a declared constructor token', async () => { + const compilation = TestBed.solitary(ServiceWithMissingToken).compile(); + + await expect(compilation).rejects.toBeInstanceOf(UndefinedTokenError); + await expect(compilation).rejects.toMatchObject({ + name: 'UndefinedTokenError', + code: 'ER31', + message: expect.stringMatching( + /^Undefined token \(code ER31\)\n[\s\S]*dependency at index \[0\]/ + ), + }); + }); +}); From 498c22d7d5c177a466b3ef915f603b7bb1875c98 Mon Sep 17 00:00:00 2001 From: omermorad Date: Fri, 27 Nov 2026 19:44:42 +0200 Subject: [PATCH 2/4] feat(di): report dependency inspection failures with their source BREAKING CHANGE: DI adapters must return an InspectionResult from inspect(). Undefined explicit tokens now use ER31. Unit rejects unresolved dependencies in real constructors and preserves the declaring slot and framework cause. --- e2e/fixtures/adapter-loading.cjs | 6 +- .../nestjs/undefined-token-error.e2e.test.ts | 74 +++++++- e2e/verify-adapter-loading.cjs | 14 +- .../assets/integration.assets.ts | 33 ++-- .../sociable/assets/integration.assets.ts | 33 ++-- .../solitary/assets/integration.assets.ts | 34 ++-- .../core/src/services/composition.spec.ts | 7 +- .../src/services/dependency-resolver.spec.ts | 49 ++++- .../core/src/services/dependency-resolver.ts | 101 +++++++--- .../core/src/services/override-usage.spec.ts | 2 +- .../core/src/services/sociable-guards.spec.ts | 27 ++- .../core/src/services/unit-mocker.spec.ts | 2 +- packages/core/src/services/unit-mocker.ts | 3 +- .../injection-js/src/class-ctor-reflector.ts | 173 ++++++++++++++---- .../injection-js/src/dependencies-adapter.ts | 14 +- .../test/adapter.integration.test.ts | 75 ++++++-- .../inversify-adapter.integration.test.ts | 69 ++++++- .../di/inversify/src/class-ctor-reflector.ts | 101 +++------- .../di/inversify/src/class-props-reflector.ts | 84 +++------ .../src/dependencies-adapter.spec.ts | 23 ++- .../di/inversify/src/dependencies-adapter.ts | 78 +++++--- .../src/identifier-builder.static.spec.ts | 12 +- .../src/identifier-builder.static.ts | 60 +++--- .../nestjs-adapter.integration.test.ts | 52 +++++- .../di/nestjs/src/class-ctor-reflector.ts | 87 ++++----- .../di/nestjs/src/class-props-reflector.ts | 74 ++++---- .../di/nestjs/src/dependencies-adapter.ts | 19 +- packages/di/nestjs/src/index.ts | 14 +- .../di/nestjs/src/params-token-resolver.ts | 88 +-------- .../property-reflection-strategies.static.ts | 98 ---------- packages/di/nestjs/src/types.ts | 8 +- packages/types/di/README.md | 2 +- packages/types/di/src/errors.ts | 38 +++- packages/types/di/src/index.ts | 29 ++- ...aper-package-resolving.integration.test.ts | 5 +- packages/unit/__test__/assets/test-adapter.ts | 2 +- .../__test__/package-resolver.base.spec.ts | 9 +- scripts/e2e-harness.test.cjs | 9 +- scripts/e2e/major-canary.cjs | 4 + scripts/eslint-type-contracts.config.mjs | 3 +- scripts/lint/type-contracts.test.cjs | 8 + 41 files changed, 929 insertions(+), 694 deletions(-) delete mode 100644 packages/di/nestjs/src/property-reflection-strategies.static.ts diff --git a/e2e/fixtures/adapter-loading.cjs b/e2e/fixtures/adapter-loading.cjs index 0e897d92..2a84cc0d 100644 --- a/e2e/fixtures/adapter-loading.cjs +++ b/e2e/fixtures/adapter-loading.cjs @@ -7,7 +7,11 @@ module.exports = async function verify(TestBed, scenario, packageName) { // A consumer can configure a builder and compile on a later turn. await new Promise((resolve) => setImmediate(resolve)); for (const builder of builders) { - if (scenario === 'valid') { + if (['legacy', 'invalid-registry', 'invalid-failure'].includes(scenario)) { + await assert.rejects(builder.compile(), { code: 'ER021', message: /Update your DI adapter for v5/ }); + continue; + } + if (scenario === 'valid' || scenario === 'multiple') { const { unit } = await builder.compile(); assert.ok(unit instanceof Subject); continue; diff --git a/e2e/jest/nestjs/undefined-token-error.e2e.test.ts b/e2e/jest/nestjs/undefined-token-error.e2e.test.ts index 8c452926..6e99f5da 100644 --- a/e2e/jest/nestjs/undefined-token-error.e2e.test.ts +++ b/e2e/jest/nestjs/undefined-token-error.e2e.test.ts @@ -1,5 +1,5 @@ import 'reflect-metadata'; -import { Inject, Injectable } from '@nestjs/common'; +import { forwardRef, Inject, Injectable } from '@nestjs/common'; import { UndefinedTokenError } from '@suites/types.di'; import { TestBed } from '@suites/unit'; @@ -32,3 +32,75 @@ describe('UndefinedTokenError', () => { }); }); }); + +describe('NestJS metadata diagnostics', () => { + it('reports the root, declaring class and symbol property for an undefined forward reference', async () => { + const property = Symbol('repository'); + @Injectable() + class Handler { + @Inject(forwardRef(() => undefined)) + readonly [property]!: unknown; + } + @Injectable() + class Checkout { + constructor(readonly handler: Handler) {} + } + await expect(TestBed.sociable(Checkout).expose(Handler).compile()).rejects.toMatchObject({ + code: 'ER31', + context: { + root: Checkout, + failure: { target: Handler, location: { kind: 'property', key: property } }, + }, + }); + }); + + it('reads an exposed dependency once per compile and preserves a throwing forward reference', async () => { + @Injectable() + class Repository {} + const resolve = jest.fn(() => Repository); + @Injectable() + class Handler { + constructor(@Inject(forwardRef(resolve)) readonly repository: Repository) {} + } + @Injectable() + class Checkout { + constructor(readonly handler: Handler) {} + } + const build = () => TestBed.sociable(Checkout).expose(Handler).compile(); + await build(); + expect(resolve).toHaveBeenCalledTimes(1); + const cause = new Error('cannot read application configuration'); + resolve.mockImplementation(() => { + throw cause; + }); + await expect(build()).rejects.toBe(cause); + expect(resolve).toHaveBeenCalledTimes(2); + }); + + it('keeps ER30 for a missing reflected dependency', async () => { + @Injectable() + class Checkout { + constructor(readonly handler: undefined) {} + } + await expect(TestBed.solitary(Checkout).compile()).rejects.toMatchObject({ + name: 'UndefinedDependencyError', + code: 'ER30', + context: { + root: Checkout, + failure: { target: Checkout, location: { kind: 'parameter', index: 0 } }, + }, + }); + }); +}); + +it('mocks a solitary collaborator without inspecting its own constructor', async () => { + class Repository { + constructor(readonly missing: unknown) {} + } + @Injectable() + class Checkout { + constructor(readonly repository: Repository) {} + } + const { unit, unitRef } = await TestBed.solitary(Checkout).compile(); + expect(unit.repository).toBe(unitRef.get(Repository)); +}); diff --git a/e2e/verify-adapter-loading.cjs b/e2e/verify-adapter-loading.cjs index 565b0fab..679018e0 100644 --- a/e2e/verify-adapter-loading.cjs +++ b/e2e/verify-adapter-loading.cjs @@ -25,7 +25,7 @@ const manifest = JSON.parse(readFileSync(join(installed, 'package.json'), 'utf8' const fromUnit = createRequire(realpathSync(join(installed, 'package.json'))); const packages = { di: 'di.nestjs', doubles: 'doubles.jest' }; const valid = { - di: 'exports.adapter = { inspect: () => ({ list: () => [], resolve: () => undefined }) };', + di: 'exports.adapter = { inspect: () => ({ kind: "success", registry: { list: () => [], resolve: () => undefined } }) };', doubles: 'exports.adapter = { mock: () => ({}), stub: () => () => {} };', }; @@ -42,6 +42,10 @@ function installAdapter(kind, scenario) { const sources = { valid: valid[kind], throws: 'throw globalThis.adapterFailure;', + legacy: 'exports.adapter = { inspect: () => ({ list: () => [], resolve: () => undefined }) };', + 'invalid-registry': 'exports.adapter = { inspect: () => ({ kind: "success", registry: {} }) };', + 'invalid-failure': 'exports.adapter = { inspect: (target) => ({ kind: "failure", target, reason: "undefined-token", location: { kind: "parameter", index: -1 }, cause: undefined }) };', + multiple: valid[kind], 'no-export': 'exports.unrelated = true;', malformed: kind === 'di' ? 'exports.adapter = { inspect: 1 };' : 'exports.adapter = { mock() {} };', @@ -71,6 +75,7 @@ try { for (const [kind, name] of Object.entries(packages)) { for (const scenario of [ 'valid', + ...(kind === 'di' ? ['legacy', 'invalid-registry', 'invalid-failure', 'multiple'] : []), 'missing', 'throws', 'no-export', @@ -81,6 +86,12 @@ try { for (const adapter of Object.keys(packages)) { installAdapter(adapter, adapter === kind ? scenario : 'valid'); } + const secondary = join(scope, 'di.inversify'); + if (scenario === 'multiple') { + mkdirSync(secondary); + // Both packages are loadable. A call to the second adapter fails this consumer. + writeFileSync(join(secondary, 'index.js'), "exports.adapter = { inspect() { throw new Error('Expected NestJS to take precedence'); } };"); + } const result = spawnSync( process.execPath, [ @@ -99,6 +110,7 @@ try { } ); assert.ifError(result.error); + if (scenario === 'multiple') rmSync(secondary, { recursive: true }); assert.equal(result.status, 0, `${format} ${kind} ${scenario}\n${result.stderr}`); } } diff --git a/packages/core/__test__/sociable-empty-constructor/assets/integration.assets.ts b/packages/core/__test__/sociable-empty-constructor/assets/integration.assets.ts index 01afcd4f..ad986c93 100644 --- a/packages/core/__test__/sociable-empty-constructor/assets/integration.assets.ts +++ b/packages/core/__test__/sociable-empty-constructor/assets/integration.assets.ts @@ -25,22 +25,25 @@ const registryToClass: Map = new Map { return { - list: () => { - return registryToClass.get(targetClass)!.list(); - }, - resolve( - identifier: Type | string, - metadata?: IdentifierMetadata - ): ClassInjectable | undefined { - return registryToClass - .get(targetClass)! - .list() - .find((injectable: WithMetadata) => { - const subject = normalizeIdentifier(identifier, metadata); - const toFind = normalizeIdentifier(injectable.identifier, injectable.metadata); + kind: 'success', + registry: { + list: () => { + return registryToClass.get(targetClass)!.list(); + }, + resolve( + identifier: Type | string, + metadata?: IdentifierMetadata + ): ClassInjectable | undefined { + return registryToClass + .get(targetClass)! + .list() + .find((injectable: WithMetadata) => { + const subject = normalizeIdentifier(identifier, metadata); + const toFind = normalizeIdentifier(injectable.identifier, injectable.metadata); - return isDeepStrictEqual(toFind, subject); - }); + return isDeepStrictEqual(toFind, subject); + }); + }, }, }; }, diff --git a/packages/core/__test__/sociable/assets/integration.assets.ts b/packages/core/__test__/sociable/assets/integration.assets.ts index 4dc6dd25..d6a4e05a 100644 --- a/packages/core/__test__/sociable/assets/integration.assets.ts +++ b/packages/core/__test__/sociable/assets/integration.assets.ts @@ -47,22 +47,25 @@ registryToClass.set(UserService, userServiceRegistry); export const FakeAdapter: DependencyInjectionAdapter = { inspect: (targetClass: Type) => { return { - list: () => { - return registryToClass.get(targetClass)!.list(); - }, - resolve( - identifier: Type | string, - metadata?: IdentifierMetadata - ): ClassInjectable | undefined { - return registryToClass - .get(targetClass)! - .list() - .find((injectable: WithMetadata) => { - const subject = normalizeIdentifier(identifier, metadata); - const toFind = normalizeIdentifier(injectable.identifier, injectable.metadata); + kind: 'success', + registry: { + list: () => { + return registryToClass.get(targetClass)!.list(); + }, + resolve( + identifier: Type | string, + metadata?: IdentifierMetadata + ): ClassInjectable | undefined { + return registryToClass + .get(targetClass)! + .list() + .find((injectable: WithMetadata) => { + const subject = normalizeIdentifier(identifier, metadata); + const toFind = normalizeIdentifier(injectable.identifier, injectable.metadata); - return isDeepStrictEqual(toFind, subject); - }); + return isDeepStrictEqual(toFind, subject); + }); + }, }, }; }, diff --git a/packages/core/__test__/solitary/assets/integration.assets.ts b/packages/core/__test__/solitary/assets/integration.assets.ts index 0e3764f6..ce3cf810 100644 --- a/packages/core/__test__/solitary/assets/integration.assets.ts +++ b/packages/core/__test__/solitary/assets/integration.assets.ts @@ -1,12 +1,13 @@ import { isDeepStrictEqual } from 'node:util'; -import { +import type { DependencyInjectionAdapter, ClassInjectable, IdentifierMetadata, - UndefinedDependency, - WithMetadata, + WithMetadata} from '@suites/types.di'; +import { + UndefinedDependency } from '@suites/types.di'; -import { Type } from '@suites/types.common'; +import type { Type } from '@suites/types.common'; import { normalizeIdentifier } from '../../../src/normalize-identifier.static.js'; interface Printer { @@ -168,17 +169,20 @@ const classInjectables: ClassInjectable[] = [ export const FakeDIAdapter: DependencyInjectionAdapter = { inspect: () => { return { - list: () => classInjectables, - resolve( - identifier: Type | string, - metadata?: IdentifierMetadata - ): ClassInjectable | undefined { - return classInjectables.find((injectable: WithMetadata) => { - const subject = normalizeIdentifier(identifier, metadata); - const toFind = normalizeIdentifier(injectable.identifier, injectable.metadata); - - return isDeepStrictEqual(toFind, subject); - }); + kind: 'success', + registry: { + list: () => classInjectables, + resolve( + identifier: Type | string, + metadata?: IdentifierMetadata + ): ClassInjectable | undefined { + return classInjectables.find((injectable: WithMetadata) => { + const subject = normalizeIdentifier(identifier, metadata); + const toFind = normalizeIdentifier(injectable.identifier, injectable.metadata); + + return isDeepStrictEqual(toFind, subject); + }); + }, }, }; }, diff --git a/packages/core/src/services/composition.spec.ts b/packages/core/src/services/composition.spec.ts index bf469060..b429eaba 100644 --- a/packages/core/src/services/composition.spec.ts +++ b/packages/core/src/services/composition.spec.ts @@ -19,8 +19,11 @@ function registry(entries: [Type, ClassInjectable[]][]): DependencyInjectionAdap return { canAutoConstruct: (type: Type) => entries.some(([target]) => type === target), inspect: (type: Type) => ({ - list: () => entries.find(([target]) => type === target)?.[1] ?? [], - resolve: () => undefined, + kind: 'success', + registry: { + list: () => entries.find(([target]) => type === target)?.[1] ?? [], + resolve: () => undefined, + }, }), } as DependencyInjectionAdapter; } diff --git a/packages/core/src/services/dependency-resolver.spec.ts b/packages/core/src/services/dependency-resolver.spec.ts index 8a12bbf1..9641813c 100644 --- a/packages/core/src/services/dependency-resolver.spec.ts +++ b/packages/core/src/services/dependency-resolver.spec.ts @@ -18,8 +18,11 @@ const secondary = { named: 'secondary' }; function adapterFor(target: Type, dependencies: ClassInjectable[]): DependencyInjectionAdapter { return { inspect: (type) => ({ - list: () => (type === target ? dependencies : []), - resolve: () => undefined, + kind: 'success', + registry: { + list: () => (type === target ? dependencies : []), + resolve: () => undefined, + }, }), } as DependencyInjectionAdapter; } @@ -151,3 +154,45 @@ describe('qualified dependency resolution', () => { expect(resolver.resolveOrMock(RealProvider, propertyMetadata)).toBe(second); }); }); + +describe('DI inspection failures', () => { + it('keeps the framework cause and declaring slot when inspecting a dependency', () => { + const cause = new Error('invalid framework metadata'); + const adapter: DependencyInjectionAdapter = { + inspect(target) { + if (target === Provider) { + return { + kind: 'failure', + reason: 'invalid-metadata', + target, + location: { kind: 'class' }, + cause, + }; + } + return adapterFor(Root, [{ identifier: Provider, value: Provider, type: 'PARAM' }]).inspect( + target + ); + }, + }; + const resolver = new DependencyResolver( + [Provider], + new DependencyContainer([]), + adapter, + jest.fn, + { mode: 'selective', bindings: new Map() }, + Root + ); + let failure: unknown; + try { + resolver.instantiateClass(Root); + } catch (error) { + failure = error; + } + expect(failure).toMatchObject({ + code: 'ER30', + context: { root: Root, failure: { target: Provider } }, + }); + ok(failure instanceof Error && 'cause' in failure); + expect(failure.cause).toBe(cause); + }); +}); diff --git a/packages/core/src/services/dependency-resolver.ts b/packages/core/src/services/dependency-resolver.ts index db47c3b7..2270e13b 100644 --- a/packages/core/src/services/dependency-resolver.ts +++ b/packages/core/src/services/dependency-resolver.ts @@ -1,5 +1,5 @@ import { isDeepStrictEqual } from 'node:util'; -import { DependencyResolutionError } from '@suites/types.common'; +import { DependencyResolutionError, SuitesError, SuitesErrorCode } from '@suites/types.common'; import type { AbstractType, FinalValue, Type } from '@suites/types.common'; import type { MockFunction, StubbedInstance } from '@suites/types.doubles'; import type { @@ -7,7 +7,11 @@ import type { DependencyInjectionAdapter, IdentifierMetadata, InjectableIdentifier, + InjectableRegistry, + InspectionFailure, + InspectionResult, } from '@suites/types.di'; +import { UndefinedDependencyError, UndefinedTokenError } from '@suites/types.di'; import type { CompositionBoundaryLookup, DependencyPathEntry } from './composition-boundary.js'; import type { DependencyContainer, IdentifierToMockOrFinal } from './dependency-container.js'; import { createGuardedDependency } from './guarded-dependency.js'; @@ -25,7 +29,30 @@ export type ResolverOptions = type ResolvedDependency = Type | FinalValue | StubbedInstance; type ResolvedBoundary = { value: ResolvedDependency }; +function validFailure(result: InspectionResult, target: Type): result is InspectionFailure { + if (result?.kind !== 'failure' || result.target !== target || !('cause' in result)) return false; + const { reason, location } = result; + if ( + reason !== 'undefined-dependency' && + reason !== 'undefined-token' && + reason !== 'invalid-metadata' && + reason !== 'unsupported-token' + ) + return false; + switch (location?.kind) { + case 'class': + return true; + case 'parameter': + return Number.isInteger(location.index) && location.index >= 0; + case 'property': + return typeof location.key === 'string' || typeof location.key === 'symbol'; + default: + return false; + } +} + export class DependencyResolver { + private readonly inspected = new Map(); private readonly dependencyMap = new DependencyMap(); private readonly usedMockEntries = new Set(); private readonly availableClassesToExpose = new Set(); @@ -38,7 +65,8 @@ export class DependencyResolver { private readonly mockedFromBeforeContainer: DependencyContainer, private readonly adapter: DependencyInjectionAdapter, private readonly mockFunction: MockFunction, - private readonly options: ResolverOptions = { mode: 'solitary' } + private readonly options: ResolverOptions = { mode: 'solitary' }, + private readonly root: Type | undefined = undefined ) {} private isExposedClass(identifier: InjectableIdentifier): identifier is Type { @@ -97,11 +125,47 @@ export class DependencyResolver { return undefined; } - public isLeafOrPrimitive(identifier: InjectableIdentifier): boolean { - return ( - typeof identifier !== 'function' || - this.adapter.inspect(identifier as Type).list().length === 0 - ); + private inspect(target: Type) { + const registry = this.inspected.get(target); + if (registry) return registry; + const result = this.adapter.inspect(target); + if ( + result?.kind === 'success' && + typeof result.registry?.list === 'function' && + typeof result.registry.resolve === 'function' + ) { + this.inspected.set(target, result.registry); + return result.registry; + } + if (!validFailure(result, target)) { + throw new SuitesError( + SuitesErrorCode.ADAPTER_ERROR, + 'Invalid DI adapter inspection result', + 'Update your DI adapter for v5. inspect() must return an InspectionResult containing a registry or a reflection failure.' + ); + } + + const { location, reason } = result; + const slot = + location.kind === 'parameter' + ? `dependency at index [${location.index}]` + : location.kind === 'property' + ? `dependency for property '${String(location.key)}'` + : 'constructor dependencies'; + const root = this.root ?? target; + const detail = `Cannot resolve ${slot} in '${target.name}' while constructing '${root.name}'.`; + const context = { root, failure: result }; + if (reason === 'undefined-token') { + throw new UndefinedTokenError( + `${detail} Check the declared token and any lazy reference.`, + context + ); + } + const advice = + reason === 'unsupported-token' + ? 'Use a dependency token supported by the installed adapter.' + : 'Check the injection decorator and emitted metadata.'; + throw new UndefinedDependencyError(`${detail} ${advice}`, context); } public resolveOrMock( @@ -141,23 +205,10 @@ export class DependencyResolver { return guard; } - if (this.isLeafOrPrimitive(identifier)) { - if (this.isExposedClass(identifier)) { - return this.instantiateClass(identifier, metadata); - } - - const mock = this.mockFunction(); - this.dependencyMap.set(identifier, mock, metadata); - return mock; - } - - if (typeof identifier === 'function' && !this.isExposedClass(identifier)) { - const mock = this.mockFunction(); - this.dependencyMap.set(identifier, mock, metadata); - return mock; - } - - return this.instantiateClass(identifier as Type, metadata); + if (this.isExposedClass(identifier)) return this.instantiateClass(identifier, metadata); + const mock = this.mockFunction(); + this.dependencyMap.set(identifier, mock, metadata); + return mock; } public instantiateClass( @@ -191,7 +242,7 @@ export class DependencyResolver { } try { - const injectableRegistry = this.adapter.inspect(type); + const injectableRegistry = this.inspect(type); injectableRegistry.list().forEach((injectable: ClassInjectable) => { this.availableClassesToExpose.add(injectable.identifier); diff --git a/packages/core/src/services/override-usage.spec.ts b/packages/core/src/services/override-usage.spec.ts index 228f41f4..330c533b 100644 --- a/packages/core/src/services/override-usage.spec.ts +++ b/packages/core/src/services/override-usage.spec.ts @@ -3,7 +3,7 @@ import { DependencyContainer, type IdentifierToMockOrFinal } from './dependency- import { DependencyResolver } from './dependency-resolver.js'; const adapter = { - inspect: () => ({ list: () => [] }), + inspect: () => ({ kind: 'success', registry: { list: () => [], resolve: () => undefined } }), } as DependencyInjectionAdapter; function resolver(entries: IdentifierToMockOrFinal[]) { diff --git a/packages/core/src/services/sociable-guards.spec.ts b/packages/core/src/services/sociable-guards.spec.ts index d67533cf..98da863f 100644 --- a/packages/core/src/services/sociable-guards.spec.ts +++ b/packages/core/src/services/sociable-guards.spec.ts @@ -21,8 +21,11 @@ class Checkout { function adapterFor(target: Type, dependencies: ClassInjectable[]): DependencyInjectionAdapter { return { inspect: (type) => ({ - list: () => (type === target ? dependencies : []), - resolve: () => undefined, + kind: 'success', + registry: { + list: () => (type === target ? dependencies : []), + resolve: () => undefined, + }, }), } as DependencyInjectionAdapter; } @@ -46,24 +49,20 @@ describe('sociable dependency guards', () => { it('injects an unused undeclared dependency without failing construction', async () => { const mocker = new UnitMocker(Promise.resolve(jest.fn), Promise.resolve(adapter)); - const result = await mocker.constructUnit( - Checkout, - [], - new DependencyContainer([]), - { mode: 'selective', bindings: new Map() } - ); + const result = await mocker.constructUnit(Checkout, [], new DependencyContainer([]), { + mode: 'selective', + bindings: new Map(), + }); expect(result.instance).toBeInstanceOf(Checkout); }); it('throws a path-aware violation when an undeclared dependency is used', async () => { const mocker = new UnitMocker(Promise.resolve(jest.fn), Promise.resolve(adapter)); - const { instance } = await mocker.constructUnit( - Checkout, - [], - new DependencyContainer([]), - { mode: 'selective', bindings: new Map() } - ); + const { instance } = await mocker.constructUnit(Checkout, [], new DependencyContainer([]), { + mode: 'selective', + bindings: new Map(), + }); expect(() => instance.available()).toThrow( /Cannot read available on undeclared dependency 'Inventory'.*Dependency path: 'Checkout' -> 'Inventory'/i diff --git a/packages/core/src/services/unit-mocker.spec.ts b/packages/core/src/services/unit-mocker.spec.ts index e4ea919a..931973ca 100644 --- a/packages/core/src/services/unit-mocker.spec.ts +++ b/packages/core/src/services/unit-mocker.spec.ts @@ -90,7 +90,7 @@ describe('Unit Mocker Unit Spec', () => { underTest = new UnitMocker( Promise.resolve(() => MockedFromBuilder), Promise.resolve({ - inspect: () => injectableRegistry, + inspect: () => ({ kind: 'success', registry: injectableRegistry }), }) ); }); diff --git a/packages/core/src/services/unit-mocker.ts b/packages/core/src/services/unit-mocker.ts index d640ad34..68032d5e 100644 --- a/packages/core/src/services/unit-mocker.ts +++ b/packages/core/src/services/unit-mocker.ts @@ -35,7 +35,8 @@ export class UnitMocker { mockContainer, await this.diAdapter, await this.mockFunction, - resolverOptions + resolverOptions, + targetClass ); const instance = dependencyResolver.instantiateClass(targetClass); diff --git a/packages/di/injection-js/src/class-ctor-reflector.ts b/packages/di/injection-js/src/class-ctor-reflector.ts index 784001ac..d4137b76 100644 --- a/packages/di/injection-js/src/class-ctor-reflector.ts +++ b/packages/di/injection-js/src/class-ctor-reflector.ts @@ -1,47 +1,152 @@ import 'reflect-metadata'; -import { InjectionToken, ReflectiveInjector } from 'injection-js'; +import { Inject, InjectionToken, ReflectiveInjector, resolveForwardRef } from 'injection-js'; import type { Type } from '@suites/types.common'; -import type { ClassInjectable, InjectableIdentifier } from '@suites/types.di'; -import { UndefinedDependency, UndefinedDependencyError } from '@suites/types.di'; +import type { ClassInjectable, InjectableIdentifier, InspectionFailure } from '@suites/types.di'; +import { UndefinedDependency } from '@suites/types.di'; export type ClassCtorReflector = ReturnType; -/** Reads constructor dependencies without creating a production injector or running constructors. */ -export function ClassCtorReflector() { - function reflectInjectables(targetClass: Type): ClassInjectable[] { - // Use InjectionJS's public resolver so token precedence, forward references, - // static parameters and lowered decorator metadata follow its own semantics. - let dependencies; - try { - dependencies = ReflectiveInjector.resolve([targetClass])[0].resolvedFactories[0].dependencies; - } catch (error) { - throw new UndefinedDependencyError( - `Cannot inspect constructor dependencies of '${targetClass.name}'. ` + - `Use @Inject(token) or enable decorator metadata. InjectionJS: ${String(error)}` - ); - } +interface LoweredDecorator { + readonly type: Type; + readonly args: readonly unknown[] | undefined; +} + +interface LoweredParameter { + readonly type: Type | undefined; + readonly decorators: readonly LoweredDecorator[] | undefined; +} + +function annotations(type: Type | undefined, decorators: readonly unknown[]): readonly unknown[] { + return type && type !== Object ? [type, ...decorators] : decorators; +} + +// InjectionJS supports static parameters, lowered decorators, and emitted Reflect metadata, +// in that order. Read each slot once so lazy tokens have the same identity as in production. +function parameters(target: Type): readonly unknown[] | undefined { + if (Object.prototype.hasOwnProperty.call(target, 'parameters') && 'parameters' in target) { + const slots = target.parameters; + if (Array.isArray(slots)) return slots; + } + + if ( + Object.prototype.hasOwnProperty.call(target, 'ctorParameters') && + 'ctorParameters' in target + ) { + const source = target.ctorParameters; + const lowered: readonly LoweredParameter[] = typeof source === 'function' ? source() : source; + return lowered.map((slot) => + annotations( + slot?.type, + (slot?.decorators ?? []).map(({ type, args }) => { + const decorator = 'annotationCls' in type ? (type.annotationCls as Type) : type; + return new decorator(...(args ?? [])); + }) + ) + ); + } + + const args: unknown[][] | undefined = Reflect.getOwnMetadata('parameters', target); + const types: Type[] | undefined = Reflect.getOwnMetadata('design:paramtypes', target); + if (!args && !types) return undefined; + return Array.from({ length: types?.length ?? args?.length ?? 0 }, (_, index) => + annotations(types?.[index], args?.[index] ?? []) + ); +} + +function injectable( + target: Type, + index: number, + token: unknown +): ClassInjectable | InspectionFailure { + if ( + typeof token !== 'function' && + typeof token !== 'string' && + typeof token !== 'symbol' && + !(token instanceof InjectionToken) + ) { + return { + kind: 'failure', + reason: 'unsupported-token', + target, + location: { kind: 'parameter', index }, + cause: undefined, + }; + } + return { + identifier: token as InjectableIdentifier, + value: typeof token === 'function' ? (token as Type) : UndefinedDependency, + type: 'PARAM', + }; +} + +function inspectParameter( + target: Type, + index: number, + slot: unknown +): ClassInjectable | InspectionFailure { + // The last type or explicit token wins; resolution modifiers do not change its identity. + const candidates: readonly unknown[] = Array.isArray(slot) ? slot : [slot]; + let selected: unknown; + for (const entry of candidates) { + if (typeof entry === 'function' || entry instanceof Inject || entry instanceof InjectionToken) + selected = entry; + } + if (!Array.isArray(slot) && slot != null) selected = slot; + const explicit = selected instanceof Inject; + // A user callback that throws must retain its exception identity. + const resolved: unknown = resolveForwardRef( + selected instanceof Inject ? selected.token : selected + ); + const undefinedToken = resolved === undefined && (explicit || typeof selected === 'function'); + try { + const [provider] = ReflectiveInjector.resolve([ + { provide: target, useFactory: () => undefined, deps: [[new Inject(resolved)]] }, + ]); + return injectable(target, index, provider.resolvedFactories[0].dependencies[0].key.token); + } catch (cause) { + return { + kind: 'failure', + reason: undefinedToken ? 'undefined-token' : 'undefined-dependency', + target, + location: { kind: 'parameter', index }, + cause, + }; + } +} - return dependencies.map(({ key }, index) => { - const token: unknown = key.token; - if ( - typeof token !== 'function' && - typeof token !== 'string' && - typeof token !== 'symbol' && - !(token instanceof InjectionToken) - ) { - throw new UndefinedDependencyError( - `Unsupported constructor token at index [${index}] in '${targetClass.name}'. ` + - 'Use a class, string, symbol, or InjectionToken.' - ); +/** Reads constructor metadata without running the constructor or creating an injector. */ +export function ClassCtorReflector() { + function reflectInjectables(target: Type): ClassInjectable[] | InspectionFailure { + const entries: ClassInjectable[] = []; + const slots = parameters(target); + if (slots) { + for (let index = 0; index < Math.max(target.length, slots.length); index++) { + const entry = inspectParameter(target, index, slots[index]); + if ('kind' in entry) return entry; + entries.push(entry); } + return entries; + } + // Leave undecorated and delegated constructors to the framework's own resolver. + let dependencies; + try { + dependencies = ReflectiveInjector.resolve([target])[0].resolvedFactories[0].dependencies; + } catch (cause) { return { - // InjectionToken is registered in the consumer's /metadata entry point. - identifier: token as InjectableIdentifier, - value: typeof token === 'function' ? (token as Type) : UndefinedDependency, - type: 'PARAM', + kind: 'failure', + reason: 'invalid-metadata', + target, + location: { kind: 'class' }, + cause, }; - }); + } + for (const [index, dependency] of dependencies.entries()) { + const entry = injectable(target, index, dependency.key.token); + if ('kind' in entry) return entry; + entries.push(entry); + } + return entries; } return { reflectInjectables }; diff --git a/packages/di/injection-js/src/dependencies-adapter.ts b/packages/di/injection-js/src/dependencies-adapter.ts index 1651cdb8..dfd5987e 100644 --- a/packages/di/injection-js/src/dependencies-adapter.ts +++ b/packages/di/injection-js/src/dependencies-adapter.ts @@ -20,12 +20,16 @@ export function DependenciesAdapter( }, inspect(targetClass: Type) { const injectables = classCtorReflector.reflectInjectables(targetClass); + if (!Array.isArray(injectables)) return injectables; return { - resolve(identifier: InjectableIdentifier) { - return injectables.find((injectable) => injectable.identifier === identifier); - }, - list() { - return injectables; + kind: 'success', + registry: { + resolve(identifier: InjectableIdentifier) { + return injectables.find((injectable) => injectable.identifier === identifier); + }, + list() { + return injectables; + }, }, }; }, diff --git a/packages/di/injection-js/test/adapter.integration.test.ts b/packages/di/injection-js/test/adapter.integration.test.ts index 47fe9a32..28bf28df 100644 --- a/packages/di/injection-js/test/adapter.integration.test.ts +++ b/packages/di/injection-js/test/adapter.integration.test.ts @@ -1,3 +1,5 @@ +import type { Type } from '@suites/types.common'; +import { ok } from 'node:assert/strict'; import 'reflect-metadata'; import { forwardRef, @@ -9,7 +11,7 @@ import { Self, SkipSelf, } from 'injection-js'; -import { UndefinedDependency, UndefinedDependencyError } from '@suites/types.di'; +import { UndefinedDependency } from '@suites/types.di'; import type {} from '../metadata.js'; import { adapter } from '../src/index.js'; @@ -33,6 +35,12 @@ class Service { ) {} } +function registryFor(target: Type) { + const result = adapter.inspect(target); + ok(result.kind === 'success'); + return result.registry; +} + describe('InjectionJS constructor adapter', () => { it('positively identifies only InjectionJS injectable classes for composition', () => { class Unmarked {} @@ -42,7 +50,7 @@ describe('InjectionJS constructor adapter', () => { }); it('uses the same token identities and order as the production resolver', () => { - const registry = adapter.inspect(Service); + const registry = registryFor(Service); const production = ReflectiveInjector.resolve([Service])[0].resolvedFactories[0].dependencies; expect(registry.list().map(({ identifier }) => identifier)).toEqual( production.map(({ key }) => key.token) @@ -69,7 +77,7 @@ describe('InjectionJS constructor adapter', () => { it('keeps different InjectionTokens with the same description distinct', () => { const other = new InjectionToken('repository'); - expect(adapter.inspect(Service).resolve(other)).toBeUndefined(); + expect(registryFor(Service).resolve(other)).toBeUndefined(); }); it('reads the public static parameters format', () => { @@ -81,8 +89,7 @@ describe('InjectionJS constructor adapter', () => { ) {} } expect( - adapter - .inspect(StaticService) + registryFor(StaticService) .list() .map(({ identifier }) => identifier) ).toEqual([TOKEN, Repository]); @@ -95,7 +102,7 @@ describe('InjectionJS constructor adapter', () => { ]; constructor(readonly token: unknown) {} } - expect(adapter.inspect(LoweredService).list()[0].identifier).toBe(TOKEN); + expect(registryFor(LoweredService).list()[0].identifier).toBe(TOKEN); }); it('does not run constructors when inspecting metadata', () => { @@ -105,7 +112,7 @@ describe('InjectionJS constructor adapter', () => { throw new Error('must not instantiate'); } } - expect(adapter.inspect(SideEffect).list()[0].identifier).toBe(Repository); + expect(registryFor(SideEffect).list()[0].identifier).toBe(Repository); }); it('treats resolution modifiers as tokens in a flat test container', () => { @@ -117,8 +124,7 @@ describe('InjectionJS constructor adapter', () => { ) {} } expect( - adapter - .inspect(Modified) + registryFor(Modified) .list() .map(({ identifier }) => identifier) ).toEqual([Repository, TOKEN]); @@ -126,14 +132,14 @@ describe('InjectionJS constructor adapter', () => { it('accepts classes without dependencies', () => { class Empty {} - expect(adapter.inspect(Empty).list()).toEqual([]); + expect(registryFor(Empty).list()).toEqual([]); }); it('rejects missing metadata instead of silently injecting undefined', () => { class Missing { constructor(readonly value: unknown) {} } - expect(() => adapter.inspect(Missing)).toThrow(UndefinedDependencyError); + expect(adapter.inspect(Missing)).toMatchObject({ kind: 'failure', target: Missing }); }); it('rejects erased interface metadata instead of mocking Object', () => { @@ -141,7 +147,7 @@ describe('InjectionJS constructor adapter', () => { class Erased { constructor(readonly value: { name: string }) {} } - expect(() => adapter.inspect(Erased)).toThrow(UndefinedDependencyError); + expect(adapter.inspect(Erased)).toMatchObject({ kind: 'failure', target: Erased }); }); it('rejects an empty token as InjectionJS does, instead of falling back to String', () => { @@ -149,7 +155,7 @@ describe('InjectionJS constructor adapter', () => { class EmptyToken { constructor(@Inject('') readonly value: string) {} } - expect(() => adapter.inspect(EmptyToken)).toThrow(UndefinedDependencyError); + expect(adapter.inspect(EmptyToken)).toMatchObject({ kind: 'failure', target: EmptyToken }); }); it.each([123, {}, true])('rejects unsupported token %p', (token) => { @@ -157,8 +163,45 @@ describe('InjectionJS constructor adapter', () => { class Unsupported { constructor(@Inject(token) readonly value: unknown) {} } - expect(() => adapter.inspect(Unsupported)).toThrow( - /Use a class, string, symbol, or InjectionToken/ - ); + expect(adapter.inspect(Unsupported)).toMatchObject({ + kind: 'failure', + target: Unsupported, + reason: 'unsupported-token', + }); + }); + it('returns the index and framework cause for an undefined lazy token', () => { + @Injectable() + class MissingToken { + constructor(@Inject(forwardRef(() => undefined)) readonly port: unknown) {} + } + expect(adapter.inspect(MissingToken)).toMatchObject({ + kind: 'failure', + reason: 'undefined-token', + target: MissingToken, + location: { kind: 'parameter', index: 0 }, + cause: expect.any(Error), + }); + }); + + it('preserves exceptions from a lazy token', () => { + const cause = new Error('application error'); + @Injectable() + class Broken { + constructor( + @Inject( + forwardRef(() => { + throw cause; + }) + ) + readonly port: unknown + ) {} + } + let caught: unknown; + try { + adapter.inspect(Broken); + } catch (error) { + caught = error; + } + expect(caught).toBe(cause); }); }); diff --git a/packages/di/inversify/__test__/inversify-adapter.integration.test.ts b/packages/di/inversify/__test__/inversify-adapter.integration.test.ts index c67e4646..e0ec6803 100644 --- a/packages/di/inversify/__test__/inversify-adapter.integration.test.ts +++ b/packages/di/inversify/__test__/inversify-adapter.integration.test.ts @@ -1,4 +1,13 @@ -import { inject, injectable, injectFromBase, named, tagged } from 'inversify'; +import type { Type } from '@suites/types.common'; +import { ok } from 'node:assert/strict'; +import { + LazyServiceIdentifier, + inject, + injectable, + injectFromBase, + named, + tagged, +} from 'inversify'; import 'reflect-metadata'; import { ConstructorBasedInjectionClass, @@ -25,6 +34,12 @@ import { import { InversifyInjectableIdentifierMetadata } from '../src/types.js'; import { adapter } from '../src.js'; +function registryFor(target: Type) { + const result = adapter.inspect(target); + ok(result.kind === 'success'); + return result.registry; +} + describe('InversifyJS Suites DI Adapter Integration Test', () => { const dependenciesAdapter = adapter; @@ -39,7 +54,7 @@ describe('InversifyJS Suites DI Adapter Integration Test', () => { let injectablesRegistry: InjectableRegistry; beforeAll(() => { - injectablesRegistry = dependenciesAdapter.inspect(ConstructorBasedInjectionClass); + injectablesRegistry = registryFor(ConstructorBasedInjectionClass); }); describe('reflecting a class with constructor based injection', () => { @@ -158,7 +173,7 @@ describe('InversifyJS Suites DI Adapter Integration Test', () => { let injectablesRegistry: InjectableRegistry; beforeAll(() => { - injectablesRegistry = dependenciesAdapter.inspect(PropertiesBasedInjectionClass); + injectablesRegistry = registryFor(PropertiesBasedInjectionClass); }); describe('reflecting a class with property based injection', () => { @@ -245,9 +260,7 @@ describe('InversifyJS Suites DI Adapter Integration Test', () => { }); describe('class constructor and properties combined', () => { - const injectablesRegistry = dependenciesAdapter - .inspect(ConstructorCombinedWithPropsClass) - .list(); + const injectablesRegistry = registryFor(ConstructorCombinedWithPropsClass).list(); it('should return an array of tuples with the class dependencies', () => { expect(injectablesRegistry).toEqual([ @@ -303,7 +316,7 @@ describe('Inversify 8 metadata', () => { } const metadata = { named: 'primary', region: 'eu', enabled: true }; - const dependency = adapter.inspect(Service).resolve('dependency', metadata); + const dependency = registryFor(Service).resolve('dependency', metadata); expect(dependency?.metadata).toEqual(metadata); }); @@ -315,7 +328,7 @@ describe('Inversify 8 metadata', () => { readonly [property]: unknown; } - expect(adapter.inspect(Service).resolve('dependency')?.property).toEqual({ key: property }); + expect(registryFor(Service).resolve('dependency')?.property).toEqual({ key: property }); }); it('reflects dependencies inherited with injectFromBase', () => { @@ -328,6 +341,44 @@ describe('Inversify 8 metadata', () => { @injectFromBase() class Derived extends Base {} - expect(adapter.inspect(Derived).list()).toEqual(adapter.inspect(Base).list()); + expect(registryFor(Derived).list()).toEqual(registryFor(Base).list()); + }); +}); + +describe('Inversify reflection failures', () => { + it('preserves the symbol property for an undefined lazy token', () => { + const key = Symbol('client'); + @injectable() + class Service { + @inject(new LazyServiceIdentifier(() => undefined as never)) + readonly [key]!: unknown; + } + expect(adapter.inspect(Service)).toMatchObject({ + kind: 'failure', + reason: 'undefined-token', + target: Service, + location: { kind: 'property', key }, + }); + }); + it('preserves exceptions thrown by a lazy constructor token', () => { + const cause = new Error('application callback'); + @injectable() + class Service { + constructor( + @inject( + new LazyServiceIdentifier(() => { + throw cause; + }) + ) + readonly port: unknown + ) {} + } + let caught: unknown; + try { + adapter.inspect(Service); + } catch (error) { + caught = error; + } + expect(caught).toBe(cause); }); }); diff --git a/packages/di/inversify/src/class-ctor-reflector.ts b/packages/di/inversify/src/class-ctor-reflector.ts index 61073a45..c048eb3f 100644 --- a/packages/di/inversify/src/class-ctor-reflector.ts +++ b/packages/di/inversify/src/class-ctor-reflector.ts @@ -1,13 +1,9 @@ -import { getClassMetadata } from '@inversifyjs/core'; -import { toInjectableMetadata } from './class-metadata.js'; +import type { ClassMetadata } from '@inversifyjs/core'; import type { Type } from '@suites/types.common'; -import type { ClassInjectable } from '@suites/types.di'; -import { UndefinedDependency, UndefinedDependencyError } from '@suites/types.di'; -import type { - InversifyInjectableIdentifierMetadata, - InversifyInjectableMetadata, - MetadataReflector, -} from './types.js'; +import type { ClassInjectable, InspectionFailure, IdentifierMetadata } from '@suites/types.di'; +import { UndefinedDependency } from '@suites/types.di'; +import { toInjectableMetadata } from './class-metadata.js'; +import type { MetadataReflector } from './types.js'; import type { IdentifierBuilder } from './identifier-builder.static.js'; export type ClassCtorReflector = ReturnType; @@ -16,75 +12,30 @@ export function ClassCtorReflector( reflector: MetadataReflector, identifierBuilder: IdentifierBuilder ) { - function reflectInjectables(targetClass: Type): ClassInjectable[] | never { - const paramTypes = reflectParamTypes(targetClass); - const reflectedParamTokens = reflectParamTokens(targetClass); - const paramTokens = constructTokensArray(paramTypes, reflectedParamTokens); - - return paramTokens.map((inversifyInjectableMetadataItems, index) => { - if (!inversifyInjectableMetadataItems) { - if (paramTypes[index] === undefined) { - throw new UndefinedDependencyError(`Suites encountered an error while attempting to detect a token or type for the -dependency at index [${index}] under the class '${targetClass.name}'. -This issue is commonly caused by either improper parameter decoration or a problem during the reflection of -the parameter type. In some cases, this error may arise due to circular dependencies. If this is the case, -please ensure that the circular dependency is resolved, or consider using 'LazyServiceIdentifier' to address it.`); - } - - return { - metadata: undefined, - identifier: paramTypes[index], - type: 'PARAM', - value: paramTypes[index], - } as InversifyInjectableIdentifierMetadata; - } - - const identifierAndMetadata = identifierBuilder.toIdentifierObject( - inversifyInjectableMetadataItems, - paramTypes[index] as Type + function reflectInjectables( + target: Type, + metadata: ClassMetadata + ): ClassInjectable[] | InspectionFailure { + const types: (Type | undefined)[] = reflector.getMetadata('design:paramtypes', target) ?? []; + const injectables: ClassInjectable[] = []; + const count = Math.max(target.length, types.length, metadata.constructorArguments.length); + for (let index = 0; index < count; index++) { + const entry = metadata.constructorArguments[index]; + const result = identifierBuilder.toIdentifierObject( + entry ? toInjectableMetadata(entry) : [], + types[index] === Object ? undefined : types[index] ); - - return { - metadata: identifierAndMetadata.metadata, - identifier: identifierAndMetadata.identifier, - value: (paramTypes[index] as Type) || UndefinedDependency, + if (result.kind === 'failure') { + return { ...result, target, location: { kind: 'parameter', index }, cause: undefined }; + } + injectables.push({ type: 'PARAM', - } as InversifyInjectableIdentifierMetadata; - }); - } - - function reflectParamTokens(targetClass: Type): Record { - return Object.fromEntries( - getClassMetadata(targetClass).constructorArguments.map((metadata, index) => [ - index, - toInjectableMetadata(metadata), - ]) - ); - } - - function reflectParamTypes(targetClass: Type): Type[] { - return reflector.getMetadata('design:paramtypes', targetClass) || []; - } - - function constructTokensArray( - paramTypes: (Type | undefined)[], - reflectedParamTokens: Record - ): (undefined | InversifyInjectableMetadata[])[] { - const paramTokens: (InversifyInjectableMetadata[] | undefined)[] = - Object.values(reflectedParamTokens); - - if (paramTypes.length === paramTokens.length) { - return paramTokens; + identifier: result.identifier, + metadata: result.metadata, + value: types[index] ?? UndefinedDependency, + } satisfies ClassInjectable); } - - return paramTypes.map((_typeOrUndefined, index) => { - if (!Object.prototype.hasOwnProperty.call(reflectedParamTokens, index)) { - return undefined; - } - - return reflectedParamTokens[index]; - }); + return injectables; } - return { reflectInjectables }; } diff --git a/packages/di/inversify/src/class-props-reflector.ts b/packages/di/inversify/src/class-props-reflector.ts index 371214bb..f2f36a54 100644 --- a/packages/di/inversify/src/class-props-reflector.ts +++ b/packages/di/inversify/src/class-props-reflector.ts @@ -1,14 +1,10 @@ -import type { ClassInjectable } from '@suites/types.di'; -import { UndefinedDependency, UndefinedDependencyError } from '@suites/types.di'; +import type { ClassMetadata } from '@inversifyjs/core'; import type { Type } from '@suites/types.common'; -import { getClassMetadata } from '@inversifyjs/core'; +import type { ClassInjectable, InspectionFailure, IdentifierMetadata } from '@suites/types.di'; +import { UndefinedDependency } from '@suites/types.di'; import { toInjectableMetadata } from './class-metadata.js'; -import type { - InversifyInjectableIdentifierMetadata, - InversifyInjectableMetadata, - MetadataReflector, -} from './types.js'; -import type { IdentifierObject, IdentifierBuilder } from './identifier-builder.static.js'; +import type { MetadataReflector } from './types.js'; +import type { IdentifierBuilder } from './identifier-builder.static.js'; export type ClassPropsReflector = ReturnType; @@ -16,60 +12,28 @@ export function ClassPropsReflector( reflector: MetadataReflector, identifierBuilder: IdentifierBuilder ) { - function reflectInjectables(targetClass: Type): ClassInjectable[] { - const classProperties = reflectProperties(targetClass); - const classInstance = Object.create(targetClass.prototype); - - return Reflect.ownKeys(classProperties).map((propertyKey) => { - const propertyParamType = reflector.getMetadata('design:type', classInstance, propertyKey) as - Type | undefined; - - const propertyMetadataItems = classProperties[propertyKey as never]; - - if (!propertyMetadataItems && !propertyParamType) { - throw new UndefinedDependencyError(`Suites encountered an error while attempting to detect a token or type for the dependency for property '${String(propertyKey)}' in the class '${targetClass.name}'. -This issue is commonly caused by either improper decoration of the property or a problem during the reflection of the parameter type. -In some cases, this error may arise due to circular dependencies. If this is the case, please ensure that the circular dependency -is resolved, or consider using 'LazyServiceIdentifier' to address it.`); + function reflectInjectables( + target: Type, + metadata: ClassMetadata + ): ClassInjectable[] | InspectionFailure { + const injectables: ClassInjectable[] = []; + for (const [key, entry] of metadata.properties) { + const type: Type | undefined = reflector.getMetadata('design:type', target.prototype, key); + const result = identifierBuilder.toIdentifierObject(toInjectableMetadata(entry), type); + if (result.kind === 'failure') { + return { ...result, target, location: { kind: 'property', key }, cause: undefined }; } - - const identifierAndMetadata = identifierBuilder.toIdentifierObject( - propertyMetadataItems, - propertyParamType as Type - ); - - return { - metadata: identifierAndMetadata.metadata, + injectables.push({ type: 'PROPERTY', - identifier: identifierAndMetadata.identifier, - value: setValue(propertyParamType, identifierAndMetadata), - property: { key: propertyKey }, - } as InversifyInjectableIdentifierMetadata; - }); - } - - function setValue(propertyParamType: Type | undefined, identifierAndMetadata: IdentifierObject) { - if (propertyParamType) { - return propertyParamType; + property: { key }, + identifier: result.identifier, + metadata: result.metadata, + value: + type ?? + (typeof result.identifier === 'function' ? result.identifier : UndefinedDependency), + } satisfies ClassInjectable); } - - if (typeof identifierAndMetadata.identifier === 'function') { - return identifierAndMetadata.identifier; - } - - return UndefinedDependency; + return injectables; } - - function reflectProperties( - targetClass: Type - ): Record { - return Object.fromEntries( - [...getClassMetadata(targetClass).properties].map(([key, metadata]) => [ - key, - toInjectableMetadata(metadata), - ]) - ); - } - return { reflectInjectables }; } diff --git a/packages/di/inversify/src/dependencies-adapter.spec.ts b/packages/di/inversify/src/dependencies-adapter.spec.ts index e95f5bae..59781118 100644 --- a/packages/di/inversify/src/dependencies-adapter.spec.ts +++ b/packages/di/inversify/src/dependencies-adapter.spec.ts @@ -1,3 +1,6 @@ +import 'reflect-metadata'; +import type { Type } from '@suites/types.common'; +import { ok } from 'node:assert/strict'; import type { DependencyInjectionAdapter, ClassInjectable } from '@suites/types.di'; import { DependenciesAdapter } from './dependencies-adapter.js'; import type { IdentifierMetadata } from './types.js'; @@ -51,6 +54,12 @@ const injectablesFixture: ClassInjectable[] = [ }, ]; +function registryFor(target: Type) { + const result = dependenciesAdapter.inspect(target); + ok(result.kind === 'success'); + return result.registry; +} + describe('Dependencies Adapter Unit Spec', () => { beforeEach(() => { classPropsReflector.reflectInjectables.mockReturnValue([]); @@ -59,44 +68,42 @@ describe('Dependencies Adapter Unit Spec', () => { it('should return undefined if no matching injectables are found', () => { classCtorReflector.reflectInjectables.mockReturnValue([]); - const result = dependenciesAdapter.inspect(targetClass).resolve('Interface', metadata as never); + const result = registryFor(targetClass).resolve('Interface', metadata as never); expect(result).toBeUndefined(); }); it('should return the injectable if only one matching injectable is found and no metadata is provided', () => { classCtorReflector.reflectInjectables.mockReturnValue(injectablesFixture); - const result = dependenciesAdapter.inspect(targetClass).resolve('Interface'); + const result = registryFor(targetClass).resolve('Interface'); expect(result).toEqual(injectablesFixture[2]); }); it('should return the injectable with matching metadata if metadata is provided', () => { classCtorReflector.reflectInjectables.mockReturnValue(injectablesFixture); - const result = dependenciesAdapter.inspect(targetClass).resolve('Interface', metadata as never); + const result = registryFor(targetClass).resolve('Interface', metadata as never); expect(result).toEqual(injectablesFixture[0]); }); it('should return undefined if no injectable with matching metadata is found', () => { classCtorReflector.reflectInjectables.mockReturnValue(injectablesFixture); - const result = dependenciesAdapter - .inspect(targetClass) - .resolve('Interface', { metadataKey: 'other' } as never); + const result = registryFor(targetClass).resolve('Interface', { metadataKey: 'other' } as never); expect(result).toBeUndefined(); }); it('should return the injectable with matching identifier and no metadata if metadata is not provided', () => { classCtorReflector.reflectInjectables.mockReturnValue(injectablesFixture); - const result = dependenciesAdapter.inspect(targetClass).resolve(arbitraryClassAsIdentifier); + const result = registryFor(targetClass).resolve(arbitraryClassAsIdentifier); expect(result).toEqual(injectablesFixture[4]); }); it('should return the injectable if there is exactly one, even no metadata provided', () => { classCtorReflector.reflectInjectables.mockReturnValue(injectablesFixture); - const result = dependenciesAdapter.inspect(targetClass).resolve('IdentifierWithMetadata'); + const result = registryFor(targetClass).resolve('IdentifierWithMetadata'); expect(result).toEqual(injectablesFixture[5]); }); diff --git a/packages/di/inversify/src/dependencies-adapter.ts b/packages/di/inversify/src/dependencies-adapter.ts index feeb15eb..7eb25f24 100644 --- a/packages/di/inversify/src/dependencies-adapter.ts +++ b/packages/di/inversify/src/dependencies-adapter.ts @@ -1,9 +1,10 @@ +import { getClassMetadata } from '@inversifyjs/core'; import { isDeepStrictEqual } from 'node:util'; import type { Type } from '@suites/types.common'; import type { DependencyInjectionAdapter, ClassInjectable, - InjectableRegistry, + InspectionResult, InjectableIdentifier, WithMetadata, } from '@suites/types.di'; @@ -20,43 +21,60 @@ export function DependenciesAdapter( classPropsReflector: ClassPropsReflector, classCtorReflector: ClassCtorReflector ): DependencyInjectionAdapter { - function inspect(targetClass: Type): InjectableRegistry { - const ctorInjectables = classCtorReflector.reflectInjectables(targetClass); - const propsInjectables = classPropsReflector.reflectInjectables(targetClass); + function inspect(targetClass: Type): InspectionResult { + let metadata; + try { + metadata = getClassMetadata(targetClass); + } catch (cause) { + return { + kind: 'failure', + reason: 'invalid-metadata', + target: targetClass, + location: { kind: 'class' }, + cause, + }; + } + const ctorInjectables = classCtorReflector.reflectInjectables(targetClass, metadata); + if (!Array.isArray(ctorInjectables)) return ctorInjectables; + const propsInjectables = classPropsReflector.reflectInjectables(targetClass, metadata); + if (!Array.isArray(propsInjectables)) return propsInjectables; const allInjectables = [...ctorInjectables, ...propsInjectables] as WithMetadata[]; return { - resolve( - identifier: InjectableIdentifier, - metadata: IdentifierMetadata | undefined - ): ClassInjectable | undefined { - const injectables = allInjectables.filter( - ({ identifier: injectableIdentifier }) => injectableIdentifier === identifier - ); + kind: 'success', + registry: { + resolve( + identifier: InjectableIdentifier, + metadata: IdentifierMetadata | undefined + ): ClassInjectable | undefined { + const injectables = allInjectables.filter( + ({ identifier: injectableIdentifier }) => injectableIdentifier === identifier + ); - if (injectables.length === 0) { - return undefined; - } + if (injectables.length === 0) { + return undefined; + } - if (injectables.length === 1 && !metadata) { - return injectables[0]; - } + if (injectables.length === 1 && !metadata) { + return injectables[0]; + } - if (metadata) { - return injectables.find(({ metadata: injectableMetadata }) => - isDeepStrictEqual(injectableMetadata, metadata) - ); - } + if (metadata) { + return injectables.find(({ metadata: injectableMetadata }) => + isDeepStrictEqual(injectableMetadata, metadata) + ); + } - const foundInjectable = injectables.find( - ({ identifier: injectableIdentifier, metadata: injectableMetadata }) => - identifier === injectableIdentifier && typeof injectableMetadata === 'undefined' - ); + const foundInjectable = injectables.find( + ({ identifier: injectableIdentifier, metadata: injectableMetadata }) => + identifier === injectableIdentifier && typeof injectableMetadata === 'undefined' + ); - return foundInjectable ? foundInjectable : undefined; - }, - list(): ClassInjectable[] { - return allInjectables; + return foundInjectable ? foundInjectable : undefined; + }, + list(): ClassInjectable[] { + return allInjectables; + }, }, }; } diff --git a/packages/di/inversify/src/identifier-builder.static.spec.ts b/packages/di/inversify/src/identifier-builder.static.spec.ts index a49c0bac..dbafd2a8 100644 --- a/packages/di/inversify/src/identifier-builder.static.spec.ts +++ b/packages/di/inversify/src/identifier-builder.static.spec.ts @@ -18,6 +18,7 @@ describe('Identifier Builder Unit Spec', () => { ); expect(result).toEqual({ + kind: 'success', identifier: paramType, metadata: { metadataKey: 'metadataValue' }, }); @@ -37,6 +38,7 @@ describe('Identifier Builder Unit Spec', () => { ); expect(result).toEqual({ + kind: 'success', identifier: paramType, metadata: { metadataKey: 'metadataValue' }, }); @@ -55,19 +57,20 @@ describe('Identifier Builder Unit Spec', () => { ); expect(result).toEqual({ + kind: 'success', identifier: paramType, metadata: undefined, }); }); - it('should throw an error indicating undefined dependency detected when lazy loader value is undefined', () => { + it('identifies an undefined explicit token when lazy loader value is undefined', () => { const inversifyInjectableMetadataItems = [ { key: 'inject', value: new LazyServiceIdentifier(() => undefined as never) }, ]; - expect(() => - IdentifierBuilder().toIdentifierObject(inversifyInjectableMetadataItems, undefined as never) - ).toThrow(); + expect( + IdentifierBuilder().toIdentifierObject(inversifyInjectableMetadataItems, undefined) + ).toEqual({ kind: 'failure', reason: 'undefined-token' }); }); it('should use the parameter type as identifier if identifier left undefined because none of the preserved keys is found', () => { @@ -80,6 +83,7 @@ describe('Identifier Builder Unit Spec', () => { ); expect(result).toEqual({ + kind: 'success', identifier: paramType, metadata: { metadataKey: 'metadataValue' }, }); diff --git a/packages/di/inversify/src/identifier-builder.static.ts b/packages/di/inversify/src/identifier-builder.static.ts index 55dd0ab6..062c0b8a 100644 --- a/packages/di/inversify/src/identifier-builder.static.ts +++ b/packages/di/inversify/src/identifier-builder.static.ts @@ -1,50 +1,32 @@ import { LazyServiceIdentifier } from 'inversify'; import type { Type } from '@suites/types.common'; -import type { IdentifierMetadata, InjectableIdentifier, WithMetadata } from '@suites/types.di'; -import type { InversifyInjectableMetadata } from './types.js'; -import { INVERSIFY_PRESERVED_KEYS } from './types.js'; - -export type IdentifierObject = { - identifier: InjectableIdentifier; - metadata: undefined | Pick, 'metadata'>; -}; +import type { InjectableIdentifier } from '@suites/types.di'; +import { INVERSIFY_PRESERVED_KEYS, type InversifyInjectableMetadata } from './types.js'; export type IdentifierBuilder = ReturnType; export function IdentifierBuilder() { function toIdentifierObject( - inversifyInjectableMetadataItems: InversifyInjectableMetadata[], - paramType: Type - ): IdentifierObject { - const obj = inversifyInjectableMetadataItems.reduce( - (acc: IdentifierObject, metadataItem: InversifyInjectableMetadata) => { - const { key: metadataKey, value: metadataValue } = metadataItem; - - if (INVERSIFY_PRESERVED_KEYS.includes(metadataKey)) { - if (metadataValue instanceof LazyServiceIdentifier) { - const unwrappedValue = metadataValue.unwrap(); - - if (typeof unwrappedValue === 'undefined') { - throw new Error('Undefined dependency identifier detected'); - } - - return { ...acc, identifier: unwrappedValue }; - } - - return { ...acc, identifier: metadataValue }; - } - - return { ...acc, metadata: { ...acc.metadata, [metadataKey]: metadataValue } }; - }, - {} as IdentifierObject - ) as IdentifierObject; - - if (typeof obj.identifier === 'undefined') { - return { identifier: paramType, metadata: obj.metadata }; + items: readonly InversifyInjectableMetadata[], + type: Type | undefined + ) { + const entry = items.find(({ key }) => INVERSIFY_PRESERVED_KEYS.includes(key)); + const token = entry ? entry.value : type; + const identifier = token instanceof LazyServiceIdentifier ? token.unwrap() : token; + if (identifier === undefined) { + return { + kind: 'failure', + reason: entry ? 'undefined-token' : 'undefined-dependency', + } as const; } - - return obj; + const tags = items.filter(({ key }) => !INVERSIFY_PRESERVED_KEYS.includes(key)); + return { + kind: 'success' as const, + identifier: identifier as InjectableIdentifier, + metadata: tags.length + ? Object.fromEntries(tags.map(({ key, value }) => [key, value])) + : undefined, + }; } - return { toIdentifierObject }; } diff --git a/packages/di/nestjs/__test__/nestjs-adapter.integration.test.ts b/packages/di/nestjs/__test__/nestjs-adapter.integration.test.ts index 3f4f5ee3..5d9fa742 100644 --- a/packages/di/nestjs/__test__/nestjs-adapter.integration.test.ts +++ b/packages/di/nestjs/__test__/nestjs-adapter.integration.test.ts @@ -1,3 +1,4 @@ +import { ok } from 'node:assert/strict'; import { ClassWithUndefinedDependency, ClassWithUndefinedDependencyProps, @@ -15,18 +16,26 @@ import { UndefinedDependency } from '@suites/types.di'; import type { Type } from '@suites/types.common'; import { adapter } from '../src.js'; +function registryFor(target: Type) { + const result = adapter.inspect(target); + ok(result.kind === 'success'); + return result.registry; +} + describe('NestJS Suites DI Adapter Integration Test', () => { const dependencyInjectionAdapter = adapter; it('positively identifies only NestJS injectable classes for composition', () => { class Unmarked {} - expect(dependencyInjectionAdapter.canAutoConstruct?.(ConstructorBasedInjectionClass)).toBe(true); + expect(dependencyInjectionAdapter.canAutoConstruct?.(ConstructorBasedInjectionClass)).toBe( + true + ); expect(dependencyInjectionAdapter.canAutoConstruct?.(Unmarked)).toBe(false); }); describe('reflecting a class with constructor based injection', () => { - const injectablesContainer = dependencyInjectionAdapter.inspect(ConstructorBasedInjectionClass); + const injectablesContainer = registryFor(ConstructorBasedInjectionClass); it('should list the dependencies in the dependencies container corresponding to the class injectables', () => { expect(injectablesContainer.list()).toStrictEqual([ @@ -103,7 +112,7 @@ describe('NestJS Suites DI Adapter Integration Test', () => { }); describe('reflecting a class with property based injection', () => { - const injectablesContainer = dependencyInjectionAdapter.inspect(PropsBasedMainClass); + const injectablesContainer = registryFor(PropsBasedMainClass); it('should list the dependencies in the dependencies container corresponding to the class injectables', () => { expect(injectablesContainer.list()).toStrictEqual([ @@ -183,9 +192,7 @@ describe('NestJS Suites DI Adapter Integration Test', () => { }); describe('reflecting a class with constructor and properties combined', () => { - const injectablesContainer = dependencyInjectionAdapter.inspect( - ConstructorCombinedWithPropsClass - ); + const injectablesContainer = registryFor(ConstructorCombinedWithPropsClass); it('should list the dependencies in the dependencies container corresponding to the class injectables', () => { expect(injectablesContainer.list()).toEqual([ @@ -235,8 +242,39 @@ describe('NestJS Suites DI Adapter Integration Test', () => { it.each([[ClassWithUndefinedDependency], [ClassWithUndefinedDependencyProps]])( 'should fail with an error indicating that the dependency is not defined', (type: Type) => { - expect(() => dependencyInjectionAdapter.inspect(type)).toThrow(); + expect(adapter.inspect(type)).toMatchObject({ + kind: 'failure', + reason: 'undefined-dependency', + target: type, + }); } ); }); }); + +describe('missing constructor metadata', () => { + it('distinguishes a required parameter from an empty constructor', () => { + class Undecorated { + constructor(readonly client: unknown) {} + } + class Empty {} + expect(adapter.inspect(Undecorated)).toMatchObject({ + kind: 'failure', + reason: 'undefined-dependency', + location: { kind: 'parameter', index: 0 }, + }); + expect(registryFor(Empty).list()).toEqual([]); + }); + + it('requires a token when the emitted parameter type is Object', () => { + class Service { + constructor(readonly client: unknown) {} + } + Reflect.defineMetadata('design:paramtypes', [Object], Service); + expect(adapter.inspect(Service)).toMatchObject({ + kind: 'failure', + reason: 'undefined-dependency', + location: { kind: 'parameter', index: 0 }, + }); + }); +}); diff --git a/packages/di/nestjs/src/class-ctor-reflector.ts b/packages/di/nestjs/src/class-ctor-reflector.ts index 68ae2301..161a3685 100644 --- a/packages/di/nestjs/src/class-ctor-reflector.ts +++ b/packages/di/nestjs/src/class-ctor-reflector.ts @@ -1,60 +1,45 @@ import { SELF_DECLARED_DEPS_METADATA, PARAMTYPES_METADATA } from '@nestjs/common/constants'; -import type { ClassInjectable } from '@suites/types.di'; -import { UndefinedDependencyError } from '@suites/types.di'; +import type { ClassInjectable, InspectionFailure } from '@suites/types.di'; +import { UndefinedDependency } from '@suites/types.di'; import type { Type } from '@suites/types.common'; -import type { MetadataReflector, NestInjectableIdentifier } from './types.js'; -import type { NestCustomToken, ParamsTokensReflector } from './params-token-resolver.js'; +import type { MetadataReflector } from './types.js'; +import { type NestCustomToken, resolveToken } from './params-token-resolver.js'; export type ClassCtorReflector = ReturnType; -export function ClassCtorReflector( - reflector: MetadataReflector, - paramsTokensReflector: ParamsTokensReflector -) { - function reflectInjectables(targetClass: Type): ClassInjectable[] | never { - const paramTypes = reflectParamTypes(targetClass); - const paramTokens = reflectParamTokens(targetClass); - const tokensIndexes = paramTokens.map(({ index }) => index); - const resolveParamTokenCb = paramsTokensReflector.resolveDependencyValue(paramTokens); - - return paramTypes.map((typeOrUndefined, paramIndex) => { - const isToken = tokensIndexes.includes(paramIndex); - const error = - new UndefinedDependencyError(`Suites encountered an error while attempting to detect a token or type for the -dependency at index [${paramIndex}] in the class '${targetClass.name}'. -This issue is commonly caused by either improper parameter decoration or a problem during the reflection of -the parameter type. In some cases, this error may arise due to circular dependencies. If this is the case, -please ensure that the circular dependency is resolved, or consider using 'forwardRef()' to address it.`); - - if (isToken) { - // eslint-disable-next-line no-useless-catch - try { - const resolved = resolveParamTokenCb(typeOrUndefined, paramIndex); - return { ...resolved, type: 'PARAM' }; - } catch (error) { - throw error; - } +export function ClassCtorReflector(reflector: MetadataReflector) { + function reflectInjectables(target: Type): ClassInjectable[] | InspectionFailure { + const types: (Type | undefined)[] = reflector.getMetadata(PARAMTYPES_METADATA, target) ?? []; + const tokens: NestCustomToken[] = + reflector.getMetadata(SELF_DECLARED_DEPS_METADATA, target) ?? []; + const slots = tokens.reduce( + (count, token) => Math.max(count, token.index + 1), + Math.max(target.length, types.length) + ); + const injectables: ClassInjectable[] = []; + + for (let index = 0; index < slots; index++) { + const type = types[index]; + const token = tokens.find((entry) => entry.index === index); + const identifier = token ? resolveToken(token.param) : type; + if (identifier === undefined || (!token && identifier === Object)) { + return { + kind: 'failure', + reason: token ? 'undefined-token' : 'undefined-dependency', + target, + location: { kind: 'parameter', index }, + cause: undefined, + }; } - - if (!typeOrUndefined) { - throw error; - } - - return { - type: 'PARAM', - identifier: typeOrUndefined as Type, - value: typeOrUndefined as Type, - } as ClassInjectable; - }); + const value = + type === undefined + ? UndefinedDependency + : typeof identifier === 'string' + ? type + : identifier; + injectables.push({ type: 'PARAM', identifier, value } satisfies ClassInjectable); + } + return injectables; } - - function reflectParamTokens(targetClass: Type): NestCustomToken[] { - return reflector.getMetadata(SELF_DECLARED_DEPS_METADATA, targetClass) || []; - } - - function reflectParamTypes(targetClass: Type): (NestInjectableIdentifier | undefined)[] { - return reflector.getMetadata(PARAMTYPES_METADATA, targetClass) || []; - } - return { reflectInjectables }; } diff --git a/packages/di/nestjs/src/class-props-reflector.ts b/packages/di/nestjs/src/class-props-reflector.ts index daa74888..4105285a 100644 --- a/packages/di/nestjs/src/class-props-reflector.ts +++ b/packages/di/nestjs/src/class-props-reflector.ts @@ -1,53 +1,43 @@ -import type { ClassInjectable, InjectableReflectedType } from '@suites/types.di'; -import { UndefinedDependencyError } from '@suites/types.di'; -import type { Type } from '@suites/types.common'; import { PROPERTY_DEPS_METADATA } from '@nestjs/common/constants'; +import type { ClassInjectable, InspectionFailure } from '@suites/types.di'; +import { UndefinedDependency } from '@suites/types.di'; +import type { Type } from '@suites/types.common'; import type { MetadataReflector, ReflectedProperty } from './types.js'; -import type { PropertyReflectionStrategy } from './property-reflection-strategies.static.js'; +import { resolveToken } from './params-token-resolver.js'; export type ClassPropsReflector = ReturnType; -export function ClassPropsReflector( - reflector: MetadataReflector, - reflectionStrategies: ReadonlyArray -) { - function reflectInjectables(targetClass: Type): ClassInjectable[] { - const classProperties = reflectProperties(targetClass); - const classInstance = Object.create(targetClass.prototype); - - return classProperties.map(({ key, type: reflectedValue }) => { - const reflectedType = reflector.getMetadata( - 'design:type', - classInstance, - key - ) as InjectableReflectedType; - - if (!reflectedType && !reflectedValue) { - throw new UndefinedDependencyError(`Suites encountered an error while attempting to detect a token or type for the dependency for property '${key}' in the class '${targetClass.name}'. -This issue is commonly caused by either improper decoration of the property or a problem during the reflection of the parameter type. -In some cases, this error may arise due to circular dependencies. If this is the case, please ensure that the circular dependency -is resolved, or consider using 'forwardRef()' to address it.`); - } - - for (const strategy of reflectionStrategies) { - if (strategy.condition(reflectedType, reflectedValue)) { - const result = strategy.exec(reflectedType, reflectedValue); - return { ...result, type: 'PROPERTY', property: { key } } as ClassInjectable; - } +export function ClassPropsReflector(reflector: MetadataReflector) { + function reflectInjectables(target: Type): ClassInjectable[] | InspectionFailure { + const properties: ReflectedProperty[] = + reflector.getMetadata(PROPERTY_DEPS_METADATA, target) ?? []; + const injectables: ClassInjectable[] = []; + for (const { key, type: token } of properties) { + const type: Type | undefined = reflector.getMetadata('design:type', target.prototype, key); + const identifier = resolveToken(token); + if (identifier === undefined) { + return { + kind: 'failure', + reason: token === undefined ? 'undefined-dependency' : 'undefined-token', + target, + location: { kind: 'property', key }, + cause: undefined, + }; } - - return { + const value = + type === undefined + ? UndefinedDependency + : typeof identifier === 'string' + ? type + : identifier; + injectables.push({ type: 'PROPERTY', - identifier: reflectedValue as Type, - value: reflectedValue as Type, + identifier, + value, property: { key }, - } as ClassInjectable; - }); + } satisfies ClassInjectable); + } + return injectables; } - - function reflectProperties(targetClass: Type): ReflectedProperty[] { - return reflector.getMetadata(PROPERTY_DEPS_METADATA, targetClass) || []; - } - return { reflectInjectables }; } diff --git a/packages/di/nestjs/src/dependencies-adapter.ts b/packages/di/nestjs/src/dependencies-adapter.ts index 78298f3a..337bc53b 100644 --- a/packages/di/nestjs/src/dependencies-adapter.ts +++ b/packages/di/nestjs/src/dependencies-adapter.ts @@ -3,7 +3,7 @@ import { INJECTABLE_WATERMARK } from '@nestjs/common/constants'; import type { DependencyInjectionAdapter, ClassInjectable, - InjectableRegistry, + InspectionResult, } from '@suites/types.di'; import type { ClassPropsReflector } from './class-props-reflector.js'; import type { ClassCtorReflector } from './class-ctor-reflector.js'; @@ -12,17 +12,22 @@ export function DependenciesAdapter( classPropsReflector: ClassPropsReflector, classCtorReflector: ClassCtorReflector ): DependencyInjectionAdapter { - function inspect(targetClass: Type): InjectableRegistry { + function inspect(targetClass: Type): InspectionResult { const ctorInjectables = classCtorReflector.reflectInjectables(targetClass); + if (!Array.isArray(ctorInjectables)) return ctorInjectables; const propsInjectables = classPropsReflector.reflectInjectables(targetClass); + if (!Array.isArray(propsInjectables)) return propsInjectables; const allInjectables = [...ctorInjectables, ...propsInjectables]; return { - resolve(identifier: Type | string): ClassInjectable | undefined { - return allInjectables.find(({ identifier: typeOrToken }) => typeOrToken === identifier); - }, - list(): ClassInjectable[] { - return allInjectables; + kind: 'success', + registry: { + resolve(identifier: Type | string): ClassInjectable | undefined { + return allInjectables.find(({ identifier: typeOrToken }) => typeOrToken === identifier); + }, + list(): ClassInjectable[] { + return allInjectables; + }, }, }; } diff --git a/packages/di/nestjs/src/index.ts b/packages/di/nestjs/src/index.ts index 3dbbc923..2a000ff0 100644 --- a/packages/di/nestjs/src/index.ts +++ b/packages/di/nestjs/src/index.ts @@ -14,17 +14,9 @@ import type { DependencyInjectionAdapter } from '@suites/types.di'; import { DependenciesAdapter } from './dependencies-adapter.js'; import { ClassPropsReflector } from './class-props-reflector.js'; import { ClassCtorReflector } from './class-ctor-reflector.js'; -import { ParamsTokensReflector } from './params-token-resolver.js'; -import { PropertyReflectionStrategies } from './property-reflection-strategies.static.js'; - -const NestJSDIAdapter: DependencyInjectionAdapter = (( - classPropsReflector: ClassPropsReflector, - classCtorReflector: ClassCtorReflector -) => { - return DependenciesAdapter(classPropsReflector, classCtorReflector); -})( - ClassPropsReflector(Reflect, PropertyReflectionStrategies), - ClassCtorReflector(Reflect, ParamsTokensReflector) +const NestJSDIAdapter: DependencyInjectionAdapter = DependenciesAdapter( + ClassPropsReflector(Reflect), + ClassCtorReflector(Reflect) ); export { IdentifierMetadata } from './types.js'; diff --git a/packages/di/nestjs/src/params-token-resolver.ts b/packages/di/nestjs/src/params-token-resolver.ts index 19750834..f39c8b1a 100644 --- a/packages/di/nestjs/src/params-token-resolver.ts +++ b/packages/di/nestjs/src/params-token-resolver.ts @@ -1,84 +1,16 @@ -import type { Type } from '@suites/types.common'; -import type { ClassInjectable, InjectableIdentifier } from '@suites/types.di'; -import { UndefinedDependency, UndefinedTokenError } from '@suites/types.di'; +import type { InjectableIdentifier } from '@suites/types.di'; import type { NestInjectableIdentifier } from './types.js'; export interface NestCustomToken { - index: number; - param: NestInjectableIdentifier; + readonly index: number; + readonly param: NestInjectableIdentifier | undefined; } -export type ParamsTokensReflector = { - resolveDependencyValue( - tokens: NestCustomToken[] - ): ( - typeOrUndefined: NestInjectableIdentifier | undefined, - index: number - ) => Omit; -}; - -export const ParamsTokensReflector = (function (): ParamsTokensReflector { - function lookupTokenInParams( - tokens: NestCustomToken[], - index: number - ): NestInjectableIdentifier | undefined { - const record = tokens.find((token) => token.index === index); - return record?.param; - } - - function resolveReferenceCallbackFromToken( - token: NestInjectableIdentifier - ): InjectableIdentifier { - return ( - typeof token === 'object' && 'forwardRef' in token ? token.forwardRef() : token - ) as InjectableIdentifier; - } - - function resolveDependencyValue( - tokens: NestCustomToken[] - ): ( - typeOrUndefined: NestInjectableIdentifier | undefined, - tokenIndexInCtor: number - ) => Omit { - return (dependencyType: Type, index: number): Omit => { - const token = lookupTokenInParams(tokens, index); - - if (!token) { - throw new UndefinedTokenError(`Suites encountered an error while attempting to detect a token for the -dependency at index [${index}]. -This issue is commonly caused by either improper parameter decoration or a problem during the reflection of -the parameter type. In some cases, this error may arise due to circular dependencies. If this is the case, -please ensure that the circular dependency is resolved, or consider using 'forwardRef()' to address it.`); - } - - const ref = resolveReferenceCallbackFromToken(token); - const refIsAType = typeof ref !== 'string'; - - if (refIsAType) { - return { - identifier: ref as Type, - value: typeof dependencyType === 'undefined' ? UndefinedDependency : (ref as Type), - }; - } - - if (!dependencyType && typeof token === 'string') { - return { - identifier: token, - value: UndefinedDependency, - }; - } else if (!dependencyType && typeof ref !== 'string') { - return { - identifier: ref, - value: UndefinedDependency, - }; - } - - return { - identifier: ref, - value: dependencyType, - }; - }; +export function resolveToken( + token: NestInjectableIdentifier | undefined +): InjectableIdentifier | undefined { + if (typeof token === 'object' && token !== null && 'forwardRef' in token) { + return token.forwardRef(); } - - return { resolveDependencyValue }; -})(); + return token; +} diff --git a/packages/di/nestjs/src/property-reflection-strategies.static.ts b/packages/di/nestjs/src/property-reflection-strategies.static.ts deleted file mode 100644 index a9946163..00000000 --- a/packages/di/nestjs/src/property-reflection-strategies.static.ts +++ /dev/null @@ -1,98 +0,0 @@ -import type { Type } from '@suites/types.common'; -import type { - InjectableIdentifier, - InjectableReflectedType, - InjectableFinalValue, -} from '@suites/types.di'; -import { UndefinedDependency } from '@suites/types.di'; -import type { ForwardRefToken, NestInjectableIdentifier } from './types.js'; - -export interface StrategyReturnType { - identifier: InjectableIdentifier; - value: InjectableFinalValue; -} - -export interface PropertyReflectionStrategy { - condition: ( - reflectedType: InjectableReflectedType, - identifier: NestInjectableIdentifier - ) => boolean; - exec: ( - reflectedType: InjectableReflectedType, - identifier: NestInjectableIdentifier - ) => StrategyReturnType; -} - -export const PropertyReflectionStrategies: ReadonlyArray = [ - { - condition: ( - _reflectedType: InjectableReflectedType, - identifier: NestInjectableIdentifier - ): boolean => { - return typeof identifier === 'object' && 'forwardRef' in identifier; - }, - exec: (reflectedType: InjectableReflectedType, identifier: NestInjectableIdentifier) => { - const forwardRefToken = (identifier as ForwardRefToken).forwardRef(); - - if (typeof forwardRefToken === 'undefined') { - throw new Error('Token is undefined'); - } - - if (typeof forwardRefToken === 'string') { - return { - identifier: forwardRefToken as string, - value: typeof identifier === 'undefined' ? UndefinedDependency : (identifier as Type), - }; - } - - return { - identifier: forwardRefToken as Type, - value: typeof reflectedType === 'undefined' ? UndefinedDependency : forwardRefToken, - }; - }, - }, - { - condition: (reflectedType: undefined, identifier: NestInjectableIdentifier): boolean => { - return !reflectedType && typeof identifier === 'string'; - }, - exec: (_reflectedType: InjectableReflectedType, type: string) => { - return { - identifier: type, - value: UndefinedDependency, - }; - }, - }, - { - condition: (reflectedType: undefined, identifier: Type): boolean => { - return !reflectedType && typeof identifier !== 'string'; - }, - exec: (reflectedType: InjectableReflectedType, type: Type) => { - return { - identifier: type, - value: UndefinedDependency, - }; - }, - }, - { - condition: (_reflectedType: InjectableReflectedType, identifier: string): boolean => { - return typeof identifier === 'string'; - }, - exec: (reflectedType: InjectableReflectedType, identifier: string) => { - return { - identifier, - value: reflectedType as InjectableFinalValue, - }; - }, - }, - { - condition: ( - reflectedType: undefined, - identifier: NestInjectableIdentifier | undefined - ): boolean => { - return !reflectedType && !identifier; - }, - exec: () => { - throw new Error('Failed'); - }, - }, -]; diff --git a/packages/di/nestjs/src/types.ts b/packages/di/nestjs/src/types.ts index 049a69af..669ae9a7 100644 --- a/packages/di/nestjs/src/types.ts +++ b/packages/di/nestjs/src/types.ts @@ -1,4 +1,4 @@ -import type { InjectableIdentifier, InjectableReflectedType } from '@suites/types.di'; +import type { InjectableIdentifier } from '@suites/types.di'; /** * Represents a forward reference token used by NestJS for circular dependencies. @@ -6,7 +6,7 @@ import type { InjectableIdentifier, InjectableReflectedType } from '@suites/type * @since 3.0.0 * @see {@link https://docs.nestjs.com/fundamentals/circular-dependency | NestJS Circular Dependency} */ -export type ForwardRefToken = { forwardRef: () => InjectableReflectedType }; +export type ForwardRefToken = { readonly forwardRef: () => InjectableIdentifier | undefined }; /** * Union type representing all valid NestJS injectable identifiers. @@ -38,7 +38,7 @@ export type IdentifierMetadata = never; */ export interface ReflectedProperty { /** The property key name */ - key: string; + readonly key: string | symbol; /** The type or token to inject */ - type: NestInjectableIdentifier; + readonly type: NestInjectableIdentifier | undefined; } diff --git a/packages/types/di/README.md b/packages/types/di/README.md index 2954504a..9de2e537 100644 --- a/packages/types/di/README.md +++ b/packages/types/di/README.md @@ -37,7 +37,7 @@ Shared contracts between Suites core and DI adapters. Application tests select ` Implement `canAutoConstruct(targetClass)` to identify classes your framework can construct automatically. Return `true` only when you have positive construction evidence, such as a framework-owned marker on the class. An empty dependency list could describe either an injectable leaf or a token. -Existing adapters that implement only `inspect()` remain valid. Without `canAutoConstruct`, Suites can inspect an explicitly selected class, but composition cannot automatically expand through classes provided by that adapter. In a guarded sociable test, a required dependency without another declaration fails when used. Test both a marked class with no dependencies and a class token your adapter must leave unresolved. +In v5, `inspect()` returns an `InspectionResult`. Wrap the former registry in `{ kind: 'success', registry }`. Return a failure with the declaring class, slot, reason and underlying cause when reflection fails. Suites translates this result into the error reported by `compile()`. Without `canAutoConstruct`, Suites can inspect an explicitly selected class, but composition cannot automatically expand through classes provided by that adapter. In a guarded sociable test, a required dependency without another declaration fails when used. Test both a marked class with no dependencies and a class token your adapter must leave unresolved. ## Load adapter declarations diff --git a/packages/types/di/src/errors.ts b/packages/types/di/src/errors.ts index f07adb90..3ce50e40 100644 --- a/packages/types/di/src/errors.ts +++ b/packages/types/di/src/errors.ts @@ -1,3 +1,5 @@ +import type { Type } from '@suites/types.common'; +import type { InspectionFailure } from './index.js'; import { SuitesError, SuitesErrorCode } from '@suites/types.common'; export class IdentifierNotFoundError extends SuitesError { @@ -7,16 +9,40 @@ export class IdentifierNotFoundError extends SuitesError { } } -export class UndefinedDependencyError extends SuitesError { - public constructor(message: string) { - super(SuitesErrorCode.UNDEFINED_DEPENDENCY, 'Undefined dependency identifier', message); +export interface InspectionContext { + readonly root: Type; + readonly failure: InspectionFailure; +} + +abstract class DIInspectionError extends SuitesError { + protected constructor( + code: SuitesErrorCode, + title: string, + message: string, + public readonly context: InspectionContext | undefined + ) { + super(code, title, message); + if (context && context.failure.cause !== undefined) { + Object.defineProperty(this, 'cause', { value: context.failure.cause, configurable: true }); + } + } +} + +export class UndefinedDependencyError extends DIInspectionError { + public constructor(message: string, context: InspectionContext | undefined = undefined) { + super( + SuitesErrorCode.UNDEFINED_DEPENDENCY, + 'Undefined dependency identifier', + message, + context + ); this.name = 'UndefinedDependencyError'; } } -export class UndefinedTokenError extends SuitesError { - public constructor(message: string) { - super(SuitesErrorCode.UNDEFINED_DEPENDENCY, 'Undefined token', message); +export class UndefinedTokenError extends DIInspectionError { + public constructor(message: string, context: InspectionContext | undefined = undefined) { + super(SuitesErrorCode.UNDEFINED_TOKEN, 'Undefined token', message, context); this.name = 'UndefinedTokenError'; } } diff --git a/packages/types/di/src/index.ts b/packages/types/di/src/index.ts index 16eece55..d40c1e7f 100644 --- a/packages/types/di/src/index.ts +++ b/packages/types/di/src/index.ts @@ -31,7 +31,7 @@ export type InjectableReflectedType = ConstantValue | Type | undefined; /** * @since 3.0.0 */ -export type InjectableFinalValue = ConstantValue | Type | UndefinedDependencySymbol; +export type InjectableFinalValue = ConstantValue | AbstractType | UndefinedDependencySymbol; /** * @since 3.0.0 @@ -40,7 +40,7 @@ export type WithoutMetadata = { identifier: InjectableIdentifier; value: InjectableFinalValue; type: 'PROPERTY' | 'PARAM'; - property?: Record; + property?: { readonly key: string | symbol }; }; /** @@ -51,7 +51,7 @@ export type WithMetadata = { value: InjectableFinalValue; type: 'PROPERTY' | 'PARAM'; metadata: Metadata; - property?: Record; + property?: { readonly key: string | symbol }; }; /** @@ -62,11 +62,26 @@ export type ClassInjectable< TIdentifier extends InjectableIdentifier = InjectableIdentifier, > = TIdentifier extends AbstractType ? WithoutMetadata : WithMetadata; -/** - * @since 3.0.0 - */ +/** Location reported by a DI adapter while inspecting a class. */ +export type InspectionLocation = + | { readonly kind: 'class' } + | { readonly kind: 'parameter'; readonly index: number } + | { readonly kind: 'property'; readonly key: string | symbol }; + +export interface InspectionFailure { + readonly kind: 'failure'; + readonly reason: + 'undefined-dependency' | 'undefined-token' | 'unsupported-token' | 'invalid-metadata'; + readonly target: Type; + readonly location: InspectionLocation; + readonly cause: unknown; +} + +export type InspectionResult = + { readonly kind: 'success'; readonly registry: InjectableRegistry } | InspectionFailure; + export interface DependencyInjectionAdapter { - inspect(targetClass: Type): InjectableRegistry; + inspect(targetClass: Type): InspectionResult; /** * Returns true when framework metadata identifies a class for automatic composition. * Adapters that omit this capability still support explicit construction through inspect(). diff --git a/packages/unit/__test__/adaper-package-resolving.integration.test.ts b/packages/unit/__test__/adaper-package-resolving.integration.test.ts index 9eb38df5..d5d2f8dc 100644 --- a/packages/unit/__test__/adaper-package-resolving.integration.test.ts +++ b/packages/unit/__test__/adaper-package-resolving.integration.test.ts @@ -1,3 +1,4 @@ +import { ok } from 'node:assert/strict'; import type { DependencyInjectionAdapter } from '@suites/types.di'; import { createPackageResolver } from '../src/package-resolver.js'; import { diContract, type PackageResolver } from '../src/package-resolver.base.js'; @@ -34,7 +35,9 @@ describe('Suites Adapter Package Resolving Integration Test', () => { it('should successfully resolve the adapter package', async () => { const diAdapter = await packageResolver.resolveCorrespondingAdapter(); - expect(diAdapter.inspect(EmptyService).list()).toEqual([]); + const inspection = diAdapter.inspect(EmptyService); + ok(inspection.kind === 'success'); + expect(inspection.registry.list()).toEqual([]); }); }); diff --git a/packages/unit/__test__/assets/test-adapter.ts b/packages/unit/__test__/assets/test-adapter.ts index aefcf588..4b0b1200 100644 --- a/packages/unit/__test__/assets/test-adapter.ts +++ b/packages/unit/__test__/assets/test-adapter.ts @@ -6,5 +6,5 @@ const emptyRegistry = { } satisfies InjectableRegistry; export const adapter = { - inspect: () => emptyRegistry, + inspect: () => ({ kind: 'success', registry: emptyRegistry }), } satisfies DependencyInjectionAdapter; diff --git a/packages/unit/__test__/package-resolver.base.spec.ts b/packages/unit/__test__/package-resolver.base.spec.ts index dcbcde10..0457ebdd 100644 --- a/packages/unit/__test__/package-resolver.base.spec.ts +++ b/packages/unit/__test__/package-resolver.base.spec.ts @@ -1,3 +1,4 @@ +import { ok } from 'node:assert/strict'; import type { DependencyInjectionAdapter } from '@suites/types.di'; import { checkPackage, @@ -30,7 +31,9 @@ describe('PackageResolver Unit Spec', () => { it('should successfully resolve the adapter', async () => { const adapter = await packageResolver.resolveCorrespondingAdapter(); - expect(adapter.inspect(EmptyService).list()).toEqual([]); + const inspection = adapter.inspect(EmptyService); + ok(inspection.kind === 'success'); + expect(inspection.registry.list()).toEqual([]); }); }); @@ -151,7 +154,9 @@ describe('PackageResolver Unit Spec', () => { it('should resolve the first matching adapter', async () => { const adapter = await packageResolver.resolveCorrespondingAdapter(); - expect(adapter.inspect(EmptyService).list()).toEqual([]); + const inspection = adapter.inspect(EmptyService); + ok(inspection.kind === 'success'); + expect(inspection.registry.list()).toEqual([]); }); it('should stop checking once a match is found', async () => { diff --git a/scripts/e2e-harness.test.cjs b/scripts/e2e-harness.test.cjs index bb835f4d..60a2bf36 100644 --- a/scripts/e2e-harness.test.cjs +++ b/scripts/e2e-harness.test.cjs @@ -36,7 +36,7 @@ function candidatePackages( ]; } -test('V5 canary staging keeps supporting packages and their dependency ranges on V4', (t) => { +test('v5 canary stages the DI contract and each implementing adapter', (t) => { const root = mkdtempSync(join(tmpdir(), 'suites-e2e-canary-versions-')); t.after(() => rmSync(root, { recursive: true, force: true })); const manifests = [ @@ -65,11 +65,14 @@ test('V5 canary staging keeps supporting packages and their dependency ranges on assert.equal(readManifest('packages/runners/vitest/package.json').version, '5.0.0-e2e.0'); assert.equal( readManifest('packages/core/package.json').dependencies['@suites/types.di'], - 'workspace:^4.1.2' + 'workspace:^5.0.0-e2e.0' ); assert.equal(readManifest('packages/types/common/package.json').version, '5.0.0-e2e.0'); assert.equal(readManifest('packages/types/di/package.json').dependencies['@suites/types.common'], 'workspace:^5.0.0-e2e.0'); - assert.equal(readManifest('packages/types/di/package.json').version, '4.1.3'); + for (const path of ['types/di', 'di/nestjs', 'di/inversify', 'di/injection-js']) { + assert.equal(readManifest(`packages/${path}/package.json`).version, '5.0.0-e2e.0'); + } + assert.equal(readManifest('packages/types/doubles/package.json').version, '4.1.3'); assert.equal( readManifest('packages/unit/package.json').dependencies['@suites/core.unit'], 'workspace:^5.0.0-e2e.0' diff --git a/scripts/e2e/major-canary.cjs b/scripts/e2e/major-canary.cjs index c30a5fde..07ff6ff1 100644 --- a/scripts/e2e/major-canary.cjs +++ b/scripts/e2e/major-canary.cjs @@ -8,6 +8,10 @@ const { automaticCompatibility } = require('./targets.cjs'); const v5ReleaseGroup = new Set([ '@suites/core.unit', '@suites/types.common', + '@suites/types.di', + '@suites/di.injectionjs', + '@suites/di.inversify', + '@suites/di.nestjs', '@suites/doubles.jest', '@suites/doubles.vitest', '@suites/runners.jest', diff --git a/scripts/eslint-type-contracts.config.mjs b/scripts/eslint-type-contracts.config.mjs index a4e75fab..a99ffa2d 100644 --- a/scripts/eslint-type-contracts.config.mjs +++ b/scripts/eslint-type-contracts.config.mjs @@ -3,7 +3,7 @@ import typescript from '@typescript-eslint/eslint-plugin'; const stateTypes = ':matches(TSInterfaceDeclaration, TSTypeAliasDeclaration)' + - '[id.name=/^(ConstructionMode|SociableConfiguration|ResolverOptions|DependencyPathEntry|CompositionBoundary)$/]'; + '[id.name=/^(ConstructionMode|SociableConfiguration|ResolverOptions|DependencyPathEntry|CompositionBoundary|InspectionResult|InspectionFailure|InspectionLocation)$/]'; const chainedAssertion = { selector: @@ -31,6 +31,7 @@ export default [ }, { files: [ + 'packages/types/di/src/index.ts', 'packages/core/src/services/builders/sociable-unit-builder.ts', 'packages/core/src/services/composition-boundary.ts', 'packages/core/src/services/dependency-resolver.ts', diff --git a/scripts/lint/type-contracts.test.cjs b/scripts/lint/type-contracts.test.cjs index 2e5542f4..98700267 100644 --- a/scripts/lint/type-contracts.test.cjs +++ b/scripts/lint/type-contracts.test.cjs @@ -51,3 +51,11 @@ test('allows optional and mutable properties outside the named core state contra }); assert.deepEqual(result.messages, []); }); + +test('requires immutable fields on DI inspection results and locations', async () => { + const filePath = 'packages/types/di/src/index.ts'; + for (const name of ['InspectionResult', 'InspectionFailure', 'InspectionLocation']) { + const [invalid] = await linter.lintText(`type ${name} = { readonly kind: "failure"; target?: string };`, { filePath }); + assert.equal(invalid.errorCount, 2); + } +}); From 0147841cc51de914a316e81eedb0403feb86ba94 Mon Sep 17 00:00:00 2001 From: omermorad Date: Fri, 27 Nov 2026 19:56:48 +0200 Subject: [PATCH 3/4] fix(core): explain how to provide a token for an erased constructor type --- packages/core/src/services/dependency-resolver.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/src/services/dependency-resolver.ts b/packages/core/src/services/dependency-resolver.ts index 2270e13b..821d5023 100644 --- a/packages/core/src/services/dependency-resolver.ts +++ b/packages/core/src/services/dependency-resolver.ts @@ -164,7 +164,7 @@ export class DependencyResolver { const advice = reason === 'unsupported-token' ? 'Use a dependency token supported by the installed adapter.' - : 'Check the injection decorator and emitted metadata.'; + : 'Check the injection decorator and emitted metadata. Use @Inject(token) in NestJS or InjectionJS, or @inject(token) in InversifyJS, for an erased constructor type.'; throw new UndefinedDependencyError(`${detail} ${advice}`, context); } From 88adc3632c3d85955fd7a755845dac343f1f2437 Mon Sep 17 00:00:00 2001 From: omermorad Date: Fri, 27 Nov 2026 19:59:23 +0200 Subject: [PATCH 4/4] test(di): cover missing metadata and explicit tokens across adapters --- .../test/adapter.integration.test.ts | 43 +++++++++++++++++++ .../inversify-adapter.integration.test.ts | 33 ++++++++++++++ .../nestjs-adapter.integration.test.ts | 40 +++++++++++++++++ 3 files changed, 116 insertions(+) diff --git a/packages/di/injection-js/test/adapter.integration.test.ts b/packages/di/injection-js/test/adapter.integration.test.ts index 28bf28df..414c6cb8 100644 --- a/packages/di/injection-js/test/adapter.integration.test.ts +++ b/packages/di/injection-js/test/adapter.integration.test.ts @@ -205,3 +205,46 @@ describe('InjectionJS constructor adapter', () => { expect(caught).toBe(cause); }); }); + +describe('InjectionJS static metadata diagnostics', () => { + it('preserves the declared index when static metadata covers only the first argument', () => { + class Checkout { + static parameters = [[Repository]]; + constructor( + readonly first: Repository, + readonly missing: unknown + ) {} + } + expect(adapter.inspect(Checkout)).toMatchObject({ + kind: 'failure', + target: Checkout, + reason: 'undefined-dependency', + location: { kind: 'parameter', index: 1 }, + cause: expect.any(Error), + }); + }); + + it('accepts raw static tokens as the production resolver does', () => { + class Checkout { + static parameters = [new Inject(TOKEN)]; + constructor(readonly repository: unknown) {} + } + const [dependency] = ReflectiveInjector.resolve([Checkout])[0].resolvedFactories[0] + .dependencies; + expect(registryFor(Checkout).list()[0].identifier).toBe(dependency.key.token); + }); + + it('handles lowered decorators in their array form with an explicit undefined token', () => { + class Checkout { + static ctorParameters = [{ type: Object, decorators: [{ type: Inject, args: [undefined] }] }]; + constructor(readonly repository: unknown) {} + } + expect(adapter.inspect(Checkout)).toMatchObject({ + kind: 'failure', + target: Checkout, + reason: 'undefined-token', + location: { kind: 'parameter', index: 0 }, + cause: expect.any(Error), + }); + }); +}); diff --git a/packages/di/inversify/__test__/inversify-adapter.integration.test.ts b/packages/di/inversify/__test__/inversify-adapter.integration.test.ts index e0ec6803..c0d315ba 100644 --- a/packages/di/inversify/__test__/inversify-adapter.integration.test.ts +++ b/packages/di/inversify/__test__/inversify-adapter.integration.test.ts @@ -382,3 +382,36 @@ describe('Inversify reflection failures', () => { expect(caught).toBe(cause); }); }); + +describe('constructor diagnostics', () => { + it('reports a constructor token whose lazy reference resolves to undefined', () => { + @injectable() + class Checkout { + constructor( + @inject('audit') readonly audit: unknown, + @inject(new LazyServiceIdentifier(() => undefined as never)) readonly payments: unknown + ) {} + } + expect(adapter.inspect(Checkout)).toEqual({ + kind: 'failure', + reason: 'undefined-token', + target: Checkout, + location: { kind: 'parameter', index: 1 }, + cause: undefined, + }); + }); + + it('retains the framework rejection for a constructor with incomplete metadata', () => { + class Undecorated { + constructor(readonly missing: unknown) {} + } + const result = adapter.inspect(Undecorated); + expect(result).toMatchObject({ + kind: 'failure', + reason: 'invalid-metadata', + target: Undecorated, + location: { kind: 'class' }, + cause: expect.any(Error), + }); + }); +}); diff --git a/packages/di/nestjs/__test__/nestjs-adapter.integration.test.ts b/packages/di/nestjs/__test__/nestjs-adapter.integration.test.ts index 5d9fa742..28f0ac9d 100644 --- a/packages/di/nestjs/__test__/nestjs-adapter.integration.test.ts +++ b/packages/di/nestjs/__test__/nestjs-adapter.integration.test.ts @@ -1,3 +1,5 @@ +import { Inject, forwardRef } from '@nestjs/common'; +import { PARAMTYPES_METADATA } from '@nestjs/common/constants'; import { ok } from 'node:assert/strict'; import { ClassWithUndefinedDependency, @@ -278,3 +280,41 @@ describe('missing constructor metadata', () => { }); }); }); + +describe('explicit tokens', () => { + it('reads a token recorded without any design:paramtypes metadata', () => { + class Checkout { + constructor(@Inject('payment') readonly payment: unknown) {} + } + Reflect.deleteMetadata(PARAMTYPES_METADATA, Checkout); + expect(registryFor(Checkout).resolve('payment')).toEqual({ + identifier: 'payment', + type: 'PARAM', + value: UndefinedDependency, + }); + }); + + it('reports the symbol property of an undefined lazy token', () => { + const key = Symbol('audit'); + class Checkout { + @Inject(forwardRef(() => undefined)) + readonly [key]!: unknown; + } + expect(adapter.inspect(Checkout)).toEqual({ + kind: 'failure', + reason: 'undefined-token', + target: Checkout, + location: { kind: 'property', key }, + cause: undefined, + }); + }); + + it('keeps a usable explicit token when its design type is Object', () => { + class Checkout { + constructor(@Inject('payment') readonly payment: unknown) {} + } + expect(registryFor(Checkout).list()).toEqual([ + { identifier: 'payment', type: 'PARAM', value: Object }, + ]); + }); +});