@asaidimu/utils-error 1.1.1 → 1.1.2

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/index.d.mts CHANGED
@@ -7,15 +7,15 @@ type Severity = "error" | "warning" | "info";
7
7
  * Designed to be machine-readable while remaining human-friendly.
8
8
  */
9
9
  interface Issue {
10
- /** Machine-readable identifier (e.g., "REQUIRED_FIELD_MISSING"). */
10
+ /** Machine-readable identifier (e.g., `"REQUIRED_FIELD_MISSING"`). */
11
11
  readonly code: string;
12
12
  /** Human-readable description of the problem. */
13
13
  readonly message: string;
14
- /** Field path in a document or state (e.g., "users.0.email"). */
14
+ /** Field path in a document or state (e.g., `"users.0.email"`). */
15
15
  readonly path?: string;
16
16
  /** Optional array index when the issue relates to a specific element. */
17
17
  readonly index?: number;
18
- /** Seriousness of the issue. Defaults to "error". */
18
+ /** Seriousness of the issue. Defaults to `"error"`. */
19
19
  readonly severity?: Severity;
20
20
  /** Optional detailed explanation, can be multi-line. */
21
21
  readonly description?: string;
@@ -23,31 +23,37 @@ interface Issue {
23
23
  readonly cause?: readonly Issue[];
24
24
  }
25
25
  /**
26
- * Standardized error code format: CATEGORY-XXX[-SUFFIX]
27
- * Examples:
28
- * - VAL-001 (Validation: required field missing)
29
- * - DB-002-NF (Database: not found)
30
- * - AUTH-003-DENIED (Auth: permission denied)
26
+ * Standardized error code format: `CATEGORY-XXX[-SUFFIX]`
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * // VAL-001 (Validation: required field missing)
31
+ * // DB-001-NF (Database: not found)
32
+ * // AUTH-001-DENIED (Auth: permission denied)
33
+ * ```
31
34
  */
32
35
  interface ErrorCodeMetadata {
33
- /** The formal error code (e.g., "VAL-001") */
36
+ /** The formal unique error code identifier (e.g., `"VAL-001"`). */
34
37
  readonly code: string;
35
- /** Human-readable name for the error type */
38
+ /** Human-readable uppercase name for the error type (e.g., `"VALIDATION_FAILED"`). */
36
39
  readonly name: string;
37
- /** Detailed description of when this error occurs */
40
+ /** Detailed description of when and why this error occurs. */
38
41
  readonly description: string;
39
- /** Suggested action for handling or resolving the error */
42
+ /** Suggested immediate action for engineers or systems to handle or resolve the error. */
40
43
  readonly action?: string;
41
- /** HTTP status code mapping (if applicable) */
44
+ /** HTTP status code mapping for upstream REST APIs (e.g., `404`, `500`). */
42
45
  readonly httpStatus?: number;
43
- /** Category of the error */
46
+ /** Operational category this error belongs to. */
44
47
  readonly category: ErrorCategory;
45
- /** Whether this error should be logged as warning vs error */
48
+ /** Recommended logging level threshold (`"debug" | "info" | "warn" | "error"`). */
46
49
  readonly logLevel?: "debug" | "info" | "warn" | "error";
47
50
  }
51
+ /**
52
+ * Categories classifying the origin and nature of an error.
53
+ */
48
54
  type ErrorCategory = "validation" | "database" | "auth" | "business" | "system" | "network" | "concurrency" | "custom";
49
55
  /**
50
- * Central registry of built-in error codes.
56
+ * Central registry of built-in system error codes.
51
57
  */
52
58
  declare const ErrorCodes: {
53
59
  readonly VALIDATION_FAILED: {
@@ -163,96 +169,144 @@ declare const ErrorCodes: {
163
169
  };
164
170
  };
165
171
  /**
166
- * Register a custom error code at runtime.
167
- * @throws if code already exists as a built-in error
172
+ * Register a custom error code at application runtime.
173
+ * @param metadata - The complete configuration and documentation for the new error code.
174
+ * @throws {Error} If the code already exists within built-in codes or is already registered.
168
175
  */
169
176
  declare function registerErrorCode(metadata: ErrorCodeMetadata): void;
170
177
  /**
171
- * Get metadata for any error code (built-in or custom).
172
- * Returns default metadata for unknown codes instead of throwing.
178
+ * Retrieve metadata details for any error code (built-in or custom dynamically registered).
179
+ * Falls back to a generic `custom` category block if the code is entirely unrecognized.
180
+ * @param code - The error code string to query.
181
+ * @returns The documented metadata configuration.
173
182
  */
174
183
  declare function getErrorMetadata(code: string): ErrorCodeMetadata;
175
184
  /**
176
- * Check if an error code is known (built-in or registered custom).
185
+ * Determines whether an error code exists in built-in configuration or runtime registries.
177
186
  */
178
187
  declare function isKnownErrorCode(code: string): boolean;
179
188
  /**
180
- * SystemError is the primary error type for all operational and validation errors.
181
- * Supports both predefined and custom error codes with full metadata.
189
+ * Configuration options container used when constructing a new `SystemError`.
190
+ */
191
+ interface SystemErrorParams {
192
+ /** The unique registered error code identifier (e.g., `ErrorCodes.INTERNAL_ERROR.code`). */
193
+ code: string;
194
+ /** Explicit error message overrides. If omitted, defaults to the error code's description. */
195
+ message?: string;
196
+ /** Operational severity tier. Defaults to `"error"`. */
197
+ severity?: Severity;
198
+ /** State path or key where the operational failure occurred (e.g., `"users.0.email"`). */
199
+ path?: string;
200
+ /** The function block, track component, or routing process executing during failure. */
201
+ operation?: string;
202
+ /** Flat array of precise granular input issues or schema violations. */
203
+ issues?: readonly Issue[];
204
+ /** The underlying trigger cause. Accepts native `Error` instances, custom errors, or concurrent `Error[]` arrays. */
205
+ cause?: unknown | unknown[];
206
+ /** Ad-hoc modifications overriding base properties mapped from the code registry. */
207
+ metadata?: Partial<Omit<ErrorCodeMetadata, "code" | "category">>;
208
+ }
209
+ /**
210
+ * A single frame in a chronological error trace.
211
+ */
212
+ interface TraceFrame {
213
+ operation: string;
214
+ message: string;
215
+ code?: string;
216
+ category?: string;
217
+ }
218
+ /**
219
+ * Represents a set of parallel error tracks (e.g., from `AggregateError`).
220
+ */
221
+ interface ParallelTrace {
222
+ type: "parallel";
223
+ tracks: TraceNode[][];
224
+ }
225
+ /** A node in the trace is either a single frame or a parallel group. */
226
+ type TraceNode = TraceFrame | ParallelTrace;
227
+ /** The full chronological trace is always an array of nodes. */
228
+ type ChronologicalTrace = TraceNode[];
229
+ /**
230
+ * Primary domain operational error wrapper.
231
+ * Unfolds historical deep error hierarchies into flat, parallel-aware trace timelines.
182
232
  */
183
233
  declare class SystemError extends Error {
234
+ /** The associated error identifier code (e.g., `"SYS-001"`). */
184
235
  readonly code: string;
236
+ /** Static documentation mapping and registration rules bound to this code type. */
185
237
  readonly codeMetadata: ErrorCodeMetadata;
238
+ /** Severity tier grading the operational consequence of this failure. */
186
239
  readonly severity: Severity;
240
+ /** Target state or document path where processing failed. */
187
241
  readonly path?: string;
242
+ /** Active system segment, workflow node, or function context executing during failure. */
188
243
  readonly operation?: string;
244
+ /** Detailed sub-layer list representing structural data validation failures. */
189
245
  readonly issues: readonly Issue[];
246
+ /** Raw backing trigger, array of concurrent branches, or source error instance. */
190
247
  readonly cause?: unknown | unknown[];
191
- constructor(params: {
192
- code: string;
193
- message?: string;
194
- severity?: Severity;
195
- path?: string;
196
- operation?: string;
197
- issues?: readonly Issue[];
198
- cause?: unknown | unknown[];
199
- metadata?: Partial<Omit<ErrorCodeMetadata, "code">>;
200
- });
248
+ /** Exact moment this error was instantiated (ISO string). */
249
+ readonly timestamp: string;
250
+ /**
251
+ * Instantiate a structurally traceable `SystemError`.
252
+ * @param params - Configuration parameters outlining the error's state context.
253
+ */
254
+ constructor(params: SystemErrorParams);
201
255
  /**
202
- * Returns a new SystemError with the specified path.
256
+ * Generates a separate immutable clone assigning a target file, state, or field path.
203
257
  */
204
258
  withPath(path: string): SystemError;
205
259
  /**
206
- * Returns a new SystemError with the specified operation name.
260
+ * Generates a separate immutable clone assigning a specific execution block or track tracking context.
207
261
  */
208
262
  withOperation(operation: string): SystemError;
209
263
  /**
210
- * Returns a new SystemError with the specified issue appended.
264
+ * Appends an operational validation structural issue to a fresh clone of this error.
211
265
  */
212
266
  withIssue(issue: Issue): SystemError;
213
267
  /**
214
- * Returns a new SystemError with multiple issues appended.
268
+ * Appends multiple validation issues onto a fresh clone of this error instance.
215
269
  */
216
270
  withIssues(issues: readonly Issue[]): SystemError;
217
271
  /**
218
- * Returns a new SystemError wrapping the specified cause.
272
+ * Maps a backing raw trigger or concurrent array tracking set to a fresh clone of this error instance.
219
273
  */
220
274
  withCause(cause: unknown | unknown[]): SystemError;
221
275
  /**
222
- * Returns the HTTP status code for this error (if applicable).
276
+ * Retrieves the recommended HTTP Status code mapped to this error's code metadata registry.
223
277
  */
224
278
  getHttpStatus(): number | undefined;
225
279
  /**
226
- * Recursively extracts errors and builds a chronological chain (deepest leaf first).
280
+ * Unrolls execution hierarchies chronologically, isolating parallel pipelines into clear trace frames.
281
+ * Always returns an array of trace nodes.
227
282
  */
228
- private extractChronologicalChain;
283
+ private extractChronologicalTrace;
229
284
  /**
230
- * Formats the error for logging with an inverted, chronological execution path.
285
+ * Transforms the error payload into a flattened transmission format.
286
+ * Strips recursive depth in favor of an array-mapped chronological failure `trace`.
231
287
  */
232
- toLogEntry(): Record<string, unknown>;
233
- /**
234
- * Helper to recursively serialize any cause (single error, system error, or an array of them)
235
- */
236
- private serializeCause;
288
+ toJSON(): Record<string, unknown>;
237
289
  /**
238
- * Automatically invoked by JSON.stringify().
290
+ * Generates a flat payload matching `toJSON` format requirements for centralized platform ingestion engines.
239
291
  */
240
- toJSON(): Record<string, unknown>;
292
+ toLogEntry(): Record<string, unknown>;
241
293
  /**
242
- * Produces a human-readable representation suitable for logging.
294
+ * Terminal terminal dump representation formatting details cleanly into plain strings.
243
295
  */
244
296
  toString(): string;
245
297
  }
246
298
  /**
247
- * Factory for creating a new SystemError with automatic metadata.
299
+ * Utility wrapper compiling a standard configured `SystemError`.
300
+ * @param code - The target static identifier code from the system directory registry.
301
+ * @param message - Custom overriding error description string.
248
302
  */
249
303
  declare function createError(code: string, message?: string): SystemError;
250
304
  /**
251
- * Helper for quick ad-hoc errors (useful for testing or prototyping).
305
+ * Helper generating quick ad-hoc test or assertion validation operational failures.
252
306
  */
253
307
  declare function error(code: string, message?: string): SystemError;
254
308
  /**
255
- * Predefined error codes for common scenarios (backward compatibility).
309
+ * Constant definitions providing direct string matching references to global built-in errors.
256
310
  */
257
311
  declare const CommonErrors: {
258
312
  readonly NOT_FOUND: "DB-001-NF";
@@ -267,18 +321,23 @@ declare const CommonErrors: {
267
321
  readonly OPERATION_ABORTED: "BUS-002-ABORT";
268
322
  };
269
323
  /**
270
- * Convenience factory functions for common errors.
324
+ * Immediate instantiation factory shortcodes.
271
325
  */
272
326
  declare const Errors: {
327
+ /** Resource missing exception handler factory. */
273
328
  notFound: (path?: string, message?: string) => SystemError;
329
+ /** Data key conflict handler factory. */
274
330
  duplicateKey: (path?: string, message?: string) => SystemError;
331
+ /** RBAC enforcement execution violation factory. */
275
332
  permissionDenied: (operation?: string, message?: string) => SystemError;
333
+ /** Structural form or schema processing failure collection compiler. */
276
334
  validationFailed: (issues: Issue[], path?: string) => SystemError;
335
+ /** Unexpected component thread collapse generic factory. */
277
336
  internalError: (cause?: unknown, message?: string) => SystemError;
278
337
  };
279
338
  /**
280
- * A functional wrapper for operations that can fail.
281
- * Encourages explicit error handling over try/catch blocks.
339
+ * Monadic functional wrapper container representing either an expected return type value,
340
+ * or a structural failure wrapper sequence without forcing explicit `throw` mechanics.
282
341
  */
283
342
  type Result<T, E = SystemError> = {
284
343
  readonly ok: true;
@@ -288,11 +347,13 @@ type Result<T, E = SystemError> = {
288
347
  readonly error: E;
289
348
  };
290
349
  /**
291
- * Type-safe helpers for creating Results.
350
+ * Type-guarded factory wrappers generating functional operational processing `Result` sets.
292
351
  */
293
352
  declare const Result: {
353
+ /** Compiles a verified positive execution return contract carrying processing changes. */
294
354
  ok: <T>(value: T) => Result<T, never>;
295
- fail: <E>(error: E) => Result<never, E>;
355
+ /** Compiles a tracked failure tracking context avoiding stack engine halts. */
356
+ fail: <E>(err: E) => Result<never, E>;
296
357
  };
297
358
 
298
- export { CommonErrors, type ErrorCategory, type ErrorCodeMetadata, ErrorCodes, Errors, type Issue, Result, type Severity, SystemError, createError, error, getErrorMetadata, isKnownErrorCode, registerErrorCode };
359
+ export { type ChronologicalTrace, CommonErrors, type ErrorCategory, type ErrorCodeMetadata, ErrorCodes, Errors, type Issue, type ParallelTrace, Result, type Severity, SystemError, type SystemErrorParams, type TraceFrame, type TraceNode, createError, error, getErrorMetadata, isKnownErrorCode, registerErrorCode };
package/index.d.ts CHANGED
@@ -7,15 +7,15 @@ type Severity = "error" | "warning" | "info";
7
7
  * Designed to be machine-readable while remaining human-friendly.
8
8
  */
9
9
  interface Issue {
10
- /** Machine-readable identifier (e.g., "REQUIRED_FIELD_MISSING"). */
10
+ /** Machine-readable identifier (e.g., `"REQUIRED_FIELD_MISSING"`). */
11
11
  readonly code: string;
12
12
  /** Human-readable description of the problem. */
13
13
  readonly message: string;
14
- /** Field path in a document or state (e.g., "users.0.email"). */
14
+ /** Field path in a document or state (e.g., `"users.0.email"`). */
15
15
  readonly path?: string;
16
16
  /** Optional array index when the issue relates to a specific element. */
17
17
  readonly index?: number;
18
- /** Seriousness of the issue. Defaults to "error". */
18
+ /** Seriousness of the issue. Defaults to `"error"`. */
19
19
  readonly severity?: Severity;
20
20
  /** Optional detailed explanation, can be multi-line. */
21
21
  readonly description?: string;
@@ -23,31 +23,37 @@ interface Issue {
23
23
  readonly cause?: readonly Issue[];
24
24
  }
25
25
  /**
26
- * Standardized error code format: CATEGORY-XXX[-SUFFIX]
27
- * Examples:
28
- * - VAL-001 (Validation: required field missing)
29
- * - DB-002-NF (Database: not found)
30
- * - AUTH-003-DENIED (Auth: permission denied)
26
+ * Standardized error code format: `CATEGORY-XXX[-SUFFIX]`
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * // VAL-001 (Validation: required field missing)
31
+ * // DB-001-NF (Database: not found)
32
+ * // AUTH-001-DENIED (Auth: permission denied)
33
+ * ```
31
34
  */
32
35
  interface ErrorCodeMetadata {
33
- /** The formal error code (e.g., "VAL-001") */
36
+ /** The formal unique error code identifier (e.g., `"VAL-001"`). */
34
37
  readonly code: string;
35
- /** Human-readable name for the error type */
38
+ /** Human-readable uppercase name for the error type (e.g., `"VALIDATION_FAILED"`). */
36
39
  readonly name: string;
37
- /** Detailed description of when this error occurs */
40
+ /** Detailed description of when and why this error occurs. */
38
41
  readonly description: string;
39
- /** Suggested action for handling or resolving the error */
42
+ /** Suggested immediate action for engineers or systems to handle or resolve the error. */
40
43
  readonly action?: string;
41
- /** HTTP status code mapping (if applicable) */
44
+ /** HTTP status code mapping for upstream REST APIs (e.g., `404`, `500`). */
42
45
  readonly httpStatus?: number;
43
- /** Category of the error */
46
+ /** Operational category this error belongs to. */
44
47
  readonly category: ErrorCategory;
45
- /** Whether this error should be logged as warning vs error */
48
+ /** Recommended logging level threshold (`"debug" | "info" | "warn" | "error"`). */
46
49
  readonly logLevel?: "debug" | "info" | "warn" | "error";
47
50
  }
51
+ /**
52
+ * Categories classifying the origin and nature of an error.
53
+ */
48
54
  type ErrorCategory = "validation" | "database" | "auth" | "business" | "system" | "network" | "concurrency" | "custom";
49
55
  /**
50
- * Central registry of built-in error codes.
56
+ * Central registry of built-in system error codes.
51
57
  */
52
58
  declare const ErrorCodes: {
53
59
  readonly VALIDATION_FAILED: {
@@ -163,96 +169,144 @@ declare const ErrorCodes: {
163
169
  };
164
170
  };
165
171
  /**
166
- * Register a custom error code at runtime.
167
- * @throws if code already exists as a built-in error
172
+ * Register a custom error code at application runtime.
173
+ * @param metadata - The complete configuration and documentation for the new error code.
174
+ * @throws {Error} If the code already exists within built-in codes or is already registered.
168
175
  */
169
176
  declare function registerErrorCode(metadata: ErrorCodeMetadata): void;
170
177
  /**
171
- * Get metadata for any error code (built-in or custom).
172
- * Returns default metadata for unknown codes instead of throwing.
178
+ * Retrieve metadata details for any error code (built-in or custom dynamically registered).
179
+ * Falls back to a generic `custom` category block if the code is entirely unrecognized.
180
+ * @param code - The error code string to query.
181
+ * @returns The documented metadata configuration.
173
182
  */
174
183
  declare function getErrorMetadata(code: string): ErrorCodeMetadata;
175
184
  /**
176
- * Check if an error code is known (built-in or registered custom).
185
+ * Determines whether an error code exists in built-in configuration or runtime registries.
177
186
  */
178
187
  declare function isKnownErrorCode(code: string): boolean;
179
188
  /**
180
- * SystemError is the primary error type for all operational and validation errors.
181
- * Supports both predefined and custom error codes with full metadata.
189
+ * Configuration options container used when constructing a new `SystemError`.
190
+ */
191
+ interface SystemErrorParams {
192
+ /** The unique registered error code identifier (e.g., `ErrorCodes.INTERNAL_ERROR.code`). */
193
+ code: string;
194
+ /** Explicit error message overrides. If omitted, defaults to the error code's description. */
195
+ message?: string;
196
+ /** Operational severity tier. Defaults to `"error"`. */
197
+ severity?: Severity;
198
+ /** State path or key where the operational failure occurred (e.g., `"users.0.email"`). */
199
+ path?: string;
200
+ /** The function block, track component, or routing process executing during failure. */
201
+ operation?: string;
202
+ /** Flat array of precise granular input issues or schema violations. */
203
+ issues?: readonly Issue[];
204
+ /** The underlying trigger cause. Accepts native `Error` instances, custom errors, or concurrent `Error[]` arrays. */
205
+ cause?: unknown | unknown[];
206
+ /** Ad-hoc modifications overriding base properties mapped from the code registry. */
207
+ metadata?: Partial<Omit<ErrorCodeMetadata, "code" | "category">>;
208
+ }
209
+ /**
210
+ * A single frame in a chronological error trace.
211
+ */
212
+ interface TraceFrame {
213
+ operation: string;
214
+ message: string;
215
+ code?: string;
216
+ category?: string;
217
+ }
218
+ /**
219
+ * Represents a set of parallel error tracks (e.g., from `AggregateError`).
220
+ */
221
+ interface ParallelTrace {
222
+ type: "parallel";
223
+ tracks: TraceNode[][];
224
+ }
225
+ /** A node in the trace is either a single frame or a parallel group. */
226
+ type TraceNode = TraceFrame | ParallelTrace;
227
+ /** The full chronological trace is always an array of nodes. */
228
+ type ChronologicalTrace = TraceNode[];
229
+ /**
230
+ * Primary domain operational error wrapper.
231
+ * Unfolds historical deep error hierarchies into flat, parallel-aware trace timelines.
182
232
  */
183
233
  declare class SystemError extends Error {
234
+ /** The associated error identifier code (e.g., `"SYS-001"`). */
184
235
  readonly code: string;
236
+ /** Static documentation mapping and registration rules bound to this code type. */
185
237
  readonly codeMetadata: ErrorCodeMetadata;
238
+ /** Severity tier grading the operational consequence of this failure. */
186
239
  readonly severity: Severity;
240
+ /** Target state or document path where processing failed. */
187
241
  readonly path?: string;
242
+ /** Active system segment, workflow node, or function context executing during failure. */
188
243
  readonly operation?: string;
244
+ /** Detailed sub-layer list representing structural data validation failures. */
189
245
  readonly issues: readonly Issue[];
246
+ /** Raw backing trigger, array of concurrent branches, or source error instance. */
190
247
  readonly cause?: unknown | unknown[];
191
- constructor(params: {
192
- code: string;
193
- message?: string;
194
- severity?: Severity;
195
- path?: string;
196
- operation?: string;
197
- issues?: readonly Issue[];
198
- cause?: unknown | unknown[];
199
- metadata?: Partial<Omit<ErrorCodeMetadata, "code">>;
200
- });
248
+ /** Exact moment this error was instantiated (ISO string). */
249
+ readonly timestamp: string;
250
+ /**
251
+ * Instantiate a structurally traceable `SystemError`.
252
+ * @param params - Configuration parameters outlining the error's state context.
253
+ */
254
+ constructor(params: SystemErrorParams);
201
255
  /**
202
- * Returns a new SystemError with the specified path.
256
+ * Generates a separate immutable clone assigning a target file, state, or field path.
203
257
  */
204
258
  withPath(path: string): SystemError;
205
259
  /**
206
- * Returns a new SystemError with the specified operation name.
260
+ * Generates a separate immutable clone assigning a specific execution block or track tracking context.
207
261
  */
208
262
  withOperation(operation: string): SystemError;
209
263
  /**
210
- * Returns a new SystemError with the specified issue appended.
264
+ * Appends an operational validation structural issue to a fresh clone of this error.
211
265
  */
212
266
  withIssue(issue: Issue): SystemError;
213
267
  /**
214
- * Returns a new SystemError with multiple issues appended.
268
+ * Appends multiple validation issues onto a fresh clone of this error instance.
215
269
  */
216
270
  withIssues(issues: readonly Issue[]): SystemError;
217
271
  /**
218
- * Returns a new SystemError wrapping the specified cause.
272
+ * Maps a backing raw trigger or concurrent array tracking set to a fresh clone of this error instance.
219
273
  */
220
274
  withCause(cause: unknown | unknown[]): SystemError;
221
275
  /**
222
- * Returns the HTTP status code for this error (if applicable).
276
+ * Retrieves the recommended HTTP Status code mapped to this error's code metadata registry.
223
277
  */
224
278
  getHttpStatus(): number | undefined;
225
279
  /**
226
- * Recursively extracts errors and builds a chronological chain (deepest leaf first).
280
+ * Unrolls execution hierarchies chronologically, isolating parallel pipelines into clear trace frames.
281
+ * Always returns an array of trace nodes.
227
282
  */
228
- private extractChronologicalChain;
283
+ private extractChronologicalTrace;
229
284
  /**
230
- * Formats the error for logging with an inverted, chronological execution path.
285
+ * Transforms the error payload into a flattened transmission format.
286
+ * Strips recursive depth in favor of an array-mapped chronological failure `trace`.
231
287
  */
232
- toLogEntry(): Record<string, unknown>;
233
- /**
234
- * Helper to recursively serialize any cause (single error, system error, or an array of them)
235
- */
236
- private serializeCause;
288
+ toJSON(): Record<string, unknown>;
237
289
  /**
238
- * Automatically invoked by JSON.stringify().
290
+ * Generates a flat payload matching `toJSON` format requirements for centralized platform ingestion engines.
239
291
  */
240
- toJSON(): Record<string, unknown>;
292
+ toLogEntry(): Record<string, unknown>;
241
293
  /**
242
- * Produces a human-readable representation suitable for logging.
294
+ * Terminal terminal dump representation formatting details cleanly into plain strings.
243
295
  */
244
296
  toString(): string;
245
297
  }
246
298
  /**
247
- * Factory for creating a new SystemError with automatic metadata.
299
+ * Utility wrapper compiling a standard configured `SystemError`.
300
+ * @param code - The target static identifier code from the system directory registry.
301
+ * @param message - Custom overriding error description string.
248
302
  */
249
303
  declare function createError(code: string, message?: string): SystemError;
250
304
  /**
251
- * Helper for quick ad-hoc errors (useful for testing or prototyping).
305
+ * Helper generating quick ad-hoc test or assertion validation operational failures.
252
306
  */
253
307
  declare function error(code: string, message?: string): SystemError;
254
308
  /**
255
- * Predefined error codes for common scenarios (backward compatibility).
309
+ * Constant definitions providing direct string matching references to global built-in errors.
256
310
  */
257
311
  declare const CommonErrors: {
258
312
  readonly NOT_FOUND: "DB-001-NF";
@@ -267,18 +321,23 @@ declare const CommonErrors: {
267
321
  readonly OPERATION_ABORTED: "BUS-002-ABORT";
268
322
  };
269
323
  /**
270
- * Convenience factory functions for common errors.
324
+ * Immediate instantiation factory shortcodes.
271
325
  */
272
326
  declare const Errors: {
327
+ /** Resource missing exception handler factory. */
273
328
  notFound: (path?: string, message?: string) => SystemError;
329
+ /** Data key conflict handler factory. */
274
330
  duplicateKey: (path?: string, message?: string) => SystemError;
331
+ /** RBAC enforcement execution violation factory. */
275
332
  permissionDenied: (operation?: string, message?: string) => SystemError;
333
+ /** Structural form or schema processing failure collection compiler. */
276
334
  validationFailed: (issues: Issue[], path?: string) => SystemError;
335
+ /** Unexpected component thread collapse generic factory. */
277
336
  internalError: (cause?: unknown, message?: string) => SystemError;
278
337
  };
279
338
  /**
280
- * A functional wrapper for operations that can fail.
281
- * Encourages explicit error handling over try/catch blocks.
339
+ * Monadic functional wrapper container representing either an expected return type value,
340
+ * or a structural failure wrapper sequence without forcing explicit `throw` mechanics.
282
341
  */
283
342
  type Result<T, E = SystemError> = {
284
343
  readonly ok: true;
@@ -288,11 +347,13 @@ type Result<T, E = SystemError> = {
288
347
  readonly error: E;
289
348
  };
290
349
  /**
291
- * Type-safe helpers for creating Results.
350
+ * Type-guarded factory wrappers generating functional operational processing `Result` sets.
292
351
  */
293
352
  declare const Result: {
353
+ /** Compiles a verified positive execution return contract carrying processing changes. */
294
354
  ok: <T>(value: T) => Result<T, never>;
295
- fail: <E>(error: E) => Result<never, E>;
355
+ /** Compiles a tracked failure tracking context avoiding stack engine halts. */
356
+ fail: <E>(err: E) => Result<never, E>;
296
357
  };
297
358
 
298
- export { CommonErrors, type ErrorCategory, type ErrorCodeMetadata, ErrorCodes, Errors, type Issue, Result, type Severity, SystemError, createError, error, getErrorMetadata, isKnownErrorCode, registerErrorCode };
359
+ export { type ChronologicalTrace, CommonErrors, type ErrorCategory, type ErrorCodeMetadata, ErrorCodes, Errors, type Issue, type ParallelTrace, Result, type Severity, SystemError, type SystemErrorParams, type TraceFrame, type TraceNode, createError, error, getErrorMetadata, isKnownErrorCode, registerErrorCode };
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e={VALIDATION_FAILED:{code:"VAL-001",name:"VALIDATION_FAILED",description:"Input validation failed due to one or more invalid fields",category:"validation",httpStatus:400,logLevel:"warn"},REQUIRED_FIELD_MISSING:{code:"VAL-002",name:"REQUIRED_FIELD_MISSING",description:"A required field was not provided in the request",category:"validation",httpStatus:400,logLevel:"warn"},INVALID_FORMAT:{code:"VAL-003",name:"INVALID_FORMAT",description:"Field value does not match expected format",category:"validation",httpStatus:400,logLevel:"warn"},NOT_FOUND:{code:"DB-001-NF",name:"NOT_FOUND",description:"The requested resource could not be found",category:"database",httpStatus:404,logLevel:"info",action:"Verify the resource identifier exists before accessing"},DUPLICATE_KEY:{code:"DB-002-DUP",name:"DUPLICATE_KEY",description:"A unique constraint violation occurred",category:"database",httpStatus:409,logLevel:"warn",action:"Check if the resource already exists before creation"},RESOURCE_LOCKED:{code:"DB-003-LOCK",name:"RESOURCE_LOCKED",description:"The resource is currently locked by another operation",category:"database",httpStatus:409,logLevel:"warn",action:"Retry the operation after a brief delay"},PERMISSION_DENIED:{code:"AUTH-001-DENIED",name:"PERMISSION_DENIED",description:"The authenticated user lacks permission for this operation",category:"auth",httpStatus:403,logLevel:"warn",action:"Check user roles and permissions"},UNAUTHENTICATED:{code:"AUTH-002-UNAUTH",name:"UNAUTHENTICATED",description:"Authentication is required for this operation",category:"auth",httpStatus:401,logLevel:"info",action:"Provide valid authentication credentials"},INVALID_COMMAND:{code:"BUS-001",name:"INVALID_COMMAND",description:"The command or operation is invalid for the current state",category:"business",httpStatus:400,logLevel:"warn"},OPERATION_ABORTED:{code:"BUS-002-ABORT",name:"OPERATION_ABORTED",description:"The operation was explicitly aborted",category:"business",httpStatus:409,logLevel:"info"},INTERNAL_ERROR:{code:"SYS-001",name:"INTERNAL_ERROR",description:"An unexpected internal error occurred",category:"system",httpStatus:500,logLevel:"error",action:"Check system logs for stack traces and diagnostic information"},BACKEND_ERROR:{code:"SYS-002",name:"BACKEND_ERROR",description:"An error occurred in a backend service",category:"system",httpStatus:502,logLevel:"error"},CONCURRENCY_ERROR:{code:"CON-001",name:"CONCURRENCY_ERROR",description:"A concurrency conflict occurred during the operation",category:"concurrency",httpStatus:409,logLevel:"warn",action:"Retry the operation with updated data"}},t=new Map;function s(s){const a=Object.values(e).find(e=>e.code===s);if(a)return a;const r=t.get(s);return r||{code:s,name:s.replace(/-/g,"_"),description:`Unknown error: ${s}`,category:"custom",httpStatus:500,logLevel:"error",action:"Check if this error code is properly registered or handle as unknown error"}}var a=class e extends Error{code;codeMetadata;severity;path;operation;issues;cause;constructor(t){const a={...s(t.code),...t.metadata,code:t.code};super(t.message??a.description),this.name="SystemError",this.code=t.code,this.codeMetadata=a,this.severity=t.severity??"error",this.path=t.path,this.operation=t.operation,this.issues=t.issues??[],this.cause=t.cause,Object.setPrototypeOf(this,e.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,e)}withPath(t){return new e({code:this.code,message:this.message,severity:this.severity,path:t,operation:this.operation,issues:this.issues,cause:this.cause,metadata:this.codeMetadata})}withOperation(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:t,issues:this.issues,cause:this.cause,metadata:this.codeMetadata})}withIssue(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:[...this.issues,t],cause:this.cause,metadata:this.codeMetadata})}withIssues(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:[...this.issues,...t],cause:this.cause,metadata:this.codeMetadata})}withCause(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:this.issues,cause:t,metadata:this.codeMetadata})}getHttpStatus(){return this.codeMetadata.httpStatus}extractChronologicalChain(e){if(!e)return[];if(Array.isArray(e))return e.flatMap(e=>this.extractChronologicalChain(e));if(e instanceof AggregateError)return e.errors.flatMap(e=>this.extractChronologicalChain(e));let t={name:e instanceof Error?e.name:"UnknownError",message:e instanceof Error?e.message:"object"==typeof e&&null!==e?JSON.stringify(e):String(e),code:e?.code,operation:e?.operation};if(!(e instanceof Error)&&"object"==typeof e&&null!==e){const t=Object.keys(e);if(1===t.length&&"object"==typeof e[t[0]])return this.extractChronologicalChain(e[t[0]])}const s=e?.cause;return s?[...this.extractChronologicalChain(s),t]:[t]}toLogEntry(){const e=this.extractChronologicalChain(this.cause);e.push({name:this.name,message:this.message,code:this.code,operation:this.operation});const t=e.map(e=>`${e.operation||e.code||e.name} (${e.message})`).join(" --\x3e ");return{name:this.name,code:this.code,category:this.codeMetadata.category,severity:this.severity,message:`${this.message} | Failure Path: ${t}`,operation:this.operation,path:this.path,issues:this.issues,history:e,stack:this.stack,timestamp:(new Date).toISOString()}}serializeCause(e){return e?Array.isArray(e)?e.map(e=>this.serializeCause(e)):e instanceof AggregateError?{name:e.name,message:e.message,errors:e.errors.map(e=>this.serializeCause(e)),stack:e.stack}:e instanceof Error?"function"==typeof e.toJSON?e.toJSON():{name:e.name,message:e.message,stack:e.stack}:e:e}toJSON(){return{name:this.name,code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,codeMetadata:this.codeMetadata,issues:this.issues,cause:this.serializeCause(this.cause)}}toString(){let e=`[${this.code}] ${this.message} (${this.codeMetadata.category})`;return this.path&&(e+=` at '${this.path}'`),this.operation&&(e+=` during '${this.operation}'`),this.issues.length>0&&(e+="\nIssues:\n"+this.issues.map((e,t)=>` ${t+1}. ${e.message} [${e.code}]`).join("\n")),this.cause&&(e+=`\nCause: ${this.cause instanceof Error?this.cause.message:String(this.cause)}`),e}};var r={NOT_FOUND:"DB-001-NF",DUPLICATE_KEY:"DB-002-DUP",INVALID_COMMAND:"BUS-001",PERMISSION_DENIED:"AUTH-001-DENIED",BACKEND_ERROR:"SYS-002",INTERNAL_ERROR:"SYS-001",VALIDATION_FAILED:"VAL-001",CONCURRENCY_ERROR:"CON-001",RESOURCE_LOCKED:"DB-003-LOCK",OPERATION_ABORTED:"BUS-002-ABORT"},o={notFound:(e,t)=>new a({code:r.NOT_FOUND,message:t,path:e}),duplicateKey:(e,t)=>new a({code:r.DUPLICATE_KEY,message:t,path:e}),permissionDenied:(e,t)=>new a({code:r.PERMISSION_DENIED,message:t,operation:e}),validationFailed:(e,t)=>new a({code:r.VALIDATION_FAILED,issues:e,path:t}),internalError:(e,t)=>new a({code:r.INTERNAL_ERROR,message:t,cause:e})};exports.CommonErrors=r,exports.ErrorCodes=e,exports.Errors=o,exports.Result={ok:e=>({ok:!0,value:e}),fail:e=>({ok:!1,error:e})},exports.SystemError=a,exports.createError=function(e,t){return new a({code:e,message:t})},exports.error=function(e,t){return new a({code:e,message:t})},exports.getErrorMetadata=s,exports.isKnownErrorCode=function(s){return Object.values(e).some(e=>e.code===s)||t.has(s)},exports.registerErrorCode=function(s){if(Object.values(e).find(e=>e.code===s.code))throw new Error(`Cannot register custom error code "${s.code}": already exists as built-in error`);if(t.has(s.code))throw new Error(`Custom error code "${s.code}" is already registered`);t.set(s.code,s)};
1
+ "use strict";var e={VALIDATION_FAILED:{code:"VAL-001",name:"VALIDATION_FAILED",description:"Input validation failed due to one or more invalid fields",category:"validation",httpStatus:400,logLevel:"warn"},REQUIRED_FIELD_MISSING:{code:"VAL-002",name:"REQUIRED_FIELD_MISSING",description:"A required field was not provided in the request",category:"validation",httpStatus:400,logLevel:"warn"},INVALID_FORMAT:{code:"VAL-003",name:"INVALID_FORMAT",description:"Field value does not match expected format",category:"validation",httpStatus:400,logLevel:"warn"},NOT_FOUND:{code:"DB-001-NF",name:"NOT_FOUND",description:"The requested resource could not be found",category:"database",httpStatus:404,logLevel:"info",action:"Verify the resource identifier exists before accessing"},DUPLICATE_KEY:{code:"DB-002-DUP",name:"DUPLICATE_KEY",description:"A unique constraint violation occurred",category:"database",httpStatus:409,logLevel:"warn",action:"Check if the resource already exists before creation"},RESOURCE_LOCKED:{code:"DB-003-LOCK",name:"RESOURCE_LOCKED",description:"The resource is currently locked by another operation",category:"database",httpStatus:409,logLevel:"warn",action:"Retry the operation after a brief delay"},PERMISSION_DENIED:{code:"AUTH-001-DENIED",name:"PERMISSION_DENIED",description:"The authenticated user lacks permission for this operation",category:"auth",httpStatus:403,logLevel:"warn",action:"Check user roles and permissions"},UNAUTHENTICATED:{code:"AUTH-002-UNAUTH",name:"UNAUTHENTICATED",description:"Authentication is required for this operation",category:"auth",httpStatus:401,logLevel:"info",action:"Provide valid authentication credentials"},INVALID_COMMAND:{code:"BUS-001",name:"INVALID_COMMAND",description:"The command or operation is invalid for the current state",category:"business",httpStatus:400,logLevel:"warn"},OPERATION_ABORTED:{code:"BUS-002-ABORT",name:"OPERATION_ABORTED",description:"The operation was explicitly aborted",category:"business",httpStatus:409,logLevel:"info"},INTERNAL_ERROR:{code:"SYS-001",name:"INTERNAL_ERROR",description:"An unexpected internal error occurred",category:"system",httpStatus:500,logLevel:"error",action:"Check system logs for stack traces and diagnostic information"},BACKEND_ERROR:{code:"SYS-002",name:"BACKEND_ERROR",description:"An error occurred in a backend service",category:"system",httpStatus:502,logLevel:"error"},CONCURRENCY_ERROR:{code:"CON-001",name:"CONCURRENCY_ERROR",description:"A concurrency conflict occurred during the operation",category:"concurrency",httpStatus:409,logLevel:"warn",action:"Retry the operation with updated data"}},t=new Map(Object.values(e).map(e=>[e.code,e])),s=new Map;function r(e){const r=t.get(e);if(r)return r;const a=s.get(e);return a||{code:e,name:e.replace(/-/g,"_"),description:`Unknown error: ${e}`,category:"custom",httpStatus:500,logLevel:"error",action:"Check if this error code is properly registered or handle as unknown error"}}var a=class e extends Error{code;codeMetadata;severity;path;operation;issues;cause;timestamp;constructor(t){const s={...r(t.code),...t.metadata,code:t.code};super(t.message??s.description),this.name="SystemError",this.code=t.code,this.codeMetadata=s,this.severity=t.severity??"error",this.path=t.path,this.operation=t.operation,this.issues=t.issues??[],this.cause=t.cause,this.timestamp=(new Date).toISOString(),Object.setPrototypeOf(this,e.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,e)}withPath(t){return new e({code:this.code,message:this.message,severity:this.severity,operation:this.operation,issues:this.issues,cause:this.cause,path:t,metadata:this.codeMetadata})}withOperation(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,issues:this.issues,cause:this.cause,operation:t,metadata:this.codeMetadata})}withIssue(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,cause:this.cause,issues:[...this.issues,t],metadata:this.codeMetadata})}withIssues(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,cause:this.cause,issues:[...this.issues,...t],metadata:this.codeMetadata})}withCause(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:this.issues,cause:t,metadata:this.codeMetadata})}getHttpStatus(){return this.codeMetadata.httpStatus}extractChronologicalTrace(e){if(!e)return[];if(e instanceof AggregateError||Array.isArray(e)){return[{type:"parallel",tracks:(Array.isArray(e)?e:e.errors).map(e=>this.extractChronologicalTrace(e))}]}if(!(e instanceof Error)&&"object"==typeof e&&null!==e){const t=Object.keys(e);if(1===t.length&&"object"==typeof e[t[0]])return this.extractChronologicalTrace(e[t[0]])}const t={operation:e?.operation||e?.code||(e instanceof Error?e.name:"UnknownError"),message:e instanceof Error?e.message:"object"==typeof e&&null!==e?JSON.stringify(e):String(e)};e?.code&&(t.code=e.code),e?.codeMetadata?.category&&(t.category=e.codeMetadata.category);const s=e?.cause;if(s){return[...this.extractChronologicalTrace(s),t]}return[t]}toJSON(){const e=this.extractChronologicalTrace(this.cause);return e.push({operation:this.operation||this.code||this.name,message:this.message,code:this.code,category:this.codeMetadata.category}),{name:this.name,code:this.code,message:this.message,severity:this.severity,category:this.codeMetadata.category,httpStatus:this.codeMetadata.httpStatus,operation:this.operation,path:this.path,issues:this.issues.length>0?this.issues:void 0,trace:e,action:this.codeMetadata.action,timestamp:this.timestamp,stack:this.stack}}toLogEntry(){return this.toJSON()}toString(){let e=`[${this.code}] ${this.message} (${this.codeMetadata.category})`;return this.path&&(e+=` at '${this.path}'`),this.operation&&(e+=` during '${this.operation}'`),this.issues.length>0&&(e+="\nIssues:\n"+this.issues.map((e,t)=>` ${t+1}. ${e.message} [${e.code}]`).join("\n")),e}};var o={NOT_FOUND:"DB-001-NF",DUPLICATE_KEY:"DB-002-DUP",INVALID_COMMAND:"BUS-001",PERMISSION_DENIED:"AUTH-001-DENIED",BACKEND_ERROR:"SYS-002",INTERNAL_ERROR:"SYS-001",VALIDATION_FAILED:"VAL-001",CONCURRENCY_ERROR:"CON-001",RESOURCE_LOCKED:"DB-003-LOCK",OPERATION_ABORTED:"BUS-002-ABORT"},i={notFound:(e,t)=>new a({code:o.NOT_FOUND,message:t,path:e}),duplicateKey:(e,t)=>new a({code:o.DUPLICATE_KEY,message:t,path:e}),permissionDenied:(e,t)=>new a({code:o.PERMISSION_DENIED,message:t,operation:e}),validationFailed:(e,t)=>new a({code:o.VALIDATION_FAILED,issues:e,path:t}),internalError:(e,t)=>new a({code:o.INTERNAL_ERROR,message:t,cause:e})};exports.CommonErrors=o,exports.ErrorCodes=e,exports.Errors=i,exports.Result={ok:e=>({ok:!0,value:e}),fail:e=>({ok:!1,error:e})},exports.SystemError=a,exports.createError=function(e,t){return new a({code:e,message:t})},exports.error=function(e,t){return new a({code:e,message:t})},exports.getErrorMetadata=r,exports.isKnownErrorCode=function(e){return t.has(e)||s.has(e)},exports.registerErrorCode=function(e){if(t.has(e.code))throw new Error(`Cannot register custom error code "${e.code}": already exists as built-in error`);if(s.has(e.code))throw new Error(`Custom error code "${e.code}" is already registered`);s.set(e.code,e)};
package/index.mjs CHANGED
@@ -1 +1 @@
1
- var e={VALIDATION_FAILED:{code:"VAL-001",name:"VALIDATION_FAILED",description:"Input validation failed due to one or more invalid fields",category:"validation",httpStatus:400,logLevel:"warn"},REQUIRED_FIELD_MISSING:{code:"VAL-002",name:"REQUIRED_FIELD_MISSING",description:"A required field was not provided in the request",category:"validation",httpStatus:400,logLevel:"warn"},INVALID_FORMAT:{code:"VAL-003",name:"INVALID_FORMAT",description:"Field value does not match expected format",category:"validation",httpStatus:400,logLevel:"warn"},NOT_FOUND:{code:"DB-001-NF",name:"NOT_FOUND",description:"The requested resource could not be found",category:"database",httpStatus:404,logLevel:"info",action:"Verify the resource identifier exists before accessing"},DUPLICATE_KEY:{code:"DB-002-DUP",name:"DUPLICATE_KEY",description:"A unique constraint violation occurred",category:"database",httpStatus:409,logLevel:"warn",action:"Check if the resource already exists before creation"},RESOURCE_LOCKED:{code:"DB-003-LOCK",name:"RESOURCE_LOCKED",description:"The resource is currently locked by another operation",category:"database",httpStatus:409,logLevel:"warn",action:"Retry the operation after a brief delay"},PERMISSION_DENIED:{code:"AUTH-001-DENIED",name:"PERMISSION_DENIED",description:"The authenticated user lacks permission for this operation",category:"auth",httpStatus:403,logLevel:"warn",action:"Check user roles and permissions"},UNAUTHENTICATED:{code:"AUTH-002-UNAUTH",name:"UNAUTHENTICATED",description:"Authentication is required for this operation",category:"auth",httpStatus:401,logLevel:"info",action:"Provide valid authentication credentials"},INVALID_COMMAND:{code:"BUS-001",name:"INVALID_COMMAND",description:"The command or operation is invalid for the current state",category:"business",httpStatus:400,logLevel:"warn"},OPERATION_ABORTED:{code:"BUS-002-ABORT",name:"OPERATION_ABORTED",description:"The operation was explicitly aborted",category:"business",httpStatus:409,logLevel:"info"},INTERNAL_ERROR:{code:"SYS-001",name:"INTERNAL_ERROR",description:"An unexpected internal error occurred",category:"system",httpStatus:500,logLevel:"error",action:"Check system logs for stack traces and diagnostic information"},BACKEND_ERROR:{code:"SYS-002",name:"BACKEND_ERROR",description:"An error occurred in a backend service",category:"system",httpStatus:502,logLevel:"error"},CONCURRENCY_ERROR:{code:"CON-001",name:"CONCURRENCY_ERROR",description:"A concurrency conflict occurred during the operation",category:"concurrency",httpStatus:409,logLevel:"warn",action:"Retry the operation with updated data"}},t=new Map;function s(s){if(Object.values(e).find(e=>e.code===s.code))throw new Error(`Cannot register custom error code "${s.code}": already exists as built-in error`);if(t.has(s.code))throw new Error(`Custom error code "${s.code}" is already registered`);t.set(s.code,s)}function a(s){const a=Object.values(e).find(e=>e.code===s);if(a)return a;const o=t.get(s);return o||{code:s,name:s.replace(/-/g,"_"),description:`Unknown error: ${s}`,category:"custom",httpStatus:500,logLevel:"error",action:"Check if this error code is properly registered or handle as unknown error"}}function o(s){return Object.values(e).some(e=>e.code===s)||t.has(s)}var r=class e extends Error{code;codeMetadata;severity;path;operation;issues;cause;constructor(t){const s={...a(t.code),...t.metadata,code:t.code};super(t.message??s.description),this.name="SystemError",this.code=t.code,this.codeMetadata=s,this.severity=t.severity??"error",this.path=t.path,this.operation=t.operation,this.issues=t.issues??[],this.cause=t.cause,Object.setPrototypeOf(this,e.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,e)}withPath(t){return new e({code:this.code,message:this.message,severity:this.severity,path:t,operation:this.operation,issues:this.issues,cause:this.cause,metadata:this.codeMetadata})}withOperation(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:t,issues:this.issues,cause:this.cause,metadata:this.codeMetadata})}withIssue(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:[...this.issues,t],cause:this.cause,metadata:this.codeMetadata})}withIssues(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:[...this.issues,...t],cause:this.cause,metadata:this.codeMetadata})}withCause(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:this.issues,cause:t,metadata:this.codeMetadata})}getHttpStatus(){return this.codeMetadata.httpStatus}extractChronologicalChain(e){if(!e)return[];if(Array.isArray(e))return e.flatMap(e=>this.extractChronologicalChain(e));if(e instanceof AggregateError)return e.errors.flatMap(e=>this.extractChronologicalChain(e));let t={name:e instanceof Error?e.name:"UnknownError",message:e instanceof Error?e.message:"object"==typeof e&&null!==e?JSON.stringify(e):String(e),code:e?.code,operation:e?.operation};if(!(e instanceof Error)&&"object"==typeof e&&null!==e){const t=Object.keys(e);if(1===t.length&&"object"==typeof e[t[0]])return this.extractChronologicalChain(e[t[0]])}const s=e?.cause;return s?[...this.extractChronologicalChain(s),t]:[t]}toLogEntry(){const e=this.extractChronologicalChain(this.cause);e.push({name:this.name,message:this.message,code:this.code,operation:this.operation});const t=e.map(e=>`${e.operation||e.code||e.name} (${e.message})`).join(" --\x3e ");return{name:this.name,code:this.code,category:this.codeMetadata.category,severity:this.severity,message:`${this.message} | Failure Path: ${t}`,operation:this.operation,path:this.path,issues:this.issues,history:e,stack:this.stack,timestamp:(new Date).toISOString()}}serializeCause(e){return e?Array.isArray(e)?e.map(e=>this.serializeCause(e)):e instanceof AggregateError?{name:e.name,message:e.message,errors:e.errors.map(e=>this.serializeCause(e)),stack:e.stack}:e instanceof Error?"function"==typeof e.toJSON?e.toJSON():{name:e.name,message:e.message,stack:e.stack}:e:e}toJSON(){return{name:this.name,code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,codeMetadata:this.codeMetadata,issues:this.issues,cause:this.serializeCause(this.cause)}}toString(){let e=`[${this.code}] ${this.message} (${this.codeMetadata.category})`;return this.path&&(e+=` at '${this.path}'`),this.operation&&(e+=` during '${this.operation}'`),this.issues.length>0&&(e+="\nIssues:\n"+this.issues.map((e,t)=>` ${t+1}. ${e.message} [${e.code}]`).join("\n")),this.cause&&(e+=`\nCause: ${this.cause instanceof Error?this.cause.message:String(this.cause)}`),e}};function i(e,t){return new r({code:e,message:t})}function n(e,t){return new r({code:e,message:t})}var c={NOT_FOUND:"DB-001-NF",DUPLICATE_KEY:"DB-002-DUP",INVALID_COMMAND:"BUS-001",PERMISSION_DENIED:"AUTH-001-DENIED",BACKEND_ERROR:"SYS-002",INTERNAL_ERROR:"SYS-001",VALIDATION_FAILED:"VAL-001",CONCURRENCY_ERROR:"CON-001",RESOURCE_LOCKED:"DB-003-LOCK",OPERATION_ABORTED:"BUS-002-ABORT"},h={notFound:(e,t)=>new r({code:c.NOT_FOUND,message:t,path:e}),duplicateKey:(e,t)=>new r({code:c.DUPLICATE_KEY,message:t,path:e}),permissionDenied:(e,t)=>new r({code:c.PERMISSION_DENIED,message:t,operation:e}),validationFailed:(e,t)=>new r({code:c.VALIDATION_FAILED,issues:e,path:t}),internalError:(e,t)=>new r({code:c.INTERNAL_ERROR,message:t,cause:e})},d={ok:e=>({ok:!0,value:e}),fail:e=>({ok:!1,error:e})};export{c as CommonErrors,e as ErrorCodes,h as Errors,d as Result,r as SystemError,i as createError,n as error,a as getErrorMetadata,o as isKnownErrorCode,s as registerErrorCode};
1
+ var e={VALIDATION_FAILED:{code:"VAL-001",name:"VALIDATION_FAILED",description:"Input validation failed due to one or more invalid fields",category:"validation",httpStatus:400,logLevel:"warn"},REQUIRED_FIELD_MISSING:{code:"VAL-002",name:"REQUIRED_FIELD_MISSING",description:"A required field was not provided in the request",category:"validation",httpStatus:400,logLevel:"warn"},INVALID_FORMAT:{code:"VAL-003",name:"INVALID_FORMAT",description:"Field value does not match expected format",category:"validation",httpStatus:400,logLevel:"warn"},NOT_FOUND:{code:"DB-001-NF",name:"NOT_FOUND",description:"The requested resource could not be found",category:"database",httpStatus:404,logLevel:"info",action:"Verify the resource identifier exists before accessing"},DUPLICATE_KEY:{code:"DB-002-DUP",name:"DUPLICATE_KEY",description:"A unique constraint violation occurred",category:"database",httpStatus:409,logLevel:"warn",action:"Check if the resource already exists before creation"},RESOURCE_LOCKED:{code:"DB-003-LOCK",name:"RESOURCE_LOCKED",description:"The resource is currently locked by another operation",category:"database",httpStatus:409,logLevel:"warn",action:"Retry the operation after a brief delay"},PERMISSION_DENIED:{code:"AUTH-001-DENIED",name:"PERMISSION_DENIED",description:"The authenticated user lacks permission for this operation",category:"auth",httpStatus:403,logLevel:"warn",action:"Check user roles and permissions"},UNAUTHENTICATED:{code:"AUTH-002-UNAUTH",name:"UNAUTHENTICATED",description:"Authentication is required for this operation",category:"auth",httpStatus:401,logLevel:"info",action:"Provide valid authentication credentials"},INVALID_COMMAND:{code:"BUS-001",name:"INVALID_COMMAND",description:"The command or operation is invalid for the current state",category:"business",httpStatus:400,logLevel:"warn"},OPERATION_ABORTED:{code:"BUS-002-ABORT",name:"OPERATION_ABORTED",description:"The operation was explicitly aborted",category:"business",httpStatus:409,logLevel:"info"},INTERNAL_ERROR:{code:"SYS-001",name:"INTERNAL_ERROR",description:"An unexpected internal error occurred",category:"system",httpStatus:500,logLevel:"error",action:"Check system logs for stack traces and diagnostic information"},BACKEND_ERROR:{code:"SYS-002",name:"BACKEND_ERROR",description:"An error occurred in a backend service",category:"system",httpStatus:502,logLevel:"error"},CONCURRENCY_ERROR:{code:"CON-001",name:"CONCURRENCY_ERROR",description:"A concurrency conflict occurred during the operation",category:"concurrency",httpStatus:409,logLevel:"warn",action:"Retry the operation with updated data"}},t=new Map(Object.values(e).map(e=>[e.code,e])),s=new Map;function a(e){if(t.has(e.code))throw new Error(`Cannot register custom error code "${e.code}": already exists as built-in error`);if(s.has(e.code))throw new Error(`Custom error code "${e.code}" is already registered`);s.set(e.code,e)}function o(e){const a=t.get(e);if(a)return a;const o=s.get(e);return o||{code:e,name:e.replace(/-/g,"_"),description:`Unknown error: ${e}`,category:"custom",httpStatus:500,logLevel:"error",action:"Check if this error code is properly registered or handle as unknown error"}}function r(e){return t.has(e)||s.has(e)}var i=class e extends Error{code;codeMetadata;severity;path;operation;issues;cause;timestamp;constructor(t){const s={...o(t.code),...t.metadata,code:t.code};super(t.message??s.description),this.name="SystemError",this.code=t.code,this.codeMetadata=s,this.severity=t.severity??"error",this.path=t.path,this.operation=t.operation,this.issues=t.issues??[],this.cause=t.cause,this.timestamp=(new Date).toISOString(),Object.setPrototypeOf(this,e.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,e)}withPath(t){return new e({code:this.code,message:this.message,severity:this.severity,operation:this.operation,issues:this.issues,cause:this.cause,path:t,metadata:this.codeMetadata})}withOperation(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,issues:this.issues,cause:this.cause,operation:t,metadata:this.codeMetadata})}withIssue(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,cause:this.cause,issues:[...this.issues,t],metadata:this.codeMetadata})}withIssues(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,cause:this.cause,issues:[...this.issues,...t],metadata:this.codeMetadata})}withCause(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:this.issues,cause:t,metadata:this.codeMetadata})}getHttpStatus(){return this.codeMetadata.httpStatus}extractChronologicalTrace(e){if(!e)return[];if(e instanceof AggregateError||Array.isArray(e)){return[{type:"parallel",tracks:(Array.isArray(e)?e:e.errors).map(e=>this.extractChronologicalTrace(e))}]}if(!(e instanceof Error)&&"object"==typeof e&&null!==e){const t=Object.keys(e);if(1===t.length&&"object"==typeof e[t[0]])return this.extractChronologicalTrace(e[t[0]])}const t={operation:e?.operation||e?.code||(e instanceof Error?e.name:"UnknownError"),message:e instanceof Error?e.message:"object"==typeof e&&null!==e?JSON.stringify(e):String(e)};e?.code&&(t.code=e.code),e?.codeMetadata?.category&&(t.category=e.codeMetadata.category);const s=e?.cause;if(s){return[...this.extractChronologicalTrace(s),t]}return[t]}toJSON(){const e=this.extractChronologicalTrace(this.cause);return e.push({operation:this.operation||this.code||this.name,message:this.message,code:this.code,category:this.codeMetadata.category}),{name:this.name,code:this.code,message:this.message,severity:this.severity,category:this.codeMetadata.category,httpStatus:this.codeMetadata.httpStatus,operation:this.operation,path:this.path,issues:this.issues.length>0?this.issues:void 0,trace:e,action:this.codeMetadata.action,timestamp:this.timestamp,stack:this.stack}}toLogEntry(){return this.toJSON()}toString(){let e=`[${this.code}] ${this.message} (${this.codeMetadata.category})`;return this.path&&(e+=` at '${this.path}'`),this.operation&&(e+=` during '${this.operation}'`),this.issues.length>0&&(e+="\nIssues:\n"+this.issues.map((e,t)=>` ${t+1}. ${e.message} [${e.code}]`).join("\n")),e}};function n(e,t){return new i({code:e,message:t})}function c(e,t){return new i({code:e,message:t})}var h={NOT_FOUND:"DB-001-NF",DUPLICATE_KEY:"DB-002-DUP",INVALID_COMMAND:"BUS-001",PERMISSION_DENIED:"AUTH-001-DENIED",BACKEND_ERROR:"SYS-002",INTERNAL_ERROR:"SYS-001",VALIDATION_FAILED:"VAL-001",CONCURRENCY_ERROR:"CON-001",RESOURCE_LOCKED:"DB-003-LOCK",OPERATION_ABORTED:"BUS-002-ABORT"},d={notFound:(e,t)=>new i({code:h.NOT_FOUND,message:t,path:e}),duplicateKey:(e,t)=>new i({code:h.DUPLICATE_KEY,message:t,path:e}),permissionDenied:(e,t)=>new i({code:h.PERMISSION_DENIED,message:t,operation:e}),validationFailed:(e,t)=>new i({code:h.VALIDATION_FAILED,issues:e,path:t}),internalError:(e,t)=>new i({code:h.INTERNAL_ERROR,message:t,cause:e})},u={ok:e=>({ok:!0,value:e}),fail:e=>({ok:!1,error:e})};export{h as CommonErrors,e as ErrorCodes,d as Errors,u as Result,i as SystemError,n as createError,c as error,o as getErrorMetadata,r as isKnownErrorCode,a as registerErrorCode};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asaidimu/utils-error",
3
- "version": "1.1.1",
3
+ "version": "1.1.2",
4
4
  "description": "A collection of error utilities.",
5
5
  "main": "index.js",
6
6
  "module": "index.mjs",