mnemonica 1.2.1 → 1.2.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.
- package/FOR_HUMANS.md +186 -138
- package/README.md +70 -249
- package/build/api/errors/exceptionConstructor.js +20 -47
- package/build/api/errors/throwModificationError.js +26 -61
- package/build/api/types/InstanceCreator.js +5 -1
- package/build/api/types/Props.js +24 -10
- package/build/api/types/index.js +18 -12
- package/build/types/index.d.ts +9 -4
- package/build/types/index.js +1 -1
- package/docs/UTILS.md +97 -8
- package/docs/async-constructors.md +2 -0
- package/docs/decorate.md +1 -1
- package/docs/empathy-in-ai.md +20 -10
- package/docs/prototype-chain.md +8 -7
- package/docs/typed-lookup.md +195 -5
- package/docs/typeomatica.md +8 -345
- package/package.json +6 -10
- package/src/api/errors/exceptionConstructor.ts +40 -83
- package/src/api/errors/throwModificationError.ts +64 -104
- package/src/api/types/InstanceCreator.ts +14 -0
- package/src/api/types/Props.ts +53 -18
- package/src/api/types/index.ts +33 -20
- package/src/types/index.ts +15 -5
- package/.ai/AGENTS.md +0 -151
- package/.ai/ARCHITECT.md +0 -110
- package/.ai/DEBUG.md +0 -178
- package/.ai/ONBOARDING.md +0 -189
- package/.ai/PROTOTYPE-CHAIN.md +0 -153
- package/.ai/mode-ask.md +0 -121
- package/.ai/mode-orchestrator.md +0 -141
- package/.ai/performance-vs-security.md +0 -395
- package/.ai/rules-async-constructors.md +0 -352
- package/.ai/rules-code-style.md +0 -95
- package/.ai/rules-coding.md +0 -246
- package/.ai/rules-context-condensing.md +0 -50
- package/.ai/rules-contributing.md +0 -227
- package/.ai/rules-define-patterns.md +0 -159
- package/.ai/rules-ecosystem.md +0 -140
- package/.ai/rules-error-system.md +0 -56
- package/.ai/rules-hooks.md +0 -46
- package/.ai/rules-instance-methods.md +0 -93
- package/.ai/rules-philosophy.md +0 -231
- package/.ai/rules-reminders.md +0 -19
- package/.ai/rules-testing.md +0 -66
- package/.ai/rules-type-system.md +0 -124
- package/.ai/theory-of-operations.md +0 -224
- package/AGENTS.md +0 -345
- package/CONTRIBUTING.md +0 -150
- package/SKILL.md +0 -114
- package/docs/ai-learning-trajectory.md +0 -141
- package/docs/purpose.md +0 -707
- package/docs/tactica-deep-dive.md +0 -629
- package/docs/tactica-pattern.md +0 -146
package/FOR_HUMANS.md
CHANGED
|
@@ -36,7 +36,7 @@ define(name, ctor) → TypeProxy → new instance.SubType()
|
|
|
36
36
|
> Status API is stable for the documented surface: advanced topics are also covered
|
|
37
37
|
> If you're looking for the deeper theory (Homotopy Type Theory, runtime Tries, AI-agent pipelines), see [`README.md`](./README.md). This document is the welcoming entry — practical, example-driven, aimed at developers who want to use the library.
|
|
38
38
|
> **For type-safe `lookup()`:** read [`docs/typed-lookup.md`](./docs/typed-lookup.md) — the `TypeRegistry` augmentation pattern, hand-written or generated by [`@mnemonica/tactica`](https://www.npmjs.com/package/@mnemonica/tactica). Runtime behaviour is identical either way.
|
|
39
|
-
> [`SKILL.md`](
|
|
39
|
+
> [`SKILL.md`](https://github.com/wentout/mnemonica/blob/master/SKILL.md) is a usage quick reference only (not for contributors).
|
|
40
40
|
|
|
41
41
|
---
|
|
42
42
|
|
|
@@ -50,14 +50,15 @@ The key inversion: subtypes are instantiated *from parent instances*, not from c
|
|
|
50
50
|
|
|
51
51
|
**Why it matters:** in any system where data transformation order matters — HTTP pipelines, ETL flows, AI agent chains — the construction history *is* the business logic. mnemonica makes that history first-class.
|
|
52
52
|
|
|
53
|
-
### One runtime,
|
|
53
|
+
### One runtime, three type-system paths
|
|
54
54
|
|
|
55
|
-
Mnemonica has one runtime behavior, but TypeScript cannot see the type graph created by runtime `define()` calls. To solve this, there are
|
|
55
|
+
Mnemonica has one runtime behavior, but TypeScript cannot see the type graph created by runtime `define()` calls. To solve this, there are three compile-time paths:
|
|
56
56
|
|
|
57
57
|
1. **Builder mode** — chain `.define()` on the `mnemonica` object or on `createTypesCollection()`. The returned object carries a local type registry, so `.lookup()` is typed without any global augmentation.
|
|
58
|
-
2. **
|
|
58
|
+
2. **Registry bridge** — merge the builder's local registry into the global `TypeRegistry` with one hand-written line (`interface TypeRegistry extends RegistryOf<typeof App> {}`), so the free `lookup()` is typed too.
|
|
59
|
+
3. **Augmented mode** — use the free `define()` / `lookup()` exports and `@decorate()`, with the global `TypeRegistry` populated by `@mnemonica/tactica` or written by hand.
|
|
59
60
|
|
|
60
|
-
|
|
61
|
+
At runtime all paths are identical — the only difference is where TypeScript looks up the types. See [`docs/typed-lookup.md`](./docs/typed-lookup.md) for details.
|
|
61
62
|
|
|
62
63
|
---
|
|
63
64
|
|
|
@@ -83,7 +84,7 @@ Concrete benefits:
|
|
|
83
84
|
## A 30-second example
|
|
84
85
|
|
|
85
86
|
```javascript
|
|
86
|
-
const { define, getProps } = require('mnemonica');
|
|
87
|
+
const { define, getProps, utils } = require('mnemonica');
|
|
87
88
|
|
|
88
89
|
// Define a base type
|
|
89
90
|
const Person = define('Person', function (data) {
|
|
@@ -121,7 +122,7 @@ The key inversion: `new` is called on the **parent instance** (`alice`), not on
|
|
|
121
122
|
- **Looking for a specific function?** Jump to the [API Reference](#api-reference).
|
|
122
123
|
- **Curious about the theory?** Read [`README.md`](./README.md) — the HoTT framing, the Trie observation, the pipeline pattern, the AI-agent angle.
|
|
123
124
|
- **Want examples you can run?** See the [Examples](#examples) section below.
|
|
124
|
-
- **Going deeper on philosophy?** Read [
|
|
125
|
+
- **Going deeper on philosophy?** Read [`.ai/purpose.md`](https://github.com/wentout/mnemonica/blob/master/.ai/purpose.md).
|
|
125
126
|
- **Background reading:** [Inheritance in JavaScript: Factory of Constructors with Prototype Chain](https://github.com/mythographica/stash/blob/master/inheritance.md) · [Architecture of Prototype Inheritance in JavaScript](https://github.com/mythographica/stash/blob/master/inheritance_architecture.md) · [Dead Simple type checker for JavaScript](https://github.com/mythographica/typologica)
|
|
126
127
|
|
|
127
128
|
---
|
|
@@ -132,6 +133,7 @@ The key inversion: `new` is called on the **parent instance** (`alice`), not on
|
|
|
132
133
|
- [Quick Start](#quick-start)
|
|
133
134
|
- [For AI Agents](#for-ai-agents)
|
|
134
135
|
- [Core Concepts](#core-concepts)
|
|
136
|
+
- [Formal definitions](#formal-definitions)
|
|
135
137
|
- [Trie Observation](#trie-observation)
|
|
136
138
|
- [Pipeline Pattern](#pipeline-pattern)
|
|
137
139
|
- [TypeScript Support](#typescript-support)
|
|
@@ -221,23 +223,7 @@ import { define, lookup } from 'mnemonica/module';
|
|
|
221
223
|
|
|
222
224
|
## For AI Agents
|
|
223
225
|
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
| Change type | Read before starting |
|
|
227
|
-
|---|---|
|
|
228
|
-
| Any `src/` change | [`AGENTS.md`](./AGENTS.md) + [`.ai/ONBOARDING.md`](./.ai/ONBOARDING.md) |
|
|
229
|
-
| Involves `define()` / type graph | + [`.ai/rules-define-patterns.md`](./.ai/rules-define-patterns.md) |
|
|
230
|
-
| Involves hooks | + [`.ai/rules-hooks.md`](./.ai/rules-hooks.md) |
|
|
231
|
-
| Involves async constructors | + [`.ai/rules-async-constructors.md`](./.ai/rules-async-constructors.md) |
|
|
232
|
-
| Involves TypeScript types | + [`.ai/rules-type-system.md`](./.ai/rules-type-system.md) |
|
|
233
|
-
| Involves proxy internals | + [`.ai/PROTOTYPE-CHAIN.md`](./.ai/PROTOTYPE-CHAIN.md) |
|
|
234
|
-
| Uses tactica / `lookup` | + [`docs/tactica-deep-dive.md`](./docs/tactica-deep-dive.md) |
|
|
235
|
-
| Docs-only change | README section you're touching only |
|
|
236
|
-
| Unfamiliar with the codebase | [`.ai/ONBOARDING.md`](./.ai/ONBOARDING.md) first — one file, five minutes |
|
|
237
|
-
|
|
238
|
-
**`AGENTS.md` + `.ai/ONBOARDING.md` are the always-required baseline for any `src/` edit.** Everything else is opt-in by change type.
|
|
239
|
-
|
|
240
|
-
AI agent integration guidance (introspection patterns, type discovery, safe construction) lives in [`AGENTS.md`](AGENTS.md). It is kept separate from the user-facing API reference.
|
|
226
|
+
Contributors editing the library itself — human or AI — should read [`AGENTS.md`](https://github.com/wentout/mnemonica/blob/master/AGENTS.md). It is the canonical contributor guide and is not duplicated here.
|
|
241
227
|
|
|
242
228
|
---
|
|
243
229
|
|
|
@@ -245,7 +231,7 @@ AI agent integration guidance (introspection patterns, type discovery, safe cons
|
|
|
245
231
|
|
|
246
232
|
### Factory of Constructors
|
|
247
233
|
|
|
248
|
-
Define types using
|
|
234
|
+
Define types using constructor functions or classes:
|
|
249
235
|
|
|
250
236
|
```js
|
|
251
237
|
// Using a constructor function
|
|
@@ -253,26 +239,45 @@ const SomeType = define('SomeType', function (opts) {
|
|
|
253
239
|
Object.assign(this, opts);
|
|
254
240
|
});
|
|
255
241
|
|
|
256
|
-
//
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
};
|
|
261
|
-
AnotherTypeConstructor.prototype.description = 'SomeType Constructor';
|
|
262
|
-
return AnotherTypeConstructor;
|
|
242
|
+
// A named function as the only argument also works —
|
|
243
|
+
// the type name is taken from fn.name
|
|
244
|
+
const AnotherType = define(function AnotherType(opts) {
|
|
245
|
+
Object.assign(this, opts);
|
|
263
246
|
});
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
Note what does **not** work: passing an *anonymous* function as the first
|
|
250
|
+
argument. `define(() => { ... return MyClass; })` throws
|
|
251
|
+
`TYPENAME_MUST_BE_A_STRING` — there is no name to register the type under.
|
|
252
|
+
For the deferred / factory case, where the constructor must be resolved
|
|
253
|
+
through a getter (to break a circular dependency, or to defer constructor
|
|
254
|
+
selection), use `.lazy()`:
|
|
264
255
|
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
}
|
|
256
|
+
```js
|
|
257
|
+
// unnamed: the type name is taken from the returned constructor's .name
|
|
258
|
+
const ClassType = SomeType.lazy(() => class ClassType {
|
|
259
|
+
constructor(opts) {
|
|
260
|
+
Object.assign(this, opts);
|
|
271
261
|
}
|
|
272
|
-
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
// named: explicit type name
|
|
265
|
+
const GuestType = SomeType.lazy('GuestType', () => function (opts) {
|
|
266
|
+
Object.assign(this, opts);
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
// also available as a free export
|
|
270
|
+
const { lazy } = require('mnemonica');
|
|
271
|
+
const StandaloneType = lazy(() => function StandaloneType(opts) {
|
|
272
|
+
Object.assign(this, opts);
|
|
273
273
|
});
|
|
274
274
|
```
|
|
275
275
|
|
|
276
|
+
The resulting type behaves exactly like one created with `define()` — same
|
|
277
|
+
registry, same `.lookup()`, same subtype chaining. See
|
|
278
|
+
[`lazy(typeName?, getter, config?)`](#lazytypename-getter-config) in the API
|
|
279
|
+
reference.
|
|
280
|
+
|
|
276
281
|
### Nested Type Definition
|
|
277
282
|
|
|
278
283
|
```js
|
|
@@ -321,6 +326,27 @@ const extracted = extract(subInstance);
|
|
|
321
326
|
|
|
322
327
|
---
|
|
323
328
|
|
|
329
|
+
## Formal definitions
|
|
330
|
+
|
|
331
|
+
These terms are used throughout the codebase and documentation with precise meanings.
|
|
332
|
+
|
|
333
|
+
| Term | Definition |
|
|
334
|
+
|---|---|
|
|
335
|
+
| **Trie node** | A type definition created by `define()`. Has a name, a constructor handler, a prototype, and a Map of subtypes. |
|
|
336
|
+
| **Trie edge** | A parent-child relationship between two nodes. Created by `ParentType.define('ChildType', ...)`. |
|
|
337
|
+
| **Trie path** | A sequence of edges from the root to a specific node. `UserType → AdminType → SuperAdminType` is a path. |
|
|
338
|
+
| **Construction context** | The construction record stored per instance (9 internal props + `__self__` installed after construction): `__type__`, `__parent__`, `__args__`, `__timestamp__`, `__creator__`, `__collection__`, `__subtypes__`, `__proto_proto__`, `__stack__`, `__self__`. Readable via `getProps(instance)`. |
|
|
339
|
+
| **Instance-level inheritance** | The mechanism where `new alice.Employee()` creates a prototype chain whose immediate parent is the **specific instance** `alice`, not a shared `Employee.prototype`. |
|
|
340
|
+
| **Nominal type** | A type whose identity is determined by its constructor function reference, not by its property shape. Two types with identical fields but different constructors are different types. |
|
|
341
|
+
| **Mnemosyne** | The prototype object inserted between `ModificatorType.prototype` and the parent instance. Stores internal construction context. User-facing instance methods (`extract`, `pick`, `parent`, etc.) are available through standalone `utils.*` or by explicit prototype attachment. |
|
|
342
|
+
| **TypeProxy** | The constructor-like object returned by `define()`. Wraps the raw constructor with `.define()`, `.lazy()`, `.decorate()`, `.lookup()`, `.registerHook()` methods. |
|
|
343
|
+
| **ModificatorType** | The actual constructor function used for `new` calls. Its prototype is linked to Mnemosyne, which is linked to the parent instance. |
|
|
344
|
+
| **WeakMap key** | Internal properties are stored in a `WeakMap` keyed by the **Mnemosyne object**, not the instance itself. This keeps instance enumeration clean; a fresh Mnemosyne object is created per construction, so metadata is strictly per-instance. |
|
|
345
|
+
|
|
346
|
+
For the exact shape of the prototype chain, layer by layer, see [`.ai/PROTOTYPE-CHAIN.md`](https://github.com/wentout/mnemonica/blob/master/.ai/PROTOTYPE-CHAIN.md).
|
|
347
|
+
|
|
348
|
+
---
|
|
349
|
+
|
|
324
350
|
## Trie Observation
|
|
325
351
|
|
|
326
352
|
A Trie is a tree where each node is reached by a sequence of keys — you look up data by walking a path, not by hashing a key. The JavaScript prototype chain is exactly this structure: each `new` narrows the search space one step further.
|
|
@@ -378,15 +404,18 @@ const route = new req.RouteData(matchedRoute);
|
|
|
378
404
|
const page = new route.PageData(await route.handler(route));
|
|
379
405
|
const res = new page.ResponseData(200);
|
|
380
406
|
|
|
381
|
-
getProps(res).__parent__.__parent__.__parent__; // the original RequestData instance
|
|
407
|
+
getProps(getProps(getProps(res).__parent__).__parent__).__parent__; // the original RequestData instance
|
|
408
|
+
// (internal props live in a WeakMap, reachable via getProps() — each hop up the chain needs its own call)
|
|
382
409
|
```
|
|
383
410
|
|
|
384
411
|
At any point in the chain, the full history is available without any additional bookkeeping. Add a `preCreation` hook on `RouteData` to measure routing latency. Add a `postCreation` hook on `ResponseData` to log the full request/response pair including every intermediate state — all from a single callback:
|
|
385
412
|
|
|
386
413
|
```javascript
|
|
387
|
-
ResponseData.registerHook('postCreation', ({ type, existentInstance }) => {
|
|
388
|
-
|
|
389
|
-
|
|
414
|
+
ResponseData.registerHook('postCreation', ({ type, existentInstance, inheritedInstance }) => {
|
|
415
|
+
// existentInstance is the parent (the PageData instance) — two hops up to RequestData.
|
|
416
|
+
// Internal props live in a WeakMap, so each hop needs its own getProps() call.
|
|
417
|
+
const reqData = getProps(getProps(existentInstance).__parent__).__parent__;
|
|
418
|
+
log({ url: reqData.url, status: inheritedInstance.status });
|
|
390
419
|
});
|
|
391
420
|
```
|
|
392
421
|
|
|
@@ -432,7 +461,7 @@ The most commonly used types for TypeScript projects:
|
|
|
432
461
|
```typescript
|
|
433
462
|
import {
|
|
434
463
|
IDEF, // Base constructor function type
|
|
435
|
-
|
|
464
|
+
LazyDef, // Zero-arg getter returning a constructor (for lazy())
|
|
436
465
|
constructorOptions, // Type config options (strictChain, blockErrors, etc.)
|
|
437
466
|
hooksTypes, // 'preCreation' | 'postCreation' | 'creationError'
|
|
438
467
|
hook, // Hook callback type
|
|
@@ -440,7 +469,7 @@ import {
|
|
|
440
469
|
} from 'mnemonica';
|
|
441
470
|
```
|
|
442
471
|
|
|
443
|
-
Additional types available: `Constructor`, `
|
|
472
|
+
Additional types available: `Constructor`, `TypeConstructor`, `TypeConstructorBase`, `Proto`, `ProtoFlat`, `InstanceResult`, `Merge`, `IDefinitorInstance`, `DecoratedClass`, `hooksOpts`, `TypesCollection`, `TypeLookup`, `LookupResult`, `RegistryOf`, `MnemonicaModule`, `TypeAbsorber`, and the `TypeRegistry` interface (for augmentation). See [`src/types/index.ts`](./src/types/index.ts) for full definitions.
|
|
444
473
|
|
|
445
474
|
### Generic Type Patterns
|
|
446
475
|
|
|
@@ -518,7 +547,7 @@ const MyType = define('MyType', function (data) {
|
|
|
518
547
|
```
|
|
519
548
|
|
|
520
549
|
**Parameters:**
|
|
521
|
-
- `typeName` (string): Name of the type
|
|
550
|
+
- `typeName` (string): Name of the type. Must be non-empty, start with an uppercase letter, and must not be one of the reserved names `Mnemonica` or `Mnemosyne`. May be a nested path (`'Parent.Child'`) to define a subtype under an existing type. (Alternatively, pass a *named* function as the only argument — the name is then taken from `fn.name`; an anonymous first-argument function throws `TYPENAME_MUST_BE_A_STRING`.)
|
|
522
551
|
- `constructHandler` (Function): Constructor function
|
|
523
552
|
- `config` (object, optional): Configuration options
|
|
524
553
|
|
|
@@ -571,9 +600,10 @@ path is ignored — `lookup('A/B')`, `lookup('A:B')`, and `lookup(' A . B ')`
|
|
|
571
600
|
all resolve like `lookup('A.B')`. The same path forms work everywhere a
|
|
572
601
|
nested type path is accepted (`define()`, `utils.parent()`, hooks, etc.).
|
|
573
602
|
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
603
|
+
**Type-safe lookup.** Without a `TypeRegistry` augmentation, `lookup()`
|
|
604
|
+
returns `TypeClass | undefined`. With an augmentation — hand-written for
|
|
605
|
+
small projects or generated by [`@mnemonica/tactica`](https://www.npmjs.com/package/@mnemonica/tactica)
|
|
606
|
+
— augmented paths return properly typed constructors:
|
|
577
607
|
|
|
578
608
|
```typescript
|
|
579
609
|
import { lookup } from 'mnemonica';
|
|
@@ -592,7 +622,7 @@ To enable type safety, generate types with tactica:
|
|
|
592
622
|
npx tactica
|
|
593
623
|
```
|
|
594
624
|
|
|
595
|
-
Then include the generated types in your project. See [`docs/typed-lookup.md`](./docs/typed-lookup.md) for
|
|
625
|
+
Then include the generated types in your project. See [`docs/typed-lookup.md`](./docs/typed-lookup.md) for both paths side by side.
|
|
596
626
|
|
|
597
627
|
#### `apply(entity, Constructor, args?)`
|
|
598
628
|
|
|
@@ -660,20 +690,17 @@ For advanced TypeScript usage, the following types are exported from `mnemonica`
|
|
|
660
690
|
|------|-------------|-------|
|
|
661
691
|
| `IDEF<T>` | Base constructor function type | `define('Name', fn: IDEF<MyType>)` |
|
|
662
692
|
| `LazyDef<T>` | Zero-arg getter returning a constructor | `lazy('Name', fn: LazyDef<MyType>)` |
|
|
663
|
-
| `
|
|
693
|
+
| `TypeConstructor<T>` | Registry-stored constructor type | What an augmented `TypeRegistry` maps paths to |
|
|
664
694
|
| `TypeClass` | Base type constructor | `const MyType: TypeClass = define(...)` |
|
|
665
695
|
| `DecoratedClass<T>` | Decorated class type | `@decorate() class MyClass {}` (see [`docs/decorate.md`](./docs/decorate.md)) |
|
|
666
696
|
| `IDefinitorInstance<N, S>` | Constructor with subtypes | Returned by `define()` with `.define()` method |
|
|
667
|
-
| `ConstructorFunction<T>` | Constructor with prototype | Generic constructor function signature |
|
|
668
697
|
| `constructorOptions` | Configuration options | `{ strictChain: true, blockErrors: true }` |
|
|
669
698
|
| `hooksTypes` | Hook type literals | `'preCreation' \| 'postCreation' \| 'creationError'` |
|
|
670
699
|
| `hook` | Hook callback type | `(opts: hooksOpts) => void` |
|
|
671
700
|
| `hooksOpts` | Hook options object | Passed to hook callbacks |
|
|
672
|
-
| `
|
|
673
|
-
| `
|
|
674
|
-
| `
|
|
675
|
-
| `CallFunction` | call() function type | `call<E, T, S>(entity, Ctor, ...args) => S` |
|
|
676
|
-
| `BindFunction` | bind() function type | `bind<E, T, S>(entity, Ctor) => (...args) => S` |
|
|
701
|
+
| `TypesCollection` | Types collection interface | What `createTypesCollection()` returns |
|
|
702
|
+
| `RegistryOf<T>` | Registry extractor | The one-line bridge: `interface TypeRegistry extends RegistryOf<typeof App> {}` |
|
|
703
|
+
| `TypeRegistry` | Global registry interface | Augmented by hand, by the bridge, or by tactica |
|
|
677
704
|
|
|
678
705
|
These types enable complete type safety when defining and using mnemonica types in TypeScript projects.
|
|
679
706
|
|
|
@@ -792,7 +819,9 @@ console.log(props.__type__, props.__args__);
|
|
|
792
819
|
setProps(instance, { myFlag: true });
|
|
793
820
|
```
|
|
794
821
|
|
|
795
|
-
`setProps` only accepts non-reserved names: the internal `__…__` properties (`__type__`, `__args__`, `__timestamp__`, etc.) are filtered out and cannot be overwritten. Also note that `getProps` returns the *live* internal object when no custom properties are set — mutating the result mutates the instance's construction record. Once `setProps` has been used, `getProps` returns a merged copy instead.
|
|
822
|
+
`setProps` only accepts non-reserved names: the internal `__…__` properties (`__type__`, `__args__`, `__timestamp__`, etc.) are filtered out and cannot be overwritten. Repeated `setProps` calls accumulate: earlier values are kept, new values override per key. Also note that `getProps` returns the *live* internal object when no custom properties are set — mutating the result mutates the instance's construction record. Once `setProps` has been used, `getProps` returns a merged copy instead.
|
|
823
|
+
|
|
824
|
+
`setProps` also works on objects with no mnemonica record at all (plain objects, `Error` objects): a record keyed by the object itself is created on demand, and `getProps` finds it directly. This is how library errors carry their data. On primitives (`setProps(5, …)`) it returns `false`.
|
|
796
825
|
|
|
797
826
|
---
|
|
798
827
|
|
|
@@ -807,7 +836,7 @@ utils.extract(instance);
|
|
|
807
836
|
utils.pick(instance, 'key');
|
|
808
837
|
utils.parent(instance, 'ParentType');
|
|
809
838
|
utils.fork(instance)(newArgs);
|
|
810
|
-
utils.exception(instance, error);
|
|
839
|
+
new utils.exception(instance, error); // must be called with `new`
|
|
811
840
|
utils.sibling(instance);
|
|
812
841
|
utils.clone(instance);
|
|
813
842
|
```
|
|
@@ -895,13 +924,20 @@ const dagInstance = forkFn.call(instanceB, 'args');
|
|
|
895
924
|
|
|
896
925
|
#### `utils.exception(instance, error, ...args)`
|
|
897
926
|
|
|
898
|
-
Creates an exception instance from the given instance.
|
|
927
|
+
Creates an exception instance from the given instance. Must be called with
|
|
928
|
+
`new` (it throws `WRONG_INSTANCE_INVOCATION` otherwise).
|
|
899
929
|
|
|
900
930
|
```ts
|
|
901
|
-
const error = utils.exception(someInstance, new Error('Something went wrong'));
|
|
931
|
+
const error = new utils.exception(someInstance, new Error('Something went wrong'));
|
|
902
932
|
throw error;
|
|
903
933
|
```
|
|
904
934
|
|
|
935
|
+
The resulting error is a plain `Error` — data lives in its props, read via
|
|
936
|
+
`getProps(error)`: `args`, `originalError`, `instance`. Only `.message` and
|
|
937
|
+
`.stack` (merged lifecycle trace) sit on the error object itself. No bound
|
|
938
|
+
methods either: use `utils.extract(getProps(error).instance)` /
|
|
939
|
+
`utils.parse(getProps(error).instance)` for properties and structural info.
|
|
940
|
+
|
|
905
941
|
#### `utils.sibling(instance)`
|
|
906
942
|
|
|
907
943
|
Access sibling types from the same collection. Returns a callable/proxy object
|
|
@@ -917,19 +953,24 @@ const sibling = siblingAccessor.OtherType;
|
|
|
917
953
|
|
|
918
954
|
### Instance Properties (via `getProps`)
|
|
919
955
|
|
|
920
|
-
|
|
956
|
+
Internal properties are stored in a `WeakMap` keyed by the instance's
|
|
957
|
+
Mnemosyne memory layer — not as own properties on the instance itself — and
|
|
958
|
+
are read via `getProps(instance)`:
|
|
921
959
|
|
|
922
|
-
| Property |
|
|
923
|
-
|
|
924
|
-
|
|
|
925
|
-
|
|
|
926
|
-
|
|
|
927
|
-
|
|
|
928
|
-
|
|
|
929
|
-
|
|
|
930
|
-
|
|
|
931
|
-
|
|
|
932
|
-
|
|
|
960
|
+
| Property | Meaning |
|
|
961
|
+
|---|---|
|
|
962
|
+
| `__type__` | The `TypeDef` for this instance's type |
|
|
963
|
+
| `__parent__` | The parent instance this was constructed from |
|
|
964
|
+
| `__args__` | The arguments passed to the constructor |
|
|
965
|
+
| `__timestamp__` | Construction time (ms since epoch) |
|
|
966
|
+
| `__creator__` | The `InstanceCreatorContext` of the immediate creator (may differ from `__type__` in chained construction) |
|
|
967
|
+
| `__collection__` | The types collection (usually `defaultTypes`) |
|
|
968
|
+
| `__subtypes__` | Map of available subtypes for this instance |
|
|
969
|
+
| `__proto_proto__` | The prototype object used during construction |
|
|
970
|
+
| `__stack__` | Construction stack trace (only if `submitStack: true`) |
|
|
971
|
+
| `__self__` | The instance this record belongs to — installed separately after construction, because the instance does not exist yet when the other props are written. When repeated `getPrototypeOf` hops have lost track of where you are in the chain, `__self__` tells you. Also used as the async completion marker (`makeAwaiter`) and the fork self-call detector |
|
|
972
|
+
|
|
973
|
+
Full shape in [`src/types/index.ts`](./src/types/index.ts) (`InstanceInternalProps`).
|
|
933
974
|
|
|
934
975
|
---
|
|
935
976
|
|
|
@@ -955,7 +996,7 @@ explicit `<T>` cast is required for ordinary use.
|
|
|
955
996
|
| `utils.merge(A, B, ...args)` | `InstanceResult<Merge<B, A>>` |
|
|
956
997
|
| `utils.parse(instance)` | `Parsed<T>` |
|
|
957
998
|
| `utils.toJSON(instance)` | `string` |
|
|
958
|
-
| `utils.collectConstructors(instance,
|
|
999
|
+
| `utils.collectConstructors(instance, asSequence?)` | `string[]` when `asSequence: true`, otherwise a `{ [name]: true }` lookup object |
|
|
959
1000
|
|
|
960
1001
|
For the full type-level explanation, helper types, and examples, see
|
|
961
1002
|
[`docs/UTILS.md`](./docs/UTILS.md).
|
|
@@ -970,6 +1011,50 @@ For the full type-level explanation, helper types, and examples, see
|
|
|
970
1011
|
- `'postCreation'` - Called after instance creation
|
|
971
1012
|
- `'creationError'` - Called when instance creation throws an error
|
|
972
1013
|
|
|
1014
|
+
#### Construction sequence
|
|
1015
|
+
|
|
1016
|
+
When `new instance.SubType(args)` fires:
|
|
1017
|
+
|
|
1018
|
+
```
|
|
1019
|
+
new instance.SubType(args)
|
|
1020
|
+
│
|
|
1021
|
+
▼
|
|
1022
|
+
TypeProxy.construct ← proxy trap intercepts the new call
|
|
1023
|
+
│
|
|
1024
|
+
▼
|
|
1025
|
+
InstanceCreator ← validates parent, resolves TypeDef
|
|
1026
|
+
│
|
|
1027
|
+
▼
|
|
1028
|
+
preCreation hooks ← may throw → construction aborts, the error propagates (no creationError hooks)
|
|
1029
|
+
│
|
|
1030
|
+
▼
|
|
1031
|
+
Mnemosyne memory layer created, proto-linked to the parent instance
|
|
1032
|
+
│
|
|
1033
|
+
▼
|
|
1034
|
+
WeakMap.set(memoryLayer, internalProps) ← __type__, __parent__, __args__, __timestamp__, ...
|
|
1035
|
+
│
|
|
1036
|
+
▼
|
|
1037
|
+
constructHandler.call(newObj, args) ← user constructor runs
|
|
1038
|
+
│
|
|
1039
|
+
▼
|
|
1040
|
+
postCreation hooks
|
|
1041
|
+
│
|
|
1042
|
+
▼
|
|
1043
|
+
return newObj
|
|
1044
|
+
```
|
|
1045
|
+
|
|
1046
|
+
`preCreation` fires before the memory layer is created; `postCreation` fires
|
|
1047
|
+
after the user constructor runs. `creationError` fires when construction
|
|
1048
|
+
produced an **errored instance** — the `blockErrors: true` path, where a
|
|
1049
|
+
failure of the user constructor body is wrapped so that
|
|
1050
|
+
`inheritedInstance instanceof Error` (see
|
|
1051
|
+
[`src/api/types/InstanceCreator.ts`](./src/api/types/InstanceCreator.ts)).
|
|
1052
|
+
With `blockErrors: false` such a failure propagates unwrapped instead. The
|
|
1053
|
+
object carries none of the internal props as own properties — they live in
|
|
1054
|
+
the WeakMap, readable via `getProps`.
|
|
1055
|
+
|
|
1056
|
+
See [`src/api/types/InstanceCreator.ts`](./src/api/types/InstanceCreator.ts) and [`src/api/types/TypeProxy.ts`](./src/api/types/TypeProxy.ts).
|
|
1057
|
+
|
|
973
1058
|
#### `type.registerHook(hookType, callback)`
|
|
974
1059
|
|
|
975
1060
|
Register a hook on a specific type.
|
|
@@ -1008,7 +1093,7 @@ interface HookData {
|
|
|
1008
1093
|
type: TypeDef; // The type being constructed
|
|
1009
1094
|
args: unknown[]; // Arguments passed to constructor
|
|
1010
1095
|
existentInstance: object; // Parent instance
|
|
1011
|
-
inheritedInstance: object; // New instance (postCreation
|
|
1096
|
+
inheritedInstance: object; // New instance (postCreation and creationError)
|
|
1012
1097
|
throwModificationError(error: Error): void; // Throw error from hook (not available in preCreation)
|
|
1013
1098
|
}
|
|
1014
1099
|
```
|
|
@@ -1020,7 +1105,7 @@ MyType.registerHook('postCreation', (hookData) => {
|
|
|
1020
1105
|
});
|
|
1021
1106
|
```
|
|
1022
1107
|
|
|
1023
|
-
**Note:** In preCreation hooks, `existentInstance`
|
|
1108
|
+
**Note:** In both preCreation and postCreation hooks, `existentInstance` is the parent instance — the instance the new one is constructed from. The new instance itself is available in postCreation (and creationError) hooks as `inheritedInstance`.
|
|
1024
1109
|
|
|
1025
1110
|
**Error wrapping boundaries.** `preCreation` hooks do not receive
|
|
1026
1111
|
`throwModificationError` — throw normally to abort construction; the error
|
|
@@ -1052,25 +1137,28 @@ errors.WRONG_ARGUMENTS_USED
|
|
|
1052
1137
|
errors.WRONG_HOOK_TYPE
|
|
1053
1138
|
errors.MISSING_HOOK_CALLBACK
|
|
1054
1139
|
errors.MISSING_CALLBACK_ARGUMENT
|
|
1055
|
-
errors.FLOW_CHECKER_REDEFINITION
|
|
1056
1140
|
errors.OPTIONS_ERROR
|
|
1057
1141
|
errors.WRONG_STACK_CLEANER
|
|
1058
1142
|
```
|
|
1059
1143
|
|
|
1060
1144
|
#### Exception Instances
|
|
1061
1145
|
|
|
1062
|
-
When creating exceptions using `utils.exception()
|
|
1146
|
+
When creating exceptions using `utils.exception()` (must be called with `new`):
|
|
1063
1147
|
|
|
1064
1148
|
```js
|
|
1065
|
-
const { utils } = require('mnemonica');
|
|
1066
|
-
const error = utils.exception(instance, new Error('Original error'));
|
|
1149
|
+
const { utils, getProps } = require('mnemonica');
|
|
1150
|
+
const error = new utils.exception(instance, new Error('Original error'));
|
|
1151
|
+
|
|
1152
|
+
// The error object itself is a plain Error: .message and .stack
|
|
1153
|
+
// (merged lifecycle trace) only. Everything else lives in props:
|
|
1154
|
+
const errorProps = getProps(error);
|
|
1155
|
+
errorProps.args // Extra arguments passed to the exception call
|
|
1156
|
+
errorProps.originalError // The original error
|
|
1157
|
+
errorProps.instance // The mnemonica instance the error was made from
|
|
1067
1158
|
|
|
1068
|
-
//
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
error.BaseStack // Base stack trace
|
|
1072
|
-
error.parse() // Parse the exception structure
|
|
1073
|
-
error.extract() // Extract properties from the exception
|
|
1159
|
+
// Errors carry no bound methods — use the utils on the props instance:
|
|
1160
|
+
utils.extract(errorProps.instance) // Extract properties from the instance
|
|
1161
|
+
utils.parse(errorProps.instance) // Parse the instance structure
|
|
1074
1162
|
```
|
|
1075
1163
|
|
|
1076
1164
|
#### Stack Cleaning
|
|
@@ -1208,7 +1296,7 @@ For complete documentation including integration patterns, error handling, and a
|
|
|
1208
1296
|
|
|
1209
1297
|
> **AI agent guidance.** Patterns for type introspection, safe property
|
|
1210
1298
|
> access, type discovery, instance traversal, and safe construction live
|
|
1211
|
-
> in [AGENTS.md](AGENTS.md). They are not duplicated here.
|
|
1299
|
+
> in [AGENTS.md](https://github.com/wentout/mnemonica/blob/master/AGENTS.md). They are not duplicated here.
|
|
1212
1300
|
|
|
1213
1301
|
---
|
|
1214
1302
|
|
|
@@ -1302,65 +1390,25 @@ const merged = merge(instanceA, instanceB, 'args');
|
|
|
1302
1390
|
|
|
1303
1391
|
## Roadmap
|
|
1304
1392
|
|
|
1305
|
-
|
|
1306
|
-
so consumers can avoid relying on them prematurely.
|
|
1307
|
-
|
|
1308
|
-
### Nested `lookup()` — resolved as unnecessary
|
|
1393
|
+
### Nested `lookup()` — designed, not yet shipped
|
|
1309
1394
|
|
|
1310
1395
|
A type-safe `.lookup()` method on constructors (e.g.
|
|
1311
|
-
`Scene2D.lookup('GraphNode2D')`)
|
|
1312
|
-
constructor
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
- Tactica-generated declaration merging already types those instance-level
|
|
1320
|
-
subtype constructors. Starting from `lookup('Scene2D')` gives a fully
|
|
1321
|
-
typed root constructor; after `const scene = new Scene2D(...)`,
|
|
1322
|
-
`scene.GraphNode2D` is typed and produces the correct chained instance.
|
|
1323
|
-
|
|
1324
|
-
If `lookup('Something')` returns `TypeClass | undefined` instead of a typed
|
|
1325
|
-
constructor, it means one of three things:
|
|
1326
|
-
|
|
1327
|
-
1. No `TypeRegistry` augmentation is in scope (the `.tactica` declarations
|
|
1328
|
-
are not imported or included in `tsconfig.json`).
|
|
1329
|
-
2. The augmentation is in scope, but does not declare `'Something'`.
|
|
1330
|
-
3. `'Something'` was never defined at runtime.
|
|
1331
|
-
|
|
1332
|
-
How nested `.lookup()` could have been implemented if it were needed:
|
|
1333
|
-
|
|
1334
|
-
1. Encode the type's dotted path in `TypeConstructor` itself:
|
|
1335
|
-
|
|
1336
|
-
```typescript
|
|
1337
|
-
interface TypeConstructor<Instance, Path extends string = string> {
|
|
1338
|
-
lookup<const K extends keyof NestedTypeRegistry[Path]>(
|
|
1339
|
-
name: K
|
|
1340
|
-
): NestedTypeRegistry[Path][K];
|
|
1341
|
-
}
|
|
1342
|
-
```
|
|
1343
|
-
|
|
1344
|
-
2. Or parse the full path with template literal types and consult a
|
|
1345
|
-
`NestedTypeRegistry` mapping parent paths to their child constructors:
|
|
1346
|
-
|
|
1347
|
-
```typescript
|
|
1348
|
-
type ParentPath<P extends string> =
|
|
1349
|
-
P extends `${infer Head}.${string}` ? Head : never;
|
|
1350
|
-
```
|
|
1351
|
-
|
|
1352
|
-
Both approaches require either changing `TypeConstructor` to carry a `Path`
|
|
1353
|
-
generic or maintaining a second registry. Since the root-constructor +
|
|
1354
|
-
instance-level subtype pattern already gives the same result with no core
|
|
1355
|
-
changes, this item is intentionally not implemented.
|
|
1396
|
+
`Scene2D.lookup('GraphNode2D')`), preserving the parent type in the returned
|
|
1397
|
+
constructor, is designed but **not yet shipped**. The runtime method already
|
|
1398
|
+
exists — it resolves relative first, then falls back to the collection root
|
|
1399
|
+
— what is missing is the type-level machinery. Until it lands, start from a
|
|
1400
|
+
typed root constructor (`lookup('Scene2D')` with a `TypeRegistry`
|
|
1401
|
+
augmentation) and construct subtypes from instances: `scene.GraphNode2D` is
|
|
1402
|
+
typed by the augmentation and produces the correctly chained instance. See
|
|
1403
|
+
[`docs/typed-lookup.md`](./docs/typed-lookup.md).
|
|
1356
1404
|
|
|
1357
1405
|
---
|
|
1358
1406
|
|
|
1359
1407
|
## Contributing
|
|
1360
1408
|
|
|
1361
|
-
See [CONTRIBUTING.md](CONTRIBUTING.md) for branch model, commit style, and
|
|
1409
|
+
See [CONTRIBUTING.md](https://github.com/wentout/mnemonica/blob/master/CONTRIBUTING.md) for branch model, commit style, and
|
|
1362
1410
|
the local build/test loop. Repository conventions, code style, and agent
|
|
1363
|
-
rules live in [AGENTS.md](AGENTS.md).
|
|
1411
|
+
rules live in [AGENTS.md](https://github.com/wentout/mnemonica/blob/master/AGENTS.md).
|
|
1364
1412
|
|
|
1365
1413
|
**Related reading:**
|
|
1366
1414
|
- [Inheritance in JavaScript: Factory of Constructors with Prototype Chain](https://github.com/mythographica/stash/blob/master/inheritance.md)
|