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.
Files changed (53) hide show
  1. package/FOR_HUMANS.md +186 -138
  2. package/README.md +70 -249
  3. package/build/api/errors/exceptionConstructor.js +20 -47
  4. package/build/api/errors/throwModificationError.js +26 -61
  5. package/build/api/types/InstanceCreator.js +5 -1
  6. package/build/api/types/Props.js +24 -10
  7. package/build/api/types/index.js +18 -12
  8. package/build/types/index.d.ts +9 -4
  9. package/build/types/index.js +1 -1
  10. package/docs/UTILS.md +97 -8
  11. package/docs/async-constructors.md +2 -0
  12. package/docs/decorate.md +1 -1
  13. package/docs/empathy-in-ai.md +20 -10
  14. package/docs/prototype-chain.md +8 -7
  15. package/docs/typed-lookup.md +195 -5
  16. package/docs/typeomatica.md +8 -345
  17. package/package.json +6 -10
  18. package/src/api/errors/exceptionConstructor.ts +40 -83
  19. package/src/api/errors/throwModificationError.ts +64 -104
  20. package/src/api/types/InstanceCreator.ts +14 -0
  21. package/src/api/types/Props.ts +53 -18
  22. package/src/api/types/index.ts +33 -20
  23. package/src/types/index.ts +15 -5
  24. package/.ai/AGENTS.md +0 -151
  25. package/.ai/ARCHITECT.md +0 -110
  26. package/.ai/DEBUG.md +0 -178
  27. package/.ai/ONBOARDING.md +0 -189
  28. package/.ai/PROTOTYPE-CHAIN.md +0 -153
  29. package/.ai/mode-ask.md +0 -121
  30. package/.ai/mode-orchestrator.md +0 -141
  31. package/.ai/performance-vs-security.md +0 -395
  32. package/.ai/rules-async-constructors.md +0 -352
  33. package/.ai/rules-code-style.md +0 -95
  34. package/.ai/rules-coding.md +0 -246
  35. package/.ai/rules-context-condensing.md +0 -50
  36. package/.ai/rules-contributing.md +0 -227
  37. package/.ai/rules-define-patterns.md +0 -159
  38. package/.ai/rules-ecosystem.md +0 -140
  39. package/.ai/rules-error-system.md +0 -56
  40. package/.ai/rules-hooks.md +0 -46
  41. package/.ai/rules-instance-methods.md +0 -93
  42. package/.ai/rules-philosophy.md +0 -231
  43. package/.ai/rules-reminders.md +0 -19
  44. package/.ai/rules-testing.md +0 -66
  45. package/.ai/rules-type-system.md +0 -124
  46. package/.ai/theory-of-operations.md +0 -224
  47. package/AGENTS.md +0 -345
  48. package/CONTRIBUTING.md +0 -150
  49. package/SKILL.md +0 -114
  50. package/docs/ai-learning-trajectory.md +0 -141
  51. package/docs/purpose.md +0 -707
  52. package/docs/tactica-deep-dive.md +0 -629
  53. package/docs/tactica-pattern.md +0 -146
@@ -90,24 +90,34 @@ const ClarifiedNeed = Turn.define('ClarifiedNeed', function (this: ClarifiedNeed
90
90
  this.need = need;
91
91
  });
92
92
 
93
- const EscalationReason = ClarifiedNeed.define('EscalationReason', function (this: EscalationReason, reason: string) {
94
- this.reason = reason;
95
- });
96
-
97
93
  // Turn 1
98
94
  const t1 = new Turn('My order is wrong.');
99
95
  const c1 = new t1.ClarifiedNeed('missing_item');
100
96
 
101
- // Turn 2: the user adds detail
102
- const t2 = new c1.Turn('I ordered two, only one arrived.');
103
- const c2 = new t2.ClarifiedNeed('quantity_error');
97
+ // Turn 2: the user adds detail — each turn extends the chain with a NEW type
98
+ // (a type name appears only once per chain; ancestor types are not
99
+ // re-constructible from deeper instances)
100
+ const FollowUp = ClarifiedNeed.define('FollowUp', function (this: FollowUp, text: string) {
101
+ this.text = text;
102
+ });
103
+ const RefinedNeed = FollowUp.define('RefinedNeed', function (this: RefinedNeed, need: string) {
104
+ this.need = need;
105
+ });
106
+ const t2 = new c1.FollowUp('I ordered two, only one arrived.');
107
+ const c2 = new t2.RefinedNeed('quantity_error');
104
108
 
105
109
  // Turn 3: escalation becomes appropriate
106
- const t3 = new c2.Turn('This is the third time this month.');
110
+ const FinalTurn = RefinedNeed.define('FinalTurn', function (this: FinalTurn, text: string) {
111
+ this.text = text;
112
+ });
113
+ const EscalationReason = FinalTurn.define('EscalationReason', function (this: EscalationReason, reason: string) {
114
+ this.reason = reason;
115
+ });
116
+ const t3 = new c2.FinalTurn('This is the third time this month.');
107
117
  const escalation = new t3.EscalationReason('repeat_issue');
108
118
  ```
109
119
 
110
- `escalation` knows it is a `EscalationReason` whose parent is `Turn('This is the third time this month.')`, whose parent is `ClarifiedNeed('quantity_error')`, whose parent is `Turn('I ordered two, only one arrived.')`, and so on. The decision to escalate is not a label produced by a classifier. It is a position in a reconstructible path.
120
+ `escalation` knows it is an `EscalationReason` whose parent is `FinalTurn('This is the third time this month.')`, whose parent is `RefinedNeed('quantity_error')`, whose parent is `FollowUp('I ordered two, only one arrived.')`, and so on back to the original `Turn`. The decision to escalate is not a label produced by a classifier. It is a position in a reconstructible path.
111
121
 
112
122
  ---
113
123
 
@@ -165,5 +175,5 @@ What it provides is a data model where context and lineage are first-class. High
165
175
  ## See also
166
176
 
167
177
  - [`docs/hott-primer.md`](./hott-primer.md) — formal background on paths, identity, and transport
168
- - [`docs/purpose.md`](./purpose.md) — data flow vs control flow, and what mnemonica does not do
178
+ - [`.ai/purpose.md`](https://github.com/wentout/mnemonica/blob/master/.ai/purpose.md) — data flow vs control flow, and what mnemonica does not do
169
179
  - [Inheritance in JavaScript — the original 2019 essay](https://github.com/mythographica/stash/blob/master/inheritance.md) — the vision that posed the empathy question
@@ -58,16 +58,17 @@ user.name === 'Alice';
58
58
 
59
59
  ### 2. The user prototype layer
60
60
 
61
- This layer holds the methods and getters you put on the type when you defined it:
61
+ This layer holds the methods and getters the constructor's own prototype
62
+ carried when the type was defined — `define()` captures them from there
63
+ (there is no `proto` config key):
62
64
 
63
65
  ```js
64
- const AdminType = UserType.define('AdminType', function (data) {
66
+ function AdminConstructor(data) {
65
67
  Object.assign(this, data);
66
- }, {
67
- proto: {
68
- isAdmin() { return true; }
69
- }
70
- });
68
+ }
69
+ AdminConstructor.prototype.isAdmin = function () { return true; };
70
+
71
+ const AdminType = UserType.define('AdminType', AdminConstructor);
71
72
  ```
72
73
 
73
74
  `admin.isAdmin()` resolves on this layer. This prototype is **fresh per instance**, so one `admin` cannot pollute the prototype of another.
@@ -20,6 +20,38 @@ TypeScript, however, cannot see a type graph built by runtime calls. There are
20
20
 
21
21
  ---
22
22
 
23
+ ## Every `define()` lands in the same collection
24
+
25
+ All of these call the **same function** and register into the same runtime
26
+ collection (`defaultTypes`, unless you pass another source explicitly):
27
+
28
+ ```typescript
29
+ import { mnemonica, define, defaultTypes } from 'mnemonica';
30
+
31
+ mnemonica.define('User', handler); // this === mnemonica → defaultTypes
32
+ define('User', handler); // this === undefined → defaultTypes
33
+
34
+ const { define: define2 } = mnemonica;
35
+ define2('User', handler); // same function, bare call → defaultTypes
36
+
37
+ defaultTypes.define('User', handler); // the collection itself, directly
38
+ ```
39
+
40
+ The routing rule is one line in the source (`src/index.ts`): the free `define`
41
+ resolves to `defaultTypes` when called bare or on the `mnemonica` module
42
+ object, and to `this` when invoked on a types collection. Runtime behavior
43
+ never changes between these call styles — same type graph, same hooks, same
44
+ registry entries.
45
+
46
+ **What differs is purely compile-time.** Builder-style calls thread the
47
+ registry through *return types*, so `chain.lookup('User')` is typed without
48
+ any augmentation. The *free* `lookup('User')` at module scope, and
49
+ `@decorate()`, can only be typed through the global `TypeRegistry` interface —
50
+ which is what Tactica (or a hand-written file) populates. That split is the
51
+ only reason declaration merging exists in this library.
52
+
53
+ ---
54
+
23
55
  ## Builder mode (default)
24
56
 
25
57
  Import the module object or create a custom collection, then chain `.define()` or `.lazy()` calls. The returned object carries a local type registry.
@@ -265,11 +297,72 @@ define('User.Admin', function (this: AdminShape, data: { role: string }) {
265
297
  this.role = data.role;
266
298
  });
267
299
 
268
- // Now the free lookup is typed.
269
- const Admin = lookup('User.Admin');
270
- const admin = new Admin({ role: 'root' });
300
+ // Now the free lookup is typed — use it for references and root types.
301
+ const User = lookup('User');
302
+ const user = new User({ name: 'Ada' });
303
+
304
+ // Subtypes are still constructed from a parent instance — same rule as always.
305
+ const admin = new user.Admin({ role: 'root' });
306
+
307
+ // The nested lookup gives you the typed constructor itself (e.g. for annotations):
308
+ const AdminCtor = lookup('User.Admin');
271
309
  ```
272
310
 
311
+ ### What tactica generates
312
+
313
+ `npx tactica` scans your `define()` calls and writes a `.tactica/` directory:
314
+
315
+ - `types.ts` — instance types (nested shapes composed with `ProtoFlat<Parent, ...>`)
316
+ - `registry.ts` — the `TypeRegistry` augmentation; **this is the critical file**
317
+ - `index.ts` — re-exports
318
+ - `hierarchy.json` / `hierarchy.txt` — the type Trie as structured JSON (parent/children
319
+ with 1-based locations) and as an ASCII tree
320
+ - `definitions.json`, `usages.json`, `flow.json` — metadata about your type graph and where types are instantiated
321
+ - `eds.json` — execution-data-structures metadata, emitted when EDS tracking is on
322
+ (auto-enabled when `@mnemonica/dive` is in your dependencies; `--eds` / `--no-eds` override)
323
+
324
+ Registry keys are **dot-separated nested paths** — the same strings `lookup()` takes.
325
+ Values are inline constructor signatures returning the generated instance types:
326
+
327
+ ```typescript
328
+ // .tactica/registry.ts (generated)
329
+ import type { User, User_Admin } from './types';
330
+
331
+ declare module 'mnemonica' {
332
+ interface TypeRegistry {
333
+ 'User' : new (data: { name: string }) => User;
334
+ 'User.Admin' : new (data: { role: string }) => User_Admin;
335
+ }
336
+ }
337
+
338
+ import type { TypeRegistry } from 'mnemonica';
339
+ export type { TypeRegistry };
340
+ ```
341
+
342
+ `.tactica/` is output, not input. Never edit generated files — change the
343
+ `define()` call and re-run tactica.
344
+
345
+ ### tsconfig setup
346
+
347
+ Declaration merging only works if TypeScript actually sees the generated
348
+ files. Put `.tactica/` in `include`:
349
+
350
+ ```json
351
+ {
352
+ "compilerOptions": {
353
+ "module": "NodeNext",
354
+ "moduleResolution": "NodeNext",
355
+ "strict": true
356
+ },
357
+ "include": ["src/**/*", ".tactica/**/*"]
358
+ }
359
+ ```
360
+
361
+ If `.tactica/` is missing from `include`, the augmentation is invisible:
362
+ `TypeRegistry` stays empty and free `lookup()` silently falls back to
363
+ `TypeClass | undefined`. This is the single most common tactica
364
+ misconfiguration.
365
+
273
366
  ### With `@decorate()`
274
367
 
275
368
  > The canonical decorator guide is [`docs/decorate.md`](./decorate.md) —
@@ -345,9 +438,9 @@ At runtime the results are identical. At compile time, TypeScript picks whicheve
345
438
 
346
439
  ---
347
440
 
348
- ## Why two type systems exist
441
+ ## Why two typing mechanisms exist
349
442
 
350
- It feels like there should be one type system. In an ideal world, every `define()` call would add its type to the same registry, and `lookup()` would always be typed. TypeScript does not allow that.
443
+ The three paths above are built from **two** underlying mechanisms: a local registry carried in builder values, and the global `TypeRegistry` interface. It feels like there should be one type system. In an ideal world, every `define()` call would add its type to the same registry, and `lookup()` would always be typed. TypeScript does not allow that.
351
444
 
352
445
  ### The hard limitation
353
446
 
@@ -413,6 +506,103 @@ types differs.
413
506
 
414
507
  ---
415
508
 
509
+ ## Common mistakes
510
+
511
+ Every one of these is a symptom of a missing or unused `TypeRegistry`
512
+ augmentation. The fix is never a cast.
513
+
514
+ ### "I'll just cast it"
515
+
516
+ ```typescript
517
+ // WRONG
518
+ const admin = new Admin({ role: 'root' }) as unknown as AdminShape;
519
+ ```
520
+
521
+ You are fighting the type system instead of using it. Every cast is a bug
522
+ waiting to happen: if the type changes, the cast still compiles and breaks at
523
+ runtime. Fix the augmentation instead — bridge, tactica, or hand-written.
524
+
525
+ ### "I'll import the generated types too"
526
+
527
+ ```typescript
528
+ // WRONG
529
+ import { Admin } from './models/admin';
530
+ import type { AdminShape } from '../.tactica/types';
531
+ const admin = new Admin({ role: 'root' }) as unknown as AdminShape;
532
+ ```
533
+
534
+ This imports the runtime constructor *and* the generated type, then bridges
535
+ them with a cast — twice the work and still unsafe. `lookup()` gives you both
536
+ in one call.
537
+
538
+ ### "lookup only works inside handlers"
539
+
540
+ ```typescript
541
+ // UNNECESSARY
542
+ app.get('/test', async () => {
543
+ const User = lookup('User');
544
+ const user = new User({ name: 'Ada' });
545
+ });
546
+ ```
547
+
548
+ `lookup()` is a runtime lookup, but it is deterministic. Calling it once at
549
+ module level is fine and cheaper:
550
+
551
+ ```typescript
552
+ const User = lookup('User');
553
+
554
+ app.get('/test', async () => {
555
+ const user = new User({ name: 'Ada' });
556
+ const admin = new user.Admin({ role: 'root' }); // subtypes from the parent instance
557
+ });
558
+ ```
559
+
560
+ ### "I need the direct import for this other API"
561
+
562
+ ```typescript
563
+ // WRONG — two references to the same object
564
+ import { Admin } from './models/admin';
565
+ const TypedAdmin = lookup('User.Admin');
566
+
567
+ app.decorate('Admin', Admin); // direct import
568
+ register(TypedAdmin); // lookup result
569
+ ```
570
+
571
+ `import { Admin }` and `lookup('User.Admin')` return the **same constructor
572
+ object** at runtime — the test suites assert reference identity between the
573
+ two. Use the looked-up one for everything, and construct subtypes from a
574
+ parent instance as usual.
575
+
576
+ ### "I'll just edit the generated file"
577
+
578
+ `.tactica/` is output, not input. Hand edits are overwritten on the next run.
579
+ If a property is missing from the generated types, the `define()` call is the
580
+ source of truth — change it and re-run `npx tactica`. Forgetting to
581
+ regenerate after changing `define()` calls shows up as
582
+ `Object literal may only specify known properties` on valid code.
583
+
584
+ ---
585
+
586
+ ## Cheat sheet
587
+
588
+ | I want to... | Do this | Don't do this |
589
+ |---|---|---|
590
+ | Get a typed constructor (builder mode) | `const T = App.lookup('T')` | `import { T } from './models/T'` + cast |
591
+ | Get a typed constructor (augmented mode) | `const T = lookup('T')` | `import { T } from './models/T'` + cast |
592
+ | Get a typed constructor from a builder value | `lookup(App, 'T')` | `lookup('T') as any` |
593
+ | Create an instance | `new T({ ... })` | `new T({ ... }) as unknown as TShape` |
594
+ | Chain to a child type | `new instance.Child({ ... })` | `new (instance as any).Child({ ... })` |
595
+ | Type free `lookup()` without tactica | one-line `RegistryOf` bridge | a second registry file kept in sync by hand |
596
+ | Reuse one constructor everywhere | `const T = lookup('T')`, then use `T` | direct import for one API, `lookup()` for another |
597
+ | Add or rename a type (builder + bridge) | edit the chain — the bridge follows | edit a hand-written augmentation to match |
598
+ | Add or rename a type (tactica) | edit `define()` → re-run `npx tactica` | hand-edit `.tactica/` |
599
+ | Fix "Property does not exist" | check the augmentation / regenerate | add `as any` or `as unknown as` |
600
+
601
+ If you find yourself writing `as unknown as` with mnemonica types, you have
602
+ taken a wrong turn. Stop. Use `lookup`. Trust the registry.
603
+
604
+ ---
605
+
416
606
  ## Summary
417
607
 
418
608
  - **Default:** builder mode — `mnemonica.define(...)` or `createTypesCollection()`, `.lookup()` on the result. No tooling.
@@ -13,12 +13,8 @@ TypeØmatica is a companion library that provides strict runtime type checking f
13
13
  - [Core Concepts](#core-concepts)
14
14
  - [API Reference](#api-reference)
15
15
  - [Integration Patterns](#integration-patterns)
16
- - [Type Examples](#type-examples)
17
- - [Working with Wrapped Values](#working-with-wrapped-values)
18
- - [Error Handling](#error-handling)
19
- - [Advanced: Custom Fields](#advanced-custom-fields)
20
16
  - [Complete Integration Example](#complete-integration-example)
21
- - [Error Reference](#error-reference)
17
+ - [Benefits Summary](#benefits-summary)
22
18
 
23
19
  ---
24
20
 
@@ -96,68 +92,11 @@ Decorators apply **bottom-to-top** (inner to outer). `@Strict` wraps the class f
96
92
 
97
93
  ## API Reference
98
94
 
99
- ### BaseClass
95
+ The full typeomatica API — `BaseClass`, `BasePrototype`, the `@Strict()` decorator and its options, `FieldConstructor`, `SymbolTypeomaticaProxyReference`, `SymbolInitialValue`, and the complete error reference (`Type Mismatch`, `Value Access Denied`, and friends) — is documented in the typeomatica package itself:
100
96
 
101
- The primary class for creating strict-type objects.
97
+ **<https://www.npmjs.com/package/typeomatica>**
102
98
 
103
- ```typescript
104
- import { BaseClass } from 'typeomatica';
105
-
106
- class MyClass extends BaseClass {
107
- field: string = 'value';
108
- constructor() {
109
- super();
110
- }
111
- }
112
- ```
113
-
114
- ### BasePrototype / BaseConstructorPrototype
115
-
116
- Functional equivalent of `BaseClass`.
117
-
118
- ```typescript
119
- import { BasePrototype } from 'typeomatica';
120
-
121
- const Base = BasePrototype({ initialProp: 123 });
122
- class MyClass extends Base { }
123
- ```
124
-
125
- ### @Strict() Decorator
126
-
127
- Apply strict typing to any class without extending BaseClass.
128
-
129
- ```typescript
130
- import { Strict } from 'typeomatica';
131
-
132
- @Strict({ deep: true })
133
- class MyClass {
134
- field: number = 0;
135
- }
136
- ```
137
-
138
- **Options:**
139
- - `deep: true` - Enables recursive/deep property checking
140
- - Pass initial values as properties to pre-define types
141
-
142
- ### SymbolTypeomaticaProxyReference
143
-
144
- Access the internal proxy reference.
145
-
146
- ```typescript
147
- import { SymbolTypeomaticaProxyReference } from 'typeomatica';
148
-
149
- const proxyRef = instance[SymbolTypeomaticaProxyReference];
150
- ```
151
-
152
- ### SymbolInitialValue
153
-
154
- Access the original initial value of a property.
155
-
156
- ```typescript
157
- import { SymbolInitialValue } from 'typeomatica';
158
-
159
- const originalValue = instance[SymbolInitialValue]('fieldName');
160
- ```
99
+ The sections below cover only what you need to combine typeomatica with mnemonica.
161
100
 
162
101
  ---
163
102
 
@@ -251,275 +190,14 @@ const PremiumCustomer = Customer.define('PremiumCustomer', function(this: { tier
251
190
  this.tier = 'gold';
252
191
  });
253
192
 
254
- const premium = new PremiumCustomer();
193
+ const premiumCustomer = new Customer();
194
+ const premium = new premiumCustomer.PremiumCustomer();
255
195
  // @ts-ignore
256
196
  premium.tier = 123; // ✗ TypeError: Type Mismatch
257
197
  ```
258
198
 
259
199
  ---
260
200
 
261
- ## Type Examples
262
-
263
- ### Primitives
264
-
265
- All primitive types are fully supported and enforced.
266
-
267
- ```typescript
268
- class Primitives extends BaseClass {
269
- str: string = 'hello';
270
- num: number = 42;
271
- bool: boolean = true;
272
- bigint: bigint = BigInt(100);
273
- sym: symbol = Symbol('test');
274
- }
275
-
276
- const p = new Primitives();
277
-
278
- // Valid assignments
279
- p.str = 'world'; // ✓ string → string
280
- p.num = 100; // ✓ number → number
281
- p.bool = false; // ✓ boolean → boolean
282
- p.bigint = BigInt(200); // ✓ bigint → bigint
283
-
284
- // Invalid assignments throw TypeError
285
- // @ts-ignore
286
- p.str = 123; // ✗ TypeError: Type Mismatch
287
- // @ts-ignore
288
- p.num = '100'; // ✗ TypeError: Type Mismatch
289
- // @ts-ignore
290
- p.bool = 'true'; // ✗ TypeError: Type Mismatch
291
- // @ts-ignore
292
- p.bigint = 100; // ✗ TypeError: Type Mismatch
293
- ```
294
-
295
- ### Null and Undefined
296
-
297
- Null and undefined are distinct types.
298
-
299
- ```typescript
300
- class Nullable extends BaseClass {
301
- nullValue: null = null;
302
- undefinedValue: undefined = undefined;
303
- }
304
-
305
- const n = new Nullable();
306
-
307
- n.nullValue = null; // ✓
308
- n.undefinedValue = undefined; // ✓
309
-
310
- // @ts-ignore
311
- n.nullValue = undefined; // ✗ TypeError: Type Mismatch
312
- // @ts-ignore
313
- n.nullValue = 0; // ✗ TypeError: Type Mismatch
314
- // @ts-ignore
315
- n.undefinedValue = null; // ✗ TypeError: Type Mismatch
316
- ```
317
-
318
- ### Objects
319
-
320
- Object types are strictly enforced by constructor.
321
-
322
- ```typescript
323
- class WithObject extends BaseClass {
324
- data: object = {};
325
- list: number[] = [];
326
- map: Map<string, number> = new Map();
327
- }
328
-
329
- const w = new WithObject();
330
-
331
- w.data = { a: 1 }; // ✓ Same type (object)
332
- w.data = { b: 2 }; // ✓ Same type (object)
333
- w.list = [1, 2, 3]; // ✓ Array → Array
334
- w.map = new Map(); // ✓ Map → Map
335
-
336
- // @ts-ignore
337
- w.data = 123; // ✗ TypeError: Type Mismatch
338
- // @ts-ignore
339
- w.data = new Set(); // ✗ TypeError: Type Mismatch (Set !== Object)
340
- // @ts-ignore
341
- w.list = new Set(); // ✗ TypeError: Type Mismatch (Set !== Array)
342
- ```
343
-
344
- ---
345
-
346
- ## Working with Wrapped Values
347
-
348
- TypeØmatica wraps primitive values to enforce type safety. Use `valueOf()` to access the raw value for operations.
349
-
350
- ### Numeric Operations
351
-
352
- ```typescript
353
- class Calculations extends BaseClass {
354
- count: number = 10;
355
- }
356
-
357
- const calc = new Calculations();
358
-
359
- // ✗ Direct arithmetic throws
360
- try {
361
- const result = calc.count + 5;
362
- } catch (e) {
363
- // ReferenceError: Value Access Denied
364
- }
365
-
366
- // ✓ Use valueOf() for operations
367
- const result = calc.count.valueOf() + 5; // 15
368
-
369
- // ✓ Use unary + for coercion
370
- const sum = 3 + +calc.count; // 13
371
-
372
- // ✓ Comparison works with valueOf()
373
- if (calc.count.valueOf() > 5) {
374
- // ...
375
- }
376
- ```
377
-
378
- ### String Operations
379
-
380
- ```typescript
381
- class TextData extends BaseClass {
382
- message: string = 'hello';
383
- }
384
-
385
- const text = new TextData();
386
-
387
- // Access string methods through valueOf()
388
- text.message.valueOf().toUpperCase(); // 'HELLO'
389
- text.message.valueOf().length; // 5
390
- text.message.valueOf().substring(0, 2); // 'he'
391
-
392
- // Template literals require valueOf()
393
- const greeting = `Message: ${text.message.valueOf()}`;
394
- ```
395
-
396
- ### Boolean Operations
397
-
398
- ```typescript
399
- class Flags extends BaseClass {
400
- active: boolean = true;
401
- }
402
-
403
- const flags = new Flags();
404
-
405
- // ✗ Direct comparison throws
406
- try {
407
- if (flags.active) { } // May throw in some contexts
408
- } catch (e) {
409
- // ReferenceError: Value Access Denied
410
- }
411
-
412
- // ✓ Use valueOf() for conditions
413
- if (flags.active.valueOf()) {
414
- // ...
415
- }
416
-
417
- // ✓ Comparison with valueOf()
418
- const isActive = flags.active.valueOf() === true;
419
- ```
420
-
421
- ---
422
-
423
- ## Error Handling
424
-
425
- TypeØmatica throws specific error types for different violations.
426
-
427
- ```typescript
428
- import { BaseClass } from 'typeomatica';
429
-
430
- class SecureData extends BaseClass {
431
- id: number = 1;
432
- name: string = 'test';
433
- data: object = {};
434
- }
435
-
436
- const secure = new SecureData();
437
-
438
- // Type Mismatch - wrong type assignment
439
- try {
440
- // @ts-ignore
441
- secure.id = 'not a number';
442
- } catch (e: any) {
443
- console.log(e.message); // 'Type Mismatch'
444
- console.log(e instanceof TypeError); // true
445
- }
446
-
447
- // Access Denied - wrong receiver context
448
- const upper = Object.create(secure);
449
- try {
450
- upper.id = 2;
451
- } catch (e: any) {
452
- console.log(e.message); // 'Value Access Denied'
453
- console.log(e instanceof ReferenceError); // true
454
- }
455
-
456
- // Undefined Property - accessing non-existent
457
- try {
458
- // @ts-ignore
459
- secure.nonExistent;
460
- } catch (e: any) {
461
- console.log(e.message);
462
- // 'Attempt to Access to Undefined Prop: [ nonExistent ] for SecureData'
463
- }
464
-
465
- // Functions Restricted - methods on data objects
466
- try {
467
- // @ts-ignore
468
- secure.name = function() {};
469
- } catch (e: any) {
470
- console.log(e.message); // 'Functions are Restricted'
471
- }
472
- ```
473
-
474
- ---
475
-
476
- ## Advanced: Custom Fields
477
-
478
- Use `FieldConstructor` to create custom property behavior.
479
-
480
- ```typescript
481
- import { BaseClass, FieldConstructor, SymbolInitialValue } from 'typeomatica';
482
-
483
- // Read-only field implementation
484
- class ReadOnlyField extends FieldConstructor<string> {
485
- private _value: string;
486
-
487
- constructor(value: string) {
488
- super(value);
489
- this._value = value;
490
- // Make enumerable for Object.keys()
491
- Reflect.defineProperty(this, 'enumerable', { value: true });
492
- }
493
-
494
- get() {
495
- return this._value;
496
- }
497
- // No set() method = read-only
498
- }
499
-
500
- // Usage
501
- const readOnly = new ReadOnlyField('v1.0.0');
502
-
503
- class Config extends BaseClass {
504
- version = readOnly;
505
- }
506
-
507
- const cfg = new Config();
508
- console.log(cfg.version); // 'v1.0.0'
509
-
510
- try {
511
- cfg.version = 'v2.0.0'; // ✗ Throws!
512
- } catch (e: any) {
513
- console.log(e.message); // 'Re-Assirnment is Forbidden'
514
- }
515
-
516
- // Access initial value
517
- const initial = cfg[SymbolInitialValue]('version');
518
- console.log(initial); // 'v1.0.0'
519
- ```
520
-
521
- ---
522
-
523
201
  ## Complete Integration Example
524
202
 
525
203
  Full example combining mnemonica's inheritance with typeomatica's runtime safety.
@@ -569,8 +247,8 @@ const Admin = User.define('Admin', function(this: {
569
247
  // Create instances with full type safety
570
248
  // ==========================================
571
249
  const entity = new Entity();
572
- const user = new User();
573
- const admin = new Admin();
250
+ const user = new entity.User(); // subtypes construct from a parent instance
251
+ const admin = new user.Admin();
574
252
 
575
253
  // Runtime type enforcement prevents bugs
576
254
  user.email = 'john@example.com'; // ✓ Works
@@ -589,21 +267,6 @@ const id = entity.id.valueOf(); // Get raw string value
589
267
 
590
268
  ---
591
269
 
592
- ## Error Reference
593
-
594
- | Error Message | Error Type | When Thrown |
595
- |---------------|------------|-------------|
596
- | `Type Mismatch` | TypeError | Assigning wrong type to property (e.g., string to number field) |
597
- | `Value Access Denied` | ReferenceError | Accessing property from wrong context/receiver |
598
- | `Attempt to Access to Undefined Prop` | Error | Reading property that doesn't exist on the object |
599
- | `Functions are Restricted` | TypeError | Assigning function to data type property |
600
- | `Re-Assirnment is Forbidden` | TypeError | Modifying read-only field (FieldConstructor without setter) |
601
- | `Setting prototype is not allowed` | Error | Calling `Object.setPrototypeOf()` on instance |
602
- | `Defining new Properties is not allowed` | Error | Calling `Object.defineProperty()` on instance |
603
- | `Properties Deletion is not allowed` | Error | Calling `delete` on instance property |
604
-
605
- ---
606
-
607
270
  ## Benefits Summary
608
271
 
609
272
  | Feature | TypeScript | TypeØmatica | Mnemonica |