mnemonica 1.4.8 → 1.5.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.
Files changed (41) hide show
  1. package/FOR_HUMANS.md +95 -31
  2. package/README.md +10 -9
  3. package/SKILL.md +4 -4
  4. package/build/api/hooks/hookTypes.d.ts +2 -0
  5. package/build/api/hooks/hookTypes.js +25 -0
  6. package/build/api/hooks/index.d.ts +2 -1
  7. package/build/api/hooks/index.js +6 -2
  8. package/build/api/hooks/registerHook.d.ts +1 -1
  9. package/build/api/hooks/registerHook.js +4 -15
  10. package/build/api/hooks/unregisterHook.d.ts +2 -0
  11. package/build/api/hooks/unregisterHook.js +18 -0
  12. package/build/api/index.d.ts +4 -3
  13. package/build/api/index.js +2 -1
  14. package/build/api/types/compileNewModificatorFunctionBody.d.ts +4 -2
  15. package/build/api/types/compileNewModificatorFunctionBody.js +16 -7
  16. package/build/api/types/index.d.ts +2 -2
  17. package/build/api/types/index.js +21 -18
  18. package/build/api/utils/index.d.ts +1 -2
  19. package/build/api/utils/index.js +37 -13
  20. package/build/descriptors/types/index.js +19 -12
  21. package/build/index.d.ts +25 -17
  22. package/build/index.js +35 -50
  23. package/build/types/index.d.ts +242 -225
  24. package/build/types/index.js +1 -1
  25. package/docs/UTILS.md +4 -5
  26. package/docs/async-constructors.md +32 -13
  27. package/docs/hott-correspondence.md +1 -1
  28. package/docs/typed-lookup.md +31 -37
  29. package/module/index.js +2 -0
  30. package/package.json +2 -2
  31. package/src/api/hooks/hookTypes.ts +37 -0
  32. package/src/api/hooks/index.ts +8 -1
  33. package/src/api/hooks/registerHook.ts +6 -19
  34. package/src/api/hooks/unregisterHook.ts +36 -0
  35. package/src/api/index.ts +2 -0
  36. package/src/api/types/compileNewModificatorFunctionBody.ts +79 -18
  37. package/src/api/types/index.ts +64 -54
  38. package/src/api/utils/index.ts +5 -51
  39. package/src/descriptors/types/index.ts +31 -22
  40. package/src/index.ts +271 -161
  41. package/src/types/index.ts +812 -590
@@ -18,22 +18,18 @@ TypeScript, however, cannot see a type graph built by runtime calls. There are
18
18
  > `lookup()` typed. Reach for Tactica when you need `@decorate()`, or when a
19
19
  > large codebase already uses free `define()` calls everywhere.
20
20
  >
21
- > **The third thing only Tactica solves — async-vs-sync detection.** An async
22
- > constructor returns a Promise at runtime, but `new` is typed as the finished
23
- > instance on BOTH builder and free-define paths, and neither TypeScript's
24
- > checks nor the runtime can see the difference (an async class constructor
25
- > returning a Promise is invisible to both). Only an AST reader sees it:
26
- > Tactica detects `async function`/async-class handlers from the source and
27
- > can type `new` as `Promise<X>` (see [`async-constructors.md`](./async-constructors.md)).
28
- > Together with `@decorate()` and declaration merging, this is the third
29
- > capability the builder pattern fundamentally cannot provide.
21
+ > **Async handlers.** An `async function` handler makes `new` a Promise at
22
+ > runtime. The constructor `define()` returns, lookups and instance-carried
23
+ > subtype constructors type it as one (`AsyncRegistryEntry` in the registry),
24
+ > and so do Tactica's registry entries
25
+ > (see [`async-constructors.md`](./async-constructors.md#typescript)).
30
26
 
31
27
  ---
32
28
 
33
29
  ## Every `define()` lands in the same collection
34
30
 
35
31
  All of these call the **same function** and register into the same runtime
36
- collection (`defaultTypes`, unless you pass another source explicitly):
32
+ collection (`defaultTypes`, unless called on another collection):
37
33
 
38
34
  ```typescript
39
35
  import { mnemonica, define, defaultTypes } from 'mnemonica';
@@ -233,10 +229,10 @@ errors in each form.
233
229
  `bind( entity, Ctor )` use the constructor's exact required, optional, and
234
230
  rest parameters.
235
231
 
236
- The legacy `define( fn, config )` form keeps the open `unknown[]` signature:
237
- the config occupies the second argument instead of a typed handler position,
238
- so the call resolves through the legacy `R` overload. Use
239
- `define( 'Name', fn, config )` when constructor argument checking is required.
232
+ `define( fn, config )` and `define( class, config )`, where the name is the
233
+ function's or class's own, keep the fields and arguments too. TypeScript sees
234
+ that name as `string`, so the type is not added to the local registry: to look
235
+ it up typed, give the name explicitly, `define( 'Name', fn, config )`.
240
236
 
241
237
  ---
242
238
 
@@ -433,37 +429,37 @@ Caveats:
433
429
 
434
430
  ---
435
431
 
436
- ## Explicit source: `lookup(source, path)` and `define(source, name, handler)`
432
+ ## Holding a builder value: use its own methods
437
433
 
438
- The free `lookup()` resolves against the global `TypeRegistry`. The free
439
- `define()` resolves against the default collection. When you hold a builder
440
- value and want the free-function style anyway, pass it as the first argument —
441
- the registry is then inferred from the source, not from the global interface:
434
+ The free `lookup()` resolves against the global `TypeRegistry`; the free
435
+ `define()` and `lazy()` define into their `this` — the default collection for
436
+ a plain call. When you hold a builder value, call its own methods: the
437
+ registry travels in the value's type.
442
438
 
443
439
  ```typescript
444
- import { lookup, define, lazy } from 'mnemonica';
445
-
446
440
  // typed from App's registry, never a silent `TypeClass | undefined`
447
- const Admin = lookup(App, 'User.Admin');
441
+ const Admin = App.lookup('User.Admin');
448
442
 
449
- // same semantics as User.define('Guest', ...) — a subtype of User
450
- const Guest = define(User, 'Guest', function (this: GuestShape, data: { token: string }) {
443
+ // a subtype of User
444
+ const Guest = User.define('Guest', function (this: GuestShape, data: { token: string }) {
451
445
  this.token = data.token;
452
446
  });
453
447
 
454
- // same semantics as collection.define('NewRoot', ...) — a root type
455
- const NewRoot = define(AppCollection, 'NewRoot', function (this: NewRootShape) { /* ... */ });
448
+ // a root type of the collection
449
+ const NewRoot = AppCollection.define('NewRoot', function (this: NewRootShape) { /* ... */ });
456
450
 
457
- // lazy variants infer the registry from the source as well
458
- const LazyGuest = lazy(User, 'Guest', () => function (this: GuestShape, data: { token: string }) {
451
+ // a lazy subtype of User
452
+ const LazyGuest = User.lazy('Guest', () => function (this: GuestShape, data: { token: string }) {
459
453
  this.token = data.token;
460
454
  });
461
455
  ```
462
456
 
463
- Semantics follow the source object: a **collection** source defines a root
464
- type, a **constructor** source defines a subtype. `lookup(source, path)`
465
- resolves exactly like `source.lookup(path)` — relative first, root fallback.
466
- The same source inference applies to `lazy(source, name, getter, config?)`.
457
+ A **collection** defines a root type, a **constructor** defines a subtype;
458
+ `lookup(path)` on a constructor resolves relative first, then from the root.
459
+ At runtime the free functions reach the same place through `this`:
460
+ `define.call(AppCollection, 'NewRoot', handler)` and
461
+ `lookup.call(App, 'User.Admin')` behave like the methods, typed as the free
462
+ functions (the global `TypeRegistry`).
467
463
 
468
464
  ---
469
465
 
@@ -621,7 +617,6 @@ Adding Tactica (or a bridge) to a project that already uses the builder API does
621
617
  |---|---|---|
622
618
  | `const App = mnemonica.define(...)` | Builder registry | The returned object carries its own type map. |
623
619
  | `App.lookup('User')` | Builder registry | `lookup()` is a method on the builder object. |
624
- | `lookup(App, 'User')` | Builder registry | The source argument carries the registry. |
625
620
  | `new user.Admin(...)` | Builder registry | Subtypes are resolved from the instance's inferred chain type. |
626
621
  | `define('User', ...)` free import | `TypeRegistry` augmentation | The free export has no local registry, so it relies on the global interface. |
627
622
  | `lookup('User')` free import | `TypeRegistry` augmentation | Same as above — populated by Tactica, hand-written, or the `RegistryOf` bridge. |
@@ -693,8 +688,8 @@ The split is a consequence of TypeScript's design, not mnemonica's. You cannot h
693
688
  2. Free function calls.
694
689
  3. Decorated classes.
695
690
 
696
- So mnemonica exposes the builder API for case 1, the bridge and two-arg
697
- overloads to connect cases 1 and 2, and the augmented API for cases 2 and 3.
691
+ So mnemonica exposes the builder API for case 1, the bridge to connect
692
+ cases 1 and 2, and the augmented API for cases 2 and 3.
698
693
  The runtime is the same everywhere; only the way TypeScript discovers the
699
694
  types differs.
700
695
 
@@ -783,7 +778,6 @@ regenerate after changing `define()` calls shows up as
783
778
  |---|---|---|
784
779
  | Get a typed constructor (builder mode) | `const T = App.lookup('T')` | `import { T } from './models/T'` + cast |
785
780
  | Get a typed constructor (augmented mode) | `const T = lookup('T')` | `import { T } from './models/T'` + cast |
786
- | Get a typed constructor from a builder value | `lookup(App, 'T')` | `lookup('T') as any` |
787
781
  | Create an instance | `new T({ ... })` | `new T({ ... }) as unknown as TShape` |
788
782
  | Chain to a child type | `new instance.Child({ ... })` | `new (instance as any).Child({ ... })` |
789
783
  | Type free `lookup()` without tactica | one-line `RegistryOf` bridge | a second registry file kept in sync by hand |
@@ -802,5 +796,5 @@ taken a wrong turn. Stop. Use `lookup`. Trust the registry.
802
796
  - **Default:** builder mode — `mnemonica.define(...)` or `createTypesCollection()`, `.lookup()` on the result. No tooling.
803
797
  - **Multiple files:** thread the chain through exports; the registry type travels with the value.
804
798
  - **Want free `lookup()` typed:** add the one-line `RegistryOf` bridge in a `registry.ts`.
805
- - **Mixing styles:** `lookup(source, path)` / `define(source, name, handler)` infer the registry from the source value.
799
+ - **Holding a builder value:** call its own methods — `App.lookup(path)`, `User.define(name, handler)`; the registry travels in its type.
806
800
  - **Need `@decorate()` typed:** use Tactica — it is the only path, and the reason is a TypeScript limitation, not a missing feature.
package/module/index.js CHANGED
@@ -24,12 +24,14 @@ const m = mnemonicaModule;
24
24
  // the ESM namespace object causes `checkThis()` to return false and then `this ||
25
25
  // defaultTypes` picks the namespace object (which has `.define` pointing back).
26
26
  export const define = m.define.bind(undefined);
27
+ export const lazy = m.lazy.bind(undefined);
27
28
  export const lookup = m.lookup.bind(undefined);
28
29
  export const apply = m.apply.bind(undefined);
29
30
  export const call = m.call.bind(undefined);
30
31
  export const bind = m.bind.bind(undefined);
31
32
  export const decorate = m.decorate.bind(undefined);
32
33
  export const registerHook = m.registerHook.bind(undefined);
34
+ export const unregisterHook = m.unregisterHook.bind(undefined);
33
35
 
34
36
  export const mnemonica = m.mnemonica;
35
37
  export const utils = m.utils;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mnemonica",
3
- "version": "1.4.8",
3
+ "version": "1.5.0",
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",
@@ -62,7 +62,7 @@
62
62
  "lint:fix": "npm run lint:src && npm run lint:test",
63
63
  "pretest": "npm run decorate:ts",
64
64
  "test": "mocha --allow-uncaught --enable-source-maps test/index.js",
65
- "test:cov": "npm run build:all && nyc --reporter=text-summary --reporter=lcov mocha --allow-uncaught --enable-source-maps --ui bdd --reporter spec ./test/index.js",
65
+ "test:cov": "npm run build:all && nyc --check-coverage --statements 100 --branches 100 --functions 100 --lines 100 --reporter=text-summary --reporter=lcov mocha --allow-uncaught --enable-source-maps --ui bdd --reporter spec ./test/index.js",
66
66
  "debug": "npx tsc --pretty --project tsconfig.json && npx mocha --allow-uncaught --enable-source-maps --reporter spec --inspect-brk test/index",
67
67
  "test:jest": "npx jest",
68
68
  "test:async_init": "mocha --allow-uncaught test_async/index.js",
@@ -0,0 +1,37 @@
1
+ 'use strict';
2
+
3
+ import type { hooksTypes } from '../../types';
4
+
5
+ import { ErrorsTypes } from '../../descriptors/errors';
6
+ const {
7
+ WRONG_HOOK_TYPE,
8
+ MISSING_HOOK_CALLBACK,
9
+ } = ErrorsTypes;
10
+
11
+ // the full names and their short forms; a Map, so that no inherited
12
+ // property name passes for a hook name
13
+ const hookTypes = new Map<string, hooksTypes>( [
14
+ [ 'preCreation', 'preCreation' ],
15
+ [ 'postCreation', 'postCreation' ],
16
+ [ 'creationError', 'creationError' ],
17
+ [ 'pre', 'preCreation' ],
18
+ [ 'post', 'postCreation' ],
19
+ [ 'error', 'creationError' ],
20
+ ] );
21
+
22
+ // The checks registerHook and unregisterHook share: which hook type the given
23
+ // name means, and that there is a callback.
24
+ export const resolveHookType = function ( name: string, cb: unknown ): hooksTypes {
25
+
26
+ const hookType = hookTypes.get( name );
27
+
28
+ if ( hookType === undefined ) {
29
+ throw new WRONG_HOOK_TYPE;
30
+ }
31
+
32
+ if ( typeof cb !== 'function' ) {
33
+ throw new MISSING_HOOK_CALLBACK;
34
+ }
35
+
36
+ return hookType;
37
+ };
@@ -1,6 +1,13 @@
1
1
  'use strict';
2
2
 
3
3
  export { invokeHook } from './invokeHook';
4
- export { registerHook } from './registerHook';
4
+ export {
5
+ registerHook,
6
+ registerHook as on
7
+ } from './registerHook';
8
+ export {
9
+ unregisterHook,
10
+ unregisterHook as off
11
+ } from './unregisterHook';
5
12
  export { registerFlowChecker } from './flowCheckers';
6
13
 
@@ -4,27 +4,14 @@ import type {
4
4
  Hookable, hook
5
5
  } from '../../types';
6
6
 
7
- import { ErrorsTypes } from '../../descriptors/errors';
8
- const {
9
- WRONG_HOOK_TYPE,
10
- MISSING_HOOK_CALLBACK,
11
- } = ErrorsTypes;
7
+ import { resolveHookType } from './hookTypes';
12
8
 
13
- const hooksTypes = [
14
- 'preCreation',
15
- 'postCreation',
16
- 'creationError',
17
- ];
9
+ export const registerHook = function ( this: Hookable, name: string, cb: hook ) {
18
10
 
19
- export const registerHook = function ( this: Hookable, hookType: string, cb: hook ) {
20
-
21
- if ( !hooksTypes.includes( hookType ) ) {
22
- throw new WRONG_HOOK_TYPE;
23
- }
24
-
25
- if ( typeof cb !== 'function' ) {
26
- throw new MISSING_HOOK_CALLBACK;
27
- }
11
+ const hookType = resolveHookType(
12
+ name,
13
+ cb
14
+ );
28
15
 
29
16
  if ( !this.hooks[ hookType ] ) {
30
17
  this.hooks[ hookType ] = new Set( [ cb ] );
@@ -0,0 +1,36 @@
1
+ 'use strict';
2
+
3
+ import type {
4
+ Hookable, hook
5
+ } from '../../types';
6
+
7
+ import { resolveHookType } from './hookTypes';
8
+
9
+ // true when the callback was registered; an unknown callback is not an error.
10
+ // The exact callback is removed: a Set holds it by reference.
11
+ export const unregisterHook = function ( this: Hookable, name: string, cb: hook ): boolean {
12
+
13
+ const hookType = resolveHookType(
14
+ name,
15
+ cb
16
+ );
17
+
18
+ const callbacks = this.hooks[ hookType ];
19
+ if ( callbacks === undefined ) {
20
+ return false;
21
+ }
22
+
23
+ const removed = callbacks.delete( cb );
24
+
25
+ // the last one out: an empty entry would still run the flow checker
26
+ // on every construction (see invokeHook)
27
+ if ( callbacks.size === 0 ) {
28
+ Reflect.deleteProperty(
29
+ this.hooks,
30
+ hookType
31
+ );
32
+ }
33
+
34
+ return removed;
35
+
36
+ };
package/src/api/index.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  import {
4
4
  invokeHook,
5
5
  registerHook,
6
+ unregisterHook,
6
7
  registerFlowChecker,
7
8
  } from './hooks';
8
9
  import {
@@ -16,6 +17,7 @@ export * as errors from './errors';
16
17
  export const hooks = {
17
18
  invokeHook,
18
19
  registerHook,
20
+ unregisterHook,
19
21
  registerFlowChecker,
20
22
  };
21
23
 
@@ -2,6 +2,7 @@
2
2
 
3
3
  import { hop } from '../../utils/hop';
4
4
  import { ErrorsTypes } from '../../descriptors/errors';
5
+ import type { MnemonicaConstructor } from '../../types';
5
6
 
6
7
  const { WRONG_MODIFICATION_PATTERN, } = ErrorsTypes;
7
8
  /*
@@ -95,6 +96,58 @@ export function classifyConstructHandler (
95
96
  }
96
97
  }
97
98
 
99
+ // const isClass = ( functionPointer: CallableFunction ) => {
100
+ // const value = Function.prototype.toString.call( functionPointer );
101
+ // return /^\s*class\s+/.test( value.trim() );
102
+ // };
103
+
104
+ // accordingly to the gist from here:
105
+ // https://gist.github.com/wentout/ea3afe9c822a6b6ef32f9e4f3e98b1ba
106
+ // a type predicate: the non-writable own prototype it checks is what
107
+ // makes the handler a class, so the class view (construct signature)
108
+ // of that same function value is named by this check, not by a cast
109
+ export const isClass = (fn: ConstructHandler): fn is ConstructHandler & ClassConstructHandler => {
110
+
111
+ /*
112
+ const str = String(fn);
113
+ const result = str.indexOf('class ') === 0;
114
+ return result;
115
+
116
+
117
+ // not necessary to check fn for typeof
118
+ // because of other checks made before
119
+ // if (typeof fn !== 'function') {
120
+ // return false;
121
+ // }
122
+
123
+ // seemingly
124
+ // class prototype is always object
125
+ if (!(fn.prototype instanceof Object)) {
126
+ return false;
127
+ }
128
+ // but only if not augmented
129
+
130
+ // class prototype.constructor cannot be re-defined (usually)
131
+ // but for functions user may re-assign it easily
132
+ // just assigning the way .prototype = {}
133
+ // and they 99.9% do this, cause nobody cares
134
+ // but we are checking if this is class, so it works ...
135
+ if (fn.prototype.constructor !== fn) {
136
+ return false;
137
+ }
138
+
139
+ // and the most unknown thing is that,
140
+ // cause for functions it it writeable )))
141
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
142
+ return Reflect.getOwnPropertyDescriptor(fn, 'prototype')!.writable === false;
143
+
144
+ */
145
+
146
+ const protoDesc = Reflect.getOwnPropertyDescriptor(fn, 'prototype');
147
+ const result = protoDesc !== undefined && protoDesc.writable === false;
148
+ return result;
149
+ };
150
+
98
151
  const getClassConstructor = (
99
152
  ConstructHandler: ClassConstructHandler,
100
153
  CreationHandler: CreationHandler,
@@ -112,7 +165,10 @@ const getClassConstructor = (
112
165
  return castResult;
113
166
  }
114
167
  };
115
- return result;
168
+ // the class as the pipeline uses it: the SymbolConstructorName mark
169
+ // it lacks here is attached by the compiler right after
170
+ const newableResult = result as MnemonicaConstructor;
171
+ return newableResult;
116
172
  };
117
173
 
118
174
  const getFunctionConstructor = (
@@ -157,46 +213,51 @@ const getFunctionConstructor = (
157
213
  }
158
214
  const result = CreationHandler.call(
159
215
  this,
160
- answer
216
+ answer
161
217
  );
162
218
  return result;
163
219
  };
164
- return funcResult;
220
+ // the compiled body is invoked with `new` by the pipeline;
221
+ // a function expression carries no construct signature, so
222
+ // the `new`-able view of the same value is named here
223
+ const newableResult = funcResult as FunctionModificationBody;
224
+ return newableResult;
165
225
  };
166
226
 
167
- type ModificationBody = new (...args: unknown[]) => object;
227
+ // the function-branch body: the plain function above, as the pipeline
228
+ // uses it — invoked with `new`, constructing an object
229
+ interface FunctionModificationBody extends MnemonicaConstructor {
230
+ (this: object, ...args: unknown[]): unknown;
231
+ }
168
232
 
169
- const compileNewModificatorFunctionBody = function ( FunctionName: string, asClass = false ) {
233
+ // what both branches produce and every caller stores: only ever invoked
234
+ // with `new` (a class body cannot be called without it)
235
+ type ModificationBody = MnemonicaConstructor;
236
+
237
+ const compileNewModificatorFunctionBody = function ( FunctionName: string ) {
170
238
  const outerResult = function (
171
239
  ConstructHandler: ConstructHandler,
172
240
  CreationHandler: CreationHandler,
173
241
  SymbolConstructorName: symbol
174
242
  ): () => ModificationBody {
243
+ // decided once per handler, here, not per construction: the class
244
+ // view of the handler when isClass() proves it, undefined otherwise
245
+ const ClassHandler = isClass( ConstructHandler ) ? ConstructHandler : undefined;
175
246
  const innerResult = function (): ModificationBody {
176
247
  let ModificationBody: ModificationBody;
177
- if ( asClass ) {
178
- // this branch runs only when isClass() verified at define
179
- // time that the handler is a class — the cast names the class
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.
248
+ if ( ClassHandler !== undefined ) {
183
249
  ModificationBody = getClassConstructor(
184
- ConstructHandler as unknown as ClassConstructHandler,
250
+ ClassHandler,
185
251
  CreationHandler
186
252
  );
187
253
  } else {
188
254
  // const ReNamedConstructHandler = {} as unknown;
189
255
  // ReNamedConstructHandler[FunctionName] = ConstructHandler;
190
256
  // ModificationBody = getFunctionConstructor(ReNamedConstructHandler[FunctionName], CreationHandler);
191
- // the compiled body is invoked with `new` by the pipeline;
192
- // a function expression carries no construct signature, so
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.
196
257
  ModificationBody = getFunctionConstructor(
197
258
  ConstructHandler,
198
259
  CreationHandler
199
- ) as unknown as ModificationBody;
260
+ );
200
261
  }
201
262
  ModificationBody.prototype.constructor = ModificationBody;
202
263
  Object.defineProperty(