@cullet/erp-core 1.4.0 → 1.5.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 +6 -0
- package/dist/app-error.cjs +14 -6
- package/dist/app-error.cjs.map +1 -1
- package/dist/app-error.js +14 -6
- package/dist/app-error.js.map +1 -1
- package/dist/condition-evaluator.cjs +14 -0
- package/dist/condition-evaluator.cjs.map +1 -1
- package/dist/condition-evaluator.js +14 -0
- package/dist/condition-evaluator.js.map +1 -1
- package/dist/entity.cjs +2 -6
- package/dist/entity.cjs.map +1 -1
- package/dist/entity.js +2 -6
- package/dist/entity.js.map +1 -1
- package/dist/errors/index.cjs +2 -1
- package/dist/errors/index.js +2 -1
- package/dist/hashing.cjs +2 -44
- package/dist/hashing.cjs.map +1 -1
- package/dist/hashing.js +2 -38
- package/dist/hashing.js.map +1 -1
- package/dist/index.cjs +3 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/policies/engines/v1/gate/index.d.cts +2 -0
- package/dist/policies/engines/v1/gate/index.d.ts +2 -0
- package/dist/policy-service.cjs +2 -1
- package/dist/policy-service.cjs.map +1 -1
- package/dist/policy-service.js +2 -1
- package/dist/policy-service.js.map +1 -1
- package/dist/requested-by.cjs +3 -3
- package/dist/requested-by.cjs.map +1 -1
- package/dist/requested-by.js +1 -1
- package/dist/requested-by.js.map +1 -1
- package/dist/stable-stringify.cjs +47 -0
- package/dist/stable-stringify.cjs.map +1 -0
- package/dist/stable-stringify.js +42 -0
- package/dist/stable-stringify.js.map +1 -0
- package/dist/temporal-use-case.cjs +5 -0
- package/dist/temporal-use-case.cjs.map +1 -1
- package/dist/temporal-use-case.d.cts +6 -1
- package/dist/temporal-use-case.d.ts +6 -1
- package/dist/temporal-use-case.js +5 -0
- package/dist/temporal-use-case.js.map +1 -1
- package/dist/use-case.cjs +2 -6
- package/dist/use-case.cjs.map +1 -1
- package/dist/use-case.js +2 -6
- package/dist/use-case.js.map +1 -1
- package/dist/uuid-identifier.cjs +2 -7
- package/dist/uuid-identifier.cjs.map +1 -1
- package/dist/uuid-identifier.js +1 -6
- package/dist/uuid-identifier.js.map +1 -1
- package/dist/uuid.cjs +18 -0
- package/dist/uuid.cjs.map +1 -0
- package/dist/uuid.js +13 -0
- package/dist/uuid.js.map +1 -0
- package/dist/validation-error.d.cts +10 -5
- package/dist/validation-error.d.ts +10 -5
- package/dist/value-object.cjs +12 -3
- package/dist/value-object.cjs.map +1 -1
- package/dist/value-object.d.cts +9 -1
- package/dist/value-object.d.ts +9 -1
- package/dist/value-object.js +12 -3
- package/dist/value-object.js.map +1 -1
- package/meta.json +4 -2
- package/package.json +1 -1
- package/src/core/application/commands/requested-by.ts +3 -4
- package/src/core/application/queries/query.ts +6 -1
- package/src/core/application/use-case.ts +1 -1
- package/src/core/domain/entity.ts +1 -1
- package/src/core/domain/uuid-identifier.ts +1 -8
- package/src/core/domain/value-object.ts +12 -3
- package/src/core/errors/utils/json-safe.ts +20 -11
- package/src/core/policies/engines/v1/condition-evaluator.ts +56 -1
- package/src/core/shared/hashing.ts +1 -55
- package/src/core/shared/stable-stringify.ts +57 -0
- package/src/core/shared/uuid.ts +11 -0
- package/src/version.ts +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"condition-evaluator.js","names":["#initialReporter","#currentReporter","#bridgeToConditionReporter"],"sources":["../src/core/config/silent-policy-reporter.ts","../src/core/config/core-config.ts","../src/core/config/core-config.instance.ts","../src/core/policies/context/path.ts","../src/core/policies/utils/date.ts","../src/core/policies/engines/v1/condition-evaluator.ts"],"sourcesContent":["import type { PolicyReporter } from \"./policy-reporter.js\";\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.js\";\nimport type { PolicyEvent, PolicyReporter } from \"./policy-reporter.js\";\nimport { SilentPolicyReporter } from \"./silent-policy-reporter.js\";\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.js\";\nimport { SilentPolicyReporter } from \"./silent-policy-reporter.js\";\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 * Utilities for reading/writing values at dot-separated paths\n * in plain objects, e.g. \"installment.dueDate\".\n */\n\nimport { Result } from \"../../result/result.js\";\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 (\n typeof value !== \"object\" ||\n value === null ||\n Array.isArray(value)\n ) {\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<\n string,\n unknown\n >;\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 { isValidDate } from \"../../shared/temporal-guards.js\";\n\nexport class PolicyDateUtils {\n static isValid(value: Date): boolean {\n return isValidDate(value);\n }\n}\n","import { PolicyContextPath } from \"../../context/index.js\";\nimport { PolicyDateUtils } from \"../../utils/index.js\";\nimport { Result } from \"../../../result/result.js\";\n\nimport type {\n ConditionAndNode,\n ConditionLeafNode,\n ConditionNode,\n ConditionNotNode,\n ConditionOp,\n ConditionOrNode,\n} from \"./condition-types.js\";\nimport type {\n ConditionEvaluationOptions,\n ConditionEvaluationReport,\n} from \"../condition-evaluator-reporter.js\";\nimport type { PolicyContext } from \"../gate-types.js\";\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 INVALID_NUMERIC_OPERAND_TAG = \"INVALID_NUMERIC_OPERAND\";\nconst INVALID_SET_OPERAND_TAG = \"INVALID_SET_OPERAND\";\nconst EMPTY_OR_CONDITION_TAG = \"EMPTY_OR_CONDITION\";\nconst EMPTY_AND_CONDITION_TAG = \"EMPTY_AND_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 buildInvalidNumericOperandMessage(\n node: ConditionLeafNode,\n ): string {\n return `${INVALID_NUMERIC_OPERAND_TAG}: \"${node.field}\" with operator \"${node.op}\" requires numeric operands`;\n }\n\n private static buildInvalidSetOperandMessage(\n node: ConditionLeafNode,\n ): string {\n return `${INVALID_SET_OPERAND_TAG}: \"${node.field}\" with operator \"${node.op}\" requires an array operand`;\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 buildEmptyAndConditionMessage(): string {\n return `${EMPTY_AND_CONDITION_TAG}: AND 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 (\n typeof value !== \"string\" ||\n !ISO_8601_UTC_DATE_PATTERN.test(value)\n ) {\n return null;\n }\n\n const parsed = new Date(value);\n if (\n !PolicyDateUtils.isValid(parsed) ||\n parsed.toISOString() !== value\n ) {\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 =\n 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 reportInvalidNumericOperand(\n node: ConditionLeafNode,\n actual: unknown,\n ): Result<boolean, string> {\n const message =\n ConditionEvaluatorV1.buildInvalidNumericOperandMessage(node);\n\n this.options.reporter.error(\n this.buildReport({\n level: \"error\",\n tag: INVALID_NUMERIC_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 reportInvalidSetOperand(\n node: ConditionLeafNode,\n actual: unknown,\n ): Result<boolean, string> {\n const message =\n ConditionEvaluatorV1.buildInvalidSetOperandMessage(node);\n\n this.options.reporter.error(\n this.buildReport({\n level: \"error\",\n tag: INVALID_SET_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 =\n 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(\n actual,\n op,\n expected,\n )\n );\n case \"gte\":\n return (\n typeof actual === \"number\" &&\n typeof expected === \"number\" &&\n ConditionEvaluatorV1.evaluateRelationalNumbers(\n actual,\n op,\n expected,\n )\n );\n case \"lt\":\n return (\n typeof actual === \"number\" &&\n typeof expected === \"number\" &&\n ConditionEvaluatorV1.evaluateRelationalNumbers(\n actual,\n op,\n expected,\n )\n );\n case \"lte\":\n return (\n typeof actual === \"number\" &&\n typeof expected === \"number\" &&\n ConditionEvaluatorV1.evaluateRelationalNumbers(\n actual,\n op,\n expected,\n )\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 =\n 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 // null + allowNull: a relational comparison against a missing value\n // never matches.\n if (actual === null) {\n return Result.ok(false);\n }\n\n // Both operands must be numbers. A present but wrong-typed operand is a\n // context/configuration error, surfaced like the date path instead of\n // silently collapsing to \"no match\".\n if (typeof actual !== \"number\" || typeof node.value !== \"number\") {\n return this.reportInvalidNumericOperand(node, actual);\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(\n node,\n actual,\n );\n if (dateResult !== null) {\n return dateResult;\n }\n\n return this.evaluateNumericRelationalNode(node, actual);\n }\n\n if (\n (node.op === \"in\" || node.op === \"notIn\") &&\n !Array.isArray(node.value)\n ) {\n return this.reportInvalidSetOperand(node, actual);\n }\n\n return Result.ok(\n this.evaluateOperator(actual, node.op, node.value),\n );\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 if (node.and.length === 0) {\n return Result.err(\n ConditionEvaluatorV1.buildEmptyAndConditionMessage(),\n );\n }\n\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(\n child,\n childPath,\n );\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:\n tracedChild.trace.lastEvaluatedLeaf,\n lastEvaluatedLeafPath:\n 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(\n ConditionEvaluatorV1.buildEmptyOrConditionMessage(),\n );\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(\n node.not,\n childPath,\n );\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:\n tracedChild.trace.lastEvaluatedLeafPath,\n lastEvaluatedLeafResult:\n 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"],"mappings":";;;AAEA,IAAa,uBAAb,MAA4D;CACxD,OAAO,QAAuD,CAAC;AACnE;;;ACWA,SAAS,aACL,gBACA,OACI;CACJ,IAAI;EACA,eAAe,OAAO,KAAK;CAC/B,QAAQ,CAER;AACJ;;;;;AAMA,IAAa,aAAb,MAAwB;CACpB;CACA;CAEA,YAAY,UAA6B,CAAC,GAAG;EACzC,MAAM,WACF,QAAQ,eAAe,YAAY,IAAI,qBAAqB;EAChE,KAAKA,mBAAmB;EACxB,KAAKC,mBAAmB;CAC5B;CAEA,UAAU,SAAkC;EACxC,MAAM,WAAW,QAAQ,eAAe;EACxC,IAAI,UACA,KAAKA,mBAAmB;EAE5B,OAAO;CACX;CAGA,QAAc;EACV,KAAKA,mBAAmB,KAAKD;EAC7B,OAAO;CACX;CAEA,oBAAoC;EAChC,OAAO,KAAKC;CAChB;CAEA,8BACI,eAC0B;EAC1B,OAAO;GACH,UAAU,KAAKC,2BAA2B,KAAKD,gBAAgB;GAC/D;EACJ;CACJ;CAEA,2BACI,gBAC0B;EAC1B,OAAO;GACH,KAAK,QAAQ;IACT,aAAa,gBAAgB;KACzB,MAAM;KACN,GAAG;IACP,CAAuB;GAC3B;GACA,MAAM,QAAQ;IACV,aAAa,gBAAgB;KACzB,MAAM;KACN,GAAG;IACP,CAAuB;GAC3B;EACJ;CACJ;AACJ;;;;;;;;;;;AC3EA,MAAa,aAAa,IAAI,WAAW,EACrC,eAAe,EAAE,UAAU,IAAI,qBAAqB,EAAE,EAC1D,CAAC;;;;;;;ACND,IAAa,oBAAb,MAAa,kBAAkB;;4BACkB,IAAI,IAAI;GACjD;GACA;GACA;EACJ,CAAC;;CAED,OAAe,QACX,KACA,MAOF;EACE,MAAM,iBAAiB,kBAAkB,cAAc,IAAI;EAC3D,IAAI,eAAe,MAAM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;EACzC,IAAI;GACA,OAAO,KAAK,0BAA0B,MAAM,GAAG;EACnD,SAAS,OAAO;GACZ,OAAO,KAAK,iBAAiB,MAAM,KAAK;EAC5C;CACJ;CAEA,OAAO,cAAc,MAA+B;EAChD,IAAI,qBAAqB,WAAW,IAAI,GACpC,OAAO,CAAC,KAAK,KAAK;EAGtB,IAAI,qBAAqB,UAAU,IAAI,GACnC,OAAO,KAAK,IAAI,SAAS,UACrB,qBAAqB,cAAc,KAAK,CAC5C;EAGJ,IAAI,qBAAqB,SAAS,IAAI,GAClC,OAAO,KAAK,GAAG,SAAS,UACpB,qBAAqB,cAAc,KAAK,CAC5C;EAGJ,IAAI,qBAAqB,UAAU,IAAI,GACnC,OAAO,qBAAqB,cAAc,KAAK,GAAG;EAGtD,OAAO,CAAC;CACZ;AACJ"}
|
|
1
|
+
{"version":3,"file":"condition-evaluator.js","names":["#initialReporter","#currentReporter","#bridgeToConditionReporter"],"sources":["../src/core/config/silent-policy-reporter.ts","../src/core/config/core-config.ts","../src/core/config/core-config.instance.ts","../src/core/policies/context/path.ts","../src/core/policies/utils/date.ts","../src/core/policies/engines/v1/condition-evaluator.ts"],"sourcesContent":["import type { PolicyReporter } from \"./policy-reporter.js\";\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.js\";\nimport type { PolicyEvent, PolicyReporter } from \"./policy-reporter.js\";\nimport { SilentPolicyReporter } from \"./silent-policy-reporter.js\";\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.js\";\nimport { SilentPolicyReporter } from \"./silent-policy-reporter.js\";\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 * Utilities for reading/writing values at dot-separated paths\n * in plain objects, e.g. \"installment.dueDate\".\n */\n\nimport { Result } from \"../../result/result.js\";\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 (\n typeof value !== \"object\" ||\n value === null ||\n Array.isArray(value)\n ) {\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<\n string,\n unknown\n >;\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 { isValidDate } from \"../../shared/temporal-guards.js\";\n\nexport class PolicyDateUtils {\n static isValid(value: Date): boolean {\n return isValidDate(value);\n }\n}\n","import { PolicyContextPath } from \"../../context/index.js\";\n// Import the date util directly (not the utils barrel): the barrel re-exports\n// PolicyHashing, whose node:crypto import would needlessly drag a Node-only\n// API into the zod-free ./abac subpath.\nimport { PolicyDateUtils } from \"../../utils/date.js\";\nimport { Result } from \"../../../result/result.js\";\n\nimport type {\n ConditionAndNode,\n ConditionLeafNode,\n ConditionNode,\n ConditionNotNode,\n ConditionOp,\n ConditionOrNode,\n} from \"./condition-types.js\";\nimport type {\n ConditionEvaluationOptions,\n ConditionEvaluationReport,\n} from \"../condition-evaluator-reporter.js\";\nimport type { PolicyContext } from \"../gate-types.js\";\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 INVALID_NUMERIC_OPERAND_TAG = \"INVALID_NUMERIC_OPERAND\";\nconst INVALID_SET_OPERAND_TAG = \"INVALID_SET_OPERAND\";\nconst EMPTY_OR_CONDITION_TAG = \"EMPTY_OR_CONDITION\";\nconst EMPTY_AND_CONDITION_TAG = \"EMPTY_AND_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 buildInvalidNumericOperandMessage(\n node: ConditionLeafNode,\n ): string {\n return `${INVALID_NUMERIC_OPERAND_TAG}: \"${node.field}\" with operator \"${node.op}\" requires numeric operands`;\n }\n\n private static buildInvalidSetOperandMessage(\n node: ConditionLeafNode,\n ): string {\n return `${INVALID_SET_OPERAND_TAG}: \"${node.field}\" with operator \"${node.op}\" requires an array operand`;\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 buildEmptyAndConditionMessage(): string {\n return `${EMPTY_AND_CONDITION_TAG}: AND 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 (\n typeof value !== \"string\" ||\n !ISO_8601_UTC_DATE_PATTERN.test(value)\n ) {\n return null;\n }\n\n const parsed = new Date(value);\n if (\n !PolicyDateUtils.isValid(parsed) ||\n parsed.toISOString() !== value\n ) {\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 static containsInvalidDate(value: unknown): boolean {\n if (value instanceof Date) {\n return !PolicyDateUtils.isValid(value);\n }\n if (Array.isArray(value)) {\n return value.some((item) =>\n ConditionEvaluatorV1.containsInvalidDate(item),\n );\n }\n return false;\n }\n\n // Valid Dates become their ISO string so equality/set operators compare\n // instants instead of references; every other value passes through.\n private static normalizeDateOperand(value: unknown): unknown {\n if (value instanceof Date) {\n return value.toISOString();\n }\n if (Array.isArray(value)) {\n return value.map((item) =>\n ConditionEvaluatorV1.normalizeDateOperand(item),\n );\n }\n return value;\n }\n\n private reportDateOperandError(\n node: ConditionLeafNode,\n actual: unknown,\n ): Result<boolean, string> {\n const message =\n 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 reportInvalidNumericOperand(\n node: ConditionLeafNode,\n actual: unknown,\n ): Result<boolean, string> {\n const message =\n ConditionEvaluatorV1.buildInvalidNumericOperandMessage(node);\n\n this.options.reporter.error(\n this.buildReport({\n level: \"error\",\n tag: INVALID_NUMERIC_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 reportInvalidSetOperand(\n node: ConditionLeafNode,\n actual: unknown,\n ): Result<boolean, string> {\n const message =\n ConditionEvaluatorV1.buildInvalidSetOperandMessage(node);\n\n this.options.reporter.error(\n this.buildReport({\n level: \"error\",\n tag: INVALID_SET_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 =\n 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(\n actual,\n op,\n expected,\n )\n );\n case \"gte\":\n return (\n typeof actual === \"number\" &&\n typeof expected === \"number\" &&\n ConditionEvaluatorV1.evaluateRelationalNumbers(\n actual,\n op,\n expected,\n )\n );\n case \"lt\":\n return (\n typeof actual === \"number\" &&\n typeof expected === \"number\" &&\n ConditionEvaluatorV1.evaluateRelationalNumbers(\n actual,\n op,\n expected,\n )\n );\n case \"lte\":\n return (\n typeof actual === \"number\" &&\n typeof expected === \"number\" &&\n ConditionEvaluatorV1.evaluateRelationalNumbers(\n actual,\n op,\n expected,\n )\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 =\n 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 // null + allowNull: a relational comparison against a missing value\n // never matches.\n if (actual === null) {\n return Result.ok(false);\n }\n\n // Both operands must be numbers. A present but wrong-typed operand is a\n // context/configuration error, surfaced like the date path instead of\n // silently collapsing to \"no match\".\n if (typeof actual !== \"number\" || typeof node.value !== \"number\") {\n return this.reportInvalidNumericOperand(node, actual);\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(\n node,\n actual,\n );\n if (dateResult !== null) {\n return dateResult;\n }\n\n return this.evaluateNumericRelationalNode(node, actual);\n }\n\n if (\n (node.op === \"in\" || node.op === \"notIn\") &&\n !Array.isArray(node.value)\n ) {\n return this.reportInvalidSetOperand(node, actual);\n }\n\n if (\n node.op === \"eq\" ||\n node.op === \"neq\" ||\n node.op === \"in\" ||\n node.op === \"notIn\"\n ) {\n // A Date operand would otherwise compare by reference and\n // silently never match. Normalize valid Dates (either side,\n // including set items) to their ISO string; an invalid Date is\n // a context/configuration error, like the relational path.\n if (\n ConditionEvaluatorV1.containsInvalidDate(actual) ||\n ConditionEvaluatorV1.containsInvalidDate(node.value)\n ) {\n return this.reportDateOperandError(node, actual);\n }\n\n return Result.ok(\n this.evaluateOperator(\n ConditionEvaluatorV1.normalizeDateOperand(actual),\n node.op,\n ConditionEvaluatorV1.normalizeDateOperand(node.value),\n ),\n );\n }\n\n return Result.ok(\n this.evaluateOperator(actual, node.op, node.value),\n );\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 if (node.and.length === 0) {\n return Result.err(\n ConditionEvaluatorV1.buildEmptyAndConditionMessage(),\n );\n }\n\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(\n child,\n childPath,\n );\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:\n tracedChild.trace.lastEvaluatedLeaf,\n lastEvaluatedLeafPath:\n 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(\n ConditionEvaluatorV1.buildEmptyOrConditionMessage(),\n );\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(\n node.not,\n childPath,\n );\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:\n tracedChild.trace.lastEvaluatedLeafPath,\n lastEvaluatedLeafResult:\n 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"],"mappings":";;;AAEA,IAAa,uBAAb,MAA4D;CACxD,OAAO,QAAuD,CAAC;AACnE;;;ACWA,SAAS,aACL,gBACA,OACI;CACJ,IAAI;EACA,eAAe,OAAO,KAAK;CAC/B,QAAQ,CAER;AACJ;;;;;AAMA,IAAa,aAAb,MAAwB;CACpB;CACA;CAEA,YAAY,UAA6B,CAAC,GAAG;EACzC,MAAM,WACF,QAAQ,eAAe,YAAY,IAAI,qBAAqB;EAChE,KAAKA,mBAAmB;EACxB,KAAKC,mBAAmB;CAC5B;CAEA,UAAU,SAAkC;EACxC,MAAM,WAAW,QAAQ,eAAe;EACxC,IAAI,UACA,KAAKA,mBAAmB;EAE5B,OAAO;CACX;CAGA,QAAc;EACV,KAAKA,mBAAmB,KAAKD;EAC7B,OAAO;CACX;CAEA,oBAAoC;EAChC,OAAO,KAAKC;CAChB;CAEA,8BACI,eAC0B;EAC1B,OAAO;GACH,UAAU,KAAKC,2BAA2B,KAAKD,gBAAgB;GAC/D;EACJ;CACJ;CAEA,2BACI,gBA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O;GACZ,OAAO,KAAK,iBAAiB,MAAM,KAAK;EAC5C;CACJ;CAEA,OAAO,cAAc,MAA+B;EAChD,IAAI,qBAAqB,WAAW,IAAI,GACpC,OAAO,CAAC,KAAK,KAAK;EAGtB,IAAI,qBAAqB,UAAU,IAAI,GACnC,OAAO,KAAK,IAAI,SAAS,UACrB,qBAAqB,cAAc,KAAK,CAC5C;EAGJ,IAAI,qBAAqB,SAAS,IAAI,GAClC,OAAO,KAAK,GAAG,SAAS,UACpB,qBAAqB,cAAc,KAAK,CAC5C;EAGJ,IAAI,qBAAqB,UAAU,IAAI,GACnC,OAAO,qBAAqB,cAAc,KAAK,GAAG;EAGtD,OAAO,CAAC;CACZ;AACJ"}
|
package/dist/entity.cjs
CHANGED
|
@@ -7,7 +7,6 @@ function assertValidAggregateVersion(aggregateVersion) {
|
|
|
7
7
|
}
|
|
8
8
|
//#endregion
|
|
9
9
|
//#region src/core/domain/entity.ts
|
|
10
|
-
var _Entity;
|
|
11
10
|
/**
|
|
12
11
|
* Base class for domain entities — objects defined by a stable identity rather
|
|
13
12
|
* than by their attributes. Two entities are "the same" when their `id`
|
|
@@ -23,9 +22,6 @@ var _Entity;
|
|
|
23
22
|
* @typeParam TIdentifier - The identity type (e.g. a branded string id or a VO).
|
|
24
23
|
*/
|
|
25
24
|
let Entity = class Entity {
|
|
26
|
-
static {
|
|
27
|
-
_Entity = this;
|
|
28
|
-
}
|
|
29
25
|
/**
|
|
30
26
|
* Reconstitutes an entity from its persisted {@link EntityState}.
|
|
31
27
|
*
|
|
@@ -86,7 +82,7 @@ let Entity = class Entity {
|
|
|
86
82
|
* an older shape.
|
|
87
83
|
*/
|
|
88
84
|
get contractVersion() {
|
|
89
|
-
return
|
|
85
|
+
return this.constructor.CONTRACT_VERSION;
|
|
90
86
|
}
|
|
91
87
|
/**
|
|
92
88
|
* The single seam through which an entity records a mutation: it advances
|
|
@@ -108,7 +104,7 @@ let Entity = class Entity {
|
|
|
108
104
|
return this._aggregateVersion;
|
|
109
105
|
}
|
|
110
106
|
};
|
|
111
|
-
Entity =
|
|
107
|
+
Entity = require_immutable.__decorate([require_immutable.version("1.0")], Entity);
|
|
112
108
|
//#endregion
|
|
113
109
|
Object.defineProperty(exports, "Entity", {
|
|
114
110
|
enumerable: true,
|
package/dist/entity.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"entity.cjs","names":["InvariantViolationException","InvariantViolationException","cloneDate","version"],"sources":["../src/core/shared/aggregate-version.ts","../src/core/domain/entity.ts"],"sourcesContent":["import { InvariantViolationException } from \"../exceptions/invariant-violation-exception.js\";\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","import { InvariantViolationException } from \"../exceptions/invariant-violation-exception.js\";\nimport { assertValidAggregateVersion } from \"../shared/aggregate-version.js\";\nimport { assertValidDate, cloneDate } from \"../shared/temporal-guards.js\";\nimport { type ContractVersion, version } from \"../versioning/version.js\";\n\n/**\n * The minimal persisted shape needed to reconstitute an {@link Entity}.\n *\n * This is the contract between storage and the domain: a repository maps a row\n * (or document) onto these four fields and hands them to a subclass constructor.\n * `aggregateVersion` travels with the state so optimistic-concurrency checks\n * survive a round-trip through the database.\n */\ninterface EntityState<TIdentifier> {\n readonly id: TIdentifier;\n readonly createdAt: Date;\n readonly updatedAt: Date;\n readonly aggregateVersion: number;\n}\n\n/**\n * Base class for domain entities — objects defined by a stable identity rather\n * than by their attributes. Two entities are \"the same\" when their `id`\n * matches, even if every other field differs; this is the opposite of a\n * {@link ValueObject}, which is defined entirely by its contents.\n *\n * The class owns the bookkeeping common to every aggregate root: a creation\n * timestamp that never changes, a last-modified timestamp, and an\n * `aggregateVersion` counter used for optimistic concurrency control. All three\n * are validated on construction and the dates are defensively cloned, so an\n * entity can never be built into — or leak — an inconsistent temporal state.\n *\n * @typeParam TIdentifier - The identity type (e.g. a branded string id or a VO).\n */\n@version(\"1.0\")\nabstract class Entity<TIdentifier> {\n declare 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 /**\n * Reconstitutes an entity from its persisted {@link EntityState}.\n *\n * Validates the temporal invariants up front so an invalid entity is\n * impossible to construct: both dates must be valid, the aggregate version\n * must be a non-negative integer, and `updatedAt` may not predate\n * `createdAt`. Both dates are cloned on the way in so a later mutation of\n * the caller's `Date` objects cannot reach into the entity's internal state.\n *\n * Declared `protected` because entities are reconstituted through a\n * subclass factory, never instantiated directly by application code.\n *\n * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.\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 /** The entity's stable identity — the basis for equality between entities. */\n public get id(): TIdentifier {\n return this._id;\n }\n\n /**\n * When the entity was first created.\n *\n * Returns a clone so callers cannot mutate the entity's internal `Date`;\n * the value is fixed at construction and never changes thereafter.\n */\n public get createdAt(): Date {\n return cloneDate(this._createdAt);\n }\n\n /**\n * When the entity was last modified.\n *\n * Returns a clone for the same encapsulation reason as {@link createdAt};\n * the underlying value advances only through {@link markAsModified}.\n */\n public get updatedAt(): Date {\n return cloneDate(this._updatedAt);\n }\n\n /**\n * Monotonic counter incremented on every mutation, used for optimistic\n * concurrency control: a writer reads this value, and the persistence layer\n * rejects the write if the stored version has moved on in the meantime.\n */\n public get aggregateVersion(): number {\n return this._aggregateVersion;\n }\n\n /**\n * The schema/contract version stamped on this entity type by the\n * `@version` decorator — used to detect and migrate state persisted under\n * an older shape.\n */\n public get contractVersion(): ContractVersion {\n return Entity.CONTRACT_VERSION;\n }\n\n /**\n * The single seam through which an entity records a mutation: it advances\n * `updatedAt` and bumps {@link aggregateVersion} by one. Subclasses must\n * call this from every state-changing method so the version counter stays\n * an accurate optimistic-lock token.\n *\n * @param updatedAt - The modification instant; defaults to now. Validated\n * and required not to predate `createdAt`, preserving the same invariant\n * the constructor enforces.\n * @returns The new aggregate version after the increment.\n * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.\n */\n protected markAsModified(updatedAt: Date = new Date()): number {\n assertValidDate(\"updatedAt\", updatedAt);\n\n if (updatedAt.getTime() < this._createdAt.getTime()) {\n throw new InvariantViolationException(\n \"updatedAt cannot be earlier than createdAt\",\n );\n }\n\n this._updatedAt = cloneDate(updatedAt);\n this._aggregateVersion += 1;\n\n return this._aggregateVersion;\n }\n}\n\nexport { Entity, type EntityState };\n"],"mappings":";;;;AAEA,SAAS,4BAA4B,kBAAgC;CACjE,IAAI,CAAC,OAAO,UAAU,gBAAgB,KAAK,mBAAmB,GAC1D,MAAM,IAAIA,sCAAAA,4BACN,8DAA8D,kBAClE;AAER
|
|
1
|
+
{"version":3,"file":"entity.cjs","names":["InvariantViolationException","InvariantViolationException","cloneDate","version"],"sources":["../src/core/shared/aggregate-version.ts","../src/core/domain/entity.ts"],"sourcesContent":["import { InvariantViolationException } from \"../exceptions/invariant-violation-exception.js\";\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","import { InvariantViolationException } from \"../exceptions/invariant-violation-exception.js\";\nimport { assertValidAggregateVersion } from \"../shared/aggregate-version.js\";\nimport { assertValidDate, cloneDate } from \"../shared/temporal-guards.js\";\nimport { type ContractVersion, version } from \"../versioning/version.js\";\n\n/**\n * The minimal persisted shape needed to reconstitute an {@link Entity}.\n *\n * This is the contract between storage and the domain: a repository maps a row\n * (or document) onto these four fields and hands them to a subclass constructor.\n * `aggregateVersion` travels with the state so optimistic-concurrency checks\n * survive a round-trip through the database.\n */\ninterface EntityState<TIdentifier> {\n readonly id: TIdentifier;\n readonly createdAt: Date;\n readonly updatedAt: Date;\n readonly aggregateVersion: number;\n}\n\n/**\n * Base class for domain entities — objects defined by a stable identity rather\n * than by their attributes. Two entities are \"the same\" when their `id`\n * matches, even if every other field differs; this is the opposite of a\n * {@link ValueObject}, which is defined entirely by its contents.\n *\n * The class owns the bookkeeping common to every aggregate root: a creation\n * timestamp that never changes, a last-modified timestamp, and an\n * `aggregateVersion` counter used for optimistic concurrency control. All three\n * are validated on construction and the dates are defensively cloned, so an\n * entity can never be built into — or leak — an inconsistent temporal state.\n *\n * @typeParam TIdentifier - The identity type (e.g. a branded string id or a VO).\n */\n@version(\"1.0\")\nabstract class Entity<TIdentifier> {\n declare 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 /**\n * Reconstitutes an entity from its persisted {@link EntityState}.\n *\n * Validates the temporal invariants up front so an invalid entity is\n * impossible to construct: both dates must be valid, the aggregate version\n * must be a non-negative integer, and `updatedAt` may not predate\n * `createdAt`. Both dates are cloned on the way in so a later mutation of\n * the caller's `Date` objects cannot reach into the entity's internal state.\n *\n * Declared `protected` because entities are reconstituted through a\n * subclass factory, never instantiated directly by application code.\n *\n * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.\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 /** The entity's stable identity — the basis for equality between entities. */\n public get id(): TIdentifier {\n return this._id;\n }\n\n /**\n * When the entity was first created.\n *\n * Returns a clone so callers cannot mutate the entity's internal `Date`;\n * the value is fixed at construction and never changes thereafter.\n */\n public get createdAt(): Date {\n return cloneDate(this._createdAt);\n }\n\n /**\n * When the entity was last modified.\n *\n * Returns a clone for the same encapsulation reason as {@link createdAt};\n * the underlying value advances only through {@link markAsModified}.\n */\n public get updatedAt(): Date {\n return cloneDate(this._updatedAt);\n }\n\n /**\n * Monotonic counter incremented on every mutation, used for optimistic\n * concurrency control: a writer reads this value, and the persistence layer\n * rejects the write if the stored version has moved on in the meantime.\n */\n public get aggregateVersion(): number {\n return this._aggregateVersion;\n }\n\n /**\n * The schema/contract version stamped on this entity type by the\n * `@version` decorator — used to detect and migrate state persisted under\n * an older shape.\n */\n public get contractVersion(): ContractVersion {\n return (this.constructor as typeof Entity).CONTRACT_VERSION;\n }\n\n /**\n * The single seam through which an entity records a mutation: it advances\n * `updatedAt` and bumps {@link aggregateVersion} by one. Subclasses must\n * call this from every state-changing method so the version counter stays\n * an accurate optimistic-lock token.\n *\n * @param updatedAt - The modification instant; defaults to now. Validated\n * and required not to predate `createdAt`, preserving the same invariant\n * the constructor enforces.\n * @returns The new aggregate version after the increment.\n * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.\n */\n protected markAsModified(updatedAt: Date = new Date()): number {\n assertValidDate(\"updatedAt\", updatedAt);\n\n if (updatedAt.getTime() < this._createdAt.getTime()) {\n throw new InvariantViolationException(\n \"updatedAt cannot be earlier than createdAt\",\n );\n }\n\n this._updatedAt = cloneDate(updatedAt);\n this._aggregateVersion += 1;\n\n return this._aggregateVers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,KAAK,CAAA,GAAA,MAAA"}
|
package/dist/entity.js
CHANGED
|
@@ -7,7 +7,6 @@ function assertValidAggregateVersion(aggregateVersion) {
|
|
|
7
7
|
}
|
|
8
8
|
//#endregion
|
|
9
9
|
//#region src/core/domain/entity.ts
|
|
10
|
-
var _Entity;
|
|
11
10
|
/**
|
|
12
11
|
* Base class for domain entities — objects defined by a stable identity rather
|
|
13
12
|
* than by their attributes. Two entities are "the same" when their `id`
|
|
@@ -23,9 +22,6 @@ var _Entity;
|
|
|
23
22
|
* @typeParam TIdentifier - The identity type (e.g. a branded string id or a VO).
|
|
24
23
|
*/
|
|
25
24
|
let Entity = class Entity {
|
|
26
|
-
static {
|
|
27
|
-
_Entity = this;
|
|
28
|
-
}
|
|
29
25
|
/**
|
|
30
26
|
* Reconstitutes an entity from its persisted {@link EntityState}.
|
|
31
27
|
*
|
|
@@ -86,7 +82,7 @@ let Entity = class Entity {
|
|
|
86
82
|
* an older shape.
|
|
87
83
|
*/
|
|
88
84
|
get contractVersion() {
|
|
89
|
-
return
|
|
85
|
+
return this.constructor.CONTRACT_VERSION;
|
|
90
86
|
}
|
|
91
87
|
/**
|
|
92
88
|
* The single seam through which an entity records a mutation: it advances
|
|
@@ -108,7 +104,7 @@ let Entity = class Entity {
|
|
|
108
104
|
return this._aggregateVersion;
|
|
109
105
|
}
|
|
110
106
|
};
|
|
111
|
-
Entity =
|
|
107
|
+
Entity = __decorate([version("1.0")], Entity);
|
|
112
108
|
//#endregion
|
|
113
109
|
export { assertValidAggregateVersion as n, Entity as t };
|
|
114
110
|
|
package/dist/entity.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"entity.js","names":[],"sources":["../src/core/shared/aggregate-version.ts","../src/core/domain/entity.ts"],"sourcesContent":["import { InvariantViolationException } from \"../exceptions/invariant-violation-exception.js\";\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","import { InvariantViolationException } from \"../exceptions/invariant-violation-exception.js\";\nimport { assertValidAggregateVersion } from \"../shared/aggregate-version.js\";\nimport { assertValidDate, cloneDate } from \"../shared/temporal-guards.js\";\nimport { type ContractVersion, version } from \"../versioning/version.js\";\n\n/**\n * The minimal persisted shape needed to reconstitute an {@link Entity}.\n *\n * This is the contract between storage and the domain: a repository maps a row\n * (or document) onto these four fields and hands them to a subclass constructor.\n * `aggregateVersion` travels with the state so optimistic-concurrency checks\n * survive a round-trip through the database.\n */\ninterface EntityState<TIdentifier> {\n readonly id: TIdentifier;\n readonly createdAt: Date;\n readonly updatedAt: Date;\n readonly aggregateVersion: number;\n}\n\n/**\n * Base class for domain entities — objects defined by a stable identity rather\n * than by their attributes. Two entities are \"the same\" when their `id`\n * matches, even if every other field differs; this is the opposite of a\n * {@link ValueObject}, which is defined entirely by its contents.\n *\n * The class owns the bookkeeping common to every aggregate root: a creation\n * timestamp that never changes, a last-modified timestamp, and an\n * `aggregateVersion` counter used for optimistic concurrency control. All three\n * are validated on construction and the dates are defensively cloned, so an\n * entity can never be built into — or leak — an inconsistent temporal state.\n *\n * @typeParam TIdentifier - The identity type (e.g. a branded string id or a VO).\n */\n@version(\"1.0\")\nabstract class Entity<TIdentifier> {\n declare 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 /**\n * Reconstitutes an entity from its persisted {@link EntityState}.\n *\n * Validates the temporal invariants up front so an invalid entity is\n * impossible to construct: both dates must be valid, the aggregate version\n * must be a non-negative integer, and `updatedAt` may not predate\n * `createdAt`. Both dates are cloned on the way in so a later mutation of\n * the caller's `Date` objects cannot reach into the entity's internal state.\n *\n * Declared `protected` because entities are reconstituted through a\n * subclass factory, never instantiated directly by application code.\n *\n * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.\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 /** The entity's stable identity — the basis for equality between entities. */\n public get id(): TIdentifier {\n return this._id;\n }\n\n /**\n * When the entity was first created.\n *\n * Returns a clone so callers cannot mutate the entity's internal `Date`;\n * the value is fixed at construction and never changes thereafter.\n */\n public get createdAt(): Date {\n return cloneDate(this._createdAt);\n }\n\n /**\n * When the entity was last modified.\n *\n * Returns a clone for the same encapsulation reason as {@link createdAt};\n * the underlying value advances only through {@link markAsModified}.\n */\n public get updatedAt(): Date {\n return cloneDate(this._updatedAt);\n }\n\n /**\n * Monotonic counter incremented on every mutation, used for optimistic\n * concurrency control: a writer reads this value, and the persistence layer\n * rejects the write if the stored version has moved on in the meantime.\n */\n public get aggregateVersion(): number {\n return this._aggregateVersion;\n }\n\n /**\n * The schema/contract version stamped on this entity type by the\n * `@version` decorator — used to detect and migrate state persisted under\n * an older shape.\n */\n public get contractVersion(): ContractVersion {\n return Entity.CONTRACT_VERSION;\n }\n\n /**\n * The single seam through which an entity records a mutation: it advances\n * `updatedAt` and bumps {@link aggregateVersion} by one. Subclasses must\n * call this from every state-changing method so the version counter stays\n * an accurate optimistic-lock token.\n *\n * @param updatedAt - The modification instant; defaults to now. Validated\n * and required not to predate `createdAt`, preserving the same invariant\n * the constructor enforces.\n * @returns The new aggregate version after the increment.\n * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.\n */\n protected markAsModified(updatedAt: Date = new Date()): number {\n assertValidDate(\"updatedAt\", updatedAt);\n\n if (updatedAt.getTime() < this._createdAt.getTime()) {\n throw new InvariantViolationException(\n \"updatedAt cannot be earlier than createdAt\",\n );\n }\n\n this._updatedAt = cloneDate(updatedAt);\n this._aggregateVersion += 1;\n\n return this._aggregateVersion;\n }\n}\n\nexport { Entity, type EntityState };\n"],"mappings":";;;;AAEA,SAAS,4BAA4B,kBAAgC;CACjE,IAAI,CAAC,OAAO,UAAU,gBAAgB,KAAK,mBAAmB,GAC1D,MAAM,IAAI,4BACN,8DAA8D,kBAClE;AAER
|
|
1
|
+
{"version":3,"file":"entity.js","names":[],"sources":["../src/core/shared/aggregate-version.ts","../src/core/domain/entity.ts"],"sourcesContent":["import { InvariantViolationException } from \"../exceptions/invariant-violation-exception.js\";\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","import { InvariantViolationException } from \"../exceptions/invariant-violation-exception.js\";\nimport { assertValidAggregateVersion } from \"../shared/aggregate-version.js\";\nimport { assertValidDate, cloneDate } from \"../shared/temporal-guards.js\";\nimport { type ContractVersion, version } from \"../versioning/version.js\";\n\n/**\n * The minimal persisted shape needed to reconstitute an {@link Entity}.\n *\n * This is the contract between storage and the domain: a repository maps a row\n * (or document) onto these four fields and hands them to a subclass constructor.\n * `aggregateVersion` travels with the state so optimistic-concurrency checks\n * survive a round-trip through the database.\n */\ninterface EntityState<TIdentifier> {\n readonly id: TIdentifier;\n readonly createdAt: Date;\n readonly updatedAt: Date;\n readonly aggregateVersion: number;\n}\n\n/**\n * Base class for domain entities — objects defined by a stable identity rather\n * than by their attributes. Two entities are \"the same\" when their `id`\n * matches, even if every other field differs; this is the opposite of a\n * {@link ValueObject}, which is defined entirely by its contents.\n *\n * The class owns the bookkeeping common to every aggregate root: a creation\n * timestamp that never changes, a last-modified timestamp, and an\n * `aggregateVersion` counter used for optimistic concurrency control. All three\n * are validated on construction and the dates are defensively cloned, so an\n * entity can never be built into — or leak — an inconsistent temporal state.\n *\n * @typeParam TIdentifier - The identity type (e.g. a branded string id or a VO).\n */\n@version(\"1.0\")\nabstract class Entity<TIdentifier> {\n declare 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 /**\n * Reconstitutes an entity from its persisted {@link EntityState}.\n *\n * Validates the temporal invariants up front so an invalid entity is\n * impossible to construct: both dates must be valid, the aggregate version\n * must be a non-negative integer, and `updatedAt` may not predate\n * `createdAt`. Both dates are cloned on the way in so a later mutation of\n * the caller's `Date` objects cannot reach into the entity's internal state.\n *\n * Declared `protected` because entities are reconstituted through a\n * subclass factory, never instantiated directly by application code.\n *\n * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.\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 /** The entity's stable identity — the basis for equality between entities. */\n public get id(): TIdentifier {\n return this._id;\n }\n\n /**\n * When the entity was first created.\n *\n * Returns a clone so callers cannot mutate the entity's internal `Date`;\n * the value is fixed at construction and never changes thereafter.\n */\n public get createdAt(): Date {\n return cloneDate(this._createdAt);\n }\n\n /**\n * When the entity was last modified.\n *\n * Returns a clone for the same encapsulation reason as {@link createdAt};\n * the underlying value advances only through {@link markAsModified}.\n */\n public get updatedAt(): Date {\n return cloneDate(this._updatedAt);\n }\n\n /**\n * Monotonic counter incremented on every mutation, used for optimistic\n * concurrency control: a writer reads this value, and the persistence layer\n * rejects the write if the stored version has moved on in the meantime.\n */\n public get aggregateVersion(): number {\n return this._aggregateVersion;\n }\n\n /**\n * The schema/contract version stamped on this entity type by the\n * `@version` decorator — used to detect and migrate state persisted under\n * an older shape.\n */\n public get contractVersion(): ContractVersion {\n return (this.constructor as typeof Entity).CONTRACT_VERSION;\n }\n\n /**\n * The single seam through which an entity records a mutation: it advances\n * `updatedAt` and bumps {@link aggregateVersion} by one. Subclasses must\n * call this from every state-changing method so the version counter stays\n * an accurate optimistic-lock token.\n *\n * @param updatedAt - The modification instant; defaults to now. Validated\n * and required not to predate `createdAt`, preserving the same invariant\n * the constructor enforces.\n * @returns The new aggregate version after the increment.\n * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.\n */\n protected markAsModified(updatedAt: Date = new Date()): number {\n assertValidDate(\"updatedAt\", updatedAt);\n\n if (updatedAt.getTime() < this._createdAt.getTime()) {\n throw new InvariantViolationException(\n \"updatedAt cannot be earlier than createdAt\",\n );\n }\n\n this._updatedAt = cloneDate(updatedAt);\n this._aggregateVersion += 1;\n\n return this._aggregateVersion;\n }\n}\n\nexport { Entity, type EntityState };\n"],"mappings":";;;;AAEA,SAAS,4BAA4B,kBAAgC;CACjE,IAAI,CAAC,OAAO,UAAU,gBAAgB,KAAK,mBAAmB,GAC1D,MAAM,IAAI,4BACN,8DAA8D,kBAClE;AAER;;;;;;;;;;;;;;;;;AC0BA,IAAA,SAAA,MACe,OAAoB;;;;;;;;;;;;;;;CAsB/B,YAAsB,OAAiC;EACnD,gBAAgB,aAAa,MAAM,SAAS;EAC5C,gBAAgB,aAAa,MAAM,SAAS;EAC5C,4BAA4B,MAAM,gBAAgB;EAElD,IAAI,MAAM,UAAU,QAAQ,IAAI,MAAM,UAAU,QAAQ,GACpD,MAAM,IAAI,4BACN,4CACJ;EAGJ,KAAK,MAAM,MAAM;EACjB,KAAK,aAAa,UAAU,MAAM,SAAS;EAC3C,KAAK,aAAa,UAAU,MAAM,SAAS;EAC3C,KAAK,oBAAoB,MAAM;CACnC;;CAGA,IAAW,KAAkB;EACzB,OAAO,KAAK;CAChB;;;;;;;CAQA,IAAW,YAAkB;EACzB,OAAO,UAAU,KAAK,UAAU;CACpC;;;;;;;CAQA,IAAW,YAAkB;EACzB,OAAO,UAAU,KAAK,UAAU;CACpC;;;;;;CAOA,IAAW,mBAA2B;EAClC,OAAO,KAAK;CAChB;;;;;;CAOA,IAAW,kBAAmC;EAC1C,OAAQ,KAAK,YAA8B;CAC/C;;;;;;;;;;;;;CAcA,eAAyB,4BAAkB,IAAI,KAAK,GAAW;EAC3D,gBAAgB,aAAa,SAAS;EAEtC,IAAI,UAAU,QAAQ,IAAI,KAAK,WAAW,QAAQ,GAC9C,MAAM,IAAI,4BACN,4CACJ;EAGJ,KAAK,aAAa,UAAU,SAAS;EACrC,KAAK,qBAAqB;EAE1B,OAAO,KAAK;CAChB;AACJ;qBA7GC,QAAQ,KAAK,CAAA,GAAA,MAAA"}
|
package/dist/errors/index.cjs
CHANGED
|
@@ -3,6 +3,7 @@ const require_app_error = require("../app-error.cjs");
|
|
|
3
3
|
const require_validation_error = require("../validation-error.cjs");
|
|
4
4
|
const require_authorization_error = require("../authorization-error.cjs");
|
|
5
5
|
const require_not_found_error = require("../not-found-error.cjs");
|
|
6
|
+
const require_stable_stringify = require("../stable-stringify.cjs");
|
|
6
7
|
const require_hashing = require("../hashing.cjs");
|
|
7
8
|
const require_unexpected_error = require("../unexpected-error.cjs");
|
|
8
9
|
exports.AlreadyExistsError = require_validation_error.AlreadyExistsError;
|
|
@@ -39,5 +40,5 @@ exports.payloadHash = require_hashing.payloadHash;
|
|
|
39
40
|
exports.safePreview = require_validation_error.safePreview;
|
|
40
41
|
exports.serializationErrorCode = require_app_error.serializationErrorCode;
|
|
41
42
|
exports.sha256Hex = require_hashing.sha256Hex;
|
|
42
|
-
exports.stableStringify =
|
|
43
|
+
exports.stableStringify = require_stable_stringify.stableStringify;
|
|
43
44
|
exports.translateUniqueViolationToDuplicate = require_validation_error.translateUniqueViolationToDuplicate;
|
package/dist/errors/index.js
CHANGED
|
@@ -2,6 +2,7 @@ import { i as serializationErrorCode, n as assertJsonSafeMetadata, r as ErrorCod
|
|
|
2
2
|
import { C as translateUniqueViolationToDuplicate, S as UniqueConstraintViolationError, _ as IdempotencyPayloadMismatchError, a as evaluateTemporalWindow, b as ConflictError, c as SerializationInError, d as safePreview, f as LegacyIncompatibleError, g as IdempotencyKeyMissingError, h as IdempotencyInProgressError, i as TemporalError, l as SerializationMessages, m as IdempotencyError, n as ExpiredError, o as SerializationCodes, p as IntegrationError, r as NotYetValidError, s as SerializationError, t as ValidationError, u as SerializationOutError, v as IdempotencyReplayNotSupportedError, w as AuthenticationError, x as DuplicateError, y as AlreadyExistsError } from "../validation-error.js";
|
|
3
3
|
import { t as AuthorizationError } from "../authorization-error.js";
|
|
4
4
|
import { n as BusinessRuleViolationError, t as NotFoundError } from "../not-found-error.js";
|
|
5
|
-
import {
|
|
5
|
+
import { t as stableStringify } from "../stable-stringify.js";
|
|
6
|
+
import { n as sha256Hex, t as payloadHash } from "../hashing.js";
|
|
6
7
|
import { t as UnexpectedError } from "../unexpected-error.js";
|
|
7
8
|
export { AlreadyExistsError, AppError, AuthenticationError, AuthorizationError, BusinessRuleViolationError, ConflictError, SerializationInError as DeserializationError, SerializationInError, DuplicateError, ErrorCodes, ExpiredError, IdempotencyError, IdempotencyInProgressError, IdempotencyKeyMissingError, IdempotencyPayloadMismatchError, IdempotencyReplayNotSupportedError, IntegrationError, LegacyIncompatibleError, NotFoundError, NotYetValidError, SerializationCodes, SerializationError, SerializationMessages, SerializationOutError, TemporalError, UnexpectedError, UniqueConstraintViolationError, ValidationError, assertJsonSafeMetadata, evaluateTemporalWindow, payloadHash, safePreview, serializationErrorCode, sha256Hex, stableStringify, translateUniqueViolationToDuplicate };
|
package/dist/hashing.cjs
CHANGED
|
@@ -1,47 +1,11 @@
|
|
|
1
|
+
const require_stable_stringify = require("./stable-stringify.cjs");
|
|
1
2
|
let node_crypto = require("node:crypto");
|
|
2
3
|
//#region src/core/shared/hashing.ts
|
|
3
|
-
const CIRCULAR_STRUCTURE_MESSAGE = "Cannot stably stringify a circular structure";
|
|
4
4
|
function sha256Hex(value) {
|
|
5
5
|
return (0, node_crypto.createHash)("sha256").update(value, "utf8").digest("hex");
|
|
6
6
|
}
|
|
7
|
-
function sortKeysDeep(value, seen) {
|
|
8
|
-
if (Array.isArray(value)) {
|
|
9
|
-
if (seen.has(value)) throw new TypeError(CIRCULAR_STRUCTURE_MESSAGE);
|
|
10
|
-
seen.add(value);
|
|
11
|
-
const mapped = value.map((item) => sortKeysDeep(item, seen));
|
|
12
|
-
seen.delete(value);
|
|
13
|
-
return mapped;
|
|
14
|
-
}
|
|
15
|
-
if (value instanceof Date) return value;
|
|
16
|
-
if (value && typeof value === "object") {
|
|
17
|
-
if (seen.has(value)) throw new TypeError(CIRCULAR_STRUCTURE_MESSAGE);
|
|
18
|
-
seen.add(value);
|
|
19
|
-
const record = value;
|
|
20
|
-
const ordered = Object.create(null);
|
|
21
|
-
for (const key of Object.keys(record).sort()) ordered[key] = sortKeysDeep(record[key], seen);
|
|
22
|
-
seen.delete(value);
|
|
23
|
-
return ordered;
|
|
24
|
-
}
|
|
25
|
-
return value;
|
|
26
|
-
}
|
|
27
|
-
/**
|
|
28
|
-
* Deterministic JSON string with object keys sorted recursively, so key order
|
|
29
|
-
* does not affect the output.
|
|
30
|
-
*
|
|
31
|
-
* Follows `JSON.stringify` semantics for the values it serializes: `undefined`,
|
|
32
|
-
* functions and symbols are dropped, non-finite numbers become `null`, `bigint`
|
|
33
|
-
* throws, and `Map`/`Set` serialize as `{}`. Distinct payloads can therefore
|
|
34
|
-
* collapse to the same string — for collision-resistant hashing use
|
|
35
|
-
* `PolicyHashing.canonicalJson` (policies/utils), which rejects those values
|
|
36
|
-
* up front.
|
|
37
|
-
*
|
|
38
|
-
* @throws {TypeError} On circular references (mirroring `JSON.stringify`).
|
|
39
|
-
*/
|
|
40
|
-
function stableStringify(value) {
|
|
41
|
-
return JSON.stringify(sortKeysDeep(value, /* @__PURE__ */ new WeakSet()));
|
|
42
|
-
}
|
|
43
7
|
function payloadHash(value) {
|
|
44
|
-
return sha256Hex(stableStringify(value));
|
|
8
|
+
return sha256Hex(require_stable_stringify.stableStringify(value));
|
|
45
9
|
}
|
|
46
10
|
//#endregion
|
|
47
11
|
Object.defineProperty(exports, "payloadHash", {
|
|
@@ -56,11 +20,5 @@ Object.defineProperty(exports, "sha256Hex", {
|
|
|
56
20
|
return sha256Hex;
|
|
57
21
|
}
|
|
58
22
|
});
|
|
59
|
-
Object.defineProperty(exports, "stableStringify", {
|
|
60
|
-
enumerable: true,
|
|
61
|
-
get: function() {
|
|
62
|
-
return stableStringify;
|
|
63
|
-
}
|
|
64
|
-
});
|
|
65
23
|
|
|
66
24
|
//# sourceMappingURL=hashing.cjs.map
|
package/dist/hashing.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hashing.cjs","names":[],"sources":["../src/core/shared/hashing.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\n\
|
|
1
|
+
{"version":3,"file":"hashing.cjs","names":["stableStringify"],"sources":["../src/core/shared/hashing.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\n\nimport { stableStringify } from \"./stable-stringify.js\";\n\nfunction sha256Hex(value: string): string {\n return createHash(\"sha256\").update(value, \"utf8\").digest(\"hex\");\n}\n\nfunction payloadHash(value: unknown): string {\n return sha256Hex(stableStringify(value));\n}\n\nexport { payloadHash, sha256Hex, stableStringify };\n"],"mappings":";;;AAIA,SAAS,UAAU,OAAuB;CACtC,QAAA,GAAA,YAAA,YAAkB,QAAQ,EAAE,OAAO,OAAO,MAAM,EAAE,OAAO,KAAK;AAClE;AAEA,SAAS,YAAY,OAAwB;CACzC,OAAO,UAAUA,yBAAAA,gBAAgB,KAAK,CAAC;AAC3C"}
|
package/dist/hashing.js
CHANGED
|
@@ -1,49 +1,13 @@
|
|
|
1
|
+
import { t as stableStringify } from "./stable-stringify.js";
|
|
1
2
|
import { createHash } from "node:crypto";
|
|
2
3
|
//#region src/core/shared/hashing.ts
|
|
3
|
-
const CIRCULAR_STRUCTURE_MESSAGE = "Cannot stably stringify a circular structure";
|
|
4
4
|
function sha256Hex(value) {
|
|
5
5
|
return createHash("sha256").update(value, "utf8").digest("hex");
|
|
6
6
|
}
|
|
7
|
-
function sortKeysDeep(value, seen) {
|
|
8
|
-
if (Array.isArray(value)) {
|
|
9
|
-
if (seen.has(value)) throw new TypeError(CIRCULAR_STRUCTURE_MESSAGE);
|
|
10
|
-
seen.add(value);
|
|
11
|
-
const mapped = value.map((item) => sortKeysDeep(item, seen));
|
|
12
|
-
seen.delete(value);
|
|
13
|
-
return mapped;
|
|
14
|
-
}
|
|
15
|
-
if (value instanceof Date) return value;
|
|
16
|
-
if (value && typeof value === "object") {
|
|
17
|
-
if (seen.has(value)) throw new TypeError(CIRCULAR_STRUCTURE_MESSAGE);
|
|
18
|
-
seen.add(value);
|
|
19
|
-
const record = value;
|
|
20
|
-
const ordered = Object.create(null);
|
|
21
|
-
for (const key of Object.keys(record).sort()) ordered[key] = sortKeysDeep(record[key], seen);
|
|
22
|
-
seen.delete(value);
|
|
23
|
-
return ordered;
|
|
24
|
-
}
|
|
25
|
-
return value;
|
|
26
|
-
}
|
|
27
|
-
/**
|
|
28
|
-
* Deterministic JSON string with object keys sorted recursively, so key order
|
|
29
|
-
* does not affect the output.
|
|
30
|
-
*
|
|
31
|
-
* Follows `JSON.stringify` semantics for the values it serializes: `undefined`,
|
|
32
|
-
* functions and symbols are dropped, non-finite numbers become `null`, `bigint`
|
|
33
|
-
* throws, and `Map`/`Set` serialize as `{}`. Distinct payloads can therefore
|
|
34
|
-
* collapse to the same string — for collision-resistant hashing use
|
|
35
|
-
* `PolicyHashing.canonicalJson` (policies/utils), which rejects those values
|
|
36
|
-
* up front.
|
|
37
|
-
*
|
|
38
|
-
* @throws {TypeError} On circular references (mirroring `JSON.stringify`).
|
|
39
|
-
*/
|
|
40
|
-
function stableStringify(value) {
|
|
41
|
-
return JSON.stringify(sortKeysDeep(value, /* @__PURE__ */ new WeakSet()));
|
|
42
|
-
}
|
|
43
7
|
function payloadHash(value) {
|
|
44
8
|
return sha256Hex(stableStringify(value));
|
|
45
9
|
}
|
|
46
10
|
//#endregion
|
|
47
|
-
export { sha256Hex as n,
|
|
11
|
+
export { sha256Hex as n, payloadHash as t };
|
|
48
12
|
|
|
49
13
|
//# sourceMappingURL=hashing.js.map
|
package/dist/hashing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hashing.js","names":[],"sources":["../src/core/shared/hashing.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\n\
|
|
1
|
+
{"version":3,"file":"hashing.js","names":[],"sources":["../src/core/shared/hashing.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\n\nimport { stableStringify } from \"./stable-stringify.js\";\n\nfunction sha256Hex(value: string): string {\n return createHash(\"sha256\").update(value, \"utf8\").digest(\"hex\");\n}\n\nfunction payloadHash(value: unknown): string {\n return sha256Hex(stableStringify(value));\n}\n\nexport { payloadHash, sha256Hex, stableStringify };\n"],"mappings":";;;AAIA,SAAS,UAAU,OAAuB;CACtC,OAAO,WAAW,QAAQ,EAAE,OAAO,OAAO,MAAM,EAAE,OAAO,KAAK;AAClE;AAEA,SAAS,YAAY,OAAwB;CACzC,OAAO,UAAU,gBAAgB,KAAK,CAAC;AAC3C"}
|
package/dist/index.cjs
CHANGED
|
@@ -3,6 +3,7 @@ const require_app_error = require("./app-error.cjs");
|
|
|
3
3
|
const require_validation_error = require("./validation-error.cjs");
|
|
4
4
|
const require_authorization_error = require("./authorization-error.cjs");
|
|
5
5
|
const require_not_found_error = require("./not-found-error.cjs");
|
|
6
|
+
const require_stable_stringify = require("./stable-stringify.cjs");
|
|
6
7
|
const require_hashing = require("./hashing.cjs");
|
|
7
8
|
const require_unexpected_error = require("./unexpected-error.cjs");
|
|
8
9
|
const require_validation_code = require("./validation-code.cjs");
|
|
@@ -29,7 +30,7 @@ const require_domain_event_contracts = require("./domain-event-contracts.cjs");
|
|
|
29
30
|
const require_outcome = require("./outcome.cjs");
|
|
30
31
|
const require_gate_engine_registry = require("./gate-engine-registry.cjs");
|
|
31
32
|
//#region src/version.ts
|
|
32
|
-
const version$1 = "1.
|
|
33
|
+
const version$1 = "1.5.0";
|
|
33
34
|
//#endregion
|
|
34
35
|
//#region src/index.ts
|
|
35
36
|
const ERP_CORE_NAME = "erp-core";
|
|
@@ -174,7 +175,7 @@ exports.registerNamespacedContextResolversIn = require_policy_service.registerNa
|
|
|
174
175
|
exports.safePreview = require_validation_error.safePreview;
|
|
175
176
|
exports.serializationErrorCode = require_app_error.serializationErrorCode;
|
|
176
177
|
exports.sha256Hex = require_hashing.sha256Hex;
|
|
177
|
-
exports.stableStringify =
|
|
178
|
+
exports.stableStringify = require_stable_stringify.stableStringify;
|
|
178
179
|
exports.translateUniqueViolationToDuplicate = require_validation_error.translateUniqueViolationToDuplicate;
|
|
179
180
|
exports.version = require_immutable.version;
|
|
180
181
|
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["version","version"],"sources":["../src/version.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.
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["version","version"],"sources":["../src/version.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.5.0\";\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;;;ACFvB,MAAa,gBAAgB;AAC7B,MAAa,mBAAmBC;AAEhC,MAAa,iBAAiB;CAC1B,MAAM;CACN,SAAS;AACb"}
|
package/dist/index.d.cts
CHANGED
|
@@ -27,10 +27,10 @@ import { a as buildDomainEventContractVersions, i as DomainEventEnvelope, n as D
|
|
|
27
27
|
|
|
28
28
|
//#region src/index.d.ts
|
|
29
29
|
declare const ERP_CORE_NAME = "erp-core";
|
|
30
|
-
declare const ERP_CORE_VERSION = "1.
|
|
30
|
+
declare const ERP_CORE_VERSION = "1.5.0";
|
|
31
31
|
declare const erpCoreRelease: {
|
|
32
32
|
readonly name: "erp-core";
|
|
33
|
-
readonly version: "1.
|
|
33
|
+
readonly version: "1.5.0";
|
|
34
34
|
};
|
|
35
35
|
//#endregion
|
|
36
36
|
export { AbacAttributes, AbacAuthorizer, AbacAuthorizerPort, AbacDecision, AbacPolicySet, AbacRequest, AbacRule, AbacRuleProps, AccessRequest, AlreadyExistsError, AppError, AppErrorOptions, AsOfSource, AuthenticationError, AuthenticationErrorMetadata, AuthenticationErrorReason, AuthorizationError, AuthorizationErrorMetadata, AuthorizationErrorReason, AuthorizationRequirement, AuthorizerPort, BasePlugin, BasePolicyDefinitionProps, BusinessRuleViolationError, BusinessRuleViolationException, CONTRACT_VERSION_PROPERTY, CacheStrategy, CombiningAlgorithm, Command, CommandInput, CommonOutcomeStatus, CompositeAccessRequest, CompositeAuthorizer, 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, ContractVersion, CoreConfig, CoreConfigOptions, CoreObservabilityConfig, CreateDomainEventEnvelopeInput, CreateTemporalContextInput, CreationRuleset, DeepReadonly, DeriveAsOfOptions, SerializationInError as DeserializationError, SerializationInError, DomainEventContractSelection, DomainEventContractVersions, DomainEventEnvelope, DomainException, DuplicateError, ERP_CORE_NAME, ERP_CORE_VERSION, Entity, EntityNotFoundException, 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, Grant, GrantProps, IdempotencyError, IdempotencyErrorMetadata, IdempotencyFailureKind, IdempotencyInProgressError, IdempotencyKeyMissingError, IdempotencyPayloadMismatchError, IdempotencyReplayNotSupportedError, InMemoryPolicyDefinitionRepository, IntegrationError, IntegrationErrorMetadata, IntegrationErrorReason, InvalidStateTransitionException, InvalidValueException, InvariantRuleset, InvariantViolationException, InvokeOptions, JsonSafePrimitive, JsonSafeRecord, JsonSafeValue, LegacyIncompatibleError, LogPayload, LoggerPort, MaybePromise, MetricLabels, MetricsPort, MultipleValidationException, NotFoundError, NotYetValidError, Ok, Outcome, Page, Permission, PermissionProps, PermissionSet, PipelineReducer, PluginContract, PluginManager, PolicyAsOfResolver, PolicyCatalog, PolicyCatalogEntryProps, PolicyCatalogFactory, PolicyContext, PolicyContextBuilder, PolicyContextBuilderOptions, PolicyContextPath, PolicyDecision, PolicyDecisionId, PolicyDefinition, PolicyDefinitionId, PolicyDefinitionProps, PolicyDefinitionStatus, PolicyEvaluationError, PolicyEvaluationErrors, PolicyEvaluationInput, PolicyEvaluationOutput, PolicyEvaluationResult, PolicyHashing, PolicyKey, PolicyKind, PolicyOwner, PolicyPackage, PolicyPort, PolicyPortError, PolicyResolver, PolicyScope, PolicyScopeLevel, PolicyScopeMatcher, PolicyService, PolicyServiceOptions, PolicyServiceParams, PolicyViolation, Query, RbacAuthorizer, Repository, RequestedBy, RequestedByKind, Result, ResultRepository, Role, RoleProps, RuleEffect, Ruleset, RulesetId, RulesetRegistry, SchoolId, Scope, ScopeChain, ScopeProps, SerializationBoundary, SerializationCodes, SerializationDirection, SerializationError, SerializationErrorMetadata, SerializationFailureCategory, SerializationMessages, SerializationOutError, TemporalContext, TemporalError, TemporalHistory, TemporalKind, TemporalRepository, TemporalUseCase, TemporalUseCaseInput, TemporalizedContextSeed, TenantId, TraceAttributeValue, TraceSpan, TracerPort, UnexpectedError, UniqueConstraintViolation, UniqueConstraintViolationError, UseCase, UseCaseObservability, UuidIdentifier, ValidationCode, ValidationError, ValidationException, ValidationField, ValidationViolation, ValueObject, ValueObjectPluginContract, ValueObjectRuleset, VersionedComputeEngine, VersionedGateEngine, VersionedTarget, abacContext, asPolicyDecisionId, asPolicyDefinitionId, asSchoolId, asTenantId, assertJsonSafeMetadata, assertTemporalContext, buildDomainEventContractVersions, contextResolverRegistry, coreConfig, createDomainEventEnvelope, createTemporalContext, erpCoreRelease, evaluateTemporalWindow, mapPolicyEvaluationError, payloadHash, rbacContextFields, registerNamespacedContextResolvers, registerNamespacedContextResolversIn, safePreview, serializationErrorCode, sha256Hex, stableStringify, translateUniqueViolationToDuplicate, version };
|