declare const ValueRefType: unique symbol; /** * References a field on the resource model. * * The phantom type parameter `[ValueRefType]` carries the resolved field type * so that operator builders (e.g. `eq`, `gt`) can enforce type-safe operand * pairing at compile time without affecting the runtime JSON-serializable shape. */ interface ResourceRef = Record, P extends string = string> { readonly type: 'resource'; readonly path: P; readonly [ValueRefType]?: Value; } /** * References a field on the evaluation context (typically the current user * or request metadata). */ interface ContextRef = Record, P extends string = string> { readonly type: 'context'; readonly path: P; readonly [ValueRefType]?: Value; } /** * An inline literal value. The phantom type parameter captures the literal's * TypeScript type so operators can verify type compatibility at compile time. */ interface LiteralRef { readonly type: 'literal'; readonly value: T; readonly [ValueRefType]?: T; } /** Union of every value-reference variant. */ type ValueRef = ResourceRef | ContextRef | LiteralRef; /** * Extracts the value type carried by a `ValueRef`'s phantom type parameter. * * @example * ```ts * type T = InferValueRef>; // string * ``` */ type InferValueRef = R extends { readonly [ValueRefType]?: infer T; } ? T : never; /** * Extracts the element type from a `ValueRef` whose phantom type is an array. * Returns `never` if the phantom type is not an array. * * @example * ```ts * type E = ArrayElementType>; // string * ``` */ type ArrayElementType = NonNullable> extends (infer E)[] ? E : never; type ComparisonOperator = 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte'; type StringOperator = 'contains' | 'startsWith' | 'endsWith'; type ArrayMembershipOperator = 'in' | 'has' | 'hasSome' | 'hasEvery'; type ComplexArrayOperator = 'some' | 'every' | 'none'; /** Every non-logical operator recognised by the new DSL. */ type DslOperator = ComparisonOperator | StringOperator | ArrayMembershipOperator | ComplexArrayOperator; type LogicalOp = 'and' | 'or' | 'not'; /** * A leaf AST node representing a single comparison / membership check. * * Serializes to: * ```json * { "type": "operator", "operator": "eq", "operands": [...] } * ``` */ interface OperatorNode { readonly type: 'operator'; readonly operator: DslOperator; readonly operands: readonly ValueRef[]; readonly options?: Readonly<{ caseInsensitive?: boolean; }>; /** Nested condition used by complex array operators (`some`, `every`, `none`). */ readonly condition?: Condition; } /** * A combining AST node for `and`, `or`, or `not`. */ interface LogicalNode { readonly type: 'logical'; readonly operator: LogicalOp; readonly operands: readonly Condition[]; } /** Discriminated union of all AST node variants. */ type AstNode = OperatorNode | LogicalNode; /** * A serializable condition object returned by the `matchCondition` builder. * * The wrapped `AstNode` tree can be serialized to JSON for storage and later * evaluated at runtime against a resource instance and evaluation context. */ interface Condition { readonly type: 'condition'; readonly node: AstNode; } /** * The builder object passed to user-defined `matchCondition` functions. * Carries value-source factories and all operator methods. */ interface MatchConditionBuilder = Record, Context extends Record = Record> { resource

>(path: P): ResourceRef; context

>(path: P): ContextRef; literal(value: T): LiteralRef; /** * Equality check. Both operands must be `ValueRef` objects whose phantom * types are compatible. Null-ish right-hand operands (`null`, * `undefined`) are always accepted so that optional-field checks remain * expressible. */ eq(left: L, right: ValueRef & { readonly [ValueRefType]?: InferValueRef | null | undefined; }): Condition; /** Negated equality — mirrors `eq` with an inverted result. */ ne(left: L, right: ValueRef & { readonly [ValueRefType]?: InferValueRef | null | undefined; }): Condition; /** Greater-than. Both operands must carry a numeric phantom type. */ gt(left: ValueRef & { readonly [ValueRefType]?: number | null | undefined; }, right: ValueRef & { readonly [ValueRefType]?: number | null | undefined; }): Condition; /** Greater-than-or-equal. Both operands must carry a numeric phantom type. */ gte(left: ValueRef & { readonly [ValueRefType]?: number | null | undefined; }, right: ValueRef & { readonly [ValueRefType]?: number | null | undefined; }): Condition; /** Less-than. Both operands must carry a numeric phantom type. */ lt(left: ValueRef & { readonly [ValueRefType]?: number | null | undefined; }, right: ValueRef & { readonly [ValueRefType]?: number | null | undefined; }): Condition; /** Less-than-or-equal. Both operands must carry a numeric phantom type. */ lte(left: ValueRef & { readonly [ValueRefType]?: number | null | undefined; }, right: ValueRef & { readonly [ValueRefType]?: number | null | undefined; }): Condition; /** * Checks whether the string `str` contains `substring`. * Both operands must carry a string phantom type. */ contains(str: ValueRef & { readonly [ValueRefType]?: string | null | undefined; }, substring: ValueRef & { readonly [ValueRefType]?: string | null | undefined; }, options?: Readonly<{ caseInsensitive?: boolean; }>): Condition; /** * Checks whether the string `str` starts with `prefix`. * Both operands must carry a string phantom type. */ startsWith(str: ValueRef & { readonly [ValueRefType]?: string | null | undefined; }, prefix: ValueRef & { readonly [ValueRefType]?: string | null | undefined; }, options?: Readonly<{ caseInsensitive?: boolean; }>): Condition; /** * Checks whether the string `str` ends with `suffix`. * Both operands must carry a string phantom type. */ endsWith(str: ValueRef & { readonly [ValueRefType]?: string | null | undefined; }, suffix: ValueRef & { readonly [ValueRefType]?: string | null | undefined; }, options?: Readonly<{ caseInsensitive?: boolean; }>): Condition; /** * Checks whether `value` is an element of `array`. * The array must be an array-typed ValueRef; the value may be any type. */ in(value: V, array: ValueRef & { readonly [ValueRefType]?: readonly unknown[]; }, options?: Readonly<{ caseInsensitive?: boolean; }>): Condition; /** * Checks whether `array` contains `value`. * The value's phantom type is inferred from the array's element type. */ has(array: A, value: ValueRef & { readonly [ValueRefType]?: ArrayElementType; }, options?: Readonly<{ caseInsensitive?: boolean; }>): Condition; /** * Checks whether `array` contains at least one of the `values`. * Both operands must carry the same array phantom type. */ hasSome(array: A, values: ValueRef & { readonly [ValueRefType]?: ReadonlyArray>; }, options?: Readonly<{ caseInsensitive?: boolean; }>): Condition; /** * Checks whether `array` contains all of the `values`. * Both operands must carry the same array phantom type. */ hasEvery(array: A, values: ValueRef & { readonly [ValueRefType]?: ReadonlyArray>; }, options?: Readonly<{ caseInsensitive?: boolean; }>): Condition; /** * Checks whether at least one element of `array` satisfies the * nested `condition`. * * The builder passed to `condition` is scoped to the array item type * so that `resource(...)` references fields of the element. * * @example * ```ts * some(resource('comments'), ({ eq, resource }) => * eq(resource('approved'), literal(true))) * ``` */ some>(array: A & { readonly [ValueRefType]?: readonly E[]; }, condition: MatchConditionFn): Condition; /** * Checks whether every element of `array` satisfies the nested * `condition`. * * @example * ```ts * every(resource('items'), ({ gt, resource }) => * gt(resource('price'), literal(0))) * ``` */ every>(array: A & { readonly [ValueRefType]?: readonly E[]; }, condition: MatchConditionFn): Condition; /** * Checks whether no element of `array` satisfies the nested * `condition`. * * @example * ```ts * none(resource('tags'), ({ eq, resource }) => * eq(resource('deleted'), literal(true))) * ``` */ none>(array: A & { readonly [ValueRefType]?: readonly E[]; }, condition: MatchConditionFn): Condition; /** * Combines conditions with logical AND. * All conditions must be satisfied for the result to be `true`. * * @example * ```ts * and(eq(resource('status'), literal('published')), gt(resource('views'), literal(0))) * ``` */ and(...conditions: Condition[]): Condition; /** * Combines conditions with logical OR. * At least one condition must be satisfied for the result to be `true`. * * @example * ```ts * or(eq(resource('role'), literal('admin')), eq(resource('role'), literal('editor'))) * ``` */ or(...conditions: Condition[]): Condition; /** * Negates a condition. * Returns the logical complement of the given condition. * * @example * ```ts * not(eq(resource('deleted'), literal(true))) * ``` */ not(condition: Condition): Condition; } /** * The user-facing function signature for a `matchCondition` rule entry. * * @example * ```ts * matchCondition: ({ eq, resource, literal, and }) => * and(eq(resource('status'), literal('published'))) * ``` */ type MatchConditionFn = Record, Context extends Record = Record> = (builder: MatchConditionBuilder) => Condition; /** * Interface representing a storage mechanism for managing rules and cache. */ interface Storage { /** * Atomically replaces all rules in storage with the provided rules. * * @param rules - Array of rules to set. * @returns A promise that resolves when the rules are set. */ setRules: (rules: GuantrRule[]) => Promise; /** * Retrieves all stored rules. * @returns A promise that resolves to an array of stored rules. */ getRules: () => Promise; /** * Queries rules for a given action and resource. * @param action - The action to filter by. * @param resource - The resource to filter by. * @returns A promise that resolves to an array of matching rules, or an empty array if none exist. */ queryRules: (action: string, resource: string) => Promise; /** * Optional cache mechanism for storing and retrieving data. * If provided, `has` is REQUIRED (no fallback logic). */ cache?: { /** * Sets a value in the cache. * @param key - The key to associate with the value. * @param value - The value to store in the cache. * @returns A promise that resolves when the value is set. */ set: (key: string, value: T) => Promise; /** * Retrieves a value from the cache. * @param key - The key associated with the value. * @returns A promise that resolves to the cached value, or `undefined` if not found. */ get: (key: string) => Promise; /** * Checks if a key exists in the cache. * Required when the cache object is provided. * * @param key - The key to check for existence in the cache. * @returns A promise that resolves to true if the key exists, false otherwise. */ has: (key: string) => Promise; /** * Clears all entries in the cache. * @returns A promise that resolves when the cache is cleared. */ clear: () => Promise; }; } /** * Options for configuring a {@link Guantr} instance. * * The `context` option accepts either a static context object or a function * that returns the context (optionally async). When a plain object is passed, * it is wrapped internally as `() => Promise.resolve(obj)` — context is still * resolved on every check, but the value is the same static object. * * **Important:** The context (and any resource models used with caching) must * be plain JSON-serializable values (numbers, strings, booleans, null, arrays, * and plain objects). Non-plain types are handled as follows: * - `Date`: serialized via `toISOString()`. * - `BigInt`: serialized as a string (e.g. `"1"`). * - `Map` / `Set`: throw a `TypeError` — use plain objects or arrays instead. * - Functions, symbols, and other non-serializable values will cause * `JSON.stringify`-level errors. */ type GuantrOptions = Record> = { context?: Context | (() => Context | Promise); storage?: Storage; /** * Maximum number of rule iterations before the circuit breaker trips. * When exceeded, a `GuantrCircuitBreakerError` is thrown instead of silently returning `false`. * @default 1000 */ maxRuleIterations?: number; }; type GuantrMeta = Record> = { ResourceMap: ResourceMap; Context: Context; }; type GuantrResourceAction = T; type GuantrResourceModel = Record> = T; type GuantrResource = { action: GuantrResourceAction; model: GuantrResourceModel; }; type GuantrResourceMap = Record> = T; /** * Extracts the Context type from a GuantrMeta, or defaults to Record. */ type GuantrContextFromMeta | undefined> = Meta extends GuantrMeta ? C : Record; /** * A rule in the authorization system. * * - When `Meta` is provided (typed mode), `resource`, `action`, and `matchCondition` are * narrowed based on the resource map. * - When `Meta` is omitted (untyped mode), all fields accept plain strings / any condition. */ type GuantrRule | undefined = undefined, ResourceKey extends Meta extends GuantrMeta ? keyof U : string = Meta extends GuantrMeta ? keyof U : string> = Meta extends GuantrMeta ? { resource: ResourceKey; action: ResourceMap[ResourceKey]['action']; matchCondition?: MatchConditionFn> | Condition | null; effect: 'allow' | 'deny'; } : { resource: string; action: string; matchCondition?: MatchConditionFn | Condition | null; effect: 'allow' | 'deny'; }; /** * Extracts leaf-level key paths from a nested object type as dot-notation string * literals. Nested objects are recursed into, while arrays terminate recursion. * * Recursion is limited to **5 levels** of depth to prevent infinite type resolution * on self-referential types. Paths deeper than the limit are silently excluded. * To increase the depth limit, adjust the `Depth` default and the corresponding * {@link Decrement} mapping. * * @example * ```ts * type Model = { user: { name: string; address: { city: string } }; tags: string[] }; * type Keys = LeafKeys; * // "user.name" | "user.address.city" | "tags" * ``` */ type LeafKeys, TypeFilter = any, Prefix extends string = '', Depth extends number = 5> = Depth extends 0 ? never : { [K in keyof Obj]: K extends string | number ? NonNullable extends Record ? NonNullable extends any[] ? TypeFilter extends NonNullable ? `${Prefix}${K}` : never : Extract extends never ? LeafKeys, TypeFilter, `${Prefix}${K}.`, Decrement> : LeafKeys, TypeFilter, `${Prefix}${K}?.`, Decrement> : TypeFilter extends NonNullable ? `${Prefix}${K}` : never : never; }[keyof Obj]; type Decrement = N extends 5 ? 4 : N extends 4 ? 3 : N extends 3 ? 2 : N extends 2 ? 1 : 0; type Value = Depth extends 0 ? never : Path extends `${infer Segment}.${infer Rest}` ? Segment extends `${infer Key}?` ? Key extends keyof Obj ? Value, Rest, Decrement> | undefined : never : Segment extends keyof Obj ? Value> : never : Path extends `${infer Key}?` ? Key extends keyof Obj ? Obj[Key] | undefined : never : Path extends keyof Obj ? Obj[Path] : never; export type { ArrayElementType as A, Condition as C, GuantrMeta as G, InferValueRef as I, LiteralRef as L, MatchConditionBuilder as M, OperatorNode as O, ResourceRef as R, Storage as S, ValueRef as V, GuantrResourceMap as a, GuantrOptions as b, GuantrContextFromMeta as c, GuantrRule as d, AstNode as e, ContextRef as f, GuantrResource as g, GuantrResourceAction as h, GuantrResourceModel as i, LogicalNode as j, MatchConditionFn as k };