mnemonica 1.3.2 → 1.3.5

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.
@@ -248,26 +248,32 @@ const makeAwaiter = function ( this: InstanceCreatorContext, type: TypeDef, then
248
248
  self.inheritedInstance = (self.inheritedInstance as Promise<object>)
249
249
  .then( ( instance: unknown ) => {
250
250
 
251
- if ( typeof instance !== 'object' ) {
252
- if ( self.config.awaitReturn ) {
253
- const msg = `should inherit from ${type.TypeName}: ` +
254
- `seems async ${type.TypeName} has no return statement`;
251
+ // null has typeof 'object' in JS, but for the unchain decision it
252
+ // is a VALUE like any other non-object: with unchain:true it
253
+ // resolves as-is; with the default it takes the readable
254
+ // mnemonica error below — never the internal TypeError from
255
+ // reading `.constructor` of null
256
+ if ( typeof instance !== 'object' || instance === null ) {
257
+ if ( self.config.unchain ) {
258
+ return instance;
259
+ } else {
260
+ const msg = `async constructor ${type.TypeName} must \`return this\` ` +
261
+ `(it resolved to ${String( instance )})`;
255
262
  throw new WRONG_MODIFICATION_PATTERN(
256
263
  msg,
257
- self.stack
264
+ self.stack
258
265
  );
259
- } else {
260
- return instance;
261
266
  }
262
267
  }
263
268
 
264
- if ( instance === null || !( instance instanceof self.type ) ) {
265
-
269
+ if ( !( instance instanceof self.type ) ) {
270
+
266
271
  const icn = (instance as object).constructor.name;
267
- const msg = `should inherit from ${type.TypeName} but got ${icn}`;
272
+ const msg = `async constructor ${type.TypeName} must resolve to its own instance ` +
273
+ `(\`return this\`), got ${icn}`;
268
274
  throw new WRONG_MODIFICATION_PATTERN(
269
275
  msg,
270
- self.stack
276
+ self.stack
271
277
  );
272
278
  }
273
279
 
@@ -1,6 +1,9 @@
1
1
  'use strict';
2
2
 
3
3
  import { hop } from '../../utils/hop';
4
+ import { ErrorsTypes } from '../../descriptors/errors';
5
+
6
+ const { WRONG_MODIFICATION_PATTERN, } = ErrorsTypes;
4
7
  /*
5
8
 
6
9
  // it is not that easy
@@ -47,6 +50,37 @@ export interface CreationHandler extends CallableFunction {
47
50
  (this: object, answer: unknown): unknown;
48
51
  }
49
52
 
53
+ // Classify the construct handler ONCE at define time from two cheap
54
+ // facts only — constructor.name and own prototype — NO toString()
55
+ // (overhead, fragile under transpilers). Async forms are NOT
56
+ // separable beyond 'AsyncFunction' (async arrows and async methods
57
+ // take the async path, accepted by design); a sync Function without
58
+ // its own prototype is a sync arrow, a shorthand method or a bound
59
+ // function — the three are indistinguishable here and all are
60
+ // rejected with the readable error (the docs: write constructors as
61
+ // regular functions or classes).
62
+ export const classifyConstructHandler = ( FunctionName: string, ConstructHandler: ConstructHandler ) => {
63
+ const handlerKind = ConstructHandler.constructor.name;
64
+ const hasOwnPrototype = hop(
65
+ ConstructHandler,
66
+ 'prototype'
67
+ );
68
+
69
+ if (
70
+ handlerKind === 'GeneratorFunction' ||
71
+ handlerKind === 'AsyncGeneratorFunction'
72
+ ) {
73
+ const msg = `${FunctionName}: generator functions are not supported as a constructor`;
74
+ throw new WRONG_MODIFICATION_PATTERN( msg );
75
+ }
76
+
77
+ if ( handlerKind === 'Function' && !hasOwnPrototype ) {
78
+ const msg = `${FunctionName}: constructor must be a regular function or a class ` +
79
+ '(arrow functions, methods and bound functions are not supported)';
80
+ throw new WRONG_MODIFICATION_PATTERN( msg );
81
+ }
82
+ };
83
+
50
84
  const getClassConstructor = (
51
85
  ConstructHandler: ClassConstructHandler,
52
86
  CreationHandler: CreationHandler,
@@ -72,7 +72,10 @@ const {
72
72
  import * as hooksApi from '../hooks';
73
73
  import { TypeProxy } from './TypeProxy';
74
74
 
75
- import compileNewModificatorFunctionBody, { ConstructHandler } from './compileNewModificatorFunctionBody';
75
+ import compileNewModificatorFunctionBody, {
76
+ classifyConstructHandler,
77
+ ConstructHandler
78
+ } from './compileNewModificatorFunctionBody';
76
79
 
77
80
  import TypesUtils, { CreationHandler } from '../utils';
78
81
  const {
@@ -406,6 +409,18 @@ const createFromDirectHandler = function (
406
409
  (typeof handler.prototype === 'object')
407
410
  ) ? handler.prototype : getDefaultPrototype();
408
411
 
412
+ // reject the unsupported handler shapes (generators, sync arrows,
413
+ // shorthand methods, bound functions) BEFORE the type is created, so
414
+ // a rejected define leaves nothing registered. Skipped when the name
415
+ // is taken: the TypeDescriptor below throws the canonical
416
+ // ALREADY_DECLARED, which wins over the shape error
417
+ if ( !target.has( name ) ) {
418
+ classifyConstructHandler(
419
+ name,
420
+ handler as ConstructHandler
421
+ );
422
+ }
423
+
409
424
  const result = new TypeDescriptor(
410
425
  defineOrigin,
411
426
  target,
@@ -73,10 +73,12 @@ const defaultOptions = {
73
73
  },
74
74
 
75
75
  // await new Constructor()
76
- // must return value
76
+ // with unchain:false the construction must resolve to its instance;
77
+ // with unchain:true a non-object resolution DROPS the chain and that
78
+ // value is the result ("unchain on await")
77
79
  // optional ./issues/106
78
- get awaitReturn () {
79
- return true;
80
+ get unchain () {
81
+ return false;
80
82
  },
81
83
 
82
84
  } as Record<string, unknown>;
package/src/index.ts CHANGED
@@ -3,6 +3,7 @@
3
3
 
4
4
  import type {
5
5
  CreateTypesCollectionFunction,
6
+ CtorParameter,
6
7
  IDEF,
7
8
  hook,
8
9
  hooksTypes,
@@ -30,6 +31,7 @@ export const {
30
31
  } = TypesUtils;
31
32
 
32
33
  export type {
34
+ CtorParameter,
33
35
  IDEF,
34
36
  LazyDef,
35
37
  TypeConstructor,
@@ -290,7 +292,7 @@ export function lookup(
290
292
 
291
293
  const $run = function <E extends object, T extends object, S extends Proto<E, T>>(
292
294
  entity: E,
293
- Ctor: IDEF<T>,
295
+ Ctor: CtorParameter<T>,
294
296
  args: unknown[]
295
297
  ): {
296
298
  [key in keyof S]: S[key]
@@ -316,7 +318,7 @@ const $run = function <E extends object, T extends object, S extends Proto<E, T>
316
318
  // TODO: apply instance .to type .with arguments
317
319
  export const apply = function <E extends object, T extends object, S extends Proto<E, T>>(
318
320
  entity: E,
319
- Ctor: IDEF<T>,
321
+ Ctor: CtorParameter<T>,
320
322
  args: unknown[] = []
321
323
  ): InstanceResult<Merge<E, T>> {
322
324
  const runResult = $run<E, T, S>(
@@ -331,7 +333,7 @@ export const apply = function <E extends object, T extends object, S extends Pro
331
333
  // TODO: call type .by instance .with arguments
332
334
  export const call = function <E extends object, T extends object, S extends Proto<E, T>>(
333
335
  entity: E,
334
- Ctor: IDEF<T>,
336
+ Ctor: CtorParameter<T>,
335
337
  ...args: unknown[]
336
338
  ): InstanceResult<Merge<E, T>> {
337
339
  const runResult = $run<E, T, S>(
@@ -346,7 +348,7 @@ export const call = function <E extends object, T extends object, S extends Prot
346
348
  // TODO: bind type .with instance → (...args)
347
349
  export const bind = function <E extends object, T extends object, S extends Proto<E, T>>(
348
350
  entity: E,
349
- Ctor: IDEF<T>
351
+ Ctor: CtorParameter<T>
350
352
  ): (...args: unknown[]) => InstanceResult<Merge<E, T>> {
351
353
  const result = (...args: unknown[]) => {
352
354
  const runResult = $run<E, T, S>(
@@ -13,6 +13,14 @@ export type PropsType = Record<string, unknown>;
13
13
  // supply Args to get typed constructor params: IDEF<MyType, [string, number]>
14
14
  export type IDEF<T, Args extends unknown[] = unknown[]> = { new(): T } | { (this: T, ...args: Args): void };
15
15
 
16
+ // Construction-function parameter for the .call/.apply/.bind family:
17
+ // anything IDEF accepts PLUS any required-argument constructor shape.
18
+ // The never[] rest accepts every parameter list by contravariance (every
19
+ // parameter type is a supertype of never) while keeping the constructed
20
+ // result typed; unknown[] would reject required params under
21
+ // strictFunctionTypes.
22
+ export type CtorParameter<T> = IDEF<T> | { new (...args: never[]): T };
23
+
16
24
  // Lazy getter type - a zero-arg factory that returns a constructor.
17
25
  // Used by the explicit .lazy() API.
18
26
  export type LazyDef<T, Args extends unknown[] = unknown[]> = () => IDEF<T, Args>;
@@ -243,8 +251,10 @@ export type constructorOptions = {
243
251
  // during the process of instance creation
244
252
  submitStack?: boolean,
245
253
  // await new Constructor()
246
- // must return value
247
- awaitReturn?: boolean,
254
+ // with false (default) the construction must resolve to its instance;
255
+ // with true a non-object resolution DROPS the chain and that value is
256
+ // the result ("unchain on await")
257
+ unchain?: boolean,
248
258
  // Force class mode (auto-detected by default)
249
259
  asClass?: boolean,
250
260
  };
@@ -301,7 +311,9 @@ export type SubTypeConstructors<
301
311
  Path extends string
302
312
  > = {
303
313
  [K in keyof Registry as K extends `${Path}.${infer Child}` ? Child : never]:
304
- LookupResult<Registry, K & string>;
314
+ AugmentedConstructor<Registry, K & string, true> & {
315
+ lookup: NestedTypeLookup<Registry, K & string>;
316
+ };
305
317
  };
306
318
 
307
319
  // Reconstruct a constructor with a new instance type while preserving every
@@ -314,17 +326,26 @@ export type SubTypeConstructors<
314
326
  // re-added only when the source constructor carries one.
315
327
  export type ReplaceConstructorInstance<
316
328
  C,
317
- NewInstance extends object
329
+ NewInstance extends object,
330
+ CallConstructs extends boolean = false
318
331
  > = C extends {
319
332
  new (...args: infer A): unknown;
320
333
  }
321
334
  ? {
322
335
  new (...args: A): NewInstance;
323
336
  readonly prototype: NewInstance & {
324
- readonly constructor: ReplaceConstructorInstance<C, NewInstance>;
337
+ readonly constructor: ReplaceConstructorInstance<C, NewInstance, CallConstructs>;
325
338
  };
326
339
  } & (C extends { (...args: infer A2): unknown }
327
- ? { (this: NewInstance, ...args: A2): NewInstance }
340
+ ? CallConstructs extends true
341
+ // SubTypeProxy-backed member: the call form constructs the child
342
+ // from the parent instance (the chain-tip form new R().A()), so
343
+ // no `this` demand — detached bare calls construct too.
344
+ ? { (...args: A2): NewInstance }
345
+ // Raw looked-up constructor: the `this` guard honestly models
346
+ // .call(childInstance, args); a bare call here is the decorator
347
+ // path at runtime, not construction.
348
+ : { (this: NewInstance, ...args: A2): NewInstance }
328
349
  : unknown)
329
350
  & Omit<C, 'prototype' | 'lookup'>
330
351
  : never;
@@ -344,10 +365,12 @@ export type WithSubTypes<
344
365
  // recursive reference from `SubTypeConstructors` resolves cleanly.
345
366
  export type AugmentedConstructor<
346
367
  Registry extends object,
347
- Path extends keyof Registry & string
368
+ Path extends keyof Registry & string,
369
+ CallConstructs extends boolean = false
348
370
  > = ReplaceConstructorInstance<
349
371
  Registry[Path],
350
- WithSubTypes<ExtractConstructorInstance<Registry[Path]>, Registry, Path>
372
+ WithSubTypes<ExtractConstructorInstance<Registry[Path]>, Registry, Path>,
373
+ CallConstructs
351
374
  >;
352
375
 
353
376
  // Result of a typed lookup: the augmented constructor plus a `lookup` method