@cullet/erp-core 1.0.11 → 1.2.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 +1 -0
- package/README.md +128 -1
- package/dist/app-error.d.ts +108 -0
- package/dist/application/index.d.ts +2 -0
- package/dist/application/index.js +3 -0
- package/dist/domain/index.d.ts +3 -0
- package/dist/domain/index.js +3 -0
- package/dist/domain-event-contracts.d.ts +27 -0
- package/dist/domain-event-contracts.js +22 -0
- package/dist/domain-event-contracts.js.map +1 -0
- package/dist/domain-exception.d.ts +7 -0
- package/dist/domain-exception.js +12 -0
- package/dist/domain-exception.js.map +1 -0
- package/dist/errors/index.d.ts +2 -1
- package/dist/errors/index.js +4 -2
- package/dist/exceptions/index.d.ts +5 -0
- package/dist/exceptions/index.js +7 -0
- package/dist/gate-engine-registry.d.ts +81 -0
- package/dist/gate-engine-registry.js +2 -1
- package/dist/gate-engine-registry.js.map +1 -1
- package/dist/gate-types.d.ts +3 -139
- package/dist/gate-v1-payload.schema.js +3 -143
- package/dist/gate-v1-payload.schema.js.map +1 -1
- package/dist/hashing.js +49 -0
- package/dist/hashing.js.map +1 -0
- package/dist/immutable.d.ts +6 -0
- package/dist/immutable.js +54 -0
- package/dist/immutable.js.map +1 -0
- package/dist/index.d.ts +21 -200
- package/dist/index.js +21 -251
- package/dist/index.js.map +1 -1
- package/dist/invalid-state-transition-exception.js +30 -0
- package/dist/invalid-state-transition-exception.js.map +1 -0
- package/dist/invariant-violation-exception.js +11 -0
- package/dist/invariant-violation-exception.js.map +1 -0
- package/dist/not-found-error.js +54 -0
- package/dist/not-found-error.js.map +1 -0
- package/dist/outcome.d.ts +140 -0
- package/dist/outcome.js +1 -1
- package/dist/parse-gate-payload.d.ts +4 -78
- package/dist/path.d.ts +90 -0
- package/dist/plugin.d.ts +85 -0
- package/dist/plugin.js +74 -0
- package/dist/plugin.js.map +1 -0
- package/dist/plugins/index.d.ts +2 -0
- package/dist/plugins/index.js +2 -0
- package/dist/policies/engines/index.d.ts +3 -2
- package/dist/policies/engines/v1/gate/index.d.ts +2 -1
- package/dist/policies/engines/v1/gate/index.js +2 -1
- package/dist/policies/engines/v1/gate/index.js.map +1 -1
- package/dist/policies/index.d.ts +6 -3
- package/dist/policies/index.js +2 -1
- package/dist/policy-service.d.ts +4 -86
- package/dist/policy-service.js +8 -16
- package/dist/policy-service.js.map +1 -1
- package/dist/result/index.d.ts +2 -0
- package/dist/result/index.js +3 -0
- package/dist/result.js +118 -0
- package/dist/result.js.map +1 -0
- package/dist/ruleset-registry.js +42 -0
- package/dist/ruleset-registry.js.map +1 -0
- package/dist/rulesets/index.d.ts +2 -0
- package/dist/rulesets/index.js +2 -0
- package/dist/temporal-guards.js +15 -0
- package/dist/temporal-guards.js.map +1 -0
- package/dist/temporal-use-case.d.ts +304 -0
- package/dist/temporal-use-case.js +150 -0
- package/dist/temporal-use-case.js.map +1 -0
- package/dist/unexpected-error.js +179 -0
- package/dist/unexpected-error.js.map +1 -0
- package/dist/use-case.js +91 -0
- package/dist/use-case.js.map +1 -0
- package/dist/uuid-identifier.d.ts +230 -0
- package/dist/uuid-identifier.js +60 -0
- package/dist/uuid-identifier.js.map +1 -0
- package/dist/validation-code.d.ts +23 -0
- package/dist/validation-code.js +1 -223
- package/dist/validation-code.js.map +1 -1
- package/dist/validation-error.d.ts +3 -128
- package/dist/validation-error.js +2 -52
- package/dist/validation-error.js.map +1 -1
- package/dist/validation-exception.d.ts +50 -0
- package/dist/validation-exception.js +24 -0
- package/dist/validation-exception.js.map +1 -0
- package/dist/value-object-ruleset.contracts.d.ts +36 -0
- package/dist/value-object.js +191 -0
- package/dist/value-object.js.map +1 -0
- package/dist/version.d.ts +10 -0
- package/dist/versioning/index.d.ts +3 -0
- package/dist/versioning/index.js +3 -0
- package/meta.json +18 -3
- package/package.json +37 -4
- package/src/application/index.ts +1 -0
- package/src/core/application/commands/index.ts +1 -0
- package/src/core/application/index.ts +12 -3
- package/src/core/application/ports/index.ts +2 -2
- package/src/core/application/ports/policy-port.ts +13 -3
- package/src/core/application/ports/repository.port.ts +37 -1
- package/src/core/application/temporal/temporal-use-case.ts +14 -2
- package/src/core/application/use-case.ts +133 -2
- package/src/core/domain/rulesets/index.ts +7 -0
- package/src/core/domain/uuid-identifier.ts +72 -0
- package/src/core/domain/value-object.ts +37 -5
- package/src/core/exceptions/index.ts +13 -0
- package/src/core/index.ts +15 -12
- package/src/core/plugins/index.ts +7 -0
- package/src/core/plugins/plugin.ts +99 -0
- package/src/core/plugins/types.ts +53 -0
- package/src/core/versioning/index.ts +14 -0
- package/src/domain/index.ts +7 -0
- package/src/examples/application/cancel-order.example.ts +124 -0
- package/src/examples/application/in-memory-account-repository.example.ts +73 -0
- package/src/exceptions/index.ts +1 -0
- package/src/plugins/index.ts +1 -0
- package/src/result/index.ts +2 -0
- package/src/rulesets/index.ts +1 -0
- package/src/version.ts +1 -1
- package/src/versioning/index.ts +1 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"temporal-use-case.js","names":[],"sources":["../src/core/application/commands/requested-by.ts","../src/core/application/commands/command.ts","../src/core/application/policy-error-mapper.ts","../src/core/application/queries/query.ts","../src/core/application/temporal/temporal-context.ts","../src/core/application/temporal/temporal-use-case.ts"],"sourcesContent":["import { ValidationCode } from \"../../exceptions/validation-code.js\";\nimport { InvalidValueException } from \"../../exceptions/validation-exception.js\";\nimport { ValidationField } from \"../../exceptions/validation-field.js\";\n\n// Identifies who triggered a Command.\n// Two valid formats:\n// - Human user: UUID v4 (e.g.: \"550e8400-e29b-41d4-a716-446655440000\")\n// - System identity: \"system:<job>\" where <job> is [a-z][a-z0-9]*(-[a-z0-9]+)*\n// (e.g.: \"system:late-fee-job\", \"system:email-sender\")\n//\n// The split between `fromUser` / `fromSystem` / `parse` exists to make intent\n// explicit at the call-site: whoever builds the value knows where it came from.\n\ntype RequestedByKind = \"user\" | \"system\";\n\nconst REQUESTED_BY_FIELD = ValidationField.of(\"requestedBy\");\n\nconst UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n// system:<job> where <job> starts with a lowercase letter and may have hyphens between segments\nconst SYSTEM_IDENTITY_PATTERN = /^system:[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\n\nclass RequestedBy {\n readonly kind: RequestedByKind;\n readonly raw: string;\n\n private constructor(kind: RequestedByKind, raw: string) {\n this.kind = kind;\n this.raw = raw;\n Object.freeze(this);\n }\n\n /** Builds from a human user ID (must be a UUID). */\n static fromUser(userId: string): RequestedBy {\n if (!UUID_PATTERN.test(userId)) {\n throw new InvalidValueException(\n REQUESTED_BY_FIELD,\n ValidationCode.INVALID_FORMAT,\n `requestedBy: user identity must be a UUID, got \"${userId}\"`,\n );\n }\n\n return new RequestedBy(\"user\", userId);\n }\n\n /**\n * Builds from a system identity.\n * Only accepts the format \"system:<job>\", where <job> matches [a-z][a-z0-9]*(-[a-z0-9]+)*.\n */\n static fromSystem(systemIdentity: string): RequestedBy {\n if (!SYSTEM_IDENTITY_PATTERN.test(systemIdentity)) {\n throw new InvalidValueException(\n REQUESTED_BY_FIELD,\n ValidationCode.INVALID_FORMAT,\n `requestedBy: system identity must match \"system:<job>\" (e.g. \"system:late-fee-job\"), got \"${systemIdentity}\"`,\n );\n }\n\n return new RequestedBy(\"system\", systemIdentity);\n }\n\n /**\n * Infers the kind from the raw value.\n * Use when the origin (user vs system) is not known at the call-site.\n */\n static parse(raw: string): RequestedBy {\n if (UUID_PATTERN.test(raw)) {\n return new RequestedBy(\"user\", raw);\n }\n\n if (SYSTEM_IDENTITY_PATTERN.test(raw)) {\n return new RequestedBy(\"system\", raw);\n }\n\n throw new InvalidValueException(\n REQUESTED_BY_FIELD,\n ValidationCode.INVALID_FORMAT,\n `requestedBy must be a UUID (user) or \"system:<job>\" (system), got \"${raw}\"`,\n );\n }\n\n get isUser(): boolean {\n return this.kind === \"user\";\n }\n\n get isSystem(): boolean {\n return this.kind === \"system\";\n }\n\n toString(): string {\n return this.raw;\n }\n}\n\nexport type { RequestedByKind };\nexport { RequestedBy };\n","import { UseCase } from \"../use-case.js\";\nimport { version } from \"../../versioning/version.js\";\nimport type { Result } from \"../../result/result.js\";\n\nimport { RequestedBy } from \"./requested-by.js\";\n\ninterface CommandInput {\n readonly requestedBy: RequestedBy;\n}\n\n/**\n * Base for use cases that **mutate state** (writes), following CQS.\n *\n * - `Input extends CommandInput` ensures every mutation records who triggered it.\n * - `Output extends Result<unknown, unknown>` ensures business errors are\n * explicit values, never thrown exceptions.\n *\n * The Command/Query distinction is semantic: the type declares the intent\n * before any implementation exists, guiding code review and API contracts.\n */\n@version(\"1.0\")\nabstract class Command<\n Input extends CommandInput,\n Output extends Result<unknown, unknown> = Result<void, never>,\n> extends UseCase<Input, Output> {}\n\nexport type { CommandInput };\nexport { Command };\n","import {\n type AppError,\n BusinessRuleViolationError,\n NotFoundError,\n UnexpectedError,\n} from \"../errors/index.js\";\nimport type { PolicyEvaluationError } from \"../policies/index.js\";\n\nexport function mapPolicyEvaluationError(err: PolicyEvaluationError): AppError {\n switch (err.kind) {\n case \"INVALID_CONTEXT\":\n return new BusinessRuleViolationError(\n `policy.${err.stage.toLowerCase()}`,\n err.message,\n { policyKey: err.policyKey, stage: err.stage },\n { cause: err.cause },\n );\n case \"INVALID_POLICY_KEY\":\n return new BusinessRuleViolationError(\n \"policy.invalid_key\",\n err.message,\n { rawPolicyKey: err.rawPolicyKey },\n { cause: err.cause },\n );\n case \"POLICY_NOT_FOUND\":\n return new NotFoundError(\n \"Policy\",\n { policyKey: err.policyKey },\n { cause: err.cause },\n );\n case \"POLICY_DEFINITION_NOT_FOUND\":\n return new NotFoundError(\n \"PolicyDefinition\",\n {\n policyKey: err.policyKey,\n contextVersion: err.contextVersion,\n asOf: err.asOf.toISOString(),\n },\n { cause: err.cause },\n );\n case \"POLICY_VARIANT_NOT_FOUND\":\n return new NotFoundError(\n \"PolicyVariant\",\n {\n policyKey: err.policyKey,\n policyKind: err.policyKind,\n payloadSchemaVersion: err.payloadSchemaVersion,\n },\n { cause: err.cause },\n );\n case \"ENGINE_FAILURE\":\n return new UnexpectedError(err.message, err.cause, {\n metadata: {\n policyKey: err.policyKey,\n engine: err.engine,\n engineVersion: err.engineVersion,\n },\n });\n }\n}\n","import { UseCase } from \"../use-case.js\";\nimport { version } from \"../../versioning/version.js\";\nimport type { AppError } from \"../../errors/index.js\";\nimport type { Result } from \"../../result/result.js\";\n\n/**\n * Paginated result of a list query.\n * Use as `Output` when the query returns a collection with pagination metadata.\n */\ninterface Page<T> {\n readonly items: readonly T[];\n readonly total: number;\n readonly page: number;\n readonly pageSize: number;\n}\n\n/**\n * Cache strategy declared by the query type.\n * Infrastructure reads this value to decide whether and how to cache the result.\n */\ntype CacheStrategy =\n | { readonly kind: \"NO_CACHE\" }\n | { readonly kind: \"TIME_TO_LIVE\"; readonly ttlMs: number }\n | { readonly kind: \"STALE_WHILE_REVALIDATE\"; readonly ttlMs: number };\n\ntype QueryOutput = object | string | number | boolean | bigint | symbol | null;\n\n/**\n * Base for use cases that **only read state**, with no side effects, following CQS.\n *\n * - `Data extends QueryOutput` prevents a query from declaring a `void` or\n * `undefined` success payload, while still allowing primitive projections\n * and `null` when that makes sense for the read. Failures stay explicit in\n * `Result<T, E>`.\n * - Override `cacheStrategy()` to declare how infrastructure should cache the\n * result. By default, no cache is applied.\n *\n * A Query must never mutate persisted data — its execution must be idempotent\n * and safe to call multiple times with the same input.\n */\n@version(\"1.0\")\nabstract class Query<\n Input = void,\n Data extends QueryOutput = never,\n Failure = AppError,\n> extends UseCase<Input, Result<Data, Failure>> {\n protected cacheStrategy(): CacheStrategy {\n return { kind: \"NO_CACHE\" };\n }\n}\n\nexport type { CacheStrategy, Page, QueryOutput };\nexport { Query };\n","import { makeImmutable } from \"../../shared/immutable.js\";\nimport { assertValidDate } from \"../../shared/temporal-guards.js\";\n\ninterface TemporalContext {\n readonly asOf: Date;\n readonly requestedAt: Date;\n}\n\ninterface CreateTemporalContextInput {\n readonly asOf?: Date;\n readonly requestedAt?: Date;\n}\n\nfunction assertTemporalContext(\n temporalContext: TemporalContext,\n fieldName: string = \"temporalContext\",\n): void {\n assertValidDate(`${fieldName}.asOf`, temporalContext.asOf);\n assertValidDate(`${fieldName}.requestedAt`, temporalContext.requestedAt);\n}\n\nfunction createTemporalContext(\n input: CreateTemporalContextInput = {},\n): TemporalContext {\n const requestedAt = input.requestedAt ?? new Date();\n const asOf = input.asOf ?? requestedAt;\n\n assertTemporalContext({ asOf, requestedAt });\n\n return makeImmutable({\n asOf,\n requestedAt,\n });\n}\n\nexport {\n assertTemporalContext,\n createTemporalContext,\n type CreateTemporalContextInput,\n type TemporalContext,\n};\n","import { UseCase } from \"../use-case.js\";\nimport type { ContextSeed } from \"../../policies/index.js\";\nimport type { Result } from \"../../result/result.js\";\n\nimport {\n createTemporalContext,\n type TemporalContext,\n} from \"./temporal-context.js\";\n\ninterface TemporalUseCaseInput {\n readonly temporalContext?: TemporalContext;\n}\n\n/**\n * A {@link ContextSeed} after temporal enrichment by\n * {@link TemporalUseCase.buildPolicySeed}: structurally identical to `TSeed`,\n * except `fields.now` is now guaranteed present as a `Date` (injected from the\n * resolved {@link TemporalContext}). Downstream policies can therefore read\n * `seed.fields.now` without a presence/type guard.\n */\ntype TemporalizedContextSeed<TSeed extends ContextSeed> = Omit<\n TSeed,\n \"fields\"\n> & {\n readonly fields: TSeed[\"fields\"] & { readonly now: Date };\n};\n\nabstract class TemporalUseCase<\n Input extends object,\n Output extends Result<unknown, unknown>,\n> extends UseCase<Input & TemporalUseCaseInput, Output> {\n protected resolveTemporalContext(\n input: Input & TemporalUseCaseInput,\n ): TemporalContext {\n return createTemporalContext(input.temporalContext);\n }\n\n protected buildPolicySeed<TSeed extends ContextSeed>(\n seed: TSeed,\n temporalContext: TemporalContext,\n ): TemporalizedContextSeed<TSeed> {\n return Object.freeze({\n ...seed,\n fields: {\n ...seed.fields,\n now: new Date(temporalContext.requestedAt.getTime()),\n },\n }) as TemporalizedContextSeed<TSeed>;\n }\n}\n\nexport type { TemporalizedContextSeed, TemporalUseCaseInput };\nexport { TemporalUseCase };\n"],"mappings":"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"}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
//#region src/core/errors/error-codes.ts
|
|
2
|
+
const ErrorCodes = {
|
|
3
|
+
authentication: {
|
|
4
|
+
missingToken: "sec.authn.missing_token",
|
|
5
|
+
invalidToken: "sec.authn.invalid_token",
|
|
6
|
+
expiredToken: "sec.authn.expired_token",
|
|
7
|
+
invalidCredentials: "sec.authn.invalid_credentials"
|
|
8
|
+
},
|
|
9
|
+
authorization: {
|
|
10
|
+
forbidden: "sec.authz.forbidden",
|
|
11
|
+
policyDenied: "sec.authz.policy_denied",
|
|
12
|
+
missingCapability: "sec.authz.missing_capability",
|
|
13
|
+
outOfScope: "sec.authz.out_of_scope"
|
|
14
|
+
},
|
|
15
|
+
businessRuleViolation: "business_rule_violation",
|
|
16
|
+
conflict: {
|
|
17
|
+
alreadyExists: "conf.already_exists",
|
|
18
|
+
duplicate: "conf.duplicate",
|
|
19
|
+
uniqueViolation: "conf.unique_violation"
|
|
20
|
+
},
|
|
21
|
+
idempotency: {
|
|
22
|
+
keyMissing: "idemp.key_missing",
|
|
23
|
+
inProgress: "idemp.in_progress",
|
|
24
|
+
payloadMismatch: "idemp.payload_mismatch",
|
|
25
|
+
replayNotSupported: "idemp.replay_not_supported"
|
|
26
|
+
},
|
|
27
|
+
integration: {
|
|
28
|
+
timeout: "int.timeout",
|
|
29
|
+
unreachable: "int.unreachable",
|
|
30
|
+
badResponse: "int.bad_response"
|
|
31
|
+
},
|
|
32
|
+
legacyIncompatible: "legacy_incompatible",
|
|
33
|
+
notFound: "not_found",
|
|
34
|
+
serialization: {
|
|
35
|
+
deserializePrefix: "ser.des",
|
|
36
|
+
serializePrefix: "ser.ser"
|
|
37
|
+
},
|
|
38
|
+
temporal: {
|
|
39
|
+
expired: "tmp.expired",
|
|
40
|
+
notYetValid: "tmp.not_yet_valid"
|
|
41
|
+
},
|
|
42
|
+
unexpected: "unexpected",
|
|
43
|
+
validation: "validation_error"
|
|
44
|
+
};
|
|
45
|
+
function serializationErrorCode(direction, category) {
|
|
46
|
+
return `${direction === "deserialize" ? ErrorCodes.serialization.deserializePrefix : ErrorCodes.serialization.serializePrefix}.${category}`;
|
|
47
|
+
}
|
|
48
|
+
//#endregion
|
|
49
|
+
//#region src/core/errors/utils/json-safe.ts
|
|
50
|
+
const NON_SERIALIZABLE_PLACEHOLDER = "[NonSerializable]";
|
|
51
|
+
const CIRCULAR_REFERENCE_PLACEHOLDER = "[Circular]";
|
|
52
|
+
function isPlainObject(value) {
|
|
53
|
+
if (value === null || typeof value !== "object") return false;
|
|
54
|
+
const proto = Object.getPrototypeOf(value);
|
|
55
|
+
return proto === Object.prototype || proto === null;
|
|
56
|
+
}
|
|
57
|
+
function sanitizeValue(value, seen) {
|
|
58
|
+
if (value === null) return null;
|
|
59
|
+
const type = typeof value;
|
|
60
|
+
if (type === "string" || type === "number" || type === "boolean") return value;
|
|
61
|
+
if (type === "bigint" || type === "function" || type === "symbol" || value === void 0) return NON_SERIALIZABLE_PLACEHOLDER;
|
|
62
|
+
if (Array.isArray(value)) {
|
|
63
|
+
if (seen.has(value)) return CIRCULAR_REFERENCE_PLACEHOLDER;
|
|
64
|
+
seen.add(value);
|
|
65
|
+
const sanitized = value.map((item) => sanitizeValue(item, seen));
|
|
66
|
+
seen.delete(value);
|
|
67
|
+
return sanitized;
|
|
68
|
+
}
|
|
69
|
+
if (value instanceof Date) return NON_SERIALIZABLE_PLACEHOLDER;
|
|
70
|
+
if (!isPlainObject(value)) return NON_SERIALIZABLE_PLACEHOLDER;
|
|
71
|
+
if (seen.has(value)) return CIRCULAR_REFERENCE_PLACEHOLDER;
|
|
72
|
+
seen.add(value);
|
|
73
|
+
const result = {};
|
|
74
|
+
for (const [key, val] of Object.entries(value)) result[key] = sanitizeValue(val, seen);
|
|
75
|
+
seen.delete(value);
|
|
76
|
+
return result;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Ensures metadata is JSON-serializable.
|
|
80
|
+
*
|
|
81
|
+
* **Allowed:** string, number, boolean, null, arrays, and plain objects.
|
|
82
|
+
*
|
|
83
|
+
* **Converted to placeholder:** Date, BigInt, class instances, functions,
|
|
84
|
+
* symbols, undefined, and circular references (which would otherwise make
|
|
85
|
+
* `JSON.stringify` throw).
|
|
86
|
+
*
|
|
87
|
+
* @throws {TypeError} If `input` is not a plain object at the root level.
|
|
88
|
+
*/
|
|
89
|
+
function assertJsonSafeMetadata(input) {
|
|
90
|
+
if (input === void 0) return {};
|
|
91
|
+
if (!isPlainObject(input)) throw new TypeError("metadata must be a plain object (Record<string, unknown>).");
|
|
92
|
+
return sanitizeValue(input, /* @__PURE__ */ new WeakSet());
|
|
93
|
+
}
|
|
94
|
+
//#endregion
|
|
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
|
+
*/
|
|
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
|
+
*/
|
|
130
|
+
constructor(message, code, options) {
|
|
131
|
+
super(message);
|
|
132
|
+
this.name = new.target.name;
|
|
133
|
+
this.code = code;
|
|
134
|
+
this.cause = options?.cause;
|
|
135
|
+
this.type = options?.type;
|
|
136
|
+
this.severity = options?.severity;
|
|
137
|
+
this.correlationId = options?.correlationId;
|
|
138
|
+
this.requestId = options?.requestId;
|
|
139
|
+
this.commandId = options?.commandId;
|
|
140
|
+
this.createdAtIso = options?.createdAtIso ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
141
|
+
this.publicMessage = options?.publicMessage;
|
|
142
|
+
this.metadata = options?.metadata ? assertJsonSafeMetadata(options.metadata) : void 0;
|
|
143
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Returns a JSON-safe representation of the error.
|
|
147
|
+
* Does NOT include `cause` by default (to avoid leaking internal details).
|
|
148
|
+
*/
|
|
149
|
+
toJSON() {
|
|
150
|
+
const payload = {
|
|
151
|
+
name: this.name,
|
|
152
|
+
code: this.code,
|
|
153
|
+
message: this.message,
|
|
154
|
+
createdAtIso: this.createdAtIso
|
|
155
|
+
};
|
|
156
|
+
if (this.type !== void 0) payload.type = this.type;
|
|
157
|
+
if (this.severity !== void 0) payload.severity = this.severity;
|
|
158
|
+
if (this.publicMessage !== void 0) payload.publicMessage = this.publicMessage;
|
|
159
|
+
if (this.metadata !== void 0) payload.metadata = this.metadata;
|
|
160
|
+
if (this.correlationId !== void 0) payload.correlationId = this.correlationId;
|
|
161
|
+
if (this.requestId !== void 0) payload.requestId = this.requestId;
|
|
162
|
+
if (this.commandId !== void 0) payload.commandId = this.commandId;
|
|
163
|
+
return payload;
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
//#endregion
|
|
167
|
+
//#region src/core/errors/unexpected-error.ts
|
|
168
|
+
var UnexpectedError = class extends AppError {
|
|
169
|
+
constructor(message = "Unexpected error", cause, options) {
|
|
170
|
+
super(message, ErrorCodes.unexpected, {
|
|
171
|
+
cause,
|
|
172
|
+
...options
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
//#endregion
|
|
177
|
+
export { serializationErrorCode as a, ErrorCodes as i, AppError as n, assertJsonSafeMetadata as r, UnexpectedError as t };
|
|
178
|
+
|
|
179
|
+
//# sourceMappingURL=unexpected-error.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"unexpected-error.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"],"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"],"mappings":"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"}
|
package/dist/use-case.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { i as version, n as __decorate } from "./immutable.js";
|
|
2
|
+
//#region src/core/application/use-case.ts
|
|
3
|
+
var _UseCase;
|
|
4
|
+
const EXECUTION_COUNTER = "use_case.executions";
|
|
5
|
+
const DURATION_HISTOGRAM = "use_case.duration_ms";
|
|
6
|
+
let UseCase = class UseCase {
|
|
7
|
+
static {
|
|
8
|
+
_UseCase = this;
|
|
9
|
+
}
|
|
10
|
+
get contractVersion() {
|
|
11
|
+
return _UseCase.CONTRACT_VERSION;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Runs the use case.
|
|
15
|
+
*
|
|
16
|
+
* `run()` is the single seam every use case crosses, so it is where
|
|
17
|
+
* cross-cutting instrumentation lives. When {@link observability} exposes
|
|
18
|
+
* any adapter, the call to `execute()` is wrapped with tracing, metrics and
|
|
19
|
+
* failure logging; otherwise it delegates directly with no overhead.
|
|
20
|
+
*
|
|
21
|
+
* Observability is strictly side-effecting: a misbehaving adapter never
|
|
22
|
+
* changes the business result nor masks a thrown error — its own failures
|
|
23
|
+
* are swallowed.
|
|
24
|
+
*/
|
|
25
|
+
async run(input) {
|
|
26
|
+
const observability = this.observability();
|
|
27
|
+
if (!observability.logger && !observability.metrics && !observability.tracer) return await this.execute(input);
|
|
28
|
+
return await this.runInstrumented(input, observability);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Adapters used to instrument {@link run}. Override to opt a use case into
|
|
32
|
+
* tracing/metrics/logging. Returns an empty object by default, which keeps
|
|
33
|
+
* the plain delegating behavior.
|
|
34
|
+
*/
|
|
35
|
+
observability() {
|
|
36
|
+
return {};
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Stable identity used for span names and metric labels. Defaults to the
|
|
40
|
+
* runtime class name; override when bundling/minification would otherwise
|
|
41
|
+
* erase a meaningful name.
|
|
42
|
+
*/
|
|
43
|
+
get useCaseName() {
|
|
44
|
+
return this.constructor.name;
|
|
45
|
+
}
|
|
46
|
+
async runInstrumented(input, observability) {
|
|
47
|
+
const { logger, metrics, tracer } = observability;
|
|
48
|
+
const name = this.useCaseName;
|
|
49
|
+
const span = safely(() => tracer?.startSpan(name, { "use_case.name": name }));
|
|
50
|
+
const startedAt = Date.now();
|
|
51
|
+
try {
|
|
52
|
+
const output = await this.execute(input);
|
|
53
|
+
const outcome = output.isOk() ? "ok" : "error";
|
|
54
|
+
if (outcome === "error") safely(() => logger?.warn(`${name} returned a business error`, { useCase: name }));
|
|
55
|
+
safely(() => span?.setAttribute("use_case.outcome", outcome));
|
|
56
|
+
safely(() => metrics?.counter(EXECUTION_COUNTER, 1, {
|
|
57
|
+
useCase: name,
|
|
58
|
+
outcome
|
|
59
|
+
}));
|
|
60
|
+
return output;
|
|
61
|
+
} catch (error) {
|
|
62
|
+
safely(() => logger?.error(`${name} threw an unexpected error`, { useCase: name }));
|
|
63
|
+
safely(() => span?.setAttribute("use_case.outcome", "exception"));
|
|
64
|
+
safely(() => span?.recordException(error));
|
|
65
|
+
safely(() => metrics?.counter(EXECUTION_COUNTER, 1, {
|
|
66
|
+
useCase: name,
|
|
67
|
+
outcome: "exception"
|
|
68
|
+
}));
|
|
69
|
+
throw error;
|
|
70
|
+
} finally {
|
|
71
|
+
safely(() => metrics?.histogram(DURATION_HISTOGRAM, Date.now() - startedAt, { useCase: name }));
|
|
72
|
+
safely(() => span?.end());
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
UseCase = _UseCase = __decorate([version("1.0")], UseCase);
|
|
77
|
+
/**
|
|
78
|
+
* Invokes an observability side effect, isolating any adapter failure so it
|
|
79
|
+
* cannot alter the use case outcome.
|
|
80
|
+
*/
|
|
81
|
+
function safely(effect) {
|
|
82
|
+
try {
|
|
83
|
+
return effect();
|
|
84
|
+
} catch {
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
//#endregion
|
|
89
|
+
export { UseCase as t };
|
|
90
|
+
|
|
91
|
+
//# sourceMappingURL=use-case.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-case.js","names":[],"sources":["../src/core/application/use-case.ts"],"sourcesContent":["import { type ContractVersion, version } from \"../versioning/version.js\";\nimport type { Result } from \"../result/result.js\";\n\nimport type { LoggerPort } from \"./ports/logger.port.js\";\nimport type { MetricsPort } from \"./ports/metrics.port.js\";\nimport type { TracerPort } from \"./ports/tracer.port.js\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\n/**\n * Observability adapters a use case may opt into.\n *\n * All fields are optional: a use case that provides none keeps the plain\n * `input → Result` behavior with zero overhead. When provided, {@link UseCase.run}\n * instruments every execution around `execute()` — opening a span, recording\n * duration, counting outcomes, and logging business/unexpected failures.\n */\ninterface UseCaseObservability {\n readonly logger?: LoggerPort;\n readonly metrics?: MetricsPort;\n readonly tracer?: TracerPort;\n}\n\nconst EXECUTION_COUNTER = \"use_case.executions\";\nconst DURATION_HISTOGRAM = \"use_case.duration_ms\";\n\ntype ExecutionOutcome = \"ok\" | \"error\" | \"exception\";\n\n@version(\"1.0\")\nabstract class UseCase<\n Input = void,\n Output extends Result<unknown, unknown> = Result<void, never>,\n> {\n declare public static readonly CONTRACT_VERSION: ContractVersion;\n\n public get contractVersion(): ContractVersion {\n return UseCase.CONTRACT_VERSION;\n }\n\n /**\n * Runs the use case.\n *\n * `run()` is the single seam every use case crosses, so it is where\n * cross-cutting instrumentation lives. When {@link observability} exposes\n * any adapter, the call to `execute()` is wrapped with tracing, metrics and\n * failure logging; otherwise it delegates directly with no overhead.\n *\n * Observability is strictly side-effecting: a misbehaving adapter never\n * changes the business result nor masks a thrown error — its own failures\n * are swallowed.\n */\n public async run(input: Input): Promise<Output> {\n const observability = this.observability();\n if (\n !observability.logger &&\n !observability.metrics &&\n !observability.tracer\n ) {\n return await this.execute(input);\n }\n\n return await this.runInstrumented(input, observability);\n }\n\n /**\n * Adapters used to instrument {@link run}. Override to opt a use case into\n * tracing/metrics/logging. Returns an empty object by default, which keeps\n * the plain delegating behavior.\n */\n protected observability(): UseCaseObservability {\n return {};\n }\n\n /**\n * Stable identity used for span names and metric labels. Defaults to the\n * runtime class name; override when bundling/minification would otherwise\n * erase a meaningful name.\n */\n protected get useCaseName(): string {\n return this.constructor.name;\n }\n\n protected abstract execute(input: Input): MaybePromise<Output>;\n\n private async runInstrumented(\n input: Input,\n observability: UseCaseObservability,\n ): Promise<Output> {\n const { logger, metrics, tracer } = observability;\n const name = this.useCaseName;\n const span = safely(() =>\n tracer?.startSpan(name, { \"use_case.name\": name }),\n );\n const startedAt = Date.now();\n\n try {\n const output = await this.execute(input);\n const outcome: ExecutionOutcome = output.isOk() ? \"ok\" : \"error\";\n\n if (outcome === \"error\") {\n safely(() =>\n logger?.warn(`${name} returned a business error`, {\n useCase: name,\n }),\n );\n }\n safely(() => span?.setAttribute(\"use_case.outcome\", outcome));\n safely(() =>\n metrics?.counter(EXECUTION_COUNTER, 1, {\n useCase: name,\n outcome,\n }),\n );\n\n return output;\n } catch (error) {\n safely(() =>\n logger?.error(`${name} threw an unexpected error`, {\n useCase: name,\n }),\n );\n safely(() => span?.setAttribute(\"use_case.outcome\", \"exception\"));\n safely(() => span?.recordException(error));\n safely(() =>\n metrics?.counter(EXECUTION_COUNTER, 1, {\n useCase: name,\n outcome: \"exception\",\n }),\n );\n\n throw error;\n } finally {\n safely(() =>\n metrics?.histogram(DURATION_HISTOGRAM, Date.now() - startedAt, {\n useCase: name,\n }),\n );\n safely(() => span?.end());\n }\n }\n}\n\n/**\n * Invokes an observability side effect, isolating any adapter failure so it\n * cannot alter the use case outcome.\n */\nfunction safely<R>(effect: () => R): R | undefined {\n try {\n return effect();\n } catch {\n return undefined;\n }\n}\n\nexport { type MaybePromise, UseCase, type UseCaseObservability };\n"],"mappings":";;;AAuBA,MAAM,oBAAoB;AAC1B,MAAM,qBAAqB;AAI3B,IAAA,UAAA,MACe,QAGb;;;;CAGE,IAAW,kBAAmC;EAC1C,OAAA,SAAe;CACnB;;;;;;;;;;;;;CAcA,MAAa,IAAI,OAA+B;EAC5C,MAAM,gBAAgB,KAAK,cAAc;EACzC,IACI,CAAC,cAAc,UACf,CAAC,cAAc,WACf,CAAC,cAAc,QAEf,OAAO,MAAM,KAAK,QAAQ,KAAK;EAGnC,OAAO,MAAM,KAAK,gBAAgB,OAAO,aAAa;CAC1D;;;;;;CAOA,gBAAgD;EAC5C,OAAO,CAAC;CACZ;;;;;;CAOA,IAAc,cAAsB;EAChC,OAAO,KAAK,YAAY;CAC5B;CAIA,MAAc,gBACV,OACA,eACe;EACf,MAAM,EAAE,QAAQ,SAAS,WAAW;EACpC,MAAM,OAAO,KAAK;EAClB,MAAM,OAAO,aACT,QAAQ,UAAU,MAAM,EAAE,iBAAiB,KAAK,CAAC,CACrD;EACA,MAAM,YAAY,KAAK,IAAI;EAE3B,IAAI;GACA,MAAM,SAAS,MAAM,KAAK,QAAQ,KAAK;GACvC,MAAM,UAA4B,OAAO,KAAK,IAAI,OAAO;GAEzD,IAAI,YAAY,SACZ,aACI,QAAQ,KAAK,GAAG,KAAK,6BAA6B,EAC9C,SAAS,KACb,CAAC,CACL;GAEJ,aAAa,MAAM,aAAa,oBAAoB,OAAO,CAAC;GAC5D,aACI,SAAS,QAAQ,mBAAmB,GAAG;IACnC,SAAS;IACT;GACJ,CAAC,CACL;GAEA,OAAO;EACX,SAAS,OAAO;GACZ,aACI,QAAQ,MAAM,GAAG,KAAK,6BAA6B,EAC/C,SAAS,KACb,CAAC,CACL;GACA,aAAa,MAAM,aAAa,oBAAoB,WAAW,CAAC;GAChE,aAAa,MAAM,gBAAgB,KAAK,CAAC;GACzC,aACI,SAAS,QAAQ,mBAAmB,GAAG;IACnC,SAAS;IACT,SAAS;GACb,CAAC,CACL;GAEA,MAAM;EACV,UAAU;GACN,aACI,SAAS,UAAU,oBAAoB,KAAK,IAAI,IAAI,WAAW,EAC3D,SAAS,KACb,CAAC,CACL;GACA,aAAa,MAAM,IAAI,CAAC;EAC5B;CACJ;AACJ;iCAhHC,QAAQ,KAAK,CAAA,GAAA,OAAA;;;;;AAsHd,SAAS,OAAU,QAAgC;CAC/C,IAAI;EACA,OAAO,OAAO;CAClB,QAAQ;EACJ;CACJ;AACJ"}
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import { n as ContractVersion } from "./version.js";
|
|
2
|
+
import { t as DeepReadonly } from "./immutable.js";
|
|
3
|
+
import { t as PluginManager } from "./plugin.js";
|
|
4
|
+
|
|
5
|
+
//#region src/core/domain/entity.d.ts
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The minimal persisted shape needed to reconstitute an {@link Entity}.
|
|
9
|
+
*
|
|
10
|
+
* This is the contract between storage and the domain: a repository maps a row
|
|
11
|
+
* (or document) onto these four fields and hands them to a subclass constructor.
|
|
12
|
+
* `aggregateVersion` travels with the state so optimistic-concurrency checks
|
|
13
|
+
* survive a round-trip through the database.
|
|
14
|
+
*/
|
|
15
|
+
interface EntityState<TIdentifier> {
|
|
16
|
+
readonly id: TIdentifier;
|
|
17
|
+
readonly createdAt: Date;
|
|
18
|
+
readonly updatedAt: Date;
|
|
19
|
+
readonly aggregateVersion: number;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Base class for domain entities — objects defined by a stable identity rather
|
|
23
|
+
* than by their attributes. Two entities are "the same" when their `id`
|
|
24
|
+
* matches, even if every other field differs; this is the opposite of a
|
|
25
|
+
* {@link ValueObject}, which is defined entirely by its contents.
|
|
26
|
+
*
|
|
27
|
+
* The class owns the bookkeeping common to every aggregate root: a creation
|
|
28
|
+
* timestamp that never changes, a last-modified timestamp, and an
|
|
29
|
+
* `aggregateVersion` counter used for optimistic concurrency control. All three
|
|
30
|
+
* are validated on construction and the dates are defensively cloned, so an
|
|
31
|
+
* entity can never be built into — or leak — an inconsistent temporal state.
|
|
32
|
+
*
|
|
33
|
+
* @typeParam TIdentifier - The identity type (e.g. a branded string id or a VO).
|
|
34
|
+
*/
|
|
35
|
+
declare abstract class Entity<TIdentifier> {
|
|
36
|
+
static readonly CONTRACT_VERSION: ContractVersion;
|
|
37
|
+
private readonly _id;
|
|
38
|
+
private readonly _createdAt;
|
|
39
|
+
private _updatedAt;
|
|
40
|
+
private _aggregateVersion;
|
|
41
|
+
/**
|
|
42
|
+
* Reconstitutes an entity from its persisted {@link EntityState}.
|
|
43
|
+
*
|
|
44
|
+
* Validates the temporal invariants up front so an invalid entity is
|
|
45
|
+
* impossible to construct: both dates must be valid, the aggregate version
|
|
46
|
+
* must be a non-negative integer, and `updatedAt` may not predate
|
|
47
|
+
* `createdAt`. Both dates are cloned on the way in so a later mutation of
|
|
48
|
+
* the caller's `Date` objects cannot reach into the entity's internal state.
|
|
49
|
+
*
|
|
50
|
+
* Declared `protected` because entities are reconstituted through a
|
|
51
|
+
* subclass factory, never instantiated directly by application code.
|
|
52
|
+
*
|
|
53
|
+
* @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.
|
|
54
|
+
*/
|
|
55
|
+
protected constructor(state: EntityState<TIdentifier>);
|
|
56
|
+
/** The entity's stable identity — the basis for equality between entities. */
|
|
57
|
+
get id(): TIdentifier;
|
|
58
|
+
/**
|
|
59
|
+
* When the entity was first created.
|
|
60
|
+
*
|
|
61
|
+
* Returns a clone so callers cannot mutate the entity's internal `Date`;
|
|
62
|
+
* the value is fixed at construction and never changes thereafter.
|
|
63
|
+
*/
|
|
64
|
+
get createdAt(): Date;
|
|
65
|
+
/**
|
|
66
|
+
* When the entity was last modified.
|
|
67
|
+
*
|
|
68
|
+
* Returns a clone for the same encapsulation reason as {@link createdAt};
|
|
69
|
+
* the underlying value advances only through {@link markAsModified}.
|
|
70
|
+
*/
|
|
71
|
+
get updatedAt(): Date;
|
|
72
|
+
/**
|
|
73
|
+
* Monotonic counter incremented on every mutation, used for optimistic
|
|
74
|
+
* concurrency control: a writer reads this value, and the persistence layer
|
|
75
|
+
* rejects the write if the stored version has moved on in the meantime.
|
|
76
|
+
*/
|
|
77
|
+
get aggregateVersion(): number;
|
|
78
|
+
/**
|
|
79
|
+
* The schema/contract version stamped on this entity type by the
|
|
80
|
+
* `@version` decorator — used to detect and migrate state persisted under
|
|
81
|
+
* an older shape.
|
|
82
|
+
*/
|
|
83
|
+
get contractVersion(): ContractVersion;
|
|
84
|
+
/**
|
|
85
|
+
* The single seam through which an entity records a mutation: it advances
|
|
86
|
+
* `updatedAt` and bumps {@link aggregateVersion} by one. Subclasses must
|
|
87
|
+
* call this from every state-changing method so the version counter stays
|
|
88
|
+
* an accurate optimistic-lock token.
|
|
89
|
+
*
|
|
90
|
+
* @param updatedAt - The modification instant; defaults to now. Validated
|
|
91
|
+
* and required not to predate `createdAt`, preserving the same invariant
|
|
92
|
+
* the constructor enforces.
|
|
93
|
+
* @returns The new aggregate version after the increment.
|
|
94
|
+
* @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.
|
|
95
|
+
*/
|
|
96
|
+
protected markAsModified(updatedAt?: Date): number;
|
|
97
|
+
}
|
|
98
|
+
//#endregion
|
|
99
|
+
//#region src/core/domain/value-object.d.ts
|
|
100
|
+
/**
|
|
101
|
+
* Extension point for value-object equality. A plugin implementing this
|
|
102
|
+
* contract overrides how any two value objects are compared, letting the host
|
|
103
|
+
* application swap in a structural comparator (e.g. `lodash.isEqual` over the
|
|
104
|
+
* wrapped `value`) without every value object having to implement `equals` by
|
|
105
|
+
* hand.
|
|
106
|
+
*/
|
|
107
|
+
type ValueObjectPluginContract = {
|
|
108
|
+
equals: (a: ValueObject<unknown, unknown>, b: ValueObject<unknown, unknown>) => boolean;
|
|
109
|
+
};
|
|
110
|
+
/**
|
|
111
|
+
* Base class for value objects — domain concepts defined entirely by their
|
|
112
|
+
* contents, with no identity of their own. Two value objects are
|
|
113
|
+
* interchangeable when they hold equal data, which is the opposite of an
|
|
114
|
+
* {@link Entity} (compared by id). Money, a CPF, a date range: replacing one
|
|
115
|
+
* instance with an equal one changes nothing about the model.
|
|
116
|
+
*
|
|
117
|
+
* Immutability is the defining guarantee here. The wrapped `value` is
|
|
118
|
+
* deep-frozen on construction, so a value object can be shared freely without
|
|
119
|
+
* any risk of a consumer mutating shared state. Subclasses seal the instance
|
|
120
|
+
* itself with {@link finalize} once their own fields are set.
|
|
121
|
+
*
|
|
122
|
+
* @typeParam T - The shape of the wrapped data.
|
|
123
|
+
* @typeParam P - The primitive form produced by {@link toPrimitive} / {@link toJSON}.
|
|
124
|
+
*/
|
|
125
|
+
declare abstract class ValueObject<T, P> {
|
|
126
|
+
static readonly CONTRACT_VERSION: ContractVersion;
|
|
127
|
+
/**
|
|
128
|
+
* Registry of equality plugins shared by every value object. Empty by
|
|
129
|
+
* default — when nothing is registered, {@link equals} falls back to a
|
|
130
|
+
* structural comparison of the wrapped `value`. Hosts register a plugin
|
|
131
|
+
* (e.g. `lodash.isEqual`) once at startup to customise equality globally.
|
|
132
|
+
*/
|
|
133
|
+
static readonly plugins: PluginManager<ValueObjectPluginContract>;
|
|
134
|
+
/** The wrapped data, deep-frozen so it can never be mutated after construction. */
|
|
135
|
+
readonly value: DeepReadonly<T>;
|
|
136
|
+
/**
|
|
137
|
+
* Wraps `value`, deep-freezing it so the value object is immutable from the
|
|
138
|
+
* moment it exists. Declared `protected` because value objects are built
|
|
139
|
+
* through a validating subclass factory, never instantiated directly.
|
|
140
|
+
*/
|
|
141
|
+
protected constructor(value: T);
|
|
142
|
+
/**
|
|
143
|
+
* The schema/contract version stamped on this value-object type by the
|
|
144
|
+
* `@version` decorator — used to detect state persisted under an older shape.
|
|
145
|
+
*/
|
|
146
|
+
get contractVersion(): ContractVersion;
|
|
147
|
+
/**
|
|
148
|
+
* Freezes the instance shell, blocking reassignment of any own field.
|
|
149
|
+
*
|
|
150
|
+
* `value` is already deep-frozen by the constructor, so the wrapped data is
|
|
151
|
+
* immutable regardless. The instance itself is NOT frozen automatically
|
|
152
|
+
* because a subclass may still need to assign its own fields after
|
|
153
|
+
* `super(value)` runs. Call `finalize()` at the very end of the subclass
|
|
154
|
+
* constructor (after all fields are set) to make the whole value object
|
|
155
|
+
* immutable.
|
|
156
|
+
*/
|
|
157
|
+
protected finalize(): void;
|
|
158
|
+
/**
|
|
159
|
+
* Hook for `JSON.stringify`. Delegates to {@link toPrimitive} so a value
|
|
160
|
+
* object serializes to its primitive form rather than exposing the internal
|
|
161
|
+
* `value` wrapper.
|
|
162
|
+
*/
|
|
163
|
+
toJSON(): P;
|
|
164
|
+
/**
|
|
165
|
+
* Compares this value object with another by content. Because value objects
|
|
166
|
+
* carry no identity, two independently constructed instances holding the
|
|
167
|
+
* same data are considered equal.
|
|
168
|
+
*
|
|
169
|
+
* Delegates to the registered equality {@link plugins}; with no plugin
|
|
170
|
+
* registered it falls back to comparing the serialized wrapped `value`.
|
|
171
|
+
* Subclasses may still override for a faster or domain-specific comparison.
|
|
172
|
+
*/
|
|
173
|
+
equals(other: this): boolean;
|
|
174
|
+
/**
|
|
175
|
+
* Projects the value object down to a plain, serializable primitive form —
|
|
176
|
+
* the representation suitable for persistence, transport, or comparison.
|
|
177
|
+
*/
|
|
178
|
+
abstract toPrimitive(): P;
|
|
179
|
+
}
|
|
180
|
+
//#endregion
|
|
181
|
+
//#region src/core/domain/uuid-identifier.d.ts
|
|
182
|
+
/**
|
|
183
|
+
* Base class for UUID-backed identity value objects.
|
|
184
|
+
*
|
|
185
|
+
* A domain typically has many of these — `OrderId`, `CustomerId`, `InvoiceId` —
|
|
186
|
+
* all wrapping the same `string` shape. Two problems follow: the UUID format
|
|
187
|
+
* check gets copy-pasted into every one, and because the wrapped shape is
|
|
188
|
+
* identical, TypeScript's structural typing would happily accept an `OrderId`
|
|
189
|
+
* where a `CustomerId` is expected. `UuidIdentifier` solves both: the format
|
|
190
|
+
* lives here once ({@link isValid}), and the `TBrand` phantom tag makes each
|
|
191
|
+
* subtype nominally distinct so the ids cannot be swapped for one another.
|
|
192
|
+
*
|
|
193
|
+
* It deliberately does not impose a factory. Identifiers vary in how they
|
|
194
|
+
* report an invalid value (their own exception type, their own message), so a
|
|
195
|
+
* concrete id adds a validating `create` that calls {@link isValid} plus a
|
|
196
|
+
* `reconstitute` that trusts an already-persisted value:
|
|
197
|
+
*
|
|
198
|
+
* ```ts
|
|
199
|
+
* class OrderId extends UuidIdentifier<"OrderId"> {
|
|
200
|
+
* private constructor(value: string) { super(value); }
|
|
201
|
+
* static create(raw: string): OrderId {
|
|
202
|
+
* if (!UuidIdentifier.isValid(raw)) throw new InvalidOrderIdError(raw);
|
|
203
|
+
* return new OrderId(raw);
|
|
204
|
+
* }
|
|
205
|
+
* static reconstitute(value: string): OrderId { return new OrderId(value); }
|
|
206
|
+
* }
|
|
207
|
+
* ```
|
|
208
|
+
*
|
|
209
|
+
* @typeParam TBrand - A unique string literal that nominally tags the subtype.
|
|
210
|
+
*/
|
|
211
|
+
declare abstract class UuidIdentifier<TBrand extends string = string> extends ValueObject<string, string> {
|
|
212
|
+
/**
|
|
213
|
+
* Phantom brand. Never assigned at runtime (`declare`), it exists only so
|
|
214
|
+
* two identifiers with different brands are not interchangeable at the type
|
|
215
|
+
* level despite sharing the same `string` value.
|
|
216
|
+
*/
|
|
217
|
+
protected readonly __brand: TBrand;
|
|
218
|
+
protected constructor(value: string);
|
|
219
|
+
toPrimitive(): string;
|
|
220
|
+
/** The wrapped UUID string — convenient for logging and interpolation. */
|
|
221
|
+
toString(): string;
|
|
222
|
+
/**
|
|
223
|
+
* Whether `candidate` is a canonical UUID (versions 1–5). The single source
|
|
224
|
+
* of truth for the format; concrete identifiers call this from `create`.
|
|
225
|
+
*/
|
|
226
|
+
static isValid(candidate: string): boolean;
|
|
227
|
+
}
|
|
228
|
+
//#endregion
|
|
229
|
+
export { EntityState as a, Entity as i, ValueObject as n, ValueObjectPluginContract as r, UuidIdentifier as t };
|
|
230
|
+
//# sourceMappingURL=uuid-identifier.d.ts.map
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { t as ValueObject } from "./value-object.js";
|
|
2
|
+
//#region src/core/domain/uuid-identifier.ts
|
|
3
|
+
/**
|
|
4
|
+
* Canonical RFC-4122 UUID (versions 1–5), matched case-insensitively. Declared
|
|
5
|
+
* once here so the dozens of typed identifiers a domain accumulates never have
|
|
6
|
+
* to re-state the pattern.
|
|
7
|
+
*/
|
|
8
|
+
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
9
|
+
/**
|
|
10
|
+
* Base class for UUID-backed identity value objects.
|
|
11
|
+
*
|
|
12
|
+
* A domain typically has many of these — `OrderId`, `CustomerId`, `InvoiceId` —
|
|
13
|
+
* all wrapping the same `string` shape. Two problems follow: the UUID format
|
|
14
|
+
* check gets copy-pasted into every one, and because the wrapped shape is
|
|
15
|
+
* identical, TypeScript's structural typing would happily accept an `OrderId`
|
|
16
|
+
* where a `CustomerId` is expected. `UuidIdentifier` solves both: the format
|
|
17
|
+
* lives here once ({@link isValid}), and the `TBrand` phantom tag makes each
|
|
18
|
+
* subtype nominally distinct so the ids cannot be swapped for one another.
|
|
19
|
+
*
|
|
20
|
+
* It deliberately does not impose a factory. Identifiers vary in how they
|
|
21
|
+
* report an invalid value (their own exception type, their own message), so a
|
|
22
|
+
* concrete id adds a validating `create` that calls {@link isValid} plus a
|
|
23
|
+
* `reconstitute` that trusts an already-persisted value:
|
|
24
|
+
*
|
|
25
|
+
* ```ts
|
|
26
|
+
* class OrderId extends UuidIdentifier<"OrderId"> {
|
|
27
|
+
* private constructor(value: string) { super(value); }
|
|
28
|
+
* static create(raw: string): OrderId {
|
|
29
|
+
* if (!UuidIdentifier.isValid(raw)) throw new InvalidOrderIdError(raw);
|
|
30
|
+
* return new OrderId(raw);
|
|
31
|
+
* }
|
|
32
|
+
* static reconstitute(value: string): OrderId { return new OrderId(value); }
|
|
33
|
+
* }
|
|
34
|
+
* ```
|
|
35
|
+
*
|
|
36
|
+
* @typeParam TBrand - A unique string literal that nominally tags the subtype.
|
|
37
|
+
*/
|
|
38
|
+
var UuidIdentifier = class extends ValueObject {
|
|
39
|
+
constructor(value) {
|
|
40
|
+
super(value);
|
|
41
|
+
}
|
|
42
|
+
toPrimitive() {
|
|
43
|
+
return this.value;
|
|
44
|
+
}
|
|
45
|
+
/** The wrapped UUID string — convenient for logging and interpolation. */
|
|
46
|
+
toString() {
|
|
47
|
+
return this.value;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Whether `candidate` is a canonical UUID (versions 1–5). The single source
|
|
51
|
+
* of truth for the format; concrete identifiers call this from `create`.
|
|
52
|
+
*/
|
|
53
|
+
static isValid(candidate) {
|
|
54
|
+
return UUID_PATTERN.test(candidate);
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
//#endregion
|
|
58
|
+
export { UuidIdentifier as t };
|
|
59
|
+
|
|
60
|
+
//# sourceMappingURL=uuid-identifier.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"uuid-identifier.js","names":[],"sources":["../src/core/domain/uuid-identifier.ts"],"sourcesContent":["import { ValueObject } from \"./value-object.js\";\n\n/**\n * Canonical RFC-4122 UUID (versions 1–5), matched case-insensitively. Declared\n * once here so the dozens of typed identifiers a domain accumulates never have\n * to re-state the pattern.\n */\nconst UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\n/**\n * Base class for UUID-backed identity value objects.\n *\n * A domain typically has many of these — `OrderId`, `CustomerId`, `InvoiceId` —\n * all wrapping the same `string` shape. Two problems follow: the UUID format\n * check gets copy-pasted into every one, and because the wrapped shape is\n * identical, TypeScript's structural typing would happily accept an `OrderId`\n * where a `CustomerId` is expected. `UuidIdentifier` solves both: the format\n * lives here once ({@link isValid}), and the `TBrand` phantom tag makes each\n * subtype nominally distinct so the ids cannot be swapped for one another.\n *\n * It deliberately does not impose a factory. Identifiers vary in how they\n * report an invalid value (their own exception type, their own message), so a\n * concrete id adds a validating `create` that calls {@link isValid} plus a\n * `reconstitute` that trusts an already-persisted value:\n *\n * ```ts\n * class OrderId extends UuidIdentifier<\"OrderId\"> {\n * private constructor(value: string) { super(value); }\n * static create(raw: string): OrderId {\n * if (!UuidIdentifier.isValid(raw)) throw new InvalidOrderIdError(raw);\n * return new OrderId(raw);\n * }\n * static reconstitute(value: string): OrderId { return new OrderId(value); }\n * }\n * ```\n *\n * @typeParam TBrand - A unique string literal that nominally tags the subtype.\n */\nabstract class UuidIdentifier<\n TBrand extends string = string,\n> extends ValueObject<string, string> {\n /**\n * Phantom brand. Never assigned at runtime (`declare`), it exists only so\n * two identifiers with different brands are not interchangeable at the type\n * level despite sharing the same `string` value.\n */\n protected declare readonly __brand: TBrand;\n\n protected constructor(value: string) {\n super(value);\n }\n\n public toPrimitive(): string {\n return this.value;\n }\n\n /** The wrapped UUID string — convenient for logging and interpolation. */\n public toString(): string {\n return this.value;\n }\n\n /**\n * Whether `candidate` is a canonical UUID (versions 1–5). The single source\n * of truth for the format; concrete identifiers call this from `create`.\n */\n public static isValid(candidate: string): boolean {\n return UUID_PATTERN.test(candidate);\n }\n}\n\nexport { UuidIdentifier };\n"],"mappings":";;;;;;;AAOA,MAAM,eACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BJ,IAAe,iBAAf,cAEU,YAA4B;CAQlC,YAAsB,OAAe;EACjC,MAAM,KAAK;CACf;CAEA,cAA6B;EACzB,OAAO,KAAK;CAChB;;CAGA,WAA0B;EACtB,OAAO,KAAK;CAChB;;;;;CAMA,OAAc,QAAQ,WAA4B;EAC9C,OAAO,aAAa,KAAK,SAAS;CACtC;AACJ"}
|