@zudojs/errors 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +9 -2
  2. package/dist/base/core/baseError.core.d.ts +18 -4
  3. package/dist/base/core/baseError.core.js +31 -46
  4. package/dist/base/core/baseError.serialize.d.ts +53 -0
  5. package/dist/base/core/baseError.serialize.js +109 -0
  6. package/dist/base/core/errorCause.redact.d.ts +20 -0
  7. package/dist/base/core/errorCause.redact.js +64 -0
  8. package/dist/base/types/errorCode.type.d.ts +10 -1
  9. package/dist/base/types/errorCode.type.js +11 -0
  10. package/dist/domain/access/authError.base.d.ts +25 -0
  11. package/dist/domain/access/authError.base.js +26 -0
  12. package/dist/domain/access/index.d.ts +2 -0
  13. package/dist/domain/access/index.js +2 -0
  14. package/dist/domain/access/oauthError.base.d.ts +24 -0
  15. package/dist/domain/access/oauthError.base.js +30 -0
  16. package/dist/domain/cli/cliError.base.d.ts +24 -0
  17. package/dist/domain/cli/cliError.base.js +34 -0
  18. package/dist/domain/cli/index.d.ts +7 -0
  19. package/dist/domain/cli/index.js +7 -0
  20. package/dist/domain/constant/constantError.base.d.ts +21 -0
  21. package/dist/domain/constant/constantError.base.js +31 -0
  22. package/dist/domain/constant/index.d.ts +7 -0
  23. package/dist/domain/constant/index.js +7 -0
  24. package/dist/domain/cqrs/cqrsError.base.d.ts +14 -0
  25. package/dist/domain/cqrs/cqrsError.base.js +26 -0
  26. package/dist/domain/cqrs/index.d.ts +7 -0
  27. package/dist/domain/cqrs/index.js +7 -0
  28. package/dist/domain/index.d.ts +6 -0
  29. package/dist/domain/index.js +6 -0
  30. package/dist/domain/openapi/index.d.ts +7 -0
  31. package/dist/domain/openapi/index.js +7 -0
  32. package/dist/domain/openapi/openApiError.base.d.ts +20 -0
  33. package/dist/domain/openapi/openApiError.base.js +24 -0
  34. package/dist/domain/schema/schemaError.base.js +1 -1
  35. package/dist/domain/shared/domainError.helpers.d.ts +3 -2
  36. package/dist/domain/shared/domainError.helpers.js +32 -8
  37. package/dist/domain/state/validationError.base.d.ts +4 -3
  38. package/dist/domain/state/validationError.base.js +5 -4
  39. package/dist/domain/transaction/index.d.ts +10 -0
  40. package/dist/domain/transaction/index.js +10 -0
  41. package/dist/domain/transaction/transactionError.base.d.ts +18 -0
  42. package/dist/domain/transaction/transactionError.base.js +21 -0
  43. package/dist/domain/transaction/transactionError.misc.d.ts +26 -0
  44. package/dist/domain/transaction/transactionError.misc.js +47 -0
  45. package/dist/domain/transaction/transactionError.types.d.ts +33 -0
  46. package/dist/domain/transaction/transactionError.types.js +62 -0
  47. package/dist/domain/traversal/index.d.ts +7 -0
  48. package/dist/domain/traversal/index.js +7 -0
  49. package/dist/domain/traversal/traversalLimit.error.d.ts +37 -0
  50. package/dist/domain/traversal/traversalLimit.error.js +39 -0
  51. package/dist/infrastructure/httpPipeline/httpMiddleware.error.d.ts +26 -0
  52. package/dist/infrastructure/httpPipeline/httpMiddleware.error.js +43 -0
  53. package/dist/infrastructure/httpPipeline/httpRequestGuard.error.d.ts +21 -0
  54. package/dist/infrastructure/httpPipeline/httpRequestGuard.error.js +28 -0
  55. package/dist/infrastructure/httpPipeline/index.d.ts +8 -0
  56. package/dist/infrastructure/httpPipeline/index.js +8 -0
  57. package/dist/infrastructure/index.d.ts +1 -0
  58. package/dist/infrastructure/index.js +1 -0
  59. package/dist/infrastructure/middleware/index.d.ts +1 -0
  60. package/dist/infrastructure/middleware/index.js +1 -0
  61. package/dist/infrastructure/middleware/middlewareError.types.d.ts +28 -0
  62. package/dist/infrastructure/middleware/middlewareError.types.js +44 -0
  63. package/dist/system/index.d.ts +1 -0
  64. package/dist/system/index.js +1 -0
  65. package/dist/system/observability/index.d.ts +7 -0
  66. package/dist/system/observability/index.js +7 -0
  67. package/dist/system/observability/observabilityError.base.d.ts +16 -0
  68. package/dist/system/observability/observabilityError.base.js +23 -0
  69. package/dist/utils/errorMapper.mappers.d.ts +1 -1
  70. package/dist/utils/errorSerializer.core.d.ts +10 -2
  71. package/dist/utils/errorSerializer.core.js +30 -76
  72. package/package.json +1 -1
@@ -0,0 +1,7 @@
1
+ /**
2
+ * @zudojs/errors/domain/traversal
3
+ *
4
+ * Bounded-traversal limit errors (depth, budget, cycle).
5
+ */
6
+ export * from "./traversalLimit.error.js";
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,7 @@
1
+ /**
2
+ * @zudojs/errors/domain/traversal
3
+ *
4
+ * Bounded-traversal limit errors (depth, budget, cycle).
5
+ */
6
+ export * from "./traversalLimit.error.js";
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Error raised when a bounded object-graph traversal stops early.
3
+ */
4
+ import { BaseError } from "../../base/core/baseError.core.js";
5
+ import { ErrorCategory } from "../../base/types/errorCategory.type.js";
6
+ import { ErrorSeverity } from "../../base/types/errorSeverity.type.js";
7
+ import type { ErrorMetadata } from "../../base/core/errorMetadata.type.js";
8
+ /** Why a traversal stopped early. */
9
+ export type TraversalHalt = "depth" | "budget" | "cycle";
10
+ /**
11
+ * Signals that a traversal hit one of its bounds (depth, cost budget or a
12
+ * cycle). Constructor matches the class `@zudojs/validation` defined
13
+ * locally; not exposed, because `path` can contain submitted keys.
14
+ */
15
+ export declare class TraversalLimitError extends BaseError {
16
+ readonly halt: TraversalHalt;
17
+ readonly path: string;
18
+ readonly observed: number;
19
+ constructor(halt: TraversalHalt, path: string, observed: number);
20
+ toJSON(): {
21
+ name: string;
22
+ message: string;
23
+ code: string;
24
+ category: ErrorCategory;
25
+ severity: ErrorSeverity;
26
+ statusCode: number;
27
+ expose: boolean;
28
+ isOperational: boolean;
29
+ metadata: Readonly<ErrorMetadata>;
30
+ stack?: string;
31
+ cause?: import("../../index.js").SerializedBaseError | unknown;
32
+ halt: TraversalHalt;
33
+ path: string;
34
+ observed: number;
35
+ };
36
+ }
37
+ //# sourceMappingURL=traversalLimit.error.d.ts.map
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Error raised when a bounded object-graph traversal stops early.
3
+ */
4
+ import { BaseError } from "../../base/core/baseError.core.js";
5
+ import { ErrorCategory } from "../../base/types/errorCategory.type.js";
6
+ import { ErrorCode } from "../../base/types/errorCode.type.js";
7
+ import { ErrorSeverity } from "../../base/types/errorSeverity.type.js";
8
+ /**
9
+ * Signals that a traversal hit one of its bounds (depth, cost budget or a
10
+ * cycle). Constructor matches the class `@zudojs/validation` defined
11
+ * locally; not exposed, because `path` can contain submitted keys.
12
+ */
13
+ export class TraversalLimitError extends BaseError {
14
+ halt;
15
+ path;
16
+ observed;
17
+ constructor(halt, path, observed) {
18
+ super(`Traversal halted (${halt}) at ${path}`, {
19
+ code: ErrorCode.VALIDATION_FAILED,
20
+ category: ErrorCategory.VALIDATION,
21
+ severity: ErrorSeverity.WARNING,
22
+ statusCode: 400,
23
+ expose: false,
24
+ metadata: { halt, observed },
25
+ });
26
+ this.halt = halt;
27
+ this.path = path;
28
+ this.observed = observed;
29
+ }
30
+ toJSON() {
31
+ return {
32
+ ...super.toJSON(),
33
+ halt: this.halt,
34
+ path: this.path,
35
+ observed: this.observed,
36
+ };
37
+ }
38
+ }
39
+ //# sourceMappingURL=traversalLimit.error.js.map
@@ -0,0 +1,26 @@
1
+ /**
2
+ * HTTP middleware pipeline errors. Names, codes and constructors match the
3
+ * classes `@zudojs/http` defined locally.
4
+ */
5
+ import { BaseError } from "../../base/core/baseError.core.js";
6
+ /** Options accepted by {@link HttpMiddlewareError}. */
7
+ export interface HttpMiddlewareErrorOptions {
8
+ readonly middlewareId?: string;
9
+ readonly middlewareName?: string;
10
+ readonly cause?: unknown;
11
+ }
12
+ /** Error raised by an HTTP middleware function (500, not exposed). */
13
+ export declare class HttpMiddlewareError extends BaseError {
14
+ /** The unique identifier of the middleware. */
15
+ readonly middlewareId: string | undefined;
16
+ /** The name of the middleware. */
17
+ readonly middlewareName: string | undefined;
18
+ constructor(message: string, options?: HttpMiddlewareErrorOptions);
19
+ }
20
+ /** Error raised when the HTTP middleware pipeline fails. */
21
+ export declare class HttpMiddlewarePipelineError extends BaseError {
22
+ /** The errors that occurred during pipeline execution. */
23
+ readonly errors: readonly HttpMiddlewareError[];
24
+ constructor(errors: readonly HttpMiddlewareError[]);
25
+ }
26
+ //# sourceMappingURL=httpMiddleware.error.d.ts.map
@@ -0,0 +1,43 @@
1
+ /**
2
+ * HTTP middleware pipeline errors. Names, codes and constructors match the
3
+ * classes `@zudojs/http` defined locally.
4
+ */
5
+ import { BaseError } from "../../base/core/baseError.core.js";
6
+ /** Error raised by an HTTP middleware function (500, not exposed). */
7
+ export class HttpMiddlewareError extends BaseError {
8
+ /** The unique identifier of the middleware. */
9
+ middlewareId;
10
+ /** The name of the middleware. */
11
+ middlewareName;
12
+ constructor(message, options = {}) {
13
+ super(message, {
14
+ code: "HTTP_MIDDLEWARE_ERROR",
15
+ statusCode: 500,
16
+ expose: false,
17
+ cause: options.cause,
18
+ });
19
+ this.name = "HttpMiddlewareError";
20
+ this.middlewareId = options.middlewareId;
21
+ this.middlewareName = options.middlewareName;
22
+ }
23
+ }
24
+ /** Error raised when the HTTP middleware pipeline fails. */
25
+ export class HttpMiddlewarePipelineError extends BaseError {
26
+ /** The errors that occurred during pipeline execution. */
27
+ errors;
28
+ constructor(errors) {
29
+ const message = errors.length === 1
30
+ ? `HTTP middleware pipeline failed: ${errors[0]?.message ?? "Unknown error"}`
31
+ : `HTTP middleware pipeline failed with ${errors.length} errors: ${errors
32
+ .map((e) => e.message)
33
+ .join(", ")}`;
34
+ super(message, {
35
+ code: "MIDDLEWARE_PIPELINE_ERROR",
36
+ statusCode: 500,
37
+ expose: false,
38
+ });
39
+ this.name = "HttpMiddlewarePipelineError";
40
+ this.errors = Object.freeze([...errors]);
41
+ }
42
+ }
43
+ //# sourceMappingURL=httpMiddleware.error.js.map
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Error thrown when an HTTP request security guard rejects a request.
3
+ */
4
+ import { BaseError } from "../../base/core/baseError.core.js";
5
+ /** The parts of a guard verdict this error records. */
6
+ export interface HttpRequestGuardRejection {
7
+ /** Status the response should use (400-499). */
8
+ readonly statusCode: number;
9
+ /** Individual validation failures, for logs only. */
10
+ readonly errors: readonly string[];
11
+ }
12
+ /**
13
+ * Carries the status the response should use and the individual failures, so
14
+ * a caller can log the detail without returning it to the client (not
15
+ * exposed). Matches `@zudojs/http`'s local class, which extended `Error`.
16
+ */
17
+ export declare class HttpRequestGuardError extends BaseError {
18
+ readonly errors: readonly string[];
19
+ constructor(result: HttpRequestGuardRejection);
20
+ }
21
+ //# sourceMappingURL=httpRequestGuard.error.d.ts.map
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Error thrown when an HTTP request security guard rejects a request.
3
+ */
4
+ import { BaseError } from "../../base/core/baseError.core.js";
5
+ import { ErrorCategory } from "../../base/types/errorCategory.type.js";
6
+ /**
7
+ * Carries the status the response should use and the individual failures, so
8
+ * a caller can log the detail without returning it to the client (not
9
+ * exposed). Matches `@zudojs/http`'s local class, which extended `Error`.
10
+ */
11
+ export class HttpRequestGuardError extends BaseError {
12
+ errors;
13
+ constructor(result) {
14
+ const errors = Array.isArray(result?.errors) ? [...result.errors] : [];
15
+ const status = result?.statusCode;
16
+ super(`Request rejected by security guard: ${errors.join("; ")}`, {
17
+ code: "HTTP_REQUEST_REJECTED",
18
+ category: ErrorCategory.VALIDATION,
19
+ statusCode: Number.isInteger(status) && status >= 400 && status <= 499
20
+ ? status
21
+ : 400,
22
+ expose: false,
23
+ });
24
+ this.name = "HttpRequestGuardError";
25
+ this.errors = Object.freeze(errors);
26
+ }
27
+ }
28
+ //# sourceMappingURL=httpRequestGuard.error.js.map
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @zudojs/errors/infrastructure/httpPipeline
3
+ *
4
+ * HTTP middleware pipeline and request-guard errors.
5
+ */
6
+ export * from "./httpMiddleware.error.js";
7
+ export * from "./httpRequestGuard.error.js";
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @zudojs/errors/infrastructure/httpPipeline
3
+ *
4
+ * HTTP middleware pipeline and request-guard errors.
5
+ */
6
+ export * from "./httpMiddleware.error.js";
7
+ export * from "./httpRequestGuard.error.js";
8
+ //# sourceMappingURL=index.js.map
@@ -10,4 +10,5 @@ export * from "./container/index.js";
10
10
  export * from "./cache/index.js";
11
11
  export * from "./middleware/index.js";
12
12
  export * from "./adapter/index.js";
13
+ export * from "./httpPipeline/index.js";
13
14
  //# sourceMappingURL=index.d.ts.map
@@ -10,4 +10,5 @@ export * from "./container/index.js";
10
10
  export * from "./cache/index.js";
11
11
  export * from "./middleware/index.js";
12
12
  export * from "./adapter/index.js";
13
+ export * from "./httpPipeline/index.js";
13
14
  //# sourceMappingURL=index.js.map
@@ -4,4 +4,5 @@
4
4
  * Middleware error types.
5
5
  */
6
6
  export * from "./middleware.error.js";
7
+ export * from "./middlewareError.types.js";
7
8
  //# sourceMappingURL=index.d.ts.map
@@ -4,4 +4,5 @@
4
4
  * Middleware error types.
5
5
  */
6
6
  export * from "./middleware.error.js";
7
+ export * from "./middlewareError.types.js";
7
8
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Pipeline-guard middleware errors. Constructors and defaults match the
3
+ * wrappers `@zudojs/middleware` defines over the shared `MiddlewareError`.
4
+ */
5
+ import { MiddlewareError } from "./middleware.error.js";
6
+ /** Error thrown when a pipeline is configured with more middleware than allowed. */
7
+ export declare class MiddlewareLimitExceededError extends MiddlewareError {
8
+ constructor(count: number, maximum: number);
9
+ }
10
+ /** Error thrown when the middleware chain nests deeper than the allowed limit. */
11
+ export declare class MiddlewareDepthExceededError extends MiddlewareError {
12
+ constructor(maxDepth: number);
13
+ }
14
+ /**
15
+ * Error thrown when a rate limit is exceeded. `retryAfterMs` feeds a
16
+ * `Retry-After` header.
17
+ */
18
+ export declare class MiddlewareRateLimitError extends MiddlewareError {
19
+ readonly retryAfterMs: number;
20
+ readonly limit: number;
21
+ readonly windowMs: number;
22
+ constructor(limit: number, windowMs: number, retryAfterMs: number);
23
+ }
24
+ /** Error thrown when a pipeline is aborted through its `AbortSignal`. */
25
+ export declare class MiddlewareAbortedError extends MiddlewareError {
26
+ constructor(reason?: unknown);
27
+ }
28
+ //# sourceMappingURL=middlewareError.types.d.ts.map
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Pipeline-guard middleware errors. Constructors and defaults match the
3
+ * wrappers `@zudojs/middleware` defines over the shared `MiddlewareError`.
4
+ */
5
+ import { MiddlewareError } from "./middleware.error.js";
6
+ /** Error thrown when a pipeline is configured with more middleware than allowed. */
7
+ export class MiddlewareLimitExceededError extends MiddlewareError {
8
+ constructor(count, maximum) {
9
+ super(`Pipeline has ${count} middleware, exceeding the maximum of ${maximum}`, { metadata: { count, maximum } });
10
+ }
11
+ }
12
+ /** Error thrown when the middleware chain nests deeper than the allowed limit. */
13
+ export class MiddlewareDepthExceededError extends MiddlewareError {
14
+ constructor(maxDepth) {
15
+ super(`Middleware chain exceeded the maximum depth of ${maxDepth}`, {
16
+ metadata: { maxDepth },
17
+ });
18
+ }
19
+ }
20
+ /**
21
+ * Error thrown when a rate limit is exceeded. `retryAfterMs` feeds a
22
+ * `Retry-After` header.
23
+ */
24
+ export class MiddlewareRateLimitError extends MiddlewareError {
25
+ retryAfterMs;
26
+ limit;
27
+ windowMs;
28
+ constructor(limit, windowMs, retryAfterMs) {
29
+ super(`Rate limit exceeded: ${limit} requests per ${windowMs}ms`, {
30
+ middlewareName: "rate-limit",
31
+ metadata: { middlewareName: "rate-limit" },
32
+ });
33
+ this.retryAfterMs = retryAfterMs;
34
+ this.limit = limit;
35
+ this.windowMs = windowMs;
36
+ }
37
+ }
38
+ /** Error thrown when a pipeline is aborted through its `AbortSignal`. */
39
+ export class MiddlewareAbortedError extends MiddlewareError {
40
+ constructor(reason) {
41
+ super("Middleware pipeline aborted", { cause: reason });
42
+ }
43
+ }
44
+ //# sourceMappingURL=middlewareError.types.js.map
@@ -7,4 +7,5 @@ export * from "./crypto.error.js";
7
7
  export * from "./system.error.js";
8
8
  export * from "./runtime.error.js";
9
9
  export * from "./logging/index.js";
10
+ export * from "./observability/index.js";
10
11
  //# sourceMappingURL=index.d.ts.map
@@ -7,4 +7,5 @@ export * from "./crypto.error.js";
7
7
  export * from "./system.error.js";
8
8
  export * from "./runtime.error.js";
9
9
  export * from "./logging/index.js";
10
+ export * from "./observability/index.js";
10
11
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ /**
2
+ * @zudojs/errors/system/observability
3
+ *
4
+ * Telemetry (metrics, tracing, exporter) errors.
5
+ */
6
+ export * from "./observabilityError.base.js";
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,7 @@
1
+ /**
2
+ * @zudojs/errors/system/observability
3
+ *
4
+ * Telemetry (metrics, tracing, exporter) errors.
5
+ */
6
+ export * from "./observabilityError.base.js";
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Base observability error: telemetry throws only for programmer errors.
3
+ */
4
+ import { BaseError } from "../../base/core/baseError.core.js";
5
+ import { ErrorCode } from "../../base/types/errorCode.type.js";
6
+ /** Options accepted by {@link ObservabilityError}. */
7
+ export interface ObservabilityErrorOptions {
8
+ readonly code?: ErrorCode;
9
+ readonly metadata?: Readonly<Record<string, unknown>>;
10
+ readonly cause?: unknown;
11
+ }
12
+ /** Base error for all observability failures (500, not exposed). */
13
+ export declare class ObservabilityError extends BaseError {
14
+ constructor(message: string, options?: ObservabilityErrorOptions);
15
+ }
16
+ //# sourceMappingURL=observabilityError.base.d.ts.map
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Base observability error: telemetry throws only for programmer errors.
3
+ */
4
+ import { BaseError } from "../../base/core/baseError.core.js";
5
+ import { ErrorCategory } from "../../base/types/errorCategory.type.js";
6
+ import { ErrorCode } from "../../base/types/errorCode.type.js";
7
+ import { ErrorSeverity } from "../../base/types/errorSeverity.type.js";
8
+ /** Base error for all observability failures (500, not exposed). */
9
+ export class ObservabilityError extends BaseError {
10
+ constructor(message, options) {
11
+ super(message, {
12
+ code: options?.code ?? ErrorCode.OPERATION_FAILED,
13
+ category: ErrorCategory.INTERNAL,
14
+ severity: ErrorSeverity.ERROR,
15
+ statusCode: 500,
16
+ expose: false,
17
+ metadata: options?.metadata,
18
+ cause: options?.cause,
19
+ });
20
+ this.name = "ObservabilityError";
21
+ }
22
+ }
23
+ //# sourceMappingURL=observabilityError.base.js.map
@@ -16,7 +16,7 @@ export declare function mapNativeError(error: unknown): BaseError | undefined;
16
16
  /** Maps an error using a registry and falls back to native error mapping. */
17
17
  export declare function mapError(error: unknown, registry?: ErrorMapperRegistry, context?: ErrorMapperContext): BaseError;
18
18
  /** Any constructor whose instances are `T` (parameters are not constrained). */
19
- export type ErrorConstructor<T extends Error> = abstract new (...args: any[]) => T;
19
+ export type ErrorConstructor<T extends Error> = abstract new (...args: never[]) => T;
20
20
  /**
21
21
  * Creates a mapping rule for a specific error constructor.
22
22
  *
@@ -19,7 +19,8 @@ export declare class ErrorSerializer {
19
19
  * Serializes an error for internal logging or monitoring.
20
20
  *
21
21
  * `includeStack`, `includeCause` and `redactSensitiveData` are applied at
22
- * every level of the cause chain.
22
+ * every level of the cause chain, including array causes and plain-object
23
+ * causes that merely look like a serialized BaseError.
23
24
  */
24
25
  serialize(error: BaseError): InternalErrorResponse;
25
26
  /**
@@ -36,7 +37,14 @@ export declare class ErrorSerializer {
36
37
  serializeUnknownPublic(value: unknown): PublicErrorResponse;
37
38
  /** Applies the serializer options to one level of a serialized error. */
38
39
  private serializeLevel;
39
- /** Applies the serializer options recursively to a serialized cause. */
40
+ /**
41
+ * Applies the serializer options recursively to a serialized cause.
42
+ *
43
+ * Only objects that a BaseError's `toJSON` really produced are treated as
44
+ * serialized BaseErrors (whose `metadata` alone needs redacting). Anything
45
+ * else, including a plain object carrying the same field names and any
46
+ * array, has every field walked and redacted.
47
+ */
40
48
  private serializeCause;
41
49
  /** Computes the metadata allowed in a public response. */
42
50
  private publicMetadata;
@@ -2,7 +2,9 @@
2
2
  * Converts errors into safe, predictable serialized structures.
3
3
  */
4
4
  import { BaseError } from "../base/core/baseError.core.js";
5
- import { isSensitiveMetadataKey, pickErrorMetadata, redactErrorMetadata, REDACTED_METADATA_VALUE, } from "../base/core/errorMetadata.core.js";
5
+ import { pickErrorMetadata, redactErrorMetadata, } from "../base/core/errorMetadata.core.js";
6
+ import { isGenuineSerializedBaseError, MAX_CAUSE_DEPTH, toJSONWithFrame, } from "../base/core/baseError.serialize.js";
7
+ import { redactCauseFields, redactCauseValue, } from "../base/core/errorCause.redact.js";
6
8
  import { normalizeUnknownError } from "./errorSerializer.factory.js";
7
9
  export { createErrorSerializer, serializeError, serializePublicError, normalizeUnknownError, } from "./errorSerializer.factory.js";
8
10
  /** Converts errors into safe, predictable serialized structures. */
@@ -27,10 +29,12 @@ export class ErrorSerializer {
27
29
  * Serializes an error for internal logging or monitoring.
28
30
  *
29
31
  * `includeStack`, `includeCause` and `redactSensitiveData` are applied at
30
- * every level of the cause chain.
32
+ * every level of the cause chain, including array causes and plain-object
33
+ * causes that merely look like a serialized BaseError.
31
34
  */
32
35
  serialize(error) {
33
- return this.serializeLevel(error.toJSON());
36
+ const raw = toJSONWithFrame(error, { depth: 0, redact: false });
37
+ return this.serializeLevel(raw, 0);
34
38
  }
35
39
  /**
36
40
  * Serializes an error for an untrusted API client.
@@ -58,7 +62,7 @@ export class ErrorSerializer {
58
62
  return this.serializePublic(normalizeUnknownError(value));
59
63
  }
60
64
  /** Applies the serializer options to one level of a serialized error. */
61
- serializeLevel(serialized) {
65
+ serializeLevel(serialized, depth) {
62
66
  const { stack, cause, metadata, ...rest } = serialized;
63
67
  const result = {
64
68
  ...rest,
@@ -69,25 +73,33 @@ export class ErrorSerializer {
69
73
  : {},
70
74
  ...(this.includeStack && stack !== undefined ? { stack } : {}),
71
75
  ...(this.includeCause && cause !== undefined
72
- ? { cause: this.serializeCause(cause) }
76
+ ? { cause: this.serializeCause(cause, depth + 1) }
73
77
  : {}),
74
78
  };
75
79
  return result;
76
80
  }
77
- /** Applies the serializer options recursively to a serialized cause. */
78
- serializeCause(cause) {
81
+ /**
82
+ * Applies the serializer options recursively to a serialized cause.
83
+ *
84
+ * Only objects that a BaseError's `toJSON` really produced are treated as
85
+ * serialized BaseErrors (whose `metadata` alone needs redacting). Anything
86
+ * else, including a plain object carrying the same field names and any
87
+ * array, has every field walked and redacted.
88
+ */
89
+ serializeCause(cause, depth) {
90
+ if (depth > MAX_CAUSE_DEPTH)
91
+ return "[MaxDepth]";
79
92
  if (cause === null || typeof cause !== "object")
80
93
  return cause;
81
- if (Array.isArray(cause))
82
- return cause;
94
+ if (Array.isArray(cause)) {
95
+ return this.redactSensitiveData
96
+ ? redactCauseValue(cause, this.sensitiveKeyPattern)
97
+ : cause;
98
+ }
83
99
  const record = cause;
84
- if (isSerializedBaseError(record)) {
85
- return this.serializeLevel(record);
100
+ if (isGenuineSerializedBaseError(record)) {
101
+ return this.serializeLevel(record, depth);
86
102
  }
87
- // Native error shape: { name, message, stack?, cause? } — or an
88
- // arbitrary plain object that was thrown/attached as a cause. The
89
- // latter reaches here by reference and used to be copied verbatim, so
90
- // `redactSensitiveData` did not apply to it.
91
103
  const { stack, cause: nested, ...rest } = record;
92
104
  const fields = this.redactSensitiveData
93
105
  ? redactCauseFields(rest, this.sensitiveKeyPattern, new WeakSet([record]))
@@ -95,7 +107,9 @@ export class ErrorSerializer {
95
107
  return {
96
108
  ...fields,
97
109
  ...(this.includeStack && stack !== undefined ? { stack } : {}),
98
- ...(nested !== undefined ? { cause: this.serializeCause(nested) } : {}),
110
+ ...(nested !== undefined
111
+ ? { cause: this.serializeCause(nested, depth + 1) }
112
+ : {}),
99
113
  };
100
114
  }
101
115
  /** Computes the metadata allowed in a public response. */
@@ -124,64 +138,4 @@ export class ErrorSerializer {
124
138
  });
125
139
  }
126
140
  }
127
- /** Plain objects (Object.prototype or null prototype) are walked; anything else is kept as-is. */
128
- function isPlainRecord(value) {
129
- if (value === null || typeof value !== "object")
130
- return false;
131
- const proto = Object.getPrototypeOf(value);
132
- return proto === Object.prototype || proto === null;
133
- }
134
- /**
135
- * Redacts sensitive keys inside a non-BaseError cause without changing its
136
- * shape: primitives, dates and class instances are kept, plain objects and
137
- * arrays are walked, cycles stop at "[Circular]".
138
- */
139
- function redactCauseFields(fields, pattern, seen = new WeakSet()) {
140
- const result = {};
141
- for (const key of Object.keys(fields)) {
142
- if (key === "__proto__" || key === "constructor" || key === "prototype")
143
- continue;
144
- const value = fields[key];
145
- const sensitive = pattern === undefined
146
- ? isSensitiveMetadataKey(key)
147
- : isSensitiveMetadataKey(key, pattern);
148
- result[key] = sensitive
149
- ? REDACTED_METADATA_VALUE
150
- : redactCauseValue(value, pattern, seen);
151
- }
152
- return result;
153
- }
154
- function redactCauseValue(value, pattern, seen) {
155
- if (Array.isArray(value)) {
156
- if (seen.has(value))
157
- return "[Circular]";
158
- seen.add(value);
159
- try {
160
- return value.map((entry) => redactCauseValue(entry, pattern, seen));
161
- }
162
- finally {
163
- seen.delete(value);
164
- }
165
- }
166
- if (!isPlainRecord(value))
167
- return value;
168
- if (seen.has(value))
169
- return "[Circular]";
170
- seen.add(value);
171
- try {
172
- return redactCauseFields(value, pattern, seen);
173
- }
174
- finally {
175
- seen.delete(value);
176
- }
177
- }
178
- /** Structural check for a serialized BaseError (used on nested causes). */
179
- function isSerializedBaseError(value) {
180
- return (typeof value.code === "string" &&
181
- typeof value.category === "string" &&
182
- typeof value.severity === "string" &&
183
- typeof value.statusCode === "number" &&
184
- typeof value.metadata === "object" &&
185
- value.metadata !== null);
186
- }
187
141
  //# sourceMappingURL=errorSerializer.core.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zudojs/errors",
3
- "version": "1.0.1",
3
+ "version": "1.1.0",
4
4
  "description": "Shared error base class, error codes, and error handling utilities for the Zudojs framework.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",