mnemonica 1.3.6 → 1.3.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.
Files changed (52) hide show
  1. package/FOR_HUMANS.md +17 -2
  2. package/build/api/errors/exceptionConstructor.js +3 -3
  3. package/build/api/errors/index.js +1 -1
  4. package/build/api/errors/throwModificationError.js +1 -1
  5. package/build/api/hooks/flowCheckers.d.ts +1 -1
  6. package/build/api/hooks/flowCheckers.js +1 -1
  7. package/build/api/hooks/invokeHook.js +1 -1
  8. package/build/api/types/InstanceCreator.js +26 -9
  9. package/build/api/types/InstanceModificator.js +6 -3
  10. package/build/api/types/TypeProxy.js +2 -2
  11. package/build/api/types/compileNewModificatorFunctionBody.js +1 -1
  12. package/build/api/types/index.js +18 -5
  13. package/build/constants/index.js +4 -1
  14. package/build/descriptors/errors/index.js +1 -1
  15. package/build/descriptors/types/index.js +14 -1
  16. package/build/index.js +6 -7
  17. package/build/types/index.d.ts +47 -2
  18. package/build/types/index.js +1 -1
  19. package/build/utils/deepParse.d.ts +2 -0
  20. package/build/utils/deepParse.js +21 -0
  21. package/build/utils/index.js +5 -1
  22. package/build/utils/lineage.d.ts +2 -0
  23. package/build/utils/lineage.js +156 -0
  24. package/build/utils/parent.d.ts +1 -1
  25. package/build/utils/parent.js +9 -4
  26. package/build/utils/parse.d.ts +3 -2
  27. package/build/utils/parse.js +19 -6
  28. package/build/utils/toJSON.js +21 -18
  29. package/docs/UTILS.md +86 -9
  30. package/docs/async-constructors.md +6 -0
  31. package/package.json +4 -2
  32. package/src/api/errors/exceptionConstructor.ts +7 -5
  33. package/src/api/errors/index.ts +5 -1
  34. package/src/api/errors/throwModificationError.ts +1 -1
  35. package/src/api/hooks/flowCheckers.ts +3 -1
  36. package/src/api/hooks/invokeHook.ts +1 -1
  37. package/src/api/types/InstanceCreator.ts +45 -12
  38. package/src/api/types/InstanceModificator.ts +19 -4
  39. package/src/api/types/TypeProxy.ts +11 -2
  40. package/src/api/types/compileNewModificatorFunctionBody.ts +6 -0
  41. package/src/api/types/index.ts +58 -5
  42. package/src/constants/index.ts +6 -0
  43. package/src/descriptors/errors/index.ts +3 -0
  44. package/src/descriptors/types/index.ts +24 -1
  45. package/src/index.ts +33 -14
  46. package/src/types/index.ts +75 -3
  47. package/src/utils/deepParse.ts +28 -0
  48. package/src/utils/index.ts +7 -0
  49. package/src/utils/lineage.ts +220 -0
  50. package/src/utils/parent.ts +20 -5
  51. package/src/utils/parse.ts +42 -6
  52. package/src/utils/toJSON.ts +35 -36
@@ -53,7 +53,7 @@ export const invokeHook = function ( this: Hookable, hookType: string, opts: hoo
53
53
 
54
54
  const flowChecker = flowCheckers.get( this );
55
55
  if ( typeof flowChecker === 'function' ) {
56
- (flowChecker as unknown as (opts: object) => unknown)({
56
+ flowChecker({
57
57
  ...hookArgs,
58
58
  invocationResults,
59
59
  hookType,
@@ -194,8 +194,20 @@ const postProcessing = function ( this: InstanceCreatorContext, continuationOf?:
194
194
  }
195
195
 
196
196
  const prev = parent(self.inheritedInstance) as object | null;
197
- if (!prev || (prev && !prev.constructor)) {
198
- const msg = 'should inherit from some instance';
197
+ if (!prev) {
198
+ // no-parent-is-null: prev is null for a ROOT inherited instance
199
+ // and for a broken chain. The raw __parent__ record tells them
200
+ // apart — a root's is the internal sentinel (has a constructor:
201
+ // the lineage is wrong, name the expected parent); a broken
202
+ // chain's is constructor-less or unreachable (reading it throws:
203
+ // "some instance")
204
+ const madeOnName = prevParentChainHeadName(self.inheritedInstance);
205
+ let msg: string;
206
+ if ( madeOnName === undefined ) {
207
+ msg = 'should inherit from some instance';
208
+ } else {
209
+ msg = `should inherit from ${self.type.parentType!.TypeName} but made on ${inheritedConstructor.name}`;
210
+ }
199
211
  self.throwModificationError( new WRONG_MODIFICATION_PATTERN(
200
212
  msg,
201
213
  stack
@@ -219,6 +231,17 @@ const postProcessing = function ( this: InstanceCreatorContext, continuationOf?:
219
231
 
220
232
  };
221
233
 
234
+ const prevParentChainHeadName = function ( inherited: object ): string | undefined {
235
+ try {
236
+ const inheritedProps = _getProps( inherited ) as Props;
237
+ const chainHead = inheritedProps.__parent__ as { constructor: { name: string } };
238
+ const chainHeadConstructorName = chainHead.constructor.name;
239
+ return chainHeadConstructorName;
240
+ } catch {
241
+ return undefined;
242
+ }
243
+ };
244
+
222
245
  const addThen = function ( this: InstanceCreatorContext, then: ThenSpec ) {
223
246
 
224
247
 
@@ -234,7 +257,7 @@ const addThen = function ( this: InstanceCreatorContext, then: ThenSpec ) {
234
257
  // was chained :
235
258
  true
236
259
  // self.existentInstance
237
- ) as unknown as Promise<object>;
260
+ );
238
261
  return self.inheritedInstance;
239
262
  } );
240
263
 
@@ -366,17 +389,21 @@ const runSetup = function (
366
389
  }
367
390
  );
368
391
 
392
+ const title = `\n<-- creation of [ ${TypeName} ] traced -->`;
393
+ // stack is always an ARRAY — it is unshifted into and spread later.
394
+ // The title alone marks the creation without the captured frames;
395
+ // getStack below replaces it with the captured frames when submitStack
396
+ // asks for them, and runAsyncHandling captures them for async
397
+ // constructions that are still title-only by then
398
+ self.stack = [ title ];
369
399
  if ( submitStack || chained ) {
370
400
  const stackAddition: string[] = chained ? self.getExistentAsyncStack( existentInstance ) as string[] : [];
371
- const title = `\n<-- creation of [ ${TypeName} ] traced -->`;
372
401
  if ( submitStack ) {
373
402
  getStack.call(
374
403
  self,
375
404
  title,
376
- stackAddition
405
+ stackAddition
377
406
  );
378
- } else {
379
- self.stack = title as unknown as string[];
380
407
  }
381
408
  }
382
409
  };
@@ -421,13 +448,14 @@ const runAsyncHandling = function ( self: InstanceCreatorContext, type: TypeDef
421
448
  // (makeAwaiter .catch → throwModificationError), the call site has
422
449
  // already unwound, and a fresh capture would hold nothing but
423
450
  // rejection-processing frames. Skipped when runSetup already captured
424
- // one (submitStack).
425
- if ( !Array.isArray( self.stack ) ) {
451
+ // one (submitStack) — and, with runSetup's [ title ] placeholder
452
+ // array, when the stack holds MORE than the title alone.
453
+ if ( !Array.isArray( self.stack ) || self.stack.length < 2 ) {
426
454
  const title = `\n<-- creation of [ ${type.TypeName} ] traced -->`;
427
455
  getStack.call(
428
456
  self,
429
457
  title,
430
- []
458
+ []
431
459
  );
432
460
  }
433
461
  const waiter = self.makeAwaiter( type );
@@ -445,7 +473,7 @@ const runAsyncHandling = function ( self: InstanceCreatorContext, type: TypeDef
445
473
  return undefined;
446
474
  };
447
475
 
448
- export const InstanceCreator = function (
476
+ const instanceCreatorImpl = function (
449
477
  this: InstanceCreatorContext,
450
478
  type: TypeDef,
451
479
  existentInstance: object,
@@ -494,7 +522,12 @@ export const InstanceCreator = function (
494
522
  // Phase 7: Return
495
523
  return self.inheritedInstance;
496
524
 
497
- } as unknown as _Internal_TC_<typeof InstanceCreatorPrototype>;
525
+ };
526
+
527
+ // always invoked with `new` (the TypeProxy construct trap, makeAwaiter's
528
+ // addThen); a function expression carries no construct signature, so it is
529
+ // named once as the constructor interface it is used through
530
+ export const InstanceCreator = instanceCreatorImpl as _Internal_TC_<typeof InstanceCreatorPrototype>;
498
531
 
499
532
  Object.assign(
500
533
  InstanceCreator.prototype,
@@ -16,15 +16,30 @@ export const makeInstanceModificator = ( self: InstanceCreatorContext ): Mnemoni
16
16
  existentInstance,
17
17
  ModificatorType,
18
18
  proto,
19
+ config,
19
20
  } = self;
20
21
 
22
+ // Class-handler prototypes need the FULL-descriptor copy: class body
23
+ // methods are non-enumerable, and an enumerable-only Object.assign copy
24
+ // silently dropped them — Type.define('X', class { m() {} }) lost m on
25
+ // the subtype while lazy kept it. Function-handler prototypes keep the
26
+ // historical enumerable-only copy: their non-enumerable props (legacy
27
+ // opt-in instance methods, exception wiring) were never copied, and
28
+ // pins depend on that (exception instances expose no bound methods)
29
+ const ModificatorTypePrototype = config.asClass
30
+ ? Object.defineProperties(
31
+ {},
32
+ Object.getOwnPropertyDescriptors( proto )
33
+ )
34
+ : Object.assign(
35
+ {},
36
+ proto
37
+ );
38
+
21
39
  const result = ModificationConstructor.call(
22
40
  existentInstance,
23
41
  ModificatorType,
24
- Object.assign(
25
- {},
26
- proto
27
- ),
42
+ ModificatorTypePrototype,
28
43
  ( __proto_proto__: unknown ) => {
29
44
  self.__proto_proto__ = __proto_proto__ as object;
30
45
  _addProps.call( self );
@@ -105,9 +105,15 @@ TypeProxy.prototype.set = function (this: TypeProxyInstance, _target: unknown, n
105
105
  // is about setting a prototype to Type
106
106
  if (name === 'prototype') {
107
107
  checkProto(value);
108
- Object.assign(
108
+ // the FULL-descriptor copy, not Object.assign: an enumerable-only
109
+ // copy silently drops non-enumerable props — assigning a class
110
+ // prototype object lost its methods — and INVOKES getters, freezing
111
+ // them to a value instead of keeping them getters. Object.assign
112
+ // does copy enumerable symbol-keyed props; what it loses is the
113
+ // non-enumerables and the getters
114
+ Object.defineProperties(
109
115
  type.proto,
110
- value
116
+ Object.getOwnPropertyDescriptors( value )
111
117
  );
112
118
  return true;
113
119
  }
@@ -140,6 +146,9 @@ const subTypeApply = (
140
146
  cstr,
141
147
  cfg
142
148
  );
149
+ // decorator contract: define() returns the constructor wrapping cstr
150
+ // (construction still runs through cstr); the class binding is
151
+ // replaced by that constructor, so it is presented as T
143
152
  const result = defineResult as unknown as T;
144
153
  return result;
145
154
  };
@@ -161,6 +161,9 @@ const compileNewModificatorFunctionBody = function ( FunctionName: string, asCla
161
161
  const innerResult = function (): ModificationBody {
162
162
  let ModificationBody: ModificationBody;
163
163
  if ( asClass ) {
164
+ // this branch runs only when isClass() verified at define
165
+ // time that the handler is a class — the cast names the class
166
+ // view (construct signature) of that same function value
164
167
  ModificationBody = getClassConstructor(
165
168
  ConstructHandler as unknown as ClassConstructHandler,
166
169
  CreationHandler
@@ -169,6 +172,9 @@ const compileNewModificatorFunctionBody = function ( FunctionName: string, asCla
169
172
  // const ReNamedConstructHandler = {} as unknown;
170
173
  // ReNamedConstructHandler[FunctionName] = ConstructHandler;
171
174
  // ModificationBody = getFunctionConstructor(ReNamedConstructHandler[FunctionName], CreationHandler);
175
+ // the compiled body is invoked with `new` by the pipeline;
176
+ // a function expression carries no construct signature, so
177
+ // the `new`-able view of the same value is named here
172
178
  ModificationBody = getFunctionConstructor(
173
179
  ConstructHandler,
174
180
  CreationHandler
@@ -64,6 +64,7 @@ const {
64
64
  WRONG_TYPE_DEFINITION,
65
65
  TYPENAME_MUST_BE_A_STRING,
66
66
  HANDLER_MUST_BE_A_FUNCTION,
67
+ OPTIONS_ERROR,
67
68
  } = ErrorsTypes;
68
69
 
69
70
  // invokeHook
@@ -95,7 +96,7 @@ export type TypesMap = Map<string, object> & {
95
96
  [MNEMOSYNE]?: CollectionDef;
96
97
  };
97
98
 
98
- const TypeDescriptor = function (
99
+ const typeDescriptorCreator = function (
99
100
  this: TypeDescriptorInstance,
100
101
  defineOrigin: TypeAbsorber,
101
102
  types: TypesMap,
@@ -124,11 +125,20 @@ const TypeDescriptor = function (
124
125
 
125
126
  const title = `${TYPE_TITLE_PREFIX}${TypeName}`;
126
127
 
128
+ // 'name' is a COLLECTION option only: a user passing it here meant to
129
+ // name the collection, not the type — say so readably
130
+ if ( config !== undefined && typeof config === 'object' && 'name' in config ) {
131
+ const nameError = '\"name\" is a collection option ' +
132
+ '(createTypesCollection({ name })) — it cannot be set on a type';
133
+ throw new OPTIONS_ERROR( nameError );
134
+ }
127
135
  config = Object.assign(
128
136
  {},
129
137
  (collection as Record<symbol, unknown>)[ SymbolConfig ],
130
138
  config
131
139
  );
140
+ // never inherited into the type's config either
141
+ Reflect.deleteProperty( config, 'name' );
132
142
 
133
143
  const type = Object.assign(
134
144
  this,
@@ -188,7 +198,13 @@ const TypeDescriptor = function (
188
198
  const result = types.get(TypeName);
189
199
  return result;
190
200
 
191
- } as unknown as _Internal_TC_<TypeDescriptorInstance>;
201
+ };
202
+
203
+ // the creator is only ever invoked with `new` (the createFrom* call sites
204
+ // below); a function expression carries no construct signature, so it is
205
+ // named once as the constructor interface it is used through — the
206
+ // prototype contract is attached immediately below
207
+ const TypeDescriptor = typeDescriptorCreator as _Internal_TC_<TypeDescriptorInstance>;
192
208
 
193
209
  Object.assign(
194
210
  TypeDescriptor.prototype,
@@ -283,13 +299,14 @@ odp(
283
299
  const result = function (options?: object) {
284
300
  const decorator = function (cstr: CallableFunction) {
285
301
  const { name } = cstr;
302
+ // define() returns the registered constructor itself —
303
+ // the full TypeClass is a richer honest type than any cast
286
304
  const defineResult = self.define(
287
305
  name,
288
306
  cstr,
289
307
  options
290
308
  );
291
- const decoratedResult = defineResult as unknown as CallableFunction;
292
- return decoratedResult;
309
+ return defineResult;
293
310
  };
294
311
  return decorator;
295
312
  };
@@ -428,6 +445,9 @@ const createFromDirectHandler = function (
428
445
  makeConstructHandler,
429
446
  proto,
430
447
  config
448
+ // new TypeDescriptor() returns the TypeProxy it registers in the
449
+ // subtypes map — a Proxy materializing the TypeClass surface
450
+ // dynamically — so the public constructor contract is named here
431
451
  ) as unknown as TypeClass;
432
452
  return result;
433
453
  };
@@ -456,8 +476,22 @@ const createFromLazyGetter = function (
456
476
  TypeName
457
477
  );
458
478
 
479
+ // reject the unsupported handler shapes at DEFINE time too — the lazy
480
+ // path used to check only typeof/name, so a getter returning an arrow,
481
+ // a method, a bound function or a generator defined fine and failed
482
+ // (or misbehaved) at construction. Same readable errors as the direct
483
+ // path; checkDuplicate runs first so a taken name still wins with the
484
+ // canonical ALREADY_DECLARED
485
+ classifyConstructHandler(
486
+ TypeName,
487
+ type as ConstructHandler
488
+ );
489
+
459
490
  const asClass = isClass(type);
460
491
 
492
+ // classifyConstructHandler above rejects only no-own-prototype
493
+ // functions; a function with an own NON-OBJECT prototype (prototype = 123)
494
+ // still passes and needs the default-prototype fallback
461
495
  const proto = (
462
496
  hop(
463
497
  type,
@@ -469,6 +503,14 @@ const createFromLazyGetter = function (
469
503
  const makeConstructHandler = () => {
470
504
  const constructHandler = getter();
471
505
 
506
+ // and on EVERY construction: the getter may return a new function
507
+ // each time, so the shape check cannot be cached from define time.
508
+ // This is what makes lazy slower than a direct define
509
+ classifyConstructHandler(
510
+ TypeName,
511
+ constructHandler as ConstructHandler
512
+ );
513
+
472
514
  odp(
473
515
  constructHandler,
474
516
  SymbolConstructorName, {
@@ -491,6 +533,12 @@ const createFromLazyGetter = function (
491
533
  return handlerResult;
492
534
  };
493
535
 
536
+ // 'name' is a COLLECTION option only (same rejection as the direct path)
537
+ if ( config !== undefined && typeof config === 'object' && 'name' in config ) {
538
+ const nameError = '\"name\" is a collection option ' +
539
+ '(createTypesCollection({ name })) — it cannot be set on a type';
540
+ throw new OPTIONS_ERROR( nameError );
541
+ }
494
542
  config = Object.assign(
495
543
  {},
496
544
  config
@@ -505,6 +553,8 @@ const createFromLazyGetter = function (
505
553
  makeConstructHandler,
506
554
  proto,
507
555
  config
556
+ // same TypeProxy return as createFromDirectHandler: the public
557
+ // TypeClass contract is materialized dynamically by the Proxy
508
558
  ) as unknown as TypeClass;
509
559
  return result;
510
560
  };
@@ -648,8 +698,11 @@ export const lookup = function (
648
698
  if (!type) {
649
699
  return undefined;
650
700
  }
701
+ // a type's subtypes map IS the runtime TypesMap (SymbolParentType and
702
+ // MNEMOSYNE are installed at definition time), so the single cast only
703
+ // names that view
651
704
  const result = lookup.call(
652
- type.subtypes as unknown as TypesMap,
705
+ type.subtypes as TypesMap,
653
706
  NextNestedPath
654
707
  );
655
708
  return result;
@@ -81,6 +81,12 @@ const defaultOptions = {
81
81
  return false;
82
82
  },
83
83
 
84
+ // the collection's name for lineage exports (lethe type.collection);
85
+ // unnamed collections export as 'defaultTypes'
86
+ get name () {
87
+ return '';
88
+ },
89
+
84
90
  } as Record<string, unknown>;
85
91
 
86
92
  export const constants = {
@@ -10,6 +10,9 @@ const { ErrorMessages, } = constants;
10
10
 
11
11
  // ErrorsTypes is dynamically built - using MnemonicaErrorConstructor to indicate these are constructable
12
12
  export const ErrorsTypes: { [ index: string ]: MnemonicaErrorConstructor } = {
13
+ // BASE_MNEMONICA_ERROR is a class: its construct signature matches the
14
+ // interface, only the (unused) call signature is missing — the map is
15
+ // only ever `new`-ed, so the bridge is safe
13
16
  BASE_MNEMONICA_ERROR : BASE_MNEMONICA_ERROR as unknown as MnemonicaErrorConstructor
14
17
  };
15
18
 
@@ -258,7 +258,10 @@ odp(
258
258
  TypeNestedPath: string
259
259
  ) {
260
260
  const lookupResult = lookup.call(
261
- this.subtypes as unknown as TypesMap,
261
+ // a collection's subtypes map IS the runtime TypesMap (the
262
+ // MNEMOSYNE/SymbolParentType props are installed at
263
+ // construction), so the single cast only names that view
264
+ this.subtypes as TypesMap,
262
265
  TypeNestedPath
263
266
  );
264
267
  return lookupResult;
@@ -373,9 +376,29 @@ const typesCollectionProxyHandler = {
373
376
  }
374
377
  };
375
378
 
379
+ // every collection exports under exactly one name (lethe type.collection):
380
+ // the first collection — the default one — is 'defaultTypes'; later
381
+ // unnamed collections get 'collection_1', 'collection_2', … in creation
382
+ // order (the scheme tactica writes for mnemographica). No two collections
383
+ // may ever export the same name.
384
+ let defaultCollectionNamed = false;
385
+ let unnamedCollections = 0;
386
+
376
387
  const createTypesCollection = (config: Record<string, unknown> = {}) => {
377
388
 
378
389
  const typesCollection = new TypesCollection(config);
390
+ const collectionConfig = (typesCollection as { [ SymbolConfig ]?: Record<string, unknown> })[
391
+ SymbolConfig
392
+ ];
393
+ if ( collectionConfig && !collectionConfig.name ) {
394
+ if ( !defaultCollectionNamed ) {
395
+ collectionConfig.name = 'defaultTypes';
396
+ defaultCollectionNamed = true;
397
+ } else {
398
+ unnamedCollections += 1;
399
+ collectionConfig.name = `collection_${unnamedCollections}`;
400
+ }
401
+ }
379
402
  const typesCollectionProxy = new Proxy(
380
403
  typesCollection,
381
404
  typesCollectionProxyHandler
package/src/index.ts CHANGED
@@ -13,6 +13,7 @@ import type {
13
13
  Constructor,
14
14
  DecoratedClass,
15
15
  TypeClass,
16
+ TypeConstructorBase,
16
17
  TypeAbsorber,
17
18
  LazyAbsorber,
18
19
  MnemonicaModule,
@@ -180,16 +181,21 @@ export function define <
180
181
  // explicit-source form: define(source, name, handler, config?)
181
182
  // the source may be a TypesCollection (object) or a TypeProxy (function),
182
183
  // so detection is: has a callable .define AND the next arg is a string name
184
+ const sourceCandidate = TypeNameOrSource as { define?: unknown };
183
185
  const mayBeSource = (
184
186
  (typeof TypeNameOrSource === 'object' && TypeNameOrSource !== null) ||
185
187
  typeof TypeNameOrSource === 'function'
186
- ) && typeof (TypeNameOrSource as { define?: unknown }).define === 'function';
188
+ ) && typeof sourceCandidate.define === 'function';
187
189
  if (mayBeSource && typeof constructHandlerOrName === 'string') {
188
- const source = TypeNameOrSource as unknown as { define: TypeAbsorber };
190
+ // .define was verified callable above; the cast only adds its signature
191
+ const source = sourceCandidate as { define: TypeAbsorber };
189
192
  const sourceDefineResult = source.define(
190
193
  constructHandlerOrName,
191
194
  configOrHandler as IDEF<T>,
192
195
  config
196
+ // facade return: the overload promises R (the caller's constructor
197
+ // view); the delegated define produces that same runtime
198
+ // constructor under a different generic instantiation
193
199
  ) as unknown as R;
194
200
  return sourceDefineResult;
195
201
  }
@@ -201,6 +207,9 @@ export function define <
201
207
  TypeNameOrSource as string,
202
208
  constructHandlerOrName as IDEF<T>,
203
209
  configOrHandler as constructorOptions
210
+ // facade return: the overload promises R (the caller's constructor
211
+ // view); the delegated define produces that same runtime
212
+ // constructor under a different generic instantiation
204
213
  ) as unknown as R;
205
214
  return defineResult;
206
215
  }
@@ -247,7 +256,7 @@ export function lazy(
247
256
  typeof arg1 === 'function'
248
257
  ) && typeof (arg1 as { lazy?: unknown }).lazy === 'function';
249
258
  if (mayBeSource) {
250
- const source = arg1 as unknown as { lazy: LazyAbsorber };
259
+ const source = arg1 as { lazy: LazyAbsorber };
251
260
  const sourceLazyResult = source.lazy(
252
261
  arg2 as string | (() => IDEF<object>),
253
262
  arg3 as (() => IDEF<object>) | constructorOptions,
@@ -313,14 +322,16 @@ const $run = function <E extends object, T extends object, S extends Proto<E, T>
313
322
  // debugger;
314
323
  // @ts-expect-error - extracting TypeName from function
315
324
  const { TypeName } = Ctor;
325
+ // the returned SubTypeProxy is a plain function at runtime — constructable —
326
+ // so TypeConstructorBase (the named minimal constructor shape) is its
327
+ // honest static type here
316
328
  const Cstr = prepareSubtypeForConstruction(
317
329
  TypeName,
318
330
  entity
319
- ) as unknown as { new(...ars: unknown[]): unknown };
331
+ ) as TypeConstructorBase;
320
332
  // TODO: check lines below and if Constructor is not mnemonized ...
321
333
  if (Cstr === undefined) {
322
- const ErrorCtor = WRONG_MODIFICATION_PATTERN as unknown as new (msg: string) => Error;
323
- throw new ErrorCtor(`[ ${TypeName} ] is not defined as a Type Constructor on used instance`);
334
+ throw new WRONG_MODIFICATION_PATTERN(`[ ${TypeName} ] is not defined as a Type Constructor on used instance`);
324
335
  }
325
336
  const runResult = new Cstr(...args);
326
337
  // @ts-expect-error - returning result as merged proto type
@@ -338,7 +349,9 @@ export const apply = function <E extends object, T extends object, S extends Pro
338
349
  Ctor,
339
350
  args
340
351
  );
341
- const result = runResult as unknown as InstanceResult<Merge<E, T>>;
352
+ // S extends Proto<E, T>, which is the same merged entity+ctor shape
353
+ // apply/call/bind promise — the named public result type
354
+ const result = runResult as InstanceResult<Merge<E, T>>;
342
355
  return result;
343
356
  };
344
357
 
@@ -353,7 +366,8 @@ export const call = function <E extends object, T extends object, S extends Prot
353
366
  Ctor,
354
367
  args
355
368
  );
356
- const result = runResult as unknown as InstanceResult<Merge<E, T>>;
369
+ // same merge narrowing as apply() above
370
+ const result = runResult as InstanceResult<Merge<E, T>>;
357
371
  return result;
358
372
  };
359
373
 
@@ -368,7 +382,8 @@ export const bind = function <E extends object, T extends object, S extends Prot
368
382
  Ctor,
369
383
  args
370
384
  );
371
- const typedResult = runResult as unknown as InstanceResult<Merge<E, T>>;
385
+ // same merge narrowing as apply() above
386
+ const typedResult = runResult as InstanceResult<Merge<E, T>>;
372
387
  return typedResult;
373
388
  };
374
389
  return result;
@@ -384,8 +399,11 @@ export const decorate = function <
384
399
  ? target as constructorOptions
385
400
  : config;
386
401
 
402
+ // decorate(SomeType, config?) expects a constructor already carrying
403
+ // .define (a previously defined type) — declared on the value so the
404
+ // decorator body below needs no cast
387
405
  const parentType = (target instanceof Function)
388
- ? target as Constructor<object>
406
+ ? target as Constructor<object> & { define: TypeAbsorber }
389
407
  : undefined;
390
408
 
391
409
  const decorator = function <U extends Constructor<object>>(cstr: U): DecoratedClass<U> {
@@ -395,16 +413,17 @@ export const decorate = function <
395
413
  name,
396
414
  cstr as IDEF<object>,
397
415
  opts
416
+ // decorator contract: define() returns the constructor that
417
+ // wraps cstr; the decorator replaces the class binding with
418
+ // it, so the result is presented as DecoratedClass<U>
398
419
  ) as unknown as DecoratedClass<U>;
399
420
  return decoratorResult;
400
421
  }
401
- const parent = parentType as unknown as {
402
- define: TypeAbsorber;
403
- };
404
- const defineResult = parent.define(
422
+ const defineResult = parentType.define(
405
423
  name,
406
424
  cstr as IDEF<object>,
407
425
  opts
426
+ // same decorator contract as the branch above
408
427
  ) as unknown as DecoratedClass<U>;
409
428
  return defineResult;
410
429
  };
@@ -558,16 +558,85 @@ export type Extracted<T extends object> = {
558
558
  // It is a one-level snapshot of the instance's prototype chain.
559
559
  // `props` contains the instance's enumerable user properties;
560
560
  // `joint` contains enumerable properties copied from the immediate prototype;
561
- // `parent` is the next link up the chain (currently not recursively parsed).
561
+ // `parent` is the parent INSTANCE — the same object utils.parent(instance)
562
+ // returns; null for no parent. Not recursively parsed — walking the whole
563
+ // lineage level by level is what utils.deepParse does — this function stays
564
+ // the one-level primitive.
565
+ // The three "no parent" readings, stated once:
566
+ // parent == null — no parent at all (covers both below);
567
+ // parent === null — the end of a REAL chain (a root instance);
568
+ // parent === undefined — nothing was given (utils.parse(null)).
562
569
  export type Parsed<T extends object> = {
563
570
  name: string;
564
571
  props: Extracted<T>;
565
572
  self: T;
566
573
  proto: object;
567
574
  joint: Record<string, unknown>;
568
- parent: object | undefined;
575
+ parent: object | null;
569
576
  };
570
577
 
578
+ // EmptyParsed: the shape utils.parse(null) returns — the one non-object
579
+ // input parse accepts. "Nothing was given": every field is its empty value,
580
+ // and parent is undefined (see the readings above).
581
+ export interface EmptyParsed {
582
+ name: undefined;
583
+ props: {};
584
+ self: null;
585
+ proto: undefined;
586
+ joint: {};
587
+ parent: undefined;
588
+ }
589
+
590
+ // --- lineage (the lethe cross-language export) -----------------------------
591
+
592
+ // A JSON-safe value in the lethe lineage graph: instances export as $ref,
593
+ // non-JSON values as tagged placeholders — never an error.
594
+ export type LineageValue =
595
+ | null
596
+ | boolean
597
+ | string
598
+ | number
599
+ | LineageValue[]
600
+ | { $ref: string }
601
+ | { '$mnemonica': 'unsupported'; kind: string }
602
+ | { [ key: string ]: LineageValue };
603
+
604
+ // Where a level's type was DECLARED — not just its name (names collide
605
+ // across levels and collections).
606
+ export interface LineageTypeRef {
607
+ collection: string;
608
+ path: string;
609
+ }
610
+
611
+ export interface LineageNode {
612
+ type: LineageTypeRef;
613
+ // the fields this level set itself — shadowed values stay with their
614
+ // writer
615
+ own: { [ key: string ]: LineageValue };
616
+ // the parent's id, null at the root
617
+ parent: string | null;
618
+ // construction args — present only when lineage() gets { args: true }
619
+ args?: LineageValue;
620
+ // opt-in metadata (e.g. __timestamp__) — present only when
621
+ // lineage() gets { props: [...] }
622
+ props?: { [ key: string ]: LineageValue };
623
+ }
624
+
625
+ // The lethe lineage graph: version "1", heads in argument order, every
626
+ // reachable instance deduplicated at any depth.
627
+ export interface LineageGraph {
628
+ version: '1';
629
+ heads: string[];
630
+ nodes: { [ id: string ]: LineageNode };
631
+ }
632
+
633
+ export interface LineageOptions {
634
+ /** include construction args as node.args */
635
+ args?: boolean;
636
+ /** opt-in getProps keys exported as node.props (e.g. [ '__timestamp__' ]) */
637
+ props?: string[];
638
+ }
639
+
571
640
  // Sibling type accessor
572
641
  export interface SiblingAccessor {
573
642
  (SiblingTypeName: string): TypeClass | undefined;
@@ -969,7 +1038,10 @@ export interface UtilsCollection {
969
1038
  ...args: unknown[]
970
1039
  ): InstanceResult<Merge<B, A>>;
971
1040
  parse<T extends object>(self: T): Parsed<T>;
972
- parent<T extends object>(instance: T): object | undefined;
1041
+ parse(self: null): EmptyParsed;
1042
+ deepParse<T extends object>(instance: T): Array<Parsed<T>>;
1043
+ lineage(instances: object[], options?: LineageOptions): LineageGraph;
1044
+ parent<T extends object>(instance: T): object | null;
973
1045
  parent<T extends object, K extends ParentPathOfInstance<T> & string>(
974
1046
  instance: T,
975
1047
  path: K