/** * @geenius/errors — Structured error handling * * Provides a hierarchy of typed errors for different error scenarios. * Enables consistent error handling and formatting across the Geenius ecosystem. */ /** * Defines the machine-readable error taxonomy shared across Geenius packages. * Use these values when errors need stable branching, serialization, or HTTP * status mapping instead of matching on human-facing messages. * * @example * if (isErrorCode(error, ErrorCode.RATE_LIMIT)) { * retryAfterBackoff() * } */ declare enum ErrorCode { UNKNOWN = "UNKNOWN", VALIDATION = "VALIDATION", NOT_FOUND = "NOT_FOUND", UNAUTHORIZED = "UNAUTHORIZED", FORBIDDEN = "FORBIDDEN", CONFLICT = "CONFLICT", INTERNAL = "INTERNAL", INVALID_CREDENTIALS = "INVALID_CREDENTIALS", SESSION_EXPIRED = "SESSION_EXPIRED", MFA_REQUIRED = "MFA_REQUIRED", INVALID_TOKEN = "INVALID_TOKEN", DATABASE_ERROR = "DATABASE_ERROR", CONSTRAINT_VIOLATION = "CONSTRAINT_VIOLATION", NETWORK_ERROR = "NETWORK_ERROR", TIMEOUT = "TIMEOUT", RATE_LIMIT = "RATE_LIMIT", INTERNAL_ERROR = "INTERNAL_ERROR", INVALID_CONFIG = "INVALID_CONFIG", MISSING_CONFIG = "MISSING_CONFIG" } declare const AUTH_ERROR_CODES: readonly [ErrorCode.INVALID_CREDENTIALS, ErrorCode.SESSION_EXPIRED, ErrorCode.MFA_REQUIRED, ErrorCode.INVALID_TOKEN, ErrorCode.UNAUTHORIZED, ErrorCode.FORBIDDEN]; type AuthErrorCode = (typeof AUTH_ERROR_CODES)[number]; interface AuthErrorOptions extends Omit { /** Auth-specific error code. */ code?: AuthErrorCode; } /** * Configures structured Geenius errors with both user-safe messages and * machine-readable metadata for logs, API responses, and UI recovery states. * * @example * const options: GeeniusErrorOptions = { * code: ErrorCode.VALIDATION, * message: 'Invalid email format', * statusCode: 400, * context: { field: 'email' }, * } */ interface GeeniusErrorOptions { /** Error code for classification */ code?: ErrorCode; /** User-friendly message */ message: string; /** Technical details */ cause?: unknown; /** HTTP status code equivalent */ statusCode?: number; /** Contextual data */ context?: Record; /** Whether error should be logged */ log?: boolean; } /** * Identifies the closest concrete error class when a Geenius error crosses a * process, worker, or network boundary. * * @example * const kind: GeeniusErrorKind = 'RateLimitError' */ type GeeniusErrorKind = 'GeeniusError' | 'ValidationError' | 'AuthError' | 'NotFoundError' | 'ConflictError' | 'RateLimitError' | 'InternalServerError' | 'UnauthorizedError'; /** * Carries Geenius errors across network, worker, and storage boundaries without * leaking native `Error` instances or non-cloneable context values. * * @example * const serialized: SerializedGeeniusError = serializeError(error) */ interface SerializedGeeniusError { [key: string]: unknown; __isGeeniusError: true; name: string; kind: GeeniusErrorKind; code: ErrorCode; message: string; statusCode: number; context: Record; cause?: Record; } /** * Accepts either a live Geenius error or its serialized snapshot so guards and * formatters work before and after transport. * * @example * const value: GeeniusErrorLike = serializeError(new GeeniusError({ message: 'Failed' })) */ type GeeniusErrorLike = GeeniusError | SerializedGeeniusError; /** * Represents the success-or-error tuple returned by safe wrappers. Use this * when callers prefer explicit branching over exceptions. * * @typeParam T - Successful result value type. * @typeParam TError - Geenius error type returned on failure. * * @example * const tuple: ErrorTuple = ['ok', null] */ type ErrorTuple = [T, null] | [null, TError]; /** * Converts unknown failures into native `Error` instances before the helpers * normalize them into `GeeniusError` values. * * @typeParam TError - Native error type produced by the handler. * @param error - Unknown failure caught by a safe wrapper. * @returns A native error that will be normalized into a Geenius error. * * @example * const handler: ErrorHandler = (error) => * new InternalServerError({ message: 'Operation failed', cause: error }) */ type ErrorHandler = (error: unknown) => TError; /** * Controls how much diagnostic data is included when unknown thrown values are * normalized for logs or transport. * * @example * const options: FormatErrorOptions = { includeStack: process.env.NODE_ENV !== 'production' } */ interface FormatErrorOptions { /** Include native Error.stack in formatted output. Defaults to false. */ includeStack?: boolean; } /** * Describes the JSON-safe shape returned by `formatError` for logs, API * responses, and reporting pipelines. * * @example * const formatted: FormattedError = formatError(new Error('Failed')) */ interface FormattedError extends Record { /** Native error name when available. */ name?: string; /** User-safe error message. */ message: string; /** Geenius error code classification. */ code: ErrorCode; /** HTTP status code equivalent. */ statusCode: number; /** Contextual metadata associated with the error. */ context: Record; /** Native stack trace when explicitly requested. */ stack?: string; } /** * Resolves a canonical Geenius code to its default HTTP status for API * adapters that need stable response mapping. * * @param code - Geenius error code to resolve. * @returns The default HTTP status code associated with the code. * * @example * const statusCode = getStatusCodeForErrorCode(ErrorCode.NOT_FOUND) */ declare function getStatusCodeForErrorCode(code: ErrorCode): number; /** * Lists every Geenius code that shares an HTTP status so consumers can build * grouped response handling or documentation tables. * * @param statusCode - HTTP status code to reverse-map. * @returns All known Geenius error codes associated with the status. * * @example * const unauthorizedCodes = getErrorCodesForStatusCode(401) */ declare function getErrorCodesForStatusCode(statusCode: number): readonly ErrorCode[]; /** * Narrows values that are known concrete Geenius errors after construction or * deserialization. * * @example * const known: KnownGeeniusError = new UnauthorizedError({ message: 'Login required' }) */ type KnownGeeniusError = GeeniusError | ValidationError | AuthError | NotFoundError | ConflictError | RateLimitError | InternalServerError | UnauthorizedError; type NormalizedHandlerError = [TError] extends [never] ? GeeniusError : [TError] extends [GeeniusError] ? TError : GeeniusError; /** * Provides the base structured error for Geenius packages. Use this when a * package needs a typed error with code, status, context, and safe JSON output * but no narrower subclass applies. * * @param options - Structured error configuration used to set message, code, * status, context, cause, and logging intent. * @returns A live `GeeniusError` instance with a safe serialization contract. * * @example * ```ts * throw new GeeniusError({ * code: ErrorCode.VALIDATION, * message: 'Invalid email format', * statusCode: 400, * context: { field: 'email' } * }) * ``` */ declare class GeeniusError extends Error { readonly kind: GeeniusErrorKind; readonly code: ErrorCode; readonly statusCode: number; readonly context: Record; readonly cause?: unknown; readonly log: boolean; /** * Creates a structured error that can be safely formatted and serialized. * * @param options - Message, classification, HTTP status, cause, and context. * * @example * const error = new GeeniusError({ message: 'Operation failed' }) */ constructor(options: GeeniusErrorOptions); private getDefaultStatusCode; /** * Converts the live error into the stable payload used for transport and * storage boundaries. * * @returns A JSON-safe Geenius error snapshot. * * @example * const payload = new GeeniusError({ message: 'Failed' }).toJSON() */ toJSON(): SerializedGeeniusError; /** * Produces a compact diagnostic string for logs and CLI output. * * @returns A string containing the error name, code, and message. * * @example * String(new GeeniusError({ message: 'Failed' })) */ toString(): string; } /** * Represents input, schema, or form validation failures. Use it when callers * can recover by correcting submitted data. * * @param options - Message, context, cause, and logging intent for the * validation failure. * @returns A `ValidationError` mapped to `ErrorCode.VALIDATION` and HTTP 400. * * @example * ```ts * throw new ValidationError({ * message: 'Invalid input', * context: { errors: { email: 'Invalid format' } } * }) * ``` */ declare class ValidationError extends GeeniusError { readonly kind = "ValidationError"; /** * Creates a validation error with the canonical validation code and status. * * @param options - Message, context, cause, and logging intent. * * @example * const error = new ValidationError({ message: 'Invalid input' }) */ constructor(options: Omit); } /** * Represents authentication and authorization-flow failures that need a more * specific auth code than the base error. * * @param options - Auth failure details and optional auth-specific code. * @returns An `AuthError` mapped to the matching auth HTTP status. * * @example * const error = new AuthError({ * code: ErrorCode.SESSION_EXPIRED, * message: 'Session expired', * }) */ declare class AuthError extends GeeniusError { readonly kind = "AuthError"; /** * Creates an auth error with a validated auth-specific code. * * @param options - Auth-specific message, code, context, cause, and log flag. * * @example * const error = new AuthError({ message: 'Invalid credentials' }) */ constructor(options: AuthErrorOptions); } /** * Represents a missing resource. Use it when a lookup completed but no matching * entity exists. * * @param options - Message, context, cause, and logging intent for the miss. * @returns A `NotFoundError` mapped to `ErrorCode.NOT_FOUND` and HTTP 404. * * @example * const error = new NotFoundError({ message: 'Project not found' }) */ declare class NotFoundError extends GeeniusError { readonly kind = "NotFoundError"; /** * Creates a not-found error with the canonical not-found code and status. * * @param options - Message, context, cause, and logging intent. * * @example * const error = new NotFoundError({ message: 'User not found' }) */ constructor(options: Omit); } /** * Represents duplicate, stale-write, or conflicting-state failures. Use it * when retrying requires changing the requested state. * * @param options - Message, context, cause, and logging intent for the conflict. * @returns A `ConflictError` mapped to `ErrorCode.CONFLICT` and HTTP 409. * * @example * const error = new ConflictError({ message: 'Email already exists' }) */ declare class ConflictError extends GeeniusError { readonly kind = "ConflictError"; /** * Creates a conflict error with the canonical conflict code and status. * * @param options - Message, context, cause, and logging intent. * * @example * const error = new ConflictError({ message: 'Duplicate key' }) */ constructor(options: Omit); } /** * Represents throttling and quota failures. Use it when callers should slow * down or retry after backoff. * * @param options - Message, context, cause, and logging intent for throttling. * @returns A `RateLimitError` mapped to `ErrorCode.RATE_LIMIT` and HTTP 429. * * @example * const error = new RateLimitError({ message: 'Too many requests' }) */ declare class RateLimitError extends GeeniusError { readonly kind = "RateLimitError"; /** * Creates a rate-limit error with the canonical rate-limit code and status. * * @param options - Message, context, cause, and logging intent. * * @example * const error = new RateLimitError({ message: 'Quota exceeded' }) */ constructor(options: Omit); } /** * Represents unexpected internal failures that should not expose implementation * details to external consumers. * * @param options - Message, context, cause, and logging intent for the failure. * @returns An `InternalServerError` mapped to `ErrorCode.INTERNAL_ERROR` and * HTTP 500. * * @example * const error = new InternalServerError({ message: 'Failed to save record' }) */ declare class InternalServerError extends GeeniusError { readonly kind = "InternalServerError"; /** * Creates an internal server error with the canonical internal code/status. * * @param options - Message, context, cause, and logging intent. * * @example * const error = new InternalServerError({ message: 'Unexpected failure' }) */ constructor(options: Omit); } /** * Represents missing or invalid credentials. Use it for authentication gates * where the user must provide or refresh credentials. * * @param options - Message, context, cause, and logging intent for the auth gap. * @returns An `UnauthorizedError` mapped to `ErrorCode.UNAUTHORIZED` and HTTP * 401. * * @example * const error = new UnauthorizedError({ message: 'Login required' }) */ declare class UnauthorizedError extends GeeniusError { readonly kind = "UnauthorizedError"; /** * Creates an unauthorized error with the canonical unauthorized code/status. * * @param options - Message, context, cause, and logging intent. * * @example * const error = new UnauthorizedError({ message: 'Missing session' }) */ constructor(options: Omit); } /** * Normalizes any thrown value into a JSON-safe error record. Use this at * logging, telemetry, and API boundaries where callers may throw strings, * native errors, Geenius errors, or plain objects. * * @param error - Unknown thrown value to normalize. * @param options - Formatting controls, including optional stack inclusion. * @returns A structured error record with message, code, status, and context. * * @example * const formatted = formatError(error, { includeStack: shouldExposeStack }) */ declare function formatError(error: unknown, options?: FormatErrorOptions): FormattedError; /** * Checks whether a value is either a live Geenius error or a serialized * Geenius error snapshot. Use this before branching on `code`, `statusCode`, * or `kind` across process boundaries. * * @param error - Unknown value to inspect. * @returns `true` when the value satisfies the Geenius error contract. * * @example * if (isGeeniusError(error)) { * console.error(error.code) * } */ declare function isGeeniusError(error: unknown): error is GeeniusErrorLike; /** * Checks whether a live or serialized Geenius error carries a specific code. * Use this for stable branching instead of matching on messages. * * @param error - Unknown value to inspect. * @param code - Error code to match. * @returns `true` when the value is a Geenius error with the requested code. * * @example * const retry = isErrorCode(error, ErrorCode.RATE_LIMIT) */ declare function isErrorCode(error: unknown, code: ErrorCode): boolean; /** * Serialize any thrown value into the stable Geenius error payload used across * network and worker boundaries. * * @param error - Unknown thrown value or existing Geenius error. * @returns A serialized Geenius error payload safe for JSON and structured * clone boundaries. * * @example * const payload = serializeError(new RateLimitError({ message: 'Slow down' })) */ declare function serializeError(error: unknown): SerializedGeeniusError; /** * Rehydrate a serialized Geenius error payload into the closest matching error * subclass. Unknown payloads are normalized into a base `GeeniusError`. * * @param error - Serialized Geenius error snapshot or unknown fallback value. * @returns A live Geenius error instance, using the closest concrete subclass * when the serialized kind is valid. * * @example * const error = deserializeError(payload) */ declare function deserializeError(error: unknown): GeeniusError; /** * Wraps an operation and returns a Go-style result tuple. * * @typeParam T - Operation result type. * @typeParam TError - Optional native error type produced by the handler. * @param operation - Promise or function to execute inside the safe boundary. * @param handler - Optional transformation for unknown failures before they are * normalized to Geenius errors. * @returns A tuple containing either `[value, null]` or `[null, error]`. * * @example * ```ts * const [result, error] = await catchError( * fetchApi(), * (err) => new GeeniusError({ * code: ErrorCode.NETWORK_ERROR, * message: 'API request failed', * cause: err * }) * ) * ``` */ declare function catchError(operation: Promise | (() => T | Promise), handler?: ErrorHandler): Promise, NormalizedHandlerError>>; type SafeReturn = TResult extends PromiseLike ? Promise> : ErrorTuple; /** * Creates a safe function that returns Go-style result tuples. * * @typeParam TArgs - Original function argument tuple. * @typeParam TResult - Original function return type. * @typeParam TError - Optional native error type produced by the handler. * @param fn - Function to wrap while preserving its argument list. * @param handler - Optional transformation for unknown failures before they are * normalized to Geenius errors. * @returns A function with the same parameters that returns an error tuple. * * @example * ```ts * const safeOp = makeSafe( * (id: string) => db.user.find(id), * (err) => new NotFoundError({ message: 'User not found', cause: err }) * ) * ``` */ declare function makeSafe(fn: (...args: TArgs) => TResult, handler?: ErrorHandler): (...args: TArgs) => SafeReturn>; /** * Enumerates the stable severity tones downstream UI packages can map to their * own visual treatment without coupling this package to a renderer. * * @example * const tone = ERROR_DISPLAY_TONES.includes('danger') ? 'danger' : 'info' */ declare const ERROR_DISPLAY_TONES: readonly ["info", "warning", "danger", "success"]; /** * Enumerates density names shared by UI packages that need compact and * comfortable layouts while keeping the core error package framework-free. * * @example * const density = ERROR_DISPLAY_DENSITIES[0] */ declare const ERROR_DISPLAY_DENSITIES: readonly ["compact", "comfortable"]; /** * Narrows display severity to the values the Geenius design system expects. * Use this when component props accept only known error tones. * * @example * const tone: ErrorDisplayTone = 'warning' */ type ErrorDisplayTone = (typeof ERROR_DISPLAY_TONES)[number]; /** * Narrows display density to the renderer-neutral choices shared by downstream * UI packages. * * @example * const density: ErrorDisplayDensity = 'compact' */ type ErrorDisplayDensity = (typeof ERROR_DISPLAY_DENSITIES)[number]; /** * Describes one validation issue in a shape that can be rendered by web, * native, CLI, or logging consumers without importing a schema library. * * @example * const issue: ValidationIssue = { field: 'email', message: 'Email is required' } */ interface ValidationIssue { field: string; message: string; code?: string; } /** * Captures display-ready error metadata for packages that need consistent * titles, messages, and severity tones without rendering anything here. * * @example * const summary: NormalizedErrorSummary = { * title: 'Rate limit reached', * message: 'Try again later', * tone: 'warning', * statusCode: 429, * } */ interface NormalizedErrorSummary { title: string; message: string; tone: ErrorDisplayTone; statusCode?: number; code?: string; } /** * Wraps an error summary and optional validation details for reporting * adapters, logs, and support payloads that need a consistent envelope. * * @example * const envelope: ErrorReportEnvelope = { * summary: { title: 'Error', message: 'Failed', tone: 'danger' }, * issueCount: 0, * validationIssues: [], * createdAt: new Date().toISOString(), * } */ interface ErrorReportEnvelope { summary: NormalizedErrorSummary; issueCount: number; validationIssues: readonly ValidationIssue[]; createdAt: string; requestId?: string; } /** * Configures deterministic report envelopes, especially in tests and request * pipelines that already know the request id. * * @example * const options: ErrorReportOptions = { * requestId: 'req_123', * now: new Date('2026-05-18T00:00:00.000Z'), * } */ interface ErrorReportOptions { requestId?: string; now?: Date; } /** * Checks untrusted display input before passing it into UI props that only * support known Geenius error tones. * * @param value - Unknown value from props, configuration, or serialized state. * @returns `true` when the value is one of the supported display tones. * * @example * const tone = isErrorDisplayTone(input) ? input : 'danger' */ declare function isErrorDisplayTone(value: unknown): value is ErrorDisplayTone; /** * Checks untrusted density input before a downstream UI package applies layout * spacing decisions. * * @param value - Unknown value from props, configuration, or serialized state. * @returns `true` when the value is one of the supported display densities. * * @example * const density = isErrorDisplayDensity(input) ? input : 'comfortable' */ declare function isErrorDisplayDensity(value: unknown): value is ErrorDisplayDensity; /** * Converts unknown thrown values into display metadata that UI packages can * render consistently while this package remains framework-agnostic. * * @param error - Unknown thrown value, serialized error, or plain object. * @param fallbackMessage - Message to use when the input does not expose a * non-empty message. * @returns A normalized title, message, tone, and optional machine metadata. * * @example * const summary = normalizeErrorSummary({ statusCode: 404, message: 'Missing' }) */ declare function normalizeErrorSummary(error: unknown, fallbackMessage?: string): NormalizedErrorSummary; /** * Formats validation issues for environments that need a simple newline * separated string, such as logs, notifications, or fallback UI. * * @param issues - Field-level validation issues in display order. * @returns A newline-separated summary with field names when available. * * @example * const text = formatValidationIssues([{ field: 'email', message: 'Required' }]) */ declare function formatValidationIssues(issues: readonly ValidationIssue[]): string; /** * Creates a transport-safe report envelope for logging and support adapters * that need summary metadata plus validation details. * * @param error - Unknown thrown value or serialized error to summarize. * @param validationIssues - Optional field-level validation issues to attach. * @param options - Request id and clock overrides for deterministic reports. * @returns A JSON-safe envelope with a normalized summary and issue metadata. * * @example * const report = createErrorReportEnvelope(error, [], { requestId: 'req_123' }) */ declare function createErrorReportEnvelope(error: unknown, validationIssues?: readonly ValidationIssue[], options?: ErrorReportOptions): ErrorReportEnvelope; /** * Determines whether a runtime mode may expose diagnostic details to operators * instead of returning production-safe generic messages. * * @param environment - Runtime environment name, usually `process.env.NODE_ENV`. * @returns `true` for development and test environments; otherwise `false`. * * @example * const includeStack = shouldExposeErrorDetails(process.env.NODE_ENV) */ declare function shouldExposeErrorDetails(environment: string | undefined): boolean; export { AuthError, ConflictError, ERROR_DISPLAY_DENSITIES, ERROR_DISPLAY_TONES, ErrorCode, type ErrorDisplayDensity, type ErrorDisplayTone, type ErrorHandler, type ErrorReportEnvelope, type ErrorReportOptions, type ErrorTuple, type FormatErrorOptions, type FormattedError, GeeniusError, type GeeniusErrorKind, type GeeniusErrorLike, type GeeniusErrorOptions, InternalServerError, type KnownGeeniusError, type NormalizedErrorSummary, NotFoundError, RateLimitError, type SerializedGeeniusError, UnauthorizedError, ValidationError, type ValidationIssue, catchError, createErrorReportEnvelope, deserializeError, formatError, formatValidationIssues, getErrorCodesForStatusCode, getStatusCodeForErrorCode, isErrorCode, isErrorDisplayDensity, isErrorDisplayTone, isGeeniusError, makeSafe, normalizeErrorSummary, serializeError, shouldExposeErrorDetails };