@eigenpal/sdk 0.25.12 → 1.0.0-rc.1

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 (73) hide show
  1. package/README.md +27 -105
  2. package/dist/client.d.ts +164 -0
  3. package/dist/client.js +234 -0
  4. package/dist/core.d.ts +82 -0
  5. package/dist/core.js +311 -0
  6. package/dist/errors.d.ts +64 -0
  7. package/dist/errors.js +132 -0
  8. package/dist/generated/operations.gen.d.ts +336 -0
  9. package/dist/generated/operations.gen.js +135 -0
  10. package/dist/generated/public.gen.d.ts +2 -0
  11. package/dist/generated/public.gen.js +2 -0
  12. package/dist/generated/resources.gen.d.ts +490 -0
  13. package/dist/generated/resources.gen.js +659 -0
  14. package/dist/generated/types.gen.d.ts +2457 -0
  15. package/dist/generated/types.gen.js +2 -0
  16. package/dist/index.d.ts +20 -0
  17. package/dist/index.js +15 -0
  18. package/dist/lib/fetch-body.d.ts +23 -0
  19. package/dist/lib/fetch-body.js +66 -0
  20. package/dist/lib/files.d.ts +134 -0
  21. package/dist/lib/files.js +296 -0
  22. package/dist/lib/upload-app-chunked.d.ts +36 -0
  23. package/dist/lib/upload-app-chunked.js +94 -0
  24. package/dist/lib/upload-limits.d.ts +32 -0
  25. package/dist/lib/upload-limits.js +60 -0
  26. package/dist/lib/upload-presigned-multipart.d.ts +74 -0
  27. package/dist/lib/upload-presigned-multipart.js +212 -0
  28. package/dist/page.d.ts +30 -0
  29. package/dist/page.js +38 -0
  30. package/dist/resources.d.ts +85 -0
  31. package/dist/resources.js +247 -0
  32. package/dist/telemetry.d.ts +20 -0
  33. package/{src/telemetry.ts → dist/telemetry.js} +26 -31
  34. package/dist/upload-file.d.ts +31 -0
  35. package/dist/upload-file.js +286 -0
  36. package/{src/upload.ts → dist/upload.d.ts} +4 -4
  37. package/dist/upload.js +12 -0
  38. package/package.json +19 -15
  39. package/src/client.ts +0 -656
  40. package/src/errors.ts +0 -130
  41. package/src/generated/client/client.gen.ts +0 -277
  42. package/src/generated/client/index.ts +0 -27
  43. package/src/generated/client/types.gen.ts +0 -218
  44. package/src/generated/client/utils.gen.ts +0 -316
  45. package/src/generated/client.gen.ts +0 -18
  46. package/src/generated/core/auth.gen.ts +0 -48
  47. package/src/generated/core/bodySerializer.gen.ts +0 -82
  48. package/src/generated/core/params.gen.ts +0 -178
  49. package/src/generated/core/pathSerializer.gen.ts +0 -171
  50. package/src/generated/core/queryKeySerializer.gen.ts +0 -117
  51. package/src/generated/core/serverSentEvents.gen.ts +0 -242
  52. package/src/generated/core/types.gen.ts +0 -110
  53. package/src/generated/core/utils.gen.ts +0 -140
  54. package/src/generated/index.ts +0 -4
  55. package/src/generated/sdk.gen.ts +0 -1361
  56. package/src/generated/types.gen.ts +0 -9282
  57. package/src/index.ts +0 -120
  58. package/src/lib/fetch-body.ts +0 -92
  59. package/src/lib/files.ts +0 -390
  60. package/src/lib/upload-app-chunked.ts +0 -121
  61. package/src/lib/upload-limits.ts +0 -72
  62. package/src/lib/upload-presigned-multipart.ts +0 -285
  63. package/src/resources/auth.ts +0 -18
  64. package/src/resources/automations.ts +0 -830
  65. package/src/resources/dataset-review-requests.ts +0 -38
  66. package/src/resources/email-servers.ts +0 -95
  67. package/src/resources/files.ts +0 -592
  68. package/src/resources/folders.ts +0 -77
  69. package/src/resources/human-reviews.ts +0 -106
  70. package/src/resources/models.ts +0 -37
  71. package/src/resources/runs.ts +0 -350
  72. package/src/resources/templates.ts +0 -153
  73. package/src/runtime-config.ts +0 -14
package/src/index.ts DELETED
@@ -1,120 +0,0 @@
1
- /**
2
- * Official TypeScript SDK for the EigenPal API.
3
- *
4
- * @example
5
- * ```ts
6
- * import { EigenpalClient } from '@eigenpal/sdk';
7
- *
8
- * const client = new EigenpalClient({ apiKey: process.env.EIGENPAL_API_KEY! });
9
- *
10
- * // Async — enqueue and poll later.
11
- * const { id } = await client.run('workflows.extract-invoice', { ... });
12
- *
13
- * // Sync (server holds the connection up to 60s).
14
- * const result = await client.run('workflows.extract-invoice', { ... }, { waitForCompletion: 60 });
15
- *
16
- * // Inspect or manage runs later.
17
- * const final = await client.runs.get(id);
18
- * ```
19
- */
20
- export {
21
- EigenpalClient,
22
- isRunFinished,
23
- type EigenpalOptions,
24
- type RerunOptions,
25
- type RunCallOptions,
26
- type RunInput,
27
- type RunStartResponse,
28
- type RunTarget,
29
- } from './client';
30
-
31
- export {
32
- EigenpalAuthError,
33
- EigenpalConflictError,
34
- EigenpalError,
35
- EigenpalForbiddenError,
36
- EigenpalNotFoundError,
37
- EigenpalPayloadTooLargeError,
38
- EigenpalRateLimitError,
39
- EigenpalServerError,
40
- EigenpalTimeoutError,
41
- EigenpalValidationError,
42
- } from './errors';
43
-
44
- export { toFile } from './lib/files';
45
- export type {
46
- FileDescriptor,
47
- FileInput,
48
- NodeReadableStream,
49
- PathFileInput,
50
- StreamFactoryFileInput,
51
- } from './lib/files';
52
- export type { ListAutomationsOptions } from './resources/automations';
53
- export type { ListDatasetReviewRequestsOptions } from './resources/dataset-review-requests';
54
- export type { ListEmailServersOptions } from './resources/email-servers';
55
- export type { ListFoldersOptions } from './resources/folders';
56
- export type { ListRunsOptions, RunExpand, RunExpandSection } from './resources/runs';
57
-
58
- // Re-export the canonical generated types so users can type their own
59
- // callbacks and helpers without reaching into `./generated`.
60
- export type {
61
- ApiErrorEnvelope,
62
- ApiErrorIssue,
63
- AuthCheckResponse,
64
- AutomationDetail,
65
- AutomationSummary,
66
- AutomationTriggerState,
67
- AutomationTriggersResponse,
68
- AutomationVersion,
69
- CreateAutomationVersionRequest,
70
- CreateEmailServerRequest,
71
- CreateFolderRequest,
72
- DeleteAutomationResponse,
73
- DeleteEmailServerResponse,
74
- DeleteFolderResponse,
75
- EmailServer,
76
- ExecutionStatus,
77
- File,
78
- Folder,
79
- FolderType,
80
- ListEmailServersResponse,
81
- ListFoldersResponse,
82
- ListModelsResponse,
83
- PublicModel,
84
- PublicModelCost,
85
- PublicModelLimits,
86
- PublicResendEmailServer,
87
- PublicSmtpEmailServer,
88
- RestoreAutomationVersionRequest,
89
- Run,
90
- RunAccepted,
91
- RunArtifact,
92
- RunArtifactsResponse,
93
- RunError,
94
- RunEvent,
95
- RunEventsResponse,
96
- RunListItem,
97
- RunStartBody,
98
- RunStepsResponse,
99
- RunUsage,
100
- RunUsageResponse,
101
- RunsCancelResponse,
102
- RunsGetResponse,
103
- RunsListResponse,
104
- RunsRerunResponse,
105
- RunsReviewsClearResponse,
106
- RunsReviewsExpectedCreateResponse,
107
- RunsReviewsExpectedFileDeleteResponse,
108
- RunsReviewsExpectedFileUpdateResponse,
109
- RunsReviewsExpectedGetResponse,
110
- RunsReviewsGetResponse,
111
- RunsReviewsUpdateResponse,
112
- RunsTraceGetResponse,
113
- Template,
114
- TemplateRevision,
115
- TestEmailServerRequest,
116
- TestEmailServerResponse,
117
- UpdateAutomationRequest,
118
- UpdateEmailServerRequest,
119
- UpdateFolderRequest,
120
- } from './generated/types.gen';
@@ -1,92 +0,0 @@
1
- /** Request init for Node/Bun fetch when streaming a Node readable body. */
2
- export type StreamableRequestInit = RequestInit & { duplex?: 'half' };
3
-
4
- /** True when `body` is a Node.js readable stream (fs.createReadStream, etc.). */
5
- export function isNodeReadableStream(body: unknown): body is NodeJS.ReadableStream {
6
- return typeof (body as { pipe?: unknown }).pipe === 'function';
7
- }
8
-
9
- /**
10
- * Copy a byte view into a standalone ArrayBuffer accepted by DOM `BodyInit`.
11
- * Avoids TS generic mismatches on `Uint8Array<ArrayBufferLike>`.
12
- */
13
- export function byteViewToArrayBuffer(view: Uint8Array): ArrayBuffer {
14
- if (
15
- view.buffer instanceof ArrayBuffer &&
16
- view.byteOffset === 0 &&
17
- view.byteLength === view.buffer.byteLength
18
- ) {
19
- return view.buffer;
20
- }
21
- const copy = new Uint8Array(view.byteLength);
22
- copy.set(view);
23
- return copy.buffer;
24
- }
25
-
26
- /** Convert bytes or a Node readable into a fetch-compatible PUT body. */
27
- export function toPutBody(body: Uint8Array | NodeJS.ReadableStream): BodyInit {
28
- if (isNodeReadableStream(body)) {
29
- // Node/Bun fetch accepts Node readables with `duplex: 'half'`.
30
- return body as unknown as BodyInit;
31
- }
32
- return byteViewToArrayBuffer(body);
33
- }
34
-
35
- export function putRequestInit(
36
- body: Uint8Array | NodeJS.ReadableStream,
37
- headers: HeadersInit,
38
- signal?: AbortSignal
39
- ): StreamableRequestInit {
40
- const stream = isNodeReadableStream(body);
41
- return {
42
- method: 'PUT',
43
- headers,
44
- body: toPutBody(body),
45
- signal,
46
- ...(stream ? { duplex: 'half' as const } : {}),
47
- };
48
- }
49
-
50
- type NodeReadableState = NodeJS.ReadableStream & {
51
- readableEnded?: boolean;
52
- destroyed?: boolean;
53
- destroy?: (error?: Error) => void;
54
- };
55
-
56
- /** Drop a Node readable that never started sending (fetch failed before upload). */
57
- export function destroyUnreadNodeReadable(stream: NodeJS.ReadableStream): void {
58
- const readable = stream as NodeReadableState;
59
- if (!readable.readableEnded && !readable.destroyed && typeof readable.destroy === 'function') {
60
- readable.destroy();
61
- }
62
- }
63
-
64
- /**
65
- * Block until every byte of a Node readable PUT body has been consumed.
66
- * Real fetch/undici should drain the stream before resolving; mocks that
67
- * return early leave bytes unread and must be drained here so callers do
68
- * not destroy the stream while a retry or background upload is still running.
69
- */
70
- export async function ensureNodeReadableFullySent(
71
- stream: NodeJS.ReadableStream,
72
- expectedByteLength?: number
73
- ): Promise<number> {
74
- const readable = stream as NodeReadableState;
75
- if (readable.readableEnded) {
76
- return expectedByteLength ?? 0;
77
- }
78
- if (readable.destroyed) {
79
- throw new Error('Upload stream was destroyed before the request body finished sending');
80
- }
81
-
82
- let bytes = 0;
83
- for await (const chunk of stream as AsyncIterable<Buffer | Uint8Array | string>) {
84
- bytes += typeof chunk === 'string' ? Buffer.byteLength(chunk) : chunk.length;
85
- }
86
- if (expectedByteLength !== undefined && bytes !== expectedByteLength) {
87
- throw new Error(
88
- `Upload sent ${bytes} byte(s) but ${expectedByteLength} were expected for this part`
89
- );
90
- }
91
- return bytes;
92
- }
package/src/lib/files.ts DELETED
@@ -1,390 +0,0 @@
1
- /**
2
- * File-input helpers for `client.run()`.
3
- *
4
- * A workflow input value is treated as a file when it is one of:
5
- * - a Node readable stream — `fs.createReadStream('contract.pdf')`
6
- * - a `File` or `Blob`
7
- * - a `{ content, filename, mimeType? }` descriptor — build one with `toFile()`
8
- *
9
- * File values are auto-detected and uploaded as `multipart/form-data`
10
- * (matching `curl -F`) — no base64 round-trip.
11
- */
12
-
13
- const DEFAULT_MIME = 'application/octet-stream';
14
-
15
- /** Common file extensions → MIME type, for upload filename inference. */
16
- const MIME_BY_EXT: Record<string, string> = {
17
- pdf: 'application/pdf',
18
- png: 'image/png',
19
- jpg: 'image/jpeg',
20
- jpeg: 'image/jpeg',
21
- gif: 'image/gif',
22
- webp: 'image/webp',
23
- txt: 'text/plain',
24
- csv: 'text/csv',
25
- json: 'application/json',
26
- xml: 'application/xml',
27
- html: 'text/html',
28
- md: 'text/markdown',
29
- doc: 'application/msword',
30
- docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
31
- xls: 'application/vnd.ms-excel',
32
- xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
33
- xlsm: 'application/vnd.ms-excel.sheet.macroenabled.12',
34
- ppt: 'application/vnd.ms-powerpoint',
35
- pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
36
- msg: 'application/vnd.ms-outlook',
37
- };
38
-
39
- /** Guess a MIME type from a filename extension; falls back to octet-stream. */
40
- function guessMimeType(filename: string): string {
41
- const ext = filename.includes('.') ? filename.split('.').pop()!.toLowerCase() : '';
42
- return MIME_BY_EXT[ext] ?? DEFAULT_MIME;
43
- }
44
-
45
- /**
46
- * Explicit file descriptor — raw bytes plus metadata. Build one with
47
- * `toFile()` when you have a `Buffer` / `Uint8Array` / `ArrayBuffer` / `Blob`
48
- * in memory rather than a path or a stream.
49
- */
50
- export interface FileDescriptor {
51
- content: ArrayBuffer | ArrayBufferView | Blob;
52
- filename: string;
53
- mimeType?: string;
54
- }
55
-
56
- /**
57
- * Disk path that can be stat'd and re-opened per part for resumable multipart.
58
- */
59
- export interface PathFileInput {
60
- path: string;
61
- filename?: string;
62
- mimeType?: string;
63
- }
64
-
65
- /**
66
- * Replayable byte-range factory for Node streams that are not a disk path.
67
- * `open` must return a fresh body for `[start, start+length)` on every call.
68
- */
69
- export interface StreamFactoryFileInput {
70
- size: number;
71
- filename: string;
72
- mimeType?: string;
73
- open: (
74
- start: number,
75
- length: number
76
- ) => Blob | Uint8Array | ReadableStream | NodeJS.ReadableStream;
77
- }
78
-
79
- /**
80
- * A Node readable stream — typically `fs.createReadStream('contract.pdf')`.
81
- * Streams with a `path` are uploaded from disk without draining. A one-shot
82
- * stream without a path cannot be multipart-resumed.
83
- */
84
- export interface NodeReadableStream extends AsyncIterable<unknown> {
85
- /** Source path; used to infer the upload filename. */
86
- readonly path?: string;
87
- }
88
-
89
- /** Any value the SDK accepts as a "file" workflow input. */
90
- export type FileInput =
91
- | Blob
92
- | FileDescriptor
93
- | PathFileInput
94
- | StreamFactoryFileInput
95
- | NodeReadableStream;
96
-
97
- /**
98
- * Attach a filename (and optional MIME type) to raw bytes. The escape hatch
99
- * for when you have a `Buffer` / `ArrayBuffer` / `Blob` in memory rather than
100
- * a file path or stream.
101
- *
102
- * ```ts
103
- * await client.run('workflows.extract-invoice', {
104
- * contract_document: toFile(buffer, 'contract.pdf'),
105
- * });
106
- * ```
107
- */
108
- export function toFile(
109
- content: ArrayBuffer | ArrayBufferView | Blob,
110
- filename: string,
111
- mimeType?: string
112
- ): FileDescriptor {
113
- return { content, filename, mimeType: mimeType ?? guessMimeType(filename) };
114
- }
115
-
116
- /** Detect a Node readable stream (`fs.createReadStream`, etc.). */
117
- export function isReadStream(value: unknown): value is NodeReadableStream {
118
- if (value === null || typeof value !== 'object') return false;
119
- const v = value as Record<PropertyKey, unknown>;
120
- return (
121
- typeof v[Symbol.asyncIterator] === 'function' &&
122
- (typeof v.pipe === 'function' || typeof v.read === 'function')
123
- );
124
- }
125
-
126
- /** Detect an explicit `{ content, filename }` descriptor. */
127
- export function isFileDescriptor(value: unknown): value is FileDescriptor {
128
- if (value === null || typeof value !== 'object') return false;
129
- const v = value as { content?: unknown; filename?: unknown };
130
- return (
131
- typeof v.filename === 'string' &&
132
- v.content != null &&
133
- (v.content instanceof ArrayBuffer ||
134
- ArrayBuffer.isView(v.content) ||
135
- (typeof Blob !== 'undefined' && v.content instanceof Blob))
136
- );
137
- }
138
-
139
- export function isPathFileInput(value: unknown): value is PathFileInput {
140
- if (value === null || typeof value !== 'object' || isReadStream(value)) return false;
141
- const v = value as { path?: unknown; open?: unknown };
142
- return typeof v.path === 'string' && typeof v.open !== 'function';
143
- }
144
-
145
- export function isStreamFactoryFileInput(value: unknown): value is StreamFactoryFileInput {
146
- if (value === null || typeof value !== 'object') return false;
147
- const v = value as { open?: unknown; size?: unknown; filename?: unknown };
148
- return (
149
- typeof v.open === 'function' &&
150
- typeof v.filename === 'string' &&
151
- typeof v.size === 'number' &&
152
- Number.isFinite(v.size)
153
- );
154
- }
155
-
156
- export function isFileInput(value: unknown): value is FileInput {
157
- if (typeof Blob !== 'undefined' && value instanceof Blob) return true;
158
- if (isReadStream(value)) return true;
159
- if (isPathFileInput(value) || isStreamFactoryFileInput(value)) return true;
160
- return isFileDescriptor(value);
161
- }
162
-
163
- export function hasFileInput(input: Record<string, unknown> | undefined): boolean {
164
- if (!input) return false;
165
- for (const value of Object.values(input)) {
166
- if (isFileInput(value)) return true;
167
- }
168
- return false;
169
- }
170
-
171
- /** Last path segment of a (possibly nested) file path. */
172
- function basename(path: string): string {
173
- const segments = path.split(/[\\/]/);
174
- return segments[segments.length - 1] || 'file';
175
- }
176
-
177
- /**
178
- * Resolve a `FileInput` to a `{ blob, filename }` pair for `FormData.append`.
179
- *
180
- * One-shot streams without a path are drained here so the body can be replayed
181
- * on HTTP retries. Disk paths and stream factories stay unbuffered until the
182
- * caller asks for bytes (small multipart leftovers).
183
- */
184
- export async function resolveFileBlob(file: FileInput): Promise<{ blob: Blob; filename: string }> {
185
- // `File` extends `Blob`, so this branch covers both.
186
- if (typeof Blob !== 'undefined' && file instanceof Blob) {
187
- return { blob: file, filename: (file as File).name || 'file' };
188
- }
189
-
190
- if (isPathFileInput(file) || (isReadStream(file) && typeof file.path === 'string')) {
191
- const filePath = isPathFileInput(file) ? file.path : file.path!;
192
- const filename = (isPathFileInput(file) ? file.filename : undefined) ?? basename(filePath);
193
- if (await pathIsFile(filePath)) {
194
- const { readFile } = await import('node:fs/promises');
195
- const bytes = await readFile(filePath);
196
- const type = (isPathFileInput(file) ? file.mimeType : undefined) ?? guessMimeType(filename);
197
- return { blob: new Blob([bytes as BlobPart], { type }), filename };
198
- }
199
- if (isPathFileInput(file)) {
200
- throw new Error(`Upload path is not a file: ${filePath}`);
201
- }
202
- // Named stream whose path is not readable — drain the in-memory stream.
203
- }
204
-
205
- if (isStreamFactoryFileInput(file)) {
206
- const body = file.open(0, file.size);
207
- if (typeof Blob !== 'undefined' && body instanceof Blob) {
208
- return { blob: body, filename: file.filename };
209
- }
210
- if (body instanceof Uint8Array) {
211
- return {
212
- blob: new Blob([body as BlobPart], { type: file.mimeType ?? guessMimeType(file.filename) }),
213
- filename: file.filename,
214
- };
215
- }
216
- throw new Error(
217
- 'Stream factory returned a non-Blob body; pass a path or Blob for small multipart leftovers'
218
- );
219
- }
220
-
221
- // Node readable stream without a path — drain it into a Blob now.
222
- if (isReadStream(file)) {
223
- const filename = typeof file.path === 'string' ? basename(file.path) : 'file';
224
- const parts: BlobPart[] = [];
225
- for await (const chunk of file) {
226
- parts.push(chunk as BlobPart);
227
- }
228
- return { blob: new Blob(parts, { type: guessMimeType(filename) }), filename };
229
- }
230
-
231
- // Explicit descriptor.
232
- const desc = file as FileDescriptor;
233
- const type = desc.mimeType ?? DEFAULT_MIME;
234
- if (!(desc.content instanceof Blob)) {
235
- // ArrayBuffer / ArrayBufferView — wrap the bytes in a typed Blob.
236
- return { blob: new Blob([desc.content as BlobPart], { type }), filename: desc.filename };
237
- }
238
- // Already a Blob — reuse it, re-slicing only to apply a different MIME type.
239
- const blob =
240
- desc.content.type === type ? desc.content : desc.content.slice(0, desc.content.size, type);
241
- return { blob, filename: desc.filename };
242
- }
243
-
244
- export async function statUploadSize(
245
- file: FileInput
246
- ): Promise<{ size: number; filename: string; contentType: string }> {
247
- if (typeof Blob !== 'undefined' && file instanceof Blob) {
248
- return {
249
- size: file.size,
250
- filename: (file as File).name || 'file',
251
- contentType: file.type || DEFAULT_MIME,
252
- };
253
- }
254
- if (isPathFileInput(file) || (isReadStream(file) && typeof file.path === 'string')) {
255
- const filePath = isPathFileInput(file) ? file.path : file.path!;
256
- const filename = (isPathFileInput(file) ? file.filename : undefined) ?? basename(filePath);
257
- if (await pathIsFile(filePath)) {
258
- const { stat } = await import('node:fs/promises');
259
- const info = await stat(filePath);
260
- return {
261
- size: info.size,
262
- filename,
263
- contentType: (isPathFileInput(file) ? file.mimeType : undefined) ?? guessMimeType(filename),
264
- };
265
- }
266
- if (isPathFileInput(file)) {
267
- throw new Error(`Upload path is not a file: ${filePath}`);
268
- }
269
- }
270
- if (isStreamFactoryFileInput(file)) {
271
- return {
272
- size: file.size,
273
- filename: file.filename,
274
- contentType: file.mimeType ?? guessMimeType(file.filename),
275
- };
276
- }
277
- if (isFileDescriptor(file)) {
278
- const size =
279
- file.content instanceof Blob
280
- ? file.content.size
281
- : file.content instanceof ArrayBuffer
282
- ? file.content.byteLength
283
- : file.content.byteLength;
284
- return {
285
- size,
286
- filename: file.filename,
287
- contentType: file.mimeType ?? guessMimeType(file.filename),
288
- };
289
- }
290
- throw new Error(
291
- 'Cannot determine size of a non-replayable stream. Pass a file path, Blob, or a stream factory with size.'
292
- );
293
- }
294
-
295
- async function pathIsFile(filePath: string): Promise<boolean> {
296
- try {
297
- const { stat } = await import('node:fs/promises');
298
- return (await stat(filePath)).isFile();
299
- } catch {
300
- return false;
301
- }
302
- }
303
-
304
- export interface MultipartParts {
305
- /** FormData ready to send as the request body. */
306
- formData: FormData;
307
- /** Number of file fields appended (0 means no files were detected). */
308
- fileCount: number;
309
- }
310
-
311
- /** Drain `input` into a FormData, appending each detected file as `files.<name>`. */
312
- async function appendFiles(
313
- fd: FormData,
314
- input: Record<string, unknown> | undefined
315
- ): Promise<{ scalars: Record<string, unknown>; fileCount: number }> {
316
- const scalars: Record<string, unknown> = {};
317
- let fileCount = 0;
318
- for (const [key, value] of Object.entries(input ?? {})) {
319
- if (isFileInput(value)) {
320
- const { blob, filename } = await resolveFileBlob(value);
321
- fd.append(`files.${key}`, blob, filename);
322
- fileCount += 1;
323
- } else {
324
- scalars[key] = value;
325
- }
326
- }
327
- return { scalars, fileCount };
328
- }
329
-
330
- /**
331
- * JSON-body counterpart of {@link buildRunMultipart}: canonical envelope
332
- * `{ target, input, overrides?, metadata? }`.
333
- */
334
- export function buildRunJsonBody(
335
- target: string,
336
- input: Record<string, unknown> | undefined,
337
- overrides?: { steps?: Record<string, Record<string, unknown>> },
338
- metadata?: Record<string, unknown>
339
- ): Record<string, unknown> {
340
- const body: Record<string, unknown> = {
341
- target,
342
- input: input ?? {},
343
- };
344
- if (overrides) body.overrides = overrides;
345
- if (metadata) body.metadata = metadata;
346
- return body;
347
- }
348
-
349
- /**
350
- * Build multipart for the canonical `client.run(...)` endpoint
351
- * (`POST /api/v1/runs`):
352
- *
353
- * - `target` is a required text field.
354
- * - Scalar inputs go in the `input` JSON text field.
355
- * - Each top-level file in `input` becomes `files.<fieldName>`.
356
- * - Per-step overrides and caller metadata use `overrides` / `metadata` JSON parts.
357
- *
358
- * Async because stream inputs are drained to bytes here. Only top-level file
359
- * values are extracted — files nested inside arrays / objects keep their
360
- * position in the JSON sidecar (the server has no nested-upload path).
361
- */
362
- export async function buildRunMultipart(args: {
363
- target: string;
364
- tags?: string | string[];
365
- input?: Record<string, unknown>;
366
- overrides?: { steps?: Record<string, Record<string, unknown>> };
367
- metadata?: Record<string, unknown>;
368
- }): Promise<MultipartParts> {
369
- const fd = new FormData();
370
- fd.append('target', args.target);
371
- if (args.tags !== undefined) fd.append('tags', JSON.stringify(args.tags));
372
- const { scalars, fileCount } = await appendFiles(fd, args.input);
373
- fd.append('input', JSON.stringify(scalars));
374
- if (args.overrides) {
375
- fd.append('overrides', JSON.stringify(args.overrides));
376
- }
377
- if (args.metadata) {
378
- fd.append('metadata', JSON.stringify(args.metadata));
379
- }
380
- return { formData: fd, fileCount };
381
- }
382
-
383
- /** Build multipart for endpoints that accept one file field plus optional name. */
384
- export async function buildSingleFileMultipart(file: FileInput, name?: string): Promise<FormData> {
385
- const fd = new FormData();
386
- const { blob, filename } = await resolveFileBlob(file);
387
- fd.append('file', blob, filename);
388
- if (name) fd.append('name', name);
389
- return fd;
390
- }