@final-hill/decorator-contracts 0.25.1 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +169 -610
- package/dist/AssertionError.d.mts +3 -8
- package/dist/Contracted.d.mts +17 -21
- package/dist/assert.d.mts +19 -7
- package/dist/demands.d.mts +6 -0
- package/dist/ensures.d.mts +6 -0
- package/dist/iff.d.mts +19 -6
- package/dist/implies.d.mts +19 -6
- package/dist/index.d.mts +10 -13
- package/dist/index.mjs +1 -2
- package/dist/index.mjs.map +1 -1
- package/dist/invariant.d.mts +5 -0
- package/dist/rescue.d.mts +6 -0
- package/dist/types.d.mts +7 -0
- package/package.json +19 -18
- package/dist/Contract.d.mts +0 -39
- package/dist/Messages.d.mts +0 -16
- package/dist/index.mjs.LICENSE.txt +0 -6
- package/dist/lib/ClassRegistration.d.mts +0 -23
- package/dist/lib/ClassType.d.mts +0 -10
- package/dist/lib/Feature.d.mts +0 -26
- package/dist/lib/assertDemands.d.mts +0 -9
- package/dist/lib/assertEnsures.d.mts +0 -10
- package/dist/lib/assertInvariants.d.mts +0 -9
- package/dist/lib/classRegistry.d.mts +0 -12
- package/dist/lib/deepFreeze.d.mts +0 -8
- package/dist/lib/index.d.mts +0 -18
- package/dist/lib/takeWhile.d.mts +0 -8
- package/dist/lib/unChecked.d.mts +0 -9
- package/dist/tests/Contract.test.d.mts +0 -7
- package/dist/tests/Stack.test.d.mts +0 -7
- package/dist/tests/assert.test.d.mts +0 -7
- package/dist/tests/deepFreeze.test.d.mts +0 -7
- package/dist/tests/demands.test.d.mts +0 -7
- package/dist/tests/ensures.test.d.mts +0 -7
- package/dist/tests/factoryPattern.test.d.mts +0 -7
- package/dist/tests/iff.test.d.mts +0 -7
- package/dist/tests/implies.test.d.mts +0 -7
- package/dist/tests/invariant.test.d.mts +0 -7
- package/dist/tests/public-properties.test.d.mts +0 -7
- package/dist/tests/rescue.test.d.mts +0 -7
- package/dist/tests/within.test.d.mts +0 -7
|
@@ -1,10 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
*
|
|
3
|
-
* Copyright (C) 2024 Final Hill LLC
|
|
4
|
-
* SPDX-License-Identifier: AGPL-3.0-only
|
|
5
|
-
* @see <https://spdx.org/licenses/AGPL-3.0-only.html>
|
|
1
|
+
/**
|
|
2
|
+
* An AssertionError represents a failed assertion with an associated message
|
|
6
3
|
*/
|
|
7
|
-
declare class AssertionError extends Error {
|
|
8
|
-
constructor(message: string);
|
|
4
|
+
export declare class AssertionError extends Error {
|
|
9
5
|
}
|
|
10
|
-
export default AssertionError;
|
package/dist/Contracted.d.mts
CHANGED
|
@@ -1,21 +1,17 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
readonly [innerContract]: T;
|
|
19
|
-
}) & U);
|
|
20
|
-
export { isContracted, innerContract };
|
|
21
|
-
export default Contracted;
|
|
1
|
+
import { InvariantPredicate } from './invariant.mjs';
|
|
2
|
+
import { DemandsPredicate } from './demands.mjs';
|
|
3
|
+
import { EnsuresPredicate } from './ensures.mjs';
|
|
4
|
+
import { RescueHandler } from './rescue.mjs';
|
|
5
|
+
export declare const checkedMode: unique symbol;
|
|
6
|
+
export declare class Contracted {
|
|
7
|
+
static [Symbol.metadata]: {
|
|
8
|
+
invariants: InvariantPredicate<typeof Contracted>[];
|
|
9
|
+
demands: Record<PropertyKey, DemandsPredicate<Contracted>[]>;
|
|
10
|
+
ensures: Record<PropertyKey, EnsuresPredicate<Contracted>[]>;
|
|
11
|
+
rescue: Record<PropertyKey, RescueHandler<Contracted>>;
|
|
12
|
+
};
|
|
13
|
+
protected static _allowConstruction: boolean;
|
|
14
|
+
static [checkedMode]: boolean;
|
|
15
|
+
static new<C extends typeof Contracted, Args extends ConstructorParameters<C>>(this: C, ...args: Args): InstanceType<C>;
|
|
16
|
+
constructor(..._args: any[]);
|
|
17
|
+
}
|
package/dist/assert.d.mts
CHANGED
|
@@ -1,8 +1,20 @@
|
|
|
1
|
-
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
1
|
+
/**
|
|
2
|
+
* An assertion is an expression of a property that must be true at a particular
|
|
3
|
+
* point of step of program execution. It consists of a boolean expression
|
|
4
|
+
* and a message. This function tests the provided condition. If the condition
|
|
5
|
+
* is false an AssertionError is raised with an optional message.
|
|
6
|
+
* If the provided condition is true then the function returns without raising an error
|
|
7
|
+
*
|
|
8
|
+
* @param condition - The condition to test. If it is false an error is raised.
|
|
9
|
+
* @param message - The message to display if the condition is false. If not provided a default message is used.
|
|
10
|
+
* @throws {AssertionError} If the condition is false an AssertionError is raised.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* import assert from "assert.mjs";
|
|
15
|
+
*
|
|
16
|
+
* let x = 15;
|
|
17
|
+
* assert(x > 5, `Expected: x > 5. Actual: x = ${x}`);
|
|
18
|
+
* ```
|
|
6
19
|
*/
|
|
7
|
-
|
|
8
|
-
export default function assert(condition: unknown, message?: string, ErrorConstructor?: Constructor<Error>): asserts condition;
|
|
20
|
+
export declare function assert(condition: unknown, message?: string): asserts condition;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { Contracted } from "./Contracted.mjs";
|
|
2
|
+
import type { FeatureDecoratorContext } from './types.mjs';
|
|
3
|
+
export type DemandsPredicate<This extends Contracted> = (self: This, ...args: any[]) => boolean;
|
|
4
|
+
export type DemandsDecorator = <This extends Contracted, Feature = unknown>(predicate: DemandsPredicate<This>) => (value: Feature, context: FeatureDecoratorContext) => Feature | void;
|
|
5
|
+
export declare const demands: DemandsDecorator;
|
|
6
|
+
export declare function assertDemands(instance: Contracted, propertyKey: PropertyKey, ...args: any[]): void;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { Contracted } from './Contracted.mjs';
|
|
2
|
+
import type { FeatureDecoratorContext } from './types.mjs';
|
|
3
|
+
export type EnsuresPredicate<This extends Contracted> = (self: This, args: any[], old: This) => boolean;
|
|
4
|
+
export type EnsuresDecorator = <This extends Contracted>(predicate: EnsuresPredicate<This>) => (value: unknown, context: FeatureDecoratorContext) => void;
|
|
5
|
+
export declare const ensures: EnsuresDecorator;
|
|
6
|
+
export declare function assertEnsures(instance: Contracted, old: Contracted, propertyKey: PropertyKey, args: any): void;
|
package/dist/iff.d.mts
CHANGED
|
@@ -1,7 +1,20 @@
|
|
|
1
|
-
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
1
|
+
/**
|
|
2
|
+
* Biconditional.
|
|
3
|
+
* p ↔ q.
|
|
4
|
+
* "P if and only if Q".
|
|
5
|
+
* An example of usage is the encoding of "You can ride the train if and only if you have a ticket"
|
|
6
|
+
* This is logically equivalent to: implies(p,q) && implies(q,p)
|
|
7
|
+
*
|
|
8
|
+
* @param p - The first boolean value (the antecedent).
|
|
9
|
+
* @param q - The second boolean value (the consequent).
|
|
10
|
+
* @returns - The result (biconditional) of p and q.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { iff } from '@final-hill/decorator-contracts';
|
|
15
|
+
*
|
|
16
|
+
* // You can ride the train if and only if you have a ticket
|
|
17
|
+
* iff(person.hasTicket, person.ridesTrain)
|
|
18
|
+
* ```
|
|
6
19
|
*/
|
|
7
|
-
export
|
|
20
|
+
export declare function iff(p: boolean, q: boolean): boolean;
|
package/dist/implies.d.mts
CHANGED
|
@@ -1,7 +1,20 @@
|
|
|
1
|
-
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
1
|
+
/**
|
|
2
|
+
* Material Implication.
|
|
3
|
+
* `p → q`
|
|
4
|
+
* Also referred to as `if-then`.
|
|
5
|
+
* An example of usage is the encoding of "sunny weather is a precondition of visiting the beach"
|
|
6
|
+
* This is logically equivalent to: !p || q
|
|
7
|
+
*
|
|
8
|
+
* @param p - The first boolean value (the antecedent).
|
|
9
|
+
* @param q - The second boolean value (the consequent).
|
|
10
|
+
* @returns - The result (material implication) of p and q.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { implies } from '@final-hill/decorator-contracts';
|
|
15
|
+
*
|
|
16
|
+
* // Sunny weather is a precondition of visiting the beach
|
|
17
|
+
* implies(weather.isSunny, person.visitsBeach)
|
|
18
|
+
* ```
|
|
6
19
|
*/
|
|
7
|
-
export
|
|
20
|
+
export declare function implies(p: boolean, q: boolean): boolean;
|
package/dist/index.d.mts
CHANGED
|
@@ -1,13 +1,10 @@
|
|
|
1
|
-
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
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';
|
|
1
|
+
export * from './types.mjs';
|
|
2
|
+
export * from "./AssertionError.mjs";
|
|
3
|
+
export * from "./assert.mjs";
|
|
4
|
+
export * from './iff.mjs';
|
|
5
|
+
export * from './implies.mjs';
|
|
6
|
+
export * from './Contracted.mjs';
|
|
7
|
+
export * from './invariant.mjs';
|
|
8
|
+
export * from './demands.mjs';
|
|
9
|
+
export * from './ensures.mjs';
|
|
10
|
+
export * from './rescue.mjs';
|
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
|
|
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};
|
|
1
|
+
Symbol.metadata??=Symbol.for("Symbol.metadata");class t extends Error{}function e(e,r="Assertion Error"){if(0==Boolean(e))throw new t(r)}function r(t,e){return t&&e||!t&&!e}function n(t,e){return!t||e}function a(t,r){if(!h[u])return;h[u]=!1;const n=t[Symbol.metadata]?.invariants??[];try{for(const a of n)e(a(r),`Invariant violated in class ${t.name}: ${a.toString()}`)}finally{h[u]=!0}}const o=t=>(r,{kind:n,metadata:a})=>{e("class"===n,"@invariant decorator can only be applied to classes"),e(r.prototype instanceof h,"@invariant decorator can only be applied to classes that extend Contracted");const o=a.invariants??[];a.invariants=[...o,t]},s=t=>(r,n)=>{e(["method","getter","setter"].includes(n.kind),"@demands decorator can only be applied to methods, getters, or setters"),e(!1===n.static,"@demands decorator cannot be applied to static features"),e(!1===n.private,"@demands decorator cannot be applied to private/protected features"),e(!String(n.name).startsWith("_"),"@demands decorator cannot be applied to private/protected features"),n.addInitializer((function(){e(this instanceof h,"@demands decorator can only be applied to classes that extend Contracted");const r=[...n.metadata?.demands?.[n.name]??[],t];n.metadata.demands={...n.metadata?.demands??{},[n.name]:r}}))};function c(t,r,...n){if(!h[u])return;h[u]=!1;const a=t.constructor,o=a[Symbol.metadata]?.demands?.[r]??[];try{if(0===o.length)return;for(const e of o)if(e(t,...n))return;e(!1,`No demands were satisfied for ${t.constructor.name}.${String(r)}`)}finally{h[u]=!0}}const i=t=>(r,n)=>{e(["method","getter","setter"].includes(n.kind),"@ensures decorator can only be applied to methods, getters, or setters"),e(!1===n.static,"@ensures decorator cannot be applied to static features"),e(!1===n.private,"@ensures decorator cannot be applied to private features"),e(!String(n.name).startsWith("_"),"@ensures decorator cannot be applied to private/protected features"),n.addInitializer((function(){e(this instanceof h,"@ensures decorator can only be applied to classes that extend Contracted");const r=[...n.metadata?.ensures?.[n.name]??[],t];n.metadata.ensures={...n.metadata?.ensures??{},[n.name]:r}}))};function d(t,r,n,a){if(!h[u])return;h[u]=!1;const o=t.constructor,s=o[Symbol.metadata]?.ensures?.[n]??[];try{if(0===s.length)return;for(const o of s)o(t,a,r)||e(!1,`No ensurances were satisfied for ${t.constructor.name}.${String(n)}`)}finally{h[u]=!0}}const l=t=>(r,n)=>{e(["method","getter","setter"].includes(n.kind),"@rescue decorator can only be applied to methods, getters, or setters"),e(!1===n.static,"@rescue decorator cannot be applied to static features"),e(!1===n.private,"@rescue decorator cannot be applied to private features"),e(!String(n.name).startsWith("_"),"@rescue decorator cannot be applied to private/protected features"),n.addInitializer((function(){e(this instanceof h,"@rescue decorator can only be applied to classes that extend Contracted"),n.metadata.rescue={...n.metadata?.rescue??{},[n.name]:t}}))},f=(t,r,n,a,o)=>{if(!h[u])return a;const s=r.constructor,c=Object.getOwnPropertyDescriptor(s.prototype,n),i=s[Symbol.metadata]?.rescue?.[n];if(!i)throw a;let d,l=!1;h[u]=!1;try{if(i.call(r,r,a,o,((...a)=>{e(!l,"retry can only be called once"),l=!0,h[u]=!0,"get"==t?d=Reflect.get(r,n,r):"set"==t?d=Reflect.set(r,n,a[0],r):"func"==t&&(d=Reflect.apply(c.value,r,a))})),!l)throw a}finally{h[u]=!0}return d},u=Symbol.for("Contracted.checkedMode"),p=t=>{if(!h[u])return;h[u]=!1;const e=Object.create(t);for(const r in t)Reflect.set(e,r,Reflect.get(t,r));return h[u]=!0,e};function y(t,e){let r=t;for(;r&&r!==Object.prototype;){const t=Object.getOwnPropertyDescriptor(r,e);if(t)return t;r=Object.getPrototypeOf(r)}}const m={get(t,e,r){if(!h[u])return Reflect.get(t,e,r);const n=t.constructor,o=y(Object.getPrototypeOf(t),e),s=(n[Symbol.metadata]?.ensures?.[e]??[]).length>0,i=s?p(t):void 0;if("function"==typeof o?.value)return function(...r){let l;a(n,t),c(t,e,r);try{l=Reflect.apply(o.value,t,r),s&&d(t,i,e,r)}catch(n){l=f("func",t,e,n,r)}finally{a(n,t)}return l};if("function"==typeof o?.get){let o;a(n,t),c(t,e,[]);try{o=Reflect.get(t,e,r),s&&d(t,i,e,[o])}catch(r){o=f("get",t,e,r,[])}finally{a(n,t)}return o}return Reflect.get(t,e,r)},set(t,e,r,n){if(!h[u])return Reflect.set(t,e,r,n);const o=y(Object.getPrototypeOf(t),e);if(!(o&&"function"==typeof o.set||"string"!=typeof e||e.startsWith("_")))throw new TypeError(`Cannot assign to property '${String(e)}': only properties starting with '_' or with a setter can be set on Contracted instances.`);const s=t.constructor,i=(s[Symbol.metadata]?.ensures?.[e]??[]).length>0,l=i?p(t):void 0;let m;a(s,t),c(t,e,[r]);try{m=Reflect.set(t,e,r,n),i&&d(t,l,e,[r])}catch(n){m=f("set",t,e,n,[r])}finally{a(s,t)}return m},deleteProperty(t,e){throw new TypeError(`Cannot delete property '${String(e)}' from Contracted instances.`)}};class h{static[Symbol.metadata];static _allowConstruction=!1;static[u]=!0;static new(...t){this._allowConstruction=!0;try{const e=new this(...t);return a(this,e),new Proxy(e,m)}finally{this._allowConstruction=!1}}constructor(...t){if(!this.constructor._allowConstruction)throw new TypeError("Use the static 'new' method to instantiate this class.")}}export{t as AssertionError,h as Contracted,f as applyRescueHandler,e as assert,c as assertDemands,d as assertEnsures,a as assertInvariants,u as checkedMode,s as demands,i as ensures,r as iff,n as implies,o as invariant,l as rescue};
|
|
3
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +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,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eP,EAAMnD,GAC3BrB,GACK+E,GACDA,GAAgB3F,EAASf,aAAmB0G,EAAahH,YACzD+C,EAASkE,mBAGb,MAAeC,UAAwBT,EAEnCU,OAAiBX,IAAgB,EAEjC,WAAAxG,IAAe2B,GACXzB,SAASyB,GAET,MAAMiB,EAAQlC,KAAKV,YACf6F,EAAoBnB,EAAc/B,YAAYC,GA5ClE,IAA0BM,EAgDV,GAFAjB,GA9CUiB,EA8CY2C,EAAmBnF,MA7C9CrB,OAAOqG,QAAQrG,OAAO+H,0BA6CwB1G,OA5ChD2G,MAAK,EAAElI,EAAK+G,KAAU,IAAI,EAAQhD,EAAc/D,EAAK+G,GAAMF,cA4CJjD,EAASuE,kBAEpDzB,EAAkB5B,iBAAkB,CAErC,MAAMsD,EAAmB,EAAU1B,EAAkBlB,YAAa6C,GAAMA,EAAG5E,QAAU6D,IACrF,CAACZ,KAAsB0B,EAAkB7C,EAAclF,IAAIiH,IAAS5F,SAAQqC,IACxEA,EAAa6B,aAAamC,EAAgB5D,GAAe,GAEjE,CAIA,OAFA,EAAiB5C,KAAMwG,EAAgB5D,IAEhC5C,IACX,CAKA,WAAY4C,KAAmB,OAAOjC,CAAU,CAChD,IAAKiC,KAAmB,OAAOjC,CAAU,EAQ7C,OAL0BqD,EAAc/B,YAAYuE,GAClCjD,kBAAmB,EAErC5E,OAAOuG,OAAOa,GAEPS,CACX,CACJ,EChEe,SAASjF,EAAOwF,EAAoBxH,EAAkB8C,EAAS2E,gBAAiBC,EAAuC,GAClI,GAA0B,GAAtBC,QAAQH,GACR,MAAM,IAAIE,EAAiB1H,EACnC,CCfe,SAAS4H,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/classRegistry.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) 2024 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) 2024 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) 2024 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) 2024 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) 2024 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) 2024 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) 2024 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\nexport default new ClassRegistry();","/*!\r\n * @license\r\n * Copyright (C) 2024 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) 2024 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, classRegistry, 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 : classRegistry.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 = classRegistry.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) 2024 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) 2024 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) 2024 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) 2024 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 classRegistry from './classRegistry.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 classRegistry,\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) 2024 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, classRegistry, 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 = classRegistry.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, classRegistry.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 = classRegistry.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) 2024 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) 2024 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","classRegistry","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
|
+
{"version":3,"file":"index.mjs","mappings":"AAGCA,OAAeC,WAAaD,OAAOE,IAAI,mBCAjC,MAAMC,UAAuBC,OCmB7B,SAASC,EAAOC,EAAoBC,EAAkB,mBACzD,GAA0B,GAAtBC,QAAQF,GACR,MAAM,IAAIH,EAAeI,EACjC,CCLO,SAASE,EAAIC,EAAYC,GAC5B,OAAQD,GAAKC,IAAQD,IAAMC,CAC/B,CCFO,SAASC,EAAQF,EAAYC,GAChC,OAAQD,GAAKC,CACjB,CCVO,SAASE,EAAyEC,EAAUC,GAC/F,IAAKC,EAAWC,GAAc,OAE9BD,EAAWC,IAAe,EAE1B,MAAMC,EAAcJ,EAAMd,OAAOC,WAAwB,YAAK,GAE9D,IACI,IAAK,MAAMkB,KAAOD,EACdb,EACIc,EAAIJ,GACJ,+BAA+BD,EAAMM,SAASD,EAAIE,aAE9D,C,QACIL,EAAWC,IAAe,CAC9B,CACJ,CAEO,MAAMK,EAAiCC,GAAc,CAACC,GAAiBC,OAAMxB,eAChFI,EAAgB,UAAToB,EAAkB,uDACzBpB,EAAOmB,EAAcE,qBAAqBV,EAAY,8EAEtD,MAAMW,EAAY1B,EAASiB,YAAc,GACzCjB,EAASiB,WAAa,IAAIS,EAAUJ,EAAU,ECtBrCK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B,EAAQpB,EAAKyB,EAAM,CAACP,GACtD,CAAE,MAAOZ,GACLK,EAASP,EAAmB,MAAOgB,EAAQK,EAA0BnB,EAAO,CAACY,GACjF,C,QACIrD,EAAiBC,EAAOsD,EAC5B,CAEA,OAAOT,CACX,EACA,cAAAwB,CAAef,EAAQK,GACnB,MAAM,IAAIS,UAAU,2BAA2BhD,OAAOuC,iCAC1D,GAGG,MAAMzD,EACTgB,OAAQhC,OAAOC,UAQL+B,2BAA4B,EAG/BA,OAAQf,IAAwB,EAEvC,UAAO,IAGOwB,GACTJ,KAAa+C,oBAAqB,EACnC,IACI,MAAMrE,EAAW,IAAIsB,QAAQI,GAG7B,OAFA5B,EAAiBwB,KAAMtB,GAEhB,IAAIsE,MAAuBtE,EAAU8D,EAChD,C,QACKxC,KAAa+C,oBAAqB,CACvC,CACJ,CAEA,WAAA1C,IAAe4C,GAEX,IADcjD,KAAKK,YACR0C,mBACP,MAAM,IAAIF,UAAU,yDAC5B,S","sources":["webpack://@final-hill/decorator-contracts/./src/types.mts","webpack://@final-hill/decorator-contracts/./src/AssertionError.mts","webpack://@final-hill/decorator-contracts/./src/assert.mts","webpack://@final-hill/decorator-contracts/./src/iff.mts","webpack://@final-hill/decorator-contracts/./src/implies.mts","webpack://@final-hill/decorator-contracts/./src/invariant.mts","webpack://@final-hill/decorator-contracts/./src/demands.mts","webpack://@final-hill/decorator-contracts/./src/ensures.mts","webpack://@final-hill/decorator-contracts/./src/rescue.mts","webpack://@final-hill/decorator-contracts/./src/Contracted.mts"],"sourcesContent":["// Polyfill Symbol.metadata if not present\r\n// ref: https://github.com/microsoft/TypeScript/issues/53461#issuecomment-1736996954\r\n// ref: https://github.com/tc39/proposal-decorator-metadata\r\n(Symbol as any).metadata ??= Symbol.for(\"Symbol.metadata\");\r\n\r\n// Extend the global SymbolConstructor type to include metadata\r\ndeclare global {\r\n interface SymbolConstructor {\r\n readonly metadata: symbol;\r\n }\r\n}\r\n\r\nexport type Constructor<T> = new (...args: any[]) => T\r\n\r\nexport type FeatureDecoratorContext = Exclude<ClassMemberDecoratorContext, ClassAccessorDecoratorContext>;","/**\r\n * An AssertionError represents a failed assertion with an associated message\r\n */\r\nexport class AssertionError extends Error { }\r\n","import { AssertionError } from \"./AssertionError.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 condition - The condition to test. If it is false an error is raised.\r\n * @param message - The message to display if the condition is false. If not provided a default message is used.\r\n * @throws {AssertionError} If the condition is false an AssertionError is raised.\r\n *\r\n * @example\r\n * ```ts\r\n * import assert from \"assert.mjs\";\r\n *\r\n * let x = 15;\r\n * assert(x > 5, `Expected: x > 5. Actual: x = ${x}`);\r\n * ```\r\n */\r\n\r\nexport function assert(condition: unknown, message: string = 'Assertion Error'): asserts condition {\r\n if (Boolean(condition) == false)\r\n throw new AssertionError(message);\r\n}\r\n","/**\r\n * Biconditional.\r\n * p ↔ q.\r\n * \"P if and only if Q\".\r\n * An example of usage is the encoding of \"You can ride the train if and only if you have a ticket\"\r\n * This is logically equivalent to: implies(p,q) && implies(q,p)\r\n *\r\n * @param p - The first boolean value (the antecedent).\r\n * @param q - The second boolean value (the consequent).\r\n * @returns - The result (biconditional) of p and q.\r\n *\r\n * @example\r\n * ```ts\r\n * import { iff } from '@final-hill/decorator-contracts';\r\n *\r\n * // You can ride the train if and only if you have a ticket\r\n * iff(person.hasTicket, person.ridesTrain)\r\n * ```\r\n */\r\n\r\nexport function iff(p: boolean, q: boolean): boolean {\r\n return (p && q) || (!p && !q);\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 * @param p - The first boolean value (the antecedent).\r\n * @param q - The second boolean value (the consequent).\r\n * @returns - The result (material implication) of p and q.\r\n *\r\n * @example\r\n * ```ts\r\n * import { implies } from '@final-hill/decorator-contracts';\r\n *\r\n * // Sunny weather is a precondition of visiting the beach\r\n * implies(weather.isSunny, person.visitsBeach)\r\n * ```\r\n */\r\n\r\nexport function implies(p: boolean, q: boolean): boolean {\r\n return !p || q;\r\n}\r\n","import { assert } from './assert.mjs';\r\nimport { checkedMode, Contracted } from './Contracted.mjs';\r\n\r\nexport type InvariantPredicate<Class extends typeof Contracted> = (self: InstanceType<Class>) => boolean;\r\n\r\nexport type InvariantDecorator = <Class extends typeof Contracted>(\r\n predicate: InvariantPredicate<Class>\r\n) => (\r\n value: Class,\r\n context: ClassDecoratorContext<Class>\r\n) => Class | void;\r\n\r\nexport function assertInvariants<C extends typeof Contracted, T extends InstanceType<C>>(Class: C, instance: T) {\r\n if (!Contracted[checkedMode]) return;\r\n\r\n Contracted[checkedMode] = false; // Disable checked mode to avoid infinite recursion \r\n\r\n const invariants = (Class[Symbol.metadata]?.['invariants'] ?? []) as InvariantPredicate<C>[];\r\n\r\n try {\r\n for (const inv of invariants)\r\n assert(\r\n inv(instance),\r\n `Invariant violated in class ${Class.name}: ${inv.toString()}`\r\n );\r\n } finally {\r\n Contracted[checkedMode] = true;\r\n }\r\n}\r\n\r\nexport const invariant: InvariantDecorator = (predicate) => (OriginalClass, { kind, metadata }) => {\r\n assert(kind === 'class', '@invariant decorator can only be applied to classes');\r\n assert(OriginalClass.prototype instanceof Contracted, '@invariant decorator can only be applied to classes that extend Contracted');\r\n\r\n const existing = (metadata.invariants ?? []) as InvariantPredicate<typeof OriginalClass>[]\r\n metadata.invariants = [...existing, predicate];\r\n};\r\n","import { assert } from './assert.mjs';\r\nimport { checkedMode, Contracted } from \"./Contracted.mjs\";\r\nimport type { FeatureDecoratorContext } from './types.mjs';\r\n\r\nexport type DemandsPredicate<This extends Contracted> = (self: This, ...args: any[]) => boolean;\r\n\r\nexport type DemandsDecorator = <This extends Contracted, Feature = unknown>(\r\n predicate: DemandsPredicate<This>\r\n) => (\r\n value: Feature,\r\n context: FeatureDecoratorContext\r\n) => Feature | void;\r\n\r\nexport const demands: DemandsDecorator = (predicate) => (_feature, ctx) => {\r\n assert([\"method\", \"getter\", \"setter\"].includes(ctx.kind), '@demands decorator can only be applied to methods, getters, or setters');\r\n assert(ctx.static === false, '@demands decorator cannot be applied to static features');\r\n assert(ctx.private === false, '@demands decorator cannot be applied to private/protected features');\r\n assert(!String(ctx.name).startsWith('_'), '@demands decorator cannot be applied to private/protected features');\r\n\r\n ctx.addInitializer(function () {\r\n assert(this instanceof Contracted, '@demands decorator can only be applied to classes that extend Contracted');\r\n const ds = [\r\n ...(ctx.metadata as any)?.demands?.[ctx.name] ?? [],\r\n predicate\r\n ]\r\n\r\n ctx.metadata.demands = {\r\n ...(ctx.metadata?.demands ?? {}),\r\n [ctx.name]: ds\r\n };\r\n })\r\n}\r\n\r\nexport function assertDemands(instance: Contracted, propertyKey: PropertyKey, ...args: any[]) {\r\n if (!Contracted[checkedMode]) return;\r\n\r\n Contracted[checkedMode] = false; // Disable checked mode to avoid infinite recursion \r\n\r\n const Class = instance.constructor as typeof Contracted,\r\n ds = Class[Symbol.metadata]?.demands?.[propertyKey] ?? [] as DemandsPredicate<Contracted>[];\r\n\r\n try {\r\n if (ds.length === 0) return;\r\n\r\n // If ANY demand is true then the obligation is considered fulfilled\r\n for (const d of ds)\r\n if (d(instance, ...args)) return;\r\n\r\n // If we reach here, it means all demands were false\r\n assert(false, `No demands were satisfied for ${instance.constructor.name}.${String(propertyKey)}`);\r\n } finally {\r\n Contracted[checkedMode] = true;\r\n }\r\n}","import { assert } from './assert.mjs';\r\nimport { checkedMode, Contracted } from './Contracted.mjs';\r\nimport type { FeatureDecoratorContext } from './types.mjs';\r\n\r\nexport type EnsuresPredicate<This extends Contracted> = (self: This, args: any[], old: This) => boolean;\r\n\r\nexport type EnsuresDecorator = <\r\n This extends Contracted\r\n>(\r\n predicate: EnsuresPredicate<This>\r\n) => (\r\n value: unknown,\r\n context: FeatureDecoratorContext\r\n) => void;\r\n\r\nexport const ensures: EnsuresDecorator = (predicate) => (_feature, ctx) => {\r\n assert([\"method\", \"getter\", \"setter\"].includes(ctx.kind), '@ensures decorator can only be applied to methods, getters, or setters');\r\n assert(ctx.static === false, '@ensures decorator cannot be applied to static features');\r\n assert(ctx.private === false, '@ensures decorator cannot be applied to private features');\r\n assert(!String(ctx.name).startsWith('_'), '@ensures decorator cannot be applied to private/protected features');\r\n\r\n ctx.addInitializer(function () {\r\n assert(this instanceof Contracted, '@ensures decorator can only be applied to classes that extend Contracted');\r\n const es = [\r\n ...(ctx.metadata as any)?.ensures?.[ctx.name] ?? [],\r\n predicate\r\n ]\r\n\r\n ctx.metadata.ensures = {\r\n ...(ctx.metadata?.ensures ?? {}),\r\n [ctx.name]: es\r\n };\r\n })\r\n}\r\n\r\nexport function assertEnsures(instance: Contracted, old: Contracted, propertyKey: PropertyKey, args: any) {\r\n if (!Contracted[checkedMode]) return;\r\n\r\n Contracted[checkedMode] = false; // Disable checked mode to avoid infinite recursion\r\n\r\n const Class = instance.constructor as typeof Contracted,\r\n es = Class[Symbol.metadata]?.ensures?.[propertyKey] ?? [] as EnsuresPredicate<Contracted>[];\r\n\r\n try {\r\n if (es.length === 0) return;\r\n\r\n // ALL ensures must be true for the obligation to be fulfilled\r\n for (const e of es)\r\n if (!e(instance, args, old))\r\n\r\n assert(false, `No ensurances were satisfied for ${instance.constructor.name}.${String(propertyKey)}`);\r\n // If we reach here, it means all ensures were true\r\n } finally {\r\n Contracted[checkedMode] = true;\r\n }\r\n}\r\n","import { assert } from './assert.mjs';\r\nimport { checkedMode, Contracted } from './Contracted.mjs';\r\nimport type { FeatureDecoratorContext } from './types.mjs';\r\n\r\nexport type RescueHandler<This extends Contracted> =\r\n (self: This, error: unknown, args: any[], retry: (this: This, ...args: any[]) => any) => void\r\n\r\nexport type RescueDecorator = <This extends Contracted>(\r\n handler: RescueHandler<This>\r\n) => (\r\n value: unknown,\r\n context: FeatureDecoratorContext\r\n) => void;\r\n\r\nexport const rescue: RescueDecorator = (handler) => (_feature, ctx) => {\r\n assert([\"method\", \"getter\", \"setter\"].includes(ctx.kind), '@rescue decorator can only be applied to methods, getters, or setters');\r\n assert(ctx.static === false, '@rescue decorator cannot be applied to static features');\r\n assert(ctx.private === false, '@rescue decorator cannot be applied to private features');\r\n assert(!String(ctx.name).startsWith('_'), '@rescue decorator cannot be applied to private/protected features');\r\n\r\n ctx.addInitializer(function () {\r\n assert(this instanceof Contracted, '@rescue decorator can only be applied to classes that extend Contracted');\r\n\r\n ctx.metadata.rescue = {\r\n ...(ctx.metadata?.rescue ?? {}),\r\n [ctx.name]: handler\r\n }\r\n })\r\n}\r\n\r\nexport const applyRescueHandler = (descriptorType: 'get' | 'set' | 'func', instance: Contracted, propertyKey: PropertyKey, error: unknown, args: any) => {\r\n if (!Contracted[checkedMode]) return error;\r\n\r\n const Class = instance.constructor as typeof Contracted,\r\n descriptor = Object.getOwnPropertyDescriptor(Class.prototype, propertyKey)!,\r\n r = Class[Symbol.metadata]?.rescue?.[propertyKey] as RescueHandler<Contracted> | undefined;\r\n\r\n if (!r) throw error;\r\n\r\n let hasRetried = false;\r\n Contracted[checkedMode] = false; // Disable checked mode to avoid infinite recursion\r\n let result: any\r\n try {\r\n r.call(instance, instance, error, args, (...args: any[]) => {\r\n assert(!hasRetried, 'retry can only be called once');\r\n hasRetried = true;\r\n Contracted[checkedMode] = true;\r\n if (descriptorType == 'get')\r\n result = Reflect.get(instance, propertyKey, instance);\r\n else if (descriptorType == 'set')\r\n result = Reflect.set(instance, propertyKey, args[0], instance);\r\n else if (descriptorType == 'func')\r\n result = Reflect.apply(descriptor.value, instance, args);\r\n })\r\n if (!hasRetried)\r\n throw error;\r\n } finally {\r\n Contracted[checkedMode] = true;\r\n }\r\n\r\n return result;\r\n}\r\n","import { assertInvariants, InvariantPredicate } from './invariant.mjs';\r\nimport { assertDemands, DemandsPredicate } from './demands.mjs';\r\nimport { assertEnsures, EnsuresPredicate } from './ensures.mjs';\r\nimport { applyRescueHandler as applyRescueHandler, RescueHandler } from './rescue.mjs';\r\n\r\n// Symbol to store checked mode state\r\nexport const checkedMode = Symbol.for('Contracted.checkedMode');\r\n\r\nconst populateOld = (target: Contracted) => {\r\n if (!Contracted[checkedMode]) return;\r\n\r\n Contracted[checkedMode] = false; // Disable checked mode to avoid infinite recursion\r\n\r\n const old = Object.create(target)\r\n for (const key in target)\r\n Reflect.set(old, key, Reflect.get(target, key));\r\n\r\n Contracted[checkedMode] = true;\r\n\r\n return old;\r\n}\r\n\r\n// Utility to walk up the prototype chain to find a property descriptor\r\nfunction getPropertyDescriptor(obj: object, prop: PropertyKey): PropertyDescriptor | undefined {\r\n let proto = obj;\r\n while (proto && proto !== Object.prototype) {\r\n const desc = Object.getOwnPropertyDescriptor(proto, prop);\r\n if (desc) return desc;\r\n proto = Object.getPrototypeOf(proto);\r\n }\r\n return undefined;\r\n}\r\n\r\nconst proxyHandler: ProxyHandler<Contracted> = {\r\n get(target, prop, receiver) {\r\n if (!Contracted[checkedMode]) return Reflect.get(target, prop, receiver);\r\n\r\n const Class = target.constructor as typeof Contracted,\r\n descriptor = getPropertyDescriptor(Object.getPrototypeOf(target), prop),\r\n es = Class[Symbol.metadata]?.ensures?.[prop] ?? [] as EnsuresPredicate<Contracted>[],\r\n hasEnsures = es.length > 0,\r\n old = hasEnsures ? populateOld(target) : undefined;\r\n\r\n if (typeof descriptor?.value === 'function') {\r\n return function (this: Contracted, ...methodArgs: any[]) {\r\n assertInvariants(Class, target);\r\n assertDemands(target, prop, methodArgs);\r\n let result\r\n try {\r\n result = Reflect.apply(descriptor.value, target, methodArgs);\r\n if (hasEnsures) assertEnsures(target, old, prop, methodArgs);\r\n } catch (error) {\r\n result = applyRescueHandler('func', target, prop as keyof Contracted, error, methodArgs);\r\n } finally {\r\n assertInvariants(Class, target);\r\n }\r\n return result;\r\n }\r\n } else if (typeof descriptor?.get === 'function') {\r\n assertInvariants(Class, target);\r\n assertDemands(target, prop, []);\r\n let result\r\n try {\r\n result = Reflect.get(target, prop, receiver);\r\n if (hasEnsures) assertEnsures(target, old, prop, [result]);\r\n } catch (error) {\r\n result = applyRescueHandler('get', target, prop, error, []);\r\n } finally {\r\n assertInvariants(Class, target);\r\n }\r\n return result;\r\n } else {\r\n return Reflect.get(target, prop, receiver);\r\n }\r\n },\r\n set(target, prop, value, receiver) {\r\n if (!Contracted[checkedMode]) return Reflect.set(target, prop, value, receiver);\r\n\r\n const descriptor = getPropertyDescriptor(Object.getPrototypeOf(target), prop)\r\n\r\n if (!(descriptor && typeof descriptor.set === 'function'))\r\n if (typeof prop === 'string' && !prop.startsWith('_'))\r\n throw new TypeError(`Cannot assign to property '${String(prop)}': only properties starting with '_' or with a setter can be set on Contracted instances.`);\r\n\r\n const Class = target.constructor as typeof Contracted,\r\n es = Class[Symbol.metadata]?.ensures?.[prop] ?? [] as EnsuresPredicate<Contracted>[],\r\n hasEnsures = es.length > 0,\r\n old = hasEnsures ? populateOld(target) : undefined;\r\n assertInvariants(Class, target);\r\n assertDemands(target, prop, [value]);\r\n let result\r\n try {\r\n result = Reflect.set(target, prop, value, receiver);\r\n if (hasEnsures) assertEnsures(target, old, prop, [value]);\r\n } catch (error) {\r\n result = applyRescueHandler('set', target, prop as keyof Contracted, error, [value])\r\n } finally {\r\n assertInvariants(Class, target);\r\n }\r\n\r\n return result;\r\n },\r\n deleteProperty(target, prop) {\r\n throw new TypeError(`Cannot delete property '${String(prop)}' from Contracted instances.`);\r\n },\r\n};\r\n\r\nexport class Contracted {\r\n static [Symbol.metadata]: {\r\n invariants: InvariantPredicate<typeof Contracted>[];\r\n demands: Record<PropertyKey, DemandsPredicate<Contracted>[]>;\r\n ensures: Record<PropertyKey, EnsuresPredicate<Contracted>[]>;\r\n rescue: Record<PropertyKey, RescueHandler<Contracted>>;\r\n };\r\n\r\n // Prevents direct instantiation of the class\r\n protected static _allowConstruction = false;\r\n\r\n // Symbol-based checked mode state\r\n public static [checkedMode]: boolean = true;\r\n\r\n static new<\r\n C extends typeof Contracted,\r\n Args extends ConstructorParameters<C>,\r\n >(this: C, ...args: Args): InstanceType<C> {\r\n (this as any)._allowConstruction = true;\r\n try {\r\n const instance = new this(...args) as InstanceType<C>;\r\n assertInvariants(this, instance);\r\n\r\n return new Proxy<InstanceType<C>>(instance, proxyHandler);\r\n } finally {\r\n (this as any)._allowConstruction = false;\r\n }\r\n }\r\n\r\n constructor(..._args: any[]) {\r\n const Class = this.constructor as typeof Contracted;\r\n if (!Class._allowConstruction)\r\n throw new TypeError(\"Use the static 'new' method to instantiate this class.\")\r\n }\r\n}"],"names":["Symbol","metadata","for","AssertionError","Error","assert","condition","message","Boolean","iff","p","q","implies","assertInvariants","Class","instance","Contracted","checkedMode","invariants","inv","name","toString","invariant","predicate","OriginalClass","kind","prototype","existing","demands","_feature","ctx","includes","static","private","String","startsWith","addInitializer","this","ds","assertDemands","propertyKey","args","constructor","length","d","ensures","es","assertEnsures","old","e","rescue","handler","applyRescueHandler","descriptorType","error","descriptor","Object","getOwnPropertyDescriptor","r","result","hasRetried","call","Reflect","get","set","apply","value","populateOld","target","create","key","getPropertyDescriptor","obj","prop","proto","desc","getPrototypeOf","proxyHandler","receiver","hasEnsures","undefined","methodArgs","TypeError","deleteProperty","_allowConstruction","Proxy","_args"],"sourceRoot":""}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { Contracted } from './Contracted.mjs';
|
|
2
|
+
export type InvariantPredicate<Class extends typeof Contracted> = (self: InstanceType<Class>) => boolean;
|
|
3
|
+
export type InvariantDecorator = <Class extends typeof Contracted>(predicate: InvariantPredicate<Class>) => (value: Class, context: ClassDecoratorContext<Class>) => Class | void;
|
|
4
|
+
export declare function assertInvariants<C extends typeof Contracted, T extends InstanceType<C>>(Class: C, instance: T): void;
|
|
5
|
+
export declare const invariant: InvariantDecorator;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { Contracted } from './Contracted.mjs';
|
|
2
|
+
import type { FeatureDecoratorContext } from './types.mjs';
|
|
3
|
+
export type RescueHandler<This extends Contracted> = (self: This, error: unknown, args: any[], retry: (this: This, ...args: any[]) => any) => void;
|
|
4
|
+
export type RescueDecorator = <This extends Contracted>(handler: RescueHandler<This>) => (value: unknown, context: FeatureDecoratorContext) => void;
|
|
5
|
+
export declare const rescue: RescueDecorator;
|
|
6
|
+
export declare const applyRescueHandler: (descriptorType: "get" | "set" | "func", instance: Contracted, propertyKey: PropertyKey, error: unknown, args: any) => any;
|
package/dist/types.d.mts
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@final-hill/decorator-contracts",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.0",
|
|
4
4
|
"description": "Code Contracts for TypeScript and ECMAScript classes",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -13,8 +13,10 @@
|
|
|
13
13
|
"prebuild": "npm run lint",
|
|
14
14
|
"build": "webpack",
|
|
15
15
|
"lint": "eslint src/ --ext .mts --fix",
|
|
16
|
-
"
|
|
16
|
+
"pretest": "npm run build",
|
|
17
|
+
"test": "globstar -- node --import tsx --test ./src/tests/*.test.mts"
|
|
17
18
|
},
|
|
19
|
+
"homepage": "https://github.com/final-hill/decorator-contracts#readme",
|
|
18
20
|
"repository": {
|
|
19
21
|
"type": "git",
|
|
20
22
|
"url": "https://github.com/final-hill/decorator-contracts"
|
|
@@ -47,23 +49,22 @@
|
|
|
47
49
|
"author": "Michael L Haufe <michael.haufe@final-hill.com> (https://final-hill.com)",
|
|
48
50
|
"license": "AGPL-3.0-only",
|
|
49
51
|
"devDependencies": {
|
|
50
|
-
"@
|
|
51
|
-
"@
|
|
52
|
-
"@
|
|
53
|
-
"@
|
|
54
|
-
"eslint": "^
|
|
55
|
-
"eslint-plugin
|
|
56
|
-
"
|
|
57
|
-
"
|
|
58
|
-
"
|
|
59
|
-
"
|
|
60
|
-
"
|
|
61
|
-
"
|
|
62
|
-
"
|
|
63
|
-
"webpack": "^
|
|
64
|
-
"webpack-cli": "^5.1.4"
|
|
52
|
+
"@eslint/js": "^9.27.0",
|
|
53
|
+
"@eslint/json": "^0.12.0",
|
|
54
|
+
"@eslint/markdown": "^6.4.0",
|
|
55
|
+
"@types/node": "^22.15.21",
|
|
56
|
+
"eslint": "^9.27.0",
|
|
57
|
+
"eslint-webpack-plugin": "^5.0.1",
|
|
58
|
+
"globals": "^16.1.0",
|
|
59
|
+
"globstar": "^1.0.0",
|
|
60
|
+
"ts-loader": "^9.5.2",
|
|
61
|
+
"tsx": "^4.19.4",
|
|
62
|
+
"typescript": "^5.8.3",
|
|
63
|
+
"typescript-eslint": "^8.32.1",
|
|
64
|
+
"webpack": "^5.99.9",
|
|
65
|
+
"webpack-cli": "^6.0.1"
|
|
65
66
|
},
|
|
66
67
|
"files": [
|
|
67
68
|
"dist"
|
|
68
69
|
]
|
|
69
|
-
}
|
|
70
|
+
}
|
package/dist/Contract.d.mts
DELETED
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
/*!
|
|
2
|
-
* @license
|
|
3
|
-
* Copyright (C) 2024 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 };
|
package/dist/Messages.d.mts
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
/*!
|
|
2
|
-
* @license
|
|
3
|
-
* Copyright (C) 2024 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,23 +0,0 @@
|
|
|
1
|
-
/*!
|
|
2
|
-
* @license
|
|
3
|
-
* Copyright (C) 2024 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;
|
package/dist/lib/ClassType.d.mts
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
/*!
|
|
2
|
-
* @license
|
|
3
|
-
* Copyright (C) 2024 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 };
|
package/dist/lib/Feature.d.mts
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
/*!
|
|
2
|
-
* @license
|
|
3
|
-
* Copyright (C) 2024 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 from './ClassRegistration.mjs';
|
|
8
|
-
declare class Feature {
|
|
9
|
-
#private;
|
|
10
|
-
readonly classRegistration: ClassRegistration;
|
|
11
|
-
readonly name: PropertyKey;
|
|
12
|
-
constructor(classRegistration: ClassRegistration, name: PropertyKey, descriptor: PropertyDescriptor);
|
|
13
|
-
get ancestorFeature(): Feature | null;
|
|
14
|
-
get getter(): (() => any) | undefined;
|
|
15
|
-
get hasGetter(): boolean;
|
|
16
|
-
get hasSetter(): boolean;
|
|
17
|
-
get isProperty(): boolean;
|
|
18
|
-
get isMethod(): boolean;
|
|
19
|
-
get isAccessor(): boolean;
|
|
20
|
-
get memberType(): 'method' | 'property' | 'accessor';
|
|
21
|
-
get setter(): ((v: any) => void) | undefined;
|
|
22
|
-
get value(): any;
|
|
23
|
-
get descriptor(): PropertyDescriptor;
|
|
24
|
-
set descriptor(desc: PropertyDescriptor);
|
|
25
|
-
}
|
|
26
|
-
export default Feature;
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
/*!
|
|
2
|
-
* @license
|
|
3
|
-
* Copyright (C) 2024 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
|
-
declare function assertDemands<U extends object>(ctx: U, contract: Contract<U>, className: string, featureName: PropertyKey, args: any[]): void;
|
|
9
|
-
export default assertDemands;
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
/*!
|
|
2
|
-
* @license
|
|
3
|
-
* Copyright (C) 2024 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 { Properties } from '../Contract.mjs';
|
|
8
|
-
import { Contract } from '../index.mjs';
|
|
9
|
-
declare function assertEnsures<U extends Properties<any>>(ctx: U, contract: Contract<any>, className: string, featureName: PropertyKey, old: U, args: any[]): void;
|
|
10
|
-
export default assertEnsures;
|