mnemonica 1.4.6 → 1.4.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -99,6 +99,8 @@ the only names a declaration file (`.d.ts`) built on mnemonica ever needs:
99
99
 
100
100
  - `RegistryEntry<Shape, Path>` — what the builder stores per defined path
101
101
  and what typed lookups read back;
102
+ - `AsyncRegistryEntry<Shape, Path>` — the same for an `async` handler: its
103
+ construction is typed `Promise<Shape>`, its instances and hooks `Shape`;
102
104
  - `LookedUpConstructor<Registry, Path>` — the type of a `lookup()` result:
103
105
  a constructor whose instances carry their registered subtypes, plus a
104
106
  `lookup()` scoped to its own path;
@@ -181,6 +183,23 @@ const admin2 = new Admin({ role: 'root' }); // fails: no parent instance
181
183
 
182
184
  Direct `new` on a constructor returned by `.define()` works for **root types** only. For subtypes the parent instance is required (or use `apply(parentInstance, Ctor, args)`). With `strictChain: true` (the default) the parent must be the immediate type; with `strictChain: false` ancestor instances further up the chain are also accepted.
183
185
 
186
+ An `async` handler makes construction a Promise at runtime, and the types say so:
187
+
188
+ ```typescript
189
+ const Sessions = App.lookup('User').define('Session', async function (this: SessionShape, token: string) {
190
+ this.token = token;
191
+ return this;
192
+ });
193
+
194
+ const user = new (Sessions.lookup('User'))({ name: 'Ada' });
195
+ const pending = new user.Session('t'); // Promise<…>: no `token` until awaited
196
+ const session = await pending;
197
+ session.token; // string
198
+ session.name; // string, inherited from User
199
+ ```
200
+
201
+ The handler must `return this` (mnemonica rejects the construction otherwise). The registry stores the type as an `AsyncRegistryEntry`; hooks registered on it receive the resolved instance.
202
+
184
203
  ---
185
204
 
186
205
  ## Constructor arguments
@@ -348,6 +367,23 @@ Rule: thread the chain through exports and keep imports tree-shaped (no
348
367
  cycles). Each file sees exactly the types registered up to its point in the
349
368
  chain.
350
369
 
370
+ A subtype defined in a later statement, on a looked-up constructor, joins
371
+ the registry it was looked up from, so the returned value carries
372
+ everything before it plus the new type:
373
+
374
+ ```typescript
375
+ export const App = mnemonica.define('User', …).define('Admin', …);
376
+ export const Sessions = App.lookup('User').define('Session', …);
377
+
378
+ const User = Sessions.lookup('User');
379
+ const user = new User({ name: 'Ada' });
380
+ new user.Admin({ role: 'root' }); // typed
381
+ new user.Session('t'); // typed
382
+ ```
383
+
384
+ `App` itself does not learn about `Session`: its type was fixed when it was
385
+ declared. Look up from the latest value in the chain.
386
+
351
387
  ---
352
388
 
353
389
  ## The registry bridge: `RegistryOf`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mnemonica",
3
- "version": "1.4.6",
3
+ "version": "1.4.8",
4
4
  "description": "AI-agent ready instance inheritance system for JavaScript/TypeScript via prototype chains",
5
5
  "type": "commonjs",
6
6
  "main": "./build/index.js",
@@ -47,9 +47,10 @@
47
47
  "example:rename": "npm run build && node ./test-patterns/ClassReName.js",
48
48
  "example:v8bug": "npm run build && node ./test-patterns/v8bug.js",
49
49
  "example:ts": "npx tsc --ignoreConfig --noCheck --experimentalDecorators --target ES2021 --module CommonJS ./test-ts/test-decorate.ts ./test-ts/test-decorate-typings.ts ./test-ts/test-example.ts ./test-ts/test-no-types.ts ./test-ts/typed-collections.ts ./test-ts/typed-utils.ts ./test-ts/typed-utils-registry.ts && npx eslint --fix ./test-ts/*.js && node ./test-ts/test-no-types.js && node ./test-ts/test-decorate-typings.js",
50
- "test:ts:strict": "npx tsc -p ./test-ts/tsconfig.strict.json",
50
+ "test:ts:strict": "node --max-old-space-size=1024 ./node_modules/typescript/bin/tsc -p ./test-ts/tsconfig.strict.json",
51
51
  "test:ts:7": "npx -y -p typescript@7.0.2 tsc --pretty --noEmit --project tsconfig.json && npx -y -p typescript@7.0.2 tsc --pretty --noEmit --project ./test-ts/tsconfig.strict.json",
52
52
  "test:ts:consumers": "node scripts/check-consumers.js",
53
+ "test:ts": "npm run test:ts:strict && npm run test:ts:consumers && npm run test:ts:7",
53
54
  "test:load": "node scripts/test-load.js",
54
55
  "deopt": "node --trace-deopt --trace-opt ./node_modules/mocha/bin/mocha.js ./test/index.js",
55
56
  "decorate:ts": "npx tsc --ignoreConfig --target ES2021 --moduleResolution NodeNext --module NodeNext --sourceMap ./test/decorate.ts ./test/decorate-builder.ts",
@@ -127,10 +128,10 @@
127
128
  "typescript": "^6.0.3"
128
129
  },
129
130
  "engines": {
130
- "node": ">=18 <26"
131
+ "node": ">=22 <27"
131
132
  },
132
133
  "overrides": {
133
- "serialize-javascript": "^7.0.5",
134
+ "serialize-javascript": "^7.1.3",
134
135
  "uuid": "^11.1.1",
135
136
  "diff": "^9.0.0",
136
137
  "@istanbuljs/load-nyc-config": {
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  import type {
4
- constructorOptions, _Internal_TC_, TypeDef, TypeDescriptorDefine
4
+ constructorOptions, _Internal_TC_, TypeDef, TypeDescriptorDefine, TypeClass
5
5
  } from '../../types';
6
6
 
7
7
  import TypesUtils from '../utils';
@@ -187,7 +187,8 @@ const subTypeApply = (
187
187
  parentType: TypeProxyType,
188
188
  cfg?: constructorOptions
189
189
  ) => {
190
- const decorator = function <T extends { new (): unknown }>(cstr: T): T {
190
+ function decorator <T extends { new (): unknown }>(cstr: T): T;
191
+ function decorator (cstr: { new (): unknown }): TypeClass {
191
192
  const { name } = cstr;
192
193
  const defineResult = parentType.define(
193
194
  name,
@@ -197,9 +198,10 @@ const subTypeApply = (
197
198
  // decorator contract: define() returns the constructor wrapping cstr
198
199
  // (construction still runs through cstr); the class binding is
199
200
  // replaced by that constructor, so it is presented as T
200
- const result = defineResult as unknown as T;
201
+ // The overload carries T; the implementation returns TypeClass directly.
202
+ const result = defineResult;
201
203
  return result;
202
- };
204
+ }
203
205
  return decorator;
204
206
  };
205
207
 
@@ -145,7 +145,7 @@ const getFunctionConstructor = (
145
145
  // !!! it MUST be strict replacement !!!
146
146
  // !!! this is the only way to keep Prototype Chain correct !!!
147
147
  // ConstructHandler.prototype = this.constructor.prototype;
148
- // answer = new (ConstructHandler as unknown as new (...args: unknown[]) => object)( ...args );
148
+ // answer = new ConstructHandler(...args);
149
149
  // ConstructHandler.prototype = _proto;
150
150
 
151
151
  const constructResult = Reflect.construct(
@@ -178,6 +178,8 @@ const compileNewModificatorFunctionBody = function ( FunctionName: string, asCla
178
178
  // this branch runs only when isClass() verified at define
179
179
  // time that the handler is a class — the cast names the class
180
180
  // view (construct signature) of that same function value
181
+ // ConstructHandler has no construct signature; the boolean cannot
182
+ // narrow it without a runtime guard or a changed public signature.
181
183
  ModificationBody = getClassConstructor(
182
184
  ConstructHandler as unknown as ClassConstructHandler,
183
185
  CreationHandler
@@ -189,6 +191,8 @@ const compileNewModificatorFunctionBody = function ( FunctionName: string, asCla
189
191
  // the compiled body is invoked with `new` by the pipeline;
190
192
  // a function expression carries no construct signature, so
191
193
  // the `new`-able view of the same value is named here
194
+ // CreationHandler returns unknown; ModificationBody must construct
195
+ // object, so a direct return annotation cannot replace this cast.
192
196
  ModificationBody = getFunctionConstructor(
193
197
  ConstructHandler,
194
198
  CreationHandler
@@ -14,7 +14,7 @@ export default function () {
14
14
  const CreateInstanceModificator = function (
15
15
  this: object,
16
16
  ModificatorType: MnemonicaConstructor,
17
- ModificatorTypePrototype: { [index: string]: unknown },
17
+ ModificatorTypePrototype: { [index: string]: unknown; constructor: unknown },
18
18
  _addProps: AddPropsCallback
19
19
  ) {
20
20
 
@@ -59,7 +59,6 @@ export default function () {
59
59
  // so now we have to copy all constructor props
60
60
  const props = Object.getOwnPropertyDescriptors(ModificatorTypePrototype);
61
61
  props.constructor = {
62
- // @ts-expect-error I'm too lazy for that
63
62
  value : ModificatorType
64
63
  };
65
64
  Object.defineProperties(
@@ -379,6 +379,8 @@ const typeDescriptorCreator = function (
379
379
  // below); a function expression carries no construct signature, so it is
380
380
  // named once as the constructor interface it is used through — the
381
381
  // prototype contract is attached immediately below
382
+ // The registered result is a TypeProxy, not the descriptor's declared
383
+ // TypeDescriptorInstance shape.
382
384
  const TypeDescriptor = typeDescriptorCreator as _Internal_TC_<TypeDescriptorInstance>;
383
385
 
384
386
  Object.assign(
@@ -607,6 +609,8 @@ const createFromDirectHandler = function (
607
609
  // new TypeDescriptor() returns the TypeProxy it registers in the
608
610
  // subtypes map — a Proxy materializing the TypeClass surface
609
611
  // dynamically — so the public constructor contract is named here
612
+ // The declared descriptor result and dynamic proxy surface differ;
613
+ // changing the producing signature breaks descriptor prototype methods.
610
614
  ) as unknown as TypeClass;
611
615
  return result;
612
616
  };
@@ -18,7 +18,8 @@ import {
18
18
  } from '../types/Props';
19
19
  import type {
20
20
  InstanceConstructor,
21
- MnemonicaConstructor
21
+ MnemonicaConstructor,
22
+ TypeClass
22
23
  } from '../../types';
23
24
 
24
25
  import compileNewModificatorFunctionBody, { ConstructHandler } from '../types/compileNewModificatorFunctionBody';
@@ -39,22 +40,25 @@ const checkProto = (proto: unknown) => {
39
40
  };
40
41
 
41
42
  const getTypeChecker = (TypeName: string) => {
42
- const seeker: unknown = (instance: object) => {
43
+ const seeker: unknown = (instance: object & { [SymbolConstructorName]?: string }) => {
43
44
 
44
- if (typeof instance !== 'object') {
45
+ if (typeof instance !== 'object' || instance === null) {
45
46
  return false;
46
47
  }
47
48
 
48
49
 
49
- if (!instance!.constructor) {
50
+ if (!instance.constructor) {
50
51
  return false;
51
52
  }
52
53
 
53
- // @ts-expect-error I'm too lazy for that
54
- if (Reflect.getPrototypeOf(instance).constructor.name === 'Promise') {
54
+ const prototype = Reflect.getPrototypeOf(instance);
55
+ if (prototype === null) {
56
+ return false;
57
+ }
58
+
59
+ if (prototype.constructor && prototype.constructor.name === 'Promise') {
55
60
  // if ( instance instanceof Promise ) {
56
61
 
57
- // @ts-expect-error I'm too lazy for that
58
62
  const checkResult = instance[ SymbolConstructorName ] === TypeName;
59
63
  return checkResult;
60
64
  }
@@ -185,8 +189,8 @@ export type parentSub = {
185
189
  __parent__: parentSub
186
190
  }
187
191
 
188
- const findSubTypeFromParent = (instance: parentSub | object | undefined, subType: string): parentSub | null => {
189
- let subtype = null;
192
+ const findSubTypeFromParent = (instance: parentSub | object | undefined, subType: string): TypeClass | null => {
193
+ let subtype: TypeClass | null = null;
190
194
 
191
195
  if (!instance) {
192
196
  return null;
@@ -195,8 +199,8 @@ const findSubTypeFromParent = (instance: parentSub | object | undefined, subType
195
199
  const props = _getProps(instance) as Props;
196
200
 
197
201
  if (props) {
198
- if (props.__type__.subtypes.has(subType)) {
199
- const _subtype = props.__type__.subtypes.get(subType);
202
+ const _subtype = props.__type__.subtypes.get(subType);
203
+ if (_subtype !== undefined) {
200
204
  subtype = _subtype;
201
205
  } else {
202
206
  subtype = findSubTypeFromParent(
@@ -206,7 +210,6 @@ const findSubTypeFromParent = (instance: parentSub | object | undefined, subType
206
210
  }
207
211
  }
208
212
 
209
- // @ts-expect-error I'm too lazy for that
210
213
  return subtype;
211
214
  };
212
215
 
@@ -103,7 +103,9 @@ export const constants = {
103
103
  return SymbolDefaultTypesCollection;
104
104
  },
105
105
 
106
- get 'SymbolConfig' () {
106
+ // typed as the declared symbol itself (unique symbol), so it can key a
107
+ // typed property such as CollectionDef's config
108
+ get 'SymbolConfig' (): typeof SymbolConfig {
107
109
  return SymbolConfig;
108
110
  },
109
111
 
@@ -80,6 +80,9 @@ const TypesCollection = function (_config: Record<string, unknown>) {
80
80
  {
81
81
  get () {
82
82
  const result = (instance: { [SymbolConstructorName]?: string }) => {
83
+ if (typeof instance !== 'object' || instance === null) {
84
+ return false;
85
+ }
83
86
  const checkResult = instance[ SymbolConstructorName ] === MNEMONICA;
84
87
  return checkResult;
85
88
  };
package/src/index.ts CHANGED
@@ -67,9 +67,10 @@ export type {
67
67
  RegistryOf,
68
68
  MnemonicaModule,
69
69
  // Deliberate public vocabulary for builder-mode consumers (TS 6
70
- // declaration emit names ONLY entry exports; these three stand in
70
+ // declaration emit names ONLY entry exports; these four stand in
71
71
  // for the internal registry/lookup machinery):
72
72
  RegistryEntry,
73
+ AsyncRegistryEntry,
73
74
  LookedUpConstructor,
74
75
  LookedUpInstance,
75
76
  typedHook,
@@ -207,25 +208,13 @@ export function define <
207
208
  constructHandler?: IDEF<T> | DefineNewableOrCallable | object | boolean,
208
209
  config?: constructorOptions,
209
210
  ): R;
210
- export function define <
211
- T extends object,
212
- P extends object = object,
213
- N extends Proto<P, T> = Proto<P, T>,
214
- R extends IDefinitorInstance<
215
- N,
216
- InstanceResult<N>,
217
- GlobalRegistry,
218
- '',
219
- object,
220
- never[]
221
- > = IDefinitorInstance<N>,
222
- >(
211
+ export function define <T extends object>(
223
212
  this: unknown,
224
213
  TypeNameOrSource?: string | DefineNewableOrCallable | RegistryHolderBase<object, object, string>,
225
214
  constructHandlerOrName?: IDEF<T> | DefineNewableOrCallable | object | boolean | string,
226
215
  configOrHandler?: constructorOptions | IDEF<T> | DefineNewableOrCallable | object | boolean,
227
216
  config?: constructorOptions,
228
- ): R {
217
+ ): IDefinitorInstance<T> {
229
218
 
230
219
  // explicit-source form: define(source, name, handler, config?)
231
220
  // the source may be a TypesCollection (object) or a TypeProxy (function),
@@ -238,28 +227,25 @@ export function define <
238
227
  if (mayBeSource && typeof constructHandlerOrName === 'string') {
239
228
  // .define was verified callable above; the cast only adds its signature
240
229
  const source = sourceCandidate as { define: TypeAbsorber };
230
+ // The implementation returns the delegated constructor directly;
231
+ // caller-specific R views live only on the overloads.
241
232
  const sourceDefineResult = source.define(
242
233
  constructHandlerOrName,
243
234
  configOrHandler as IDEF<T>,
244
235
  config
245
- // facade return: the overload promises R (the caller's constructor
246
- // view); the delegated define produces that same runtime
247
- // constructor under a different generic instantiation
248
- ) as unknown as R;
236
+ );
249
237
  return sourceDefineResult;
250
238
  }
251
239
 
252
240
  const types = checkThis(this) ? defaultTypes : this || defaultTypes;
253
241
  // Type assertion needed because TypesCollectionProxy is a Proxy
242
+ // The implementation returns the delegated constructor directly.
254
243
  const defineResult = (types as { define: TypeAbsorber })
255
244
  .define(
256
245
  TypeNameOrSource as string,
257
246
  constructHandlerOrName as IDEF<T>,
258
247
  configOrHandler as constructorOptions
259
- // facade return: the overload promises R (the caller's constructor
260
- // view); the delegated define produces that same runtime
261
- // constructor under a different generic instantiation
262
- ) as unknown as R;
248
+ );
263
249
  return defineResult;
264
250
  }
265
251
 
@@ -357,7 +343,10 @@ const $run = function <E extends object, T extends object, S extends Proto<E, T>
357
343
  } {
358
344
 
359
345
  // debugger;
360
- // @ts-expect-error - extracting TypeName from function
346
+ // CtorParameter deliberately accepts constructors without a TypeName
347
+ // declaration; runtime mnemonica constructors carry it. Widening that
348
+ // public input type would change the API, so this property read stays.
349
+ // @ts-expect-error -- runtime mnemonica constructors carry TypeName
361
350
  const { TypeName } = Ctor;
362
351
  // the returned SubTypeProxy is a plain function at runtime — constructable —
363
352
  // so TypeConstructorBase (the named minimal constructor shape) is its
@@ -370,7 +359,10 @@ const $run = function <E extends object, T extends object, S extends Proto<E, T>
370
359
  throw new WRONG_MODIFICATION_PATTERN(`[ ${TypeName} ] is not defined as a Type Constructor on used instance`);
371
360
  }
372
361
  const runResult = new Cstr(...args);
373
- // @ts-expect-error - returning result as merged proto type
362
+ // new Cstr returns object here; S is the caller's merged entity/constructor
363
+ // shape and cannot be recovered by narrowing without changing the public
364
+ // result type, so the return stays suppressed.
365
+ // @ts-expect-error -- the merged result shape cannot be recovered by narrowing
374
366
  return runResult;
375
367
  };
376
368
 
@@ -447,7 +439,12 @@ export const decorate = function <
447
439
  ? target as Constructor<object> & { define: TypeAbsorber }
448
440
  : undefined;
449
441
 
450
- const decorator = function <U extends Constructor<object>>(cstr: U): DecoratedClass<U> {
442
+ // decorator contract: define() returns the constructor that wraps cstr;
443
+ // the decorator replaces the class binding with it, so callers see the
444
+ // result as DecoratedClass<U>. The overload states that contract; the
445
+ // implementation signature (not emitted) returns what define() gives.
446
+ function decorator <U extends Constructor<object>>(cstr: U): DecoratedClass<U>;
447
+ function decorator (cstr: Constructor<object>): object {
451
448
  const { name } = cstr;
452
449
  const handler: IDEF<object, never[]> = cstr;
453
450
  if (parentType === undefined) {
@@ -455,20 +452,17 @@ export const decorate = function <
455
452
  name,
456
453
  handler,
457
454
  opts
458
- // decorator contract: define() returns the constructor that
459
- // wraps cstr; the decorator replaces the class binding with
460
- // it, so the result is presented as DecoratedClass<U>
461
- ) as unknown as DecoratedClass<U>;
455
+ );
462
456
  return decoratorResult;
463
457
  }
458
+ // same decorator contract as the branch above
464
459
  const defineResult = parentType.define(
465
460
  name,
466
461
  handler,
467
462
  opts
468
- // same decorator contract as the branch above
469
- ) as unknown as DecoratedClass<U>;
463
+ );
470
464
  return defineResult;
471
- };
465
+ }
472
466
  return decorator;
473
467
  };
474
468
 
@@ -2,6 +2,7 @@
2
2
  /* eslint no-unused-vars: "off" */
3
3
 
4
4
  import type { TypeRegistry } from '../index';
5
+ import type { constants } from '../constants';
5
6
 
6
7
  // Props type for getProps/setProps
7
8
  export type PropsType = Record<string, unknown>;
@@ -87,7 +88,7 @@ export interface ThrowModificationError extends CallableFunction {
87
88
  // The bound fork invoker that instance.fork() returns: consumes fork
88
89
  // arguments, produces a fresh instance of the forked type.
89
90
  export interface ForkInvoker<T extends object> extends CallableFunction {
90
- (this: object, ...forkArgs: unknown[]): T;
91
+ (this: object | void, ...forkArgs: unknown[]): T;
91
92
  }
92
93
 
93
94
  // Error message types - all error messages are strings
@@ -463,11 +464,23 @@ export interface CollectionLookup extends CallableFunction {
463
464
  }
464
465
 
465
466
  // Collection definition
467
+ // A collection's config, stored under SymbolConfig. Every collection carries
468
+ // a name by construction: 'defaultTypes' for the default one, the given or
469
+ // auto-numbered name for custom ones (createTypesCollection).
470
+ export type CollectionConfig = {
471
+ name: string;
472
+ [key: string]: unknown;
473
+ };
474
+
475
+ // the config key is SymbolConfig's own unique symbol type; a mapped type
476
+ // over it keeps this module type-only (no runtime import of constants)
466
477
  export type CollectionDef = Hookable & {
467
478
  define: TypeAbsorber;
468
479
  lookup: CollectionLookup;
469
480
  subtypes: SubtypesMap;
470
481
  [key: string]: unknown;
482
+ } & {
483
+ [K in typeof constants.SymbolConfig]: CollectionConfig;
471
484
  };
472
485
 
473
486
  // Type lookup function type: may have augmentation by Tactica re-definition
@@ -481,13 +494,22 @@ export type CollectionDef = Hookable & {
481
494
  export type GlobalRegistry = TypeRegistry & Record<string, TypeConstructorBase>;
482
495
 
483
496
  // Extract the instance type returned by a mnemonica-compatible constructor.
484
- // Falls back to `object` so generic helpers that require an object constraint
485
- // do not fail when the constructor shape is not yet narrowed.
497
+ // Async entries construct a Promise, but inheritance, hooks, and subtype
498
+ // lookup all operate on the resolved instance. Falls back to `object` so
499
+ // generic helpers that require an object constraint do not fail when the
500
+ // constructor shape is not yet narrowed.
486
501
  export type ExtractConstructorInstance<C> =
487
502
  C extends { new (...args: never[]): infer I }
488
- ? I extends object ? I : object
503
+ ? Awaited<I> extends object ? Awaited<I> : object
489
504
  : object;
490
505
 
506
+ // Preserve the entry's construction kind when replacing its instance shape:
507
+ // an async entry stays Promise-returning on both new and call signatures.
508
+ export type ConstructResult<C, NewInstance extends object> =
509
+ C extends { new (...args: never[]): PromiseLike<unknown> }
510
+ ? Promise<NewInstance>
511
+ : NewInstance;
512
+
491
513
  // Map dotted registry paths that extend `${Path}.${Child}` into child
492
514
  // constructor properties on the parent instance. This lets typed lookups
493
515
  // return a constructor whose instances carry their subtypes, e.g.
@@ -516,7 +538,7 @@ export type ReplaceConstructorInstance<
516
538
  new (...args: infer A): unknown;
517
539
  }
518
540
  ? {
519
- new (...args: A): NewInstance;
541
+ new (...args: A): ConstructResult<C, NewInstance>;
520
542
  readonly prototype: NewInstance & {
521
543
  readonly constructor: ReplaceConstructorInstance<C, NewInstance, CallConstructs>;
522
544
  };
@@ -525,11 +547,11 @@ export type ReplaceConstructorInstance<
525
547
  // SubTypeProxy-backed member: the call form constructs the child
526
548
  // from the parent instance (the chain-tip form new R().A()), so
527
549
  // no `this` demand — detached bare calls construct too.
528
- ? { (...args: A2): NewInstance }
550
+ ? { (...args: A2): ConstructResult<C, NewInstance> }
529
551
  // Raw looked-up constructor: the `this` guard honestly models
530
552
  // .call(childInstance, args); a bare call here is the decorator
531
553
  // path at runtime, not construction.
532
- : { (this: NewInstance, ...args: A2): NewInstance }
554
+ : { (this: NewInstance, ...args: A2): ConstructResult<C, NewInstance> }
533
555
  : unknown)
534
556
  & Omit<C, 'prototype' | 'lookup'>
535
557
  : never;
@@ -567,19 +589,40 @@ export type LookedUpInstance<
567
589
  Path extends string
568
590
  > = WithSubTypes<ExtractConstructorInstance<Registry[Path & keyof Registry]>, Registry, Path>;
569
591
 
570
- // Lookup result type (public vocabulary): the augmented constructor plus a
571
- // lookup method scoped to the constructor's own type path. Non-conditional
572
- // on purpose: a conditional alias resolves during inference and its
573
- // expansion (internal helpers) would leak into consumer declaration emit.
574
- // CallConstructs mirrors the SubTypeProxy distinction (true drops the this
575
- // demand for instance-carried child constructors).
592
+ // Type-only key: no runtime property carries it. It holds a looked-up
593
+ // constructor's own type path (see TypePathMark below).
594
+ declare const TypePathKey: unique symbol;
595
+
596
+ // A looked-up constructor's type path as a member TypeScript compares first.
597
+ // Runtime types are nominal: constructors of different paths are different
598
+ // types even when their shapes match. Without this member, relating two
599
+ // looked-up constructors of different paths walks both subtrees member by
600
+ // member (their path's variance is unreliable, through the template-literal
601
+ // key remapping), at a cost exponential in the subtree's depth and fan, and
602
+ // the checker runs out of memory, e.g. when an instance is passed to a
603
+ // parameter typed as a union of generated types with the wrong member
604
+ // first. With it, such a relation fails at this member.
605
+ export type TypePathMark<Path extends string> = {
606
+ readonly [TypePathKey]?: Path;
607
+ };
608
+
609
+ // Lookup result type (public vocabulary): the full-registry definition
610
+ // surface plus the augmented constructor and a lookup method scoped to the
611
+ // constructor's own type path. Non-conditional on purpose: a conditional
612
+ // alias resolves during inference and its expansion (internal helpers) would
613
+ // leak into consumer declaration emit. CallConstructs mirrors the SubTypeProxy
614
+ // distinction (true drops the this demand for instance-carried child constructors).
615
+ // TypePathMark comes first: an intersection target is checked member by
616
+ // member in order, so a different path is rejected before anything else.
576
617
  export type LookedUpConstructor<
577
618
  Registry extends object,
578
619
  Path extends keyof Registry & string,
579
620
  CallConstructs extends boolean = false
580
- > = AugmentedConstructor<Registry, Path, CallConstructs> & {
581
- lookup: NestedTypeLookup<Registry, Path>;
582
- };
621
+ > = TypePathMark<Path> &
622
+ RegistryHolderBase<Registry, ExtractConstructorInstance<Registry[Path]>, Path> &
623
+ AugmentedConstructor<Registry, Path, CallConstructs> & {
624
+ lookup: NestedTypeLookup<Registry, Path>;
625
+ };
583
626
 
584
627
  // Typed registerHook surface for lookup results whose registry entries are
585
628
  // bare constructors (tactica-emitted or hand-written TypeRegistry entries):
@@ -933,6 +976,24 @@ export interface RegistryEntry<
933
976
  registerHook<HT extends hooksTypes>(hookType: HT, cb: typedHook<HT, Parent, F>): void;
934
977
  }
935
978
 
979
+ // Async registry VALUE: the same public vocabulary as RegistryEntry, with
980
+ // construction returning the Promise that the runtime always produces for an
981
+ // async handler. The resolved F remains the instance used by hooks and
982
+ // subtypes; only construction is deferred.
983
+ export interface AsyncRegistryEntry<
984
+ F extends object,
985
+ Path extends string = '',
986
+ Parent extends object = object,
987
+ Args extends unknown[] = unknown[]
988
+ > extends RegistryHolderBase<{}, F, Path> {
989
+ new (...args: Args): Promise<F>;
990
+ (this: F, ...args: Args): Promise<F>;
991
+ readonly prototype: F & {
992
+ readonly constructor: AsyncRegistryEntry<F, Path, Parent, Args>;
993
+ };
994
+ registerHook<HT extends hooksTypes>(hookType: HT, cb: typedHook<HT, Parent, F>): void;
995
+ }
996
+
936
997
  // Registry holder base - provides the accumulating .define() method.
937
998
  // `Parent` tracks the instance type of the last defined constructor, so chained
938
999
  // subtypes get the correct merged `Proto<Parent, N>` instance type.
@@ -950,6 +1011,29 @@ export interface RegistryHolderBase<
950
1011
  configOrUndefined?: constructorOptions | DefineNewableOrCallable | boolean
951
1012
  ): IDefinitorInstance<SubType>;
952
1013
 
1014
+ // Async modern overload: a Promise-returning callable handler stores an
1015
+ // async entry. It must precede the IDEF overload, whose callable void
1016
+ // result otherwise accepts async functions and erases their Promise.
1017
+ define<
1018
+ const Name extends string,
1019
+ N extends object,
1020
+ Args extends unknown[] = unknown[],
1021
+ F extends Proto<Parent, N> = Proto<Parent, N>,
1022
+ ChildPath extends string = Path extends '' ? Name : `${Path}.${Name}`
1023
+ >(
1024
+ this: RegistryHolderBase<T, Parent, Path>,
1025
+ TypeName: Name,
1026
+ constructHandler: (this: N, ...args: Args) => PromiseLike<unknown>,
1027
+ config?: constructorOptions
1028
+ ): IDefinitorInstance<
1029
+ F,
1030
+ InstanceResult<F>,
1031
+ T & Record<ChildPath, AsyncRegistryEntry<F, ChildPath, Parent, Args>>,
1032
+ ChildPath,
1033
+ Parent,
1034
+ Args
1035
+ >;
1036
+
953
1037
  // Modern overload: define(TypeName, constructHandler, config?)
954
1038
  define<
955
1039
  const Name extends string,
@@ -971,6 +1055,28 @@ export interface RegistryHolderBase<
971
1055
  Args
972
1056
  >;
973
1057
 
1058
+ // Async lazy getter: the callback itself stays synchronous, but the
1059
+ // constructor it returns may produce a Promise on every construction.
1060
+ lazy<
1061
+ const Name extends string,
1062
+ N extends object,
1063
+ Args extends unknown[],
1064
+ F extends Proto<Parent, N> = Proto<Parent, N>,
1065
+ ChildPath extends string = Path extends '' ? Name : `${Path}.${Name}`
1066
+ >(
1067
+ this: RegistryHolderBase<T, Parent, Path>,
1068
+ TypeName: Name,
1069
+ getter: () => (this: N, ...args: Args) => PromiseLike<unknown>,
1070
+ config?: constructorOptions
1071
+ ): IDefinitorInstance<
1072
+ F,
1073
+ InstanceResult<F>,
1074
+ T & Record<ChildPath, AsyncRegistryEntry<F, ChildPath, Parent, Args>>,
1075
+ ChildPath,
1076
+ Parent,
1077
+ Args
1078
+ >;
1079
+
974
1080
  // Lazy getter: .lazy(TypeName, () => Constructor, config?)
975
1081
  // (the unnamed form is dropped: the callback is never called at define
976
1082
  // time, so there is nothing to derive the name from)