@vielzeug/ward 26.10.14 → 26.10.16

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.
@@ -1 +1 @@
1
- {"version":3,"file":"_compile.cjs","names":[],"sources":["../src/_compile.ts"],"sourcesContent":["import { WardConfigError } from './errors';\nimport type { WardAttributes, WardAttributeValue, WardRule } from './types';\n\nfunction snapshotValue(value: unknown, path: string, ancestors: Set<object>): WardAttributeValue {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') return value;\n\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new WardConfigError(`${path} must contain only finite numbers`);\n return value;\n }\n\n if (typeof value !== 'object') {\n throw new WardConfigError(`${path} must contain only JSON-compatible values`);\n }\n\n if (ancestors.has(value)) throw new WardConfigError(`${path} must not contain circular references`);\n\n const prototype = Object.getPrototypeOf(value);\n if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) {\n throw new WardConfigError(`${path} must contain only arrays and plain objects`);\n }\n\n ancestors.add(value);\n\n try {\n if (Array.isArray(value)) {\n return Object.freeze(Array.from(value, (item, index) => snapshotValue(item, `${path}[${index}]`, ancestors)));\n }\n\n return Object.freeze(\n Object.fromEntries(\n Object.keys(value).map((key) => [\n key,\n snapshotValue((value as Record<string, unknown>)[key], `${path}.${key}`, ancestors),\n ]),\n ),\n );\n } finally {\n ancestors.delete(value);\n }\n}\n\nexport function snapshotAttributes(value: unknown, path: string): WardAttributes | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new WardConfigError(`${path} must be a plain object`);\n }\n\n return snapshotValue(value, path, new Set()) as WardAttributes;\n}\n\n/**\n * Validates and snapshots a single rule definition at ward-creation time.\n * Throws {@link WardConfigError} with a `Rule[index]`-prefixed message on failure.\n */\nexport function compileRule<TAction extends string, TResource extends string, TAttributes extends WardAttributes>(\n rule: WardRule<TAction, TResource, TAttributes>,\n index: number,\n): WardRule<TAction, TResource, TAttributes> {\n const at = `Rule[${index}]`;\n\n if (typeof rule !== 'object' || rule === null || Array.isArray(rule)) {\n throw new WardConfigError(`${at} must be a plain object`);\n }\n const prototype = Object.getPrototypeOf(rule);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new WardConfigError(`${at} must be a plain object`);\n }\n\n if (typeof rule.action !== 'string' || !rule.action.trim()) {\n throw new WardConfigError(`${at}.action must be a non-empty string`);\n }\n\n if (rule.action.endsWith(':')) {\n throw new WardConfigError(`${at}.action '${rule.action}' ends with ':': did you mean '${rule.action}*'?`);\n }\n\n if (typeof rule.resource !== 'string' || !rule.resource.trim()) {\n throw new WardConfigError(`${at}.resource must be a non-empty string`);\n }\n\n if (rule.resource.endsWith(':')) {\n throw new WardConfigError(`${at}.resource '${rule.resource}' ends with ':': did you mean '${rule.resource}*'?`);\n }\n\n if (rule.effect !== 'allow' && rule.effect !== 'deny') {\n throw new WardConfigError(`${at}.effect must be \"allow\" or \"deny\"`);\n }\n\n if (rule.condition !== undefined && typeof rule.condition !== 'function') {\n throw new WardConfigError(`${at}.condition must be a function`);\n }\n\n if (rule.roles !== undefined) {\n if (!Array.isArray(rule.roles) || rule.roles.some((role) => typeof role !== 'string' || !role.trim())) {\n throw new WardConfigError(`${at}.roles must be an array of non-empty strings`);\n }\n }\n\n return Object.freeze({\n action: rule.action,\n ...(rule.attributes === undefined ? {} : { attributes: snapshotAttributes(rule.attributes, `${at}.attributes`) }),\n ...(rule.condition === undefined ? {} : { condition: rule.condition }),\n effect: rule.effect,\n resource: rule.resource,\n ...(rule.roles === undefined ? {} : { roles: Object.freeze([...rule.roles]) }),\n }) as WardRule<TAction, TResource, TAttributes>;\n}\n"],"mappings":"gCAGA,SAAS,cAAc,EAAgB,EAAc,EAA4C,CAC/F,GAAI,IAAU,MAAQ,OAAO,GAAU,WAAa,OAAO,GAAU,SAAU,OAAO,EAEtF,GAAI,OAAO,GAAU,SAAU,CAC7B,GAAI,CAAC,OAAO,SAAS,CAAK,EAAG,MAA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AO,OAAO,OAAO,CAAC,GAAG,EAAK,KAAK,CAAC,CAAE,CAC9E,CAAC,CACH"}
1
+ {"version":3,"file":"_compile.cjs","names":["WardConfigError","require_errors","value","path","ancestors","prototype","item","index","key","at","rule","role"],"sources":["../src/_compile.ts"],"sourcesContent":["import { WardConfigError } from './errors';\nimport type { WardAttributes, WardAttributeValue, WardRule } from './types';\n\nfunction snapshotValue(value: unknown, path: string, ancestors: Set<object>): WardAttributeValue {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') return value;\n\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new WardConfigError(`${path} must contain only finite numbers`);\n return value;\n }\n\n if (typeof value !== 'object') {\n throw new WardConfigError(`${path} must contain only JSON-compatible values`);\n }\n\n if (ancestors.has(value)) throw new WardConfigError(`${path} must not contain circular references`);\n\n const prototype = Object.getPrototypeOf(value);\n if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) {\n throw new WardConfigError(`${path} must contain only arrays and plain objects`);\n }\n\n ancestors.add(value);\n\n try {\n if (Array.isArray(value)) {\n return Object.freeze(Array.from(value, (item, index) => snapshotValue(item, `${path}[${index}]`, ancestors)));\n }\n\n return Object.freeze(\n Object.fromEntries(\n Object.keys(value).map((key) => [\n key,\n snapshotValue((value as Record<string, unknown>)[key], `${path}.${key}`, ancestors),\n ]),\n ),\n );\n } finally {\n ancestors.delete(value);\n }\n}\n\nexport function snapshotAttributes(value: unknown, path: string): WardAttributes | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new WardConfigError(`${path} must be a plain object`);\n }\n\n return snapshotValue(value, path, new Set()) as WardAttributes;\n}\n\n/**\n * Validates and snapshots a single rule definition at ward-creation time.\n * Throws {@link WardConfigError} with a `Rule[index]`-prefixed message on failure.\n */\nexport function compileRule<TAction extends string, TResource extends string, TAttributes extends WardAttributes>(\n rule: WardRule<TAction, TResource, TAttributes>,\n index: number,\n): WardRule<TAction, TResource, TAttributes> {\n const at = `Rule[${index}]`;\n\n if (typeof rule !== 'object' || rule === null || Array.isArray(rule)) {\n throw new WardConfigError(`${at} must be a plain object`);\n }\n const prototype = Object.getPrototypeOf(rule);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new WardConfigError(`${at} must be a plain object`);\n }\n\n if (typeof rule.action !== 'string' || !rule.action.trim()) {\n throw new WardConfigError(`${at}.action must be a non-empty string`);\n }\n\n if (rule.action.endsWith(':')) {\n throw new WardConfigError(`${at}.action '${rule.action}' ends with ':': did you mean '${rule.action}*'?`);\n }\n\n if (typeof rule.resource !== 'string' || !rule.resource.trim()) {\n throw new WardConfigError(`${at}.resource must be a non-empty string`);\n }\n\n if (rule.resource.endsWith(':')) {\n throw new WardConfigError(`${at}.resource '${rule.resource}' ends with ':': did you mean '${rule.resource}*'?`);\n }\n\n if (rule.effect !== 'allow' && rule.effect !== 'deny') {\n throw new WardConfigError(`${at}.effect must be \"allow\" or \"deny\"`);\n }\n\n if (rule.condition !== undefined && typeof rule.condition !== 'function') {\n throw new WardConfigError(`${at}.condition must be a function`);\n }\n\n if (rule.roles !== undefined) {\n if (!Array.isArray(rule.roles) || rule.roles.some((role) => typeof role !== 'string' || !role.trim())) {\n throw new WardConfigError(`${at}.roles must be an array of non-empty strings`);\n }\n }\n\n return Object.freeze({\n action: rule.action,\n ...(rule.attributes === undefined ? {} : { attributes: snapshotAttributes(rule.attributes, `${at}.attributes`) }),\n ...(rule.condition === undefined ? {} : { condition: rule.condition }),\n effect: rule.effect,\n resource: rule.resource,\n ...(rule.roles === undefined ? {} : { roles: Object.freeze([...rule.roles]) }),\n }) as WardRule<TAction, TResource, TAttributes>;\n}\n"],"mappings":"A,gCAGA,SAAS,cAAc,EAAgB,EAAc,EAA4C,CAC/F,GAAIE,IAAU,MAAQ,OAAOA,GAAU,WAAa,OAAOA,GAAU,SAAU,OAAOA,EAEtF,GAAI,OAAOA,GAAU,SAAU,CAC7B,GAAI,CAAC,OAAO,SAASA,CAAK,EAAG,MA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AAC,EAAI,CAAE,UAAWA,EAAK,SAAU,EACpE,OAAQA,EAAK,OACb,SAAUA,EAAK,SACf,GAAIA,EAAK,QAAU,IAAA,GAAY,CAAC,EAAI,CAAE,MAAO,OAAO,OAAO,CAAC,GAAGA,EAAK,KAAK,CAAC,CAAE,CAC9E,CAAC,CACH,C"}
package/dist/_compile.js CHANGED
@@ -1,2 +1,50 @@
1
- import{WardConfigError as e}from"./errors.js";function snapshotValue(t,n,r){if(t===null||typeof t==`boolean`||typeof t==`string`)return t;if(typeof t==`number`){if(!Number.isFinite(t))throw new e(`${n} must contain only finite numbers`);return t}if(typeof t!=`object`)throw new e(`${n} must contain only JSON-compatible values`);if(r.has(t))throw new e(`${n} must not contain circular references`);let i=Object.getPrototypeOf(t);if(!Array.isArray(t)&&i!==Object.prototype&&i!==null)throw new e(`${n} must contain only arrays and plain objects`);r.add(t);try{return Object.freeze(Array.isArray(t)?Array.from(t,(e,t)=>snapshotValue(e,`${n}[${t}]`,r)):Object.fromEntries(Object.keys(t).map(e=>[e,snapshotValue(t[e],`${n}.${e}`,r)])))}finally{r.delete(t)}}function snapshotAttributes(t,n){if(t!==void 0){if(typeof t!=`object`||!t||Array.isArray(t))throw new e(`${n} must be a plain object`);return snapshotValue(t,n,new Set)}}function compileRule(t,n){let r=`Rule[${n}]`;if(typeof t!=`object`||!t||Array.isArray(t))throw new e(`${r} must be a plain object`);let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)throw new e(`${r} must be a plain object`);if(typeof t.action!=`string`||!t.action.trim())throw new e(`${r}.action must be a non-empty string`);if(t.action.endsWith(`:`))throw new e(`${r}.action '${t.action}' ends with ':': did you mean '${t.action}*'?`);if(typeof t.resource!=`string`||!t.resource.trim())throw new e(`${r}.resource must be a non-empty string`);if(t.resource.endsWith(`:`))throw new e(`${r}.resource '${t.resource}' ends with ':': did you mean '${t.resource}*'?`);if(t.effect!==`allow`&&t.effect!==`deny`)throw new e(`${r}.effect must be "allow" or "deny"`);if(t.condition!==void 0&&typeof t.condition!=`function`)throw new e(`${r}.condition must be a function`);if(t.roles!==void 0&&(!Array.isArray(t.roles)||t.roles.some(e=>typeof e!=`string`||!e.trim())))throw new e(`${r}.roles must be an array of non-empty strings`);return Object.freeze({action:t.action,...t.attributes===void 0?{}:{attributes:snapshotAttributes(t.attributes,`${r}.attributes`)},...t.condition===void 0?{}:{condition:t.condition},effect:t.effect,resource:t.resource,...t.roles===void 0?{}:{roles:Object.freeze([...t.roles])}})}export{compileRule,snapshotAttributes};
1
+ import { WardConfigError as e } from "./errors.js";
2
+ //#region src/_compile.ts
3
+ function snapshotValue(t, n, r) {
4
+ if (t === null || typeof t == "boolean" || typeof t == "string") return t;
5
+ if (typeof t == "number") {
6
+ if (!Number.isFinite(t)) throw new e(`${n} must contain only finite numbers`);
7
+ return t;
8
+ }
9
+ if (typeof t != "object") throw new e(`${n} must contain only JSON-compatible values`);
10
+ if (r.has(t)) throw new e(`${n} must not contain circular references`);
11
+ let i = Object.getPrototypeOf(t);
12
+ if (!Array.isArray(t) && i !== Object.prototype && i !== null) throw new e(`${n} must contain only arrays and plain objects`);
13
+ r.add(t);
14
+ try {
15
+ return Object.freeze(Array.isArray(t) ? Array.from(t, (e, t) => snapshotValue(e, `${n}[${t}]`, r)) : Object.fromEntries(Object.keys(t).map((e) => [e, snapshotValue(t[e], `${n}.${e}`, r)])));
16
+ } finally {
17
+ r.delete(t);
18
+ }
19
+ }
20
+ function snapshotAttributes(t, n) {
21
+ if (t !== void 0) {
22
+ if (typeof t != "object" || !t || Array.isArray(t)) throw new e(`${n} must be a plain object`);
23
+ return snapshotValue(t, n, /* @__PURE__ */ new Set());
24
+ }
25
+ }
26
+ function compileRule(t, n) {
27
+ let r = `Rule[${n}]`;
28
+ if (typeof t != "object" || !t || Array.isArray(t)) throw new e(`${r} must be a plain object`);
29
+ let i = Object.getPrototypeOf(t);
30
+ if (i !== Object.prototype && i !== null) throw new e(`${r} must be a plain object`);
31
+ if (typeof t.action != "string" || !t.action.trim()) throw new e(`${r}.action must be a non-empty string`);
32
+ if (t.action.endsWith(":")) throw new e(`${r}.action '${t.action}' ends with ':': did you mean '${t.action}*'?`);
33
+ if (typeof t.resource != "string" || !t.resource.trim()) throw new e(`${r}.resource must be a non-empty string`);
34
+ if (t.resource.endsWith(":")) throw new e(`${r}.resource '${t.resource}' ends with ':': did you mean '${t.resource}*'?`);
35
+ if (t.effect !== "allow" && t.effect !== "deny") throw new e(`${r}.effect must be "allow" or "deny"`);
36
+ if (t.condition !== void 0 && typeof t.condition != "function") throw new e(`${r}.condition must be a function`);
37
+ if (t.roles !== void 0 && (!Array.isArray(t.roles) || t.roles.some((e) => typeof e != "string" || !e.trim()))) throw new e(`${r}.roles must be an array of non-empty strings`);
38
+ return Object.freeze({
39
+ action: t.action,
40
+ ...t.attributes === void 0 ? {} : { attributes: snapshotAttributes(t.attributes, `${r}.attributes`) },
41
+ ...t.condition === void 0 ? {} : { condition: t.condition },
42
+ effect: t.effect,
43
+ resource: t.resource,
44
+ ...t.roles === void 0 ? {} : { roles: Object.freeze([...t.roles]) }
45
+ });
46
+ }
47
+ //#endregion
48
+ export { compileRule, snapshotAttributes };
49
+
2
50
  //# sourceMappingURL=_compile.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"_compile.js","names":[],"sources":["../src/_compile.ts"],"sourcesContent":["import { WardConfigError } from './errors';\nimport type { WardAttributes, WardAttributeValue, WardRule } from './types';\n\nfunction snapshotValue(value: unknown, path: string, ancestors: Set<object>): WardAttributeValue {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') return value;\n\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new WardConfigError(`${path} must contain only finite numbers`);\n return value;\n }\n\n if (typeof value !== 'object') {\n throw new WardConfigError(`${path} must contain only JSON-compatible values`);\n }\n\n if (ancestors.has(value)) throw new WardConfigError(`${path} must not contain circular references`);\n\n const prototype = Object.getPrototypeOf(value);\n if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) {\n throw new WardConfigError(`${path} must contain only arrays and plain objects`);\n }\n\n ancestors.add(value);\n\n try {\n if (Array.isArray(value)) {\n return Object.freeze(Array.from(value, (item, index) => snapshotValue(item, `${path}[${index}]`, ancestors)));\n }\n\n return Object.freeze(\n Object.fromEntries(\n Object.keys(value).map((key) => [\n key,\n snapshotValue((value as Record<string, unknown>)[key], `${path}.${key}`, ancestors),\n ]),\n ),\n );\n } finally {\n ancestors.delete(value);\n }\n}\n\nexport function snapshotAttributes(value: unknown, path: string): WardAttributes | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new WardConfigError(`${path} must be a plain object`);\n }\n\n return snapshotValue(value, path, new Set()) as WardAttributes;\n}\n\n/**\n * Validates and snapshots a single rule definition at ward-creation time.\n * Throws {@link WardConfigError} with a `Rule[index]`-prefixed message on failure.\n */\nexport function compileRule<TAction extends string, TResource extends string, TAttributes extends WardAttributes>(\n rule: WardRule<TAction, TResource, TAttributes>,\n index: number,\n): WardRule<TAction, TResource, TAttributes> {\n const at = `Rule[${index}]`;\n\n if (typeof rule !== 'object' || rule === null || Array.isArray(rule)) {\n throw new WardConfigError(`${at} must be a plain object`);\n }\n const prototype = Object.getPrototypeOf(rule);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new WardConfigError(`${at} must be a plain object`);\n }\n\n if (typeof rule.action !== 'string' || !rule.action.trim()) {\n throw new WardConfigError(`${at}.action must be a non-empty string`);\n }\n\n if (rule.action.endsWith(':')) {\n throw new WardConfigError(`${at}.action '${rule.action}' ends with ':': did you mean '${rule.action}*'?`);\n }\n\n if (typeof rule.resource !== 'string' || !rule.resource.trim()) {\n throw new WardConfigError(`${at}.resource must be a non-empty string`);\n }\n\n if (rule.resource.endsWith(':')) {\n throw new WardConfigError(`${at}.resource '${rule.resource}' ends with ':': did you mean '${rule.resource}*'?`);\n }\n\n if (rule.effect !== 'allow' && rule.effect !== 'deny') {\n throw new WardConfigError(`${at}.effect must be \"allow\" or \"deny\"`);\n }\n\n if (rule.condition !== undefined && typeof rule.condition !== 'function') {\n throw new WardConfigError(`${at}.condition must be a function`);\n }\n\n if (rule.roles !== undefined) {\n if (!Array.isArray(rule.roles) || rule.roles.some((role) => typeof role !== 'string' || !role.trim())) {\n throw new WardConfigError(`${at}.roles must be an array of non-empty strings`);\n }\n }\n\n return Object.freeze({\n action: rule.action,\n ...(rule.attributes === undefined ? {} : { attributes: snapshotAttributes(rule.attributes, `${at}.attributes`) }),\n ...(rule.condition === undefined ? {} : { condition: rule.condition }),\n effect: rule.effect,\n resource: rule.resource,\n ...(rule.roles === undefined ? {} : { roles: Object.freeze([...rule.roles]) }),\n }) as WardRule<TAction, TResource, TAttributes>;\n}\n"],"mappings":"8CAGA,SAAS,cAAc,EAAgB,EAAc,EAA4C,CAC/F,GAAI,IAAU,MAAQ,OAAO,GAAU,WAAa,OAAO,GAAU,SAAU,OAAO,EAEtF,GAAI,OAAO,GAAU,SAAU,CAC7B,GAAI,CAAC,OAAO,SAAS,CAAK,EAAG,MAAM,IAAI,EAAgB,GAAG,EAAK,kCAAkC,EACjG,OAAO,CACT,CAEA,GAAI,OAAO,GAAU,SACnB,MAAM,IAAI,EAAgB,GAAG,EAAK,0CAA0C,EAG9E,GAAI,EAAU,IAAI,CAAK,EAAG,MAAM,IAAI,EAAgB,GAAG,EAAK,sCAAsC,EAElG,IAAM,EAAY,OAAO,eAAe,CAAK,EAC7C,GAAI,CAAC,MAAM,QAAQ,CAAK,GAAK,IAAc,OAAO,WAAa,IAAc,KAC3E,MAAM,IAAI,EAAgB,GAAG,EAAK,4CAA4C,EAGhF,EAAU,IAAI,CAAK,EAEnB,GAAI,CAKF,OAHS,OAAO,OADZ,MAAM,QAAQ,CAAK,EACA,MAAM,KAAK,GAAQ,EAAM,IAAU,cAAc,EAAM,GAAG,EAAK,GAAG,EAAM,GAAI,CAAS,CAAC,EAI3G,OAAO,YACL,OAAO,KAAK,CAAK,CAAC,CAAC,IAAK,GAAQ,C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WAC5D,MAAM,IAAI,EAAgB,GAAG,EAAG,8BAA8B,EAGhE,GAAI,EAAK,QAAU,IAAA,KACb,CAAC,MAAM,QAAQ,EAAK,KAAK,GAAK,EAAK,MAAM,KAAM,GAAS,OAAO,GAAS,UAAY,CAAC,EAAK,KAAK,CAAC,GAClG,MAAM,IAAI,EAAgB,GAAG,EAAG,6CAA6C,EAIjF,OAAO,OAAO,OAAO,CACnB,OAAQ,EAAK,OACb,GAAI,EAAK,aAAe,IAAA,GAAY,CAAC,EAAI,CAAE,WAAY,mBAAmB,EAAK,WAAY,GAAG,EAAG,YAAY,CAAE,EAC/G,GAAI,EAAK,YAAc,IAAA,GAAY,CAAC,EAAI,CAAE,UAAW,EAAK,SAAU,EACpE,OAAQ,EAAK,OACb,SAAU,EAAK,SACf,GAAI,EAAK,QAAU,IAAA,GAAY,CAAC,EAAI,CAAE,MAAO,OAAO,OAAO,CAAC,GAAG,EAAK,KAAK,CAAC,CAAE,CAC9E,CAAC,CACH"}
1
+ {"version":3,"file":"_compile.js","names":["value","WardConfigError","path","ancestors","prototype","item","index","key","at","rule","role"],"sources":["../src/_compile.ts"],"sourcesContent":["import { WardConfigError } from './errors';\nimport type { WardAttributes, WardAttributeValue, WardRule } from './types';\n\nfunction snapshotValue(value: unknown, path: string, ancestors: Set<object>): WardAttributeValue {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') return value;\n\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new WardConfigError(`${path} must contain only finite numbers`);\n return value;\n }\n\n if (typeof value !== 'object') {\n throw new WardConfigError(`${path} must contain only JSON-compatible values`);\n }\n\n if (ancestors.has(value)) throw new WardConfigError(`${path} must not contain circular references`);\n\n const prototype = Object.getPrototypeOf(value);\n if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) {\n throw new WardConfigError(`${path} must contain only arrays and plain objects`);\n }\n\n ancestors.add(value);\n\n try {\n if (Array.isArray(value)) {\n return Object.freeze(Array.from(value, (item, index) => snapshotValue(item, `${path}[${index}]`, ancestors)));\n }\n\n return Object.freeze(\n Object.fromEntries(\n Object.keys(value).map((key) => [\n key,\n snapshotValue((value as Record<string, unknown>)[key], `${path}.${key}`, ancestors),\n ]),\n ),\n );\n } finally {\n ancestors.delete(value);\n }\n}\n\nexport function snapshotAttributes(value: unknown, path: string): WardAttributes | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new WardConfigError(`${path} must be a plain object`);\n }\n\n return snapshotValue(value, path, new Set()) as WardAttributes;\n}\n\n/**\n * Validates and snapshots a single rule definition at ward-creation time.\n * Throws {@link WardConfigError} with a `Rule[index]`-prefixed message on failure.\n */\nexport function compileRule<TAction extends string, TResource extends string, TAttributes extends WardAttributes>(\n rule: WardRule<TAction, TResource, TAttributes>,\n index: number,\n): WardRule<TAction, TResource, TAttributes> {\n const at = `Rule[${index}]`;\n\n if (typeof rule !== 'object' || rule === null || Array.isArray(rule)) {\n throw new WardConfigError(`${at} must be a plain object`);\n }\n const prototype = Object.getPrototypeOf(rule);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new WardConfigError(`${at} must be a plain object`);\n }\n\n if (typeof rule.action !== 'string' || !rule.action.trim()) {\n throw new WardConfigError(`${at}.action must be a non-empty string`);\n }\n\n if (rule.action.endsWith(':')) {\n throw new WardConfigError(`${at}.action '${rule.action}' ends with ':': did you mean '${rule.action}*'?`);\n }\n\n if (typeof rule.resource !== 'string' || !rule.resource.trim()) {\n throw new WardConfigError(`${at}.resource must be a non-empty string`);\n }\n\n if (rule.resource.endsWith(':')) {\n throw new WardConfigError(`${at}.resource '${rule.resource}' ends with ':': did you mean '${rule.resource}*'?`);\n }\n\n if (rule.effect !== 'allow' && rule.effect !== 'deny') {\n throw new WardConfigError(`${at}.effect must be \"allow\" or \"deny\"`);\n }\n\n if (rule.condition !== undefined && typeof rule.condition !== 'function') {\n throw new WardConfigError(`${at}.condition must be a function`);\n }\n\n if (rule.roles !== undefined) {\n if (!Array.isArray(rule.roles) || rule.roles.some((role) => typeof role !== 'string' || !role.trim())) {\n throw new WardConfigError(`${at}.roles must be an array of non-empty strings`);\n }\n }\n\n return Object.freeze({\n action: rule.action,\n ...(rule.attributes === undefined ? {} : { attributes: snapshotAttributes(rule.attributes, `${at}.attributes`) }),\n ...(rule.condition === undefined ? {} : { condition: rule.condition }),\n effect: rule.effect,\n resource: rule.resource,\n ...(rule.roles === undefined ? {} : { roles: Object.freeze([...rule.roles]) }),\n }) as WardRule<TAction, TResource, TAttributes>;\n}\n"],"mappings":";;AAGA,SAAS,cAAc,GAAgB,GAAc,GAA4C;CAC/F,IAAIA,MAAU,QAAQ,OAAOA,KAAU,aAAa,OAAOA,KAAU,UAAU,OAAOA;CAEtF,IAAI,OAAOA,KAAU,UAAU;EAC7B,IAAI,CAAC,OAAO,SAASA,CAAK,GAAG,MAAM,IAAIC,EAAgB,GAAGC,EAAK,kCAAkC;EACjG,OAAOF;CACT;CAEA,IAAI,OAAOA,KAAU,UACnB,MAAM,IAAIC,EAAgB,GAAGC,EAAK,0CAA0C;CAG9E,IAAIC,EAAU,IAAIH,CAAK,GAAG,MAAM,IAAIC,EAAgB,GAAGC,EAAK,sCAAsC;CAElG,IAAME,IAAY,OAAO,eAAeJ,CAAK;CAC7C,IAAI,CAAC,MAAM,QAAQA,CAAK,KAAKI,MAAc,OAAO,aAAaA,MAAc,MAC3E,MAAM,IAAIH,EAAgB,GAAGC,EAAK,4CAA4C;CAGhF,EAAU,IAAIF,CAAK;CAEnB,IAAI;EAKF,OAHS,OAAO,OADZ,MAAM,QAAQA,CAAK,IACA,MAAM,KAAKA,IAAQ,GAAM,MAAU,cAAcK,GAAM,GAAGH,EAAK,GAAGI,EAAM,IAAIH,CAAS,CAAC,IAI3G,OAAO,YACL,OAAO,KAAKH,CAAK,CAAC,CAAC,KAAK,MAAQ,CAC9BO,GACA,cAAeP,EAAkCO,IAAM,GAAGL,EAAK,GAAGK,KAAOJ,CAAS,CACpF,CAAC,CAC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AM,IAAIR,EAAgB,GAAGO,EAAG,8BAA8B;CAGhE,IAAIC,EAAK,UAAU,KAAA,MACb,CAAC,MAAM,QAAQA,EAAK,KAAK,KAAKA,EAAK,MAAM,MAAM,MAAS,OAAOC,KAAS,YAAY,CAACA,EAAK,KAAK,CAAC,IAClG,MAAM,IAAIT,EAAgB,GAAGO,EAAG,6CAA6C;CAIjF,OAAO,OAAO,OAAO;EACnB,QAAQC,EAAK;EACb,GAAIA,EAAK,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY,mBAAmBA,EAAK,YAAY,GAAGD,EAAG,YAAY,EAAE;EAC/G,GAAIC,EAAK,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,WAAWA,EAAK,UAAU;EACpE,QAAQA,EAAK;EACb,UAAUA,EAAK;EACf,GAAIA,EAAK,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,OAAO,OAAO,CAAC,GAAGA,EAAK,KAAK,CAAC,EAAE;CAC9E,CAAC;AACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"_match.cjs","names":[],"sources":["../src/_match.ts"],"sourcesContent":["import { snapshotAttributes } from './_compile';\nimport { ANONYMOUS, WILDCARD } from './constants';\nimport { WardConditionError, WardConfigError } from './errors';\nimport { matchesPattern } from './resource';\nimport type {\n Principal,\n UserPrincipal,\n WardAttributes,\n WardAttributeValue,\n WardDecisionInput,\n WardRule,\n} from './types';\n\n/** Asserts that `input` is a valid `UserPrincipal`. Throws with a clear message otherwise. */\nexport function assertUserPrincipal(input: unknown): asserts input is UserPrincipal {\n if (typeof input !== 'object' || !input) {\n throw new WardConfigError('Invalid principal: expected { id: string, roles: string[] }');\n }\n\n const principal = input as Record<string, unknown>;\n\n if (typeof principal.id !== 'string' || !principal.id.trim()) {\n throw new WardConfigError('Invalid principal: id must be a non-empty string');\n }\n\n if (!Array.isArray(principal.roles) || principal.roles.some((role) => typeof role !== 'string' || !role.trim())) {\n throw new WardConfigError('Invalid principal: roles must be an array of non-empty strings');\n }\n}\n\nexport function snapshotPrincipal(principal: Principal | undefined): Principal {\n if (principal === undefined || principal === null) return null;\n\n assertUserPrincipal(principal);\n\n return Object.freeze({\n ...(principal.attributes === undefined\n ? {}\n : { attributes: snapshotAttributes(principal.attributes, 'Principal.attributes') }),\n id: principal.id,\n roles: Object.freeze([...principal.roles]),\n });\n}\n\nexport function snapshotDecisionInput<\n TAction extends string,\n TResource extends string,\n TAttributes extends WardAttributes,\n>(\n input: WardDecisionInput<TAction, TResource, TAttributes>,\n): WardDecisionInput<TAction, TResource, TAttributes> & {\n principal: Principal;\n} {\n if (typeof input.action !== 'string' || !input.action.trim()) {\n throw new WardConfigError('Decision.action must be a non-empty string');\n }\n if (typeof input.resource !== 'string' || !input.resource.trim()) {\n throw new WardConfigError('Decision.resource must be a non-empty string');\n }\n\n return Object.freeze({\n action: input.action,\n ...(input.attributes === undefined\n ? {}\n : { attributes: snapshotAttributes(input.attributes, 'Decision.attributes') as TAttributes }),\n principal: snapshotPrincipal(input.principal),\n resource: input.resource,\n });\n}\n\nfunction deepEqual(left: WardAttributeValue, right: WardAttributeValue): boolean {\n if (Object.is(left, right)) return true;\n if (typeof left !== 'object' || typeof right !== 'object' || left === null || right === null) return false;\n if (Array.isArray(left) || Array.isArray(right)) {\n return (\n Array.isArray(left) &&\n Array.isArray(right) &&\n left.length === right.length &&\n left.every((value, index) => deepEqual(value, right[index]))\n );\n }\n\n const leftRecord = left as Record<string, WardAttributeValue>;\n const rightRecord = right as Record<string, WardAttributeValue>;\n const leftKeys = Object.keys(leftRecord);\n const rightKeys = Object.keys(rightRecord);\n\n return (\n leftKeys.length === rightKeys.length &&\n leftKeys.every((key) => Object.hasOwn(rightRecord, key) && deepEqual(leftRecord[key], rightRecord[key]))\n );\n}\n\nexport function attributesMatch(expected: WardAttributes | undefined, actual: WardAttributes | undefined): boolean {\n if (!expected) return true;\n if (!actual) return false;\n\n return Object.keys(expected).every((key) => Object.hasOwn(actual, key) && deepEqual(expected[key], actual[key]));\n}\n\n/**\n * Declarative role check: `ANONYMOUS` matches a null principal, `WILDCARD`\n * matches any authenticated principal, an exact role must be in the principal's\n * roles. A rule without `roles` matches every principal.\n */\nfunction rolesMatch(expected: readonly string[] | undefined, principal: Principal): boolean {\n if (!expected) return true;\n\n return expected.some((candidate) =>\n candidate === ANONYMOUS\n ? principal === null\n : candidate === WILDCARD\n ? principal !== null\n : (principal?.roles.includes(candidate) ?? false),\n );\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === 'object' && value !== null && 'then' in value && typeof value.then === 'function') ||\n (typeof value === 'function' && 'then' in value && typeof value.then === 'function')\n );\n}\n\nexport function ruleMatches<TAction extends string, TResource extends string, TAttributes extends WardAttributes>(\n rule: WardRule<TAction, TResource, TAttributes>,\n index: number,\n input: WardDecisionInput<TAction, TResource, TAttributes> & { principal: Principal },\n): boolean {\n if (!matchesPattern(rule.action, input.action)) return false;\n if (!matchesPattern(rule.resource, input.resource)) return false;\n if (!rolesMatch(rule.roles, input.principal)) return false;\n if (!attributesMatch(rule.attributes, input.attributes)) return false;\n if (!rule.condition) return true;\n\n try {\n const result: unknown = rule.condition({ attributes: input.attributes, principal: input.principal });\n\n if (isThenable(result)) {\n throw new TypeError('Async conditions are not supported; return a boolean');\n }\n if (typeof result !== 'boolean') {\n throw new TypeError('Conditions must return a boolean');\n }\n\n return result;\n } catch (error) {\n throw new WardConditionError(index, error);\n }\n}\n"],"mappings":"mHAcA,SAAgB,oBAAoB,EAAgD,CAClF,GAAI,OAAO,GAAU,UAAY,CAAC,EAChC,MAAM,IAAI,EAAA,gBAAgB,6DAA6D,EAGzF,IAAM,EAAY,EAElB,GAAI,OAAO,EAAU,IAAO,UAAY,CAAC,EAAU,GAAG,KAAK,EACzD,MAAM,IAAI,EAAA,gBAAgB,kDAAkD,EAG9E,GAAI,CAAC,MAAM,QAAQ,EAAU,KAAK,GAAK,EAAU,MAAM,KAAM,GAAS,OAAO,GAAS,UAAY,C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":["WardConfigError","snapshotAttributes","matchesPattern","WardConditionError","require_errors","require__compile","require_resource","input","principal","role","left","right","value","index","leftRecord","rightRecord","leftKeys","rightKeys","key","expected","actual","candidate","rule","result","error"],"sources":["../src/_match.ts"],"sourcesContent":["import { snapshotAttributes } from './_compile';\nimport { ANONYMOUS, WILDCARD } from './constants';\nimport { WardConditionError, WardConfigError } from './errors';\nimport { matchesPattern } from './resource';\nimport type {\n Principal,\n UserPrincipal,\n WardAttributes,\n WardAttributeValue,\n WardDecisionInput,\n WardRule,\n} from './types';\n\n/** Asserts that `input` is a valid `UserPrincipal`. Throws with a clear message otherwise. */\nexport function assertUserPrincipal(input: unknown): asserts input is UserPrincipal {\n if (typeof input !== 'object' || !input) {\n throw new WardConfigError('Invalid principal: expected { id: string, roles: string[] }');\n }\n\n const principal = input as Record<string, unknown>;\n\n if (typeof principal.id !== 'string' || !principal.id.trim()) {\n throw new WardConfigError('Invalid principal: id must be a non-empty string');\n }\n\n if (!Array.isArray(principal.roles) || principal.roles.some((role) => typeof role !== 'string' || !role.trim())) {\n throw new WardConfigError('Invalid principal: roles must be an array of non-empty strings');\n }\n}\n\nexport function snapshotPrincipal(principal: Principal | undefined): Principal {\n if (principal === undefined || principal === null) return null;\n\n assertUserPrincipal(principal);\n\n return Object.freeze({\n ...(principal.attributes === undefined\n ? {}\n : { attributes: snapshotAttributes(principal.attributes, 'Principal.attributes') }),\n id: principal.id,\n roles: Object.freeze([...principal.roles]),\n });\n}\n\nexport function snapshotDecisionInput<\n TAction extends string,\n TResource extends string,\n TAttributes extends WardAttributes,\n>(\n input: WardDecisionInput<TAction, TResource, TAttributes>,\n): WardDecisionInput<TAction, TResource, TAttributes> & {\n principal: Principal;\n} {\n if (typeof input.action !== 'string' || !input.action.trim()) {\n throw new WardConfigError('Decision.action must be a non-empty string');\n }\n if (typeof input.resource !== 'string' || !input.resource.trim()) {\n throw new WardConfigError('Decision.resource must be a non-empty string');\n }\n\n return Object.freeze({\n action: input.action,\n ...(input.attributes === undefined\n ? {}\n : { attributes: snapshotAttributes(input.attributes, 'Decision.attributes') as TAttributes }),\n principal: snapshotPrincipal(input.principal),\n resource: input.resource,\n });\n}\n\nfunction deepEqual(left: WardAttributeValue, right: WardAttributeValue): boolean {\n if (Object.is(left, right)) return true;\n if (typeof left !== 'object' || typeof right !== 'object' || left === null || right === null) return false;\n if (Array.isArray(left) || Array.isArray(right)) {\n return (\n Array.isArray(left) &&\n Array.isArray(right) &&\n left.length === right.length &&\n left.every((value, index) => deepEqual(value, right[index]))\n );\n }\n\n const leftRecord = left as Record<string, WardAttributeValue>;\n const rightRecord = right as Record<string, WardAttributeValue>;\n const leftKeys = Object.keys(leftRecord);\n const rightKeys = Object.keys(rightRecord);\n\n return (\n leftKeys.length === rightKeys.length &&\n leftKeys.every((key) => Object.hasOwn(rightRecord, key) && deepEqual(leftRecord[key], rightRecord[key]))\n );\n}\n\nexport function attributesMatch(expected: WardAttributes | undefined, actual: WardAttributes | undefined): boolean {\n if (!expected) return true;\n if (!actual) return false;\n\n return Object.keys(expected).every((key) => Object.hasOwn(actual, key) && deepEqual(expected[key], actual[key]));\n}\n\n/**\n * Declarative role check: `ANONYMOUS` matches a null principal, `WILDCARD`\n * matches any authenticated principal, an exact role must be in the principal's\n * roles. A rule without `roles` matches every principal.\n */\nfunction rolesMatch(expected: readonly string[] | undefined, principal: Principal): boolean {\n if (!expected) return true;\n\n return expected.some((candidate) =>\n candidate === ANONYMOUS\n ? principal === null\n : candidate === WILDCARD\n ? principal !== null\n : (principal?.roles.includes(candidate) ?? false),\n );\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === 'object' && value !== null && 'then' in value && typeof value.then === 'function') ||\n (typeof value === 'function' && 'then' in value && typeof value.then === 'function')\n );\n}\n\nexport function ruleMatches<TAction extends string, TResource extends string, TAttributes extends WardAttributes>(\n rule: WardRule<TAction, TResource, TAttributes>,\n index: number,\n input: WardDecisionInput<TAction, TResource, TAttributes> & { principal: Principal },\n): boolean {\n if (!matchesPattern(rule.action, input.action)) return false;\n if (!matchesPattern(rule.resource, input.resource)) return false;\n if (!rolesMatch(rule.roles, input.principal)) return false;\n if (!attributesMatch(rule.attributes, input.attributes)) return false;\n if (!rule.condition) return true;\n\n try {\n const result: unknown = rule.condition({ attributes: input.attributes, principal: input.principal });\n\n if (isThenable(result)) {\n throw new TypeError('Async conditions are not supported; return a boolean');\n }\n if (typeof result !== 'boolean') {\n throw new TypeError('Conditions must return a boolean');\n }\n\n return result;\n } catch (error) {\n throw new WardConditionError(index, error);\n }\n}\n"],"mappings":"A,mHAcA,SAAgB,oBAAoB,EAAgD,CAClF,GAAI,OAAOO,GAAU,UAAY,CAACA,EAChC,MAAM,IAAIP,EAAAA,gBAAgB,6DAA6D,EAGzF,IAAMQ,EAAYD,EAElB,GAAI,OAAOC,EAAU,IAAO,UAAY,CAACA,EAAU,GAAG,KAAK,EACzD,MAAM,IAAIR,EAAAA,gBAAgB,kDAAkD,EAG9E,GAAI,CAAC,MAAM,QAAQQ,EAAU,KAAK,GAAKA,EAAU,MAAM,KAAM,GAAS,OAAOC,GAAS,UAAY,CAACA,EAAK,KAAK,CAAC,EAC5G,MAAM,IAAIT,EAAAA,gBAAgB,gEAAgE,CAE9F,CAEA,SAAgB,kBAAkB,EAA6C,CAK7E,OAJIQ,GAAyC,KAAa,MAE1D,oBAAoBA,CAAS,EAEtB,OAAO,OAAO,CACnB,GAAIA,EAAU,aAAe,IAAA,GACzB,CAAC,EACD,CAAE,WAAYP,EAAAA,mBAAmBO,EAAU,WAAY,sBAAsB,CAAE,EACnF,GAAIA,EAAU,GACd,MAAO,OAAO,OAAO,CAAC,GAAGA,EAAU,KAAK,CAAC,CAC3C,CAAC,EACH,CAEA,SAAgB,sBAKd,EAGA,CACA,GAAI,OAAOD,EAAM,QAAW,UAAY,CAACA,EAAM,OAAO,KAAK,EACzD,MAAM,IAAIP,EAAAA,gBAAgB,4CAA4C,EAExE,GAAI,OAAOO,EAAM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Ac,KACbA,GAAW,MAAM,SAASa,CAAS,GAAK,EACjD,CACF,CAEA,SAAS,WAAW,EAA+C,CACjE,OACG,OAAOT,GAAU,YAAYA,GAAkB,SAAUA,GAAS,OAAOA,EAAM,MAAS,YACxF,OAAOA,GAAU,YAAc,SAAUA,GAAS,OAAOA,EAAM,MAAS,UAE7E,CAEA,SAAgB,YACd,EACA,EACA,EACS,CAIT,GAHI,CAACV,EAAAA,eAAeoB,EAAK,OAAQf,EAAM,MAAM,GACzC,CAACL,EAAAA,eAAeoB,EAAK,SAAUf,EAAM,QAAQ,GAC7C,CAAC,WAAWe,EAAK,MAAOf,EAAM,SAAS,GACvC,CAAC,gBAAgBe,EAAK,WAAYf,EAAM,UAAU,EAAG,MAAO,GAChE,GAAI,CAACe,EAAK,UAAW,MAAO,GAE5B,GAAI,CACF,IAAMC,EAAkBD,EAAK,UAAU,CAAE,WAAYf,EAAM,WAAY,UAAWA,EAAM,SAAU,CAAC,EAEnG,GAAI,WAAWgB,CAAM,EACnB,MAAU,UAAU,sDAAsD,EAE5E,GAAI,OAAOA,GAAW,UACpB,MAAU,UAAU,kCAAkC,EAGxD,OAAOA,CACT,OAASC,EAAO,CACd,MAAM,IAAIrB,EAAAA,mBAAmBU,EAAOW,CAAK,CAC3C,CACF,C"}
package/dist/_match.js CHANGED
@@ -1,2 +1,63 @@
1
- import"./constants.js";import{WardConditionError as e,WardConfigError as t}from"./errors.js";import{snapshotAttributes as n}from"./_compile.js";import{matchesPattern as r}from"./resource.js";function assertUserPrincipal(e){if(typeof e!=`object`||!e)throw new t(`Invalid principal: expected { id: string, roles: string[] }`);let n=e;if(typeof n.id!=`string`||!n.id.trim())throw new t(`Invalid principal: id must be a non-empty string`);if(!Array.isArray(n.roles)||n.roles.some(e=>typeof e!=`string`||!e.trim()))throw new t(`Invalid principal: roles must be an array of non-empty strings`)}function snapshotPrincipal(e){return e==null?null:(assertUserPrincipal(e),Object.freeze({...e.attributes===void 0?{}:{attributes:n(e.attributes,`Principal.attributes`)},id:e.id,roles:Object.freeze([...e.roles])}))}function snapshotDecisionInput(e){if(typeof e.action!=`string`||!e.action.trim())throw new t(`Decision.action must be a non-empty string`);if(typeof e.resource!=`string`||!e.resource.trim())throw new t(`Decision.resource must be a non-empty string`);return Object.freeze({action:e.action,...e.attributes===void 0?{}:{attributes:n(e.attributes,`Decision.attributes`)},principal:snapshotPrincipal(e.principal),resource:e.resource})}function deepEqual(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null)return!1;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>deepEqual(e,t[n]));let n=e,r=t,i=Object.keys(n),a=Object.keys(r);return i.length===a.length&&i.every(e=>Object.hasOwn(r,e)&&deepEqual(n[e],r[e]))}function attributesMatch(e,t){return e?t?Object.keys(e).every(n=>Object.hasOwn(t,n)&&deepEqual(e[n],t[n])):!1:!0}function rolesMatch(e,t){return!e||e.some(e=>e===`anonymous`?t===null:e===`*`?t!==null:t?.roles.includes(e)??!1)}function isThenable(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`||typeof e==`function`&&`then`in e&&typeof e.then==`function`}function ruleMatches(t,n,i){if(!r(t.action,i.action)||!r(t.resource,i.resource)||!rolesMatch(t.roles,i.principal)||!attributesMatch(t.attributes,i.attributes))return!1;if(!t.condition)return!0;try{let e=t.condition({attributes:i.attributes,principal:i.principal});if(isThenable(e))throw TypeError(`Async conditions are not supported; return a boolean`);if(typeof e!=`boolean`)throw TypeError(`Conditions must return a boolean`);return e}catch(t){throw new e(n,t)}}export{assertUserPrincipal,attributesMatch,ruleMatches,snapshotDecisionInput,snapshotPrincipal};
1
+ import "./constants.js";
2
+ import { WardConditionError as e, WardConfigError as t } from "./errors.js";
3
+ import { snapshotAttributes as n } from "./_compile.js";
4
+ import { matchesPattern as r } from "./resource.js";
5
+ //#region src/_match.ts
6
+ function assertUserPrincipal(e) {
7
+ if (typeof e != "object" || !e) throw new t("Invalid principal: expected { id: string, roles: string[] }");
8
+ let n = e;
9
+ if (typeof n.id != "string" || !n.id.trim()) throw new t("Invalid principal: id must be a non-empty string");
10
+ if (!Array.isArray(n.roles) || n.roles.some((e) => typeof e != "string" || !e.trim())) throw new t("Invalid principal: roles must be an array of non-empty strings");
11
+ }
12
+ function snapshotPrincipal(e) {
13
+ return e == null ? null : (assertUserPrincipal(e), Object.freeze({
14
+ ...e.attributes === void 0 ? {} : { attributes: n(e.attributes, "Principal.attributes") },
15
+ id: e.id,
16
+ roles: Object.freeze([...e.roles])
17
+ }));
18
+ }
19
+ function snapshotDecisionInput(e) {
20
+ if (typeof e.action != "string" || !e.action.trim()) throw new t("Decision.action must be a non-empty string");
21
+ if (typeof e.resource != "string" || !e.resource.trim()) throw new t("Decision.resource must be a non-empty string");
22
+ return Object.freeze({
23
+ action: e.action,
24
+ ...e.attributes === void 0 ? {} : { attributes: n(e.attributes, "Decision.attributes") },
25
+ principal: snapshotPrincipal(e.principal),
26
+ resource: e.resource
27
+ });
28
+ }
29
+ function deepEqual(e, t) {
30
+ if (Object.is(e, t)) return !0;
31
+ if (typeof e != "object" || typeof t != "object" || e === null || t === null) return !1;
32
+ if (Array.isArray(e) || Array.isArray(t)) return Array.isArray(e) && Array.isArray(t) && e.length === t.length && e.every((e, n) => deepEqual(e, t[n]));
33
+ let n = e, r = t, i = Object.keys(n), a = Object.keys(r);
34
+ return i.length === a.length && i.every((e) => Object.hasOwn(r, e) && deepEqual(n[e], r[e]));
35
+ }
36
+ function attributesMatch(e, t) {
37
+ return e ? t ? Object.keys(e).every((n) => Object.hasOwn(t, n) && deepEqual(e[n], t[n])) : !1 : !0;
38
+ }
39
+ function rolesMatch(e, t) {
40
+ return !e || e.some((e) => e === "anonymous" ? t === null : e === "*" ? t !== null : t?.roles.includes(e) ?? !1);
41
+ }
42
+ function isThenable(e) {
43
+ return typeof e == "object" && !!e && "then" in e && typeof e.then == "function" || typeof e == "function" && "then" in e && typeof e.then == "function";
44
+ }
45
+ function ruleMatches(t, n, i) {
46
+ if (!r(t.action, i.action) || !r(t.resource, i.resource) || !rolesMatch(t.roles, i.principal) || !attributesMatch(t.attributes, i.attributes)) return !1;
47
+ if (!t.condition) return !0;
48
+ try {
49
+ let e = t.condition({
50
+ attributes: i.attributes,
51
+ principal: i.principal
52
+ });
53
+ if (isThenable(e)) throw TypeError("Async conditions are not supported; return a boolean");
54
+ if (typeof e != "boolean") throw TypeError("Conditions must return a boolean");
55
+ return e;
56
+ } catch (t) {
57
+ throw new e(n, t);
58
+ }
59
+ }
60
+ //#endregion
61
+ export { assertUserPrincipal, attributesMatch, ruleMatches, snapshotDecisionInput, snapshotPrincipal };
62
+
2
63
  //# sourceMappingURL=_match.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"_match.js","names":[],"sources":["../src/_match.ts"],"sourcesContent":["import { snapshotAttributes } from './_compile';\nimport { ANONYMOUS, WILDCARD } from './constants';\nimport { WardConditionError, WardConfigError } from './errors';\nimport { matchesPattern } from './resource';\nimport type {\n Principal,\n UserPrincipal,\n WardAttributes,\n WardAttributeValue,\n WardDecisionInput,\n WardRule,\n} from './types';\n\n/** Asserts that `input` is a valid `UserPrincipal`. Throws with a clear message otherwise. */\nexport function assertUserPrincipal(input: unknown): asserts input is UserPrincipal {\n if (typeof input !== 'object' || !input) {\n throw new WardConfigError('Invalid principal: expected { id: string, roles: string[] }');\n }\n\n const principal = input as Record<string, unknown>;\n\n if (typeof principal.id !== 'string' || !principal.id.trim()) {\n throw new WardConfigError('Invalid principal: id must be a non-empty string');\n }\n\n if (!Array.isArray(principal.roles) || principal.roles.some((role) => typeof role !== 'string' || !role.trim())) {\n throw new WardConfigError('Invalid principal: roles must be an array of non-empty strings');\n }\n}\n\nexport function snapshotPrincipal(principal: Principal | undefined): Principal {\n if (principal === undefined || principal === null) return null;\n\n assertUserPrincipal(principal);\n\n return Object.freeze({\n ...(principal.attributes === undefined\n ? {}\n : { attributes: snapshotAttributes(principal.attributes, 'Principal.attributes') }),\n id: principal.id,\n roles: Object.freeze([...principal.roles]),\n });\n}\n\nexport function snapshotDecisionInput<\n TAction extends string,\n TResource extends string,\n TAttributes extends WardAttributes,\n>(\n input: WardDecisionInput<TAction, TResource, TAttributes>,\n): WardDecisionInput<TAction, TResource, TAttributes> & {\n principal: Principal;\n} {\n if (typeof input.action !== 'string' || !input.action.trim()) {\n throw new WardConfigError('Decision.action must be a non-empty string');\n }\n if (typeof input.resource !== 'string' || !input.resource.trim()) {\n throw new WardConfigError('Decision.resource must be a non-empty string');\n }\n\n return Object.freeze({\n action: input.action,\n ...(input.attributes === undefined\n ? {}\n : { attributes: snapshotAttributes(input.attributes, 'Decision.attributes') as TAttributes }),\n principal: snapshotPrincipal(input.principal),\n resource: input.resource,\n });\n}\n\nfunction deepEqual(left: WardAttributeValue, right: WardAttributeValue): boolean {\n if (Object.is(left, right)) return true;\n if (typeof left !== 'object' || typeof right !== 'object' || left === null || right === null) return false;\n if (Array.isArray(left) || Array.isArray(right)) {\n return (\n Array.isArray(left) &&\n Array.isArray(right) &&\n left.length === right.length &&\n left.every((value, index) => deepEqual(value, right[index]))\n );\n }\n\n const leftRecord = left as Record<string, WardAttributeValue>;\n const rightRecord = right as Record<string, WardAttributeValue>;\n const leftKeys = Object.keys(leftRecord);\n const rightKeys = Object.keys(rightRecord);\n\n return (\n leftKeys.length === rightKeys.length &&\n leftKeys.every((key) => Object.hasOwn(rightRecord, key) && deepEqual(leftRecord[key], rightRecord[key]))\n );\n}\n\nexport function attributesMatch(expected: WardAttributes | undefined, actual: WardAttributes | undefined): boolean {\n if (!expected) return true;\n if (!actual) return false;\n\n return Object.keys(expected).every((key) => Object.hasOwn(actual, key) && deepEqual(expected[key], actual[key]));\n}\n\n/**\n * Declarative role check: `ANONYMOUS` matches a null principal, `WILDCARD`\n * matches any authenticated principal, an exact role must be in the principal's\n * roles. A rule without `roles` matches every principal.\n */\nfunction rolesMatch(expected: readonly string[] | undefined, principal: Principal): boolean {\n if (!expected) return true;\n\n return expected.some((candidate) =>\n candidate === ANONYMOUS\n ? principal === null\n : candidate === WILDCARD\n ? principal !== null\n : (principal?.roles.includes(candidate) ?? false),\n );\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === 'object' && value !== null && 'then' in value && typeof value.then === 'function') ||\n (typeof value === 'function' && 'then' in value && typeof value.then === 'function')\n );\n}\n\nexport function ruleMatches<TAction extends string, TResource extends string, TAttributes extends WardAttributes>(\n rule: WardRule<TAction, TResource, TAttributes>,\n index: number,\n input: WardDecisionInput<TAction, TResource, TAttributes> & { principal: Principal },\n): boolean {\n if (!matchesPattern(rule.action, input.action)) return false;\n if (!matchesPattern(rule.resource, input.resource)) return false;\n if (!rolesMatch(rule.roles, input.principal)) return false;\n if (!attributesMatch(rule.attributes, input.attributes)) return false;\n if (!rule.condition) return true;\n\n try {\n const result: unknown = rule.condition({ attributes: input.attributes, principal: input.principal });\n\n if (isThenable(result)) {\n throw new TypeError('Async conditions are not supported; return a boolean');\n }\n if (typeof result !== 'boolean') {\n throw new TypeError('Conditions must return a boolean');\n }\n\n return result;\n } catch (error) {\n throw new WardConditionError(index, error);\n }\n}\n"],"mappings":"+LAcA,SAAgB,oBAAoB,EAAgD,CAClF,GAAI,OAAO,GAAU,UAAY,CAAC,EAChC,MAAM,IAAI,EAAgB,6DAA6D,EAGzF,IAAM,EAAY,EAElB,GAAI,OAAO,EAAU,IAAO,UAAY,CAAC,EAAU,GAAG,KAAK,EACzD,MAAM,IAAI,EAAgB,kDAAkD,EAG9E,GAAI,CAAC,MAAM,QAAQ,EAAU,KAAK,GAAK,EAAU,MAAM,KAAM,GAAS,OAAO,GAAS,UAAY,CAAC,EAAK,KAAK,CAAC,EAC5G,MAAM,IAAI,EAAgB,gEAAgE,CAE9F,CAEA,SAAgB,kBAAkB,EAA6C,CAK7E,OAJI,GAAyC,KAAa,MAE1D,oBAAoB,CAAS,EAEtB,OAAO,OAAO,CACnB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EE,OAAO,KAAK,CAAQ,CAAC,CAAC,MAAO,GAAQ,OAAO,OAAO,EAAQ,CAAG,GAAK,UAAU,EAAS,GAAM,EAAO,EAAI,CAAC,EAF3F,GADE,EAIxB,CAOA,SAAS,WAAW,EAAyC,EAA+B,CAG1F,MAFA,CAAK,GAEE,EAAS,KAAM,GACpB,IAAA,YACI,IAAc,KACd,IAAA,IACE,IAAc,KACb,GAAW,MAAM,SAAS,CAAS,GAAK,EACjD,CACF,CAEA,SAAS,WAAW,EAA+C,CACjE,OACG,OAAO,GAAU,YAAY,GAAkB,SAAU,GAAS,OAAO,EAAM,MAAS,YACxF,OAAO,GAAU,YAAc,SAAU,GAAS,OAAO,EAAM,MAAS,UAE7E,CAEA,SAAgB,YACd,EACA,EACA,EACS,CAIT,GAHI,CAAC,EAAe,EAAK,OAAQ,EAAM,MAAM,GACzC,CAAC,EAAe,EAAK,SAAU,EAAM,QAAQ,GAC7C,CAAC,WAAW,EAAK,MAAO,EAAM,SAAS,GACvC,CAAC,gBAAgB,EAAK,WAAY,EAAM,UAAU,EAAG,MAAO,GAChE,GAAI,CAAC,EAAK,UAAW,MAAO,GAE5B,GAAI,CACF,IAAM,EAAkB,EAAK,UAAU,CAAE,WAAY,EAAM,WAAY,UAAW,EAAM,SAAU,CAAC,EAEnG,GAAI,WAAW,CAAM,EACnB,MAAU,UAAU,sDAAsD,EAE5E,GAAI,OAAO,GAAW,UACpB,MAAU,UAAU,kCAAkC,EAGxD,OAAO,CACT,OAAS,EAAO,CACd,MAAM,IAAI,EAAmB,EAAO,CAAK,CAC3C,CACF"}
1
+ {"version":3,"file":"_match.js","names":["input","WardConfigError","principal","role","snapshotAttributes","left","right","value","index","leftRecord","rightRecord","leftKeys","rightKeys","key","expected","actual","candidate","matchesPattern","rule","result","error","WardConditionError"],"sources":["../src/_match.ts"],"sourcesContent":["import { snapshotAttributes } from './_compile';\nimport { ANONYMOUS, WILDCARD } from './constants';\nimport { WardConditionError, WardConfigError } from './errors';\nimport { matchesPattern } from './resource';\nimport type {\n Principal,\n UserPrincipal,\n WardAttributes,\n WardAttributeValue,\n WardDecisionInput,\n WardRule,\n} from './types';\n\n/** Asserts that `input` is a valid `UserPrincipal`. Throws with a clear message otherwise. */\nexport function assertUserPrincipal(input: unknown): asserts input is UserPrincipal {\n if (typeof input !== 'object' || !input) {\n throw new WardConfigError('Invalid principal: expected { id: string, roles: string[] }');\n }\n\n const principal = input as Record<string, unknown>;\n\n if (typeof principal.id !== 'string' || !principal.id.trim()) {\n throw new WardConfigError('Invalid principal: id must be a non-empty string');\n }\n\n if (!Array.isArray(principal.roles) || principal.roles.some((role) => typeof role !== 'string' || !role.trim())) {\n throw new WardConfigError('Invalid principal: roles must be an array of non-empty strings');\n }\n}\n\nexport function snapshotPrincipal(principal: Principal | undefined): Principal {\n if (principal === undefined || principal === null) return null;\n\n assertUserPrincipal(principal);\n\n return Object.freeze({\n ...(principal.attributes === undefined\n ? {}\n : { attributes: snapshotAttributes(principal.attributes, 'Principal.attributes') }),\n id: principal.id,\n roles: Object.freeze([...principal.roles]),\n });\n}\n\nexport function snapshotDecisionInput<\n TAction extends string,\n TResource extends string,\n TAttributes extends WardAttributes,\n>(\n input: WardDecisionInput<TAction, TResource, TAttributes>,\n): WardDecisionInput<TAction, TResource, TAttributes> & {\n principal: Principal;\n} {\n if (typeof input.action !== 'string' || !input.action.trim()) {\n throw new WardConfigError('Decision.action must be a non-empty string');\n }\n if (typeof input.resource !== 'string' || !input.resource.trim()) {\n throw new WardConfigError('Decision.resource must be a non-empty string');\n }\n\n return Object.freeze({\n action: input.action,\n ...(input.attributes === undefined\n ? {}\n : { attributes: snapshotAttributes(input.attributes, 'Decision.attributes') as TAttributes }),\n principal: snapshotPrincipal(input.principal),\n resource: input.resource,\n });\n}\n\nfunction deepEqual(left: WardAttributeValue, right: WardAttributeValue): boolean {\n if (Object.is(left, right)) return true;\n if (typeof left !== 'object' || typeof right !== 'object' || left === null || right === null) return false;\n if (Array.isArray(left) || Array.isArray(right)) {\n return (\n Array.isArray(left) &&\n Array.isArray(right) &&\n left.length === right.length &&\n left.every((value, index) => deepEqual(value, right[index]))\n );\n }\n\n const leftRecord = left as Record<string, WardAttributeValue>;\n const rightRecord = right as Record<string, WardAttributeValue>;\n const leftKeys = Object.keys(leftRecord);\n const rightKeys = Object.keys(rightRecord);\n\n return (\n leftKeys.length === rightKeys.length &&\n leftKeys.every((key) => Object.hasOwn(rightRecord, key) && deepEqual(leftRecord[key], rightRecord[key]))\n );\n}\n\nexport function attributesMatch(expected: WardAttributes | undefined, actual: WardAttributes | undefined): boolean {\n if (!expected) return true;\n if (!actual) return false;\n\n return Object.keys(expected).every((key) => Object.hasOwn(actual, key) && deepEqual(expected[key], actual[key]));\n}\n\n/**\n * Declarative role check: `ANONYMOUS` matches a null principal, `WILDCARD`\n * matches any authenticated principal, an exact role must be in the principal's\n * roles. A rule without `roles` matches every principal.\n */\nfunction rolesMatch(expected: readonly string[] | undefined, principal: Principal): boolean {\n if (!expected) return true;\n\n return expected.some((candidate) =>\n candidate === ANONYMOUS\n ? principal === null\n : candidate === WILDCARD\n ? principal !== null\n : (principal?.roles.includes(candidate) ?? false),\n );\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === 'object' && value !== null && 'then' in value && typeof value.then === 'function') ||\n (typeof value === 'function' && 'then' in value && typeof value.then === 'function')\n );\n}\n\nexport function ruleMatches<TAction extends string, TResource extends string, TAttributes extends WardAttributes>(\n rule: WardRule<TAction, TResource, TAttributes>,\n index: number,\n input: WardDecisionInput<TAction, TResource, TAttributes> & { principal: Principal },\n): boolean {\n if (!matchesPattern(rule.action, input.action)) return false;\n if (!matchesPattern(rule.resource, input.resource)) return false;\n if (!rolesMatch(rule.roles, input.principal)) return false;\n if (!attributesMatch(rule.attributes, input.attributes)) return false;\n if (!rule.condition) return true;\n\n try {\n const result: unknown = rule.condition({ attributes: input.attributes, principal: input.principal });\n\n if (isThenable(result)) {\n throw new TypeError('Async conditions are not supported; return a boolean');\n }\n if (typeof result !== 'boolean') {\n throw new TypeError('Conditions must return a boolean');\n }\n\n return result;\n } catch (error) {\n throw new WardConditionError(index, error);\n }\n}\n"],"mappings":";;;;;AAcA,SAAgB,oBAAoB,GAAgD;CAClF,IAAI,OAAOA,KAAU,YAAY,CAACA,GAChC,MAAM,IAAIC,EAAgB,6DAA6D;CAGzF,IAAMC,IAAYF;CAElB,IAAI,OAAOE,EAAU,MAAO,YAAY,CAACA,EAAU,GAAG,KAAK,GACzD,MAAM,IAAID,EAAgB,kDAAkD;CAG9E,IAAI,CAAC,MAAM,QAAQC,EAAU,KAAK,KAAKA,EAAU,MAAM,MAAM,MAAS,OAAOC,KAAS,YAAY,CAACA,EAAK,KAAK,CAAC,GAC5G,MAAM,IAAIF,EAAgB,gEAAgE;AAE9F;AAEA,SAAgB,kBAAkB,GAA6C;CAK7E,OAJIC,KAAyC,OAAa,QAE1D,oBAAoBA,CAAS,GAEtB,OAAO,OAAO;EACnB,GAAIA,EAAU,eAAe,KAAA,IACzB,CAAC,IACD,EAAE,YAAYE,EAAmBF,EAAU,YAAY,sBAAsB,EAAE;EACnF,IAAIA,EAAU;EACd,OAAO,OAAO,OAAO,CAAC,GAAGA,EAAU,KAAK,CAAC;CAC3C,CAAC;AACH;AAEA,SAAgB,sBAKd,GAGA;CACA,IAAI,OAAOF,EAAM,UAAW,YAAY,CAACA,EAAM,OAAO,KAAK,GACzD,MAAM,IAAIC,EAAgB,4CAA4C;CAExE,IAAI,OAAOD,EAAM,YAAa,YAAY,CAACA,EAAM,SAAS,KAAK,GAC7D,MAAM,IAAIC,EAAgB,8CAA8C;CAG1E,OAAO,OAAO,OAAO;EACnB,QAAQD,EAAM;EACd,GAAIA,EAAM,eAAe,KAAA,IACrB,CAAC,IACD,EAAE,YAAYI,EAAmBJ,EAAM,YAAY,qBAAqB,EAAiB;EAC7F,WAAW,kBAAkBA,EAAM,SAAS;EAC5C,UAAUA,EAAM;CAClB,CAAC;AACH;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AACiB,EAAeC,EAAK,UAAUlB,EAAM,QAAQ,KAC7C,CAAC,WAAWkB,EAAK,OAAOlB,EAAM,SAAS,KACvC,CAAC,gBAAgBkB,EAAK,YAAYlB,EAAM,UAAU,GAAG,OAAO;CAChE,IAAI,CAACkB,EAAK,WAAW,OAAO;CAE5B,IAAI;EACF,IAAMC,IAAkBD,EAAK,UAAU;GAAE,YAAYlB,EAAM;GAAY,WAAWA,EAAM;EAAU,CAAC;EAEnG,IAAI,WAAWmB,CAAM,GACnB,MAAU,UAAU,sDAAsD;EAE5E,IAAI,OAAOA,KAAW,WACpB,MAAU,UAAU,kCAAkC;EAGxD,OAAOA;CACT,SAASC,GAAO;EACd,MAAM,IAAIC,EAAmBb,GAAOY,CAAK;CAC3C;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"constants.cjs","names":[],"sources":["../src/constants.ts"],"sourcesContent":["export const WILDCARD = '*' as const;\nexport const ANONYMOUS = 'anonymous' as const;\n"],"mappings":"AAAA,IAAa,EAAW,IACX,EAAY"}
1
+ {"version":3,"file":"constants.cjs","names":["WILDCARD","ANONYMOUS"],"sources":["../src/constants.ts"],"sourcesContent":["export const WILDCARD = '*' as const;\nexport const ANONYMOUS = 'anonymous' as const;\n"],"mappings":"AAAA,IAAaA,EAAW,IACXC,EAAY,Y"}
package/dist/constants.js CHANGED
@@ -1,2 +1,6 @@
1
- var e=`*`,t=`anonymous`;export{t as ANONYMOUS,e as WILDCARD};
1
+ //#region src/constants.ts
2
+ var e = "*", t = "anonymous";
3
+ //#endregion
4
+ export { t as ANONYMOUS, e as WILDCARD };
5
+
2
6
  //# sourceMappingURL=constants.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","names":[],"sources":["../src/constants.ts"],"sourcesContent":["export const WILDCARD = '*' as const;\nexport const ANONYMOUS = 'anonymous' as const;\n"],"mappings":"AAAA,IAAa,EAAW,IACX,EAAY"}
1
+ {"version":3,"file":"constants.js","names":["WILDCARD","ANONYMOUS"],"sources":["../src/constants.ts"],"sourcesContent":["export const WILDCARD = '*' as const;\nexport const ANONYMOUS = 'anonymous' as const;\n"],"mappings":";AAAA,IAAaA,IAAW,KACXC,IAAY"}
@@ -1 +1 @@
1
- {"version":3,"file":"errors.cjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/** Base class for all ward errors. Use `instanceof WardError` to catch any ward-originated error. */\nexport class WardError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when a rule definition, decision attributes, or principal is malformed. */\nexport class WardConfigError extends WardError {}\n\n/** Thrown when an application-provided rule condition fails. */\nexport class WardConditionError extends WardError {\n readonly ruleIndex: number;\n\n constructor(ruleIndex: number, cause: unknown) {\n super(`Rule[${ruleIndex}].condition failed`, { cause });\n this.ruleIndex = ruleIndex;\n }\n}\n"],"mappings":"AACA,IAAa,UAAb,cAA+B,KAAM,CACnC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAGa,gBAAb,cAAqC,SAAU,CAAC,EAGnC,mBAAb,cAAwC,SAAU,CAChD,UAEA,YAAY,EAAmB,EAAgB,CAC7C,MAAM,QAAQ,EAAU,oBAAqB,CAAE,OAAM,CAAC,EACtD,KAAK,UAAY,CACnB,CACF"}
1
+ {"version":3,"file":"errors.cjs","names":["message","opts","ruleIndex"],"sources":["../src/errors.ts"],"sourcesContent":["/** Base class for all ward errors. Use `instanceof WardError` to catch any ward-originated error. */\nexport class WardError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when a rule definition, decision attributes, or principal is malformed. */\nexport class WardConfigError extends WardError {}\n\n/** Thrown when an application-provided rule condition fails. */\nexport class WardConditionError extends WardError {\n readonly ruleIndex: number;\n\n constructor(ruleIndex: number, cause: unknown) {\n super(`Rule[${ruleIndex}].condition failed`, { cause });\n this.ruleIndex = ruleIndex;\n }\n}\n"],"mappings":"AACA,IAAa,UAAb,cAA+B,KAAM,CACnC,YAAY,EAAiB,EAAqB,CAChD,MAAMA,EAASC,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAGa,gBAAb,cAAqC,SAAU,CAAC,EAGnC,mBAAb,cAAwC,SAAU,CAChD,UAEA,YAAY,EAAmB,EAAgB,CAC7C,MAAM,QAAQC,EAAU,oBAAqB,CAAE,OAAM,CAAC,EACtD,KAAK,UAAYA,CACnB,CACF,E"}
package/dist/errors.js CHANGED
@@ -1,2 +1,15 @@
1
- var WardError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},WardConfigError=class extends WardError{},WardConditionError=class extends WardError{ruleIndex;constructor(e,t){super(`Rule[${e}].condition failed`,{cause:t}),this.ruleIndex=e}};export{WardConditionError,WardConfigError,WardError};
1
+ //#region src/errors.ts
2
+ var WardError = class extends Error {
3
+ constructor(e, t) {
4
+ super(e, t), this.name = new.target.name, Object.setPrototypeOf(this, new.target.prototype);
5
+ }
6
+ }, WardConfigError = class extends WardError {}, WardConditionError = class extends WardError {
7
+ ruleIndex;
8
+ constructor(e, t) {
9
+ super(`Rule[${e}].condition failed`, { cause: t }), this.ruleIndex = e;
10
+ }
11
+ };
12
+ //#endregion
13
+ export { WardConditionError, WardConfigError, WardError };
14
+
2
15
  //# sourceMappingURL=errors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/** Base class for all ward errors. Use `instanceof WardError` to catch any ward-originated error. */\nexport class WardError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when a rule definition, decision attributes, or principal is malformed. */\nexport class WardConfigError extends WardError {}\n\n/** Thrown when an application-provided rule condition fails. */\nexport class WardConditionError extends WardError {\n readonly ruleIndex: number;\n\n constructor(ruleIndex: number, cause: unknown) {\n super(`Rule[${ruleIndex}].condition failed`, { cause });\n this.ruleIndex = ruleIndex;\n }\n}\n"],"mappings":"AACA,IAAa,UAAb,cAA+B,KAAM,CACnC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAGa,gBAAb,cAAqC,SAAU,CAAC,EAGnC,mBAAb,cAAwC,SAAU,CAChD,UAEA,YAAY,EAAmB,EAAgB,CAC7C,MAAM,QAAQ,EAAU,oBAAqB,CAAE,OAAM,CAAC,EACtD,KAAK,UAAY,CACnB,CACF"}
1
+ {"version":3,"file":"errors.js","names":["message","opts","ruleIndex"],"sources":["../src/errors.ts"],"sourcesContent":["/** Base class for all ward errors. Use `instanceof WardError` to catch any ward-originated error. */\nexport class WardError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when a rule definition, decision attributes, or principal is malformed. */\nexport class WardConfigError extends WardError {}\n\n/** Thrown when an application-provided rule condition fails. */\nexport class WardConditionError extends WardError {\n readonly ruleIndex: number;\n\n constructor(ruleIndex: number, cause: unknown) {\n super(`Rule[${ruleIndex}].condition failed`, { cause });\n this.ruleIndex = ruleIndex;\n }\n}\n"],"mappings":";AACA,IAAa,YAAb,cAA+B,MAAM;CACnC,YAAY,GAAiB,GAAqB;EAGhD,AAFA,MAAMA,GAASC,CAAI,GACnB,KAAK,OAAO,WAAW,MACvB,OAAO,eAAe,MAAM,WAAW,SAAS;CAClD;AACF,GAGa,kBAAb,cAAqC,UAAU,CAAC,GAGnC,qBAAb,cAAwC,UAAU;CAChD;CAEA,YAAY,GAAmB,GAAgB;EAE7C,AADA,MAAM,QAAQC,EAAU,qBAAqB,EAAE,SAAM,CAAC,GACtD,KAAK,YAAYA;CACnB;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"factory.cjs","names":[],"sources":["../src/factory.ts"],"sourcesContent":["import { tapper } from '@vielzeug/arsenal';\n\nimport { compileRule } from './_compile';\nimport { ruleMatches, snapshotDecisionInput, snapshotPrincipal } from './_match';\nimport type {\n BoundWard,\n Principal,\n Ward,\n WardAttributes,\n WardDecision,\n WardDecisionInput,\n WardEvent,\n WardRule,\n} from './types';\n\n/**\n * Creates an authorization ward from an ordered list of rules.\n *\n * **Decision model**: rules are evaluated in declaration order; the first rule\n * that matches the request wins. If no rule matches, the decision is **deny**\n * (default deny). There is no priority, specificity scoring, or conflict\n * detection: order is the only tiebreaker.\n *\n * A rule matches when:\n * 1. Its `action` pattern matches the requested action (`*` or `ns:*` or exact).\n * 2. Its `resource` pattern matches the requested resource.\n * 3. Its declarative `roles` (if any) include the principal's role, `ANONYMOUS`\n * matches a null principal, and `WILDCARD` matches any authenticated principal.\n * 4. Every key in its declarative `attributes` is present and equal in the\n * request's `attributes` (deep equality).\n * 5. Its `condition` escape-hatch callback (if any) returns `true`.\n */\nexport function createWard<\n TAction extends string = string,\n TResource extends string = string,\n TAttributes extends WardAttributes = WardAttributes,\n>(\n rules: readonly (\n | WardRule<NoInfer<TAction>, NoInfer<TResource>, NoInfer<TAttributes>>\n | readonly WardRule<NoInfer<TAction>, NoInfer<TResource>, NoInfer<TAttributes>>[]\n )[] = [],\n): Ward<TAction, TResource, TAttributes> {\n const compiled = Object.freeze(rules.flat().map((rule, index) => compileRule(rule, index)));\n const knownActions = Object.freeze([\n ...new Set(\n compiled.flatMap((rule) => (rule.effect === 'allow' && !rule.action.includes('*') ? [rule.action] : [])),\n ),\n ]) as readonly TAction[];\n const tappers = tapper<WardEvent<TAction, TResource, TAttributes>>();\n\n function evaluate(\n input: WardDecisionInput<TAction, TResource, TAttributes>,\n emit: boolean,\n ): WardDecision<TAction, TResource, TAttributes> {\n const normalized = snapshotDecisionInput(input);\n\n for (let index = 0; index < compiled.length; index++) {\n const rule = compiled[index];\n\n if (ruleMatches(rule, index, normalized)) {\n const decision = Object.freeze({\n effect: rule.effect,\n matched: true,\n reason: `rule[${index}] ${rule.effect === 'allow' ? 'allows' : 'denies'} '${normalized.action}' on '${normalized.resource}'`,\n rule,\n }) as WardDecision<TAction, TResource, TAttributes>;\n\n if (emit) emitDecision(normalized, decision);\n return decision;\n }\n }\n\n const decision = Object.freeze({\n effect: 'deny',\n matched: false,\n reason: `no matching rule for '${normalized.action}' on '${normalized.resource}' (default deny)`,\n }) as WardDecision<TAction, TResource, TAttributes>;\n\n if (emit) emitDecision(normalized, decision);\n return decision;\n }\n\n function emitDecision(\n input: WardDecisionInput<TAction, TResource, TAttributes> & { principal: Principal },\n decision: WardDecision<TAction, TResource, TAttributes>,\n ): void {\n tappers.emit(Object.freeze({ decision, input, type: 'decision' as const }));\n }\n\n function decide(\n input: WardDecisionInput<TAction, TResource, TAttributes>,\n ): WardDecision<TAction, TResource, TAttributes> {\n return evaluate(input, true);\n }\n\n function checkAll(\n inputs: readonly WardDecisionInput<TAction, TResource, TAttributes>[],\n ): WardDecision<TAction, TResource, TAttributes>[] {\n return inputs.map(decide);\n }\n\n function allowedActions(input: {\n attributes?: TAttributes;\n filter?: readonly TAction[];\n principal?: Principal;\n resource: TResource;\n }): TAction[] {\n const candidates = input.filter ?? knownActions;\n const seen = new Set<TAction>();\n\n return candidates.filter((action) => {\n if (seen.has(action)) return false;\n seen.add(action);\n return evaluate({ ...input, action }, false).effect === 'allow';\n });\n }\n\n function forPrincipal(principal?: Principal): BoundWard<TAction, TResource, TAttributes> {\n const snapshot = snapshotPrincipal(principal);\n\n return {\n allowedActions: (input) => allowedActions({ ...input, principal: snapshot }),\n checkAll: (inputs) => checkAll(inputs.map((input) => ({ ...input, principal: snapshot }))),\n decide: (input) => decide({ ...input, principal: snapshot }),\n };\n }\n\n return {\n allowedActions,\n checkAll,\n decide,\n forPrincipal,\n knownActions,\n rules: compiled,\n tap: (handler, options) => tappers.tap(handler, options),\n };\n}\n"],"mappings":"+FAgCA,SAAgB,WAKd,EAGM,CAAC,EACgC,CACvC,IAAM,EAAW,OAAO,OAAO,EAAM,KAAK,CAAC,CAAC,KAAK,EAAM,IAAU,EAAA,YAAY,EAAM,CAAK,CAAC,CAAC,EACpF,EAAe,OAAO,OAAO,CACjC,GAAG,IAAI,IACL,EAAS,QAAS,GAAU,EAAK,SAAW,SAAW,CAAC,EAAK,OAAO,SAAS,GAAG,EAAI,CAAC,EAAK,MAAM,EAAI,CAAC,CAAE,CACzG,CACF,CAAC,EACK,GAAA,EAAU,EAAA,OAAA,CAAmD,EAEnE,SAAS,SACP,EACA,EAC+C,CAC/C,IAAM,EAAa,EAAA,sBAAsB,CAAK,EAE9C,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAS,OAAQ,IAAS,CACpD,IAAM,EAAO,EAAS,GAEtB,GAAI,EAAA,YAAY,EAAM,EAAO,CAAU,EAAG,CACxC,IAAM,EAAW,OAAO,OAAO,CAC7B,OAAQ,EAAK,OACb,QAAS,GACT,OAAQ,QAAQ,EAAM,IAAI,EAAK,SAAW,QAAU,SAAW,SAAS,IAAI,EAAW,OAAO,QAAQ,EAAW,SAAS,GAC1H,MACF,CAAC,EAGD,OADI,GAAM,aAAa,EAAY,CAAQ,EACpC,CACT,CACF,CAEA,IAAM,EAAW,OAAO,OAAO,CAC7B,OAAQ,OACR,QAAS,GACT,OAAQ,yBAAyB,EAAW,OAAO,QAAQ,EAAW,SAAS,iBACjF,CAAC,EAGD,OADI,GAAM,aAAa,EAAY,CAAQ,EACpC,CACT,CAEA,SAAS,aACP,EACA,EACM,CACN,EAAQ,KAAK,OAAO,OAAO,CAAE,WAAU,QAAO,KAAM,UAAoB,CAAC,CAAC,CAC5E,CAEA,SAAS,OACP,EAC+C,CAC/C,OAAO,SAAS,EAAO,EAAI,CAC7B,CAEA,SAAS,SACP,EACiD,CACjD,OAAO,EAAO,IAAI,MAAM,CAC1B,CAEA,SAAS,eAAe,EAKV,CACZ,IAAM,EAAa,EAAM,QAAU,EAC7B,EAAO,IAAI,IAEjB,OAAO,EAAW,OAAQ,GACxB,CAAI,EAAK,IAAI,CAAM,IACnB,EAAK,IAAI,CAAM,EACR,SAAS,CAAE,GAAG,EAAO,QAAO,EAAG,EAAK,CAAC,CAAC,SAAW,QACzD,CACH,CAEA,SAAS,aAAa,EAAmE,CACvF,IAAM,EAAW,EAAA,kBAAkB,CAAS,EAE5C,MAAO,CACL,eAAiB,GAAU,eAAe,CAAE,GAAG,EAAO,UAAW,CAAS,CAAC,EAC3E,SAAW,GAAW,SAAS,EAAO,IAAK,IAAW,CAAE,GAAG,EAAO,UAAW,CAAS,EAAE,CAAC,EACzF,OAAS,GAAU,OAAO,CAAE,GAAG,EAAO,UAAW,CAAS,CAAC,CAC7D,CACF,CAEA,MAAO,CACL,eACA,SACA,OACA,aACA,eACA,MAAO,EACP,KAAM,EAAS,IAAY,EAAQ,IAAI,EAAS,CAAO,CACzD,CACF"}
1
+ {"version":3,"file":"factory.cjs","names":["compileRule","tapper","snapshotDecisionInput","ruleMatches","snapshotPrincipal","require__compile","require__match","_vielzeug_arsenal","compiled","rules","rule","index","knownActions","tappers","normalized","input","decision","emit","inputs","candidates","seen","action","snapshot","principal","handler","options"],"sources":["../src/factory.ts"],"sourcesContent":["import { tapper } from '@vielzeug/arsenal';\n\nimport { compileRule } from './_compile';\nimport { ruleMatches, snapshotDecisionInput, snapshotPrincipal } from './_match';\nimport type {\n BoundWard,\n Principal,\n Ward,\n WardAttributes,\n WardDecision,\n WardDecisionInput,\n WardEvent,\n WardRule,\n} from './types';\n\n/**\n * Creates an authorization ward from an ordered list of rules.\n *\n * **Decision model**: rules are evaluated in declaration order; the first rule\n * that matches the request wins. If no rule matches, the decision is **deny**\n * (default deny). There is no priority, specificity scoring, or conflict\n * detection: order is the only tiebreaker.\n *\n * A rule matches when:\n * 1. Its `action` pattern matches the requested action (`*` or `ns:*` or exact).\n * 2. Its `resource` pattern matches the requested resource.\n * 3. Its declarative `roles` (if any) include the principal's role, `ANONYMOUS`\n * matches a null principal, and `WILDCARD` matches any authenticated principal.\n * 4. Every key in its declarative `attributes` is present and equal in the\n * request's `attributes` (deep equality).\n * 5. Its `condition` escape-hatch callback (if any) returns `true`.\n */\nexport function createWard<\n TAction extends string = string,\n TResource extends string = string,\n TAttributes extends WardAttributes = WardAttributes,\n>(\n rules: readonly (\n | WardRule<NoInfer<TAction>, NoInfer<TResource>, NoInfer<TAttributes>>\n | readonly WardRule<NoInfer<TAction>, NoInfer<TResource>, NoInfer<TAttributes>>[]\n )[] = [],\n): Ward<TAction, TResource, TAttributes> {\n const compiled = Object.freeze(rules.flat().map((rule, index) => compileRule(rule, index)));\n const knownActions = Object.freeze([\n ...new Set(\n compiled.flatMap((rule) => (rule.effect === 'allow' && !rule.action.includes('*') ? [rule.action] : [])),\n ),\n ]) as readonly TAction[];\n const tappers = tapper<WardEvent<TAction, TResource, TAttributes>>();\n\n function evaluate(\n input: WardDecisionInput<TAction, TResource, TAttributes>,\n emit: boolean,\n ): WardDecision<TAction, TResource, TAttributes> {\n const normalized = snapshotDecisionInput(input);\n\n for (let index = 0; index < compiled.length; index++) {\n const rule = compiled[index];\n\n if (ruleMatches(rule, index, normalized)) {\n const decision = Object.freeze({\n effect: rule.effect,\n matched: true,\n reason: `rule[${index}] ${rule.effect === 'allow' ? 'allows' : 'denies'} '${normalized.action}' on '${normalized.resource}'`,\n rule,\n }) as WardDecision<TAction, TResource, TAttributes>;\n\n if (emit) emitDecision(normalized, decision);\n return decision;\n }\n }\n\n const decision = Object.freeze({\n effect: 'deny',\n matched: false,\n reason: `no matching rule for '${normalized.action}' on '${normalized.resource}' (default deny)`,\n }) as WardDecision<TAction, TResource, TAttributes>;\n\n if (emit) emitDecision(normalized, decision);\n return decision;\n }\n\n function emitDecision(\n input: WardDecisionInput<TAction, TResource, TAttributes> & { principal: Principal },\n decision: WardDecision<TAction, TResource, TAttributes>,\n ): void {\n tappers.emit(Object.freeze({ decision, input, type: 'decision' as const }));\n }\n\n function decide(\n input: WardDecisionInput<TAction, TResource, TAttributes>,\n ): WardDecision<TAction, TResource, TAttributes> {\n return evaluate(input, true);\n }\n\n function checkAll(\n inputs: readonly WardDecisionInput<TAction, TResource, TAttributes>[],\n ): WardDecision<TAction, TResource, TAttributes>[] {\n return inputs.map(decide);\n }\n\n function allowedActions(input: {\n attributes?: TAttributes;\n filter?: readonly TAction[];\n principal?: Principal;\n resource: TResource;\n }): TAction[] {\n const candidates = input.filter ?? knownActions;\n const seen = new Set<TAction>();\n\n return candidates.filter((action) => {\n if (seen.has(action)) return false;\n seen.add(action);\n return evaluate({ ...input, action }, false).effect === 'allow';\n });\n }\n\n function forPrincipal(principal?: Principal): BoundWard<TAction, TResource, TAttributes> {\n const snapshot = snapshotPrincipal(principal);\n\n return {\n allowedActions: (input) => allowedActions({ ...input, principal: snapshot }),\n checkAll: (inputs) => checkAll(inputs.map((input) => ({ ...input, principal: snapshot }))),\n decide: (input) => decide({ ...input, principal: snapshot }),\n };\n }\n\n return {\n allowedActions,\n checkAll,\n decide,\n forPrincipal,\n knownActions,\n rules: compiled,\n tap: (handler, options) => tappers.tap(handler, options),\n };\n}\n"],"mappings":"A,+FAgCA,SAAgB,WAKd,EAGM,CAAC,EACgC,CACvC,IAAMQ,EAAW,OAAO,OAAOC,EAAM,KAAK,CAAC,CAAC,KAAK,EAAM,IAAUT,EAAAA,YAAYU,EAAMC,CAAK,CAAC,CAAC,EACpFC,EAAe,OAAO,OAAO,CACjC,GAAG,IAAI,IACLJ,EAAS,QAAS,GAAUE,EAAK,SAAW,SAAW,CAACA,EAAK,OAAO,SAAS,GAAG,EAAI,CAACA,EAAK,MAAM,EAAI,CAAC,CAAE,CACzG,CACF,CAAC,EACKG,GAAA,EAAUZ,EAAAA,OAAAA,CAAmD,EAE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WO,CAAS,CAAC,EAC3E,SAAW,GAAW,SAASJ,EAAO,IAAK,IAAW,CAAE,GAAGH,EAAO,UAAWO,CAAS,EAAE,CAAC,EACzF,OAAS,GAAU,OAAO,CAAE,GAAGP,EAAO,UAAWO,CAAS,CAAC,CAC7D,CACF,CAEA,MAAO,CACL,eACA,SACA,OACA,aACA,eACA,MAAOd,EACP,KAAM,EAAS,IAAYK,EAAQ,IAAIW,EAASC,CAAO,CACzD,CACF,C"}
package/dist/factory.js CHANGED
@@ -1,2 +1,78 @@
1
- import{compileRule as e}from"./_compile.js";import{ruleMatches as t,snapshotDecisionInput as n,snapshotPrincipal as r}from"./_match.js";import{tapper as i}from"@vielzeug/arsenal";function createWard(a=[]){let o=Object.freeze(a.flat().map((t,n)=>e(t,n))),s=Object.freeze([...new Set(o.flatMap(e=>e.effect===`allow`&&!e.action.includes(`*`)?[e.action]:[]))]),c=i();function evaluate(e,r){let i=n(e);for(let e=0;e<o.length;e++){let n=o[e];if(t(n,e,i)){let t=Object.freeze({effect:n.effect,matched:!0,reason:`rule[${e}] ${n.effect===`allow`?`allows`:`denies`} '${i.action}' on '${i.resource}'`,rule:n});return r&&emitDecision(i,t),t}}let a=Object.freeze({effect:`deny`,matched:!1,reason:`no matching rule for '${i.action}' on '${i.resource}' (default deny)`});return r&&emitDecision(i,a),a}function emitDecision(e,t){c.emit(Object.freeze({decision:t,input:e,type:`decision`}))}function decide(e){return evaluate(e,!0)}function checkAll(e){return e.map(decide)}function allowedActions(e){let t=e.filter??s,n=new Set;return t.filter(t=>!n.has(t)&&(n.add(t),evaluate({...e,action:t},!1).effect===`allow`))}function forPrincipal(e){let t=r(e);return{allowedActions:e=>allowedActions({...e,principal:t}),checkAll:e=>checkAll(e.map(e=>({...e,principal:t}))),decide:e=>decide({...e,principal:t})}}return{allowedActions,checkAll,decide,forPrincipal,knownActions:s,rules:o,tap:(e,t)=>c.tap(e,t)}}export{createWard};
1
+ import { compileRule as e } from "./_compile.js";
2
+ import { ruleMatches as t, snapshotDecisionInput as n, snapshotPrincipal as r } from "./_match.js";
3
+ import { tapper as i } from "@vielzeug/arsenal";
4
+ //#region src/factory.ts
5
+ function createWard(a = []) {
6
+ let o = Object.freeze(a.flat().map((t, n) => e(t, n))), s = Object.freeze([...new Set(o.flatMap((e) => e.effect === "allow" && !e.action.includes("*") ? [e.action] : []))]), c = i();
7
+ function evaluate(e, r) {
8
+ let i = n(e);
9
+ for (let e = 0; e < o.length; e++) {
10
+ let n = o[e];
11
+ if (t(n, e, i)) {
12
+ let t = Object.freeze({
13
+ effect: n.effect,
14
+ matched: !0,
15
+ reason: `rule[${e}] ${n.effect === "allow" ? "allows" : "denies"} '${i.action}' on '${i.resource}'`,
16
+ rule: n
17
+ });
18
+ return r && emitDecision(i, t), t;
19
+ }
20
+ }
21
+ let a = Object.freeze({
22
+ effect: "deny",
23
+ matched: !1,
24
+ reason: `no matching rule for '${i.action}' on '${i.resource}' (default deny)`
25
+ });
26
+ return r && emitDecision(i, a), a;
27
+ }
28
+ function emitDecision(e, t) {
29
+ c.emit(Object.freeze({
30
+ decision: t,
31
+ input: e,
32
+ type: "decision"
33
+ }));
34
+ }
35
+ function decide(e) {
36
+ return evaluate(e, !0);
37
+ }
38
+ function checkAll(e) {
39
+ return e.map(decide);
40
+ }
41
+ function allowedActions(e) {
42
+ let t = e.filter ?? s, n = /* @__PURE__ */ new Set();
43
+ return t.filter((t) => !n.has(t) && (n.add(t), evaluate({
44
+ ...e,
45
+ action: t
46
+ }, !1).effect === "allow"));
47
+ }
48
+ function forPrincipal(e) {
49
+ let t = r(e);
50
+ return {
51
+ allowedActions: (e) => allowedActions({
52
+ ...e,
53
+ principal: t
54
+ }),
55
+ checkAll: (e) => checkAll(e.map((e) => ({
56
+ ...e,
57
+ principal: t
58
+ }))),
59
+ decide: (e) => decide({
60
+ ...e,
61
+ principal: t
62
+ })
63
+ };
64
+ }
65
+ return {
66
+ allowedActions,
67
+ checkAll,
68
+ decide,
69
+ forPrincipal,
70
+ knownActions: s,
71
+ rules: o,
72
+ tap: (e, t) => c.tap(e, t)
73
+ };
74
+ }
75
+ //#endregion
76
+ export { createWard };
77
+
2
78
  //# sourceMappingURL=factory.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"factory.js","names":[],"sources":["../src/factory.ts"],"sourcesContent":["import { tapper } from '@vielzeug/arsenal';\n\nimport { compileRule } from './_compile';\nimport { ruleMatches, snapshotDecisionInput, snapshotPrincipal } from './_match';\nimport type {\n BoundWard,\n Principal,\n Ward,\n WardAttributes,\n WardDecision,\n WardDecisionInput,\n WardEvent,\n WardRule,\n} from './types';\n\n/**\n * Creates an authorization ward from an ordered list of rules.\n *\n * **Decision model**: rules are evaluated in declaration order; the first rule\n * that matches the request wins. If no rule matches, the decision is **deny**\n * (default deny). There is no priority, specificity scoring, or conflict\n * detection: order is the only tiebreaker.\n *\n * A rule matches when:\n * 1. Its `action` pattern matches the requested action (`*` or `ns:*` or exact).\n * 2. Its `resource` pattern matches the requested resource.\n * 3. Its declarative `roles` (if any) include the principal's role, `ANONYMOUS`\n * matches a null principal, and `WILDCARD` matches any authenticated principal.\n * 4. Every key in its declarative `attributes` is present and equal in the\n * request's `attributes` (deep equality).\n * 5. Its `condition` escape-hatch callback (if any) returns `true`.\n */\nexport function createWard<\n TAction extends string = string,\n TResource extends string = string,\n TAttributes extends WardAttributes = WardAttributes,\n>(\n rules: readonly (\n | WardRule<NoInfer<TAction>, NoInfer<TResource>, NoInfer<TAttributes>>\n | readonly WardRule<NoInfer<TAction>, NoInfer<TResource>, NoInfer<TAttributes>>[]\n )[] = [],\n): Ward<TAction, TResource, TAttributes> {\n const compiled = Object.freeze(rules.flat().map((rule, index) => compileRule(rule, index)));\n const knownActions = Object.freeze([\n ...new Set(\n compiled.flatMap((rule) => (rule.effect === 'allow' && !rule.action.includes('*') ? [rule.action] : [])),\n ),\n ]) as readonly TAction[];\n const tappers = tapper<WardEvent<TAction, TResource, TAttributes>>();\n\n function evaluate(\n input: WardDecisionInput<TAction, TResource, TAttributes>,\n emit: boolean,\n ): WardDecision<TAction, TResource, TAttributes> {\n const normalized = snapshotDecisionInput(input);\n\n for (let index = 0; index < compiled.length; index++) {\n const rule = compiled[index];\n\n if (ruleMatches(rule, index, normalized)) {\n const decision = Object.freeze({\n effect: rule.effect,\n matched: true,\n reason: `rule[${index}] ${rule.effect === 'allow' ? 'allows' : 'denies'} '${normalized.action}' on '${normalized.resource}'`,\n rule,\n }) as WardDecision<TAction, TResource, TAttributes>;\n\n if (emit) emitDecision(normalized, decision);\n return decision;\n }\n }\n\n const decision = Object.freeze({\n effect: 'deny',\n matched: false,\n reason: `no matching rule for '${normalized.action}' on '${normalized.resource}' (default deny)`,\n }) as WardDecision<TAction, TResource, TAttributes>;\n\n if (emit) emitDecision(normalized, decision);\n return decision;\n }\n\n function emitDecision(\n input: WardDecisionInput<TAction, TResource, TAttributes> & { principal: Principal },\n decision: WardDecision<TAction, TResource, TAttributes>,\n ): void {\n tappers.emit(Object.freeze({ decision, input, type: 'decision' as const }));\n }\n\n function decide(\n input: WardDecisionInput<TAction, TResource, TAttributes>,\n ): WardDecision<TAction, TResource, TAttributes> {\n return evaluate(input, true);\n }\n\n function checkAll(\n inputs: readonly WardDecisionInput<TAction, TResource, TAttributes>[],\n ): WardDecision<TAction, TResource, TAttributes>[] {\n return inputs.map(decide);\n }\n\n function allowedActions(input: {\n attributes?: TAttributes;\n filter?: readonly TAction[];\n principal?: Principal;\n resource: TResource;\n }): TAction[] {\n const candidates = input.filter ?? knownActions;\n const seen = new Set<TAction>();\n\n return candidates.filter((action) => {\n if (seen.has(action)) return false;\n seen.add(action);\n return evaluate({ ...input, action }, false).effect === 'allow';\n });\n }\n\n function forPrincipal(principal?: Principal): BoundWard<TAction, TResource, TAttributes> {\n const snapshot = snapshotPrincipal(principal);\n\n return {\n allowedActions: (input) => allowedActions({ ...input, principal: snapshot }),\n checkAll: (inputs) => checkAll(inputs.map((input) => ({ ...input, principal: snapshot }))),\n decide: (input) => decide({ ...input, principal: snapshot }),\n };\n }\n\n return {\n allowedActions,\n checkAll,\n decide,\n forPrincipal,\n knownActions,\n rules: compiled,\n tap: (handler, options) => tappers.tap(handler, options),\n };\n}\n"],"mappings":"mLAgCA,SAAgB,WAKd,EAGM,CAAC,EACgC,CACvC,IAAM,EAAW,OAAO,OAAO,EAAM,KAAK,CAAC,CAAC,KAAK,EAAM,IAAU,EAAY,EAAM,CAAK,CAAC,CAAC,EACpF,EAAe,OAAO,OAAO,CACjC,GAAG,IAAI,IACL,EAAS,QAAS,GAAU,EAAK,SAAW,SAAW,CAAC,EAAK,OAAO,SAAS,GAAG,EAAI,CAAC,EAAK,MAAM,EAAI,CAAC,CAAE,CACzG,CACF,CAAC,EACK,EAAU,EAAmD,EAEnE,SAAS,SACP,EACA,EAC+C,CAC/C,IAAM,EAAa,EAAsB,CAAK,EAE9C,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAS,OAAQ,IAAS,CACpD,IAAM,EAAO,EAAS,GAEtB,GAAI,EAAY,EAAM,EAAO,CAAU,EAAG,CACxC,IAAM,EAAW,OAAO,OAAO,CAC7B,OAAQ,EAAK,OACb,QAAS,GACT,OAAQ,QAAQ,EAAM,IAAI,EAAK,SAAW,QAAU,SAAW,SAAS,IAAI,EAAW,OAAO,QAAQ,EAAW,SAAS,GAC1H,MACF,CAAC,EAGD,OADI,GAAM,aAAa,EAAY,CAAQ,EACpC,CACT,CACF,CAEA,IAAM,EAAW,OAAO,OAAO,CAC7B,OAAQ,OACR,QAAS,GACT,OAAQ,yBAAyB,EAAW,OAAO,QAAQ,EAAW,SAAS,iBACjF,CAAC,EAGD,OADI,GAAM,aAAa,EAAY,CAAQ,EACpC,CACT,CAEA,SAAS,aACP,EACA,EACM,CACN,EAAQ,KAAK,OAAO,OAAO,CAAE,WAAU,QAAO,KAAM,UAAoB,CAAC,CAAC,CAC5E,CAEA,SAAS,OACP,EAC+C,CAC/C,OAAO,SAAS,EAAO,EAAI,CAC7B,CAEA,SAAS,SACP,EACiD,CACjD,OAAO,EAAO,IAAI,MAAM,CAC1B,CAEA,SAAS,eAAe,EAKV,CACZ,IAAM,EAAa,EAAM,QAAU,EAC7B,EAAO,IAAI,IAEjB,OAAO,EAAW,OAAQ,GACxB,CAAI,EAAK,IAAI,CAAM,IACnB,EAAK,IAAI,CAAM,EACR,SAAS,CAAE,GAAG,EAAO,QAAO,EAAG,EAAK,CAAC,CAAC,SAAW,QACzD,CACH,CAEA,SAAS,aAAa,EAAmE,CACvF,IAAM,EAAW,EAAkB,CAAS,EAE5C,MAAO,CACL,eAAiB,GAAU,eAAe,CAAE,GAAG,EAAO,UAAW,CAAS,CAAC,EAC3E,SAAW,GAAW,SAAS,EAAO,IAAK,IAAW,CAAE,GAAG,EAAO,UAAW,CAAS,EAAE,CAAC,EACzF,OAAS,GAAU,OAAO,CAAE,GAAG,EAAO,UAAW,CAAS,CAAC,CAC7D,CACF,CAEA,MAAO,CACL,eACA,SACA,OACA,aACA,eACA,MAAO,EACP,KAAM,EAAS,IAAY,EAAQ,IAAI,EAAS,CAAO,CACzD,CACF"}
1
+ {"version":3,"file":"factory.js","names":["compiled","rules","compileRule","rule","index","knownActions","tappers","tapper","normalized","snapshotDecisionInput","input","ruleMatches","decision","emit","inputs","candidates","seen","action","snapshot","snapshotPrincipal","principal","handler","options"],"sources":["../src/factory.ts"],"sourcesContent":["import { tapper } from '@vielzeug/arsenal';\n\nimport { compileRule } from './_compile';\nimport { ruleMatches, snapshotDecisionInput, snapshotPrincipal } from './_match';\nimport type {\n BoundWard,\n Principal,\n Ward,\n WardAttributes,\n WardDecision,\n WardDecisionInput,\n WardEvent,\n WardRule,\n} from './types';\n\n/**\n * Creates an authorization ward from an ordered list of rules.\n *\n * **Decision model**: rules are evaluated in declaration order; the first rule\n * that matches the request wins. If no rule matches, the decision is **deny**\n * (default deny). There is no priority, specificity scoring, or conflict\n * detection: order is the only tiebreaker.\n *\n * A rule matches when:\n * 1. Its `action` pattern matches the requested action (`*` or `ns:*` or exact).\n * 2. Its `resource` pattern matches the requested resource.\n * 3. Its declarative `roles` (if any) include the principal's role, `ANONYMOUS`\n * matches a null principal, and `WILDCARD` matches any authenticated principal.\n * 4. Every key in its declarative `attributes` is present and equal in the\n * request's `attributes` (deep equality).\n * 5. Its `condition` escape-hatch callback (if any) returns `true`.\n */\nexport function createWard<\n TAction extends string = string,\n TResource extends string = string,\n TAttributes extends WardAttributes = WardAttributes,\n>(\n rules: readonly (\n | WardRule<NoInfer<TAction>, NoInfer<TResource>, NoInfer<TAttributes>>\n | readonly WardRule<NoInfer<TAction>, NoInfer<TResource>, NoInfer<TAttributes>>[]\n )[] = [],\n): Ward<TAction, TResource, TAttributes> {\n const compiled = Object.freeze(rules.flat().map((rule, index) => compileRule(rule, index)));\n const knownActions = Object.freeze([\n ...new Set(\n compiled.flatMap((rule) => (rule.effect === 'allow' && !rule.action.includes('*') ? [rule.action] : [])),\n ),\n ]) as readonly TAction[];\n const tappers = tapper<WardEvent<TAction, TResource, TAttributes>>();\n\n function evaluate(\n input: WardDecisionInput<TAction, TResource, TAttributes>,\n emit: boolean,\n ): WardDecision<TAction, TResource, TAttributes> {\n const normalized = snapshotDecisionInput(input);\n\n for (let index = 0; index < compiled.length; index++) {\n const rule = compiled[index];\n\n if (ruleMatches(rule, index, normalized)) {\n const decision = Object.freeze({\n effect: rule.effect,\n matched: true,\n reason: `rule[${index}] ${rule.effect === 'allow' ? 'allows' : 'denies'} '${normalized.action}' on '${normalized.resource}'`,\n rule,\n }) as WardDecision<TAction, TResource, TAttributes>;\n\n if (emit) emitDecision(normalized, decision);\n return decision;\n }\n }\n\n const decision = Object.freeze({\n effect: 'deny',\n matched: false,\n reason: `no matching rule for '${normalized.action}' on '${normalized.resource}' (default deny)`,\n }) as WardDecision<TAction, TResource, TAttributes>;\n\n if (emit) emitDecision(normalized, decision);\n return decision;\n }\n\n function emitDecision(\n input: WardDecisionInput<TAction, TResource, TAttributes> & { principal: Principal },\n decision: WardDecision<TAction, TResource, TAttributes>,\n ): void {\n tappers.emit(Object.freeze({ decision, input, type: 'decision' as const }));\n }\n\n function decide(\n input: WardDecisionInput<TAction, TResource, TAttributes>,\n ): WardDecision<TAction, TResource, TAttributes> {\n return evaluate(input, true);\n }\n\n function checkAll(\n inputs: readonly WardDecisionInput<TAction, TResource, TAttributes>[],\n ): WardDecision<TAction, TResource, TAttributes>[] {\n return inputs.map(decide);\n }\n\n function allowedActions(input: {\n attributes?: TAttributes;\n filter?: readonly TAction[];\n principal?: Principal;\n resource: TResource;\n }): TAction[] {\n const candidates = input.filter ?? knownActions;\n const seen = new Set<TAction>();\n\n return candidates.filter((action) => {\n if (seen.has(action)) return false;\n seen.add(action);\n return evaluate({ ...input, action }, false).effect === 'allow';\n });\n }\n\n function forPrincipal(principal?: Principal): BoundWard<TAction, TResource, TAttributes> {\n const snapshot = snapshotPrincipal(principal);\n\n return {\n allowedActions: (input) => allowedActions({ ...input, principal: snapshot }),\n checkAll: (inputs) => checkAll(inputs.map((input) => ({ ...input, principal: snapshot }))),\n decide: (input) => decide({ ...input, principal: snapshot }),\n };\n }\n\n return {\n allowedActions,\n checkAll,\n decide,\n forPrincipal,\n knownActions,\n rules: compiled,\n tap: (handler, options) => tappers.tap(handler, options),\n };\n}\n"],"mappings":";;;;AAgCA,SAAgB,WAKd,IAGM,CAAC,GACgC;CACvC,IAAMA,IAAW,OAAO,OAAOC,EAAM,KAAK,CAAC,CAAC,KAAK,GAAM,MAAUC,EAAYC,GAAMC,CAAK,CAAC,CAAC,GACpFC,IAAe,OAAO,OAAO,CACjC,GAAG,IAAI,IACLL,EAAS,SAAS,MAAUG,EAAK,WAAW,WAAW,CAACA,EAAK,OAAO,SAAS,GAAG,IAAI,CAACA,EAAK,MAAM,IAAI,CAAC,CAAE,CACzG,CACF,CAAC,GACKG,IAAUC,EAAmD;CAEnE,SAAS,SACP,GACA,GAC+C;EAC/C,IAAMC,IAAaC,EAAsBC,CAAK;EAE9C,KAAK,IAAIN,IAAQ,G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ACzF,SAAS,MAAU,OAAO;IAAE,GAAGR;IAAO,WAAWQ;GAAS,CAAC;EAC7D;CACF;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA,OAAOlB;EACP,MAAM,GAAS,MAAYM,EAAQ,IAAIe,GAASC,CAAO;CACzD;AACF"}
package/dist/index.js CHANGED
@@ -1 +1,6 @@
1
- import{ANONYMOUS as e,WILDCARD as t}from"./constants.js";import{WardConditionError as n,WardConfigError as r,WardError as i}from"./errors.js";import{matchesPattern as a}from"./resource.js";import{createWard as o}from"./factory.js";import{allow as s,deny as c,predicate as l}from"./rules.js";export{e as ANONYMOUS,t as WILDCARD,n as WardConditionError,r as WardConfigError,i as WardError,s as allow,o as createWard,c as deny,a as matchesPattern,l as predicate};
1
+ import { ANONYMOUS as e, WILDCARD as t } from "./constants.js";
2
+ import { WardConditionError as n, WardConfigError as r, WardError as i } from "./errors.js";
3
+ import { matchesPattern as a } from "./resource.js";
4
+ import { createWard as o } from "./factory.js";
5
+ import { allow as s, deny as c, predicate as l } from "./rules.js";
6
+ export { e as ANONYMOUS, t as WILDCARD, n as WardConditionError, r as WardConfigError, i as WardError, s as allow, o as createWard, c as deny, a as matchesPattern, l as predicate };
@@ -1 +1 @@
1
- {"version":3,"file":"resource.cjs","names":[],"sources":["../src/resource.ts"],"sourcesContent":["import { WILDCARD } from './constants';\n\n/**\n * Matches a rule pattern against a concrete value string.\n * Works for both resource patterns and action patterns (action hierarchy).\n *\n * Matching rules (evaluated in order):\n * 1. `WILDCARD` (`*`) matches any value string.\n * 2. An exact string matches itself.\n * 3. A colon-namespaced pattern ending in `:*` (e.g. `posts:*` or `read:*`)\n * matches any string that starts with the given namespace prefix followed by `:`.\n * Example: `posts:*` matches `posts:123`, `posts:draft:42`, etc.\n * `read:*` matches `read:own`, `read:all`, etc.\n *\n * @example\n * matchesPattern('*', 'posts:123') // true: global wildcard\n * matchesPattern('posts', 'posts') // true: exact\n * matchesPattern('posts:*', 'posts:123') // true: namespace wildcard\n * matchesPattern('posts:*', 'comments:1') // false: different namespace\n * matchesPattern('posts:42', 'posts:42') // true: exact namespaced id\n * matchesPattern('read:*', 'read:own') // true: action namespace wildcard\n * matchesPattern('read:*', 'write:all') // false: different action namespace\n */\nexport function matchesPattern(pattern: string, value: string): boolean {\n if (pattern === WILDCARD) return true;\n\n if (pattern === value) return true;\n\n // Namespace wildcard: \"namespace:*\" matches \"namespace:anything\"\n if (pattern.endsWith(':*')) {\n const ns = pattern.slice(0, -1); // keep the trailing colon as prefix delimiter\n\n return value.startsWith(ns);\n }\n\n return false;\n}\n"],"mappings":"2BAuBA,SAAgB,eAAe,EAAiB,EAAwB,CAGtE,GAFI,IAAA,KAEA,IAAY,EAAO,MAAO,GAG9B,GAAI,EAAQ,SAAS,IAAI,EAAG,CAC1B,IAAM,EAAK,EAAQ,MAAM,EAAG,EAAE,EAE9B,OAAO,EAAM,WAAW,CAAE,CAC5B,CAEA,MAAO,EACT"}
1
+ {"version":3,"file":"resource.cjs","names":["pattern","value","ns"],"sources":["../src/resource.ts"],"sourcesContent":["import { WILDCARD } from './constants';\n\n/**\n * Matches a rule pattern against a concrete value string.\n * Works for both resource patterns and action patterns (action hierarchy).\n *\n * Matching rules (evaluated in order):\n * 1. `WILDCARD` (`*`) matches any value string.\n * 2. An exact string matches itself.\n * 3. A colon-namespaced pattern ending in `:*` (e.g. `posts:*` or `read:*`)\n * matches any string that starts with the given namespace prefix followed by `:`.\n * Example: `posts:*` matches `posts:123`, `posts:draft:42`, etc.\n * `read:*` matches `read:own`, `read:all`, etc.\n *\n * @example\n * matchesPattern('*', 'posts:123') // true: global wildcard\n * matchesPattern('posts', 'posts') // true: exact\n * matchesPattern('posts:*', 'posts:123') // true: namespace wildcard\n * matchesPattern('posts:*', 'comments:1') // false: different namespace\n * matchesPattern('posts:42', 'posts:42') // true: exact namespaced id\n * matchesPattern('read:*', 'read:own') // true: action namespace wildcard\n * matchesPattern('read:*', 'write:all') // false: different action namespace\n */\nexport function matchesPattern(pattern: string, value: string): boolean {\n if (pattern === WILDCARD) return true;\n\n if (pattern === value) return true;\n\n // Namespace wildcard: \"namespace:*\" matches \"namespace:anything\"\n if (pattern.endsWith(':*')) {\n const ns = pattern.slice(0, -1); // keep the trailing colon as prefix delimiter\n\n return value.startsWith(ns);\n }\n\n return false;\n}\n"],"mappings":"A,2BAuBA,SAAgB,eAAe,EAAiB,EAAwB,CAGtE,GAFIA,IAAA,KAEAA,IAAYC,EAAO,MAAO,GAG9B,GAAID,EAAQ,SAAS,IAAI,EAAG,CAC1B,IAAME,EAAKF,EAAQ,MAAM,EAAG,EAAE,EAE9B,OAAOC,EAAM,WAAWC,CAAE,CAC5B,CAEA,MAAO,EACT,C"}
package/dist/resource.js CHANGED
@@ -1,2 +1,14 @@
1
- import"./constants.js";function matchesPattern(e,t){if(e===`*`||e===t)return!0;if(e.endsWith(`:*`)){let n=e.slice(0,-1);return t.startsWith(n)}return!1}export{matchesPattern};
1
+ import "./constants.js";
2
+ //#region src/resource.ts
3
+ function matchesPattern(e, t) {
4
+ if (e === "*" || e === t) return !0;
5
+ if (e.endsWith(":*")) {
6
+ let n = e.slice(0, -1);
7
+ return t.startsWith(n);
8
+ }
9
+ return !1;
10
+ }
11
+ //#endregion
12
+ export { matchesPattern };
13
+
2
14
  //# sourceMappingURL=resource.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"resource.js","names":[],"sources":["../src/resource.ts"],"sourcesContent":["import { WILDCARD } from './constants';\n\n/**\n * Matches a rule pattern against a concrete value string.\n * Works for both resource patterns and action patterns (action hierarchy).\n *\n * Matching rules (evaluated in order):\n * 1. `WILDCARD` (`*`) matches any value string.\n * 2. An exact string matches itself.\n * 3. A colon-namespaced pattern ending in `:*` (e.g. `posts:*` or `read:*`)\n * matches any string that starts with the given namespace prefix followed by `:`.\n * Example: `posts:*` matches `posts:123`, `posts:draft:42`, etc.\n * `read:*` matches `read:own`, `read:all`, etc.\n *\n * @example\n * matchesPattern('*', 'posts:123') // true: global wildcard\n * matchesPattern('posts', 'posts') // true: exact\n * matchesPattern('posts:*', 'posts:123') // true: namespace wildcard\n * matchesPattern('posts:*', 'comments:1') // false: different namespace\n * matchesPattern('posts:42', 'posts:42') // true: exact namespaced id\n * matchesPattern('read:*', 'read:own') // true: action namespace wildcard\n * matchesPattern('read:*', 'write:all') // false: different action namespace\n */\nexport function matchesPattern(pattern: string, value: string): boolean {\n if (pattern === WILDCARD) return true;\n\n if (pattern === value) return true;\n\n // Namespace wildcard: \"namespace:*\" matches \"namespace:anything\"\n if (pattern.endsWith(':*')) {\n const ns = pattern.slice(0, -1); // keep the trailing colon as prefix delimiter\n\n return value.startsWith(ns);\n }\n\n return false;\n}\n"],"mappings":"uBAuBA,SAAgB,eAAe,EAAiB,EAAwB,CAGtE,GAFI,IAAA,KAEA,IAAY,EAAO,MAAO,GAG9B,GAAI,EAAQ,SAAS,IAAI,EAAG,CAC1B,IAAM,EAAK,EAAQ,MAAM,EAAG,EAAE,EAE9B,OAAO,EAAM,WAAW,CAAE,CAC5B,CAEA,MAAO,EACT"}
1
+ {"version":3,"file":"resource.js","names":["pattern","value","ns"],"sources":["../src/resource.ts"],"sourcesContent":["import { WILDCARD } from './constants';\n\n/**\n * Matches a rule pattern against a concrete value string.\n * Works for both resource patterns and action patterns (action hierarchy).\n *\n * Matching rules (evaluated in order):\n * 1. `WILDCARD` (`*`) matches any value string.\n * 2. An exact string matches itself.\n * 3. A colon-namespaced pattern ending in `:*` (e.g. `posts:*` or `read:*`)\n * matches any string that starts with the given namespace prefix followed by `:`.\n * Example: `posts:*` matches `posts:123`, `posts:draft:42`, etc.\n * `read:*` matches `read:own`, `read:all`, etc.\n *\n * @example\n * matchesPattern('*', 'posts:123') // true: global wildcard\n * matchesPattern('posts', 'posts') // true: exact\n * matchesPattern('posts:*', 'posts:123') // true: namespace wildcard\n * matchesPattern('posts:*', 'comments:1') // false: different namespace\n * matchesPattern('posts:42', 'posts:42') // true: exact namespaced id\n * matchesPattern('read:*', 'read:own') // true: action namespace wildcard\n * matchesPattern('read:*', 'write:all') // false: different action namespace\n */\nexport function matchesPattern(pattern: string, value: string): boolean {\n if (pattern === WILDCARD) return true;\n\n if (pattern === value) return true;\n\n // Namespace wildcard: \"namespace:*\" matches \"namespace:anything\"\n if (pattern.endsWith(':*')) {\n const ns = pattern.slice(0, -1); // keep the trailing colon as prefix delimiter\n\n return value.startsWith(ns);\n }\n\n return false;\n}\n"],"mappings":";;AAuBA,SAAgB,eAAe,GAAiB,GAAwB;CAGtE,IAFIA,MAAA,OAEAA,MAAYC,GAAO,OAAO;CAG9B,IAAID,EAAQ,SAAS,IAAI,GAAG;EAC1B,IAAME,IAAKF,EAAQ,MAAM,GAAG,EAAE;EAE9B,OAAOC,EAAM,WAAWC,CAAE;CAC5B;CAEA,OAAO;AACT"}