@cullet/erp-core 1.0.11 → 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.
- package/KIT_CONTEXT.md +67 -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 +2 -0
- package/dist/errors/index.d.ts +2 -1
- package/dist/errors/index.js +4 -2
- package/dist/gate-engine-registry.d.ts +80 -0
- package/dist/gate-v1-payload.schema.js +2 -28
- 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/index.d.ts +11 -45
- package/dist/index.js +12 -85
- package/dist/index.js.map +1 -1
- package/dist/not-found-error.js +54 -0
- package/dist/not-found-error.js.map +1 -0
- package/dist/outcome.js +1 -1
- package/dist/parse-gate-payload.d.ts +3 -78
- package/dist/path.d.ts +89 -0
- package/dist/policies/engines/index.d.ts +2 -1
- package/dist/policies/index.d.ts +4 -2
- package/dist/policy-service.d.ts +3 -86
- package/dist/policy-service.js +5 -16
- package/dist/policy-service.js.map +1 -1
- package/dist/temporal-guards.js +30 -0
- package/dist/temporal-guards.js.map +1 -0
- package/dist/temporal-use-case.d.ts +309 -0
- package/dist/temporal-use-case.js +284 -0
- package/dist/temporal-use-case.js.map +1 -0
- package/dist/validation-code.js +1 -47
- package/dist/validation-code.js.map +1 -1
- package/dist/validation-error.d.ts +2 -107
- package/dist/validation-error.js +2 -52
- package/dist/validation-error.js.map +1 -1
- package/dist/validation-exception.js +18 -0
- package/dist/validation-exception.js.map +1 -0
- package/meta.json +3 -2
- package/package.json +5 -1
- 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/index.ts +1 -10
- package/src/examples/application/cancel-order.example.ts +124 -0
- package/src/examples/application/in-memory-account-repository.example.ts +73 -0
- package/src/version.ts +1 -1
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
import { I as Result } from "./gate-types.js";
|
|
2
|
+
import { t as AppError } from "./app-error.js";
|
|
3
|
+
import { b as ContextSeed, r as PolicyEvaluationResult, s as PolicyEvaluationError, t as EvaluateInput } from "./policy-service.js";
|
|
4
|
+
|
|
5
|
+
//#region src/core/versioning/version.d.ts
|
|
6
|
+
type ContractVersion = `${number}.${number}`;
|
|
7
|
+
//#endregion
|
|
8
|
+
//#region src/core/application/ports/logger.port.d.ts
|
|
9
|
+
type LogPayload = Record<string, unknown>;
|
|
10
|
+
interface LoggerPort {
|
|
11
|
+
debug(message: string, payload?: LogPayload): void;
|
|
12
|
+
info(message: string, payload?: LogPayload): void;
|
|
13
|
+
warn(message: string, payload?: LogPayload): void;
|
|
14
|
+
error(message: string, payload?: LogPayload): void;
|
|
15
|
+
}
|
|
16
|
+
//#endregion
|
|
17
|
+
//#region src/core/application/ports/metrics.port.d.ts
|
|
18
|
+
type MetricLabels = Readonly<Record<string, string | number | boolean>>;
|
|
19
|
+
interface MetricsPort {
|
|
20
|
+
counter(name: string, value: number, labels?: MetricLabels): void;
|
|
21
|
+
gauge(name: string, value: number, labels?: MetricLabels): void;
|
|
22
|
+
histogram(name: string, value: number, labels?: MetricLabels): void;
|
|
23
|
+
}
|
|
24
|
+
//#endregion
|
|
25
|
+
//#region src/core/application/ports/tracer.port.d.ts
|
|
26
|
+
type TraceAttributeValue = string | number | boolean;
|
|
27
|
+
interface TraceSpan {
|
|
28
|
+
setAttribute(key: string, value: TraceAttributeValue): void;
|
|
29
|
+
recordException(error: unknown): void;
|
|
30
|
+
end(): void;
|
|
31
|
+
}
|
|
32
|
+
interface TracerPort {
|
|
33
|
+
startSpan(name: string, attributes?: Record<string, TraceAttributeValue>): TraceSpan;
|
|
34
|
+
}
|
|
35
|
+
//#endregion
|
|
36
|
+
//#region src/core/application/use-case.d.ts
|
|
37
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
38
|
+
/**
|
|
39
|
+
* Observability adapters a use case may opt into.
|
|
40
|
+
*
|
|
41
|
+
* All fields are optional: a use case that provides none keeps the plain
|
|
42
|
+
* `input → Result` behavior with zero overhead. When provided, {@link UseCase.run}
|
|
43
|
+
* instruments every execution around `execute()` — opening a span, recording
|
|
44
|
+
* duration, counting outcomes, and logging business/unexpected failures.
|
|
45
|
+
*/
|
|
46
|
+
interface UseCaseObservability {
|
|
47
|
+
readonly logger?: LoggerPort;
|
|
48
|
+
readonly metrics?: MetricsPort;
|
|
49
|
+
readonly tracer?: TracerPort;
|
|
50
|
+
}
|
|
51
|
+
declare abstract class UseCase<Input = void, Output extends Result<unknown, unknown> = Result<void, never>> {
|
|
52
|
+
static readonly CONTRACT_VERSION: ContractVersion;
|
|
53
|
+
get contractVersion(): ContractVersion;
|
|
54
|
+
/**
|
|
55
|
+
* Runs the use case.
|
|
56
|
+
*
|
|
57
|
+
* `run()` is the single seam every use case crosses, so it is where
|
|
58
|
+
* cross-cutting instrumentation lives. When {@link observability} exposes
|
|
59
|
+
* any adapter, the call to `execute()` is wrapped with tracing, metrics and
|
|
60
|
+
* failure logging; otherwise it delegates directly with no overhead.
|
|
61
|
+
*
|
|
62
|
+
* Observability is strictly side-effecting: a misbehaving adapter never
|
|
63
|
+
* changes the business result nor masks a thrown error — its own failures
|
|
64
|
+
* are swallowed.
|
|
65
|
+
*/
|
|
66
|
+
run(input: Input): Promise<Output>;
|
|
67
|
+
/**
|
|
68
|
+
* Adapters used to instrument {@link run}. Override to opt a use case into
|
|
69
|
+
* tracing/metrics/logging. Returns an empty object by default, which keeps
|
|
70
|
+
* the plain delegating behavior.
|
|
71
|
+
*/
|
|
72
|
+
protected observability(): UseCaseObservability;
|
|
73
|
+
/**
|
|
74
|
+
* Stable identity used for span names and metric labels. Defaults to the
|
|
75
|
+
* runtime class name; override when bundling/minification would otherwise
|
|
76
|
+
* erase a meaningful name.
|
|
77
|
+
*/
|
|
78
|
+
protected get useCaseName(): string;
|
|
79
|
+
protected abstract execute(input: Input): MaybePromise<Output>;
|
|
80
|
+
private runInstrumented;
|
|
81
|
+
}
|
|
82
|
+
//#endregion
|
|
83
|
+
//#region src/core/application/commands/requested-by.d.ts
|
|
84
|
+
type RequestedByKind = "user" | "system";
|
|
85
|
+
declare class RequestedBy {
|
|
86
|
+
readonly kind: RequestedByKind;
|
|
87
|
+
readonly raw: string;
|
|
88
|
+
private constructor();
|
|
89
|
+
/** Builds from a human user ID (must be a UUID). */
|
|
90
|
+
static fromUser(userId: string): RequestedBy;
|
|
91
|
+
/**
|
|
92
|
+
* Builds from a system identity.
|
|
93
|
+
* Only accepts the format "system:<job>", where <job> matches [a-z][a-z0-9]*(-[a-z0-9]+)*.
|
|
94
|
+
*/
|
|
95
|
+
static fromSystem(systemIdentity: string): RequestedBy;
|
|
96
|
+
/**
|
|
97
|
+
* Infers the kind from the raw value.
|
|
98
|
+
* Use when the origin (user vs system) is not known at the call-site.
|
|
99
|
+
*/
|
|
100
|
+
static parse(raw: string): RequestedBy;
|
|
101
|
+
get isUser(): boolean;
|
|
102
|
+
get isSystem(): boolean;
|
|
103
|
+
toString(): string;
|
|
104
|
+
}
|
|
105
|
+
//#endregion
|
|
106
|
+
//#region src/core/application/commands/command.d.ts
|
|
107
|
+
interface CommandInput {
|
|
108
|
+
readonly requestedBy: RequestedBy;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Base for use cases that **mutate state** (writes), following CQS.
|
|
112
|
+
*
|
|
113
|
+
* - `Input extends CommandInput` ensures every mutation records who triggered it.
|
|
114
|
+
* - `Output extends Result<unknown, unknown>` ensures business errors are
|
|
115
|
+
* explicit values, never thrown exceptions.
|
|
116
|
+
*
|
|
117
|
+
* The Command/Query distinction is semantic: the type declares the intent
|
|
118
|
+
* before any implementation exists, guiding code review and API contracts.
|
|
119
|
+
*/
|
|
120
|
+
declare abstract class Command<Input extends CommandInput, Output extends Result<unknown, unknown> = Result<void, never>> extends UseCase<Input, Output> {}
|
|
121
|
+
//#endregion
|
|
122
|
+
//#region src/core/application/ports/policy-port.d.ts
|
|
123
|
+
type PolicyEvaluationInput = EvaluateInput;
|
|
124
|
+
type PolicyEvaluationOutput = PolicyEvaluationResult;
|
|
125
|
+
/**
|
|
126
|
+
* Failure surfaced by {@link PolicyPort.evaluate}.
|
|
127
|
+
*
|
|
128
|
+
* This is the *post-mapping* boundary: the structured `PolicyEvaluationError`
|
|
129
|
+
* union produced inside the policies module is expected to have already been
|
|
130
|
+
* translated into an {@link AppError} (e.g. via `mapPolicyEvaluationError`)
|
|
131
|
+
* before it reaches a use case. Named distinctly from the policies-layer
|
|
132
|
+
* `PolicyEvaluationError` to avoid a collision on the public surface.
|
|
133
|
+
*/
|
|
134
|
+
type PolicyPortError = AppError;
|
|
135
|
+
interface PolicyPort {
|
|
136
|
+
evaluate(input: PolicyEvaluationInput): Promise<Result<PolicyEvaluationOutput, PolicyPortError>>;
|
|
137
|
+
}
|
|
138
|
+
//#endregion
|
|
139
|
+
//#region src/core/application/ports/repository.port.d.ts
|
|
140
|
+
/**
|
|
141
|
+
* Persistence port for an aggregate in the imperative style: absence is
|
|
142
|
+
* modelled as `null`, and failures (missing row on delete, optimistic
|
|
143
|
+
* concurrency conflicts, infrastructure errors) surface as thrown exceptions.
|
|
144
|
+
*
|
|
145
|
+
* Prefer {@link ResultRepository} when you want those persistence outcomes to
|
|
146
|
+
* be explicit, recoverable values rather than exceptions.
|
|
147
|
+
*/
|
|
148
|
+
interface Repository<TEntity, TId> {
|
|
149
|
+
findById(id: TId): Promise<TEntity | null>;
|
|
150
|
+
save(entity: TEntity): Promise<void>;
|
|
151
|
+
delete(id: TId): Promise<void>;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* `Result`-returning counterpart of {@link Repository}, aligned with the
|
|
155
|
+
* "errors as values" philosophy used by `Command` / `UseCase`.
|
|
156
|
+
*
|
|
157
|
+
* Where {@link Repository} returns `Promise<void>` from `save`/`delete` and
|
|
158
|
+
* relies on thrown exceptions, this variant lets a repository *signal*
|
|
159
|
+
* recoverable persistence outcomes without breaking control flow — for
|
|
160
|
+
* example a `NotFoundError` when updating/deleting a missing aggregate, or a
|
|
161
|
+
* `ConflictError` on an optimistic-concurrency version mismatch. A successful
|
|
162
|
+
* write resolves to `Result.ok(undefined)`.
|
|
163
|
+
*
|
|
164
|
+
* `findById` keeps `null` as the "not present" answer to a lookup (not an
|
|
165
|
+
* error) while still wrapping the call in a `Result` so genuine failures
|
|
166
|
+
* (e.g. a connectivity error) stay in band.
|
|
167
|
+
*
|
|
168
|
+
* `TError` defaults to {@link AppError} to match the rest of the application
|
|
169
|
+
* boundary (see `PolicyPortError`); narrow it per repository when the failure
|
|
170
|
+
* set is known, e.g. `ResultRepository<Order, OrderId, NotFoundError | ConflictError>`.
|
|
171
|
+
*/
|
|
172
|
+
interface ResultRepository<TEntity, TId, TError = AppError> {
|
|
173
|
+
findById(id: TId): Promise<Result<TEntity | null, TError>>;
|
|
174
|
+
save(entity: TEntity): Promise<Result<void, TError>>;
|
|
175
|
+
delete(id: TId): Promise<Result<void, TError>>;
|
|
176
|
+
}
|
|
177
|
+
//#endregion
|
|
178
|
+
//#region src/core/domain/temporal/transaction-time.d.ts
|
|
179
|
+
/**
|
|
180
|
+
* Represents transaction time (Transaction Time).
|
|
181
|
+
* Defines when the system learned about or recorded a piece of information.
|
|
182
|
+
* Useful for auditing and reconstructing system state at a specific past moment.
|
|
183
|
+
*/
|
|
184
|
+
interface TransactionTime {
|
|
185
|
+
/** When the information was first recorded in the system. */
|
|
186
|
+
readonly recordedAt: Date;
|
|
187
|
+
/** When this information was superseded or invalidated by a newer version. */
|
|
188
|
+
readonly supersededAt?: Date;
|
|
189
|
+
}
|
|
190
|
+
//#endregion
|
|
191
|
+
//#region src/core/domain/temporal/valid-time.d.ts
|
|
192
|
+
/**
|
|
193
|
+
* Represents business time (Valid Time).
|
|
194
|
+
* Defines when a piece of information is considered true or in effect in the real world.
|
|
195
|
+
*/
|
|
196
|
+
interface ValidTime {
|
|
197
|
+
/** Start of the validity window (inclusive). */
|
|
198
|
+
readonly from: Date;
|
|
199
|
+
/** End of the validity window (exclusive). When absent, the information is still in effect. */
|
|
200
|
+
readonly to?: Date;
|
|
201
|
+
}
|
|
202
|
+
//#endregion
|
|
203
|
+
//#region src/core/shared/immutable.d.ts
|
|
204
|
+
type PrimitiveValue = bigint | boolean | null | number | string | symbol | undefined;
|
|
205
|
+
type DeepReadonly<T> = T extends PrimitiveValue | Date ? T : T extends readonly (infer TItem)[] ? readonly DeepReadonly<TItem>[] : { readonly [TKey in keyof T]: DeepReadonly<T[TKey]> };
|
|
206
|
+
//#endregion
|
|
207
|
+
//#region src/core/domain/temporal/temporal-snapshot.d.ts
|
|
208
|
+
/**
|
|
209
|
+
* Pairs a domain datum with its time dimensions (Business and Transaction).
|
|
210
|
+
* It is the representation of an entry in the append-only (historical) table.
|
|
211
|
+
*/
|
|
212
|
+
interface TemporalSnapshot<T> {
|
|
213
|
+
/** The data or state captured by the snapshot. */
|
|
214
|
+
readonly data: DeepReadonly<T>;
|
|
215
|
+
/** Period during which this datum was valid in the real world. */
|
|
216
|
+
readonly validTime: ValidTime;
|
|
217
|
+
/** Period during which this record was the state known to the system. */
|
|
218
|
+
readonly txTime: TransactionTime;
|
|
219
|
+
}
|
|
220
|
+
//#endregion
|
|
221
|
+
//#region src/core/application/ports/temporal-repository.port.d.ts
|
|
222
|
+
type TemporalHistory<TEntity> = readonly TemporalSnapshot<TEntity>[];
|
|
223
|
+
interface TemporalRepository<TEntity, TId> extends Repository<TEntity, TId> {
|
|
224
|
+
findAsOf(id: TId, asOf: Date): Promise<TEntity | null>;
|
|
225
|
+
findAtTransaction(id: TId, txTime: Date): Promise<TEntity | null>;
|
|
226
|
+
findHistory(id: TId): Promise<TemporalHistory<TEntity>>;
|
|
227
|
+
save(entity: TEntity, validFrom?: Date): Promise<void>;
|
|
228
|
+
}
|
|
229
|
+
//#endregion
|
|
230
|
+
//#region src/core/application/policy-error-mapper.d.ts
|
|
231
|
+
declare function mapPolicyEvaluationError(err: PolicyEvaluationError): AppError;
|
|
232
|
+
//#endregion
|
|
233
|
+
//#region src/core/application/queries/query.d.ts
|
|
234
|
+
/**
|
|
235
|
+
* Paginated result of a list query.
|
|
236
|
+
* Use as `Output` when the query returns a collection with pagination metadata.
|
|
237
|
+
*/
|
|
238
|
+
interface Page<T> {
|
|
239
|
+
readonly items: readonly T[];
|
|
240
|
+
readonly total: number;
|
|
241
|
+
readonly page: number;
|
|
242
|
+
readonly pageSize: number;
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Cache strategy declared by the query type.
|
|
246
|
+
* Infrastructure reads this value to decide whether and how to cache the result.
|
|
247
|
+
*/
|
|
248
|
+
type CacheStrategy = {
|
|
249
|
+
readonly kind: "NO_CACHE";
|
|
250
|
+
} | {
|
|
251
|
+
readonly kind: "TIME_TO_LIVE";
|
|
252
|
+
readonly ttlMs: number;
|
|
253
|
+
} | {
|
|
254
|
+
readonly kind: "STALE_WHILE_REVALIDATE";
|
|
255
|
+
readonly ttlMs: number;
|
|
256
|
+
};
|
|
257
|
+
type QueryOutput = object | string | number | boolean | bigint | symbol | null;
|
|
258
|
+
/**
|
|
259
|
+
* Base for use cases that **only read state**, with no side effects, following CQS.
|
|
260
|
+
*
|
|
261
|
+
* - `Data extends QueryOutput` prevents a query from declaring a `void` or
|
|
262
|
+
* `undefined` success payload, while still allowing primitive projections
|
|
263
|
+
* and `null` when that makes sense for the read. Failures stay explicit in
|
|
264
|
+
* `Result<T, E>`.
|
|
265
|
+
* - Override `cacheStrategy()` to declare how infrastructure should cache the
|
|
266
|
+
* result. By default, no cache is applied.
|
|
267
|
+
*
|
|
268
|
+
* A Query must never mutate persisted data — its execution must be idempotent
|
|
269
|
+
* and safe to call multiple times with the same input.
|
|
270
|
+
*/
|
|
271
|
+
declare abstract class Query<Input = void, Data extends QueryOutput = never, Failure = AppError> extends UseCase<Input, Result<Data, Failure>> {
|
|
272
|
+
protected cacheStrategy(): CacheStrategy;
|
|
273
|
+
}
|
|
274
|
+
//#endregion
|
|
275
|
+
//#region src/core/application/temporal/temporal-context.d.ts
|
|
276
|
+
interface TemporalContext {
|
|
277
|
+
readonly asOf: Date;
|
|
278
|
+
readonly requestedAt: Date;
|
|
279
|
+
}
|
|
280
|
+
interface CreateTemporalContextInput {
|
|
281
|
+
readonly asOf?: Date;
|
|
282
|
+
readonly requestedAt?: Date;
|
|
283
|
+
}
|
|
284
|
+
declare function assertTemporalContext(temporalContext: TemporalContext, fieldName?: string): void;
|
|
285
|
+
declare function createTemporalContext(input?: CreateTemporalContextInput): TemporalContext;
|
|
286
|
+
//#endregion
|
|
287
|
+
//#region src/core/application/temporal/temporal-use-case.d.ts
|
|
288
|
+
interface TemporalUseCaseInput {
|
|
289
|
+
readonly temporalContext?: TemporalContext;
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* A {@link ContextSeed} after temporal enrichment by
|
|
293
|
+
* {@link TemporalUseCase.buildPolicySeed}: structurally identical to `TSeed`,
|
|
294
|
+
* except `fields.now` is now guaranteed present as a `Date` (injected from the
|
|
295
|
+
* resolved {@link TemporalContext}). Downstream policies can therefore read
|
|
296
|
+
* `seed.fields.now` without a presence/type guard.
|
|
297
|
+
*/
|
|
298
|
+
type TemporalizedContextSeed<TSeed extends ContextSeed> = Omit<TSeed, "fields"> & {
|
|
299
|
+
readonly fields: TSeed["fields"] & {
|
|
300
|
+
readonly now: Date;
|
|
301
|
+
};
|
|
302
|
+
};
|
|
303
|
+
declare abstract class TemporalUseCase<Input extends object, Output extends Result<unknown, unknown>> extends UseCase<Input & TemporalUseCaseInput, Output> {
|
|
304
|
+
protected resolveTemporalContext(input: Input & TemporalUseCaseInput): TemporalContext;
|
|
305
|
+
protected buildPolicySeed<TSeed extends ContextSeed>(seed: TSeed, temporalContext: TemporalContext): TemporalizedContextSeed<TSeed>;
|
|
306
|
+
}
|
|
307
|
+
//#endregion
|
|
308
|
+
export { TracerPort as A, RequestedBy as C, UseCaseObservability as D, UseCase as E, ContractVersion as F, MetricsPort as M, LogPayload as N, TraceAttributeValue as O, LoggerPort as P, CommandInput as S, MaybePromise as T, PolicyEvaluationInput as _, TemporalContext as a, PolicyPortError as b, CacheStrategy as c, mapPolicyEvaluationError as d, TemporalHistory as f, ResultRepository as g, Repository as h, CreateTemporalContextInput as i, MetricLabels as j, TraceSpan as k, Page as l, DeepReadonly as m, TemporalUseCaseInput as n, assertTemporalContext as o, TemporalRepository as p, TemporalizedContextSeed as r, createTemporalContext as s, TemporalUseCase as t, Query as u, PolicyEvaluationOutput as v, RequestedByKind as w, Command as x, PolicyPort as y };
|
|
309
|
+
//# sourceMappingURL=temporal-use-case.d.ts.map
|
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import { n as UnexpectedError, t as ValidationCode } from "./validation-code.js";
|
|
2
|
+
import { n as BusinessRuleViolationError, t as NotFoundError } from "./not-found-error.js";
|
|
3
|
+
import { t as ValidationField } from "./validation-field.js";
|
|
4
|
+
import { i as InvariantViolationException, t as assertValidDate } from "./temporal-guards.js";
|
|
5
|
+
import { t as InvalidValueException } from "./validation-exception.js";
|
|
6
|
+
//#region src/core/versioning/version.ts
|
|
7
|
+
const CONTRACT_VERSION_PROPERTY = "CONTRACT_VERSION";
|
|
8
|
+
const CONTRACT_VERSION_PATTERN = /^\d+\.\d+$/;
|
|
9
|
+
function version(contractVersion) {
|
|
10
|
+
if (!CONTRACT_VERSION_PATTERN.test(contractVersion)) throw new TypeError(`Invalid contract version "${contractVersion}". Expected MAJOR.MINOR.`);
|
|
11
|
+
return (target) => {
|
|
12
|
+
Object.defineProperty(target, CONTRACT_VERSION_PROPERTY, {
|
|
13
|
+
value: contractVersion,
|
|
14
|
+
writable: false,
|
|
15
|
+
configurable: false,
|
|
16
|
+
enumerable: false
|
|
17
|
+
});
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region \0@oxc-project+runtime@0.132.0/helpers/decorate.js
|
|
22
|
+
function __decorate(decorators, target, key, desc) {
|
|
23
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
24
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
25
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
26
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
27
|
+
}
|
|
28
|
+
//#endregion
|
|
29
|
+
//#region src/core/application/use-case.ts
|
|
30
|
+
var _UseCase;
|
|
31
|
+
const EXECUTION_COUNTER = "use_case.executions";
|
|
32
|
+
const DURATION_HISTOGRAM = "use_case.duration_ms";
|
|
33
|
+
let UseCase = class UseCase {
|
|
34
|
+
static {
|
|
35
|
+
_UseCase = this;
|
|
36
|
+
}
|
|
37
|
+
get contractVersion() {
|
|
38
|
+
return _UseCase.CONTRACT_VERSION;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Runs the use case.
|
|
42
|
+
*
|
|
43
|
+
* `run()` is the single seam every use case crosses, so it is where
|
|
44
|
+
* cross-cutting instrumentation lives. When {@link observability} exposes
|
|
45
|
+
* any adapter, the call to `execute()` is wrapped with tracing, metrics and
|
|
46
|
+
* failure logging; otherwise it delegates directly with no overhead.
|
|
47
|
+
*
|
|
48
|
+
* Observability is strictly side-effecting: a misbehaving adapter never
|
|
49
|
+
* changes the business result nor masks a thrown error — its own failures
|
|
50
|
+
* are swallowed.
|
|
51
|
+
*/
|
|
52
|
+
async run(input) {
|
|
53
|
+
const observability = this.observability();
|
|
54
|
+
if (!observability.logger && !observability.metrics && !observability.tracer) return await this.execute(input);
|
|
55
|
+
return await this.runInstrumented(input, observability);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Adapters used to instrument {@link run}. Override to opt a use case into
|
|
59
|
+
* tracing/metrics/logging. Returns an empty object by default, which keeps
|
|
60
|
+
* the plain delegating behavior.
|
|
61
|
+
*/
|
|
62
|
+
observability() {
|
|
63
|
+
return {};
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Stable identity used for span names and metric labels. Defaults to the
|
|
67
|
+
* runtime class name; override when bundling/minification would otherwise
|
|
68
|
+
* erase a meaningful name.
|
|
69
|
+
*/
|
|
70
|
+
get useCaseName() {
|
|
71
|
+
return this.constructor.name;
|
|
72
|
+
}
|
|
73
|
+
async runInstrumented(input, observability) {
|
|
74
|
+
const { logger, metrics, tracer } = observability;
|
|
75
|
+
const name = this.useCaseName;
|
|
76
|
+
const span = safely(() => tracer?.startSpan(name, { "use_case.name": name }));
|
|
77
|
+
const startedAt = Date.now();
|
|
78
|
+
try {
|
|
79
|
+
const output = await this.execute(input);
|
|
80
|
+
const outcome = output.isOk() ? "ok" : "error";
|
|
81
|
+
if (outcome === "error") safely(() => logger?.warn(`${name} returned a business error`, { useCase: name }));
|
|
82
|
+
safely(() => span?.setAttribute("use_case.outcome", outcome));
|
|
83
|
+
safely(() => metrics?.counter(EXECUTION_COUNTER, 1, {
|
|
84
|
+
useCase: name,
|
|
85
|
+
outcome
|
|
86
|
+
}));
|
|
87
|
+
return output;
|
|
88
|
+
} catch (error) {
|
|
89
|
+
safely(() => logger?.error(`${name} threw an unexpected error`, { useCase: name }));
|
|
90
|
+
safely(() => span?.setAttribute("use_case.outcome", "exception"));
|
|
91
|
+
safely(() => span?.recordException(error));
|
|
92
|
+
safely(() => metrics?.counter(EXECUTION_COUNTER, 1, {
|
|
93
|
+
useCase: name,
|
|
94
|
+
outcome: "exception"
|
|
95
|
+
}));
|
|
96
|
+
throw error;
|
|
97
|
+
} finally {
|
|
98
|
+
safely(() => metrics?.histogram(DURATION_HISTOGRAM, Date.now() - startedAt, { useCase: name }));
|
|
99
|
+
safely(() => span?.end());
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
UseCase = _UseCase = __decorate([version("1.0")], UseCase);
|
|
104
|
+
/**
|
|
105
|
+
* Invokes an observability side effect, isolating any adapter failure so it
|
|
106
|
+
* cannot alter the use case outcome.
|
|
107
|
+
*/
|
|
108
|
+
function safely(effect) {
|
|
109
|
+
try {
|
|
110
|
+
return effect();
|
|
111
|
+
} catch {
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
//#endregion
|
|
116
|
+
//#region src/core/application/commands/requested-by.ts
|
|
117
|
+
const REQUESTED_BY_FIELD = ValidationField.of("requestedBy");
|
|
118
|
+
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
119
|
+
const SYSTEM_IDENTITY_PATTERN = /^system:[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
|
|
120
|
+
var RequestedBy = class RequestedBy {
|
|
121
|
+
constructor(kind, raw) {
|
|
122
|
+
this.kind = kind;
|
|
123
|
+
this.raw = raw;
|
|
124
|
+
Object.freeze(this);
|
|
125
|
+
}
|
|
126
|
+
/** Builds from a human user ID (must be a UUID). */
|
|
127
|
+
static fromUser(userId) {
|
|
128
|
+
if (!UUID_PATTERN.test(userId)) throw new InvalidValueException(REQUESTED_BY_FIELD, ValidationCode.INVALID_FORMAT, `requestedBy: user identity must be a UUID, got "${userId}"`);
|
|
129
|
+
return new RequestedBy("user", userId);
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Builds from a system identity.
|
|
133
|
+
* Only accepts the format "system:<job>", where <job> matches [a-z][a-z0-9]*(-[a-z0-9]+)*.
|
|
134
|
+
*/
|
|
135
|
+
static fromSystem(systemIdentity) {
|
|
136
|
+
if (!SYSTEM_IDENTITY_PATTERN.test(systemIdentity)) throw new InvalidValueException(REQUESTED_BY_FIELD, ValidationCode.INVALID_FORMAT, `requestedBy: system identity must match "system:<job>" (e.g. "system:late-fee-job"), got "${systemIdentity}"`);
|
|
137
|
+
return new RequestedBy("system", systemIdentity);
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Infers the kind from the raw value.
|
|
141
|
+
* Use when the origin (user vs system) is not known at the call-site.
|
|
142
|
+
*/
|
|
143
|
+
static parse(raw) {
|
|
144
|
+
if (UUID_PATTERN.test(raw)) return new RequestedBy("user", raw);
|
|
145
|
+
if (SYSTEM_IDENTITY_PATTERN.test(raw)) return new RequestedBy("system", raw);
|
|
146
|
+
throw new InvalidValueException(REQUESTED_BY_FIELD, ValidationCode.INVALID_FORMAT, `requestedBy must be a UUID (user) or "system:<job>" (system), got "${raw}"`);
|
|
147
|
+
}
|
|
148
|
+
get isUser() {
|
|
149
|
+
return this.kind === "user";
|
|
150
|
+
}
|
|
151
|
+
get isSystem() {
|
|
152
|
+
return this.kind === "system";
|
|
153
|
+
}
|
|
154
|
+
toString() {
|
|
155
|
+
return this.raw;
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
//#endregion
|
|
159
|
+
//#region src/core/application/commands/command.ts
|
|
160
|
+
/**
|
|
161
|
+
* Base for use cases that **mutate state** (writes), following CQS.
|
|
162
|
+
*
|
|
163
|
+
* - `Input extends CommandInput` ensures every mutation records who triggered it.
|
|
164
|
+
* - `Output extends Result<unknown, unknown>` ensures business errors are
|
|
165
|
+
* explicit values, never thrown exceptions.
|
|
166
|
+
*
|
|
167
|
+
* The Command/Query distinction is semantic: the type declares the intent
|
|
168
|
+
* before any implementation exists, guiding code review and API contracts.
|
|
169
|
+
*/
|
|
170
|
+
let Command = class Command extends UseCase {};
|
|
171
|
+
Command = __decorate([version("1.0")], Command);
|
|
172
|
+
//#endregion
|
|
173
|
+
//#region src/core/application/policy-error-mapper.ts
|
|
174
|
+
function mapPolicyEvaluationError(err) {
|
|
175
|
+
switch (err.kind) {
|
|
176
|
+
case "INVALID_CONTEXT": return new BusinessRuleViolationError(`policy.${err.stage.toLowerCase()}`, err.message, {
|
|
177
|
+
policyKey: err.policyKey,
|
|
178
|
+
stage: err.stage
|
|
179
|
+
}, { cause: err.cause });
|
|
180
|
+
case "INVALID_POLICY_KEY": return new BusinessRuleViolationError("policy.invalid_key", err.message, { rawPolicyKey: err.rawPolicyKey }, { cause: err.cause });
|
|
181
|
+
case "POLICY_NOT_FOUND": return new NotFoundError("Policy", { policyKey: err.policyKey }, { cause: err.cause });
|
|
182
|
+
case "POLICY_DEFINITION_NOT_FOUND": return new NotFoundError("PolicyDefinition", {
|
|
183
|
+
policyKey: err.policyKey,
|
|
184
|
+
contextVersion: err.contextVersion,
|
|
185
|
+
asOf: err.asOf.toISOString()
|
|
186
|
+
}, { cause: err.cause });
|
|
187
|
+
case "POLICY_VARIANT_NOT_FOUND": return new NotFoundError("PolicyVariant", {
|
|
188
|
+
policyKey: err.policyKey,
|
|
189
|
+
policyKind: err.policyKind,
|
|
190
|
+
payloadSchemaVersion: err.payloadSchemaVersion
|
|
191
|
+
}, { cause: err.cause });
|
|
192
|
+
case "ENGINE_FAILURE": return new UnexpectedError(err.message, err.cause, { metadata: {
|
|
193
|
+
policyKey: err.policyKey,
|
|
194
|
+
engine: err.engine,
|
|
195
|
+
engineVersion: err.engineVersion
|
|
196
|
+
} });
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
//#endregion
|
|
200
|
+
//#region src/core/application/queries/query.ts
|
|
201
|
+
/**
|
|
202
|
+
* Base for use cases that **only read state**, with no side effects, following CQS.
|
|
203
|
+
*
|
|
204
|
+
* - `Data extends QueryOutput` prevents a query from declaring a `void` or
|
|
205
|
+
* `undefined` success payload, while still allowing primitive projections
|
|
206
|
+
* and `null` when that makes sense for the read. Failures stay explicit in
|
|
207
|
+
* `Result<T, E>`.
|
|
208
|
+
* - Override `cacheStrategy()` to declare how infrastructure should cache the
|
|
209
|
+
* result. By default, no cache is applied.
|
|
210
|
+
*
|
|
211
|
+
* A Query must never mutate persisted data — its execution must be idempotent
|
|
212
|
+
* and safe to call multiple times with the same input.
|
|
213
|
+
*/
|
|
214
|
+
let Query = class Query extends UseCase {
|
|
215
|
+
cacheStrategy() {
|
|
216
|
+
return { kind: "NO_CACHE" };
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
Query = __decorate([version("1.0")], Query);
|
|
220
|
+
//#endregion
|
|
221
|
+
//#region src/core/shared/immutable.ts
|
|
222
|
+
function deepFreeze(value) {
|
|
223
|
+
return deepFreezeInternal(value, /* @__PURE__ */ new WeakSet());
|
|
224
|
+
}
|
|
225
|
+
function deepFreezeInternal(value, seen) {
|
|
226
|
+
if (typeof value !== "object" || value === null || value instanceof Date) return value;
|
|
227
|
+
if (seen.has(value)) return value;
|
|
228
|
+
seen.add(value);
|
|
229
|
+
if (Array.isArray(value)) {
|
|
230
|
+
for (const item of value) deepFreezeInternal(item, seen);
|
|
231
|
+
return Object.freeze(value);
|
|
232
|
+
}
|
|
233
|
+
const objectValue = value;
|
|
234
|
+
for (const propertyKey of Reflect.ownKeys(objectValue)) deepFreezeInternal(objectValue[propertyKey], seen);
|
|
235
|
+
return Object.freeze(value);
|
|
236
|
+
}
|
|
237
|
+
function makeImmutable(value) {
|
|
238
|
+
if (typeof value !== "object" || value === null) return value;
|
|
239
|
+
let snapshot;
|
|
240
|
+
try {
|
|
241
|
+
snapshot = structuredClone(value);
|
|
242
|
+
} catch (error) {
|
|
243
|
+
throw new InvariantViolationException(`makeImmutable requires a structured-cloneable value: ${error instanceof Error ? error.message : String(error)}`);
|
|
244
|
+
}
|
|
245
|
+
return deepFreeze(snapshot);
|
|
246
|
+
}
|
|
247
|
+
//#endregion
|
|
248
|
+
//#region src/core/application/temporal/temporal-context.ts
|
|
249
|
+
function assertTemporalContext(temporalContext, fieldName = "temporalContext") {
|
|
250
|
+
assertValidDate(`${fieldName}.asOf`, temporalContext.asOf);
|
|
251
|
+
assertValidDate(`${fieldName}.requestedAt`, temporalContext.requestedAt);
|
|
252
|
+
}
|
|
253
|
+
function createTemporalContext(input = {}) {
|
|
254
|
+
const requestedAt = input.requestedAt ?? /* @__PURE__ */ new Date();
|
|
255
|
+
const asOf = input.asOf ?? requestedAt;
|
|
256
|
+
assertTemporalContext({
|
|
257
|
+
asOf,
|
|
258
|
+
requestedAt
|
|
259
|
+
});
|
|
260
|
+
return makeImmutable({
|
|
261
|
+
asOf,
|
|
262
|
+
requestedAt
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
//#endregion
|
|
266
|
+
//#region src/core/application/temporal/temporal-use-case.ts
|
|
267
|
+
var TemporalUseCase = class extends UseCase {
|
|
268
|
+
resolveTemporalContext(input) {
|
|
269
|
+
return createTemporalContext(input.temporalContext);
|
|
270
|
+
}
|
|
271
|
+
buildPolicySeed(seed, temporalContext) {
|
|
272
|
+
return Object.freeze({
|
|
273
|
+
...seed,
|
|
274
|
+
fields: {
|
|
275
|
+
...seed.fields,
|
|
276
|
+
now: new Date(temporalContext.requestedAt.getTime())
|
|
277
|
+
}
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
};
|
|
281
|
+
//#endregion
|
|
282
|
+
export { Query as a, RequestedBy as c, version as d, makeImmutable as i, UseCase as l, assertTemporalContext as n, mapPolicyEvaluationError as o, createTemporalContext as r, Command as s, TemporalUseCase as t, __decorate as u };
|
|
283
|
+
|
|
284
|
+
//# sourceMappingURL=temporal-use-case.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"temporal-use-case.js","names":[],"sources":["../src/core/versioning/version.ts","../src/core/application/use-case.ts","../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/shared/immutable.ts","../src/core/application/temporal/temporal-context.ts","../src/core/application/temporal/temporal-use-case.ts"],"sourcesContent":["type ContractVersion = `${number}.${number}`;\n\ntype VersionedTarget = {\n readonly prototype: object;\n};\n\nconst CONTRACT_VERSION_PROPERTY = \"CONTRACT_VERSION\" as const;\nconst CONTRACT_VERSION_PATTERN = /^\\d+\\.\\d+$/;\n\nfunction version<const TVersion extends ContractVersion>(\n contractVersion: TVersion,\n) {\n if (!CONTRACT_VERSION_PATTERN.test(contractVersion)) {\n throw new TypeError(\n `Invalid contract version \"${contractVersion}\". Expected MAJOR.MINOR.`,\n );\n }\n\n return (target: VersionedTarget): void => {\n Object.defineProperty(target, CONTRACT_VERSION_PROPERTY, {\n value: contractVersion,\n writable: false,\n configurable: false,\n enumerable: false,\n });\n };\n}\n\nexport {\n CONTRACT_VERSION_PROPERTY,\n type ContractVersion,\n version,\n type VersionedTarget,\n};\n","import { 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","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 { InvariantViolationException } from \"../exceptions/invariant-violation-exception.js\";\n\ntype PrimitiveValue =\n | bigint\n | boolean\n | null\n | number\n | string\n | symbol\n | undefined;\n\ntype DeepReadonly<T> = T extends PrimitiveValue | Date\n ? T\n : T extends readonly (infer TItem)[]\n ? readonly DeepReadonly<TItem>[]\n : { readonly [TKey in keyof T]: DeepReadonly<T[TKey]> };\n\nfunction deepFreeze<T>(value: T): T {\n return deepFreezeInternal(value, new WeakSet<object>());\n}\n\nfunction deepFreezeInternal<T>(value: T, seen: WeakSet<object>): T {\n // Primitives and `null` need no freezing. `Date` is intentionally returned\n // as-is: `Object.freeze` cannot stop a Date's mutators (`setTime`,\n // `setFullYear`, …) because they write an internal slot, not an own\n // property — freezing it is a no-op against mutation. `makeImmutable`\n // already hands us a `structuredClone` copy, so the caller's original Date\n // is never aliased; deep-freezing of nested Dates is deliberately skipped.\n if (typeof value !== \"object\" || value === null || value instanceof Date) {\n return value;\n }\n\n // A value already on `seen` has been visited on this pass (cyclic graph or a\n // shared reference); revisiting it would recurse forever.\n if (seen.has(value)) {\n return value;\n }\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const item of value) {\n deepFreezeInternal(item, seen);\n }\n\n return Object.freeze(value);\n }\n\n const objectValue = value as Record<PropertyKey, object | PrimitiveValue>;\n\n for (const propertyKey of Reflect.ownKeys(objectValue)) {\n deepFreezeInternal(objectValue[propertyKey], seen);\n }\n\n return Object.freeze(value);\n}\n\nfunction makeImmutable<T>(value: T): DeepReadonly<T> {\n if (typeof value !== \"object\" || value === null) {\n return value as DeepReadonly<T>;\n }\n\n let snapshot: T;\n try {\n snapshot = structuredClone(value);\n } catch (error) {\n // `structuredClone` throws `DataCloneError` for functions, symbols and\n // class instances. Surface it as a domain invariant instead of leaking\n // a host-specific runtime error to callers building value objects.\n throw new InvariantViolationException(\n `makeImmutable requires a structured-cloneable value: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n\n return deepFreeze(snapshot) as DeepReadonly<T>;\n}\n\nexport { deepFreeze, makeImmutable, type DeepReadonly };\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":";;;;;;AAMA,MAAM,4BAA4B;AAClC,MAAM,2BAA2B;AAEjC,SAAS,QACL,iBACF;CACE,IAAI,CAAC,yBAAyB,KAAK,eAAe,GAC9C,MAAM,IAAI,UACN,6BAA6B,gBAAgB,yBACjD;CAGJ,QAAQ,WAAkC;EACtC,OAAO,eAAe,QAAQ,2BAA2B;GACrD,OAAO;GACP,UAAU;GACV,cAAc;GACd,YAAY;EAChB,CAAC;CACL;AACJ;;;;;;;;;;;;ACHA,MAAM,oBAAoB;AAC1B,MAAM,qBAAqB;AAI3B,IAAA,UAAA,MACe,QAGb;;;;CAGE,IAAW,kBAAmC;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