@svadmin/core 0.71.0 → 0.72.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@svadmin/core",
3
- "version": "0.71.0",
3
+ "version": "0.72.0",
4
4
  "author": "zuohuadong",
5
5
  "repository": {
6
6
  "type": "git",
@@ -150,6 +150,18 @@
150
150
  "./contracts": {
151
151
  "types": "./src/contracts.ts",
152
152
  "default": "./src/contracts.ts"
153
+ },
154
+ "./result": {
155
+ "types": "./src/result.ts",
156
+ "default": "./src/result.ts"
157
+ },
158
+ "./domain-errors": {
159
+ "types": "./src/domain-errors.ts",
160
+ "default": "./src/domain-errors.ts"
161
+ },
162
+ "./resilience": {
163
+ "types": "./src/resilience.ts",
164
+ "default": "./src/resilience.ts"
153
165
  }
154
166
  },
155
167
  "bugs": {
@@ -18,6 +18,8 @@ import { auditWithProvider } from './audit';
18
18
  import { HttpError } from './types';
19
19
  import { useTranslation } from './i18n.svelte';
20
20
  import { toast } from './toast.svelte';
21
+ import { ok, err, type Result as SafeResult } from './result';
22
+ import { toDomainError, type DomainError } from './domain-errors';
21
23
 
22
24
  export interface ContractCreateOptions<S extends ContractSchemas> {
23
25
  resource: ResourceContract<S>;
@@ -331,13 +333,21 @@ export function useContractCreate<S extends ContractSchemas>(options: ContractCr
331
333
  mutate(params: ContractCreateParams<S>, callbacks?: Callbacks<S>): void {
332
334
  void mutateAsync(params, callbacks).catch(() => {});
333
335
  },
336
+ async safeMutate(params: ContractCreateParams<S>, callbacks?: Callbacks<S>): Promise<SafeResult<ContractRecord<S>, DomainError>> {
337
+ try {
338
+ const res = await mutateAsync(params, callbacks);
339
+ return ok(res.data);
340
+ } catch (cause) {
341
+ return err(toDomainError(cause));
342
+ }
343
+ },
334
344
  reset() { active = undefined; latest = undefined; latestToken = undefined; mutation.reset(); },
335
345
  });
336
346
  const idle: typeof result = {
337
347
  context: undefined, data: undefined, error: null, failureCount: 0, failureReason: null,
338
348
  isError: false, isIdle: true, isPending: false, isPaused: false, isSuccess: false,
339
349
  status: 'idle', submittedAt: 0, variables: undefined,
340
- mutate: result.mutate, mutateAsync: result.mutateAsync, reset: result.reset,
350
+ mutate: result.mutate, mutateAsync: result.mutateAsync, safeMutate: result.safeMutate, reset: result.reset,
341
351
  };
342
352
  const view = createQueryResultView(() => {
343
353
  const invocation = mutation.variables;
@@ -15,6 +15,8 @@ import { getAdminOptions } from './options.svelte';
15
15
  import { captureAuthLiveScope, clearAuthQueries, handleAuthError } from './auth-hooks.svelte';
16
16
  import { auditWithProvider } from './audit';
17
17
  import { HttpError } from './types';
18
+ import { ok, err, type Result as SafeResult } from './result';
19
+ import { toDomainError, type DomainError } from './domain-errors';
18
20
  import { useTranslation } from './i18n.svelte';
19
21
  import { toast } from './toast.svelte';
20
22
 
@@ -377,13 +379,21 @@ export function useContractCreateMany<S extends ContractSchemas>(options: Contra
377
379
  mutate(params: ContractCreateManyParams<S>, callbacks?: Callbacks<S>): void {
378
380
  void mutateAsync(params, callbacks).catch(() => {});
379
381
  },
382
+ async safeMutate(params: ContractCreateManyParams<S>, callbacks?: Callbacks<S>): Promise<SafeResult<ContractRecord<S>[], DomainError>> {
383
+ try {
384
+ const res = await mutateAsync(params, callbacks);
385
+ return ok(res.data);
386
+ } catch (cause) {
387
+ return err(toDomainError(cause));
388
+ }
389
+ },
380
390
  reset() { active = undefined; latest = undefined; latestToken = undefined; mutation.reset(); },
381
391
  });
382
392
  const idle: typeof result = {
383
393
  context: undefined, data: undefined, error: null, failureCount: 0, failureReason: null,
384
394
  isError: false, isIdle: true, isPending: false, isPaused: false, isSuccess: false,
385
395
  status: 'idle', submittedAt: 0, variables: undefined,
386
- mutate: result.mutate, mutateAsync: result.mutateAsync, reset: result.reset,
396
+ mutate: result.mutate, mutateAsync: result.mutateAsync, safeMutate: result.safeMutate, reset: result.reset,
387
397
  };
388
398
  const view = createQueryResultView(() => {
389
399
  const invocation = mutation.variables;
@@ -17,6 +17,8 @@ import { auditWithProvider } from './audit';
17
17
  import { HttpError, UndoError } from './types';
18
18
  import { useTranslation } from './i18n.svelte';
19
19
  import { toast, getToasts, removeToast } from './toast.svelte';
20
+ import { ok, err, type Result as SafeResult } from './result';
21
+ import { toDomainError, type DomainError } from './domain-errors';
20
22
 
21
23
  export type { ContractDeleteParams } from './delete-contract';
22
24
  export interface ContractDeleteOptions<S extends ContractSchemas> {
@@ -384,13 +386,21 @@ export function useContractDelete<S extends ContractSchemas>(options: ContractDe
384
386
  mutate(params: ContractDeleteParams<S>, callbacks?: Callbacks<S>): void {
385
387
  void mutateAsync(params, callbacks).catch(() => {});
386
388
  },
389
+ async safeMutate(params: ContractDeleteParams<S>, callbacks?: Callbacks<S>): Promise<SafeResult<ContractRecord<S>, DomainError>> {
390
+ try {
391
+ const res = await mutateAsync(params, callbacks);
392
+ return ok(res.data);
393
+ } catch (cause) {
394
+ return err(toDomainError(cause));
395
+ }
396
+ },
387
397
  reset() { latestToken = undefined; clearActive(); mutation.reset(); },
388
398
  });
389
399
  const idle: typeof result = {
390
400
  context: undefined, data: undefined, error: null, failureCount: 0, failureReason: null,
391
401
  isError: false, isIdle: true, isPending: false, isPaused: false, isSuccess: false,
392
402
  status: 'idle', submittedAt: 0, variables: undefined,
393
- mutate: result.mutate, mutateAsync: result.mutateAsync, reset: result.reset,
403
+ mutate: result.mutate, mutateAsync: result.mutateAsync, safeMutate: result.safeMutate, reset: result.reset,
394
404
  };
395
405
  const view = createQueryResultView(() => {
396
406
  const invocation = mutation.variables;
@@ -15,6 +15,8 @@ import { getAdminOptions } from './options.svelte';
15
15
  import { captureAuthLiveScope, clearAuthQueries, handleAuthError } from './auth-hooks.svelte';
16
16
  import { auditWithProvider } from './audit';
17
17
  import { DeleteManyPartialError, HttpError } from './types';
18
+ import { ok, err, type Result as SafeResult } from './result';
19
+ import { toDomainError, type DomainError } from './domain-errors';
18
20
  import { useTranslation } from './i18n.svelte';
19
21
  import { toast } from './toast.svelte';
20
22
 
@@ -386,13 +388,21 @@ export function useContractDeleteMany<S extends ContractSchemas>(options: Contra
386
388
  mutate(params: ContractDeleteManyParams<S>, callbacks?: Callbacks<S>): void {
387
389
  void mutateAsync(params, callbacks).catch(() => {});
388
390
  },
391
+ async safeMutate(params: ContractDeleteManyParams<S>, callbacks?: Callbacks<S>): Promise<SafeResult<ContractRecord<S>[], DomainError>> {
392
+ try {
393
+ const res = await mutateAsync(params, callbacks);
394
+ return ok(res.data);
395
+ } catch (cause) {
396
+ return err(toDomainError(cause));
397
+ }
398
+ },
389
399
  reset() { active = undefined; latest = undefined; latestToken = undefined; mutation.reset(); },
390
400
  });
391
401
  const idle: typeof result = {
392
402
  context: undefined, data: undefined, error: null, failureCount: 0, failureReason: null,
393
403
  isError: false, isIdle: true, isPending: false, isPaused: false, isSuccess: false,
394
404
  status: 'idle', submittedAt: 0, variables: undefined,
395
- mutate: result.mutate, mutateAsync: result.mutateAsync, reset: result.reset,
405
+ mutate: result.mutate, mutateAsync: result.mutateAsync, safeMutate: result.safeMutate, reset: result.reset,
396
406
  };
397
407
  const view = createQueryResultView(() => {
398
408
  const invocation = mutation.variables;
@@ -0,0 +1,418 @@
1
+ import { HttpError, UndoError, type ValidationErrors, type HttpErrorOptions } from './types';
2
+ import { definedOptions } from './defined-options';
3
+
4
+ export class ValidationError extends HttpError {
5
+ readonly _tag = 'ValidationError' as const;
6
+ readonly fieldErrors: ValidationErrors;
7
+
8
+ constructor(
9
+ message: string = 'Validation failed',
10
+ fieldErrors: ValidationErrors = {},
11
+ options: HttpErrorOptions = {},
12
+ ) {
13
+ super(message, 422, fieldErrors, definedOptions({
14
+ code: options.code ?? 'VALIDATION_FAILED',
15
+ details: options.details,
16
+ body: options.body,
17
+ cause: options.cause,
18
+ }));
19
+ this.name = 'ValidationError';
20
+ this.fieldErrors = fieldErrors;
21
+ }
22
+ }
23
+
24
+ export interface ConflictErrorOptions extends HttpErrorOptions {
25
+ resource?: string | undefined;
26
+ recordId?: string | number | undefined;
27
+ currentVersion?: string | number | undefined;
28
+ expectedVersion?: string | number | undefined;
29
+ }
30
+
31
+ export class ConflictError extends HttpError {
32
+ readonly _tag = 'ConflictError' as const;
33
+ readonly resource?: string | undefined;
34
+ readonly recordId?: string | number | undefined;
35
+ readonly currentVersion?: string | number | undefined;
36
+ readonly expectedVersion?: string | number | undefined;
37
+
38
+ constructor(
39
+ message: string = 'Resource conflict detected',
40
+ options: ConflictErrorOptions = {},
41
+ ) {
42
+ super(message, 409, undefined, definedOptions({
43
+ code: options.code ?? 'RESOURCE_CONFLICT',
44
+ details: options.details,
45
+ body: options.body,
46
+ cause: options.cause,
47
+ }));
48
+ this.name = 'ConflictError';
49
+ this.resource = options.resource;
50
+ this.recordId = options.recordId;
51
+ this.currentVersion = options.currentVersion;
52
+ this.expectedVersion = options.expectedVersion;
53
+ }
54
+ }
55
+
56
+ export interface AuthErrorOptions extends HttpErrorOptions {
57
+ resource?: string | undefined;
58
+ action?: string | undefined;
59
+ }
60
+
61
+ export class AuthError extends HttpError {
62
+ readonly _tag = 'AuthError' as const;
63
+ readonly kind: 'unauthorized' | 'forbidden';
64
+ readonly resource?: string | undefined;
65
+ readonly action?: string | undefined;
66
+
67
+ constructor(
68
+ kind: 'unauthorized' | 'forbidden',
69
+ message?: string,
70
+ options: AuthErrorOptions = {},
71
+ ) {
72
+ const statusCode = kind === 'unauthorized' ? 401 : 403;
73
+ const defaultMsg = kind === 'unauthorized' ? 'Authentication required' : 'Permission denied';
74
+ super(message ?? defaultMsg, statusCode, undefined, definedOptions({
75
+ code: options.code ?? (kind === 'unauthorized' ? 'UNAUTHORIZED' : 'FORBIDDEN'),
76
+ details: options.details,
77
+ body: options.body,
78
+ cause: options.cause,
79
+ }));
80
+ this.name = 'AuthError';
81
+ this.kind = kind;
82
+ this.resource = options.resource;
83
+ this.action = options.action;
84
+ }
85
+ }
86
+
87
+ export interface NetworkErrorOptions extends HttpErrorOptions {
88
+ isTimeout?: boolean | undefined;
89
+ isOffline?: boolean | undefined;
90
+ statusCode?: number | undefined;
91
+ }
92
+
93
+ export class NetworkError extends HttpError {
94
+ readonly _tag = 'NetworkError' as const;
95
+ readonly isTimeout: boolean;
96
+ readonly isOffline: boolean;
97
+ readonly retryable = true as const;
98
+
99
+ constructor(
100
+ message: string = 'Network communication failure',
101
+ options: NetworkErrorOptions = {},
102
+ ) {
103
+ const isTimeout = options.isTimeout ?? false;
104
+ super(message, options.statusCode ?? (isTimeout ? 504 : 0), undefined, definedOptions({
105
+ code: options.code ?? (isTimeout ? 'NETWORK_TIMEOUT' : 'NETWORK_ERROR'),
106
+ details: options.details,
107
+ body: options.body,
108
+ cause: options.cause,
109
+ }));
110
+ this.name = 'NetworkError';
111
+ this.isTimeout = isTimeout;
112
+ this.isOffline = options.isOffline ?? false;
113
+ }
114
+ }
115
+
116
+ export interface ContractDecodingErrorOptions extends HttpErrorOptions {
117
+ resource?: string | undefined;
118
+ issues?: readonly unknown[] | undefined;
119
+ }
120
+
121
+ export class ContractDecodingError extends HttpError {
122
+ readonly _tag = 'ContractDecodingError' as const;
123
+ readonly resource?: string | undefined;
124
+ readonly issues?: readonly unknown[] | undefined;
125
+
126
+ constructor(
127
+ message: string = 'Contract decoding mismatch',
128
+ options: ContractDecodingErrorOptions = {},
129
+ ) {
130
+ super(message, 502, undefined, definedOptions({
131
+ code: options.code ?? 'CONTRACT_DECODING_ERROR',
132
+ details: options.details ?? options.issues,
133
+ body: options.body,
134
+ cause: options.cause,
135
+ }));
136
+ this.name = 'ContractDecodingError';
137
+ this.resource = options.resource;
138
+ this.issues = options.issues;
139
+ }
140
+ }
141
+
142
+ export interface NotFoundErrorOptions extends HttpErrorOptions {
143
+ resource?: string | undefined;
144
+ id?: string | number | undefined;
145
+ }
146
+
147
+ export class NotFoundError extends HttpError {
148
+ readonly _tag = 'NotFoundError' as const;
149
+ readonly resource?: string | undefined;
150
+ readonly id?: string | number | undefined;
151
+
152
+ constructor(
153
+ message: string = 'Resource not found',
154
+ options: NotFoundErrorOptions = {},
155
+ ) {
156
+ super(message, 404, undefined, definedOptions({
157
+ code: options.code ?? 'RESOURCE_NOT_FOUND',
158
+ details: options.details,
159
+ body: options.body,
160
+ cause: options.cause,
161
+ }));
162
+ this.name = 'NotFoundError';
163
+ this.resource = options.resource;
164
+ this.id = options.id;
165
+ }
166
+ }
167
+
168
+ export interface ServerInternalErrorOptions extends HttpErrorOptions {
169
+ traceId?: string | undefined;
170
+ }
171
+
172
+ export class ServerInternalError extends HttpError {
173
+ readonly _tag = 'ServerInternalError' as const;
174
+ readonly traceId?: string | undefined;
175
+
176
+ constructor(
177
+ message: string = 'Internal server failure',
178
+ statusCode: number = 500,
179
+ options: ServerInternalErrorOptions = {},
180
+ ) {
181
+ super(message, statusCode, undefined, definedOptions({
182
+ code: options.code ?? 'INTERNAL_SERVER_ERROR',
183
+ details: options.details,
184
+ body: options.body,
185
+ cause: options.cause,
186
+ }));
187
+ this.name = 'ServerInternalError';
188
+ this.traceId = options.traceId;
189
+ }
190
+ }
191
+
192
+ export class BadRequestError extends HttpError {
193
+ readonly _tag = 'BadRequestError' as const;
194
+ readonly fieldErrors: ValidationErrors;
195
+
196
+ constructor(
197
+ message: string = 'Bad request',
198
+ fieldErrors: ValidationErrors = {},
199
+ options: HttpErrorOptions = {},
200
+ ) {
201
+ super(message, 400, fieldErrors, definedOptions({
202
+ code: options.code ?? 'BAD_REQUEST',
203
+ details: options.details,
204
+ body: options.body,
205
+ cause: options.cause,
206
+ }));
207
+ this.name = 'BadRequestError';
208
+ this.fieldErrors = fieldErrors;
209
+ }
210
+ }
211
+
212
+ export class RateLimitError extends HttpError {
213
+ readonly _tag = 'RateLimitError' as const;
214
+ readonly retryable = true as const;
215
+
216
+ constructor(
217
+ message: string = 'Rate limit exceeded',
218
+ options: HttpErrorOptions = {},
219
+ ) {
220
+ super(message, 429, undefined, definedOptions({
221
+ code: options.code ?? 'RATE_LIMITED',
222
+ details: options.details,
223
+ body: options.body,
224
+ cause: options.cause,
225
+ }));
226
+ this.name = 'RateLimitError';
227
+ }
228
+ }
229
+
230
+ export class UnavailableError extends HttpError {
231
+ readonly _tag = 'UnavailableError' as const;
232
+ readonly retryable = true as const;
233
+
234
+ constructor(
235
+ message: string = 'Service unavailable',
236
+ statusCode: number = 503,
237
+ options: HttpErrorOptions = {},
238
+ ) {
239
+ super(message, statusCode, undefined, definedOptions({
240
+ code: options.code ?? 'SERVICE_UNAVAILABLE',
241
+ details: options.details,
242
+ body: options.body,
243
+ cause: options.cause,
244
+ }));
245
+ this.name = 'UnavailableError';
246
+ }
247
+ }
248
+
249
+ export class CancelledError extends HttpError {
250
+ readonly _tag = 'CancelledError' as const;
251
+ readonly writeMayHaveSucceeded: boolean;
252
+
253
+ constructor(
254
+ message: string = 'Operation cancelled',
255
+ statusCode: number = 409,
256
+ options: HttpErrorOptions = {},
257
+ ) {
258
+ super(message, statusCode, undefined, definedOptions({
259
+ code: options.code ?? 'OPERATION_CANCELLED',
260
+ details: options.details,
261
+ body: options.body,
262
+ cause: options.cause,
263
+ }));
264
+ this.name = 'CancelledError';
265
+ this.writeMayHaveSucceeded = writeMayHaveSucceeded(options.details);
266
+ }
267
+ }
268
+
269
+ export class AbortedError extends HttpError {
270
+ readonly _tag = 'AbortedError' as const;
271
+ readonly retryable = false as const;
272
+
273
+ constructor(
274
+ message: string = 'Operation aborted',
275
+ options: HttpErrorOptions = {},
276
+ ) {
277
+ super(message, 0, undefined, definedOptions({
278
+ code: options.code ?? 'ABORTED',
279
+ details: options.details,
280
+ body: options.body,
281
+ cause: options.cause,
282
+ }));
283
+ this.name = 'AbortedError';
284
+ }
285
+ }
286
+
287
+ /** 用户撤销不是服务器失败,不能伪装成 500。 */
288
+ export class UndoneError extends Error {
289
+ readonly _tag = 'UndoneError' as const;
290
+
291
+ constructor(
292
+ message: string = 'Mutation undone',
293
+ options: { cause?: unknown } = {},
294
+ ) {
295
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
296
+ this.name = 'UndoneError';
297
+ }
298
+ }
299
+
300
+ export type DomainError =
301
+ | ValidationError
302
+ | ConflictError
303
+ | AuthError
304
+ | NetworkError
305
+ | ContractDecodingError
306
+ | NotFoundError
307
+ | ServerInternalError
308
+ | BadRequestError
309
+ | RateLimitError
310
+ | UnavailableError
311
+ | CancelledError
312
+ | AbortedError
313
+ | UndoneError;
314
+
315
+ export type DomainErrorTag = DomainError['_tag'];
316
+
317
+ type ErrorHandlers<E extends { readonly _tag: string }, R> = {
318
+ [K in E['_tag']]: (error: Extract<E, { readonly _tag: K }>) => R;
319
+ };
320
+
321
+ /** 要么覆盖全部分支,要么提供 `_` 兜底。缺分支在编译期失败。 */
322
+ export type ErrorPattern<E extends { readonly _tag: string }, R> =
323
+ | ErrorHandlers<E, R>
324
+ | (Partial<ErrorHandlers<E, R>> & { _: (error: E) => R });
325
+
326
+ export function matchError<E extends { readonly _tag: string }, R>(
327
+ error: E,
328
+ patterns: ErrorPattern<E, R>,
329
+ ): R {
330
+ const tag = error._tag as E['_tag'];
331
+ const handler = (patterns as Partial<ErrorHandlers<E, R>>)[tag];
332
+ if (typeof handler === 'function') {
333
+ return handler(error as never);
334
+ }
335
+ if ('_' in patterns && typeof patterns._ === 'function') {
336
+ return patterns._(error);
337
+ }
338
+ throw new Error(`Unhandled domain error tag: ${tag}`);
339
+ }
340
+
341
+ function writeMayHaveSucceeded(details: unknown): boolean {
342
+ return typeof details === 'object'
343
+ && details !== null
344
+ && 'writeMayHaveSucceeded' in details
345
+ && details.writeMayHaveSucceeded === true;
346
+ }
347
+
348
+ function carried(cause: HttpError): HttpErrorOptions {
349
+ return definedOptions({
350
+ code: cause.code,
351
+ details: cause.details,
352
+ body: cause.body,
353
+ cause,
354
+ });
355
+ }
356
+
357
+ function isDomainError(cause: unknown): cause is DomainError {
358
+ return cause instanceof ValidationError
359
+ || cause instanceof ConflictError
360
+ || cause instanceof AuthError
361
+ || cause instanceof NetworkError
362
+ || cause instanceof ContractDecodingError
363
+ || cause instanceof NotFoundError
364
+ || cause instanceof ServerInternalError
365
+ || cause instanceof BadRequestError
366
+ || cause instanceof RateLimitError
367
+ || cause instanceof UnavailableError
368
+ || cause instanceof CancelledError
369
+ || cause instanceof AbortedError
370
+ || cause instanceof UndoneError;
371
+ }
372
+
373
+ /**
374
+ * 保留 HttpError 的 code、details、body。
375
+ * 取消和撤销不能改写成冲突或 500,否则 safeMutate 会丢掉 writeMayHaveSucceeded。
376
+ */
377
+ export function toDomainError(cause: unknown): DomainError {
378
+ if (isDomainError(cause)) return cause;
379
+
380
+ if (cause instanceof UndoError) {
381
+ return new UndoneError(cause.message, { cause });
382
+ }
383
+
384
+ if (cause instanceof HttpError) {
385
+ const options = carried(cause);
386
+ if (typeof cause.code === 'string' && cause.code.endsWith('_CANCELLED')) {
387
+ return new CancelledError(cause.message, cause.statusCode, options);
388
+ }
389
+ const status = cause.statusCode;
390
+ if (status === 422) return new ValidationError(cause.message, cause.errors ?? {}, options);
391
+ if (status === 409) return new ConflictError(cause.message, options);
392
+ if (status === 401) return new AuthError('unauthorized', cause.message, options);
393
+ if (status === 403) return new AuthError('forbidden', cause.message, options);
394
+ if (status === 404) return new NotFoundError(cause.message, options);
395
+ if (status === 400) return new BadRequestError(cause.message, cause.errors ?? {}, options);
396
+ if (status === 408 || status === 504 || status === 0) {
397
+ return new NetworkError(cause.message, definedOptions({
398
+ isTimeout: status === 408 || status === 504,
399
+ statusCode: status,
400
+ code: cause.code,
401
+ details: cause.details,
402
+ body: cause.body,
403
+ cause,
404
+ }));
405
+ }
406
+ if (status === 429) return new RateLimitError(cause.message, options);
407
+ if (status === 503) return new UnavailableError(cause.message, status, options);
408
+ return new ServerInternalError(cause.message, status, options);
409
+ }
410
+
411
+ if (cause instanceof Error) {
412
+ if (cause.name === 'AbortError') return new AbortedError(cause.message, { cause });
413
+ if (cause.name === 'TimeoutError') return new NetworkError(cause.message, { isTimeout: true, cause });
414
+ return new ServerInternalError(cause.message, 500, { cause });
415
+ }
416
+
417
+ return new ServerInternalError(typeof cause === 'string' ? cause : 'Unknown system error', 500, { cause });
418
+ }
package/src/index.ts CHANGED
@@ -423,3 +423,52 @@ export { formatProductPreview, runProductPipeline } from './product-pipeline';
423
423
  export type { ProductPipelineInput, ProductPipelineOutput } from './product-pipeline';
424
424
  export { reviewProductPlan } from './product-review';
425
425
  export type { ProductReviewIssue, ProductReviewMetrics, ProductReviewReport, ProductReviewSeverity } from './product-review';
426
+
427
+ // High-Rigor Typed Result, Domain Errors & Resilience
428
+ export {
429
+ ok, err, isOk, isErr, unwrapResult, unwrapOr,
430
+ mapResult, mapErr, flatMapResult, matchResult,
431
+ fromThrowable, fromPromise,
432
+ } from './result';
433
+ export type { Result, Ok, Err } from './result';
434
+
435
+ export {
436
+ ValidationError,
437
+ ConflictError,
438
+ AuthError,
439
+ NetworkError,
440
+ ContractDecodingError,
441
+ NotFoundError,
442
+ ServerInternalError,
443
+ BadRequestError,
444
+ RateLimitError,
445
+ UnavailableError,
446
+ CancelledError,
447
+ AbortedError,
448
+ UndoneError,
449
+ matchError,
450
+ toDomainError,
451
+ } from './domain-errors';
452
+ export type {
453
+ DomainError,
454
+ DomainErrorTag,
455
+ ErrorPattern,
456
+ ConflictErrorOptions,
457
+ AuthErrorOptions,
458
+ NetworkErrorOptions,
459
+ ContractDecodingErrorOptions,
460
+ NotFoundErrorOptions,
461
+ ServerInternalErrorOptions,
462
+ } from './domain-errors';
463
+
464
+ export {
465
+ ConcurrencyLimitClearedError,
466
+ createConcurrencyLimiter,
467
+ withRetry,
468
+ wrapDataProviderWithResult,
469
+ } from './resilience';
470
+ export type {
471
+ ConcurrencyLimiter,
472
+ RetryOptions,
473
+ SafeDataProvider,
474
+ } from './resilience';
@@ -0,0 +1,185 @@
1
+ import { err, fromPromise, type Result } from './result';
2
+ import { toDomainError, type DomainError } from './domain-errors';
3
+ import type {
4
+ DataProvider,
5
+ GetListParams,
6
+ GetListResult,
7
+ GetOneParams,
8
+ GetOneResult,
9
+ CreateParams,
10
+ CreateResult,
11
+ UpdateParams,
12
+ UpdateResult,
13
+ DeleteParams,
14
+ DeleteResult,
15
+ GetManyParams,
16
+ GetManyResult,
17
+ CreateManyParams,
18
+ CreateManyResult,
19
+ UpdateManyParams,
20
+ UpdateManyResult,
21
+ DeleteManyParams,
22
+ DeleteManyResult,
23
+ CustomParams,
24
+ CustomResult,
25
+ } from './types';
26
+
27
+ export class ConcurrencyLimitClearedError extends Error {
28
+ constructor() {
29
+ super('Concurrency limiter cleared');
30
+ this.name = 'ConcurrencyLimitClearedError';
31
+ }
32
+ }
33
+
34
+ export interface ConcurrencyLimiter {
35
+ <T>(fn: () => Promise<T>): Promise<T>;
36
+ readonly activeCount: number;
37
+ readonly pendingCount: number;
38
+ clear(): void;
39
+ }
40
+
41
+ interface LimitWaiter {
42
+ resolve: () => void;
43
+ reject: (error: unknown) => void;
44
+ }
45
+
46
+ /**
47
+ * Creates a lightweight concurrency limiter (zero external dependencies).
48
+ * Perfect for batch imports, multi-record deletions, and asset uploads.
49
+ */
50
+ export function createConcurrencyLimiter(concurrency: number): ConcurrencyLimiter {
51
+ if (concurrency < 1) {
52
+ throw new RangeError('Concurrency limit must be at least 1');
53
+ }
54
+
55
+ let active = 0;
56
+ const queue: LimitWaiter[] = [];
57
+
58
+ const next = () => {
59
+ if (active < concurrency && queue.length > 0) {
60
+ const run = queue.shift();
61
+ if (run) {
62
+ active++;
63
+ run.resolve();
64
+ }
65
+ }
66
+ };
67
+
68
+ const limiter = async <T>(fn: () => Promise<T>): Promise<T> => {
69
+ await new Promise<void>((resolve, reject) => {
70
+ queue.push({ resolve, reject });
71
+ next();
72
+ });
73
+
74
+ try {
75
+ return await fn();
76
+ } finally {
77
+ active--;
78
+ next();
79
+ }
80
+ };
81
+
82
+ Object.defineProperties(limiter, {
83
+ activeCount: { get: () => active },
84
+ pendingCount: { get: () => queue.length },
85
+ });
86
+
87
+ limiter.clear = () => {
88
+ const dropped = queue.splice(0);
89
+ for (const waiter of dropped) waiter.reject(new ConcurrencyLimitClearedError());
90
+ };
91
+
92
+ return limiter as ConcurrencyLimiter;
93
+ }
94
+
95
+ export interface RetryOptions {
96
+ readonly retries?: number;
97
+ readonly minTimeout?: number;
98
+ readonly maxTimeout?: number;
99
+ readonly factor?: number;
100
+ readonly jitter?: boolean;
101
+ readonly shouldRetry?: (error: unknown, attempt: number) => boolean;
102
+ }
103
+
104
+ /**
105
+ * Executes an async task with exponential backoff and jitter.
106
+ */
107
+ export async function withRetry<T>(
108
+ task: (attempt: number) => Promise<T>,
109
+ options: RetryOptions = {},
110
+ ): Promise<T> {
111
+ const retries = options.retries ?? 3;
112
+ const minTimeout = options.minTimeout ?? 200;
113
+ const maxTimeout = options.maxTimeout ?? 3000;
114
+ const factor = options.factor ?? 2;
115
+ const jitter = options.jitter ?? true;
116
+ const shouldRetry = options.shouldRetry ?? (() => true);
117
+
118
+ let attempt = 0;
119
+ while (true) {
120
+ attempt++;
121
+ try {
122
+ return await task(attempt);
123
+ } catch (cause) {
124
+ if (attempt > retries || !shouldRetry(cause, attempt)) {
125
+ throw cause;
126
+ }
127
+ const baseDelay = Math.min(minTimeout * Math.pow(factor, attempt - 1), maxTimeout);
128
+ const delay = jitter ? baseDelay * (0.5 + Math.random() * 0.5) : baseDelay;
129
+ await new Promise((resolve) => setTimeout(resolve, delay));
130
+ }
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Safe DataProvider contract that returns `Promise<Result<T, DomainError>>`
136
+ * for imperative workflows, scripts, and high-rigor pipelines.
137
+ */
138
+ export interface SafeDataProvider {
139
+ readonly raw: DataProvider;
140
+ getList: (params: GetListParams) => Promise<Result<GetListResult, DomainError>>;
141
+ getOne: (params: GetOneParams) => Promise<Result<GetOneResult, DomainError>>;
142
+ create: (params: CreateParams) => Promise<Result<CreateResult, DomainError>>;
143
+ update: (params: UpdateParams) => Promise<Result<UpdateResult, DomainError>>;
144
+ deleteOne: (params: DeleteParams) => Promise<Result<DeleteResult, DomainError>>;
145
+ getApiUrl: () => string;
146
+ getMany?: ((params: GetManyParams) => Promise<Result<GetManyResult, DomainError>>) | undefined;
147
+ createMany?: ((params: CreateManyParams) => Promise<Result<CreateManyResult, DomainError>>) | undefined;
148
+ updateMany?: ((params: UpdateManyParams) => Promise<Result<UpdateManyResult, DomainError>>) | undefined;
149
+ deleteMany?: ((params: DeleteManyParams) => Promise<Result<DeleteManyResult, DomainError>>) | undefined;
150
+ custom?: ((params: CustomParams) => Promise<Result<CustomResult, DomainError>>) | undefined;
151
+ }
152
+
153
+ /**
154
+ * Wraps an existing DataProvider into a SafeDataProvider returning Result<T, DomainError>.
155
+ */
156
+ export function wrapDataProviderWithResult(provider: DataProvider): SafeDataProvider {
157
+ const getMany = provider.getMany?.bind(provider);
158
+ const createMany = provider.createMany?.bind(provider);
159
+ const updateMany = provider.updateMany?.bind(provider);
160
+ const deleteMany = provider.deleteMany?.bind(provider);
161
+ const custom = provider.custom?.bind(provider);
162
+
163
+ const asResult = <T>(run: () => Promise<T>): Promise<Result<T, DomainError>> => {
164
+ try {
165
+ return fromPromise(Promise.resolve(run()), toDomainError);
166
+ } catch (cause) {
167
+ return Promise.resolve(err(toDomainError(cause)));
168
+ }
169
+ };
170
+
171
+ return {
172
+ raw: provider,
173
+ getApiUrl: () => provider.getApiUrl(),
174
+ getList: (params) => asResult(() => provider.getList(params)),
175
+ getOne: (params) => asResult(() => provider.getOne(params)),
176
+ create: (params) => asResult(() => provider.create(params)),
177
+ update: (params) => asResult(() => provider.update(params)),
178
+ deleteOne: (params) => asResult(() => provider.deleteOne(params)),
179
+ getMany: getMany ? (params) => asResult(() => getMany(params)) : undefined,
180
+ createMany: createMany ? (params) => asResult(() => createMany(params)) : undefined,
181
+ updateMany: updateMany ? (params) => asResult(() => updateMany(params)) : undefined,
182
+ deleteMany: deleteMany ? (params) => asResult(() => deleteMany(params)) : undefined,
183
+ custom: custom ? (params) => asResult(() => custom(params)) : undefined,
184
+ };
185
+ }
package/src/result.ts ADDED
@@ -0,0 +1,99 @@
1
+ /**
2
+ * High-rigor Result<T, E> algebraic data type for safe, typed error handling
3
+ * without throwing exceptions.
4
+ */
5
+
6
+ export interface Ok<T> {
7
+ readonly ok: true;
8
+ readonly value: T;
9
+ readonly error?: never;
10
+ }
11
+
12
+ export interface Err<E> {
13
+ readonly ok: false;
14
+ readonly error: E;
15
+ readonly value?: never;
16
+ }
17
+
18
+ export type Result<T, E> = Ok<T> | Err<E>;
19
+
20
+ export function ok<T>(value: T): Ok<T> {
21
+ return { ok: true, value };
22
+ }
23
+
24
+ export function err<E>(error: E): Err<E> {
25
+ return { ok: false, error };
26
+ }
27
+
28
+ export function isOk<T, E>(result: Result<T, E>): result is Ok<T> {
29
+ return result.ok === true;
30
+ }
31
+
32
+ export function isErr<T, E>(result: Result<T, E>): result is Err<E> {
33
+ return result.ok === false;
34
+ }
35
+
36
+ export function unwrapResult<T, E>(result: Result<T, E>): T {
37
+ if (result.ok) {
38
+ return result.value;
39
+ }
40
+ throw result.error;
41
+ }
42
+
43
+ export function unwrapOr<T, E>(result: Result<T, E>, fallback: T): T {
44
+ return result.ok ? result.value : fallback;
45
+ }
46
+
47
+ export function mapResult<T, E, U>(result: Result<T, E>, fn: (value: T) => U): Result<U, E> {
48
+ if (result.ok) {
49
+ return ok(fn(result.value));
50
+ }
51
+ return result;
52
+ }
53
+
54
+ export function mapErr<T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F> {
55
+ if (!result.ok) {
56
+ return err(fn(result.error));
57
+ }
58
+ return result;
59
+ }
60
+
61
+ export function flatMapResult<T, E, U>(result: Result<T, E>, fn: (value: T) => Result<U, E>): Result<U, E> {
62
+ if (result.ok) {
63
+ return fn(result.value);
64
+ }
65
+ return result;
66
+ }
67
+
68
+ export function matchResult<T, E, R>(
69
+ result: Result<T, E>,
70
+ patterns: {
71
+ ok: (value: T) => R;
72
+ err: (error: E) => R;
73
+ },
74
+ ): R {
75
+ return result.ok ? patterns.ok(result.value) : patterns.err(result.error);
76
+ }
77
+
78
+ export function fromThrowable<T, E = unknown>(
79
+ fn: () => T,
80
+ onError: (cause: unknown) => E,
81
+ ): Result<T, E> {
82
+ try {
83
+ return ok(fn());
84
+ } catch (cause) {
85
+ return err(onError(cause));
86
+ }
87
+ }
88
+
89
+ export async function fromPromise<T, E = unknown>(
90
+ promise: Promise<T>,
91
+ onError: (cause: unknown) => E,
92
+ ): Promise<Result<T, E>> {
93
+ try {
94
+ const value = await promise;
95
+ return ok(value);
96
+ } catch (cause) {
97
+ return err(onError(cause));
98
+ }
99
+ }
@@ -17,6 +17,8 @@ import { auditWithProvider } from './audit';
17
17
  import { HttpError } from './types';
18
18
  import { useTranslation } from './i18n.svelte';
19
19
  import { toast } from './toast.svelte';
20
+ import { ok, err, type Result as SafeResult } from './result';
21
+ import { toDomainError, type DomainError } from './domain-errors';
20
22
 
21
23
  export type { ContractUpdateParams } from './update-contract';
22
24
  export interface ContractUpdateOptions<S extends ContractSchemas> {
@@ -328,13 +330,21 @@ export function useContractUpdate<S extends ContractSchemas>(options: ContractUp
328
330
  mutate(params: ContractUpdateParams<S>, callbacks?: Callbacks<S>): void {
329
331
  void mutateAsync(params, callbacks).catch(() => {});
330
332
  },
333
+ async safeMutate(params: ContractUpdateParams<S>, callbacks?: Callbacks<S>): Promise<SafeResult<ContractRecord<S>, DomainError>> {
334
+ try {
335
+ const res = await mutateAsync(params, callbacks);
336
+ return ok(res.data);
337
+ } catch (cause) {
338
+ return err(toDomainError(cause));
339
+ }
340
+ },
331
341
  reset() { active = undefined; latest = undefined; latestToken = undefined; mutation.reset(); },
332
342
  });
333
343
  const idle: typeof result = {
334
344
  context: undefined, data: undefined, error: null, failureCount: 0, failureReason: null,
335
345
  isError: false, isIdle: true, isPending: false, isPaused: false, isSuccess: false,
336
346
  status: 'idle', submittedAt: 0, variables: undefined,
337
- mutate: result.mutate, mutateAsync: result.mutateAsync, reset: result.reset,
347
+ mutate: result.mutate, mutateAsync: result.mutateAsync, safeMutate: result.safeMutate, reset: result.reset,
338
348
  };
339
349
  const view = createQueryResultView(() => {
340
350
  const invocation = mutation.variables;
@@ -15,6 +15,8 @@ import { getAdminOptions } from './options.svelte';
15
15
  import { captureAuthLiveScope, clearAuthQueries, handleAuthError } from './auth-hooks.svelte';
16
16
  import { auditWithProvider } from './audit';
17
17
  import { HttpError } from './types';
18
+ import { ok, err, type Result as SafeResult } from './result';
19
+ import { toDomainError, type DomainError } from './domain-errors';
18
20
  import { useTranslation } from './i18n.svelte';
19
21
  import { toast } from './toast.svelte';
20
22
 
@@ -357,13 +359,21 @@ export function useContractUpdateMany<S extends ContractSchemas>(options: Contra
357
359
  mutate(params: ContractUpdateManyParams<S>, callbacks?: Callbacks<S>): void {
358
360
  void mutateAsync(params, callbacks).catch(() => {});
359
361
  },
362
+ async safeMutate(params: ContractUpdateManyParams<S>, callbacks?: Callbacks<S>): Promise<SafeResult<ContractRecord<S>[], DomainError>> {
363
+ try {
364
+ const res = await mutateAsync(params, callbacks);
365
+ return ok(res.data);
366
+ } catch (cause) {
367
+ return err(toDomainError(cause));
368
+ }
369
+ },
360
370
  reset() { active = undefined; latest = undefined; latestToken = undefined; mutation.reset(); },
361
371
  });
362
372
  const idle: typeof result = {
363
373
  context: undefined, data: undefined, error: null, failureCount: 0, failureReason: null,
364
374
  isError: false, isIdle: true, isPending: false, isPaused: false, isSuccess: false,
365
375
  status: 'idle', submittedAt: 0, variables: undefined,
366
- mutate: result.mutate, mutateAsync: result.mutateAsync, reset: result.reset,
376
+ mutate: result.mutate, mutateAsync: result.mutateAsync, safeMutate: result.safeMutate, reset: result.reset,
367
377
  };
368
378
  const view = createQueryResultView(() => {
369
379
  const invocation = mutation.variables;