@fuserstudio/sdk 0.0.2 → 0.0.4

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 CHANGED
@@ -1,13 +1,23 @@
1
1
  # @fuserstudio/sdk
2
2
 
3
- The TypeScript SDK for the [Fuser](https://fuser.studio) API. Each API tool is a
4
- method named after it: `canvas_edit` becomes `fuser.canvas.edit()`. The
5
- arguments and results are the same as in the REST API and the MCP server.
3
+ The official TypeScript SDK for the [Fuser](https://fuser.studio) API.
4
+
5
+ Fuser is a node canvas for AI image, video, audio and 3D work. With this SDK
6
+ you build canvases, run them, and collect the results from code: the same
7
+ things the Fuser app and the Fuser MCP server do. Every API tool is a method
8
+ named after it (`canvas_edit` is `fuser.canvas.edit()`), with the same
9
+ arguments and results as the REST API, fully typed.
10
+
11
+ ## Install
6
12
 
7
13
  ```bash
8
14
  npm install @fuserstudio/sdk
9
15
  ```
10
16
 
17
+ Works on Node 20.3+, Bun, Deno and Cloudflare Workers. It has no dependencies.
18
+
19
+ ## Usage
20
+
11
21
  ```ts
12
22
  import { Fuser } from '@fuserstudio/sdk';
13
23
 
@@ -34,7 +44,104 @@ const run = await fuser.run
34
44
  console.log(run.nodes[0]?.outputs);
35
45
  ```
36
46
 
37
- Works on Node 20.3+, Bun, Deno and Cloudflare Workers. Keep your API key on a
38
- server. It acts as you, so the SDK refuses to run in a browser unless you pass `dangerouslyAllowBrowser`.
47
+ ## What's in it
48
+
49
+ | Group | Methods | For |
50
+ | --------------- | ------------------------------------ | --------------------------------------------- |
51
+ | `fuser.account` | `get` | Credits, plan and workspaces |
52
+ | `fuser.canvas` | `list`, `get`, `edit`, `arrange` | Reading, changing and laying out canvases |
53
+ | `fuser.catalog` | `search` | Finding node types, their inputs and prices |
54
+ | `fuser.run` | `start`, `get`, `cancel`, `wait` | Pricing and running nodes |
55
+ | `fuser.media` | `search`, `view`, `import`, `export` | Your images and videos, and ZIP downloads |
56
+ | `fuser.upload` | `files`, `start`, `finish` | Sending local files to a canvas |
57
+ | `fuser.tool` | `search`, `build` | Tool nodes that crop, join, convert and so on |
58
+
59
+ ## Authentication
60
+
61
+ Create an API key in Fuser and set it as `FUSER_API_KEY`, or pass it in:
62
+
63
+ ```ts
64
+ const fuser = new Fuser({ apiKey: process.env.MY_FUSER_KEY });
65
+ ```
66
+
67
+ A key acts as you, so keep it on a server. The SDK refuses to run in a browser
68
+ unless you pass `dangerouslyAllowBrowser: true`.
69
+
70
+ ## Waiting for runs and builds
71
+
72
+ `run.start()` and `tool.build()` answer straight away. Await them for that
73
+ first answer, or add `.wait()` to get the finished result:
74
+
75
+ ```ts
76
+ const quote = await fuser.run.start({ canvasId, dryRun: true }); // price only
77
+
78
+ const run = await fuser.run.start({ canvasId, maxCredits: 200 }).wait();
79
+ ```
80
+
81
+ `.wait()` gives up after 30 minutes for a run and 10 for a tool build; pass
82
+ `timeoutMs` or an `AbortSignal` to change that.
83
+
84
+ ## Lists
85
+
86
+ List methods return one page when awaited and every item when iterated:
87
+
88
+ ```ts
89
+ const firstPage = await fuser.canvas.list();
90
+
91
+ for await (const canvas of fuser.canvas.list()) {
92
+ console.log(canvas.title);
93
+ }
94
+ ```
95
+
96
+ ## Uploading files
97
+
98
+ ```ts
99
+ import { readFile } from 'node:fs/promises';
100
+
101
+ const [photo] = await fuser.upload.files(canvasId, [
102
+ {
103
+ fileName: 'bag.jpg',
104
+ data: await readFile('bag.jpg'),
105
+ contentType: 'image/jpeg',
106
+ },
107
+ ]);
108
+ ```
109
+
110
+ ## Errors
111
+
112
+ Every failure is a `FuserError` with the `tool` that failed, the HTTP `status`,
113
+ the API's `code` and a `requestId`. Subclasses say what went wrong:
114
+ `BadRequestError`, `AuthenticationError`, `PermissionDeniedError`,
115
+ `NotFoundError`, `ConflictError`, `RateLimitError`, `InternalServerError`,
116
+ `ConnectionError`, `TimeoutError` and `RunRefusedError`.
117
+
118
+ ```ts
119
+ import { ConflictError } from '@fuserstudio/sdk';
120
+
121
+ try {
122
+ await fuser.canvas.edit({ canvasId, expectedRevision, diff });
123
+ } catch (error) {
124
+ if (error instanceof ConflictError && error.reason === 'stale_revision') {
125
+ // someone else changed the canvas: read it again and retry
126
+ }
127
+ throw error;
128
+ }
129
+ ```
130
+
131
+ ## Retries and timeouts
132
+
133
+ Requests time out after 60 seconds and are retried twice. Change both on the
134
+ client or for one call:
135
+
136
+ ```ts
137
+ const fuser = new Fuser({ timeoutMs: 20_000, maxRetries: 0 });
138
+
139
+ await fuser.canvas.get({ canvasId }, { timeoutMs: 5_000 });
140
+ ```
141
+
142
+ `beforeSend` and `afterSend` let you log or change each request, and `fetch`
143
+ swaps the HTTP client.
144
+
145
+ ## Documentation
39
146
 
40
- Full guide: https://docs.fuser.studio/docs/api/sdk
147
+ Full guide and API reference: https://docs.fuser.studio/docs/api/sdk
package/index.d.ts CHANGED
@@ -2100,7 +2100,7 @@ declare const toolSearch: <ThrowOnError extends boolean = false>(options: Option
2100
2100
  /**
2101
2101
  * Build a tool
2102
2102
  *
2103
- * Turn a Tool node (type UtilityNode, added with canvas_edit) into a working tool: describe it in prompt and Fuser writes its code, or place a saved one with toolId. Tools do what generators can't: join, cut, trim or speed up videos, mix audio, crop, grid, filter, measure and convert between images, video, audio, 3D models, text and JSON (not PDF, ZIP or other files). Call it again with a prompt to change a built tool, or with neither to check on a build. Once built, wire its input sockets and set its controls with canvas_edit, then run it like any node. Writing or changing a tool with a prompt spends credits (often 60 to 350 per build, more for a hard one) and no quote covers it; placing a saved tool with toolId is free, and a free tool costs nothing to run.
2103
+ * Turn a Tool node (type UtilityNode, added with canvas_edit) into a working tool: describe it in prompt and Fuser writes its code, or place a saved one with toolId. Tools do what generators can't: join, cut, trim or speed up videos, mix audio, crop, grid, filter, measure and convert between images, video, audio, 3D models, text and JSON (not PDF, ZIP or other files). Call it again with a prompt to change a built tool, or with neither to check on a build. Once built, wire its input sockets and set its controls with canvas_edit, then run it like any node; free tools cost nothing to run.
2104
2104
  */
2105
2105
  declare const toolBuild: <ThrowOnError extends boolean = false>(options: Options<ToolBuildData, ThrowOnError>) => RequestResult<ToolBuildResponses, ToolBuildErrors, ThrowOnError>;
2106
2106
  //#endregion
package/index.js CHANGED
@@ -1004,7 +1004,7 @@ const toolSearch = (options) => (options.client ?? client).get({
1004
1004
  /**
1005
1005
  * Build a tool
1006
1006
  *
1007
- * Turn a Tool node (type UtilityNode, added with canvas_edit) into a working tool: describe it in prompt and Fuser writes its code, or place a saved one with toolId. Tools do what generators can't: join, cut, trim or speed up videos, mix audio, crop, grid, filter, measure and convert between images, video, audio, 3D models, text and JSON (not PDF, ZIP or other files). Call it again with a prompt to change a built tool, or with neither to check on a build. Once built, wire its input sockets and set its controls with canvas_edit, then run it like any node. Writing or changing a tool with a prompt spends credits (often 60 to 350 per build, more for a hard one) and no quote covers it; placing a saved tool with toolId is free, and a free tool costs nothing to run.
1007
+ * Turn a Tool node (type UtilityNode, added with canvas_edit) into a working tool: describe it in prompt and Fuser writes its code, or place a saved one with toolId. Tools do what generators can't: join, cut, trim or speed up videos, mix audio, crop, grid, filter, measure and convert between images, video, audio, 3D models, text and JSON (not PDF, ZIP or other files). Call it again with a prompt to change a built tool, or with neither to check on a build. Once built, wire its input sockets and set its controls with canvas_edit, then run it like any node; free tools cost nothing to run.
1008
1008
  */
1009
1009
  const toolBuild = (options) => (options.client ?? client).post({
1010
1010
  security: [{
package/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["sdk"],"sources":["../src/errors.ts","../src/generated/core/bodySerializer.gen.ts","../src/generated/core/params.gen.ts","../src/generated/core/serverSentEvents.gen.ts","../src/generated/core/pathSerializer.gen.ts","../src/generated/core/utils.gen.ts","../src/generated/core/auth.gen.ts","../src/generated/client/utils.gen.ts","../src/generated/client/client.gen.ts","../src/generated/client.gen.ts","../src/generated/sdk.gen.ts","../src/pages.ts","../src/fuser.ts"],"sourcesContent":["import type { ApiError } from './generated/types.gen.js';\n\nexport interface FuserErrorDetails {\n /** The tool that failed, e.g. `run_start`. */\n tool: string;\n status?: number;\n /** The API's error kind, e.g. `NOT_FOUND`. */\n code?: string;\n /** Which conflict a 409 is, e.g. `stale_revision`. */\n reason?: string;\n issues?: ApiError['issues'];\n requestId?: string;\n retryAfterMs?: number;\n body?: unknown;\n cause?: unknown;\n}\n\n/** Every error the SDK throws. Subclasses say what went wrong. */\nexport class FuserError extends Error {\n override name = 'FuserError';\n readonly tool: string;\n readonly status: number | undefined;\n readonly code: string | undefined;\n readonly reason: string | undefined;\n readonly issues: ApiError['issues'];\n readonly requestId: string | undefined;\n readonly retryAfterMs: number | undefined;\n readonly body: unknown;\n\n constructor(message: string, details: FuserErrorDetails) {\n super(message, { cause: details.cause });\n this.tool = details.tool;\n this.status = details.status;\n this.code = details.code;\n this.reason = details.reason;\n this.issues = details.issues;\n this.requestId = details.requestId;\n this.retryAfterMs = details.retryAfterMs;\n this.body = details.body;\n }\n}\n\nexport class BadRequestError extends FuserError {\n override name = 'BadRequestError';\n}\n\nexport class AuthenticationError extends FuserError {\n override name = 'AuthenticationError';\n}\n\nexport class PermissionDeniedError extends FuserError {\n override name = 'PermissionDeniedError';\n}\n\nexport class NotFoundError extends FuserError {\n override name = 'NotFoundError';\n}\n\nexport class ConflictError extends FuserError {\n override name = 'ConflictError';\n}\n\nexport class RateLimitError extends FuserError {\n override name = 'RateLimitError';\n}\n\nexport class InternalServerError extends FuserError {\n override name = 'InternalServerError';\n}\n\nexport class ConnectionError extends FuserError {\n override name = 'ConnectionError';\n}\n\nexport class TimeoutError extends FuserError {\n override name = 'TimeoutError';\n}\n\n/** `run.start(...).wait()` on a run Fuser refused to start. */\nexport class RunRefusedError extends FuserError {\n override name = 'RunRefusedError';\n}\n\nconst BY_STATUS: Record<number, typeof FuserError> = {\n 400: BadRequestError,\n 401: AuthenticationError,\n 403: PermissionDeniedError,\n 404: NotFoundError,\n 409: ConflictError,\n 429: RateLimitError,\n};\n\nexport function errorFromResponse(\n tool: string,\n response: Response,\n body: unknown,\n): FuserError {\n const parsed: Partial<ApiError> =\n body && typeof body === 'object' ? body : {};\n\n const Kind =\n BY_STATUS[response.status] ??\n (response.status >= 500 ? InternalServerError : FuserError);\n\n const retryAfter = Number(response.headers.get('retry-after'));\n\n const message =\n parsed.message ?? `${tool} failed with HTTP ${String(response.status)}.`;\n\n const issues = parsed.issues\n ?.map(issue =>\n issue.path ? `${issue.path}: ${issue.message}` : issue.message,\n )\n .join('; ');\n\n return new Kind(issues ? `${message}: ${issues}` : message, {\n tool,\n status: response.status,\n code: parsed.code,\n reason: parsed.reason,\n issues: parsed.issues,\n requestId: response.headers.get('x-request-id') ?? undefined,\n retryAfterMs: retryAfter > 0 ? retryAfter * 1000 : undefined,\n body,\n });\n}\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen.js';\n\nexport type QuerySerializer = (query: Record<string, unknown>) => string;\n\nexport type BodySerializer = (body: unknown) => unknown;\n\ntype QuerySerializerOptionsObject = {\n allowReserved?: boolean;\n array?: Partial<SerializerOptions<ArrayStyle>>;\n object?: Partial<SerializerOptions<ObjectStyle>>;\n};\n\nexport type QuerySerializerOptions = QuerySerializerOptionsObject & {\n /**\n * Per-parameter serialization overrides. When provided, these settings\n * override the global array/object settings for specific parameter names.\n */\n parameters?: Record<string, QuerySerializerOptionsObject>;\n};\n\nconst serializeFormDataPair = (data: FormData, key: string, value: unknown): void => {\n if (typeof value === 'string' || value instanceof Blob) {\n data.append(key, value);\n } else if (value instanceof Date) {\n data.append(key, value.toISOString());\n } else {\n data.append(key, JSON.stringify(value));\n }\n};\n\nconst serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => {\n if (typeof value === 'string') {\n data.append(key, value);\n } else {\n data.append(key, JSON.stringify(value));\n }\n};\n\nexport const formDataBodySerializer = {\n bodySerializer: (body: unknown): FormData => {\n const data = new FormData();\n\n Object.entries(body as Record<string, unknown>).forEach(([key, value]) => {\n if (value === undefined || value === null) {\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((v) => serializeFormDataPair(data, key, v));\n } else {\n serializeFormDataPair(data, key, value);\n }\n });\n\n return data;\n },\n};\n\nexport const jsonBodySerializer = {\n bodySerializer: (body: unknown): string =>\n JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)),\n};\n\nexport const urlSearchParamsBodySerializer = {\n bodySerializer: (body: unknown): string => {\n const data = new URLSearchParams();\n\n Object.entries(body as Record<string, unknown>).forEach(([key, value]) => {\n if (value === undefined || value === null) {\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));\n } else {\n serializeUrlSearchParamsPair(data, key, value);\n }\n });\n\n return data.toString();\n },\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\ntype Slot = 'body' | 'headers' | 'path' | 'query';\n\nexport type Field =\n | {\n in: Exclude<Slot, 'body'>;\n /**\n * Field name. This is the name we want the user to see and use.\n */\n key: string;\n /**\n * Field mapped name. This is the name we want to use in the request.\n * If omitted, we use the same value as `key`.\n */\n map?: string;\n }\n | {\n in: Extract<Slot, 'body'>;\n /**\n * Key isn't required for bodies.\n */\n key?: string;\n map?: string;\n }\n | {\n /**\n * Field name. This is the name we want the user to see and use.\n */\n key: string;\n /**\n * Field mapped name. This is the name we want to use in the request.\n * If `in` is omitted, `map` aliases `key` to the transport layer.\n */\n map: Slot;\n };\n\nexport interface Fields {\n allowExtra?: Partial<Record<Slot, boolean>>;\n args?: ReadonlyArray<Field>;\n}\n\nexport type FieldsConfig = ReadonlyArray<Field | Fields>;\n\nconst extraPrefixesMap: Record<string, Slot> = {\n $body_: 'body',\n $headers_: 'headers',\n $path_: 'path',\n $query_: 'query',\n};\nconst extraPrefixes = Object.entries(extraPrefixesMap);\n\ntype KeyMap = Map<\n string,\n | {\n in: Slot;\n map?: string;\n }\n | {\n in?: never;\n map: Slot;\n }\n>;\n\nfunction buildKeyMap(fields: FieldsConfig, map?: KeyMap): KeyMap {\n if (!map) {\n map = new Map();\n }\n\n for (const config of fields) {\n if ('in' in config) {\n if (config.key) {\n map.set(config.key, {\n in: config.in,\n map: config.map,\n });\n }\n } else if ('key' in config) {\n map.set(config.key, {\n map: config.map,\n });\n } else if (config.args) {\n buildKeyMap(config.args, map);\n }\n }\n\n return map;\n}\n\ninterface Params {\n body?: unknown;\n headers: Record<string, unknown>;\n path: Record<string, unknown>;\n query: Record<string, unknown>;\n}\n\nfunction stripEmptySlots(params: Params): void {\n for (const [slot, value] of Object.entries(params)) {\n if (slot === 'body') continue;\n if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) {\n delete params[slot as Slot];\n }\n }\n}\n\nexport function buildClientParams(args: ReadonlyArray<unknown>, fields: FieldsConfig): Params {\n const params: Params = {\n headers: Object.create(null),\n path: Object.create(null),\n query: Object.create(null),\n };\n\n const map = buildKeyMap(fields);\n\n function writeSlot(slot: Slot, key: string, value: unknown): void {\n let record = params[slot] as Record<string, unknown> | undefined;\n if (record === undefined) {\n record = Object.create(null) as Record<string, unknown>;\n params[slot] = record;\n }\n record[key] = value;\n }\n\n let config: FieldsConfig[number] | undefined;\n\n for (const [index, arg] of args.entries()) {\n if (fields[index]) {\n config = fields[index];\n }\n\n if (!config) {\n continue;\n }\n\n if ('in' in config) {\n if (config.key) {\n const field = map.get(config.key)!;\n const name = field.map || config.key;\n if (field.in) {\n writeSlot(field.in, name, arg);\n }\n } else {\n params.body = arg;\n }\n } else {\n for (const [key, value] of Object.entries(arg ?? {})) {\n const field = map.get(key);\n\n if (field) {\n if (field.in) {\n const name = field.map || key;\n writeSlot(field.in, name, value);\n } else {\n params[field.map] = value;\n }\n } else {\n const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix));\n\n if (extra) {\n const [prefix, slot] = extra;\n writeSlot(slot, key.slice(prefix.length), value);\n } else if ('allowExtra' in config && config.allowExtra) {\n for (const [slot, allowed] of Object.entries(config.allowExtra)) {\n if (allowed) {\n writeSlot(slot as Slot, key, value);\n break;\n }\n }\n }\n }\n }\n }\n }\n\n stripEmptySlots(params);\n\n return params;\n}\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport type { Config } from './types.gen.js';\n\nexport type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, 'method'> &\n Pick<Config, 'method' | 'responseTransformer' | 'responseValidator'> & {\n /**\n * Fetch API implementation. You can use this option to provide a custom\n * fetch instance.\n *\n * @default globalThis.fetch\n */\n fetch?: typeof fetch;\n /**\n * Implementing clients can call request interceptors inside this hook.\n */\n onRequest?: (url: string, init: RequestInit) => Promise<Request>;\n /**\n * Callback invoked when a network or parsing error occurs during streaming.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @param error The error that occurred.\n */\n onSseError?: (error: unknown) => void;\n /**\n * Callback invoked when an event is streamed from the server.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @param event Event streamed from the server.\n * @returns Nothing (void).\n */\n onSseEvent?: (event: StreamEvent<TData>) => void;\n serializedBody?: RequestInit['body'];\n /**\n * Default retry delay in milliseconds.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @default 3000\n */\n sseDefaultRetryDelay?: number;\n /**\n * Maximum number of retry attempts before giving up.\n */\n sseMaxRetryAttempts?: number;\n /**\n * Maximum retry delay in milliseconds.\n *\n * Applies only when exponential backoff is used.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @default 30000\n */\n sseMaxRetryDelay?: number;\n /**\n * Optional sleep function for retry backoff.\n *\n * Defaults to using `setTimeout`.\n */\n sseSleepFn?: (ms: number) => Promise<void>;\n url: string;\n };\n\nexport interface StreamEvent<TData = unknown> {\n data: TData;\n event?: string;\n id?: string;\n retry?: number;\n}\n\nexport type ServerSentEventsResult<TData = unknown, TReturn = void, TNext = unknown> = {\n stream: AsyncGenerator<\n TData extends Record<string, unknown> ? TData[keyof TData] : TData,\n TReturn,\n TNext\n >;\n};\n\nexport function createSseClient<TData = unknown>({\n onRequest,\n onSseError,\n onSseEvent,\n responseTransformer,\n responseValidator,\n sseDefaultRetryDelay,\n sseMaxRetryAttempts,\n sseMaxRetryDelay,\n sseSleepFn,\n url,\n ...options\n}: ServerSentEventsOptions): ServerSentEventsResult<TData> {\n let lastEventId: string | undefined;\n\n const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));\n\n const createStream = async function* () {\n let retryDelay: number = sseDefaultRetryDelay ?? 3000;\n let attempt = 0;\n const signal = options.signal ?? new AbortController().signal;\n\n while (true) {\n if (signal.aborted) break;\n\n attempt++;\n\n const headers =\n options.headers instanceof Headers\n ? options.headers\n : new Headers(options.headers as Record<string, string> | undefined);\n\n if (lastEventId !== undefined) {\n headers.set('Last-Event-ID', lastEventId);\n }\n\n try {\n const requestInit: RequestInit = {\n redirect: 'follow',\n ...options,\n body: options.serializedBody,\n headers,\n signal,\n };\n let request = new Request(url, requestInit);\n if (onRequest) {\n request = await onRequest(url, requestInit);\n }\n // fetch must be assigned here, otherwise it would throw the error:\n // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation\n const _fetch = options.fetch ?? globalThis.fetch;\n const response = await _fetch(request);\n\n if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);\n\n if (!response.body) throw new Error('No body in SSE response');\n\n const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();\n\n let buffer = '';\n\n const abortHandler = () => {\n try {\n reader.cancel();\n } catch {\n // noop\n }\n };\n\n signal.addEventListener('abort', abortHandler);\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += value;\n buffer = buffer.replace(/\\r\\n?/g, '\\n'); // normalize line endings\n\n const chunks = buffer.split('\\n\\n');\n buffer = chunks.pop() ?? '';\n\n for (const chunk of chunks) {\n const lines = chunk.split('\\n');\n const dataLines: Array<string> = [];\n let eventName: string | undefined;\n\n for (const line of lines) {\n if (line.startsWith('data:')) {\n dataLines.push(line.replace(/^data:\\s*/, ''));\n } else if (line.startsWith('event:')) {\n eventName = line.replace(/^event:\\s*/, '');\n } else if (line.startsWith('id:')) {\n lastEventId = line.replace(/^id:\\s*/, '');\n } else if (line.startsWith('retry:')) {\n const parsed = Number.parseInt(line.replace(/^retry:\\s*/, ''), 10);\n if (!Number.isNaN(parsed)) {\n retryDelay = parsed;\n }\n }\n }\n\n let data: unknown;\n let parsedJson = false;\n\n if (dataLines.length) {\n const rawData = dataLines.join('\\n');\n try {\n data = JSON.parse(rawData);\n parsedJson = true;\n } catch {\n data = rawData;\n }\n }\n\n if (parsedJson) {\n if (responseValidator) {\n await responseValidator(data);\n }\n\n if (responseTransformer) {\n data = await responseTransformer(data);\n }\n }\n\n onSseEvent?.({\n data,\n event: eventName,\n id: lastEventId,\n retry: retryDelay,\n });\n\n if (dataLines.length) {\n yield data as any;\n }\n }\n }\n } finally {\n signal.removeEventListener('abort', abortHandler);\n reader.releaseLock();\n }\n\n break; // exit loop on normal completion\n } catch (error) {\n // connection failed or aborted; retry after delay\n onSseError?.(error);\n\n if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) {\n break; // stop after firing error\n }\n\n // exponential backoff: double retry each attempt, cap at 30s\n const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000);\n await sleep(backoff);\n }\n }\n };\n\n const stream = createStream();\n\n return { stream };\n}\n","// This file is auto-generated by @hey-api/openapi-ts\n\ninterface SerializeOptions<T> extends SerializePrimitiveOptions, SerializerOptions<T> {}\n\ninterface SerializePrimitiveOptions {\n allowReserved?: boolean;\n name: string;\n}\n\nexport interface SerializerOptions<T> {\n /**\n * @default true\n */\n explode: boolean;\n style: T;\n}\n\nexport type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';\nexport type ArraySeparatorStyle = ArrayStyle | MatrixStyle;\ntype MatrixStyle = 'label' | 'matrix' | 'simple';\nexport type ObjectStyle = 'form' | 'deepObject';\ntype ObjectSeparatorStyle = ObjectStyle | MatrixStyle;\n\ninterface SerializePrimitiveParam extends SerializePrimitiveOptions {\n value: string;\n}\n\nexport const separatorArrayExplode = (style: ArraySeparatorStyle): '.' | ';' | ',' | '&' => {\n switch (style) {\n case 'label':\n return '.';\n case 'matrix':\n return ';';\n case 'simple':\n return ',';\n default:\n return '&';\n }\n};\n\nexport const separatorArrayNoExplode = (style: ArraySeparatorStyle): ',' | '|' | '%20' => {\n switch (style) {\n case 'form':\n return ',';\n case 'pipeDelimited':\n return '|';\n case 'spaceDelimited':\n return '%20';\n default:\n return ',';\n }\n};\n\nexport const separatorObjectExplode = (style: ObjectSeparatorStyle): '.' | ';' | ',' | '&' => {\n switch (style) {\n case 'label':\n return '.';\n case 'matrix':\n return ';';\n case 'simple':\n return ',';\n default:\n return '&';\n }\n};\n\nexport const serializeArrayParam = ({\n allowReserved,\n explode,\n name,\n style,\n value,\n}: SerializeOptions<ArraySeparatorStyle> & {\n value: unknown[];\n}): string => {\n if (!explode) {\n const joinedValues = (\n allowReserved ? value : value.map((v) => encodeURIComponent(v as string))\n ).join(separatorArrayNoExplode(style));\n switch (style) {\n case 'label':\n return `.${joinedValues}`;\n case 'matrix':\n return `;${name}=${joinedValues}`;\n case 'simple':\n return joinedValues;\n default:\n return `${name}=${joinedValues}`;\n }\n }\n\n const separator = separatorArrayExplode(style);\n const joinedValues = value\n .map((v) => {\n if (style === 'label' || style === 'simple') {\n return allowReserved ? v : encodeURIComponent(v as string);\n }\n\n return serializePrimitiveParam({\n allowReserved,\n name,\n value: v as string,\n });\n })\n .join(separator);\n return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues;\n};\n\nexport const serializePrimitiveParam = ({\n allowReserved,\n name,\n value,\n}: SerializePrimitiveParam): string => {\n if (value === undefined || value === null) {\n return '';\n }\n\n if (typeof value === 'object') {\n throw new Error(\n 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.',\n );\n }\n\n return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;\n};\n\nexport const serializeObjectParam = ({\n allowReserved,\n explode,\n name,\n style,\n value,\n valueOnly,\n}: SerializeOptions<ObjectSeparatorStyle> & {\n value: Record<string, unknown> | Date;\n valueOnly?: boolean;\n}): string => {\n if (value instanceof Date) {\n return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;\n }\n\n if (style !== 'deepObject' && !explode) {\n let values: string[] = [];\n Object.entries(value).forEach(([key, v]) => {\n values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)];\n });\n const joinedValues = values.join(',');\n switch (style) {\n case 'form':\n return `${name}=${joinedValues}`;\n case 'label':\n return `.${joinedValues}`;\n case 'matrix':\n return `;${name}=${joinedValues}`;\n default:\n return joinedValues;\n }\n }\n\n const separator = separatorObjectExplode(style);\n const joinedValues = Object.entries(value)\n .map(([key, v]) =>\n serializePrimitiveParam({\n allowReserved,\n name: style === 'deepObject' ? `${name}[${key}]` : key,\n value: v as string,\n }),\n )\n .join(separator);\n return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues;\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport type { BodySerializer, QuerySerializer } from './bodySerializer.gen.js';\nimport {\n type ArraySeparatorStyle,\n serializeArrayParam,\n serializeObjectParam,\n serializePrimitiveParam,\n} from './pathSerializer.gen.js';\n\nexport interface PathSerializer {\n path: Record<string, unknown>;\n url: string;\n}\n\nexport const PATH_PARAM_RE: RegExp = /\\{[^{}]+\\}/g;\n\nexport const defaultPathSerializer = ({ path, url: _url }: PathSerializer): string => {\n let url = _url;\n const matches = _url.match(PATH_PARAM_RE);\n if (matches) {\n for (const match of matches) {\n let explode = false;\n let name = match.substring(1, match.length - 1);\n let style: ArraySeparatorStyle = 'simple';\n\n if (name.endsWith('*')) {\n explode = true;\n name = name.substring(0, name.length - 1);\n }\n\n if (name.startsWith('.')) {\n name = name.substring(1);\n style = 'label';\n } else if (name.startsWith(';')) {\n name = name.substring(1);\n style = 'matrix';\n }\n\n const value = path[name];\n\n if (value === undefined || value === null) {\n continue;\n }\n\n if (Array.isArray(value)) {\n url = url.replace(match, serializeArrayParam({ explode, name, style, value }));\n continue;\n }\n\n if (typeof value === 'object') {\n url = url.replace(\n match,\n serializeObjectParam({\n explode,\n name,\n style,\n value: value as Record<string, unknown>,\n valueOnly: true,\n }),\n );\n continue;\n }\n\n if (style === 'matrix') {\n url = url.replace(\n match,\n `;${serializePrimitiveParam({\n name,\n value: value as string,\n })}`,\n );\n continue;\n }\n\n const replaceValue = encodeURIComponent(\n style === 'label' ? `.${value as string}` : (value as string),\n );\n url = url.replace(match, replaceValue);\n }\n }\n return url;\n};\n\nexport const getUrl = ({\n baseUrl,\n path,\n query,\n querySerializer,\n url: _url,\n}: {\n baseUrl?: string;\n path?: Record<string, unknown>;\n query?: Record<string, unknown>;\n querySerializer: QuerySerializer;\n url: string;\n}): string => {\n const pathUrl = _url.startsWith('/') ? _url : `/${_url}`;\n let url = (baseUrl ?? '') + pathUrl;\n if (path) {\n url = defaultPathSerializer({ path, url });\n }\n let search = query ? querySerializer(query) : '';\n if (search.startsWith('?')) {\n search = search.substring(1);\n }\n if (search) {\n url += `?${search}`;\n }\n return url;\n};\n\nexport function getValidRequestBody(options: {\n body?: unknown;\n bodySerializer?: BodySerializer | null;\n serializedBody?: unknown;\n}): unknown {\n const hasBody = options.body !== undefined;\n const isSerializedBody = hasBody && options.bodySerializer;\n\n if (isSerializedBody) {\n if ('serializedBody' in options) {\n const hasSerializedBody =\n options.serializedBody !== undefined && options.serializedBody !== '';\n\n return hasSerializedBody ? options.serializedBody : null;\n }\n\n // not all clients implement a serializedBody property (i.e., client-axios)\n return options.body !== '' ? options.body : null;\n }\n\n // plain/text body\n if (hasBody) {\n return options.body;\n }\n\n // no body was provided\n return undefined;\n}\n","// This file is auto-generated by @hey-api/openapi-ts\n\nexport type AuthToken = string | undefined;\n\nexport interface Auth {\n /**\n * Which part of the request do we use to send the auth?\n *\n * @default 'header'\n */\n in?: 'header' | 'query' | 'cookie';\n /**\n * A unique identifier for the security scheme.\n *\n * Defined only when there are multiple security schemes whose `Auth`\n * shape would otherwise be identical.\n */\n key?: string;\n /**\n * Header or query parameter name.\n *\n * @default 'Authorization'\n */\n name?: string;\n scheme?: 'basic' | 'bearer';\n type: 'apiKey' | 'http';\n}\n\nexport const getAuthToken = async (\n auth: Auth,\n callback: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken,\n): Promise<string | undefined> => {\n const token = typeof callback === 'function' ? await callback(auth) : callback;\n\n if (!token) {\n return;\n }\n\n if (auth.scheme === 'bearer') {\n return `Bearer ${token}`;\n }\n\n if (auth.scheme === 'basic') {\n return `Basic ${btoa(token)}`;\n }\n\n return token;\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { getAuthToken } from '../core/auth.gen.js';\nimport type { QuerySerializerOptions } from '../core/bodySerializer.gen.js';\nimport { jsonBodySerializer } from '../core/bodySerializer.gen.js';\nimport {\n serializeArrayParam,\n serializeObjectParam,\n serializePrimitiveParam,\n} from '../core/pathSerializer.gen.js';\nimport { getUrl } from '../core/utils.gen.js';\nimport type { Client, ClientOptions, Config, RequestOptions } from './types.gen.js';\n\nexport const createQuerySerializer = <T = unknown>({\n parameters = {},\n ...args\n}: QuerySerializerOptions = {}): ((queryParams: T) => string) => {\n const querySerializer = (queryParams: T): string => {\n const search: string[] = [];\n if (queryParams && typeof queryParams === 'object') {\n for (const name in queryParams) {\n const value = queryParams[name];\n\n if (value === undefined || value === null) {\n continue;\n }\n\n const options = parameters[name] || args;\n\n if (Array.isArray(value)) {\n const serializedArray = serializeArrayParam({\n allowReserved: options.allowReserved,\n explode: true,\n name,\n style: 'form',\n value,\n ...options.array,\n });\n if (serializedArray) search.push(serializedArray);\n } else if (typeof value === 'object') {\n const serializedObject = serializeObjectParam({\n allowReserved: options.allowReserved,\n explode: true,\n name,\n style: 'deepObject',\n value: value as Record<string, unknown>,\n ...options.object,\n });\n if (serializedObject) search.push(serializedObject);\n } else {\n const serializedPrimitive = serializePrimitiveParam({\n allowReserved: options.allowReserved,\n name,\n value: value as string,\n });\n if (serializedPrimitive) search.push(serializedPrimitive);\n }\n }\n }\n return search.join('&');\n };\n return querySerializer;\n};\n\n/**\n * Infers parseAs value from provided Content-Type header.\n */\nexport const getParseAs = (contentType: string | null): Exclude<Config['parseAs'], 'auto'> => {\n if (!contentType) {\n // If no Content-Type header is provided, the best we can do is return the raw response body,\n // which is effectively the same as the 'stream' option.\n return 'stream';\n }\n\n const cleanContent = contentType.split(';')[0]?.trim();\n\n if (!cleanContent) {\n return;\n }\n\n if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) {\n return 'json';\n }\n\n if (cleanContent === 'multipart/form-data') {\n return 'formData';\n }\n\n if (\n ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type))\n ) {\n return 'blob';\n }\n\n if (cleanContent.startsWith('text/')) {\n return 'text';\n }\n\n return;\n};\n\nconst checkForExistence = (\n options: Pick<RequestOptions, 'auth' | 'query'> & {\n headers: Headers;\n },\n name?: string,\n): boolean => {\n if (!name) {\n return false;\n }\n if (\n options.headers.has(name) ||\n options.query?.[name] ||\n options.headers.get('Cookie')?.includes(`${name}=`)\n ) {\n return true;\n }\n return false;\n};\n\nexport async function setAuthParams(\n options: Pick<RequestOptions, 'auth' | 'query' | 'security'> & {\n headers: Headers;\n },\n): Promise<void> {\n for (const auth of options.security ?? []) {\n if (checkForExistence(options, auth.name)) {\n continue;\n }\n\n const token = await getAuthToken(auth, options.auth);\n\n if (!token) {\n continue;\n }\n\n const name = auth.name ?? 'Authorization';\n\n switch (auth.in) {\n case 'query':\n if (!options.query) {\n options.query = {};\n }\n options.query[name] = token;\n break;\n case 'cookie':\n options.headers.append('Cookie', `${name}=${token}`);\n break;\n case 'header':\n default:\n options.headers.set(name, token);\n break;\n }\n }\n}\n\nexport const buildUrl: Client['buildUrl'] = (options) =>\n getUrl({\n baseUrl: options.baseUrl as string,\n path: options.path,\n query: options.query,\n querySerializer:\n typeof options.querySerializer === 'function'\n ? options.querySerializer\n : createQuerySerializer(options.querySerializer),\n url: options.url,\n });\n\nexport const mergeConfigs = (a: Config, b: Config): Config => {\n const config = { ...a, ...b };\n if (config.baseUrl?.endsWith('/')) {\n config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);\n }\n config.headers = mergeHeaders(a.headers, b.headers);\n return config;\n};\n\nconst headersEntries = (headers: Headers): Array<[string, string]> => {\n const entries: Array<[string, string]> = [];\n headers.forEach((value, key) => {\n entries.push([key, value]);\n });\n return entries;\n};\n\nexport const mergeHeaders = (\n ...headers: Array<Required<Config>['headers'] | undefined>\n): Headers => {\n const mergedHeaders = new Headers();\n for (const header of headers) {\n if (!header) {\n continue;\n }\n\n const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);\n\n for (const [key, value] of iterator) {\n if (value === null) {\n mergedHeaders.delete(key);\n } else if (Array.isArray(value)) {\n for (const v of value) {\n mergedHeaders.append(key, v as string);\n }\n } else if (value !== undefined) {\n // assume object headers are meant to be JSON stringified, i.e., their\n // content value in OpenAPI specification is 'application/json'\n mergedHeaders.set(\n key,\n typeof value === 'object' ? JSON.stringify(value) : (value as string),\n );\n }\n }\n }\n return mergedHeaders;\n};\n\ntype ErrInterceptor<Err, Res, Req, Options> = (\n error: Err,\n /** response may be undefined due to a network error where no response object is produced */\n response: Res | undefined,\n /** request may be undefined, because error may be from building the request object itself */\n request: Req | undefined,\n options: Options,\n) => Err | Promise<Err>;\n\ntype ReqInterceptor<Req, Options> = (request: Req, options: Options) => Req | Promise<Req>;\n\ntype ResInterceptor<Res, Req, Options> = (\n response: Res,\n request: Req,\n options: Options,\n) => Res | Promise<Res>;\n\nclass Interceptors<Interceptor> {\n fns: Array<Interceptor | null> = [];\n\n clear(): void {\n this.fns = [];\n }\n\n eject(id: number | Interceptor): void {\n const index = this.getInterceptorIndex(id);\n if (this.fns[index]) {\n this.fns[index] = null;\n }\n }\n\n exists(id: number | Interceptor): boolean {\n const index = this.getInterceptorIndex(id);\n return Boolean(this.fns[index]);\n }\n\n getInterceptorIndex(id: number | Interceptor): number {\n if (typeof id === 'number') {\n return this.fns[id] ? id : -1;\n }\n return this.fns.indexOf(id);\n }\n\n update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false {\n const index = this.getInterceptorIndex(id);\n if (this.fns[index]) {\n this.fns[index] = fn;\n return id;\n }\n return false;\n }\n\n use(fn: Interceptor): number {\n this.fns.push(fn);\n return this.fns.length - 1;\n }\n}\n\nexport interface Middleware<Req, Res, Err, Options> {\n error: Interceptors<ErrInterceptor<Err, Res, Req, Options>>;\n request: Interceptors<ReqInterceptor<Req, Options>>;\n response: Interceptors<ResInterceptor<Res, Req, Options>>;\n}\n\nexport const createInterceptors = <Req, Res, Err, Options>(): Middleware<\n Req,\n Res,\n Err,\n Options\n> => ({\n error: new Interceptors<ErrInterceptor<Err, Res, Req, Options>>(),\n request: new Interceptors<ReqInterceptor<Req, Options>>(),\n response: new Interceptors<ResInterceptor<Res, Req, Options>>(),\n});\n\nconst defaultQuerySerializer = createQuerySerializer({\n allowReserved: false,\n array: {\n explode: true,\n style: 'form',\n },\n object: {\n explode: true,\n style: 'deepObject',\n },\n});\n\nconst defaultHeaders = {\n 'Content-Type': 'application/json',\n};\n\nexport const createConfig = <T extends ClientOptions = ClientOptions>(\n override: Config<Omit<ClientOptions, keyof T> & T> = {},\n): Config<Omit<ClientOptions, keyof T> & T> => ({\n ...jsonBodySerializer,\n headers: defaultHeaders,\n parseAs: 'auto',\n querySerializer: defaultQuerySerializer,\n ...override,\n});\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { createSseClient } from '../core/serverSentEvents.gen.js';\nimport type { HttpMethod } from '../core/types.gen.js';\nimport { getValidRequestBody } from '../core/utils.gen.js';\nimport type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen.js';\nimport {\n buildUrl,\n createConfig,\n createInterceptors,\n getParseAs,\n mergeConfigs,\n mergeHeaders,\n setAuthParams,\n} from './utils.gen.js';\n\ntype ReqInit = Omit<RequestInit, 'body' | 'headers'> & {\n body?: any;\n headers: ReturnType<typeof mergeHeaders>;\n};\n\nexport const createClient = (config: Config = {}): Client => {\n let _config = mergeConfigs(createConfig(), config);\n\n const getConfig = (): Config => ({ ..._config });\n\n const setConfig = (config: Config): Config => {\n _config = mergeConfigs(_config, config);\n return getConfig();\n };\n\n const interceptors = createInterceptors<Request, Response, unknown, ResolvedRequestOptions>();\n\n const beforeRequest = async <\n TData = unknown,\n TResponseStyle extends 'data' | 'fields' = 'fields',\n ThrowOnError extends boolean = boolean,\n Url extends string = string,\n >(\n options: RequestOptions<TData, TResponseStyle, ThrowOnError, Url>,\n ) => {\n const opts = {\n ..._config,\n ...options,\n fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,\n headers: mergeHeaders(_config.headers, options.headers),\n serializedBody: undefined as string | undefined,\n };\n\n if (opts.security) {\n await setAuthParams(opts);\n }\n\n if (opts.requestValidator) {\n await opts.requestValidator(opts);\n }\n\n if (opts.body !== undefined && opts.bodySerializer) {\n opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined;\n }\n\n // remove Content-Type header if body is empty to avoid sending invalid requests\n if (opts.body === undefined || opts.serializedBody === '') {\n opts.headers.delete('Content-Type');\n }\n\n const resolvedOpts = opts as typeof opts &\n ResolvedRequestOptions<TResponseStyle, ThrowOnError, Url>;\n const url = buildUrl(resolvedOpts);\n\n return { opts: resolvedOpts, url };\n };\n\n const request: Client['request'] = async (options) => {\n const throwOnError = options.throwOnError ?? _config.throwOnError;\n const responseStyle = options.responseStyle ?? _config.responseStyle;\n\n let request: Request | undefined;\n let response: Response | undefined;\n\n try {\n const { opts, url } = await beforeRequest(options);\n const requestInit: ReqInit = {\n redirect: 'follow',\n ...opts,\n body: getValidRequestBody(opts),\n };\n\n request = new Request(url, requestInit);\n\n for (const fn of interceptors.request.fns) {\n if (fn) {\n request = await fn(request, opts);\n }\n }\n\n // fetch must be assigned here, otherwise it would throw the error:\n // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation\n const _fetch = opts.fetch!;\n\n response = await _fetch(request);\n\n for (const fn of interceptors.response.fns) {\n if (fn) {\n response = await fn(response, request, opts);\n }\n }\n\n const result = {\n request,\n response,\n };\n\n if (response.ok) {\n const parseAs =\n (opts.parseAs === 'auto'\n ? getParseAs(response.headers.get('Content-Type'))\n : opts.parseAs) ?? 'json';\n\n if (response.status === 204 || response.headers.get('Content-Length') === '0') {\n let emptyData: any;\n switch (parseAs) {\n case 'arrayBuffer':\n case 'blob':\n case 'text':\n emptyData = await response[parseAs]();\n break;\n case 'formData':\n emptyData = new FormData();\n break;\n case 'stream':\n emptyData = response.body;\n break;\n case 'json':\n default:\n emptyData = {};\n break;\n }\n return opts.responseStyle === 'data'\n ? emptyData\n : {\n data: emptyData,\n ...result,\n };\n }\n\n let data: any;\n switch (parseAs) {\n case 'arrayBuffer':\n case 'blob':\n case 'formData':\n case 'text':\n data = await response[parseAs]();\n break;\n case 'json': {\n // Some servers return 200 with no Content-Length and empty body.\n // response.json() would throw; read as text and parse if non-empty.\n const text = await response.text();\n data = text ? JSON.parse(text) : {};\n break;\n }\n case 'stream':\n return opts.responseStyle === 'data'\n ? response.body\n : {\n data: response.body,\n ...result,\n };\n }\n\n if (parseAs === 'json') {\n if (opts.responseValidator) {\n await opts.responseValidator(data);\n }\n\n if (opts.responseTransformer) {\n data = await opts.responseTransformer(data);\n }\n }\n\n return opts.responseStyle === 'data'\n ? data\n : {\n data,\n ...result,\n };\n }\n\n const textError = await response.text();\n let jsonError: unknown;\n\n try {\n jsonError = JSON.parse(textError);\n } catch {\n // noop\n }\n\n throw jsonError ?? textError;\n } catch (error) {\n let finalError = error;\n\n for (const fn of interceptors.error.fns) {\n if (fn) {\n finalError = await fn(finalError, response, request, options as ResolvedRequestOptions);\n }\n }\n\n finalError = finalError || {};\n\n if (throwOnError) {\n throw finalError;\n }\n\n // TODO: we probably want to return error and improve types\n return responseStyle === 'data'\n ? undefined\n : {\n error: finalError,\n request,\n response,\n };\n }\n };\n\n const makeMethodFn = (method: Uppercase<HttpMethod>) => (options: RequestOptions) =>\n request({ ...options, method });\n\n const makeSseFn = (method: Uppercase<HttpMethod>) => async (options: RequestOptions) => {\n const { opts, url } = await beforeRequest(options);\n return createSseClient({\n ...opts,\n body: opts.body as BodyInit | null | undefined,\n method,\n onRequest: async (url, init) => {\n let request = new Request(url, init);\n for (const fn of interceptors.request.fns) {\n if (fn) {\n request = await fn(request, opts);\n }\n }\n return request;\n },\n serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined,\n url,\n });\n };\n\n const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options });\n\n return {\n buildUrl: _buildUrl,\n connect: makeMethodFn('CONNECT'),\n delete: makeMethodFn('DELETE'),\n get: makeMethodFn('GET'),\n getConfig,\n head: makeMethodFn('HEAD'),\n interceptors,\n options: makeMethodFn('OPTIONS'),\n patch: makeMethodFn('PATCH'),\n post: makeMethodFn('POST'),\n put: makeMethodFn('PUT'),\n request,\n setConfig,\n sse: {\n connect: makeSseFn('CONNECT'),\n delete: makeSseFn('DELETE'),\n get: makeSseFn('GET'),\n head: makeSseFn('HEAD'),\n options: makeSseFn('OPTIONS'),\n patch: makeSseFn('PATCH'),\n post: makeSseFn('POST'),\n put: makeSseFn('PUT'),\n trace: makeSseFn('TRACE'),\n },\n trace: makeMethodFn('TRACE'),\n } as Client;\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { type Client, type ClientOptions, type Config, createClient, createConfig } from './client/index.js';\nimport type { ClientOptions as ClientOptions2 } from './types.gen.js';\n\n/**\n * The `createClientConfig()` function will be called on client initialization\n * and the returned object will become the client's initial configuration.\n *\n * You may want to initialize your client this way instead of calling\n * `setConfig()`. This is useful for example if you're using Next.js\n * to ensure your client always has the correct values.\n */\nexport type CreateClientConfig<T extends ClientOptions = ClientOptions2> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;\n\nexport const client: Client = createClient(createConfig<ClientOptions2>({ baseUrl: 'https://api.fuser.studio' }));\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { client } from './client.gen.js';\nimport type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client/index.js';\nimport type { AccountGetData, AccountGetErrors, AccountGetResponses, CanvasArrangeData, CanvasArrangeErrors, CanvasArrangeResponses, CanvasEditData, CanvasEditErrors, CanvasEditResponses, CanvasGetData, CanvasGetErrors, CanvasGetResponses, CanvasListData, CanvasListErrors, CanvasListResponses, CatalogSearchData, CatalogSearchErrors, CatalogSearchResponses, MediaExportData, MediaExportErrors, MediaExportResponses, MediaImportData, MediaImportErrors, MediaImportResponses, MediaSearchData, MediaSearchErrors, MediaSearchResponses, MediaViewData, MediaViewErrors, MediaViewResponses, RunCancelData, RunCancelErrors, RunCancelResponses, RunGetData, RunGetErrors, RunGetResponses, RunStartData, RunStartErrors, RunStartResponses, ToolBuildData, ToolBuildErrors, ToolBuildResponses, ToolSearchData, ToolSearchErrors, ToolSearchResponses, UploadFinishData, UploadFinishErrors, UploadFinishResponses, UploadStartData, UploadStartErrors, UploadStartResponses } from './types.gen.js';\n\nexport type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {\n /**\n * You can provide a client instance returned by `createClient()` instead of\n * individual options. This might be also useful if you want to implement a\n * custom client.\n */\n client?: Client;\n /**\n * You can pass arbitrary values through the `meta` object. This can be\n * used to access values that aren't defined as part of the SDK function.\n */\n meta?: keyof ClientMeta extends never ? Record<string, unknown> : ClientMeta;\n};\n\n/**\n * List canvases\n *\n * Canvases you can open, most recently edited first, with a link to each. Reuse one only when the user points to it; put new work on a new canvas, and never present results that were already there as new.\n */\nexport const canvasList = <ThrowOnError extends boolean = false>(options?: Options<CanvasListData, ThrowOnError>): RequestResult<CanvasListResponses, CanvasListErrors, ThrowOnError> => (options?.client ?? client).get<CanvasListResponses, CanvasListErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/canvas_list',\n ...options\n});\n\n/**\n * Read a canvas\n *\n * A compact view of a canvas: a summary, then pages of nodes (id, type, label, socket keys, literal values, result links) and their edges. On a big canvas, find nodes with search or read specific ones with nodeIds instead of paging through everything.\n */\nexport const canvasGet = <ThrowOnError extends boolean = false>(options: Options<CanvasGetData, ThrowOnError>): RequestResult<CanvasGetResponses, CanvasGetErrors, ThrowOnError> => (options.client ?? client).get<CanvasGetResponses, CanvasGetErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/canvas_get',\n ...options\n});\n\n/**\n * Edit a canvas\n *\n * Apply a graph diff to a canvas all at once: add nodes and edges, change inputs, disconnect edges, delete nodes. Every change lands or none does. Keep each edit to about 30 new nodes; build a bigger canvas one section per edit, so a mistake costs one small resend.\n */\nexport const canvasEdit = <ThrowOnError extends boolean = false>(options: Options<CanvasEditData, ThrowOnError>): RequestResult<CanvasEditResponses, CanvasEditErrors, ThrowOnError> => (options.client ?? client).post<CanvasEditResponses, CanvasEditErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/canvas_edit',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Arrange nodes on a canvas\n *\n * Lay out existing nodes with Fuser's layout instead of working out positions. Without layout it tidies them along their wiring, inputs to the left of what they feed; with layout it puts them in a row, column or grid in nodeIds order. Without an origin the block stays where the nodes are and slides clear of the nodes around it. Use it when the user asks to rearrange, line up or tidy nodes, or after resizing nodes that now overlap. It changes positions only.\n */\nexport const canvasArrange = <ThrowOnError extends boolean = false>(options: Options<CanvasArrangeData, ThrowOnError>): RequestResult<CanvasArrangeResponses, CanvasArrangeErrors, ThrowOnError> => (options.client ?? client).post<CanvasArrangeResponses, CanvasArrangeErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/canvas_arrange',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Find node types\n *\n * Node types a canvas_edit diff may use, with what each is good at, its input ids and its output socket. Call it with no query first: it returns the recommended node for each common job. Search only when none of them fits.\n */\nexport const catalogSearch = <ThrowOnError extends boolean = false>(options?: Options<CatalogSearchData, ThrowOnError>): RequestResult<CatalogSearchResponses, CatalogSearchErrors, ThrowOnError> => (options?.client ?? client).get<CatalogSearchResponses, CatalogSearchErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/catalog_search',\n ...options\n});\n\n/**\n * Run a canvas\n *\n * Run the whole canvas or named nodes. Prices the run first and refuses it when it costs more than maxCredits; dryRun returns only the price. Starts a run once per idempotencyKey; check on it with run_get, not by calling run_start again.\n */\nexport const runStart = <ThrowOnError extends boolean = false>(options: Options<RunStartData, ThrowOnError>): RequestResult<RunStartResponses, RunStartErrors, ThrowOnError> => (options.client ?? client).post<RunStartResponses, RunStartErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/run_start',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Check a run\n *\n * Status of a run you started, per node, with links to each node's results.\n */\nexport const runGet = <ThrowOnError extends boolean = false>(options: Options<RunGetData, ThrowOnError>): RequestResult<RunGetResponses, RunGetErrors, ThrowOnError> => (options.client ?? client).get<RunGetResponses, RunGetErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/run_get',\n ...options\n});\n\n/**\n * Cancel a run\n *\n * Stop a run you started. Nodes already finished keep their results.\n */\nexport const runCancel = <ThrowOnError extends boolean = false>(options: Options<RunCancelData, ThrowOnError>): RequestResult<RunCancelResponses, RunCancelErrors, ThrowOnError> => (options.client ?? client).post<RunCancelResponses, RunCancelErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/run_cancel',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Import an image or video\n *\n * Copy an image or video from a public URL into the canvas's assets and get a Fuser link for it. Use it before putting a web link on the canvas: it says straight away when the link can't be fetched, and the copy won't expire. For a file on the user's machine use upload_start.\n */\nexport const mediaImport = <ThrowOnError extends boolean = false>(options: Options<MediaImportData, ThrowOnError>): RequestResult<MediaImportResponses, MediaImportErrors, ThrowOnError> => (options.client ?? client).post<MediaImportResponses, MediaImportErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/media_import',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Upload files\n *\n * Step 1 of putting files from the user's machine on a canvas, for agents that run commands on that machine (Claude Code, Codex, an IDE). List the files (up to 50): each comes back with a link to PUT it to, or done if Fuser already has it. Then call upload_finish with uploadId. In a chat app use upload_box instead; a cloud code sandbox can't reach these links.\n */\nexport const uploadStart = <ThrowOnError extends boolean = false>(options: Options<UploadStartData, ThrowOnError>): RequestResult<UploadStartResponses, UploadStartErrors, ThrowOnError> => (options.client ?? client).post<UploadStartResponses, UploadStartErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/upload_start',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Finish uploading files\n *\n * Step 2: returns a link for every file that arrived, to use as an ImageNode or VideoNode input, and says why for any that did not. For files the user is adding on the upload page, call it after they say they are done.\n */\nexport const uploadFinish = <ThrowOnError extends boolean = false>(options: Options<UploadFinishData, ThrowOnError>): RequestResult<UploadFinishResponses, UploadFinishErrors, ThrowOnError> => (options.client ?? client).post<UploadFinishResponses, UploadFinishErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/upload_finish',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Look at media\n *\n * See Fuser images and 3D models as small previews, and the first frame of a video, with facts such as size, length and transparency. Look at results before describing or judging them.\n */\nexport const mediaView = <ThrowOnError extends boolean = false>(options: Options<MediaViewData, ThrowOnError>): RequestResult<MediaViewResponses, MediaViewErrors, ThrowOnError> => (options.client ?? client).post<MediaViewResponses, MediaViewErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/media_view',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Find your media\n *\n * Search the images, videos, audio and 3D files you made or uploaded, by meaning (\"the coral reef image\", \"a dog running on a beach\") or by similarity to one you have. Without query or similarTo it lists the newest first. Look at matches with media_view.\n */\nexport const mediaSearch = <ThrowOnError extends boolean = false>(options: Options<MediaSearchData, ThrowOnError>): RequestResult<MediaSearchResponses, MediaSearchErrors, ThrowOnError> => (options.client ?? client).post<MediaSearchResponses, MediaSearchErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/media_search',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Download media as a zip\n *\n * A link that downloads a canvas's results as one zip file, for when the user wants their files ('download everything', 'send me the images as a zip'). Give the user the link; it works for an hour. It changes nothing on the canvas.\n */\nexport const mediaExport = <ThrowOnError extends boolean = false>(options: Options<MediaExportData, ThrowOnError>): RequestResult<MediaExportResponses, MediaExportErrors, ThrowOnError> => (options.client ?? client).post<MediaExportResponses, MediaExportErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/media_export',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Read your account\n *\n * Who you are, your personal credits and plan, and each workspace you belong to with your role, its plan, the team's credits and your monthly spend limit there. Runs on a workspace canvas spend that workspace's credits if you belong to it; runs on a personal canvas, or a workspace canvas shared with you from outside, spend yours.\n */\nexport const accountGet = <ThrowOnError extends boolean = false>(options?: Options<AccountGetData, ThrowOnError>): RequestResult<AccountGetResponses, AccountGetErrors, ThrowOnError> => (options?.client ?? client).get<AccountGetResponses, AccountGetErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/account_get',\n ...options\n});\n\n/**\n * Find a saved tool\n *\n * Search the canvas's tool library (tools you or your workspace built) and Fuser's featured tools by title and description. Place a match with tool_build toolId. Only worth it when a tool for the job likely exists; building a new one with tool_build prompt is fine too.\n */\nexport const toolSearch = <ThrowOnError extends boolean = false>(options: Options<ToolSearchData, ThrowOnError>): RequestResult<ToolSearchResponses, ToolSearchErrors, ThrowOnError> => (options.client ?? client).get<ToolSearchResponses, ToolSearchErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/tool_search',\n ...options\n});\n\n/**\n * Build a tool\n *\n * Turn a Tool node (type UtilityNode, added with canvas_edit) into a working tool: describe it in prompt and Fuser writes its code, or place a saved one with toolId. Tools do what generators can't: join, cut, trim or speed up videos, mix audio, crop, grid, filter, measure and convert between images, video, audio, 3D models, text and JSON (not PDF, ZIP or other files). Call it again with a prompt to change a built tool, or with neither to check on a build. Once built, wire its input sockets and set its controls with canvas_edit, then run it like any node. Writing or changing a tool with a prompt spends credits (often 60 to 350 per build, more for a hard one) and no quote covers it; placing a saved tool with toolId is free, and a free tool costs nothing to run.\n */\nexport const toolBuild = <ThrowOnError extends boolean = false>(options: Options<ToolBuildData, ThrowOnError>): RequestResult<ToolBuildResponses, ToolBuildErrors, ThrowOnError> => (options.client ?? client).post<ToolBuildResponses, ToolBuildErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/tool_build',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n","interface Page {\n nextCursor: string | null;\n}\n\n/**\n * A paged list: await it for the first page, or `for await` it for every\n * item on every page.\n */\nexport class PagePromise<P extends Page, I>\n implements PromiseLike<P>, AsyncIterable<I>\n{\n #first: Promise<P> | undefined;\n readonly #load: (cursor?: string) => Promise<P>;\n readonly #items: (page: P) => readonly I[];\n\n constructor(\n load: (cursor?: string) => Promise<P>,\n items: (page: P) => readonly I[],\n ) {\n this.#load = load;\n this.#items = items;\n }\n\n #firstPage(): Promise<P> {\n this.#first ??= this.#load();\n\n return this.#first;\n }\n\n then<A = P, B = never>(\n onfulfilled?: ((value: P) => A | PromiseLike<A>) | null,\n onrejected?: ((reason: unknown) => B | PromiseLike<B>) | null,\n ): Promise<A | B> {\n return this.#firstPage().then(onfulfilled, onrejected);\n }\n\n async *pages(): AsyncGenerator<P> {\n let page = await this.#firstPage();\n\n yield page;\n\n while (page.nextCursor) {\n page = await this.#load(page.nextCursor);\n\n yield page;\n }\n }\n\n async *[Symbol.asyncIterator](): AsyncGenerator<I> {\n for await (const page of this.pages()) {\n yield* this.#items(page);\n }\n }\n\n /** Every item on every page. */\n async all(): Promise<I[]> {\n const items: I[] = [];\n\n for await (const item of this) {\n items.push(item);\n }\n\n return items;\n }\n}\n","import {\n ConnectionError,\n errorFromResponse,\n FuserError,\n RunRefusedError,\n TimeoutError,\n} from './errors.js';\nimport { createClient } from './generated/client/index.js';\nimport * as sdk from './generated/sdk.gen.js';\nimport { PagePromise } from './pages.js';\n\nimport type { Client } from './generated/client/index.js';\n\ntype Sdk = typeof sdk;\n\n/** A generated operation, e.g. `canvasEdit`. */\ntype OperationKey = keyof Sdk;\n\ntype Snake<S extends string> = S extends `${infer Head}${infer Rest}`\n ? `${Head extends Lowercase<Head> ? Head : `_${Lowercase<Head>}`}${Snake<Rest>}`\n : S;\n\n/** An MCP tool and REST path name, e.g. `canvas_edit`. */\nexport type ToolName = Snake<OperationKey>;\n\ntype KeyOf<N extends ToolName> = {\n [K in OperationKey]: Snake<K> extends N ? K : never;\n}[OperationKey];\n\ntype OptionsOf<K extends OperationKey> = NonNullable<Parameters<Sdk[K]>[0]>;\n\ntype Field<K extends OperationKey, F extends 'body' | 'query'> =\n OptionsOf<K> extends { [P in F]?: infer V } ? NonNullable<V> : never;\n\ntype InOf<K extends OperationKey> = [Field<K, 'body'>] extends [never]\n ? 'query'\n : 'body';\n\ntype ArgsOf<K extends OperationKey> = [Field<K, InOf<K>>] extends [never]\n ? void\n : Field<K, InOf<K>>;\n\ntype ResultOf<K extends OperationKey> = Extract<\n Awaited<ReturnType<Sdk[K]>>,\n { error: undefined }\n>['data'];\n\n/** Exactly the arguments an agent passes to the MCP tool. */\nexport type ToolArgs<N extends ToolName> = ArgsOf<KeyOf<N>>;\n\n/** Exactly the JSON the MCP tool returns. */\nexport type ToolResult<N extends ToolName> = ResultOf<KeyOf<N>>;\n\ntype Resource = ToolName extends infer N\n ? N extends `${infer R}_${string}`\n ? R\n : never\n : never;\n\n/**\n * One namespace per resource and one method per tool: `canvas_list` is\n * `fuser.canvas.list()`. A new or renamed tool fails the build until the\n * class covers it.\n */\ntype Surface = {\n [R in Resource]: {\n [N in ToolName as N extends `${R}_${infer M}` ? M : never]: (\n args: ToolArgs<N>,\n options?: RequestOptions,\n ) => PromiseLike<ToolResult<N>>;\n };\n};\n\ntype Retry = 'transient' | 'rate-limit';\n\n// How each tool retries. Typed over every generated operation, so a new tool\n// needs a deliberate choice: `transient` retries 408, 429, 5xx and network\n// errors; `rate-limit` only 429, for calls that could do the work twice.\nconst OPERATIONS: {\n [K in OperationKey]: {\n in: InOf<K>;\n retry: Retry | ((args: ArgsOf<K>) => Retry);\n };\n} = {\n accountGet: { in: 'query', retry: 'transient' },\n canvasArrange: {\n in: 'body',\n retry: args =>\n args.expectedRevision === undefined ? 'transient' : 'rate-limit',\n },\n canvasEdit: { in: 'body', retry: 'transient' },\n canvasGet: { in: 'query', retry: 'transient' },\n canvasList: { in: 'query', retry: 'transient' },\n catalogSearch: { in: 'query', retry: 'transient' },\n mediaExport: { in: 'body', retry: 'transient' },\n mediaImport: { in: 'body', retry: 'rate-limit' },\n mediaSearch: { in: 'body', retry: 'transient' },\n mediaView: { in: 'body', retry: 'transient' },\n runCancel: { in: 'body', retry: 'transient' },\n runGet: { in: 'query', retry: 'transient' },\n runStart: { in: 'body', retry: 'transient' },\n toolBuild: {\n in: 'body',\n retry: args => (args.prompt || args.toolId ? 'rate-limit' : 'transient'),\n },\n toolSearch: { in: 'query', retry: 'transient' },\n uploadFinish: { in: 'body', retry: 'transient' },\n uploadStart: { in: 'body', retry: 'transient' },\n};\n\nconst RETRYABLE_STATUSES = new Set([408, 429, 500, 502, 503, 504]);\n\n/** upload_start takes at most this many files. */\nconst MAX_UPLOAD_FILES = 50;\n\n/** The server holds a waiting call open at most this long. */\nconst MAX_WAIT_SECONDS = 45;\n\n/** Runs answer sooner: the server waits at most this long on a run. */\nconst RUN_WAIT_SECONDS = 10;\n\n/** A longer Retry-After is the caller's call, not ours to sleep through. */\nconst MAX_RETRY_DELAY_MS = 60_000;\n\nexport interface RequestOptions {\n signal?: AbortSignal;\n /** Per attempt, on top of any `waitSeconds`. */\n timeoutMs?: number;\n maxRetries?: number;\n headers?: Record<string, string>;\n}\n\nexport interface WaitOptions {\n /** Give up after this long. Defaults to 30 minutes for runs, 10 for builds. */\n timeoutMs?: number;\n signal?: AbortSignal;\n}\n\nexport interface FuserOptions {\n /** Defaults to the `FUSER_API_KEY` environment variable. */\n apiKey?: string;\n /** Defaults to `https://api.fuser.studio`. */\n baseUrl?: string;\n fetch?: typeof fetch;\n /** Per attempt. Defaults to 60 seconds. */\n timeoutMs?: number;\n /** Defaults to 2. */\n maxRetries?: number;\n beforeSend?: (request: Request) => Request | void | Promise<Request | void>;\n afterSend?: (response: Response, request: Request) => void | Promise<void>;\n /** An API key acts as you; only set this if the page is yours alone. */\n dangerouslyAllowBrowser?: boolean;\n}\n\ntype RunStartResult = ToolResult<'run_start'>;\ntype RunSummary = ToolResult<'run_get'>;\ntype ToolBuildResult = ToolResult<'tool_build'>;\ntype UploadedFile = ToolResult<'upload_finish'>['files'][number];\n\nabstract class StartedCall<T> implements PromiseLike<T> {\n protected readonly started: Promise<T>;\n\n constructor(started: Promise<T>) {\n this.started = started;\n }\n\n then<A = T, B = never>(\n onfulfilled?: ((value: T) => A | PromiseLike<A>) | null,\n onrejected?: ((reason: unknown) => B | PromiseLike<B>) | null,\n ): Promise<A | B> {\n return this.started.then(onfulfilled, onrejected);\n }\n}\n\n/** `run.start()`: await for the start result, or `.wait()` for the finished run. */\nexport class RunCall extends StartedCall<RunStartResult> {\n readonly #wait: (runId: string, options?: WaitOptions) => Promise<RunSummary>;\n\n constructor(\n started: Promise<RunStartResult>,\n wait: (runId: string, options?: WaitOptions) => Promise<RunSummary>,\n ) {\n super(started);\n this.#wait = wait;\n }\n\n /** The run once it stops running. Throws if it was refused or only priced. */\n async wait(options?: WaitOptions): Promise<RunSummary> {\n const timeoutMs = options?.timeoutMs ?? 30 * 60_000;\n const startedAt = Date.now();\n\n const scope = deadline(\n timeoutMs,\n options?.signal,\n 'The run is still starting.',\n 'run_start',\n );\n\n const result = await scope.guard(this.started);\n\n if (result.status === 'refused') {\n throw new RunRefusedError(result.error, {\n tool: 'run_start',\n reason: result.reason,\n body: result,\n });\n }\n\n if (result.status === 'quoted') {\n throw new FuserError(\n 'A dry run only prices the run; nothing to wait for.',\n {\n tool: 'run_start',\n body: result,\n },\n );\n }\n\n if (result.run && result.run.status !== 'running') {\n return result.run;\n }\n\n return this.#wait(result.runId, {\n signal: options?.signal,\n timeoutMs: Math.max(timeoutMs - (Date.now() - startedAt), 1),\n });\n }\n}\n\n/** `tool.build()`: await for its state now, or `.wait()` until it's built. */\nexport class ToolBuildCall extends StartedCall<ToolBuildResult> {\n readonly #check: (signal?: AbortSignal) => Promise<ToolBuildResult>;\n\n constructor(\n started: Promise<ToolBuildResult>,\n check: (signal?: AbortSignal) => Promise<ToolBuildResult>,\n ) {\n super(started);\n this.#check = check;\n }\n\n /** The tool once its build stops; check `status` for built or failed. */\n async wait(options?: WaitOptions): Promise<ToolBuildResult> {\n const scope = deadline(\n options?.timeoutMs ?? 10 * 60_000,\n options?.signal,\n 'The tool is still building.',\n 'tool_build',\n );\n\n let state = await scope.guard(this.started);\n\n while (state.status === 'building') {\n options?.signal?.throwIfAborted();\n\n if (scope.expired()) {\n throw scope.timeout();\n }\n\n state = await scope.guard(this.#check(scope.signal));\n }\n\n return state;\n }\n}\n\nexport interface UploadInput {\n fileName: string;\n data: Blob | ArrayBuffer | Uint8Array;\n /** Required unless `data` is a Blob with a type. */\n contentType?: string;\n}\n\nconst toCamel = (name: string) =>\n name.replace(/_([a-z])/g, (_, letter: string) => letter.toUpperCase());\n\nconst toSnake = (key: string) =>\n key.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);\n\nconst sleep = (ms: number, signal?: AbortSignal) =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason);\n\n return;\n }\n\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n\nfunction base64(bytes: Uint8Array): string {\n let binary = '';\n\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n\n return btoa(binary);\n}\n\nconst withSignal = (signal: AbortSignal | undefined, other: AbortSignal) =>\n signal ? AbortSignal.any([signal, other]) : other;\n\nconst mergeSignals = (\n first: AbortSignal | undefined,\n second: AbortSignal | undefined,\n) => (first && second ? AbortSignal.any([first, second]) : (first ?? second));\n\n/** One deadline for a whole wait: every poll and retry shares its signal. */\nfunction deadline(\n timeoutMs: number,\n signal: AbortSignal | undefined,\n message: string,\n tool: string,\n) {\n const timer = AbortSignal.timeout(timeoutMs);\n\n const expired = () => timer.aborted && !signal?.aborted;\n\n const timeout = (cause?: unknown) =>\n new TimeoutError(message, { tool, cause });\n\n return {\n signal: withSignal(signal, timer),\n expired,\n timeout,\n /** `work`, or a timeout or abort as soon as either fires, whichever is first. */\n async guard<T>(work: Promise<T>): Promise<T> {\n const combined = withSignal(signal, timer);\n\n let stop = () => {};\n\n const stopped = new Promise<never>((_, reject) => {\n stop = () =>\n reject(expired() ? timeout() : (signal?.reason ?? timeout()));\n\n if (combined.aborted) {\n stop();\n } else {\n combined.addEventListener('abort', stop, { once: true });\n }\n });\n\n // Settles after `work` wins too; nothing is waiting on it then.\n stopped.catch(() => undefined);\n\n try {\n return await Promise.race([work, stopped]);\n } catch (error) {\n throw expired() && !(error instanceof TimeoutError)\n ? timeout(error)\n : error;\n } finally {\n combined.removeEventListener('abort', stop);\n }\n },\n };\n}\n\n/**\n * The Fuser API. Each tool is a method named after it: `canvas_edit` is\n * `fuser.canvas.edit()`, with the same arguments and result as the MCP tool.\n */\nexport class Fuser implements Surface {\n readonly client: Client;\n readonly #fetch: typeof fetch;\n readonly #timeoutMs: number;\n readonly #maxRetries: number;\n\n readonly account = {\n get: (_args?: void, options?: RequestOptions) =>\n this.#request('accountGet', undefined, options),\n };\n\n readonly canvas = {\n /** Await for a page, or `for await` for every canvas. */\n list: (args?: ToolArgs<'canvas_list'>, options?: RequestOptions) =>\n this.#pages('canvasList', args ?? {}, page => page.canvases, options),\n /** Await for a page, or `for await` for every node. */\n get: (args: ToolArgs<'canvas_get'>, options?: RequestOptions) =>\n this.#pages('canvasGet', args, page => page.nodes, options),\n /** `idempotencyKey` defaults to a new one per call. */\n edit: (\n args: Omit<ToolArgs<'canvas_edit'>, 'idempotencyKey'> & {\n idempotencyKey?: string;\n },\n options?: RequestOptions,\n ) => this.#request('canvasEdit', args as ToolArgs<'canvas_edit'>, options),\n arrange: (args: ToolArgs<'canvas_arrange'>, options?: RequestOptions) =>\n this.#request('canvasArrange', args, options),\n };\n\n readonly catalog = {\n search: (args?: ToolArgs<'catalog_search'>, options?: RequestOptions) =>\n this.#request('catalogSearch', args ?? {}, options),\n };\n\n readonly run = {\n /** `idempotencyKey` defaults to a new one per call. Add `.wait()` to wait. */\n start: (args: ToolArgs<'run_start'>, options?: RequestOptions) =>\n new RunCall(\n this.#request('runStart', args, options),\n (runId, waitOptions) =>\n this.#waitForRun(\n { canvasId: args.canvasId, runId },\n {\n ...waitOptions,\n signal: mergeSignals(options?.signal, waitOptions?.signal),\n },\n ),\n ),\n get: (args: ToolArgs<'run_get'>, options?: RequestOptions) =>\n this.#request('runGet', args, options),\n cancel: (args: ToolArgs<'run_cancel'>, options?: RequestOptions) =>\n this.#request('runCancel', args, options),\n /** Checks a run until it stops running. */\n wait: (args: { canvasId: string; runId: string }, options?: WaitOptions) =>\n this.#waitForRun(args, options),\n };\n\n readonly media = {\n export: (args: ToolArgs<'media_export'>, options?: RequestOptions) =>\n this.#request('mediaExport', args, options),\n import: (args: ToolArgs<'media_import'>, options?: RequestOptions) =>\n this.#request('mediaImport', args, options),\n /** Await for a page, or `for await` for every match. */\n search: (args: ToolArgs<'media_search'>, options?: RequestOptions) =>\n this.#pages('mediaSearch', args, page => page.assets, options),\n view: (args: ToolArgs<'media_view'>, options?: RequestOptions) =>\n this.#request('mediaView', args, options),\n };\n\n readonly upload = {\n start: (args: ToolArgs<'upload_start'>, options?: RequestOptions) =>\n this.#request('uploadStart', args, options),\n finish: (args: ToolArgs<'upload_finish'>, options?: RequestOptions) =>\n this.#request('uploadFinish', args, options),\n /** Hashes, starts, sends and finishes in one call. */\n files: (canvasId: string, files: UploadInput[], options?: RequestOptions) =>\n this.#uploadFiles(canvasId, files, options),\n };\n\n readonly tool = {\n search: (args: ToolArgs<'tool_search'>, options?: RequestOptions) =>\n this.#request('toolSearch', args, options),\n /** Add `.wait()` to wait until it's built. */\n build: (args: ToolArgs<'tool_build'>, options?: RequestOptions) => {\n const { canvasId, nodeId } = args;\n\n return new ToolBuildCall(\n this.#request('toolBuild', args, options),\n signal =>\n this.#request(\n 'toolBuild',\n { canvasId, nodeId, waitSeconds: MAX_WAIT_SECONDS },\n {\n ...options,\n ...(signal\n ? { signal: withSignal(options?.signal, signal) }\n : {}),\n },\n ),\n );\n },\n };\n\n constructor(options: FuserOptions = {}) {\n const apiKey =\n options.apiKey ??\n (globalThis as { process?: { env?: Record<string, string | undefined> } })\n .process?.env?.FUSER_API_KEY;\n\n if (\n 'document' in globalThis &&\n 'window' in globalThis &&\n !options.dangerouslyAllowBrowser\n ) {\n throw new FuserError(\n 'A Fuser API key acts as you, so keep it on a server. Pass dangerouslyAllowBrowser to use it in a browser anyway.',\n { tool: 'client' },\n );\n }\n\n this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.#timeoutMs = options.timeoutMs ?? 60_000;\n this.#maxRetries = options.maxRetries ?? 2;\n\n this.client = createClient({\n baseUrl: options.baseUrl ?? 'https://api.fuser.studio',\n fetch: this.#fetch,\n auth: scheme => (scheme.scheme === 'bearer' ? apiKey : undefined),\n });\n\n const { beforeSend, afterSend } = options;\n\n if (beforeSend) {\n this.client.interceptors.request.use(\n async request => (await beforeSend(request)) ?? request,\n );\n }\n\n if (afterSend) {\n this.client.interceptors.response.use(async (response, request) => {\n await afterSend(response, request);\n\n return response;\n });\n }\n }\n\n /** Calls a tool by its MCP name, with the exact arguments an agent sent. */\n call<N extends ToolName>(\n name: N,\n args: ToolArgs<N>,\n options?: RequestOptions,\n ): Promise<ToolResult<N>> {\n return this.#request(toCamel(name) as KeyOf<N>, args, options);\n }\n\n #pages<K extends OperationKey, I>(\n key: K,\n args: ArgsOf<K> & { cursor?: string },\n items: (page: ResultOf<K> & { nextCursor: string | null }) => readonly I[],\n options?: RequestOptions,\n ) {\n return new PagePromise(\n async cursor =>\n (await this.#request(\n key,\n { ...args, cursor: cursor ?? args.cursor },\n options,\n )) as ResultOf<K> & { nextCursor: string | null },\n items,\n );\n }\n\n async #waitForRun(\n args: { canvasId: string; runId: string },\n options?: WaitOptions,\n ): Promise<RunSummary> {\n const scope = deadline(\n options?.timeoutMs ?? 30 * 60_000,\n options?.signal,\n `Run ${args.runId} is still running.`,\n 'run_get',\n );\n\n for (;;) {\n const summary = await scope.guard(\n this.run.get(\n { ...args, waitSeconds: RUN_WAIT_SECONDS },\n { signal: scope.signal },\n ),\n );\n\n if (summary.status !== 'running') {\n return summary;\n }\n\n options?.signal?.throwIfAborted();\n\n if (scope.expired()) {\n throw scope.timeout();\n }\n }\n }\n\n async #uploadFiles(\n canvasId: string,\n inputs: UploadInput[],\n options?: RequestOptions,\n ): Promise<UploadedFile[]> {\n const uploaded: UploadedFile[] = [];\n\n for (let start = 0; start < inputs.length; start += MAX_UPLOAD_FILES) {\n uploaded.push(\n ...(await this.#uploadBatch(\n canvasId,\n inputs.slice(start, start + MAX_UPLOAD_FILES),\n options,\n )),\n );\n }\n\n return uploaded;\n }\n\n async #uploadBatch(\n canvasId: string,\n inputs: UploadInput[],\n options?: RequestOptions,\n ): Promise<UploadedFile[]> {\n const prepared = await Promise.all(\n inputs.map(async input => {\n const bytes =\n input.data instanceof Blob\n ? new Uint8Array(await input.data.arrayBuffer())\n : new Uint8Array(input.data);\n\n const contentType =\n input.contentType ||\n (input.data instanceof Blob ? input.data.type : '');\n\n if (!contentType) {\n throw new FuserError(`${input.fileName} needs a contentType.`, {\n tool: 'upload_start',\n });\n }\n\n const digest = await crypto.subtle.digest('SHA-256', bytes);\n\n return {\n bytes,\n file: {\n fileName: input.fileName,\n contentType,\n size: bytes.byteLength,\n sha256: base64(new Uint8Array(digest)),\n },\n };\n }),\n );\n\n const started = await this.upload.start(\n { canvasId, files: prepared.map(item => item.file) },\n options,\n );\n\n const sent = new Set<string>();\n // A failed PUT is reported on its file, as the docs promise; only an\n // abort stops the batch.\n const putErrors: (string | undefined)[] = [];\n\n await Promise.all(\n started.files.map(async (file, index) => {\n if (file.status === 'done' || sent.has(file.url)) {\n return;\n }\n\n sent.add(file.url);\n\n const timeout = AbortSignal.timeout(\n options?.timeoutMs ?? this.#timeoutMs,\n );\n\n try {\n const response = await this.#fetch(file.url, {\n method: file.method,\n headers: file.headers,\n body: prepared[index]!.bytes,\n signal: withSignal(options?.signal, timeout),\n });\n\n if (!response.ok && response.status !== 412) {\n putErrors[index] =\n `Uploading ${file.fileName} failed (HTTP ${String(response.status)}).`;\n }\n } catch {\n options?.signal?.throwIfAborted();\n\n putErrors[index] = timeout.aborted\n ? `Uploading ${file.fileName} timed out.`\n : `Uploading ${file.fileName} failed: the connection dropped.`;\n }\n }),\n );\n\n const finished = await this.upload.finish(\n { uploadId: started.uploadId },\n options,\n );\n\n return finished.files.map((file, index) =>\n file.status === 'failed' && putErrors[index]\n ? { ...file, error: putErrors[index] }\n : file,\n );\n }\n\n async #request<K extends OperationKey>(\n key: K,\n args: ArgsOf<K>,\n options: RequestOptions = {},\n ): Promise<ResultOf<K>> {\n const tool = toSnake(key);\n\n const operation = OPERATIONS[key] as {\n in: 'body' | 'query';\n retry: Retry | ((args: unknown) => Retry);\n };\n\n const policy =\n typeof operation.retry === 'function'\n ? operation.retry(args)\n : operation.retry;\n\n const keyed =\n key === 'canvasEdit' ||\n (key === 'runStart' && !(args as { dryRun?: boolean }).dryRun);\n\n const body = keyed\n ? {\n ...args,\n idempotencyKey:\n (args as { idempotencyKey?: string }).idempotencyKey ??\n crypto.randomUUID(),\n }\n : args;\n\n const send = sdk[key] as unknown as (options: object) => Promise<{\n data?: unknown;\n error?: unknown;\n response?: Response;\n }>;\n\n const waitSeconds = Math.min(\n (args as { waitSeconds?: number } | undefined)?.waitSeconds ??\n (key === 'toolBuild' ? MAX_WAIT_SECONDS : 0),\n MAX_WAIT_SECONDS,\n );\n\n const timeoutMs =\n (options.timeoutMs ?? this.#timeoutMs) + waitSeconds * 1000;\n\n const maxRetries = options.maxRetries ?? this.#maxRetries;\n\n for (let attempt = 0; ; attempt++) {\n const timeout = AbortSignal.timeout(timeoutMs);\n\n const result = await send({\n client: this.client,\n ...(body === undefined ? {} : { [operation.in]: body }),\n ...(options.headers ? { headers: options.headers } : {}),\n signal: withSignal(options.signal, timeout),\n });\n\n if (result.error === undefined && result.response?.ok) {\n return result.data as ResultOf<K>;\n }\n\n options.signal?.throwIfAborted();\n\n const error =\n result.response && !result.response.ok\n ? errorFromResponse(tool, result.response, result.error)\n : timeout.aborted\n ? new TimeoutError(`${tool} timed out.`, {\n tool,\n cause: result.error,\n })\n : new ConnectionError(`${tool} could not reach Fuser.`, {\n tool,\n cause: result.error,\n });\n\n const retryable =\n error.status === undefined\n ? policy === 'transient'\n : policy === 'transient'\n ? RETRYABLE_STATUSES.has(error.status)\n : error.status === 429;\n\n const delay =\n error.retryAfterMs ??\n Math.min(8000, 500 * 2 ** attempt) * (0.75 + Math.random() / 2);\n\n if (!retryable || attempt >= maxRetries || delay > MAX_RETRY_DELAY_MS) {\n throw error;\n }\n\n await sleep(delay, options.signal);\n }\n }\n}\n"],"mappings":";;;AAkBA,IAAa,aAAb,cAAgC,MAAM;CACpC,OAAgB;CAChB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,SAAiB,SAA4B;EACvD,MAAM,SAAS,EAAE,OAAO,QAAQ,MAAM,CAAC;EACvC,KAAK,OAAO,QAAQ;EACpB,KAAK,SAAS,QAAQ;EACtB,KAAK,OAAO,QAAQ;EACpB,KAAK,SAAS,QAAQ;EACtB,KAAK,SAAS,QAAQ;EACtB,KAAK,YAAY,QAAQ;EACzB,KAAK,eAAe,QAAQ;EAC5B,KAAK,OAAO,QAAQ;CACtB;AACF;AAEA,IAAa,kBAAb,cAAqC,WAAW;CAC9C,OAAgB;AAClB;AAEA,IAAa,sBAAb,cAAyC,WAAW;CAClD,OAAgB;AAClB;AAEA,IAAa,wBAA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AK;IACb,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,GAAG,UAAU,KAAK,KAAK;IACrD,GAAI,QAAQ,UAAU,EAAE,SAAS,QAAQ,QAAQ,IAAI,CAAC;IACtD,QAAQ,WAAW,QAAQ,QAAQ,OAAO;GAC5C,CAAC;GAED,IAAI,OAAO,UAAU,KAAA,KAAa,OAAO,UAAU,IACjD,OAAO,OAAO;GAGhB,QAAQ,QAAQ,eAAe;GAE/B,MAAM,QACJ,OAAO,YAAY,CAAC,OAAO,SAAS,KAChC,kBAAkB,MAAM,OAAO,UAAU,OAAO,KAAK,IACrD,QAAQ,UACN,IAAI,aAAa,GAAG,KAAK,cAAc;IACrC;IACA,OAAO,OAAO;GAChB,CAAC,IACD,IAAI,gBAAgB,GAAG,KAAK,0BAA0B;IACpD;IACA,OAAO,OAAO;GAChB,CAAC;GAET,MAAM,YACJ,MAAM,WAAW,KAAA,IACb,WAAW,cACX,WAAW,cACT,mBAAmB,IAAI,MAAM,MAAM,IACnC,MAAM,WAAW;GAEzB,MAAM,QACJ,MAAM,gBACN,KAAK,IAAI,KAAM,MAAM,KAAK,OAAO,KAAK,MAAO,KAAK,OAAO,IAAI;GAE/D,IAAI,CAAC,aAAa,WAAW,cAAc,QAAQ,oBACjD,MAAM;GAGR,MAAM,MAAM,OAAO,QAAQ,MAAM;EACnC;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":["sdk"],"sources":["../src/errors.ts","../src/generated/core/bodySerializer.gen.ts","../src/generated/core/params.gen.ts","../src/generated/core/serverSentEvents.gen.ts","../src/generated/core/pathSerializer.gen.ts","../src/generated/core/utils.gen.ts","../src/generated/core/auth.gen.ts","../src/generated/client/utils.gen.ts","../src/generated/client/client.gen.ts","../src/generated/client.gen.ts","../src/generated/sdk.gen.ts","../src/pages.ts","../src/fuser.ts"],"sourcesContent":["import type { ApiError } from './generated/types.gen.js';\n\nexport interface FuserErrorDetails {\n /** The tool that failed, e.g. `run_start`. */\n tool: string;\n status?: number;\n /** The API's error kind, e.g. `NOT_FOUND`. */\n code?: string;\n /** Which conflict a 409 is, e.g. `stale_revision`. */\n reason?: string;\n issues?: ApiError['issues'];\n requestId?: string;\n retryAfterMs?: number;\n body?: unknown;\n cause?: unknown;\n}\n\n/** Every error the SDK throws. Subclasses say what went wrong. */\nexport class FuserError extends Error {\n override name = 'FuserError';\n readonly tool: string;\n readonly status: number | undefined;\n readonly code: string | undefined;\n readonly reason: string | undefined;\n readonly issues: ApiError['issues'];\n readonly requestId: string | undefined;\n readonly retryAfterMs: number | undefined;\n readonly body: unknown;\n\n constructor(message: string, details: FuserErrorDetails) {\n super(message, { cause: details.cause });\n this.tool = details.tool;\n this.status = details.status;\n this.code = details.code;\n this.reason = details.reason;\n this.issues = details.issues;\n this.requestId = details.requestId;\n this.retryAfterMs = details.retryAfterMs;\n this.body = details.body;\n }\n}\n\nexport class BadRequestError extends FuserError {\n override name = 'BadRequestError';\n}\n\nexport class AuthenticationError extends FuserError {\n override name = 'AuthenticationError';\n}\n\nexport class PermissionDeniedError extends FuserError {\n override name = 'PermissionDeniedError';\n}\n\nexport class NotFoundError extends FuserError {\n override name = 'NotFoundError';\n}\n\nexport class ConflictError extends FuserError {\n override name = 'ConflictError';\n}\n\nexport class RateLimitError extends FuserError {\n override name = 'RateLimitError';\n}\n\nexport class InternalServerError extends FuserError {\n override name = 'InternalServerError';\n}\n\nexport class ConnectionError extends FuserError {\n override name = 'ConnectionError';\n}\n\nexport class TimeoutError extends FuserError {\n override name = 'TimeoutError';\n}\n\n/** `run.start(...).wait()` on a run Fuser refused to start. */\nexport class RunRefusedError extends FuserError {\n override name = 'RunRefusedError';\n}\n\nconst BY_STATUS: Record<number, typeof FuserError> = {\n 400: BadRequestError,\n 401: AuthenticationError,\n 403: PermissionDeniedError,\n 404: NotFoundError,\n 409: ConflictError,\n 429: RateLimitError,\n};\n\nexport function errorFromResponse(\n tool: string,\n response: Response,\n body: unknown,\n): FuserError {\n const parsed: Partial<ApiError> =\n body && typeof body === 'object' ? body : {};\n\n const Kind =\n BY_STATUS[response.status] ??\n (response.status >= 500 ? InternalServerError : FuserError);\n\n const retryAfter = Number(response.headers.get('retry-after'));\n\n const message =\n parsed.message ?? `${tool} failed with HTTP ${String(response.status)}.`;\n\n const issues = parsed.issues\n ?.map(issue =>\n issue.path ? `${issue.path}: ${issue.message}` : issue.message,\n )\n .join('; ');\n\n return new Kind(issues ? `${message}: ${issues}` : message, {\n tool,\n status: response.status,\n code: parsed.code,\n reason: parsed.reason,\n issues: parsed.issues,\n requestId: response.headers.get('x-request-id') ?? undefined,\n retryAfterMs: retryAfter > 0 ? retryAfter * 1000 : undefined,\n body,\n });\n}\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen.js';\n\nexport type QuerySerializer = (query: Record<string, unknown>) => string;\n\nexport type BodySerializer = (body: unknown) => unknown;\n\ntype QuerySerializerOptionsObject = {\n allowReserved?: boolean;\n array?: Partial<SerializerOptions<ArrayStyle>>;\n object?: Partial<SerializerOptions<ObjectStyle>>;\n};\n\nexport type QuerySerializerOptions = QuerySerializerOptionsObject & {\n /**\n * Per-parameter serialization overrides. When provided, these settings\n * override the global array/object settings for specific parameter names.\n */\n parameters?: Record<string, QuerySerializerOptionsObject>;\n};\n\nconst serializeFormDataPair = (data: FormData, key: string, value: unknown): void => {\n if (typeof value === 'string' || value instanceof Blob) {\n data.append(key, value);\n } else if (value instanceof Date) {\n data.append(key, value.toISOString());\n } else {\n data.append(key, JSON.stringify(value));\n }\n};\n\nconst serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => {\n if (typeof value === 'string') {\n data.append(key, value);\n } else {\n data.append(key, JSON.stringify(value));\n }\n};\n\nexport const formDataBodySerializer = {\n bodySerializer: (body: unknown): FormData => {\n const data = new FormData();\n\n Object.entries(body as Record<string, unknown>).forEach(([key, value]) => {\n if (value === undefined || value === null) {\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((v) => serializeFormDataPair(data, key, v));\n } else {\n serializeFormDataPair(data, key, value);\n }\n });\n\n return data;\n },\n};\n\nexport const jsonBodySerializer = {\n bodySerializer: (body: unknown): string =>\n JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)),\n};\n\nexport const urlSearchParamsBodySerializer = {\n bodySerializer: (body: unknown): string => {\n const data = new URLSearchParams();\n\n Object.entries(body as Record<string, unknown>).forEach(([key, value]) => {\n if (value === undefined || value === null) {\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));\n } else {\n serializeUrlSearchParamsPair(data, key, value);\n }\n });\n\n return data.toString();\n },\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\ntype Slot = 'body' | 'headers' | 'path' | 'query';\n\nexport type Field =\n | {\n in: Exclude<Slot, 'body'>;\n /**\n * Field name. This is the name we want the user to see and use.\n */\n key: string;\n /**\n * Field mapped name. This is the name we want to use in the request.\n * If omitted, we use the same value as `key`.\n */\n map?: string;\n }\n | {\n in: Extract<Slot, 'body'>;\n /**\n * Key isn't required for bodies.\n */\n key?: string;\n map?: string;\n }\n | {\n /**\n * Field name. This is the name we want the user to see and use.\n */\n key: string;\n /**\n * Field mapped name. This is the name we want to use in the request.\n * If `in` is omitted, `map` aliases `key` to the transport layer.\n */\n map: Slot;\n };\n\nexport interface Fields {\n allowExtra?: Partial<Record<Slot, boolean>>;\n args?: ReadonlyArray<Field>;\n}\n\nexport type FieldsConfig = ReadonlyArray<Field | Fields>;\n\nconst extraPrefixesMap: Record<string, Slot> = {\n $body_: 'body',\n $headers_: 'headers',\n $path_: 'path',\n $query_: 'query',\n};\nconst extraPrefixes = Object.entries(extraPrefixesMap);\n\ntype KeyMap = Map<\n string,\n | {\n in: Slot;\n map?: string;\n }\n | {\n in?: never;\n map: Slot;\n }\n>;\n\nfunction buildKeyMap(fields: FieldsConfig, map?: KeyMap): KeyMap {\n if (!map) {\n map = new Map();\n }\n\n for (const config of fields) {\n if ('in' in config) {\n if (config.key) {\n map.set(config.key, {\n in: config.in,\n map: config.map,\n });\n }\n } else if ('key' in config) {\n map.set(config.key, {\n map: config.map,\n });\n } else if (config.args) {\n buildKeyMap(config.args, map);\n }\n }\n\n return map;\n}\n\ninterface Params {\n body?: unknown;\n headers: Record<string, unknown>;\n path: Record<string, unknown>;\n query: Record<string, unknown>;\n}\n\nfunction stripEmptySlots(params: Params): void {\n for (const [slot, value] of Object.entries(params)) {\n if (slot === 'body') continue;\n if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) {\n delete params[slot as Slot];\n }\n }\n}\n\nexport function buildClientParams(args: ReadonlyArray<unknown>, fields: FieldsConfig): Params {\n const params: Params = {\n headers: Object.create(null),\n path: Object.create(null),\n query: Object.create(null),\n };\n\n const map = buildKeyMap(fields);\n\n function writeSlot(slot: Slot, key: string, value: unknown): void {\n let record = params[slot] as Record<string, unknown> | undefined;\n if (record === undefined) {\n record = Object.create(null) as Record<string, unknown>;\n params[slot] = record;\n }\n record[key] = value;\n }\n\n let config: FieldsConfig[number] | undefined;\n\n for (const [index, arg] of args.entries()) {\n if (fields[index]) {\n config = fields[index];\n }\n\n if (!config) {\n continue;\n }\n\n if ('in' in config) {\n if (config.key) {\n const field = map.get(config.key)!;\n const name = field.map || config.key;\n if (field.in) {\n writeSlot(field.in, name, arg);\n }\n } else {\n params.body = arg;\n }\n } else {\n for (const [key, value] of Object.entries(arg ?? {})) {\n const field = map.get(key);\n\n if (field) {\n if (field.in) {\n const name = field.map || key;\n writeSlot(field.in, name, value);\n } else {\n params[field.map] = value;\n }\n } else {\n const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix));\n\n if (extra) {\n const [prefix, slot] = extra;\n writeSlot(slot, key.slice(prefix.length), value);\n } else if ('allowExtra' in config && config.allowExtra) {\n for (const [slot, allowed] of Object.entries(config.allowExtra)) {\n if (allowed) {\n writeSlot(slot as Slot, key, value);\n break;\n }\n }\n }\n }\n }\n }\n }\n\n stripEmptySlots(params);\n\n return params;\n}\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport type { Config } from './types.gen.js';\n\nexport type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, 'method'> &\n Pick<Config, 'method' | 'responseTransformer' | 'responseValidator'> & {\n /**\n * Fetch API implementation. You can use this option to provide a custom\n * fetch instance.\n *\n * @default globalThis.fetch\n */\n fetch?: typeof fetch;\n /**\n * Implementing clients can call request interceptors inside this hook.\n */\n onRequest?: (url: string, init: RequestInit) => Promise<Request>;\n /**\n * Callback invoked when a network or parsing error occurs during streaming.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @param error The error that occurred.\n */\n onSseError?: (error: unknown) => void;\n /**\n * Callback invoked when an event is streamed from the server.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @param event Event streamed from the server.\n * @returns Nothing (void).\n */\n onSseEvent?: (event: StreamEvent<TData>) => void;\n serializedBody?: RequestInit['body'];\n /**\n * Default retry delay in milliseconds.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @default 3000\n */\n sseDefaultRetryDelay?: number;\n /**\n * Maximum number of retry attempts before giving up.\n */\n sseMaxRetryAttempts?: number;\n /**\n * Maximum retry delay in milliseconds.\n *\n * Applies only when exponential backoff is used.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @default 30000\n */\n sseMaxRetryDelay?: number;\n /**\n * Optional sleep function for retry backoff.\n *\n * Defaults to using `setTimeout`.\n */\n sseSleepFn?: (ms: number) => Promise<void>;\n url: string;\n };\n\nexport interface StreamEvent<TData = unknown> {\n data: TData;\n event?: string;\n id?: string;\n retry?: number;\n}\n\nexport type ServerSentEventsResult<TData = unknown, TReturn = void, TNext = unknown> = {\n stream: AsyncGenerator<\n TData extends Record<string, unknown> ? TData[keyof TData] : TData,\n TReturn,\n TNext\n >;\n};\n\nexport function createSseClient<TData = unknown>({\n onRequest,\n onSseError,\n onSseEvent,\n responseTransformer,\n responseValidator,\n sseDefaultRetryDelay,\n sseMaxRetryAttempts,\n sseMaxRetryDelay,\n sseSleepFn,\n url,\n ...options\n}: ServerSentEventsOptions): ServerSentEventsResult<TData> {\n let lastEventId: string | undefined;\n\n const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));\n\n const createStream = async function* () {\n let retryDelay: number = sseDefaultRetryDelay ?? 3000;\n let attempt = 0;\n const signal = options.signal ?? new AbortController().signal;\n\n while (true) {\n if (signal.aborted) break;\n\n attempt++;\n\n const headers =\n options.headers instanceof Headers\n ? options.headers\n : new Headers(options.headers as Record<string, string> | undefined);\n\n if (lastEventId !== undefined) {\n headers.set('Last-Event-ID', lastEventId);\n }\n\n try {\n const requestInit: RequestInit = {\n redirect: 'follow',\n ...options,\n body: options.serializedBody,\n headers,\n signal,\n };\n let request = new Request(url, requestInit);\n if (onRequest) {\n request = await onRequest(url, requestInit);\n }\n // fetch must be assigned here, otherwise it would throw the error:\n // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation\n const _fetch = options.fetch ?? globalThis.fetch;\n const response = await _fetch(request);\n\n if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);\n\n if (!response.body) throw new Error('No body in SSE response');\n\n const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();\n\n let buffer = '';\n\n const abortHandler = () => {\n try {\n reader.cancel();\n } catch {\n // noop\n }\n };\n\n signal.addEventListener('abort', abortHandler);\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += value;\n buffer = buffer.replace(/\\r\\n?/g, '\\n'); // normalize line endings\n\n const chunks = buffer.split('\\n\\n');\n buffer = chunks.pop() ?? '';\n\n for (const chunk of chunks) {\n const lines = chunk.split('\\n');\n const dataLines: Array<string> = [];\n let eventName: string | undefined;\n\n for (const line of lines) {\n if (line.startsWith('data:')) {\n dataLines.push(line.replace(/^data:\\s*/, ''));\n } else if (line.startsWith('event:')) {\n eventName = line.replace(/^event:\\s*/, '');\n } else if (line.startsWith('id:')) {\n lastEventId = line.replace(/^id:\\s*/, '');\n } else if (line.startsWith('retry:')) {\n const parsed = Number.parseInt(line.replace(/^retry:\\s*/, ''), 10);\n if (!Number.isNaN(parsed)) {\n retryDelay = parsed;\n }\n }\n }\n\n let data: unknown;\n let parsedJson = false;\n\n if (dataLines.length) {\n const rawData = dataLines.join('\\n');\n try {\n data = JSON.parse(rawData);\n parsedJson = true;\n } catch {\n data = rawData;\n }\n }\n\n if (parsedJson) {\n if (responseValidator) {\n await responseValidator(data);\n }\n\n if (responseTransformer) {\n data = await responseTransformer(data);\n }\n }\n\n onSseEvent?.({\n data,\n event: eventName,\n id: lastEventId,\n retry: retryDelay,\n });\n\n if (dataLines.length) {\n yield data as any;\n }\n }\n }\n } finally {\n signal.removeEventListener('abort', abortHandler);\n reader.releaseLock();\n }\n\n break; // exit loop on normal completion\n } catch (error) {\n // connection failed or aborted; retry after delay\n onSseError?.(error);\n\n if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) {\n break; // stop after firing error\n }\n\n // exponential backoff: double retry each attempt, cap at 30s\n const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000);\n await sleep(backoff);\n }\n }\n };\n\n const stream = createStream();\n\n return { stream };\n}\n","// This file is auto-generated by @hey-api/openapi-ts\n\ninterface SerializeOptions<T> extends SerializePrimitiveOptions, SerializerOptions<T> {}\n\ninterface SerializePrimitiveOptions {\n allowReserved?: boolean;\n name: string;\n}\n\nexport interface SerializerOptions<T> {\n /**\n * @default true\n */\n explode: boolean;\n style: T;\n}\n\nexport type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';\nexport type ArraySeparatorStyle = ArrayStyle | MatrixStyle;\ntype MatrixStyle = 'label' | 'matrix' | 'simple';\nexport type ObjectStyle = 'form' | 'deepObject';\ntype ObjectSeparatorStyle = ObjectStyle | MatrixStyle;\n\ninterface SerializePrimitiveParam extends SerializePrimitiveOptions {\n value: string;\n}\n\nexport const separatorArrayExplode = (style: ArraySeparatorStyle): '.' | ';' | ',' | '&' => {\n switch (style) {\n case 'label':\n return '.';\n case 'matrix':\n return ';';\n case 'simple':\n return ',';\n default:\n return '&';\n }\n};\n\nexport const separatorArrayNoExplode = (style: ArraySeparatorStyle): ',' | '|' | '%20' => {\n switch (style) {\n case 'form':\n return ',';\n case 'pipeDelimited':\n return '|';\n case 'spaceDelimited':\n return '%20';\n default:\n return ',';\n }\n};\n\nexport const separatorObjectExplode = (style: ObjectSeparatorStyle): '.' | ';' | ',' | '&' => {\n switch (style) {\n case 'label':\n return '.';\n case 'matrix':\n return ';';\n case 'simple':\n return ',';\n default:\n return '&';\n }\n};\n\nexport const serializeArrayParam = ({\n allowReserved,\n explode,\n name,\n style,\n value,\n}: SerializeOptions<ArraySeparatorStyle> & {\n value: unknown[];\n}): string => {\n if (!explode) {\n const joinedValues = (\n allowReserved ? value : value.map((v) => encodeURIComponent(v as string))\n ).join(separatorArrayNoExplode(style));\n switch (style) {\n case 'label':\n return `.${joinedValues}`;\n case 'matrix':\n return `;${name}=${joinedValues}`;\n case 'simple':\n return joinedValues;\n default:\n return `${name}=${joinedValues}`;\n }\n }\n\n const separator = separatorArrayExplode(style);\n const joinedValues = value\n .map((v) => {\n if (style === 'label' || style === 'simple') {\n return allowReserved ? v : encodeURIComponent(v as string);\n }\n\n return serializePrimitiveParam({\n allowReserved,\n name,\n value: v as string,\n });\n })\n .join(separator);\n return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues;\n};\n\nexport const serializePrimitiveParam = ({\n allowReserved,\n name,\n value,\n}: SerializePrimitiveParam): string => {\n if (value === undefined || value === null) {\n return '';\n }\n\n if (typeof value === 'object') {\n throw new Error(\n 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.',\n );\n }\n\n return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;\n};\n\nexport const serializeObjectParam = ({\n allowReserved,\n explode,\n name,\n style,\n value,\n valueOnly,\n}: SerializeOptions<ObjectSeparatorStyle> & {\n value: Record<string, unknown> | Date;\n valueOnly?: boolean;\n}): string => {\n if (value instanceof Date) {\n return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;\n }\n\n if (style !== 'deepObject' && !explode) {\n let values: string[] = [];\n Object.entries(value).forEach(([key, v]) => {\n values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)];\n });\n const joinedValues = values.join(',');\n switch (style) {\n case 'form':\n return `${name}=${joinedValues}`;\n case 'label':\n return `.${joinedValues}`;\n case 'matrix':\n return `;${name}=${joinedValues}`;\n default:\n return joinedValues;\n }\n }\n\n const separator = separatorObjectExplode(style);\n const joinedValues = Object.entries(value)\n .map(([key, v]) =>\n serializePrimitiveParam({\n allowReserved,\n name: style === 'deepObject' ? `${name}[${key}]` : key,\n value: v as string,\n }),\n )\n .join(separator);\n return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues;\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport type { BodySerializer, QuerySerializer } from './bodySerializer.gen.js';\nimport {\n type ArraySeparatorStyle,\n serializeArrayParam,\n serializeObjectParam,\n serializePrimitiveParam,\n} from './pathSerializer.gen.js';\n\nexport interface PathSerializer {\n path: Record<string, unknown>;\n url: string;\n}\n\nexport const PATH_PARAM_RE: RegExp = /\\{[^{}]+\\}/g;\n\nexport const defaultPathSerializer = ({ path, url: _url }: PathSerializer): string => {\n let url = _url;\n const matches = _url.match(PATH_PARAM_RE);\n if (matches) {\n for (const match of matches) {\n let explode = false;\n let name = match.substring(1, match.length - 1);\n let style: ArraySeparatorStyle = 'simple';\n\n if (name.endsWith('*')) {\n explode = true;\n name = name.substring(0, name.length - 1);\n }\n\n if (name.startsWith('.')) {\n name = name.substring(1);\n style = 'label';\n } else if (name.startsWith(';')) {\n name = name.substring(1);\n style = 'matrix';\n }\n\n const value = path[name];\n\n if (value === undefined || value === null) {\n continue;\n }\n\n if (Array.isArray(value)) {\n url = url.replace(match, serializeArrayParam({ explode, name, style, value }));\n continue;\n }\n\n if (typeof value === 'object') {\n url = url.replace(\n match,\n serializeObjectParam({\n explode,\n name,\n style,\n value: value as Record<string, unknown>,\n valueOnly: true,\n }),\n );\n continue;\n }\n\n if (style === 'matrix') {\n url = url.replace(\n match,\n `;${serializePrimitiveParam({\n name,\n value: value as string,\n })}`,\n );\n continue;\n }\n\n const replaceValue = encodeURIComponent(\n style === 'label' ? `.${value as string}` : (value as string),\n );\n url = url.replace(match, replaceValue);\n }\n }\n return url;\n};\n\nexport const getUrl = ({\n baseUrl,\n path,\n query,\n querySerializer,\n url: _url,\n}: {\n baseUrl?: string;\n path?: Record<string, unknown>;\n query?: Record<string, unknown>;\n querySerializer: QuerySerializer;\n url: string;\n}): string => {\n const pathUrl = _url.startsWith('/') ? _url : `/${_url}`;\n let url = (baseUrl ?? '') + pathUrl;\n if (path) {\n url = defaultPathSerializer({ path, url });\n }\n let search = query ? querySerializer(query) : '';\n if (search.startsWith('?')) {\n search = search.substring(1);\n }\n if (search) {\n url += `?${search}`;\n }\n return url;\n};\n\nexport function getValidRequestBody(options: {\n body?: unknown;\n bodySerializer?: BodySerializer | null;\n serializedBody?: unknown;\n}): unknown {\n const hasBody = options.body !== undefined;\n const isSerializedBody = hasBody && options.bodySerializer;\n\n if (isSerializedBody) {\n if ('serializedBody' in options) {\n const hasSerializedBody =\n options.serializedBody !== undefined && options.serializedBody !== '';\n\n return hasSerializedBody ? options.serializedBody : null;\n }\n\n // not all clients implement a serializedBody property (i.e., client-axios)\n return options.body !== '' ? options.body : null;\n }\n\n // plain/text body\n if (hasBody) {\n return options.body;\n }\n\n // no body was provided\n return undefined;\n}\n","// This file is auto-generated by @hey-api/openapi-ts\n\nexport type AuthToken = string | undefined;\n\nexport interface Auth {\n /**\n * Which part of the request do we use to send the auth?\n *\n * @default 'header'\n */\n in?: 'header' | 'query' | 'cookie';\n /**\n * A unique identifier for the security scheme.\n *\n * Defined only when there are multiple security schemes whose `Auth`\n * shape would otherwise be identical.\n */\n key?: string;\n /**\n * Header or query parameter name.\n *\n * @default 'Authorization'\n */\n name?: string;\n scheme?: 'basic' | 'bearer';\n type: 'apiKey' | 'http';\n}\n\nexport const getAuthToken = async (\n auth: Auth,\n callback: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken,\n): Promise<string | undefined> => {\n const token = typeof callback === 'function' ? await callback(auth) : callback;\n\n if (!token) {\n return;\n }\n\n if (auth.scheme === 'bearer') {\n return `Bearer ${token}`;\n }\n\n if (auth.scheme === 'basic') {\n return `Basic ${btoa(token)}`;\n }\n\n return token;\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { getAuthToken } from '../core/auth.gen.js';\nimport type { QuerySerializerOptions } from '../core/bodySerializer.gen.js';\nimport { jsonBodySerializer } from '../core/bodySerializer.gen.js';\nimport {\n serializeArrayParam,\n serializeObjectParam,\n serializePrimitiveParam,\n} from '../core/pathSerializer.gen.js';\nimport { getUrl } from '../core/utils.gen.js';\nimport type { Client, ClientOptions, Config, RequestOptions } from './types.gen.js';\n\nexport const createQuerySerializer = <T = unknown>({\n parameters = {},\n ...args\n}: QuerySerializerOptions = {}): ((queryParams: T) => string) => {\n const querySerializer = (queryParams: T): string => {\n const search: string[] = [];\n if (queryParams && typeof queryParams === 'object') {\n for (const name in queryParams) {\n const value = queryParams[name];\n\n if (value === undefined || value === null) {\n continue;\n }\n\n const options = parameters[name] || args;\n\n if (Array.isArray(value)) {\n const serializedArray = serializeArrayParam({\n allowReserved: options.allowReserved,\n explode: true,\n name,\n style: 'form',\n value,\n ...options.array,\n });\n if (serializedArray) search.push(serializedArray);\n } else if (typeof value === 'object') {\n const serializedObject = serializeObjectParam({\n allowReserved: options.allowReserved,\n explode: true,\n name,\n style: 'deepObject',\n value: value as Record<string, unknown>,\n ...options.object,\n });\n if (serializedObject) search.push(serializedObject);\n } else {\n const serializedPrimitive = serializePrimitiveParam({\n allowReserved: options.allowReserved,\n name,\n value: value as string,\n });\n if (serializedPrimitive) search.push(serializedPrimitive);\n }\n }\n }\n return search.join('&');\n };\n return querySerializer;\n};\n\n/**\n * Infers parseAs value from provided Content-Type header.\n */\nexport const getParseAs = (contentType: string | null): Exclude<Config['parseAs'], 'auto'> => {\n if (!contentType) {\n // If no Content-Type header is provided, the best we can do is return the raw response body,\n // which is effectively the same as the 'stream' option.\n return 'stream';\n }\n\n const cleanContent = contentType.split(';')[0]?.trim();\n\n if (!cleanContent) {\n return;\n }\n\n if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) {\n return 'json';\n }\n\n if (cleanContent === 'multipart/form-data') {\n return 'formData';\n }\n\n if (\n ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type))\n ) {\n return 'blob';\n }\n\n if (cleanContent.startsWith('text/')) {\n return 'text';\n }\n\n return;\n};\n\nconst checkForExistence = (\n options: Pick<RequestOptions, 'auth' | 'query'> & {\n headers: Headers;\n },\n name?: string,\n): boolean => {\n if (!name) {\n return false;\n }\n if (\n options.headers.has(name) ||\n options.query?.[name] ||\n options.headers.get('Cookie')?.includes(`${name}=`)\n ) {\n return true;\n }\n return false;\n};\n\nexport async function setAuthParams(\n options: Pick<RequestOptions, 'auth' | 'query' | 'security'> & {\n headers: Headers;\n },\n): Promise<void> {\n for (const auth of options.security ?? []) {\n if (checkForExistence(options, auth.name)) {\n continue;\n }\n\n const token = await getAuthToken(auth, options.auth);\n\n if (!token) {\n continue;\n }\n\n const name = auth.name ?? 'Authorization';\n\n switch (auth.in) {\n case 'query':\n if (!options.query) {\n options.query = {};\n }\n options.query[name] = token;\n break;\n case 'cookie':\n options.headers.append('Cookie', `${name}=${token}`);\n break;\n case 'header':\n default:\n options.headers.set(name, token);\n break;\n }\n }\n}\n\nexport const buildUrl: Client['buildUrl'] = (options) =>\n getUrl({\n baseUrl: options.baseUrl as string,\n path: options.path,\n query: options.query,\n querySerializer:\n typeof options.querySerializer === 'function'\n ? options.querySerializer\n : createQuerySerializer(options.querySerializer),\n url: options.url,\n });\n\nexport const mergeConfigs = (a: Config, b: Config): Config => {\n const config = { ...a, ...b };\n if (config.baseUrl?.endsWith('/')) {\n config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);\n }\n config.headers = mergeHeaders(a.headers, b.headers);\n return config;\n};\n\nconst headersEntries = (headers: Headers): Array<[string, string]> => {\n const entries: Array<[string, string]> = [];\n headers.forEach((value, key) => {\n entries.push([key, value]);\n });\n return entries;\n};\n\nexport const mergeHeaders = (\n ...headers: Array<Required<Config>['headers'] | undefined>\n): Headers => {\n const mergedHeaders = new Headers();\n for (const header of headers) {\n if (!header) {\n continue;\n }\n\n const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);\n\n for (const [key, value] of iterator) {\n if (value === null) {\n mergedHeaders.delete(key);\n } else if (Array.isArray(value)) {\n for (const v of value) {\n mergedHeaders.append(key, v as string);\n }\n } else if (value !== undefined) {\n // assume object headers are meant to be JSON stringified, i.e., their\n // content value in OpenAPI specification is 'application/json'\n mergedHeaders.set(\n key,\n typeof value === 'object' ? JSON.stringify(value) : (value as string),\n );\n }\n }\n }\n return mergedHeaders;\n};\n\ntype ErrInterceptor<Err, Res, Req, Options> = (\n error: Err,\n /** response may be undefined due to a network error where no response object is produced */\n response: Res | undefined,\n /** request may be undefined, because error may be from building the request object itself */\n request: Req | undefined,\n options: Options,\n) => Err | Promise<Err>;\n\ntype ReqInterceptor<Req, Options> = (request: Req, options: Options) => Req | Promise<Req>;\n\ntype ResInterceptor<Res, Req, Options> = (\n response: Res,\n request: Req,\n options: Options,\n) => Res | Promise<Res>;\n\nclass Interceptors<Interceptor> {\n fns: Array<Interceptor | null> = [];\n\n clear(): void {\n this.fns = [];\n }\n\n eject(id: number | Interceptor): void {\n const index = this.getInterceptorIndex(id);\n if (this.fns[index]) {\n this.fns[index] = null;\n }\n }\n\n exists(id: number | Interceptor): boolean {\n const index = this.getInterceptorIndex(id);\n return Boolean(this.fns[index]);\n }\n\n getInterceptorIndex(id: number | Interceptor): number {\n if (typeof id === 'number') {\n return this.fns[id] ? id : -1;\n }\n return this.fns.indexOf(id);\n }\n\n update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false {\n const index = this.getInterceptorIndex(id);\n if (this.fns[index]) {\n this.fns[index] = fn;\n return id;\n }\n return false;\n }\n\n use(fn: Interceptor): number {\n this.fns.push(fn);\n return this.fns.length - 1;\n }\n}\n\nexport interface Middleware<Req, Res, Err, Options> {\n error: Interceptors<ErrInterceptor<Err, Res, Req, Options>>;\n request: Interceptors<ReqInterceptor<Req, Options>>;\n response: Interceptors<ResInterceptor<Res, Req, Options>>;\n}\n\nexport const createInterceptors = <Req, Res, Err, Options>(): Middleware<\n Req,\n Res,\n Err,\n Options\n> => ({\n error: new Interceptors<ErrInterceptor<Err, Res, Req, Options>>(),\n request: new Interceptors<ReqInterceptor<Req, Options>>(),\n response: new Interceptors<ResInterceptor<Res, Req, Options>>(),\n});\n\nconst defaultQuerySerializer = createQuerySerializer({\n allowReserved: false,\n array: {\n explode: true,\n style: 'form',\n },\n object: {\n explode: true,\n style: 'deepObject',\n },\n});\n\nconst defaultHeaders = {\n 'Content-Type': 'application/json',\n};\n\nexport const createConfig = <T extends ClientOptions = ClientOptions>(\n override: Config<Omit<ClientOptions, keyof T> & T> = {},\n): Config<Omit<ClientOptions, keyof T> & T> => ({\n ...jsonBodySerializer,\n headers: defaultHeaders,\n parseAs: 'auto',\n querySerializer: defaultQuerySerializer,\n ...override,\n});\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { createSseClient } from '../core/serverSentEvents.gen.js';\nimport type { HttpMethod } from '../core/types.gen.js';\nimport { getValidRequestBody } from '../core/utils.gen.js';\nimport type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen.js';\nimport {\n buildUrl,\n createConfig,\n createInterceptors,\n getParseAs,\n mergeConfigs,\n mergeHeaders,\n setAuthParams,\n} from './utils.gen.js';\n\ntype ReqInit = Omit<RequestInit, 'body' | 'headers'> & {\n body?: any;\n headers: ReturnType<typeof mergeHeaders>;\n};\n\nexport const createClient = (config: Config = {}): Client => {\n let _config = mergeConfigs(createConfig(), config);\n\n const getConfig = (): Config => ({ ..._config });\n\n const setConfig = (config: Config): Config => {\n _config = mergeConfigs(_config, config);\n return getConfig();\n };\n\n const interceptors = createInterceptors<Request, Response, unknown, ResolvedRequestOptions>();\n\n const beforeRequest = async <\n TData = unknown,\n TResponseStyle extends 'data' | 'fields' = 'fields',\n ThrowOnError extends boolean = boolean,\n Url extends string = string,\n >(\n options: RequestOptions<TData, TResponseStyle, ThrowOnError, Url>,\n ) => {\n const opts = {\n ..._config,\n ...options,\n fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,\n headers: mergeHeaders(_config.headers, options.headers),\n serializedBody: undefined as string | undefined,\n };\n\n if (opts.security) {\n await setAuthParams(opts);\n }\n\n if (opts.requestValidator) {\n await opts.requestValidator(opts);\n }\n\n if (opts.body !== undefined && opts.bodySerializer) {\n opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined;\n }\n\n // remove Content-Type header if body is empty to avoid sending invalid requests\n if (opts.body === undefined || opts.serializedBody === '') {\n opts.headers.delete('Content-Type');\n }\n\n const resolvedOpts = opts as typeof opts &\n ResolvedRequestOptions<TResponseStyle, ThrowOnError, Url>;\n const url = buildUrl(resolvedOpts);\n\n return { opts: resolvedOpts, url };\n };\n\n const request: Client['request'] = async (options) => {\n const throwOnError = options.throwOnError ?? _config.throwOnError;\n const responseStyle = options.responseStyle ?? _config.responseStyle;\n\n let request: Request | undefined;\n let response: Response | undefined;\n\n try {\n const { opts, url } = await beforeRequest(options);\n const requestInit: ReqInit = {\n redirect: 'follow',\n ...opts,\n body: getValidRequestBody(opts),\n };\n\n request = new Request(url, requestInit);\n\n for (const fn of interceptors.request.fns) {\n if (fn) {\n request = await fn(request, opts);\n }\n }\n\n // fetch must be assigned here, otherwise it would throw the error:\n // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation\n const _fetch = opts.fetch!;\n\n response = await _fetch(request);\n\n for (const fn of interceptors.response.fns) {\n if (fn) {\n response = await fn(response, request, opts);\n }\n }\n\n const result = {\n request,\n response,\n };\n\n if (response.ok) {\n const parseAs =\n (opts.parseAs === 'auto'\n ? getParseAs(response.headers.get('Content-Type'))\n : opts.parseAs) ?? 'json';\n\n if (response.status === 204 || response.headers.get('Content-Length') === '0') {\n let emptyData: any;\n switch (parseAs) {\n case 'arrayBuffer':\n case 'blob':\n case 'text':\n emptyData = await response[parseAs]();\n break;\n case 'formData':\n emptyData = new FormData();\n break;\n case 'stream':\n emptyData = response.body;\n break;\n case 'json':\n default:\n emptyData = {};\n break;\n }\n return opts.responseStyle === 'data'\n ? emptyData\n : {\n data: emptyData,\n ...result,\n };\n }\n\n let data: any;\n switch (parseAs) {\n case 'arrayBuffer':\n case 'blob':\n case 'formData':\n case 'text':\n data = await response[parseAs]();\n break;\n case 'json': {\n // Some servers return 200 with no Content-Length and empty body.\n // response.json() would throw; read as text and parse if non-empty.\n const text = await response.text();\n data = text ? JSON.parse(text) : {};\n break;\n }\n case 'stream':\n return opts.responseStyle === 'data'\n ? response.body\n : {\n data: response.body,\n ...result,\n };\n }\n\n if (parseAs === 'json') {\n if (opts.responseValidator) {\n await opts.responseValidator(data);\n }\n\n if (opts.responseTransformer) {\n data = await opts.responseTransformer(data);\n }\n }\n\n return opts.responseStyle === 'data'\n ? data\n : {\n data,\n ...result,\n };\n }\n\n const textError = await response.text();\n let jsonError: unknown;\n\n try {\n jsonError = JSON.parse(textError);\n } catch {\n // noop\n }\n\n throw jsonError ?? textError;\n } catch (error) {\n let finalError = error;\n\n for (const fn of interceptors.error.fns) {\n if (fn) {\n finalError = await fn(finalError, response, request, options as ResolvedRequestOptions);\n }\n }\n\n finalError = finalError || {};\n\n if (throwOnError) {\n throw finalError;\n }\n\n // TODO: we probably want to return error and improve types\n return responseStyle === 'data'\n ? undefined\n : {\n error: finalError,\n request,\n response,\n };\n }\n };\n\n const makeMethodFn = (method: Uppercase<HttpMethod>) => (options: RequestOptions) =>\n request({ ...options, method });\n\n const makeSseFn = (method: Uppercase<HttpMethod>) => async (options: RequestOptions) => {\n const { opts, url } = await beforeRequest(options);\n return createSseClient({\n ...opts,\n body: opts.body as BodyInit | null | undefined,\n method,\n onRequest: async (url, init) => {\n let request = new Request(url, init);\n for (const fn of interceptors.request.fns) {\n if (fn) {\n request = await fn(request, opts);\n }\n }\n return request;\n },\n serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined,\n url,\n });\n };\n\n const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options });\n\n return {\n buildUrl: _buildUrl,\n connect: makeMethodFn('CONNECT'),\n delete: makeMethodFn('DELETE'),\n get: makeMethodFn('GET'),\n getConfig,\n head: makeMethodFn('HEAD'),\n interceptors,\n options: makeMethodFn('OPTIONS'),\n patch: makeMethodFn('PATCH'),\n post: makeMethodFn('POST'),\n put: makeMethodFn('PUT'),\n request,\n setConfig,\n sse: {\n connect: makeSseFn('CONNECT'),\n delete: makeSseFn('DELETE'),\n get: makeSseFn('GET'),\n head: makeSseFn('HEAD'),\n options: makeSseFn('OPTIONS'),\n patch: makeSseFn('PATCH'),\n post: makeSseFn('POST'),\n put: makeSseFn('PUT'),\n trace: makeSseFn('TRACE'),\n },\n trace: makeMethodFn('TRACE'),\n } as Client;\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { type Client, type ClientOptions, type Config, createClient, createConfig } from './client/index.js';\nimport type { ClientOptions as ClientOptions2 } from './types.gen.js';\n\n/**\n * The `createClientConfig()` function will be called on client initialization\n * and the returned object will become the client's initial configuration.\n *\n * You may want to initialize your client this way instead of calling\n * `setConfig()`. This is useful for example if you're using Next.js\n * to ensure your client always has the correct values.\n */\nexport type CreateClientConfig<T extends ClientOptions = ClientOptions2> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;\n\nexport const client: Client = createClient(createConfig<ClientOptions2>({ baseUrl: 'https://api.fuser.studio' }));\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { client } from './client.gen.js';\nimport type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client/index.js';\nimport type { AccountGetData, AccountGetErrors, AccountGetResponses, CanvasArrangeData, CanvasArrangeErrors, CanvasArrangeResponses, CanvasEditData, CanvasEditErrors, CanvasEditResponses, CanvasGetData, CanvasGetErrors, CanvasGetResponses, CanvasListData, CanvasListErrors, CanvasListResponses, CatalogSearchData, CatalogSearchErrors, CatalogSearchResponses, MediaExportData, MediaExportErrors, MediaExportResponses, MediaImportData, MediaImportErrors, MediaImportResponses, MediaSearchData, MediaSearchErrors, MediaSearchResponses, MediaViewData, MediaViewErrors, MediaViewResponses, RunCancelData, RunCancelErrors, RunCancelResponses, RunGetData, RunGetErrors, RunGetResponses, RunStartData, RunStartErrors, RunStartResponses, ToolBuildData, ToolBuildErrors, ToolBuildResponses, ToolSearchData, ToolSearchErrors, ToolSearchResponses, UploadFinishData, UploadFinishErrors, UploadFinishResponses, UploadStartData, UploadStartErrors, UploadStartResponses } from './types.gen.js';\n\nexport type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {\n /**\n * You can provide a client instance returned by `createClient()` instead of\n * individual options. This might be also useful if you want to implement a\n * custom client.\n */\n client?: Client;\n /**\n * You can pass arbitrary values through the `meta` object. This can be\n * used to access values that aren't defined as part of the SDK function.\n */\n meta?: keyof ClientMeta extends never ? Record<string, unknown> : ClientMeta;\n};\n\n/**\n * List canvases\n *\n * Canvases you can open, most recently edited first, with a link to each. Reuse one only when the user points to it; put new work on a new canvas, and never present results that were already there as new.\n */\nexport const canvasList = <ThrowOnError extends boolean = false>(options?: Options<CanvasListData, ThrowOnError>): RequestResult<CanvasListResponses, CanvasListErrors, ThrowOnError> => (options?.client ?? client).get<CanvasListResponses, CanvasListErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/canvas_list',\n ...options\n});\n\n/**\n * Read a canvas\n *\n * A compact view of a canvas: a summary, then pages of nodes (id, type, label, socket keys, literal values, result links) and their edges. On a big canvas, find nodes with search or read specific ones with nodeIds instead of paging through everything.\n */\nexport const canvasGet = <ThrowOnError extends boolean = false>(options: Options<CanvasGetData, ThrowOnError>): RequestResult<CanvasGetResponses, CanvasGetErrors, ThrowOnError> => (options.client ?? client).get<CanvasGetResponses, CanvasGetErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/canvas_get',\n ...options\n});\n\n/**\n * Edit a canvas\n *\n * Apply a graph diff to a canvas all at once: add nodes and edges, change inputs, disconnect edges, delete nodes. Every change lands or none does. Keep each edit to about 30 new nodes; build a bigger canvas one section per edit, so a mistake costs one small resend.\n */\nexport const canvasEdit = <ThrowOnError extends boolean = false>(options: Options<CanvasEditData, ThrowOnError>): RequestResult<CanvasEditResponses, CanvasEditErrors, ThrowOnError> => (options.client ?? client).post<CanvasEditResponses, CanvasEditErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/canvas_edit',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Arrange nodes on a canvas\n *\n * Lay out existing nodes with Fuser's layout instead of working out positions. Without layout it tidies them along their wiring, inputs to the left of what they feed; with layout it puts them in a row, column or grid in nodeIds order. Without an origin the block stays where the nodes are and slides clear of the nodes around it. Use it when the user asks to rearrange, line up or tidy nodes, or after resizing nodes that now overlap. It changes positions only.\n */\nexport const canvasArrange = <ThrowOnError extends boolean = false>(options: Options<CanvasArrangeData, ThrowOnError>): RequestResult<CanvasArrangeResponses, CanvasArrangeErrors, ThrowOnError> => (options.client ?? client).post<CanvasArrangeResponses, CanvasArrangeErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/canvas_arrange',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Find node types\n *\n * Node types a canvas_edit diff may use, with what each is good at, its input ids and its output socket. Call it with no query first: it returns the recommended node for each common job. Search only when none of them fits.\n */\nexport const catalogSearch = <ThrowOnError extends boolean = false>(options?: Options<CatalogSearchData, ThrowOnError>): RequestResult<CatalogSearchResponses, CatalogSearchErrors, ThrowOnError> => (options?.client ?? client).get<CatalogSearchResponses, CatalogSearchErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/catalog_search',\n ...options\n});\n\n/**\n * Run a canvas\n *\n * Run the whole canvas or named nodes. Prices the run first and refuses it when it costs more than maxCredits; dryRun returns only the price. Starts a run once per idempotencyKey; check on it with run_get, not by calling run_start again.\n */\nexport const runStart = <ThrowOnError extends boolean = false>(options: Options<RunStartData, ThrowOnError>): RequestResult<RunStartResponses, RunStartErrors, ThrowOnError> => (options.client ?? client).post<RunStartResponses, RunStartErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/run_start',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Check a run\n *\n * Status of a run you started, per node, with links to each node's results.\n */\nexport const runGet = <ThrowOnError extends boolean = false>(options: Options<RunGetData, ThrowOnError>): RequestResult<RunGetResponses, RunGetErrors, ThrowOnError> => (options.client ?? client).get<RunGetResponses, RunGetErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/run_get',\n ...options\n});\n\n/**\n * Cancel a run\n *\n * Stop a run you started. Nodes already finished keep their results.\n */\nexport const runCancel = <ThrowOnError extends boolean = false>(options: Options<RunCancelData, ThrowOnError>): RequestResult<RunCancelResponses, RunCancelErrors, ThrowOnError> => (options.client ?? client).post<RunCancelResponses, RunCancelErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/run_cancel',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Import an image or video\n *\n * Copy an image or video from a public URL into the canvas's assets and get a Fuser link for it. Use it before putting a web link on the canvas: it says straight away when the link can't be fetched, and the copy won't expire. For a file on the user's machine use upload_start.\n */\nexport const mediaImport = <ThrowOnError extends boolean = false>(options: Options<MediaImportData, ThrowOnError>): RequestResult<MediaImportResponses, MediaImportErrors, ThrowOnError> => (options.client ?? client).post<MediaImportResponses, MediaImportErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/media_import',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Upload files\n *\n * Step 1 of putting files from the user's machine on a canvas, for agents that run commands on that machine (Claude Code, Codex, an IDE). List the files (up to 50): each comes back with a link to PUT it to, or done if Fuser already has it. Then call upload_finish with uploadId. In a chat app use upload_box instead; a cloud code sandbox can't reach these links.\n */\nexport const uploadStart = <ThrowOnError extends boolean = false>(options: Options<UploadStartData, ThrowOnError>): RequestResult<UploadStartResponses, UploadStartErrors, ThrowOnError> => (options.client ?? client).post<UploadStartResponses, UploadStartErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/upload_start',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Finish uploading files\n *\n * Step 2: returns a link for every file that arrived, to use as an ImageNode or VideoNode input, and says why for any that did not. For files the user is adding on the upload page, call it after they say they are done.\n */\nexport const uploadFinish = <ThrowOnError extends boolean = false>(options: Options<UploadFinishData, ThrowOnError>): RequestResult<UploadFinishResponses, UploadFinishErrors, ThrowOnError> => (options.client ?? client).post<UploadFinishResponses, UploadFinishErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/upload_finish',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Look at media\n *\n * See Fuser images and 3D models as small previews, and the first frame of a video, with facts such as size, length and transparency. Look at results before describing or judging them.\n */\nexport const mediaView = <ThrowOnError extends boolean = false>(options: Options<MediaViewData, ThrowOnError>): RequestResult<MediaViewResponses, MediaViewErrors, ThrowOnError> => (options.client ?? client).post<MediaViewResponses, MediaViewErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/media_view',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Find your media\n *\n * Search the images, videos, audio and 3D files you made or uploaded, by meaning (\"the coral reef image\", \"a dog running on a beach\") or by similarity to one you have. Without query or similarTo it lists the newest first. Look at matches with media_view.\n */\nexport const mediaSearch = <ThrowOnError extends boolean = false>(options: Options<MediaSearchData, ThrowOnError>): RequestResult<MediaSearchResponses, MediaSearchErrors, ThrowOnError> => (options.client ?? client).post<MediaSearchResponses, MediaSearchErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/media_search',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Download media as a zip\n *\n * A link that downloads a canvas's results as one zip file, for when the user wants their files ('download everything', 'send me the images as a zip'). Give the user the link; it works for an hour. It changes nothing on the canvas.\n */\nexport const mediaExport = <ThrowOnError extends boolean = false>(options: Options<MediaExportData, ThrowOnError>): RequestResult<MediaExportResponses, MediaExportErrors, ThrowOnError> => (options.client ?? client).post<MediaExportResponses, MediaExportErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/media_export',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Read your account\n *\n * Who you are, your personal credits and plan, and each workspace you belong to with your role, its plan, the team's credits and your monthly spend limit there. Runs on a workspace canvas spend that workspace's credits if you belong to it; runs on a personal canvas, or a workspace canvas shared with you from outside, spend yours.\n */\nexport const accountGet = <ThrowOnError extends boolean = false>(options?: Options<AccountGetData, ThrowOnError>): RequestResult<AccountGetResponses, AccountGetErrors, ThrowOnError> => (options?.client ?? client).get<AccountGetResponses, AccountGetErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/account_get',\n ...options\n});\n\n/**\n * Find a saved tool\n *\n * Search the canvas's tool library (tools you or your workspace built) and Fuser's featured tools by title and description. Place a match with tool_build toolId. Only worth it when a tool for the job likely exists; building a new one with tool_build prompt is fine too.\n */\nexport const toolSearch = <ThrowOnError extends boolean = false>(options: Options<ToolSearchData, ThrowOnError>): RequestResult<ToolSearchResponses, ToolSearchErrors, ThrowOnError> => (options.client ?? client).get<ToolSearchResponses, ToolSearchErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/tool_search',\n ...options\n});\n\n/**\n * Build a tool\n *\n * Turn a Tool node (type UtilityNode, added with canvas_edit) into a working tool: describe it in prompt and Fuser writes its code, or place a saved one with toolId. Tools do what generators can't: join, cut, trim or speed up videos, mix audio, crop, grid, filter, measure and convert between images, video, audio, 3D models, text and JSON (not PDF, ZIP or other files). Call it again with a prompt to change a built tool, or with neither to check on a build. Once built, wire its input sockets and set its controls with canvas_edit, then run it like any node; free tools cost nothing to run.\n */\nexport const toolBuild = <ThrowOnError extends boolean = false>(options: Options<ToolBuildData, ThrowOnError>): RequestResult<ToolBuildResponses, ToolBuildErrors, ThrowOnError> => (options.client ?? client).post<ToolBuildResponses, ToolBuildErrors, ThrowOnError>({\n security: [{ name: 'x-api-key', type: 'apiKey' }, { scheme: 'bearer', type: 'http' }],\n url: '/v1/tool_build',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n","interface Page {\n nextCursor: string | null;\n}\n\n/**\n * A paged list: await it for the first page, or `for await` it for every\n * item on every page.\n */\nexport class PagePromise<P extends Page, I>\n implements PromiseLike<P>, AsyncIterable<I>\n{\n #first: Promise<P> | undefined;\n readonly #load: (cursor?: string) => Promise<P>;\n readonly #items: (page: P) => readonly I[];\n\n constructor(\n load: (cursor?: string) => Promise<P>,\n items: (page: P) => readonly I[],\n ) {\n this.#load = load;\n this.#items = items;\n }\n\n #firstPage(): Promise<P> {\n this.#first ??= this.#load();\n\n return this.#first;\n }\n\n then<A = P, B = never>(\n onfulfilled?: ((value: P) => A | PromiseLike<A>) | null,\n onrejected?: ((reason: unknown) => B | PromiseLike<B>) | null,\n ): Promise<A | B> {\n return this.#firstPage().then(onfulfilled, onrejected);\n }\n\n async *pages(): AsyncGenerator<P> {\n let page = await this.#firstPage();\n\n yield page;\n\n while (page.nextCursor) {\n page = await this.#load(page.nextCursor);\n\n yield page;\n }\n }\n\n async *[Symbol.asyncIterator](): AsyncGenerator<I> {\n for await (const page of this.pages()) {\n yield* this.#items(page);\n }\n }\n\n /** Every item on every page. */\n async all(): Promise<I[]> {\n const items: I[] = [];\n\n for await (const item of this) {\n items.push(item);\n }\n\n return items;\n }\n}\n","import {\n ConnectionError,\n errorFromResponse,\n FuserError,\n RunRefusedError,\n TimeoutError,\n} from './errors.js';\nimport { createClient } from './generated/client/index.js';\nimport * as sdk from './generated/sdk.gen.js';\nimport { PagePromise } from './pages.js';\n\nimport type { Client } from './generated/client/index.js';\n\ntype Sdk = typeof sdk;\n\n/** A generated operation, e.g. `canvasEdit`. */\ntype OperationKey = keyof Sdk;\n\ntype Snake<S extends string> = S extends `${infer Head}${infer Rest}`\n ? `${Head extends Lowercase<Head> ? Head : `_${Lowercase<Head>}`}${Snake<Rest>}`\n : S;\n\n/** An MCP tool and REST path name, e.g. `canvas_edit`. */\nexport type ToolName = Snake<OperationKey>;\n\ntype KeyOf<N extends ToolName> = {\n [K in OperationKey]: Snake<K> extends N ? K : never;\n}[OperationKey];\n\ntype OptionsOf<K extends OperationKey> = NonNullable<Parameters<Sdk[K]>[0]>;\n\ntype Field<K extends OperationKey, F extends 'body' | 'query'> =\n OptionsOf<K> extends { [P in F]?: infer V } ? NonNullable<V> : never;\n\ntype InOf<K extends OperationKey> = [Field<K, 'body'>] extends [never]\n ? 'query'\n : 'body';\n\ntype ArgsOf<K extends OperationKey> = [Field<K, InOf<K>>] extends [never]\n ? void\n : Field<K, InOf<K>>;\n\ntype ResultOf<K extends OperationKey> = Extract<\n Awaited<ReturnType<Sdk[K]>>,\n { error: undefined }\n>['data'];\n\n/** Exactly the arguments an agent passes to the MCP tool. */\nexport type ToolArgs<N extends ToolName> = ArgsOf<KeyOf<N>>;\n\n/** Exactly the JSON the MCP tool returns. */\nexport type ToolResult<N extends ToolName> = ResultOf<KeyOf<N>>;\n\ntype Resource = ToolName extends infer N\n ? N extends `${infer R}_${string}`\n ? R\n : never\n : never;\n\n/**\n * One namespace per resource and one method per tool: `canvas_list` is\n * `fuser.canvas.list()`. A new or renamed tool fails the build until the\n * class covers it.\n */\ntype Surface = {\n [R in Resource]: {\n [N in ToolName as N extends `${R}_${infer M}` ? M : never]: (\n args: ToolArgs<N>,\n options?: RequestOptions,\n ) => PromiseLike<ToolResult<N>>;\n };\n};\n\ntype Retry = 'transient' | 'rate-limit';\n\n// How each tool retries. Typed over every generated operation, so a new tool\n// needs a deliberate choice: `transient` retries 408, 429, 5xx and network\n// errors; `rate-limit` only 429, for calls that could do the work twice.\nconst OPERATIONS: {\n [K in OperationKey]: {\n in: InOf<K>;\n retry: Retry | ((args: ArgsOf<K>) => Retry);\n };\n} = {\n accountGet: { in: 'query', retry: 'transient' },\n canvasArrange: {\n in: 'body',\n retry: args =>\n args.expectedRevision === undefined ? 'transient' : 'rate-limit',\n },\n canvasEdit: { in: 'body', retry: 'transient' },\n canvasGet: { in: 'query', retry: 'transient' },\n canvasList: { in: 'query', retry: 'transient' },\n catalogSearch: { in: 'query', retry: 'transient' },\n mediaExport: { in: 'body', retry: 'transient' },\n mediaImport: { in: 'body', retry: 'rate-limit' },\n mediaSearch: { in: 'body', retry: 'transient' },\n mediaView: { in: 'body', retry: 'transient' },\n runCancel: { in: 'body', retry: 'transient' },\n runGet: { in: 'query', retry: 'transient' },\n runStart: { in: 'body', retry: 'transient' },\n toolBuild: {\n in: 'body',\n retry: args => (args.prompt || args.toolId ? 'rate-limit' : 'transient'),\n },\n toolSearch: { in: 'query', retry: 'transient' },\n uploadFinish: { in: 'body', retry: 'transient' },\n uploadStart: { in: 'body', retry: 'transient' },\n};\n\nconst RETRYABLE_STATUSES = new Set([408, 429, 500, 502, 503, 504]);\n\n/** upload_start takes at most this many files. */\nconst MAX_UPLOAD_FILES = 50;\n\n/** The server holds a waiting call open at most this long. */\nconst MAX_WAIT_SECONDS = 45;\n\n/** Runs answer sooner: the server waits at most this long on a run. */\nconst RUN_WAIT_SECONDS = 10;\n\n/** A longer Retry-After is the caller's call, not ours to sleep through. */\nconst MAX_RETRY_DELAY_MS = 60_000;\n\nexport interface RequestOptions {\n signal?: AbortSignal;\n /** Per attempt, on top of any `waitSeconds`. */\n timeoutMs?: number;\n maxRetries?: number;\n headers?: Record<string, string>;\n}\n\nexport interface WaitOptions {\n /** Give up after this long. Defaults to 30 minutes for runs, 10 for builds. */\n timeoutMs?: number;\n signal?: AbortSignal;\n}\n\nexport interface FuserOptions {\n /** Defaults to the `FUSER_API_KEY` environment variable. */\n apiKey?: string;\n /** Defaults to `https://api.fuser.studio`. */\n baseUrl?: string;\n fetch?: typeof fetch;\n /** Per attempt. Defaults to 60 seconds. */\n timeoutMs?: number;\n /** Defaults to 2. */\n maxRetries?: number;\n beforeSend?: (request: Request) => Request | void | Promise<Request | void>;\n afterSend?: (response: Response, request: Request) => void | Promise<void>;\n /** An API key acts as you; only set this if the page is yours alone. */\n dangerouslyAllowBrowser?: boolean;\n}\n\ntype RunStartResult = ToolResult<'run_start'>;\ntype RunSummary = ToolResult<'run_get'>;\ntype ToolBuildResult = ToolResult<'tool_build'>;\ntype UploadedFile = ToolResult<'upload_finish'>['files'][number];\n\nabstract class StartedCall<T> implements PromiseLike<T> {\n protected readonly started: Promise<T>;\n\n constructor(started: Promise<T>) {\n this.started = started;\n }\n\n then<A = T, B = never>(\n onfulfilled?: ((value: T) => A | PromiseLike<A>) | null,\n onrejected?: ((reason: unknown) => B | PromiseLike<B>) | null,\n ): Promise<A | B> {\n return this.started.then(onfulfilled, onrejected);\n }\n}\n\n/** `run.start()`: await for the start result, or `.wait()` for the finished run. */\nexport class RunCall extends StartedCall<RunStartResult> {\n readonly #wait: (runId: string, options?: WaitOptions) => Promise<RunSummary>;\n\n constructor(\n started: Promise<RunStartResult>,\n wait: (runId: string, options?: WaitOptions) => Promise<RunSummary>,\n ) {\n super(started);\n this.#wait = wait;\n }\n\n /** The run once it stops running. Throws if it was refused or only priced. */\n async wait(options?: WaitOptions): Promise<RunSummary> {\n const timeoutMs = options?.timeoutMs ?? 30 * 60_000;\n const startedAt = Date.now();\n\n const scope = deadline(\n timeoutMs,\n options?.signal,\n 'The run is still starting.',\n 'run_start',\n );\n\n const result = await scope.guard(this.started);\n\n if (result.status === 'refused') {\n throw new RunRefusedError(result.error, {\n tool: 'run_start',\n reason: result.reason,\n body: result,\n });\n }\n\n if (result.status === 'quoted') {\n throw new FuserError(\n 'A dry run only prices the run; nothing to wait for.',\n {\n tool: 'run_start',\n body: result,\n },\n );\n }\n\n if (result.run && result.run.status !== 'running') {\n return result.run;\n }\n\n return this.#wait(result.runId, {\n signal: options?.signal,\n timeoutMs: Math.max(timeoutMs - (Date.now() - startedAt), 1),\n });\n }\n}\n\n/** `tool.build()`: await for its state now, or `.wait()` until it's built. */\nexport class ToolBuildCall extends StartedCall<ToolBuildResult> {\n readonly #check: (signal?: AbortSignal) => Promise<ToolBuildResult>;\n\n constructor(\n started: Promise<ToolBuildResult>,\n check: (signal?: AbortSignal) => Promise<ToolBuildResult>,\n ) {\n super(started);\n this.#check = check;\n }\n\n /** The tool once its build stops; check `status` for built or failed. */\n async wait(options?: WaitOptions): Promise<ToolBuildResult> {\n const scope = deadline(\n options?.timeoutMs ?? 10 * 60_000,\n options?.signal,\n 'The tool is still building.',\n 'tool_build',\n );\n\n let state = await scope.guard(this.started);\n\n while (state.status === 'building') {\n options?.signal?.throwIfAborted();\n\n if (scope.expired()) {\n throw scope.timeout();\n }\n\n state = await scope.guard(this.#check(scope.signal));\n }\n\n return state;\n }\n}\n\nexport interface UploadInput {\n fileName: string;\n data: Blob | ArrayBuffer | Uint8Array;\n /** Required unless `data` is a Blob with a type. */\n contentType?: string;\n}\n\nconst toCamel = (name: string) =>\n name.replace(/_([a-z])/g, (_, letter: string) => letter.toUpperCase());\n\nconst toSnake = (key: string) =>\n key.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);\n\nconst sleep = (ms: number, signal?: AbortSignal) =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason);\n\n return;\n }\n\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n\nfunction base64(bytes: Uint8Array): string {\n let binary = '';\n\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n\n return btoa(binary);\n}\n\nconst withSignal = (signal: AbortSignal | undefined, other: AbortSignal) =>\n signal ? AbortSignal.any([signal, other]) : other;\n\nconst mergeSignals = (\n first: AbortSignal | undefined,\n second: AbortSignal | undefined,\n) => (first && second ? AbortSignal.any([first, second]) : (first ?? second));\n\n/** One deadline for a whole wait: every poll and retry shares its signal. */\nfunction deadline(\n timeoutMs: number,\n signal: AbortSignal | undefined,\n message: string,\n tool: string,\n) {\n const timer = AbortSignal.timeout(timeoutMs);\n\n const expired = () => timer.aborted && !signal?.aborted;\n\n const timeout = (cause?: unknown) =>\n new TimeoutError(message, { tool, cause });\n\n return {\n signal: withSignal(signal, timer),\n expired,\n timeout,\n /** `work`, or a timeout or abort as soon as either fires, whichever is first. */\n async guard<T>(work: Promise<T>): Promise<T> {\n const combined = withSignal(signal, timer);\n\n let stop = () => {};\n\n const stopped = new Promise<never>((_, reject) => {\n stop = () =>\n reject(expired() ? timeout() : (signal?.reason ?? timeout()));\n\n if (combined.aborted) {\n stop();\n } else {\n combined.addEventListener('abort', stop, { once: true });\n }\n });\n\n // Settles after `work` wins too; nothing is waiting on it then.\n stopped.catch(() => undefined);\n\n try {\n return await Promise.race([work, stopped]);\n } catch (error) {\n throw expired() && !(error instanceof TimeoutError)\n ? timeout(error)\n : error;\n } finally {\n combined.removeEventListener('abort', stop);\n }\n },\n };\n}\n\n/**\n * The Fuser API. Each tool is a method named after it: `canvas_edit` is\n * `fuser.canvas.edit()`, with the same arguments and result as the MCP tool.\n */\nexport class Fuser implements Surface {\n readonly client: Client;\n readonly #fetch: typeof fetch;\n readonly #timeoutMs: number;\n readonly #maxRetries: number;\n\n readonly account = {\n get: (_args?: void, options?: RequestOptions) =>\n this.#request('accountGet', undefined, options),\n };\n\n readonly canvas = {\n /** Await for a page, or `for await` for every canvas. */\n list: (args?: ToolArgs<'canvas_list'>, options?: RequestOptions) =>\n this.#pages('canvasList', args ?? {}, page => page.canvases, options),\n /** Await for a page, or `for await` for every node. */\n get: (args: ToolArgs<'canvas_get'>, options?: RequestOptions) =>\n this.#pages('canvasGet', args, page => page.nodes, options),\n /** `idempotencyKey` defaults to a new one per call. */\n edit: (\n args: Omit<ToolArgs<'canvas_edit'>, 'idempotencyKey'> & {\n idempotencyKey?: string;\n },\n options?: RequestOptions,\n ) => this.#request('canvasEdit', args as ToolArgs<'canvas_edit'>, options),\n arrange: (args: ToolArgs<'canvas_arrange'>, options?: RequestOptions) =>\n this.#request('canvasArrange', args, options),\n };\n\n readonly catalog = {\n search: (args?: ToolArgs<'catalog_search'>, options?: RequestOptions) =>\n this.#request('catalogSearch', args ?? {}, options),\n };\n\n readonly run = {\n /** `idempotencyKey` defaults to a new one per call. Add `.wait()` to wait. */\n start: (args: ToolArgs<'run_start'>, options?: RequestOptions) =>\n new RunCall(\n this.#request('runStart', args, options),\n (runId, waitOptions) =>\n this.#waitForRun(\n { canvasId: args.canvasId, runId },\n {\n ...waitOptions,\n signal: mergeSignals(options?.signal, waitOptions?.signal),\n },\n ),\n ),\n get: (args: ToolArgs<'run_get'>, options?: RequestOptions) =>\n this.#request('runGet', args, options),\n cancel: (args: ToolArgs<'run_cancel'>, options?: RequestOptions) =>\n this.#request('runCancel', args, options),\n /** Checks a run until it stops running. */\n wait: (args: { canvasId: string; runId: string }, options?: WaitOptions) =>\n this.#waitForRun(args, options),\n };\n\n readonly media = {\n export: (args: ToolArgs<'media_export'>, options?: RequestOptions) =>\n this.#request('mediaExport', args, options),\n import: (args: ToolArgs<'media_import'>, options?: RequestOptions) =>\n this.#request('mediaImport', args, options),\n /** Await for a page, or `for await` for every match. */\n search: (args: ToolArgs<'media_search'>, options?: RequestOptions) =>\n this.#pages('mediaSearch', args, page => page.assets, options),\n view: (args: ToolArgs<'media_view'>, options?: RequestOptions) =>\n this.#request('mediaView', args, options),\n };\n\n readonly upload = {\n start: (args: ToolArgs<'upload_start'>, options?: RequestOptions) =>\n this.#request('uploadStart', args, options),\n finish: (args: ToolArgs<'upload_finish'>, options?: RequestOptions) =>\n this.#request('uploadFinish', args, options),\n /** Hashes, starts, sends and finishes in one call. */\n files: (canvasId: string, files: UploadInput[], options?: RequestOptions) =>\n this.#uploadFiles(canvasId, files, options),\n };\n\n readonly tool = {\n search: (args: ToolArgs<'tool_search'>, options?: RequestOptions) =>\n this.#request('toolSearch', args, options),\n /** Add `.wait()` to wait until it's built. */\n build: (args: ToolArgs<'tool_build'>, options?: RequestOptions) => {\n const { canvasId, nodeId } = args;\n\n return new ToolBuildCall(\n this.#request('toolBuild', args, options),\n signal =>\n this.#request(\n 'toolBuild',\n { canvasId, nodeId, waitSeconds: MAX_WAIT_SECONDS },\n {\n ...options,\n ...(signal\n ? { signal: withSignal(options?.signal, signal) }\n : {}),\n },\n ),\n );\n },\n };\n\n constructor(options: FuserOptions = {}) {\n const apiKey =\n options.apiKey ??\n (globalThis as { process?: { env?: Record<string, string | undefined> } })\n .process?.env?.FUSER_API_KEY;\n\n if (\n 'document' in globalThis &&\n 'window' in globalThis &&\n !options.dangerouslyAllowBrowser\n ) {\n throw new FuserError(\n 'A Fuser API key acts as you, so keep it on a server. Pass dangerouslyAllowBrowser to use it in a browser anyway.',\n { tool: 'client' },\n );\n }\n\n this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.#timeoutMs = options.timeoutMs ?? 60_000;\n this.#maxRetries = options.maxRetries ?? 2;\n\n this.client = createClient({\n baseUrl: options.baseUrl ?? 'https://api.fuser.studio',\n fetch: this.#fetch,\n auth: scheme => (scheme.scheme === 'bearer' ? apiKey : undefined),\n });\n\n const { beforeSend, afterSend } = options;\n\n if (beforeSend) {\n this.client.interceptors.request.use(\n async request => (await beforeSend(request)) ?? request,\n );\n }\n\n if (afterSend) {\n this.client.interceptors.response.use(async (response, request) => {\n await afterSend(response, request);\n\n return response;\n });\n }\n }\n\n /** Calls a tool by its MCP name, with the exact arguments an agent sent. */\n call<N extends ToolName>(\n name: N,\n args: ToolArgs<N>,\n options?: RequestOptions,\n ): Promise<ToolResult<N>> {\n return this.#request(toCamel(name) as KeyOf<N>, args, options);\n }\n\n #pages<K extends OperationKey, I>(\n key: K,\n args: ArgsOf<K> & { cursor?: string },\n items: (page: ResultOf<K> & { nextCursor: string | null }) => readonly I[],\n options?: RequestOptions,\n ) {\n return new PagePromise(\n async cursor =>\n (await this.#request(\n key,\n { ...args, cursor: cursor ?? args.cursor },\n options,\n )) as ResultOf<K> & { nextCursor: string | null },\n items,\n );\n }\n\n async #waitForRun(\n args: { canvasId: string; runId: string },\n options?: WaitOptions,\n ): Promise<RunSummary> {\n const scope = deadline(\n options?.timeoutMs ?? 30 * 60_000,\n options?.signal,\n `Run ${args.runId} is still running.`,\n 'run_get',\n );\n\n for (;;) {\n const summary = await scope.guard(\n this.run.get(\n { ...args, waitSeconds: RUN_WAIT_SECONDS },\n { signal: scope.signal },\n ),\n );\n\n if (summary.status !== 'running') {\n return summary;\n }\n\n options?.signal?.throwIfAborted();\n\n if (scope.expired()) {\n throw scope.timeout();\n }\n }\n }\n\n async #uploadFiles(\n canvasId: string,\n inputs: UploadInput[],\n options?: RequestOptions,\n ): Promise<UploadedFile[]> {\n const uploaded: UploadedFile[] = [];\n\n for (let start = 0; start < inputs.length; start += MAX_UPLOAD_FILES) {\n uploaded.push(\n ...(await this.#uploadBatch(\n canvasId,\n inputs.slice(start, start + MAX_UPLOAD_FILES),\n options,\n )),\n );\n }\n\n return uploaded;\n }\n\n async #uploadBatch(\n canvasId: string,\n inputs: UploadInput[],\n options?: RequestOptions,\n ): Promise<UploadedFile[]> {\n const prepared = await Promise.all(\n inputs.map(async input => {\n const bytes =\n input.data instanceof Blob\n ? new Uint8Array(await input.data.arrayBuffer())\n : new Uint8Array(input.data);\n\n const contentType =\n input.contentType ||\n (input.data instanceof Blob ? input.data.type : '');\n\n if (!contentType) {\n throw new FuserError(`${input.fileName} needs a contentType.`, {\n tool: 'upload_start',\n });\n }\n\n const digest = await crypto.subtle.digest('SHA-256', bytes);\n\n return {\n bytes,\n file: {\n fileName: input.fileName,\n contentType,\n size: bytes.byteLength,\n sha256: base64(new Uint8Array(digest)),\n },\n };\n }),\n );\n\n const started = await this.upload.start(\n { canvasId, files: prepared.map(item => item.file) },\n options,\n );\n\n const sent = new Set<string>();\n // A failed PUT is reported on its file, as the docs promise; only an\n // abort stops the batch.\n const putErrors: (string | undefined)[] = [];\n\n await Promise.all(\n started.files.map(async (file, index) => {\n if (file.status === 'done' || sent.has(file.url)) {\n return;\n }\n\n sent.add(file.url);\n\n const timeout = AbortSignal.timeout(\n options?.timeoutMs ?? this.#timeoutMs,\n );\n\n try {\n const response = await this.#fetch(file.url, {\n method: file.method,\n headers: file.headers,\n body: prepared[index]!.bytes,\n signal: withSignal(options?.signal, timeout),\n });\n\n if (!response.ok && response.status !== 412) {\n putErrors[index] =\n `Uploading ${file.fileName} failed (HTTP ${String(response.status)}).`;\n }\n } catch {\n options?.signal?.throwIfAborted();\n\n putErrors[index] = timeout.aborted\n ? `Uploading ${file.fileName} timed out.`\n : `Uploading ${file.fileName} failed: the connection dropped.`;\n }\n }),\n );\n\n const finished = await this.upload.finish(\n { uploadId: started.uploadId },\n options,\n );\n\n return finished.files.map((file, index) =>\n file.status === 'failed' && putErrors[index]\n ? { ...file, error: putErrors[index] }\n : file,\n );\n }\n\n async #request<K extends OperationKey>(\n key: K,\n args: ArgsOf<K>,\n options: RequestOptions = {},\n ): Promise<ResultOf<K>> {\n const tool = toSnake(key);\n\n const operation = OPERATIONS[key] as {\n in: 'body' | 'query';\n retry: Retry | ((args: unknown) => Retry);\n };\n\n const policy =\n typeof operation.retry === 'function'\n ? operation.retry(args)\n : operation.retry;\n\n const keyed =\n key === 'canvasEdit' ||\n (key === 'runStart' && !(args as { dryRun?: boolean }).dryRun);\n\n const body = keyed\n ? {\n ...args,\n idempotencyKey:\n (args as { idempotencyKey?: string }).idempotencyKey ??\n crypto.randomUUID(),\n }\n : args;\n\n const send = sdk[key] as unknown as (options: object) => Promise<{\n data?: unknown;\n error?: unknown;\n response?: Response;\n }>;\n\n const waitSeconds = Math.min(\n (args as { waitSeconds?: number } | undefined)?.waitSeconds ??\n (key === 'toolBuild' ? MAX_WAIT_SECONDS : 0),\n MAX_WAIT_SECONDS,\n );\n\n const timeoutMs =\n (options.timeoutMs ?? this.#timeoutMs) + waitSeconds * 1000;\n\n const maxRetries = options.maxRetries ?? this.#maxRetries;\n\n for (let attempt = 0; ; attempt++) {\n const timeout = AbortSignal.timeout(timeoutMs);\n\n const result = await send({\n client: this.client,\n ...(body === undefined ? {} : { [operation.in]: body }),\n ...(options.headers ? { headers: options.headers } : {}),\n signal: withSignal(options.signal, timeout),\n });\n\n if (result.error === undefined && result.response?.ok) {\n return result.data as ResultOf<K>;\n }\n\n options.signal?.throwIfAborted();\n\n const error =\n result.response && !result.response.ok\n ? errorFromResponse(tool, result.response, result.error)\n : timeout.aborted\n ? new TimeoutError(`${tool} timed out.`, {\n tool,\n cause: result.error,\n })\n : new ConnectionError(`${tool} could not reach Fuser.`, {\n tool,\n cause: result.error,\n });\n\n const retryable =\n error.status === undefined\n ? policy === 'transient'\n : policy === 'transient'\n ? RETRYABLE_STATUSES.has(error.status)\n : error.status === 429;\n\n const delay =\n error.retryAfterMs ??\n Math.min(8000, 500 * 2 ** attempt) * (0.75 + Math.random() / 2);\n\n if (!retryable || attempt >= maxRetries || delay > MAX_RETRY_DELAY_MS) {\n throw error;\n }\n\n await sleep(delay, options.signal);\n }\n }\n}\n"],"mappings":";;;AAkBA,IAAa,aAAb,cAAgC,MAAM;CACpC,OAAgB;CAChB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,SAAiB,SAA4B;EACvD,MAAM,SAAS,EAAE,OAAO,QAAQ,MAAM,CAAC;EACvC,KAAK,OAAO,QAAQ;EACpB,KAAK,SAAS,QAAQ;EACtB,KAAK,OAAO,QAAQ;EACpB,KAAK,SAAS,QAAQ;EACtB,KAAK,SAAS,QAAQ;EACtB,KAAK,YAAY,QAAQ;EACzB,KAAK,eAAe,QAAQ;EAC5B,KAAK,OAAO,QAAQ;CACtB;AACF;AAEA,IAAa,kBAAb,cAAqC,WAAW;CAC9C,OAAgB;AAClB;AAEA,IAAa,sBAAb,cAAyC,WAAW;CAClD,OAAgB;AAClB;AAEA,IAAa,wBAAb,cAA2C,WAAW;CACpD,OAAgB;AAClB;AAEA,IAAa,gBAAb,cAAmC,WAAW;CAC5C,OAAgB;AAClB;AAEA,IAAa,gBAAb,cAAmC,WA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Q,IAAI,CAAC;IACtD,QAAQ,WAAW,QAAQ,QAAQ,OAAO;GAC5C,CAAC;GAED,IAAI,OAAO,UAAU,KAAA,KAAa,OAAO,UAAU,IACjD,OAAO,OAAO;GAGhB,QAAQ,QAAQ,eAAe;GAE/B,MAAM,QACJ,OAAO,YAAY,CAAC,OAAO,SAAS,KAChC,kBAAkB,MAAM,OAAO,UAAU,OAAO,KAAK,IACrD,QAAQ,UACN,IAAI,aAAa,GAAG,KAAK,cAAc;IACrC;IACA,OAAO,OAAO;GAChB,CAAC,IACD,IAAI,gBAAgB,GAAG,KAAK,0BAA0B;IACpD;IACA,OAAO,OAAO;GAChB,CAAC;GAET,MAAM,YACJ,MAAM,WAAW,KAAA,IACb,WAAW,cACX,WAAW,cACT,mBAAmB,IAAI,MAAM,MAAM,IACnC,MAAM,WAAW;GAEzB,MAAM,QACJ,MAAM,gBACN,KAAK,IAAI,KAAM,MAAM,KAAK,OAAO,KAAK,MAAO,KAAK,OAAO,IAAI;GAE/D,IAAI,CAAC,aAAa,WAAW,cAAc,QAAQ,oBACjD,MAAM;GAGR,MAAM,MAAM,OAAO,QAAQ,MAAM;EACnC;CACF;AACF"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@fuserstudio/sdk",
3
- "version": "0.0.2",
4
- "description": "TypeScript SDK for the Fuser API.",
3
+ "version": "0.0.4",
4
+ "description": "Official TypeScript SDK for the Fuser API: build and run AI image, video, audio and 3D canvases from code.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "exports": {