mnemonica 1.0.8 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -253,9 +253,124 @@ export type CollectionDef = Hookable & {
253
253
  };
254
254
 
255
255
  // Type lookup function type: may have augmentation by Tactica re-definition
256
- export interface TypeLookup extends CallableFunction {
257
- (this: Map<string, unknown>, TypeNestedPath: string): TypeClass | undefined;
256
+ // Global registry shape used as the default for TypeLookup. It combines any
257
+ // augmented TypeRegistry entries with a broad string index signature so the
258
+ // generic TypeLookup constraint is satisfied.
259
+ export type GlobalRegistry = TypeRegistry & Record<string, TypeConstructorBase>;
260
+
261
+ // Extract the instance type returned by a mnemonica-compatible constructor.
262
+ // Falls back to `object` so generic helpers that require an object constraint
263
+ // do not fail when the constructor shape is not yet narrowed.
264
+ export type ExtractConstructorInstance<C> =
265
+ C extends { new (...args: unknown[]): infer I }
266
+ ? I extends object ? I : object
267
+ : object;
268
+
269
+ // Map dotted registry paths that extend `${Path}.${Child}` into child
270
+ // constructor properties on the parent instance. This lets typed lookups
271
+ // return a constructor whose instances carry their subtypes, e.g.
272
+ // `new (App.lookup('User'))(...).Admin`.
273
+ export type SubTypeConstructors<
274
+ Registry extends object,
275
+ Path extends string
276
+ > = {
277
+ [K in keyof Registry as K extends `${Path}.${infer Child}` ? Child : never]:
278
+ LookupResult<Registry, K & string>;
279
+ };
280
+
281
+ // Reconstruct a constructor with a new instance type while preserving every
282
+ // non-`prototype`, non-`lookup` property (`define`, hooks, etc.). `lookup` is
283
+ // replaced separately so it can be scoped to the constructor's own type path.
284
+ export type ReplaceConstructorInstance<
285
+ C,
286
+ NewInstance extends object
287
+ > = C extends {
288
+ new (...args: infer A): unknown;
289
+ (...args: infer A2): unknown;
290
+ readonly prototype: unknown;
258
291
  }
292
+ ? {
293
+ new (...args: A): NewInstance;
294
+ (this: NewInstance, ...args: A2): NewInstance;
295
+ readonly prototype: NewInstance & {
296
+ readonly constructor: ReplaceConstructorInstance<C, NewInstance>;
297
+ };
298
+ } & Omit<C, 'prototype' | 'lookup'>
299
+ : never;
300
+
301
+ // Instance type produced by a typed lookup: the constructor's own instance
302
+ // shape plus child-constructor properties for every registered subtype.
303
+ // Kept as a named alias so hover tooltips show the base shape first instead of
304
+ // expanding the whole registry.
305
+ export type WithSubTypes<
306
+ Instance extends object,
307
+ Registry extends object,
308
+ Path extends string
309
+ > = Instance & SubTypeConstructors<Registry, Path>;
310
+
311
+ // Constructor returned by a typed lookup, with its instance type augmented by
312
+ // the subtypes registered under that path. Kept as a named alias so the
313
+ // recursive reference from `SubTypeConstructors` resolves cleanly.
314
+ export type AugmentedConstructor<
315
+ Registry extends object,
316
+ Path extends keyof Registry & string
317
+ > = ReplaceConstructorInstance<
318
+ Registry[Path],
319
+ WithSubTypes<ExtractConstructorInstance<Registry[Path]>, Registry, Path>
320
+ >;
321
+
322
+ // Result of a typed lookup: the augmented constructor plus a `lookup` method
323
+ // scoped to the constructor's own type path for relative subtype lookups.
324
+ export type LookupResult<
325
+ Registry extends object,
326
+ Path extends keyof Registry & string
327
+ > = Registry[Path] extends TypeConstructorBase
328
+ ? AugmentedConstructor<Registry, Path> & {
329
+ lookup: NestedTypeLookup<Registry, Path>;
330
+ }
331
+ : never;
332
+
333
+ export interface TypeLookup<T extends object = GlobalRegistry> extends CallableFunction {
334
+ <const K extends keyof T & string>(this: unknown, TypeNestedPath: K): LookupResult<T, K>;
335
+ (this: unknown, TypeNestedPath: string): TypeClass | undefined;
336
+ }
337
+
338
+ // Relative keys of a registry under a given dotted path. For a root path (`''`)
339
+ // this is all string keys; for a non-empty path it is the tail after `${Path}.`.
340
+ export type RelativeKeys<
341
+ Registry extends object,
342
+ Path extends string
343
+ > = Path extends ''
344
+ ? keyof Registry & string
345
+ : (keyof Registry extends infer K
346
+ ? K extends `${Path}.${infer Child}` ? Child : never
347
+ : never);
348
+
349
+ // Full registry key that corresponds to a relative key `K` under `Path`.
350
+ export type FullKey<
351
+ Registry extends object,
352
+ Path extends string,
353
+ K extends string
354
+ > = Path extends '' ? K : Extract<keyof Registry & string, `${Path}.${K}`>;
355
+
356
+ // Lookup function type for constructors and registry holders that know their
357
+ // own dotted type path. Root holders use `Path = ''` and behave like the global
358
+ // `TypeLookup`; child constructors use their own path for relative lookups.
359
+ export type NestedTypeLookup<
360
+ Registry extends object,
361
+ Path extends string = ''
362
+ > = (Path extends ''
363
+ ? {
364
+ <const K extends keyof Registry & string>(this: unknown, TypeNestedPath: K): LookupResult<Registry, K>;
365
+ }
366
+ : {
367
+ <const K extends RelativeKeys<Registry, Path> & string>(
368
+ this: unknown,
369
+ TypeNestedPath: K
370
+ ): LookupResult<Registry, Extract<keyof Registry & string, `${Path}.${K}`>>;
371
+ }) & {
372
+ (this: unknown, TypeNestedPath: string): TypeClass | undefined;
373
+ };
259
374
 
260
375
  // Specification for chained subtype creation with .then()
261
376
  export interface ThenSpec {
@@ -297,7 +412,12 @@ export interface InstanceCreatorContext {
297
412
  *
298
413
  * Result: child T gets all its own props, plus parent's non-overlapping props.
299
414
  */
300
- export type Proto<P extends object, T extends object> = T & Pick<P, Exclude<keyof P, keyof T>>;
415
+ // When the parent contributes no properties, collapse to the child type so
416
+ // hover tooltips stay readable.
417
+ export type Proto<P extends object, T extends object> =
418
+ [Exclude<keyof P, keyof T>] extends [never]
419
+ ? T
420
+ : T & Pick<P, Exclude<keyof P, keyof T>>;
301
421
 
302
422
 
303
423
  // export type ProtoFlat<
@@ -403,13 +523,75 @@ export type InstanceResult<
403
523
  N extends object,
404
524
  > = { [K in keyof N]: N[K] };
405
525
 
526
+ // Lightweight constructor type stored inside a typed registry map.
527
+ // It preserves the dotted `Path` so that `.define()` on a looked-up constructor
528
+ // computes the correct child path, but it omits the full `GlobalRegistry`
529
+ // generic to keep hover tooltips readable.
530
+ export type StoredConstructor<
531
+ F extends object,
532
+ Path extends string = ''
533
+ > = _Internal_TC_<F> & RegistryHolderBase<{}, F, Path>;
534
+
535
+ // Registry holder base - provides the accumulating .define() method.
536
+ // `Parent` tracks the instance type of the last defined constructor, so chained
537
+ // subtypes get the correct merged `Proto<Parent, N>` instance type.
538
+ // `Path` is the dotted type path of the holder (empty for root holders).
539
+ export interface RegistryHolderBase<
540
+ T extends object = {},
541
+ Parent extends object = object,
542
+ Path extends string = ''
543
+ > {
544
+ // Legacy overload: define(constructHandler, config?)
545
+ define<SubType extends object>(
546
+ this: RegistryHolderBase<T, Parent, Path>,
547
+ TypeOrTypeName: CallableFunction,
548
+ constructHandlerOrConfig?: IDEF<SubType> | object | boolean | CallableFunction,
549
+ configOrUndefined?: constructorOptions | CallableFunction | boolean
550
+ ): IDefinitorInstance<SubType>;
551
+
552
+ // Modern overload: define(TypeName, constructHandler, config?)
553
+ define<
554
+ const Name extends string,
555
+ N extends object,
556
+ Args extends unknown[],
557
+ F extends Proto<Parent, N> = Proto<Parent, N>,
558
+ ChildPath extends string = Path extends '' ? Name : `${Path}.${Name}`
559
+ >(
560
+ this: RegistryHolderBase<T, Parent, Path>,
561
+ TypeName: Name,
562
+ constructHandler?: IDEF<N, Args>,
563
+ config?: constructorOptions
564
+ ): IDefinitorInstance<
565
+ F,
566
+ InstanceResult<F>,
567
+ T & Record<ChildPath, StoredConstructor<F, ChildPath>>,
568
+ ChildPath
569
+ >;
570
+ }
571
+
572
+ // Full registry holder - adds typed .lookup() for collections that are not
573
+ // also constructors (createTypesCollection, the mnemonica module object).
574
+ export interface RegistryHolder<
575
+ T extends object = {},
576
+ Parent extends object = object,
577
+ Path extends string = ''
578
+ >
579
+ extends RegistryHolderBase<T, Parent, Path> {
580
+ lookup: NestedTypeLookup<T, Path>;
581
+ }
582
+
406
583
  // Definitor instance - the constructor function returned by define
407
584
  // N = instance type (properties available on instances)
408
- // S = subtypes map
585
+ // R = wrapped result instance type
586
+ // Registry = typed registry map for lookup()
587
+ // Path = dotted type path of this constructor (empty for root types)
409
588
  export interface IDefinitorInstance<
410
589
  N extends object,
411
- R extends InstanceResult<N> = InstanceResult<N>
412
- > {
590
+ R extends InstanceResult<N> = InstanceResult<N>,
591
+ Registry extends object = GlobalRegistry,
592
+ Path extends string = ''
593
+ >
594
+ extends RegistryHolderBase<Registry, N, Path> {
413
595
 
414
596
  TypeName: string;
415
597
  prototype: N;
@@ -426,27 +608,12 @@ export interface IDefinitorInstance<
426
608
  // the line below should make is a @decorate decorator working
427
609
  (...args: unknown[]): IDefinitorInstance<R>;
428
610
 
611
+ lookup: TypeLookup<Registry>;
429
612
 
430
- // Define method that combines parent N with new type T using Proto
431
- define<
432
- T extends object,
433
-
434
- // this will be instance type for sub-type !!!
435
- // F extends Flatten<Proto<N, T>>
436
- F extends Proto<N, T>
437
- >(
438
- TypeOrTypeName: string | CallableFunction,
439
- constructHandlerOrConfig?: IDEF<T> | object | boolean | CallableFunction,
440
- configOrUndefined?: constructorOptions | CallableFunction | boolean
441
- ): IDefinitorInstance<F>;
442
-
443
- lookup: TypeLookup;
444
-
445
613
  registerHook(hookType: hooksTypes, cb: hook): void;
446
-
447
-
614
+
448
615
  subtypes: SubtypesMap;
449
-
616
+
450
617
  // Internal properties accessed by tests
451
618
  __type__?: TypeDef;
452
619
  collection?: CollectionDef;
@@ -473,9 +640,12 @@ export interface TypeAbsorber extends CallableFunction {
473
640
 
474
641
  // TypesCollection interface for createTypesCollection
475
642
  // This represents the actual return type of createTypesCollection
476
- export interface TypesCollection extends Hookable {
477
- define: TypeAbsorber;
478
- lookup: TypeLookup;
643
+ export interface TypesCollection<
644
+ T extends object = {},
645
+ Parent extends object = object,
646
+ Path extends string = ''
647
+ >
648
+ extends RegistryHolder<T, Parent, Path>, Hookable {
479
649
  subtypes: SubtypesMap;
480
650
  [key: string]: unknown;
481
651
  }
@@ -489,11 +659,18 @@ export interface Hookable {
489
659
  }
490
660
 
491
661
  // createTypesCollection function type
492
- export type CreateTypesCollectionFunction = (config?: constructorOptions) => TypesCollection;
662
+ export type CreateTypesCollectionFunction =
663
+ <T extends object = {}, Parent extends object = object>(
664
+ config?: constructorOptions
665
+ ) => TypesCollection<T, Parent>;
493
666
 
494
667
  // Type class - base type constructor
495
668
  export type TypeClass = IDefinitorInstance<object>;
496
669
 
670
+ // Generic registry map used by typed collections and the mnemonica builder.
671
+ // Keys are dotted type paths; values are mnemonica-compatible constructors.
672
+ export type TypeRegistryMap = Record<string, TypeConstructorBase>;
673
+
497
674
  // Mnemonica constructor — the constructor function returned by constructHandler()
498
675
  // Has SymbolConstructorName attached and is both newable and callable
499
676
  export interface MnemonicaConstructor extends NewableFunction {
@@ -525,14 +702,24 @@ export type TypeDescriptorInstance = {
525
702
  // Constructor type for decorate function
526
703
  export type Constructor<T = object> = new (...args: unknown[]) => T;
527
704
 
528
- // Decorated class type - includes call signature for decorator pattern
705
+ // Name of a constructor as a string literal type.
706
+ export type ConstructorName<T extends Constructor<object>> =
707
+ T extends { name: infer N } ? N extends string ? N : string : string;
708
+
709
+ // Decorated class type - includes call signature for decorator pattern and
710
+ // aligns with `IDefinitorInstance` so decorated classes expose the same
711
+ // constructor/lookup surface as builder-created types. It still relies on the
712
+ // global `TypeRegistry` for typed lookups because decorators cannot carry a
713
+ // local accumulating registry across independent class declarations.
529
714
  export type DecoratedClass<T extends Constructor<object>> =
530
715
  T &
716
+ Omit<
717
+ IDefinitorInstance<InstanceType<T>, InstanceType<T>, TypeRegistry, ConstructorName<T>>,
718
+ 'define' | 'lookup'
719
+ > &
531
720
  (<U extends Constructor<object>>(target: U) => DecoratedClass<U>) & {
532
721
  define: TypeAbsorber;
533
- registerHook(hookType: hooksTypes, cb: hook): void;
534
- lookup: TypeLookup;
535
- TypeName: string;
722
+ lookup: TypeLookup<TypeRegistry>;
536
723
  };
537
724
 
538
725
  // Helper: merge parent entity (E) and child constructor instance (T) into a
@@ -595,14 +782,12 @@ export interface UtilsCollection {
595
782
  [key: string]: CallableFunction;
596
783
  }
597
784
 
598
- // Main mnemonica module interface - represents the exported module object
599
- export interface MnemonicaModule {
600
- // Core functions
601
- define: TypeAbsorber;
602
- lookup: {
603
- (TypeNestedPath: string): TypeClass | undefined;
604
- <const K extends keyof TypeRegistry>(TypeNestedPath: K): TypeRegistry[K];
605
- };
785
+ // Main mnemonica module interface - represents the exported module object.
786
+ // The optional Registry generic lets the object act as a typed registry holder
787
+ // when chaining .define() calls.
788
+ export interface MnemonicaModule<Registry extends object = {}>
789
+ extends RegistryHolder<Registry, object> {
790
+ // Core functions not covered by RegistryHolder
606
791
  apply: ApplyFunction;
607
792
  call: CallFunction;
608
793
  bind: BindFunction;
@@ -613,7 +798,7 @@ export interface MnemonicaModule {
613
798
  registerHook: <T extends object>(Constructor: IDEF<T>, hookType: hooksTypes, cb: hook) => void;
614
799
 
615
800
  // Descriptors
616
- defaultTypes: TypesCollection;
801
+ defaultTypes: TypesCollection<Registry>;
617
802
 
618
803
  // Errors
619
804
  BASE_MNEMONICA_ERROR: MnemonicaErrorConstructor;
@@ -1,12 +0,0 @@
1
- 'use strict';
2
-
3
- const sss = async function () {
4
- this.m = 1;
5
- };
6
-
7
- console.log(Object.hasOwnProperty.call(sss, 'prototype'));
8
- try {
9
- new sss;
10
- } catch (error) {
11
- console.error(error);
12
- }
@@ -1,23 +0,0 @@
1
- const name = 'ClassName';
2
-
3
- const pointer = class {
4
- constructor () {
5
- this.name = this.constructor.name;
6
- }
7
- };
8
-
9
- console.log( ( new pointer ).name );
10
-
11
-
12
- const reNamer = {};
13
-
14
- reNamer[ name ] = pointer;
15
- Object.defineProperty( reNamer[ name ].prototype.constructor, 'name', {
16
- get () {
17
- return name;
18
- }
19
- } );
20
-
21
- console.log( ( new reNamer[ name ] ).name );
22
-
23
- console.log( ( new pointer ).name );
@@ -1,40 +0,0 @@
1
- # Examples
2
-
3
- Standalone scripts that demonstrate edge cases and document JavaScript /
4
- Node.js behaviors that mnemonica has to work around. They are runnable
5
- from the project root after `npm run build`:
6
-
7
- ```bash
8
- npm run example:async # AsyncNewTest.js
9
- npm run example:rename # ClassReName.js
10
- npm run example:v8bug # v8bug.js
11
- ```
12
-
13
- ## AsyncNewTest.js
14
-
15
- Minimal demonstration that an `async function` does **not** have a
16
- `prototype` property and therefore cannot be invoked with `new`. Mnemonica
17
- must detect this case and route async constructors through a different
18
- path. Useful when reasoning about why `define(name, async fn)` needs
19
- special handling.
20
-
21
- ## ClassReName.js
22
-
23
- Shows how `Object.defineProperty(Ctor.prototype.constructor, 'name', …)`
24
- gives a class a runtime-renamed `constructor.name`. This is the technique
25
- mnemonica uses internally to make every defined type's instance report
26
- its declared `TypeName`, instead of the literal source-level identifier.
27
- The "v8 bug" referenced in `v8bug.js` is the reason this technique
28
- matters.
29
-
30
- ## v8bug.js
31
-
32
- Documents a Node.js 22 regression in how `Object.prototype.hasOwnProperty`
33
- treats the `stack` property of objects whose prototype chain includes an
34
- `Error`. On Node 20 it returns `true` after assignment; on Node 22+ V8
35
- optimizes the assignment away unless `Object.defineProperty` is used.
36
- Mnemonica's stack-cleaning logic must use the getter pattern shown at the
37
- bottom of the file for cross-version compatibility.
38
-
39
- These are regression notes, not tutorials. For user-facing examples and
40
- the public API, start with [`README.md`](../README.md).
package/examples/v8bug.js DELETED
@@ -1,64 +0,0 @@
1
- 'use strict';
2
-
3
-
4
- // though Error.prototype.stack is non standard
5
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack
6
-
7
- const myErrorObject = new Error('my error');
8
- myErrorObject.prop = 123;
9
- const hop = (o, p) => Object.prototype.hasOwnProperty.call(o, p);
10
-
11
- // nodejs v20 & v22 it works properly
12
- console.log(hop(myErrorObject, 'stack'));
13
- // and for Firefox this property above just does not exists at all
14
- // hop(Object.getPrototypeOf(myErrorObject), 'stack');
15
-
16
-
17
- const myIntermediateObject = {};
18
-
19
- Object.setPrototypeOf(myIntermediateObject, myErrorObject);
20
-
21
- console.log(myIntermediateObject instanceof Error);
22
-
23
- myIntermediateObject.stack = myErrorObject.stack;
24
- // it doesn't matter which value you assign there,
25
- // for example uncomment the next line
26
- // myIntermediateObject.stack = 'myErrorObject.stack';
27
- myIntermediateObject.prop = 123;
28
-
29
- // this works properly for node.js v20, but not for v22
30
- console.log(':', hop(myIntermediateObject, 'stack'));
31
- console.log(':', hop(myIntermediateObject, 'prop'));
32
-
33
- const myCorrectedObject = {};
34
- Object.setPrototypeOf(myCorrectedObject, myErrorObject);
35
- console.log(myCorrectedObject instanceof Error);
36
-
37
- Object.defineProperty(myCorrectedObject, 'stack', {
38
- get () {
39
- return myErrorObject.stack;
40
- }
41
- });
42
-
43
- // nodejs v20 & v22 it works properly
44
- console.log(hop(myCorrectedObject, 'stack'));
45
-
46
-
47
-
48
- // so for objects with Error in prototoype chain
49
- // it optimizes .stack property
50
-
51
- // general behaviour works correctly for both
52
- const base = {
53
- stack : 'str',
54
- prop : 123
55
- };
56
-
57
- const sup = {};
58
-
59
- Object.setPrototypeOf(sup, base);
60
-
61
- sup.stack = 'str';
62
- sup.prop = 123;
63
- console.log(hop(sup, 'stack'));
64
- console.log(hop(sup, 'prop'));