@longzai-intelligence/shared-kernel 0.0.1

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/README.md ADDED
@@ -0,0 +1,35 @@
1
+ # @longzai-intelligence/shared-kernel
2
+
3
+ DDD 基础抽象包 - 提供领域驱动设计的核心抽象,无具体业务实现。
4
+
5
+ ## 安装
6
+
7
+ ```bash
8
+ bun add @longzai-intelligence/shared-kernel
9
+ ```
10
+
11
+ ## 核心模块
12
+
13
+ ### 实体基类
14
+
15
+ 提供领域实体和聚合根的基础抽象。
16
+
17
+ ### 领域事件
18
+
19
+ 提供领域事件的基类和通用事件类型。
20
+
21
+ ### Result 模式
22
+
23
+ 提供函数式的错误处理模式。
24
+
25
+ ### 领域异常
26
+
27
+ 提供统一的领域异常体系。
28
+
29
+ ### 值对象
30
+
31
+ 提供值对象的基础抽象。
32
+
33
+ ### 仓储接口
34
+
35
+ 提供仓储的基础接口定义。
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require(`zod`);var t=class{_id;_props;_events=[];constructor(e,t){this._id=e,this._props=t}get id(){return this._id}get props(){return this._props}updateProps(e,t){this._props[e]=t}addEvent(e){this._events.push(e)}pullEvents(){let e=[...this._events];return this._events=[],e}hasEvents(){return this._events.length>0}equals(e){return this._id===e._id}},n=class extends t{_version=1;_isDirty=!1;get version(){return this._version}get isDirty(){return this._isDirty}markAsDirty(){this._isDirty=!0,this._version++}},r=class{static TYPE;eventId;occurredAt;traceContext;constructor(e,t){this.eventId=e,this.occurredAt=new Date,this.traceContext=t}toJSON(){return{eventId:this.eventId,type:this.type,occurredAt:this.occurredAt.toISOString(),traceContext:this.traceContext}}},i=class extends r{type=`entity:created`;constructor(e,t,n){super(e),this.entityType=t,this.entityId=n}toJSON(){return{...super.toJSON(),entityType:this.entityType,entityId:this.entityId}}},a=class extends r{type=`entity:updated`;constructor(e,t,n,r){super(e),this.entityType=t,this.entityId=n,this.changes=r}toJSON(){return{...super.toJSON(),entityType:this.entityType,entityId:this.entityId,changes:this.changes}}},o=class extends r{type=`entity:deleted`;constructor(e,t,n){super(e),this.entityType=t,this.entityId=n}toJSON(){return{...super.toJSON(),entityType:this.entityType,entityId:this.entityId}}},s=class extends Error{constructor(e,t=`DOMAIN_ERROR`,n){super(e),this.code=t,this.context=n,this.name=`DomainError`}toJSON(){return{name:this.name,code:this.code,message:this.message,context:this.context,stack:this.stack}}},c=class extends s{constructor(e,t,n){super(e,`VALIDATION_ERROR`,{field:t,value:n}),this.field=t,this.value=n,this.name=`ValidationError`}},l=class extends s{constructor(e,t){super(e,`BUSINESS_RULE_ERROR`,{rule:t}),this.name=`BusinessRuleError`}},u=class extends s{constructor(e,t){super(`${e} 未找到: ${t}`,`ENTITY_NOT_FOUND`,{entityType:e,entityId:t}),this.entityType=e,this.entityId=t,this.name=`EntityNotFoundError`}},d=class extends s{constructor(e,t,n){super(e,`REPOSITORY_ERROR`,n),this.cause=t,this.name=`RepositoryError`}toJSON(){return{...super.toJSON(),cause:this.cause?.message}}},f=class extends s{constructor(e=`并发冲突,请重试`){super(e,`CONCURRENCY_ERROR`),this.name=`ConcurrencyError`}},p=class extends s{constructor(e,t){super(`无权限执行操作: ${t} on ${e}`,`PERMISSION_DENIED`,{resource:e,action:t}),this.resource=e,this.action=t,this.name=`PermissionDeniedError`}},m=class extends s{constructor(e,t){super(e,`CONFIGURATION_ERROR`,{key:t}),this.key=t,this.name=`ConfigurationError`}},h=class extends s{constructor(e,t,n){super(t,`EXTERNAL_SERVICE_ERROR`,{service:e}),this.service=e,this.name=`ExternalServiceError`,n&&(this.cause=n)}};function g(e){return e instanceof s?e:e instanceof Error?new d(e.message,e):new d(String(e))}function _(e,t,n){(n?t.withOperation(n):t).error(e.message,e,{code:e.code,name:e.name,context:e.context})}function v(e){return[`CONCURRENCY_ERROR`,`EXTERNAL_SERVICE_ERROR`].includes(e.code)}function y(e){return[`VALIDATION_ERROR`,`BUSINESS_RULE_ERROR`,`ENTITY_NOT_FOUND`,`PERMISSION_DENIED`].includes(e.code)}function b(e){return e instanceof c}function x(e){return e instanceof l}function S(e){return e instanceof u}function C(e){return e instanceof d}function w(e){return e instanceof f}function T(e){return e instanceof p}function E(e){return e instanceof m}function D(e){return e instanceof h}const O=Symbol(`UnitOfWork`);var k=class{_value;constructor(e){this._value=Object.freeze(e)}get value(){return this._value}valueOf(){return this._value}toString(){return String(this._value)}},A=class e extends k{constructor(e){super(e)}static fromString(t){if(!t||t.trim().length===0)throw Error(`实体 ID 不能为空`);return new e(t)}equals(e){return this._value===e._value}},j=class e extends k{constructor(e){super(e)}static now(){return new e(Date.now())}static fromDate(t){return new e(t.getTime())}static fromMillis(t){return new e(t)}toDate(){return new Date(this._value)}equals(e){return this._value===e._value}},M=class e extends k{constructor(e){super(e)}static initial(){return new e(0)}static fromNumber(t){if(!Number.isInteger(t)||t<0)throw Error(`版本号必须是非负整数`);return new e(t)}increment(){return new e(this._value+1)}equals(e){return this._value===e._value}isInitial(){return this._value===0}};let N=function(e){return e.LOCAL=`local`,e.PENDING=`pending`,e.SYNCED=`synced`,e.CONFLICT=`conflict`,e}({});var P=class e extends k{constructor(e){super(e)}static local(){return new e(N.LOCAL)}static pending(){return new e(N.PENDING)}static synced(){return new e(N.SYNCED)}static conflict(){return new e(N.CONFLICT)}static fromString(t){switch(t){case`local`:return e.local();case`pending`:return e.pending();case`synced`:return e.synced();case`conflict`:return e.conflict();default:throw Error(`未知的同步状态: ${t}`)}}needsSync(){return this._value===N.LOCAL||this._value===N.PENDING}equals(e){return this._value===e._value}},F=class{isSuccess=!0;isFailure=!1;constructor(e){this.value=e}map(e){return L(e(this.value))}flatMap(e){return e(this.value)}mapError(e){return L(this.value)}getOrElse(e){return this.value}match(e){return e.success(this.value)}},I=class{isSuccess=!1;isFailure=!0;constructor(e){this.error=e}map(e){return R(this.error)}flatMap(e){return R(this.error)}mapError(e){return R(e(this.error))}getOrElse(e){return e}match(e){return e.failure(this.error)}};function L(e){return new F(e)}function R(e){return new I(e)}function z(e){let t=[];for(let n of e){if(n.isFailure)return R(n.error);t.push(n.value)}return L(t)}function B(e){return e.isSuccess}function V(e){return e.isFailure}function H(e){if(e.isFailure)throw g(e.error);return e.value}const U=e.z.string().uuid(`无效的UUID格式`),W=U,G=e.z.number().int().positive(),K=e.z.number().int().nonnegative(),q=e.z.enum([`create`,`update`,`delete`]),J=e.z.enum([`local-wins`,`remote-wins`,`merge`,`manual`]),Y=e.z.object({id:e.z.string(),type:e.z.string()}),X=e.z.object({start:e.z.coerce.date(),end:e.z.coerce.date()}),Z=e.z.object({id:e.z.string(),type:e.z.string(),version:K,data:e.z.record(e.z.string(),e.z.unknown()),timestamp:G}),Q=e.z.object({entityId:e.z.string(),entityType:e.z.string(),changeType:q,data:e.z.record(e.z.string(),e.z.unknown()).optional(),timestamp:G,version:K}),$=e.z.object({id:e.z.string(),entityType:e.z.string(),entityId:e.z.string(),localVersion:K,remoteVersion:K,localData:e.z.record(e.z.string(),e.z.unknown()),remoteData:e.z.record(e.z.string(),e.z.unknown()),conflictedAt:G}),ee=e.z.object({conflictId:e.z.string(),strategy:J,resolvedData:e.z.record(e.z.string(),e.z.unknown()),resolvedAt:G});exports.AggregateRoot=n,exports.AggregateRootEntity=n,exports.BusinessRuleError=l,exports.ChangeTypeSchema=q,exports.ConcurrencyError=f,exports.ConfigurationError=m,exports.ConflictDataSchema=$,exports.ConflictResolutionSchema=ee,exports.ConflictResolutionStrategySchema=J,exports.DomainError=s,exports.DomainEvent=r,exports.Entity=t,exports.EntityChangeSchema=Q,exports.EntityCreatedEvent=i,exports.EntityDeletedEvent=o,exports.EntityIdSchema=W,exports.EntityIdVO=A,exports.EntityNotFoundError=u,exports.EntityUpdatedEvent=a,exports.ExternalServiceError=h,exports.Failure=I,exports.IdReferenceSchema=Y,exports.PermissionDeniedError=p,exports.RepositoryError=d,exports.Success=F,exports.SyncDataSchema=Z,exports.SyncStatus=N,exports.SyncStatusVO=P,exports.TimeRangeSchema=X,exports.TimestampSchema=G,exports.TimestampVO=j,exports.UNIT_OF_WORK_TOKEN=O,exports.UuidSchema=U,exports.ValidationError=c,exports.ValueObject=k,exports.VersionSchema=K,exports.VersionVO=M,exports.combine=z,exports.failure=R,exports.isBusinessRuleError=x,exports.isClientError=y,exports.isConcurrencyError=w,exports.isConfigurationError=E,exports.isEntityNotFoundError=S,exports.isExternalServiceError=D,exports.isFailure=V,exports.isPermissionDeniedError=T,exports.isRepositoryError=C,exports.isRetryableError=v,exports.isSuccess=B,exports.isValidationError=b,exports.logError=_,exports.success=L,exports.toDomainError=g,exports.unwrapResult=H;
@@ -0,0 +1,410 @@
1
+ import { z } from "zod";
2
+
3
+ //#region src/domain/events/domain-event.types.d.ts
4
+ type Event = {
5
+ readonly eventId: string;
6
+ readonly occurredAt: Date;
7
+ readonly type: string;
8
+ };
9
+ type TraceContext = {
10
+ traceId: string;
11
+ spanId: string;
12
+ parentSpanId?: string;
13
+ };
14
+ type DomainEvent$1 = Event & {
15
+ readonly traceContext?: TraceContext;
16
+ };
17
+ //#endregion
18
+ //#region src/domain/events/domain-event.base.d.ts
19
+ declare abstract class DomainEvent implements DomainEvent$1 {
20
+ static readonly TYPE: string;
21
+ readonly eventId: string;
22
+ readonly occurredAt: Date;
23
+ abstract readonly type: string;
24
+ readonly traceContext?: TraceContext;
25
+ constructor(eventId: string, traceContext?: TraceContext);
26
+ toJSON(): Record<string, unknown>;
27
+ }
28
+ //#endregion
29
+ //#region src/domain/events/entity.events.d.ts
30
+ declare class EntityCreatedEvent extends DomainEvent {
31
+ readonly entityType: string;
32
+ readonly entityId: string;
33
+ readonly type = "entity:created";
34
+ constructor(eventId: string, entityType: string, entityId: string);
35
+ toJSON(): Record<string, unknown>;
36
+ }
37
+ declare class EntityUpdatedEvent extends DomainEvent {
38
+ readonly entityType: string;
39
+ readonly entityId: string;
40
+ readonly changes: Record<string, unknown>;
41
+ readonly type = "entity:updated";
42
+ constructor(eventId: string, entityType: string, entityId: string, changes: Record<string, unknown>);
43
+ toJSON(): Record<string, unknown>;
44
+ }
45
+ declare class EntityDeletedEvent extends DomainEvent {
46
+ readonly entityType: string;
47
+ readonly entityId: string;
48
+ readonly type = "entity:deleted";
49
+ constructor(eventId: string, entityType: string, entityId: string);
50
+ toJSON(): Record<string, unknown>;
51
+ }
52
+ //#endregion
53
+ //#region src/domain/events/event-bus.types.d.ts
54
+ type DomainEventHandler<T extends DomainEvent$1> = (event: T) => Promise<void> | void;
55
+ type DomainEventConstructor<T extends DomainEvent$1> = {
56
+ readonly TYPE: string;
57
+ new (...args: unknown[]): T;
58
+ };
59
+ type EventConstructor<T extends DomainEvent$1> = DomainEventConstructor<T>;
60
+ //#endregion
61
+ //#region src/domain/entities/entity.base.d.ts
62
+ declare abstract class Entity<T> {
63
+ protected readonly _id: string;
64
+ protected _props: T;
65
+ private _events;
66
+ constructor(id: string, props: T);
67
+ get id(): string;
68
+ get props(): Readonly<T>;
69
+ protected updateProps<K extends keyof T>(key: K, value: T[K]): void;
70
+ protected addEvent(event: DomainEvent): void;
71
+ pullEvents(): DomainEvent[];
72
+ hasEvents(): boolean;
73
+ equals(other: Entity<T>): boolean;
74
+ }
75
+ //#endregion
76
+ //#region src/domain/entities/aggregate-root.entity.d.ts
77
+ declare abstract class AggregateRootEntity<T> extends Entity<T> {
78
+ protected _version: number;
79
+ protected _isDirty: boolean;
80
+ get version(): number;
81
+ get isDirty(): boolean;
82
+ protected markAsDirty(): void;
83
+ }
84
+ //#endregion
85
+ //#region src/domain/tracing/tracing-context.types.d.ts
86
+ type TracingContextManager = {
87
+ getCurrentContext(): TraceContext | undefined;
88
+ getCurrentTraceId(): string | undefined;
89
+ getCurrentSpanId(): string | undefined;
90
+ createNewContext(): TraceContext;
91
+ createChildContext(parentContext: TraceContext): TraceContext;
92
+ runWithContext<T>(context: TraceContext, fn: () => T): T;
93
+ runWithNewTrace<T>(fn: () => T): T;
94
+ runWithChildSpan<T>(fn: () => T): T;
95
+ };
96
+ //#endregion
97
+ //#region src/domain/exception/domain-exception.errors.d.ts
98
+ declare abstract class DomainError extends Error {
99
+ readonly code: string;
100
+ readonly context?: Record<string, unknown> | undefined;
101
+ constructor(message: string, code?: string, context?: Record<string, unknown> | undefined);
102
+ toJSON(): object;
103
+ }
104
+ declare class ValidationError extends DomainError {
105
+ readonly field?: string | undefined;
106
+ readonly value?: unknown | undefined;
107
+ constructor(message: string, field?: string | undefined, value?: unknown | undefined);
108
+ }
109
+ declare class BusinessRuleError extends DomainError {
110
+ constructor(message: string, rule?: string);
111
+ }
112
+ declare class EntityNotFoundError extends DomainError {
113
+ readonly entityType: string;
114
+ readonly entityId: string;
115
+ constructor(entityType: string, entityId: string);
116
+ }
117
+ declare class RepositoryError extends DomainError {
118
+ readonly cause?: Error | undefined;
119
+ constructor(message: string, cause?: Error | undefined, context?: Record<string, unknown>);
120
+ toJSON(): object;
121
+ }
122
+ declare class ConcurrencyError extends DomainError {
123
+ constructor(message?: string);
124
+ }
125
+ declare class PermissionDeniedError extends DomainError {
126
+ readonly resource: string;
127
+ readonly action: string;
128
+ constructor(resource: string, action: string);
129
+ }
130
+ declare class ConfigurationError extends DomainError {
131
+ readonly key?: string | undefined;
132
+ constructor(message: string, key?: string | undefined);
133
+ }
134
+ declare class ExternalServiceError extends DomainError {
135
+ readonly service: string;
136
+ constructor(service: string, message: string, cause?: Error);
137
+ }
138
+ //#endregion
139
+ //#region ../logger/core/dist/index.d.mts
140
+ //#endregion
141
+ //#region src/tracing/context.types.d.ts
142
+ type TraceContext$1 = {
143
+ traceId: string;
144
+ spanId: string;
145
+ parentSpanId?: string;
146
+ };
147
+ //#endregion
148
+ //#region src/log/logger.types.d.ts
149
+ type Logger = {
150
+ debug(message: string, metadata?: Record<string, unknown>): void;
151
+ info(message: string, metadata?: Record<string, unknown>): void;
152
+ warn(message: string, metadata?: Record<string, unknown>): void;
153
+ error(message: string, error?: Error, metadata?: Record<string, unknown>): void;
154
+ withOperation(operation: string): Logger;
155
+ withTrace(trace: TraceContext$1): Logger;
156
+ };
157
+ //#endregion
158
+ //#region src/domain/exception/error-utils.d.ts
159
+ declare function toDomainError(error: unknown): DomainError;
160
+ declare function logError(error: DomainError, logger: Logger, operation?: string): void;
161
+ declare function isRetryableError(error: DomainError): boolean;
162
+ declare function isClientError(error: DomainError): boolean;
163
+ declare function isValidationError(error: DomainError): error is ValidationError;
164
+ declare function isBusinessRuleError(error: DomainError): error is BusinessRuleError;
165
+ declare function isEntityNotFoundError(error: DomainError): error is EntityNotFoundError;
166
+ declare function isRepositoryError(error: DomainError): error is RepositoryError;
167
+ declare function isConcurrencyError(error: DomainError): error is ConcurrencyError;
168
+ declare function isPermissionDeniedError(error: DomainError): error is PermissionDeniedError;
169
+ declare function isConfigurationError(error: DomainError): error is ConfigurationError;
170
+ declare function isExternalServiceError(error: DomainError): error is ExternalServiceError;
171
+ //#endregion
172
+ //#region src/domain/repositories/repository.types.d.ts
173
+ type PaginationParams = {
174
+ page: number;
175
+ pageSize: number;
176
+ };
177
+ type SortParams = {
178
+ field: string;
179
+ direction: 'asc' | 'desc';
180
+ };
181
+ type QueryOptions = {
182
+ pagination?: PaginationParams;
183
+ sort?: SortParams[];
184
+ includeDeleted?: boolean;
185
+ };
186
+ type Repository<T extends Entity<unknown>> = {
187
+ findById(id: string): Promise<T | null>;
188
+ findAll(): Promise<T[]>;
189
+ save(entity: T): Promise<void>;
190
+ saveAll(entities: T[]): Promise<void>;
191
+ delete(id: string): Promise<void>;
192
+ exists(id: string): Promise<boolean>;
193
+ };
194
+ //#endregion
195
+ //#region src/domain/result/result.types.d.ts
196
+ type MapFunction<T, U> = (value: T) => U;
197
+ type FlatMapFunction<T, U, E> = (value: T) => Result<U, E>;
198
+ type ErrorMapFunction<E, F> = (error: E) => F;
199
+ type MatchHandlers<T, E, U> = {
200
+ success: (value: T) => U;
201
+ failure: (error: E) => U;
202
+ };
203
+ type Result<T, E = DomainError> = Success<T, E> | Failure<T, E>;
204
+ declare class Success<T, E = DomainError> {
205
+ readonly value: T;
206
+ readonly isSuccess: true;
207
+ readonly isFailure: false;
208
+ constructor(value: T);
209
+ map<U>(fn: MapFunction<T, U>): Result<U, E>;
210
+ flatMap<U>(fn: FlatMapFunction<T, U, E>): Result<U, E>;
211
+ mapError<F>(_fn: ErrorMapFunction<E, F>): Result<T, F>;
212
+ getOrElse(_defaultValue: T): T;
213
+ match<U>(handlers: MatchHandlers<T, E, U>): U;
214
+ }
215
+ declare class Failure<T, E = DomainError> {
216
+ readonly error: E;
217
+ readonly isSuccess: false;
218
+ readonly isFailure: true;
219
+ constructor(error: E);
220
+ map<U>(_fn: MapFunction<T, U>): Result<U, E>;
221
+ flatMap<U>(_fn: FlatMapFunction<T, U, E>): Result<U, E>;
222
+ mapError<F>(fn: ErrorMapFunction<E, F>): Result<T, F>;
223
+ getOrElse(defaultValue: T): T;
224
+ match<U>(handlers: MatchHandlers<T, E, U>): U;
225
+ }
226
+ declare function success<T, E = DomainError>(value: T): Result<T, E>;
227
+ declare function failure<T, E = DomainError>(error: E): Result<T, E>;
228
+ declare function combine<T, E = DomainError>(results: Result<T, E>[]): Result<T[], E>;
229
+ declare function isSuccess<T, E>(result: Result<T, E>): result is Success<T, E>;
230
+ declare function isFailure<T, E>(result: Result<T, E>): result is Failure<T, E>;
231
+ declare function unwrapResult<T, E = DomainError>(result: Result<T, E>): T;
232
+ //#endregion
233
+ //#region src/domain/repositories/unit-of-work.types.d.ts
234
+ type UnitOfWork = {
235
+ start(): Promise<Result<void, DomainError>>;
236
+ commit(): Promise<Result<void, DomainError>>;
237
+ rollback(): Promise<Result<void, DomainError>>;
238
+ withTransaction<T>(work: () => Promise<Result<T, DomainError>>): Promise<Result<T, DomainError>>;
239
+ };
240
+ declare const UNIT_OF_WORK_TOKEN: unique symbol;
241
+ //#endregion
242
+ //#region src/domain/value-object/value-object.base.d.ts
243
+ declare abstract class ValueObject<T> {
244
+ protected readonly _value: T;
245
+ constructor(value: T);
246
+ get value(): T;
247
+ valueOf(): T;
248
+ abstract equals(other: ValueObject<T>): boolean;
249
+ toString(): string;
250
+ }
251
+ //#endregion
252
+ //#region src/domain/value-object/entity-id.vo.d.ts
253
+ declare class EntityIdVO extends ValueObject<string> {
254
+ private constructor();
255
+ static fromString(value: string): EntityIdVO;
256
+ equals(other: EntityIdVO): boolean;
257
+ }
258
+ //#endregion
259
+ //#region src/domain/value-object/timestamp.vo.d.ts
260
+ declare class TimestampVO extends ValueObject<number> {
261
+ private constructor();
262
+ static now(): TimestampVO;
263
+ static fromDate(date: Date): TimestampVO;
264
+ static fromMillis(millis: number): TimestampVO;
265
+ toDate(): Date;
266
+ equals(other: TimestampVO): boolean;
267
+ }
268
+ //#endregion
269
+ //#region src/domain/value-object/version.vo.d.ts
270
+ declare class VersionVO extends ValueObject<number> {
271
+ private constructor();
272
+ static initial(): VersionVO;
273
+ static fromNumber(value: number): VersionVO;
274
+ increment(): VersionVO;
275
+ equals(other: VersionVO): boolean;
276
+ isInitial(): boolean;
277
+ }
278
+ //#endregion
279
+ //#region src/domain/value-object/sync-status.vo.d.ts
280
+ declare enum SyncStatus {
281
+ LOCAL = "local",
282
+ PENDING = "pending",
283
+ SYNCED = "synced",
284
+ CONFLICT = "conflict"
285
+ }
286
+ declare class SyncStatusVO extends ValueObject<SyncStatus> {
287
+ private constructor();
288
+ static local(): SyncStatusVO;
289
+ static pending(): SyncStatusVO;
290
+ static synced(): SyncStatusVO;
291
+ static conflict(): SyncStatusVO;
292
+ static fromString(value: string): SyncStatusVO;
293
+ needsSync(): boolean;
294
+ equals(other: SyncStatusVO): boolean;
295
+ }
296
+ //#endregion
297
+ //#region src/domain/types/types.d.ts
298
+ type SyncData = {
299
+ id: string;
300
+ type: string;
301
+ version: number;
302
+ data: Record<string, unknown>;
303
+ timestamp: number;
304
+ };
305
+ type EntityChange = {
306
+ entityId: string;
307
+ entityType: string;
308
+ changeType: 'create' | 'update' | 'delete';
309
+ data?: Record<string, unknown>;
310
+ timestamp: number;
311
+ version: number;
312
+ };
313
+ type ConflictData = {
314
+ id: string;
315
+ entityType: string;
316
+ entityId: string;
317
+ localVersion: number;
318
+ remoteVersion: number;
319
+ localData: Record<string, unknown>;
320
+ remoteData: Record<string, unknown>;
321
+ conflictedAt: number;
322
+ };
323
+ type ConflictResolutionStrategy = 'local-wins' | 'remote-wins' | 'merge' | 'manual';
324
+ type ConflictResolution = {
325
+ conflictId: string;
326
+ strategy: ConflictResolutionStrategy;
327
+ resolvedData: Record<string, unknown>;
328
+ resolvedAt: number;
329
+ };
330
+ type TimeRange = {
331
+ start: Date;
332
+ end: Date;
333
+ };
334
+ type Reference = {
335
+ id: string;
336
+ type: string;
337
+ };
338
+ //#endregion
339
+ //#region src/domain/schemas/common.schema.d.ts
340
+ declare const UuidSchema: z.ZodString;
341
+ declare const EntityIdSchema: z.ZodString;
342
+ declare const TimestampSchema: z.ZodNumber;
343
+ declare const VersionSchema: z.ZodNumber;
344
+ declare const ChangeTypeSchema: z.ZodEnum<{
345
+ create: "create";
346
+ update: "update";
347
+ delete: "delete";
348
+ }>;
349
+ declare const ConflictResolutionStrategySchema: z.ZodEnum<{
350
+ "local-wins": "local-wins";
351
+ "remote-wins": "remote-wins";
352
+ merge: "merge";
353
+ manual: "manual";
354
+ }>;
355
+ declare const IdReferenceSchema: z.ZodObject<{
356
+ id: z.ZodString;
357
+ type: z.ZodString;
358
+ }, z.core.$strip>;
359
+ declare const TimeRangeSchema: z.ZodObject<{
360
+ start: z.ZodCoercedDate<unknown>;
361
+ end: z.ZodCoercedDate<unknown>;
362
+ }, z.core.$strip>;
363
+ declare const SyncDataSchema: z.ZodObject<{
364
+ id: z.ZodString;
365
+ type: z.ZodString;
366
+ version: z.ZodNumber;
367
+ data: z.ZodRecord<z.ZodString, z.ZodUnknown>;
368
+ timestamp: z.ZodNumber;
369
+ }, z.core.$strip>;
370
+ declare const EntityChangeSchema: z.ZodObject<{
371
+ entityId: z.ZodString;
372
+ entityType: z.ZodString;
373
+ changeType: z.ZodEnum<{
374
+ create: "create";
375
+ update: "update";
376
+ delete: "delete";
377
+ }>;
378
+ data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
379
+ timestamp: z.ZodNumber;
380
+ version: z.ZodNumber;
381
+ }, z.core.$strip>;
382
+ declare const ConflictDataSchema: z.ZodObject<{
383
+ id: z.ZodString;
384
+ entityType: z.ZodString;
385
+ entityId: z.ZodString;
386
+ localVersion: z.ZodNumber;
387
+ remoteVersion: z.ZodNumber;
388
+ localData: z.ZodRecord<z.ZodString, z.ZodUnknown>;
389
+ remoteData: z.ZodRecord<z.ZodString, z.ZodUnknown>;
390
+ conflictedAt: z.ZodNumber;
391
+ }, z.core.$strip>;
392
+ declare const ConflictResolutionSchema: z.ZodObject<{
393
+ conflictId: z.ZodString;
394
+ strategy: z.ZodEnum<{
395
+ "local-wins": "local-wins";
396
+ "remote-wins": "remote-wins";
397
+ merge: "merge";
398
+ manual: "manual";
399
+ }>;
400
+ resolvedData: z.ZodRecord<z.ZodString, z.ZodUnknown>;
401
+ resolvedAt: z.ZodNumber;
402
+ }, z.core.$strip>;
403
+ type Uuid = z.infer<typeof UuidSchema>;
404
+ type EntityId = z.infer<typeof EntityIdSchema>;
405
+ type Timestamp = z.infer<typeof TimestampSchema>;
406
+ type Version = z.infer<typeof VersionSchema>;
407
+ type ChangeType = z.infer<typeof ChangeTypeSchema>;
408
+ type IdReference = z.infer<typeof IdReferenceSchema>;
409
+ //#endregion
410
+ export { AggregateRootEntity as AggregateRoot, AggregateRootEntity, BusinessRuleError, type ChangeType, ChangeTypeSchema, ConcurrencyError, ConfigurationError, type ConflictData, ConflictDataSchema, type ConflictResolution, ConflictResolutionSchema, type ConflictResolutionStrategy, ConflictResolutionStrategySchema, DomainError, DomainEvent, type DomainEventConstructor, type DomainEventHandler, Entity, type EntityChange, EntityChangeSchema, EntityCreatedEvent, EntityDeletedEvent, type EntityId, EntityIdSchema, EntityIdVO, EntityNotFoundError, EntityUpdatedEvent, type EventConstructor, ExternalServiceError, Failure, type IdReference, IdReferenceSchema, PermissionDeniedError, type QueryOptions, type Reference, type Repository, RepositoryError, type Result, type SortParams, Success, type SyncData, SyncDataSchema, SyncStatus, SyncStatusVO, type TimeRange, TimeRangeSchema, type Timestamp, TimestampSchema, TimestampVO, type TraceContext, type TracingContextManager, UNIT_OF_WORK_TOKEN, type UnitOfWork, type Uuid, UuidSchema, ValidationError, ValueObject, type Version, VersionSchema, VersionVO, combine, failure, isBusinessRuleError, isClientError, isConcurrencyError, isConfigurationError, isEntityNotFoundError, isExternalServiceError, isFailure, isPermissionDeniedError, isRepositoryError, isRetryableError, isSuccess, isValidationError, logError, success, toDomainError, unwrapResult };
@@ -0,0 +1,410 @@
1
+ import { z } from "zod";
2
+
3
+ //#region src/domain/events/domain-event.types.d.ts
4
+ type Event = {
5
+ readonly eventId: string;
6
+ readonly occurredAt: Date;
7
+ readonly type: string;
8
+ };
9
+ type TraceContext = {
10
+ traceId: string;
11
+ spanId: string;
12
+ parentSpanId?: string;
13
+ };
14
+ type DomainEvent$1 = Event & {
15
+ readonly traceContext?: TraceContext;
16
+ };
17
+ //#endregion
18
+ //#region src/domain/events/domain-event.base.d.ts
19
+ declare abstract class DomainEvent implements DomainEvent$1 {
20
+ static readonly TYPE: string;
21
+ readonly eventId: string;
22
+ readonly occurredAt: Date;
23
+ abstract readonly type: string;
24
+ readonly traceContext?: TraceContext;
25
+ constructor(eventId: string, traceContext?: TraceContext);
26
+ toJSON(): Record<string, unknown>;
27
+ }
28
+ //#endregion
29
+ //#region src/domain/events/entity.events.d.ts
30
+ declare class EntityCreatedEvent extends DomainEvent {
31
+ readonly entityType: string;
32
+ readonly entityId: string;
33
+ readonly type = "entity:created";
34
+ constructor(eventId: string, entityType: string, entityId: string);
35
+ toJSON(): Record<string, unknown>;
36
+ }
37
+ declare class EntityUpdatedEvent extends DomainEvent {
38
+ readonly entityType: string;
39
+ readonly entityId: string;
40
+ readonly changes: Record<string, unknown>;
41
+ readonly type = "entity:updated";
42
+ constructor(eventId: string, entityType: string, entityId: string, changes: Record<string, unknown>);
43
+ toJSON(): Record<string, unknown>;
44
+ }
45
+ declare class EntityDeletedEvent extends DomainEvent {
46
+ readonly entityType: string;
47
+ readonly entityId: string;
48
+ readonly type = "entity:deleted";
49
+ constructor(eventId: string, entityType: string, entityId: string);
50
+ toJSON(): Record<string, unknown>;
51
+ }
52
+ //#endregion
53
+ //#region src/domain/events/event-bus.types.d.ts
54
+ type DomainEventHandler<T extends DomainEvent$1> = (event: T) => Promise<void> | void;
55
+ type DomainEventConstructor<T extends DomainEvent$1> = {
56
+ readonly TYPE: string;
57
+ new (...args: unknown[]): T;
58
+ };
59
+ type EventConstructor<T extends DomainEvent$1> = DomainEventConstructor<T>;
60
+ //#endregion
61
+ //#region src/domain/entities/entity.base.d.ts
62
+ declare abstract class Entity<T> {
63
+ protected readonly _id: string;
64
+ protected _props: T;
65
+ private _events;
66
+ constructor(id: string, props: T);
67
+ get id(): string;
68
+ get props(): Readonly<T>;
69
+ protected updateProps<K extends keyof T>(key: K, value: T[K]): void;
70
+ protected addEvent(event: DomainEvent): void;
71
+ pullEvents(): DomainEvent[];
72
+ hasEvents(): boolean;
73
+ equals(other: Entity<T>): boolean;
74
+ }
75
+ //#endregion
76
+ //#region src/domain/entities/aggregate-root.entity.d.ts
77
+ declare abstract class AggregateRootEntity<T> extends Entity<T> {
78
+ protected _version: number;
79
+ protected _isDirty: boolean;
80
+ get version(): number;
81
+ get isDirty(): boolean;
82
+ protected markAsDirty(): void;
83
+ }
84
+ //#endregion
85
+ //#region src/domain/tracing/tracing-context.types.d.ts
86
+ type TracingContextManager = {
87
+ getCurrentContext(): TraceContext | undefined;
88
+ getCurrentTraceId(): string | undefined;
89
+ getCurrentSpanId(): string | undefined;
90
+ createNewContext(): TraceContext;
91
+ createChildContext(parentContext: TraceContext): TraceContext;
92
+ runWithContext<T>(context: TraceContext, fn: () => T): T;
93
+ runWithNewTrace<T>(fn: () => T): T;
94
+ runWithChildSpan<T>(fn: () => T): T;
95
+ };
96
+ //#endregion
97
+ //#region src/domain/exception/domain-exception.errors.d.ts
98
+ declare abstract class DomainError extends Error {
99
+ readonly code: string;
100
+ readonly context?: Record<string, unknown> | undefined;
101
+ constructor(message: string, code?: string, context?: Record<string, unknown> | undefined);
102
+ toJSON(): object;
103
+ }
104
+ declare class ValidationError extends DomainError {
105
+ readonly field?: string | undefined;
106
+ readonly value?: unknown | undefined;
107
+ constructor(message: string, field?: string | undefined, value?: unknown | undefined);
108
+ }
109
+ declare class BusinessRuleError extends DomainError {
110
+ constructor(message: string, rule?: string);
111
+ }
112
+ declare class EntityNotFoundError extends DomainError {
113
+ readonly entityType: string;
114
+ readonly entityId: string;
115
+ constructor(entityType: string, entityId: string);
116
+ }
117
+ declare class RepositoryError extends DomainError {
118
+ readonly cause?: Error | undefined;
119
+ constructor(message: string, cause?: Error | undefined, context?: Record<string, unknown>);
120
+ toJSON(): object;
121
+ }
122
+ declare class ConcurrencyError extends DomainError {
123
+ constructor(message?: string);
124
+ }
125
+ declare class PermissionDeniedError extends DomainError {
126
+ readonly resource: string;
127
+ readonly action: string;
128
+ constructor(resource: string, action: string);
129
+ }
130
+ declare class ConfigurationError extends DomainError {
131
+ readonly key?: string | undefined;
132
+ constructor(message: string, key?: string | undefined);
133
+ }
134
+ declare class ExternalServiceError extends DomainError {
135
+ readonly service: string;
136
+ constructor(service: string, message: string, cause?: Error);
137
+ }
138
+ //#endregion
139
+ //#region ../logger/core/dist/index.d.mts
140
+ //#endregion
141
+ //#region src/tracing/context.types.d.ts
142
+ type TraceContext$1 = {
143
+ traceId: string;
144
+ spanId: string;
145
+ parentSpanId?: string;
146
+ };
147
+ //#endregion
148
+ //#region src/log/logger.types.d.ts
149
+ type Logger = {
150
+ debug(message: string, metadata?: Record<string, unknown>): void;
151
+ info(message: string, metadata?: Record<string, unknown>): void;
152
+ warn(message: string, metadata?: Record<string, unknown>): void;
153
+ error(message: string, error?: Error, metadata?: Record<string, unknown>): void;
154
+ withOperation(operation: string): Logger;
155
+ withTrace(trace: TraceContext$1): Logger;
156
+ };
157
+ //#endregion
158
+ //#region src/domain/exception/error-utils.d.ts
159
+ declare function toDomainError(error: unknown): DomainError;
160
+ declare function logError(error: DomainError, logger: Logger, operation?: string): void;
161
+ declare function isRetryableError(error: DomainError): boolean;
162
+ declare function isClientError(error: DomainError): boolean;
163
+ declare function isValidationError(error: DomainError): error is ValidationError;
164
+ declare function isBusinessRuleError(error: DomainError): error is BusinessRuleError;
165
+ declare function isEntityNotFoundError(error: DomainError): error is EntityNotFoundError;
166
+ declare function isRepositoryError(error: DomainError): error is RepositoryError;
167
+ declare function isConcurrencyError(error: DomainError): error is ConcurrencyError;
168
+ declare function isPermissionDeniedError(error: DomainError): error is PermissionDeniedError;
169
+ declare function isConfigurationError(error: DomainError): error is ConfigurationError;
170
+ declare function isExternalServiceError(error: DomainError): error is ExternalServiceError;
171
+ //#endregion
172
+ //#region src/domain/repositories/repository.types.d.ts
173
+ type PaginationParams = {
174
+ page: number;
175
+ pageSize: number;
176
+ };
177
+ type SortParams = {
178
+ field: string;
179
+ direction: 'asc' | 'desc';
180
+ };
181
+ type QueryOptions = {
182
+ pagination?: PaginationParams;
183
+ sort?: SortParams[];
184
+ includeDeleted?: boolean;
185
+ };
186
+ type Repository<T extends Entity<unknown>> = {
187
+ findById(id: string): Promise<T | null>;
188
+ findAll(): Promise<T[]>;
189
+ save(entity: T): Promise<void>;
190
+ saveAll(entities: T[]): Promise<void>;
191
+ delete(id: string): Promise<void>;
192
+ exists(id: string): Promise<boolean>;
193
+ };
194
+ //#endregion
195
+ //#region src/domain/result/result.types.d.ts
196
+ type MapFunction<T, U> = (value: T) => U;
197
+ type FlatMapFunction<T, U, E> = (value: T) => Result<U, E>;
198
+ type ErrorMapFunction<E, F> = (error: E) => F;
199
+ type MatchHandlers<T, E, U> = {
200
+ success: (value: T) => U;
201
+ failure: (error: E) => U;
202
+ };
203
+ type Result<T, E = DomainError> = Success<T, E> | Failure<T, E>;
204
+ declare class Success<T, E = DomainError> {
205
+ readonly value: T;
206
+ readonly isSuccess: true;
207
+ readonly isFailure: false;
208
+ constructor(value: T);
209
+ map<U>(fn: MapFunction<T, U>): Result<U, E>;
210
+ flatMap<U>(fn: FlatMapFunction<T, U, E>): Result<U, E>;
211
+ mapError<F>(_fn: ErrorMapFunction<E, F>): Result<T, F>;
212
+ getOrElse(_defaultValue: T): T;
213
+ match<U>(handlers: MatchHandlers<T, E, U>): U;
214
+ }
215
+ declare class Failure<T, E = DomainError> {
216
+ readonly error: E;
217
+ readonly isSuccess: false;
218
+ readonly isFailure: true;
219
+ constructor(error: E);
220
+ map<U>(_fn: MapFunction<T, U>): Result<U, E>;
221
+ flatMap<U>(_fn: FlatMapFunction<T, U, E>): Result<U, E>;
222
+ mapError<F>(fn: ErrorMapFunction<E, F>): Result<T, F>;
223
+ getOrElse(defaultValue: T): T;
224
+ match<U>(handlers: MatchHandlers<T, E, U>): U;
225
+ }
226
+ declare function success<T, E = DomainError>(value: T): Result<T, E>;
227
+ declare function failure<T, E = DomainError>(error: E): Result<T, E>;
228
+ declare function combine<T, E = DomainError>(results: Result<T, E>[]): Result<T[], E>;
229
+ declare function isSuccess<T, E>(result: Result<T, E>): result is Success<T, E>;
230
+ declare function isFailure<T, E>(result: Result<T, E>): result is Failure<T, E>;
231
+ declare function unwrapResult<T, E = DomainError>(result: Result<T, E>): T;
232
+ //#endregion
233
+ //#region src/domain/repositories/unit-of-work.types.d.ts
234
+ type UnitOfWork = {
235
+ start(): Promise<Result<void, DomainError>>;
236
+ commit(): Promise<Result<void, DomainError>>;
237
+ rollback(): Promise<Result<void, DomainError>>;
238
+ withTransaction<T>(work: () => Promise<Result<T, DomainError>>): Promise<Result<T, DomainError>>;
239
+ };
240
+ declare const UNIT_OF_WORK_TOKEN: unique symbol;
241
+ //#endregion
242
+ //#region src/domain/value-object/value-object.base.d.ts
243
+ declare abstract class ValueObject<T> {
244
+ protected readonly _value: T;
245
+ constructor(value: T);
246
+ get value(): T;
247
+ valueOf(): T;
248
+ abstract equals(other: ValueObject<T>): boolean;
249
+ toString(): string;
250
+ }
251
+ //#endregion
252
+ //#region src/domain/value-object/entity-id.vo.d.ts
253
+ declare class EntityIdVO extends ValueObject<string> {
254
+ private constructor();
255
+ static fromString(value: string): EntityIdVO;
256
+ equals(other: EntityIdVO): boolean;
257
+ }
258
+ //#endregion
259
+ //#region src/domain/value-object/timestamp.vo.d.ts
260
+ declare class TimestampVO extends ValueObject<number> {
261
+ private constructor();
262
+ static now(): TimestampVO;
263
+ static fromDate(date: Date): TimestampVO;
264
+ static fromMillis(millis: number): TimestampVO;
265
+ toDate(): Date;
266
+ equals(other: TimestampVO): boolean;
267
+ }
268
+ //#endregion
269
+ //#region src/domain/value-object/version.vo.d.ts
270
+ declare class VersionVO extends ValueObject<number> {
271
+ private constructor();
272
+ static initial(): VersionVO;
273
+ static fromNumber(value: number): VersionVO;
274
+ increment(): VersionVO;
275
+ equals(other: VersionVO): boolean;
276
+ isInitial(): boolean;
277
+ }
278
+ //#endregion
279
+ //#region src/domain/value-object/sync-status.vo.d.ts
280
+ declare enum SyncStatus {
281
+ LOCAL = "local",
282
+ PENDING = "pending",
283
+ SYNCED = "synced",
284
+ CONFLICT = "conflict"
285
+ }
286
+ declare class SyncStatusVO extends ValueObject<SyncStatus> {
287
+ private constructor();
288
+ static local(): SyncStatusVO;
289
+ static pending(): SyncStatusVO;
290
+ static synced(): SyncStatusVO;
291
+ static conflict(): SyncStatusVO;
292
+ static fromString(value: string): SyncStatusVO;
293
+ needsSync(): boolean;
294
+ equals(other: SyncStatusVO): boolean;
295
+ }
296
+ //#endregion
297
+ //#region src/domain/types/types.d.ts
298
+ type SyncData = {
299
+ id: string;
300
+ type: string;
301
+ version: number;
302
+ data: Record<string, unknown>;
303
+ timestamp: number;
304
+ };
305
+ type EntityChange = {
306
+ entityId: string;
307
+ entityType: string;
308
+ changeType: 'create' | 'update' | 'delete';
309
+ data?: Record<string, unknown>;
310
+ timestamp: number;
311
+ version: number;
312
+ };
313
+ type ConflictData = {
314
+ id: string;
315
+ entityType: string;
316
+ entityId: string;
317
+ localVersion: number;
318
+ remoteVersion: number;
319
+ localData: Record<string, unknown>;
320
+ remoteData: Record<string, unknown>;
321
+ conflictedAt: number;
322
+ };
323
+ type ConflictResolutionStrategy = 'local-wins' | 'remote-wins' | 'merge' | 'manual';
324
+ type ConflictResolution = {
325
+ conflictId: string;
326
+ strategy: ConflictResolutionStrategy;
327
+ resolvedData: Record<string, unknown>;
328
+ resolvedAt: number;
329
+ };
330
+ type TimeRange = {
331
+ start: Date;
332
+ end: Date;
333
+ };
334
+ type Reference = {
335
+ id: string;
336
+ type: string;
337
+ };
338
+ //#endregion
339
+ //#region src/domain/schemas/common.schema.d.ts
340
+ declare const UuidSchema: z.ZodString;
341
+ declare const EntityIdSchema: z.ZodString;
342
+ declare const TimestampSchema: z.ZodNumber;
343
+ declare const VersionSchema: z.ZodNumber;
344
+ declare const ChangeTypeSchema: z.ZodEnum<{
345
+ create: "create";
346
+ update: "update";
347
+ delete: "delete";
348
+ }>;
349
+ declare const ConflictResolutionStrategySchema: z.ZodEnum<{
350
+ "local-wins": "local-wins";
351
+ "remote-wins": "remote-wins";
352
+ merge: "merge";
353
+ manual: "manual";
354
+ }>;
355
+ declare const IdReferenceSchema: z.ZodObject<{
356
+ id: z.ZodString;
357
+ type: z.ZodString;
358
+ }, z.core.$strip>;
359
+ declare const TimeRangeSchema: z.ZodObject<{
360
+ start: z.ZodCoercedDate<unknown>;
361
+ end: z.ZodCoercedDate<unknown>;
362
+ }, z.core.$strip>;
363
+ declare const SyncDataSchema: z.ZodObject<{
364
+ id: z.ZodString;
365
+ type: z.ZodString;
366
+ version: z.ZodNumber;
367
+ data: z.ZodRecord<z.ZodString, z.ZodUnknown>;
368
+ timestamp: z.ZodNumber;
369
+ }, z.core.$strip>;
370
+ declare const EntityChangeSchema: z.ZodObject<{
371
+ entityId: z.ZodString;
372
+ entityType: z.ZodString;
373
+ changeType: z.ZodEnum<{
374
+ create: "create";
375
+ update: "update";
376
+ delete: "delete";
377
+ }>;
378
+ data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
379
+ timestamp: z.ZodNumber;
380
+ version: z.ZodNumber;
381
+ }, z.core.$strip>;
382
+ declare const ConflictDataSchema: z.ZodObject<{
383
+ id: z.ZodString;
384
+ entityType: z.ZodString;
385
+ entityId: z.ZodString;
386
+ localVersion: z.ZodNumber;
387
+ remoteVersion: z.ZodNumber;
388
+ localData: z.ZodRecord<z.ZodString, z.ZodUnknown>;
389
+ remoteData: z.ZodRecord<z.ZodString, z.ZodUnknown>;
390
+ conflictedAt: z.ZodNumber;
391
+ }, z.core.$strip>;
392
+ declare const ConflictResolutionSchema: z.ZodObject<{
393
+ conflictId: z.ZodString;
394
+ strategy: z.ZodEnum<{
395
+ "local-wins": "local-wins";
396
+ "remote-wins": "remote-wins";
397
+ merge: "merge";
398
+ manual: "manual";
399
+ }>;
400
+ resolvedData: z.ZodRecord<z.ZodString, z.ZodUnknown>;
401
+ resolvedAt: z.ZodNumber;
402
+ }, z.core.$strip>;
403
+ type Uuid = z.infer<typeof UuidSchema>;
404
+ type EntityId = z.infer<typeof EntityIdSchema>;
405
+ type Timestamp = z.infer<typeof TimestampSchema>;
406
+ type Version = z.infer<typeof VersionSchema>;
407
+ type ChangeType = z.infer<typeof ChangeTypeSchema>;
408
+ type IdReference = z.infer<typeof IdReferenceSchema>;
409
+ //#endregion
410
+ export { AggregateRootEntity as AggregateRoot, AggregateRootEntity, BusinessRuleError, type ChangeType, ChangeTypeSchema, ConcurrencyError, ConfigurationError, type ConflictData, ConflictDataSchema, type ConflictResolution, ConflictResolutionSchema, type ConflictResolutionStrategy, ConflictResolutionStrategySchema, DomainError, DomainEvent, type DomainEventConstructor, type DomainEventHandler, Entity, type EntityChange, EntityChangeSchema, EntityCreatedEvent, EntityDeletedEvent, type EntityId, EntityIdSchema, EntityIdVO, EntityNotFoundError, EntityUpdatedEvent, type EventConstructor, ExternalServiceError, Failure, type IdReference, IdReferenceSchema, PermissionDeniedError, type QueryOptions, type Reference, type Repository, RepositoryError, type Result, type SortParams, Success, type SyncData, SyncDataSchema, SyncStatus, SyncStatusVO, type TimeRange, TimeRangeSchema, type Timestamp, TimestampSchema, TimestampVO, type TraceContext, type TracingContextManager, UNIT_OF_WORK_TOKEN, type UnitOfWork, type Uuid, UuidSchema, ValidationError, ValueObject, type Version, VersionSchema, VersionVO, combine, failure, isBusinessRuleError, isClientError, isConcurrencyError, isConfigurationError, isEntityNotFoundError, isExternalServiceError, isFailure, isPermissionDeniedError, isRepositoryError, isRetryableError, isSuccess, isValidationError, logError, success, toDomainError, unwrapResult };
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ import{z as e}from"zod";var t=class{_id;_props;_events=[];constructor(e,t){this._id=e,this._props=t}get id(){return this._id}get props(){return this._props}updateProps(e,t){this._props[e]=t}addEvent(e){this._events.push(e)}pullEvents(){let e=[...this._events];return this._events=[],e}hasEvents(){return this._events.length>0}equals(e){return this._id===e._id}},n=class extends t{_version=1;_isDirty=!1;get version(){return this._version}get isDirty(){return this._isDirty}markAsDirty(){this._isDirty=!0,this._version++}},r=class{static TYPE;eventId;occurredAt;traceContext;constructor(e,t){this.eventId=e,this.occurredAt=new Date,this.traceContext=t}toJSON(){return{eventId:this.eventId,type:this.type,occurredAt:this.occurredAt.toISOString(),traceContext:this.traceContext}}},i=class extends r{type=`entity:created`;constructor(e,t,n){super(e),this.entityType=t,this.entityId=n}toJSON(){return{...super.toJSON(),entityType:this.entityType,entityId:this.entityId}}},a=class extends r{type=`entity:updated`;constructor(e,t,n,r){super(e),this.entityType=t,this.entityId=n,this.changes=r}toJSON(){return{...super.toJSON(),entityType:this.entityType,entityId:this.entityId,changes:this.changes}}},o=class extends r{type=`entity:deleted`;constructor(e,t,n){super(e),this.entityType=t,this.entityId=n}toJSON(){return{...super.toJSON(),entityType:this.entityType,entityId:this.entityId}}},s=class extends Error{constructor(e,t=`DOMAIN_ERROR`,n){super(e),this.code=t,this.context=n,this.name=`DomainError`}toJSON(){return{name:this.name,code:this.code,message:this.message,context:this.context,stack:this.stack}}},c=class extends s{constructor(e,t,n){super(e,`VALIDATION_ERROR`,{field:t,value:n}),this.field=t,this.value=n,this.name=`ValidationError`}},l=class extends s{constructor(e,t){super(e,`BUSINESS_RULE_ERROR`,{rule:t}),this.name=`BusinessRuleError`}},u=class extends s{constructor(e,t){super(`${e} 未找到: ${t}`,`ENTITY_NOT_FOUND`,{entityType:e,entityId:t}),this.entityType=e,this.entityId=t,this.name=`EntityNotFoundError`}},d=class extends s{constructor(e,t,n){super(e,`REPOSITORY_ERROR`,n),this.cause=t,this.name=`RepositoryError`}toJSON(){return{...super.toJSON(),cause:this.cause?.message}}},f=class extends s{constructor(e=`并发冲突,请重试`){super(e,`CONCURRENCY_ERROR`),this.name=`ConcurrencyError`}},p=class extends s{constructor(e,t){super(`无权限执行操作: ${t} on ${e}`,`PERMISSION_DENIED`,{resource:e,action:t}),this.resource=e,this.action=t,this.name=`PermissionDeniedError`}},m=class extends s{constructor(e,t){super(e,`CONFIGURATION_ERROR`,{key:t}),this.key=t,this.name=`ConfigurationError`}},h=class extends s{constructor(e,t,n){super(t,`EXTERNAL_SERVICE_ERROR`,{service:e}),this.service=e,this.name=`ExternalServiceError`,n&&(this.cause=n)}};function g(e){return e instanceof s?e:e instanceof Error?new d(e.message,e):new d(String(e))}function _(e,t,n){(n?t.withOperation(n):t).error(e.message,e,{code:e.code,name:e.name,context:e.context})}function v(e){return[`CONCURRENCY_ERROR`,`EXTERNAL_SERVICE_ERROR`].includes(e.code)}function y(e){return[`VALIDATION_ERROR`,`BUSINESS_RULE_ERROR`,`ENTITY_NOT_FOUND`,`PERMISSION_DENIED`].includes(e.code)}function b(e){return e instanceof c}function x(e){return e instanceof l}function S(e){return e instanceof u}function C(e){return e instanceof d}function w(e){return e instanceof f}function T(e){return e instanceof p}function E(e){return e instanceof m}function D(e){return e instanceof h}const O=Symbol(`UnitOfWork`);var k=class{_value;constructor(e){this._value=Object.freeze(e)}get value(){return this._value}valueOf(){return this._value}toString(){return String(this._value)}},A=class e extends k{constructor(e){super(e)}static fromString(t){if(!t||t.trim().length===0)throw Error(`实体 ID 不能为空`);return new e(t)}equals(e){return this._value===e._value}},j=class e extends k{constructor(e){super(e)}static now(){return new e(Date.now())}static fromDate(t){return new e(t.getTime())}static fromMillis(t){return new e(t)}toDate(){return new Date(this._value)}equals(e){return this._value===e._value}},M=class e extends k{constructor(e){super(e)}static initial(){return new e(0)}static fromNumber(t){if(!Number.isInteger(t)||t<0)throw Error(`版本号必须是非负整数`);return new e(t)}increment(){return new e(this._value+1)}equals(e){return this._value===e._value}isInitial(){return this._value===0}};let N=function(e){return e.LOCAL=`local`,e.PENDING=`pending`,e.SYNCED=`synced`,e.CONFLICT=`conflict`,e}({});var P=class e extends k{constructor(e){super(e)}static local(){return new e(N.LOCAL)}static pending(){return new e(N.PENDING)}static synced(){return new e(N.SYNCED)}static conflict(){return new e(N.CONFLICT)}static fromString(t){switch(t){case`local`:return e.local();case`pending`:return e.pending();case`synced`:return e.synced();case`conflict`:return e.conflict();default:throw Error(`未知的同步状态: ${t}`)}}needsSync(){return this._value===N.LOCAL||this._value===N.PENDING}equals(e){return this._value===e._value}},F=class{isSuccess=!0;isFailure=!1;constructor(e){this.value=e}map(e){return L(e(this.value))}flatMap(e){return e(this.value)}mapError(e){return L(this.value)}getOrElse(e){return this.value}match(e){return e.success(this.value)}},I=class{isSuccess=!1;isFailure=!0;constructor(e){this.error=e}map(e){return R(this.error)}flatMap(e){return R(this.error)}mapError(e){return R(e(this.error))}getOrElse(e){return e}match(e){return e.failure(this.error)}};function L(e){return new F(e)}function R(e){return new I(e)}function z(e){let t=[];for(let n of e){if(n.isFailure)return R(n.error);t.push(n.value)}return L(t)}function B(e){return e.isSuccess}function V(e){return e.isFailure}function H(e){if(e.isFailure)throw g(e.error);return e.value}const U=e.string().uuid(`无效的UUID格式`),W=U,G=e.number().int().positive(),K=e.number().int().nonnegative(),q=e.enum([`create`,`update`,`delete`]),J=e.enum([`local-wins`,`remote-wins`,`merge`,`manual`]),Y=e.object({id:e.string(),type:e.string()}),X=e.object({start:e.coerce.date(),end:e.coerce.date()}),Z=e.object({id:e.string(),type:e.string(),version:K,data:e.record(e.string(),e.unknown()),timestamp:G}),Q=e.object({entityId:e.string(),entityType:e.string(),changeType:q,data:e.record(e.string(),e.unknown()).optional(),timestamp:G,version:K}),$=e.object({id:e.string(),entityType:e.string(),entityId:e.string(),localVersion:K,remoteVersion:K,localData:e.record(e.string(),e.unknown()),remoteData:e.record(e.string(),e.unknown()),conflictedAt:G}),ee=e.object({conflictId:e.string(),strategy:J,resolvedData:e.record(e.string(),e.unknown()),resolvedAt:G});export{n as AggregateRoot,n as AggregateRootEntity,l as BusinessRuleError,q as ChangeTypeSchema,f as ConcurrencyError,m as ConfigurationError,$ as ConflictDataSchema,ee as ConflictResolutionSchema,J as ConflictResolutionStrategySchema,s as DomainError,r as DomainEvent,t as Entity,Q as EntityChangeSchema,i as EntityCreatedEvent,o as EntityDeletedEvent,W as EntityIdSchema,A as EntityIdVO,u as EntityNotFoundError,a as EntityUpdatedEvent,h as ExternalServiceError,I as Failure,Y as IdReferenceSchema,p as PermissionDeniedError,d as RepositoryError,F as Success,Z as SyncDataSchema,N as SyncStatus,P as SyncStatusVO,X as TimeRangeSchema,G as TimestampSchema,j as TimestampVO,O as UNIT_OF_WORK_TOKEN,U as UuidSchema,c as ValidationError,k as ValueObject,K as VersionSchema,M as VersionVO,z as combine,R as failure,x as isBusinessRuleError,y as isClientError,w as isConcurrencyError,E as isConfigurationError,S as isEntityNotFoundError,D as isExternalServiceError,V as isFailure,T as isPermissionDeniedError,C as isRepositoryError,v as isRetryableError,B as isSuccess,b as isValidationError,_ as logError,L as success,g as toDomainError,H as unwrapResult};
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@longzai-intelligence/shared-kernel",
3
+ "version": "0.0.1",
4
+ "type": "module",
5
+ "types": "./dist/index.d.mts",
6
+ "main": "./dist/index.cjs",
7
+ "exports": {
8
+ ".": {
9
+ "types": {
10
+ "import": "./dist/index.d.mts",
11
+ "require": "./dist/index.d.cts"
12
+ },
13
+ "import": "./dist/index.mjs",
14
+ "require": "./dist/index.cjs"
15
+ }
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "scripts": {
21
+ "build": "tsdown",
22
+ "build:prod": "NODE_ENV=production tsdown",
23
+ "prepublishOnly": "bun run build:prod",
24
+ "dev": "tsdown --watch",
25
+ "clean": "rimraf dist tsconfig/.cache",
26
+ "test": "vitest run",
27
+ "test:watch": "vitest",
28
+ "test:coverage": "vitest run --coverage",
29
+ "lint": "eslint .",
30
+ "lint:fix": "eslint . --fix",
31
+ "typecheck": "bun run typecheck:app && bun run typecheck:node && bun run typecheck:test",
32
+ "typecheck:app": "tsc --noEmit -p tsconfig/app.json",
33
+ "typecheck:node": "tsc --noEmit -p tsconfig/node.json",
34
+ "typecheck:test": "tsc --noEmit -p tsconfig/test.json"
35
+ },
36
+ "dependencies": {
37
+ "reflect-metadata": "^0.2.2",
38
+ "zod": "^4.3.6"
39
+ },
40
+ "devDependencies": {
41
+ "@longzai-intelligence/logger-core": "0.0.2",
42
+ "@types/node": "^25.5.2",
43
+ "bun-types": "^1.3.11",
44
+ "eslint": "^10.2.0",
45
+ "rimraf": "^6.1.3",
46
+ "typescript": "^6.0.2",
47
+ "vitest": "^4.1.3",
48
+ "@longzai-intelligence/eslint-preset-library": "0.0.3",
49
+ "@longzai-intelligence/vitest-config": "0.0.3",
50
+ "@longzai-intelligence/typescript-config": "0.0.2",
51
+ "tsdown": "^0.21.7",
52
+ "@longzai-intelligence/tsdown-config": "0.0.1"
53
+ },
54
+ "packageManager": "bun@1.3.11",
55
+ "license": "UNLICENSED",
56
+ "module": "./dist/index.mjs"
57
+ }