@keln.ai/sdk 0.0.0-stage → 0.1.0

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.
Files changed (77) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +6 -0
  4. package/README.md +598 -2
  5. package/dist/api-promise.d.ts +30 -0
  6. package/dist/api-promise.js +38 -0
  7. package/dist/api-promise.js.map +1 -0
  8. package/dist/api.d.ts +130 -0
  9. package/dist/api.js +321 -0
  10. package/dist/api.js.map +1 -0
  11. package/dist/client.d.ts +27 -0
  12. package/dist/client.js +42 -0
  13. package/dist/client.js.map +1 -0
  14. package/dist/commands.d.ts +78 -0
  15. package/dist/commands.js +269 -0
  16. package/dist/commands.js.map +1 -0
  17. package/dist/errors.d.ts +93 -0
  18. package/dist/errors.js +173 -0
  19. package/dist/errors.js.map +1 -0
  20. package/dist/files.d.ts +33 -0
  21. package/dist/files.js +130 -0
  22. package/dist/files.js.map +1 -0
  23. package/dist/images.d.ts +79 -0
  24. package/dist/images.js +150 -0
  25. package/dist/images.js.map +1 -0
  26. package/dist/index.d.ts +23 -0
  27. package/dist/index.js +14 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/inference.d.ts +672 -0
  30. package/dist/inference.js +244 -0
  31. package/dist/inference.js.map +1 -0
  32. package/dist/retry.d.ts +10 -0
  33. package/dist/retry.js +87 -0
  34. package/dist/retry.js.map +1 -0
  35. package/dist/sandbox.d.ts +132 -0
  36. package/dist/sandbox.js +216 -0
  37. package/dist/sandbox.js.map +1 -0
  38. package/dist/sse.d.ts +20 -0
  39. package/dist/sse.js +119 -0
  40. package/dist/sse.js.map +1 -0
  41. package/dist/streaming.d.ts +20 -0
  42. package/dist/streaming.js +77 -0
  43. package/dist/streaming.js.map +1 -0
  44. package/dist/terminals.d.ts +75 -0
  45. package/dist/terminals.js +239 -0
  46. package/dist/terminals.js.map +1 -0
  47. package/dist/types.d.ts +226 -0
  48. package/dist/types.js +6 -0
  49. package/dist/types.js.map +1 -0
  50. package/dist/uploads.d.ts +35 -0
  51. package/dist/uploads.js +154 -0
  52. package/dist/uploads.js.map +1 -0
  53. package/dist/util.d.ts +19 -0
  54. package/dist/util.js +69 -0
  55. package/dist/util.js.map +1 -0
  56. package/dist/web.d.ts +66 -0
  57. package/dist/web.js +44 -0
  58. package/dist/web.js.map +1 -0
  59. package/package.json +57 -4
  60. package/src/api-promise.ts +50 -0
  61. package/src/api.ts +415 -0
  62. package/src/client.ts +43 -0
  63. package/src/commands.ts +325 -0
  64. package/src/errors.ts +185 -0
  65. package/src/files.ts +149 -0
  66. package/src/images.ts +174 -0
  67. package/src/index.ts +114 -0
  68. package/src/inference.ts +737 -0
  69. package/src/retry.ts +77 -0
  70. package/src/sandbox.ts +281 -0
  71. package/src/sse.ts +124 -0
  72. package/src/streaming.ts +79 -0
  73. package/src/terminals.ts +269 -0
  74. package/src/types.ts +241 -0
  75. package/src/uploads.ts +177 -0
  76. package/src/util.ts +78 -0
  77. package/src/web.ts +94 -0
@@ -0,0 +1,269 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ import type WebSocket from 'ws';
3
+ import type { Api } from './api.js';
4
+ import { apiError } from './errors.js';
5
+ import type { CallOptions, ListData, TerminalData, TerminalState } from './types.js';
6
+ import { sandboxPath } from './util.js';
7
+
8
+ /** A terminal socket's frames: the first byte of each says what it is. */
9
+ const OP_DATA = 0x00;
10
+ const OP_RESIZE = 0x01;
11
+ const OP_EXIT = 0x03;
12
+ /** Unread output frames before the socket stops reading: a slow reader slows the program, not fills memory. */
13
+ const PAUSE_AT_FRAMES = 1024;
14
+
15
+ export type TerminalCreateOptions = CallOptions & {
16
+ /** A shell line, run through `bash -lc`. Without `command` or `argv` the terminal runs a login shell. */
17
+ command?: string;
18
+ /** The program and its arguments, run directly. */
19
+ argv?: string[];
20
+ /** Absolute. Defaults to the user's home. */
21
+ cwd?: string;
22
+ env?: Record<string, string>;
23
+ /** Default 80. */
24
+ cols?: number;
25
+ /** Default 24. */
26
+ rows?: number;
27
+ };
28
+
29
+ /**
30
+ * An open socket to a terminal: `send` input, `resize` it, iterate its output bytes. Iterating ends when the program
31
+ * exits, with its code in `exitCode`, or after `close()`. A socket dropped before that throws `KelnConnectionError`;
32
+ * the program may still run, and `terminal.attach()` opens a new socket. An aborted signal ends it with its reason.
33
+ */
34
+ export class TerminalSocket implements AsyncIterable<Uint8Array> {
35
+ /** The program's exit code, once the socket has ended, if the API sent one. */
36
+ exitCode: number | undefined;
37
+ readonly #api: Api;
38
+ readonly #socket: WebSocket;
39
+ readonly #output: Uint8Array[] = [];
40
+ #wake: (() => void) | undefined;
41
+ #ended = false;
42
+ #closing = false;
43
+ #failure: unknown;
44
+ readonly #opened = Promise.withResolvers<void>();
45
+ readonly #closed = Promise.withResolvers<void>();
46
+
47
+ /** Every listener goes on before the socket connects: a first frame can arrive with the upgrade's answer. */
48
+ private constructor(api: Api, socket: WebSocket, signal: AbortSignal | undefined) {
49
+ this.#api = api;
50
+ this.#socket = socket;
51
+ this.#opened.promise.catch(() => {});
52
+ socket.binaryType = 'nodebuffer';
53
+ const onAbort = (): void => {
54
+ this.#failure = signal?.reason;
55
+ this.#output.length = 0;
56
+ this.#opened.reject(signal?.reason);
57
+ socket.terminate();
58
+ };
59
+ signal?.addEventListener('abort', onAbort, { once: true });
60
+ socket.on('open', () => this.#opened.resolve());
61
+ socket.on('unexpected-response', (_request, response) => this.#refused(response));
62
+ socket.on('error', (error: Error) => this.#fail(error));
63
+ socket.on('message', (data: Buffer, isBinary: boolean) => this.#frame(data, isBinary));
64
+ socket.on('close', (code: number, reason: Buffer) => {
65
+ signal?.removeEventListener('abort', onAbort);
66
+ this.#ended = true;
67
+ // The service closes with `exit:<code>` after the exit frame, and the close alone can carry it.
68
+ const exit = /^exit:(-?\d+)$/.exec(reason.toString('utf8'));
69
+ if (exit !== null) this.exitCode ??= Number(exit[1]);
70
+ if (code !== 1000 && this.exitCode === undefined && !this.#closing) this.#fail(`the socket closed with code ${code}`);
71
+ this.#opened.reject(this.#failure);
72
+ this.#closed.resolve();
73
+ this.#wake?.();
74
+ });
75
+ }
76
+
77
+ /** Attaches, with the retries a read gets. Used by `terminal.attach()`. */
78
+ static async open(api: Api, path: string, signal: AbortSignal | undefined): Promise<TerminalSocket> {
79
+ return await api.retrying(true, signal, async () => {
80
+ signal?.throwIfAborted();
81
+ const socket = new TerminalSocket(api, api.webSocket(path), signal);
82
+ await socket.#opened.promise;
83
+ return socket;
84
+ });
85
+ }
86
+
87
+ /** A refused upgrade: the API's answer, read whole, with its headers. */
88
+ #refused(response: IncomingMessage): void {
89
+ const chunks: Buffer[] = [];
90
+ response.on('data', (chunk: Buffer) => chunks.push(chunk));
91
+ response.on('end', () => {
92
+ const text = this.#api.redact(Buffer.concat(chunks).toString('utf8'));
93
+ const headers = new Headers();
94
+ for (const [name, value] of Object.entries(response.headers)) {
95
+ for (const one of Array.isArray(value) ? value : value === undefined ? [] : [value]) headers.append(name, one);
96
+ }
97
+ const retryAfter = response.headers['retry-after'];
98
+ this.#failure = apiError(response.statusCode, text, Array.isArray(retryAfter) ? retryAfter[0] : retryAfter, headers);
99
+ this.#opened.reject(this.#failure);
100
+ this.#socket.terminate();
101
+ });
102
+ response.on('error', (error: Error) => {
103
+ this.#fail(error);
104
+ this.#socket.terminate();
105
+ });
106
+ }
107
+
108
+ #fail(cause: unknown): void {
109
+ this.#failure ??= this.#api.connectionError(cause);
110
+ this.#opened.reject(this.#failure);
111
+ }
112
+
113
+ #frame(data: Buffer, isBinary: boolean): void {
114
+ if (!isBinary) return; // text frames and unknown opcodes are not part of the protocol
115
+ if (data[0] === OP_DATA && data.length > 1) {
116
+ this.#output.push(new Uint8Array(data.subarray(1)));
117
+ if (this.#output.length >= PAUSE_AT_FRAMES) this.#socket.pause();
118
+ this.#wake?.();
119
+ } else if (data[0] === OP_EXIT && data.length >= 5) {
120
+ this.exitCode = data.readInt32BE(1);
121
+ void this.close(); // the last frame. The server closes next; a late frame is still read until it does
122
+ }
123
+ }
124
+
125
+ #write(frame: Uint8Array): Promise<void> {
126
+ return new Promise((resolve, reject) => {
127
+ this.#socket.send(frame, { binary: true }, (error) => {
128
+ if (error === undefined || error === null) resolve();
129
+ else reject(this.#api.connectionError(error));
130
+ });
131
+ });
132
+ }
133
+
134
+ /** Sends input to the program. */
135
+ async send(data: Uint8Array | string): Promise<void> {
136
+ const bytes = typeof data === 'string' ? new TextEncoder().encode(data) : data;
137
+ const frame = new Uint8Array(bytes.length + 1);
138
+ frame[0] = OP_DATA;
139
+ frame.set(bytes, 1);
140
+ await this.#write(frame);
141
+ }
142
+
143
+ /** Resizes the terminal. */
144
+ async resize(cols: number, rows: number): Promise<void> {
145
+ const frame = Buffer.alloc(5);
146
+ frame[0] = OP_RESIZE;
147
+ frame.writeUInt16BE(cols, 1);
148
+ frame.writeUInt16BE(rows, 3);
149
+ await this.#write(frame);
150
+ }
151
+
152
+ /** Closes the socket. The program keeps running; `terminal.kill()` ends it. */
153
+ async close(): Promise<void> {
154
+ this.#closing = true;
155
+ this.#socket.resume(); // a paused socket would never read the close it is waiting for
156
+ this.#socket.close();
157
+ await this.#closed.promise;
158
+ }
159
+
160
+ async *[Symbol.asyncIterator](): AsyncGenerator<Uint8Array> {
161
+ while (true) {
162
+ const chunk = this.#output.shift();
163
+ if (chunk !== undefined) {
164
+ if (this.#output.length === 0) this.#socket.resume();
165
+ yield chunk;
166
+ } else if (this.#ended) {
167
+ if (this.#failure !== undefined) throw this.#failure;
168
+ return;
169
+ } else {
170
+ await new Promise<void>((resolve) => {
171
+ this.#wake = resolve;
172
+ });
173
+ }
174
+ }
175
+ }
176
+ }
177
+
178
+ /** One terminal. Its fields are the API's, as of the last answer. */
179
+ export class Terminal {
180
+ id!: string;
181
+ object!: string;
182
+ sandboxId!: string;
183
+ state!: TerminalState;
184
+ cols!: number;
185
+ rows!: number;
186
+ exitCode!: number | null;
187
+ createdAt!: number;
188
+ endedAt!: number | null;
189
+ /** The object as the API sent it. */
190
+ raw!: TerminalData;
191
+ readonly #api: Api;
192
+
193
+ /** Made by `sandbox.terminals`. */
194
+ constructor(api: Api, data: TerminalData) {
195
+ this.#api = api;
196
+ this.#apply(data);
197
+ }
198
+
199
+ #apply(data: TerminalData): this {
200
+ this.raw = data;
201
+ this.id = data.id;
202
+ this.object = data.object;
203
+ this.sandboxId = data.sandbox_id;
204
+ this.state = data.state;
205
+ this.cols = data.cols;
206
+ this.rows = data.rows;
207
+ this.exitCode = data.exit_code ?? null;
208
+ this.createdAt = data.created_at;
209
+ this.endedAt = data.ended_at ?? null;
210
+ return this;
211
+ }
212
+
213
+ get #path(): string {
214
+ return `${sandboxPath(this.sandboxId)}/terminals/${encodeURIComponent(this.id)}`;
215
+ }
216
+
217
+ /**
218
+ * Opens a socket to the terminal. A terminal can be attached again after a disconnect; a socket receives the
219
+ * output written while it is attached. The signal stays with the socket: aborting it later ends the socket.
220
+ */
221
+ async attach(options: CallOptions = {}): Promise<TerminalSocket> {
222
+ return await TerminalSocket.open(this.#api, `${this.#path}/ws`, options.signal);
223
+ }
224
+
225
+ /** Reads the terminal again and updates this object. */
226
+ async refresh(options: CallOptions = {}): Promise<this> {
227
+ return this.#apply(await this.#api.json<TerminalData>('GET', this.#path, options));
228
+ }
229
+
230
+ /** Resizes the terminal, the same as a resize frame on a socket. */
231
+ async resize(cols: number, rows: number, options: CallOptions = {}): Promise<this> {
232
+ const path = `${this.#path}/resize`;
233
+ return this.#apply(await this.#api.json<TerminalData>('POST', path, { ...options, json: { cols, rows } }));
234
+ }
235
+
236
+ /** Ends the terminal's program. Ending an exited terminal changes nothing. */
237
+ async kill(options: CallOptions = {}): Promise<this> {
238
+ return this.#apply(await this.#api.json<TerminalData>('DELETE', this.#path, options));
239
+ }
240
+ }
241
+
242
+ /** The terminals of one sandbox: `sandbox.terminals`. */
243
+ export class Terminals {
244
+ readonly #api: Api;
245
+ readonly #path: string;
246
+
247
+ /** Made by `Sandbox`. */
248
+ constructor(api: Api, sandboxId: string) {
249
+ this.#api = api;
250
+ this.#path = `${sandboxPath(sandboxId)}/terminals`;
251
+ }
252
+
253
+ /** Starts a program on a pseudo-terminal. Attach to it with `terminal.attach()`. */
254
+ async create(options: TerminalCreateOptions = {}): Promise<Terminal> {
255
+ const { signal, ...json } = options;
256
+ return new Terminal(this.#api, await this.#api.json<TerminalData>('POST', this.#path, { json, signal }));
257
+ }
258
+
259
+ /** The sandbox's terminals, oldest first. */
260
+ async list(options: CallOptions = {}): Promise<Terminal[]> {
261
+ const page = await this.#api.json<ListData<TerminalData>>('GET', this.#path, options);
262
+ return page.data.map((data) => new Terminal(this.#api, data));
263
+ }
264
+
265
+ async get(terminalId: string, options: CallOptions = {}): Promise<Terminal> {
266
+ const path = `${this.#path}/${encodeURIComponent(terminalId)}`;
267
+ return new Terminal(this.#api, await this.#api.json<TerminalData>('GET', path, options));
268
+ }
269
+ }
package/src/types.ts ADDED
@@ -0,0 +1,241 @@
1
+ /**
2
+ * The Keln Sandbox API's shapes. The `*Data` types are what the API sends, snake_case, as `raw` holds them; a field
3
+ * added later is reachable through the index signature.
4
+ */
5
+
6
+ /** Every call takes one. Aborting it ends the call with the signal's reason. */
7
+ export type CallOptions = { signal?: AbortSignal };
8
+
9
+ /** `starting`, `running`, `paused`, `stopped`, or a state added later, passed through as a string. */
10
+ export type SandboxState = 'starting' | 'running' | 'paused' | 'stopped' | (string & {});
11
+ /** `running`, `exited`, or a state added later, passed through as a string. */
12
+ export type CommandState = 'running' | 'exited' | (string & {});
13
+ export type TerminalState = 'running' | 'exited' | (string & {});
14
+
15
+ export type Network = {
16
+ /** Outbound internet access, DNS included. `false` blocks everything not in `allow`. Default `true`. */
17
+ internet?: boolean;
18
+ /** Domains, IPv4 addresses or IPv4 CIDRs reachable even with `internet` false. */
19
+ allow?: string[];
20
+ /** Domains, IPv4 addresses or IPv4 CIDRs always blocked. Wins over `allow`. */
21
+ deny?: string[];
22
+ };
23
+
24
+ export type Port = {
25
+ port: number;
26
+ public: boolean;
27
+ /** `https://<port>-<id without sbx_>.<preview domain>`. */
28
+ url: string;
29
+ };
30
+
31
+ export type SandboxData = {
32
+ id: string;
33
+ object: string;
34
+ state: SandboxState;
35
+ template: string;
36
+ image?: string | null;
37
+ cpu: number;
38
+ memory_mb: number;
39
+ disk_mb: number;
40
+ created_at: number;
41
+ started_at?: number | null;
42
+ expires_at: number;
43
+ ended_at?: number | null;
44
+ paused_at?: number | null;
45
+ end_reason?: string | null;
46
+ metadata: Record<string, string>;
47
+ network: Network;
48
+ ports?: Port[];
49
+ port_token?: string | null;
50
+ [field: string]: unknown;
51
+ };
52
+
53
+ export type SandboxListData = {
54
+ object: string;
55
+ data: SandboxData[];
56
+ has_more: boolean;
57
+ next_cursor?: string | null;
58
+ [field: string]: unknown;
59
+ };
60
+
61
+ export type SandboxTemplateData = {
62
+ object: string;
63
+ name: string;
64
+ cpu: number;
65
+ memory_mb: number;
66
+ disk_mb: number;
67
+ [field: string]: unknown;
68
+ };
69
+
70
+ /**
71
+ * `creating`, `ready`, `failed`, or a state added later, passed through as a string. `deleted` comes only in the answer
72
+ * to a delete.
73
+ */
74
+ export type SandboxImageState = 'creating' | 'ready' | 'failed' | 'deleted' | (string & {});
75
+
76
+ /** Why a `failed` image failed. A code added later passes through as a string. */
77
+ export type SandboxImageError = {
78
+ code: 'snapshot_failed' | 'sandbox_stopped' | (string & {});
79
+ message: string;
80
+ [field: string]: unknown;
81
+ };
82
+
83
+ export type SandboxImageData = {
84
+ id: string;
85
+ object: string;
86
+ state: SandboxImageState;
87
+ sandbox_id: string;
88
+ template: string;
89
+ cpu: number;
90
+ memory_mb: number;
91
+ disk_mb: number;
92
+ size_bytes: number | null;
93
+ created_at: number;
94
+ ready_at: number | null;
95
+ error: SandboxImageError | null;
96
+ metadata: Record<string, string>;
97
+ [field: string]: unknown;
98
+ };
99
+
100
+ export type SandboxImageListData = {
101
+ object: string;
102
+ data: SandboxImageData[];
103
+ has_more: boolean;
104
+ next_cursor?: string | null;
105
+ [field: string]: unknown;
106
+ };
107
+
108
+ export type CommandData = {
109
+ id: string;
110
+ object: string;
111
+ sandbox_id: string;
112
+ state: CommandState;
113
+ argv: string[];
114
+ exit_code?: number | null;
115
+ signal?: number | null;
116
+ oom_killed?: boolean;
117
+ stdin: boolean;
118
+ started_at: number;
119
+ ended_at?: number | null;
120
+ [field: string]: unknown;
121
+ };
122
+
123
+ export type TerminalData = {
124
+ id: string;
125
+ object: string;
126
+ sandbox_id: string;
127
+ state: TerminalState;
128
+ cols: number;
129
+ rows: number;
130
+ exit_code?: number | null;
131
+ created_at: number;
132
+ ended_at?: number | null;
133
+ [field: string]: unknown;
134
+ };
135
+
136
+ export type FileWrittenData = { object: string; path: string; size: number; [field: string]: unknown };
137
+
138
+ export type FileEntryData = {
139
+ name: string;
140
+ path: string;
141
+ type: string;
142
+ size?: number | null;
143
+ modified_at?: number | null;
144
+ [field: string]: unknown;
145
+ };
146
+
147
+ export type FileStatData = {
148
+ object: string;
149
+ path: string;
150
+ type: string;
151
+ size?: number | null;
152
+ modified_at?: number | null;
153
+ [field: string]: unknown;
154
+ };
155
+
156
+ export type ListData<T> = { object: string; data: T[]; [field: string]: unknown };
157
+
158
+ export type SandboxTemplate = {
159
+ object: string;
160
+ name: string;
161
+ /** The default vCPUs. */
162
+ cpu: number;
163
+ /** The default memory in MiB. */
164
+ memoryMb: number;
165
+ diskMb: number;
166
+ raw: SandboxTemplateData;
167
+ };
168
+
169
+ export type FileWritten = {
170
+ object: string;
171
+ path: string;
172
+ /** Bytes written. */
173
+ size: number;
174
+ raw: FileWrittenData;
175
+ };
176
+
177
+ export type FileEntry = {
178
+ name: string;
179
+ path: string;
180
+ /** `file` or `dir`. A symbolic link lists as `file`. */
181
+ type: string;
182
+ size: number | null;
183
+ modifiedAt: number | null;
184
+ raw: FileEntryData;
185
+ };
186
+
187
+ export type FileStat = {
188
+ object: string;
189
+ path: string;
190
+ /** `file`, `dir` or `other` (a device, socket or pipe). */
191
+ type: string;
192
+ size: number | null;
193
+ modifiedAt: number | null;
194
+ raw: FileStatData;
195
+ };
196
+
197
+ /** What a command ended with. A non-zero exit is a result, not an exception. */
198
+ export type CommandResult = {
199
+ /** The command's id, `cmd_…`. */
200
+ id: string;
201
+ exitCode: number | null;
202
+ stdout: string;
203
+ stderr: string;
204
+ /** The signal that ended it, if one did. */
205
+ exitSignal: number | null;
206
+ oomKilled: boolean;
207
+ };
208
+
209
+ export type StartedEvent = {
210
+ type: 'started';
211
+ /** The event's position in the command's stream, the value of `lastEventId`. */
212
+ id: string;
213
+ commandId: string;
214
+ pid: number;
215
+ raw: Record<string, unknown>;
216
+ };
217
+
218
+ export type OutputEvent = {
219
+ type: 'stdout' | 'stderr';
220
+ id: string;
221
+ /** The output bytes. */
222
+ data: Uint8Array;
223
+ /** When the output was captured, Unix milliseconds. */
224
+ ts: number | undefined;
225
+ raw: Record<string, unknown>;
226
+ };
227
+
228
+ export type ExitEvent = {
229
+ type: 'exit';
230
+ id: string;
231
+ exitCode: number | null;
232
+ signal: number | null;
233
+ oomKilled: boolean;
234
+ raw: Record<string, unknown>;
235
+ };
236
+
237
+ /**
238
+ * One event of a command's stream. A type added to the API later is passed through too, with its name in `type`, its
239
+ * id in `id` and its data in `raw`. It is not in this union, which keeps `event.type === 'stdout'` narrowing.
240
+ */
241
+ export type CommandEvent = StartedEvent | OutputEvent | ExitEvent;
package/src/uploads.ts ADDED
@@ -0,0 +1,177 @@
1
+ // Portions adapted from openai-node (Apache-2.0, Copyright 2026 OpenAI) and changed by Keln. See NOTICE.
2
+ /**
3
+ * Uploads: what a call's `file` may be, and the multipart form it travels in (`keln.audio.transcriptions`,
4
+ * `keln.images.edit`). Node 22 and later only, so the global `File`, `Blob` and `FormData` are used as they are. Every
5
+ * upload is read into memory before it is sent, so a retry can send it again, and a call's signal stops that read.
6
+ * Filenames are the last part of a path. A file can also go as a base64 data URL, for the JSON form of an image edit.
7
+ */
8
+ import { untilAborted } from './util.js';
9
+
10
+ /** Text, binary content, or a Blob inside a file's parts. */
11
+ type BlobLikePart = string | ArrayBuffer | ArrayBufferView | Blob;
12
+ /** The parts a `File` is made of. The SDK builds without the DOM types, so it names them itself. */
13
+ type BlobPart = BlobLikePart;
14
+ /** A `File`'s type and modification time. */
15
+ type FilePropertyBag = { type?: string; lastModified?: number };
16
+
17
+ /**
18
+ * What a call's `file` may be: a `File` or `Blob`, a fetch `Response`, or any async iterable of bytes, a Node
19
+ * `fs.createReadStream(path)` among them. `toFile` makes a `File` from a `Buffer` or `Uint8Array`.
20
+ */
21
+ export type Uploadable = File | Blob | Response | AsyncIterable<BlobLikePart>;
22
+
23
+ /** What `toFile` takes. A top-level string is left out, so a path is never mistaken for the file's contents. */
24
+ export type ToFileInput = File | Blob | Response | Exclude<BlobLikePart, string> | AsyncIterable<BlobLikePart>;
25
+
26
+ /** A `File`; a missing name becomes `unknown_file`. */
27
+ export function makeFile(fileBits: BlobPart[], fileName: string | undefined, options?: FilePropertyBag): File {
28
+ // The runtime File takes every BlobPart; Node's declared constructor leaves ArrayBuffer out.
29
+ return new File(fileBits as unknown as ConstructorParameters<typeof File>[0], fileName ?? 'unknown_file', options);
30
+ }
31
+
32
+ function basename(value: string): string | undefined {
33
+ return value.split(/[\\/]/).pop() || undefined;
34
+ }
35
+
36
+ /** A filename from an object's `name`, `filename`, `url` or `path`, without its directories. */
37
+ export function getName(value: unknown): string | undefined {
38
+ if (typeof value !== 'object' || value === null) return undefined;
39
+ const v = value as { name?: unknown; filename?: unknown; url?: unknown; path?: unknown };
40
+ const text = (x: unknown): string | undefined => (x ? String(x) : undefined);
41
+ const explicit = text(v.name) ?? text(v.filename);
42
+ if (explicit !== undefined) return basename(explicit);
43
+ const url = text(v.url);
44
+ if (url !== undefined) {
45
+ try {
46
+ return basename(decodeURIComponent(new URL(url).pathname));
47
+ } catch {
48
+ return basename(url);
49
+ }
50
+ }
51
+ const path = text(v.path);
52
+ return path !== undefined ? basename(path) : undefined;
53
+ }
54
+
55
+ const isAsyncIterable = (value: unknown): value is AsyncIterable<unknown> =>
56
+ value !== null && typeof value === 'object' && typeof (value as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function';
57
+
58
+ /** Whether `value` is a file to upload: a `File` or `Blob`, a fetch `Response`, or an async iterable of bytes. */
59
+ export function isUploadable(value: unknown): value is Uploadable {
60
+ return value instanceof Blob || value instanceof Response || isAsyncIterable(value);
61
+ }
62
+
63
+ /**
64
+ * The parts of `value`, an async iterable read to its end. An abort of `signal` throws its reason at once and ends
65
+ * the iteration, so a stream that is read stops.
66
+ */
67
+ async function getBytes(value: BlobLikePart | AsyncIterable<BlobLikePart>, signal?: AbortSignal): Promise<BlobPart[]> {
68
+ if (typeof value === 'string' || ArrayBuffer.isView(value) || value instanceof ArrayBuffer || value instanceof Blob) {
69
+ return [value as BlobPart];
70
+ }
71
+ if (isAsyncIterable(value)) {
72
+ const iterator = value[Symbol.asyncIterator]();
73
+ const parts: BlobPart[] = [];
74
+ try {
75
+ while (true) {
76
+ const next = await untilAborted(iterator.next(), signal, () => {});
77
+ if (next.done === true) return parts;
78
+ parts.push(...(await getBytes(next.value, signal)));
79
+ }
80
+ } catch (error) {
81
+ void Promise.resolve()
82
+ .then(() => iterator.return?.())
83
+ .catch(() => {});
84
+ throw error;
85
+ }
86
+ }
87
+ const constructor = (value as { constructor?: { name?: string } } | null)?.constructor?.name;
88
+ throw new TypeError(
89
+ `A file's content must be a string, bytes, a Blob or an async iterable of them, not ${typeof value}${constructor ? ` (${constructor})` : ''}.`,
90
+ );
91
+ }
92
+
93
+ /** A `Response`'s body as a `Blob`, typed by its `Content-Type`. An abort of `signal` throws its reason at once. */
94
+ async function blobOf(response: Response, signal: AbortSignal | undefined): Promise<Blob> {
95
+ return await untilAborted(response.blob(), signal, () => {});
96
+ }
97
+
98
+ /** `toFile`, its reading stopped by an abort of `signal`. */
99
+ async function toFileUntil(
100
+ value: ToFileInput | PromiseLike<ToFileInput>,
101
+ name: string | null | undefined,
102
+ options: FilePropertyBag | undefined,
103
+ signal: AbortSignal | undefined,
104
+ ): Promise<File> {
105
+ const input = await value;
106
+ if (input instanceof File) {
107
+ if ((name == null || name === input.name) && (options?.type == null || options.type === input.type)) return input;
108
+ return makeFile([input], name ?? input.name, { ...options, type: options?.type ?? input.type, lastModified: input.lastModified });
109
+ }
110
+ if (input instanceof Response) {
111
+ const blob = await blobOf(input, signal);
112
+ return makeFile([blob], name ?? getName(input), options?.type === undefined && blob.type ? { ...options, type: blob.type } : options);
113
+ }
114
+ const parts = await getBytes(input, signal);
115
+ const typed = parts.find((p): p is Blob => p instanceof Blob && p.type !== '');
116
+ return makeFile(parts, name ?? getName(input), options?.type === undefined && typed ? { ...options, type: typed.type } : options);
117
+ }
118
+
119
+ /**
120
+ * Content as a `File`, buffered: a `File` comes back as it is unless renamed or retyped, a `Response` or `Blob` keeps
121
+ * its type, and bytes or an async iterable of them become a file named `name`, else after the input's own name.
122
+ */
123
+ export async function toFile(
124
+ value: ToFileInput | PromiseLike<ToFileInput>,
125
+ name?: string | null,
126
+ options?: FilePropertyBag,
127
+ ): Promise<File> {
128
+ return await toFileUntil(value, name, options, undefined);
129
+ }
130
+
131
+ /**
132
+ * One value into the form: a string, number or boolean as text, a file-like value as a file part, an array as
133
+ * repeated `key[]` fields, an object as `key[name]` fields; `undefined` is left out, `null` refused.
134
+ */
135
+ async function addFormValue(form: FormData, key: string, value: unknown, signal: AbortSignal | undefined): Promise<void> {
136
+ if (value === undefined) return;
137
+ if (value === null) {
138
+ throw new TypeError(`"${key}" is null, and a form field can't be null: leave it out, or send the string 'null'.`);
139
+ }
140
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
141
+ form.append(key, String(value));
142
+ } else if (value instanceof Response) {
143
+ const blob = await blobOf(value, signal);
144
+ form.append(key, makeFile([blob], getName(value), { type: blob.type }));
145
+ } else if (value instanceof Blob) {
146
+ const filename = getName(value);
147
+ if (filename === undefined) form.append(key, value);
148
+ else form.append(key, value, filename);
149
+ } else if (isAsyncIterable(value)) {
150
+ form.append(key, makeFile(await getBytes(value as AsyncIterable<BlobLikePart>, signal), getName(value)));
151
+ } else if (Array.isArray(value)) {
152
+ for (const entry of value) await addFormValue(form, `${key}[]`, entry, signal);
153
+ } else if (typeof value === 'object') {
154
+ for (const [name, prop] of Object.entries(value)) await addFormValue(form, `${key}[${name}]`, prop, signal);
155
+ } else {
156
+ throw new TypeError(
157
+ `"${key}" is ${typeof value}: a form field takes a string, number, boolean, object, array, File or Blob.`,
158
+ );
159
+ }
160
+ }
161
+
162
+ /** A request body as `FormData`, its fields in the body's order. An abort of `signal` stops reading its files. */
163
+ export async function createForm(body: Record<string, unknown>, signal?: AbortSignal): Promise<FormData> {
164
+ const form = new FormData();
165
+ for (const [key, value] of Object.entries(body)) await addFormValue(form, key, value, signal);
166
+ return form;
167
+ }
168
+
169
+ /**
170
+ * A file as a base64 data URL, read whole and typed as its multipart part would be: the file's own type, else
171
+ * `application/octet-stream`. The API reads an image's real type from its bytes. An abort of `signal` stops the read.
172
+ */
173
+ export async function toDataUrl(value: Uploadable, signal?: AbortSignal): Promise<string> {
174
+ const file = await toFileUntil(value, undefined, undefined, signal);
175
+ const base64 = Buffer.from(await untilAborted(file.arrayBuffer(), signal, () => {})).toString('base64');
176
+ return `data:${file.type || 'application/octet-stream'};base64,${base64}`;
177
+ }