@cullet/erp-core 1.0.10 → 1.1.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.
Files changed (62) hide show
  1. package/KIT_CONTEXT.md +67 -0
  2. package/README.md +128 -1
  3. package/dist/app-error.d.ts +108 -0
  4. package/dist/application/index.d.ts +2 -0
  5. package/dist/application/index.js +2 -0
  6. package/dist/errors/index.d.ts +2 -1
  7. package/dist/errors/index.js +4 -2
  8. package/dist/gate-engine-registry.d.ts +80 -0
  9. package/dist/gate-v1-payload.schema.js +2 -28
  10. package/dist/gate-v1-payload.schema.js.map +1 -1
  11. package/dist/hashing.js +49 -0
  12. package/dist/hashing.js.map +1 -0
  13. package/dist/index.d.ts +122 -45
  14. package/dist/index.js +104 -85
  15. package/dist/index.js.map +1 -1
  16. package/dist/not-found-error.js +54 -0
  17. package/dist/not-found-error.js.map +1 -0
  18. package/dist/outcome.js +1 -1
  19. package/dist/parse-gate-payload.d.ts +3 -78
  20. package/dist/path.d.ts +89 -0
  21. package/dist/policies/engines/index.d.ts +2 -1
  22. package/dist/policies/index.d.ts +4 -2
  23. package/dist/policy-service.d.ts +102 -86
  24. package/dist/policy-service.js +78 -16
  25. package/dist/policy-service.js.map +1 -1
  26. package/dist/temporal-guards.js +30 -0
  27. package/dist/temporal-guards.js.map +1 -0
  28. package/dist/temporal-use-case.d.ts +309 -0
  29. package/dist/temporal-use-case.js +284 -0
  30. package/dist/temporal-use-case.js.map +1 -0
  31. package/dist/validation-code.js +34 -47
  32. package/dist/validation-code.js.map +1 -1
  33. package/dist/validation-error.d.ts +171 -74
  34. package/dist/validation-error.js +152 -38
  35. package/dist/validation-error.js.map +1 -1
  36. package/dist/validation-exception.js +18 -0
  37. package/dist/validation-exception.js.map +1 -0
  38. package/meta.json +4 -2
  39. package/package.json +5 -1
  40. package/src/application/index.ts +1 -0
  41. package/src/core/application/commands/index.ts +1 -0
  42. package/src/core/application/index.ts +12 -3
  43. package/src/core/application/ports/index.ts +2 -2
  44. package/src/core/application/ports/policy-port.ts +13 -3
  45. package/src/core/application/ports/repository.port.ts +37 -1
  46. package/src/core/application/temporal/temporal-use-case.ts +14 -2
  47. package/src/core/application/use-case.ts +133 -2
  48. package/src/core/domain/entity.ts +71 -0
  49. package/src/core/domain/value-object.ts +41 -0
  50. package/src/core/errors/app-error.ts +33 -0
  51. package/src/core/errors/authorization-error.ts +43 -0
  52. package/src/core/errors/conflict-error.ts +69 -0
  53. package/src/core/errors/integration-error.ts +25 -0
  54. package/src/core/errors/not-found-error.ts +14 -0
  55. package/src/core/errors/validation-error.ts +18 -0
  56. package/src/core/index.ts +1 -10
  57. package/src/core/policies/catalog/policy-catalog.ts +36 -0
  58. package/src/core/policies/resolver/policy-resolver.ts +10 -0
  59. package/src/core/policies/service/policy-service.ts +53 -0
  60. package/src/examples/application/cancel-order.example.ts +124 -0
  61. package/src/examples/application/in-memory-account-repository.example.ts +73 -0
  62. package/src/version.ts +1 -1
@@ -1,4 +1,3 @@
1
- import { createHash } from "node:crypto";
2
1
  //#region src/core/errors/error-codes.ts
3
2
  const ErrorCodes = {
4
3
  authentication: {
@@ -94,7 +93,40 @@ function assertJsonSafeMetadata(input) {
94
93
  }
95
94
  //#endregion
96
95
  //#region src/core/errors/app-error.ts
96
+ /**
97
+ * Root of the application/domain error hierarchy. Every error the system raises
98
+ * on purpose extends `AppError`, which gives callers a single `instanceof` to
99
+ * catch and a uniform, serializable shape to log and transport.
100
+ *
101
+ * Beyond the native `Error` message it carries a stable `code` (the contract the
102
+ * outside world matches on), an optional non-leaking `publicMessage`, a
103
+ * severity, JSON-safe `metadata`, and the correlation/request/command ids that
104
+ * stitch an error back to the request that produced it. The metadata is
105
+ * validated as JSON-safe on construction, so a logger can serialize any
106
+ * `AppError` without hitting a circular reference or a non-serializable value.
107
+ *
108
+ * Abstract on purpose: callers should throw a specific subclass (e.g.
109
+ * {@link ValidationError}, {@link NotFoundError}) so the `code` and shape are
110
+ * meaningful, never a bare `AppError`.
111
+ */
97
112
  var AppError = class extends Error {
113
+ /**
114
+ * Builds the common error envelope shared by every subclass.
115
+ *
116
+ * `name` is taken from `new.target` so the thrown instance reports its
117
+ * concrete subclass name (not `"AppError"`), and the prototype is re-pinned
118
+ * via `setPrototypeOf` so `instanceof` keeps working after transpilation to
119
+ * older targets where extending built-ins breaks the chain. `createdAtIso`
120
+ * defaults to now, and `metadata` is validated as JSON-safe so the error is
121
+ * always serializable.
122
+ *
123
+ * Declared `protected`: instantiate a concrete subclass, never `AppError`.
124
+ *
125
+ * @param message - The internal, developer-facing message.
126
+ * @param code - The stable machine-readable code callers match on.
127
+ * @param options - Optional cause, metadata, severity, and correlation ids.
128
+ * @throws When `options.metadata` contains a value that is not JSON-safe.
129
+ */
98
130
  constructor(message, code, options) {
99
131
  super(message);
100
132
  this.name = new.target.name;
@@ -132,51 +164,6 @@ var AppError = class extends Error {
132
164
  }
133
165
  };
134
166
  //#endregion
135
- //#region src/core/shared/hashing.ts
136
- const CIRCULAR_STRUCTURE_MESSAGE = "Cannot stably stringify a circular structure";
137
- function sha256Hex(value) {
138
- return createHash("sha256").update(value, "utf8").digest("hex");
139
- }
140
- function sortKeysDeep(value, seen) {
141
- if (Array.isArray(value)) {
142
- if (seen.has(value)) throw new TypeError(CIRCULAR_STRUCTURE_MESSAGE);
143
- seen.add(value);
144
- const mapped = value.map((item) => sortKeysDeep(item, seen));
145
- seen.delete(value);
146
- return mapped;
147
- }
148
- if (value instanceof Date) return value;
149
- if (value && typeof value === "object") {
150
- if (seen.has(value)) throw new TypeError(CIRCULAR_STRUCTURE_MESSAGE);
151
- seen.add(value);
152
- const record = value;
153
- const ordered = Object.create(null);
154
- for (const key of Object.keys(record).sort()) ordered[key] = sortKeysDeep(record[key], seen);
155
- seen.delete(value);
156
- return ordered;
157
- }
158
- return value;
159
- }
160
- /**
161
- * Deterministic JSON string with object keys sorted recursively, so key order
162
- * does not affect the output.
163
- *
164
- * Follows `JSON.stringify` semantics for the values it serializes: `undefined`,
165
- * functions and symbols are dropped, non-finite numbers become `null`, `bigint`
166
- * throws, and `Map`/`Set` serialize as `{}`. Distinct payloads can therefore
167
- * collapse to the same string — for collision-resistant hashing use
168
- * `PolicyHashing.canonicalJson` (policies/utils), which rejects those values
169
- * up front.
170
- *
171
- * @throws {TypeError} On circular references (mirroring `JSON.stringify`).
172
- */
173
- function stableStringify(value) {
174
- return JSON.stringify(sortKeysDeep(value, /* @__PURE__ */ new WeakSet()));
175
- }
176
- function payloadHash(value) {
177
- return sha256Hex(stableStringify(value));
178
- }
179
- //#endregion
180
167
  //#region src/core/errors/unexpected-error.ts
181
168
  var UnexpectedError = class extends AppError {
182
169
  constructor(message = "Unexpected error", cause, options) {
@@ -239,6 +226,6 @@ var ValidationCode = class ValidationCode {
239
226
  }
240
227
  };
241
228
  //#endregion
242
- export { stableStringify as a, ErrorCodes as c, sha256Hex as i, serializationErrorCode as l, UnexpectedError as n, AppError as o, payloadHash as r, assertJsonSafeMetadata as s, ValidationCode as t };
229
+ export { ErrorCodes as a, assertJsonSafeMetadata as i, UnexpectedError as n, serializationErrorCode as o, AppError as r, ValidationCode as t };
243
230
 
244
231
  //# sourceMappingURL=validation-code.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"validation-code.js","names":[],"sources":["../src/core/errors/error-codes.ts","../src/core/errors/utils/json-safe.ts","../src/core/errors/app-error.ts","../src/core/shared/hashing.ts","../src/core/errors/unexpected-error.ts","../src/core/exceptions/validation-code.ts"],"sourcesContent":["const ErrorCodes = {\n authentication: {\n missingToken: \"sec.authn.missing_token\",\n invalidToken: \"sec.authn.invalid_token\",\n expiredToken: \"sec.authn.expired_token\",\n invalidCredentials: \"sec.authn.invalid_credentials\",\n },\n authorization: {\n forbidden: \"sec.authz.forbidden\",\n policyDenied: \"sec.authz.policy_denied\",\n missingCapability: \"sec.authz.missing_capability\",\n outOfScope: \"sec.authz.out_of_scope\",\n },\n businessRuleViolation: \"business_rule_violation\",\n conflict: {\n alreadyExists: \"conf.already_exists\",\n duplicate: \"conf.duplicate\",\n uniqueViolation: \"conf.unique_violation\",\n },\n idempotency: {\n keyMissing: \"idemp.key_missing\",\n inProgress: \"idemp.in_progress\",\n payloadMismatch: \"idemp.payload_mismatch\",\n replayNotSupported: \"idemp.replay_not_supported\",\n },\n integration: {\n timeout: \"int.timeout\",\n unreachable: \"int.unreachable\",\n badResponse: \"int.bad_response\",\n },\n legacyIncompatible: \"legacy_incompatible\",\n notFound: \"not_found\",\n serialization: {\n deserializePrefix: \"ser.des\",\n serializePrefix: \"ser.ser\",\n },\n temporal: {\n expired: \"tmp.expired\",\n notYetValid: \"tmp.not_yet_valid\",\n },\n unexpected: \"unexpected\",\n validation: \"validation_error\",\n} as const;\n\ntype SerializationCodeDirection = \"deserialize\" | \"serialize\";\n\nfunction serializationErrorCode(\n direction: SerializationCodeDirection,\n category: string,\n): string {\n const prefix =\n direction === \"deserialize\"\n ? ErrorCodes.serialization.deserializePrefix\n : ErrorCodes.serialization.serializePrefix;\n\n return `${prefix}.${category}`;\n}\n\nexport { ErrorCodes, serializationErrorCode };\nexport type { SerializationCodeDirection };\n","// Utilities for ensuring metadata is JSON-serializable.\n\nimport type { JsonSafeRecord, JsonSafeValue } from \"../types.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Constants\n// ─────────────────────────────────────────────────────────────────────────────\n\nconst NON_SERIALIZABLE_PLACEHOLDER = \"[NonSerializable]\";\nconst CIRCULAR_REFERENCE_PLACEHOLDER = \"[Circular]\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Internal helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n// `seen` tracks the ancestors on the current traversal branch (a DFS path), not\n// every object visited. This collapses true circular references to a placeholder\n// while still serializing the same object referenced more than once across\n// sibling branches (a DAG) — matching `JSON.stringify`, which only rejects\n// cycles, not shared references.\nfunction sanitizeValue(value: unknown, seen: WeakSet<object>): JsonSafeValue {\n // Null passthrough\n if (value === null) return null;\n\n const type = typeof value;\n\n // Primitives\n if (type === \"string\" || type === \"number\" || type === \"boolean\") {\n return value as JsonSafeValue;\n }\n\n // Non-serializable primitives\n if (\n type === \"bigint\" ||\n type === \"function\" ||\n type === \"symbol\" ||\n value === undefined\n ) {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Arrays (recursive)\n if (Array.isArray(value)) {\n if (seen.has(value)) return CIRCULAR_REFERENCE_PLACEHOLDER;\n seen.add(value);\n const sanitized = value.map((item) => sanitizeValue(item, seen));\n seen.delete(value);\n return sanitized;\n }\n\n // Date → placeholder (could also use .toISOString() if preferred)\n if (value instanceof Date) {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Class instances and non-plain objects → placeholder\n if (!isPlainObject(value)) {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Plain object (recursive)\n if (seen.has(value)) return CIRCULAR_REFERENCE_PLACEHOLDER;\n seen.add(value);\n const result: Record<string, JsonSafeValue> = {};\n for (const [key, val] of Object.entries(value)) {\n result[key] = sanitizeValue(val, seen);\n }\n seen.delete(value);\n return result;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Public API\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Ensures metadata is JSON-serializable.\n *\n * **Allowed:** string, number, boolean, null, arrays, and plain objects.\n *\n * **Converted to placeholder:** Date, BigInt, class instances, functions,\n * symbols, undefined, and circular references (which would otherwise make\n * `JSON.stringify` throw).\n *\n * @throws {TypeError} If `input` is not a plain object at the root level.\n */\nfunction assertJsonSafeMetadata(input: unknown): JsonSafeRecord {\n if (input === undefined) {\n return {};\n }\n\n if (!isPlainObject(input)) {\n throw new TypeError(\n \"metadata must be a plain object (Record<string, unknown>).\",\n );\n }\n\n return sanitizeValue(input, new WeakSet<object>()) as JsonSafeRecord;\n}\n\nexport {\n assertJsonSafeMetadata,\n CIRCULAR_REFERENCE_PLACEHOLDER,\n NON_SERIALIZABLE_PLACEHOLDER,\n};\n","// Base application error for the domain/application layer.\n// Encapsulates a code, optional cause, and JSON-safe metadata.\n\nimport type {\n AppErrorOptions,\n ErrorSeverity,\n JsonSafeRecord,\n} from \"./types.js\";\nimport { assertJsonSafeMetadata } from \"./utils/index.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// AppError (abstract base class)\n// ─────────────────────────────────────────────────────────────────────────────\n\nabstract class AppError extends Error {\n public readonly code: string;\n public readonly cause?: unknown;\n public readonly metadata?: JsonSafeRecord;\n public readonly type?: string;\n public readonly severity?: ErrorSeverity;\n public readonly createdAtIso: string;\n public readonly publicMessage?: string;\n /**\n * Identifies a single execution \"story\" in the system. All operations\n * related to the same logical flow must share the same correlationId.\n */\n public readonly correlationId?: string;\n /**\n * Identifies a specific technical request attempt (each retry may produce\n * a new requestId), even when the correlationId stays the same.\n */\n public readonly requestId?: string;\n /**\n * Marks the business intent / idempotency key; stays the same across\n * technical retries and multiple requests that represent the same intent.\n */\n public readonly commandId?: string;\n\n protected constructor(\n message: string,\n code: string,\n options?: AppErrorOptions,\n ) {\n super(message);\n\n this.name = new.target.name;\n this.code = code;\n this.cause = options?.cause;\n this.type = options?.type;\n this.severity = options?.severity;\n this.correlationId = options?.correlationId;\n this.requestId = options?.requestId;\n this.commandId = options?.commandId;\n this.createdAtIso = options?.createdAtIso ?? new Date().toISOString();\n this.publicMessage = options?.publicMessage;\n\n this.metadata = options?.metadata\n ? assertJsonSafeMetadata(options.metadata)\n : undefined;\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n /**\n * Returns a JSON-safe representation of the error.\n * Does NOT include `cause` by default (to avoid leaking internal details).\n */\n public toJSON(): Record<string, unknown> {\n const payload: Record<string, unknown> = {\n name: this.name,\n code: this.code,\n message: this.message,\n createdAtIso: this.createdAtIso,\n };\n\n // Optional fields are emitted only when defined, so the serialized\n // shape never carries `undefined`-valued keys (consistent with how the\n // correlation/request/command ids are handled).\n if (this.type !== undefined) payload.type = this.type;\n if (this.severity !== undefined) payload.severity = this.severity;\n if (this.publicMessage !== undefined)\n payload.publicMessage = this.publicMessage;\n if (this.metadata !== undefined) payload.metadata = this.metadata;\n if (this.correlationId !== undefined)\n payload.correlationId = this.correlationId;\n if (this.requestId !== undefined) payload.requestId = this.requestId;\n if (this.commandId !== undefined) payload.commandId = this.commandId;\n\n return payload;\n }\n}\n\nexport { AppError };\n","import { createHash } from \"node:crypto\";\n\nconst CIRCULAR_STRUCTURE_MESSAGE =\n \"Cannot stably stringify a circular structure\";\n\nfunction sha256Hex(value: string): string {\n return createHash(\"sha256\").update(value, \"utf8\").digest(\"hex\");\n}\n\n// `seen` holds the current traversal branch so true cycles are rejected while\n// repeated (acyclic) references are still serialized — matching JSON.stringify.\nfunction sortKeysDeep(value: unknown, seen: WeakSet<object>): unknown {\n if (Array.isArray(value)) {\n if (seen.has(value)) {\n throw new TypeError(CIRCULAR_STRUCTURE_MESSAGE);\n }\n seen.add(value);\n const mapped = value.map((item) => sortKeysDeep(item, seen));\n seen.delete(value);\n return mapped;\n }\n\n if (value instanceof Date) {\n return value;\n }\n\n if (value && typeof value === \"object\") {\n if (seen.has(value)) {\n throw new TypeError(CIRCULAR_STRUCTURE_MESSAGE);\n }\n seen.add(value);\n const record = value as Record<string, unknown>;\n const ordered = Object.create(null) as Record<string, unknown>;\n\n for (const key of Object.keys(record).sort()) {\n ordered[key] = sortKeysDeep(record[key], seen);\n }\n seen.delete(value);\n\n return ordered;\n }\n\n return value;\n}\n\n/**\n * Deterministic JSON string with object keys sorted recursively, so key order\n * does not affect the output.\n *\n * Follows `JSON.stringify` semantics for the values it serializes: `undefined`,\n * functions and symbols are dropped, non-finite numbers become `null`, `bigint`\n * throws, and `Map`/`Set` serialize as `{}`. Distinct payloads can therefore\n * collapse to the same string — for collision-resistant hashing use\n * `PolicyHashing.canonicalJson` (policies/utils), which rejects those values\n * up front.\n *\n * @throws {TypeError} On circular references (mirroring `JSON.stringify`).\n */\nfunction stableStringify(value: unknown): string {\n return JSON.stringify(sortKeysDeep(value, new WeakSet<object>()));\n}\n\nfunction payloadHash(value: unknown): string {\n return sha256Hex(stableStringify(value));\n}\n\nexport { payloadHash, sha256Hex, stableStringify };\n","import { AppError } from \"./app-error.js\";\nimport { ErrorCodes } from \"./error-codes.js\";\nimport type { AppErrorOptions } from \"./types.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// UnexpectedError\n// ─────────────────────────────────────────────────────────────────────────────\n\nclass UnexpectedError extends AppError {\n constructor(\n message = \"Unexpected error\",\n cause?: unknown,\n options?: Omit<AppErrorOptions, \"cause\">,\n ) {\n super(message, ErrorCodes.unexpected, {\n cause,\n ...options,\n });\n }\n}\n\nexport { UnexpectedError };\n","// Object-oriented representation of validation codes (similar to Kotlin inline class).\n// Provides common reusable codes while allowing custom codes via `of`.\n\nclass ValidationCode {\n public readonly value: string;\n\n private constructor(value: string) {\n this.value = value;\n }\n\n // Factory for custom codes\n public static of(value: string): ValidationCode {\n return new ValidationCode(value);\n }\n\n // Common, domain-friendly codes\n public static readonly BLANK = new ValidationCode(\"blank\");\n public static readonly REQUIRED = new ValidationCode(\"required\");\n public static readonly INVALID_FORMAT = new ValidationCode(\n \"invalid_format\",\n );\n public static readonly INVALID_CHARACTERS = new ValidationCode(\n \"invalid_characters\",\n );\n public static readonly INVALID_LENGTH = new ValidationCode(\n \"invalid_length\",\n );\n public static readonly TOO_SHORT = new ValidationCode(\"too_short\");\n public static readonly TOO_LONG = new ValidationCode(\"too_long\");\n public static readonly OUT_OF_RANGE = new ValidationCode(\"out_of_range\");\n public static readonly INVALID_CHECKSUM = new ValidationCode(\n \"invalid_checksum\",\n );\n public static readonly INVALID_CHECKING_DIGIT = new ValidationCode(\n \"invalid_checking_digit\",\n );\n public static readonly ALREADY_EXISTS = new ValidationCode(\n \"already_exists\",\n );\n public static readonly NOT_FOUND = new ValidationCode(\"not_found\");\n public static readonly NOT_ALLOWED = new ValidationCode(\"not_allowed\");\n public static readonly UNEXPECTED = new ValidationCode(\"unexpected\");\n}\n\nexport { ValidationCode };\n"],"mappings":";;AAAA,MAAM,aAAa;CACf,gBAAgB;EACZ,cAAc;EACd,cAAc;EACd,cAAc;EACd,oBAAoB;CACxB;CACA,eAAe;EACX,WAAW;EACX,cAAc;EACd,mBAAmB;EACnB,YAAY;CAChB;CACA,uBAAuB;CACvB,UAAU;EACN,eAAe;EACf,WAAW;EACX,iBAAiB;CACrB;CACA,aAAa;EACT,YAAY;EACZ,YAAY;EACZ,iBAAiB;EACjB,oBAAoB;CACxB;CACA,aAAa;EACT,SAAS;EACT,aAAa;EACb,aAAa;CACjB;CACA,oBAAoB;CACpB,UAAU;CACV,eAAe;EACX,mBAAmB;EACnB,iBAAiB;CACrB;CACA,UAAU;EACN,SAAS;EACT,aAAa;CACjB;CACA,YAAY;CACZ,YAAY;AAChB;AAIA,SAAS,uBACL,WACA,UACM;CAMN,OAAO,GAJH,cAAc,gBACR,WAAW,cAAc,oBACzB,WAAW,cAAc,gBAElB,GAAG;AACxB;;;AChDA,MAAM,+BAA+B;AACrC,MAAM,iCAAiC;AAMvC,SAAS,cAAc,OAAkD;CACrE,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,MAAM,QAAQ,OAAO,eAAe,KAAK;CACzC,OAAO,UAAU,OAAO,aAAa,UAAU;AACnD;AAOA,SAAS,cAAc,OAAgB,MAAsC;CAEzE,IAAI,UAAU,MAAM,OAAO;CAE3B,MAAM,OAAO,OAAO;CAGpB,IAAI,SAAS,YAAY,SAAS,YAAY,SAAS,WACnD,OAAO;CAIX,IACI,SAAS,YACT,SAAS,cACT,SAAS,YACT,UAAU,KAAA,GAEV,OAAO;CAIX,IAAI,MAAM,QAAQ,KAAK,GAAG;EACtB,IAAI,KAAK,IAAI,KAAK,GAAG,OAAO;EAC5B,KAAK,IAAI,KAAK;EACd,MAAM,YAAY,MAA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AAwB;CACzC,OAAO,UAAU,gBAAgB,KAAK,CAAC;AAC3C;;;ACxDA,IAAM,kBAAN,cAA8B,SAAS;CACnC,YACI,UAAU,oBACV,OACA,SACF;EACE,MAAM,SAAS,WAAW,YAAY;GAClC;GACA,GAAG;EACP,CAAC;CACL;AACJ;;;AChBA,IAAM,iBAAN,MAAM,eAAe;CAGjB,YAAoB,OAAe;EAC/B,KAAK,QAAQ;CACjB;CAGA,OAAc,GAAG,OAA+B;EAC5C,OAAO,IAAI,eAAe,KAAK;CACnC;;eAG+B,IAAI,eAAe,OAAO;;;kBACvB,IAAI,eAAe,UAAU;;;wBACvB,IAAI,eACxC,gBACJ;;;4BAC4C,IAAI,eAC5C,oBACJ;;;wBACwC,IAAI,eACxC,gBACJ;;;mBACmC,IAAI,eAAe,WAAW;;;kBAC/B,IAAI,eAAe,UAAU;;;sBACzB,IAAI,eAAe,cAAc;;;0BAC7B,IAAI,eAC1C,kBACJ;;;gCACgD,IAAI,eAChD,wBACJ;;;wBACwC,IAAI,eACxC,gBACJ;;;mBACmC,IAAI,eAAe,WAAW;;;qBAC5B,IAAI,eAAe,aAAa;;;oBACjC,IAAI,eAAe,YAAY;;AACvE"}
1
+ {"version":3,"file":"validation-code.js","names":[],"sources":["../src/core/errors/error-codes.ts","../src/core/errors/utils/json-safe.ts","../src/core/errors/app-error.ts","../src/core/errors/unexpected-error.ts","../src/core/exceptions/validation-code.ts"],"sourcesContent":["const ErrorCodes = {\n authentication: {\n missingToken: \"sec.authn.missing_token\",\n invalidToken: \"sec.authn.invalid_token\",\n expiredToken: \"sec.authn.expired_token\",\n invalidCredentials: \"sec.authn.invalid_credentials\",\n },\n authorization: {\n forbidden: \"sec.authz.forbidden\",\n policyDenied: \"sec.authz.policy_denied\",\n missingCapability: \"sec.authz.missing_capability\",\n outOfScope: \"sec.authz.out_of_scope\",\n },\n businessRuleViolation: \"business_rule_violation\",\n conflict: {\n alreadyExists: \"conf.already_exists\",\n duplicate: \"conf.duplicate\",\n uniqueViolation: \"conf.unique_violation\",\n },\n idempotency: {\n keyMissing: \"idemp.key_missing\",\n inProgress: \"idemp.in_progress\",\n payloadMismatch: \"idemp.payload_mismatch\",\n replayNotSupported: \"idemp.replay_not_supported\",\n },\n integration: {\n timeout: \"int.timeout\",\n unreachable: \"int.unreachable\",\n badResponse: \"int.bad_response\",\n },\n legacyIncompatible: \"legacy_incompatible\",\n notFound: \"not_found\",\n serialization: {\n deserializePrefix: \"ser.des\",\n serializePrefix: \"ser.ser\",\n },\n temporal: {\n expired: \"tmp.expired\",\n notYetValid: \"tmp.not_yet_valid\",\n },\n unexpected: \"unexpected\",\n validation: \"validation_error\",\n} as const;\n\ntype SerializationCodeDirection = \"deserialize\" | \"serialize\";\n\nfunction serializationErrorCode(\n direction: SerializationCodeDirection,\n category: string,\n): string {\n const prefix =\n direction === \"deserialize\"\n ? ErrorCodes.serialization.deserializePrefix\n : ErrorCodes.serialization.serializePrefix;\n\n return `${prefix}.${category}`;\n}\n\nexport { ErrorCodes, serializationErrorCode };\nexport type { SerializationCodeDirection };\n","// Utilities for ensuring metadata is JSON-serializable.\n\nimport type { JsonSafeRecord, JsonSafeValue } from \"../types.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Constants\n// ─────────────────────────────────────────────────────────────────────────────\n\nconst NON_SERIALIZABLE_PLACEHOLDER = \"[NonSerializable]\";\nconst CIRCULAR_REFERENCE_PLACEHOLDER = \"[Circular]\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Internal helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n// `seen` tracks the ancestors on the current traversal branch (a DFS path), not\n// every object visited. This collapses true circular references to a placeholder\n// while still serializing the same object referenced more than once across\n// sibling branches (a DAG) — matching `JSON.stringify`, which only rejects\n// cycles, not shared references.\nfunction sanitizeValue(value: unknown, seen: WeakSet<object>): JsonSafeValue {\n // Null passthrough\n if (value === null) return null;\n\n const type = typeof value;\n\n // Primitives\n if (type === \"string\" || type === \"number\" || type === \"boolean\") {\n return value as JsonSafeValue;\n }\n\n // Non-serializable primitives\n if (\n type === \"bigint\" ||\n type === \"function\" ||\n type === \"symbol\" ||\n value === undefined\n ) {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Arrays (recursive)\n if (Array.isArray(value)) {\n if (seen.has(value)) return CIRCULAR_REFERENCE_PLACEHOLDER;\n seen.add(value);\n const sanitized = value.map((item) => sanitizeValue(item, seen));\n seen.delete(value);\n return sanitized;\n }\n\n // Date → placeholder (could also use .toISOString() if preferred)\n if (value instanceof Date) {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Class instances and non-plain objects → placeholder\n if (!isPlainObject(value)) {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Plain object (recursive)\n if (seen.has(value)) return CIRCULAR_REFERENCE_PLACEHOLDER;\n seen.add(value);\n const result: Record<string, JsonSafeValue> = {};\n for (const [key, val] of Object.entries(value)) {\n result[key] = sanitizeValue(val, seen);\n }\n seen.delete(value);\n return result;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Public API\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Ensures metadata is JSON-serializable.\n *\n * **Allowed:** string, number, boolean, null, arrays, and plain objects.\n *\n * **Converted to placeholder:** Date, BigInt, class instances, functions,\n * symbols, undefined, and circular references (which would otherwise make\n * `JSON.stringify` throw).\n *\n * @throws {TypeError} If `input` is not a plain object at the root level.\n */\nfunction assertJsonSafeMetadata(input: unknown): JsonSafeRecord {\n if (input === undefined) {\n return {};\n }\n\n if (!isPlainObject(input)) {\n throw new TypeError(\n \"metadata must be a plain object (Record<string, unknown>).\",\n );\n }\n\n return sanitizeValue(input, new WeakSet<object>()) as JsonSafeRecord;\n}\n\nexport {\n assertJsonSafeMetadata,\n CIRCULAR_REFERENCE_PLACEHOLDER,\n NON_SERIALIZABLE_PLACEHOLDER,\n};\n","// Base application error for the domain/application layer.\n// Encapsulates a code, optional cause, and JSON-safe metadata.\n\nimport type {\n AppErrorOptions,\n ErrorSeverity,\n JsonSafeRecord,\n} from \"./types.js\";\nimport { assertJsonSafeMetadata } from \"./utils/index.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// AppError (abstract base class)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Root of the application/domain error hierarchy. Every error the system raises\n * on purpose extends `AppError`, which gives callers a single `instanceof` to\n * catch and a uniform, serializable shape to log and transport.\n *\n * Beyond the native `Error` message it carries a stable `code` (the contract the\n * outside world matches on), an optional non-leaking `publicMessage`, a\n * severity, JSON-safe `metadata`, and the correlation/request/command ids that\n * stitch an error back to the request that produced it. The metadata is\n * validated as JSON-safe on construction, so a logger can serialize any\n * `AppError` without hitting a circular reference or a non-serializable value.\n *\n * Abstract on purpose: callers should throw a specific subclass (e.g.\n * {@link ValidationError}, {@link NotFoundError}) so the `code` and shape are\n * meaningful, never a bare `AppError`.\n */\nabstract class AppError extends Error {\n public readonly code: string;\n public readonly cause?: unknown;\n public readonly metadata?: JsonSafeRecord;\n public readonly type?: string;\n public readonly severity?: ErrorSeverity;\n public readonly createdAtIso: string;\n public readonly publicMessage?: string;\n /**\n * Identifies a single execution \"story\" in the system. All operations\n * related to the same logical flow must share the same correlationId.\n */\n public readonly correlationId?: string;\n /**\n * Identifies a specific technical request attempt (each retry may produce\n * a new requestId), even when the correlationId stays the same.\n */\n public readonly requestId?: string;\n /**\n * Marks the business intent / idempotency key; stays the same across\n * technical retries and multiple requests that represent the same intent.\n */\n public readonly commandId?: string;\n\n /**\n * Builds the common error envelope shared by every subclass.\n *\n * `name` is taken from `new.target` so the thrown instance reports its\n * concrete subclass name (not `\"AppError\"`), and the prototype is re-pinned\n * via `setPrototypeOf` so `instanceof` keeps working after transpilation to\n * older targets where extending built-ins breaks the chain. `createdAtIso`\n * defaults to now, and `metadata` is validated as JSON-safe so the error is\n * always serializable.\n *\n * Declared `protected`: instantiate a concrete subclass, never `AppError`.\n *\n * @param message - The internal, developer-facing message.\n * @param code - The stable machine-readable code callers match on.\n * @param options - Optional cause, metadata, severity, and correlation ids.\n * @throws When `options.metadata` contains a value that is not JSON-safe.\n */\n protected constructor(\n message: string,\n code: string,\n options?: AppErrorOptions,\n ) {\n super(message);\n\n this.name = new.target.name;\n this.code = code;\n this.cause = options?.cause;\n this.type = options?.type;\n this.severity = options?.severity;\n this.correlationId = options?.correlationId;\n this.requestId = options?.requestId;\n this.commandId = options?.commandId;\n this.createdAtIso = options?.createdAtIso ?? new Date().toISOString();\n this.publicMessage = options?.publicMessage;\n\n this.metadata = options?.metadata\n ? assertJsonSafeMetadata(options.metadata)\n : undefined;\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n /**\n * Returns a JSON-safe representation of the error.\n * Does NOT include `cause` by default (to avoid leaking internal details).\n */\n public toJSON(): Record<string, unknown> {\n const payload: Record<string, unknown> = {\n name: this.name,\n code: this.code,\n message: this.message,\n createdAtIso: this.createdAtIso,\n };\n\n // Optional fields are emitted only when defined, so the serialized\n // shape never carries `undefined`-valued keys (consistent with how the\n // correlation/request/command ids are handled).\n if (this.type !== undefined) payload.type = this.type;\n if (this.severity !== undefined) payload.severity = this.severity;\n if (this.publicMessage !== undefined)\n payload.publicMessage = this.publicMessage;\n if (this.metadata !== undefined) payload.metadata = this.metadata;\n if (this.correlationId !== undefined)\n payload.correlationId = this.correlationId;\n if (this.requestId !== undefined) payload.requestId = this.requestId;\n if (this.commandId !== undefined) payload.commandId = this.commandId;\n\n return payload;\n }\n}\n\nexport { AppError };\n","import { AppError } from \"./app-error.js\";\nimport { ErrorCodes } from \"./error-codes.js\";\nimport type { AppErrorOptions } from \"./types.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// UnexpectedError\n// ─────────────────────────────────────────────────────────────────────────────\n\nclass UnexpectedError extends AppError {\n constructor(\n message = \"Unexpected error\",\n cause?: unknown,\n options?: Omit<AppErrorOptions, \"cause\">,\n ) {\n super(message, ErrorCodes.unexpected, {\n cause,\n ...options,\n });\n }\n}\n\nexport { UnexpectedError };\n","// Object-oriented representation of validation codes (similar to Kotlin inline class).\n// Provides common reusable codes while allowing custom codes via `of`.\n\nclass ValidationCode {\n public readonly value: string;\n\n private constructor(value: string) {\n this.value = value;\n }\n\n // Factory for custom codes\n public static of(value: string): ValidationCode {\n return new ValidationCode(value);\n }\n\n // Common, domain-friendly codes\n public static readonly BLANK = new ValidationCode(\"blank\");\n public static readonly REQUIRED = new ValidationCode(\"required\");\n public static readonly INVALID_FORMAT = new ValidationCode(\n \"invalid_format\",\n );\n public static readonly INVALID_CHARACTERS = new ValidationCode(\n \"invalid_characters\",\n );\n public static readonly INVALID_LENGTH = new ValidationCode(\n \"invalid_length\",\n );\n public static readonly TOO_SHORT = new ValidationCode(\"too_short\");\n public static readonly TOO_LONG = new ValidationCode(\"too_long\");\n public static readonly OUT_OF_RANGE = new ValidationCode(\"out_of_range\");\n public static readonly INVALID_CHECKSUM = new ValidationCode(\n \"invalid_checksum\",\n );\n public static readonly INVALID_CHECKING_DIGIT = new ValidationCode(\n \"invalid_checking_digit\",\n );\n public static readonly ALREADY_EXISTS = new ValidationCode(\n \"already_exists\",\n );\n public static readonly NOT_FOUND = new ValidationCode(\"not_found\");\n public static readonly NOT_ALLOWED = new ValidationCode(\"not_allowed\");\n public static readonly UNEXPECTED = new ValidationCode(\"unexpected\");\n}\n\nexport { ValidationCode };\n"],"mappings":";AAAA,MAAM,aAAa;CACf,gBAAgB;EACZ,cAAc;EACd,cAAc;EACd,cAAc;EACd,oBAAoB;CACxB;CACA,eAAe;EACX,WAAW;EACX,cAAc;EACd,mBAAmB;EACnB,YAAY;CAChB;CACA,uBAAuB;CACvB,UAAU;EACN,eAAe;EACf,WAAW;EACX,iBAAiB;CACrB;CACA,aAAa;EACT,YAAY;EACZ,YAAY;EACZ,iBAAiB;EAC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O;CACX;AACJ;;;ACnHA,IAAM,kBAAN,cAA8B,SAAS;CACnC,YACI,UAAU,oBACV,OACA,SACF;EACE,MAAM,SAAS,WAAW,YAAY;GAClC;GACA,GAAG;EACP,CAAC;CACL;AACJ;;;AChBA,IAAM,iBAAN,MAAM,eAAe;CAGjB,YAAoB,OAAe;EAC/B,KAAK,QAAQ;CACjB;CAGA,OAAc,GAAG,OAA+B;EAC5C,OAAO,IAAI,eAAe,KAAK;CACnC;;eAG+B,IAAI,eAAe,OAAO;;;kBACvB,IAAI,eAAe,UAAU;;;wBACvB,IAAI,eACxC,gBACJ;;;4BAC4C,IAAI,eAC5C,oBACJ;;;wBACwC,IAAI,eACxC,gBACJ;;;mBACmC,IAAI,eAAe,WAAW;;;kBAC/B,IAAI,eAAe,UAAU;;;sBACzB,IAAI,eAAe,cAAc;;;0BAC7B,IAAI,eAC1C,kBACJ;;;gCACgD,IAAI,eAChD,wBACJ;;;wBACwC,IAAI,eACxC,gBACJ;;;mBACmC,IAAI,eAAe,WAAW;;;qBAC5B,IAAI,eAAe,aAAa;;;oBACjC,IAAI,eAAe,YAAY;;AACvE"}
@@ -1,46 +1,6 @@
1
+ import { a as JsonSafeRecord, n as AppErrorOptions, r as ErrorSeverity, t as AppError } from "./app-error.js";
1
2
  import { t as ValidationField } from "./validation-field.js";
2
3
 
3
- //#region src/core/errors/types.d.ts
4
- type ErrorSeverity = "low" | "medium" | "high" | "critical";
5
- type JsonSafePrimitive = string | number | boolean | null;
6
- type JsonSafeValue = JsonSafePrimitive | JsonSafeValue[] | {
7
- [key: string]: JsonSafeValue;
8
- };
9
- type JsonSafeRecord = Record<string, JsonSafeValue>;
10
- /**
11
- * Options accepted by the AppError constructor.
12
- * Subclasses can extend or pick from this type.
13
- */
14
- type AppErrorOptions = {
15
- /** Original error or exception that caused this error. */
16
- cause?: unknown;
17
- /** Arbitrary key-value metadata (will be sanitized to JSON-safe values). */
18
- metadata?: Record<string, unknown>;
19
- /** Error category/type for grouping (e.g., "authentication", "validation"). */
20
- type?: string;
21
- /** severity level for alerting/logging prioritization. */
22
- severity?: ErrorSeverity;
23
- /**
24
- * Identifies a single execution "story" in the system. All operations
25
- * related to the same logical flow must share the same correlationId.
26
- */
27
- correlationId?: string;
28
- /**
29
- * Identifies a specific technical request attempt (each retry may produce
30
- * a new requestId), even when the correlationId stays the same.
31
- */
32
- requestId?: string;
33
- /**
34
- * Identifies a unique business intent (idempotency key); stays the same
35
- * across technical retries and multiple requests that represent the same intent.
36
- */
37
- commandId?: string;
38
- /** ISO timestamp of when the error was created (defaults to now). */
39
- createdAtIso?: string;
40
- /** Safe message that can be exposed to end users (no internal details). */
41
- publicMessage?: string;
42
- };
43
- //#endregion
44
4
  //#region src/core/errors/error-codes.d.ts
45
5
  declare const ErrorCodes: {
46
6
  readonly authentication: {
@@ -102,38 +62,6 @@ declare function serializationErrorCode(direction: SerializationCodeDirection, c
102
62
  */
103
63
  declare function assertJsonSafeMetadata(input: unknown): JsonSafeRecord;
104
64
  //#endregion
105
- //#region src/core/errors/app-error.d.ts
106
- declare abstract class AppError extends Error {
107
- readonly code: string;
108
- readonly cause?: unknown;
109
- readonly metadata?: JsonSafeRecord;
110
- readonly type?: string;
111
- readonly severity?: ErrorSeverity;
112
- readonly createdAtIso: string;
113
- readonly publicMessage?: string;
114
- /**
115
- * Identifies a single execution "story" in the system. All operations
116
- * related to the same logical flow must share the same correlationId.
117
- */
118
- readonly correlationId?: string;
119
- /**
120
- * Identifies a specific technical request attempt (each retry may produce
121
- * a new requestId), even when the correlationId stays the same.
122
- */
123
- readonly requestId?: string;
124
- /**
125
- * Marks the business intent / idempotency key; stays the same across
126
- * technical retries and multiple requests that represent the same intent.
127
- */
128
- readonly commandId?: string;
129
- protected constructor(message: string, code: string, options?: AppErrorOptions);
130
- /**
131
- * Returns a JSON-safe representation of the error.
132
- * Does NOT include `cause` by default (to avoid leaking internal details).
133
- */
134
- toJSON(): Record<string, unknown>;
135
- }
136
- //#endregion
137
65
  //#region src/core/errors/authentication-error.d.ts
138
66
  type AuthenticationErrorReason = "missing_token" | "malformed_token" | "invalid_token" | "expired_token" | "revoked_token" | "invalid_credentials" | "session_not_found" | "session_expired" | "unknown";
139
67
  type AuthenticationErrorMetadata = {
@@ -196,18 +124,61 @@ type AuthorizationErrorMetadata = {
196
124
  * Combines metadata fields (except 'reason') with common AppError options.
197
125
  */
198
126
  type AuthorizationErrorFactoryOptions = Omit<AuthorizationErrorMetadata, "reason"> & Omit<AppErrorOptions, "metadata">;
127
+ /**
128
+ * Raised when an authenticated actor is not allowed to perform a business
129
+ * action — the "you may not" error, distinct from authentication ("who are
130
+ * you"). Maps to an HTTP 403 at the edge.
131
+ *
132
+ * The discriminating {@link reason} records *why* access was denied (a flat
133
+ * forbid, a missing role/capability, an out-of-scope target, or a policy
134
+ * decision) so the boundary can shape the response without re-deriving it. The
135
+ * metadata is deliberately built around a stable business `action` and a
136
+ * type/id resource reference rather than an HTTP route or full payload, keeping
137
+ * sensitive data out of logs. Instances are frozen. Construct through the
138
+ * static factories, never directly.
139
+ */
199
140
  declare class AuthorizationError extends AppError {
200
141
  readonly reason: AuthorizationErrorReason;
201
142
  private constructor();
143
+ /**
144
+ * A flat denial with no more specific reason — the actor simply may not
145
+ * perform this action. Reach for a more precise factory
146
+ * ({@link AuthorizationError.missingCapability}, {@link AuthorizationError.outOfScope},
147
+ * {@link AuthorizationError.policyDenied}) when the cause is known.
148
+ */
202
149
  static forbidden(input: AuthorizationErrorFactoryOptions): AuthorizationError;
150
+ /**
151
+ * The action was denied by an evaluated policy. Captures the deciding
152
+ * policy's id, version, and evaluation instant into the metadata (with
153
+ * `decision: "deny"`) so the denial is auditable back to the exact policy
154
+ * that produced it.
155
+ *
156
+ * @param input - Factory options plus the required `policyId`,
157
+ * `policyVersion`, and `evaluatedAtIso` of the deciding policy.
158
+ */
203
159
  static policyDenied(input: AuthorizationErrorFactoryOptions & {
204
160
  policyId: string;
205
161
  policyVersion: number;
206
162
  evaluatedAtIso: string;
207
163
  }): AuthorizationError;
164
+ /**
165
+ * The actor lacks a required role or capability. The expected
166
+ * {@link AuthorizationRequirement} is recorded so the boundary can tell the
167
+ * caller precisely what grant is missing.
168
+ *
169
+ * @param input - Factory options plus the `required` role/capability/scope.
170
+ */
208
171
  static missingCapability(input: AuthorizationErrorFactoryOptions & {
209
172
  required: AuthorizationRequirement;
210
173
  }): AuthorizationError;
174
+ /**
175
+ * The actor may perform the action in general, but not on *this* target —
176
+ * the resource falls outside the actor's permitted scope (e.g. a different
177
+ * school or tenant than the one they are bound to).
178
+ *
179
+ * @param input - Factory options plus the optional `required` scope that the
180
+ * target failed to satisfy.
181
+ */
211
182
  static outOfScope(input: AuthorizationErrorFactoryOptions & {
212
183
  required?: AuthorizationRequirement;
213
184
  }): AuthorizationError;
@@ -241,12 +212,28 @@ type ConflictErrorMetadata = {
241
212
  commandId?: string;
242
213
  hint?: string;
243
214
  };
215
+ /**
216
+ * Storage-level description of a unique-constraint breach, as reported by a
217
+ * database driver. Used to translate a raw DB error into a domain
218
+ * {@link DuplicateError} via {@link translateUniqueViolationToDuplicate}.
219
+ */
244
220
  type UniqueConstraintViolation = {
245
221
  kind: "unique_violation";
246
222
  constraintName?: string;
247
223
  table?: string;
248
224
  columns?: string[];
249
225
  };
226
+ /**
227
+ * Base for errors that signal a state conflict — the request collides with data
228
+ * that already exists. Common at an HTTP 409 boundary.
229
+ *
230
+ * The discriminating {@link kind} lets a handler branch on *why* it conflicted
231
+ * (an already-existing record, a domain duplicate, or a raw storage uniqueness
232
+ * breach) without `instanceof` chains. Abstract: construct one of the concrete
233
+ * subclasses through its `detected(...)` factory, which fills in the right code,
234
+ * message, and metadata. Instances are frozen, so a conflict error can be shared
235
+ * and rethrown without risk of tampering.
236
+ */
250
237
  declare abstract class ConflictError extends AppError {
251
238
  readonly kind: ConflictKind;
252
239
  protected constructor(params: {
@@ -257,8 +244,21 @@ declare abstract class ConflictError extends AppError {
257
244
  cause?: unknown;
258
245
  } & AppErrorOptions);
259
246
  }
247
+ /**
248
+ * The operation cannot proceed because a matching record already exists —
249
+ * e.g. creating something whose natural key is already taken. Construct via
250
+ * {@link AlreadyExistsError.detected}.
251
+ */
260
252
  declare class AlreadyExistsError extends ConflictError {
261
253
  private constructor();
254
+ /**
255
+ * Builds an {@link AlreadyExistsError} for a detected collision. `operation`
256
+ * defaults to `"create"` and a generic retry `hint` is supplied when none is
257
+ * given, so the error is actionable even from a minimal call site.
258
+ *
259
+ * @param input - The conflicting entity plus optional non-sensitive context
260
+ * (operation, field, existing id, value hash/preview, correlation ids).
261
+ */
262
262
  static detected(input: {
263
263
  entity: string;
264
264
  operation?: string;
@@ -274,8 +274,22 @@ declare class AlreadyExistsError extends ConflictError {
274
274
  cause?: unknown;
275
275
  }): AlreadyExistsError;
276
276
  }
277
+ /**
278
+ * A domain-level duplicate: the data being written would duplicate an existing
279
+ * record under the model's own uniqueness rules. Use this when the duplication
280
+ * is recognized in the domain, as opposed to a raw DB constraint
281
+ * ({@link UniqueConstraintViolationError}). Construct via
282
+ * {@link DuplicateError.detected}.
283
+ */
277
284
  declare class DuplicateError extends ConflictError {
278
285
  private constructor();
286
+ /**
287
+ * Builds a {@link DuplicateError} for a detected duplicate, defaulting to a
288
+ * "adjust the data so it does not duplicate" hint when none is provided.
289
+ *
290
+ * @param input - The conflicting entity plus optional non-sensitive context
291
+ * (field, constraint name, existing id, value hash/preview, correlation ids).
292
+ */
279
293
  static detected(input: {
280
294
  entity: string;
281
295
  operation?: string;
@@ -292,8 +306,23 @@ declare class DuplicateError extends ConflictError {
292
306
  cause?: unknown;
293
307
  }): DuplicateError;
294
308
  }
309
+ /**
310
+ * A uniqueness breach surfaced by the storage layer itself (a database unique
311
+ * index), carrying the raw {@link UniqueConstraintViolation} (constraint, table,
312
+ * columns). Keep this distinct from {@link DuplicateError}: this one is the
313
+ * infrastructure signal; translate it into a domain duplicate at the boundary
314
+ * with {@link translateUniqueViolationToDuplicate} when the model should own the
315
+ * message. Construct via {@link UniqueConstraintViolationError.detected}.
316
+ */
295
317
  declare class UniqueConstraintViolationError extends ConflictError {
296
318
  private constructor();
319
+ /**
320
+ * Builds a {@link UniqueConstraintViolationError} from the constraint details
321
+ * a driver reports, packaging them into a nested `violation` payload.
322
+ *
323
+ * @param input - The entity plus the offending constraint name, table, and
324
+ * columns, and optional correlation ids.
325
+ */
297
326
  static detected(input: {
298
327
  entity: string;
299
328
  operation?: string;
@@ -307,6 +336,17 @@ declare class UniqueConstraintViolationError extends ConflictError {
307
336
  cause?: unknown;
308
337
  }): UniqueConstraintViolationError;
309
338
  }
339
+ /**
340
+ * Translates a raw storage {@link UniqueConstraintViolation} into a domain-level
341
+ * {@link DuplicateError}. This is the seam where an infrastructure concern (a DB
342
+ * unique index firing) is re-expressed in the language of the model, so callers
343
+ * upstream catch a `DuplicateError` and never have to know a database was
344
+ * involved.
345
+ *
346
+ * @param input - The entity, the driver-reported `violation`, and optional
347
+ * request context (`ctx`) carrying correlation ids and a clock instant.
348
+ * @returns A {@link DuplicateError} carrying the constraint name as its field hint.
349
+ */
310
350
  declare function translateUniqueViolationToDuplicate(input: {
311
351
  entity: string;
312
352
  operation?: string;
@@ -522,11 +562,36 @@ type IntegrationErrorMetadata = {
522
562
  statusCode?: number;
523
563
  responseCode?: string;
524
564
  };
565
+ /**
566
+ * Raised when a call to an external provider fails — a timeout, an unreachable
567
+ * endpoint, or a malformed response. This is the boundary error that separates
568
+ * "our code is fine, the outside world misbehaved" from internal faults, which
569
+ * matters for retry and alerting decisions.
570
+ *
571
+ * Every instance records the `provider`, the `operation`, and timing
572
+ * (`startedAtIso` / `durationMs`) so failures are correlatable across services
573
+ * and a slow dependency is visible in the metadata. The discriminating
574
+ * {@link reason} lets callers decide whether a failure is worth retrying.
575
+ * Instances are frozen; construct through the static factories.
576
+ */
525
577
  declare class IntegrationError extends AppError {
526
578
  readonly reason: IntegrationErrorReason;
527
579
  private constructor();
580
+ /**
581
+ * The provider did not respond within the allotted time. Usually retryable,
582
+ * since a timeout leaves the outcome unknown rather than known-failed.
583
+ */
528
584
  static timeout(options: IntegrationErrorTimeoutOptions): IntegrationError;
585
+ /**
586
+ * The provider could not be reached at all (connection refused, DNS
587
+ * failure, network partition) — the request never landed.
588
+ */
529
589
  static unreachable(options: IntegrationErrorEndpointOptions): IntegrationError;
590
+ /**
591
+ * The provider answered, but with something the system cannot use — an
592
+ * unexpected status, an unparsable body, or a contract mismatch. Unlike a
593
+ * timeout this is a definite failure, so blind retries rarely help.
594
+ */
530
595
  static badResponse(options: IntegrationErrorEndpointOptions): IntegrationError;
531
596
  }
532
597
  type IntegrationErrorBaseOptions = {
@@ -556,7 +621,21 @@ declare class LegacyIncompatibleError extends AppError {
556
621
  }
557
622
  //#endregion
558
623
  //#region src/core/errors/not-found-error.d.ts
624
+ /**
625
+ * Raised when a requested resource does not exist. Maps naturally onto an HTTP
626
+ * 404 at the edge, but stays transport-agnostic here.
627
+ *
628
+ * The `resource` name builds the message (`"<resource> not found"`) and, with
629
+ * the optional lookup `criteria`, lands in the metadata so logs show *what* was
630
+ * searched for without the caller having to restate it in the message.
631
+ */
559
632
  declare class NotFoundError extends AppError {
633
+ /**
634
+ * @param resource - Human-readable name of the missing resource (e.g. `"Order"`).
635
+ * @param criteria - Optional lookup keys used in the search; recorded in
636
+ * metadata to aid debugging. Avoid putting sensitive values here.
637
+ * @param options - Optional cause, correlation ids, and extra metadata.
638
+ */
560
639
  constructor(resource: string, criteria?: Record<string, unknown>, options?: AppErrorOptions);
561
640
  }
562
641
  //#endregion
@@ -692,9 +771,27 @@ declare class ValidationCode {
692
771
  }
693
772
  //#endregion
694
773
  //#region src/core/errors/validation-error.d.ts
774
+ /**
775
+ * Raised when a single input fails a validation rule — the canonical
776
+ * "this field is wrong, and here is why" error.
777
+ *
778
+ * It pins the offending `field` and a machine-readable `validationCode` into
779
+ * the metadata (merged ahead of any caller-supplied metadata) so an API layer
780
+ * can map the failure straight onto a form field without parsing the message.
781
+ * The fixed {@link ErrorCodes.validation} code lets callers catch all
782
+ * validation failures uniformly while still distinguishing the specific rule
783
+ * through `validationCode`.
784
+ */
695
785
  declare class ValidationError extends AppError {
786
+ /**
787
+ * @param field - The input that failed validation; surfaced as `metadata.field`.
788
+ * @param code - The specific rule that was violated; surfaced as `metadata.validationCode`.
789
+ * @param message - The developer-facing description of the failure.
790
+ * @param options - Optional cause, correlation ids, and extra metadata
791
+ * (merged over the field/code metadata, never overwriting it by accident).
792
+ */
696
793
  constructor(field: ValidationField, code: ValidationCode, message: string, options?: AppErrorOptions);
697
794
  }
698
795
  //#endregion
699
- export { ErrorCodes as $, IdempotencyPayloadMismatchError as A, UniqueConstraintViolation as B, IntegrationErrorMetadata as C, IdempotencyFailureKind as D, IdempotencyErrorMetadata as E, AlreadyExistsError as F, AuthorizationErrorMetadata as G, translateUniqueViolationToDuplicate as H, ConflictError as I, AuthenticationError as J, AuthorizationErrorReason as K, ConflictErrorMetadata as L, payloadHash as M, sha256Hex as N, IdempotencyInProgressError as O, stableStringify as P, assertJsonSafeMetadata as Q, ConflictKind as R, IntegrationError as S, IdempotencyError as T, BusinessRuleViolationError as U, UniqueConstraintViolationError as V, AuthorizationError as W, AuthenticationErrorReason as X, AuthenticationErrorMetadata as Y, AppError as Z, SerializationMessages as _, TemporalError as a, JsonSafeValue as at, NotFoundError as b, TemporalPrecision as c, SerializationCodes as d, serializationErrorCode as et, SerializationDirection as f, SerializationInError as g, SerializationFailureCategory as h, NotYetValidError as i, JsonSafeRecord as it, IdempotencyReplayNotSupportedError as j, IdempotencyKeyMissingError as k, evaluateTemporalWindow as l, SerializationErrorMetadata as m, UnexpectedError as n, ErrorSeverity as nt, TemporalErrorMetadata as o, SerializationError as p, AuthorizationRequirement as q, ExpiredError as r, JsonSafePrimitive as rt, TemporalKind as s, ValidationError as t, AppErrorOptions as tt, SerializationBoundary as u, SerializationOutError as v, IntegrationErrorReason as w, LegacyIncompatibleError as x, safePreview as y, DuplicateError as z };
796
+ export { serializationErrorCode as $, IdempotencyPayloadMismatchError as A, UniqueConstraintViolation as B, IntegrationErrorMetadata as C, IdempotencyFailureKind as D, IdempotencyErrorMetadata as E, AlreadyExistsError as F, AuthorizationErrorMetadata as G, translateUniqueViolationToDuplicate as H, ConflictError as I, AuthenticationError as J, AuthorizationErrorReason as K, ConflictErrorMetadata as L, payloadHash as M, sha256Hex as N, IdempotencyInProgressError as O, stableStringify as P, ErrorCodes as Q, ConflictKind as R, IntegrationError as S, IdempotencyError as T, BusinessRuleViolationError as U, UniqueConstraintViolationError as V, AuthorizationError as W, AuthenticationErrorReason as X, AuthenticationErrorMetadata as Y, assertJsonSafeMetadata as Z, SerializationMessages as _, TemporalError as a, NotFoundError as b, TemporalPrecision as c, SerializationCodes as d, SerializationDirection as f, SerializationInError as g, SerializationFailureCategory as h, NotYetValidError as i, IdempotencyReplayNotSupportedError as j, IdempotencyKeyMissingError as k, evaluateTemporalWindow as l, SerializationErrorMetadata as m, UnexpectedError as n, TemporalErrorMetadata as o, SerializationError as p, AuthorizationRequirement as q, ExpiredError as r, TemporalKind as s, ValidationError as t, SerializationBoundary as u, SerializationOutError as v, IntegrationErrorReason as w, LegacyIncompatibleError as x, safePreview as y, DuplicateError as z };
700
797
  //# sourceMappingURL=validation-error.d.ts.map