//#region ../connect-core/build/index-BAgdJKZy.d.mts //#region src/error/utils/packError/packError.enums.d.ts declare enum EErrorPackType { no_pack = "no_pack", msg_pack = "msg_pack", cause_pack = "cause_pack" } //#endregion //#region src/error/NiceError/NiceError.enums.d.ts declare enum EContextSerializedState { serde_unset = "serde_unset", unhydrated = "unhydrated", hydrated = "hydrated" } //#endregion //#region src/error/NiceError/NiceError.types.d.ts interface IRegularErrorJsonObject extends Omit { name: string; message: string; stack?: string | undefined; cause?: unknown; /** Present when the original was an `AggregateError` — its serialized sub-errors. */ errors?: unknown[]; } type JSONSerializableValue = string | number | boolean | null | { [key: string]: JSONSerializableValue; } | JSONSerializableValue[]; interface ISerializationDefinition { toJsonSerializable: (context: C) => D; fromJsonSerializable: (obj: D) => C; } /** Describes the context attached to a single error id. */ interface INiceErrorContextDefinition { required?: boolean; serialization?: ISerializationDefinition; } /** * A single entry in a NiceErrorDomain schema. * `C` is the context value type (defaults to `never` = no context). */ interface INiceErrorIdMetadata { context?: [C] extends [never] ? never : INiceErrorContextDefinition; /** Static message string OR a function that receives the context value and returns a string. */ message?: [C] extends [never] ? string : string | ((context: C) => string); httpStatusCode?: [C] extends [never] ? number : number | ((context: C) => number); } /** A record mapping error-id string keys to their metadata. */ type TNiceErrorSchema = Record>; /** Extracts the raw context value type `C` from a single schema entry. */ type TExtractContextType = M extends INiceErrorIdMetadata ? C : never; /** * Given a schema entry M, returns the context argument type expected by `fromId`: * * - `C = never` → `undefined` (no context field on this id) * - `C` defined, `required: true` → `C` (context is a required argument) * - `C` defined, `required` absent/false → `C | undefined` (context is optional) * * Note: `required: true` must be a literal `true` for TypeScript to narrow correctly. * Use the `err()` helper (which preserves literal types) rather than writing schema * entries inline without `as const`. */ type ExtractFromIdContextArg = M extends INiceErrorIdMetadata ? [C] extends [never] ? undefined : M extends { context: { required: true; }; } ? C : C | undefined : undefined; /** * No custom serializer is defined for this error id's context. * `value` holds the typed context directly (plain JSON-safe value, or `undefined` * if the context was optional and not provided). * * This state is safe across a JSON round-trip because no type information is lost. */ type TContextStateNoSerialization = { kind: EContextSerializedState.serde_unset; /** The typed context value (or `undefined` if optional and not provided). */ value: C | undefined; }; /** * A custom serializer is defined, but the context has **not** been deserialized * from its JSON-wire form yet. * * This state occurs after `castNiceError` reconstructs an error from a serialized * payload. `value` is absent — the raw serialized representation is in `serialized`. * * Call `niceErrorDefined.hydrate(error)` to reconstruct the typed context via * `fromJsonSerializable` and advance to the `"hydrated"` state. */ type TContextStateUnhydrated = { kind: EContextSerializedState.unhydrated; /** The JSON-serializable representation of the original context. */ serialized: JSONSerializableValue; }; /** * A custom serializer is defined, and the context is fully deserialized to its * original typed value. * * This state is set when the error is first created via `fromId`/`fromContext`, * or after `niceErrorDefined.hydrate(error)` reconstructs it. * * Note: `toJsonObject()` intentionally downgrades this to `"unhydrated"` on * output so the flag cannot survive a JSON round-trip as a false positive. */ type TContextStateHydrated = { kind: EContextSerializedState.hydrated; /** The typed context value — the original value as provided at error creation. */ value: C; /** The JSON-serializable representation (produced by `toJsonSerializable`). */ serialized: JSONSerializableValue; }; /** * Runtime context state — union of all three lifecycle states. * Stored in `_errorDataMap` on a live `NiceError` instance. */ type TContextState = TContextStateNoSerialization | TContextStateUnhydrated | TContextStateHydrated; /** * Wire-safe context state — excludes `"hydrated"` because `toJsonObject()` downgrades * it to `"unhydrated"` before serialization. This is the only state that appears in * `INiceErrorJsonObject` and on errors reconstructed via `castNiceError`. */ type TSerializedContextState = TContextStateNoSerialization | TContextStateUnhydrated; /** * Runtime reconciled data for a single error id, stored in `_errorDataMap`. * Uses the full `TContextState` union (including `"hydrated"`). */ type TErrorReconciledData = { contextState: TContextState>; message: string; httpStatusCode: number; timeAdded: number; }; /** * Wire-safe reconciled data — uses `TSerializedContextState` (no `"hydrated"`). * This is the shape stored in `INiceErrorJsonObject.errorData` and transmitted * over the wire. `"hydrated"` is excluded so that the serialization state can * never be trusted after a JSON round-trip. */ type TSerializedErrorReconciledData> = { contextState: TSerializedContextState>; message: string; httpStatusCode: number; timeAdded: number; }; type TErrorDataForIdMap = TSchemaNiceErrorId> = { [key in K]?: TErrorReconciledData; }; /** Wire-safe version of `TErrorDataForIdMap`. Used in `INiceErrorJsonObject`. */ type TSerializedErrorDataMap = { [K in TSchemaNiceErrorId]?: TSerializedErrorReconciledData; }; /** * The Partial record that `fromContext` accepts: callers supply one or more * { [errorId]: contextValue } entries and NiceError stores them all. */ type TFromContextInput = { [K in TSchemaNiceErrorId]?: TExtractContextType | undefined; }; /** * Resolves the args tuple for `fromId` / `addId`: * * - No context on this id → `[id]` * - Context defined, `required: true` → `[id, context]` * - Context defined, `required` absent/false → `[id] | [id, context]` */ type FromIdArgs> = [ExtractFromIdContextArg] extends [undefined] ? [id: K] : [undefined] extends [ExtractFromIdContextArg] ? [id: K] | [id: K, context: NonNullable>] : [id: K, context: ExtractFromIdContextArg]; interface IPackErrorAs_Base { packAs: EErrorPackType; } interface IPackErrorAs_MatchEnvVar extends IPackErrorAs_Base { matchEnvVar: string; } interface IDefineNewNiceErrorDomainOptions { defaultHttpStatusCode?: number; defaultMessage?: string; packAs?: () => EErrorPackType | void; domain: ERR_DOMAIN; schema: SCHEMA; } interface INiceErrorDomainProps { packAs?: () => EErrorPackType | void; defaultHttpStatusCode?: number; defaultMessage?: string; domain: ERR_DOMAINS[number]; allDomains: ERR_DOMAINS; schema: SCHEMA; } interface INiceErrorJsonObject = TDomainNiceErrorId> { name: "NiceError"; def: Omit; ids: ID[]; /** Wire-safe error data — context is in `"raw_unset"` or `"unhydrated"` state only. */ errorData: TSerializedErrorDataMap; /** `true` for the generic `err_cast_not_nice` wrapper; see {@link NiceError.isUnhandled}. */ isUnhandled: boolean; message: string; httpStatusCode: number; /** The stack trace of the NiceError at the point it was created. */ stack?: string; cause?: unknown; originError?: IRegularErrorJsonObject | undefined; timeCreated: number; } /** * Flat, log-friendly projection of a `NiceError` for telemetry / structured logging. * Distinct from `toJsonObject()` (the wire/transport form) — this is for humans and * log pipelines, so it omits wire bookkeeping (errorData/context state) and surfaces * the {@link NiceError.isUnhandled} signal. */ interface INiceErrorStructuredLog { domain: string; ids: string[]; message: string; httpStatusCode: number; isUnhandled: boolean; timeCreated: number; originError?: IRegularErrorJsonObject; } type TSchemaNiceErrorId = keyof SCHEMA & string; type TDomainNiceErrorId = TSchemaNiceErrorId; /** * The widest ERR_DEF used when creating a NiceError without a definition * (bare construction, castNiceError, etc.). * * Uses the base `INiceErrorDomainProps` defaults (`string[]` domains, * `TNiceErrorSchema` schema) so that type-guard narrowing via `is()` works * correctly — `string & "specific_domain"` narrows to `"specific_domain"` * instead of collapsing the intersection to `never`. */ type TUnknownNiceErrorDef = INiceErrorDomainProps; /** * Wide id type for bare / cast NiceErrors that have no schema. * Using `string` (rather than a literal `"unknown"`) ensures that * `is()` type-guard intersections narrow cleanly: `string & K` = `K`. */ type TUnknownNiceErrorId = string; //#endregion //#region src/error/NiceError/NiceErrorHydrated.d.ts /** * Resolves the args tuple for `addId` — mirrors `FromIdArgs` exactly so that * optional vs required context is consistent across both `fromId` and `addId`. * * - No context on this id → `[id]` * - Context defined, `required: true` → `[id, context]` * - Context defined, `required` absent/false → `[id] | [id, context]` */ type AddIdArgs> = [ExtractFromIdContextArg] extends [undefined] ? [id: K] : [undefined] extends [ExtractFromIdContextArg] ? [id: K] | [id: K, context: NonNullable>] : [id: K, context: ExtractFromIdContextArg]; /** Full-featured construction from NiceErrorDomain.fromId / fromContext. */ interface INiceErrorHydratedOptions> extends INiceErrorOptions { def: ERR_DEF; niceErrorDefined: NiceErrorDomain; } declare class NiceErrorHydrated = TDomainNiceErrorId> extends NiceError { readonly def: ERR_DEF; private readonly niceErrorDefined; constructor(options: INiceErrorHydratedOptions); /** * Returns a **new** `NiceErrorHydrated` with additional id+context entries merged in. * The returned error's `ACTIVE_IDS` is the union of the original ids and the * newly supplied keys. * * ```ts * const err = errDef.fromId("id_a", { a: 1 }) * .addContext({ id_b: { b: "x" } }); * err.getIds(); // ["id_a", "id_b"] * ``` */ addContext>(context: INPUT & Record, never>): NiceErrorHydrated; /** * Returns a **new** `NiceErrorHydrated` with an additional error id (and its context, * if the schema requires one). Equivalent to `addContext({ [id]: context })` * but mirrors the `fromId` ergonomics for single-id additions. */ addId>(...args: AddIdArgs): NiceErrorHydrated; } //#endregion //#region src/error/NiceErrorDomain/NiceErrorDomain.d.ts type ChildDef = { domain: SUB["domain"]; allDomains: [SUB["domain"], ...PARENT_DEF["allDomains"]]; schema: SUB["schema"]; }; /** * Extracts the union of keys present in a `TFromContextInput` object. * e.g. `{ invalid_credentials: {...} }` → `"invalid_credentials"` */ type KeysOfContextInput = keyof INPUT & string; /** * Infers the strongly-typed `NiceError` class type from a `NiceErrorDomain` instance. * * `ACTIVE_IDS` is set to the full union of all schema keys. Use `hasId` / * `hasOneOfIds` to narrow further at the call site. * * @example * ```ts * const err_user_auth = defineNiceError({ domain: "err_user_auth", schema: { ... } }); * type TUserAuthError = InferNiceError; * // → NiceError<{ domain: "err_user_auth"; ... }, keyof schema> * ``` */ type InferNiceError> = T extends NiceErrorDomain ? NiceError : never; /** * Infers the strongly-typed `NiceErrorHydrated` class type from a `NiceErrorDomain` instance. * * Use this when you need the builder methods (`addId`, `addContext`) as part of * the inferred type — e.g. for function return types or variable annotations. * * @example * ```ts * const err_user_auth = defineNiceError({ domain: "err_user_auth", schema: { ... } }); * type TUserAuthErrorHydrated = InferNiceErrorHydrated; * // → NiceErrorHydrated<{ domain: "err_user_auth"; ... }, keyof schema> * ``` */ type InferNiceErrorHydrated> = T extends NiceErrorDomain ? NiceErrorHydrated : never; declare class NiceErrorDomain { readonly domain: ERR_DEF["domain"]; readonly allDomains: ERR_DEF["allDomains"]; readonly defaultHttpStatusCode?: number; readonly defaultMessage?: string; /** Kept for runtime use (message resolution, httpStatusCode, context serialization, etc.). */ private readonly _schema; private _definedChildNiceErrors; private _definedParentNiceError?; /** Set by `.packAs()` — explicit per-instance override, takes priority over `_packAsFn`. */ private _setPack?; /** Set at definition time — called dynamically each time an error is created. */ private _packAsFn?; constructor(definition: ERR_DEF); /** * Creates a child domain that inherits this domain in `allDomains`. * The child has its own schema and its own domain string. */ createChildDomain(subErrorDef: SUB & { [K in Exclude]: never; }): NiceErrorDomain>; protected addParentNiceErrorDomain(parentError: NiceErrorDomain): void; protected addChildNiceErrorDomain(child: NiceErrorDomain): void; packAs(pack: EErrorPackType): this; private createError; /** * Promotes a plain `NiceError` back into a `NiceErrorHydrated` so * that builder methods (`addId`, `addContext`, etc.) are available again. * * For each active id, if the context is in the `"unhydrated"` state (i.e. the * error was reconstructed from a JSON payload), `hydrate` calls * `fromJsonSerializable` to reconstruct the typed value and advances the state * to `"hydrated"`. Ids already in `"hydrated"` or `"raw_unset"` state * are passed through unchanged. * * @throws If `error.def.domain` does not match this definition's domain. Use * `niceErrorDefined.isExact(error)` before calling `hydrate` to ensure compatibility. * * ```ts * const raw = castNiceError(apiResponseBody); * * if (err_user_auth.isExact(raw)) { * const hydrated = err_user_auth.hydrate(raw); * // hydrated.getContext("invalid_credentials") — fully typed, no throw * // hydrated.addId / addContext — available again * } * ``` */ hydrate = TDomainNiceErrorId>(error: NiceError | INiceErrorJsonObject): NiceErrorHydrated; /** * Creates a `NiceErrorHydrated` for a single error id. * * - `id` autocompletes to the schema keys. * - The second argument `context` is required / optional / absent based on * whether the schema entry declares `context.required: true`. * - The returned error has `ACTIVE_IDS` narrowed to exactly `K`, so * `getContext(id)` is immediately strongly typed. */ fromId(...args: FromIdArgs): NiceErrorHydrated; fromContext>(context: INPUT & Record, never>): NiceErrorHydrated>; /** * Returns `true` if `error` is a `NiceError` whose `def.domain` exactly matches * this definition's domain. * * Use this after `castNiceError` to narrow an unknown error to this specific * domain before accessing its typed ids/context: * * ```ts * const caught = castNiceError(e); * * if (err_user_auth.isExact(caught)) { * // caught is now NiceError * const hydrated = err_user_auth.hydrate(caught); * const { username } = hydrated.getContext("invalid_credentials"); * } * ``` */ isExact(error: unknown): error is NiceError; isThisOrChild(error: unknown): boolean; /** * Returns `true` if this domain appears anywhere in the target's ancestry * chain (including an exact domain match). * * Accepts either a `NiceErrorDomain` (domain definition) or a `NiceError` * instance (extracts the domain from its `def`). */ isParentOf(target: NiceErrorDomain | NiceError): boolean; private _buildDef; private _resolveMessage; private _resolveHttpStatusCode; reconcileErrorDataForId(id: keyof ERR_DEF["schema"] & string, context: TFromContextInput[typeof id]): TErrorReconciledData; } //#endregion //#region src/error/NiceErrorHandler/NiceErrorHandler.types.d.ts type MaybePromise = T | Promise; /** * Broad handler signature used internally for storage and dispatch. */ type TBroadErrorHandler = (action: E) => MaybePromise; /** * Handler registered via forDomain. * * `act.input` is typed as the union of input types for every action in `ACT_DOM`, * and `act.coreAction` carries the matching schema — the same narrowing you get * from `forActionIds` over all action IDs in the domain. */ type TErrorHandlerForDomain = (error: NiceErrorHydrated) => MaybePromise; /** * Handler registered via forActionId — receives a specific action ID, with * the primed action's input narrowed to that ID's schema. */ type TErrorIdHandlerForDomain> = (error: NiceErrorHydrated) => MaybePromise; declare enum EErrorHandlerTargetType { ids = "ids", domain = "domain", default = "default" } type TErrorHandlerTarget = ({ type: EErrorHandlerTargetType.ids; domain: string; ids: string[]; } | { type: EErrorHandlerTargetType.domain; domain: string; } | { type: EErrorHandlerTargetType.default; }) & { identifier: string; }; /** * A single case in a `handleWith` / `handleWithAsync` call. * * Construct via `forDomain` or `forIds` — do not build this object directly. */ interface IErrorHandlerConfig = NiceError, RES = unknown> { /** * Duck-typed reference to the domain definition. * Needs only `isExact()` and `hydrate()` at runtime — avoids any circular value import. * @internal */ readonly target: TErrorHandlerTarget; readonly _matcher: (action: ERR) => boolean; readonly _requester: TBroadErrorHandler; } interface IErrorHandleAttempt_Success { handled: true; result: RES; target: TErrorHandlerTarget; } interface IErrorHandleAttempt_Failure { handled: false; result?: undefined; targets: TErrorHandlerTarget[]; } type TErrorHandleAttempt = IErrorHandleAttempt_Success | IErrorHandleAttempt_Failure; interface IHandleErrorOptions { throwOnUnhandled?: boolean; } type THandleErrorWithPromiseInspection = { isPromise: false; matched: true; target: TErrorHandlerTarget; handlerResponse: RES; } | { isPromise: true; matched: true; target: TErrorHandlerTarget; handlerPromise: Promise; } | { matched: false; attemptedTargets: TErrorHandlerTarget[]; }; type THandleResponse = { handled: false; } | { handled: true; isPromise: boolean; response: RES; }; //#endregion //#region src/error/NiceErrorHandler/NiceErrorHandler.d.ts declare class NiceErrorHandler { private handlerConfigs; private _defaultRequester?; handleErrorWithPromiseInspection(error: NiceError, options?: IHandleErrorOptions): THandleErrorWithPromiseInspection; /** * Register a handler that fires for **any** error whose domain matches `domain`. * The handler receives a fully hydrated error — `getContext`, `addId`, and `addContext` * are all available. First matching case wins. */ forDomain(domain: NiceErrorDomain, handler: (error: NiceErrorHydrated>) => MaybePromise): NiceErrorHandler; forId, H_RES = void>(domain: NiceErrorDomain, id: ID, handler: (error: NiceErrorHydrated) => MaybePromise): NiceErrorHandler; forIds[], H_RES = void>(domain: NiceErrorDomain, ids: IDS, handler: (error: NiceErrorHydrated) => MaybePromise): NiceErrorHandler; /** * Register a fallback handler that fires when no other case matches. * Only one default handler can be registered — calling this twice replaces the previous one. */ setDefaultHandler(handler: (error: NiceError) => MaybePromise): NiceErrorHandler; } //#endregion //#region src/error/NiceError/NiceError.d.ts type ContextOf = TExtractContextType; /** Full-featured construction from NiceErrorDomain.fromId / fromContext. */ interface INiceErrorOptions = TDomainNiceErrorId> { def: Omit; /** Primary id is first entry in ids. */ ids: ID[]; /** All active ids with their messages, http status codes, and context state. */ errorData: TErrorDataForIdMap; message: string; httpStatusCode?: number; originError?: IRegularErrorJsonObject | undefined; timeCreated?: number; } declare class NiceError = TDomainNiceErrorId> extends Error { readonly name: "NiceError"; readonly def: Omit; /** Primary id is first entry in ids. */ readonly ids: ACTIVE_IDS[]; readonly httpStatusCode: number; readonly timeCreated: number; readonly cleanMessage: string; originError?: IRegularErrorJsonObject; _packedState?: { packedAs: EErrorPackType.cause_pack; cause: unknown; } | { packedAs: EErrorPackType.msg_pack; message: string; } | undefined; /** Internal: all active id → reconciled data pairs. */ protected readonly _errorDataMap: TErrorDataForIdMap; constructor(options: INiceErrorOptions); /** * `true` when this error is the generic wrapper `castNiceError` produces for a * value that wasn't already a `NiceError` (native throw, error-like object, * nullish, primitive) — i.e. an error that fell through without being handled * by any defined domain. * * Defined as "belongs to the `err_cast_not_nice` domain", so it is stable across * a serialization round-trip (the domain travels on the wire) and is `false` for * every domain-defined error, including a real `NiceError` reconstructed from JSON. */ get isUnhandled(): boolean; /** * Type guard: returns `true` if this error was created with (or contains) the * given `id`. After the guard, `getContext(id)` will be strongly typed. */ hasId(id: ID): this is NiceError; /** * Returns `true` if this error contains **at least one** of the supplied ids. * Narrows `ACTIVE_IDS` to the matching subset of `IDS`. */ hasOneOfIds>(ids: IDS): this is NiceError; /** `true` when this error was created with more than one id (via `fromContext`). */ get hasMultiple(): boolean; /** Returns all active error ids on this instance. */ getIds(): Array; /** * Returns the typed context value for the given error id. * * TypeScript will only allow you to call this with an id that is part of * `ACTIVE_IDS` (i.e. an id confirmed via `hasId` / `hasOneOfIds`, or passed * to `fromId` / `fromContext`). * * @throws If the context is in the `"unhydrated"` state — the error was * reconstructed from a JSON payload and its context has a custom serializer * that hasn't been run yet. Call `niceErrorDefined.hydrate(error)` first. */ getContext(id: ID): ContextOf; getErrorDataForId(id: ID): TErrorReconciledData | undefined; withOriginError(error: unknown): this; /** * Returns `true` if `other` has the same domain and the exact same set of * active error ids as this error (order-independent). * * Useful for deduplication, retry logic, and asserting that two errors * represent the same "kind" of problem without comparing context values. * * ```ts * const a = err_auth.fromId("invalid_credentials", { username: "alice" }); * const b = err_auth.fromId("invalid_credentials", { username: "bob" }); * a.matches(b); // true — same domain + same id set * * const c = err_auth.fromId("account_locked"); * a.matches(c); // false — same domain, different id * ``` */ matches(other: NiceError): boolean; toJsonObject(): INiceErrorJsonObject; toJSON(): INiceErrorJsonObject; /** * The **wire form** — {@link toJsonObject} minus the server-only diagnostic fields (`stack`, * `originError`) that disclose server internals and fatten the frame. Everything a peer needs to * reconstruct a fully-typed error survives — ids, per-id context, rendered message, `isUnhandled`, * and the domain definition — so `castNiceError` on the far side yields an error whose `getIds()`, * `getContext()`, `message`, and `isUnknownOutcomeRejection(...)` all behave identically. * * Use this whenever an error crosses a trust/observability boundary to an untrusted peer (e.g. a * realm reject frame fanned out to every client): the stack must not leave the process, and at * high frequency (a cursor-write reject storm) the ~1.5 kB full form is mostly stack. Keep the * complete {@link toJsonObject} for server-side logs and hooks. */ toWireJsonObject(): INiceErrorJsonObject; /** * A flat, log-friendly object for telemetry / structured logging — distinct * from {@link toJsonObject} (the wire form). Surfaces {@link isUnhandled} so a * sink can separate "an error we accounted for" from "one we didn't". */ toStructuredLog(): INiceErrorStructuredLog; toJsonString(): string; toHttpResponse(): Response; hydrate(definedNiceError: NiceErrorDomain): NiceErrorHydrated; /** * Iterates `cases` in order, finds the first whose domain matches this error * (via `is()`), optionally further filters by active ids, hydrates the error, * calls the handler, and returns `true`. Returns `false` if no case matched. * * Build cases with `forDomain` (any id in the domain) or `forIds` (specific * id subset). Handlers are invoked synchronously — any returned Promise is * not awaited. Use `handleWithAsync` when handlers are async. * * @example * ```ts * const handled = error.handleWith([ * forIds(err_feature, ["not_found"], (h) => { * res.status(404).json({ missing: h.getContext("not_found").resource }); * }), * forDomain(err_feature, (h) => { * matchFirst(h, { * forbidden: ({ userId }) => res.status(403).json({ userId }), * _: () => res.status(500).end(), * }); * }), * forDomain(err_service, (h) => { * res.status(h.httpStatusCode).json({ error: h.message }); * }), * ]); * if (!handled) next(error); * ``` */ handleWithSync(handlerInput: NiceErrorHandler | ReadonlyArray>, handlerOptions?: IHandleErrorOptions): R | RD | undefined; /** * Same matching logic as `handleWith`, but `await`s the handler's returned * Promise before resolving. Use this when your handlers perform async work * (database writes, HTTP calls, etc.). * * @example * ```ts * const handled = await error.handleWithAsync([ * forDomain(err_payments, async (h) => { * await db.logFailedPayment(h); * await notifyOps(h.message); * }), * ]); * ``` */ handleWithAsync(handlerInput: NiceErrorHandler | ReadonlyArray>, handlerOptions?: IHandleErrorOptions): Promise; get isPacked(): boolean; pack(packType?: EErrorPackType): this; unpack(): this; } //#endregion //#region src/error/internal/nice_core_errors.d.ts declare const err_nice: NiceErrorDomain<{ domain: "err_nice"; allDomains: ["err_nice"]; schema: {}; }>; //#endregion //#region src/error/NiceErrorDomain/defineNiceError.d.ts declare const defineNiceError: (definition: IDefineNewNiceErrorDomainOptions) => NiceErrorDomain<{ domain: ERR_DOMAIN; allDomains: [ERR_DOMAIN]; schema: SCHEMA; }>; //#endregion //#region src/error/NiceErrorDomain/err.d.ts /** * Schema entry factory — the idiomatic way to define a single error id in a * `NiceErrorDomain` schema. * * Using `err()` instead of writing schema entries as plain object literals * ensures TypeScript resolves the context argument as **required** vs **optional** * correctly in `fromId` / `addId` call sites. * * How `required` affects the call site: * * | Schema entry | `fromId("id")` | `fromId("id", ctx)` | * |------------------------------------|----------------|---------------------| * | `err()` / `err({ ... })` | ✓ | ✗ (no context) | * | `err({ context: {} })` | ✓ | ✓ (optional ctx) | * | `err({ context: { required: true } })` | ✗ | ✓ (required ctx) | * * @example * ```ts * // No context — `fromId("not_found")` takes no second argument. * not_found: err({ message: "Resource not found", httpStatusCode: 404 }), * * // Optional context — second arg accepted but not required. * rate_limited: err<{ retryAfter: number }>({ * message: (ctx) => ctx ? `Retry after ${ctx.retryAfter}s` : "Rate limited", * httpStatusCode: 429, * context: {}, * }), * * // Required context — `fromId("invalid_input", { field: "email" })` (second arg is required). * invalid_input: err<{ field: string }>({ * message: ({ field }) => `Invalid value for field: ${field}`, * httpStatusCode: 422, * context: { required: true }, * }), * * // Required context with custom serialization (for non-JSON-safe context values). * fs_error: err<{ cause: NodeJS.ErrnoException }>({ * message: ({ cause }) => `File system error: ${cause.message}`, * context: { * required: true, * serialization: { * toJsonSerializable: ({ cause }) => ({ code: cause.code, message: cause.message }), * fromJsonSerializable: (obj) => ({ cause: Object.assign(new Error(obj.message), obj) }), * }, * }, * }), * ``` */ declare function err>(meta: INiceErrorIdMetadata & { context: INiceErrorContextDefinition & { required: true; }; }): INiceErrorIdMetadata & { context: { required: true; }; }; declare function err(meta?: INiceErrorIdMetadata): INiceErrorIdMetadata; //#endregion //#region src/error/NiceErrorHandler/handleWith.d.ts declare function forDomain(domain: NiceErrorDomain, handler: (error: NiceErrorHydrated>) => MaybePromise): NiceErrorHandler; declare function forId, H_RES = void>(domain: NiceErrorDomain, id: ID, handler: (error: NiceErrorHydrated) => MaybePromise): NiceErrorHandler; declare function forIds[], H_RES = void>(domain: NiceErrorDomain, ids: IDS, handler: (error: NiceErrorHydrated) => MaybePromise): NiceErrorHandler; //#endregion //#region src/error/observability/tap.d.ts /** * A subscriber notified once for every `NiceError` at creation time. Use it to * pipe errors into telemetry (Sentry / OTel), devtools, or structured logging * the moment they're born — without threading a reporter through every call site. */ type TNiceErrorTap = (error: NiceError) => void; /** * Register a tap fired for every `NiceError` created via a domain * (`fromId` / `fromContext`). Returns an unsubscribe function. * * Opt-in and zero-cost when unused. A tap that throws is swallowed so it can * never break error creation. */ declare function onNiceError(tap: TNiceErrorTap): () => void; /** Internal: notify all registered taps. Never throws. */ declare function emitNiceError(error: NiceError): void; //#endregion //#region src/error/result/TNiceResult.d.ts /** * A success/failure outcome whose failure branch is always a `NiceError`. * * The canonical result shape for "ran something that could fail" — produced by * {@link niceTry} / {@link niceTryAsync}. `nice-action`'s action result is a * structural superset of this (it adds an `expected` discriminant), so the two * compose cleanly. */ type TNiceResult = NiceError> = { ok: true; output: OUT; } | { ok: false; error: ERR; }; /** Build a success result. */ declare const niceOk: (output: OUT) => TNiceResult; /** Build a failure result. */ declare const niceErr: >(error: ERR) => TNiceResult; //#endregion //#region src/error/result/niceTry.d.ts /** * Run a synchronous function and capture the outcome as a {@link TNiceResult}. * * Any thrown value is run through {@link castNiceError}, so the `error` branch is * always a `NiceError` — a defined domain error passes through untouched; a native * throw / nullish / primitive becomes an `err_cast_not_nice` wrapper (`isUnhandled`). * * ```ts * const r = niceTry(() => JSON.parse(input)); * if (!r.ok) report(r.error); * else use(r.output); * ``` */ declare function niceTry(fn: () => OUT): TNiceResult; /** * Async counterpart of {@link niceTry}. Accepts a sync or async function and * awaits its result; a rejection is caught and `castNiceError`-d into the * `error` branch. */ declare function niceTryAsync(fn: () => Promise | OUT): Promise>; //#endregion //#region src/error/utils/castAndHydrate.d.ts /** * Combines `castNiceError`, `isExact()`, and `hydrate()` in a single call — the * idiomatic way to handle an unknown value arriving from a remote boundary * (API response, message queue, IPC, etc.) when you have a specific domain in mind. * * - Casts `value` to a `NiceError` using `castNiceError`. * - If the result belongs to `niceErrorDefined`'s domain (`isExact()` returns `true`), * hydrates it and returns a fully-typed `NiceErrorHydrated`. * - Otherwise returns the raw cast `NiceError` (which may be an `isUnhandled` error * if `value` was not a NiceError at all). * * @example * ```ts * // In an Express error handler: * app.use((err, req, res, next) => { * const error = castAndHydrate(err, err_user_auth); * * if (err_user_auth.isExact(error)) { * // error is NiceErrorHydrated — getContext / addId available * const result = matchFirst(error, { * invalid_credentials: ({ username }) => res.status(401).json({ username }), * account_locked: () => res.status(403).json({ locked: true }), * }); * if (result) return; * } * * next(err); * }); * ``` */ declare function castAndHydrate(value: unknown, niceErrorDefined: NiceErrorDomain): NiceErrorHydrated | NiceError; //#endregion //#region src/error/utils/castNiceError.d.ts /** * Casts any unknown value into a `NiceError`. * * - If the value is already a `NiceError` instance, it is returned as-is. * - If the value is a plain `Error`, it is wrapped with the original as `originError`. * - If the value is a JSON-serialised `NiceError` object (e.g. from an API * response), a best-effort `NiceError` is re-created from it. * - For all other values, a generic `NiceError` is created with a descriptive * message. * * After casting, use `NiceErrorDomain.isExact(error)` to narrow the error to a * specific domain and access its strongly-typed ids and context. */ declare const castNiceError: (error: unknown) => NiceError; //#endregion //#region src/error/utils/logger.d.ts /** * Injectable logger seam. * * `nice-error` ships zero hard runtime deps and must run anywhere (browser, * Workers, edge, RTC). Instead of bundling a Node-oriented logger, it logs * through this small interface, defaulting to the universal `console`. Consumers * can route diagnostics into their own logger (tslog / pino / a devtools sink) * via {@link setNiceErrorLogger}. */ interface INiceErrorLogger { warn(message: string, meta?: unknown): void; debug(message: string, meta?: unknown): void; error(message: string, meta?: unknown): void; } /** Replace the logger `nice-error` uses for internal diagnostics. */ declare function setNiceErrorLogger(logger: INiceErrorLogger): void; /** The logger `nice-error` currently logs through (defaults to `console`). */ declare function getNiceErrorLogger(): INiceErrorLogger; //#endregion //#region src/error/utils/matchFirst.d.ts /** * Handler map for `matchFirst`. Each key is an error id (from `ACTIVE_IDS`) and * the value is a function that receives the typed context for that id. * * The `_` key is an optional fallback that runs when no id-specific handler matched. */ type TMatchFirstHandlers = { [K in ACTIVE_IDS]?: (context: TExtractContextType) => RESULT; } & { _?: () => RESULT; }; /** * Pattern-matches an error against a map of id → handler functions, returning the * result of the first handler whose id is active on the error. * * - Ids are tested in the order returned by `error.getIds()`. * - If no id-specific handler matched and `_` is provided, the fallback is called. * - Returns `undefined` when neither any id handler nor the fallback fires. * * **Requires hydrated context.** If any matched id is in the `"unhydrated"` state, * `getContext` will throw. Call `niceErrorDefined.hydrate(error)` beforehand when * working with errors deserialized from a JSON payload. * * @example * ```ts * const result = matchFirst(error, { * invalid_credentials: ({ username }) => `Wrong password for ${username}`, * account_locked: () => "Account is locked", * _: () => "Unknown auth error", * }); * ``` */ declare function matchFirst(error: NiceError, handlers: TMatchFirstHandlers): RESULT | undefined; //#endregion export { TUnknownNiceErrorDef as $, TContextState as A, TErrorReconciledData as B, JSONSerializableValue as C, NiceErrorHandler as D, NiceErrorDomain as E, TErrorDataForIdMap as F, TMatchFirstHandlers as G, TFromContextInput as H, TErrorHandleAttempt as I, TNiceResult as J, TNiceErrorSchema as K, TErrorHandlerForDomain as L, TContextStateNoSerialization as M, TContextStateUnhydrated as N, NiceErrorHydrated as O, TDomainNiceErrorId as P, TSerializedErrorReconciledData as Q, TErrorHandlerTarget as R, InferNiceErrorHydrated as S, NiceError as T, THandleErrorWithPromiseInspection as U, TExtractContextType as V, THandleResponse as W, TSerializedContextState as X, TSchemaNiceErrorId as Y, TSerializedErrorDataMap as Z, INiceErrorStructuredLog as _, setNiceErrorLogger as _t, IDefineNewNiceErrorDomainOptions as a, err as at, IRegularErrorJsonObject as b, IErrorHandlerConfig as c, forId as ct, INiceErrorDomainProps as d, matchFirst as dt, TUnknownNiceErrorId as et, INiceErrorHydratedOptions as f, niceErr as ft, INiceErrorOptions as g, onNiceError as gt, INiceErrorLogger as h, niceTryAsync as ht, FromIdArgs as i, emitNiceError as it, TContextStateHydrated as j, TBroadErrorHandler as k, IHandleErrorOptions as l, forIds as lt, INiceErrorJsonObject as m, niceTry as mt, EErrorPackType as n, castNiceError as nt, IErrorHandleAttempt_Failure as o, err_nice as ot, INiceErrorIdMetadata as p, niceOk as pt, TNiceErrorTap as q, ExtractFromIdContextArg as r, defineNiceError as rt, IErrorHandleAttempt_Success as s, forDomain as st, EErrorHandlerTargetType as t, castAndHydrate as tt, INiceErrorContextDefinition as u, getNiceErrorLogger as ut, IPackErrorAs_Base as v, MaybePromise as w, InferNiceError as x, IPackErrorAs_MatchEnvVar as y, TErrorIdHandlerForDomain as z }; //# sourceMappingURL=index-BAgdJKZy-COfXA16I.d.cts.map