@cullet/erp-core 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/KIT_CONTEXT.md +39 -0
- package/README.md +110 -0
- package/dist/errors/index.d.ts +2 -0
- package/dist/errors/index.js +3 -0
- package/dist/exceptions/validation-field.d.ts +2 -0
- package/dist/exceptions/validation-field.js +2 -0
- package/dist/gate-engine-registry.js +260 -0
- package/dist/gate-engine-registry.js.map +1 -0
- package/dist/gate-types.d.ts +307 -0
- package/dist/gate-v1-payload.schema.js +677 -0
- package/dist/gate-v1-payload.schema.js.map +1 -0
- package/dist/index.d.ts +88 -0
- package/dist/index.js +153 -0
- package/dist/index.js.map +1 -0
- package/dist/outcome.js +92 -0
- package/dist/outcome.js.map +1 -0
- package/dist/parse-gate-payload.d.ts +136 -0
- package/dist/policies/engines/index.d.ts +3 -0
- package/dist/policies/engines/index.js +2 -0
- package/dist/policies/engines/v1/gate/index.d.ts +115 -0
- package/dist/policies/engines/v1/gate/index.js +84 -0
- package/dist/policies/engines/v1/gate/index.js.map +1 -0
- package/dist/policies/index.d.ts +4 -0
- package/dist/policies/index.js +5 -0
- package/dist/policy-service.d.ts +541 -0
- package/dist/policy-service.js +992 -0
- package/dist/policy-service.js.map +1 -0
- package/dist/validation-code.js +210 -0
- package/dist/validation-code.js.map +1 -0
- package/dist/validation-error.d.ts +686 -0
- package/dist/validation-error.js +757 -0
- package/dist/validation-error.js.map +1 -0
- package/dist/validation-field.d.ts +12 -0
- package/dist/validation-field.js +23 -0
- package/dist/validation-field.js.map +1 -0
- package/meta.json +66 -0
- package/package.json +59 -0
- package/src/core/application/commands/command.ts +28 -0
- package/src/core/application/commands/index.ts +2 -0
- package/src/core/application/commands/requested-by.ts +97 -0
- package/src/core/application/index.ts +31 -0
- package/src/core/application/policy-error-mapper.ts +60 -0
- package/src/core/application/ports/index.ts +14 -0
- package/src/core/application/ports/logger.port.ts +10 -0
- package/src/core/application/ports/metrics.port.ts +9 -0
- package/src/core/application/ports/policy-port.ts +20 -0
- package/src/core/application/ports/repository.port.ts +7 -0
- package/src/core/application/ports/temporal-repository.port.ts +14 -0
- package/src/core/application/ports/tracer.port.ts +16 -0
- package/src/core/application/queries/index.ts +2 -0
- package/src/core/application/queries/query.ts +53 -0
- package/src/core/application/temporal/index.ts +11 -0
- package/src/core/application/temporal/temporal-context.ts +41 -0
- package/src/core/application/temporal/temporal-use-case.ts +41 -0
- package/src/core/application/use-case.ts +24 -0
- package/src/core/config/core-config.instance.ts +14 -0
- package/src/core/config/core-config.ts +87 -0
- package/src/core/config/index.ts +12 -0
- package/src/core/config/policy-reporter.ts +60 -0
- package/src/core/config/silent-policy-reporter.ts +5 -0
- package/src/core/domain/entity.ts +69 -0
- package/src/core/domain/rulesets/entity-ruleset.contracts.ts +16 -0
- package/src/core/domain/rulesets/ruleset-registry.ts +71 -0
- package/src/core/domain/rulesets/ruleset.contracts.ts +15 -0
- package/src/core/domain/rulesets/value-object-ruleset.contracts.ts +13 -0
- package/src/core/domain/temporal/index.ts +18 -0
- package/src/core/domain/temporal/temporal-range.ts +53 -0
- package/src/core/domain/temporal/temporal-snapshot.ts +47 -0
- package/src/core/domain/temporal/transaction-time.ts +60 -0
- package/src/core/domain/temporal/valid-time.ts +57 -0
- package/src/core/domain/value-object.ts +30 -0
- package/src/core/errors/app-error.ts +85 -0
- package/src/core/errors/authentication-error.ts +171 -0
- package/src/core/errors/authorization-error.ts +204 -0
- package/src/core/errors/business-rule-violation-error.ts +28 -0
- package/src/core/errors/conflict-error.ts +246 -0
- package/src/core/errors/error-codes.ts +60 -0
- package/src/core/errors/idempotency-error.ts +372 -0
- package/src/core/errors/index.ts +99 -0
- package/src/core/errors/integration-error.ts +157 -0
- package/src/core/errors/legacy-incompatible-error.ts +26 -0
- package/src/core/errors/not-found-error.ts +27 -0
- package/src/core/errors/serialization-error.ts +233 -0
- package/src/core/errors/temporal-error.ts +145 -0
- package/src/core/errors/types.ts +74 -0
- package/src/core/errors/unexpected-error.ts +22 -0
- package/src/core/errors/utils/index.ts +4 -0
- package/src/core/errors/utils/json-safe.ts +93 -0
- package/src/core/errors/validation-error.ts +34 -0
- package/src/core/exceptions/business-rule-violation-exception.ts +12 -0
- package/src/core/exceptions/domain-exception.ts +9 -0
- package/src/core/exceptions/entity-not-found-exception.ts +12 -0
- package/src/core/exceptions/invalid-state-transition-exception.ts +15 -0
- package/src/core/exceptions/invariant-violation-exception.ts +9 -0
- package/src/core/exceptions/validation-code.ts +39 -0
- package/src/core/exceptions/validation-exception.ts +39 -0
- package/src/core/exceptions/validation-field.ts +32 -0
- package/src/core/index.ts +15 -0
- package/src/core/policies/asof/asof.ts +68 -0
- package/src/core/policies/asof/index.ts +2 -0
- package/src/core/policies/catalog/catalog-types.ts +12 -0
- package/src/core/policies/catalog/catalog.instance.ts +21 -0
- package/src/core/policies/catalog/index.ts +11 -0
- package/src/core/policies/catalog/policy-catalog-entry.ts +220 -0
- package/src/core/policies/catalog/policy-catalog.ts +124 -0
- package/src/core/policies/catalog/policy-key.ts +78 -0
- package/src/core/policies/context/context-builder.ts +391 -0
- package/src/core/policies/context/context-registry.instance.ts +26 -0
- package/src/core/policies/context/context-registry.ts +95 -0
- package/src/core/policies/context/context-resolver.ts +31 -0
- package/src/core/policies/context/context-seed.ts +32 -0
- package/src/core/policies/context/index.ts +21 -0
- package/src/core/policies/context/path.ts +152 -0
- package/src/core/policies/defs/in-memory-policy-definition-repo.ts +73 -0
- package/src/core/policies/defs/index.ts +20 -0
- package/src/core/policies/defs/policy-definition-repository.ts +8 -0
- package/src/core/policies/defs/policy-definition.ts +192 -0
- package/src/core/policies/defs/policy-payload.contracts.ts +13 -0
- package/src/core/policies/defs/policy-scope.ts +53 -0
- package/src/core/policies/defs/policy-semver.ts +83 -0
- package/src/core/policies/engines/compute-engine-registry.ts +57 -0
- package/src/core/policies/engines/compute-evaluator-registry.ts +28 -0
- package/src/core/policies/engines/compute-payload.ts +5 -0
- package/src/core/policies/engines/compute-registry.ts +67 -0
- package/src/core/policies/engines/compute-types.ts +51 -0
- package/src/core/policies/engines/condition-evaluator-reporter.ts +34 -0
- package/src/core/policies/engines/gate-engine-registry.ts +38 -0
- package/src/core/policies/engines/gate-payload.ts +5 -0
- package/src/core/policies/engines/gate-types.ts +63 -0
- package/src/core/policies/engines/index.ts +48 -0
- package/src/core/policies/engines/parse-compute-payload.ts +71 -0
- package/src/core/policies/engines/parse-gate-payload.ts +68 -0
- package/src/core/policies/engines/v1/compute/compute-engine-v1.ts +55 -0
- package/src/core/policies/engines/v1/compute/compute-payload.schema.ts +75 -0
- package/src/core/policies/engines/v1/compute/index.ts +12 -0
- package/src/core/policies/engines/v1/compute/resolve-decision-table-v1.ts +54 -0
- package/src/core/policies/engines/v1/condition-evaluator.ts +592 -0
- package/src/core/policies/engines/v1/condition-schema.ts +50 -0
- package/src/core/policies/engines/v1/condition-types.ts +41 -0
- package/src/core/policies/engines/v1/gate/gate-engine-v1.ts +157 -0
- package/src/core/policies/engines/v1/gate/gate-types-v1.ts +12 -0
- package/src/core/policies/engines/v1/gate/gate-v1-payload.schema.ts +46 -0
- package/src/core/policies/engines/v1/gate/index.ts +9 -0
- package/src/core/policies/engines/v1/index.ts +13 -0
- package/src/core/policies/index.ts +132 -0
- package/src/core/policies/package/policy-package.ts +17 -0
- package/src/core/policies/policy-ids.ts +60 -0
- package/src/core/policies/resolver/index.ts +1 -0
- package/src/core/policies/resolver/policy-resolver.ts +57 -0
- package/src/core/policies/service/index.ts +10 -0
- package/src/core/policies/service/policy-evaluation-error.ts +148 -0
- package/src/core/policies/service/policy-service.ts +493 -0
- package/src/core/policies/utils/date.ts +7 -0
- package/src/core/policies/utils/hash.ts +90 -0
- package/src/core/policies/utils/index.ts +3 -0
- package/src/core/policies/utils/result.ts +4 -0
- package/src/core/result/outcome.ts +158 -0
- package/src/core/result/result.ts +153 -0
- package/src/core/shared/aggregate-version.ts +11 -0
- package/src/core/shared/hashing.ts +38 -0
- package/src/core/shared/immutable.ts +46 -0
- package/src/core/shared/temporal-guards.ts +22 -0
- package/src/core/versioning/domain-event-contracts.ts +73 -0
- package/src/core/versioning/version.ts +34 -0
- package/src/errors/index.ts +1 -0
- package/src/examples/rulesets/entity/order-creation-rules-v1.ts +31 -0
- package/src/examples/rulesets/entity/order-invariants-v1.ts +48 -0
- package/src/examples/rulesets/entity/order-invariants-v2.ts +28 -0
- package/src/examples/rulesets/entity/order.ts +162 -0
- package/src/examples/rulesets/value-object/cpf-rules-v1.ts +52 -0
- package/src/examples/rulesets/value-object/cpf-rules-v2.ts +27 -0
- package/src/examples/rulesets/value-object/cpf.ts +37 -0
- package/src/examples/rulesets/value-object/customer.ts +67 -0
- package/src/examples/rulesets/value-object/person-name-rules-v1.ts +37 -0
- package/src/examples/rulesets/value-object/person-name-rules-v2.ts +27 -0
- package/src/examples/rulesets/value-object/person-name.ts +39 -0
- package/src/exceptions/validation-field.ts +1 -0
- package/src/index.ts +11 -0
- package/src/policies/engines/index.ts +1 -0
- package/src/policies/engines/v1/gate/index.ts +1 -0
- package/src/policies/index.ts +1 -0
- package/src/version.ts +7 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"gate-v1-payload.schema.js","names":["#initialReporter","#currentReporter","#bridgeToConditionReporter"],"sources":["../src/core/exceptions/domain-exception.ts","../src/core/exceptions/invariant-violation-exception.ts","../src/core/shared/temporal-guards.ts","../src/core/config/silent-policy-reporter.ts","../src/core/config/core-config.ts","../src/core/config/core-config.instance.ts","../src/core/result/result.ts","../src/core/policies/utils/date.ts","../src/core/policies/context/path.ts","../src/core/policies/engines/v1/condition-schema.ts","../src/core/policies/engines/v1/condition-evaluator.ts","../src/core/policies/engines/v1/gate/gate-v1-payload.schema.ts"],"sourcesContent":["abstract class DomainException extends Error {\n constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n this.name = new.target.name;\n }\n}\n\nexport { DomainException };\n","import { DomainException } from \"./domain-exception\";\n\nclass InvariantViolationException extends DomainException {\n constructor(message: string) {\n super(message);\n }\n}\n\nexport { InvariantViolationException };\n","import { InvariantViolationException } from \"../exceptions/invariant-violation-exception\";\n\nfunction isValidDate(value: unknown): value is Date {\n return value instanceof Date && !Number.isNaN(value.getTime());\n}\n\nfunction cloneDate(date: Date): Date {\n return new Date(date.getTime());\n}\n\nfunction assertValidDate(\n fieldName: string,\n value: unknown,\n): asserts value is Date {\n if (!isValidDate(value)) {\n throw new InvariantViolationException(\n `${fieldName} must be a valid Date instance`,\n );\n }\n}\n\nexport { assertValidDate, cloneDate, isValidDate };\n","import type { PolicyReporter } from \"./policy-reporter\";\n\nexport class SilentPolicyReporter implements PolicyReporter {\n report(_event: Parameters<PolicyReporter[\"report\"]>[0]): void {}\n}\n","import type {\n ConditionEvaluationOptions,\n ConditionEvaluatorReporter,\n} from \"../policies/engines/condition-evaluator-reporter\";\nimport type { PolicyEvent, PolicyReporter } from \"./policy-reporter\";\nimport { SilentPolicyReporter } from \"./silent-policy-reporter\";\n\nexport interface CoreObservabilityConfig {\n readonly reporter?: PolicyReporter;\n}\n\nexport interface CoreConfigOptions {\n readonly observability?: CoreObservabilityConfig;\n}\n\nfunction reportSafely(\n policyReporter: PolicyReporter,\n event: PolicyEvent,\n): void {\n try {\n policyReporter.report(event);\n } catch {\n // Falhas de telemetria nao podem interromper o fluxo de dominio.\n }\n}\n\n/**\n * Centraliza a configuracao pura do core sem depender de implementacoes\n * concretas de logging, tracing ou report.\n */\nexport class CoreConfig {\n readonly #initialReporter: PolicyReporter;\n #currentReporter: PolicyReporter;\n\n constructor(options: CoreConfigOptions = {}) {\n const reporter =\n options.observability?.reporter ?? new SilentPolicyReporter();\n this.#initialReporter = reporter;\n this.#currentReporter = reporter;\n }\n\n configure(options: CoreConfigOptions): this {\n const reporter = options.observability?.reporter;\n if (reporter) {\n this.#currentReporter = reporter;\n }\n return this;\n }\n\n // Restores the reporter captured at construction time.\n reset(): this {\n this.#currentReporter = this.#initialReporter;\n return this;\n }\n\n getPolicyReporter(): PolicyReporter {\n return this.#currentReporter;\n }\n\n getConditionEvaluationOptions(\n engineVersion: number,\n ): ConditionEvaluationOptions {\n return {\n reporter: this.#bridgeToConditionReporter(this.#currentReporter),\n engineVersion,\n };\n }\n\n #bridgeToConditionReporter(\n policyReporter: PolicyReporter,\n ): ConditionEvaluatorReporter {\n return {\n warn(report) {\n reportSafely(policyReporter, {\n kind: \"condition-eval\",\n ...report,\n } satisfies PolicyEvent);\n },\n error(report) {\n reportSafely(policyReporter, {\n kind: \"condition-eval\",\n ...report,\n } satisfies PolicyEvent);\n },\n };\n }\n}\n","import { CoreConfig } from \"./core-config\";\nimport { SilentPolicyReporter } from \"./silent-policy-reporter\";\n\n/**\n * Shared instance for the application composition root.\n * Use `new CoreConfig()` for isolated runtimes, tests, or multi-tenant hosts.\n *\n * The default reporter is silent so the core has no runtime logging dependency.\n * Hosts can swap in their own `PolicyReporter` via\n * `coreConfig.configure({ observability: { reporter } })`.\n */\nexport const coreConfig = new CoreConfig({\n observability: { reporter: new SilentPolicyReporter() },\n});\n","/**\n * Represents the outcome of an operation that may succeed or fail.\n * Useful for avoiding excessive exceptions and making error flows explicit.\n */\nexport abstract class Result<T, E> {\n protected constructor() {\n // prevent direct instantiation\n }\n\n /**\n * Creates a success result containing a value.\n */\n static ok<T>(value: T): Result<T, never> {\n return new Ok(value);\n }\n\n /**\n * Creates an error result containing an error object.\n */\n static err<E>(error: E): Result<never, E> {\n return new Err(error);\n }\n\n /**\n * Returns true when this is a success result.\n */\n abstract isOk(): this is Ok<T>;\n\n /**\n * Returns true when this is an error result.\n */\n abstract isErr(): this is Err<E>;\n\n /**\n * Runs a handler based on the result state (similar to pattern matching).\n */\n abstract match<R>(handlers: { ok: (value: T) => R; err: (error: E) => R }): R;\n\n /**\n * Returns the value when this is success, or null when this is an error.\n */\n getOrNull(): T | null {\n return this.match({\n ok: (value) => value,\n err: () => null,\n });\n }\n\n /**\n * Returns the error when this is a failure, or null when this is a success.\n */\n errorOrNull(): E | null {\n return this.match({\n ok: () => null,\n err: (error) => error,\n });\n }\n\n /**\n * Returns the value when this is a success, or throws the error when this is a failure.\n */\n getOrThrow(): T {\n return this.match({\n ok: (value) => value,\n err: (error) => {\n throw error instanceof Error ? error : new Error(String(error));\n },\n });\n }\n\n /**\n * Transforms the success value using the provided function. Keeps the error when this is a failure.\n */\n map<R>(transform: (value: T) => R): Result<R, E> {\n return this.match<Result<R, E>>({\n ok: (value) => Result.ok(transform(value)),\n // TS does not \"see\" variance here; the cast is intentional and safe:\n // Err carries no T, so it can be widened to Result<R, E> safely.\n err: (error) => Result.err(error) as unknown as Result<R, E>,\n });\n }\n\n /**\n * Transforms the error using the provided function. Keeps the value when this is a success.\n */\n mapError<F>(transform: (error: E) => F): Result<T, F> {\n return this.match<Result<T, F>>({\n // Ok carries no E, so it can be widened to Result<T, F>.\n ok: (value) => Result.ok(value) as unknown as Result<T, F>,\n err: (error) => Result.err(transform(error)),\n });\n }\n\n /**\n * Chains another operation that returns a Result when this result is a success.\n */\n flatMap<R>(transform: (value: T) => Result<R, E>): Result<R, E> {\n return this.match<Result<R, E>>({\n ok: (value) => transform(value),\n err: (error) => Result.err(error) as unknown as Result<R, E>,\n });\n }\n}\n\n/**\n * Success variant of Result.\n */\nexport class Ok<T> extends Result<T, never> {\n public readonly value: T;\n\n constructor(value: T) {\n super();\n this.value = value;\n Object.freeze(this);\n }\n\n isOk(): this is Ok<T> {\n return true;\n }\n\n isErr(): this is Err<never> {\n return false;\n }\n\n match<R>(handlers: { ok: (value: T) => R; err: (error: never) => R }): R {\n return handlers.ok(this.value);\n }\n}\n\n/**\n * Error variant of Result.\n */\nexport class Err<E> extends Result<never, E> {\n public readonly error: E;\n\n constructor(error: E) {\n super();\n this.error = error;\n Object.freeze(this);\n }\n\n isOk(): this is Ok<never> {\n return false;\n }\n\n isErr(): this is Err<E> {\n return true;\n }\n\n match<R>(handlers: { ok: (value: never) => R; err: (error: E) => R }): R {\n return handlers.err(this.error);\n }\n}\n","import { isValidDate } from \"../../shared/temporal-guards\";\n\nexport class PolicyDateUtils {\n static isValid(value: Date): boolean {\n return isValidDate(value);\n }\n}\n","/**\n * Utilities for reading/writing values at dot-separated paths\n * in plain objects, e.g. \"installment.dueDate\".\n */\n\nimport { Result } from \"../../result/result\";\n\nexport class PolicyContextPath {\n private static readonly FORBIDDEN_SEGMENTS = new Set([\n \"__proto__\",\n \"prototype\",\n \"constructor\",\n ]);\n\n private static resolve(\n obj: Record<string, unknown>,\n path: string,\n ): Result<\n {\n readonly found: boolean;\n readonly value: unknown;\n },\n string\n > {\n const segmentsResult = PolicyContextPath.parseSegments(path);\n if (segmentsResult.isErr()) {\n return Result.err(segmentsResult.errorOrNull()!);\n }\n\n const segments = segmentsResult.getOrNull()!;\n let current: unknown = obj;\n\n for (const segment of segments) {\n if (\n current === null ||\n current === undefined ||\n typeof current !== \"object\"\n ) {\n return Result.ok({ found: false, value: undefined });\n }\n\n const record = current as Record<string, unknown>;\n if (!Object.prototype.hasOwnProperty.call(record, segment)) {\n return Result.ok({ found: false, value: undefined });\n }\n\n current = record[segment];\n }\n\n return Result.ok({ found: true, value: current });\n }\n\n private static parseSegments(\n path: string,\n ): Result<readonly string[], string> {\n if (path.trim().length === 0) {\n return Result.err(\"Path cannot be empty\");\n }\n\n const segments = path.split(\".\");\n if (segments.some((segment) => segment.length === 0)) {\n return Result.err(`Path \"${path}\" contains an empty segment`);\n }\n\n const forbiddenSegment = segments.find((segment) =>\n PolicyContextPath.FORBIDDEN_SEGMENTS.has(segment),\n );\n if (forbiddenSegment !== undefined) {\n return Result.err(\n `Path \"${path}\" contains forbidden segment \"${forbiddenSegment}\"`,\n );\n }\n\n return Result.ok(segments);\n }\n\n private static isPlainRecord(\n value: unknown,\n ): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n }\n\n static getOrAbsent(\n obj: Record<string, unknown>,\n path: string,\n ): Result<unknown, \"absent\"> {\n const resolvedPath = PolicyContextPath.resolve(obj, path);\n if (resolvedPath.isErr()) {\n return Result.err(\"absent\");\n }\n\n const { found, value } = resolvedPath.getOrNull()!;\n if (!found) {\n return Result.err(\"absent\");\n }\n\n return Result.ok(value);\n }\n\n static has(obj: Record<string, unknown>, path: string): boolean {\n const resolvedPath = PolicyContextPath.resolve(obj, path);\n if (resolvedPath.isErr()) {\n return false;\n }\n\n return resolvedPath.getOrNull()!.found;\n }\n\n static set(\n obj: Record<string, unknown>,\n path: string,\n value: unknown,\n ): Result<void, string> {\n const segmentsResult = PolicyContextPath.parseSegments(path);\n if (segmentsResult.isErr()) {\n return Result.err(segmentsResult.errorOrNull()!);\n }\n\n const segments = segmentsResult.getOrNull()!;\n let current: Record<string, unknown> = obj;\n\n for (let i = 0; i < segments.length - 1; i++) {\n const seg = segments[i];\n const next = current[seg];\n\n if (next === undefined) {\n const container = Object.create(null) as Record<string, unknown>;\n current[seg] = container;\n current = container;\n continue;\n }\n\n if (!PolicyContextPath.isPlainRecord(next)) {\n return Result.err(\n `Cannot create nested path \"${path}\" because \"${segments\n .slice(0, i + 1)\n .join(\".\")}\" already contains a non-plain object`,\n );\n }\n\n current = next;\n }\n\n current[segments[segments.length - 1]] = value;\n return Result.ok(undefined);\n }\n}\n","import { z } from \"zod\";\n\nimport type { ConditionLeafNode, ConditionNode } from \"./condition-types\";\n\n// ─── Shared v1 condition Zod schemas ─────────────────────────────────────────\n// Extracted from gate/v1 so both gate/v1 and compute/v1 can validate\n// condition nodes without either engine depending on the other.\n\nconst conditionOpSchema = z.enum([\n \"eq\",\n \"neq\",\n \"gt\",\n \"gte\",\n \"lt\",\n \"lte\",\n \"in\",\n \"notIn\",\n \"isNull\",\n \"isNotNull\",\n]);\n\nexport const conditionLeafNodeSchema: z.ZodType<ConditionLeafNode> = z\n .object({\n field: z.string().min(1),\n op: conditionOpSchema,\n value: z.unknown(),\n allowNull: z.literal(true).optional(),\n })\n .strict() as z.ZodType<ConditionLeafNode>;\n\nexport const conditionNodeSchema: z.ZodType<ConditionNode> = z.lazy(() =>\n z.union([\n conditionLeafNodeSchema,\n z\n .object({\n and: z.array(conditionNodeSchema).min(1),\n })\n .strict(),\n z\n .object({\n or: z.array(conditionNodeSchema).min(1),\n })\n .strict(),\n z\n .object({\n not: conditionNodeSchema,\n })\n .strict(),\n ]),\n);\n","import { PolicyContextPath } from \"../../context\";\nimport { PolicyDateUtils } from \"../../utils\";\nimport { Result } from \"../../../result/result\";\n\nimport type {\n ConditionAndNode,\n ConditionLeafNode,\n ConditionNode,\n ConditionNotNode,\n ConditionOp,\n ConditionOrNode,\n} from \"./condition-types\";\nimport type {\n ConditionEvaluationOptions,\n ConditionEvaluationReport,\n} from \"../condition-evaluator-reporter\";\nimport type { PolicyContext } from \"../gate-types\";\n\nconst CONDITION_EVAL_THROWN_TAG = \"CONDITION_EVAL_THREW\";\nconst NULLISH_NUMERIC_OPERAND_NOT_ALLOWED_TAG =\n \"NULLISH_NUMERIC_OPERAND_NOT_ALLOWED\";\nconst NULLISH_DATE_OPERAND_NOT_ALLOWED_TAG = \"NULLISH_DATE_OPERAND_NOT_ALLOWED\";\nconst INVALID_DATE_OPERAND_TAG = \"INVALID_DATE_OPERAND\";\nconst EMPTY_OR_CONDITION_TAG = \"EMPTY_OR_CONDITION\";\nconst ISO_8601_UTC_DATE_PATTERN =\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$/;\n\nexport interface ConditionEvaluationTrace {\n readonly conditionPath: string;\n readonly decisiveNode: ConditionNode;\n readonly lastEvaluatedLeaf: ConditionLeafNode;\n readonly lastEvaluatedLeafPath: string;\n readonly lastEvaluatedLeafResult: boolean;\n}\n\nexport interface TracedConditionEvaluation {\n readonly matched: boolean;\n readonly trace: ConditionEvaluationTrace;\n}\n\ntype RelationalOperator = Extract<ConditionOp, \"gt\" | \"gte\" | \"lt\" | \"lte\">;\n\nexport class ConditionEvaluatorV1 {\n constructor(\n private readonly context: PolicyContext,\n private readonly options: ConditionEvaluationOptions,\n ) {}\n\n private static isLeafNode(node: ConditionNode): node is ConditionLeafNode {\n return \"field\" in node && \"op\" in node;\n }\n\n private static isAndNode(node: ConditionNode): node is ConditionAndNode {\n return \"and\" in node;\n }\n\n private static isOrNode(node: ConditionNode): node is ConditionOrNode {\n return \"or\" in node;\n }\n\n private static isNotNode(node: ConditionNode): node is ConditionNotNode {\n return \"not\" in node;\n }\n\n private static isRelationalOperator(\n op: ConditionOp,\n ): op is RelationalOperator {\n return op === \"gt\" || op === \"gte\" || op === \"lt\" || op === \"lte\";\n }\n\n private static describeError(error: unknown): {\n name: string;\n message: string;\n } {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n };\n }\n\n return {\n name: \"NonErrorThrown\",\n message: String(error),\n };\n }\n\n private static buildNullishNumericOperandMessage(\n node: ConditionLeafNode,\n actual: null | undefined,\n ): string {\n const resolvedValue = actual === null ? \"null\" : \"undefined\";\n\n return `${NULLISH_NUMERIC_OPERAND_NOT_ALLOWED_TAG}: \"${node.field}\" resolved to ${resolvedValue} for numeric operator \"${node.op}\"`;\n }\n\n private static buildNullishDateOperandMessage(\n node: ConditionLeafNode,\n actual: null | undefined,\n ): string {\n const resolvedValue = actual === null ? \"null\" : \"undefined\";\n\n return `${NULLISH_DATE_OPERAND_NOT_ALLOWED_TAG}: \"${node.field}\" resolved to ${resolvedValue} for date comparison operator \"${node.op}\"`;\n }\n\n private static buildInvalidDateOperandMessage(\n node: ConditionLeafNode,\n ): string {\n return `${INVALID_DATE_OPERAND_TAG}: \"${node.field}\" with operator \"${node.op}\" requires Date or ISO 8601 UTC string operands`;\n }\n\n private static buildEmptyOrConditionMessage(): string {\n return `${EMPTY_OR_CONDITION_TAG}: OR nodes must contain at least one child condition`;\n }\n\n private static parseComparableDate(\n value: unknown,\n ): Result<Date, string> | null {\n if (value instanceof Date) {\n if (!PolicyDateUtils.isValid(value)) {\n return Result.err(\"Invalid Date instance\");\n }\n\n return Result.ok(value);\n }\n\n if (typeof value !== \"string\" || !ISO_8601_UTC_DATE_PATTERN.test(value)) {\n return null;\n }\n\n const parsed = new Date(value);\n if (!PolicyDateUtils.isValid(parsed) || parsed.toISOString() !== value) {\n return Result.err(\"Invalid ISO 8601 UTC date string\");\n }\n\n return Result.ok(parsed);\n }\n\n private static evaluateRelationalNumbers(\n actual: number,\n op: RelationalOperator,\n expected: number,\n ): boolean {\n switch (op) {\n case \"gt\":\n return actual > expected;\n case \"gte\":\n return actual >= expected;\n case \"lt\":\n return actual < expected;\n case \"lte\":\n return actual <= expected;\n }\n }\n\n private buildReport(params: {\n readonly level: ConditionEvaluationReport[\"level\"];\n readonly tag: ConditionEvaluationReport[\"tag\"];\n readonly message: string;\n readonly details: Readonly<Record<string, unknown>>;\n }): ConditionEvaluationReport {\n return {\n occurredAt: new Date(),\n level: params.level,\n tag: params.tag,\n message: params.message,\n engineVersion: this.options.engineVersion,\n details: params.details,\n };\n }\n\n private conditionEvalErr<TValue>(\n node: ConditionNode,\n error: unknown,\n ): Result<TValue, string> {\n const cause = ConditionEvaluatorV1.describeError(error);\n const message = `${CONDITION_EVAL_THROWN_TAG}: ${cause.name}: ${cause.message}`;\n\n this.options.reporter.error(\n this.buildReport({\n level: \"error\",\n tag: CONDITION_EVAL_THROWN_TAG,\n message,\n details: { node, cause },\n }),\n );\n\n return Result.err(message);\n }\n\n private reportDateOperandError(\n node: ConditionLeafNode,\n actual: unknown,\n ): Result<boolean, string> {\n const message = ConditionEvaluatorV1.buildInvalidDateOperandMessage(node);\n\n this.options.reporter.error(\n this.buildReport({\n level: \"error\",\n tag: INVALID_DATE_OPERAND_TAG,\n message,\n details: {\n field: node.field,\n op: node.op,\n actual,\n expected: node.value,\n node,\n },\n }),\n );\n\n return Result.err(message);\n }\n\n private evaluateDateRelationalNode(\n node: ConditionLeafNode,\n actual: unknown,\n ): Result<boolean, string> | null {\n if (!ConditionEvaluatorV1.isRelationalOperator(node.op)) {\n return null;\n }\n\n const actualDateResult = ConditionEvaluatorV1.parseComparableDate(actual);\n const expectedDateResult = ConditionEvaluatorV1.parseComparableDate(\n node.value,\n );\n\n if (actualDateResult === null && expectedDateResult === null) {\n return null;\n }\n\n const allowsNull = node.allowNull === true;\n\n if (actual === null) {\n if (allowsNull) {\n return Result.ok(false);\n }\n\n const message = ConditionEvaluatorV1.buildNullishDateOperandMessage(\n node,\n actual,\n );\n this.options.reporter.error(\n this.buildReport({\n level: \"error\",\n tag: NULLISH_DATE_OPERAND_NOT_ALLOWED_TAG,\n message,\n details: {\n field: node.field,\n op: node.op,\n actual,\n expected: node.value,\n allowNull: allowsNull,\n node,\n },\n }),\n );\n\n return Result.err(message);\n }\n\n if (actual === undefined) {\n const message = ConditionEvaluatorV1.buildNullishDateOperandMessage(\n node,\n actual,\n );\n this.options.reporter.error(\n this.buildReport({\n level: \"error\",\n tag: NULLISH_DATE_OPERAND_NOT_ALLOWED_TAG,\n message,\n details: {\n field: node.field,\n op: node.op,\n actual,\n expected: node.value,\n allowNull: allowsNull,\n node,\n },\n }),\n );\n\n return Result.err(message);\n }\n\n if (\n actualDateResult === null ||\n actualDateResult.isErr() ||\n expectedDateResult === null ||\n expectedDateResult.isErr()\n ) {\n return this.reportDateOperandError(node, actual);\n }\n\n return Result.ok(\n ConditionEvaluatorV1.evaluateRelationalNumbers(\n actualDateResult.getOrNull()!.getTime(),\n node.op,\n expectedDateResult.getOrNull()!.getTime(),\n ),\n );\n }\n\n private evaluateOperator(\n actual: unknown,\n op: ConditionOp,\n expected: unknown,\n ): boolean {\n switch (op) {\n case \"eq\":\n return actual === expected;\n case \"neq\":\n return actual !== expected;\n case \"gt\":\n return (\n typeof actual === \"number\" &&\n typeof expected === \"number\" &&\n ConditionEvaluatorV1.evaluateRelationalNumbers(actual, op, expected)\n );\n case \"gte\":\n return (\n typeof actual === \"number\" &&\n typeof expected === \"number\" &&\n ConditionEvaluatorV1.evaluateRelationalNumbers(actual, op, expected)\n );\n case \"lt\":\n return (\n typeof actual === \"number\" &&\n typeof expected === \"number\" &&\n ConditionEvaluatorV1.evaluateRelationalNumbers(actual, op, expected)\n );\n case \"lte\":\n return (\n typeof actual === \"number\" &&\n typeof expected === \"number\" &&\n ConditionEvaluatorV1.evaluateRelationalNumbers(actual, op, expected)\n );\n case \"in\":\n return Array.isArray(expected) && expected.includes(actual);\n case \"notIn\":\n return Array.isArray(expected) && !expected.includes(actual);\n case \"isNull\":\n return actual === null;\n case \"isNotNull\":\n return actual !== null && actual !== undefined;\n }\n }\n\n private evaluateNumericRelationalNode(\n node: ConditionLeafNode,\n actual: unknown,\n ): Result<boolean, string> {\n const allowsNull = node.allowNull === true;\n if (actual === undefined || (actual === null && !allowsNull)) {\n const message = ConditionEvaluatorV1.buildNullishNumericOperandMessage(\n node,\n actual as null | undefined,\n );\n\n this.options.reporter.error(\n this.buildReport({\n level: \"error\",\n tag: NULLISH_NUMERIC_OPERAND_NOT_ALLOWED_TAG,\n message,\n details: {\n field: node.field,\n op: node.op,\n actual,\n expected: node.value,\n allowNull: allowsNull,\n node,\n },\n }),\n );\n\n return Result.err(message);\n }\n\n return Result.ok(this.evaluateOperator(actual, node.op, node.value));\n }\n\n private evaluateLeafNode(node: ConditionLeafNode): Result<boolean, string> {\n const actualResult = PolicyContextPath.getOrAbsent(\n this.context,\n node.field,\n );\n if (actualResult.isErr()) {\n this.options.reporter.warn(\n this.buildReport({\n level: \"warn\",\n tag: \"MISSING_CONTEXT_FIELD\",\n message: `MISSING_CONTEXT_FIELD: \"${node.field}\" not found in context`,\n details: { field: node.field, node },\n }),\n );\n\n return Result.err(\n `MISSING_CONTEXT_FIELD: \"${node.field}\" not found in context`,\n );\n }\n\n try {\n const actual = actualResult.getOrThrow();\n if (ConditionEvaluatorV1.isRelationalOperator(node.op)) {\n const dateResult = this.evaluateDateRelationalNode(node, actual);\n if (dateResult !== null) {\n return dateResult;\n }\n\n return this.evaluateNumericRelationalNode(node, actual);\n }\n\n return Result.ok(this.evaluateOperator(actual, node.op, node.value));\n } catch (error) {\n return this.conditionEvalErr(node, error);\n }\n }\n\n private buildTrace(params: {\n readonly conditionPath: string;\n readonly decisiveNode: ConditionNode;\n readonly lastEvaluatedLeaf: ConditionLeafNode;\n readonly lastEvaluatedLeafPath: string;\n readonly lastEvaluatedLeafResult: boolean;\n }): ConditionEvaluationTrace {\n return {\n conditionPath: params.conditionPath,\n decisiveNode: params.decisiveNode,\n lastEvaluatedLeaf: params.lastEvaluatedLeaf,\n lastEvaluatedLeafPath: params.lastEvaluatedLeafPath,\n lastEvaluatedLeafResult: params.lastEvaluatedLeafResult,\n };\n }\n\n private evaluateWithTraceInternal(\n node: ConditionNode,\n path: string,\n ): Result<TracedConditionEvaluation, string> {\n if (ConditionEvaluatorV1.isLeafNode(node)) {\n const leafResult = this.evaluateLeafNode(node);\n if (leafResult.isErr()) {\n return Result.err(leafResult.errorOrNull()!);\n }\n\n const matched = leafResult.getOrNull()!;\n return Result.ok({\n matched,\n trace: this.buildTrace({\n conditionPath: path,\n decisiveNode: node,\n lastEvaluatedLeaf: node,\n lastEvaluatedLeafPath: path,\n lastEvaluatedLeafResult: matched,\n }),\n });\n }\n\n if (ConditionEvaluatorV1.isAndNode(node)) {\n let lastTracedChild: TracedConditionEvaluation | null = null;\n\n for (const [index, child] of node.and.entries()) {\n const childPath = `${path}.and[${index}]`;\n const childResult = this.evaluateWithTraceInternal(child, childPath);\n if (childResult.isErr()) {\n return Result.err(childResult.errorOrNull()!);\n }\n\n const tracedChild = childResult.getOrNull()!;\n lastTracedChild = tracedChild;\n if (!tracedChild.matched) {\n return Result.ok({\n matched: false,\n trace: this.buildTrace({\n conditionPath: childPath,\n decisiveNode: child,\n lastEvaluatedLeaf: tracedChild.trace.lastEvaluatedLeaf,\n lastEvaluatedLeafPath: tracedChild.trace.lastEvaluatedLeafPath,\n lastEvaluatedLeafResult:\n tracedChild.trace.lastEvaluatedLeafResult,\n }),\n });\n }\n }\n\n return Result.ok({\n matched: true,\n trace: lastTracedChild!.trace,\n });\n }\n\n if (ConditionEvaluatorV1.isOrNode(node)) {\n let lastTrace: ConditionEvaluationTrace | null = null;\n\n for (const [index, child] of node.or.entries()) {\n const childResult = this.evaluateWithTraceInternal(\n child,\n `${path}.or[${index}]`,\n );\n if (childResult.isErr()) {\n return Result.err(childResult.errorOrNull()!);\n }\n\n const tracedChild = childResult.getOrNull()!;\n lastTrace = tracedChild.trace;\n if (tracedChild.matched) {\n return Result.ok({\n matched: true,\n trace: tracedChild.trace,\n });\n }\n }\n\n if (lastTrace === null) {\n return Result.err(ConditionEvaluatorV1.buildEmptyOrConditionMessage());\n }\n\n return Result.ok({ matched: false, trace: lastTrace! });\n }\n\n if (ConditionEvaluatorV1.isNotNode(node)) {\n const childPath = `${path}.not`;\n const childResult = this.evaluateWithTraceInternal(node.not, childPath);\n if (childResult.isErr()) {\n return Result.err(childResult.errorOrNull()!);\n }\n\n const tracedChild = childResult.getOrNull()!;\n return Result.ok({\n matched: !tracedChild.matched,\n trace: this.buildTrace({\n conditionPath: path,\n decisiveNode: node,\n lastEvaluatedLeaf: tracedChild.trace.lastEvaluatedLeaf,\n lastEvaluatedLeafPath: tracedChild.trace.lastEvaluatedLeafPath,\n lastEvaluatedLeafResult: tracedChild.trace.lastEvaluatedLeafResult,\n }),\n });\n }\n\n return this.conditionEvalErr(\n node,\n new TypeError(\"Invalid condition node shape\"),\n );\n }\n\n evaluate(node: ConditionNode): Result<boolean, string> {\n try {\n const result = this.evaluateWithTraceInternal(node, \"$\");\n if (result.isErr()) {\n return Result.err(result.errorOrNull()!);\n }\n\n return Result.ok(result.getOrNull()!.matched);\n } catch (error) {\n return this.conditionEvalErr(node, error);\n }\n }\n\n evaluateWithTrace(\n node: ConditionNode,\n ): Result<TracedConditionEvaluation, string> {\n try {\n return this.evaluateWithTraceInternal(node, \"$\");\n } catch (error) {\n return this.conditionEvalErr(node, error);\n }\n }\n\n static extractFields(node: ConditionNode): string[] {\n if (ConditionEvaluatorV1.isLeafNode(node)) {\n return [node.field];\n }\n\n if (ConditionEvaluatorV1.isAndNode(node)) {\n return node.and.flatMap((child) =>\n ConditionEvaluatorV1.extractFields(child),\n );\n }\n\n if (ConditionEvaluatorV1.isOrNode(node)) {\n return node.or.flatMap((child) =>\n ConditionEvaluatorV1.extractFields(child),\n );\n }\n\n if (ConditionEvaluatorV1.isNotNode(node)) {\n return ConditionEvaluatorV1.extractFields(node.not);\n }\n\n return [];\n }\n}\n","import { z } from \"zod\";\n\nimport { Result } from \"../../../../result/result\";\n\nimport type { GatePayloadV1 } from \"./gate-types-v1\";\nimport {\n conditionLeafNodeSchema,\n conditionNodeSchema,\n} from \"../condition-schema\";\n\n// Re-export so gate/v1 public API remains unchanged.\nexport { conditionLeafNodeSchema, conditionNodeSchema };\n\nexport class GatePayloadSchemaV1 {\n static readonly schema = z.union([\n z\n .object({\n condition: conditionNodeSchema,\n })\n .strict(),\n z\n .object({\n allowIf: conditionNodeSchema,\n defaultOutcome: z.enum([\"ALLOW\", \"DENY\"]),\n })\n .strict(),\n ]);\n\n static parse(payload: unknown): Result<GatePayloadV1, string> {\n const parsed = GatePayloadSchemaV1.schema.safeParse(payload);\n if (!parsed.success) {\n const details = parsed.error.issues\n .map((issue) => {\n const path = issue.path.join(\".\");\n return path.length > 0 ? `${path}: ${issue.message}` : issue.message;\n })\n .join(\"; \");\n\n return Result.err(`Invalid gate payload: ${details}`);\n }\n\n return Result.ok(parsed.data as GatePayloadV1);\n }\n}\n\nexport const gatePayloadSchema = GatePayloadSchemaV1.schema;\n"],"mappings":";;AAAA,IAAe,kBAAf,cAAuC,MAAM;CAC3C,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,OAAO,eAAe,MAAM,IAAI,OAAO,SAAS;EAChD,KAAK,OAAO,IAAI,OAAO;CACzB;AACF;;;ACJA,IAAM,8BAAN,cAA0C,gBAAgB;CACxD,YAAY,SAAiB;EAC3B,MAAM,OAAO;CACf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,OAAO,CAAC,KAAK,KAAK;EAGpB,IAAI,qBAAqB,UAAU,IAAI,GACrC,OAAO,KAAK,IAAI,SAAS,UACvB,qBAAqB,cAAc,KAAK,CAC1C;EAGF,IAAI,qBAAqB,SAAS,IAAI,GACpC,OAAO,KAAK,GAAG,SAAS,UACtB,qBAAqB,cAAc,KAAK,CAC1C;EAGF,IAAI,qBAAqB,UAAU,IAAI,GACrC,OAAO,qBAAqB,cAAc,KAAK,GAAG;EAGpD,OAAO,CAAC;CACV;AACF;;;AClkBA,IAAa,sBAAb,MAAa,oBAAoB;;gBACN,EAAE,MAAM,CAC/B,EACG,OAAO,EACN,WAAW,oBACb,CAAC,EACA,OAAO,GACV,EACG,OAAO;GACN,SAAS;GACT,gBAAgB,EAAE,KAAK,CAAC,SAAS,MAAM,CAAC;EAC1C,CAAC,EACA,OAAO,CACZ,CAAC;;CAED,OAAO,MAAM,SAAiD;EAC5D,MAAM,SAAS,oBAAoB,OAAO,UAAU,OAAO;EAC3D,IAAI,CAAC,OAAO,SAAS;GACnB,MAAM,UAAU,OAAO,MAAM,OAC1B,KAAK,UAAU;IACd,MAAM,OAAO,MAAM,KAAK,KAAK,GAAG;IAChC,OAAO,KAAK,SAAS,IAAI,GAAG,KAAK,IAAI,MAAM,YAAY,MAAM;GAC/D,CAAC,EACA,KAAK,IAAI;GAEZ,OAAO,OAAO,IAAI,yBAAyB,SAAS;EACtD;EAEA,OAAO,OAAO,GAAG,OAAO,IAAqB;CAC/C;AACF;AAEA,MAAa,oBAAoB,oBAAoB"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { $ as ErrorCodes, A as IdempotencyPayloadMismatchError, B as UniqueConstraintViolation, C as IntegrationErrorMetadata, D as IdempotencyFailureKind, E as IdempotencyErrorMetadata, F as AlreadyExistsError, G as AuthorizationErrorMetadata, H as translateUniqueViolationToDuplicate, I as ConflictError, J as AuthenticationError, K as AuthorizationErrorReason, L as ConflictErrorMetadata, M as payloadHash, N as sha256Hex, O as IdempotencyInProgressError, P as stableStringify, Q as assertJsonSafeMetadata, R as ConflictKind, S as IntegrationError, T as IdempotencyError, U as BusinessRuleViolationError, V as UniqueConstraintViolationError, W as AuthorizationError, X as AuthenticationErrorReason, Y as AuthenticationErrorMetadata, Z as AppError, _ as SerializationMessages, a as TemporalError, at as JsonSafeValue, b as NotFoundError, c as TemporalPrecision, d as SerializationCodes, et as serializationErrorCode, f as SerializationDirection, g as SerializationInError, h as SerializationFailureCategory, i as NotYetValidError, it as JsonSafeRecord, j as IdempotencyReplayNotSupportedError, k as IdempotencyKeyMissingError, l as evaluateTemporalWindow, m as SerializationErrorMetadata, n as UnexpectedError, nt as ErrorSeverity, o as TemporalErrorMetadata, p as SerializationError, q as AuthorizationRequirement, r as ExpiredError, rt as JsonSafePrimitive, s as TemporalKind, t as ValidationError, tt as AppErrorOptions, u as SerializationBoundary, v as SerializationOutError, w as IntegrationErrorReason, x as LegacyIncompatibleError, y as safePreview, z as DuplicateError } from "./validation-error.js";
|
|
2
|
+
import { t as ValidationField } from "./validation-field.js";
|
|
3
|
+
import { A as ConditionEvaluationReport, C as TenantId, D as asTenantId, E as asSchoolId, F as Ok, I as Result, M as ConditionEvaluationReportTag, N as ConditionEvaluatorReporter, O as ConditionEvaluationCause, P as Err, S as SchoolId, T as asPolicyDefinitionId, _ as CoreConfigOptions, a as GateTraceNodeSnapshot, b as PolicyDecisionId, c as PolicyViolation, g as CoreConfig, h as Outcome, i as GateTraceLeafSnapshot, j as ConditionEvaluationReportLevel, k as ConditionEvaluationOptions, l as VersionedGateEngine, m as CommonOutcomeStatus, n as GateOutcomeData, o as GateViolationTrace, r as GateStatus, s as PolicyContext, t as GateOutcome, u as GatePayload, v as CoreObservabilityConfig, w as asPolicyDecisionId, x as PolicyDefinitionId } from "./gate-types.js";
|
|
4
|
+
import { A as FindCandidatesParams, B as PolicyKey, C as ContextSeed, D as InMemoryPolicyDefinitionRepository, E as PolicyPackage, F as PolicyScope, G as PolicyHashing, H as PolicyKind, I as PolicyScopeMatcher, K as coreConfig, L as ScopeChain, M as PolicyDefinition, N as PolicyDefinitionProps, O as BasePolicyDefinitionProps, P as PolicyDefinitionStatus, R as PolicyCatalog, S as ContextValueResolver, T as PolicyCatalogFactory, U as PolicyOwner, V as AsOfSource, W as PolicyScopeLevel, _ as ContextResolverRegistry, a as PolicyServiceOptions, b as ContextResolverResilienceOptions, c as PolicyEvaluationErrors, d as PolicyAsOfResolver, f as PolicyContextPath, g as PolicyContextBuilderOptions, h as PolicyContextBuilder, i as PolicyService, j as GatePolicyDefinitionProps, k as ComputePolicyDefinitionProps, l as PolicyResolver, m as registerNamespacedContextResolvers, n as PolicyDecision, o as PolicyServiceParams, p as contextResolverRegistry, r as PolicyEvaluationResult, s as PolicyEvaluationError, t as EvaluateInput, u as DeriveAsOfOptions, v as registerNamespacedContextResolversIn, w as ContextSeedValidator, x as ContextResolverRetryOptions, y as ContextResolverCircuitBreakerOptions, z as PolicyCatalogEntryProps } from "./policy-service.js";
|
|
5
|
+
import { a as ComputePayloadParserRegistry, c as ComputeRegistry, d as ComputeEvaluator, f as ComputeEvaluatorRegistration, g as VersionedComputeEngine, h as ComputeStatus, l as ComputeEngineRegistry, m as ComputeOutcomeData, o as ComputePayloadParsers, p as ComputeOutcome, r as GatePayloadParsers, s as GateEngineRegistry, u as ComputeEvaluatorRegistry } from "./parse-gate-payload.js";
|
|
6
|
+
|
|
7
|
+
//#region src/core/versioning/version.d.ts
|
|
8
|
+
type ContractVersion = `${number}.${number}`;
|
|
9
|
+
//#endregion
|
|
10
|
+
//#region src/core/application/ports/logger.port.d.ts
|
|
11
|
+
type LogPayload = Record<string, unknown>;
|
|
12
|
+
interface LoggerPort {
|
|
13
|
+
debug(message: string, payload?: LogPayload): void;
|
|
14
|
+
info(message: string, payload?: LogPayload): void;
|
|
15
|
+
warn(message: string, payload?: LogPayload): void;
|
|
16
|
+
error(message: string, payload?: LogPayload): void;
|
|
17
|
+
}
|
|
18
|
+
//#endregion
|
|
19
|
+
//#region src/core/application/ports/metrics.port.d.ts
|
|
20
|
+
type MetricLabels = Readonly<Record<string, string | number | boolean>>;
|
|
21
|
+
interface MetricsPort {
|
|
22
|
+
counter(name: string, value: number, labels?: MetricLabels): void;
|
|
23
|
+
gauge(name: string, value: number, labels?: MetricLabels): void;
|
|
24
|
+
histogram(name: string, value: number, labels?: MetricLabels): void;
|
|
25
|
+
}
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region src/core/shared/immutable.d.ts
|
|
28
|
+
type PrimitiveValue = bigint | boolean | null | number | string | symbol | undefined;
|
|
29
|
+
type DeepReadonly<T> = T extends PrimitiveValue | Date ? T : T extends readonly (infer TItem)[] ? readonly DeepReadonly<TItem>[] : { readonly [TKey in keyof T]: DeepReadonly<T[TKey]> };
|
|
30
|
+
//#endregion
|
|
31
|
+
//#region src/core/application/ports/tracer.port.d.ts
|
|
32
|
+
type TraceAttributeValue = string | number | boolean;
|
|
33
|
+
interface TraceSpan {
|
|
34
|
+
setAttribute(key: string, value: TraceAttributeValue): void;
|
|
35
|
+
recordException(error: unknown): void;
|
|
36
|
+
end(): void;
|
|
37
|
+
}
|
|
38
|
+
interface TracerPort {
|
|
39
|
+
startSpan(name: string, attributes?: Record<string, TraceAttributeValue>): TraceSpan;
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
//#region src/core/application/policy-error-mapper.d.ts
|
|
43
|
+
declare function mapPolicyEvaluationError(err: PolicyEvaluationError): AppError;
|
|
44
|
+
//#endregion
|
|
45
|
+
//#region src/core/domain/entity.d.ts
|
|
46
|
+
interface EntityState<TIdentifier> {
|
|
47
|
+
readonly id: TIdentifier;
|
|
48
|
+
readonly createdAt: Date;
|
|
49
|
+
readonly updatedAt: Date;
|
|
50
|
+
readonly aggregateVersion: number;
|
|
51
|
+
}
|
|
52
|
+
declare abstract class Entity<TIdentifier> {
|
|
53
|
+
static readonly CONTRACT_VERSION: ContractVersion;
|
|
54
|
+
private readonly _id;
|
|
55
|
+
private readonly _createdAt;
|
|
56
|
+
private _updatedAt;
|
|
57
|
+
private _aggregateVersion;
|
|
58
|
+
protected constructor(state: EntityState<TIdentifier>);
|
|
59
|
+
get id(): TIdentifier;
|
|
60
|
+
get createdAt(): Date;
|
|
61
|
+
get updatedAt(): Date;
|
|
62
|
+
get aggregateVersion(): number;
|
|
63
|
+
get contractVersion(): ContractVersion;
|
|
64
|
+
protected markAsModified(updatedAt?: Date): number;
|
|
65
|
+
}
|
|
66
|
+
//#endregion
|
|
67
|
+
//#region src/core/domain/value-object.d.ts
|
|
68
|
+
declare abstract class ValueObject<T, P> {
|
|
69
|
+
static readonly CONTRACT_VERSION: ContractVersion;
|
|
70
|
+
readonly value: DeepReadonly<T>;
|
|
71
|
+
protected constructor(value: T);
|
|
72
|
+
get contractVersion(): ContractVersion;
|
|
73
|
+
protected finalize(): void;
|
|
74
|
+
toJSON(): P;
|
|
75
|
+
abstract equals(other: this): boolean;
|
|
76
|
+
abstract toPrimitive(): P;
|
|
77
|
+
}
|
|
78
|
+
//#endregion
|
|
79
|
+
//#region src/index.d.ts
|
|
80
|
+
declare const ERP_CORE_NAME = "erp-core";
|
|
81
|
+
declare const ERP_CORE_VERSION = "1.0.0";
|
|
82
|
+
declare const erpCoreRelease: {
|
|
83
|
+
readonly name: "erp-core";
|
|
84
|
+
readonly version: "1.0.0";
|
|
85
|
+
};
|
|
86
|
+
//#endregion
|
|
87
|
+
export { AlreadyExistsError, AppError, AppErrorOptions, AsOfSource, AuthenticationError, AuthenticationErrorMetadata, AuthenticationErrorReason, AuthorizationError, AuthorizationErrorMetadata, AuthorizationErrorReason, AuthorizationRequirement, BasePolicyDefinitionProps, BusinessRuleViolationError, CommonOutcomeStatus, ComputeEngineRegistry, ComputeEvaluator, ComputeEvaluatorRegistration, ComputeEvaluatorRegistry, ComputeOutcome, ComputeOutcomeData, ComputePayloadParserRegistry, ComputePayloadParsers, ComputePolicyDefinitionProps, ComputeRegistry, ComputeStatus, ConditionEvaluationCause, ConditionEvaluationOptions, ConditionEvaluationReport, ConditionEvaluationReportLevel, ConditionEvaluationReportTag, ConditionEvaluatorReporter, ConflictError, ConflictErrorMetadata, ConflictKind, ContextResolverCircuitBreakerOptions, ContextResolverRegistry, ContextResolverResilienceOptions, ContextResolverRetryOptions, ContextSeed, ContextSeedValidator, ContextValueResolver, CoreConfig, CoreConfigOptions, CoreObservabilityConfig, type DeepReadonly, DeriveAsOfOptions, SerializationInError as DeserializationError, SerializationInError, DuplicateError, ERP_CORE_NAME, ERP_CORE_VERSION, Entity, type EntityState, Err, ErrorCodes, ErrorSeverity, EvaluateInput, ExpiredError, TemporalErrorMetadata as ExpiredErrorMetadata, TemporalErrorMetadata, TemporalPrecision as ExpiredErrorPrecision, TemporalPrecision, FindCandidatesParams, GateEngineRegistry, GateOutcome, GateOutcomeData, GatePayload, GatePayloadParsers, GatePolicyDefinitionProps, GateStatus, GateTraceLeafSnapshot, GateTraceNodeSnapshot, GateViolationTrace, IdempotencyError, IdempotencyErrorMetadata, IdempotencyFailureKind, IdempotencyInProgressError, IdempotencyKeyMissingError, IdempotencyPayloadMismatchError, IdempotencyReplayNotSupportedError, InMemoryPolicyDefinitionRepository, IntegrationError, IntegrationErrorMetadata, IntegrationErrorReason, JsonSafePrimitive, JsonSafeRecord, JsonSafeValue, LegacyIncompatibleError, type LogPayload, type LoggerPort, type MetricLabels, type MetricsPort, NotFoundError, NotYetValidError, Ok, Outcome, PolicyAsOfResolver, PolicyCatalog, PolicyCatalogEntryProps, PolicyCatalogFactory, PolicyContext, PolicyContextBuilder, PolicyContextBuilderOptions, PolicyContextPath, PolicyDecision, PolicyDecisionId, PolicyDefinition, PolicyDefinitionId, PolicyDefinitionProps, PolicyDefinitionStatus, PolicyEvaluationError, PolicyEvaluationErrors, PolicyEvaluationResult, PolicyHashing, PolicyKey, PolicyKind, PolicyOwner, PolicyPackage, PolicyResolver, PolicyScope, PolicyScopeLevel, PolicyScopeMatcher, PolicyService, PolicyServiceOptions, PolicyServiceParams, PolicyViolation, Result, SchoolId, ScopeChain, SerializationBoundary, SerializationCodes, SerializationDirection, SerializationError, SerializationErrorMetadata, SerializationFailureCategory, SerializationMessages, SerializationOutError, TemporalError, TemporalKind, TenantId, type TraceAttributeValue, type TraceSpan, type TracerPort, UnexpectedError, UniqueConstraintViolation, UniqueConstraintViolationError, ValidationError, ValidationField, ValueObject, VersionedComputeEngine, VersionedGateEngine, asPolicyDecisionId, asPolicyDefinitionId, asSchoolId, asTenantId, assertJsonSafeMetadata, contextResolverRegistry, coreConfig, erpCoreRelease, evaluateTemporalWindow, mapPolicyEvaluationError, payloadHash, registerNamespacedContextResolvers, registerNamespacedContextResolversIn, safePreview, serializationErrorCode, sha256Hex, stableStringify, translateUniqueViolationToDuplicate };
|
|
88
|
+
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { a as stableStringify, c as ErrorCodes, i as sha256Hex, l as serializationErrorCode, n as UnexpectedError, o as AppError, r as payloadHash, s as assertJsonSafeMetadata } from "./validation-code.js";
|
|
2
|
+
import { C as UniqueConstraintViolationError, D as AuthenticationError, E as AuthorizationError, S as DuplicateError, T as BusinessRuleViolationError, _ as IdempotencyKeyMissingError, a as evaluateTemporalWindow, b as AlreadyExistsError, c as SerializationInError, d as safePreview, f as NotFoundError, g as IdempotencyInProgressError, h as IdempotencyError, i as TemporalError, l as SerializationMessages, m as IntegrationError, n as ExpiredError, o as SerializationCodes, p as LegacyIncompatibleError, r as NotYetValidError, s as SerializationError, t as ValidationError, u as SerializationOutError, v as IdempotencyPayloadMismatchError, w as translateUniqueViolationToDuplicate, x as ConflictError, y as IdempotencyReplayNotSupportedError } from "./validation-error.js";
|
|
3
|
+
import { t as ValidationField } from "./validation-field.js";
|
|
4
|
+
import { c as Ok, d as CoreConfig, g as InvariantViolationException, l as Result, m as cloneDate, o as PolicyContextPath, p as assertValidDate, s as Err, u as coreConfig } from "./gate-v1-payload.schema.js";
|
|
5
|
+
import { t as Outcome } from "./outcome.js";
|
|
6
|
+
import { _ as asPolicyDecisionId, a as ContextSeedValidator, b as asTenantId, c as ContextResolverRegistry, d as PolicyDefinition, f as InMemoryPolicyDefinitionRepository, g as PolicyCatalog, h as PolicyCatalogFactory, i as PolicyAsOfResolver, l as registerNamespacedContextResolversIn, m as PolicyKey, n as PolicyEvaluationErrors, o as contextResolverRegistry, p as PolicyScopeMatcher, r as PolicyResolver, s as registerNamespacedContextResolvers, t as PolicyService, u as PolicyContextBuilder, v as asPolicyDefinitionId, x as PolicyHashing, y as asSchoolId } from "./policy-service.js";
|
|
7
|
+
import { a as ComputeEvaluatorRegistry, c as ComputePayloadParsers, i as ComputeRegistry, o as ComputeEngineRegistry, r as GatePayloadParsers, s as ComputePayloadParserRegistry, t as GateEngineRegistry } from "./gate-engine-registry.js";
|
|
8
|
+
//#region src/version.ts
|
|
9
|
+
const version$1 = "1.0.0";
|
|
10
|
+
//#endregion
|
|
11
|
+
//#region src/core/application/policy-error-mapper.ts
|
|
12
|
+
function mapPolicyEvaluationError(err) {
|
|
13
|
+
switch (err.kind) {
|
|
14
|
+
case "INVALID_CONTEXT": return new BusinessRuleViolationError(`policy.${err.stage.toLowerCase()}`, err.message, {
|
|
15
|
+
policyKey: err.policyKey,
|
|
16
|
+
stage: err.stage
|
|
17
|
+
}, { cause: err.cause });
|
|
18
|
+
case "INVALID_POLICY_KEY": return new BusinessRuleViolationError("policy.invalid_key", err.message, { rawPolicyKey: err.rawPolicyKey }, { cause: err.cause });
|
|
19
|
+
case "POLICY_NOT_FOUND": return new NotFoundError("Policy", { policyKey: err.policyKey }, { cause: err.cause });
|
|
20
|
+
case "POLICY_DEFINITION_NOT_FOUND": return new NotFoundError("PolicyDefinition", {
|
|
21
|
+
policyKey: err.policyKey,
|
|
22
|
+
contextVersion: err.contextVersion,
|
|
23
|
+
asOf: err.asOf.toISOString()
|
|
24
|
+
}, { cause: err.cause });
|
|
25
|
+
case "POLICY_VARIANT_NOT_FOUND": return new NotFoundError("PolicyVariant", {
|
|
26
|
+
policyKey: err.policyKey,
|
|
27
|
+
policyKind: err.policyKind,
|
|
28
|
+
payloadSchemaVersion: err.payloadSchemaVersion
|
|
29
|
+
}, { cause: err.cause });
|
|
30
|
+
case "ENGINE_FAILURE": return new UnexpectedError(err.message, err.cause, { metadata: {
|
|
31
|
+
policyKey: err.policyKey,
|
|
32
|
+
engine: err.engine,
|
|
33
|
+
engineVersion: err.engineVersion
|
|
34
|
+
} });
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
//#endregion
|
|
38
|
+
//#region src/core/shared/aggregate-version.ts
|
|
39
|
+
function assertValidAggregateVersion(aggregateVersion) {
|
|
40
|
+
if (!Number.isInteger(aggregateVersion) || aggregateVersion < 0) throw new InvariantViolationException(`aggregateVersion must be a non-negative integer. Received: ${aggregateVersion}`);
|
|
41
|
+
}
|
|
42
|
+
//#endregion
|
|
43
|
+
//#region src/core/versioning/version.ts
|
|
44
|
+
const CONTRACT_VERSION_PROPERTY = "CONTRACT_VERSION";
|
|
45
|
+
const CONTRACT_VERSION_PATTERN = /^\d+\.\d+$/;
|
|
46
|
+
function version(contractVersion) {
|
|
47
|
+
if (!CONTRACT_VERSION_PATTERN.test(contractVersion)) throw new TypeError(`Invalid contract version "${contractVersion}". Expected MAJOR.MINOR.`);
|
|
48
|
+
return (target) => {
|
|
49
|
+
Object.defineProperty(target, CONTRACT_VERSION_PROPERTY, {
|
|
50
|
+
value: contractVersion,
|
|
51
|
+
writable: false,
|
|
52
|
+
configurable: false,
|
|
53
|
+
enumerable: false
|
|
54
|
+
});
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
//#endregion
|
|
58
|
+
//#region \0@oxc-project+runtime@0.132.0/helpers/decorate.js
|
|
59
|
+
function __decorate(decorators, target, key, desc) {
|
|
60
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
61
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
62
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
63
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
64
|
+
}
|
|
65
|
+
//#endregion
|
|
66
|
+
//#region src/core/domain/entity.ts
|
|
67
|
+
var _Entity;
|
|
68
|
+
let Entity = class Entity {
|
|
69
|
+
static {
|
|
70
|
+
_Entity = this;
|
|
71
|
+
}
|
|
72
|
+
constructor(state) {
|
|
73
|
+
assertValidDate("createdAt", state.createdAt);
|
|
74
|
+
assertValidDate("updatedAt", state.updatedAt);
|
|
75
|
+
assertValidAggregateVersion(state.aggregateVersion);
|
|
76
|
+
if (state.updatedAt.getTime() < state.createdAt.getTime()) throw new InvariantViolationException("updatedAt cannot be earlier than createdAt");
|
|
77
|
+
this._id = state.id;
|
|
78
|
+
this._createdAt = cloneDate(state.createdAt);
|
|
79
|
+
this._updatedAt = cloneDate(state.updatedAt);
|
|
80
|
+
this._aggregateVersion = state.aggregateVersion;
|
|
81
|
+
}
|
|
82
|
+
get id() {
|
|
83
|
+
return this._id;
|
|
84
|
+
}
|
|
85
|
+
get createdAt() {
|
|
86
|
+
return cloneDate(this._createdAt);
|
|
87
|
+
}
|
|
88
|
+
get updatedAt() {
|
|
89
|
+
return cloneDate(this._updatedAt);
|
|
90
|
+
}
|
|
91
|
+
get aggregateVersion() {
|
|
92
|
+
return this._aggregateVersion;
|
|
93
|
+
}
|
|
94
|
+
get contractVersion() {
|
|
95
|
+
return _Entity.CONTRACT_VERSION;
|
|
96
|
+
}
|
|
97
|
+
markAsModified(updatedAt = /* @__PURE__ */ new Date()) {
|
|
98
|
+
assertValidDate("updatedAt", updatedAt);
|
|
99
|
+
this._updatedAt = cloneDate(updatedAt);
|
|
100
|
+
this._aggregateVersion += 1;
|
|
101
|
+
return this._aggregateVersion;
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
Entity = _Entity = __decorate([version("1.0")], Entity);
|
|
105
|
+
//#endregion
|
|
106
|
+
//#region src/core/shared/immutable.ts
|
|
107
|
+
function deepFreeze(value) {
|
|
108
|
+
if (typeof value !== "object" || value === null || value instanceof Date) return value;
|
|
109
|
+
if (Array.isArray(value)) {
|
|
110
|
+
for (const item of value) deepFreeze(item);
|
|
111
|
+
return Object.freeze(value);
|
|
112
|
+
}
|
|
113
|
+
const objectValue = value;
|
|
114
|
+
for (const propertyKey of Reflect.ownKeys(objectValue)) deepFreeze(objectValue[propertyKey]);
|
|
115
|
+
return Object.freeze(value);
|
|
116
|
+
}
|
|
117
|
+
function makeImmutable(value) {
|
|
118
|
+
if (typeof value !== "object" || value === null) return value;
|
|
119
|
+
return deepFreeze(structuredClone(value));
|
|
120
|
+
}
|
|
121
|
+
//#endregion
|
|
122
|
+
//#region src/core/domain/value-object.ts
|
|
123
|
+
var _ValueObject;
|
|
124
|
+
let ValueObject = class ValueObject {
|
|
125
|
+
static {
|
|
126
|
+
_ValueObject = this;
|
|
127
|
+
}
|
|
128
|
+
constructor(value) {
|
|
129
|
+
this.value = makeImmutable(value);
|
|
130
|
+
}
|
|
131
|
+
get contractVersion() {
|
|
132
|
+
return _ValueObject.CONTRACT_VERSION;
|
|
133
|
+
}
|
|
134
|
+
finalize() {
|
|
135
|
+
Object.freeze(this);
|
|
136
|
+
}
|
|
137
|
+
toJSON() {
|
|
138
|
+
return this.toPrimitive();
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
ValueObject = _ValueObject = __decorate([version("1.0")], ValueObject);
|
|
142
|
+
//#endregion
|
|
143
|
+
//#region src/index.ts
|
|
144
|
+
const ERP_CORE_NAME = "erp-core";
|
|
145
|
+
const ERP_CORE_VERSION = version$1;
|
|
146
|
+
const erpCoreRelease = {
|
|
147
|
+
name: ERP_CORE_NAME,
|
|
148
|
+
version: ERP_CORE_VERSION
|
|
149
|
+
};
|
|
150
|
+
//#endregion
|
|
151
|
+
export { AlreadyExistsError, AppError, AuthenticationError, AuthorizationError, BusinessRuleViolationError, ComputeEngineRegistry, ComputeEvaluatorRegistry, ComputePayloadParserRegistry, ComputePayloadParsers, ComputeRegistry, ConflictError, ContextResolverRegistry, ContextSeedValidator, CoreConfig, SerializationInError as DeserializationError, SerializationInError, DuplicateError, ERP_CORE_NAME, ERP_CORE_VERSION, Entity, Err, ErrorCodes, ExpiredError, GateEngineRegistry, GatePayloadParsers, IdempotencyError, IdempotencyInProgressError, IdempotencyKeyMissingError, IdempotencyPayloadMismatchError, IdempotencyReplayNotSupportedError, InMemoryPolicyDefinitionRepository, IntegrationError, LegacyIncompatibleError, NotFoundError, NotYetValidError, Ok, Outcome, PolicyAsOfResolver, PolicyCatalog, PolicyCatalogFactory, PolicyContextBuilder, PolicyContextPath, PolicyDefinition, PolicyEvaluationErrors, PolicyHashing, PolicyKey, PolicyResolver, PolicyScopeMatcher, PolicyService, Result, SerializationCodes, SerializationError, SerializationMessages, SerializationOutError, TemporalError, UnexpectedError, UniqueConstraintViolationError, ValidationError, ValidationField, ValueObject, asPolicyDecisionId, asPolicyDefinitionId, asSchoolId, asTenantId, assertJsonSafeMetadata, contextResolverRegistry, coreConfig, erpCoreRelease, evaluateTemporalWindow, mapPolicyEvaluationError, payloadHash, registerNamespacedContextResolvers, registerNamespacedContextResolversIn, safePreview, serializationErrorCode, sha256Hex, stableStringify, translateUniqueViolationToDuplicate };
|
|
152
|
+
|
|
153
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["version","version"],"sources":["../src/version.ts","../src/core/application/policy-error-mapper.ts","../src/core/shared/aggregate-version.ts","../src/core/versioning/version.ts","../src/core/domain/entity.ts","../src/core/shared/immutable.ts","../src/core/domain/value-object.ts","../src/index.ts"],"sourcesContent":["// Versao do kit, sincronizada com package.json por scripts/sync-kit-version.mjs.\n// Nao edite a mao: rode `npm run sync-kit-version` (ou e regenerado no release).\n//\n// Mantemos a versao aqui, dentro de src/, para que a copia full-control seja\n// auto-contida: ao copiar so o conteudo de src/, o entry nao depende de um\n// `../package.json` que deixaria de existir no projeto consumidor.\nexport const version = \"1.0.0\";\n","import {\n type AppError,\n BusinessRuleViolationError,\n NotFoundError,\n UnexpectedError,\n} from \"../errors\";\nimport type { PolicyEvaluationError } from \"../policies\";\n\nexport function mapPolicyEvaluationError(err: PolicyEvaluationError): AppError {\n switch (err.kind) {\n case \"INVALID_CONTEXT\":\n return new BusinessRuleViolationError(\n `policy.${err.stage.toLowerCase()}`,\n err.message,\n { policyKey: err.policyKey, stage: err.stage },\n { cause: err.cause },\n );\n case \"INVALID_POLICY_KEY\":\n return new BusinessRuleViolationError(\n \"policy.invalid_key\",\n err.message,\n { rawPolicyKey: err.rawPolicyKey },\n { cause: err.cause },\n );\n case \"POLICY_NOT_FOUND\":\n return new NotFoundError(\n \"Policy\",\n { policyKey: err.policyKey },\n { cause: err.cause },\n );\n case \"POLICY_DEFINITION_NOT_FOUND\":\n return new NotFoundError(\n \"PolicyDefinition\",\n {\n policyKey: err.policyKey,\n contextVersion: err.contextVersion,\n asOf: err.asOf.toISOString(),\n },\n { cause: err.cause },\n );\n case \"POLICY_VARIANT_NOT_FOUND\":\n return new NotFoundError(\n \"PolicyVariant\",\n {\n policyKey: err.policyKey,\n policyKind: err.policyKind,\n payloadSchemaVersion: err.payloadSchemaVersion,\n },\n { cause: err.cause },\n );\n case \"ENGINE_FAILURE\":\n return new UnexpectedError(err.message, err.cause, {\n metadata: {\n policyKey: err.policyKey,\n engine: err.engine,\n engineVersion: err.engineVersion,\n },\n });\n }\n}\n","import { InvariantViolationException } from \"../exceptions/invariant-violation-exception\";\n\nfunction assertValidAggregateVersion(aggregateVersion: number): void {\n if (!Number.isInteger(aggregateVersion) || aggregateVersion < 0) {\n throw new InvariantViolationException(\n `aggregateVersion must be a non-negative integer. Received: ${aggregateVersion}`,\n );\n }\n}\n\nexport { assertValidAggregateVersion };\n","type ContractVersion = `${number}.${number}`;\n\ntype VersionedTarget = {\n readonly prototype: object;\n};\n\nconst CONTRACT_VERSION_PROPERTY = \"CONTRACT_VERSION\" as const;\nconst CONTRACT_VERSION_PATTERN = /^\\d+\\.\\d+$/;\n\nfunction version<const TVersion extends ContractVersion>(\n contractVersion: TVersion,\n) {\n if (!CONTRACT_VERSION_PATTERN.test(contractVersion)) {\n throw new TypeError(\n `Invalid contract version \"${contractVersion}\". Expected MAJOR.MINOR.`,\n );\n }\n\n return (target: VersionedTarget): void => {\n Object.defineProperty(target, CONTRACT_VERSION_PROPERTY, {\n value: contractVersion,\n writable: false,\n configurable: false,\n enumerable: false,\n });\n };\n}\n\nexport {\n CONTRACT_VERSION_PROPERTY,\n type ContractVersion,\n version,\n type VersionedTarget,\n};\n","import { InvariantViolationException } from \"../exceptions/invariant-violation-exception\";\nimport { assertValidAggregateVersion } from \"../shared/aggregate-version\";\nimport { assertValidDate, cloneDate } from \"../shared/temporal-guards\";\nimport { type ContractVersion, version } from \"../versioning/version\";\n\ninterface EntityState<TIdentifier> {\n readonly id: TIdentifier;\n readonly createdAt: Date;\n readonly updatedAt: Date;\n readonly aggregateVersion: number;\n}\n\n@version(\"1.0\")\nabstract class Entity<TIdentifier> {\n public static readonly CONTRACT_VERSION: ContractVersion;\n\n private readonly _id: TIdentifier;\n private readonly _createdAt: Date;\n private _updatedAt: Date;\n private _aggregateVersion: number;\n\n protected constructor(state: EntityState<TIdentifier>) {\n assertValidDate(\"createdAt\", state.createdAt);\n assertValidDate(\"updatedAt\", state.updatedAt);\n assertValidAggregateVersion(state.aggregateVersion);\n\n if (state.updatedAt.getTime() < state.createdAt.getTime()) {\n throw new InvariantViolationException(\n \"updatedAt cannot be earlier than createdAt\",\n );\n }\n\n this._id = state.id;\n this._createdAt = cloneDate(state.createdAt);\n this._updatedAt = cloneDate(state.updatedAt);\n this._aggregateVersion = state.aggregateVersion;\n }\n\n public get id(): TIdentifier {\n return this._id;\n }\n\n public get createdAt(): Date {\n return cloneDate(this._createdAt);\n }\n\n public get updatedAt(): Date {\n return cloneDate(this._updatedAt);\n }\n\n public get aggregateVersion(): number {\n return this._aggregateVersion;\n }\n\n public get contractVersion(): ContractVersion {\n return Entity.CONTRACT_VERSION;\n }\n\n protected markAsModified(updatedAt: Date = new Date()): number {\n assertValidDate(\"updatedAt\", updatedAt);\n\n this._updatedAt = cloneDate(updatedAt);\n this._aggregateVersion += 1;\n\n return this._aggregateVersion;\n }\n}\n\nexport { Entity, type EntityState };\n","type PrimitiveValue =\n | bigint\n | boolean\n | null\n | number\n | string\n | symbol\n | undefined;\n\ntype DeepReadonly<T> = T extends PrimitiveValue | Date\n ? T\n : T extends readonly (infer TItem)[]\n ? readonly DeepReadonly<TItem>[]\n : { readonly [TKey in keyof T]: DeepReadonly<T[TKey]> };\n\nfunction deepFreeze<T>(value: T): T {\n if (typeof value !== \"object\" || value === null || value instanceof Date) {\n return value;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n deepFreeze(item);\n }\n\n return Object.freeze(value);\n }\n\n const objectValue = value as Record<PropertyKey, object | PrimitiveValue>;\n\n for (const propertyKey of Reflect.ownKeys(objectValue)) {\n deepFreeze(objectValue[propertyKey]);\n }\n\n return Object.freeze(value);\n}\n\nfunction makeImmutable<T>(value: T): DeepReadonly<T> {\n if (typeof value !== \"object\" || value === null) {\n return value as DeepReadonly<T>;\n }\n\n return deepFreeze(structuredClone(value)) as DeepReadonly<T>;\n}\n\nexport { deepFreeze, makeImmutable, type DeepReadonly };\n","import { type DeepReadonly, makeImmutable } from \"../shared/immutable\";\nimport { type ContractVersion, version } from \"../versioning/version\";\n\n@version(\"1.0\")\nabstract class ValueObject<T, P> {\n public static readonly CONTRACT_VERSION: ContractVersion;\n public readonly value: DeepReadonly<T>;\n\n protected constructor(value: T) {\n this.value = makeImmutable(value);\n }\n\n public get contractVersion(): ContractVersion {\n return ValueObject.CONTRACT_VERSION;\n }\n\n protected finalize(): void {\n Object.freeze(this);\n }\n\n public toJSON(): P {\n return this.toPrimitive();\n }\n\n public abstract equals(other: this): boolean;\n\n public abstract toPrimitive(): P;\n}\n\nexport { type DeepReadonly, ValueObject };\n","import { version } from \"./version.js\";\n\nexport * from \"./core/index.js\";\n\nexport const ERP_CORE_NAME = \"erp-core\";\nexport const ERP_CORE_VERSION = version;\n\nexport const erpCoreRelease = {\n name: ERP_CORE_NAME,\n version: ERP_CORE_VERSION,\n} as const;\n"],"mappings":";;;;;;;;AAMA,MAAaA,YAAU;;;ACEvB,SAAgB,yBAAyB,KAAsC;CAC7E,QAAQ,IAAI,MAAZ;EACE,KAAK,mBACH,OAAO,IAAI,2BACT,UAAU,IAAI,MAAM,YAAY,KAChC,IAAI,SACJ;GAAE,WAAW,IAAI;GAAW,OAAO,IAAI;EAAM,GAC7C,EAAE,OAAO,IAAI,MAAM,CACrB;EACF,KAAK,sBACH,OAAO,IAAI,2BACT,sBACA,IAAI,SACJ,EAAE,cAAc,IAAI,aAAa,GACjC,EAAE,OAAO,IAAI,MAAM,CACrB;EACF,KAAK,oBACH,OAAO,IAAI,cACT,UACA,EAAE,WAAW,IAAI,UAAU,GAC3B,EAAE,OAAO,IAAI,MAAM,CACrB;EACF,KAAK,+BACH,OAAO,IAAI,cACT,oBACA;GACE,WAAW,IAAI;GACf,gBAAgB,IAAI;GACpB,MAAM,IAAI,KAAK,YAAY;EAC7B,GACA,EAAE,OAAO,IAAI,MAAM,CACrB;EACF,KAAK,4BACH,OAAO,IAAI,cACT,iBACA;GACE,WAAW,IAAI;GACf,YAAY,IAAI;GAChB,sBAAsB,IAAI;EAC5B,GACA,EAAE,OAAO,IAAI,MAAM,CACrB;EACF,KAAK,kBACH,OAAO,IAAI,gBAAgB,IAAI,SAAS,IAAI,OAAO,EACjD,UAAU;GACR,WAAW,IAAI;GACf,QAAQ,IAAI;GACZ,eAAe,IAAI;EACrB,EACF,CAAC;CACL;AACF;;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S,WAAc,OAAa;CAClC,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,iBAAiB,MAClE,OAAO;CAGT,IAAI,MAAM,QAAQ,KAAK,GAAG;EACxB,KAAK,MAAM,QAAQ,OACjB,WAAW,IAAI;EAGjB,OAAO,OAAO,OAAO,KAAK;CAC5B;CAEA,MAAM,cAAc;CAEpB,KAAK,MAAM,eAAe,QAAQ,QAAQ,WAAW,GACnD,WAAW,YAAY,YAAY;CAGrC,OAAO,OAAO,OAAO,KAAK;AAC5B;AAEA,SAAS,cAAiB,OAA2B;CACnD,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,OAAO;CAGT,OAAO,WAAW,gBAAgB,KAAK,CAAC;AAC1C;;;;ACxCA,IAAA,cAAA,MACe,YAAkB;;;;CAI/B,YAAsB,OAAU;EAC9B,KAAK,QAAQ,cAAc,KAAK;CAClC;CAEA,IAAW,kBAAmC;EAC5C,OAAA,aAAmB;CACrB;CAEA,WAA2B;EACzB,OAAO,OAAO,IAAI;CACpB;CAEA,SAAmB;EACjB,OAAO,KAAK,YAAY;CAC1B;AAKF;yCAxBC,QAAQ,KAAK,CAAA,GAAA,WAAA;;;ACCd,MAAa,gBAAgB;AAC7B,MAAa,mBAAmBC;AAEhC,MAAa,iBAAiB;CAC5B,MAAM;CACN,SAAS;AACX"}
|
package/dist/outcome.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { g as InvariantViolationException } from "./gate-v1-payload.schema.js";
|
|
2
|
+
//#region src/core/result/outcome.ts
|
|
3
|
+
/**
|
|
4
|
+
* Outcome — Business decision abstraction.
|
|
5
|
+
*
|
|
6
|
+
* Represents the semantic result of a domain decision, policy evaluation,
|
|
7
|
+
* or business rule. NOT for technical success/failure — use Result for that.
|
|
8
|
+
*
|
|
9
|
+
* Mental model:
|
|
10
|
+
* "What was the business decision?"
|
|
11
|
+
* NOT "Did the operation succeed?"
|
|
12
|
+
*
|
|
13
|
+
* The status axis represents valid business outcomes (APPROVED, REJECTED,
|
|
14
|
+
* ALLOW, DENY, NO_OP, etc.), never technical Ok/Err.
|
|
15
|
+
*
|
|
16
|
+
* @typeParam S - Union of valid status literals for this outcome
|
|
17
|
+
* @typeParam D - Shape of the decision data carried by this outcome
|
|
18
|
+
*/
|
|
19
|
+
var Outcome = class Outcome {
|
|
20
|
+
constructor(status, data, reason, metadata) {
|
|
21
|
+
this.status = status;
|
|
22
|
+
this.data = data;
|
|
23
|
+
this.reason = reason;
|
|
24
|
+
this.metadata = metadata;
|
|
25
|
+
Object.freeze(this);
|
|
26
|
+
}
|
|
27
|
+
static of(status, data, reason, metadata) {
|
|
28
|
+
return new Outcome(status, data, reason, Object.freeze({ ...metadata }));
|
|
29
|
+
}
|
|
30
|
+
static approved(data, reason) {
|
|
31
|
+
return new Outcome("APPROVED", data, reason, Object.freeze({}));
|
|
32
|
+
}
|
|
33
|
+
static rejected(data, reason) {
|
|
34
|
+
return new Outcome("REJECTED", data, reason, Object.freeze({}));
|
|
35
|
+
}
|
|
36
|
+
static noOp(data, reason) {
|
|
37
|
+
return new Outcome("NO_OP", data, reason, Object.freeze({}));
|
|
38
|
+
}
|
|
39
|
+
static deferred(data, reason) {
|
|
40
|
+
return new Outcome("DEFERRED", data, reason, Object.freeze({}));
|
|
41
|
+
}
|
|
42
|
+
static requiresReview(data, reason) {
|
|
43
|
+
return new Outcome("REQUIRES_REVIEW", data, reason, Object.freeze({}));
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Narrows this Outcome to a specific status.
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* if (outcome.is('DENY')) {
|
|
50
|
+
* outcome.data.violations // TS knows status is 'DENY'
|
|
51
|
+
* }
|
|
52
|
+
*/
|
|
53
|
+
is(status) {
|
|
54
|
+
return this.status === status;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Exhaustive pattern match over all possible statuses.
|
|
58
|
+
* TypeScript enforces that every status has a handler.
|
|
59
|
+
*
|
|
60
|
+
* @example
|
|
61
|
+
* outcome.match({
|
|
62
|
+
* ALLOW: (o) => handleAllow(o.data),
|
|
63
|
+
* DENY: (o) => handleDeny(o.data.violations),
|
|
64
|
+
* })
|
|
65
|
+
*/
|
|
66
|
+
match(handlers) {
|
|
67
|
+
const handler = handlers[this.status];
|
|
68
|
+
if (typeof handler !== "function") {
|
|
69
|
+
const availableStatuses = Object.keys(handlers);
|
|
70
|
+
throw new InvariantViolationException(`Outcome.match is missing a handler for runtime status "${this.status}". Available handlers: ${availableStatuses.join(", ") || "(none)"}`);
|
|
71
|
+
}
|
|
72
|
+
return handler(this);
|
|
73
|
+
}
|
|
74
|
+
withMetadata(extra) {
|
|
75
|
+
return new Outcome(this.status, this.data, this.reason, Object.freeze({
|
|
76
|
+
...this.metadata,
|
|
77
|
+
...extra
|
|
78
|
+
}));
|
|
79
|
+
}
|
|
80
|
+
withReason(reason) {
|
|
81
|
+
return new Outcome(this.status, this.data, reason, this.metadata);
|
|
82
|
+
}
|
|
83
|
+
toString() {
|
|
84
|
+
const parts = [this.status];
|
|
85
|
+
if (this.reason) parts.push(`reason="${this.reason}"`);
|
|
86
|
+
return `Outcome(${parts.join(", ")})`;
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
//#endregion
|
|
90
|
+
export { Outcome as t };
|
|
91
|
+
|
|
92
|
+
//# sourceMappingURL=outcome.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"outcome.js","names":[],"sources":["../src/core/result/outcome.ts"],"sourcesContent":["// core/domain/outcome.ts\n\nimport { InvariantViolationException } from \"../exceptions/invariant-violation-exception\";\n\n/**\n * Outcome — Business decision abstraction.\n *\n * Represents the semantic result of a domain decision, policy evaluation,\n * or business rule. NOT for technical success/failure — use Result for that.\n *\n * Mental model:\n * \"What was the business decision?\"\n * NOT \"Did the operation succeed?\"\n *\n * The status axis represents valid business outcomes (APPROVED, REJECTED,\n * ALLOW, DENY, NO_OP, etc.), never technical Ok/Err.\n *\n * @typeParam S - Union of valid status literals for this outcome\n * @typeParam D - Shape of the decision data carried by this outcome\n */\nexport class Outcome<S extends string, D = undefined> {\n readonly status: S;\n readonly data: D;\n readonly reason: string | undefined;\n readonly metadata: Readonly<Record<string, unknown>>;\n\n private constructor(\n status: S,\n data: D,\n reason: string | undefined,\n metadata: Readonly<Record<string, unknown>>,\n ) {\n this.status = status;\n this.data = data;\n this.reason = reason;\n this.metadata = metadata;\n Object.freeze(this);\n }\n\n // ─── Generic factory ────────────────────────────────────────────────\n\n static of<S extends string, D = undefined>(\n status: S,\n data: D,\n reason?: string,\n metadata?: Record<string, unknown>,\n ): Outcome<S, D> {\n return new Outcome(status, data, reason, Object.freeze({ ...metadata }));\n }\n\n // ─── Convenience factories for common business statuses ─────────────\n\n static approved<D = undefined>(\n data: D,\n reason?: string,\n ): Outcome<\"APPROVED\", D> {\n return new Outcome(\"APPROVED\", data, reason, Object.freeze({}));\n }\n\n static rejected<D = undefined>(\n data: D,\n reason: string,\n ): Outcome<\"REJECTED\", D> {\n return new Outcome(\"REJECTED\", data, reason, Object.freeze({}));\n }\n\n static noOp<D = undefined>(data: D, reason?: string): Outcome<\"NO_OP\", D> {\n return new Outcome(\"NO_OP\", data, reason, Object.freeze({}));\n }\n\n static deferred<D = undefined>(\n data: D,\n reason: string,\n ): Outcome<\"DEFERRED\", D> {\n return new Outcome(\"DEFERRED\", data, reason, Object.freeze({}));\n }\n\n static requiresReview<D = undefined>(\n data: D,\n reason: string,\n ): Outcome<\"REQUIRES_REVIEW\", D> {\n return new Outcome(\"REQUIRES_REVIEW\", data, reason, Object.freeze({}));\n }\n\n // ─── Type narrowing ────────────────────────────────────────────────\n\n /**\n * Narrows this Outcome to a specific status.\n *\n * @example\n * if (outcome.is('DENY')) {\n * outcome.data.violations // TS knows status is 'DENY'\n * }\n */\n is<T extends S>(status: T): this is Outcome<T, D> {\n return (this.status as string) === status;\n }\n\n // ─── Exhaustive match ──────────────────────────────────────────────\n\n /**\n * Exhaustive pattern match over all possible statuses.\n * TypeScript enforces that every status has a handler.\n *\n * @example\n * outcome.match({\n * ALLOW: (o) => handleAllow(o.data),\n * DENY: (o) => handleDeny(o.data.violations),\n * })\n */\n match<THandlers extends { [K in S]: (outcome: Outcome<K, D>) => unknown }>(\n handlers: THandlers,\n ): ReturnType<THandlers[S]> {\n const handler = (\n handlers as Partial<Record<string, (o: unknown) => unknown>>\n )[this.status];\n\n if (typeof handler !== \"function\") {\n const availableStatuses = Object.keys(handlers);\n throw new InvariantViolationException(\n `Outcome.match is missing a handler for runtime status \"${this.status}\". Available handlers: ${availableStatuses.join(\", \") || \"(none)\"}`,\n );\n }\n\n return handler(this) as ReturnType<THandlers[S]>;\n }\n\n // ─── Derived copies ────────────────────────────────────────────────\n\n withMetadata(extra: Record<string, unknown>): Outcome<S, D> {\n return new Outcome(\n this.status,\n this.data,\n this.reason,\n Object.freeze({ ...this.metadata, ...extra }),\n );\n }\n\n withReason(reason: string): Outcome<S, D> {\n return new Outcome(this.status, this.data, reason, this.metadata);\n }\n\n // ─── Debug ─────────────────────────────────────────────────────────\n\n toString(): string {\n const parts: string[] = [this.status];\n if (this.reason) parts.push(`reason=\"${this.reason}\"`);\n return `Outcome(${parts.join(\", \")})`;\n }\n}\n\n/** Common business outcome statuses. Extend per domain as needed. */\nexport type CommonOutcomeStatus =\n | \"APPROVED\"\n | \"REJECTED\"\n | \"NO_OP\"\n | \"DEFERRED\"\n | \"REQUIRES_REVIEW\";\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoBA,IAAa,UAAb,MAAa,QAAyC;CAMpD,YACE,QACA,MACA,QACA,UACA;EACA,KAAK,SAAS;EACd,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,WAAW;EAChB,OAAO,OAAO,IAAI;CACpB;CAIA,OAAO,GACL,QACA,MACA,QACA,UACe;EACf,OAAO,IAAI,QAAQ,QAAQ,MAAM,QAAQ,OAAO,OAAO,EAAE,GAAG,SAAS,CAAC,CAA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OAAO,WAAW,MAAM,KAAK,IAAI,EAAE;CACrC;AACF"}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { I as Result, c as PolicyViolation, d as GatePayloadV1, g as CoreConfig, h as Outcome, l as VersionedGateEngine, p as ConditionNode, s as PolicyContext, t as GateOutcome, u as GatePayload } from "./gate-types.js";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
//#region src/core/policies/engines/v1/compute/compute-payload.schema.d.ts
|
|
5
|
+
interface ComputeParamsPayload {
|
|
6
|
+
readonly type: "params";
|
|
7
|
+
readonly data: Readonly<Record<string, unknown>>;
|
|
8
|
+
}
|
|
9
|
+
interface ComputeDecisionTableRule<R = unknown> {
|
|
10
|
+
readonly conditions: ConditionNode;
|
|
11
|
+
readonly result: R;
|
|
12
|
+
}
|
|
13
|
+
interface ComputeDecisionTablePayload<R = unknown> {
|
|
14
|
+
readonly type: "decision-table";
|
|
15
|
+
readonly rules: readonly ComputeDecisionTableRule<R>[];
|
|
16
|
+
readonly default: R;
|
|
17
|
+
}
|
|
18
|
+
type ComputePayloadV1 = ComputeDecisionTablePayload<unknown> | ComputeParamsPayload;
|
|
19
|
+
//#endregion
|
|
20
|
+
//#region src/core/policies/engines/compute-payload.d.ts
|
|
21
|
+
type ComputePayload = ComputePayloadV1;
|
|
22
|
+
//#endregion
|
|
23
|
+
//#region src/core/policies/engines/compute-types.d.ts
|
|
24
|
+
type ComputeStatus = "OK" | "NOT_APPLICABLE" | "ERROR";
|
|
25
|
+
interface ComputeOutcomeData {
|
|
26
|
+
readonly values: unknown | null;
|
|
27
|
+
readonly violations: readonly PolicyViolation[];
|
|
28
|
+
}
|
|
29
|
+
/** Semantic outcome of a COMPUTE policy evaluation. */
|
|
30
|
+
type ComputeOutcome = Outcome<ComputeStatus, ComputeOutcomeData>;
|
|
31
|
+
/**
|
|
32
|
+
* Pure compute operation: receives a resolved value + context, returns a
|
|
33
|
+
* business decision. Registration metadata (policy key/version) lives outside
|
|
34
|
+
* this contract.
|
|
35
|
+
*
|
|
36
|
+
* The engine resolves the structural payload before calling the evaluator:
|
|
37
|
+
* - `params` -> `payload.data`
|
|
38
|
+
* - `decision-table` -> matching `rule.result` or `default`
|
|
39
|
+
*
|
|
40
|
+
* Result wraps technical failures (invalid value shape).
|
|
41
|
+
* Outcome carries the semantic business decision.
|
|
42
|
+
*/
|
|
43
|
+
interface ComputeEvaluator {
|
|
44
|
+
evaluate(resolvedValue: unknown, context: Record<string, unknown>): Result<ComputeOutcome, string>;
|
|
45
|
+
}
|
|
46
|
+
interface ComputeEvaluatorRegistration {
|
|
47
|
+
readonly policyKey: string;
|
|
48
|
+
readonly version: number;
|
|
49
|
+
readonly evaluator: ComputeEvaluator;
|
|
50
|
+
}
|
|
51
|
+
interface VersionedComputeEngine {
|
|
52
|
+
readonly version: number;
|
|
53
|
+
evaluate(payload: ComputePayload, context: PolicyContext, evaluator: ComputeEvaluator): Result<ComputeOutcome, string>;
|
|
54
|
+
}
|
|
55
|
+
//#endregion
|
|
56
|
+
//#region src/core/policies/engines/compute-evaluator-registry.d.ts
|
|
57
|
+
declare class ComputeEvaluatorRegistry {
|
|
58
|
+
private readonly evaluators;
|
|
59
|
+
private static toRegistryKey;
|
|
60
|
+
register(registration: ComputeEvaluatorRegistration): void;
|
|
61
|
+
get(policyKey: string, version: number): ComputeEvaluator | undefined;
|
|
62
|
+
}
|
|
63
|
+
//#endregion
|
|
64
|
+
//#region src/core/policies/engines/compute-engine-registry.d.ts
|
|
65
|
+
declare class ComputeEngineRegistry {
|
|
66
|
+
private readonly engines;
|
|
67
|
+
register(engine: VersionedComputeEngine): void;
|
|
68
|
+
get(version: number): VersionedComputeEngine | undefined;
|
|
69
|
+
evaluate(version: number, params: {
|
|
70
|
+
readonly policyKey: string;
|
|
71
|
+
readonly payloadSchemaVersion: number;
|
|
72
|
+
readonly payload: unknown;
|
|
73
|
+
readonly context: PolicyContext;
|
|
74
|
+
readonly evaluators: ComputeEvaluatorRegistry;
|
|
75
|
+
}): Result<ComputeOutcome, string>;
|
|
76
|
+
}
|
|
77
|
+
//#endregion
|
|
78
|
+
//#region src/core/policies/engines/compute-registry.d.ts
|
|
79
|
+
interface ComputeRegistryOptions {
|
|
80
|
+
readonly coreConfig?: CoreConfig;
|
|
81
|
+
}
|
|
82
|
+
declare class ComputeRegistry {
|
|
83
|
+
private readonly engines;
|
|
84
|
+
private readonly evaluators;
|
|
85
|
+
constructor(params?: ComputeRegistryOptions);
|
|
86
|
+
register(registration: ComputeEvaluatorRegistration): void;
|
|
87
|
+
registerEngine(engine: VersionedComputeEngine): void;
|
|
88
|
+
getEngine(version: number): VersionedComputeEngine | undefined;
|
|
89
|
+
getEvaluator(policyKey: string, version: number): ComputeEvaluator | undefined;
|
|
90
|
+
evaluate(policyKey: string, computeEngineVersion: number, payloadSchemaVersion: number, payload: unknown, context: PolicyContext): Result<ComputeOutcome, string>;
|
|
91
|
+
}
|
|
92
|
+
//#endregion
|
|
93
|
+
//#region src/core/policies/engines/gate-engine-registry.d.ts
|
|
94
|
+
declare class GateEngineRegistry {
|
|
95
|
+
private readonly engines;
|
|
96
|
+
register(engine: VersionedGateEngine): void;
|
|
97
|
+
get(version: number): VersionedGateEngine | undefined;
|
|
98
|
+
evaluate(version: number, payload: unknown, context: PolicyContext): Result<GateOutcome, string>;
|
|
99
|
+
}
|
|
100
|
+
//#endregion
|
|
101
|
+
//#region src/core/policies/engines/parse-compute-payload.d.ts
|
|
102
|
+
type ComputePayloadParser = (payload: unknown) => Result<ComputePayload, string>;
|
|
103
|
+
declare class ComputePayloadParserRegistry {
|
|
104
|
+
private readonly parsers;
|
|
105
|
+
register(payloadSchemaVersion: number, parser: ComputePayloadParser): void;
|
|
106
|
+
get(payloadSchemaVersion: number): ComputePayloadParser | undefined;
|
|
107
|
+
parse(payloadSchemaVersion: number, payload: unknown): Result<ComputePayloadV1, string>;
|
|
108
|
+
}
|
|
109
|
+
declare class ComputePayloadParsers {
|
|
110
|
+
private static readonly registry;
|
|
111
|
+
private static defaultsRegistered;
|
|
112
|
+
private static ensureDefaults;
|
|
113
|
+
static register(payloadSchemaVersion: number, parser: ComputePayloadParser): void;
|
|
114
|
+
static get(payloadSchemaVersion: number): ComputePayloadParser | undefined;
|
|
115
|
+
static parse(payloadSchemaVersion: number, payload: unknown): Result<ComputePayloadV1, string>;
|
|
116
|
+
}
|
|
117
|
+
//#endregion
|
|
118
|
+
//#region src/core/policies/engines/parse-gate-payload.d.ts
|
|
119
|
+
type GatePayloadParser = (payload: unknown) => Result<GatePayload, string>;
|
|
120
|
+
declare class GatePayloadParserRegistry {
|
|
121
|
+
private readonly parsers;
|
|
122
|
+
register(engineVersion: number, parser: GatePayloadParser): void;
|
|
123
|
+
get(engineVersion: number): GatePayloadParser | undefined;
|
|
124
|
+
parse(engineVersion: number, payload: unknown): Result<GatePayloadV1, string>;
|
|
125
|
+
}
|
|
126
|
+
declare class GatePayloadParsers {
|
|
127
|
+
private static readonly registry;
|
|
128
|
+
private static defaultsRegistered;
|
|
129
|
+
private static ensureDefaults;
|
|
130
|
+
static register(engineVersion: number, parser: GatePayloadParser): void;
|
|
131
|
+
static get(engineVersion: number): GatePayloadParser | undefined;
|
|
132
|
+
static parse(engineVersion: number, payload: unknown): Result<GatePayloadV1, string>;
|
|
133
|
+
}
|
|
134
|
+
//#endregion
|
|
135
|
+
export { ComputePayload as _, ComputePayloadParserRegistry as a, ComputeParamsPayload as b, ComputeRegistry as c, ComputeEvaluator as d, ComputeEvaluatorRegistration as f, VersionedComputeEngine as g, ComputeStatus as h, ComputePayloadParser as i, ComputeEngineRegistry as l, ComputeOutcomeData as m, GatePayloadParserRegistry as n, ComputePayloadParsers as o, ComputeOutcome as p, GatePayloadParsers as r, GateEngineRegistry as s, GatePayloadParser as t, ComputeEvaluatorRegistry as u, ComputeDecisionTablePayload as v, ComputePayloadV1 as x, ComputeDecisionTableRule as y };
|
|
136
|
+
//# sourceMappingURL=parse-gate-payload.d.ts.map
|