UNPKG

@lifi/composer-sdk

Version:

Public Composer SDK for building and submitting flows

249 lines (248 loc) • 8.59 kB
import { parseServerErrorBody } from "./responseSchemas.js"; import z from "zod"; // src/errors.ts /** * Error class for all failures originating from the Compose SDK or API. * * Includes structured metadata beyond the error message to support * programmatic error handling. * * @example * ```ts * try { * await builder.compile(run); * } catch (e) { * if (isComposeError(e) && e.code === 'VALIDATION_ERROR') { * console.error('Invalid request:', e.message, e.path); * } * } * ``` */ var ComposeError = class extends Error { name = "ComposeError"; /** Machine-readable error category. */ code; /** HTTP status code, when the error originated from an HTTP response. */ status; /** The request URL that produced the error. */ url; /** Server-provided error kind for finer-grained classification. */ kind; /** * Where a validation error points: the node id for a rejection of an * authored node, or a JSON-pointer path for a rejection of the request shape. */ path; /** * The input port of {@link ComposeError.path}'s node whose binding caused the * error. Set when the rejection is about what a port binds rather than about * the node's config. */ port; /** * The one edit that clears the error, written for whoever authored the flow. * Set on `continuation.settle` authoring rejections; may be absent on other * `validation_error`s. */ fix; /** * The amount the flow was short by, when the error's cause is an amount that * cannot cover what a step needs: `required` is the least amount that would * clear the step, `available` the amount the flow had, both decimal strings * in the token's units. A failed op carries its own in `failedOps[].shortfall`. */ shortfall; /** * Simulation revert diagnostics attached to `simulation_revert` errors. * Contains the raw error bytes and decoded error candidates when the * backend can parse the revert reason. */ details; /** * The delivery tranche's reason, first quote, and abandoned escrow, * attached to `delivery_error` errors. Narrow with * {@link isComposeDeliveryError}. */ delivery; /** * The prepared ops that failed, attached to `preparation_error` errors. * Each entry carries the `callId` of the failing node so callers can drop * the unroutable legs and resubmit a smaller flow. */ failedOps; /** * The `callId`s of the prepared ops that succeeded, attached to * `preparation_error` errors alongside {@link ComposeError.failedOps}. */ succeededOps; /** Version details attached only to `sdk_outdated` errors. */ sdkOutdated; /** Version details attached only to `server_outdated` errors. */ serverOutdated; constructor(code, message, options) { super(message, { cause: options?.cause }); this.code = code; this.status = options?.status; this.url = options?.url; this.kind = options?.kind; this.path = options?.path; this.port = options?.port; this.fix = options?.fix; this.shortfall = options?.shortfall; this.details = options?.details; this.delivery = options?.delivery; this.failedOps = options?.failedOps; this.succeededOps = options?.succeededOps; this.sdkOutdated = options?.sdkOutdated; this.serverOutdated = options?.serverOutdated; } }; /** * Type guard that narrows an unknown error to {@link ComposeError}. * @param e - The value to check. * @returns `true` if `e` is an instance of `ComposeError`. */ const isComposeError = (e) => e instanceof ComposeError || e instanceof Error && e.name === "ComposeError" && "code" in e; /** * Type guard for `preparation_error` failures (HTTP 422): a mixed basket where * some prepared ops failed and others succeeded. Narrows both * {@link ComposeError.failedOps} and {@link ComposeError.succeededOps} to * present, so callers can read them without a cast or a truthiness check. * * @param e - The value to check. * @returns `true` if `e` is a `ComposeError` carrying per-op preparation diagnostics. * * @example * ```ts * try { * await builder.compile(run); * } catch (e) { * if (isComposePreparationError(e)) { * console.error('Failed ops:', e.failedOps); * console.error('Succeeded ops:', e.succeededOps); * } * } * ``` */ const isComposePreparationError = (e) => isComposeError(e) && e.kind === "preparation_error" && Array.isArray(e.failedOps) && Array.isArray(e.succeededOps); /** * Type guard for `delivery_error` failures (HTTP 422): a bridge delivering into * a settle escrow no longer fits it. Narrows {@link ComposeError.delivery} to * present. Recompile: each compile quotes and registers afresh. * * @param e - The value to check. * @returns `true` if `e` is a `ComposeError` carrying delivery details. */ const isComposeDeliveryError = (e) => isComposeError(e) && e.kind === "delivery_error" && e.delivery !== void 0; const sdkOutdatedSchema = z.object({ sdkVersion: z.string(), serverVersion: z.string(), minimumSdkVersion: z.string() }); /** * Narrows an outdated-SDK rejection to its required version details. * * @example * ```ts * try { * await builder.compile(run); * } catch (e) { * if (isComposeSdkOutdatedError(e)) { * console.error(`Upgrade to at least ${e.sdkOutdated.minimumSdkVersion}`); * return; * } * throw e; * } * ``` */ const isComposeSdkOutdatedError = (e) => isComposeError(e) && e.kind === "sdk_outdated" && sdkOutdatedSchema.safeParse(e.sdkOutdated).success; const serverOutdatedSchema = z.object({ sdkVersion: z.string(), serverVersion: z.string() }); /** * Narrows a server-behind-SDK rejection to its required version details. * * This is the deploy-window error: the SDK on npm is ahead of the backend that * answered. Pin the SDK to the server's `major.minor`, or wait for the rollout. * * @example * ```ts * try { * await builder.compile(run); * } catch (e) { * if (isComposeServerOutdatedError(e)) { * console.error(`Server serves ${e.serverOutdated.serverVersion}`); * return; * } * throw e; * } * ``` */ const isComposeServerOutdatedError = (e) => isComposeError(e) && e.kind === "server_outdated" && serverOutdatedSchema.safeParse(e.serverOutdated).success; const STATUS_TO_CODE = /* @__PURE__ */ new Map([ [400, "VALIDATION_ERROR"], [401, "UNAUTHENTICATED"], [402, "PAYMENT_REQUIRED"], [403, "FORBIDDEN"], [404, "NOT_FOUND"], [422, "VALIDATION_ERROR"], [429, "RATE_LIMITED"] ]); const tryParseErrorBody = (body) => { let json; try { json = JSON.parse(body); } catch { return null; } return parseServerErrorBody(json); }; /** * Extracts the version triple an `sdk_outdated` or `server_outdated` envelope * carries, and routes the wire `details` by kind. The version slots reuse the * same schemas the type guards narrow with. Zod strips keys the schema does * not declare, so the parsed value is exactly the triple; a partial payload * fails the parse and yields `undefined` rather than a half-populated object. * A `delivery_error`'s `details` land in `delivery`; every other kind's are * forwarded verbatim as `details`. */ const readKindSlots = (serverError) => { const delivery = serverError?.kind === "delivery_error"; return { sdkOutdated: serverError?.kind === "sdk_outdated" ? sdkOutdatedSchema.safeParse(serverError).data : void 0, serverOutdated: serverError?.kind === "server_outdated" ? serverOutdatedSchema.safeParse(serverError).data : void 0, details: delivery ? void 0 : serverError?.details, delivery: delivery ? serverError.details : void 0 }; }; /** * Constructs a {@link ComposeError} from an HTTP error response, extracting * structured error details from the response body when available. * * @param status - The HTTP status code. * @param body - The raw response body text. * @param url - The request URL that produced the error. * @returns A `ComposeError` with the appropriate error code and metadata. */ const errorFromHttpResponse = (status, body, url) => { const serverError = tryParseErrorBody(body)?.error; const slots = readKindSlots(serverError); return new ComposeError(STATUS_TO_CODE.get(status) ?? (status >= 500 ? "SERVER_ERROR" : "UNKNOWN_ERROR"), (serverError?.message ?? body) || `HTTP ${status}`, { status, url, kind: serverError?.kind, path: serverError?.path, port: serverError?.port, fix: serverError?.fix, shortfall: serverError?.shortfall, ...slots, failedOps: serverError?.failedOps?.map((op) => ({ ...op, kind: op.kind })), succeededOps: serverError?.succeededOps }); }; export { ComposeError, errorFromHttpResponse, isComposeDeliveryError, isComposeError, isComposePreparationError, isComposeSdkOutdatedError, isComposeServerOutdatedError }; //# sourceMappingURL=errors.js.map