@final-hill/decorator-contracts 0.24.1 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +22 -143
  2. package/dist/{AssertionError.d.ts → AssertionError.d.mts} +10 -10
  3. package/dist/Contract.d.mts +39 -0
  4. package/dist/Contracted.d.mts +21 -0
  5. package/dist/Messages.d.mts +16 -0
  6. package/dist/{assert.d.ts → assert.d.mts} +8 -8
  7. package/dist/{iff.d.ts → iff.d.mts} +7 -7
  8. package/dist/{implies.d.ts → implies.d.mts} +7 -7
  9. package/dist/index.d.mts +13 -0
  10. package/dist/index.mjs +3 -0
  11. package/dist/{index.js.LICENSE.txt → index.mjs.LICENSE.txt} +1 -1
  12. package/dist/index.mjs.map +1 -0
  13. package/dist/lib/{CLASS_REGISTRY.d.ts → CLASS_REGISTRY.d.mts} +12 -12
  14. package/dist/lib/{ClassRegistration.d.ts → ClassRegistration.d.mts} +23 -24
  15. package/dist/lib/ClassType.d.mts +10 -0
  16. package/dist/lib/{Feature.d.ts → Feature.d.mts} +26 -29
  17. package/dist/lib/{assertDemands.d.ts → assertDemands.d.mts} +9 -9
  18. package/dist/lib/assertEnsures.d.mts +10 -0
  19. package/dist/lib/{assertInvariants.d.ts → assertInvariants.d.mts} +9 -9
  20. package/dist/lib/{deepFreeze.d.ts → deepFreeze.d.mts} +8 -8
  21. package/dist/lib/index.d.mts +18 -0
  22. package/dist/lib/{takeWhile.d.ts → takeWhile.d.mts} +8 -8
  23. package/dist/lib/{unChecked.d.ts → unChecked.d.mts} +9 -9
  24. package/dist/tests/{deepFreeze.test.d.ts → Contract.test.d.mts} +7 -7
  25. package/dist/tests/{Contract.test.d.ts → Stack.test.d.mts} +7 -7
  26. package/dist/tests/{assert.test.d.ts → assert.test.d.mts} +7 -7
  27. package/dist/tests/{Stack.test.d.ts → deepFreeze.test.d.mts} +7 -7
  28. package/dist/tests/demands.test.d.mts +7 -0
  29. package/dist/tests/ensures.test.d.mts +7 -0
  30. package/dist/tests/factoryPattern.test.d.mts +7 -0
  31. package/dist/tests/iff.test.d.mts +7 -0
  32. package/dist/tests/implies.test.d.mts +7 -0
  33. package/dist/tests/invariant.test.d.mts +7 -0
  34. package/dist/tests/public-properties.test.d.mts +7 -0
  35. package/dist/tests/rescue.test.d.mts +7 -0
  36. package/dist/tests/within.test.d.mts +7 -0
  37. package/package.json +26 -46
  38. package/CHANGELOG.md +0 -282
  39. package/dist/Contract.d.ts +0 -39
  40. package/dist/Contracted.d.ts +0 -12
  41. package/dist/Messages.d.ts +0 -18
  42. package/dist/index.d.ts +0 -14
  43. package/dist/index.js +0 -3
  44. package/dist/index.js.map +0 -1
  45. package/dist/lib/ClassType.d.ts +0 -10
  46. package/dist/lib/assertEnsures.d.ts +0 -9
  47. package/dist/lib/index.d.ts +0 -18
  48. package/dist/override.d.ts +0 -8
  49. package/dist/tests/demands.test.d.ts +0 -7
  50. package/dist/tests/ensures.test.d.ts +0 -7
  51. package/dist/tests/factoryPattern.test.d.ts +0 -7
  52. package/dist/tests/iff.test.d.ts +0 -7
  53. package/dist/tests/implies.test.d.ts +0 -7
  54. package/dist/tests/invariant.test.d.ts +0 -7
  55. package/dist/tests/override.test.d.ts +0 -7
  56. package/dist/tests/public-properties.test.d.ts +0 -7
  57. package/dist/tests/rescue.test.d.ts +0 -7
  58. package/dist/tests/within.test.d.ts +0 -7
package/README.md CHANGED
@@ -13,7 +13,6 @@
13
13
  - [Assertions](#assertions)
14
14
  - [Implies](#implies)
15
15
  - [Iff](#iff)
16
- - [Overrides](#overrides)
17
16
  - [Encapsulation](#encapsulation)
18
17
  - [Invariants](#invariants)
19
18
  - [Demands](#demands)
@@ -40,21 +39,29 @@ using this. If you would like an exception to this license per section 7
40
39
 
41
40
  ## Library Installation
42
41
 
43
- As a dependency run the command:
42
+ The latest version:
44
43
 
45
44
  `npm install @final-hill/decorator-contracts`
46
45
 
47
- You can also use a specific [version](https://www.npmjs.com/package/@final-hill/decorator-contracts):
46
+ A specific version:
48
47
 
49
- `npm install @final-hill/decorator-contracts@0.24.1`
48
+ `npm install @final-hill/decorator-contracts@x.x.x`
50
49
 
51
- For use in a webpage:
50
+ For use in a browser (no build step) via [unpkg.com](https://unpkg.com/):
52
51
 
53
- `<script src="https://cdn.skypack.dev/@final-hill/decorator-contracts"></script>`
52
+ ```html
53
+ <script type="importmap">
54
+ {
55
+ "imports": {
56
+ "@final-hill/decorator-contracts": "https://unpkg.com/@final-hill/decorator-contracts"
57
+ }
58
+ }
59
+ </script>
60
+ ```
54
61
 
55
- With a specific [version](https://www.npmjs.com/package/@final-hill/decorator-contracts@0.24.1):
62
+ Via [skypack.dev](https://www.skypack.dev/):
56
63
 
57
- `<script src="https://cdn.skypack.dev/@final-hill/decorator-contracts@0.24.1"></script>`
64
+ `<script type="module" src="https://cdn.skypack.dev/@final-hill/decorator-contracts"></script>`
58
65
 
59
66
  ## Usage
60
67
 
@@ -298,96 +305,6 @@ iff(
298
305
 
299
306
  This is logically equivalent to: `implies(p,q) && implies(q,p)`
300
307
 
301
- ## Overrides
302
-
303
- Class features implemented in a base class can be overridden in a subclass. The
304
- subclass implementation can augment or entirely replace the one belonging
305
- to the base class. This can be done for a variety of reasons such as
306
- providing a more efficient implementation in the context of the subclass.
307
- Regardless of the reason the overridden member should be semantically
308
- consistent with the base class member. In other
309
- words it should follow [Liskov's Substitution Principle](https://en.wikipedia.org/wiki/Liskov_substitution_principle).
310
- To aid in the enforcement and documentation of this principle the library
311
- provides an `@override` decorator for class methods and accessors.
312
-
313
- A simple example is calculating the area of Convex Polygons. While a [general
314
- formula](https://en.wikipedia.org/wiki/Heron%27s_formula) exists to accomplish this
315
- more efficient and direct formulas exist for specific polygons such as a Right Triangle:
316
-
317
- ```typescript
318
- type Side = number
319
- type Vertex = [number, number]
320
-
321
- function _triArea(v1: Vertex, v2: Vertex, v3: Vertex): number {
322
- const {hypot,sqrt} = Math,
323
- a = hypot((v1[0] - v2[0]), (v1[1] - v2[1])),
324
- b = hypot((v2[0] - v3[0]), (v2[1] - v3[1])),
325
- c = hypot((v3[0] - v1[0]), (v3[1] - v1[1])),
326
- s = 0.5 * (a + b + c)
327
-
328
- return sqrt(s*(s-a)*(s-b)*(s-c))
329
- }
330
-
331
- @Contracted()
332
- class ConvexShape {
333
- #vertices: Vertex[]
334
-
335
- constructor(...vertices: Vertex[]) {
336
- this.#vertices = vertices
337
- }
338
-
339
- area(): number {
340
- let [v1, v2, v3, ...vs] = this.#vertices
341
- return this.#vertices.length >= 3 ?
342
- _triArea(v1, v2, v3) + new ConvexShape(v1, v3, ...vs).area() :
343
- 0
344
- }
345
-
346
- get vertices(): Vertex[] { return this.#vertices.slice() }
347
- }
348
-
349
- class RightTriangle extends ConvexShape {
350
- #base: Side
351
- #height: Side
352
-
353
- constructor(base: Side, height: Side) {
354
- super([0,0], [base,0], [base,height])
355
- this.#base = base
356
- this.#height = height
357
- }
358
-
359
- @override
360
- area(): number { return this.#base * this.#height / 2 }
361
-
362
- get base(): Side { return this.#base }
363
- get height(): Side { return this.#height }
364
- }
365
- ```
366
-
367
- Above you can see the `area()` method being overridden with the more
368
- efficient implementation. The `@override` decorator makes explicit
369
- that the method is replacing another implementation.
370
-
371
- This decorator does not only document and verify that the method is
372
- overridden; it will also verify that the parameter count matches.
373
-
374
- Note that the current class or one of its ancestors must have `@Contracted(...)` assigned.
375
- When assigned, candidate overrides are identified and an
376
- error is raised if an associated `@override` is missing for that feature.
377
-
378
- Static methods including the constructor cannot be assigned an `@override`
379
- decorator. In the future this may be enabled for non-constructor static methods
380
- but the implications are not clear at present.
381
-
382
- [TypeScript 4.3](https://devblogs.microsoft.com/typescript/announcing-typescript-4-3-beta/#override-and-the-noimplicitoverride-flag) has added an `override` keyword.
383
- This should be compatible but possibly redundant. The pro/cons are:
384
-
385
- | `override` | `@override` |
386
- |---------------------------|-------------------------------------|
387
- | Compile Time | Runtime |
388
- | TypeScript Only | TypeScript and JavaScript |
389
- | Enforces type constraints | Enforces parameter count constraint |
390
-
391
308
  ## Encapsulation
392
309
 
393
310
  To guarantee invariants remain valid for classes, public property definitions are forbidden.
@@ -526,8 +443,7 @@ If a class feature is overridden then the `demands` assertion still applies:
526
443
 
527
444
  ```typescript
528
445
  class MyStack<T> extends Stack<T> {
529
- @overrides
530
- pop(): { ... }
446
+ override pop(): { ... }
531
447
  }
532
448
 
533
449
  ...
@@ -579,8 +495,7 @@ const subContract = new Contract<Sub>({
579
495
 
580
496
  @Contracted(subContract)
581
497
  class Sub extends Base {
582
- @override
583
- someMethod(x: number){ ... }
498
+ override someMethod(x: number){ ... }
584
499
  }
585
500
  ```
586
501
 
@@ -642,8 +557,7 @@ If a class feature is overridden then the `ensures` assertion still applies:
642
557
 
643
558
  ```typescript
644
559
  class MyStack<T> extends Stack<T> {
645
- @overrides
646
- push(value: T): { ... }
560
+ override push(value: T): { ... }
647
561
  }
648
562
 
649
563
  ...
@@ -829,8 +743,7 @@ class Base {
829
743
  }
830
744
 
831
745
  class Sub extends Base {
832
- @override
833
- myMethod(){ ... throw new Error('BOOM!') ... }
746
+ override myMethod(){ ... throw new Error('BOOM!') ... }
834
747
  }
835
748
  ```
836
749
 
@@ -839,7 +752,7 @@ Another capability that the `rescue` declaration provides is
839
752
  to enable [Fault-Tolerance](https://en.wikipedia.org/wiki/Fault_tolerance)
840
753
  and [Redundancy](https://en.wikipedia.org/wiki/Redundancy_(engineering)).
841
754
 
842
- A dated example of this is performing ajax requests in mult-browser environments where `fetch` may not exist:
755
+ A dated example of this is performing ajax requests in multi-browser environments where `fetch` may not exist:
843
756
 
844
757
  ```ts
845
758
  const ajaxRequestContract = new Contract<AjaxRequest>({
@@ -906,9 +819,7 @@ where you can lexically determine where the handling occurs and optionally perfo
906
819
 
907
820
  When `obj.feature` is called the happy path is:
908
821
 
909
- ```ts
910
- invariant -> demands -> { feature body } -> ensures -> invariant
911
- ```
822
+ ![image](./docs/happy-path.png)
912
823
 
913
824
  If an error is thrown and there is no `rescue` defined then the `invariant`
914
825
  is checked before the error is raised to the caller.
@@ -927,39 +838,7 @@ starts from the beginning.
927
838
  If `rescue` throws an error or does not call `retry` then the
928
839
  `invariant` is checked before the error is raised to the caller.
929
840
 
930
- ```mermaid
931
- flowchart LR
932
-
933
- Feature(("obj.feature(...)"))
934
- Invariant["@invariant"]
935
- Invariant2["@invariant"]
936
- Invariant3["@invariant"]
937
- Demands["@demands"]
938
- Ensures["@ensures"]
939
- Rescue["@rescue"]
940
- Error(("Error"))
941
- Body["{feature body}"]
942
- Result(("Result"))
943
-
944
- Feature --> Invariant
945
- Invariant -->|throws| Error
946
- Invariant --> Demands
947
- Demands -->|throws| Error
948
- Demands --> Body
949
- Body -->|throws| Rescue
950
- Rescue -->|retry| Invariant
951
- Body -->|returns| Ensures
952
- Ensures -->|throws| Rescue
953
- Ensures --> Invariant3
954
- Invariant3 --> Result
955
- Rescue --> |throws| Invariant2
956
- Rescue --> |returns| Invariant2
957
- Invariant2 --> Error
958
-
959
- style Error fill:red
960
- style Result fill:green
961
- style Rescue fill:darkorange
962
- ```
841
+ ![image](./docs/order-of-assertions.png)
963
842
 
964
843
  ## Further Reading
965
844
 
@@ -1,10 +1,10 @@
1
- /*!
2
- * @license
3
- * Copyright (C) 2022 Final Hill LLC
4
- * SPDX-License-Identifier: AGPL-3.0-only
5
- * @see <https://spdx.org/licenses/AGPL-3.0-only.html>
6
- */
7
- declare class AssertionError extends Error {
8
- constructor(message: string);
9
- }
10
- export default AssertionError;
1
+ /*!
2
+ * @license
3
+ * Copyright (C) 2023 Final Hill LLC
4
+ * SPDX-License-Identifier: AGPL-3.0-only
5
+ * @see <https://spdx.org/licenses/AGPL-3.0-only.html>
6
+ */
7
+ declare class AssertionError extends Error {
8
+ constructor(message: string);
9
+ }
10
+ export default AssertionError;
@@ -0,0 +1,39 @@
1
+ /*!
2
+ * @license
3
+ * Copyright (C) 2023 Final Hill LLC
4
+ * SPDX-License-Identifier: AGPL-3.0-only
5
+ * @see <https://spdx.org/licenses/AGPL-3.0-only.html>
6
+ */
7
+ declare const checkedMode: unique symbol, invariant: unique symbol, extend: unique symbol;
8
+ type AnyObject = Record<PropertyKey, any>;
9
+ type AnyFunc = (...args: any[]) => any;
10
+ type NonFunctionPropertyNames<T extends AnyObject> = {
11
+ [K in keyof T]: T[K] extends AnyFunc ? never : K;
12
+ }[keyof T];
13
+ export type Properties<T extends AnyObject> = Pick<T, NonFunctionPropertyNames<T>>;
14
+ export type Invariant<T extends AnyObject> = (self: T) => boolean;
15
+ export type Demands<T extends AnyObject, F extends T[any]> = (self: T, ...args: Parameters<F>) => boolean;
16
+ export type Ensures<T extends AnyObject, F extends T[any]> = (self: T, old: Properties<T>, ...args: Parameters<F>) => boolean;
17
+ export type Rescue<T extends AnyObject, F extends T[any]> = (self: T, error: Error, args: F extends AnyFunc ? Parameters<F> : [F], retry: F extends AnyFunc ? (...args: Parameters<F>) => any : (value: F) => void) => void;
18
+ export type ContractOptions<T extends AnyObject> = {
19
+ [extend]: Contract<T>;
20
+ [invariant]: Invariant<T>;
21
+ [checkedMode]: boolean;
22
+ } & {
23
+ [K in keyof T]?: FeatureOption<T, T[K]>;
24
+ };
25
+ export interface FeatureOption<T extends AnyObject, F extends T[any]> {
26
+ demands?: Demands<T, F>;
27
+ ensures?: Ensures<T, F>;
28
+ rescue?: Rescue<T, F>;
29
+ within?: number;
30
+ }
31
+ export declare class Contract<T extends AnyObject> {
32
+ #private;
33
+ [checkedMode]: boolean;
34
+ readonly [extend]?: Contract<T>;
35
+ readonly assertions: ContractOptions<T>;
36
+ constructor(assertions?: Partial<ContractOptions<T>>);
37
+ get [invariant](): Invariant<T>;
38
+ }
39
+ export { checkedMode, extend, invariant };
@@ -0,0 +1,21 @@
1
+ /*!
2
+ * @license
3
+ * Copyright (C) 2023 Final Hill LLC
4
+ * SPDX-License-Identifier: AGPL-3.0-only
5
+ * @see <https://spdx.org/licenses/AGPL-3.0-only.html>
6
+ */
7
+ import { ClassType } from './lib/index.mjs';
8
+ import { Contract } from './index.mjs';
9
+ declare const isContracted: unique symbol, innerContract: unique symbol;
10
+ declare function Contracted<T extends Contract<any> = Contract<any>, U extends ClassType<any> = ClassType<any>>(contract?: T): (Clazz: U & {
11
+ [innerContract]?: Contract<any>;
12
+ }, ctx: ClassDecoratorContext<U>) => (U & {
13
+ [innerContract]?: Contract<any> | undefined;
14
+ }) | (((abstract new (...args: any[]) => {
15
+ readonly [innerContract]: T;
16
+ }) & {
17
+ readonly [isContracted]: true;
18
+ readonly [innerContract]: T;
19
+ }) & U);
20
+ export { isContracted, innerContract };
21
+ export default Contracted;
@@ -0,0 +1,16 @@
1
+ /*!
2
+ * @license
3
+ * Copyright (C) 2023 Final Hill LLC
4
+ * SPDX-License-Identifier: AGPL-3.0-only
5
+ * @see <https://spdx.org/licenses/AGPL-3.0-only.html>
6
+ */
7
+ export declare enum Messages {
8
+ AssertionFailed = "Assertion failure",
9
+ MsgNoProperties = "Public properties are forbidden",
10
+ MsgNotContracted = "The current class or one of its ancestors must declare @Contracted(...)",
11
+ MsgMissingFeature = "The requested feature is not registered",
12
+ MsgSingleContract = "Only a single @Contracted decorator is allowed per class",
13
+ MsgSingleRetry = "retry can only be called once",
14
+ MsgInvalidContext = "A contracted feature can not be applied to objects of a different base class",
15
+ MsgBadSubcontract = "A sub contract must extend a base contract"
16
+ }
@@ -1,8 +1,8 @@
1
- /*!
2
- * @license
3
- * Copyright (C) 2022 Final Hill LLC
4
- * SPDX-License-Identifier: AGPL-3.0-only
5
- * @see <https://spdx.org/licenses/AGPL-3.0-only.html>
6
- */
7
- import { Constructor } from './';
8
- export default function assert(condition: unknown, message?: string, ErrorConstructor?: Constructor<Error>): asserts condition;
1
+ /*!
2
+ * @license
3
+ * Copyright (C) 2023 Final Hill LLC
4
+ * SPDX-License-Identifier: AGPL-3.0-only
5
+ * @see <https://spdx.org/licenses/AGPL-3.0-only.html>
6
+ */
7
+ import { Constructor } from './index.mjs';
8
+ export default function assert(condition: unknown, message?: string, ErrorConstructor?: Constructor<Error>): asserts condition;
@@ -1,7 +1,7 @@
1
- /*!
2
- * @license
3
- * Copyright (C) 2022 Final Hill LLC
4
- * SPDX-License-Identifier: AGPL-3.0-only
5
- * @see <https://spdx.org/licenses/AGPL-3.0-only.html>
6
- */
7
- export default function iff(p: boolean, q: boolean): boolean;
1
+ /*!
2
+ * @license
3
+ * Copyright (C) 2023 Final Hill LLC
4
+ * SPDX-License-Identifier: AGPL-3.0-only
5
+ * @see <https://spdx.org/licenses/AGPL-3.0-only.html>
6
+ */
7
+ export default function iff(p: boolean, q: boolean): boolean;
@@ -1,7 +1,7 @@
1
- /*!
2
- * @license
3
- * Copyright (C) 2022 Final Hill LLC
4
- * SPDX-License-Identifier: AGPL-3.0-only
5
- * @see <https://spdx.org/licenses/AGPL-3.0-only.html>
6
- */
7
- export default function implies(p: boolean, q: boolean): boolean;
1
+ /*!
2
+ * @license
3
+ * Copyright (C) 2023 Final Hill LLC
4
+ * SPDX-License-Identifier: AGPL-3.0-only
5
+ * @see <https://spdx.org/licenses/AGPL-3.0-only.html>
6
+ */
7
+ export default function implies(p: boolean, q: boolean): boolean;
@@ -0,0 +1,13 @@
1
+ /*!
2
+ * @license
3
+ * Copyright (C) 2023 Final Hill LLC
4
+ * SPDX-License-Identifier: AGPL-3.0-only
5
+ * @see <https://spdx.org/licenses/AGPL-3.0-only.html>
6
+ */
7
+ import AssertionError from './AssertionError.mjs';
8
+ import Contracted, { innerContract } from './Contracted.mjs';
9
+ import assert from './assert.mjs';
10
+ import implies from './implies.mjs';
11
+ export { AssertionError, Contracted, implies, innerContract, assert };
12
+ export { Contract, extend, invariant, Invariant, checkedMode, Rescue } from './Contract.mjs';
13
+ export { Constructor, AbstractConstructor, ClassType } from './lib/ClassType.mjs';
package/dist/index.mjs ADDED
@@ -0,0 +1,3 @@
1
+ /*! For license information please see index.mjs.LICENSE.txt */
2
+ var t={d:(e,s)=>{for(var r in s)t.o(s,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:s[r]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},e={};t.d(e,{ps:()=>r,CH:()=>a,Hk:()=>M,hu:()=>P,Mc:()=>n,l7:()=>i,K8:()=>j,li:()=>w,kG:()=>o});class s extends Error{constructor(t){super(t)}}const r=s,n=Symbol("checkedMode"),o=Symbol("invariant"),i=Symbol("extend");class a{#t;[n];[i];assertions=Object.create(null);constructor(t=Object.create(null)){this[i]=t[i],this[n]=t[n]??!0,this.#t=t[o]??O,Object.keys(t).forEach((e=>{const s=t[e];Object.defineProperty(this.assertions,e,{value:{demands:s.demands??O,ensures:s.ensures??O,rescue:s.rescue,within:s.within}})})),b(this.assertions)}get[o](){return this.#t}}const c=(t,e)=>{try{t[n]=!1,e()}finally{t[n]=!0}},l=function t(e,s,r,o,a){let l=!0;const u=Reflect.get(s.assertions,o)?.demands,h=`demands not met on ${r}.prototype.${String(o)}\r\n${u}`;s[n]&&u&&c(s,(()=>l=u.call(e,e,...a))),s[i]&&!l?t(e,s[i],r,o,a):P(l,h)},u=function t(e,s,r,o,a,l){const u=Reflect.get(s.assertions,o)?.ensures,h=`ensures not met on ${r}.prototype.${String(o)}\r\n${u}`;s[n]&&u&&c(s,(()=>P(u.call(e,e,a,...l),h))),s[i]&&t(e,s[i],r,o,a,l)},h=function t(e,s){s[n]&&c(s,(()=>{const t=s[o];P(t.call(e,e),`Invariant violated. ${t.toString()}`)})),s[i]&&t(e,s[i])};class d extends WeakMap{getOrCreate(t){return this.has(t)||this.set(t,new y(t)),this.get(t)}}const p=new d;var f;function g(t,e,s){return function r(...o){const{Class:i}=s,a=i.name;P(this instanceof i,`${f.MsgInvalidContext}. Expected: this instanceof ${a}. this: ${this.constructor.name}`);const d=Reflect.get(this,w);if(!d[n])return e.apply(this,o);let p;h(this,d),l(this,d,a,t,o);try{const r=Object.create(null);c(d,(()=>{s.features.forEach((({name:t,hasGetter:e})=>{e&&Object.defineProperty(r,t,{value:this[t]})}))}));const n=Reflect.get(d.assertions,t)?.within,i=Date.now();p=e.apply(this,o);const l=Date.now();n&&P(l-i<n,`Timing constraint violated. Constraint: ${n}ms, actual: ${l-i}ms`),u(this,d,a,t,r,o)}catch(e){const s=Reflect.get(d.assertions,t)?.rescue;if(null==s)throw h(this,d),e;let o=!1;if(c(d,(()=>{s.call(this,this,e,[],((...t)=>{P(!o,f.MsgSingleRetry),o=!0,d[n]=!0,p=r.call(this,...t)}))})),!o)throw h(this,d),e}return h(this,d),p}}!function(t){t.AssertionFailed="Assertion failure",t.MsgNoProperties="Public properties are forbidden",t.MsgNotContracted="The current class or one of its ancestors must declare @Contracted(...)",t.MsgMissingFeature="The requested feature is not registered",t.MsgSingleContract="Only a single @Contracted decorator is allowed per class",t.MsgSingleRetry="retry can only be called once",t.MsgInvalidContext="A contracted feature can not be applied to objects of a different base class",t.MsgBadSubcontract="A sub contract must extend a base contract"}(f||(f={}));const y=class{Class;#e;contract;contractsChecked=!1;constructor(t){this.Class=t;const e=this.Class.prototype;this.#e=Reflect.ownKeys(e).filter((t=>"constructor"!=t&&t!==w)).map((t=>new C(this,t,Object.getOwnPropertyDescriptor(e,t))))}get features(){return[...this.#e]}get ParentClass(){return Object.getPrototypeOf(this.Class.prototype)?.constructor}get parentRegistration(){return null==this.ParentClass?null:p.getOrCreate(this.ParentClass)}ancestry(){if(null==this.ParentClass)return[];{const t=p.getOrCreate(this.ParentClass);return[t,...t.ancestry()]}}ancestryFeatures(){return this.ancestry().flatMap((({features:t})=>t))}bindContract(t){if(this.contract=t,!t[n])return;const e=this.Class.prototype;this.features.forEach((t=>{const{name:s,hasGetter:r,hasSetter:n,isMethod:o}=t;Object.defineProperty(e,s,{enumerable:!0,...r?{get:g(s,t.getter,this)}:{},...n?{set:g(s,t.setter,this)}:{},...o?{value:g(s,t.value,this)}:{}}),t.descriptor=Object.getOwnPropertyDescriptor(e,s)}))}findFeature(t){return this.features.find((({name:e})=>e===t))??this.parentRegistration?.findFeature(t)}},b=function t(e){for(const[,s]of Object.entries(e))null!=s&&"object"==typeof s&&t(s);Object.freeze(e)},C=class{classRegistration;name;#s;constructor(t,e,s){this.classRegistration=t,this.name=e,this.#s=s}get ancestorFeature(){return this.classRegistration.ancestryFeatures().filter((t=>t.name===this.name))[0]}get getter(){return this.#s.get}get hasGetter(){return this.isAccessor&&null!=this.#s.get}get hasSetter(){return this.isAccessor&&null!=this.#s.set}get isProperty(){return"function"!=typeof this.#s.value&&void 0!==this.#s.value}get isMethod(){return"function"==typeof this.#s.value}get isAccessor(){return void 0===this.#s.value}get memberType(){return this.isMethod?"method":this.isProperty?"property":"accessor"}get setter(){return this.#s.set}get value(){return this.#s.value}get descriptor(){return this.#s}set descriptor(t){this.#s=t}},m=function t(e,s){return e.length&&s(e[0])?[e[0],...t(e.slice(1),s)]:[]},O=()=>!0,v=Symbol("isContracted"),w=Symbol("innerContract"),M=function(t=new a){return function(e,s){if("class"!==s.kind)throw new TypeError(f.MsgNotContracted);if(P(!Object.getOwnPropertySymbols(e).includes(v),f.MsgSingleContract),!1===t[n])return e;const r=e[w];P(!r||r&&t[i]instanceof r.constructor,f.MsgBadSubcontract);class o extends e{static[v]=!0;constructor(...t){super(...t);const s=this.constructor,r=p.getOrCreate(s);var n;if(P((n=r,this,!Object.entries(Object.getOwnPropertyDescriptors(this)).some((([t,e])=>new C(n,t,e).isProperty))),f.MsgNoProperties),!r.contractsChecked){const t=m(r.ancestry(),(t=>t.Class!==e));[r,...t,p.get(e)].forEach((t=>{t.bindContract(o[w])}))}return h(this,o[w]),this}static get[w](){return t}get[w](){return t}}return p.getOrCreate(o).contractsChecked=!1,Object.freeze(e),o}};function P(t,e=f.AssertionFailed,s=r){if(0==Boolean(t))throw new s(e)}function j(t,e){return!t||e}var S=e.ps,R=e.CH,k=e.Hk,$=e.hu,x=e.Mc,A=e.l7,E=e.K8,F=e.li,D=e.kG;export{S as AssertionError,R as Contract,k as Contracted,$ as assert,x as checkedMode,A as extend,E as implies,F as innerContract,D as invariant};
3
+ //# sourceMappingURL=index.mjs.map
@@ -1,6 +1,6 @@
1
1
  /*!
2
2
  * @license
3
- * Copyright (C) 2022 Final Hill LLC
3
+ * Copyright (C) 2023 Final Hill LLC
4
4
  * SPDX-License-Identifier: AGPL-3.0-only
5
5
  * @see <https://spdx.org/licenses/AGPL-3.0-only.html>
6
6
  */
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","mappings":";AACA,IAAIA,EAAsB,CCA1BA,EAAwB,CAACC,EAASC,KACjC,IAAI,IAAIC,KAAOD,EACXF,EAAoBI,EAAEF,EAAYC,KAASH,EAAoBI,EAAEH,EAASE,IAC5EE,OAAOC,eAAeL,EAASE,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,IAE1E,ECNDH,EAAwB,CAACS,EAAKC,IAAUL,OAAOM,UAAUC,eAAeC,KAAKJ,EAAKC,mGCUlF,MAAMI,UAAuBC,MAMzB,WAAAC,CAAYC,GACRC,MAAMD,EACV,EAGJ,UCZME,EAAcC,OAAO,eACvBC,EAAYD,OAAO,aACnBE,EAASF,OAAO,UAmCb,MAAMG,EACT,GACA,CAACJ,GACQ,CAACG,GACDE,WAAiCnB,OAAOoB,OAAO,MAExD,WAAAT,CAAYQ,EAA0CnB,OAAOoB,OAAO,OAChEC,KAAKJ,GAAUE,EAAWF,GAC1BI,KAAKP,GAAeK,EAAWL,KAAgB,EAC/CO,MAAK,EAAaF,EAAWH,IAAcM,EAE3CtB,OAAOuB,KAAKJ,GAAYK,SAAQC,IAC5B,MAAMC,EAAgBP,EAAWM,GACjCzB,OAAOC,eAAeoB,KAAKF,WAAYM,EAAa,CAChDE,MAAO,CACHC,QAASF,EAAcE,SAAWN,EAClCO,QAASH,EAAcG,SAAWP,EAClCQ,OAAQJ,EAAcI,OACtBC,OAAQL,EAAcK,SAE5B,IAGN,EAAWV,KAAKF,WACpB,CAEA,IAAKH,KACD,OAAOK,MAAK,CAChB,EC5DJ,MASA,EATkB,CAACW,EAAyBC,KACxC,IACID,E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EAAiB5C,KAAMuG,EAAgB3D,IAEhC5C,IACX,CAKA,WAAY4C,KAAmB,OAAOjC,CAAU,CAChD,IAAKiC,KAAmB,OAAOjC,CAAU,EAQ7C,OAL0B,EAAesB,YAAYsE,GACnChD,kBAAmB,EAErC5E,OAAOsG,OAAOa,GAEPS,CACX,CACJ,EChEe,SAAShF,EAAOuF,EAAoBvH,EAAkB8C,EAAS0E,gBAAiBC,EAAuC,GAClI,GAA0B,GAAtBC,QAAQH,GACR,MAAM,IAAIE,EAAiBzH,EACnC,CCfe,SAAS2H,EAAQC,EAAYC,GACxC,OAAQD,GAAKC,CACjB","sources":["webpack://@final-hill/decorator-contracts/webpack/bootstrap","webpack://@final-hill/decorator-contracts/webpack/runtime/define property getters","webpack://@final-hill/decorator-contracts/webpack/runtime/hasOwnProperty shorthand","webpack://@final-hill/decorator-contracts/./src/AssertionError.mts","webpack://@final-hill/decorator-contracts/./src/Contract.mts","webpack://@final-hill/decorator-contracts/./src/lib/unChecked.mts","webpack://@final-hill/decorator-contracts/./src/lib/assertDemands.mts","webpack://@final-hill/decorator-contracts/./src/lib/assertEnsures.mts","webpack://@final-hill/decorator-contracts/./src/lib/assertInvariants.mts","webpack://@final-hill/decorator-contracts/./src/lib/CLASS_REGISTRY.mts","webpack://@final-hill/decorator-contracts/./src/Messages.mts","webpack://@final-hill/decorator-contracts/./src/lib/ClassRegistration.mts","webpack://@final-hill/decorator-contracts/./src/lib/deepFreeze.mts","webpack://@final-hill/decorator-contracts/./src/lib/Feature.mts","webpack://@final-hill/decorator-contracts/./src/lib/takeWhile.mts","webpack://@final-hill/decorator-contracts/./src/lib/index.mts","webpack://@final-hill/decorator-contracts/./src/Contracted.mts","webpack://@final-hill/decorator-contracts/./src/assert.mts","webpack://@final-hill/decorator-contracts/./src/implies.mts"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","/*!\r\n * @license\r\n * Copyright (C) 2023 Final Hill LLC\r\n * SPDX-License-Identifier: AGPL-3.0-only\r\n * @see <https://spdx.org/licenses/AGPL-3.0-only.html>\r\n */\r\n\r\n/**\r\n * An AssertionError represents a failed assertion with an associated message\r\n */\r\nclass AssertionError extends Error {\r\n /**\r\n * Constructs a new instance of AssertionError\r\n *\r\n * @param {string} message - The associated message\r\n */\r\n constructor(message: string) {\r\n super(message);\r\n }\r\n}\r\n\r\nexport default AssertionError;","/*!\r\n * @license\r\n * Copyright (C) 2023 Final Hill LLC\r\n * SPDX-License-Identifier: AGPL-3.0-only\r\n * @see <https://spdx.org/licenses/AGPL-3.0-only.html>\r\n */\r\n\r\nimport { deepFreeze, fnTrue } from './lib/index.mjs';\r\n\r\nconst checkedMode = Symbol('checkedMode'),\r\n invariant = Symbol('invariant'),\r\n extend = Symbol('extend');\r\n\r\ntype AnyObject = Record<PropertyKey, any>;\r\ntype AnyFunc = (...args: any[]) => any;\r\n\r\ntype NonFunctionPropertyNames<T extends AnyObject> = { [K in keyof T]: T[K] extends AnyFunc ? never : K }[keyof T];\r\nexport type Properties<T extends AnyObject> = Pick<T, NonFunctionPropertyNames<T>>;\r\n\r\nexport type Invariant<T extends AnyObject> = (self: T) => boolean;\r\nexport type Demands<T extends AnyObject, F extends T[any]> = (self: T, ...args: Parameters<F>) => boolean;\r\nexport type Ensures<T extends AnyObject, F extends T[any]> = (self: T, old: Properties<T>, ...args: Parameters<F>) => boolean;\r\nexport type Rescue<T extends AnyObject, F extends T[any]> = (\r\n self: T,\r\n error: Error,\r\n args: F extends AnyFunc ? Parameters<F> : [F],\r\n retry: F extends AnyFunc ? (...args: Parameters<F>) => any : (value: F) => void\r\n) => void;\r\n\r\nexport type ContractOptions<\r\n T extends AnyObject\r\n> = {\r\n [extend]: Contract<T>;\r\n [invariant]: Invariant<T>;\r\n [checkedMode]: boolean;\r\n} & {\r\n [K in keyof T]?: FeatureOption<T, T[K]>\r\n };\r\n\r\nexport interface FeatureOption<T extends AnyObject, F extends T[any]> {\r\n demands?: Demands<T, F>;\r\n ensures?: Ensures<T, F>;\r\n rescue?: Rescue<T, F>;\r\n within?: number;\r\n}\r\n\r\nexport class Contract<T extends AnyObject> {\r\n #invariant: Invariant<T>;\r\n [checkedMode]: boolean;\r\n readonly [extend]?: Contract<T>;\r\n readonly assertions: ContractOptions<T> = Object.create(null);\r\n\r\n constructor(assertions: Partial<ContractOptions<T>> = Object.create(null)) {\r\n this[extend] = assertions[extend];\r\n this[checkedMode] = assertions[checkedMode] ?? true;\r\n this.#invariant = assertions[invariant] ?? fnTrue;\r\n\r\n Object.keys(assertions).forEach(propertyKey => {\r\n const featureOption = assertions[propertyKey]!;\r\n Object.defineProperty(this.assertions, propertyKey, {\r\n value: {\r\n demands: featureOption.demands ?? fnTrue,\r\n ensures: featureOption.ensures ?? fnTrue,\r\n rescue: featureOption.rescue,\r\n within: featureOption.within\r\n }\r\n });\r\n });\r\n\r\n deepFreeze(this.assertions);\r\n }\r\n\r\n get [invariant](): Invariant<T> {\r\n return this.#invariant;\r\n }\r\n}\r\n\r\nexport { checkedMode, extend, invariant };","/*!\r\n * @license\r\n * Copyright (C) 2023 Final Hill LLC\r\n * SPDX-License-Identifier: AGPL-3.0-only\r\n * @see <https://spdx.org/licenses/AGPL-3.0-only.html>\r\n */\r\n\r\nimport { checkedMode, Contract } from '../index.mjs';\r\n\r\n/**\r\n * Disable contract checking for the provided function\r\n * @param {Contract<any>} contract - The code contract\r\n * @param {function(...args: any[]): any} fn - The function to execute\r\n */\r\nconst unChecked = (contract: Contract<any>, fn: () => any) => {\r\n try {\r\n contract[checkedMode] = false;\r\n fn();\r\n } finally {\r\n contract[checkedMode] = true;\r\n }\r\n};\r\n\r\nexport default unChecked;","/*!\r\n * @license\r\n * Copyright (C) 2023 Final Hill LLC\r\n * SPDX-License-Identifier: AGPL-3.0-only\r\n * @see <https://spdx.org/licenses/AGPL-3.0-only.html>\r\n */\r\n\r\nimport { Demands, extend } from '../Contract.mjs';\r\nimport { assert, checkedMode, Contract } from '../index.mjs';\r\nimport unChecked from './unChecked.mjs';\r\n\r\n/**\r\n * Applies invariant assertions to the provided class instance\r\n *\r\n * @param {U} ctx - The context class\r\n * @param {Contract<any>} contract - The contract\r\n * @param {string} className - The name of the class\r\n * @param {PropertyKey} featureName - The name of the feature\r\n * @param {any[]} args - The arguments of the feature to apply to the assertion\r\n * @throws {AssertionError}\r\n */\r\nfunction assertDemands<U extends object>(ctx: U, contract: Contract<U>, className: string, featureName: PropertyKey, args: any[]) {\r\n let result = true;\r\n const d: Demands<any, any> | undefined = Reflect.get(contract.assertions, featureName)?.demands,\r\n demandsError = `demands not met on ${className}.prototype.${String(featureName)}\\r\\n${d}`;\r\n if (contract[checkedMode])\r\n if (d)\r\n unChecked(contract, () =>\r\n result = d.call(ctx, ctx, ...args)\r\n );\r\n\r\n if (contract[extend] && !result)\r\n assertDemands(ctx, contract[extend], className, featureName, args);\r\n else\r\n assert(result, demandsError);\r\n}\r\n\r\nexport default assertDemands;","/*!\r\n * @license\r\n * Copyright (C) 2023 Final Hill LLC\r\n * SPDX-License-Identifier: AGPL-3.0-only\r\n * @see <https://spdx.org/licenses/AGPL-3.0-only.html>\r\n */\r\n\r\nimport { Ensures, extend, Properties } from '../Contract.mjs';\r\nimport { assert, checkedMode, Contract } from '../index.mjs';\r\nimport unChecked from './unChecked.mjs';\r\n\r\n/**\r\n * Applies invariant assertions to the provided class instance\r\n *\r\n * @param {U} ctx - The context class\r\n * @param {Contract<any>} contract - The contract\r\n * @param {string} className - The name of the class\r\n * @param {PropertyKey} featureName - The name of the feature\r\n * @param {U} old - The original properties before execution\r\n * @param {any[]} args - The arguments of the feature to apply to the assertion\r\n * @throws {AssertionError}\r\n */\r\nfunction assertEnsures<U extends Properties<any>>(\r\n ctx: U,\r\n contract: Contract<any>,\r\n className: string,\r\n featureName: PropertyKey,\r\n old: U,\r\n args: any[]\r\n) {\r\n const e: Ensures<any, any> | undefined = Reflect.get(contract.assertions, featureName)?.ensures,\r\n ensuresError = `ensures not met on ${className}.prototype.${String(featureName)}\\r\\n${e}`;\r\n\r\n if (contract[checkedMode])\r\n if (e)\r\n unChecked(contract, () =>\r\n assert(e.call(ctx, ctx, old, ...args), ensuresError)\r\n );\r\n\r\n if (contract[extend])\r\n assertEnsures(ctx, contract[extend]!, className, featureName, old, args);\r\n}\r\n\r\nexport default assertEnsures;","/*!\r\n * @license\r\n * Copyright (C) 2023 Final Hill LLC\r\n * SPDX-License-Identifier: AGPL-3.0-only\r\n * @see <https://spdx.org/licenses/AGPL-3.0-only.html>\r\n */\r\n\r\nimport { unChecked } from './index.mjs';\r\nimport { assert, checkedMode, Contract, extend, invariant } from '../index.mjs';\r\n\r\n/**\r\n * Applies invariant assertions to the provided class instance\r\n *\r\n * @param {U} ctx - The context class\r\n * @param {Contract<any>} contract - The contract\r\n * @throws {AssertionError}\r\n */\r\nfunction assertInvariants<U>(ctx: U, contract: Contract<any>) {\r\n if (contract[checkedMode])\r\n unChecked(contract, () => {\r\n const iv = contract[invariant];\r\n assert(iv.call(ctx, ctx), `Invariant violated. ${iv.toString()}`);\r\n });\r\n\r\n if (contract[extend])\r\n assertInvariants(ctx, contract[extend]!);\r\n}\r\n\r\nexport default assertInvariants;","/*!\r\n * @license\r\n * Copyright (C) 2023 Final Hill LLC\r\n * SPDX-License-Identifier: AGPL-3.0-only\r\n * @see <https://spdx.org/licenses/AGPL-3.0-only.html>\r\n */\r\n\r\nimport { ClassRegistration, ClassType } from './index.mjs';\r\n\r\n/**\r\n * A WeakMap that tracks class registrations.\r\n * @see {@link ClassRegistration}\r\n */\r\nclass ClassRegistry extends WeakMap<ClassType<any>, ClassRegistration> {\r\n /**\r\n * Returns the class registry defined for the current class.\r\n * If the registry is undefined, a new one is created\r\n *\r\n * @param {ClassType<any>} Class - The class\r\n * @returns {ClassRegistration} - The ClassRegistration\r\n */\r\n getOrCreate(Class: ClassType<any>): ClassRegistration {\r\n if (this.has(Class))\r\n return this.get(Class)!;\r\n else {\r\n this.set(Class, new ClassRegistration(Class));\r\n\r\n return this.get(Class)!;\r\n }\r\n }\r\n}\r\n\r\nconst CLASS_REGISTRY = new ClassRegistry();\r\n\r\nexport default CLASS_REGISTRY;","/*!\r\n * @license\r\n * Copyright (C) 2023 Final Hill LLC\r\n * SPDX-License-Identifier: AGPL-3.0-only\r\n * @see <https://spdx.org/licenses/AGPL-3.0-only.html>\r\n */\r\n\r\nexport enum Messages {\r\n AssertionFailed = 'Assertion failure',\r\n MsgNoProperties = 'Public properties are forbidden',\r\n MsgNotContracted = 'The current class or one of its ancestors must declare @Contracted(...)',\r\n MsgMissingFeature = 'The requested feature is not registered',\r\n MsgSingleContract = 'Only a single @Contracted decorator is allowed per class',\r\n MsgSingleRetry = 'retry can only be called once',\r\n MsgInvalidContext = 'A contracted feature can not be applied to objects of a different base class',\r\n MsgBadSubcontract = 'A sub contract must extend a base contract'\r\n}","/*!\r\n * @license\r\n * Copyright (C) 2023 Final Hill LLC\r\n * SPDX-License-Identifier: AGPL-3.0-only\r\n * @see <https://spdx.org/licenses/AGPL-3.0-only.html>\r\n */\r\n\r\nimport { Messages } from '../Messages.mjs';\r\nimport { assert, checkedMode, Contract, innerContract } from '../index.mjs';\r\nimport { assertInvariants, assertDemands, CLASS_REGISTRY, ClassType, Feature, unChecked } from './index.mjs';\r\nimport assertEnsures from './assertEnsures.mjs';\r\n\r\n/**\r\n * Manages the evaluation of contract assertions for a feature\r\n *\r\n * @param {string} featureName - The name of the feature\r\n * @param {function(...args: any[]): any} fnOrig - The original unchecked feature\r\n * @param {ClassRegistration} registration - The class registration\r\n *\r\n * @returns {function(...args: any[]): any} - The original function augments with assertion checks\r\n */\r\nfunction checkedFeature(\r\n featureName: PropertyKey,\r\n fnOrig: (...args: any[]) => any,\r\n registration: ClassRegistration\r\n) {\r\n return function innerCheckedFeature(this: any, ...args: any[]) {\r\n const { Class } = registration,\r\n className = Class.name;\r\n\r\n assert(this instanceof Class, `${Messages.MsgInvalidContext}. Expected: this instanceof ${className}. this: ${this.constructor.name}`);\r\n\r\n const contract = Reflect.get(this, innerContract);\r\n if (!contract[checkedMode])\r\n return fnOrig.apply(this, args);\r\n\r\n assertInvariants(this, contract);\r\n assertDemands(this, contract, className, featureName, args);\r\n\r\n let result;\r\n try {\r\n const old = Object.create(null);\r\n unChecked(contract, () => {\r\n registration.features.forEach(({ name, hasGetter }) => {\r\n if (hasGetter)\r\n Object.defineProperty(old, name, { value: this[name] });\r\n });\r\n });\r\n const within: number = Reflect.get(contract.assertions, featureName)?.within,\r\n // TODO:Not all environments currently support performance.now() as a global and conditional import is inconvenient\r\n t0 = Date.now();\r\n result = fnOrig.apply(this, args);\r\n const t1 = Date.now();\r\n if (within)\r\n assert(t1 - t0 < within,\r\n `Timing constraint violated. Constraint: ${within}ms, actual: ${t1 - t0}ms`\r\n );\r\n\r\n assertEnsures(this, contract, className, featureName, old, args);\r\n } catch (error) {\r\n const rescue = Reflect.get(contract.assertions, featureName)?.rescue;\r\n if (rescue == null) {\r\n assertInvariants(this, contract);\r\n throw error;\r\n }\r\n let hasRetried = false;\r\n unChecked(contract, () => {\r\n rescue.call(this, this, error, [], (...args: any[]) => {\r\n assert(!hasRetried, Messages.MsgSingleRetry);\r\n hasRetried = true;\r\n contract[checkedMode] = true;\r\n result = innerCheckedFeature.call(this, ...args);\r\n });\r\n });\r\n if (!hasRetried) {\r\n assertInvariants(this, contract);\r\n throw error;\r\n }\r\n }\r\n\r\n assertInvariants(this, contract);\r\n\r\n return result;\r\n };\r\n}\r\n\r\nclass ClassRegistration {\r\n #features: Feature[];\r\n contract!: Contract<any>; // Assigned by the Contracted class via this.bindContract\r\n contractsChecked = false;\r\n\r\n constructor(readonly Class: ClassType<any>) {\r\n const proto = this.Class.prototype;\r\n this.#features =\r\n Reflect.ownKeys(proto)\r\n .filter(key => key != 'constructor' && key !== innerContract)\r\n .map(key => new Feature(this, key, Object.getOwnPropertyDescriptor(proto, key)!));\r\n }\r\n\r\n /**\r\n * Returns the features associated with the registered class.\r\n *\r\n * @returns {Set<Feature>} The set of features\r\n */\r\n get features(): Feature[] {\r\n return [...this.#features];\r\n }\r\n\r\n /**\r\n * Returns a reference to the parent class\r\n */\r\n get ParentClass(): ClassType<any> | null {\r\n return Object.getPrototypeOf(this.Class.prototype)?.constructor;\r\n }\r\n\r\n /**\r\n * Returns the classRegistration of the parent class\r\n */\r\n get parentRegistration(): ClassRegistration | null {\r\n return this.ParentClass == null ? null : CLASS_REGISTRY.getOrCreate(this.ParentClass);\r\n }\r\n\r\n /**\r\n * Returns the registered class's ancestor class registrations.\r\n * Does not include the current class.\r\n *\r\n * @returns {ClassRegistration[]} - The ancestor class registrations\r\n */\r\n ancestry(): ClassRegistration[] {\r\n if (this.ParentClass == null)\r\n return [];\r\n else {\r\n const parentRegistry = CLASS_REGISTRY.getOrCreate(this.ParentClass);\r\n\r\n return [parentRegistry, ...parentRegistry.ancestry()];\r\n }\r\n }\r\n\r\n /**\r\n * Returns the features associated with the registered class's ancestors.\r\n * Does not include the current class.\r\n *\r\n * @returns {Feature[]} - The feature names\r\n */\r\n ancestryFeatures(): Feature[] {\r\n return this.ancestry().flatMap(({ features }) => features);\r\n }\r\n\r\n bindContract<T extends Contract<any>>(contract: T) {\r\n this.contract = contract;\r\n if (!contract[checkedMode])\r\n return;\r\n\r\n const proto = this.Class.prototype;\r\n this.features.forEach(feature => {\r\n const { name, hasGetter, hasSetter, isMethod } = feature;\r\n\r\n Object.defineProperty(proto, name, {\r\n enumerable: true,\r\n ...(hasGetter ? { get: checkedFeature(name, feature.getter!, this) } : {}),\r\n ...(hasSetter ? { set: checkedFeature(name, feature.setter!, this) } : {}),\r\n ...(isMethod ? { value: checkedFeature(name, feature.value, this) } : {})\r\n });\r\n\r\n feature.descriptor = Object.getOwnPropertyDescriptor(proto, name)!;\r\n });\r\n }\r\n\r\n /**\r\n * Searches the current class and its ancestors for the nearest feature\r\n * matching the provided propertyKey.\r\n *\r\n * @param {PropertyKey} propertyKey - The key being searched\r\n * @returns {Feature | undefined} - The feature if it exists else otherwise\r\n */\r\n findFeature(propertyKey: PropertyKey): Feature | undefined {\r\n return this.features.find(({ name }) => name === propertyKey) ??\r\n this.parentRegistration?.findFeature(propertyKey);\r\n }\r\n}\r\n\r\nexport default ClassRegistration;","/*!\r\n * @license\r\n * Copyright (C) 2023 Final Hill LLC\r\n * SPDX-License-Identifier: AGPL-3.0-only\r\n * @see <https://spdx.org/licenses/AGPL-3.0-only.html>\r\n */\r\n\r\n/**\r\n * Apply Object.freeze recursively\r\n * @param {object} object - The object to freeze\r\n */\r\nfunction deepFreeze(object: Record<PropertyKey, any>): void {\r\n // Freeze properties before freezing self\r\n for (const [, value] of Object.entries(object))\r\n if (value != undefined && typeof value === 'object')\r\n deepFreeze(value);\r\n\r\n Object.freeze(object);\r\n}\r\n\r\nexport default deepFreeze;","/*!\r\n * @license\r\n * Copyright (C) 2023 Final Hill LLC\r\n * SPDX-License-Identifier: AGPL-3.0-only\r\n * @see <https://spdx.org/licenses/AGPL-3.0-only.html>\r\n */\r\n\r\nimport ClassRegistration from './ClassRegistration.mjs';\r\n\r\nclass Feature {\r\n #descriptor: PropertyDescriptor;\r\n\r\n constructor(readonly classRegistration: ClassRegistration, readonly name: PropertyKey, descriptor: PropertyDescriptor) {\r\n this.#descriptor = descriptor;\r\n }\r\n\r\n /**\r\n * Finds the nearest ancestor feature of the same key if it exists\r\n */\r\n get ancestorFeature(): Feature | null {\r\n return this.classRegistration.ancestryFeatures().filter(feature => feature.name === this.name)[0];\r\n }\r\n\r\n /**\r\n * Returns a reference to the getter if it exists\r\n */\r\n get getter() {\r\n return this.#descriptor.get;\r\n }\r\n\r\n /**\r\n * Determines if the feature is an accessor with a getter defined\r\n */\r\n get hasGetter(): boolean {\r\n return this.isAccessor && this.#descriptor.get != undefined;\r\n }\r\n\r\n /**\r\n * Determines if the feature is an accessor with a setter defined\r\n */\r\n get hasSetter(): boolean {\r\n return this.isAccessor && this.#descriptor.set != undefined;\r\n }\r\n\r\n /**\r\n * Determines if the feature is a property\r\n */\r\n get isProperty(): boolean {\r\n return typeof this.#descriptor.value != 'function' &&\r\n typeof this.#descriptor.value != 'undefined';\r\n }\r\n\r\n /**\r\n * Determines if the feature is a method\r\n */\r\n get isMethod(): boolean {\r\n return typeof this.#descriptor.value == 'function';\r\n }\r\n\r\n /**\r\n * Determines if the feature is an accessor\r\n */\r\n get isAccessor(): boolean {\r\n return typeof this.#descriptor.value == 'undefined';\r\n }\r\n\r\n /**\r\n * Returns a string representing the type of feature.\r\n * @returns {string} 'method' | 'property' | 'accessor'\r\n */\r\n get memberType(): 'method' | 'property' | 'accessor' {\r\n return this.isMethod ? 'method' :\r\n this.isProperty ? 'property' :\r\n 'accessor';\r\n }\r\n\r\n /**\r\n * Returns a reference to the setter if it exists\r\n */\r\n get setter() {\r\n return this.#descriptor.set;\r\n }\r\n\r\n /**\r\n * If the feature is a method, returns a reference to the implementation.\r\n * If the feature is a property, returns the value of the property\r\n * Otherwise returns undefined\r\n */\r\n get value(): any {\r\n return this.#descriptor.value;\r\n }\r\n\r\n /**\r\n * Returns a reference to the descriptor\r\n */\r\n get descriptor() {\r\n return this.#descriptor;\r\n }\r\n set descriptor(desc: PropertyDescriptor) {\r\n this.#descriptor = desc;\r\n }\r\n}\r\n\r\nexport default Feature;","/*!\r\n * @license\r\n * Copyright (C) 2023 Final Hill LLC\r\n * SPDX-License-Identifier: AGPL-3.0-only\r\n * @see <https://spdx.org/licenses/AGPL-3.0-only.html>\r\n */\r\n\r\n/**\r\n * Creates a new array from another one. Items from the original array\r\n * are taken if the provided predicate succeed. When the predicate fails,\r\n * no new items are taken\r\n *\r\n * @param {T[]} xs - The array to evaluate\r\n * @param {function(x:T): T[]} pred - The condition to apply to every element\r\n * @returns {T[]} - The filtered list\r\n */\r\nexport function takeWhile<T>(xs: T[], pred: (x: T) => boolean): T[] {\r\n return xs.length && pred(xs[0]) ? [xs[0], ...takeWhile(xs.slice(1), pred)] : [];\r\n}\r\n\r\nexport default takeWhile;","/*!\r\n * @license\r\n * Copyright (C) 2023 Final Hill LLC\r\n * SPDX-License-Identifier: AGPL-3.0-only\r\n * @see <https://spdx.org/licenses/AGPL-3.0-only.html>\r\n */\r\n\r\nimport assertDemands from './assertDemands.mjs';\r\nimport assertEnsures from './assertEnsures.mjs';\r\nimport assertInvariants from './assertInvariants.mjs';\r\nimport CLASS_REGISTRY from './CLASS_REGISTRY.mjs';\r\nimport ClassRegistration from './ClassRegistration.mjs';\r\nimport { ClassType } from './ClassType.mjs';\r\nimport deepFreeze from './deepFreeze.mjs';\r\nimport Feature from './Feature.mjs';\r\nimport takeWhile from './takeWhile.mjs';\r\nimport unChecked from './unChecked.mjs';\r\n\r\nconst fnTrue = () => true;\r\n\r\nexport {\r\n assertDemands,\r\n assertEnsures,\r\n assertInvariants,\r\n CLASS_REGISTRY,\r\n ClassRegistration,\r\n ClassType,\r\n deepFreeze,\r\n Feature,\r\n fnTrue,\r\n takeWhile,\r\n unChecked\r\n};","/*!\r\n * @license\r\n * Copyright (C) 2023 Final Hill LLC\r\n * SPDX-License-Identifier: AGPL-3.0-only\r\n * @see <https://spdx.org/licenses/AGPL-3.0-only.html>\r\n */\r\n\r\nimport { ClassRegistration, CLASS_REGISTRY, ClassType, Feature, takeWhile, assertInvariants } from './lib/index.mjs';\r\nimport { assert, checkedMode, Contract, extend } from './index.mjs';\r\nimport { Messages } from './Messages.mjs';\r\n\r\nconst isContracted = Symbol('isContracted'),\r\n innerContract = Symbol('innerContract');\r\n\r\n/**\r\n * Checks the features of the provided object for properties.\r\n * If any are found an exception is thrown\r\n * @param {ClassRegistration} registration - The ClassRegistration for the object\r\n * @param {U} obj - The object to check\r\n * @throws {AssertionError} - Throws if a property is found\r\n * @returns {boolean} - The result of the test\r\n */\r\nfunction hasProperties<U>(registration: ClassRegistration, obj: U): boolean {\r\n return Object.entries(Object.getOwnPropertyDescriptors(obj))\r\n .some(([key, desc]) => new Feature(registration, key, desc).isProperty);\r\n}\r\n\r\n/**\r\n * Associates a contract with a class via the mixin pattern.\r\n *\r\n * @param {Contract} contract The Contract definition\r\n * @param {T} Base An optional base class\r\n * @returns {T} The base class for extension\r\n * @example\r\n *\r\n * @Contracted(stackContract)\r\n * class Stack<T> { ... }\r\n */\r\nfunction Contracted<\r\n T extends Contract<any> = Contract<any>,\r\n U extends ClassType<any> = ClassType<any>\r\n>(contract: T = new Contract() as T) {\r\n return function (Clazz: U & { [innerContract]?: Contract<any> }, ctx: ClassDecoratorContext<U>) {\r\n if (ctx.kind !== 'class')\r\n throw new TypeError(Messages.MsgNotContracted);\r\n\r\n assert(!Object.getOwnPropertySymbols(Clazz).includes(isContracted), Messages.MsgSingleContract);\r\n\r\n if (contract[checkedMode] === false)\r\n return Clazz;\r\n\r\n const baseContract = Clazz[innerContract];\r\n assert(\r\n !baseContract ||\r\n baseContract && contract[extend] instanceof baseContract.constructor,\r\n Messages.MsgBadSubcontract\r\n );\r\n\r\n abstract class InnerContracted extends Clazz {\r\n // prevents multiple @Contracted decorators from being applied\r\n static readonly [isContracted] = true;\r\n\r\n constructor(...args: any[]) {\r\n super(...args);\r\n\r\n const Class = this.constructor as ClassType<any>,\r\n classRegistration = CLASS_REGISTRY.getOrCreate(Class);\r\n\r\n assert(!hasProperties(classRegistration, this), Messages.MsgNoProperties);\r\n\r\n if (!classRegistration.contractsChecked) {\r\n // bottom-up to closest Contracted class bind contracts\r\n const ancRegistrations = takeWhile(classRegistration.ancestry(), (cr => cr.Class !== Clazz));\r\n [classRegistration, ...ancRegistrations, CLASS_REGISTRY.get(Clazz)!].forEach(registration => {\r\n registration.bindContract(InnerContracted[innerContract]);\r\n });\r\n }\r\n\r\n assertInvariants(this, InnerContracted[innerContract]);\r\n\r\n return this;\r\n }\r\n\r\n // FIXME: dirty hack. Possibly resolved by moving to contracts as classes\r\n // The static getter is used by the construction invariant check\r\n // The instance getter is used by the feature declarations\r\n static get [innerContract]() { return contract; }\r\n get [innerContract]() { return contract; }\r\n }\r\n\r\n const classRegistration = CLASS_REGISTRY.getOrCreate(InnerContracted);\r\n classRegistration.contractsChecked = false;\r\n\r\n Object.freeze(Clazz);\r\n\r\n return InnerContracted;\r\n };\r\n}\r\n\r\nexport { isContracted, innerContract };\r\nexport default Contracted;","/*!\r\n * @license\r\n * Copyright (C) 2023 Final Hill LLC\r\n * SPDX-License-Identifier: AGPL-3.0-only\r\n * @see <https://spdx.org/licenses/AGPL-3.0-only.html>\r\n */\r\n\r\nimport AssertionError from './AssertionError.mjs';\r\nimport { Messages } from './Messages.mjs';\r\nimport { Constructor } from './index.mjs';\r\n\r\n/**\r\n * An assertion is an expression of a property that must be true at a particular\r\n * point of step of program execution. It consists of a boolean expression\r\n * and a message. This function tests the provided condition. If the condition\r\n * is false an AssertionError is raised with an optional message.\r\n * If the provided condition is true then the function returns without raising an error\r\n *\r\n * @param {boolean} condition - The condition to test\r\n * @param {string} message - A descriptive message to associate with the AssertionError\r\n * @param {ClassType<Error>} ErrorConstructor - The constructor of the Error to use\r\n * @throws {Error} - When the condition is false\r\n * @see AssertionError\r\n * @throws {AssertionError} - Throws an AssertionError by default if the condition is false\r\n *\r\n * @example\r\n * let x = 15;\r\n * assert(x > 5, `Expected: x > 5. Actual: x = ${x}`)\r\n *\r\n * @example\r\n * let name = \"Tom\"\r\n * assert(name.trim().length > 0, 'Name is required', TypeError)\r\n */\r\nexport default function assert(condition: unknown, message: string = Messages.AssertionFailed, ErrorConstructor: Constructor<Error> = AssertionError): asserts condition {\r\n if (Boolean(condition) == false)\r\n throw new ErrorConstructor(message);\r\n}","/*!\r\n * @license\r\n * Copyright (C) 2023 Final Hill LLC\r\n * SPDX-License-Identifier: AGPL-3.0-only\r\n * @see <https://spdx.org/licenses/AGPL-3.0-only.html>\r\n */\r\n\r\n/**\r\n * Material Implication.\r\n * `p → q`\r\n * Also referred to as `if-then`.\r\n * An example of usage is the encoding of \"sunny weather is a precondition of visiting the beach\"\r\n * This is logically equivalent to: !p || q\r\n *\r\n * @example\r\n * implies(weather.isSunny, person.visitsBeach)\r\n *\r\n * @param {boolean} p - The antecedent\r\n * @param {boolean} q - The consequent\r\n * @returns {boolean} - The result\r\n */\r\nexport default function implies(p: boolean, q: boolean): boolean {\r\n return !p || q;\r\n}"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","AssertionError","Error","constructor","message","super","checkedMode","Symbol","invariant","extend","Contract","assertions","create","this","fnTrue","keys","forEach","propertyKey","featureOption","value","demands","ensures","rescue","within","contract","fn","assertDemands","ctx","className","featureName","args","result","d","Reflect","demandsError","String","assert","assertEnsures","old","e","ensuresError","assertInvariants","iv","toString","ClassRegistry","WeakMap","getOrCreate","Class","has","set","Messages","checkedFeature","fnOrig","registration","innerCheckedFeature","name","MsgInvalidContext","innerContract","apply","features","hasGetter","t0","Date","now","t1","error","hasRetried","MsgSingleRetry","contractsChecked","proto","ownKeys","filter","map","getOwnPropertyDescriptor","ParentClass","getPrototypeOf","parentRegistration","ancestry","parentRegistry","ancestryFeatures","flatMap","bindContract","feature","hasSetter","isMethod","getter","setter","descriptor","findFeature","find","deepFreeze","object","entries","undefined","freeze","classRegistration","ancestorFeature","isAccessor","isProperty","memberType","desc","takeWhile","xs","pred","length","slice","isContracted","Clazz","kind","TypeError","MsgNotContracted","getOwnPropertySymbols","includes","MsgSingleContract","baseContract","MsgBadSubcontract","InnerContracted","static","getOwnPropertyDescriptors","some","MsgNoProperties","ancRegistrations","cr","condition","AssertionFailed","ErrorConstructor","Boolean","implies","p","q"],"sourceRoot":""}
@@ -1,12 +1,12 @@
1
- /*!
2
- * @license
3
- * Copyright (C) 2022 Final Hill LLC
4
- * SPDX-License-Identifier: AGPL-3.0-only
5
- * @see <https://spdx.org/licenses/AGPL-3.0-only.html>
6
- */
7
- import { ClassRegistration, ClassType } from './';
8
- declare class ClassRegistry extends WeakMap<ClassType<any>, ClassRegistration> {
9
- getOrCreate(Class: ClassType<any>): ClassRegistration;
10
- }
11
- declare const CLASS_REGISTRY: ClassRegistry;
12
- export default CLASS_REGISTRY;
1
+ /*!
2
+ * @license
3
+ * Copyright (C) 2023 Final Hill LLC
4
+ * SPDX-License-Identifier: AGPL-3.0-only
5
+ * @see <https://spdx.org/licenses/AGPL-3.0-only.html>
6
+ */
7
+ import { ClassRegistration, ClassType } from './index.mjs';
8
+ declare class ClassRegistry extends WeakMap<ClassType<any>, ClassRegistration> {
9
+ getOrCreate(Class: ClassType<any>): ClassRegistration;
10
+ }
11
+ declare const CLASS_REGISTRY: ClassRegistry;
12
+ export default CLASS_REGISTRY;
@@ -1,24 +1,23 @@
1
- /*!
2
- * @license
3
- * Copyright (C) 2022 Final Hill LLC
4
- * SPDX-License-Identifier: AGPL-3.0-only
5
- * @see <https://spdx.org/licenses/AGPL-3.0-only.html>
6
- */
7
- import { Contract } from '../';
8
- import { ClassType, Feature } from './';
9
- declare class ClassRegistration {
10
- #private;
11
- readonly Class: ClassType<any>;
12
- contract: Contract<any>;
13
- contractsChecked: boolean;
14
- constructor(Class: ClassType<any>);
15
- get features(): Feature[];
16
- get ParentClass(): ClassType<any> | null;
17
- get parentRegistration(): ClassRegistration | null;
18
- ancestry(): ClassRegistration[];
19
- ancestryFeatures(): Feature[];
20
- bindContract<T extends Contract<any>>(contract: T): void;
21
- checkOverrides(): void;
22
- findFeature(propertyKey: PropertyKey): Feature | undefined;
23
- }
24
- export default ClassRegistration;
1
+ /*!
2
+ * @license
3
+ * Copyright (C) 2023 Final Hill LLC
4
+ * SPDX-License-Identifier: AGPL-3.0-only
5
+ * @see <https://spdx.org/licenses/AGPL-3.0-only.html>
6
+ */
7
+ import { Contract } from '../index.mjs';
8
+ import { ClassType, Feature } from './index.mjs';
9
+ declare class ClassRegistration {
10
+ #private;
11
+ readonly Class: ClassType<any>;
12
+ contract: Contract<any>;
13
+ contractsChecked: boolean;
14
+ constructor(Class: ClassType<any>);
15
+ get features(): Feature[];
16
+ get ParentClass(): ClassType<any> | null;
17
+ get parentRegistration(): ClassRegistration | null;
18
+ ancestry(): ClassRegistration[];
19
+ ancestryFeatures(): Feature[];
20
+ bindContract<T extends Contract<any>>(contract: T): void;
21
+ findFeature(propertyKey: PropertyKey): Feature | undefined;
22
+ }
23
+ export default ClassRegistration;
@@ -0,0 +1,10 @@
1
+ /*!
2
+ * @license
3
+ * Copyright (C) 2023 Final Hill LLC
4
+ * SPDX-License-Identifier: AGPL-3.0-only
5
+ * @see <https://spdx.org/licenses/AGPL-3.0-only.html>
6
+ */
7
+ type Constructor<T> = new (...args: any[]) => T;
8
+ type AbstractConstructor<T> = abstract new (...args: any[]) => T;
9
+ type ClassType<T> = Constructor<T> | AbstractConstructor<T>;
10
+ export { Constructor, AbstractConstructor, ClassType };