@final-hill/decorator-contracts 2.0.0 → 3.1.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.
- package/LICENSE +660 -660
- package/README.md +1722 -879
- package/dist/AssertionError.d.mts +28 -1
- package/dist/Contracted.d.mts +72 -10
- package/dist/admissibility.d.mts +353 -4
- package/dist/assert.d.mts +41 -4
- package/dist/decorator.d.mts +66 -4
- package/dist/demands.d.mts +88 -10
- package/dist/ensures.d.mts +104 -8
- package/dist/feature-kind.d.mts +25 -0
- package/dist/iff.d.mts +9 -4
- package/dist/implies.d.mts +9 -2
- package/dist/index.d.mts +10 -3
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/inspect.d.mts +38 -0
- package/dist/invariant.d.mts +20 -2
- package/dist/metadata.d.mts +98 -0
- package/dist/name.d.mts +70 -0
- package/dist/rescue.d.mts +94 -12
- package/dist/serialization.d.mts +63 -0
- package/dist/types.d.mts +22 -1
- package/package.json +82 -82
package/README.md
CHANGED
|
@@ -1,879 +1,1722 @@
|
|
|
1
|
-
# Decorator Contracts
|
|
2
|
-
|
|
3
|
-
[](https://github.com/final-hill/decorator-contracts/actions?query=workflow%3ABuild%2FRelease)
|
|
4
|
-
[](https://www.npmjs.com/package/@final-hill/decorator-contracts)
|
|
5
|
-
[](https://www.npmjs.com/package/@final-hill/decorator-contracts)
|
|
6
|
-
|
|
7
|
-
## Table of Contents
|
|
8
|
-
|
|
9
|
-
- [Introduction](#introduction)
|
|
10
|
-
- [Library Installation](#library-installation)
|
|
11
|
-
- [Node.js version](#nodejs-version)
|
|
12
|
-
- [Development](#development)
|
|
13
|
-
- [Usage](#usage)
|
|
14
|
-
- [Checked Mode](#checked-mode)
|
|
15
|
-
- [Assertions](#assertions)
|
|
16
|
-
- [Implies](#implies)
|
|
17
|
-
- [Iff](#iff)
|
|
18
|
-
- [Contracts are Hoare triples](#contracts-are-hoare-triples)
|
|
19
|
-
- [Contract failures](#contract-failures)
|
|
20
|
-
- [Encapsulation](#encapsulation)
|
|
21
|
-
- [
|
|
22
|
-
- [
|
|
23
|
-
- [
|
|
24
|
-
- [
|
|
25
|
-
- [
|
|
26
|
-
- [
|
|
27
|
-
- [
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
[
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
[
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
@
|
|
140
|
-
|
|
141
|
-
self.
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
}
|
|
195
|
-
```
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
```
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
`
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
```
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
```
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
}
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
```
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
```
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
```
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
A
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
}
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
}
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
class
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
|
610
|
-
|
|
|
611
|
-
|
|
|
612
|
-
|
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
```
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
```
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
```
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
```
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
```typescript
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
```
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
1
|
+
# Decorator Contracts
|
|
2
|
+
|
|
3
|
+
[](https://github.com/final-hill/decorator-contracts/actions?query=workflow%3ABuild%2FRelease)
|
|
4
|
+
[](https://www.npmjs.com/package/@final-hill/decorator-contracts)
|
|
5
|
+
[](https://www.npmjs.com/package/@final-hill/decorator-contracts)
|
|
6
|
+
|
|
7
|
+
## Table of Contents
|
|
8
|
+
|
|
9
|
+
- [Introduction](#introduction)
|
|
10
|
+
- [Library Installation](#library-installation)
|
|
11
|
+
- [Node.js version](#nodejs-version)
|
|
12
|
+
- [Development](#development)
|
|
13
|
+
- [Usage](#usage)
|
|
14
|
+
- [Checked Mode](#checked-mode)
|
|
15
|
+
- [Assertions](#assertions)
|
|
16
|
+
- [Implies](#implies)
|
|
17
|
+
- [Iff](#iff)
|
|
18
|
+
- [Contracts are Hoare triples](#contracts-are-hoare-triples)
|
|
19
|
+
- [Contract failures](#contract-failures)
|
|
20
|
+
- [Encapsulation](#encapsulation)
|
|
21
|
+
- [Inspecting and serializing](#inspecting-and-serializing)
|
|
22
|
+
- [Asynchronous features](#asynchronous-features)
|
|
23
|
+
- [An awaited predicate](#an-awaited-predicate)
|
|
24
|
+
- [Internal calls are not contracted](#an-internal-call-runs-none-of-the-callees-contracts)
|
|
25
|
+
- [Invariants](#invariants)
|
|
26
|
+
- [Demands](#demands)
|
|
27
|
+
- [Ensures](#ensures)
|
|
28
|
+
- [Rescue](#rescue)
|
|
29
|
+
- [Standard Schema](#standard-schema)
|
|
30
|
+
- [Inspecting contracts](#inspecting-contracts)
|
|
31
|
+
- [Contracts and your test suite](#contracts-and-your-test-suite)
|
|
32
|
+
- [The order of assertions](#the-order-of-assertions)
|
|
33
|
+
- [The subject a predicate is called with](#the-subject-a-predicate-is-called-with)
|
|
34
|
+
- [Further Reading](#further-reading)
|
|
35
|
+
|
|
36
|
+
## Introduction
|
|
37
|
+
|
|
38
|
+
Decorator Contracts is a library that provides the ability to create and assign
|
|
39
|
+
Code Contracts to ECMAScript and TypeScript classes. This enables
|
|
40
|
+
enforcement of the
|
|
41
|
+
[Liskov substitution principle](https://en.wikipedia.org/wiki/Liskov_substitution_principle)
|
|
42
|
+
of [SOLID](https://en.wikipedia.org/wiki/SOLID)
|
|
43
|
+
and [Organized Panic](https://en.wikipedia.org/wiki/Exception_handling#Exception_handling_based_on_design_by_contract) to support
|
|
44
|
+
[Design By Contract™](https://en.wikipedia.org/wiki/Design_by_contract).
|
|
45
|
+
|
|
46
|
+
Note that the license for this library is [AGPL-3.0-only](https://www.gnu.org/licenses/agpl-3.0.en.html).
|
|
47
|
+
You should [know what that means](https://choosealicense.com/licenses/agpl-3.0/) before
|
|
48
|
+
using this. If you would like an exception to this license per section 7
|
|
49
|
+
[contact the author](mailto:michael.haufe@final-hill.com).
|
|
50
|
+
|
|
51
|
+
## Library Installation
|
|
52
|
+
|
|
53
|
+
The latest version:
|
|
54
|
+
|
|
55
|
+
`npm install @final-hill/decorator-contracts`
|
|
56
|
+
|
|
57
|
+
A specific version:
|
|
58
|
+
|
|
59
|
+
`npm install @final-hill/decorator-contracts@x.x.x`
|
|
60
|
+
|
|
61
|
+
For use in a browser (no build step) via [unpkg.com](https://unpkg.com/):
|
|
62
|
+
|
|
63
|
+
```html
|
|
64
|
+
<script type="importmap">
|
|
65
|
+
{
|
|
66
|
+
"imports": {
|
|
67
|
+
"@final-hill/decorator-contracts": "https://unpkg.com/@final-hill/decorator-contracts"
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
</script>
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Via [skypack.dev](https://www.skypack.dev/):
|
|
74
|
+
|
|
75
|
+
`<script type="module" src="https://cdn.skypack.dev/@final-hill/decorator-contracts"></script>`
|
|
76
|
+
|
|
77
|
+
## Node.js version
|
|
78
|
+
|
|
79
|
+
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.
|
|
80
|
+
|
|
81
|
+
## Development
|
|
82
|
+
|
|
83
|
+
A [development container](https://containers.dev/) is provided, pinned to the same Node version CI uses:
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
# open the repository in the container, then
|
|
87
|
+
npm ci # installed automatically on create
|
|
88
|
+
npm run build
|
|
89
|
+
npm test
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
`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.
|
|
93
|
+
|
|
94
|
+
| Script | Purpose |
|
|
95
|
+
| --- | --- |
|
|
96
|
+
| `npm run lint` | Lint, failing on warnings; does not modify files |
|
|
97
|
+
| `npm run lint:fix` | Lint and autofix |
|
|
98
|
+
| `npm run typecheck` | Type-check the library and the test suite |
|
|
99
|
+
| `npm test` | Type-check, then run the tests |
|
|
100
|
+
| `npm run test:coverage` | Run the tests with coverage, writing `coverage/lcov.info` |
|
|
101
|
+
|
|
102
|
+
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/`.
|
|
103
|
+
|
|
104
|
+
## Usage
|
|
105
|
+
|
|
106
|
+
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.
|
|
107
|
+
|
|
108
|
+
```typescript
|
|
109
|
+
import {
|
|
110
|
+
Contracted, demands, ensures, invariant,
|
|
111
|
+
} from '@final-hill/decorator-contracts';
|
|
112
|
+
|
|
113
|
+
@invariant(({ self }) =>
|
|
114
|
+
self.isEmpty() == (self.size == 0) &&
|
|
115
|
+
self.isFull() == (self.size == self.limit) &&
|
|
116
|
+
self.size >= 0 && self.size <= self.limit
|
|
117
|
+
)
|
|
118
|
+
class Stack<T> extends Contracted {
|
|
119
|
+
private _implementation: T[] = [];
|
|
120
|
+
private _size = 0;
|
|
121
|
+
private _limit: number;
|
|
122
|
+
|
|
123
|
+
constructor(limit: number) {
|
|
124
|
+
super();
|
|
125
|
+
this._limit = limit;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
get limit() { return this._limit; }
|
|
129
|
+
get size() { return this._size; }
|
|
130
|
+
|
|
131
|
+
clear(): void {
|
|
132
|
+
this._implementation = [];
|
|
133
|
+
this._size = 0;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
isEmpty(): boolean { return this._implementation.length == 0; }
|
|
137
|
+
isFull(): boolean { return this._implementation.length == this.limit; }
|
|
138
|
+
|
|
139
|
+
@demands(({ self }) => !self.isEmpty())
|
|
140
|
+
@ensures(({ self, old }) =>
|
|
141
|
+
!self.isFull() && self.size == old.size - 1)
|
|
142
|
+
pop(): T {
|
|
143
|
+
this._size--;
|
|
144
|
+
return this._implementation.pop()!;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
@demands(({ self }) => !self.isFull())
|
|
148
|
+
@ensures(({ self, args: [item], old }) =>
|
|
149
|
+
!self.isEmpty() &&
|
|
150
|
+
self.top === item &&
|
|
151
|
+
self.size === old.size + 1
|
|
152
|
+
)
|
|
153
|
+
push(item: T): void {
|
|
154
|
+
this._size++;
|
|
155
|
+
this._implementation.push(item);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
get top(): T | undefined {
|
|
159
|
+
return this._implementation.at(-1);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const stack = Stack.new(3);
|
|
164
|
+
stack.push(1);
|
|
165
|
+
stack.push(2);
|
|
166
|
+
stack.pop();
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
## Instantiation: Using the Static `.new(...)` Method
|
|
170
|
+
|
|
171
|
+
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(...)`).
|
|
172
|
+
|
|
173
|
+
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.
|
|
174
|
+
|
|
175
|
+
## Checked Mode
|
|
176
|
+
|
|
177
|
+
Checked Mode controls whether the contracts (invariants, demands, ensures, and rescue) are evaluated at runtime, so a production build can skip the checking cost while development and tests keep it.
|
|
178
|
+
|
|
179
|
+
It is a coarse switch, not a re-entrancy mechanism: disabling it skips contract evaluation entirely, so a feature call and a field read look the same and no lifecycle starts. A body still runs on the instance itself, so it may mutate its own state exactly as it may with the checks on — the switch removes the checks, not the place the body runs.
|
|
180
|
+
|
|
181
|
+
**It is separate from encapsulation.** Encapsulation is the name rule: an external caller cannot assign, define, or delete a public property. It has its own switch, `[encapsulationMode]`. The two answer different questions — a test double may want the checks off while still refusing a write to a field it never declared, and a class may want the write protection without the checks.
|
|
182
|
+
|
|
183
|
+
By default both are enabled. Assign the static on a class to change it for that class and the subclasses that do not declare their own:
|
|
184
|
+
|
|
185
|
+
```typescript
|
|
186
|
+
import { checkedMode, Contracted, encapsulationMode } from '@final-hill/decorator-contracts';
|
|
187
|
+
|
|
188
|
+
class DataHolder extends Contracted {
|
|
189
|
+
static [checkedMode] = false; // skip the contracts
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
class OpenBox extends Contracted {
|
|
193
|
+
static [encapsulationMode] = false; // allow external writes, keep the contracts
|
|
194
|
+
}
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
The nearest declaration on the class chain wins, and each switch is resolved independently, so a subclass can re-enable what an ancestor disabled. A sibling or a base class that declares nothing is unaffected. Assigning on `Contracted` itself sets the default for every class that declares neither.
|
|
198
|
+
|
|
199
|
+
| | contracts on | contracts off |
|
|
200
|
+
| --- | --- | --- |
|
|
201
|
+
| **encapsulation on** | full enforcement | public writes still refused, no checks |
|
|
202
|
+
| **encapsulation off** | public writes allowed, checks still run on the write | neither |
|
|
203
|
+
|
|
204
|
+
Disabling encapsulation removes one verdict — whether the name may be written at all. It does not remove the write from the lifecycle: a permitted write is still an external mutation, so `@invariant` runs on entry and exit and a setter's `@demands` and `@ensures` describe it. Turning the contracts off is what removes the checks, in every quadrant.
|
|
205
|
+
|
|
206
|
+
**The switch is set on the class, never on an instance.** Assigning, defining, or deleting either symbol on an instance raises a `TypeError`, including when both switches are off — a switch a caller can set is a guarantee a caller can remove.
|
|
207
|
+
|
|
208
|
+
The switch is read on every trap rather than captured at construction, so a class assigned during a test affects instances that already exist.
|
|
209
|
+
|
|
210
|
+
One approach to managing this is to leverage environment variables. For example, you can interrogate `NODE_ENV` to decide the default:
|
|
211
|
+
|
|
212
|
+
```typescript
|
|
213
|
+
Contracted[checkedMode] = process.env.NODE_ENV === 'development';
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
### Interaction with `@rescue`
|
|
217
|
+
|
|
218
|
+
`@rescue` is one of the contracts, so disabling the contracts disables it: the body's own error reaches the caller and no handler runs. This is deliberate — a handler exists to translate and repair a contract failure, and with no contract failure to report there is nothing for it to act on.
|
|
219
|
+
|
|
220
|
+
Note that a `@rescue` handler cannot observe a failed `@demands` at all, whatever the switch says: a rejected precondition never enters a body. See [What a `@rescue` observes](#what-a-rescue-observes).
|
|
221
|
+
|
|
222
|
+
## Assertions
|
|
223
|
+
|
|
224
|
+
Use the `assert` function for inline assertions:
|
|
225
|
+
|
|
226
|
+
```typescript
|
|
227
|
+
import { assert } from '@final-hill/decorator-contracts';
|
|
228
|
+
|
|
229
|
+
function avg(xs: number[]): number {
|
|
230
|
+
assert(xs.length > 0, 'The list can not be empty');
|
|
231
|
+
return xs.reduce((sum, next) => sum + next) / xs.length;
|
|
232
|
+
}
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
If you are using TypeScript, `assert` will also assert the type of the condition:
|
|
236
|
+
|
|
237
|
+
```typescript
|
|
238
|
+
let str: any = 'foo';
|
|
239
|
+
|
|
240
|
+
str.toUpperCase(); // str is any
|
|
241
|
+
|
|
242
|
+
assert(typeof str == 'string');
|
|
243
|
+
|
|
244
|
+
str.toUpperCase(); // str is now a string
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
**`assert` should not be used for validating arguments**
|
|
248
|
+
|
|
249
|
+
Use the `@demands` decorator for this purpose.
|
|
250
|
+
|
|
251
|
+
## Implies
|
|
252
|
+
|
|
253
|
+
When defining predicates it is a common use case to encode [material implication](https://en.wikipedia.org/wiki/Material_conditional):
|
|
254
|
+
|
|
255
|
+
```typescript
|
|
256
|
+
import { implies } from '@final-hill/decorator-contracts';
|
|
257
|
+
|
|
258
|
+
implies(weather.isSunny, person.visitsBeach);
|
|
259
|
+
// Logically equivalent to: !weather.isSunny || person.visitsBeach
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
Both functions always return a `boolean`, even when an operand is not a boolean: a truthy object is coerced rather than passed through. Their parameters are `boolean` as well, so a typed non-boolean operand does not compile. The coercion therefore decides only what a value means when it reached the helper past the type system — typed `any`, or plain JavaScript — where a truthy operand answers `true` instead of being named:
|
|
263
|
+
|
|
264
|
+
```typescript
|
|
265
|
+
@invariant(({ self }) => implies(true, self._entry)) // passes: the object is truthy
|
|
266
|
+
class CacheEntry extends Contracted {
|
|
267
|
+
public _entry: any = { loaded: false }; // `any`: the operand type is not checked
|
|
268
|
+
}
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
A contract names a non-boolean *result*, but it cannot inspect an operand, so state a contract through a helper only when both operands are already booleans, and write the comparison when you want the operand itself checked.
|
|
272
|
+
|
|
273
|
+
Use these combinators to state a **relationship between two properties**, which is what an invariant and a precondition are. Do not use one in place of a postcondition's target-state conjunction: it weakens the obligation. A body that does nothing satisfies `iff(self.onHold, !self.available)` and `implies(!self.available, self.onHold)`, while `self.onHold && !self.available` rejects it.
|
|
274
|
+
|
|
275
|
+
## Iff
|
|
276
|
+
|
|
277
|
+
When defining predicates it is a common use case to encode [if and only if](https://en.wikipedia.org/wiki/Logical_biconditional):
|
|
278
|
+
|
|
279
|
+
```typescript
|
|
280
|
+
import { iff } from '@final-hill/decorator-contracts';
|
|
281
|
+
|
|
282
|
+
iff(person.hasTicket, person.ridesTrain);
|
|
283
|
+
// Logically equivalent to: implies(p, q) && implies(q, p)
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
It returns a `boolean`, coerces a non-boolean operand, and must not stand in for a postcondition's target-state conjunction — all three stated under [Implies](#implies), which applies to both.
|
|
287
|
+
|
|
288
|
+
## Contracts are Hoare triples
|
|
289
|
+
|
|
290
|
+
A contract describes the **observable boundary** of a feature, in the sense of a [Hoare triple](https://en.wikipedia.org/wiki/Hoare_logic):
|
|
291
|
+
|
|
292
|
+
$$\{P\}\; C\; \{Q\}$$
|
|
293
|
+
|
|
294
|
+
`@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.
|
|
295
|
+
|
|
296
|
+
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.
|
|
297
|
+
|
|
298
|
+
## Contract failures
|
|
299
|
+
|
|
300
|
+
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:
|
|
301
|
+
|
|
302
|
+
```text
|
|
303
|
+
@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
|
+
```
|
|
305
|
+
|
|
306
|
+
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. The class name in `violation.className` and in the message is likewise the build's output unless the class declares one — see [Naming a class in a failure](#naming-a-class-in-a-failure).
|
|
307
|
+
|
|
308
|
+
The error also carries a `violation` property so callers can react without parsing the message:
|
|
309
|
+
|
|
310
|
+
```typescript
|
|
311
|
+
import { AssertionError } from '@final-hill/decorator-contracts';
|
|
312
|
+
|
|
313
|
+
try {
|
|
314
|
+
account.withdraw({ amount: 500 });
|
|
315
|
+
} catch (error) {
|
|
316
|
+
if (error instanceof AssertionError && error.violation?.contract === '@demands') {
|
|
317
|
+
// a precondition failed; the feature was never entered
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
`violation` has the shape:
|
|
323
|
+
|
|
324
|
+
```typescript
|
|
325
|
+
interface ContractViolation {
|
|
326
|
+
contract: '@invariant' | '@demands' | '@ensures';
|
|
327
|
+
className: string;
|
|
328
|
+
feature?: string; // absent for `@invariant`
|
|
329
|
+
failedIndices: number[]; // positions in the contract's composition list
|
|
330
|
+
thrownIndices?: number[]; // the failing arms that threw, in evaluation order
|
|
331
|
+
thrown?: string[]; // what they threw, described, aligned with `thrownIndices`
|
|
332
|
+
predicates: string[]; // source text, aligned with `failedIndices`
|
|
333
|
+
}
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
`@demands` is OR-composed, so a failure lists **every** arm that rejected the call — any of them could have permitted it. `@ensures` and `@invariant` are AND-composed, so a failure lists only the arms that broke.
|
|
337
|
+
|
|
338
|
+
An `AssertionError` thrown by `assert()` itself has no `violation`.
|
|
339
|
+
|
|
340
|
+
### Naming a class in a failure
|
|
341
|
+
|
|
342
|
+
`className` is read from the constructor, so it is only as stable as the name the build emitted. Without minification that is the class's name. With it, it degrades: a minifier is free to rename the class, and the standard decorator lowering wraps a decorated class in an immediately invoked arrow that returns a **class expression**, which a compressor may leave anonymous outright. The message then reads:
|
|
343
|
+
|
|
344
|
+
```text
|
|
345
|
+
@demands failed for .withdraw (1 of 1 predicate unsatisfied: ...)
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
There is no earlier moment with a better name. The class object is created once, and a class decorator observes the same name the violation would report later, so capturing it at decoration time cannot improve it. A declaration is the only signal that survives a build:
|
|
349
|
+
|
|
350
|
+
```typescript
|
|
351
|
+
import { contractName, Contracted, demands } from '@final-hill/decorator-contracts';
|
|
352
|
+
|
|
353
|
+
class Cart extends Contracted {
|
|
354
|
+
static [contractName] = 'Cart';
|
|
355
|
+
|
|
356
|
+
@demands(({ args: [quantity] }) => quantity > 0)
|
|
357
|
+
withdraw(quantity: number): number { return quantity; }
|
|
358
|
+
}
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
Every failure that names the class uses the declaration: `violation.className`, the message, a non-boolean predicate diagnostic, and the "returned a promise but is not declared `async`" message. An empty or non-string declaration falls back to the constructor name, so a mistyped one cannot produce the empty label above. A declaration that throws falls back the same way, because a name is read on the way to reporting a failure and must not become the error the caller receives instead of it.
|
|
362
|
+
|
|
363
|
+
Set it on the class, as with the enforcement switches: it is read from the constructor, so an instance write has no effect. The lookup is made once per contract that has arms to label, so a class with none of them never pays for it.
|
|
364
|
+
|
|
365
|
+
**A name is declared, not inherited**, which parts company with `[checkedMode]` and `[encapsulationMode]`. Those inherit because they answer how a class *behaves*, and a subclass that says nothing about behaviour should behave like its base. A name answers who the class *is*, so applying the base's name to a subclass would report a failure in `Base` when it happened in `Derived`. A subclass that wants a stable name declares one.
|
|
366
|
+
|
|
367
|
+
The **feature name is unaffected**, because it is not a name lookup: `@demands` receives `ctx.name`, which the lowering emits as a string literal in the decorator context, and a minifier does not touch it.
|
|
368
|
+
|
|
369
|
+
If a declaration is not an option, a `keepNames` setting keeps the constructor name intact and nothing else is needed:
|
|
370
|
+
|
|
371
|
+
- `esbuild`: `keepNames: true`
|
|
372
|
+
- `terser`: `keep_classnames` is not sufficient on its own, because compression inlines the class expression and drops the name. Also set `compress: { keep_classnames: true }`, or disable compression.
|
|
373
|
+
|
|
374
|
+
Neither setting reaches the feature names, which never needed help. Exclude the library and the decorator lowering helpers from property mangling (`mangle.properties`), which renames the context and descriptor fields the lowering reads.
|
|
375
|
+
|
|
376
|
+
### A predicate that throws is a failed predicate
|
|
377
|
+
|
|
378
|
+
A predicate that throws has answered *no*. It has not withdrawn the other arms, so evaluation continues and a later arm can still permit the call. This is what makes OR-composition hold: a subtype may weaken a precondition, and an arm that throws must not be able to deny a call its sibling allows.
|
|
379
|
+
|
|
380
|
+
```typescript
|
|
381
|
+
class Base extends Contracted {
|
|
382
|
+
@demands(({ args: [x] }) => { if (x !== 42) throw new Denied(); return true; })
|
|
383
|
+
method(x: number): number { return x; }
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
class Sub extends Base {
|
|
387
|
+
@demands(({ args: [x] }) => x === 7) // a legal weakening arm
|
|
388
|
+
override method(x: number): number { return x; }
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
Sub.new().method(7); // permitted: the second arm holds, so the first arm's throw is moot
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
When **every** arm fails and at least one of them threw, that thrown value is raised in place of the `AssertionError`, so a typed error reaches the caller. The **first arm that threw** decides which value that is. The structured violation is still attached to it, non-enumerable, so `error.violation` describes the contract the same way it does for a verdict; the underlying `AssertionError`, whose message names every unsatisfied arm, travels as `error.cause`:
|
|
395
|
+
|
|
396
|
+
```typescript
|
|
397
|
+
try {
|
|
398
|
+
Sub.new().method(1); // both arms fail
|
|
399
|
+
} catch (error) {
|
|
400
|
+
error instanceof Denied; // true; the typed error, not an AssertionError
|
|
401
|
+
error.violation.contract; // '@demands'
|
|
402
|
+
error.violation.thrownIndices; // [0]
|
|
403
|
+
error.cause.message; // names every arm, marking the one that threw
|
|
404
|
+
}
|
|
405
|
+
```
|
|
406
|
+
|
|
407
|
+
The record describes each thrown value rather than holding it, because `ContractViolation` is otherwise plain data that a caller logs and serialises; the value itself is the error in their `catch`.
|
|
408
|
+
|
|
409
|
+
A thrown primitive is raised unchanged, since it has nowhere to carry the violation. A `TypeError` from inside a predicate — a bug rather than a decision — keeps its own class, so a caller's `catch` still branches on the bug rather than on a contract failure.
|
|
410
|
+
|
|
411
|
+
An error the contract did not create is never damaged: a frozen or non-extensible one is raised without the annotation, and a `cause` the consumer set is left alone. A contract's own `cause` never replaces one.
|
|
412
|
+
|
|
413
|
+
### Raising a typed error with `onViolation`
|
|
414
|
+
|
|
415
|
+
A predicate must not throw, so a typed error cannot be raised from inside one. `@demands` and `@ensures` therefore accept an `onViolation` factory on their options, which runs **once, after every arm has failed**, and its result is what the caller receives:
|
|
416
|
+
|
|
417
|
+
```typescript
|
|
418
|
+
import { Contracted, demands, type ContractViolation, type DemandsSubject } from '@final-hill/decorator-contracts';
|
|
419
|
+
|
|
420
|
+
class PermissionDenied extends Error {
|
|
421
|
+
override name = 'PermissionDenied';
|
|
422
|
+
|
|
423
|
+
constructor(message: string, readonly violation?: ContractViolation) {
|
|
424
|
+
super(message);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
class Account extends Contracted {
|
|
429
|
+
private _balance = 0;
|
|
430
|
+
|
|
431
|
+
@demands(({ self }: DemandsSubject<Account>) => self._balance > 0, {
|
|
432
|
+
onViolation: violation => new PermissionDenied('insufficient funds', violation),
|
|
433
|
+
})
|
|
434
|
+
withdraw(): void {
|
|
435
|
+
this._balance--;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
```
|
|
439
|
+
|
|
440
|
+
The factory receives the full `ContractViolation`, which is the only machine-readable part of a failure. That is why the option takes a factory rather than a bare error constructor: an error boundary or a metadata-driven test needs `failedIndices`, `thrownIndices`, and the schema `issues`, and a constructor called without the violation would discard them.
|
|
441
|
+
|
|
442
|
+
The returned error carries the violation as `violation` and the `AssertionError` naming every unsatisfied arm as `cause`, both non-enumerable. A factory may supply its own `violation` and `cause`; those are kept, so an error that records what actually went wrong underneath keeps its record. The factory must return an object, since a primitive has nowhere to hold either field — that is reported as a `TypeError` naming the contract and feature, with the contract failure as its `cause`.
|
|
443
|
+
|
|
444
|
+
**Precedence across arms.** Scope is per contract, not per arm: there is no case where two arms of one contract need different error types, and per-arm would make precedence meaningless. When several arms declare a factory, the one belonging to the **first arm evaluated** decides — the same rule that makes the first passing arm decide a normalized value. Arms evaluate in the contract's composition order, so a decorator written last in source is evaluated first, and inherited arms come before a subclass's own. An arm that declares no factory defers to the next.
|
|
445
|
+
|
|
446
|
+
**When an arm also throws.** The factory still decides. A declared factory is the caller's explicit choice of error type, and it is given `thrownIndices` and `thrown`, so preferring it loses nothing.
|
|
447
|
+
|
|
448
|
+
**`@ensures` vs `@invariant`.** `@ensures` accepts the option on the same terms, with one difference at the boundary: when the body also leaves the instance invariant-invalid, the invariant failure is what the caller receives and the factory's error travels as its `cause`, because a broken instance is the state that has to surface. `@invariant` **refuses the option at decoration time**, because an invariant failure is what tells the lifecycle that the instance is in a state a `@rescue` handler must repair: the check is recognised by being an `AssertionError` whose `violation.contract` is `'@invariant'`. An error built by a factory is neither, so the repair protocol would not see it. Use a `@rescue` handler instead — it observes a failure a feature raised and can raise a typed error of its own.
|
|
449
|
+
|
|
450
|
+
That route covers the entry and exit checks only. The invariant `Contracted.new()` evaluates before it proxies the instance is outside every handler, so a class whose initial state violates an invariant reports an untyped `AssertionError`.
|
|
451
|
+
|
|
452
|
+
`checkedMode` disables the factory along with the contract, since a contract that does not run cannot fail.
|
|
453
|
+
|
|
454
|
+
## Encapsulation
|
|
455
|
+
|
|
456
|
+
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.
|
|
457
|
+
|
|
458
|
+
```typescript
|
|
459
|
+
class Example extends Contracted {
|
|
460
|
+
_private = 1; // Allowed
|
|
461
|
+
publicProp = 2; // Not allowed from outside
|
|
462
|
+
}
|
|
463
|
+
```
|
|
464
|
+
|
|
465
|
+
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.
|
|
466
|
+
|
|
467
|
+
```typescript
|
|
468
|
+
class Example extends Contracted {
|
|
469
|
+
publicProp = 2; // allowed: field initialiser
|
|
470
|
+
constructor() {
|
|
471
|
+
super();
|
|
472
|
+
this.publicProp = 3; // allowed: still inside construction
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
```
|
|
476
|
+
|
|
477
|
+
An external write to a public property raises a `TypeError`:
|
|
478
|
+
|
|
479
|
+
```typescript
|
|
480
|
+
const example = Example.new();
|
|
481
|
+
|
|
482
|
+
example.publicProp = 3; // TypeError
|
|
483
|
+
```
|
|
484
|
+
|
|
485
|
+
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:
|
|
486
|
+
|
|
487
|
+
```typescript
|
|
488
|
+
class Example extends Contracted {
|
|
489
|
+
publicProp = 1;
|
|
490
|
+
|
|
491
|
+
update(): void {
|
|
492
|
+
this.publicProp = 2; // allowed; `@ensures` and `@invariant` are the guarantee
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
```
|
|
496
|
+
|
|
497
|
+
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.
|
|
498
|
+
|
|
499
|
+
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.
|
|
500
|
+
|
|
501
|
+
### An internal call runs none of the callee's contracts
|
|
502
|
+
|
|
503
|
+
Replacing a guard call with a contract does not widen coverage: it **turns the check off** at every internal call site.
|
|
504
|
+
|
|
505
|
+
```typescript
|
|
506
|
+
import { Contracted, demands } from '@final-hill/decorator-contracts';
|
|
507
|
+
|
|
508
|
+
class Range extends Contracted {
|
|
509
|
+
@demands(({ args: [x] }) => x > 0)
|
|
510
|
+
inner(x: number) { return x; }
|
|
511
|
+
|
|
512
|
+
outer(x: number) { return this.inner(x); }
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
Range.new().outer(-1); // -1, and no error: `inner`'s @demands never ran
|
|
516
|
+
```
|
|
517
|
+
|
|
518
|
+
Every contract on `inner` is skipped this way — `@demands`, `@ensures`, and the `@invariant` around it. Only `outer` is a boundary, so only `outer` is checked, and it returns whatever `inner` produced.
|
|
519
|
+
|
|
520
|
+
The mechanism is that a feature body runs against the **raw** instance, not the proxy (see above), so `this.inner(…)` reaches the undecorated function directly.
|
|
521
|
+
|
|
522
|
+
### Why the body gets the raw instance
|
|
523
|
+
|
|
524
|
+
Handing the body the proxy instead would contract the internal call, which sounds like strictly more checking. It is not available, and the reason is not a preference about cost.
|
|
525
|
+
|
|
526
|
+
**A predicate is evaluated inside a trap, so its view must not start a lifecycle.** `@invariant(({ self }) => self.value >= 0)` reads `self.value` on every evaluation — twice for one getter read. A predicate therefore receives a purpose-built read-only proxy, not the instance's lifecycle proxy: reading through it is an ordinary property access, while assignment, deletion, and definition are refused. A feature body receives the raw target for the same reason — its internal accesses are not feature boundaries — and the two together are what keep one invocation to one lifecycle.
|
|
527
|
+
|
|
528
|
+
**The alternative also changes what the contract is about.** `{ P } C { Q }` treats `C` as unconstrained. If `C` ran other features' contracts, `outer`'s postcondition would be asserted over a composition of `inner`'s pre- and postconditions; a failure would name `inner` while `outer` is what the caller invoked, and the caller has no way to act on it.
|
|
529
|
+
|
|
530
|
+
**And it would make two ordinary shapes impossible.** A lenient façade delegating to a stricter core is a boundary today — a `@demands` of `x > 0` on `read` reaching a core requiring `x > 100` accepts `read(50)`, and the façade's arm runs exactly once. So is recursion: `down(n - 1)` is one lifecycle for the entry call. Contracting the internal call rejects the first and re-evaluates the invariant per frame for the second.
|
|
531
|
+
|
|
532
|
+
The cost of the rule is per call rather than per internal access: three internal calls to contracted features measure **2** invariant evaluations, not 4 or 6.
|
|
533
|
+
|
|
534
|
+
### The cross-instance case is checked
|
|
535
|
+
|
|
536
|
+
A call on a **different** instance is a boundary, because the callee is reached through that instance's proxy. The same class, both directions:
|
|
537
|
+
|
|
538
|
+
```typescript
|
|
539
|
+
class Range extends Contracted {
|
|
540
|
+
@demands(({ args: [x] }) => x > 0)
|
|
541
|
+
inner(x: number) { return x; }
|
|
542
|
+
|
|
543
|
+
viaThis(x: number) { return this.inner(x); } // `this` is raw: unchecked
|
|
544
|
+
viaPeer(peer: Range, x: number) { return peer.inner(x); } // peer is a proxy: checked
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
const range = Range.new();
|
|
548
|
+
|
|
549
|
+
range.viaThis(-1); // -1
|
|
550
|
+
range.viaPeer(range, -1); // @demands failed
|
|
551
|
+
```
|
|
552
|
+
|
|
553
|
+
The second line fails even though `peer` is the same object, because what decides is whether the reference reaches the proxy, not whether the instances are equal. The rejection crosses the boundary as a throw into the calling feature's body, so the calling feature's `@rescue` observes it. A failure in the callee's own body runs the callee's handler first, on the callee's lifecycle; a failed `@demands` consults no handler at all, for the reason given under [What a `@rescue` observes](#what-a-rescue-observes).
|
|
554
|
+
|
|
555
|
+
### Which shape to use
|
|
556
|
+
|
|
557
|
+
A public feature that another public feature calls needs one of two shapes. Both are correct; they trade a redundant declaration against a longer call chain.
|
|
558
|
+
|
|
559
|
+
**Every public verb declares its own arm.** The delegating verb declares the guard it would otherwise rely on the callee for, so the check is redundant by design:
|
|
560
|
+
|
|
561
|
+
```typescript
|
|
562
|
+
class Repository extends Contracted {
|
|
563
|
+
@demands(({ args: [id] }) => id.length > 0)
|
|
564
|
+
read(id: string): unknown { return { id }; }
|
|
565
|
+
|
|
566
|
+
@demands(({ args: [id] }) => id.length > 0) // redundant, and the point
|
|
567
|
+
describe(id: string): unknown { return this.read(id); }
|
|
568
|
+
}
|
|
569
|
+
```
|
|
570
|
+
|
|
571
|
+
This is the shape to reach for when a verb is cheap to describe and the precondition is short. The duplication is a property of the boundary rather than an accident, so it does not drift: a call from outside reaches `describe` and runs its arm, and the call it makes inward is the same computation it already authorised.
|
|
572
|
+
|
|
573
|
+
**A public verb is a guard plus a delegation to a private core.** The guarded work lives in one place, and each public entry point guards it:
|
|
574
|
+
|
|
575
|
+
```typescript
|
|
576
|
+
class Repository extends Contracted {
|
|
577
|
+
@demands(({ args: [id] }) => id.length > 0)
|
|
578
|
+
read(id: string): unknown { return this.core(id); }
|
|
579
|
+
|
|
580
|
+
@demands(({ args: [id] }) => id.length > 0)
|
|
581
|
+
describe(id: string): unknown { return this.core(id); }
|
|
582
|
+
|
|
583
|
+
/** Not contracted: every public path to it is. */
|
|
584
|
+
core(id: string): unknown { return { id }; }
|
|
585
|
+
}
|
|
586
|
+
```
|
|
587
|
+
|
|
588
|
+
The `core` method is deliberately undecorated. It is not a boundary a caller can reach, so a contract on it would be unreachable code; the guard belongs to the verbs that are reachable.
|
|
589
|
+
|
|
590
|
+
### The declaration still reads as enforcement
|
|
591
|
+
|
|
592
|
+
The consequence that follows from all of this is that `@demands` on a feature reached only internally declares an obligation nothing enforces, and the library cannot refuse it at the point it is written. Every other contract in this library refuses a declaration it cannot honour — `normalize` on a predicate arm, `normalize` on `@invariant`, `allowWeakening` on an AND-composed contract — because a declaration that cannot act reads as an intention that is in force when it is not. This is the one case where the check would have to see a call, and a decorator is handed the element and a context, never the body.
|
|
593
|
+
|
|
594
|
+
A runtime warning cannot close it either. The body holds the raw target, so `this.inner(x)` is a direct function call with no trap to observe it, and making the body's `this` an observing proxy would fire on the redundant-arm shape above, which is correct code.
|
|
595
|
+
|
|
596
|
+
So the rule is a review question about your class rather than something the compiler or this library can check: a feature that is only ever reached from inside the class needs its guard on the verb a caller actually invokes.
|
|
597
|
+
|
|
598
|
+
**A `protected` or `private` member has no external path, only a peer path.** The modifier is a compile-time refinement of an ordinary public property: the emitted JavaScript carries no record of it, and a standard decorator context reports `private: false` for both (`context.private` is true only for a native `#private` member). A caller outside the class cannot name the member, and the usual access inside it is `this.member`, which runs against the raw target and starts no lifecycle.
|
|
599
|
+
|
|
600
|
+
The arm is therefore reachable only through the [cross-instance case](#the-cross-instance-case-is-checked): a subclass method that reads the member on another instance, as `peer.member`, does cross a proxy and does evaluate it. When no such call exists, the declaration describes a boundary no invocation can reach.
|
|
601
|
+
|
|
602
|
+
The decorator cannot refuse that declaration, because it never sees the modifier, and a check keyed on it would also refuse the public member it is indistinguishable from. The `_` prefix is the one signal the runtime does have, which is why a `_`-prefixed feature is refused outright. Write a member that only the class calls as an undecorated method, as `core` is above; the guard belongs on the public verb, and a declaration that names a member nothing can reach reads as a guarantee it does not give.
|
|
603
|
+
|
|
604
|
+
### Deletion
|
|
605
|
+
|
|
606
|
+
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.
|
|
607
|
+
|
|
608
|
+
| Expression | Result |
|
|
609
|
+
| --- | --- |
|
|
610
|
+
| `delete example._private` | allowed |
|
|
611
|
+
| `delete example.publicProp` | `TypeError` |
|
|
612
|
+
| `delete example.nonexistent` | `TypeError` (the name is not `_`-prefixed) |
|
|
613
|
+
|
|
614
|
+
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.
|
|
615
|
+
|
|
616
|
+
### Property definition
|
|
617
|
+
|
|
618
|
+
Defining a property is the same kind of external mutation as assigning one, so it follows the same rule: only `_`-prefixed names may be defined, and `Object.defineProperty`, `Reflect.defineProperty`, and `Object.defineProperties` are all intercepted.
|
|
619
|
+
|
|
620
|
+
This matters because definition can do more than assignment. Redefining a public field escapes the postcondition that would have caught the change, and replacing a contracted **method** routes callers around its `@demands` and `@ensures` entirely:
|
|
621
|
+
|
|
622
|
+
```typescript
|
|
623
|
+
const example = Example.new();
|
|
624
|
+
|
|
625
|
+
Object.defineProperty(example, 'publicProp', { value: 3 }); // TypeError
|
|
626
|
+
Object.defineProperty(example, 'guard', { value: () => 1 }); // TypeError
|
|
627
|
+
```
|
|
628
|
+
|
|
629
|
+
A **prototype setter does not authorise defining the same name**, unlike assignment. Assignment invokes the setter, which is the sanctioned route; defining an own property shadows the accessor instead of invoking it, so it is refused.
|
|
630
|
+
|
|
631
|
+
Two operations remain available for every property name, because neither changes nor shadows state:
|
|
632
|
+
|
|
633
|
+
| Expression | Result |
|
|
634
|
+
| --- | --- |
|
|
635
|
+
| `Object.freeze(example)` | allowed (seals each existing property) |
|
|
636
|
+
| `Object.seal(example)` | allowed |
|
|
637
|
+
| `Object.preventExtensions(example)` | allowed (no property definition involved) |
|
|
638
|
+
|
|
639
|
+
Once an instance is frozen, a write it cannot accept **throws**, rather than being reported as a successful assignment.
|
|
640
|
+
|
|
641
|
+
### Replacing the prototype
|
|
642
|
+
|
|
643
|
+
`Object.setPrototypeOf` and `Reflect.setPrototypeOf` throw. A replacement changes which descriptors a feature resolves to, which would leave the instance running methods that do not match the contracts it reports.
|
|
644
|
+
|
|
645
|
+
## Inspecting and serializing
|
|
646
|
+
|
|
647
|
+
A contracted instance holds its state in `_`-prefixed properties, so the two ways of turning an instance into something printable behave differently on purpose: one shows a developer everything, and the other publishes a shape the class declares.
|
|
648
|
+
|
|
649
|
+
### `util.inspect` shows the instance, not the proxy
|
|
650
|
+
|
|
651
|
+
`util.inspect` renders the class name and the instance's own state:
|
|
652
|
+
|
|
653
|
+
```text
|
|
654
|
+
Account { _balance: 5, _orgId: 'o' }
|
|
655
|
+
```
|
|
656
|
+
|
|
657
|
+
Without this the fallback rendering labels it as a proxy — `Proxy(Account { ... })` — so a reader cannot tell a contracted instance from an accidental one, and a nested instance renders the same way again.
|
|
658
|
+
|
|
659
|
+
The `_`-prefixed fields **are** shown. That is the point: `inspect` is the surface a developer uses to see what an object actually holds, and hiding the state would defeat it. It is not a serialization format.
|
|
660
|
+
|
|
661
|
+
The rendering reads own property *descriptors*, so it runs no contract and cannot fail because one does. A contracted instance is therefore inspectable in exactly the situation a reader most needs it: when its invariant is broken, or when a getter throws.
|
|
662
|
+
|
|
663
|
+
An accessor is not rendered, because it holds no state — its value is already visible through the field it reads. A reference back to an instance already being rendered is shown as `[Circular]`.
|
|
664
|
+
|
|
665
|
+
The name reported is the class's [`contractName`](#naming-a-class-in-a-failure) when it declares one, and the constructor's name otherwise, so a class that named itself is named the same way in a debugger as in a failure.
|
|
666
|
+
|
|
667
|
+
`depth` is honoured the way `util.inspect` honours it for a plain object: the instance itself is shown at `depth: 0`, each unit of depth shows one more level, and the first value with no budget left is rendered `[Object]`.
|
|
668
|
+
|
|
669
|
+
Two options are **not** honoured, because the rendering reports state rather than evaluating it: `showHidden` does not filter the `_`-prefixed fields out (they are the state being shown), and `getters: true` cannot opt an accessor in.
|
|
670
|
+
|
|
671
|
+
A subclass may replace the rendering by declaring its own method:
|
|
672
|
+
|
|
673
|
+
```typescript
|
|
674
|
+
class Account extends Contracted {
|
|
675
|
+
protected _balance = 0;
|
|
676
|
+
|
|
677
|
+
get balance() { return this._balance; }
|
|
678
|
+
|
|
679
|
+
[Symbol.for('nodejs.util.inspect.custom')]() {
|
|
680
|
+
return `Account(${this.balance})`;
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
```
|
|
684
|
+
|
|
685
|
+
### `JSON.stringify` is opt-in
|
|
686
|
+
|
|
687
|
+
By default `JSON.stringify` emits the instance's own data properties, which are the `_`-prefixed ones:
|
|
688
|
+
|
|
689
|
+
```typescript
|
|
690
|
+
JSON.stringify(Account.new()); // {"_balance":5,"_orgId":"o"}
|
|
691
|
+
```
|
|
692
|
+
|
|
693
|
+
That is a leak, but it cannot be fixed by a default `toJSON`. Which fields are *public* is a decision about your domain, and `_` is a convention this library enforces for assignment rather than a declaration of what may be published. A default would also change the output of every existing `JSON.stringify`, which is the kind of silent break a library must not make.
|
|
694
|
+
|
|
695
|
+
So a class opts in with `@serializable`, naming the getters to publish:
|
|
696
|
+
|
|
697
|
+
```typescript
|
|
698
|
+
import { Contracted, serializable } from '@final-hill/decorator-contracts';
|
|
699
|
+
|
|
700
|
+
@serializable('balance', 'orgId')
|
|
701
|
+
class Account extends Contracted {
|
|
702
|
+
protected _balance = 0;
|
|
703
|
+
protected _orgId = 'o';
|
|
704
|
+
|
|
705
|
+
get balance() { return this._balance; }
|
|
706
|
+
get orgId() { return this._orgId; }
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
JSON.stringify(Account.new()); // {"balance":0,"orgId":"o"}
|
|
710
|
+
```
|
|
711
|
+
|
|
712
|
+
Naming **getters** rather than fields is deliberate: a field name is storage, while a getter is the class's own statement of what is observable, and it is already the only way a caller reads state the encapsulation rule protects. The published shape is therefore the shape a caller can already see. Every name is checked when the decorator runs, so a typo fails at the declaration rather than producing an empty object in whichever logger calls it.
|
|
713
|
+
|
|
714
|
+
One class declares one shape. Applying `@serializable` twice, or applying it to a class that already declares its own `toJSON`, is a `TypeError` at decoration time — the two declarations cannot both be the shape the class publishes, and silently preferring one of them would publish a shape the author did not choose.
|
|
715
|
+
|
|
716
|
+
The published shape follows substitution: a subclass that declares its own `@serializable` publishes its own list, and one that declares nothing inherits the base's, because the subclass *is* a base instance. `toJSON` is a public feature, so the entry and exit `@invariant` hold around the whole serialization.
|
|
717
|
+
|
|
718
|
+
### What is not supported
|
|
719
|
+
|
|
720
|
+
Neither of these produces a usable copy, and both are limitations rather than defects:
|
|
721
|
+
|
|
722
|
+
| Expression | Result |
|
|
723
|
+
| --- | --- |
|
|
724
|
+
| `{ ...instance }` | own data only; methods live on the prototype, so they are lost, and the copy is not contracted |
|
|
725
|
+
| `structuredClone(instance)` | `DataCloneError` |
|
|
726
|
+
|
|
727
|
+
`structuredClone` fails on **any** `Proxy`, not just this library's — a bare `new Proxy({ a: 1 }, {})` fails the same way. A `toJSON` does not help it either, since cloning does not consult that method. A copy that is both useful and contracted needs an explicit copy protocol, which is a larger question than a serialization surface and is not provided here.
|
|
728
|
+
|
|
729
|
+
## Asynchronous features
|
|
730
|
+
|
|
731
|
+
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.
|
|
732
|
+
|
|
733
|
+
```typescript
|
|
734
|
+
class Account extends Contracted {
|
|
735
|
+
protected _balance = 0;
|
|
736
|
+
public _ledger!: Ledger; // a collaborator the caller sets
|
|
737
|
+
get balance() { return this._balance; }
|
|
738
|
+
|
|
739
|
+
@demands(({ self, args: [amount] }) => self.balance + amount >= 0)
|
|
740
|
+
@ensures(({ self, args: [amount], old }) => self.balance === old.balance + amount)
|
|
741
|
+
async deposit(amount: number): Promise<void> {
|
|
742
|
+
await this._ledger.record(amount); // suspension happens here
|
|
743
|
+
this._balance += amount; // observed by @ensures
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
```
|
|
747
|
+
|
|
748
|
+
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.
|
|
749
|
+
|
|
750
|
+
### Failure is delivered as a rejection
|
|
751
|
+
|
|
752
|
+
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.
|
|
753
|
+
|
|
754
|
+
```typescript
|
|
755
|
+
await assert.rejects(() => account.deposit(-5)); // AssertionError, not a sync throw
|
|
756
|
+
```
|
|
757
|
+
|
|
758
|
+
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.
|
|
759
|
+
|
|
760
|
+
### A synchronous feature must not return a promise
|
|
761
|
+
|
|
762
|
+
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:
|
|
763
|
+
|
|
764
|
+
```typescript
|
|
765
|
+
@ensures(...)
|
|
766
|
+
thenable(): Promise<void> { // AssertionError: not declared 'async'
|
|
767
|
+
return (async () => { await work(); this._value++; })();
|
|
768
|
+
}
|
|
769
|
+
```
|
|
770
|
+
|
|
771
|
+
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.
|
|
772
|
+
|
|
773
|
+
### An awaited predicate
|
|
774
|
+
|
|
775
|
+
An `async` feature's exit checks already sit behind its promise, so its entry checks can wait for one too. Declaring `awaitPredicate` allows a `@demands` or `@ensures` predicate to answer with a promise, which the lifecycle awaits before it decides the arm:
|
|
776
|
+
|
|
777
|
+
```typescript
|
|
778
|
+
class Account extends Contracted {
|
|
779
|
+
protected _limit = 100;
|
|
780
|
+
protected _balance = 0;
|
|
781
|
+
|
|
782
|
+
@demands(async ({ self, args: [amount] }) => self._balance + amount <= self._limit, { awaitPredicate: true })
|
|
783
|
+
@ensures(async ({ self, args: [amount], old }) => self._balance === old._balance + amount, { awaitPredicate: true })
|
|
784
|
+
async deposit(amount: number): Promise<void> {
|
|
785
|
+
this._balance += amount;
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
```
|
|
789
|
+
|
|
790
|
+
The option is the opt-in, not the predicate's shape. Without it an `async` predicate is a compile error and, at runtime, the same refusal a synchronous feature gives: a verdict that has not settled must not be read as a yes.
|
|
791
|
+
|
|
792
|
+
Awaiting a predicate decides only *when* the verdict arrives, not what it means:
|
|
793
|
+
|
|
794
|
+
- Only a resolved `true` permits the call. A resolved non-boolean is refused, exactly as a synchronous non-boolean is.
|
|
795
|
+
- A predicate that throws or rejects is a **failed arm**, not an abort. `@demands` is OR-composed, so a sibling arm may still permit the call; the rejection is raised only if every arm fails. `@ensures` is AND-composed, so every arm is still evaluated and the rejection is reported with the others.
|
|
796
|
+
|
|
797
|
+
The option is refused where nothing could await it: a getter or setter (read or assigned synchronously), a generator or async generator (one boundary per step — awaiting one would make every `next()` asynchronous), `@invariant` (evaluated on every accessor access), and a schema arm (`validate` is synchronous). Each refusal happens where the declaration is written, naming the reason.
|
|
798
|
+
|
|
799
|
+
The exit checks keep their place. When no arm asked to be awaited, `@ensures` and the exit `@invariant` run in the tick the body settles in, so a caller that resumes cannot observe state the invariant has not approved. Only a declaring arm adds a suspension, and the exit `@invariant` runs as soon as that suspension settles.
|
|
800
|
+
|
|
801
|
+
An awaited `@demands` keeps the instance reachable across one more await boundary, so a concurrent caller can observe it between the check and the body. That window is the same one a hand-written guard that reads a database already has; it is not hidden here.
|
|
802
|
+
|
|
803
|
+
### Generators
|
|
804
|
+
|
|
805
|
+
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:
|
|
806
|
+
|
|
807
|
+
```text
|
|
808
|
+
call -> @invariant, @demands the call arguments are P
|
|
809
|
+
next() -> @invariant entry of the step
|
|
810
|
+
segment -> body up to the next yield
|
|
811
|
+
next() -> @ensures, @invariant the yielded value and the new state are Q
|
|
812
|
+
```
|
|
813
|
+
|
|
814
|
+
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:
|
|
815
|
+
|
|
816
|
+
```typescript
|
|
817
|
+
class Counter extends Contracted {
|
|
818
|
+
protected _count = 0;
|
|
819
|
+
|
|
820
|
+
@ensures(({ self, args: [_value], old }: EnsuresSubject<Counter, [number], unknown>) => self._count === old._count + 1)
|
|
821
|
+
*tick(): Generator<number> {
|
|
822
|
+
this._count++; yield this._count; // each step is checked
|
|
823
|
+
this._count++; yield this._count;
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
```
|
|
827
|
+
|
|
828
|
+
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.
|
|
829
|
+
|
|
830
|
+
#### Why the invariant runs on every resume
|
|
831
|
+
|
|
832
|
+
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.
|
|
833
|
+
|
|
834
|
+
```typescript
|
|
835
|
+
const iterator = ledger.payments();
|
|
836
|
+
iterator.next(); // segment 1 checked on exit
|
|
837
|
+
ledger.audit(); // a public call, and it sees a valid object
|
|
838
|
+
```
|
|
839
|
+
|
|
840
|
+
#### `@demands` describes the call
|
|
841
|
+
|
|
842
|
+
`@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`:
|
|
843
|
+
|
|
844
|
+
```typescript
|
|
845
|
+
@demands(({ args: [count] }) => count > 0)
|
|
846
|
+
*gen(count: number): Generator<number> { /* ... */ }
|
|
847
|
+
|
|
848
|
+
for (const value of obj.gen(3)) { /* works: no value is injected */ }
|
|
849
|
+
```
|
|
850
|
+
|
|
851
|
+
#### `@rescue` covers the traversal
|
|
852
|
+
|
|
853
|
+
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.
|
|
854
|
+
|
|
855
|
+
## Note on Private Fields and Accessors
|
|
856
|
+
|
|
857
|
+
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:
|
|
858
|
+
|
|
859
|
+
```typescript
|
|
860
|
+
class Example extends Contracted {
|
|
861
|
+
private _value = 0;
|
|
862
|
+
get value() { return this._value; }
|
|
863
|
+
set value(v: number) { this._value = v; }
|
|
864
|
+
}
|
|
865
|
+
```
|
|
866
|
+
|
|
867
|
+
Do **not** use:
|
|
868
|
+
|
|
869
|
+
- `#privateField` syntax
|
|
870
|
+
- `accessor foo` syntax
|
|
871
|
+
|
|
872
|
+
These will not work correctly with the contract enforcement provided by this library.
|
|
873
|
+
|
|
874
|
+
## Invariants
|
|
875
|
+
|
|
876
|
+
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.
|
|
877
|
+
|
|
878
|
+
```typescript
|
|
879
|
+
@invariant(({ self }) => self.value >= 0)
|
|
880
|
+
class Foo extends Contracted {
|
|
881
|
+
protected _value = 0;
|
|
882
|
+
get value() { return this._value; }
|
|
883
|
+
set value(v: number) { this._value = v; }
|
|
884
|
+
|
|
885
|
+
inc(): void { this.value++; }
|
|
886
|
+
dec(): void { this.value--; }
|
|
887
|
+
}
|
|
888
|
+
```
|
|
889
|
+
|
|
890
|
+
### Contract predicates must return a boolean
|
|
891
|
+
|
|
892
|
+
`@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.
|
|
893
|
+
|
|
894
|
+
```typescript
|
|
895
|
+
@demands(() => Promise.resolve(true)) // AssertionError: returned a Promise
|
|
896
|
+
```
|
|
897
|
+
|
|
898
|
+
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.
|
|
899
|
+
|
|
900
|
+
A predicate that needs an asynchronous answer is supported on an `async` feature, when the declaration opts in: see [An awaited predicate](#an-awaited-predicate).
|
|
901
|
+
|
|
902
|
+
Asynchronous *features* are supported; see [Asynchronous features](#asynchronous-features).
|
|
903
|
+
|
|
904
|
+
### Contract predicates may not change the instance
|
|
905
|
+
|
|
906
|
+
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.
|
|
907
|
+
|
|
908
|
+
```typescript
|
|
909
|
+
@demands(({ self }) => { self._value = 0; return true; })
|
|
910
|
+
// TypeError: A contract predicate may not assign '_value'.
|
|
911
|
+
```
|
|
912
|
+
|
|
913
|
+
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.
|
|
914
|
+
|
|
915
|
+
```typescript
|
|
916
|
+
@invariant(({ self }) => {
|
|
917
|
+
self._value = 0; // would repair the state being checked
|
|
918
|
+
return self._value >= 0; // and then pass
|
|
919
|
+
})
|
|
920
|
+
```
|
|
921
|
+
|
|
922
|
+
`@rescue` is deliberately **not** restricted. Restoring corrupted state is its purpose, so its handler receives the raw instance.
|
|
923
|
+
|
|
924
|
+
#### What is not blocked
|
|
925
|
+
|
|
926
|
+
The guard covers the instance's own surface. A mutation *through* a nested value still reaches the shared object:
|
|
927
|
+
|
|
928
|
+
```typescript
|
|
929
|
+
@demands(({ self }) => { self._items.push(item); return true; }) // not intercepted
|
|
930
|
+
```
|
|
931
|
+
|
|
932
|
+
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.
|
|
933
|
+
|
|
934
|
+
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.
|
|
935
|
+
|
|
936
|
+
### Subcontracting and Invariants
|
|
937
|
+
|
|
938
|
+
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.
|
|
939
|
+
|
|
940
|
+
```typescript
|
|
941
|
+
@invariant(({ self }) => self.value >= 0)
|
|
942
|
+
class Base extends Contracted {
|
|
943
|
+
// ...
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
@invariant(({ self }) => self.value <= 10)
|
|
947
|
+
class Sub extends Base {
|
|
948
|
+
// ...
|
|
949
|
+
}
|
|
950
|
+
// The effective invariant for Sub is: (self.value >= 0) && (self.value <= 10)
|
|
951
|
+
```
|
|
952
|
+
|
|
953
|
+
## Demands
|
|
954
|
+
|
|
955
|
+
Use the `@demands` decorator to specify preconditions for methods or get/set. If the condition fails, an error is thrown before the method executes.
|
|
956
|
+
|
|
957
|
+
```typescript
|
|
958
|
+
class Foo extends Contracted {
|
|
959
|
+
protected _value = 0;
|
|
960
|
+
get value() { return this._value; }
|
|
961
|
+
set value(v: number) { this._value = v; }
|
|
962
|
+
|
|
963
|
+
@demands(({ self }) => self.value >= 0)
|
|
964
|
+
dec(): void { this.value--; }
|
|
965
|
+
}
|
|
966
|
+
```
|
|
967
|
+
|
|
968
|
+
### Subcontracting and Demands
|
|
969
|
+
|
|
970
|
+
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.
|
|
971
|
+
|
|
972
|
+
```typescript
|
|
973
|
+
class Base extends Contracted {
|
|
974
|
+
@demands(({ args: [x] }) => x >= 0)
|
|
975
|
+
foo(x: number) { /* ... */ }
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
class Sub extends Base {
|
|
979
|
+
@demands(({ args: [x] }) => x === 42)
|
|
980
|
+
override foo(x: number) { /* ... */ }
|
|
981
|
+
}
|
|
982
|
+
// The effective demand for Sub#foo is: (x >= 0) || (x === 42)
|
|
983
|
+
```
|
|
984
|
+
|
|
985
|
+
A demand is called with a `DemandsSubject`: `{ self, args }`. `args` is the
|
|
986
|
+
**argument list** of the invocation, so destructure it inside the parameter:
|
|
987
|
+
`({ args: [x] }) => x >= 0`. Writing `({ args }) => args >= 0` does not compile,
|
|
988
|
+
because `args` is the array rather than the first argument.
|
|
989
|
+
|
|
990
|
+
A predicate takes one object rather than a positional list, so the shape it
|
|
991
|
+
expects is visible where it is declared: a predicate that reads only `self` is
|
|
992
|
+
written `({ self }) => ...`, and the parameter list says so. The runtime supplies
|
|
993
|
+
every field listed above whether or not the predicate destructures it.
|
|
994
|
+
|
|
995
|
+
## Ensures
|
|
996
|
+
|
|
997
|
+
Use the `@ensures` decorator to specify postconditions for methods or get/set. If the condition fails, an error is thrown after the method executes.
|
|
998
|
+
|
|
999
|
+
```typescript
|
|
1000
|
+
class Foo extends Contracted {
|
|
1001
|
+
protected _value = 0;
|
|
1002
|
+
get value() { return this._value; }
|
|
1003
|
+
set value(v: number) { this._value = v; }
|
|
1004
|
+
|
|
1005
|
+
@ensures(({ self }) => self.value >= 0)
|
|
1006
|
+
dec(): void { this.value--; }
|
|
1007
|
+
}
|
|
1008
|
+
```
|
|
1009
|
+
|
|
1010
|
+
### The `old` instance
|
|
1011
|
+
|
|
1012
|
+
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:
|
|
1013
|
+
|
|
1014
|
+
```typescript
|
|
1015
|
+
class Counter extends Contracted {
|
|
1016
|
+
protected _n = 0;
|
|
1017
|
+
get n() { return this._n; }
|
|
1018
|
+
|
|
1019
|
+
@ensures(({ self, old }) => self.n === old.n + 1)
|
|
1020
|
+
inc(): void { this._n++; }
|
|
1021
|
+
}
|
|
1022
|
+
```
|
|
1023
|
+
|
|
1024
|
+
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:
|
|
1025
|
+
|
|
1026
|
+
| Value | Behaviour in `old` |
|
|
1027
|
+
| --- | --- |
|
|
1028
|
+
| Primitives | copied |
|
|
1029
|
+
| Arrays | cloned recursively |
|
|
1030
|
+
| `Date` | cloned |
|
|
1031
|
+
| `Map`, `Set` | cloned (keys and values recursively) |
|
|
1032
|
+
| Plain objects | cloned recursively, including cycles |
|
|
1033
|
+
| Class instances | **shared by reference** |
|
|
1034
|
+
| Functions | **shared by reference** |
|
|
1035
|
+
|
|
1036
|
+
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.
|
|
1037
|
+
|
|
1038
|
+
Accessors are copied as descriptors rather than evaluated, so snapshotting never invokes a getter.
|
|
1039
|
+
|
|
1040
|
+
### The `oldArgs` arguments
|
|
1041
|
+
|
|
1042
|
+
`oldArgs` is the same snapshot, taken over the call's arguments instead of the
|
|
1043
|
+
instance. It is what lets a postcondition describe an object it was *given*: a
|
|
1044
|
+
consequence that spans two objects belongs to neither one, so it is stated by a class
|
|
1045
|
+
that takes both as arguments, and `oldArgs` is how that class asks what its argument
|
|
1046
|
+
was before the call.
|
|
1047
|
+
|
|
1048
|
+
```typescript
|
|
1049
|
+
class Usage extends Contracted {
|
|
1050
|
+
@demands(({ args: [book] }) => !book.onHold)
|
|
1051
|
+
@ensures(({ args: [book], oldArgs: [before] }) => book.onHold && !before.onHold)
|
|
1052
|
+
holdForPatron(book: Book, _patron: string): void { book.placeHold(_patron); }
|
|
1053
|
+
}
|
|
1054
|
+
```
|
|
1055
|
+
|
|
1056
|
+
Without `oldArgs` the only spelling of that property is `book.onHold && !book.onHold`,
|
|
1057
|
+
which is false for every book, or a comparison against the argument itself, which is
|
|
1058
|
+
vacuously true: `old` shares a class instance by reference, so `old.…` and `self.…` are
|
|
1059
|
+
the same object when the instance is held in a field.
|
|
1060
|
+
|
|
1061
|
+
It follows `old`'s policy exactly, and one detail is worth stating because it differs
|
|
1062
|
+
from the instance case: a **contracted argument** is copied the way `old` is. The copy
|
|
1063
|
+
is a new object that shares the argument's prototype and its own state, so a getter on
|
|
1064
|
+
it reads the historical value. Its descriptors are read below the proxy, so
|
|
1065
|
+
snapshotting an argument does not run that object's contracts and does not fail on an
|
|
1066
|
+
instance that is already invalid. Every other argument takes the field rule: plain
|
|
1067
|
+
containers are cloned, class instances are shared by reference.
|
|
1068
|
+
|
|
1069
|
+
The snapshot is taken **after `@demands` and before the body**, so it is the argument
|
|
1070
|
+
the body actually receives — a normalizing precondition has already replaced it — and
|
|
1071
|
+
a mutation the body makes is not visible through it. A `@rescue` that retries takes a
|
|
1072
|
+
fresh snapshot for the retried attempt.
|
|
1073
|
+
|
|
1074
|
+
It is taken whenever the feature declares a predicate `@ensures` arm, whether or
|
|
1075
|
+
not that particular arm reads it, because an arm is not inspectable for what it
|
|
1076
|
+
references. One case is excluded on the strength of the declaration rather than a
|
|
1077
|
+
guess: when **every** `@ensures` arm is a Standard Schema, no arm is handed the
|
|
1078
|
+
subject at all — a schema validates the result — so neither snapshot is taken.
|
|
1079
|
+
|
|
1080
|
+
Two consequences follow when an arm could read it:
|
|
1081
|
+
|
|
1082
|
+
- An argument that cannot be described fails the call. A `Proxy` with a throwing
|
|
1083
|
+
`getPrototypeOf`, for instance, raises a `TypeError` naming the feature and the
|
|
1084
|
+
argument's position before the body runs.
|
|
1085
|
+
- A large plain-data argument is deep-cloned on every call. A 200 000-element array
|
|
1086
|
+
measured 1.4 ms per call, against about 1 µs for the same feature with no `@ensures`.
|
|
1087
|
+
|
|
1088
|
+
A getter and a generator carry an empty `oldArgs`: their `args` describes a result or
|
|
1089
|
+
a yielded value, neither of which has a pre-state.
|
|
1090
|
+
|
|
1091
|
+
### Subcontracting and Ensures
|
|
1092
|
+
|
|
1093
|
+
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.
|
|
1094
|
+
|
|
1095
|
+
```typescript
|
|
1096
|
+
class Base extends Contracted {
|
|
1097
|
+
@ensures(({ args: [x] }) => x >= 0)
|
|
1098
|
+
foo(x: number) { /* ... */ }
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
class Sub extends Base {
|
|
1102
|
+
@ensures(({ args: [x] }) => x <= 10)
|
|
1103
|
+
override foo(x: number) { /* ... */ }
|
|
1104
|
+
}
|
|
1105
|
+
// The effective ensures for Sub#foo is: (x >= 0) && (x <= 10)
|
|
1106
|
+
```
|
|
1107
|
+
|
|
1108
|
+
A postcondition is called with an `EnsuresSubject`: `{ self, args, old, result }`.
|
|
1109
|
+
`args` is the argument list, `old` is the snapshot of the instance from before the
|
|
1110
|
+
feature ran, and `result` is the value the feature produced. Destructure the
|
|
1111
|
+
fields the predicate reads; the runtime supplies the rest unused.
|
|
1112
|
+
|
|
1113
|
+
### The `result`
|
|
1114
|
+
|
|
1115
|
+
A postcondition receives `result`, the value the feature returned:
|
|
1116
|
+
|
|
1117
|
+
```typescript
|
|
1118
|
+
class Proposal extends Contracted {
|
|
1119
|
+
protected _state = 'Draft';
|
|
1120
|
+
get state() { return this._state; }
|
|
1121
|
+
|
|
1122
|
+
@ensures(({ result }: EnsuresSubject<Contracted, any[], any>) => result.state === 'Proposed')
|
|
1123
|
+
submit(): Proposal {
|
|
1124
|
+
this._state = 'Proposed';
|
|
1125
|
+
return this;
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
```
|
|
1129
|
+
|
|
1130
|
+
For a getter, `result` is the value the getter returned. For an `async` feature
|
|
1131
|
+
it is the settled value, so the postcondition observes the promise's resolution
|
|
1132
|
+
rather than the promise. For a generator it is the value yielded by the step being
|
|
1133
|
+
checked, because a generator's boundary is per step.
|
|
1134
|
+
|
|
1135
|
+
A rejected `async` feature has no value to describe, so `@ensures` does not run for
|
|
1136
|
+
it; the rejection reaches the caller (or `@rescue`) directly. The same holds for a
|
|
1137
|
+
getter that returns a promise, which is refused as an `async` mistake before any
|
|
1138
|
+
postcondition is evaluated: `result` is therefore the value a *synchronous* getter
|
|
1139
|
+
returned.
|
|
1140
|
+
|
|
1141
|
+
Every arm receives the **same** result: the raw value the body produced. A
|
|
1142
|
+
normalizing schema arm validates that value and only then replaces what the caller
|
|
1143
|
+
receives, so a predicate and a normalizing schema in one composition agree about
|
|
1144
|
+
what they were shown. `result` is therefore *not* the post-normalization value.
|
|
1145
|
+
|
|
1146
|
+
A write has no value to deliver, so for a setter `result` is the value that was
|
|
1147
|
+
assigned.
|
|
1148
|
+
|
|
1149
|
+
## Rescue
|
|
1150
|
+
|
|
1151
|
+
Use the `@rescue` decorator to handle exceptions thrown by a method, restore invariants, or retry execution:
|
|
1152
|
+
|
|
1153
|
+
```typescript
|
|
1154
|
+
import { Contracted, rescue } from '@final-hill/decorator-contracts';
|
|
1155
|
+
|
|
1156
|
+
class Example extends Contracted {
|
|
1157
|
+
private _value = 3;
|
|
1158
|
+
get value() { return this._value; }
|
|
1159
|
+
set value(v) { this._value = v; }
|
|
1160
|
+
|
|
1161
|
+
@rescue(({ self }) => self.value = 5)
|
|
1162
|
+
method1(): void { throw new Error('I am error'); }
|
|
1163
|
+
}
|
|
1164
|
+
```
|
|
1165
|
+
|
|
1166
|
+
You can also use the `retry` function in your rescue handler to attempt the method again:
|
|
1167
|
+
|
|
1168
|
+
```typescript
|
|
1169
|
+
class Example extends Contracted {
|
|
1170
|
+
@rescue(({ retry }) => retry(3))
|
|
1171
|
+
method(value: number): number {
|
|
1172
|
+
if (value <= 0)
|
|
1173
|
+
throw new Error('value must be greater than 0');
|
|
1174
|
+
else
|
|
1175
|
+
return value;
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
```
|
|
1179
|
+
|
|
1180
|
+
`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:
|
|
1181
|
+
|
|
1182
|
+
```typescript
|
|
1183
|
+
@rescue(({ args, retry }) => retry(...args))
|
|
1184
|
+
```
|
|
1185
|
+
|
|
1186
|
+
Calling `retry()` retries with no arguments.
|
|
1187
|
+
|
|
1188
|
+
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:
|
|
1189
|
+
|
|
1190
|
+
```typescript
|
|
1191
|
+
@rescue(({ args, retry }) => {
|
|
1192
|
+
// the handler restores state, then asks for a second attempt
|
|
1193
|
+
retry(...args);
|
|
1194
|
+
})
|
|
1195
|
+
method(value: number): number { /* ... */ }
|
|
1196
|
+
```
|
|
1197
|
+
|
|
1198
|
+
This keeps the postcondition meaningful: a result the body never produced would not be covered by `@ensures`.
|
|
1199
|
+
|
|
1200
|
+
### What a `@rescue` observes
|
|
1201
|
+
|
|
1202
|
+
A handler is the place to repair an instance, so it sees every failure that leaves state worth repairing:
|
|
1203
|
+
|
|
1204
|
+
| Failure | Reaches the feature's own `@rescue`? |
|
|
1205
|
+
| --- | --- |
|
|
1206
|
+
| the body throws | **yes** |
|
|
1207
|
+
| own `@ensures` fails | **yes** |
|
|
1208
|
+
| own `@invariant` fails, on entry or exit | **yes** |
|
|
1209
|
+
| own `@demands` fails | **no** |
|
|
1210
|
+
|
|
1211
|
+
The last row is deliberate. A precondition rejects a call that has not begun, so there is no body to resume, and a handler that retried with an argument the precondition also rejects would recurse without end. A failed precondition therefore reaches the caller directly.
|
|
1212
|
+
|
|
1213
|
+
The third row is what makes a broken instance recoverable. Once an instance fails its invariant, every accessor throws on exit, so without this a handler could not even reach the state it would fix:
|
|
1214
|
+
|
|
1215
|
+
```typescript
|
|
1216
|
+
import nodeAssert from 'node:assert/strict';
|
|
1217
|
+
import { Contracted, invariant, rescue } from '@final-hill/decorator-contracts';
|
|
1218
|
+
|
|
1219
|
+
@invariant(({ self }) => self._balance >= 0)
|
|
1220
|
+
class Account extends Contracted {
|
|
1221
|
+
public _balance = 1;
|
|
1222
|
+
@rescue(({ self }) => { self._balance = 0; })
|
|
1223
|
+
withdraw(amount: number): void { this._balance -= amount; }
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
const account = Account.new();
|
|
1227
|
+
nodeAssert.throws(() => account.withdraw(5), /@invariant failed/); // overdrawn
|
|
1228
|
+
account._balance; // 0 — usable again
|
|
1229
|
+
```
|
|
1230
|
+
|
|
1231
|
+
The call still fails, because `@rescue` resumes a body and this one has already run. What the handler buys is an instance that is valid again, which a later `retry` can use.
|
|
1232
|
+
|
|
1233
|
+
A getter or setter behaves the same way: the handler runs and can repair the instance, but the access is not resumed, because an accessor has no body to re-run. A handler that repairs a getter's state therefore leaves the instance usable without that particular read succeeding.
|
|
1234
|
+
|
|
1235
|
+
A handler is called **before** the invariant is re-tested, so it can repair the state rather than being denied the attempt. That means a handler observes the error that failed, which is the body's own error when the body threw.
|
|
1236
|
+
|
|
1237
|
+
When nothing has repaired the instance, the invariant failure supersedes the original on the way to the caller, and the original travels as `cause`:
|
|
1238
|
+
|
|
1239
|
+
```typescript
|
|
1240
|
+
import { Contracted, invariant } from '@final-hill/decorator-contracts';
|
|
1241
|
+
|
|
1242
|
+
@invariant(({ self }) => self._balance >= 0)
|
|
1243
|
+
class Account extends Contracted {
|
|
1244
|
+
public _balance = 1;
|
|
1245
|
+
|
|
1246
|
+
withdraw(amount: number): void {
|
|
1247
|
+
this._balance -= amount;
|
|
1248
|
+
if (this._balance < 0) throw new Error('insufficient funds');
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
try {
|
|
1253
|
+
Account.new().withdraw(5); // body throws, and leaves the balance negative
|
|
1254
|
+
} catch (error: any) {
|
|
1255
|
+
error.violation.contract; // '@invariant'
|
|
1256
|
+
error.cause.message; // 'insufficient funds'
|
|
1257
|
+
}
|
|
1258
|
+
```
|
|
1259
|
+
|
|
1260
|
+
A handler that repairs the state before declining to retry prevents that: the instance is valid by the time the invariant is re-tested, so the body's own error is what the caller receives.
|
|
1261
|
+
|
|
1262
|
+
Because a handler runs before the invariant is re-tested, it receives the error that failed rather than the invariant failure that may supersede it. A per-feature handler knows which feature it was attached to, so that is unambiguous; a class-level handler covers every feature, which is why the subject carries `feature` (see [One handler for a whole class](#one-handler-for-a-whole-class)).
|
|
1263
|
+
|
|
1264
|
+
### Retry bounds
|
|
1265
|
+
|
|
1266
|
+
`retry` restarts the body, so it can always be attempted again. The one boundary that cannot be restarted is the *entry* check: nothing has run yet, so a retry can only re-check the state the handler just set. That repair is attempted **once**; if the invariant still fails, the failure is raised rather than looping, because every further attempt would fail identically.
|
|
1267
|
+
|
|
1268
|
+
Everywhere else, retries are unbounded by default and `maxRetries` bounds them, as described under [N-Version programming](#robustness-organized-panic-and-the-benefits-of-rescue). An unbounded handler that never repairs will therefore loop until it does — that is the price of allowing a handler to choose the next alternative.
|
|
1269
|
+
|
|
1270
|
+
### One handler for a whole class
|
|
1271
|
+
|
|
1272
|
+
`@rescue` also applies to a class, where it covers every feature that declares none of its own:
|
|
1273
|
+
|
|
1274
|
+
```typescript
|
|
1275
|
+
import { Contracted, rescue } from '@final-hill/decorator-contracts';
|
|
1276
|
+
|
|
1277
|
+
@rescue(({ feature, error }) => {
|
|
1278
|
+
// one translation and one telemetry event, whichever verb failed
|
|
1279
|
+
console.log(`${String(feature)} failed`, error);
|
|
1280
|
+
})
|
|
1281
|
+
class Service extends Contracted {
|
|
1282
|
+
charge(_amount: number): void { /* ... */ }
|
|
1283
|
+
refund(_amount: number): void { /* ... */ }
|
|
1284
|
+
}
|
|
1285
|
+
```
|
|
1286
|
+
|
|
1287
|
+
The subject is unchanged, and `feature` is what makes the form usable: a per-feature handler knows its own name because it was written next to it, while a class-level handler serves all of them. It holds the property key the lifecycle was running for, so `delete` reports the deleted property and an accessor reports its own name.
|
|
1288
|
+
|
|
1289
|
+
**Precedence** is fixed, and the two rules answer different questions:
|
|
1290
|
+
|
|
1291
|
+
1. A **feature-level** declaration wins over any class-level one, including one on the class that declares the feature. Inheriting a feature declaration from a base class already works, and being inherited is not a reason to lose to the class-level form.
|
|
1292
|
+
2. Otherwise the **nearest class-level** declaration walking up the constructor chain applies, so a subclass overrides a handler its base declared without restating it per feature.
|
|
1293
|
+
|
|
1294
|
+
```typescript
|
|
1295
|
+
class Base extends Contracted {
|
|
1296
|
+
@rescue(({ self }) => { self._reset(); }) // 1: wins for `run`
|
|
1297
|
+
run(): void { throw new Error('boom'); }
|
|
1298
|
+
|
|
1299
|
+
_reset(): void { /* ... */ }
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
@rescue(({ error }) => { console.log(error); }) // 2: wins for `other`
|
|
1303
|
+
class Sub extends Base {
|
|
1304
|
+
other(): void { throw new Error('boom'); }
|
|
1305
|
+
}
|
|
1306
|
+
```
|
|
1307
|
+
|
|
1308
|
+
**What it covers** is every feature the lifecycle runs for: methods, getters, setters, async functions, generators, and the `delete` trap. A getter has no body to re-run, so `retry` on a failing read restarts the read rather than supplying a value, which is what a per-feature handler does already.
|
|
1309
|
+
|
|
1310
|
+
A `_`-prefixed feature is covered by neither form. The decorator refuses a feature-level `@rescue` on one, so the class-level form leaves it out too: a feature a consumer cannot override is a feature they could not exempt from the class handler.
|
|
1311
|
+
|
|
1312
|
+
**What it does not solve.** A class-level handler inherits the per-feature semantics exactly, so it does not make a typed precondition reachable: a failed `@demands` still never consults a handler, because nothing ran. Rescue means "resume the body", and a failed precondition has no body to resume; use the [`onViolation` factory](#raising-a-typed-error-with-onviolation) for that.
|
|
1313
|
+
|
|
1314
|
+
`maxRetries` is counted per invocation of the feature the handler served, not across the class, so two failing calls each get their own budget, and one failing feature does not spend another's.
|
|
1315
|
+
|
|
1316
|
+
### Robustness, Organized Panic, and the Benefits of `@rescue`
|
|
1317
|
+
|
|
1318
|
+
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**.
|
|
1319
|
+
|
|
1320
|
+
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.
|
|
1321
|
+
|
|
1322
|
+
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.
|
|
1323
|
+
|
|
1324
|
+
A dated example of this is performing ajax requests in a multi-browser environment:
|
|
1325
|
+
|
|
1326
|
+
```typescript
|
|
1327
|
+
import { Contracted, rescue } from '@final-hill/decorator-contracts';
|
|
1328
|
+
|
|
1329
|
+
declare function legacyGet(url: string): string;
|
|
1330
|
+
declare function activeXGet(url: string): string;
|
|
1331
|
+
declare function xhrGet(url: string): string;
|
|
1332
|
+
declare const window: any;
|
|
1333
|
+
|
|
1334
|
+
class AjaxRequest extends Contracted {
|
|
1335
|
+
private _version = 0;
|
|
1336
|
+
private _versions = ['legacy', 'activex', 'xhr'] as const;
|
|
1337
|
+
|
|
1338
|
+
@rescue(({ self, args, retry }) => {
|
|
1339
|
+
self._version++;
|
|
1340
|
+
retry(...args);
|
|
1341
|
+
}, { maxRetries: 2 })
|
|
1342
|
+
get(url: string): string {
|
|
1343
|
+
const version = this._versions[this._version];
|
|
1344
|
+
|
|
1345
|
+
switch (version) {
|
|
1346
|
+
case 'legacy':
|
|
1347
|
+
if (!window.XMLHttpRequest) throw new Error(`${version} unsupported`);
|
|
1348
|
+
return legacyGet(url);
|
|
1349
|
+
case 'activex':
|
|
1350
|
+
if (!window.ActiveXObject) throw new Error(`${version} unsupported`);
|
|
1351
|
+
return activeXGet(url);
|
|
1352
|
+
default:
|
|
1353
|
+
return xhrGet(url);
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
```
|
|
1358
|
+
|
|
1359
|
+
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:
|
|
1360
|
+
|
|
1361
|
+
```typescript
|
|
1362
|
+
@rescue(({ args, retry }) => retry(...args), { maxRetries: 3 })
|
|
1363
|
+
```
|
|
1364
|
+
|
|
1365
|
+
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.
|
|
1366
|
+
|
|
1367
|
+
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:
|
|
1368
|
+
|
|
1369
|
+
- You can lexically determine where exception handling occurs.
|
|
1370
|
+
- You can restore invariants or perform corrective actions before retrying or failing.
|
|
1371
|
+
- 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.
|
|
1372
|
+
- You can implement alternative strategies for error recovery, supporting N-Version programming and redundancy.
|
|
1373
|
+
|
|
1374
|
+
**Inheritance:**
|
|
1375
|
+
|
|
1376
|
+
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. A class-level declaration follows the same rule and is inherited by a subclass that declares none of its own; see [One handler for a whole class](#one-handler-for-a-whole-class) for how the two forms rank against each other.
|
|
1377
|
+
|
|
1378
|
+
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.
|
|
1379
|
+
|
|
1380
|
+
## Standard Schema
|
|
1381
|
+
|
|
1382
|
+
`@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.
|
|
1383
|
+
|
|
1384
|
+
```typescript
|
|
1385
|
+
import { z } from 'zod';
|
|
1386
|
+
import { Contracted, demands, ensures } from '@final-hill/decorator-contracts';
|
|
1387
|
+
|
|
1388
|
+
const positive = z.number().positive();
|
|
1389
|
+
const quantity = z.tuple([z.number().positive()]);
|
|
1390
|
+
|
|
1391
|
+
class Inventory extends Contracted {
|
|
1392
|
+
protected _stock = 0;
|
|
1393
|
+
get stock() { return this._stock; }
|
|
1394
|
+
|
|
1395
|
+
@demands(quantity) // validates the argument tuple
|
|
1396
|
+
@ensures(positive) // validates the result
|
|
1397
|
+
add(...[count]: [number]): number {
|
|
1398
|
+
this._stock += count;
|
|
1399
|
+
|
|
1400
|
+
return this._stock;
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
```
|
|
1404
|
+
|
|
1405
|
+
### What a schema validates
|
|
1406
|
+
|
|
1407
|
+
The subject is the subject the contract already describes, so the two kinds of arm are interchangeable:
|
|
1408
|
+
|
|
1409
|
+
| Decorator | A schema validates | A predicate receives | Composition |
|
|
1410
|
+
| --- | --- | --- | --- |
|
|
1411
|
+
| `@invariant` | the instance | `({ self })` | AND |
|
|
1412
|
+
| `@demands` | the **argument tuple** | `({ self, args })` | OR |
|
|
1413
|
+
| `@ensures` | the **result** | `({ self, args, old, oldArgs, result })` | AND |
|
|
1414
|
+
|
|
1415
|
+
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, and it is what makes an issue's `path` point at the argument that failed.
|
|
1416
|
+
|
|
1417
|
+
A schema is the subject for the contract, not for the feature it happens to guard: `@demands` takes the tuple, `@ensures` takes the result, `@invariant` takes the instance. Declaring the tuple once and sharing it keeps that true across every feature with the same shape:
|
|
1418
|
+
|
|
1419
|
+
```typescript
|
|
1420
|
+
const quantity = z.tuple([z.number().positive()]);
|
|
1421
|
+
|
|
1422
|
+
class Inventory extends Contracted {
|
|
1423
|
+
@demands(quantity) add(count: number): number { /* ... */ }
|
|
1424
|
+
@demands(quantity) remove(count: number): number { /* ... */ }
|
|
1425
|
+
}
|
|
1426
|
+
```
|
|
1427
|
+
|
|
1428
|
+
### `normalize` and `@invariant`
|
|
1429
|
+
|
|
1430
|
+
`normalize` replaces the contract's subject with the schema's output, which is meaningful where the subject is something the runtime can substitute: the arguments for `@demands`, and the result for `@ensures`.
|
|
1431
|
+
|
|
1432
|
+
An invariant's subject is the instance, and nothing replaces it. `normalize` is therefore **refused at decoration time**, for either kind of arm:
|
|
1433
|
+
|
|
1434
|
+
```text
|
|
1435
|
+
@invariant cannot normalize: its subject is the instance, which no arm can replace.
|
|
1436
|
+
```
|
|
1437
|
+
|
|
1438
|
+
The option is refused for what it would do rather than for appearing, so
|
|
1439
|
+
`normalize: false` is still accepted.
|
|
1440
|
+
|
|
1441
|
+
### Composition follows variance
|
|
1442
|
+
|
|
1443
|
+
The rules above are the substitution rules, not a convention:
|
|
1444
|
+
|
|
1445
|
+
- **`@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.
|
|
1446
|
+
- **`@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.
|
|
1447
|
+
|
|
1448
|
+
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.
|
|
1449
|
+
|
|
1450
|
+
**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.
|
|
1451
|
+
|
|
1452
|
+
Because that mistake is easy to make and silent, declaring a `@demands` arm on a feature that already has inherited arms **warns** at decoration time, naming the feature and the inherited arm count:
|
|
1453
|
+
|
|
1454
|
+
```text
|
|
1455
|
+
@demands on add adds an arm to a precondition that already has 2 inherited arm(s).
|
|
1456
|
+
`@demands` is OR-composed, so this arm cannot narrow what the base permits:
|
|
1457
|
+
satisfying any inherited arm still allows the call. Move the restriction to the
|
|
1458
|
+
base feature, or declare the arm with `allowWeakening` if a genuine weakening is
|
|
1459
|
+
what was meant.
|
|
1460
|
+
```
|
|
1461
|
+
|
|
1462
|
+
It warns rather than throws because the arm is always a legal weakening — the defect is the author's model of it, not the declaration. Pass `{ allowWeakening: true }` when the wider precondition is what you meant.
|
|
1463
|
+
|
|
1464
|
+
The warning is issued once per feature however many arms the class declares, since it describes the feature rather than any one arm.
|
|
1465
|
+
|
|
1466
|
+
`allowWeakening` is refused on `@ensures` and `@invariant`. It suppresses a diagnostic about OR-composition, which only a precondition has, so on an AND-composed contract it would be a declaration that could never do anything. This is the same rule `normalize` and `onViolation` follow: an option that cannot act is a mistake about which contract the declaration belongs to.
|
|
1467
|
+
|
|
1468
|
+
**This asymmetry is `@demands`-only.** An `@ensures` arm on a subclass is AND-composed, so it genuinely strengthens the obligation and takes effect:
|
|
1469
|
+
|
|
1470
|
+
```typescript
|
|
1471
|
+
class Base extends Contracted {
|
|
1472
|
+
@ensures(({ result }: { result: number }) => result >= 0)
|
|
1473
|
+
m(): number { return 5; }
|
|
1474
|
+
}
|
|
1475
|
+
|
|
1476
|
+
class Sub extends Base {
|
|
1477
|
+
@ensures(({ result }: { result: number }) => result <= 3) // does restrict the result
|
|
1478
|
+
override m(): number { return 5; }
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
Base.new().m(); // 5
|
|
1482
|
+
Sub.new().m(); // @ensures failed: the base arm passes, the subclass arm does not
|
|
1483
|
+
```
|
|
1484
|
+
|
|
1485
|
+
`@invariant` behaves like `@ensures`: it is AND-composed and covariant. Only a precondition is contravariant, which is why only a precondition has an arm that cannot narrow.
|
|
1486
|
+
|
|
1487
|
+
### Failure reporting
|
|
1488
|
+
|
|
1489
|
+
A schema failure carries the provider's own `issues` in the structured payload, and renders them into the message:
|
|
1490
|
+
|
|
1491
|
+
```typescript
|
|
1492
|
+
try {
|
|
1493
|
+
inventory.add(-1);
|
|
1494
|
+
} catch (error) {
|
|
1495
|
+
error.violation?.contract; // '@demands'
|
|
1496
|
+
error.violation?.issues; // ReadonlyArray<{ message, path? }>
|
|
1497
|
+
}
|
|
1498
|
+
```
|
|
1499
|
+
|
|
1500
|
+
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`:
|
|
1501
|
+
|
|
1502
|
+
```text
|
|
1503
|
+
@demands failed for Shipping.send (1 of 1 schema unsatisfied: schema #1: ...).
|
|
1504
|
+
Reported: 0.zip: Invalid string: must match pattern /^\d{5}$/.
|
|
1505
|
+
```
|
|
1506
|
+
|
|
1507
|
+
### Normalization is opt-in
|
|
1508
|
+
|
|
1509
|
+
`validate` may transform its input. Applying that transformation changes what the body receives and what later contracts observe, so it is an explicit choice:
|
|
1510
|
+
|
|
1511
|
+
```typescript
|
|
1512
|
+
@demands(trimmedName, { normalize: true })
|
|
1513
|
+
rename(name: string): void { /* receives the trimmed name */ }
|
|
1514
|
+
```
|
|
1515
|
+
|
|
1516
|
+
- **`@demands`** is OR-composed, so the **first passing arm** decides the normalized value. That is deterministic and matches evaluation order.
|
|
1517
|
+
- **`@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.
|
|
1518
|
+
|
|
1519
|
+
Off by default: without `normalize`, a schema only reports a verdict.
|
|
1520
|
+
|
|
1521
|
+
### Synchronous only
|
|
1522
|
+
|
|
1523
|
+
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.
|
|
1524
|
+
|
|
1525
|
+
### No type inference
|
|
1526
|
+
|
|
1527
|
+
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.
|
|
1528
|
+
|
|
1529
|
+
### Providers
|
|
1530
|
+
|
|
1531
|
+
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:
|
|
1532
|
+
|
|
1533
|
+
```typescript
|
|
1534
|
+
import type { StandardSchemaV1 } from '@final-hill/decorator-contracts';
|
|
1535
|
+
```
|
|
1536
|
+
|
|
1537
|
+
## Inspecting contracts
|
|
1538
|
+
|
|
1539
|
+
`getContractMetadata(Class)` reports the contracts a class declares, and
|
|
1540
|
+
`getFeatureContracts(Class, feature)` reports the arms that apply to one feature
|
|
1541
|
+
in the order they are evaluated. Use them instead of reading `Contracted[Symbol.metadata]`
|
|
1542
|
+
directly: the symbol holds the record the runtime consults, so a consumer who edits
|
|
1543
|
+
it edits their own class's contracts. The accessors return frozen copies.
|
|
1544
|
+
|
|
1545
|
+
This is what turns "every public verb declares a precondition" into one
|
|
1546
|
+
architectural test rather than one test per verb:
|
|
1547
|
+
|
|
1548
|
+
```typescript
|
|
1549
|
+
import {
|
|
1550
|
+
Contracted, getContractMetadata, getFeatureContracts, demands,
|
|
1551
|
+
} from '@final-hill/decorator-contracts';
|
|
1552
|
+
|
|
1553
|
+
class Repository extends Contracted {
|
|
1554
|
+
public _connected = true;
|
|
1555
|
+
get connected() { return this._connected; }
|
|
1556
|
+
|
|
1557
|
+
@demands(({ self }) => self.connected)
|
|
1558
|
+
read(_id: string): unknown { return { id: _id }; }
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
const metadata = getContractMetadata(Repository);
|
|
1562
|
+
|
|
1563
|
+
metadata.invariants; // every class-level arm
|
|
1564
|
+
metadata.demands['read'].length; // 1: the arms declared for `read`
|
|
1565
|
+
getFeatureContracts(Repository, 'read').demands.length; // 1
|
|
1566
|
+
```
|
|
1567
|
+
|
|
1568
|
+
The lists are already **effective**: a subclass's record contains its own
|
|
1569
|
+
declarations and the inherited ones, so there is no prototype chain to walk. The
|
|
1570
|
+
order is the evaluation order — inherited arms first, then the class's own, and
|
|
1571
|
+
within one class in **reverse source order**, because decorators evaluate
|
|
1572
|
+
bottom-up.
|
|
1573
|
+
|
|
1574
|
+
A class that declares nothing has no record at all, so both accessors report empty
|
|
1575
|
+
lists rather than `undefined`.
|
|
1576
|
+
|
|
1577
|
+
`@rescue` is reported as the declaration the runtime would apply. A feature’s own
|
|
1578
|
+
handler is `metadata.rescue[feature]`; when it declares none, `metadata.classRescue`
|
|
1579
|
+
is the handler a [class-level declaration](#one-handler-for-a-whole-class) gives it,
|
|
1580
|
+
and `getFeatureContracts` returns that one. A `_`-prefixed feature has neither, so
|
|
1581
|
+
both report `undefined` for it.
|
|
1582
|
+
|
|
1583
|
+
### A predicate arm and a schema arm are not equally readable
|
|
1584
|
+
|
|
1585
|
+
The arm you get back is the one you declared, so a test can compare it against the
|
|
1586
|
+
declaration by identity. What it can then *do* with it depends on the kind:
|
|
1587
|
+
|
|
1588
|
+
- A **predicate** is opaque. Calling it is the whole interface: `({ args }) => args[0] > 0`
|
|
1589
|
+
describes its domain nowhere else, and reading its source text would be a second
|
|
1590
|
+
implementation of the predicate that also breaks under minification.
|
|
1591
|
+
- A **schema** may describe its own input when its provider carries the Standard JSON
|
|
1592
|
+
Schema trait, `schema['~standard'].jsonSchema.input({ target: 'draft-2020-12' })`. That
|
|
1593
|
+
is a *separate* trait layered on Standard Schema V1, so it is optional and its
|
|
1594
|
+
coverage varies by provider; and it is lossy, because it reports bounds and `enum` but
|
|
1595
|
+
not refinements, transforms, or a `Date`.
|
|
1596
|
+
|
|
1597
|
+
So a schema arm can *propose* candidate inputs for a contract, and a predicate arm
|
|
1598
|
+
cannot. The verdict is still the contract's either way: a proposed value is only
|
|
1599
|
+
plausible until `validate` accepts it.
|
|
1600
|
+
|
|
1601
|
+
### The stability guarantee
|
|
1602
|
+
|
|
1603
|
+
The shape of `ContractMetadata` and `FeatureContracts` is stable for the major
|
|
1604
|
+
version: fields may be added, but an existing field will not change meaning
|
|
1605
|
+
without one. The *arms* are whatever you declared — a predicate, a schema, and the
|
|
1606
|
+
options passed alongside it — so their identity is preserved and comparing an arm
|
|
1607
|
+
against the one you wrote works.
|
|
1608
|
+
|
|
1609
|
+
## Contracts and your test suite
|
|
1610
|
+
|
|
1611
|
+
A contracted class already *is* a specification: `@demands` states what every
|
|
1612
|
+
permitted call assumes, `@ensures` what it guarantees, and `@invariant` what holds
|
|
1613
|
+
throughout. A test that restates one of those is a second copy of the same claim, and
|
|
1614
|
+
the copy is the one that drifts.
|
|
1615
|
+
|
|
1616
|
+
Three roles split the work. A **requirements class** declares the contracts and does
|
|
1617
|
+
not sequence them. A **specification driver** is a `Contracted` class with no state of
|
|
1618
|
+
its own whose features take the objects they relate as arguments; it states what no
|
|
1619
|
+
single class can, such as *a patron cannot hold a book that is already held*, using
|
|
1620
|
+
`@demands` over its own arguments and `@ensures` over `oldArgs`. A **scenario** is a
|
|
1621
|
+
test that supplies the inputs and shows the behaviour; it validates the
|
|
1622
|
+
specification and does not provide it.
|
|
1623
|
+
|
|
1624
|
+
The rule for a test you already have:
|
|
1625
|
+
|
|
1626
|
+
- An arrange block that only establishes a precondition → the precondition belongs in
|
|
1627
|
+
`@demands`, and the test goes.
|
|
1628
|
+
- An assertion that restates an `@ensures` or an `@invariant` → the test goes.
|
|
1629
|
+
- A property spanning two objects → keep it as a scenario, and if it is not yet a
|
|
1630
|
+
declaration, add the driver that states it.
|
|
1631
|
+
- A house rule over a set of classes → keep it; it reads `getContractMetadata` and no
|
|
1632
|
+
class's contracts can state it.
|
|
1633
|
+
- A regression or an interaction with the environment → keep it; no contract can
|
|
1634
|
+
state either.
|
|
1635
|
+
|
|
1636
|
+
What contracts cannot do is *show behaviour*: they say a property must hold, never
|
|
1637
|
+
what the system does or which inputs are interesting. So a sweep of inputs whose
|
|
1638
|
+
verdicts are the contract's is still a test, and a property over inputs the contract
|
|
1639
|
+
has already approved is still the strongest form of one. [Testing a contracted
|
|
1640
|
+
class](./docs/testing.md) is the long form: arranging state, asserting a failure,
|
|
1641
|
+
mocking, `async`, and generating inputs — including where a schema arm can propose
|
|
1642
|
+
them and a predicate arm cannot.
|
|
1643
|
+
|
|
1644
|
+
## The order of assertions
|
|
1645
|
+
|
|
1646
|
+
When `obj.feature` is called the happy path is:
|
|
1647
|
+
|
|
1648
|
+

|
|
1649
|
+
|
|
1650
|
+
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. That means the nested feature's own contracts do not run; see [An internal call runs none of the callee's contracts](#an-internal-call-runs-none-of-the-callees-contracts).
|
|
1651
|
+
|
|
1652
|
+
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).
|
|
1653
|
+
|
|
1654
|
+
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.
|
|
1655
|
+
|
|
1656
|
+
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.
|
|
1657
|
+
|
|
1658
|
+
If an error is thrown and there is no `@rescue` defined then the `@invariant` is checked before the error is raised to the caller. If the instance has become invalid, that invariant failure is what reaches the caller, with the original error as its `cause`.
|
|
1659
|
+
|
|
1660
|
+
If an error is thrown in the `@invariant` then the `@rescue` is executed, so a handler can restore the state. Without a handler, or once its attempts are spent, the failure is raised to the caller.
|
|
1661
|
+
|
|
1662
|
+
If an error is thrown in the `@demands` then the error is raised to the caller, and `@rescue` is not consulted. A precondition rejects a call that has not begun, so there is no body to resume. The exit `@invariant` is not checked either, because the feature body has not been entered and the instance cannot have changed.
|
|
1663
|
+
|
|
1664
|
+
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.
|
|
1665
|
+
|
|
1666
|
+
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.
|
|
1667
|
+
|
|
1668
|
+
If `@rescue` throws an error or does not call `retry` then the `@invariant` is checked before the error is raised to the caller.
|
|
1669
|
+
|
|
1670
|
+

|
|
1671
|
+
|
|
1672
|
+
## The subject a predicate is called with
|
|
1673
|
+
|
|
1674
|
+
Every contract calls its predicate with a single object. Destructuring is what
|
|
1675
|
+
makes the shape visible at the declaration, and it keeps every declaration to one
|
|
1676
|
+
parameter so a `max-params: 1` configuration is satisfied.
|
|
1677
|
+
|
|
1678
|
+
| Contract | Subject fields |
|
|
1679
|
+
| --- | --- |
|
|
1680
|
+
| `@demands` | `{ self, args }` |
|
|
1681
|
+
| `@ensures` | `{ self, args, old, oldArgs, result }` |
|
|
1682
|
+
| `@invariant` | `{ self }` |
|
|
1683
|
+
| `@rescue` | `{ self, error, args, retry, feature }` |
|
|
1684
|
+
|
|
1685
|
+
Bind the fields a predicate reads and omit the rest; the runtime supplies them all
|
|
1686
|
+
whether or not the parameter list names them. A predicate that destructured its
|
|
1687
|
+
arguments as `[x]` writes `({ args: [x] }) => x > 0`, so the body is unchanged.
|
|
1688
|
+
|
|
1689
|
+
The compiler rejects a parameter list that does not line up with the subject.
|
|
1690
|
+
A two-parameter leftover fails with *Target signature provides too few arguments*:
|
|
1691
|
+
`(self: Cart, [x]: [number]) => ...`. A one-parameter leftover is rejected
|
|
1692
|
+
because the instance is not assignable to a `DemandsSubject`: `(self: Cart) =>
|
|
1693
|
+
...`. Parameters typed `any` are the one case the compiler cannot check, and such
|
|
1694
|
+
a predicate receives the subject object where it expects the instance.
|
|
1695
|
+
|
|
1696
|
+
`retry` is a field of the subject, so a handler that forwards its arguments
|
|
1697
|
+
writes `({ args, retry }) => retry(...args)`.
|
|
1698
|
+
|
|
1699
|
+
The subject is **inferred**, so a predicate that reads instance state usually needs
|
|
1700
|
+
no annotation at all:
|
|
1701
|
+
|
|
1702
|
+
```typescript
|
|
1703
|
+
@demands(({ self, args }) => self.total + args[0] >= 0) // `self` is the class, `args` is the call tuple
|
|
1704
|
+
```
|
|
1705
|
+
|
|
1706
|
+
An annotation is only needed when the runtime subject differs from the call
|
|
1707
|
+
signature. The one place that happens is a generator's `@ensures`, whose `args` is
|
|
1708
|
+
the value the step yielded rather than the call arguments:
|
|
1709
|
+
|
|
1710
|
+
```typescript
|
|
1711
|
+
@ensures(({ args: [yielded] }: EnsuresSubject<Counter, [number]>) => ...)
|
|
1712
|
+
```
|
|
1713
|
+
|
|
1714
|
+
`result` always stays `unknown`, because a method's return type and a getter's
|
|
1715
|
+
property type are both inference sites for it and the compiler would resolve it to
|
|
1716
|
+
their intersection. Name it on the subject when a predicate needs more.
|
|
1717
|
+
|
|
1718
|
+
## Further Reading
|
|
1719
|
+
|
|
1720
|
+
- [Design by Contract](https://en.wikipedia.org/wiki/Design_by_contract)
|
|
1721
|
+
- [Liskov Substitution Principle](https://en.wikipedia.org/wiki/Liskov_substitution_principle)
|
|
1722
|
+
- [Object-Oriented Software Construction](https://en.wikipedia.org/wiki/Object-Oriented_Software_Construction)
|