@final-hill/decorator-contracts 0.25.3 → 2.0.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 (46) hide show
  1. package/README.md +580 -542
  2. package/dist/AssertionError.d.mts +52 -8
  3. package/dist/Contracted.d.mts +29 -21
  4. package/dist/admissibility.d.mts +81 -0
  5. package/dist/assert.d.mts +73 -8
  6. package/dist/decorator.d.mts +12 -0
  7. package/dist/demands.d.mts +54 -0
  8. package/dist/ensures.d.mts +39 -0
  9. package/dist/iff.d.mts +24 -6
  10. package/dist/implies.d.mts +22 -6
  11. package/dist/index.d.mts +11 -13
  12. package/dist/index.mjs +1 -2
  13. package/dist/index.mjs.map +1 -1
  14. package/dist/invariant.d.mts +27 -0
  15. package/dist/read-only.d.mts +45 -0
  16. package/dist/rescue.d.mts +61 -0
  17. package/dist/standard-schema.d.mts +46 -0
  18. package/dist/types.d.mts +7 -0
  19. package/package.json +33 -18
  20. package/dist/Contract.d.mts +0 -39
  21. package/dist/Messages.d.mts +0 -16
  22. package/dist/index.mjs.LICENSE.txt +0 -6
  23. package/dist/lib/ClassRegistration.d.mts +0 -23
  24. package/dist/lib/ClassType.d.mts +0 -10
  25. package/dist/lib/Feature.d.mts +0 -26
  26. package/dist/lib/assertDemands.d.mts +0 -9
  27. package/dist/lib/assertEnsures.d.mts +0 -10
  28. package/dist/lib/assertInvariants.d.mts +0 -9
  29. package/dist/lib/classRegistry.d.mts +0 -12
  30. package/dist/lib/deepFreeze.d.mts +0 -8
  31. package/dist/lib/index.d.mts +0 -18
  32. package/dist/lib/takeWhile.d.mts +0 -8
  33. package/dist/lib/unChecked.d.mts +0 -9
  34. package/dist/tests/Contract.test.d.mts +0 -7
  35. package/dist/tests/Stack.test.d.mts +0 -7
  36. package/dist/tests/assert.test.d.mts +0 -7
  37. package/dist/tests/deepFreeze.test.d.mts +0 -7
  38. package/dist/tests/demands.test.d.mts +0 -7
  39. package/dist/tests/ensures.test.d.mts +0 -7
  40. package/dist/tests/factoryPattern.test.d.mts +0 -7
  41. package/dist/tests/iff.test.d.mts +0 -7
  42. package/dist/tests/implies.test.d.mts +0 -7
  43. package/dist/tests/invariant.test.d.mts +0 -7
  44. package/dist/tests/public-properties.test.d.mts +0 -7
  45. package/dist/tests/rescue.test.d.mts +0 -7
  46. package/dist/tests/within.test.d.mts +0 -7
package/README.md CHANGED
@@ -8,17 +8,21 @@
8
8
 
9
9
  - [Introduction](#introduction)
10
10
  - [Library Installation](#library-installation)
11
+ - [Node.js version](#nodejs-version)
12
+ - [Development](#development)
11
13
  - [Usage](#usage)
12
14
  - [Checked Mode](#checked-mode)
13
15
  - [Assertions](#assertions)
14
16
  - [Implies](#implies)
15
17
  - [Iff](#iff)
18
+ - [Contracts are Hoare triples](#contracts-are-hoare-triples)
19
+ - [Contract failures](#contract-failures)
16
20
  - [Encapsulation](#encapsulation)
17
21
  - [Invariants](#invariants)
18
22
  - [Demands](#demands)
19
23
  - [Ensures](#ensures)
20
- - [Within](#within)
21
24
  - [Rescue](#rescue)
25
+ - [Standard Schema](#standard-schema)
22
26
  - [The order of assertions](#the-order-of-assertions)
23
27
  - [Further Reading](#further-reading)
24
28
 
@@ -63,183 +67,134 @@ Via [skypack.dev](https://www.skypack.dev/):
63
67
 
64
68
  `<script type="module" src="https://cdn.skypack.dev/@final-hill/decorator-contracts"></script>`
65
69
 
66
- ## Usage
70
+ ## Node.js version
67
71
 
68
- After installation the library can be used as such:
72
+ This library requires **Node.js 26 or later**, as declared in `engines.node`. It relies on decorator metadata and targets ES2024, so an older runtime will fail at class definition rather than at an obvious call site.
69
73
 
70
- ```typescript
71
- import {Contract, Contracted, invariant, checkedMode} from '@final-hill/decorator-contracts';
74
+ ## Development
72
75
 
73
- interface StackType<T> {
74
- readonly limit: number;
75
- readonly size: number;
76
- clear(): void;
77
- isEmpty(): boolean;
78
- isFull(): boolean;
79
- pop(): T;
80
- push(item: T): void;
81
- top(): T;
82
- }
76
+ A [development container](https://containers.dev/) is provided, pinned to the same Node version CI uses:
83
77
 
84
- const stackContract = new Contract<StackType<any>>({
85
- [checkedMode]: process.env.NODE_ENV === 'development',
86
- [invariant](self) {
87
- return self.isEmpty() == (self.size == 0) &&
88
- self.isFull() == (self.size == self.limit) &&
89
- self.size >= 0 && self.size <= self.limit;
90
- },
91
- pop: {
92
- demands(self) { return !self.isEmpty(); },
93
- ensures(self,old) {
94
- return !self.isFull() &&
95
- self.size == old.size - 1;
96
- }
97
- },
98
- push: {
99
- demands(self){ return !self.isFull(); },
100
- ensures(self, old, item) {
101
- return !self.isEmpty() &&
102
- self.top() === item &&
103
- self.size === old.size + 1;
104
- }
105
- },
106
- top: {
107
- demands(self) {
108
- return !self.isEmpty();
109
- }
110
- }
111
- });
78
+ ```bash
79
+ # open the repository in the container, then
80
+ npm ci # installed automatically on create
81
+ npm run build
82
+ npm test
83
+ ```
112
84
 
113
- @Contracted(stackContract)
114
- class Stack<T> implements StackType<T> {
115
- #implementation: T[] = [];
116
- #size = 0;
117
- #limit: number;
85
+ `npm ci` honours the lockfile and fails if it disagrees with `package.json`, which is what CI runs. Running `npm install` locally can rewrite the lockfile and is the usual cause of a build that passes locally and fails in CI.
118
86
 
119
- constructor(limit: number) {
120
- this.#limit = limit;
121
- }
87
+ | Script | Purpose |
88
+ | --- | --- |
89
+ | `npm run lint` | Lint, failing on warnings; does not modify files |
90
+ | `npm run lint:fix` | Lint and autofix |
91
+ | `npm run typecheck` | Type-check the library and the test suite |
92
+ | `npm test` | Type-check, then run the tests |
93
+ | `npm run test:coverage` | Run the tests with coverage, writing `coverage/lcov.info` |
122
94
 
123
- clear(): void {
124
- this.#implementation = [];
125
- this.#size = 0;
126
- }
95
+ The test suite imports the package by name, so it exercises the built `dist/` output rather than the sources. `npm test` builds first for that reason; running a single test file directly requires an existing `dist/`.
127
96
 
128
- isEmpty(): boolean {
129
- return this.#implementation.length == 0;
130
- }
97
+ ## Usage
131
98
 
132
- isFull(): boolean {
133
- return this.#implementation.length == this.limit;
134
- }
99
+ After installation, use the decorators directly on your class methods and properties. All contracted classes must extend `Contracted` and be instantiated using the static `.new()` method.
135
100
 
136
- get limit() {
137
- return this.#limit;
138
- }
101
+ ```typescript
102
+ import { Contracted, invariant, demands, ensures } from '@final-hill/decorator-contracts';
139
103
 
140
- pop(): T {
141
- this.#size--;
104
+ @invariant((self: Stack<any>) =>
105
+ self.isEmpty() == (self.size == 0) &&
106
+ self.isFull() == (self.size == self.limit) &&
107
+ self.size >= 0 && self.size <= self.limit
108
+ )
109
+ class Stack<T> extends Contracted {
110
+ private _implementation: T[] = [];
111
+ private _size = 0;
112
+ private _limit: number;
142
113
 
143
- return this.#implementation.pop()!;
114
+ constructor(limit: number) {
115
+ super();
116
+ this._limit = limit;
144
117
  }
145
118
 
146
- push(item: T): void {
147
- this.#size++;
148
- this.#implementation.push(item);
149
- }
119
+ get limit() { return this._limit; }
120
+ get size() { return this._size; }
150
121
 
151
- get size(): number {
152
- return this.#size;
122
+ clear(): void {
123
+ this._implementation = [];
124
+ this._size = 0;
153
125
  }
154
126
 
155
- top(): T {
156
- return this.#implementation.at(-1);
127
+ isEmpty(): boolean { return this._implementation.length == 0; }
128
+ isFull(): boolean { return this._implementation.length == this.limit; }
129
+
130
+ @demands((self: Stack<any>) => !self.isEmpty())
131
+ @ensures((self: Stack<any>, _args, old: Stack<any>) =>
132
+ !self.isFull() && self.size == old.size - 1)
133
+ pop(): T {
134
+ this._size--;
135
+ return this._implementation.pop()!;
157
136
  }
158
- }
159
- ```
160
137
 
161
- A contract specifies the semantics of a class and is defined independently from it
162
- the same way that an interface is. Its has the following form:
163
-
164
- ```ts
165
- const fooContract = new Contract<Foo>({
166
- [checkedMode]: true,
167
- [invariant](self: Foo) { return self instanceof Foo },
168
- methodName: {
169
- demands(self: Foo, arg1, arg2, argN) { return true },
170
- ensures(self: Foo, old: Foo, arg1, arg2, argN){ return true }
171
- rescue(self, error, args, retry) {
172
- console.error(`Error with given arguments ${JSON.stringify(args)}`)
173
- console.error(error)
174
- console.log('Attempting to retry')
175
- self.value = 7
176
- retry(...args)
177
- }
178
- },
179
- accessorName: {
180
- ...
138
+ @demands((self: Stack<any>) => !self.isFull())
139
+ @ensures((self, [item], old: Stack<any>) =>
140
+ !self.isEmpty() &&
141
+ self.top === item &&
142
+ self.size === old.size + 1
143
+ )
144
+ push(item: T): void {
145
+ this._size++;
146
+ this._implementation.push(item);
181
147
  }
182
- })
183
148
 
184
- const subContract = new Contract<Sub>({
185
- [extend]: fooContract,
186
- methodName: {
187
- demands(self: Foo){ return true }
149
+ get top(): T | undefined {
150
+ return this._implementation.at(-1);
188
151
  }
189
- })
152
+ }
153
+
154
+ const stack = Stack.new(3);
155
+ stack.push(1);
156
+ stack.push(2);
157
+ stack.pop();
190
158
  ```
191
159
 
192
- ## Checked Mode
160
+ ## Instantiation: Using the Static `.new(...)` Method
193
161
 
194
- A contract can be enabled or disabled with the `checkedMode` property.
162
+ Because this library uses JavaScript `Proxy` to enforce contracts, you **must** instantiate all classes that extend `Contracted` using the static `.new(...)` method (not with `new MyClass(...)`).
195
163
 
196
- ```ts
197
- const stackContract = new Contract<StackType<any>>({
198
- [checkedMode]: true,
199
- ...
200
- })
201
- ```
164
+ This is required so that the instance is wrapped in a Proxy and invariants are asserted immediately after construction. Direct use of the `new` keyword will throw an error.
202
165
 
203
- During development and testing you will want to use checked mode. This will
204
- enable all assertion checks. In production all assertion checks become
205
- no-ops for run-time efficiency. As the number of contract definitions can
206
- be numerous, using the appropriate mode becomes increasingly important.
166
+ ## Checked Mode
207
167
 
208
- You are not prevented from mixing modes in the event you desire to maintain
209
- a number of checks in a production environment.
168
+ Checked Mode controls whether contract checking (invariants, demands, ensures, and rescue) is enabled or disabled at runtime. This feature allows you to turn off contract enforcement in production environments for maximum performance, while keeping it enabled during development and testing to catch bugs and contract violations early.
210
169
 
211
- This property is optional and defaults to `true`
170
+ Checked Mode is a coarse switch over the whole library, not a re-entrancy mechanism. When it is disabled, contract evaluation is skipped entirely and external encapsulation is not enforced either, so an instance behaves like a plain object.
212
171
 
213
- One approach you could use to manage this is the `env-cmd` package. Details can be [found here](https://www.digitalocean.com/community/tutorials/nodejs-take-command-with-env-cmd). Usage may look like:
172
+ By default, Checked Mode is enabled. You can control it via the static `[checkedMode]` symbol property of Contracted:
214
173
 
215
- ```ts
216
- const fooContract = new Contract<Foo>({
217
- [checkedMode]: !process.env.IS_PRODUCTION,
218
- ...
219
- })
174
+ ```typescript
175
+ Contracted[checkedMode] = false; // Disable Checked Mode
220
176
  ```
221
177
 
222
- Note: `checkedMode` is set to `false` during evaluation of the assertions and `rescue`. This prevents non-termination when your contract uses other class features during its evaluation. This means you should
223
- avoid mutating state in your assertions, especially the `invariant`, in order to prevent your object
224
- from being put in an invalid state.
178
+ One approach to managing this is to leverage environment variables. For example, you can interrogate `NODE_ENV` to determine whether to enable or disable Checked Mode:
179
+
180
+ ```typescript
181
+ Contracted[checkedMode] = process.env.NODE_ENV === 'development'
182
+ ```
225
183
 
226
184
  ## Assertions
227
185
 
228
- Assertions are a fundamental tool for enforcing correctness in an implementation.
229
- They are used inline to express a condition that must evaluate to true at a
230
- particular point of execution.
186
+ Use the `assert` function for inline assertions:
231
187
 
232
188
  ```typescript
233
- import {assert} from '@final-hill/decorator-contracts';
189
+ import { assert } from '@final-hill/decorator-contracts';
234
190
 
235
191
  function avg(xs: number[]): number {
236
- assert(xs.length > 0, 'The list can not be empty')
237
-
238
- return xs.reduce((sum, next) => sum + next) / xs.length
192
+ assert(xs.length > 0, 'The list can not be empty');
193
+ return xs.reduce((sum, next) => sum + next) / xs.length;
239
194
  }
240
195
  ```
241
196
 
242
- If you are using TypeScript `assert` will also assert the type of the condition:
197
+ If you are using TypeScript, `assert` will also assert the type of the condition:
243
198
 
244
199
  ```typescript
245
200
  let str: any = 'foo';
@@ -253,561 +208,641 @@ str.toUpperCase(); // str is now a string
253
208
 
254
209
  **`assert` should not be used for validating arguments**
255
210
 
256
- Use the `demands` declaration for this purpose.
211
+ Use the `@demands` decorator for this purpose.
257
212
 
258
213
  ## Implies
259
214
 
260
- When defining predicates it is a common use case to encode
261
- [material implication](https://en.wikipedia.org/wiki/Material_conditional).
215
+ When defining predicates it is a common use case to encode [material implication](https://en.wikipedia.org/wiki/Material_conditional):
262
216
 
263
- The truth table is as follows:
217
+ ```typescript
218
+ import { implies } from '@final-hill/decorator-contracts';
264
219
 
265
- | *p* | *q* | *p* &rarr; *q* |
266
- |-----|-----|----------------|
267
- | T | T | T |
268
- | T | F | F |
269
- | F | T | T |
270
- | F | F | T |
220
+ implies(weather.isSunny, person.visitsBeach);
221
+ // Logically equivalent to: !weather.isSunny || person.visitsBeach
222
+ ```
271
223
 
272
- An example of usage is the encoding of `sunny weather is a precondition of visiting the beach`:
224
+ Both functions always return a `boolean`, even when an operand is not a boolean: a truthy object is coerced rather than passed through. Inside a contract this is redundant, because `@demands` and friends already require a literal `true` or `false` and name the offending feature.
273
225
 
274
- ```ts
275
- implies(
276
- weather.isSunny,
277
- person.visitsBeach
278
- )
226
+ ## Iff
227
+
228
+ When defining predicates it is a common use case to encode [if and only if](https://en.wikipedia.org/wiki/Logical_biconditional):
229
+
230
+ ```typescript
231
+ import { iff } from '@final-hill/decorator-contracts';
232
+
233
+ iff(person.hasTicket, person.ridesTrain);
234
+ // Logically equivalent to: implies(p, q) && implies(q, p)
279
235
  ```
280
236
 
281
- This is logically equivalent to: `!p || q`
237
+ Both functions always return a `boolean`, even when an operand is not a boolean: a truthy object is coerced rather than passed through. Inside a contract this is redundant, because `@demands` and friends already require a literal `true` or `false` and name the offending feature.
282
238
 
283
- ## Iff
239
+ ## Contracts are Hoare triples
284
240
 
285
- When defining predicates it is a common use case to encode [if and only if](https://en.wikipedia.org/wiki/Logical_biconditional).
286
- Also referred to as a biconditional.
241
+ A contract describes the **observable boundary** of a feature, in the sense of a [Hoare triple](https://en.wikipedia.org/wiki/Hoare_logic):
287
242
 
288
- The truth table is as follows:
243
+ $$\{P\}\; C\; \{Q\}$$
289
244
 
290
- | *p* | *q* | *p* &harr; *q* |
291
- |-----|-----|----------------|
292
- | T | T | T |
293
- | T | F | F |
294
- | F | T | F |
295
- | F | F | T |
245
+ `@demands` is $P$, `@ensures` is $Q$, and the feature body is $C$. Nothing inside $C$ is constrained: a body may assign to its own properties, including public ones, and may call its own features without re-entering the contracts. Correctness is the obligation that $P$ and $Q$ hold at the boundary, with the invariant additionally holding on entry and exit.
296
246
 
297
- An example of usage is the encoding of `You can ride the train if and only if you have a ticket`:
247
+ This is why there is no need to police what a body does to itself. If a body leaves the object in an invalid state, `@invariant` rejects it on exit. If it produces the wrong result, `@ensures` rejects it. Attempting to enforce correctness *inside* $C$ as well would mean the same guarantee twice, at the cost of forbidding legitimate intermediate states.
298
248
 
299
- ```ts
300
- iff(
301
- person.hasTicket,
302
- person.ridesTrain
303
- )
249
+ ## Contract failures
250
+
251
+ A failed contract throws an `AssertionError`. Its `name` is `AssertionError` regardless of how the bundle was minified, and its message names the contract, the feature, and the predicate(s) that failed:
252
+
253
+ ```text
254
+ @ensures failed for Account.withdraw (1 of 2 predicates unsatisfied: predicate #2: (self,[amount],old)=>self.balance===old.balance-amount). A postcondition was not satisfied after the feature ran.
304
255
  ```
305
256
 
306
- This is logically equivalent to: `implies(p,q) && implies(q,p)`
257
+ The predicate text is whatever the predicate's `toString()` returns, which is minified in a bundled build. The structured `violation` below is the reliable way to identify a failure.
307
258
 
308
- ## Encapsulation
259
+ The error also carries a `violation` property so callers can react without parsing the message:
260
+
261
+ ```typescript
262
+ import { AssertionError } from '@final-hill/decorator-contracts';
309
263
 
310
- To guarantee invariants remain valid for classes, public property definitions are forbidden.
311
- All interactions with a contracted class must be done through a method or accessor.
312
- This prevents modification of object state outside of the contract system. Private
313
- properties with accessors should be used instead. Example:
314
-
315
- ```ts
316
- @Contracted(pointContract)
317
- class Point2D {
318
- accessor x: number
319
- accessor y: number
320
-
321
- constructor(x: number, y: number) {
322
- super()
323
- this.x = x
324
- this.y = y
264
+ try {
265
+ account.withdraw({ amount: 500 });
266
+ } catch (error) {
267
+ if (error instanceof AssertionError && error.violation?.contract === '@demands') {
268
+ // a precondition failed; the feature was never entered
325
269
  }
326
270
  }
327
271
  ```
328
272
 
329
- ## Invariants
330
-
331
- A class is not just a collection of methods it has semantics that
332
- bind them together and the `invariant` declaration describes and enforces these relationships.
333
- This assertion is checked after the associated class is constructed, before and
334
- after every method execution, and before and after every accessor usage (get/set).
335
- If this evaluates to false during class usage an `AssertionError` will be thrown in the library code
336
- as it indicates a bug in the class where it has the [opportunity](#rescue) to handle it.
337
- True assertions do not throw an error. An example of this is given below using a Stack:
273
+ `violation` has the shape:
338
274
 
339
275
  ```typescript
340
- const stackContract = new Contract<StackType<any>>({
341
- [invariant](self) {
342
- return self.isEmpty() == (self.size == 0) &&
343
- self.isFull() == (self.size == self.limit) &&
344
- self.size >= 0 && self.size <= self.limit
345
- }
346
- })
347
-
348
- @Contracted(stackContract)
349
- class Stack<T> implements StackType<T> {
350
- ...
276
+ interface ContractViolation {
277
+ contract: '@invariant' | '@demands' | '@ensures';
278
+ className: string;
279
+ feature?: string; // absent for `@invariant`
280
+ failedIndices: number[]; // positions in the contract's composition list
281
+ predicates: string[]; // source text, aligned with `failedIndices`
351
282
  }
352
283
  ```
353
284
 
354
- With the above invariant any attempt to construct an invalid stack will fail:
285
+ `@demands` is OR-composed, so a failure lists **every** arm — any of them could have permitted the call. `@ensures` and `@invariant` are AND-composed, so a failure lists only the predicates that broke.
286
+
287
+ An `AssertionError` thrown by `assert()` itself has no `violation`.
288
+
289
+ ## Encapsulation
290
+
291
+ Encapsulation governs the **external surface**. Public property assignment is forbidden from outside a contracted class, so a caller cannot mutate state without a postcondition to catch it. All interactions must go through a method or getter/setter, and only properties starting with `_` (conventionally private) can be assigned to after construction.
355
292
 
356
293
  ```typescript
357
- let myStack = new Stack(-1)
294
+ class Example extends Contracted {
295
+ _private = 1; // Allowed
296
+ publicProp = 2; // Not allowed from outside
297
+ }
358
298
  ```
359
299
 
360
- Additionally, attempting to pop an item from an empty stack would be
361
- nonsensical according to the invariant therefore the following will
362
- throw an `AssertionError` after `pop()` is executed due to the size being negative:
300
+ The boundary begins *after* construction. A constructor runs before the instance is proxied, so its assignments — to public properties included — are unrestricted. That is deliberate: field initialisers and `Object.assign(this, ...)` are ordinary ways to establish initial state, and the invariant evaluated at the end of `Contracted.new()` is what validates the result.
363
301
 
364
302
  ```typescript
365
- let myStack = new Stack(3)
366
- let item = myStack.pop();
303
+ class Example extends Contracted {
304
+ publicProp = 2; // allowed: field initialiser
305
+ constructor() {
306
+ super();
307
+ this.publicProp = 3; // allowed: still inside construction
308
+ }
309
+ }
367
310
  ```
368
311
 
369
- A contract can be extended and declare an invariant of its own.
312
+ An external write to a public property raises a `TypeError`:
370
313
 
371
314
  ```typescript
372
- const baseContract = new Contract<Base>({
373
- [invariant](self) { return 0 <= self.value && self.value <= 10 }
374
- })
315
+ const example = Example.new();
375
316
 
376
- @Contracted(baseContract)
377
- class Base { ... }
317
+ example.publicProp = 3; // TypeError
318
+ ```
378
319
 
379
- const subContract = new Contract<Sub>({
380
- [extend]: baseContract,
381
- [invariant](self){ return 10 <= self.value && self.value <= 20 }
382
- })
320
+ A feature body is $C$ and is **not** subject to this rule. It runs against the instance directly, so internal state — public or private — is its own business:
321
+
322
+ ```typescript
323
+ class Example extends Contracted {
324
+ publicProp = 1;
383
325
 
384
- @Contracted(subContract)
385
- class Sub extends Base { ... }
326
+ update(): void {
327
+ this.publicProp = 2; // allowed; `@ensures` and `@invariant` are the guarantee
328
+ }
329
+ }
386
330
  ```
387
331
 
388
- The result is that the invariant of `Sub` is strengthened, meaning that the assertions are and-ed together:
332
+ A method calling another method of the same instance likewise does not start a second contract lifecycle. The enclosing invocation owns the assertions, so the invariant is evaluated once on entry and once on exit regardless of how many internal accesses the body performs.
389
333
 
390
- `(0 <= self.value && self.value <= 10) && (10 <= self.value && self.value <= 20)`
334
+ One consequence: a body that leaks `this` outward — passing it to a callback, storing it in a module-level variable, or returning it — hands out a reference that bypasses the traps. Do not do that; expose an explicit API instead.
391
335
 
392
- Effectively meaning that `self.value` can only be `10`
336
+ ### Deletion
393
337
 
394
- Only public features have to honor the `invariant`. During execution it can be broken as long as it is restored before exiting.
338
+ Deletion is an external mutation, so it follows exactly the same rule as assignment: `_`-prefixed properties may be deleted, public properties may not, and the invariant is evaluated around the deletion.
395
339
 
396
- ## Demands
340
+ | Expression | Result |
341
+ | --- | --- |
342
+ | `delete example._private` | allowed |
343
+ | `delete example.publicProp` | `TypeError` |
344
+ | `delete example.nonexistent` | `TypeError` (the name is not `_`-prefixed) |
397
345
 
398
- The `demands` declaration describes and enforces an assertion that must be true
399
- before its associated feature can execute. In other words before a client
400
- of your class can execute a method or accessor the defined precondition
401
- must first be met or an error will be raised [to the caller](#the-order-of-assertions).
402
- This is because a failure to meet the precondition indicates a bug in the caller's code
403
- and not yours.
404
-
405
- ```typescript
406
- const stackContract = new Contract<StackType<any>>({
407
- ...
408
- pop: {
409
- demands: self => !self.isEmpty()
410
- },
411
- push: {
412
- demands: self => !self.isFull()
413
- }
414
- })
346
+ The last row surprises people, but it is the same rule `set` applies to an assignment of a property that does not exist: the restriction is on the *name*, not on whether the property is present. Once checked mode is disabled the proxy steps aside and `delete` behaves as it does on a plain object.
415
347
 
416
- @Contracted(stackContract)
417
- class Stack<T> implements StackType<T> {
418
- ...
419
- pop(): T {
420
- return this.#implementation.pop();
421
- }
422
- push(item: T): void {
423
- this.#implementation.push(item);
348
+ `Object.defineProperty`, `Reflect.defineProperty`, and `Reflect.deleteProperty` operate below the proxy and are not intercepted.
349
+
350
+ ## Asynchronous features
351
+
352
+ A feature declared `async` is fully contracted. Because an `async` body returns its promise before a single line of it has run, the exit boundary follows the value: `@ensures` and the exit `@invariant` are evaluated after the promise settles, against the state the body actually reached.
353
+
354
+ ```typescript
355
+ class Account extends Contracted {
356
+ protected _balance = 0;
357
+ public _ledger!: Ledger; // a collaborator the caller sets
358
+ get balance() { return this._balance; }
359
+
360
+ @demands((self, [amount]: [number]) => self.balance + amount >= 0)
361
+ @ensures((self, [amount]: [number], old) => self.balance === old.balance + amount)
362
+ async deposit(amount: number): Promise<void> {
363
+ await this._ledger.record(amount); // suspension happens here
364
+ this._balance += amount; // observed by @ensures
424
365
  }
425
366
  }
426
367
  ```
427
368
 
428
- In the above example the precondition of executing `pop`
429
- on a stack is that it is not empty. If this assertion fails
430
- an `AssertionError` is raised.
369
+ The lifecycle is unchanged in order and in count: `@invariant` -> `@demands` -> body -> `@ensures` -> `@invariant`, with the invariant evaluated twice per call. Only the *position* of the exit checks differs, because the body has not finished until the promise settles. A `@rescue` observes rejections as it observes synchronous throws, and `retry` restarts the lifecycle for an asynchronous feature too.
370
+
371
+ ### Failure is delivered as a rejection
372
+
373
+ A contract violation on an `async` feature reaches the caller as a rejected promise, never as a synchronous throw — the same way the feature's own errors reach it. Adding a contract to a feature must not change how its failures are observed.
374
+
375
+ ```typescript
376
+ await assert.rejects(() => account.deposit(-5)); // AssertionError, not a sync throw
377
+ ```
378
+
379
+ This follows from substitutability. `() => T` and `() => Promise<T>` are mutually non-assignable in TypeScript, so neither is a subtype of the other and no sync/async conversion is implied. What must hold is the observable surface: a caller of the undecorated feature receives a promise that may reject, so a caller of the contracted feature must receive the same.
431
380
 
432
- Static features, including the constructor, cannot be assigned a `demands`
433
- assertion. In the future this may be enabled for non-constructor static methods
434
- but the implications are not clear at present.
381
+ ### A synchronous feature must not return a promise
435
382
 
436
- If a class feature is overridden then the `demands` assertion still applies:
383
+ Contracts on a feature that is not declared `async` are evaluated when its body returns. A body that defers its work through a promise would therefore be checked before it has done anything, so this is rejected:
437
384
 
438
385
  ```typescript
439
- class MyStack<T> extends Stack<T> {
440
- override pop(): { ... }
386
+ @ensures(...)
387
+ thenable(): Promise<void> { // AssertionError: not declared 'async'
388
+ return (async () => { await work(); this._value++; })();
441
389
  }
390
+ ```
391
+
392
+ Declare the feature `async` instead. Awaiting arbitrary thenables was rejected as a rule because it would make the `async` keyword optional while silently changing when failures are reported: a plain function cannot return pending work *and* raise the resulting failure itself.
442
393
 
443
- ...
444
- let myStack = new MyStack()
394
+ ### Generators
445
395
 
446
- myStack.pop() // throws
396
+ A generator has a contract boundary per **step**, not one per call. Calling the feature runs nothing; each `next()` runs the body from where it was suspended up to the following `yield`. When `next()` returns the segment has finished and the instance holds the state it will be observed with, so the contracts bracket each step:
397
+
398
+ ```
399
+ call -> @invariant, @demands the call arguments are P
400
+ next() -> @invariant entry of the step
401
+ segment -> body up to the next yield
402
+ next() -> @ensures, @invariant the yielded value and the new state are Q
447
403
  ```
448
404
 
449
- A contract can be extended and that sub contract can declare a `demands` assertion of its own
450
- for the same feature:
405
+ This is the same sandwich shown above, applied once per step. A yield is the observable delivery of a traversal, which is what `@ensures` describes, so every yielded value must satisfy it:
451
406
 
452
- ```ts
453
- const baseContract = new Contract<Base>({
454
- someMethod: {
455
- demands(){ ... }
456
- }
457
- })
407
+ ```typescript
408
+ class Counter extends Contracted {
409
+ protected _count = 0;
458
410
 
459
- const subContract = new Contract<Sub>({
460
- [extend]: baseContract,
461
- someMethod: {
462
- demands(){ ... }
411
+ @ensures((self, [_value]: [number], old) => self._count === old._count + 1)
412
+ *tick(): Generator<number> {
413
+ this._count++; yield this._count; // each step is checked
414
+ this._count++; yield this._count;
463
415
  }
464
- })
416
+ }
465
417
  ```
466
418
 
467
- This subcontracted `demands` declaration can not strengthen the `demands` of the base contract.
468
- What this means is that the new precondition will be or-ed with its ancestors. If any `demand` is true
469
- then the obligation is considered fulfilled by the user of the feature.
419
+ The `old` snapshot is per step, not per traversal: it describes the state the segment is about to change. A `return` value is not covered by `@ensures`, because nothing is yielded.
470
420
 
471
- ```ts
472
- const baseContract = new Contract<Base>({
473
- someMethod: {
474
- demands(_self, x: number) { return 0 <= x && x <= 10 }
475
- }
476
- })
421
+ #### Why the invariant runs on every resume
477
422
 
478
- @Contracted(baseContract)
479
- class Base {
480
- someMethod(x: number) { ... }
481
- }
423
+ A suspended generator's instance is publicly reachable, so another feature can be called on it between yields. Checking the invariant only at completion would leave the object knowingly invalid for the whole traversal, and would never check at all if the iterator were abandoned or only partially drained. Evaluating it on each resume is what keeps the guarantee every other feature already has: no public interaction leaves the object invalid.
482
424
 
483
- const subContract = new Contract<Sub>({
484
- [extend]: baseContract,
485
- someMethod: {
486
- demands(_self, x: number){ return -10 <= x && x <= 20 }
487
- }
488
- })
425
+ ```typescript
426
+ const iterator = ledger.payments();
427
+ iterator.next(); // segment 1 checked on exit
428
+ ledger.audit(); // a public call, and it sees a valid object
429
+ ```
489
430
 
490
- @Contracted(subContract)
491
- class Sub extends Base {
492
- override someMethod(x: number){ ... }
493
- }
431
+ #### `@demands` describes the call
432
+
433
+ `@demands` runs once, on the first step: there is one call, so there is one precondition. A later step may also be *given* a value through `next(value)`, which becomes the value of the preceding `yield` expression and is not an argument of the call; that input is checked as a precondition **when it is present**. `for...of` iterates with `next()` and injects nothing, so it never re-enters the precondition with `undefined`:
434
+
435
+ ```typescript
436
+ @demands((_self, [count]: [number]) => count > 0)
437
+ *gen(count: number): Generator<number> { /* ... */ }
438
+
439
+ for (const value of obj.gen(3)) { /* works: no value is injected */ }
494
440
  ```
495
441
 
496
- In the above example the precondition of `Sub.prototype.someMethod` is:
442
+ #### `@rescue` covers the traversal
497
443
 
498
- `(-10 <= x && x <= 20) || (0 <= x && x <= 10)`
444
+ A generator that has already been consumed cannot be resumed from the beginning, so `retry` restarts the traversal, rerunning the body exactly as it does for an ordinary feature. A throw escaping a step is what the handler observes.
499
445
 
500
- ## Ensures
446
+ ## Note on Private Fields and Accessors
501
447
 
502
- The `ensures` declaration describes and enforces an assertion that must be true *after* its associated feature executes. In other words after a client of your class executes a method or accessor the defined post-condition must be met or an error will be [raised to the library author](#the-order-of-assertions). This indicates a bug in the library code and not in the
503
- caller. The library code then has the [opportunity](#rescue) to capture and fix this error if it's expected.
448
+ Due to the use of JavaScript `Proxy` in the implementation of this library, native `#private` fields and the `accessor` keyword are **not supported**. Instead, use conventional private fields (e.g., `_private`) and define explicit getter/setter pairs for encapsulation:
504
449
 
505
450
  ```typescript
506
- const stackContract<Stack<any>> = new Contract({
507
- push: {
508
- ensures(self){ return !self.isEmpty() }
509
- }
510
- })
511
-
512
- @Contracted(stackContract)
513
- class Stack<T> {
514
- ...
515
- push(value: T) {
516
- ...
517
- this.#implementation.push(value);
518
- }
451
+ class Example extends Contracted {
452
+ private _value = 0;
453
+ get value() { return this._value; }
454
+ set value(v: number) { this._value = v; }
519
455
  }
520
456
  ```
521
457
 
522
- In the above example the post-condition of executing push on a stack is that it is not empty. If this assertion fails an `AssertionError` is raised.
458
+ Do **not** use:
523
459
 
524
- Static features, including the constructor, cannot be assigned an `ensures` declaration. In the future this may be enabled for non-constructor static methods but the implications are not clear at present.
460
+ - `#privateField` syntax
461
+ - `accessor foo` syntax
525
462
 
526
- In addition to the `self` argument there is also an `old` argument which provides access to the values of any getters of the instance before its associated member was executed.
463
+ These will not work correctly with the contract enforcement provided by this library.
527
464
 
528
- ```typescript
529
- const stackContract = new Contract<Stack<any>>({
530
- push: {
531
- ensures(self, old){ return self.size == old.size + 1 }
532
- },
533
- pop: {
534
- ensures(self, old){ return self.size == old.size - 1 }
535
- }
536
- })
465
+ ## Invariants
537
466
 
538
- @Contracted(stackContract)
539
- class Stack<T> {
540
- ...
541
- push(value: T) {
542
- this.#implementation.push(value);
543
- }
544
- pop(): T {
545
- return this.#implementation.pop();
546
- }
467
+ Use the `@invariant` decorator on your class to enforce relationships between properties and methods. The invariant is checked after construction, before and after every method execution, and before and after every get/set usage.
468
+
469
+ ```typescript
470
+ @invariant(self => self.value >= 0)
471
+ class Foo extends Contracted {
472
+ protected _value = 0;
473
+ get value() { return this._value; }
474
+ set value(v: number) { this._value = v; }
475
+
476
+ inc(): void { this.value++; }
477
+ dec(): void { this.value--; }
547
478
  }
548
479
  ```
549
480
 
550
- If a class feature is overridden then the `ensures` assertion still applies:
481
+ ### Contract predicates must return a boolean
482
+
483
+ `@invariant`, `@demands`, and `@ensures` predicates must return `true` or `false`. The result is not coerced: a non-boolean result raises an `AssertionError` naming the contract, the feature, and which predicate in the composition failed.
551
484
 
552
485
  ```typescript
553
- class MyStack<T> extends Stack<T> {
554
- override push(value: T): { ... }
555
- }
486
+ @demands(() => Promise.resolve(true)) // AssertionError: returned a Promise
487
+ ```
556
488
 
557
- ...
558
- let myStack = new MyStack()
489
+ This is deliberate. A `Promise` is always truthy, so coercing the result would silently treat an accidentally asynchronous predicate — one that has not actually checked anything yet — as a satisfied contract. Failing closed is the only safe option, and the message points at the mistake.
559
490
 
560
- myStack.push()
561
- myStack.isEmpty() == false;
491
+ Asynchronous *predicates* are therefore not supported: a predicate that needs the result of an asynchronous operation cannot be expressed as a boolean.
492
+
493
+ Asynchronous *features* are supported; see [Asynchronous features](#asynchronous-features).
494
+
495
+ ### Contract predicates may not change the instance
496
+
497
+ A predicate answers a question, so it cannot change the state it is asked about. `@invariant`, `@demands`, and `@ensures` receive a **read-only view** of the instance: assigning, deleting, or defining a property raises a `TypeError` naming the property.
498
+
499
+ ```typescript
500
+ @demands((self) => { self._value = 0; return true; })
501
+ // TypeError: A contract predicate may not assign '_value'.
562
502
  ```
563
503
 
564
- The remaining arguments of `ensures` reflect the arguments of the associated feature.
504
+ This matters because a predicate runs *between* the entry and exit `@invariant`. A write inside a predicate can therefore hide a violation the invariant would otherwise have reported, turning a detectable bug into a silent one.
565
505
 
566
506
  ```typescript
567
- const baseContract = new Contract<Base>({
568
- someMethod: {
569
- ensures(_self, _old, x: number){ return 0 <= x && x <= 10 }
570
- }
507
+ @invariant((self) => {
508
+ self._value = 0; // would repair the state being checked
509
+ return self._value >= 0; // and then pass
571
510
  })
511
+ ```
572
512
 
573
- @Contracted(baseContract)
574
- class Base {
575
- someMethod(x: number) { ... }
576
- }
513
+ `@rescue` is deliberately **not** restricted. Restoring corrupted state is its purpose, so its handler receives the raw instance.
514
+
515
+ #### What is not blocked
516
+
517
+ The guard covers the instance's own surface. A mutation *through* a nested value still reaches the shared object:
518
+
519
+ ```typescript
520
+ @demands((self) => { self._items.push(item); return true; }) // not intercepted
577
521
  ```
578
522
 
579
- A contract can be extended and that sub contract can declare an `ensures` assertion of its own for the same feature:
523
+ Closing that would mean deep-wrapping every value a predicate reads, which changes object identity and would break legitimate comparisons such as `old.child === self.child`. The guarantee is therefore "a predicate cannot assign to the instance", which is the case that corrupts contract evaluation.
580
524
 
581
- ```ts
582
- const baseContract = new Contract<Base>({
583
- someMethod: {
584
- ensures(){ ... }
585
- }
586
- })
525
+ The feature body is unaffected: it still receives the instance itself and mutates freely. The view is scoped to the predicate call, which is why a scoped `Proxy` is used rather than `Object.freeze` — freezing is permanent, and would leave the body unable to change anything afterwards.
587
526
 
588
- const subContract = new Contract<Sub>({
589
- [extend]: baseContract,
590
- someMethod: {
591
- ensures(){ ... }
592
- }
593
- })
527
+ ### Subcontracting and Invariants
528
+
529
+ When subclassing, if a subclass defines its own `@invariant`, the resulting invariant is **strengthened**: the subclass invariant and the base class invariant are both enforced (they are logically AND-ed together). This means all invariants in the inheritance chain must hold for the object to be valid.
530
+
531
+ ```typescript
532
+ @invariant(self => self.value >= 0)
533
+ class Base extends Contracted {
534
+ // ...
535
+ }
536
+
537
+ @invariant(self => self.value <= 10)
538
+ class Sub extends Base {
539
+ // ...
540
+ }
541
+ // The effective invariant for Sub is: (self.value >= 0) && (self.value <= 10)
594
542
  ```
595
543
 
596
- This subcontracted `ensures` declaration cannot weaken the `ensures` of the base contract. What this means is that the new post-condition will be and-ed with its ancestors. If all of the `ensures` are true then the obligation is considered fulfilled by the author of the feature otherwise an `AssertionError` is raised.
544
+ ## Demands
545
+
546
+ Use the `@demands` decorator to specify preconditions for methods or get/set. If the condition fails, an error is thrown before the method executes.
597
547
 
598
548
  ```typescript
599
- const baseContract = new Contract<Base>({
600
- method: {
601
- ensures(_self, _old, x: number) { return 0 <= x && x <= 10 }
602
- }
603
- })
549
+ class Foo extends Contracted {
550
+ protected _value = 0;
551
+ get value() { return this._value; }
552
+ set value(v: number) { this._value = v; }
604
553
 
605
- @Contracted(baseContract)
606
- class Base {
607
- method(x: number){ ... }
554
+ @demands(self => self.value >= 0)
555
+ dec(): void { this.value--; }
608
556
  }
557
+ ```
609
558
 
610
- const subContract = new Contract<Sub>({
611
- [extend]: baseContract,
612
- method: {
613
- ensures(_self, _old, x: number){ return -10 <= x && x <= 20 }
614
- }
615
- })
559
+ ### Subcontracting and Demands
560
+
561
+ When subclassing, if a subclass defines its own `@demands` for a method, the resulting precondition is **weakened**: the subclass and base class demands are OR-ed together. The method can be called if **any** of the demands in the inheritance chain are satisfied.
562
+
563
+ ```typescript
564
+ class Base extends Contracted {
565
+ @demands((_self, [x]: [number]) => x >= 0)
566
+ foo(x: number) { /* ... */ }
567
+ }
616
568
 
617
- @Contracted(subContract)
618
569
  class Sub extends Base {
619
- method(x: number) { ... }
570
+ @demands((_self, [x]: [number]) => x === 42)
571
+ override foo(x: number) { /* ... */ }
620
572
  }
573
+ // The effective demand for Sub#foo is: (x >= 0) || (x === 42)
621
574
  ```
622
575
 
623
- In the above example the post-condition of `Sub.prototype.method` is:
576
+ A demand receives the **argument list**, so destructure it: `(_self, [x])`. Writing `(_self, x: number) => x >= 0` does not compile, because the second parameter is the array rather than the first argument.
624
577
 
625
- `(-10 <= x && x <= 20) && (0 <= x && x <= 10)`
578
+ ## Ensures
626
579
 
627
- Which effectively means that if the method returns `x === 10`
580
+ Use the `@ensures` decorator to specify postconditions for methods or get/set. If the condition fails, an error is thrown after the method executes.
628
581
 
629
- ## Within
582
+ ```typescript
583
+ class Foo extends Contracted {
584
+ protected _value = 0;
585
+ get value() { return this._value; }
586
+ set value(v: number) { this._value = v; }
630
587
 
631
- The `within` declaration provides a means of requiring the associated feature
632
- to complete execution within a time constraint.
588
+ @ensures(self => self.value >= 0)
589
+ dec(): void { this.value--; }
590
+ }
591
+ ```
592
+
593
+ ### The `old` instance
594
+
595
+ A postcondition receives `old`, a snapshot of the instance taken immediately before the feature ran. `old` inherits from the instance, so prototype getters and methods remain usable, and reading a prototype getter on `old` returns the historical value:
633
596
 
634
597
  ```typescript
635
- const timingContract = new Contract<Spinner>({
636
- spinLock: {
637
- within: 100
638
- }
639
- });
640
-
641
- @Contracted(timingContract)
642
- class Spinner {
643
- spinLock(delay: number) {
644
- const t1 = Date.now();
645
- while(Date.now() - t1 < delay) {
646
- continue;
647
- }
598
+ class Counter extends Contracted {
599
+ protected _n = 0;
600
+ get n() { return this._n; }
648
601
 
649
- return 'Okay';
650
- }
602
+ @ensures((self, _args, old) => self.n === old.n + 1)
603
+ inc(): void { this._n++; }
651
604
  }
605
+ ```
606
+
607
+ Own state is copied, so mutations made by the feature body are not visible through `old`. The copy is deep for the containers contracts routinely compare:
608
+
609
+ | Value | Behaviour in `old` |
610
+ | --- | --- |
611
+ | Primitives | copied |
612
+ | Arrays | cloned recursively |
613
+ | `Date` | cloned |
614
+ | `Map`, `Set` | cloned (keys and values recursively) |
615
+ | Plain objects | cloned recursively, including cycles |
616
+ | Class instances | **shared by reference** |
617
+ | Functions | **shared by reference** |
652
618
 
653
- new Ticker().spinLock(50) === 'Okay';
619
+ Class instances and functions are shared deliberately. They carry behaviour, so a structural copy would produce an object that is not a real instance of its class, and many cannot be cloned meaningfully at all. The consequence is that mutating a class instance held in a field *is* visible through `old`; if a postcondition depends on such an object's previous state, copy it explicitly in the predicate.
654
620
 
655
- new Ticker().spinLock(500) // throws "Timing constraint violated...";
621
+ Accessors are copied as descriptors rather than evaluated, so snapshotting never invokes a getter.
622
+
623
+ ### Subcontracting and Ensures
624
+
625
+ When subclassing, if a subclass defines its own `@ensures` for a method, the resulting postcondition is **strengthened**: the subclass and base class ensures are AND-ed together. The method's result must satisfy **all** ensures in the inheritance chain.
626
+
627
+ ```typescript
628
+ class Base extends Contracted {
629
+ @ensures((_self, [x]: [number]) => x >= 0)
630
+ foo(x: number) { /* ... */ }
631
+ }
632
+
633
+ class Sub extends Base {
634
+ @ensures((_self, [x]: [number]) => x <= 10)
635
+ override foo(x: number) { /* ... */ }
636
+ }
637
+ // The effective ensures for Sub#foo is: (x >= 0) && (x <= 10)
656
638
  ```
657
639
 
658
- Currently `within` only supports synchronous features. async feature support is planned for a future version
640
+ The signature is `(self, args, old)`: the argument list, then the snapshot of the instance from before the feature ran. Writing `(_self, _args, x: number) => x >= 0` does not compile — the third parameter is `old`, and comparing it to a number is always `false`.
659
641
 
660
642
  ## Rescue
661
643
 
662
- The `rescue` declaration enables a mechanism for providing **Robustness**.
663
- Robustness is the ability of an implementation to respond to situations
664
- not specified; in other words the ability to handle exceptions (pun intended).
665
- This declaration can be associated with class features. The intent of this
666
- is to restore any invariants of the class and optionally retry execution.
644
+ Use the `@rescue` decorator to handle exceptions thrown by a method, restore invariants, or retry execution:
667
645
 
668
646
  ```typescript
669
- const stackContract = new Contract<Stack<any>>({
670
- pop: {
671
- rescue(_self, error, _args, _retry) {
672
- console.log(error)
673
- }
674
- }
675
- })
647
+ import { rescue } from '@final-hill/decorator-contracts';
676
648
 
677
- @Contracted(stackContract)
678
- class Stack<T> {
679
- ...
680
- pop(): T {
681
- assert(!this.isEmpty(), 'You can not pop from an empty stack')
649
+ class Example extends Contracted {
650
+ private _value = 3;
651
+ get value() { return this._value; }
652
+ set value(v) { this._value = v; }
682
653
 
683
- return this.#implementation.pop()!
684
- }
685
- ...
654
+ @rescue(self => self.value = 5)
655
+ method1(): void { throw new Error('I am error'); }
686
656
  }
687
657
  ```
688
658
 
689
- In the above naive example if the `pop` method is called when the stack is
690
- empty an exception occurs. The `rescue` declaration intercepts this
691
- exception and handles it by simply logging the error. The exception is
692
- then raised to the caller.
693
-
694
- You also have the ability to retry the execution of the decorated
695
- feature from the beginning by calling the `retry` function. This provides
696
- a mechanism for [fault tolerance](https://en.wikipedia.org/wiki/Fault_tolerance).
697
- When `retry` is called the exception will no longer be raised to the caller of the original method.
698
- `retry` can only be called once per exception rescue in order to prevent unbounded
699
- recursion. An example of `retry` usage:
700
-
701
- ```ts
702
- const studentRepositoryContract = new Contract<StudentRepository>({
703
- getStudent: {
704
- rescue(_self, error, [id], retry) {
705
- console.error(error)
706
- console.log('Retrying with legacy id...')
707
- retry(`old-${id}`)
708
- }
659
+ You can also use the `retry` function in your rescue handler to attempt the method again:
660
+
661
+ ```typescript
662
+ class Example extends Contracted {
663
+ @rescue((_self, _error, _args, retry) => retry(3))
664
+ method(value: number): number {
665
+ if (value <= 0)
666
+ throw new Error('value must be greater than 0');
667
+ else
668
+ return value;
709
669
  }
670
+ }
671
+ ```
672
+
673
+ `retry` passes **only** the arguments you give it — it does not replay the original arguments. To retry with the same arguments, forward the `args` you received:
674
+
675
+ ```typescript
676
+ @rescue((_self, _error, args, retry) => retry(...args))
677
+ ```
678
+
679
+ Calling `retry()` retries with no arguments.
680
+
681
+ A `@rescue` handler **cannot supply the feature's result**. Only `retry` can produce one, by running the body again; a value returned from the handler is ignored, and the original error is raised to the caller when `retry` is not called. To recover with a substitute value, restructure the body to accept the alternative and retry with it:
682
+
683
+ ```typescript
684
+ @rescue((_self, _error, args, retry) => {
685
+ // the handler restores state, then asks for a second attempt
686
+ retry(...args);
710
687
  })
688
+ method(value: number): number { /* ... */ }
689
+ ```
690
+
691
+ This keeps the postcondition meaningful: a result the body never produced would not be covered by `@ensures`.
692
+
693
+ ### Robustness, Organized Panic, and the Benefits of `@rescue`
711
694
 
712
- @Contracted(studentRepositoryContract)
713
- class StudentRepository {
714
- ...
715
- async getStudent(id: string): Student {
716
- const data = await fetch(`/repos/students/${id}`).then(response => response.json())
695
+ The `@rescue` decorator enables a mechanism for **Robustness** in your code. It allows your implementation to respond to situations not specified, providing the ability to handle exceptions in a structured way. This is sometimes called **Organized Panic**.
717
696
 
718
- return new Student(data)
697
+ In addition, `@rescue` provides a foundation for **N-Version programming**, **Fault-Tolerance**, and **Redundancy**. You can implement multiple strategies for handling errors, retrying with alternative logic or data, and ensuring your application can recover from unexpected failures.
698
+
699
+ A retried invocation re-enters the full assertion lifecycle (`@invariant` -> `@demands` -> body -> `@ensures`), and if it fails again the `@rescue` handler runs again. This means the handler is executed once per attempt, which is what N-Version programming requires: each invocation of the handler can select the next alternative.
700
+
701
+ A dated example of this is performing ajax requests in a multi-browser environment:
702
+
703
+ ```typescript
704
+ class AjaxRequest extends Contracted {
705
+ private _version = 0;
706
+ private _versions = ['legacy', 'activex', 'xhr'] as const;
707
+
708
+ @rescue((self: AjaxRequest, _error, args, retry) => {
709
+ self._version++;
710
+ retry(...args);
711
+ }, { maxRetries: 2 })
712
+ get(url: string): string {
713
+ const version = this._versions[this._version];
714
+
715
+ switch (version) {
716
+ case 'legacy':
717
+ if (!window.XMLHttpRequest) throw new Error(`${version} unsupported`);
718
+ return legacyGet(url);
719
+ case 'activex':
720
+ if (!window.ActiveXObject) throw new Error(`${version} unsupported`);
721
+ return activeXGet(url);
722
+ default:
723
+ return xhrGet(url);
724
+ }
719
725
  }
720
726
  }
721
727
  ```
722
728
 
723
- The `rescue` can be defined on the contract of an ancestor class feature and it will be used if none
724
- is defined on the current class:
729
+ Because a rescue handler may retry unconditionally, retries are unbounded by default. Set the `maxRetries` option on the `@rescue` declaration to bound them; when the limit is reached the last error is raised to the caller:
725
730
 
726
- ```ts
727
- const baseContract = new Contract<Base>({
728
- myMethod: {
729
- rescue(self, error, args, retry){ ... }
730
- }
731
- })
731
+ ```typescript
732
+ @rescue((_self, _error, args, retry) => retry(...args), { maxRetries: 3 })
733
+ ```
732
734
 
733
- @Contracted(baseContract)
734
- class Base {
735
- ...
736
- myMethod(){ ... }
737
- }
735
+ The option belongs to the declaration because the number of alternatives is a property of the feature, not of an individual failure. It is enforced per invocation of the feature, so a single call performs at most `maxRetries` retries however many `@rescue` executions that involves.
738
736
 
739
- class Sub extends Base {
740
- override myMethod(){ ... throw new Error('BOOM!') ... }
737
+ Unlike traditional `try/catch`, where exceptions are non-resumable and often handled far from the source (leading to scattered and redundant error handling), `@rescue` allows for **resumable exceptions** and localized, declarative error handling. This means:
738
+
739
+ - You can lexically determine where exception handling occurs.
740
+ - You can restore invariants or perform corrective actions before retrying or failing.
741
+ - You can optionally call `retry` to attempt the method again with new arguments or after fixing state, providing a form of fault tolerance and robustness.
742
+ - You can implement alternative strategies for error recovery, supporting N-Version programming and redundancy.
743
+
744
+ **Inheritance:**
745
+
746
+ If a base class declares a `@rescue` handler for a method, that handler is inherited by subclasses unless the subclass overrides it with its own `@rescue` declaration. This ensures that robust error handling is preserved throughout the inheritance chain, unless explicitly changed.
747
+
748
+ This approach leads to more maintainable and robust code, as error handling is organized and closely tied to the contract of the class feature, rather than being scattered throughout the call stack.
749
+
750
+ ## Standard Schema
751
+
752
+ `@invariant`, `@demands`, and `@ensures` accept a [Standard Schema V1](https://github.com/standard-schema/standard-schema) value anywhere they accept a predicate. Zod, Valibot, ArkType, and Effect Schema are then interchangeable: the library consumes the protocol and never depends on a provider.
753
+
754
+ ```typescript
755
+ import { z } from 'zod';
756
+
757
+ const positive = z.number().positive();
758
+ const quantity = z.tuple([z.number().positive()]);
759
+
760
+ class Inventory extends Contracted {
761
+ protected _stock = 0;
762
+ get stock() { return this._stock; }
763
+
764
+ @demands(quantity) // validates the argument tuple
765
+ @ensures(positive) // validates the result
766
+ add(...[count]: [number]): number {
767
+ this._stock += count;
768
+
769
+ return this._stock;
770
+ }
741
771
  }
742
772
  ```
743
773
 
744
- Another capability that the `rescue` declaration provides is
745
- [N-Version programming](https://en.wikipedia.org/wiki/N-version_programming)
746
- to enable [Fault-Tolerance](https://en.wikipedia.org/wiki/Fault_tolerance)
747
- and [Redundancy](https://en.wikipedia.org/wiki/Redundancy_(engineering)).
774
+ ### What a schema validates
748
775
 
749
- A dated example of this is performing ajax requests in multi-browser environments where `fetch` may not exist:
776
+ The subject is the subject the contract already describes, so the two kinds of arm are interchangeable:
750
777
 
751
- ```ts
752
- const ajaxRequestContract = new Contract<AjaxRequest>({
753
- get: {
754
- rescue(self, _error, [url], retry) {
755
- self.attempts++
756
- if(self.attempts < 2)
757
- retry(url)
758
- }
759
- }
760
- })
778
+ | Decorator | A schema validates | A predicate receives | Composition |
779
+ | --- | --- | --- | --- |
780
+ | `@invariant` | the instance | `(self)` | AND |
781
+ | `@demands` | the **argument tuple** | `(self, args)` | OR |
782
+ | `@ensures` | the **result** | `(self, args, old)` | AND |
761
783
 
762
- @Contracted(ajaxRequestContract)
763
- class AjaxRequest {
764
- #attempts = 0
784
+ Because `@demands` validates the argument tuple rather than the first argument, a one-parameter method is written as a tuple of one (`z.tuple([...])`). This keeps the subject unambiguous for any arity.
765
785
 
766
- get attempts(): number { return this.#attempts }
767
- set attempts(value: number) { this.#attempts = value }
786
+ ### Composition follows variance
768
787
 
769
- get(url) {
770
- if(this.#attempts == 0)
771
- return this.getFetch(url)
772
- else if(this.#attempts == 1)
773
- return this.getXhr(url)
774
- }
788
+ The rules above are the substitution rules, not a convention:
775
789
 
776
- async getFetch(url) {
777
- return await fetch(url)
778
- }
790
+ - **`@demands` is contravariant.** A subtype may accept *wider* input, so conditions are OR-composed and any inherited arm satisfies the call. A subtype adding an arm therefore **weakens** the precondition.
791
+ - **`@ensures` and `@invariant` are covariant.** A subtype may promise *narrower* output and must preserve *more* state, so conditions are AND-composed and every arm must hold. A subtype adding an arm therefore **strengthens** the obligation.
779
792
 
780
- async getXhr(url) {
781
- return await new Promise((resolve, reject) => {
782
- const xhr = new XMLHttpRequest();
783
- xhr.open('GET', url);
784
- xhr.onload = function() {
785
- if (this.status >= 200 && this.status < 300) {
786
- resolve(xhr.response);
787
- } else {
788
- reject({
789
- status: this.status,
790
- statusText: xhr.statusText
791
- });
792
- }
793
- };
794
- xhr.onerror = function() {
795
- reject({
796
- status: this.status,
797
- statusText: xhr.statusText
798
- });
799
- };
800
- xhr.send();
801
- })
802
- }
793
+ A schema arm composes exactly like a predicate arm, which is why no separate decorators exist: the rule belongs to the contract, not to the kind of arm.
794
+
795
+ **A narrowing subtype precondition has no effect, and that is correct.** Writing `@demands(z.number().min(5))` in a subtype does not restrict anything, because OR-composition keeps the inherited arm. A subtype is not permitted to narrow what its supertype accepts, so the runtime refuses to give it that power. TypeScript will not catch the mistake either — **method parameters are bivariant** under `strictFunctionTypes` — so this is a review obligation. Declare input schemas on the base feature.
796
+
797
+ ### Failure reporting
798
+
799
+ A schema failure carries the provider's own `issues` in the structured payload, and renders them into the message:
800
+
801
+ ```typescript
802
+ try {
803
+ inventory.add(-1);
804
+ } catch (error) {
805
+ error.violation?.contract; // '@demands'
806
+ error.violation?.issues; // ReadonlyArray<{ message, path? }>
803
807
  }
804
808
  ```
805
809
 
806
- Unlike `try/catch` where exceptions are non-resumable and handled at a location often distantly
807
- and indirectly related to the source, and probably redundantly across the callers,
808
- you can see from the above examples that the `rescue` mechanism enables resumable exceptions and
809
- "[Organized Panic](https://en.wikipedia.org/wiki/Exception_handling#Exception_handling_based_on_design_by_contract)"
810
- where you can lexically determine where the handling occurs and optionally perform changes and retry the feature call.
810
+ One consequence of validating the argument tuple is that an issue's `path` is also relative to it, so the first argument is index `0`:
811
+
812
+ ```text
813
+ @demands failed for Shipping.send (1 of 1 schema unsatisfied: schema #1: ...).
814
+ Reported: 0.zip: Invalid string: must match pattern /^\d{5}$/.
815
+ ```
816
+
817
+ ### Normalization is opt-in
818
+
819
+ `validate` may transform its input. Applying that transformation changes what the body receives and what later contracts observe, so it is an explicit choice:
820
+
821
+ ```typescript
822
+ @demands(trimmedName, { normalize: true })
823
+ rename(name: string): void { /* receives the trimmed name */ }
824
+ ```
825
+
826
+ - **`@demands`** is OR-composed, so the **first passing arm** decides the normalized value. That is deterministic and matches evaluation order.
827
+ - **`@ensures`** is AND-composed, so two normalizing arms would disagree about what the caller receives. That is refused at decoration time rather than resolved arbitrarily.
828
+
829
+ Off by default: without `normalize`, a schema only reports a verdict.
830
+
831
+ ### Synchronous only
832
+
833
+ Contract evaluation is synchronous, so a `validate` that returns a Promise is refused with a message asking for a synchronous schema. Treating a pending validation as satisfied would be worse than failing, and awaiting would move the feature's boundary.
834
+
835
+ ### No type inference
836
+
837
+ Decorators cannot change a feature's signature, so a schema gives **runtime enforcement only**: it neither narrows the declared parameter types nor infers `Input`/`Output`. Accurate inference needs a builder API, which this library does not have.
838
+
839
+ ### Providers
840
+
841
+ Any implementation of the protocol works, and no provider is a dependency. The `StandardSchemaV1` types are exported if you want to annotate your own schemas:
842
+
843
+ ```typescript
844
+ import type { StandardSchemaV1 } from '@final-hill/decorator-contracts';
845
+ ```
811
846
 
812
847
  ## The order of assertions
813
848
 
@@ -815,22 +850,25 @@ When `obj.feature` is called the happy path is:
815
850
 
816
851
  ![image](./docs/happy-path.png)
817
852
 
818
- If an error is thrown and there is no `rescue` defined then the `invariant`
819
- is checked before the error is raised to the caller.
853
+ The invariant is evaluated **twice** per successful call: once on entry and once on exit. Each of `@demands`, the feature body, and `@ensures` runs once. Accessors follow the same lifecycle as methods, and an accessor that reads another accessor or calls a method does not start a nested lifecycle.
854
+
855
+ An `async` feature follows the same order with the exit checks moved after the promise settles, so they observe the state the body actually reached; its failures reach the caller as a rejection. A generator applies the same order **once per step**, as described in [Generators](#generators).
856
+
857
+ The entry check is not redundant with `Contracted.new()`. Object state can be corrupted without going through a checked feature — via `Object.defineProperty`, by running with checked mode disabled and re-enabling it, or internally from a feature body. The entry check is what turns that into a precise error at the next public interaction rather than letting an invalid object keep operating.
858
+
859
+ Because the invariant is checked first, an invalid object reports its invariant violation rather than a precondition failure. That ordering is deliberate: the object is broken in a way that makes the caller's arguments moot.
860
+
861
+ If an error is thrown and there is no `@rescue` defined then the `@invariant` is checked before the error is raised to the caller.
862
+
863
+ If an error is thrown in the `@invariant` then it is raised to the caller.
820
864
 
821
- If an error is thrown in the `invariant` then it is raised to the caller.
865
+ If an error is thrown in the `@demands` then the error is raised to the caller. In this case the exit `@invariant` is not checked because the feature body has not been entered and the instance cannot have changed.
822
866
 
823
- If an error is thrown in the `demands` then the error is raised to the caller.
824
- In this case the `invariant` is not checked because the feature body has not
825
- been entered and the assertion cannot modify the state of the class without
826
- calling another method which is governed by its own contracts.
867
+ If an error is thrown by the feature body or the `@ensures` then the `@rescue` is executed. If `retry` is called then the process starts from the beginning.
827
868
 
828
- If an error is thrown by the feature body or the `ensures` then
829
- the `rescue` is executed. If `retry` is called then the process
830
- starts from the beginning.
869
+ If the retried invocation fails, its `@rescue` is executed again, so the handler runs once per attempt. Retries are bounded by the `maxRetries` option; without it they are unbounded.
831
870
 
832
- If `rescue` throws an error or does not call `retry` then the
833
- `invariant` is checked before the error is raised to the caller.
871
+ If `@rescue` throws an error or does not call `retry` then the `@invariant` is checked before the error is raised to the caller.
834
872
 
835
873
  ![image](./docs/order-of-assertions.png)
836
874