@lifi/composer-sdk 0.6.1 → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -10
- package/dist/client.cjs +1 -1
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +7 -7
- package/dist/client.d.ts +7 -7
- package/dist/client.js +1 -1
- package/dist/client.js.map +1 -1
- package/dist/errors.cjs +20 -1
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.cts +18 -1
- package/dist/errors.d.ts +18 -1
- package/dist/errors.js +20 -1
- package/dist/errors.js.map +1 -1
- package/dist/index.cjs +3 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/reachability.cjs +123 -0
- package/dist/reachability.cjs.map +1 -0
- package/dist/reachability.d.cts +71 -0
- package/dist/reachability.d.ts +71 -0
- package/dist/reachability.js +99 -0
- package/dist/reachability.js.map +1 -0
- package/dist/responseSchemas.cjs +5 -1
- package/dist/responseSchemas.cjs.map +1 -1
- package/dist/responseSchemas.d.cts +4 -0
- package/dist/responseSchemas.d.ts +4 -0
- package/dist/responseSchemas.js +5 -1
- package/dist/responseSchemas.js.map +1 -1
- package/package.json +2 -2
- package/src/client.ts +7 -7
- package/src/errors.ts +22 -1
- package/src/index.ts +7 -0
- package/src/reachability.ts +203 -0
- package/src/responseSchemas.ts +11 -1
package/README.md
CHANGED
|
@@ -162,12 +162,13 @@ if (result.status === 'success') {
|
|
|
162
162
|
- `raw.guard(kind, config?)` / `raw.materialiser(kind, config?)` — low-level factories for guards and materialisers
|
|
163
163
|
- `buildSimulateRequest({ result, chainId, signer, trackedBalances, requirements?, block?, value? })` — assembles a `SimulateRequest` from a compile result (pure, no I/O)
|
|
164
164
|
- `routeAmount.exact(amount)` / `routeAmount.all(simAmount)` — amount constructors for `sdk.route(...)`
|
|
165
|
+
- `buildReachability(packs, { maxHops?, allowAsyncRoutes? })` — computes the pairs `route` can connect by chaining catalog edges (pure, no I/O). See [Discovering routable pairs](#discovering-routable-pairs).
|
|
165
166
|
|
|
166
167
|
## Routing a token pair
|
|
167
168
|
|
|
168
169
|
Authoring a flow is the general path: you decide the operations and how they chain. `sdk.route(...)` is the shortcut for the case where the backend can decide for you — you hand it a from/to token pair, an amount, and a signer, and it returns the same submit-ready `ComposeCompileResult` that `compile()` returns.
|
|
169
170
|
|
|
170
|
-
|
|
171
|
+
The backend plans a short chain of steps for that pair: up to a few edges of its routing catalog — entering or exiting a protocol position, a wrap or unwrap, a mint or burn — optionally opened by one `lifi.swap` when the input token has to be sold first. Every intermediate step settles inside the proxy in the same transaction; only the last step may pay out to a recipient or land after settlement (and the latter only with `allowAsyncRoutes`). A route that opens with a swap requires `sweepTo`, because the swap can leave a residue of the sold token in the proxy. A pair the planner cannot connect comes back as `no_route_error` whose `details` report the hop budget (`maxHops`) and whether the search was cut short (`searchTruncated`). It is not a general swap aggregator: a swap is only used as a first step into a hub token or into the underlying of the next deposit.
|
|
171
172
|
|
|
172
173
|
```ts
|
|
173
174
|
import { createComposeSdk, routeAmount } from '@lifi/composer-sdk';
|
|
@@ -193,19 +194,29 @@ if (result.status === 'success') {
|
|
|
193
194
|
|
|
194
195
|
### Discovering routable pairs
|
|
195
196
|
|
|
196
|
-
The catalog is dynamic — protocols, chains, and token blacklists move — so discover pairs instead of hardcoding them:
|
|
197
|
+
The catalog is dynamic — protocols, chains, and token blacklists move — so discover pairs instead of hardcoding them. `getZapPacks` lists single routing edges; `route` chains up to the server's hop budget of them, so the pairs it connects are the closure of the catalog, not the catalog itself. `buildReachability` computes that closure locally with the planner's rule:
|
|
197
198
|
|
|
198
199
|
```ts
|
|
199
|
-
|
|
200
|
+
import { buildReachability } from '@lifi/composer-sdk';
|
|
200
201
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
202
|
+
const packs = await sdk.client.getZapPacks();
|
|
203
|
+
const reach = buildReachability(packs);
|
|
204
|
+
|
|
205
|
+
reach.canRoute(aUsdc, yvUsdc); // aUSDC -> USDC -> yvUSDC: true
|
|
206
|
+
for (const pair of reach.routableFrom(aUsdc)) {
|
|
207
|
+
console.log(pair.in.address, '->', pair.out.address, `(${pair.hops} hops)`);
|
|
205
208
|
}
|
|
206
209
|
```
|
|
207
210
|
|
|
208
|
-
|
|
211
|
+
`pair.in` and `pair.out` are the `fromToken` and `toToken` of a `route` call on `pair.in.chainId`. The rule the helper applies, and `route` enforces:
|
|
212
|
+
|
|
213
|
+
- every edge except the last must leave its output in the proxy for the next edge to consume, so an edge with `recipient: 'required'` or `availability: 'future'` can only be the last hop
|
|
214
|
+
- the last edge must be synchronous unless you pass `allowAsyncRoutes: true` to both `buildReachability` and `route`
|
|
215
|
+
- a route never visits the same token twice, and never exceeds `maxHops`
|
|
216
|
+
|
|
217
|
+
`maxHops` defaults to 2, the deployment default; the server reports its effective value in `no_route_error.details.maxHops`, so raise the option if that differs. `inAmountMin` / `inAmountMax` bound the amount when the protocol constrains an edge; the helper cannot apply them to an intermediate hop without an amount, so a reported pair is routable structurally, exactly as a listed edge is. Routes that open with a `lifi.swap` depend on what the aggregator can sell and are not enumerable.
|
|
218
|
+
|
|
219
|
+
Two edge fields change how you call `route`:
|
|
209
220
|
|
|
210
221
|
- **`recipient: 'required'`** — the protocol mints to a named receiver, so set `sweepTo` when the output should not land with the signer.
|
|
211
222
|
- **`availability: 'future'`** — the output only exists once the transaction settles. `route` skips these unless you pass `allowAsyncRoutes: true`, so by default a pair reachable only this way is a `no_route_error` and every terminal output delivers now (`delivery.when: 'now'`). Opt in and `sweepTo` names the future output's owner, no slippage floor is applied, and you must track settlement rather than treat the transaction as completing the job. A synchronous edge still wins whenever the pair has one, so read each terminal output's `delivery.when` in `result.outputs` to know which representation you got.
|
|
@@ -235,13 +246,13 @@ Both accept a `bigint` or a decimal string. `bigint` values are serialised for y
|
|
|
235
246
|
|
|
236
247
|
### When to author a flow instead
|
|
237
248
|
|
|
238
|
-
`route` gives you
|
|
249
|
+
`route` gives you a short server-planned chain: the server picks the catalog edges (and at most one opening swap) for you. Reach for `sdk.flow(...)` when you need anything it does not express: a chain you choose yourself or one longer than the server's hop ceiling, splitting one input across several destinations, guards on intermediate outputs, explicit preconditions, arithmetic, or funding from proxy-held balances. Swapping WETH to USDC and then depositing the USDC into Aave is a route when the server can plan it (USDC is the deposit's underlying) and a flow when you want to control the swap yourself or add steps around it; depositing USDC straight into Aave is a route. An asynchronous position (`availability: 'future'`) as the destination is a route once you pass `allowAsyncRoutes: true` — the server picks `lifi.zapAsync` for you — but authoring the flow yourself is still the way to combine it with other steps.
|
|
239
250
|
|
|
240
251
|
### Errors
|
|
241
252
|
|
|
242
253
|
`route` maps failures the same way `compile` does — see [Error handling](#error-handling). Two are specific to this path:
|
|
243
254
|
|
|
244
|
-
- **`NOT_FOUND`** with `kind: 'no_route_error'` — the
|
|
255
|
+
- **`NOT_FOUND`** with `kind: 'no_route_error'` — the planner cannot connect the pair on that chain within `details.maxHops` catalog edges; `details.searchTruncated` reports whether the search hit its work bound. `buildReachability(await sdk.client.getZapPacks())` reports which pairs do connect.
|
|
245
256
|
- **`VALIDATION_ERROR`** — the pair is routable but the request is rejected, for example a price impact above `maxPriceImpactBps`, or a simulation revert under the default `'strict'` policy.
|
|
246
257
|
|
|
247
258
|
## Simulation policy and partial results
|
package/dist/client.cjs
CHANGED
|
@@ -25,7 +25,7 @@ module.exports = __toCommonJS(client_exports);
|
|
|
25
25
|
var import_compose_spec = require("@lifi/compose-spec");
|
|
26
26
|
var import_errors = require("./errors.js");
|
|
27
27
|
var import_responseSchemas = require("./responseSchemas.js");
|
|
28
|
-
const SDK_VERSION = true ? "0.6.
|
|
28
|
+
const SDK_VERSION = true ? "0.6.2" : "dev";
|
|
29
29
|
const SDK_VERSION_TRIPLE = (0, import_compose_spec.parseVersion)(SDK_VERSION);
|
|
30
30
|
const bigintReplacer = (_key, value) => typeof value === "bigint" ? value.toString() : value;
|
|
31
31
|
const isNonNullObject = (v) => typeof v === "object" && v !== null;
|
package/dist/client.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client.ts"],"sourcesContent":["import type {\n ComposeCompilePartialData,\n ComposeCompileRequest,\n ComposeCompileResult,\n ComposeCompileSuccessData,\n ComposeManifest,\n ComposeRouteRequest,\n SimulateRequest,\n SimulateResult,\n} from '@lifi/compose-spec';\nimport {\n checkCompatibility,\n COMPOSE_VERSION_HEADER,\n COMPOSER_SDK_VERSION_HEADER,\n parseVersion,\n} from '@lifi/compose-spec';\n\nimport type {\n ChainSummary,\n GetZapPacksOptions,\n ZapPackOverview,\n} from './discovery.js';\nimport { ComposeError, errorFromHttpResponse } from './errors.js';\nimport {\n parseCompilePartialEnvelope,\n parseSimulateResult,\n} from './responseSchemas.js';\n\n// __SDK_VERSION__ is a compile-time constant injected by tsup (via `define` in tsup.config.ts)\n// and by vitest (via `define` in vitest.config.ts). Both read the version from package.json\n// at build/test time and replace this identifier with the literal string value.\n// It is sent as the `COMPOSER_SDK_VERSION_HEADER` request header so the server can identify the caller.\n// Falls back to 'dev' when running via tsx without tsup substitution (e.g. the example harness).\ndeclare const __SDK_VERSION__: string;\n\nconst SDK_VERSION: string =\n typeof __SDK_VERSION__ !== 'undefined' ? __SDK_VERSION__ : 'dev';\n// `undefined` for the `dev` sentinel, which disables the response version check.\nconst SDK_VERSION_TRIPLE = parseVersion(SDK_VERSION);\n\n/**\n * Configuration for creating a low-level Compose API client.\n */\nexport interface ComposeClientOptions {\n /** Base URL of the Compose API. */\n readonly baseUrl: string;\n /** Optional custom `fetch` implementation. Defaults to `globalThis.fetch`. */\n readonly fetch?: typeof globalThis.fetch;\n /** LI.FI API key, sent as the `x-lifi-api-key` header on every request. Required — the Compose API rejects unauthenticated requests. */\n readonly apiKey: string;\n}\n\n/**\n * Low-level HTTP client for the Compose API.\n *\n * Handles request serialization, SDK version headers, and error mapping.\n * Prefer using {@link ComposeSdk} for the full builder experience. Use this\n * directly when you need to decouple request building from submission — e.g.\n * build via `sdk.request()` then submit via `client.compile()` with custom\n * retry logic or request inspection.\n */\nexport interface ComposeClient {\n /**\n * Fetches the server's operation manifest describing all supported operations,\n * guards, materialisers, and preconditions.\n * @returns The manifest document.\n * @throws {@link ComposeError} on network, validation, or server errors.\n */\n readonly getManifest: () => Promise<ComposeManifest>;\n /**\n * Fetches the chains the Compose API supports, ascending by `chainId`.\n *\n * A chain is listed once the server confirms the VM contract is deployed on\n * it — the same condition {@link compile}, {@link route} and\n * {@link simulate} validate against. A chain absent from this list is\n * rejected outright by those endpoints.\n *\n * The converse does not hold: a listed chain can still have no routing edge\n * for a given token pair, which {@link route} reports as `no_route_error`.\n * Use {@link getZapPacks} to enumerate the pairs that do route.\n *\n * Each entry carries a display `name` alongside its `chainId`. The name is a\n * deployment-maintained label — render it, but key on `chainId`.\n *\n * The list tracks the server's chain registry, which refreshes periodically.\n * Results are not cached by the SDK; callers should cache as appropriate.\n *\n * @returns The supported chains, ascending by `chainId`.\n * @throws {@link ComposeError} on network or server errors.\n */\n readonly getChains: () => Promise<readonly ChainSummary[]>;\n /**\n * Submits a compile request and returns the result.\n *\n * When the caller passes `simulationPolicy: 'allow-revert'` and the transaction\n * reverts in simulation, the server responds with HTTP 206 and the SDK returns a\n * partial result (`status: 'partial'`) instead of throwing. The partial result\n * includes the transaction (without `gasLimit`) and revert diagnostics.\n *\n * @param request - The full compile request including flow and run inputs.\n * @returns A discriminated result: `status: 'success'` or `status: 'partial'`.\n * @throws {@link ComposeError} on network, validation, or server errors.\n */\n readonly compile: (\n request: ComposeCompileRequest,\n ) => Promise<ComposeCompileResult>;\n /**\n * Compiles a token pair into a submit-ready transaction via\n * `POST /compose/route`.\n *\n * A convenience path that skips flow authoring: the server builds a one-node\n * zap flow with a `directDeposit` input from the `fromToken` / `toToken`\n * pair and runs it through the same pipeline as {@link compile}. The\n * response is therefore the same discriminated result — HTTP 206 under\n * `simulationPolicy: 'allow-revert'` yields `status: 'partial'` rather than\n * throwing, exactly as it does for {@link compile}.\n *\n * As of today that flow is a single zap step: one edge of the backend's\n * routing catalog (a position entry or exit, a wrap or unwrap, a mint or\n * burn). Enumerate the pairs it covers with {@link getZapPacks}; a pair with\n * no edge is rejected with `kind: 'no_route_error'`. The endpoint is meant to\n * author richer flows later, so the single-step limit is the current state of\n * the server, not the shape of this contract.\n *\n * Only synchronous edges are considered unless the request sets\n * `allowAsyncRoutes: true`, so by default every terminal output comes back\n * `delivery.when: 'now'` and a pair reachable only after settlement is a\n * `no_route_error`. Opting in adds the `lifi.zapAsync` fallback, which still\n * loses to a synchronous edge when the pair has one; read\n * `outputs[*].delivery.when` to see which representation you got.\n *\n * Use {@link compile} for what the server does not author for you: several\n * chained operations, splits, explicit preconditions, or per-op guards.\n *\n * `bigint` amounts in `amount` are serialised to decimal strings\n * automatically.\n *\n * @param request - The from/to token pair, amount, signer, and route options.\n * @returns A discriminated result: `status: 'success'` or `status: 'partial'`.\n * @throws {@link ComposeError} on network, validation, or server errors —\n * including `NOT_FOUND` (HTTP 404) when no catalog edge covers the pair.\n */\n readonly route: (\n request: ComposeRouteRequest,\n ) => Promise<ComposeCompileResult>;\n /**\n * Fetches the available routing edges grouped by protocol.\n *\n * The edge catalog is dynamic — it reflects the current state of the\n * backend's routing snapshot (protocols, chains, token blacklists).\n * Results are not cached by the SDK; callers should cache as appropriate.\n *\n * @param options - Optional filter to restrict results to specific protocols.\n * @returns An array of {@link ZapPackOverview} objects, one per protocol.\n * @throws {@link ComposeError} on network or server errors (503 when the\n * routing catalog is not yet initialized).\n */\n readonly getZapPacks: (\n options?: GetZapPacksOptions,\n ) => Promise<readonly ZapPackOverview[]>;\n /**\n * Simulates a raw, pre-encoded transaction against `POST /simulate` and\n * reports how the watched balances change and how much inner-call gas it\n * burns.\n *\n * The result is a discriminated union on `status`:\n * - `'ok'` — the simulation ran successfully; `deltas`/`gasUsed` are populated.\n * - `'revert'` — the simulation ran but the transaction reverted on-chain. A\n * revert is a *successful simulation*, not a transport error, so it is\n * returned (HTTP 200) rather than thrown — mirroring how {@link compile}\n * returns `status: 'partial'` on a simulated revert.\n * - `'error'` — the request was well-formed but the simulation could not be\n * set up or run (HTTP 422); `message` is intentionally generic.\n *\n * `bigint` amounts in the request (`value`, requirement `balance`/`allowance`)\n * are serialised to decimal strings automatically.\n *\n * @param request - The raw transaction plus funding `requirements` and the\n * `trackedBalances` to watch.\n * @returns A {@link SimulateResult} (`ok` / `revert` / `error`).\n * @throws {@link ComposeError} on network failures, HTTP 400 (malformed\n * input), 401/403 (auth), 404, 429, and 5xx.\n */\n readonly simulate: (request: SimulateRequest) => Promise<SimulateResult>;\n}\n\n/**\n * `JSON.stringify` replacer that renders `bigint` amounts as decimal strings.\n *\n * The compose wire carries token amounts as decimal strings, and `bigint` has\n * no JSON representation, so every payload this client sends goes through it.\n * Exported so the example harness prints a request exactly as it is sent.\n */\nexport const bigintReplacer = (_key: string, value: unknown): unknown =>\n typeof value === 'bigint' ? value.toString() : value;\n\nconst isNonNullObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null;\n\n// Non-negative decimal integer string, as the server sends token amounts.\nconst INTEGER_STRING = /^\\d+$/;\n\nconst decodeAmount = (value: unknown, path: string, url: string): bigint => {\n if (typeof value !== 'string' || !INTEGER_STRING.test(value)) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n `Malformed compose response: ${path} is ${\n value === undefined ? 'absent' : 'not an integer string'\n }`,\n { url },\n );\n }\n return BigInt(value);\n};\n\n// The two records this seam reads out of a compile-family response body. Each\n// is `unknown` because the seam is what establishes its shape: it validates\n// every field before writing a decoded `bigint` back over the wire string.\ninterface WireAmountBody {\n outputs?: unknown;\n}\n\n// One `Amount` as it arrives: each leaf is `unknown` until this seam has\n// checked it, and is overwritten in place with the decoded `bigint`.\ninterface WireAmount {\n estimate?: unknown;\n minimum?: unknown;\n}\n\nconst malformed = (path: string, what: string, url: string): ComposeError =>\n new ComposeError(\n 'UNKNOWN_ERROR',\n `Malformed compose response: ${path} ${what}`,\n { url },\n );\n\n// Decode one `Estimate` / `Minimum` leaf in place: `{ basis, value }` with\n// `value` a decimal string on the wire and a `bigint` on `Amount`.\nconst decodeAmountLeaf = (\n amount: WireAmount,\n field: 'estimate' | 'minimum',\n path: string,\n url: string,\n): void => {\n const leaf = amount[field];\n if (leaf === undefined) return;\n if (!isNonNullObject(leaf)) {\n throw malformed(`${path}.${field}`, 'is not an object', url);\n }\n leaf.value = decodeAmount(leaf.value, `${path}.${field}.value`, url);\n};\n\n// `outputs` is REQUIRED on every compile-family body and is the record a\n// caller reads amounts from, so its structure is checked here — the body is\n// cast, not schema-parsed — before each `value` leaf becomes a `bigint`.\nconst decodeOutputs = (data: WireAmountBody, url: string): void => {\n const outputs = data.outputs;\n if (!isNonNullObject(outputs)) {\n throw malformed(\n 'outputs',\n outputs === undefined ? 'is absent' : 'is not an object',\n url,\n );\n }\n for (const key of Object.keys(outputs)) {\n const entry = outputs[key];\n if (!isNonNullObject(entry)) {\n throw malformed(`outputs.${key}`, 'is not an object', url);\n }\n const amount = entry.amount;\n if (!isNonNullObject(amount)) {\n throw malformed(\n `outputs.${key}.amount`,\n amount === undefined ? 'is absent' : 'is not an object',\n url,\n );\n }\n decodeAmountLeaf(amount, 'estimate', `outputs.${key}.amount`, url);\n decodeAmountLeaf(amount, 'minimum', `outputs.${key}.amount`, url);\n }\n};\n\n// THE decode seam for a compile-family response body: every amount the wire\n// renders as a decimal string becomes the `bigint` its declared type promises.\n// The amount record is handled here so the body is narrowed once — a\n// non-object body is not this function's error to raise, since the enveloping\n// parse already rejected it.\nconst decodeWireAmounts = (data: unknown, url: string): void => {\n if (!isNonNullObject(data)) return;\n decodeOutputs(data, url);\n};\n\nconst parseBody = async <T>(res: Response, url: string): Promise<T> => {\n const body = await res.json().catch((_) => null);\n if (!isNonNullObject(body) || !('data' in body)) {\n throw new ComposeError('UNKNOWN_ERROR', 'Unexpected response format', {\n url,\n });\n }\n return body.data as T;\n};\n\nconst parseCompileSuccessBody = async (\n res: Response,\n url: string,\n): Promise<ComposeCompileResult> => {\n const data = await parseBody<ComposeCompileSuccessData>(res, url);\n decodeWireAmounts(data, url);\n return { ...data, status: 'success' as const };\n};\n\nconst parsePartialBody = async (\n res: Response,\n url: string,\n): Promise<ComposeCompileResult> => {\n const body = await res.json().catch((_) => null);\n const envelope = parseCompilePartialEnvelope(body);\n if (envelope === null) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n 'Unexpected partial response format',\n { url },\n );\n }\n // `data` is validated as an object by the schema; compose-spec owns its full\n // shape as a hand-authored type, so we narrow it here rather than re-declaring\n // that type as a schema. `error` is fully validated — no cast needed.\n const data = envelope.data as ComposeCompilePartialData;\n decodeWireAmounts(data, url);\n return { ...data, status: 'partial' as const, error: envelope.error };\n};\n\n// `/simulate` is un-enveloped: the discriminated body (`{ status, ... }`) is at\n// the top level, NOT wrapped in `{ data }` like `/compose`. So this reads the\n// body directly and validates it against the simulate union rather than reusing\n// `parseBody`.\nconst parseSimulateBody = async (\n res: Response,\n url: string,\n): Promise<SimulateResult> => {\n const body = await res.json().catch((_) => null);\n const result = parseSimulateResult(body);\n if (result === null) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n 'Unexpected simulate response format',\n { url },\n );\n }\n return result;\n};\n// `POST /compose` and `POST /compose/route` differ only in path and request\n// shape: both return the enveloped success data on 200 and the partial\n// envelope on 206, so they share one transport.\ntype ComposeTransport = {\n readonly fetchFn: typeof fetch;\n readonly baseHeaders: Record<string, string>;\n};\n\n// A patch bump is additive and a minor bump is breaking, so a 200 from a\n// backend behind this SDK cannot be trusted: the newer flow this SDK authored\n// may have compiled under the server's older semantics without raising an\n// error. This covers the deploy window where the SDK is published to npm ahead\n// of the backend rollout. Only the compile-family POSTs are checked; discovery\n// GETs stay reachable from a mismatched SDK, as on the server. An absent header\n// (a pre-gate backend, a header-stripping proxy) is accepted, mirroring the\n// server's pass-through of a compile that carries no version header.\nconst assertServerVersion = (res: Response, url: string): void => {\n const serverVersion = res.headers.get(COMPOSE_VERSION_HEADER);\n if (serverVersion === null || SDK_VERSION_TRIPLE === undefined) return;\n const serverTriple = parseVersion(serverVersion);\n if (serverTriple === undefined) return;\n\n const compatibility = checkCompatibility(SDK_VERSION_TRIPLE, serverTriple);\n if (compatibility === 'compatible') return;\n\n const versions = { sdkVersion: SDK_VERSION, serverVersion };\n if (compatibility === 'sdk_outdated') {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `composer-sdk ${SDK_VERSION} is older than the compose contract served at ${url} (${serverVersion}); upgrade @lifi/composer-sdk and @lifi/compose-spec`,\n {\n status: res.status,\n url,\n kind: 'sdk_outdated',\n sdkOutdated: {\n ...versions,\n minimumSdkVersion: `${serverTriple.major}.${serverTriple.minor}.0`,\n },\n },\n );\n }\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `composer-sdk ${SDK_VERSION} targets a newer compose contract than the server at ${url} serves (${serverVersion}); pin @lifi/composer-sdk and @lifi/compose-spec to ${serverVersion} or wait for the server rollout`,\n {\n status: res.status,\n url,\n kind: 'server_outdated',\n serverOutdated: versions,\n },\n );\n};\n\ntype SendInit =\n | { readonly method: 'GET' }\n | { readonly method: 'POST'; readonly body: unknown };\n\n// GETs on this API carry no body; POSTs carry a JSON one with `bigint` amounts\n// rendered as decimal strings.\nconst requestInit = (\n baseHeaders: Record<string, string>,\n init: SendInit,\n): RequestInit =>\n init.method === 'GET'\n ? { method: 'GET', headers: { ...baseHeaders } }\n : {\n method: 'POST',\n headers: { ...baseHeaders, 'Content-Type': 'application/json' },\n body: JSON.stringify(init.body, bigintReplacer),\n };\n\n// One fetch path for every route: maps transport failures to `NETWORK_ERROR`.\n// The response version check is not here — only the compile-family POSTs gate\n// on it (see `postCompile`); discovery GETs and `/simulate` are ungated.\nconst send = async (\n { fetchFn, baseHeaders }: ComposeTransport,\n url: string,\n init: SendInit,\n): Promise<Response> => {\n try {\n return await fetchFn(url, requestInit(baseHeaders, init));\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n};\n\nconst postCompile = async (\n transport: ComposeTransport,\n url: string,\n request: ComposeCompileRequest | ComposeRouteRequest,\n): Promise<ComposeCompileResult> => {\n const res = await send(transport, url, { method: 'POST', body: request });\n assertServerVersion(res, url);\n if (res.status === 206) {\n return await parsePartialBody(res, url);\n }\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseCompileSuccessBody(res, url);\n};\n\n// Every enveloped GET on this API behaves identically: no body, no query\n// semantics of its own, `{ data }` on success, an error envelope otherwise.\nconst getJson = async <T>(\n transport: ComposeTransport,\n url: string,\n): Promise<T> => {\n const res = await send(transport, url, { method: 'GET' });\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseBody<T>(res, url);\n};\n\n/**\n * Creates a low-level Compose API client.\n *\n * @param options - Client configuration including the API base URL.\n * @returns A {@link ComposeClient} instance.\n */\nexport const createComposeClient = (\n options: ComposeClientOptions,\n): ComposeClient => {\n if (!options.baseUrl || !/^https?:\\/\\//i.test(options.baseUrl)) {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `Invalid baseUrl: expected an HTTP(S) URL, got \"${options.baseUrl}\"`,\n );\n }\n const trimmedApiKey = options.apiKey?.trim() || undefined;\n if (!trimmedApiKey) {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n 'apiKey is required: pass a LI.FI API key to createComposeSdk().',\n );\n }\n const fetchFn = options.fetch ?? globalThis.fetch;\n const base = options.baseUrl.replace(/\\/$/, '');\n\n const baseHeaders: Record<string, string> = {\n Accept: 'application/json',\n [COMPOSER_SDK_VERSION_HEADER]: SDK_VERSION,\n 'x-lifi-api-key': trimmedApiKey,\n };\n const transport: ComposeTransport = { fetchFn, baseHeaders };\n\n const getManifest = async (): Promise<ComposeManifest> =>\n getJson<ComposeManifest>(transport, `${base}/compose/manifest`);\n\n const getChains = async (): Promise<readonly ChainSummary[]> =>\n getJson<readonly ChainSummary[]>(transport, `${base}/chains`);\n\n const compile = async (\n request: ComposeCompileRequest,\n ): Promise<ComposeCompileResult> =>\n postCompile(transport, `${base}/compose`, request);\n\n const route = async (\n request: ComposeRouteRequest,\n ): Promise<ComposeCompileResult> =>\n postCompile(transport, `${base}/compose/route`, request);\n\n const getZapPacks = async (\n options?: GetZapPacksOptions,\n ): Promise<readonly ZapPackOverview[]> => {\n const params = new URLSearchParams();\n if (options?.protocols !== undefined) {\n // Backend expects a single comma-separated value, not repeated keys.\n const raw = options.protocols;\n const list = typeof raw === 'string' ? raw : raw.join(',');\n params.set('protocols', list);\n }\n const qs = params.toString();\n return getJson<readonly ZapPackOverview[]>(\n transport,\n `${base}/compose/zap-packs${qs ? `?${qs}` : ''}`,\n );\n };\n\n const simulate = async (\n request: SimulateRequest,\n ): Promise<SimulateResult> => {\n const url = `${base}/simulate`;\n const res = await send(transport, url, { method: 'POST', body: request });\n // Only 200 (carries `ok`/`revert`) and 422 (carries the `error` member of\n // the union) have a discriminated body. 422 is deliberately intercepted\n // here (not thrown as VALIDATION_ERROR) so callers get one exhaustive\n // `switch (result.status)`. Every other status is a transport error and is\n // thrown — including HTTP 400 (malformed input, no `status` body) and any\n // unexpected 2xx.\n if (res.status === 200 || res.status === 422) {\n return await parseSimulateBody(res, url);\n }\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n };\n\n return { getManifest, getChains, compile, route, getZapPacks, simulate };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUA,0BAKO;AAOP,oBAAoD;AACpD,6BAGO;AASP,MAAM,cACJ,OAAyC,UAAkB;AAE7D,MAAM,yBAAqB,kCAAa,WAAW;AA2J5C,MAAM,iBAAiB,CAAC,MAAc,UAC3C,OAAO,UAAU,WAAW,MAAM,SAAS,IAA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":["options"]}
|
|
1
|
+
{"version":3,"sources":["../src/client.ts"],"sourcesContent":["import type {\n ComposeCompilePartialData,\n ComposeCompileRequest,\n ComposeCompileResult,\n ComposeCompileSuccessData,\n ComposeManifest,\n ComposeRouteRequest,\n SimulateRequest,\n SimulateResult,\n} from '@lifi/compose-spec';\nimport {\n checkCompatibility,\n COMPOSE_VERSION_HEADER,\n COMPOSER_SDK_VERSION_HEADER,\n parseVersion,\n} from '@lifi/compose-spec';\n\nimport type {\n ChainSummary,\n GetZapPacksOptions,\n ZapPackOverview,\n} from './discovery.js';\nimport { ComposeError, errorFromHttpResponse } from './errors.js';\nimport {\n parseCompilePartialEnvelope,\n parseSimulateResult,\n} from './responseSchemas.js';\n\n// __SDK_VERSION__ is a compile-time constant injected by tsup (via `define` in tsup.config.ts)\n// and by vitest (via `define` in vitest.config.ts). Both read the version from package.json\n// at build/test time and replace this identifier with the literal string value.\n// It is sent as the `COMPOSER_SDK_VERSION_HEADER` request header so the server can identify the caller.\n// Falls back to 'dev' when running via tsx without tsup substitution (e.g. the example harness).\ndeclare const __SDK_VERSION__: string;\n\nconst SDK_VERSION: string =\n typeof __SDK_VERSION__ !== 'undefined' ? __SDK_VERSION__ : 'dev';\n// `undefined` for the `dev` sentinel, which disables the response version check.\nconst SDK_VERSION_TRIPLE = parseVersion(SDK_VERSION);\n\n/**\n * Configuration for creating a low-level Compose API client.\n */\nexport interface ComposeClientOptions {\n /** Base URL of the Compose API. */\n readonly baseUrl: string;\n /** Optional custom `fetch` implementation. Defaults to `globalThis.fetch`. */\n readonly fetch?: typeof globalThis.fetch;\n /** LI.FI API key, sent as the `x-lifi-api-key` header on every request. Required — the Compose API rejects unauthenticated requests. */\n readonly apiKey: string;\n}\n\n/**\n * Low-level HTTP client for the Compose API.\n *\n * Handles request serialization, SDK version headers, and error mapping.\n * Prefer using {@link ComposeSdk} for the full builder experience. Use this\n * directly when you need to decouple request building from submission — e.g.\n * build via `sdk.request()` then submit via `client.compile()` with custom\n * retry logic or request inspection.\n */\nexport interface ComposeClient {\n /**\n * Fetches the server's operation manifest describing all supported operations,\n * guards, materialisers, and preconditions.\n * @returns The manifest document.\n * @throws {@link ComposeError} on network, validation, or server errors.\n */\n readonly getManifest: () => Promise<ComposeManifest>;\n /**\n * Fetches the chains the Compose API supports, ascending by `chainId`.\n *\n * A chain is listed once the server confirms the VM contract is deployed on\n * it — the same condition {@link compile}, {@link route} and\n * {@link simulate} validate against. A chain absent from this list is\n * rejected outright by those endpoints.\n *\n * The converse does not hold: a listed chain can still have no routing edge\n * for a given token pair, which {@link route} reports as `no_route_error`.\n * Use {@link getZapPacks} to enumerate the pairs that do route.\n *\n * Each entry carries a display `name` alongside its `chainId`. The name is a\n * deployment-maintained label — render it, but key on `chainId`.\n *\n * The list tracks the server's chain registry, which refreshes periodically.\n * Results are not cached by the SDK; callers should cache as appropriate.\n *\n * @returns The supported chains, ascending by `chainId`.\n * @throws {@link ComposeError} on network or server errors.\n */\n readonly getChains: () => Promise<readonly ChainSummary[]>;\n /**\n * Submits a compile request and returns the result.\n *\n * When the caller passes `simulationPolicy: 'allow-revert'` and the transaction\n * reverts in simulation, the server responds with HTTP 206 and the SDK returns a\n * partial result (`status: 'partial'`) instead of throwing. The partial result\n * includes the transaction (without `gasLimit`) and revert diagnostics.\n *\n * @param request - The full compile request including flow and run inputs.\n * @returns A discriminated result: `status: 'success'` or `status: 'partial'`.\n * @throws {@link ComposeError} on network, validation, or server errors.\n */\n readonly compile: (\n request: ComposeCompileRequest,\n ) => Promise<ComposeCompileResult>;\n /**\n * Compiles a token pair into a submit-ready transaction via\n * `POST /compose/route`.\n *\n * A convenience path that skips flow authoring: the server builds a one-node\n * zap flow with a `directDeposit` input from the `fromToken` / `toToken`\n * pair and runs it through the same pipeline as {@link compile}. The\n * response is therefore the same discriminated result — HTTP 206 under\n * `simulationPolicy: 'allow-revert'` yields `status: 'partial'` rather than\n * throwing, exactly as it does for {@link compile}.\n *\n * The server plans a short chain of catalog edges for the pair (a position\n * entry or exit, a wrap or unwrap, a mint or burn), optionally opened by a\n * `lifi.swap`. {@link getZapPacks} lists the single edges; the pairs the\n * planner connects are their closure up to the hop budget, which\n * {@link buildReachability} computes locally. A pair the planner cannot\n * connect is rejected with `kind: 'no_route_error'`.\n *\n * Only synchronous edges are considered unless the request sets\n * `allowAsyncRoutes: true`, so by default every terminal output comes back\n * `delivery.when: 'now'` and a pair reachable only after settlement is a\n * `no_route_error`. Opting in adds the `lifi.zapAsync` fallback, which still\n * loses to a synchronous edge when the pair has one; read\n * `outputs[*].delivery.when` to see which representation you got.\n *\n * Use {@link compile} for what the server does not author for you: several\n * chained operations, splits, explicit preconditions, or per-op guards.\n *\n * `bigint` amounts in `amount` are serialised to decimal strings\n * automatically.\n *\n * @param request - The from/to token pair, amount, signer, and route options.\n * @returns A discriminated result: `status: 'success'` or `status: 'partial'`.\n * @throws {@link ComposeError} on network, validation, or server errors —\n * including `NOT_FOUND` (HTTP 404) when the planner cannot connect the pair.\n */\n readonly route: (\n request: ComposeRouteRequest,\n ) => Promise<ComposeCompileResult>;\n /**\n * Fetches the available routing edges grouped by protocol.\n *\n * The edge catalog is dynamic — it reflects the current state of the\n * backend's routing snapshot (protocols, chains, token blacklists).\n * Results are not cached by the SDK; callers should cache as appropriate.\n *\n * @param options - Optional filter to restrict results to specific protocols.\n * @returns An array of {@link ZapPackOverview} objects, one per protocol.\n * @throws {@link ComposeError} on network or server errors (503 when the\n * routing catalog is not yet initialized).\n */\n readonly getZapPacks: (\n options?: GetZapPacksOptions,\n ) => Promise<readonly ZapPackOverview[]>;\n /**\n * Simulates a raw, pre-encoded transaction against `POST /simulate` and\n * reports how the watched balances change and how much inner-call gas it\n * burns.\n *\n * The result is a discriminated union on `status`:\n * - `'ok'` — the simulation ran successfully; `deltas`/`gasUsed` are populated.\n * - `'revert'` — the simulation ran but the transaction reverted on-chain. A\n * revert is a *successful simulation*, not a transport error, so it is\n * returned (HTTP 200) rather than thrown — mirroring how {@link compile}\n * returns `status: 'partial'` on a simulated revert.\n * - `'error'` — the request was well-formed but the simulation could not be\n * set up or run (HTTP 422); `message` is intentionally generic.\n *\n * `bigint` amounts in the request (`value`, requirement `balance`/`allowance`)\n * are serialised to decimal strings automatically.\n *\n * @param request - The raw transaction plus funding `requirements` and the\n * `trackedBalances` to watch.\n * @returns A {@link SimulateResult} (`ok` / `revert` / `error`).\n * @throws {@link ComposeError} on network failures, HTTP 400 (malformed\n * input), 401/403 (auth), 404, 429, and 5xx.\n */\n readonly simulate: (request: SimulateRequest) => Promise<SimulateResult>;\n}\n\n/**\n * `JSON.stringify` replacer that renders `bigint` amounts as decimal strings.\n *\n * The compose wire carries token amounts as decimal strings, and `bigint` has\n * no JSON representation, so every payload this client sends goes through it.\n * Exported so the example harness prints a request exactly as it is sent.\n */\nexport const bigintReplacer = (_key: string, value: unknown): unknown =>\n typeof value === 'bigint' ? value.toString() : value;\n\nconst isNonNullObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null;\n\n// Non-negative decimal integer string, as the server sends token amounts.\nconst INTEGER_STRING = /^\\d+$/;\n\nconst decodeAmount = (value: unknown, path: string, url: string): bigint => {\n if (typeof value !== 'string' || !INTEGER_STRING.test(value)) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n `Malformed compose response: ${path} is ${\n value === undefined ? 'absent' : 'not an integer string'\n }`,\n { url },\n );\n }\n return BigInt(value);\n};\n\n// The two records this seam reads out of a compile-family response body. Each\n// is `unknown` because the seam is what establishes its shape: it validates\n// every field before writing a decoded `bigint` back over the wire string.\ninterface WireAmountBody {\n outputs?: unknown;\n}\n\n// One `Amount` as it arrives: each leaf is `unknown` until this seam has\n// checked it, and is overwritten in place with the decoded `bigint`.\ninterface WireAmount {\n estimate?: unknown;\n minimum?: unknown;\n}\n\nconst malformed = (path: string, what: string, url: string): ComposeError =>\n new ComposeError(\n 'UNKNOWN_ERROR',\n `Malformed compose response: ${path} ${what}`,\n { url },\n );\n\n// Decode one `Estimate` / `Minimum` leaf in place: `{ basis, value }` with\n// `value` a decimal string on the wire and a `bigint` on `Amount`.\nconst decodeAmountLeaf = (\n amount: WireAmount,\n field: 'estimate' | 'minimum',\n path: string,\n url: string,\n): void => {\n const leaf = amount[field];\n if (leaf === undefined) return;\n if (!isNonNullObject(leaf)) {\n throw malformed(`${path}.${field}`, 'is not an object', url);\n }\n leaf.value = decodeAmount(leaf.value, `${path}.${field}.value`, url);\n};\n\n// `outputs` is REQUIRED on every compile-family body and is the record a\n// caller reads amounts from, so its structure is checked here — the body is\n// cast, not schema-parsed — before each `value` leaf becomes a `bigint`.\nconst decodeOutputs = (data: WireAmountBody, url: string): void => {\n const outputs = data.outputs;\n if (!isNonNullObject(outputs)) {\n throw malformed(\n 'outputs',\n outputs === undefined ? 'is absent' : 'is not an object',\n url,\n );\n }\n for (const key of Object.keys(outputs)) {\n const entry = outputs[key];\n if (!isNonNullObject(entry)) {\n throw malformed(`outputs.${key}`, 'is not an object', url);\n }\n const amount = entry.amount;\n if (!isNonNullObject(amount)) {\n throw malformed(\n `outputs.${key}.amount`,\n amount === undefined ? 'is absent' : 'is not an object',\n url,\n );\n }\n decodeAmountLeaf(amount, 'estimate', `outputs.${key}.amount`, url);\n decodeAmountLeaf(amount, 'minimum', `outputs.${key}.amount`, url);\n }\n};\n\n// THE decode seam for a compile-family response body: every amount the wire\n// renders as a decimal string becomes the `bigint` its declared type promises.\n// The amount record is handled here so the body is narrowed once — a\n// non-object body is not this function's error to raise, since the enveloping\n// parse already rejected it.\nconst decodeWireAmounts = (data: unknown, url: string): void => {\n if (!isNonNullObject(data)) return;\n decodeOutputs(data, url);\n};\n\nconst parseBody = async <T>(res: Response, url: string): Promise<T> => {\n const body = await res.json().catch((_) => null);\n if (!isNonNullObject(body) || !('data' in body)) {\n throw new ComposeError('UNKNOWN_ERROR', 'Unexpected response format', {\n url,\n });\n }\n return body.data as T;\n};\n\nconst parseCompileSuccessBody = async (\n res: Response,\n url: string,\n): Promise<ComposeCompileResult> => {\n const data = await parseBody<ComposeCompileSuccessData>(res, url);\n decodeWireAmounts(data, url);\n return { ...data, status: 'success' as const };\n};\n\nconst parsePartialBody = async (\n res: Response,\n url: string,\n): Promise<ComposeCompileResult> => {\n const body = await res.json().catch((_) => null);\n const envelope = parseCompilePartialEnvelope(body);\n if (envelope === null) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n 'Unexpected partial response format',\n { url },\n );\n }\n // `data` is validated as an object by the schema; compose-spec owns its full\n // shape as a hand-authored type, so we narrow it here rather than re-declaring\n // that type as a schema. `error` is fully validated — no cast needed.\n const data = envelope.data as ComposeCompilePartialData;\n decodeWireAmounts(data, url);\n return { ...data, status: 'partial' as const, error: envelope.error };\n};\n\n// `/simulate` is un-enveloped: the discriminated body (`{ status, ... }`) is at\n// the top level, NOT wrapped in `{ data }` like `/compose`. So this reads the\n// body directly and validates it against the simulate union rather than reusing\n// `parseBody`.\nconst parseSimulateBody = async (\n res: Response,\n url: string,\n): Promise<SimulateResult> => {\n const body = await res.json().catch((_) => null);\n const result = parseSimulateResult(body);\n if (result === null) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n 'Unexpected simulate response format',\n { url },\n );\n }\n return result;\n};\n// `POST /compose` and `POST /compose/route` differ only in path and request\n// shape: both return the enveloped success data on 200 and the partial\n// envelope on 206, so they share one transport.\ntype ComposeTransport = {\n readonly fetchFn: typeof fetch;\n readonly baseHeaders: Record<string, string>;\n};\n\n// A patch bump is additive and a minor bump is breaking, so a 200 from a\n// backend behind this SDK cannot be trusted: the newer flow this SDK authored\n// may have compiled under the server's older semantics without raising an\n// error. This covers the deploy window where the SDK is published to npm ahead\n// of the backend rollout. Only the compile-family POSTs are checked; discovery\n// GETs stay reachable from a mismatched SDK, as on the server. An absent header\n// (a pre-gate backend, a header-stripping proxy) is accepted, mirroring the\n// server's pass-through of a compile that carries no version header.\nconst assertServerVersion = (res: Response, url: string): void => {\n const serverVersion = res.headers.get(COMPOSE_VERSION_HEADER);\n if (serverVersion === null || SDK_VERSION_TRIPLE === undefined) return;\n const serverTriple = parseVersion(serverVersion);\n if (serverTriple === undefined) return;\n\n const compatibility = checkCompatibility(SDK_VERSION_TRIPLE, serverTriple);\n if (compatibility === 'compatible') return;\n\n const versions = { sdkVersion: SDK_VERSION, serverVersion };\n if (compatibility === 'sdk_outdated') {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `composer-sdk ${SDK_VERSION} is older than the compose contract served at ${url} (${serverVersion}); upgrade @lifi/composer-sdk and @lifi/compose-spec`,\n {\n status: res.status,\n url,\n kind: 'sdk_outdated',\n sdkOutdated: {\n ...versions,\n minimumSdkVersion: `${serverTriple.major}.${serverTriple.minor}.0`,\n },\n },\n );\n }\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `composer-sdk ${SDK_VERSION} targets a newer compose contract than the server at ${url} serves (${serverVersion}); pin @lifi/composer-sdk and @lifi/compose-spec to ${serverVersion} or wait for the server rollout`,\n {\n status: res.status,\n url,\n kind: 'server_outdated',\n serverOutdated: versions,\n },\n );\n};\n\ntype SendInit =\n | { readonly method: 'GET' }\n | { readonly method: 'POST'; readonly body: unknown };\n\n// GETs on this API carry no body; POSTs carry a JSON one with `bigint` amounts\n// rendered as decimal strings.\nconst requestInit = (\n baseHeaders: Record<string, string>,\n init: SendInit,\n): RequestInit =>\n init.method === 'GET'\n ? { method: 'GET', headers: { ...baseHeaders } }\n : {\n method: 'POST',\n headers: { ...baseHeaders, 'Content-Type': 'application/json' },\n body: JSON.stringify(init.body, bigintReplacer),\n };\n\n// One fetch path for every route: maps transport failures to `NETWORK_ERROR`.\n// The response version check is not here — only the compile-family POSTs gate\n// on it (see `postCompile`); discovery GETs and `/simulate` are ungated.\nconst send = async (\n { fetchFn, baseHeaders }: ComposeTransport,\n url: string,\n init: SendInit,\n): Promise<Response> => {\n try {\n return await fetchFn(url, requestInit(baseHeaders, init));\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n};\n\nconst postCompile = async (\n transport: ComposeTransport,\n url: string,\n request: ComposeCompileRequest | ComposeRouteRequest,\n): Promise<ComposeCompileResult> => {\n const res = await send(transport, url, { method: 'POST', body: request });\n assertServerVersion(res, url);\n if (res.status === 206) {\n return await parsePartialBody(res, url);\n }\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseCompileSuccessBody(res, url);\n};\n\n// Every enveloped GET on this API behaves identically: no body, no query\n// semantics of its own, `{ data }` on success, an error envelope otherwise.\nconst getJson = async <T>(\n transport: ComposeTransport,\n url: string,\n): Promise<T> => {\n const res = await send(transport, url, { method: 'GET' });\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseBody<T>(res, url);\n};\n\n/**\n * Creates a low-level Compose API client.\n *\n * @param options - Client configuration including the API base URL.\n * @returns A {@link ComposeClient} instance.\n */\nexport const createComposeClient = (\n options: ComposeClientOptions,\n): ComposeClient => {\n if (!options.baseUrl || !/^https?:\\/\\//i.test(options.baseUrl)) {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `Invalid baseUrl: expected an HTTP(S) URL, got \"${options.baseUrl}\"`,\n );\n }\n const trimmedApiKey = options.apiKey?.trim() || undefined;\n if (!trimmedApiKey) {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n 'apiKey is required: pass a LI.FI API key to createComposeSdk().',\n );\n }\n const fetchFn = options.fetch ?? globalThis.fetch;\n const base = options.baseUrl.replace(/\\/$/, '');\n\n const baseHeaders: Record<string, string> = {\n Accept: 'application/json',\n [COMPOSER_SDK_VERSION_HEADER]: SDK_VERSION,\n 'x-lifi-api-key': trimmedApiKey,\n };\n const transport: ComposeTransport = { fetchFn, baseHeaders };\n\n const getManifest = async (): Promise<ComposeManifest> =>\n getJson<ComposeManifest>(transport, `${base}/compose/manifest`);\n\n const getChains = async (): Promise<readonly ChainSummary[]> =>\n getJson<readonly ChainSummary[]>(transport, `${base}/chains`);\n\n const compile = async (\n request: ComposeCompileRequest,\n ): Promise<ComposeCompileResult> =>\n postCompile(transport, `${base}/compose`, request);\n\n const route = async (\n request: ComposeRouteRequest,\n ): Promise<ComposeCompileResult> =>\n postCompile(transport, `${base}/compose/route`, request);\n\n const getZapPacks = async (\n options?: GetZapPacksOptions,\n ): Promise<readonly ZapPackOverview[]> => {\n const params = new URLSearchParams();\n if (options?.protocols !== undefined) {\n // Backend expects a single comma-separated value, not repeated keys.\n const raw = options.protocols;\n const list = typeof raw === 'string' ? raw : raw.join(',');\n params.set('protocols', list);\n }\n const qs = params.toString();\n return getJson<readonly ZapPackOverview[]>(\n transport,\n `${base}/compose/zap-packs${qs ? `?${qs}` : ''}`,\n );\n };\n\n const simulate = async (\n request: SimulateRequest,\n ): Promise<SimulateResult> => {\n const url = `${base}/simulate`;\n const res = await send(transport, url, { method: 'POST', body: request });\n // Only 200 (carries `ok`/`revert`) and 422 (carries the `error` member of\n // the union) have a discriminated body. 422 is deliberately intercepted\n // here (not thrown as VALIDATION_ERROR) so callers get one exhaustive\n // `switch (result.status)`. Every other status is a transport error and is\n // thrown — including HTTP 400 (malformed input, no `status` body) and any\n // unexpected 2xx.\n if (res.status === 200 || res.status === 422) {\n return await parseSimulateBody(res, url);\n }\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n };\n\n return { getManifest, getChains, compile, route, getZapPacks, simulate };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUA,0BAKO;AAOP,oBAAoD;AACpD,6BAGO;AASP,MAAM,cACJ,OAAyC,UAAkB;AAE7D,MAAM,yBAAqB,kCAAa,WAAW;AA2J5C,MAAM,iBAAiB,CAAC,MAAc,UAC3C,OAAO,UAAU,WAAW,MAAM,SAAS,IAAI;AAEjD,MAAM,kBAAkB,CAAC,MACvB,OAAO,MAAM,YAAY,MAAM;AAGjC,MAAM,iBAAiB;AAEvB,MAAM,eAAe,CAAC,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status: 'partial'` rather than
|
|
76
76
|
* throwing, exactly as it does for {@link compile}.
|
|
77
77
|
*
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
*
|
|
83
|
-
*
|
|
78
|
+
* The server plans a short chain of catalog edges for the pair (a position
|
|
79
|
+
* entry or exit, a wrap or unwrap, a mint or burn), optionally opened by a
|
|
80
|
+
* `lifi.swap`. {@link getZapPacks} lists the single edges; the pairs the
|
|
81
|
+
* planner connects are their closure up to the hop budget, which
|
|
82
|
+
* {@link buildReachability} computes locally. A pair the planner cannot
|
|
83
|
+
* connect is rejected with `kind: 'no_route_error'`.
|
|
84
84
|
*
|
|
85
85
|
* Only synchronous edges are considered unless the request sets
|
|
86
86
|
* `allowAsyncRoutes: true`, so by default every terminal output comes back
|
|
@@ -98,7 +98,7 @@ interface ComposeClient {
|
|
|
98
98
|
* @param request - The from/to token pair, amount, signer, and route options.
|
|
99
99
|
* @returns A discriminated result: `status: 'success'` or `status: 'partial'`.
|
|
100
100
|
* @throws {@link ComposeError} on network, validation, or server errors —
|
|
101
|
-
* including `NOT_FOUND` (HTTP 404) when
|
|
101
|
+
* including `NOT_FOUND` (HTTP 404) when the planner cannot connect the pair.
|
|
102
102
|
*/
|
|
103
103
|
readonly route: (request: ComposeRouteRequest) => Promise<ComposeCompileResult>;
|
|
104
104
|
/**
|
package/dist/client.d.ts
CHANGED
|
@@ -75,12 +75,12 @@ interface ComposeClient {
|
|
|
75
75
|
* `simulationPolicy: 'allow-revert'` yields `status: 'partial'` rather than
|
|
76
76
|
* throwing, exactly as it does for {@link compile}.
|
|
77
77
|
*
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
*
|
|
83
|
-
*
|
|
78
|
+
* The server plans a short chain of catalog edges for the pair (a position
|
|
79
|
+
* entry or exit, a wrap or unwrap, a mint or burn), optionally opened by a
|
|
80
|
+
* `lifi.swap`. {@link getZapPacks} lists the single edges; the pairs the
|
|
81
|
+
* planner connects are their closure up to the hop budget, which
|
|
82
|
+
* {@link buildReachability} computes locally. A pair the planner cannot
|
|
83
|
+
* connect is rejected with `kind: 'no_route_error'`.
|
|
84
84
|
*
|
|
85
85
|
* Only synchronous edges are considered unless the request sets
|
|
86
86
|
* `allowAsyncRoutes: true`, so by default every terminal output comes back
|
|
@@ -98,7 +98,7 @@ interface ComposeClient {
|
|
|
98
98
|
* @param request - The from/to token pair, amount, signer, and route options.
|
|
99
99
|
* @returns A discriminated result: `status: 'success'` or `status: 'partial'`.
|
|
100
100
|
* @throws {@link ComposeError} on network, validation, or server errors —
|
|
101
|
-
* including `NOT_FOUND` (HTTP 404) when
|
|
101
|
+
* including `NOT_FOUND` (HTTP 404) when the planner cannot connect the pair.
|
|
102
102
|
*/
|
|
103
103
|
readonly route: (request: ComposeRouteRequest) => Promise<ComposeCompileResult>;
|
|
104
104
|
/**
|
package/dist/client.js
CHANGED
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
parseCompilePartialEnvelope,
|
|
10
10
|
parseSimulateResult
|
|
11
11
|
} from "./responseSchemas.js";
|
|
12
|
-
const SDK_VERSION = true ? "0.6.
|
|
12
|
+
const SDK_VERSION = true ? "0.6.2" : "dev";
|
|
13
13
|
const SDK_VERSION_TRIPLE = parseVersion(SDK_VERSION);
|
|
14
14
|
const bigintReplacer = (_key, value) => typeof value === "bigint" ? value.toString() : value;
|
|
15
15
|
const isNonNullObject = (v) => typeof v === "object" && v !== null;
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client.ts"],"sourcesContent":["import type {\n ComposeCompilePartialData,\n ComposeCompileRequest,\n ComposeCompileResult,\n ComposeCompileSuccessData,\n ComposeManifest,\n ComposeRouteRequest,\n SimulateRequest,\n SimulateResult,\n} from '@lifi/compose-spec';\nimport {\n checkCompatibility,\n COMPOSE_VERSION_HEADER,\n COMPOSER_SDK_VERSION_HEADER,\n parseVersion,\n} from '@lifi/compose-spec';\n\nimport type {\n ChainSummary,\n GetZapPacksOptions,\n ZapPackOverview,\n} from './discovery.js';\nimport { ComposeError, errorFromHttpResponse } from './errors.js';\nimport {\n parseCompilePartialEnvelope,\n parseSimulateResult,\n} from './responseSchemas.js';\n\n// __SDK_VERSION__ is a compile-time constant injected by tsup (via `define` in tsup.config.ts)\n// and by vitest (via `define` in vitest.config.ts). Both read the version from package.json\n// at build/test time and replace this identifier with the literal string value.\n// It is sent as the `COMPOSER_SDK_VERSION_HEADER` request header so the server can identify the caller.\n// Falls back to 'dev' when running via tsx without tsup substitution (e.g. the example harness).\ndeclare const __SDK_VERSION__: string;\n\nconst SDK_VERSION: string =\n typeof __SDK_VERSION__ !== 'undefined' ? __SDK_VERSION__ : 'dev';\n// `undefined` for the `dev` sentinel, which disables the response version check.\nconst SDK_VERSION_TRIPLE = parseVersion(SDK_VERSION);\n\n/**\n * Configuration for creating a low-level Compose API client.\n */\nexport interface ComposeClientOptions {\n /** Base URL of the Compose API. */\n readonly baseUrl: string;\n /** Optional custom `fetch` implementation. Defaults to `globalThis.fetch`. */\n readonly fetch?: typeof globalThis.fetch;\n /** LI.FI API key, sent as the `x-lifi-api-key` header on every request. Required — the Compose API rejects unauthenticated requests. */\n readonly apiKey: string;\n}\n\n/**\n * Low-level HTTP client for the Compose API.\n *\n * Handles request serialization, SDK version headers, and error mapping.\n * Prefer using {@link ComposeSdk} for the full builder experience. Use this\n * directly when you need to decouple request building from submission — e.g.\n * build via `sdk.request()` then submit via `client.compile()` with custom\n * retry logic or request inspection.\n */\nexport interface ComposeClient {\n /**\n * Fetches the server's operation manifest describing all supported operations,\n * guards, materialisers, and preconditions.\n * @returns The manifest document.\n * @throws {@link ComposeError} on network, validation, or server errors.\n */\n readonly getManifest: () => Promise<ComposeManifest>;\n /**\n * Fetches the chains the Compose API supports, ascending by `chainId`.\n *\n * A chain is listed once the server confirms the VM contract is deployed on\n * it — the same condition {@link compile}, {@link route} and\n * {@link simulate} validate against. A chain absent from this list is\n * rejected outright by those endpoints.\n *\n * The converse does not hold: a listed chain can still have no routing edge\n * for a given token pair, which {@link route} reports as `no_route_error`.\n * Use {@link getZapPacks} to enumerate the pairs that do route.\n *\n * Each entry carries a display `name` alongside its `chainId`. The name is a\n * deployment-maintained label — render it, but key on `chainId`.\n *\n * The list tracks the server's chain registry, which refreshes periodically.\n * Results are not cached by the SDK; callers should cache as appropriate.\n *\n * @returns The supported chains, ascending by `chainId`.\n * @throws {@link ComposeError} on network or server errors.\n */\n readonly getChains: () => Promise<readonly ChainSummary[]>;\n /**\n * Submits a compile request and returns the result.\n *\n * When the caller passes `simulationPolicy: 'allow-revert'` and the transaction\n * reverts in simulation, the server responds with HTTP 206 and the SDK returns a\n * partial result (`status: 'partial'`) instead of throwing. The partial result\n * includes the transaction (without `gasLimit`) and revert diagnostics.\n *\n * @param request - The full compile request including flow and run inputs.\n * @returns A discriminated result: `status: 'success'` or `status: 'partial'`.\n * @throws {@link ComposeError} on network, validation, or server errors.\n */\n readonly compile: (\n request: ComposeCompileRequest,\n ) => Promise<ComposeCompileResult>;\n /**\n * Compiles a token pair into a submit-ready transaction via\n * `POST /compose/route`.\n *\n * A convenience path that skips flow authoring: the server builds a one-node\n * zap flow with a `directDeposit` input from the `fromToken` / `toToken`\n * pair and runs it through the same pipeline as {@link compile}. The\n * response is therefore the same discriminated result — HTTP 206 under\n * `simulationPolicy: 'allow-revert'` yields `status: 'partial'` rather than\n * throwing, exactly as it does for {@link compile}.\n *\n * As of today that flow is a single zap step: one edge of the backend's\n * routing catalog (a position entry or exit, a wrap or unwrap, a mint or\n * burn). Enumerate the pairs it covers with {@link getZapPacks}; a pair with\n * no edge is rejected with `kind: 'no_route_error'`. The endpoint is meant to\n * author richer flows later, so the single-step limit is the current state of\n * the server, not the shape of this contract.\n *\n * Only synchronous edges are considered unless the request sets\n * `allowAsyncRoutes: true`, so by default every terminal output comes back\n * `delivery.when: 'now'` and a pair reachable only after settlement is a\n * `no_route_error`. Opting in adds the `lifi.zapAsync` fallback, which still\n * loses to a synchronous edge when the pair has one; read\n * `outputs[*].delivery.when` to see which representation you got.\n *\n * Use {@link compile} for what the server does not author for you: several\n * chained operations, splits, explicit preconditions, or per-op guards.\n *\n * `bigint` amounts in `amount` are serialised to decimal strings\n * automatically.\n *\n * @param request - The from/to token pair, amount, signer, and route options.\n * @returns A discriminated result: `status: 'success'` or `status: 'partial'`.\n * @throws {@link ComposeError} on network, validation, or server errors —\n * including `NOT_FOUND` (HTTP 404) when no catalog edge covers the pair.\n */\n readonly route: (\n request: ComposeRouteRequest,\n ) => Promise<ComposeCompileResult>;\n /**\n * Fetches the available routing edges grouped by protocol.\n *\n * The edge catalog is dynamic — it reflects the current state of the\n * backend's routing snapshot (protocols, chains, token blacklists).\n * Results are not cached by the SDK; callers should cache as appropriate.\n *\n * @param options - Optional filter to restrict results to specific protocols.\n * @returns An array of {@link ZapPackOverview} objects, one per protocol.\n * @throws {@link ComposeError} on network or server errors (503 when the\n * routing catalog is not yet initialized).\n */\n readonly getZapPacks: (\n options?: GetZapPacksOptions,\n ) => Promise<readonly ZapPackOverview[]>;\n /**\n * Simulates a raw, pre-encoded transaction against `POST /simulate` and\n * reports how the watched balances change and how much inner-call gas it\n * burns.\n *\n * The result is a discriminated union on `status`:\n * - `'ok'` — the simulation ran successfully; `deltas`/`gasUsed` are populated.\n * - `'revert'` — the simulation ran but the transaction reverted on-chain. A\n * revert is a *successful simulation*, not a transport error, so it is\n * returned (HTTP 200) rather than thrown — mirroring how {@link compile}\n * returns `status: 'partial'` on a simulated revert.\n * - `'error'` — the request was well-formed but the simulation could not be\n * set up or run (HTTP 422); `message` is intentionally generic.\n *\n * `bigint` amounts in the request (`value`, requirement `balance`/`allowance`)\n * are serialised to decimal strings automatically.\n *\n * @param request - The raw transaction plus funding `requirements` and the\n * `trackedBalances` to watch.\n * @returns A {@link SimulateResult} (`ok` / `revert` / `error`).\n * @throws {@link ComposeError} on network failures, HTTP 400 (malformed\n * input), 401/403 (auth), 404, 429, and 5xx.\n */\n readonly simulate: (request: SimulateRequest) => Promise<SimulateResult>;\n}\n\n/**\n * `JSON.stringify` replacer that renders `bigint` amounts as decimal strings.\n *\n * The compose wire carries token amounts as decimal strings, and `bigint` has\n * no JSON representation, so every payload this client sends goes through it.\n * Exported so the example harness prints a request exactly as it is sent.\n */\nexport const bigintReplacer = (_key: string, value: unknown): unknown =>\n typeof value === 'bigint' ? value.toString() : value;\n\nconst isNonNullObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null;\n\n// Non-negative decimal integer string, as the server sends token amounts.\nconst INTEGER_STRING = /^\\d+$/;\n\nconst decodeAmount = (value: unknown, path: string, url: string): bigint => {\n if (typeof value !== 'string' || !INTEGER_STRING.test(value)) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n `Malformed compose response: ${path} is ${\n value === undefined ? 'absent' : 'not an integer string'\n }`,\n { url },\n );\n }\n return BigInt(value);\n};\n\n// The two records this seam reads out of a compile-family response body. Each\n// is `unknown` because the seam is what establishes its shape: it validates\n// every field before writing a decoded `bigint` back over the wire string.\ninterface WireAmountBody {\n outputs?: unknown;\n}\n\n// One `Amount` as it arrives: each leaf is `unknown` until this seam has\n// checked it, and is overwritten in place with the decoded `bigint`.\ninterface WireAmount {\n estimate?: unknown;\n minimum?: unknown;\n}\n\nconst malformed = (path: string, what: string, url: string): ComposeError =>\n new ComposeError(\n 'UNKNOWN_ERROR',\n `Malformed compose response: ${path} ${what}`,\n { url },\n );\n\n// Decode one `Estimate` / `Minimum` leaf in place: `{ basis, value }` with\n// `value` a decimal string on the wire and a `bigint` on `Amount`.\nconst decodeAmountLeaf = (\n amount: WireAmount,\n field: 'estimate' | 'minimum',\n path: string,\n url: string,\n): void => {\n const leaf = amount[field];\n if (leaf === undefined) return;\n if (!isNonNullObject(leaf)) {\n throw malformed(`${path}.${field}`, 'is not an object', url);\n }\n leaf.value = decodeAmount(leaf.value, `${path}.${field}.value`, url);\n};\n\n// `outputs` is REQUIRED on every compile-family body and is the record a\n// caller reads amounts from, so its structure is checked here — the body is\n// cast, not schema-parsed — before each `value` leaf becomes a `bigint`.\nconst decodeOutputs = (data: WireAmountBody, url: string): void => {\n const outputs = data.outputs;\n if (!isNonNullObject(outputs)) {\n throw malformed(\n 'outputs',\n outputs === undefined ? 'is absent' : 'is not an object',\n url,\n );\n }\n for (const key of Object.keys(outputs)) {\n const entry = outputs[key];\n if (!isNonNullObject(entry)) {\n throw malformed(`outputs.${key}`, 'is not an object', url);\n }\n const amount = entry.amount;\n if (!isNonNullObject(amount)) {\n throw malformed(\n `outputs.${key}.amount`,\n amount === undefined ? 'is absent' : 'is not an object',\n url,\n );\n }\n decodeAmountLeaf(amount, 'estimate', `outputs.${key}.amount`, url);\n decodeAmountLeaf(amount, 'minimum', `outputs.${key}.amount`, url);\n }\n};\n\n// THE decode seam for a compile-family response body: every amount the wire\n// renders as a decimal string becomes the `bigint` its declared type promises.\n// The amount record is handled here so the body is narrowed once — a\n// non-object body is not this function's error to raise, since the enveloping\n// parse already rejected it.\nconst decodeWireAmounts = (data: unknown, url: string): void => {\n if (!isNonNullObject(data)) return;\n decodeOutputs(data, url);\n};\n\nconst parseBody = async <T>(res: Response, url: string): Promise<T> => {\n const body = await res.json().catch((_) => null);\n if (!isNonNullObject(body) || !('data' in body)) {\n throw new ComposeError('UNKNOWN_ERROR', 'Unexpected response format', {\n url,\n });\n }\n return body.data as T;\n};\n\nconst parseCompileSuccessBody = async (\n res: Response,\n url: string,\n): Promise<ComposeCompileResult> => {\n const data = await parseBody<ComposeCompileSuccessData>(res, url);\n decodeWireAmounts(data, url);\n return { ...data, status: 'success' as const };\n};\n\nconst parsePartialBody = async (\n res: Response,\n url: string,\n): Promise<ComposeCompileResult> => {\n const body = await res.json().catch((_) => null);\n const envelope = parseCompilePartialEnvelope(body);\n if (envelope === null) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n 'Unexpected partial response format',\n { url },\n );\n }\n // `data` is validated as an object by the schema; compose-spec owns its full\n // shape as a hand-authored type, so we narrow it here rather than re-declaring\n // that type as a schema. `error` is fully validated — no cast needed.\n const data = envelope.data as ComposeCompilePartialData;\n decodeWireAmounts(data, url);\n return { ...data, status: 'partial' as const, error: envelope.error };\n};\n\n// `/simulate` is un-enveloped: the discriminated body (`{ status, ... }`) is at\n// the top level, NOT wrapped in `{ data }` like `/compose`. So this reads the\n// body directly and validates it against the simulate union rather than reusing\n// `parseBody`.\nconst parseSimulateBody = async (\n res: Response,\n url: string,\n): Promise<SimulateResult> => {\n const body = await res.json().catch((_) => null);\n const result = parseSimulateResult(body);\n if (result === null) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n 'Unexpected simulate response format',\n { url },\n );\n }\n return result;\n};\n// `POST /compose` and `POST /compose/route` differ only in path and request\n// shape: both return the enveloped success data on 200 and the partial\n// envelope on 206, so they share one transport.\ntype ComposeTransport = {\n readonly fetchFn: typeof fetch;\n readonly baseHeaders: Record<string, string>;\n};\n\n// A patch bump is additive and a minor bump is breaking, so a 200 from a\n// backend behind this SDK cannot be trusted: the newer flow this SDK authored\n// may have compiled under the server's older semantics without raising an\n// error. This covers the deploy window where the SDK is published to npm ahead\n// of the backend rollout. Only the compile-family POSTs are checked; discovery\n// GETs stay reachable from a mismatched SDK, as on the server. An absent header\n// (a pre-gate backend, a header-stripping proxy) is accepted, mirroring the\n// server's pass-through of a compile that carries no version header.\nconst assertServerVersion = (res: Response, url: string): void => {\n const serverVersion = res.headers.get(COMPOSE_VERSION_HEADER);\n if (serverVersion === null || SDK_VERSION_TRIPLE === undefined) return;\n const serverTriple = parseVersion(serverVersion);\n if (serverTriple === undefined) return;\n\n const compatibility = checkCompatibility(SDK_VERSION_TRIPLE, serverTriple);\n if (compatibility === 'compatible') return;\n\n const versions = { sdkVersion: SDK_VERSION, serverVersion };\n if (compatibility === 'sdk_outdated') {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `composer-sdk ${SDK_VERSION} is older than the compose contract served at ${url} (${serverVersion}); upgrade @lifi/composer-sdk and @lifi/compose-spec`,\n {\n status: res.status,\n url,\n kind: 'sdk_outdated',\n sdkOutdated: {\n ...versions,\n minimumSdkVersion: `${serverTriple.major}.${serverTriple.minor}.0`,\n },\n },\n );\n }\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `composer-sdk ${SDK_VERSION} targets a newer compose contract than the server at ${url} serves (${serverVersion}); pin @lifi/composer-sdk and @lifi/compose-spec to ${serverVersion} or wait for the server rollout`,\n {\n status: res.status,\n url,\n kind: 'server_outdated',\n serverOutdated: versions,\n },\n );\n};\n\ntype SendInit =\n | { readonly method: 'GET' }\n | { readonly method: 'POST'; readonly body: unknown };\n\n// GETs on this API carry no body; POSTs carry a JSON one with `bigint` amounts\n// rendered as decimal strings.\nconst requestInit = (\n baseHeaders: Record<string, string>,\n init: SendInit,\n): RequestInit =>\n init.method === 'GET'\n ? { method: 'GET', headers: { ...baseHeaders } }\n : {\n method: 'POST',\n headers: { ...baseHeaders, 'Content-Type': 'application/json' },\n body: JSON.stringify(init.body, bigintReplacer),\n };\n\n// One fetch path for every route: maps transport failures to `NETWORK_ERROR`.\n// The response version check is not here — only the compile-family POSTs gate\n// on it (see `postCompile`); discovery GETs and `/simulate` are ungated.\nconst send = async (\n { fetchFn, baseHeaders }: ComposeTransport,\n url: string,\n init: SendInit,\n): Promise<Response> => {\n try {\n return await fetchFn(url, requestInit(baseHeaders, init));\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n};\n\nconst postCompile = async (\n transport: ComposeTransport,\n url: string,\n request: ComposeCompileRequest | ComposeRouteRequest,\n): Promise<ComposeCompileResult> => {\n const res = await send(transport, url, { method: 'POST', body: request });\n assertServerVersion(res, url);\n if (res.status === 206) {\n return await parsePartialBody(res, url);\n }\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseCompileSuccessBody(res, url);\n};\n\n// Every enveloped GET on this API behaves identically: no body, no query\n// semantics of its own, `{ data }` on success, an error envelope otherwise.\nconst getJson = async <T>(\n transport: ComposeTransport,\n url: string,\n): Promise<T> => {\n const res = await send(transport, url, { method: 'GET' });\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseBody<T>(res, url);\n};\n\n/**\n * Creates a low-level Compose API client.\n *\n * @param options - Client configuration including the API base URL.\n * @returns A {@link ComposeClient} instance.\n */\nexport const createComposeClient = (\n options: ComposeClientOptions,\n): ComposeClient => {\n if (!options.baseUrl || !/^https?:\\/\\//i.test(options.baseUrl)) {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `Invalid baseUrl: expected an HTTP(S) URL, got \"${options.baseUrl}\"`,\n );\n }\n const trimmedApiKey = options.apiKey?.trim() || undefined;\n if (!trimmedApiKey) {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n 'apiKey is required: pass a LI.FI API key to createComposeSdk().',\n );\n }\n const fetchFn = options.fetch ?? globalThis.fetch;\n const base = options.baseUrl.replace(/\\/$/, '');\n\n const baseHeaders: Record<string, string> = {\n Accept: 'application/json',\n [COMPOSER_SDK_VERSION_HEADER]: SDK_VERSION,\n 'x-lifi-api-key': trimmedApiKey,\n };\n const transport: ComposeTransport = { fetchFn, baseHeaders };\n\n const getManifest = async (): Promise<ComposeManifest> =>\n getJson<ComposeManifest>(transport, `${base}/compose/manifest`);\n\n const getChains = async (): Promise<readonly ChainSummary[]> =>\n getJson<readonly ChainSummary[]>(transport, `${base}/chains`);\n\n const compile = async (\n request: ComposeCompileRequest,\n ): Promise<ComposeCompileResult> =>\n postCompile(transport, `${base}/compose`, request);\n\n const route = async (\n request: ComposeRouteRequest,\n ): Promise<ComposeCompileResult> =>\n postCompile(transport, `${base}/compose/route`, request);\n\n const getZapPacks = async (\n options?: GetZapPacksOptions,\n ): Promise<readonly ZapPackOverview[]> => {\n const params = new URLSearchParams();\n if (options?.protocols !== undefined) {\n // Backend expects a single comma-separated value, not repeated keys.\n const raw = options.protocols;\n const list = typeof raw === 'string' ? raw : raw.join(',');\n params.set('protocols', list);\n }\n const qs = params.toString();\n return getJson<readonly ZapPackOverview[]>(\n transport,\n `${base}/compose/zap-packs${qs ? `?${qs}` : ''}`,\n );\n };\n\n const simulate = async (\n request: SimulateRequest,\n ): Promise<SimulateResult> => {\n const url = `${base}/simulate`;\n const res = await send(transport, url, { method: 'POST', body: request });\n // Only 200 (carries `ok`/`revert`) and 422 (carries the `error` member of\n // the union) have a discriminated body. 422 is deliberately intercepted\n // here (not thrown as VALIDATION_ERROR) so callers get one exhaustive\n // `switch (result.status)`. Every other status is a transport error and is\n // thrown — including HTTP 400 (malformed input, no `status` body) and any\n // unexpected 2xx.\n if (res.status === 200 || res.status === 422) {\n return await parseSimulateBody(res, url);\n }\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n };\n\n return { getManifest, getChains, compile, route, getZapPacks, simulate };\n};\n"],"mappings":"AAUA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAOP,SAAS,cAAc,6BAA6B;AACpD;AAAA,EACE;AAAA,EACA;AAAA,OACK;AASP,MAAM,cACJ,OAAyC,UAAkB;AAE7D,MAAM,qBAAqB,aAAa,WAAW;AA2J5C,MAAM,iBAAiB,CAAC,MAAc,UAC3C,OAAO,UAAU,WAAW,MAAM,SAAS,IAAI;AAEjD,MAAM,kBAAkB,CAAC,MACvB,OAAO,MAAM,YAAY,MAAM;AAGjC,MAAM,iBAAiB;AAEvB,MAAM,eAAe,CAAC,OAAgB,MAAc,QAAwB;AAC1E,MAAI,OAAO,UAAU,YAAY,CAAC,eAAe,KAAK,KAAK,GAAG;AAC5D,UAAM,IAAI;AAAA,MACR;AAAA,MACA,+BAA+B,IAAI,OACjC,UAAU,SAAY,WAAW,uBACnC;AAAA,MACA,EAAE,IAAI;AAAA,IACR;AAAA,EACF;AACA,SAAO,OAAO,KAAK;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OACd,YAEA,YAAY,WAAW,GAAG,IAAI,YAAY,OAAO;AAEnD,QAAM,QAAQ,OACZ,YAEA,YAAY,WAAW,GAAG,IAAI,kBAAkB,OAAO;AAEzD,QAAM,cAAc,OAClBA,aACwC;AACxC,UAAM,SAAS,IAAI,gBAAgB;AACnC,QAAIA,UAAS,cAAc,QAAW;AAEpC,YAAM,MAAMA,SAAQ;AACpB,YAAM,OAAO,OAAO,QAAQ,WAAW,MAAM,IAAI,KAAK,GAAG;AACzD,aAAO,IAAI,aAAa,IAAI;AAAA,IAC9B;AACA,UAAM,KAAK,OAAO,SAAS;AAC3B,WAAO;AAAA,MACL;AAAA,MACA,GAAG,IAAI,qBAAqB,KAAK,IAAI,EAAE,KAAK,EAAE;AAAA,IAChD;AAAA,EACF;AAEA,QAAM,WAAW,OACf,YAC4B;AAC5B,UAAM,MAAM,GAAG,IAAI;AACnB,UAAM,MAAM,MAAM,KAAK,WAAW,KAAK,EAAE,QAAQ,QAAQ,MAAM,QAAQ,CAAC;AAOxE,QAAI,IAAI,WAAW,OAAO,IAAI,WAAW,KAAK;AAC5C,aAAO,MAAM,kBAAkB,KAAK,GAAG;AAAA,IACzC;AACA,UAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,UAAM,sBAAsB,IAAI,QAAQ,MAAM,GAAG;AAAA,EACnD;AAEA,SAAO,EAAE,aAAa,WAAW,SAAS,OAAO,aAAa,SAAS;AACzE;","names":["options"]}
|
|
1
|
+
{"version":3,"sources":["../src/client.ts"],"sourcesContent":["import type {\n ComposeCompilePartialData,\n ComposeCompileRequest,\n ComposeCompileResult,\n ComposeCompileSuccessData,\n ComposeManifest,\n ComposeRouteRequest,\n SimulateRequest,\n SimulateResult,\n} from '@lifi/compose-spec';\nimport {\n checkCompatibility,\n COMPOSE_VERSION_HEADER,\n COMPOSER_SDK_VERSION_HEADER,\n parseVersion,\n} from '@lifi/compose-spec';\n\nimport type {\n ChainSummary,\n GetZapPacksOptions,\n ZapPackOverview,\n} from './discovery.js';\nimport { ComposeError, errorFromHttpResponse } from './errors.js';\nimport {\n parseCompilePartialEnvelope,\n parseSimulateResult,\n} from './responseSchemas.js';\n\n// __SDK_VERSION__ is a compile-time constant injected by tsup (via `define` in tsup.config.ts)\n// and by vitest (via `define` in vitest.config.ts). Both read the version from package.json\n// at build/test time and replace this identifier with the literal string value.\n// It is sent as the `COMPOSER_SDK_VERSION_HEADER` request header so the server can identify the caller.\n// Falls back to 'dev' when running via tsx without tsup substitution (e.g. the example harness).\ndeclare const __SDK_VERSION__: string;\n\nconst SDK_VERSION: string =\n typeof __SDK_VERSION__ !== 'undefined' ? __SDK_VERSION__ : 'dev';\n// `undefined` for the `dev` sentinel, which disables the response version check.\nconst SDK_VERSION_TRIPLE = parseVersion(SDK_VERSION);\n\n/**\n * Configuration for creating a low-level Compose API client.\n */\nexport interface ComposeClientOptions {\n /** Base URL of the Compose API. */\n readonly baseUrl: string;\n /** Optional custom `fetch` implementation. Defaults to `globalThis.fetch`. */\n readonly fetch?: typeof globalThis.fetch;\n /** LI.FI API key, sent as the `x-lifi-api-key` header on every request. Required — the Compose API rejects unauthenticated requests. */\n readonly apiKey: string;\n}\n\n/**\n * Low-level HTTP client for the Compose API.\n *\n * Handles request serialization, SDK version headers, and error mapping.\n * Prefer using {@link ComposeSdk} for the full builder experience. Use this\n * directly when you need to decouple request building from submission — e.g.\n * build via `sdk.request()` then submit via `client.compile()` with custom\n * retry logic or request inspection.\n */\nexport interface ComposeClient {\n /**\n * Fetches the server's operation manifest describing all supported operations,\n * guards, materialisers, and preconditions.\n * @returns The manifest document.\n * @throws {@link ComposeError} on network, validation, or server errors.\n */\n readonly getManifest: () => Promise<ComposeManifest>;\n /**\n * Fetches the chains the Compose API supports, ascending by `chainId`.\n *\n * A chain is listed once the server confirms the VM contract is deployed on\n * it — the same condition {@link compile}, {@link route} and\n * {@link simulate} validate against. A chain absent from this list is\n * rejected outright by those endpoints.\n *\n * The converse does not hold: a listed chain can still have no routing edge\n * for a given token pair, which {@link route} reports as `no_route_error`.\n * Use {@link getZapPacks} to enumerate the pairs that do route.\n *\n * Each entry carries a display `name` alongside its `chainId`. The name is a\n * deployment-maintained label — render it, but key on `chainId`.\n *\n * The list tracks the server's chain registry, which refreshes periodically.\n * Results are not cached by the SDK; callers should cache as appropriate.\n *\n * @returns The supported chains, ascending by `chainId`.\n * @throws {@link ComposeError} on network or server errors.\n */\n readonly getChains: () => Promise<readonly ChainSummary[]>;\n /**\n * Submits a compile request and returns the result.\n *\n * When the caller passes `simulationPolicy: 'allow-revert'` and the transaction\n * reverts in simulation, the server responds with HTTP 206 and the SDK returns a\n * partial result (`status: 'partial'`) instead of throwing. The partial result\n * includes the transaction (without `gasLimit`) and revert diagnostics.\n *\n * @param request - The full compile request including flow and run inputs.\n * @returns A discriminated result: `status: 'success'` or `status: 'partial'`.\n * @throws {@link ComposeError} on network, validation, or server errors.\n */\n readonly compile: (\n request: ComposeCompileRequest,\n ) => Promise<ComposeCompileResult>;\n /**\n * Compiles a token pair into a submit-ready transaction via\n * `POST /compose/route`.\n *\n * A convenience path that skips flow authoring: the server builds a one-node\n * zap flow with a `directDeposit` input from the `fromToken` / `toToken`\n * pair and runs it through the same pipeline as {@link compile}. The\n * response is therefore the same discriminated result — HTTP 206 under\n * `simulationPolicy: 'allow-revert'` yields `status: 'partial'` rather than\n * throwing, exactly as it does for {@link compile}.\n *\n * The server plans a short chain of catalog edges for the pair (a position\n * entry or exit, a wrap or unwrap, a mint or burn), optionally opened by a\n * `lifi.swap`. {@link getZapPacks} lists the single edges; the pairs the\n * planner connects are their closure up to the hop budget, which\n * {@link buildReachability} computes locally. A pair the planner cannot\n * connect is rejected with `kind: 'no_route_error'`.\n *\n * Only synchronous edges are considered unless the request sets\n * `allowAsyncRoutes: true`, so by default every terminal output comes back\n * `delivery.when: 'now'` and a pair reachable only after settlement is a\n * `no_route_error`. Opting in adds the `lifi.zapAsync` fallback, which still\n * loses to a synchronous edge when the pair has one; read\n * `outputs[*].delivery.when` to see which representation you got.\n *\n * Use {@link compile} for what the server does not author for you: several\n * chained operations, splits, explicit preconditions, or per-op guards.\n *\n * `bigint` amounts in `amount` are serialised to decimal strings\n * automatically.\n *\n * @param request - The from/to token pair, amount, signer, and route options.\n * @returns A discriminated result: `status: 'success'` or `status: 'partial'`.\n * @throws {@link ComposeError} on network, validation, or server errors —\n * including `NOT_FOUND` (HTTP 404) when the planner cannot connect the pair.\n */\n readonly route: (\n request: ComposeRouteRequest,\n ) => Promise<ComposeCompileResult>;\n /**\n * Fetches the available routing edges grouped by protocol.\n *\n * The edge catalog is dynamic — it reflects the current state of the\n * backend's routing snapshot (protocols, chains, token blacklists).\n * Results are not cached by the SDK; callers should cache as appropriate.\n *\n * @param options - Optional filter to restrict results to specific protocols.\n * @returns An array of {@link ZapPackOverview} objects, one per protocol.\n * @throws {@link ComposeError} on network or server errors (503 when the\n * routing catalog is not yet initialized).\n */\n readonly getZapPacks: (\n options?: GetZapPacksOptions,\n ) => Promise<readonly ZapPackOverview[]>;\n /**\n * Simulates a raw, pre-encoded transaction against `POST /simulate` and\n * reports how the watched balances change and how much inner-call gas it\n * burns.\n *\n * The result is a discriminated union on `status`:\n * - `'ok'` — the simulation ran successfully; `deltas`/`gasUsed` are populated.\n * - `'revert'` — the simulation ran but the transaction reverted on-chain. A\n * revert is a *successful simulation*, not a transport error, so it is\n * returned (HTTP 200) rather than thrown — mirroring how {@link compile}\n * returns `status: 'partial'` on a simulated revert.\n * - `'error'` — the request was well-formed but the simulation could not be\n * set up or run (HTTP 422); `message` is intentionally generic.\n *\n * `bigint` amounts in the request (`value`, requirement `balance`/`allowance`)\n * are serialised to decimal strings automatically.\n *\n * @param request - The raw transaction plus funding `requirements` and the\n * `trackedBalances` to watch.\n * @returns A {@link SimulateResult} (`ok` / `revert` / `error`).\n * @throws {@link ComposeError} on network failures, HTTP 400 (malformed\n * input), 401/403 (auth), 404, 429, and 5xx.\n */\n readonly simulate: (request: SimulateRequest) => Promise<SimulateResult>;\n}\n\n/**\n * `JSON.stringify` replacer that renders `bigint` amounts as decimal strings.\n *\n * The compose wire carries token amounts as decimal strings, and `bigint` has\n * no JSON representation, so every payload this client sends goes through it.\n * Exported so the example harness prints a request exactly as it is sent.\n */\nexport const bigintReplacer = (_key: string, value: unknown): unknown =>\n typeof value === 'bigint' ? value.toString() : value;\n\nconst isNonNullObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null;\n\n// Non-negative decimal integer string, as the server sends token amounts.\nconst INTEGER_STRING = /^\\d+$/;\n\nconst decodeAmount = (value: unknown, path: string, url: string): bigint => {\n if (typeof value !== 'string' || !INTEGER_STRING.test(value)) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n `Malformed compose response: ${path} is ${\n value === undefined ? 'absent' : 'not an integer string'\n }`,\n { url },\n );\n }\n return BigInt(value);\n};\n\n// The two records this seam reads out of a compile-family response body. Each\n// is `unknown` because the seam is what establishes its shape: it validates\n// every field before writing a decoded `bigint` back over the wire string.\ninterface WireAmountBody {\n outputs?: unknown;\n}\n\n// One `Amount` as it arrives: each leaf is `unknown` until this seam has\n// checked it, and is overwritten in place with the decoded `bigint`.\ninterface WireAmount {\n estimate?: unknown;\n minimum?: unknown;\n}\n\nconst malformed = (path: string, what: string, url: string): ComposeError =>\n new ComposeError(\n 'UNKNOWN_ERROR',\n `Malformed compose response: ${path} ${what}`,\n { url },\n );\n\n// Decode one `Estimate` / `Minimum` leaf in place: `{ basis, value }` with\n// `value` a decimal string on the wire and a `bigint` on `Amount`.\nconst decodeAmountLeaf = (\n amount: WireAmount,\n field: 'estimate' | 'minimum',\n path: string,\n url: string,\n): void => {\n const leaf = amount[field];\n if (leaf === undefined) return;\n if (!isNonNullObject(leaf)) {\n throw malformed(`${path}.${field}`, 'is not an object', url);\n }\n leaf.value = decodeAmount(leaf.value, `${path}.${field}.value`, url);\n};\n\n// `outputs` is REQUIRED on every compile-family body and is the record a\n// caller reads amounts from, so its structure is checked here — the body is\n// cast, not schema-parsed — before each `value` leaf becomes a `bigint`.\nconst decodeOutputs = (data: WireAmountBody, url: string): void => {\n const outputs = data.outputs;\n if (!isNonNullObject(outputs)) {\n throw malformed(\n 'outputs',\n outputs === undefined ? 'is absent' : 'is not an object',\n url,\n );\n }\n for (const key of Object.keys(outputs)) {\n const entry = outputs[key];\n if (!isNonNullObject(entry)) {\n throw malformed(`outputs.${key}`, 'is not an object', url);\n }\n const amount = entry.amount;\n if (!isNonNullObject(amount)) {\n throw malformed(\n `outputs.${key}.amount`,\n amount === undefined ? 'is absent' : 'is not an object',\n url,\n );\n }\n decodeAmountLeaf(amount, 'estimate', `outputs.${key}.amount`, url);\n decodeAmountLeaf(amount, 'minimum', `outputs.${key}.amount`, url);\n }\n};\n\n// THE decode seam for a compile-family response body: every amount the wire\n// renders as a decimal string becomes the `bigint` its declared type promises.\n// The amount record is handled here so the body is narrowed once — a\n// non-object body is not this function's error to raise, since the enveloping\n// parse already rejected it.\nconst decodeWireAmounts = (data: unknown, url: string): void => {\n if (!isNonNullObject(data)) return;\n decodeOutputs(data, url);\n};\n\nconst parseBody = async <T>(res: Response, url: string): Promise<T> => {\n const body = await res.json().catch((_) => null);\n if (!isNonNullObject(body) || !('data' in body)) {\n throw new ComposeError('UNKNOWN_ERROR', 'Unexpected response format', {\n url,\n });\n }\n return body.data as T;\n};\n\nconst parseCompileSuccessBody = async (\n res: Response,\n url: string,\n): Promise<ComposeCompileResult> => {\n const data = await parseBody<ComposeCompileSuccessData>(res, url);\n decodeWireAmounts(data, url);\n return { ...data, status: 'success' as const };\n};\n\nconst parsePartialBody = async (\n res: Response,\n url: string,\n): Promise<ComposeCompileResult> => {\n const body = await res.json().catch((_) => null);\n const envelope = parseCompilePartialEnvelope(body);\n if (envelope === null) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n 'Unexpected partial response format',\n { url },\n );\n }\n // `data` is validated as an object by the schema; compose-spec owns its full\n // shape as a hand-authored type, so we narrow it here rather than re-declaring\n // that type as a schema. `error` is fully validated — no cast needed.\n const data = envelope.data as ComposeCompilePartialData;\n decodeWireAmounts(data, url);\n return { ...data, status: 'partial' as const, error: envelope.error };\n};\n\n// `/simulate` is un-enveloped: the discriminated body (`{ status, ... }`) is at\n// the top level, NOT wrapped in `{ data }` like `/compose`. So this reads the\n// body directly and validates it against the simulate union rather than reusing\n// `parseBody`.\nconst parseSimulateBody = async (\n res: Response,\n url: string,\n): Promise<SimulateResult> => {\n const body = await res.json().catch((_) => null);\n const result = parseSimulateResult(body);\n if (result === null) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n 'Unexpected simulate response format',\n { url },\n );\n }\n return result;\n};\n// `POST /compose` and `POST /compose/route` differ only in path and request\n// shape: both return the enveloped success data on 200 and the partial\n// envelope on 206, so they share one transport.\ntype ComposeTransport = {\n readonly fetchFn: typeof fetch;\n readonly baseHeaders: Record<string, string>;\n};\n\n// A patch bump is additive and a minor bump is breaking, so a 200 from a\n// backend behind this SDK cannot be trusted: the newer flow this SDK authored\n// may have compiled under the server's older semantics without raising an\n// error. This covers the deploy window where the SDK is published to npm ahead\n// of the backend rollout. Only the compile-family POSTs are checked; discovery\n// GETs stay reachable from a mismatched SDK, as on the server. An absent header\n// (a pre-gate backend, a header-stripping proxy) is accepted, mirroring the\n// server's pass-through of a compile that carries no version header.\nconst assertServerVersion = (res: Response, url: string): void => {\n const serverVersion = res.headers.get(COMPOSE_VERSION_HEADER);\n if (serverVersion === null || SDK_VERSION_TRIPLE === undefined) return;\n const serverTriple = parseVersion(serverVersion);\n if (serverTriple === undefined) return;\n\n const compatibility = checkCompatibility(SDK_VERSION_TRIPLE, serverTriple);\n if (compatibility === 'compatible') return;\n\n const versions = { sdkVersion: SDK_VERSION, serverVersion };\n if (compatibility === 'sdk_outdated') {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `composer-sdk ${SDK_VERSION} is older than the compose contract served at ${url} (${serverVersion}); upgrade @lifi/composer-sdk and @lifi/compose-spec`,\n {\n status: res.status,\n url,\n kind: 'sdk_outdated',\n sdkOutdated: {\n ...versions,\n minimumSdkVersion: `${serverTriple.major}.${serverTriple.minor}.0`,\n },\n },\n );\n }\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `composer-sdk ${SDK_VERSION} targets a newer compose contract than the server at ${url} serves (${serverVersion}); pin @lifi/composer-sdk and @lifi/compose-spec to ${serverVersion} or wait for the server rollout`,\n {\n status: res.status,\n url,\n kind: 'server_outdated',\n serverOutdated: versions,\n },\n );\n};\n\ntype SendInit =\n | { readonly method: 'GET' }\n | { readonly method: 'POST'; readonly body: unknown };\n\n// GETs on this API carry no body; POSTs carry a JSON one with `bigint` amounts\n// rendered as decimal strings.\nconst requestInit = (\n baseHeaders: Record<string, string>,\n init: SendInit,\n): RequestInit =>\n init.method === 'GET'\n ? { method: 'GET', headers: { ...baseHeaders } }\n : {\n method: 'POST',\n headers: { ...baseHeaders, 'Content-Type': 'application/json' },\n body: JSON.stringify(init.body, bigintReplacer),\n };\n\n// One fetch path for every route: maps transport failures to `NETWORK_ERROR`.\n// The response version check is not here — only the compile-family POSTs gate\n// on it (see `postCompile`); discovery GETs and `/simulate` are ungated.\nconst send = async (\n { fetchFn, baseHeaders }: ComposeTransport,\n url: string,\n init: SendInit,\n): Promise<Response> => {\n try {\n return await fetchFn(url, requestInit(baseHeaders, init));\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n};\n\nconst postCompile = async (\n transport: ComposeTransport,\n url: string,\n request: ComposeCompileRequest | ComposeRouteRequest,\n): Promise<ComposeCompileResult> => {\n const res = await send(transport, url, { method: 'POST', body: request });\n assertServerVersion(res, url);\n if (res.status === 206) {\n return await parsePartialBody(res, url);\n }\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseCompileSuccessBody(res, url);\n};\n\n// Every enveloped GET on this API behaves identically: no body, no query\n// semantics of its own, `{ data }` on success, an error envelope otherwise.\nconst getJson = async <T>(\n transport: ComposeTransport,\n url: string,\n): Promise<T> => {\n const res = await send(transport, url, { method: 'GET' });\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseBody<T>(res, url);\n};\n\n/**\n * Creates a low-level Compose API client.\n *\n * @param options - Client configuration including the API base URL.\n * @returns A {@link ComposeClient} instance.\n */\nexport const createComposeClient = (\n options: ComposeClientOptions,\n): ComposeClient => {\n if (!options.baseUrl || !/^https?:\\/\\//i.test(options.baseUrl)) {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `Invalid baseUrl: expected an HTTP(S) URL, got \"${options.baseUrl}\"`,\n );\n }\n const trimmedApiKey = options.apiKey?.trim() || undefined;\n if (!trimmedApiKey) {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n 'apiKey is required: pass a LI.FI API key to createComposeSdk().',\n );\n }\n const fetchFn = options.fetch ?? globalThis.fetch;\n const base = options.baseUrl.replace(/\\/$/, '');\n\n const baseHeaders: Record<string, string> = {\n Accept: 'application/json',\n [COMPOSER_SDK_VERSION_HEADER]: SDK_VERSION,\n 'x-lifi-api-key': trimmedApiKey,\n };\n const transport: ComposeTransport = { fetchFn, baseHeaders };\n\n const getManifest = async (): Promise<ComposeManifest> =>\n getJson<ComposeManifest>(transport, `${base}/compose/manifest`);\n\n const getChains = async (): Promise<readonly ChainSummary[]> =>\n getJson<readonly ChainSummary[]>(transport, `${base}/chains`);\n\n const compile = async (\n request: ComposeCompileRequest,\n ): Promise<ComposeCompileResult> =>\n postCompile(transport, `${base}/compose`, request);\n\n const route = async (\n request: ComposeRouteRequest,\n ): Promise<ComposeCompileResult> =>\n postCompile(transport, `${base}/compose/route`, request);\n\n const getZapPacks = async (\n options?: GetZapPacksOptions,\n ): Promise<readonly ZapPackOverview[]> => {\n const params = new URLSearchParams();\n if (options?.protocols !== undefined) {\n // Backend expects a single comma-separated value, not repeated keys.\n const raw = options.protocols;\n const list = typeof raw === 'string' ? raw : raw.join(',');\n params.set('protocols', list);\n }\n const qs = params.toString();\n return getJson<readonly ZapPackOverview[]>(\n transport,\n `${base}/compose/zap-packs${qs ? `?${qs}` : ''}`,\n );\n };\n\n const simulate = async (\n request: SimulateRequest,\n ): Promise<SimulateResult> => {\n const url = `${base}/simulate`;\n const res = await send(transport, url, { method: 'POST', body: request });\n // Only 200 (carries `ok`/`revert`) and 422 (carries the `error` member of\n // the union) have a discriminated body. 422 is deliberately intercepted\n // here (not thrown as VALIDATION_ERROR) so callers get one exhaustive\n // `switch (result.status)`. Every other status is a transport error and is\n // thrown — including HTTP 400 (malformed input, no `status` body) and any\n // unexpected 2xx.\n if (res.status === 200 || res.status === 422) {\n return await parseSimulateBody(res, url);\n }\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n };\n\n return { getManifest, getChains, compile, route, getZapPacks, simulate };\n};\n"],"mappings":"AAUA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAOP,SAAS,cAAc,6BAA6B;AACpD;AAAA,EACE;AAAA,EACA;AAAA,OACK;AASP,MAAM,cACJ,OAAyC,UAAkB;AAE7D,MAAM,qBAAqB,aAAa,WAAW;AA2J5C,MAAM,iBAAiB,CAAC,MAAc,UAC3C,OAAO,UAAU,WAAW,MAAM,SAAS,IAAI;AAEjD,MAAM,kBAAkB,CAAC,MACvB,OAAO,MAAM,YAAY,MAAM;AAGjC,MAAM,iBAAiB;AAEvB,MAAM,eAAe,CAAC,OAAgB,MAAc,QAAwB;AAC1E,MAAI,OAAO,UAAU,YAAY,CAAC,eAAe,KAAK,KAAK,GAAG;AAC5D,UAAM,IAAI;AAAA,MACR;AAAA,MACA,+BAA+B,IAAI,OACjC,UAAU,SAAY,WAAW,uBACnC;AAAA,MACA,EAAE,IAAI;AAAA,IACR;AAAA,EACF;AACA,SAAO,OAAO,KAAK;AACrB;AAgBA,MAAM,YAAY,CAAC,MAAc,MAAc,QAC7C,IAAI;AAAA,EACF;AAAA,EACA,+BAA+B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WAAW,GAAG,IAAI,kBAAkB,OAAO;AAEzD,QAAM,cAAc,OAClBA,aACwC;AACxC,UAAM,SAAS,IAAI,gBAAgB;AACnC,QAAIA,UAAS,cAAc,QAAW;AAEpC,YAAM,MAAMA,SAAQ;AACpB,YAAM,OAAO,OAAO,QAAQ,WAAW,MAAM,IAAI,KAAK,GAAG;AACzD,aAAO,IAAI,aAAa,IAAI;AAAA,IAC9B;AACA,UAAM,KAAK,OAAO,SAAS;AAC3B,WAAO;AAAA,MACL;AAAA,MACA,GAAG,IAAI,qBAAqB,KAAK,IAAI,EAAE,KAAK,EAAE;AAAA,IAChD;AAAA,EACF;AAEA,QAAM,WAAW,OACf,YAC4B;AAC5B,UAAM,MAAM,GAAG,IAAI;AACnB,UAAM,MAAM,MAAM,KAAK,WAAW,KAAK,EAAE,QAAQ,QAAQ,MAAM,QAAQ,CAAC;AAOxE,QAAI,IAAI,WAAW,OAAO,IAAI,WAAW,KAAK;AAC5C,aAAO,MAAM,kBAAkB,KAAK,GAAG;AAAA,IACzC;AACA,UAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,UAAM,sBAAsB,IAAI,QAAQ,MAAM,GAAG;AAAA,EACnD;AAEA,SAAO,EAAE,aAAa,WAAW,SAAS,OAAO,aAAa,SAAS;AACzE;","names":["options"]}
|
package/dist/errors.cjs
CHANGED
|
@@ -48,8 +48,23 @@ class ComposeError extends Error {
|
|
|
48
48
|
url;
|
|
49
49
|
/** Server-provided error kind for finer-grained classification. */
|
|
50
50
|
kind;
|
|
51
|
-
/**
|
|
51
|
+
/**
|
|
52
|
+
* Where a validation error points: the node id for a rejection of an
|
|
53
|
+
* authored node, or a JSON-pointer path for a rejection of the request shape.
|
|
54
|
+
*/
|
|
52
55
|
path;
|
|
56
|
+
/**
|
|
57
|
+
* The input port of {@link ComposeError.path}'s node whose binding caused the
|
|
58
|
+
* error. Set when the rejection is about what a port binds rather than about
|
|
59
|
+
* the node's config.
|
|
60
|
+
*/
|
|
61
|
+
port;
|
|
62
|
+
/**
|
|
63
|
+
* The one edit that clears the error, written for whoever authored the flow.
|
|
64
|
+
* Set on `continuation.settle` authoring rejections; may be absent on other
|
|
65
|
+
* `validation_error`s.
|
|
66
|
+
*/
|
|
67
|
+
fix;
|
|
53
68
|
/**
|
|
54
69
|
* Simulation revert diagnostics attached to `simulation_revert` errors.
|
|
55
70
|
* Contains the raw error bytes and decoded error candidates when the
|
|
@@ -78,6 +93,8 @@ class ComposeError extends Error {
|
|
|
78
93
|
this.url = options?.url;
|
|
79
94
|
this.kind = options?.kind;
|
|
80
95
|
this.path = options?.path;
|
|
96
|
+
this.port = options?.port;
|
|
97
|
+
this.fix = options?.fix;
|
|
81
98
|
this.details = options?.details;
|
|
82
99
|
this.failedOps = options?.failedOps;
|
|
83
100
|
this.succeededOps = options?.succeededOps;
|
|
@@ -131,6 +148,8 @@ const errorFromHttpResponse = (status, body, url) => {
|
|
|
131
148
|
url,
|
|
132
149
|
kind: serverError?.kind,
|
|
133
150
|
path: serverError?.path,
|
|
151
|
+
port: serverError?.port,
|
|
152
|
+
fix: serverError?.fix,
|
|
134
153
|
details: serverError?.details,
|
|
135
154
|
// The wire schema types `kind` as a bare string; the server only ever
|
|
136
155
|
// reports generic kinds for individual ops.
|
package/dist/errors.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts"],"sourcesContent":["import type {\n ComposeErrorKind,\n ComposeRouteErrorKind,\n FailedPreparedOp,\n GenericComposeErrorKind,\n SimulationRevert,\n} from '@lifi/compose-spec';\nimport z from 'zod';\n\nimport {\n parseServerErrorBody,\n type ServerErrorBody,\n} from './responseSchemas.js';\n\n/**\n * Machine-readable error codes returned by the SDK.\n *\n * - `NETWORK_ERROR` — The HTTP request failed (DNS, timeout, connection refused).\n * - `VALIDATION_ERROR` — The server rejected the request (HTTP 400/422).\n * - `UNAUTHENTICATED` — The request lacks valid authentication credentials (HTTP 401).\n * - `FORBIDDEN` — The server understood the request but refuses to authorise it (HTTP 403).\n * - `SERVER_ERROR` — The server returned a 5xx status.\n * - `RATE_LIMITED` — The server returned HTTP 429.\n * - `NOT_FOUND` — The requested resource does not exist (HTTP 404).\n * - `UNKNOWN_ERROR` — An unexpected error that doesn't fit other categories.\n */\nexport type ComposeErrorCode =\n | 'NETWORK_ERROR'\n | 'VALIDATION_ERROR'\n | 'UNAUTHENTICATED'\n | 'FORBIDDEN'\n | 'SERVER_ERROR'\n | 'RATE_LIMITED'\n | 'NOT_FOUND'\n | 'UNKNOWN_ERROR';\n\n/** Version details returned when the backend rejects an outdated SDK. */\nexport interface ComposeSdkOutdated {\n readonly sdkVersion: string;\n readonly serverVersion: string;\n readonly minimumSdkVersion: string;\n}\n\n/**\n * Version details attached when the SDK is ahead of the backend it reached.\n * Raised by the backend's version gate, or by the SDK itself when the\n * `x-lifi-composer-version` response header names an older contract than the\n * one this SDK was built against.\n */\nexport interface ComposeServerOutdated {\n readonly sdkVersion: string;\n readonly serverVersion: string;\n}\n\n/**\n * Error class for all failures originating from the Compose SDK or API.\n *\n * Includes structured metadata beyond the error message to support\n * programmatic error handling.\n *\n * @example\n * ```ts\n * try {\n * await builder.compile(run);\n * } catch (e) {\n * if (isComposeError(e) && e.code === 'VALIDATION_ERROR') {\n * console.error('Invalid request:', e.message, e.path);\n * }\n * }\n * ```\n */\nexport class ComposeError extends Error {\n override readonly name = 'ComposeError';\n /** Machine-readable error category. */\n readonly code: ComposeErrorCode;\n /** HTTP status code, when the error originated from an HTTP response. */\n readonly status?: number;\n /** The request URL that produced the error. */\n readonly url?: string;\n /** Server-provided error kind for finer-grained classification. */\n readonly kind?: ComposeErrorKind | ComposeRouteErrorKind;\n /** JSON-pointer path to the field that caused a validation error. */\n readonly path?: string;\n /**\n * Simulation revert diagnostics attached to `simulation_revert` errors.\n * Contains the raw error bytes and decoded error candidates when the\n * backend can parse the revert reason.\n */\n readonly details?: SimulationRevert;\n /**\n * The prepared ops that failed, attached to `preparation_error` errors.\n * Each entry carries the `callId` of the failing node so callers can drop\n * the unroutable legs and resubmit a smaller flow.\n */\n readonly failedOps?: readonly FailedPreparedOp[];\n /**\n * The `callId`s of the prepared ops that succeeded, attached to\n * `preparation_error` errors alongside {@link ComposeError.failedOps}.\n */\n readonly succeededOps?: readonly string[];\n /** Version details attached only to `sdk_outdated` errors. */\n readonly sdkOutdated?: ComposeSdkOutdated;\n /** Version details attached only to `server_outdated` errors. */\n readonly serverOutdated?: ComposeServerOutdated;\n\n constructor(\n code: ComposeErrorCode,\n message: string,\n options?: {\n status?: number;\n url?: string;\n cause?: unknown;\n kind?: ComposeErrorKind | ComposeRouteErrorKind;\n path?: string;\n details?: SimulationRevert;\n failedOps?: readonly FailedPreparedOp[];\n succeededOps?: readonly string[];\n sdkOutdated?: ComposeSdkOutdated;\n serverOutdated?: ComposeServerOutdated;\n },\n ) {\n super(message, { cause: options?.cause });\n this.code = code;\n this.status = options?.status;\n this.url = options?.url;\n this.kind = options?.kind;\n this.path = options?.path;\n this.details = options?.details;\n this.failedOps = options?.failedOps;\n this.succeededOps = options?.succeededOps;\n this.sdkOutdated = options?.sdkOutdated;\n this.serverOutdated = options?.serverOutdated;\n }\n}\n\n/**\n * The per-op preparation diagnostics carried by `preparation_error` responses,\n * with both arrays known to be present. Produced by narrowing with\n * {@link isComposePreparationError}.\n */\nexport interface ComposePreparationOps {\n readonly failedOps: readonly FailedPreparedOp[];\n readonly succeededOps: readonly string[];\n}\n\n/**\n * Type guard that narrows an unknown error to {@link ComposeError}.\n * @param e - The value to check.\n * @returns `true` if `e` is an instance of `ComposeError`.\n */\nexport const isComposeError = (e: unknown): e is ComposeError =>\n e instanceof ComposeError ||\n (e instanceof Error && e.name === 'ComposeError' && 'code' in e);\n\n/**\n * Type guard for `preparation_error` failures (HTTP 422): a mixed basket where\n * some prepared ops failed and others succeeded. Narrows both\n * {@link ComposeError.failedOps} and {@link ComposeError.succeededOps} to\n * present, so callers can read them without a cast or a truthiness check.\n *\n * @param e - The value to check.\n * @returns `true` if `e` is a `ComposeError` carrying per-op preparation diagnostics.\n *\n * @example\n * ```ts\n * try {\n * await builder.compile(run);\n * } catch (e) {\n * if (isComposePreparationError(e)) {\n * console.error('Failed ops:', e.failedOps);\n * console.error('Succeeded ops:', e.succeededOps);\n * }\n * }\n * ```\n */\nexport const isComposePreparationError = (\n e: unknown,\n): e is ComposeError & ComposePreparationOps =>\n isComposeError(e) &&\n e.kind === 'preparation_error' &&\n Array.isArray(e.failedOps) &&\n Array.isArray(e.succeededOps);\n\n// `isComposeError` accepts a structurally-similar error by name, so an error\n// raised by a *second* copy of this package in the dependency tree reaches the\n// guard below without its `sdkOutdated` field being type-guaranteed. Parse it.\nconst sdkOutdatedSchema = z.object({\n sdkVersion: z.string(),\n serverVersion: z.string(),\n minimumSdkVersion: z.string(),\n});\n\n/**\n * Narrows an outdated-SDK rejection to its required version details.\n *\n * @example\n * ```ts\n * try {\n * await builder.compile(run);\n * } catch (e) {\n * if (isComposeSdkOutdatedError(e)) {\n * console.error(`Upgrade to at least ${e.sdkOutdated.minimumSdkVersion}`);\n * return;\n * }\n * throw e;\n * }\n * ```\n */\nexport const isComposeSdkOutdatedError = (\n e: unknown,\n): e is ComposeError & { readonly sdkOutdated: ComposeSdkOutdated } =>\n isComposeError(e) &&\n e.kind === 'sdk_outdated' &&\n sdkOutdatedSchema.safeParse(e.sdkOutdated).success;\n\nconst serverOutdatedSchema = z.object({\n sdkVersion: z.string(),\n serverVersion: z.string(),\n});\n\n/**\n * Narrows a server-behind-SDK rejection to its required version details.\n *\n * This is the deploy-window error: the SDK on npm is ahead of the backend that\n * answered. Pin the SDK to the server's `major.minor`, or wait for the rollout.\n *\n * @example\n * ```ts\n * try {\n * await builder.compile(run);\n * } catch (e) {\n * if (isComposeServerOutdatedError(e)) {\n * console.error(`Server serves ${e.serverOutdated.serverVersion}`);\n * return;\n * }\n * throw e;\n * }\n * ```\n */\nexport const isComposeServerOutdatedError = (\n e: unknown,\n): e is ComposeError & { readonly serverOutdated: ComposeServerOutdated } =>\n isComposeError(e) &&\n e.kind === 'server_outdated' &&\n serverOutdatedSchema.safeParse(e.serverOutdated).success;\n\nconst STATUS_TO_CODE: ReadonlyMap<number, ComposeErrorCode> = new Map<\n number,\n ComposeErrorCode\n>([\n [400, 'VALIDATION_ERROR'],\n [401, 'UNAUTHENTICATED'],\n [403, 'FORBIDDEN'],\n [404, 'NOT_FOUND'],\n [422, 'VALIDATION_ERROR'],\n [429, 'RATE_LIMITED'],\n]);\n\nconst tryParseErrorBody = (body: string): ServerErrorBody | null => {\n let json: unknown;\n try {\n json = JSON.parse(body);\n } catch {\n return null;\n }\n return parseServerErrorBody(json);\n};\n\n/**\n * Extracts the version triple an `sdk_outdated` or `server_outdated` envelope\n * carries. The slots reuse the same schemas the type guards narrow with. Zod\n * strips keys the schema does not declare, so the parsed value is exactly the\n * triple; a partial payload fails the parse and yields `undefined` rather than\n * a half-populated object.\n */\nconst readVersionSlots = (serverError: ServerErrorBody['error']) => ({\n sdkOutdated:\n serverError?.kind === 'sdk_outdated'\n ? sdkOutdatedSchema.safeParse(serverError).data\n : undefined,\n serverOutdated:\n serverError?.kind === 'server_outdated'\n ? serverOutdatedSchema.safeParse(serverError).data\n : undefined,\n});\n\n/**\n * Constructs a {@link ComposeError} from an HTTP error response, extracting\n * structured error details from the response body when available.\n *\n * @param status - The HTTP status code.\n * @param body - The raw response body text.\n * @param url - The request URL that produced the error.\n * @returns A `ComposeError` with the appropriate error code and metadata.\n */\nexport const errorFromHttpResponse = (\n status: number,\n body: string,\n url: string,\n): ComposeError => {\n const parsed = tryParseErrorBody(body);\n const serverError = parsed?.error;\n const { sdkOutdated, serverOutdated } = readVersionSlots(serverError);\n\n return new ComposeError(\n STATUS_TO_CODE.get(status) ??\n (status >= 500 ? 'SERVER_ERROR' : 'UNKNOWN_ERROR'),\n (serverError?.message ?? body) || `HTTP ${status}`,\n {\n status,\n url,\n kind: serverError?.kind as\n ComposeErrorKind | ComposeRouteErrorKind | undefined,\n path: serverError?.path,\n details: serverError?.details,\n // The wire schema types `kind` as a bare string; the server only ever\n // reports generic kinds for individual ops.\n failedOps: serverError?.failedOps?.map((op) => ({\n ...op,\n kind: op.kind as GenericComposeErrorKind,\n })),\n succeededOps: serverError?.succeededOps,\n sdkOutdated,\n serverOutdated,\n },\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,iBAAc;AAEd,6BAGO;AA2DA,MAAM,qBAAqB,MAAM;AAAA,EACpB,OAAO;AAAA;AAAA,EAEhB;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA,EAET,YACE,MACA,SACA,SAYA;AACA,UAAM,SAAS,EAAE,OAAO,SAAS,MAAM,CAAC;AACxC,SAAK,OAAO;AACZ,SAAK,SAAS,SAAS;AACvB,SAAK,MAAM,SAAS;AACpB,SAAK,OAAO,SAAS;AACrB,SAAK,OAAO,SAAS;AACrB,SAAK,UAAU,SAAS;AACxB,SAAK,YAAY,SAAS;AAC1B,SAAK,eAAe,SAAS;AAC7B,SAAK,cAAc,SAAS;AAC5B,SAAK,iBAAiB,SAAS;AAAA,EACjC;AACF;AAiBO,MAAM,iBAAiB,CAAC,MAC7B,aAAa,gBACZ,aAAa,SAAS,EAAE,SAAS,kBAAkB,UAAU;AAuBzD,MAAM,4BAA4B,CACvC,MAEA,eAAe,CAAC,KAChB,EAAE,SAAS,uBACX,MAAM,QAAQ,EAAE,SAAS,KACzB,MAAM,QAAQ,EAAE,YAAY;AAK9B,MAAM,oBAAoB,WAAAA,QAAE,OAAO;AAAA,EACjC,YAAY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iBAAiB;AAAA,KACnC,aAAa,WAAW,SAAS,QAAQ,MAAM;AAAA,IAChD;AAAA,MACE;AAAA,MACA;AAAA,MACA,MAAM,aAAa;AAAA,MAEnB,MAAM,aAAa;AAAA,MACnB,SAAS,aAAa;AAAA;AAAA;AAAA,MAGtB,WAAW,aAAa,WAAW,IAAI,CAAC,QAAQ;AAAA,QAC9C,GAAG;AAAA,QACH,MAAM,GAAG;AAAA,MACX,EAAE;AAAA,MACF,cAAc,aAAa;AAAA,MAC3B;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;","names":["z"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts"],"sourcesContent":["import type {\n ComposeErrorKind,\n ComposeRouteErrorKind,\n FailedPreparedOp,\n GenericComposeErrorKind,\n SimulationRevert,\n} from '@lifi/compose-spec';\nimport z from 'zod';\n\nimport {\n parseServerErrorBody,\n type ServerErrorBody,\n} from './responseSchemas.js';\n\n/**\n * Machine-readable error codes returned by the SDK.\n *\n * - `NETWORK_ERROR` — The HTTP request failed (DNS, timeout, connection refused).\n * - `VALIDATION_ERROR` — The server rejected the request (HTTP 400/422).\n * - `UNAUTHENTICATED` — The request lacks valid authentication credentials (HTTP 401).\n * - `FORBIDDEN` — The server understood the request but refuses to authorise it (HTTP 403).\n * - `SERVER_ERROR` — The server returned a 5xx status.\n * - `RATE_LIMITED` — The server returned HTTP 429.\n * - `NOT_FOUND` — The requested resource does not exist (HTTP 404).\n * - `UNKNOWN_ERROR` — An unexpected error that doesn't fit other categories.\n */\nexport type ComposeErrorCode =\n | 'NETWORK_ERROR'\n | 'VALIDATION_ERROR'\n | 'UNAUTHENTICATED'\n | 'FORBIDDEN'\n | 'SERVER_ERROR'\n | 'RATE_LIMITED'\n | 'NOT_FOUND'\n | 'UNKNOWN_ERROR';\n\n/** Version details returned when the backend rejects an outdated SDK. */\nexport interface ComposeSdkOutdated {\n readonly sdkVersion: string;\n readonly serverVersion: string;\n readonly minimumSdkVersion: string;\n}\n\n/**\n * Version details attached when the SDK is ahead of the backend it reached.\n * Raised by the backend's version gate, or by the SDK itself when the\n * `x-lifi-composer-version` response header names an older contract than the\n * one this SDK was built against.\n */\nexport interface ComposeServerOutdated {\n readonly sdkVersion: string;\n readonly serverVersion: string;\n}\n\n/**\n * Error class for all failures originating from the Compose SDK or API.\n *\n * Includes structured metadata beyond the error message to support\n * programmatic error handling.\n *\n * @example\n * ```ts\n * try {\n * await builder.compile(run);\n * } catch (e) {\n * if (isComposeError(e) && e.code === 'VALIDATION_ERROR') {\n * console.error('Invalid request:', e.message, e.path);\n * }\n * }\n * ```\n */\nexport class ComposeError extends Error {\n override readonly name = 'ComposeError';\n /** Machine-readable error category. */\n readonly code: ComposeErrorCode;\n /** HTTP status code, when the error originated from an HTTP response. */\n readonly status?: number;\n /** The request URL that produced the error. */\n readonly url?: string;\n /** Server-provided error kind for finer-grained classification. */\n readonly kind?: ComposeErrorKind | ComposeRouteErrorKind;\n /**\n * Where a validation error points: the node id for a rejection of an\n * authored node, or a JSON-pointer path for a rejection of the request shape.\n */\n readonly path?: string;\n /**\n * The input port of {@link ComposeError.path}'s node whose binding caused the\n * error. Set when the rejection is about what a port binds rather than about\n * the node's config.\n */\n readonly port?: string;\n /**\n * The one edit that clears the error, written for whoever authored the flow.\n * Set on `continuation.settle` authoring rejections; may be absent on other\n * `validation_error`s.\n */\n readonly fix?: string;\n /**\n * Simulation revert diagnostics attached to `simulation_revert` errors.\n * Contains the raw error bytes and decoded error candidates when the\n * backend can parse the revert reason.\n */\n readonly details?: SimulationRevert;\n /**\n * The prepared ops that failed, attached to `preparation_error` errors.\n * Each entry carries the `callId` of the failing node so callers can drop\n * the unroutable legs and resubmit a smaller flow.\n */\n readonly failedOps?: readonly FailedPreparedOp[];\n /**\n * The `callId`s of the prepared ops that succeeded, attached to\n * `preparation_error` errors alongside {@link ComposeError.failedOps}.\n */\n readonly succeededOps?: readonly string[];\n /** Version details attached only to `sdk_outdated` errors. */\n readonly sdkOutdated?: ComposeSdkOutdated;\n /** Version details attached only to `server_outdated` errors. */\n readonly serverOutdated?: ComposeServerOutdated;\n\n constructor(\n code: ComposeErrorCode,\n message: string,\n options?: {\n status?: number;\n url?: string;\n cause?: unknown;\n kind?: ComposeErrorKind | ComposeRouteErrorKind;\n path?: string;\n port?: string;\n fix?: string;\n details?: SimulationRevert;\n failedOps?: readonly FailedPreparedOp[];\n succeededOps?: readonly string[];\n sdkOutdated?: ComposeSdkOutdated;\n serverOutdated?: ComposeServerOutdated;\n },\n ) {\n super(message, { cause: options?.cause });\n this.code = code;\n this.status = options?.status;\n this.url = options?.url;\n this.kind = options?.kind;\n this.path = options?.path;\n this.port = options?.port;\n this.fix = options?.fix;\n this.details = options?.details;\n this.failedOps = options?.failedOps;\n this.succeededOps = options?.succeededOps;\n this.sdkOutdated = options?.sdkOutdated;\n this.serverOutdated = options?.serverOutdated;\n }\n}\n\n/**\n * The per-op preparation diagnostics carried by `preparation_error` responses,\n * with both arrays known to be present. Produced by narrowing with\n * {@link isComposePreparationError}.\n */\nexport interface ComposePreparationOps {\n readonly failedOps: readonly FailedPreparedOp[];\n readonly succeededOps: readonly string[];\n}\n\n/**\n * Type guard that narrows an unknown error to {@link ComposeError}.\n * @param e - The value to check.\n * @returns `true` if `e` is an instance of `ComposeError`.\n */\nexport const isComposeError = (e: unknown): e is ComposeError =>\n e instanceof ComposeError ||\n (e instanceof Error && e.name === 'ComposeError' && 'code' in e);\n\n/**\n * Type guard for `preparation_error` failures (HTTP 422): a mixed basket where\n * some prepared ops failed and others succeeded. Narrows both\n * {@link ComposeError.failedOps} and {@link ComposeError.succeededOps} to\n * present, so callers can read them without a cast or a truthiness check.\n *\n * @param e - The value to check.\n * @returns `true` if `e` is a `ComposeError` carrying per-op preparation diagnostics.\n *\n * @example\n * ```ts\n * try {\n * await builder.compile(run);\n * } catch (e) {\n * if (isComposePreparationError(e)) {\n * console.error('Failed ops:', e.failedOps);\n * console.error('Succeeded ops:', e.succeededOps);\n * }\n * }\n * ```\n */\nexport const isComposePreparationError = (\n e: unknown,\n): e is ComposeError & ComposePreparationOps =>\n isComposeError(e) &&\n e.kind === 'preparation_error' &&\n Array.isArray(e.failedOps) &&\n Array.isArray(e.succeededOps);\n\n// `isComposeError` accepts a structurally-similar error by name, so an error\n// raised by a *second* copy of this package in the dependency tree reaches the\n// guard below without its `sdkOutdated` field being type-guaranteed. Parse it.\nconst sdkOutdatedSchema = z.object({\n sdkVersion: z.string(),\n serverVersion: z.string(),\n minimumSdkVersion: z.string(),\n});\n\n/**\n * Narrows an outdated-SDK rejection to its required version details.\n *\n * @example\n * ```ts\n * try {\n * await builder.compile(run);\n * } catch (e) {\n * if (isComposeSdkOutdatedError(e)) {\n * console.error(`Upgrade to at least ${e.sdkOutdated.minimumSdkVersion}`);\n * return;\n * }\n * throw e;\n * }\n * ```\n */\nexport const isComposeSdkOutdatedError = (\n e: unknown,\n): e is ComposeError & { readonly sdkOutdated: ComposeSdkOutdated } =>\n isComposeError(e) &&\n e.kind === 'sdk_outdated' &&\n sdkOutdatedSchema.safeParse(e.sdkOutdated).success;\n\nconst serverOutdatedSchema = z.object({\n sdkVersion: z.string(),\n serverVersion: z.string(),\n});\n\n/**\n * Narrows a server-behind-SDK rejection to its required version details.\n *\n * This is the deploy-window error: the SDK on npm is ahead of the backend that\n * answered. Pin the SDK to the server's `major.minor`, or wait for the rollout.\n *\n * @example\n * ```ts\n * try {\n * await builder.compile(run);\n * } catch (e) {\n * if (isComposeServerOutdatedError(e)) {\n * console.error(`Server serves ${e.serverOutdated.serverVersion}`);\n * return;\n * }\n * throw e;\n * }\n * ```\n */\nexport const isComposeServerOutdatedError = (\n e: unknown,\n): e is ComposeError & { readonly serverOutdated: ComposeServerOutdated } =>\n isComposeError(e) &&\n e.kind === 'server_outdated' &&\n serverOutdatedSchema.safeParse(e.serverOutdated).success;\n\nconst STATUS_TO_CODE: ReadonlyMap<number, ComposeErrorCode> = new Map<\n number,\n ComposeErrorCode\n>([\n [400, 'VALIDATION_ERROR'],\n [401, 'UNAUTHENTICATED'],\n [403, 'FORBIDDEN'],\n [404, 'NOT_FOUND'],\n [422, 'VALIDATION_ERROR'],\n [429, 'RATE_LIMITED'],\n]);\n\nconst tryParseErrorBody = (body: string): ServerErrorBody | null => {\n let json: unknown;\n try {\n json = JSON.parse(body);\n } catch {\n return null;\n }\n return parseServerErrorBody(json);\n};\n\n/**\n * Extracts the version triple an `sdk_outdated` or `server_outdated` envelope\n * carries. The slots reuse the same schemas the type guards narrow with. Zod\n * strips keys the schema does not declare, so the parsed value is exactly the\n * triple; a partial payload fails the parse and yields `undefined` rather than\n * a half-populated object.\n */\nconst readVersionSlots = (serverError: ServerErrorBody['error']) => ({\n sdkOutdated:\n serverError?.kind === 'sdk_outdated'\n ? sdkOutdatedSchema.safeParse(serverError).data\n : undefined,\n serverOutdated:\n serverError?.kind === 'server_outdated'\n ? serverOutdatedSchema.safeParse(serverError).data\n : undefined,\n});\n\n/**\n * Constructs a {@link ComposeError} from an HTTP error response, extracting\n * structured error details from the response body when available.\n *\n * @param status - The HTTP status code.\n * @param body - The raw response body text.\n * @param url - The request URL that produced the error.\n * @returns A `ComposeError` with the appropriate error code and metadata.\n */\nexport const errorFromHttpResponse = (\n status: number,\n body: string,\n url: string,\n): ComposeError => {\n const parsed = tryParseErrorBody(body);\n const serverError = parsed?.error;\n const { sdkOutdated, serverOutdated } = readVersionSlots(serverError);\n\n return new ComposeError(\n STATUS_TO_CODE.get(status) ??\n (status >= 500 ? 'SERVER_ERROR' : 'UNKNOWN_ERROR'),\n (serverError?.message ?? body) || `HTTP ${status}`,\n {\n status,\n url,\n kind: serverError?.kind as\n ComposeErrorKind | ComposeRouteErrorKind | undefined,\n path: serverError?.path,\n port: serverError?.port,\n fix: serverError?.fix,\n details: serverError?.details,\n // The wire schema types `kind` as a bare string; the server only ever\n // reports generic kinds for individual ops.\n failedOps: serverError?.failedOps?.map((op) => ({\n ...op,\n kind: op.kind as GenericComposeErrorKind,\n })),\n succeededOps: ser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AiB;AAAA,KACnC,aAAa,WAAW,SAAS,QAAQ,MAAM;AAAA,IAChD;AAAA,MACE;AAAA,MACA;AAAA,MACA,MAAM,aAAa;AAAA,MAEnB,MAAM,aAAa;AAAA,MACnB,MAAM,aAAa;AAAA,MACnB,KAAK,aAAa;AAAA,MAClB,SAAS,aAAa;AAAA;AAAA;AAAA,MAGtB,WAAW,aAAa,WAAW,IAAI,CAAC,QAAQ;AAAA,QAC9C,GAAG;AAAA,QACH,MAAM,GAAG;AAAA,MACX,EAAE;AAAA,MACF,cAAc,aAAa;AAAA,MAC3B;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;","names":["z"]}
|
package/dist/errors.d.cts
CHANGED
|
@@ -56,8 +56,23 @@ declare class ComposeError extends Error {
|
|
|
56
56
|
readonly url?: string;
|
|
57
57
|
/** Server-provided error kind for finer-grained classification. */
|
|
58
58
|
readonly kind?: ComposeErrorKind | ComposeRouteErrorKind;
|
|
59
|
-
/**
|
|
59
|
+
/**
|
|
60
|
+
* Where a validation error points: the node id for a rejection of an
|
|
61
|
+
* authored node, or a JSON-pointer path for a rejection of the request shape.
|
|
62
|
+
*/
|
|
60
63
|
readonly path?: string;
|
|
64
|
+
/**
|
|
65
|
+
* The input port of {@link ComposeError.path}'s node whose binding caused the
|
|
66
|
+
* error. Set when the rejection is about what a port binds rather than about
|
|
67
|
+
* the node's config.
|
|
68
|
+
*/
|
|
69
|
+
readonly port?: string;
|
|
70
|
+
/**
|
|
71
|
+
* The one edit that clears the error, written for whoever authored the flow.
|
|
72
|
+
* Set on `continuation.settle` authoring rejections; may be absent on other
|
|
73
|
+
* `validation_error`s.
|
|
74
|
+
*/
|
|
75
|
+
readonly fix?: string;
|
|
61
76
|
/**
|
|
62
77
|
* Simulation revert diagnostics attached to `simulation_revert` errors.
|
|
63
78
|
* Contains the raw error bytes and decoded error candidates when the
|
|
@@ -85,6 +100,8 @@ declare class ComposeError extends Error {
|
|
|
85
100
|
cause?: unknown;
|
|
86
101
|
kind?: ComposeErrorKind | ComposeRouteErrorKind;
|
|
87
102
|
path?: string;
|
|
103
|
+
port?: string;
|
|
104
|
+
fix?: string;
|
|
88
105
|
details?: SimulationRevert;
|
|
89
106
|
failedOps?: readonly FailedPreparedOp[];
|
|
90
107
|
succeededOps?: readonly string[];
|