@anyformat/sdk 0.2.2 → 1.0.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -23,23 +23,75 @@ __export(index_exports, {
23
23
  APIError: () => APIError,
24
24
  Anyformat: () => Anyformat,
25
25
  AnyformatError: () => AnyformatError,
26
- BadRequest: () => BadRequest,
27
- Forbidden: () => Forbidden,
28
- NotFound: () => NotFound,
26
+ BadRequestError: () => BadRequestError,
27
+ DatasetUpload: () => DatasetUpload,
28
+ ExtractionCancelledError: () => ExtractionCancelledError,
29
+ ExtractionFailedError: () => ExtractionFailedError,
30
+ ForbiddenError: () => ForbiddenError,
31
+ InsufficientScopeError: () => InsufficientScopeError,
32
+ NotFoundError: () => NotFoundError,
29
33
  ParseView: () => ParseView,
30
- RateLimited: () => RateLimited,
34
+ PaymentRequiredError: () => PaymentRequiredError,
35
+ RateLimitedError: () => RateLimitedError,
31
36
  Result: () => Result,
32
37
  Run: () => Run,
33
- SDKTimeout: () => SDKTimeout,
38
+ RunFailedError: () => RunFailedError,
39
+ SDKTimeoutError: () => SDKTimeoutError,
34
40
  Schema: () => Schema,
35
41
  ServerError: () => ServerError,
36
- Unauthorized: () => Unauthorized,
42
+ TermsAcceptanceRequiredError: () => TermsAcceptanceRequiredError,
43
+ UnauthorizedError: () => UnauthorizedError,
44
+ Upload: () => Upload,
37
45
  Workflow: () => Workflow,
38
46
  WorkflowBuilder: () => WorkflowBuilder,
39
- WorkflowBuilderError: () => WorkflowBuilderError
47
+ WorkflowBuilderError: () => WorkflowBuilderError,
48
+ WorkflowNameConflictError: () => WorkflowNameConflictError
40
49
  });
41
50
  module.exports = __toCommonJS(index_exports);
42
51
 
52
+ // package.json
53
+ var package_default = {
54
+ name: "@anyformat/sdk",
55
+ version: "1.0.0-rc.2",
56
+ description: "TypeScript SDK for the AnyFormat API",
57
+ license: "MIT",
58
+ author: "Anyformat <info@anyformat.ai>",
59
+ type: "module",
60
+ main: "./dist/index.cjs",
61
+ module: "./dist/index.js",
62
+ types: "./dist/index.d.ts",
63
+ exports: {
64
+ ".": {
65
+ types: "./dist/index.d.ts",
66
+ import: "./dist/index.js",
67
+ require: "./dist/index.cjs"
68
+ }
69
+ },
70
+ files: [
71
+ "dist"
72
+ ],
73
+ engines: {
74
+ node: ">=18"
75
+ },
76
+ scripts: {
77
+ "gen:spec": 'ROOT=$(unset GIT_DIR && git rev-parse --show-toplevel) && cd "$ROOT/anyformat/services/api" && uv run python "$ROOT/anyformat/libs/public/sdk-js/scripts/dump_openapi.py" "$ROOT/anyformat/libs/public/sdk-js/openapi/v2.json" --surface v2 && uv run python "$ROOT/anyformat/libs/public/sdk-js/scripts/dump_openapi.py" "$ROOT/anyformat/libs/public/sdk-js/openapi/v3.json" --surface v3',
78
+ "gen:client": "openapi-ts",
79
+ gen: "bun run gen:spec && bun run gen:client",
80
+ "gen:check": "bun run gen && git diff --exit-code -- openapi src/sdk",
81
+ build: "tsup",
82
+ typecheck: "tsc --noEmit",
83
+ test: "vitest run",
84
+ prepublishOnly: "bun run build"
85
+ },
86
+ devDependencies: {
87
+ "@hey-api/openapi-ts": "^0.99.0",
88
+ "@types/node": "^25.9.1",
89
+ tsup: "^8.3.0",
90
+ typescript: "^5.6.0",
91
+ vitest: "^4.1.7"
92
+ }
93
+ };
94
+
43
95
  // src/builder.ts
44
96
  var import_node_fs = require("fs");
45
97
  var import_node_path = require("path");
@@ -83,8 +135,8 @@ var Result = class {
83
135
  }
84
136
  raw;
85
137
  _parse;
86
- get collectionId() {
87
- return this.raw.collection_id;
138
+ get documentPacketId() {
139
+ return this.raw.document_packet_id;
88
140
  }
89
141
  get extractions() {
90
142
  return this.raw.extractions ?? [];
@@ -101,13 +153,22 @@ var Result = class {
101
153
  return this._parse;
102
154
  }
103
155
  /**
104
- * Convenience accessor for a top-level scalar field on the first
105
- * extraction (linear workflows). Returns `undefined` for missing fields
106
- * or list-valued fields — read `extractions` directly for those.
156
+ * Convenience accessor for a top-level field on the untagged (linear)
157
+ * extraction. Returns the scalar `ExtractedField` for a scalar field, or
158
+ * the array of row records (`ExtractedRows`) for a list/object field such
159
+ * as `line_items`. `undefined` only when the field is absent.
160
+ *
161
+ * Parameterise with the declared schema type to type a scalar's `.value`:
162
+ * `result.field<number>("total").value` is `number | null`.
107
163
  */
108
164
  field(name) {
109
- const value = this.extractions[0]?.fields?.[name];
110
- return value !== void 0 && !Array.isArray(value) ? value : void 0;
165
+ const untagged = this.extractions.find(
166
+ (e) => e.split_name == null && e.partition == null
167
+ );
168
+ const value = untagged?.fields?.[name];
169
+ if (value === void 0) return void 0;
170
+ if (Array.isArray(value)) return value;
171
+ return value;
111
172
  }
112
173
  };
113
174
 
@@ -120,39 +181,116 @@ var APIError = class extends AnyformatError {
120
181
  this.status = status;
121
182
  this.body = body;
122
183
  this.name = new.target.name;
184
+ if (body && typeof body === "object") {
185
+ const envelope = body;
186
+ if (typeof envelope.error_code === "string") this.errorCode = envelope.error_code;
187
+ if (envelope.detail !== void 0) this.detail = envelope.detail;
188
+ if (typeof envelope.retryable === "boolean") this.retryable = envelope.retryable;
189
+ if (typeof envelope.request_id === "string") this.requestId = envelope.request_id;
190
+ if (envelope.params && typeof envelope.params === "object") {
191
+ this.params = envelope.params;
192
+ }
193
+ }
123
194
  }
124
195
  status;
125
196
  body;
197
+ /** Stable identifier for programmatic handling, e.g. `PAYMENT_REQUIRED`. */
198
+ errorCode;
199
+ /** Developer-facing explanation; not surfaced in `message` (ADR platform/0053 §2). Often a `ValidationItem[]`. */
200
+ detail;
201
+ /** Named substitutions the `error` summary refers to, e.g. `{ required_scope }`. */
202
+ params;
203
+ /** Whether the API says retrying the same request can succeed. */
204
+ retryable;
205
+ /** Correlation id to quote in support requests. */
206
+ requestId;
126
207
  };
127
- var BadRequest = class extends APIError {
208
+ var BadRequestError = class extends APIError {
128
209
  };
129
- var Unauthorized = class extends APIError {
210
+ var UnauthorizedError = class extends APIError {
130
211
  };
131
- var Forbidden = class extends APIError {
212
+ var PaymentRequiredError = class extends APIError {
132
213
  };
133
- var NotFound = class extends APIError {
214
+ var ForbiddenError = class extends APIError {
134
215
  };
135
- var RateLimited = class extends APIError {
216
+ var NotFoundError = class extends APIError {
217
+ };
218
+ var RateLimitedError = class extends APIError {
219
+ constructor(status, message, body, retryAfter) {
220
+ super(status, message, body);
221
+ this.retryAfter = retryAfter;
222
+ }
223
+ retryAfter;
136
224
  };
137
225
  var ServerError = class extends APIError {
138
226
  };
139
- var SDKTimeout = class extends AnyformatError {
227
+ function parseRetryAfter(raw) {
228
+ if (raw == null || raw.trim() === "") return void 0;
229
+ const seconds = Number(raw);
230
+ if (!Number.isNaN(seconds)) return seconds;
231
+ const when = Date.parse(raw);
232
+ if (Number.isNaN(when)) return void 0;
233
+ return Math.max((when - Date.now()) / 1e3, 0);
234
+ }
235
+ var InsufficientScopeError = class extends ForbiddenError {
236
+ };
237
+ var TermsAcceptanceRequiredError = class extends ForbiddenError {
238
+ };
239
+ var WorkflowNameConflictError = class extends APIError {
240
+ };
241
+ var SDKTimeoutError = class extends AnyformatError {
242
+ };
243
+ var RunFailedError = class extends AnyformatError {
244
+ constructor(runId, status) {
245
+ super(`Run ${runId} ended with status "${status}"`);
246
+ this.runId = runId;
247
+ this.status = status;
248
+ this.name = new.target.name;
249
+ }
250
+ runId;
251
+ status;
252
+ };
253
+ var ExtractionFailedError = class extends RunFailedError {
254
+ constructor(runId) {
255
+ super(runId, "error");
256
+ }
257
+ };
258
+ var ExtractionCancelledError = class extends RunFailedError {
259
+ constructor(runId) {
260
+ super(runId, "cancelled");
261
+ }
140
262
  };
141
263
  var WorkflowBuilderError = class extends AnyformatError {
142
264
  };
143
- function toApiError(status, body) {
144
- const message = `AnyFormat API error (${status})`;
265
+ function messageFrom(status, body) {
266
+ const fallback = `AnyFormat API error (${status})`;
267
+ if (!body || typeof body !== "object") return fallback;
268
+ const envelope = body;
269
+ return typeof envelope.error === "string" && envelope.error ? envelope.error : fallback;
270
+ }
271
+ var BY_ERROR_CODE = {
272
+ insufficient_api_key_scope: InsufficientScopeError,
273
+ terms_acceptance_required: TermsAcceptanceRequiredError,
274
+ WORKFLOW_NAME_CONFLICT: WorkflowNameConflictError
275
+ };
276
+ function toApiError(status, body, headers) {
277
+ const message = messageFrom(status, body);
278
+ const errorCode = body && typeof body === "object" && typeof body.error_code === "string" ? body.error_code : void 0;
279
+ const ByCode = errorCode ? BY_ERROR_CODE[errorCode] : void 0;
280
+ if (ByCode) return new ByCode(status, message, body);
145
281
  switch (status) {
146
282
  case 400:
147
- return new BadRequest(status, message, body);
283
+ return new BadRequestError(status, message, body);
148
284
  case 401:
149
- return new Unauthorized(status, message, body);
285
+ return new UnauthorizedError(status, message, body);
286
+ case 402:
287
+ return new PaymentRequiredError(status, message, body);
150
288
  case 403:
151
- return new Forbidden(status, message, body);
289
+ return new ForbiddenError(status, message, body);
152
290
  case 404:
153
- return new NotFound(status, message, body);
291
+ return new NotFoundError(status, message, body);
154
292
  case 429:
155
- return new RateLimited(status, message, body);
293
+ return new RateLimitedError(status, message, body, parseRetryAfter(headers?.get("Retry-After")));
156
294
  default:
157
295
  return status >= 500 ? new ServerError(status, message, body) : new APIError(status, message, body);
158
296
  }
@@ -212,7 +350,7 @@ function createSseClient({
212
350
  ...options
213
351
  }) {
214
352
  let lastEventId;
215
- const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
353
+ const sleep2 = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
216
354
  const createStream = async function* () {
217
355
  let retryDelay = sseDefaultRetryDelay ?? 3e3;
218
356
  let attempt = 0;
@@ -316,7 +454,7 @@ function createSseClient({
316
454
  break;
317
455
  }
318
456
  const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
319
- await sleep(backoff);
457
+ await sleep2(backoff);
320
458
  }
321
459
  }
322
460
  };
@@ -969,46 +1107,115 @@ var createClient = (config = {}) => {
969
1107
  };
970
1108
 
971
1109
  // src/sdk/client.gen.ts
972
- var client = createClient(createConfig({ baseUrl: "https://api-dev.anyformat.ai" }));
1110
+ var client = createClient(createConfig({ baseUrl: "https://api.anyformat.dev" }));
973
1111
 
974
1112
  // src/sdk/sdk.gen.ts
975
- var v2ListWorkflows = (options) => (options?.client ?? client).get({
1113
+ var v3DeleteDocumentPacket = (options) => (options.client ?? client).delete({
1114
+ security: [{ scheme: "bearer", type: "http" }],
1115
+ url: "/v3/document-packets/{document_packet_id}/",
1116
+ ...options
1117
+ });
1118
+ var v3GetDocumentPacket = (options) => (options.client ?? client).get({
1119
+ security: [{ scheme: "bearer", type: "http" }],
1120
+ url: "/v3/document-packets/{document_packet_id}/",
1121
+ ...options
1122
+ });
1123
+ var v3RunDocumentPacket = (options) => (options.client ?? client).post({
976
1124
  security: [{ scheme: "bearer", type: "http" }],
977
- url: "/v2/workflows/",
1125
+ url: "/v3/document-packets/{document_packet_id}/run/",
978
1126
  ...options
979
1127
  });
980
- var v2CreateWorkflow = (options) => (options.client ?? client).post({
1128
+ var v3Parse = (options) => (options.client ?? client).post({
1129
+ ...formDataBodySerializer,
981
1130
  security: [{ scheme: "bearer", type: "http" }],
982
- url: "/v2/workflows/",
1131
+ url: "/v3/parse/",
1132
+ ...options,
1133
+ headers: {
1134
+ "Content-Type": null,
1135
+ ...options.headers
1136
+ }
1137
+ });
1138
+ var v3GetRun = (options) => (options.client ?? client).get({
1139
+ security: [{ scheme: "bearer", type: "http" }],
1140
+ url: "/v3/runs/{run_id}/",
1141
+ ...options
1142
+ });
1143
+ var v3ListWorkflows = (options) => (options?.client ?? client).get({
1144
+ security: [{ scheme: "bearer", type: "http" }],
1145
+ url: "/v3/workflows/",
1146
+ ...options
1147
+ });
1148
+ var v3CreateWorkflow = (options) => (options.client ?? client).post({
1149
+ security: [{ scheme: "bearer", type: "http" }],
1150
+ url: "/v3/workflows/",
983
1151
  ...options,
984
1152
  headers: {
985
1153
  "Content-Type": "application/json",
986
1154
  ...options.headers
987
1155
  }
988
1156
  });
989
- var v2DeleteWorkflow = (options) => (options.client ?? client).delete({
1157
+ var v3DeleteWorkflow = (options) => (options.client ?? client).delete({
1158
+ security: [{ scheme: "bearer", type: "http" }],
1159
+ url: "/v3/workflows/{workflow_id}/",
1160
+ ...options
1161
+ });
1162
+ var v3GetWorkflow = (options) => (options.client ?? client).get({
990
1163
  security: [{ scheme: "bearer", type: "http" }],
991
- url: "/v2/workflows/{workflow_id}/",
1164
+ url: "/v3/workflows/{workflow_id}/",
992
1165
  ...options
993
1166
  });
994
- var v2UpdateWorkflow = (options) => (options.client ?? client).put({
1167
+ var v3UpdateWorkflow = (options) => (options.client ?? client).patch({
995
1168
  security: [{ scheme: "bearer", type: "http" }],
996
- url: "/v2/workflows/{workflow_id}/",
1169
+ url: "/v3/workflows/{workflow_id}/",
997
1170
  ...options,
998
1171
  headers: {
999
1172
  "Content-Type": "application/json",
1000
1173
  ...options.headers
1001
1174
  }
1002
1175
  });
1003
- var v2GetFileResults = (options) => (options.client ?? client).get({
1176
+ var v3UploadToDataset = (options) => (options.client ?? client).post({
1177
+ ...formDataBodySerializer,
1004
1178
  security: [{ scheme: "bearer", type: "http" }],
1005
- url: "/v2/workflows/{workflow_id}/files/{collection_id}/results/",
1179
+ url: "/v3/workflows/{workflow_id}/dataset/upload/",
1180
+ ...options,
1181
+ headers: {
1182
+ "Content-Type": null,
1183
+ ...options.headers
1184
+ }
1185
+ });
1186
+ var v3ListWorkflowDocumentPackets = (options) => (options.client ?? client).get({
1187
+ security: [{ scheme: "bearer", type: "http" }],
1188
+ url: "/v3/workflows/{workflow_id}/document-packets/",
1189
+ ...options
1190
+ });
1191
+ var v3ListWorkflowRuns = (options) => (options.client ?? client).get({
1192
+ security: [{ scheme: "bearer", type: "http" }],
1193
+ url: "/v3/workflows/{workflow_id}/runs/",
1006
1194
  ...options
1007
1195
  });
1008
- var v2RunWorkflow = (options) => (options.client ?? client).post({
1196
+ var v3UploadToWorkflow = (options) => (options.client ?? client).post({
1009
1197
  ...formDataBodySerializer,
1010
1198
  security: [{ scheme: "bearer", type: "http" }],
1011
- url: "/v2/workflows/{workflow_id}/run/",
1199
+ url: "/v3/workflows/{workflow_id}/upload/",
1200
+ ...options,
1201
+ headers: {
1202
+ "Content-Type": null,
1203
+ ...options.headers
1204
+ }
1205
+ });
1206
+ var v3UploadFromUrl = (options) => (options.client ?? client).post({
1207
+ security: [{ scheme: "bearer", type: "http" }],
1208
+ url: "/v3/workflows/{workflow_id}/upload/from-url/",
1209
+ ...options,
1210
+ headers: {
1211
+ "Content-Type": "application/json",
1212
+ ...options.headers
1213
+ }
1214
+ });
1215
+ var v3UploadAndRunWorkflow = (options) => (options.client ?? client).post({
1216
+ ...formDataBodySerializer,
1217
+ security: [{ scheme: "bearer", type: "http" }],
1218
+ url: "/v3/workflows/{workflow_id}/upload/run/",
1012
1219
  ...options,
1013
1220
  headers: {
1014
1221
  "Content-Type": null,
@@ -1017,36 +1224,129 @@ var v2RunWorkflow = (options) => (options.client ?? client).post({
1017
1224
  });
1018
1225
 
1019
1226
  // src/run.ts
1227
+ function isTransientStatus(status) {
1228
+ return status === 429 || status >= 500;
1229
+ }
1230
+ var RETRY_BASE_MS = 1e3;
1231
+ var RETRY_MAX_MS = 3e4;
1232
+ function retryDelayMs(response, attempt) {
1233
+ const retryAfter = parseRetryAfter(response?.headers?.get("Retry-After"));
1234
+ if (retryAfter !== void 0) return Math.min(retryAfter * 1e3, RETRY_MAX_MS);
1235
+ const base = Math.min(RETRY_BASE_MS * 2 ** attempt, RETRY_MAX_MS);
1236
+ return base * (0.75 + Math.random() * 0.5);
1237
+ }
1238
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1020
1239
  var Run = class {
1021
1240
  /** @internal */
1022
- constructor(client2, workflowId, id) {
1241
+ constructor(client2, id, workflowId, documentPacketId, status = "queued") {
1023
1242
  this.client = client2;
1024
- this.workflowId = workflowId;
1025
1243
  this.id = id;
1244
+ this.workflowId = workflowId;
1245
+ this.documentPacketId = documentPacketId;
1246
+ this.status = status;
1026
1247
  }
1027
1248
  client;
1028
- workflowId;
1029
1249
  id;
1250
+ workflowId;
1251
+ documentPacketId;
1252
+ /** Status at trigger time, refreshed on every `wait()` poll. */
1253
+ status;
1030
1254
  async wait(opts = {}) {
1031
1255
  const timeoutMs = opts.timeoutMs ?? 3e5;
1032
1256
  const pollMs = opts.pollMs ?? 3e3;
1033
1257
  const deadline = Date.now() + timeoutMs;
1034
- while (Date.now() < deadline) {
1035
- const results = await v2GetFileResults({
1036
- client: this.client,
1037
- path: { workflow_id: this.workflowId, collection_id: this.id }
1038
- });
1039
- if (!results.error) return new Result(results.data);
1040
- if (results.response?.status !== 412) {
1041
- throw toApiError(results.response?.status ?? 500, results.error);
1258
+ let transientFailures = 0;
1259
+ for (; ; ) {
1260
+ const res = await v3GetRun({ client: this.client, path: { run_id: this.id } });
1261
+ if (res.error) {
1262
+ const status = res.response?.status ?? 500;
1263
+ if (!isTransientStatus(status)) throw toApiError(status, res.error, res.response?.headers);
1264
+ const remainingMs = deadline - Date.now();
1265
+ if (remainingMs <= 0) {
1266
+ throw new SDKTimeoutError(`Extraction did not complete within ${timeoutMs}ms`);
1267
+ }
1268
+ await sleep(Math.min(retryDelayMs(res.response, transientFailures), remainingMs));
1269
+ transientFailures += 1;
1270
+ continue;
1271
+ }
1272
+ transientFailures = 0;
1273
+ const detail = res.data;
1274
+ this.status = detail.status;
1275
+ if (detail.status === "processed") {
1276
+ if (!detail.results) {
1277
+ throw new AnyformatError(`Run ${this.id} is processed but the API returned no results`);
1278
+ }
1279
+ return new Result(detail.results);
1042
1280
  }
1043
- await new Promise((resolve) => setTimeout(resolve, pollMs));
1281
+ if (detail.status === "error") throw new ExtractionFailedError(this.id);
1282
+ if (detail.status === "cancelled") throw new ExtractionCancelledError(this.id);
1283
+ if (Date.now() >= deadline) {
1284
+ throw new SDKTimeoutError(`Extraction did not complete within ${timeoutMs}ms`);
1285
+ }
1286
+ await sleep(pollMs);
1044
1287
  }
1045
- throw new SDKTimeout(`Extraction did not complete within ${timeoutMs}ms`);
1288
+ }
1289
+ };
1290
+
1291
+ // src/upload.ts
1292
+ var DatasetUpload = class {
1293
+ /** @internal */
1294
+ constructor(workflowId, documentPacketId, files, groundTruthSaved) {
1295
+ this.workflowId = workflowId;
1296
+ this.documentPacketId = documentPacketId;
1297
+ this.files = files;
1298
+ this.groundTruthSaved = groundTruthSaved;
1299
+ }
1300
+ workflowId;
1301
+ documentPacketId;
1302
+ files;
1303
+ groundTruthSaved;
1304
+ };
1305
+ var Upload = class {
1306
+ /** @internal */
1307
+ constructor(client2, workflowId, documentPacketId, files) {
1308
+ this.client = client2;
1309
+ this.workflowId = workflowId;
1310
+ this.documentPacketId = documentPacketId;
1311
+ this.files = files;
1312
+ }
1313
+ client;
1314
+ workflowId;
1315
+ documentPacketId;
1316
+ files;
1317
+ /** Trigger extraction on the staged packet and return a pending `Run`. */
1318
+ async run(opts = {}) {
1319
+ const res = await v3RunDocumentPacket({
1320
+ client: this.client,
1321
+ path: { document_packet_id: this.documentPacketId },
1322
+ ...opts.idempotencyKey ? { headers: { "Idempotency-Key": opts.idempotencyKey } } : {}
1323
+ });
1324
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1325
+ const data = res.data;
1326
+ return new Run(this.client, data.run_id, data.workflow_id, data.document_packet_id, data.status);
1046
1327
  }
1047
1328
  };
1048
1329
 
1049
1330
  // src/workflow.ts
1331
+ var MAX_FILES_PER_PACKET = 100;
1332
+ function normalizeFiles(files, op) {
1333
+ const list = files == null ? [] : Array.isArray(files) ? files : [files];
1334
+ if (list.length === 0) {
1335
+ throw new WorkflowBuilderError(`${op}() requires at least one named file`);
1336
+ }
1337
+ if (list.length > MAX_FILES_PER_PACKET) {
1338
+ throw new WorkflowBuilderError(`${op}() accepts at most ${MAX_FILES_PER_PACKET} files per document packet`);
1339
+ }
1340
+ for (const file of list) {
1341
+ const filename = file.name;
1342
+ if (typeof filename !== "string" || filename.length === 0) {
1343
+ throw new WorkflowBuilderError(
1344
+ `${op}() needs a named file so the server can detect its type \u2014 pass a File, e.g. new File([bytes], "invoice.pdf"), not a bare Blob`
1345
+ );
1346
+ }
1347
+ }
1348
+ return list;
1349
+ }
1050
1350
  var Workflow = class {
1051
1351
  /** @internal */
1052
1352
  constructor(client2, id, name) {
@@ -1057,29 +1357,90 @@ var Workflow = class {
1057
1357
  client;
1058
1358
  id;
1059
1359
  name;
1060
- /** Submit a document against this workflow and return a pending `Run`. */
1061
- async run(file = null, opts = {}) {
1062
- if (file === null && !opts.text) {
1063
- throw new WorkflowBuilderError("run() requires a document \u2014 pass a file or non-empty opts.text");
1064
- }
1065
- if (file !== null && opts.text !== void 0) {
1066
- throw new WorkflowBuilderError("run() accepts either a file or text, not both");
1067
- }
1068
- if (file !== null) {
1069
- const filename = file.name;
1070
- if (typeof filename !== "string" || filename.length === 0) {
1071
- throw new WorkflowBuilderError(
1072
- 'run() needs a named file so the server can detect its type \u2014 pass a File, e.g. new File([bytes], "invoice.pdf"), not a bare Blob'
1073
- );
1074
- }
1360
+ /** Upload 1..100 files as one document packet and run it. Returns a pending `Run`. */
1361
+ async run(files = null, opts = {}) {
1362
+ const list = normalizeFiles(files, "run");
1363
+ const submitted = await v3UploadAndRunWorkflow({
1364
+ client: this.client,
1365
+ path: { workflow_id: this.id },
1366
+ body: { files: list, ...opts.onConflict ? { on_conflict: opts.onConflict } : {} },
1367
+ ...opts.idempotencyKey ? { headers: { "Idempotency-Key": opts.idempotencyKey } } : {}
1368
+ });
1369
+ if (submitted.error) throw toApiError(submitted.response?.status ?? 500, submitted.error, submitted.response?.headers);
1370
+ const data = submitted.data;
1371
+ return new Run(this.client, data.run_id, data.workflow_id, data.document_packet_id, data.status);
1372
+ }
1373
+ /**
1374
+ * Stage 1..100 files as one document packet WITHOUT running it (no credits
1375
+ * spent). Returns an `Upload`; call `.run()` on it to start extraction.
1376
+ */
1377
+ async upload(files = null, opts = {}) {
1378
+ const list = normalizeFiles(files, "upload");
1379
+ const staged = await v3UploadToWorkflow({
1380
+ client: this.client,
1381
+ path: { workflow_id: this.id },
1382
+ body: { files: list, ...opts.onConflict ? { on_conflict: opts.onConflict } : {} },
1383
+ ...opts.idempotencyKey ? { headers: { "Idempotency-Key": opts.idempotencyKey } } : {}
1384
+ });
1385
+ if (staged.error) throw toApiError(staged.response?.status ?? 500, staged.error, staged.response?.headers);
1386
+ const data = staged.data;
1387
+ return new Upload(this.client, data.workflow_id, data.document_packet_id, data.files);
1388
+ }
1389
+ /**
1390
+ * Upload 1..100 files as ONE document (+ optional ground truth) into the
1391
+ * workflow's dataset, as one document packet. Atomic: any rejected file or a
1392
+ * ground-truth failure fails the call and stores nothing. By default a
1393
+ * colliding filename fails with `409`; pass `onConflict: "rename"` to
1394
+ * auto-rename instead.
1395
+ */
1396
+ async uploadToDataset(files = null, opts = {}) {
1397
+ const list = normalizeFiles(files, "uploadToDataset");
1398
+ const registered = await v3UploadToDataset({
1399
+ client: this.client,
1400
+ path: { workflow_id: this.id },
1401
+ body: {
1402
+ files: list,
1403
+ ...opts.groundTruth != null ? { ground_truth: JSON.stringify(opts.groundTruth) } : {},
1404
+ ...opts.onConflict ? { on_conflict: opts.onConflict } : {}
1405
+ },
1406
+ ...opts.idempotencyKey ? { headers: { "Idempotency-Key": opts.idempotencyKey } } : {}
1407
+ });
1408
+ if (registered.error) throw toApiError(registered.response?.status ?? 500, registered.error, registered.response?.headers);
1409
+ const data = registered.data;
1410
+ return new DatasetUpload(this.id, data.document_packet_id, data.files, data.ground_truth_saved);
1411
+ }
1412
+ /**
1413
+ * Client-orchestrated bulk dataset upload: one atomic call per document,
1414
+ * in order. There is no batch endpoint — each document is bounded and
1415
+ * independently retryable. On failure the call rejects; documents already
1416
+ * uploaded stay registered.
1417
+ */
1418
+ async uploadDocumentsToDataset(documents) {
1419
+ const uploaded = [];
1420
+ for (const doc of documents) {
1421
+ uploaded.push(
1422
+ await this.uploadToDataset(doc.files, {
1423
+ groundTruth: doc.groundTruth,
1424
+ idempotencyKey: doc.idempotencyKey,
1425
+ onConflict: doc.onConflict
1426
+ })
1427
+ );
1075
1428
  }
1076
- const submitted = await v2RunWorkflow({
1429
+ return uploaded;
1430
+ }
1431
+ /**
1432
+ * Import 1..10 HTTPS URLs server-side into one document packet, atomically.
1433
+ * Returns an `Upload`; call `.run()` on it to start extraction.
1434
+ */
1435
+ async uploadFromUrls(urls, opts = {}) {
1436
+ const staged = await v3UploadFromUrl({
1077
1437
  client: this.client,
1078
1438
  path: { workflow_id: this.id },
1079
- body: { file, text: opts.text ?? null }
1439
+ body: { urls, ...opts.onConflict ? { on_conflict: opts.onConflict } : {} }
1080
1440
  });
1081
- if (submitted.error) throw toApiError(submitted.response?.status ?? 500, submitted.error);
1082
- return new Run(this.client, this.id, submitted.data.id);
1441
+ if (staged.error) throw toApiError(staged.response?.status ?? 500, staged.error, staged.response?.headers);
1442
+ const data = staged.data;
1443
+ return new Upload(this.client, data.workflow_id, data.document_packet_id, data.files);
1083
1444
  }
1084
1445
  };
1085
1446
 
@@ -1109,13 +1470,16 @@ var WorkflowBuilder = class {
1109
1470
  }
1110
1471
  parse(opts = {}) {
1111
1472
  this.require(this.parseNode === null, "parse() can only be called once");
1473
+ const o = opts;
1112
1474
  this.parseNode = {
1113
1475
  type: "parse",
1114
- id: opts.id ?? this.nextId("parse"),
1115
- mode: opts.mode ?? "standard",
1116
- ...opts.promptHint !== void 0 ? { prompt_hint: opts.promptHint } : {},
1117
- figure_enhancement: opts.figureEnhancement ?? false,
1118
- cache: opts.cache ?? true
1476
+ id: o.id ?? this.nextId("parse"),
1477
+ mode: o.mode ?? "standard",
1478
+ ...o.promptHint !== void 0 ? { prompt_hint: o.promptHint } : {},
1479
+ figure_enhancement: o.figureEnhancement ?? false,
1480
+ cache: o.cache ?? true,
1481
+ ...o.effort !== void 0 ? { effort: o.effort } : {},
1482
+ ...o.scannedPages !== void 0 ? { scanned_pages: o.scannedPages } : {}
1119
1483
  };
1120
1484
  return this;
1121
1485
  }
@@ -1162,9 +1526,12 @@ var WorkflowBuilder = class {
1162
1526
  const node = {
1163
1527
  type: "extract",
1164
1528
  id: opts.id ?? this.nextId("extract"),
1529
+ ...opts.mode !== void 0 ? { mode: opts.mode } : {},
1165
1530
  extraction_schema: { fields },
1166
1531
  ...lookupFileUploads.length > 0 ? { lookup_file_uploads: lookupFileUploads } : {},
1167
- ...opts.lookupSuggestion !== void 0 ? { lookup_suggestion: opts.lookupSuggestion } : {}
1532
+ ...opts.lookupSuggestion !== void 0 ? { lookup_suggestion: opts.lookupSuggestion } : {},
1533
+ ...opts.lookupReasoningEffort !== void 0 ? { lookup_reasoning_effort: opts.lookupReasoningEffort } : {},
1534
+ ...opts.useImages !== void 0 ? { use_images: opts.useImages } : {}
1168
1535
  };
1169
1536
  this.extracts.push([node, branchId]);
1170
1537
  return this;
@@ -1246,21 +1613,22 @@ var WorkflowBuilder = class {
1246
1613
  }
1247
1614
  return { name: this.name, description: this.description, nodes, edges };
1248
1615
  }
1249
- /** Persist the workflow and return a handle you can `.run(file)` on. */
1616
+ /** Persist the workflow and return a handle you can `.run(files)` on. */
1250
1617
  async create() {
1251
- const res = await v2CreateWorkflow({ client: this.client, body: this.build() });
1252
- if (res.error) throw toApiError(res.response?.status ?? 500, res.error);
1618
+ const res = await v3CreateWorkflow({ client: this.client, body: this.build() });
1619
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1253
1620
  return new Workflow(this.client, res.data.id, res.data.name);
1254
1621
  }
1255
- /** Replace an existing workflow's definition and return a handle you can `.run(file)` on. */
1622
+ /** Replace an existing workflow's typed graph and return a handle you can `.run(files)` on. */
1256
1623
  async update(workflowId) {
1257
- const res = await v2UpdateWorkflow({ client: this.client, path: { workflow_id: workflowId }, body: this.build() });
1258
- if (res.error) throw toApiError(res.response?.status ?? 500, res.error);
1624
+ const res = await v3UpdateWorkflow({ client: this.client, path: { workflow_id: workflowId }, body: this.build() });
1625
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1259
1626
  return new Workflow(this.client, res.data.id, res.data.name);
1260
1627
  }
1261
1628
  };
1262
1629
 
1263
1630
  // src/client.ts
1631
+ var SDK_USER_AGENT = `anyformat-typescript-sdk-${package_default.version}`;
1264
1632
  var Anyformat = class {
1265
1633
  /** @internal */
1266
1634
  _client;
@@ -1270,47 +1638,206 @@ var Anyformat = class {
1270
1638
  baseUrl: opts.baseUrl ?? "https://api.anyformat.ai",
1271
1639
  auth: opts.apiKey,
1272
1640
  // Identifies the caller in our logs (Datadog facet). Plain HTTP callers
1273
- // send no such header and are logged as origin "api".
1274
- headers: { "x-anyformat-origin": "js-sdk" }
1641
+ // send no such header and are logged as origin "api". User-Agent is
1642
+ // ignored by browsers (forbidden header) but used by Node fetch.
1643
+ headers: {
1644
+ "x-anyformat-origin": "js-sdk",
1645
+ "User-Agent": SDK_USER_AGENT
1646
+ }
1275
1647
  })
1276
1648
  );
1277
1649
  }
1278
1650
  workflow(name, description) {
1279
1651
  return new WorkflowBuilder(this._client, name, description);
1280
1652
  }
1281
- async listWorkflows(opts) {
1282
- const res = await v2ListWorkflows({
1653
+ async listWorkflows(opts = {}) {
1654
+ const res = await v3ListWorkflows({
1655
+ client: this._client,
1656
+ query: { limit: opts.limit, cursor: opts.cursor }
1657
+ });
1658
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1659
+ return {
1660
+ items: res.data.items.map((r) => new Workflow(this._client, r.id, r.name)),
1661
+ nextCursor: res.data.next_cursor ?? null
1662
+ };
1663
+ }
1664
+ /** Retrieve a workflow with its complete typed graph inline (round-trippable into `updateWorkflow`). */
1665
+ async getWorkflow(workflowId) {
1666
+ const res = await v3GetWorkflow({ client: this._client, path: { workflow_id: workflowId } });
1667
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1668
+ return res.data;
1669
+ }
1670
+ /**
1671
+ * Replace a workflow's typed graph (atomic). Accepts the shape `getWorkflow`
1672
+ * returns — echo each field's `persistent_id` unchanged (including across
1673
+ * renames) to keep the field's identity; omit it for new fields.
1674
+ */
1675
+ async updateWorkflow(workflowId, definition) {
1676
+ const res = await v3UpdateWorkflow({
1283
1677
  client: this._client,
1284
- query: { page: opts?.page, page_size: opts?.pageSize, status: opts?.status }
1678
+ path: { workflow_id: workflowId },
1679
+ // The PATCH body forbids unknown keys, so a fetched detail's read-only
1680
+ // fields (id, timestamps) must not be forwarded.
1681
+ body: {
1682
+ name: definition.name,
1683
+ description: definition.description,
1684
+ nodes: definition.nodes,
1685
+ edges: definition.edges
1686
+ }
1285
1687
  });
1286
- if (res.error) throw toApiError(res.response?.status ?? 500, res.error);
1287
- return res.data.results.map((r) => new Workflow(this._client, r.id, r.name ?? ""));
1688
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1689
+ return res.data;
1288
1690
  }
1289
1691
  async deleteWorkflow(workflowId) {
1290
- const res = await v2DeleteWorkflow({
1692
+ const res = await v3DeleteWorkflow({
1291
1693
  client: this._client,
1292
1694
  path: { workflow_id: workflowId }
1293
1695
  });
1294
- if (res.error) throw toApiError(res.response?.status ?? 500, res.error);
1696
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1295
1697
  return workflowId;
1296
1698
  }
1699
+ /** Stage 1..100 files as one document packet without running it. Returns an `Upload`. */
1700
+ upload(workflowId, files, opts = {}) {
1701
+ return new Workflow(this._client, workflowId, "").upload(files, opts);
1702
+ }
1703
+ /** Upload 1..100 files (+ optional ground truth) as one dataset collection. Returns a `DatasetUpload`. */
1704
+ uploadToDataset(workflowId, files, opts = {}) {
1705
+ return new Workflow(this._client, workflowId, "").uploadToDataset(files, opts);
1706
+ }
1707
+ /** Bulk-upload documents into a workflow's dataset, one atomic call per document. */
1708
+ uploadDocumentsToDataset(workflowId, documents) {
1709
+ return new Workflow(this._client, workflowId, "").uploadDocumentsToDataset(documents);
1710
+ }
1711
+ async getDocumentPacket(documentPacketId) {
1712
+ const res = await v3GetDocumentPacket({
1713
+ client: this._client,
1714
+ path: { document_packet_id: documentPacketId }
1715
+ });
1716
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1717
+ return res.data;
1718
+ }
1719
+ /** Delete a document packet and all its files. Irreversible. */
1720
+ async deleteDocumentPacket(documentPacketId) {
1721
+ const res = await v3DeleteDocumentPacket({
1722
+ client: this._client,
1723
+ path: { document_packet_id: documentPacketId }
1724
+ });
1725
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1726
+ return documentPacketId;
1727
+ }
1728
+ /** Run (or re-run) a document packet on the latest version of its workflow. */
1729
+ async runDocumentPacket(documentPacketId, opts = {}) {
1730
+ const res = await v3RunDocumentPacket({
1731
+ client: this._client,
1732
+ path: { document_packet_id: documentPacketId },
1733
+ ...opts.idempotencyKey ? { headers: { "Idempotency-Key": opts.idempotencyKey } } : {}
1734
+ });
1735
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1736
+ const data = res.data;
1737
+ return new Run(this._client, data.run_id, data.workflow_id, data.document_packet_id, data.status);
1738
+ }
1739
+ async listDocumentPackets(workflowId, opts = {}) {
1740
+ const res = await v3ListWorkflowDocumentPackets({
1741
+ client: this._client,
1742
+ path: { workflow_id: workflowId },
1743
+ query: { limit: opts.limit, cursor: opts.cursor }
1744
+ });
1745
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1746
+ return { items: res.data.items, nextCursor: res.data.next_cursor ?? null };
1747
+ }
1748
+ async listRuns(workflowId, opts = {}) {
1749
+ const res = await v3ListWorkflowRuns({
1750
+ client: this._client,
1751
+ path: { workflow_id: workflowId },
1752
+ query: { limit: opts.limit, cursor: opts.cursor }
1753
+ });
1754
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1755
+ return { items: res.data.items, nextCursor: res.data.next_cursor ?? null };
1756
+ }
1757
+ /**
1758
+ * Every workflow, following `nextCursor` across pages so no rows are silently
1759
+ * truncated. Lazy — each page is fetched on demand as the iterator advances.
1760
+ */
1761
+ async *iterWorkflows(opts = {}) {
1762
+ let cursor;
1763
+ for (; ; ) {
1764
+ const page = await this.listWorkflows({ limit: opts.limit, cursor });
1765
+ yield* page.items;
1766
+ if (page.nextCursor === null) return;
1767
+ cursor = page.nextCursor;
1768
+ }
1769
+ }
1770
+ /** Every document packet of a workflow, following `nextCursor` across pages. Lazy. */
1771
+ async *iterDocumentPackets(workflowId, opts = {}) {
1772
+ let cursor;
1773
+ for (; ; ) {
1774
+ const page = await this.listDocumentPackets(workflowId, { limit: opts.limit, cursor });
1775
+ yield* page.items;
1776
+ if (page.nextCursor === null) return;
1777
+ cursor = page.nextCursor;
1778
+ }
1779
+ }
1780
+ /** Every run of a workflow, following `nextCursor` across pages. Lazy. */
1781
+ async *iterRuns(workflowId, opts = {}) {
1782
+ let cursor;
1783
+ for (; ; ) {
1784
+ const page = await this.listRuns(workflowId, { limit: opts.limit, cursor });
1785
+ yield* page.items;
1786
+ if (page.nextCursor === null) return;
1787
+ cursor = page.nextCursor;
1788
+ }
1789
+ }
1790
+ /** Retrieve one run: lifecycle status plus results inline once `processed`. */
1791
+ async getRun(runId) {
1792
+ const res = await v3GetRun({ client: this._client, path: { run_id: runId } });
1793
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1794
+ return res.data;
1795
+ }
1796
+ /**
1797
+ * Parse a document with the platform's atomic parse operation (fast lite
1798
+ * parse). Returns the run id; poll `getParseMarkdown(runId)` for the parsed
1799
+ * markdown.
1800
+ */
1801
+ async parse(file) {
1802
+ const res = await v3Parse({ client: this._client, body: { file } });
1803
+ if (res.error !== void 0) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1804
+ return res.data.run_id;
1805
+ }
1806
+ /**
1807
+ * Poll a parse run. Returns the parsed markdown once the run is `processed`,
1808
+ * or `null` while it is still queued or in progress.
1809
+ */
1810
+ async getParseMarkdown(runId) {
1811
+ const run = await this.getRun(runId);
1812
+ if (run.status === "processed") {
1813
+ const markdown = run.results?.parse?.markdown;
1814
+ if (markdown == null) throw new AnyformatError(`Run ${runId} is processed but the API returned no results`);
1815
+ return markdown;
1816
+ }
1817
+ if (run.status === "error") throw new ExtractionFailedError(runId);
1818
+ if (run.status === "cancelled") throw new ExtractionCancelledError(runId);
1819
+ return null;
1820
+ }
1297
1821
  };
1298
1822
 
1299
1823
  // src/schema.ts
1300
- function withLookup(base, opts) {
1301
- if (opts?.lookup) return { ...base, lookup: true };
1302
- return base;
1824
+ function withOpts(base, opts) {
1825
+ return {
1826
+ ...base,
1827
+ ...opts?.source && opts.source !== "extraction" ? { source: opts.source } : {},
1828
+ ...opts?.persistentId !== void 0 ? { persistent_id: opts.persistentId } : {}
1829
+ };
1303
1830
  }
1304
1831
  var Schema = {
1305
- string: (name, description, opts) => withLookup({ data_type: "string", name, description }, opts),
1306
- integer: (name, description, opts) => withLookup({ data_type: "integer", name, description }, opts),
1307
- float: (name, description, opts) => withLookup({ data_type: "float", name, description }, opts),
1308
- boolean: (name, description, opts) => withLookup({ data_type: "boolean", name, description }, opts),
1309
- date: (name, description, opts) => withLookup({ data_type: "date", name, description }, opts),
1310
- datetime: (name, description, opts) => withLookup({ data_type: "datetime", name, description }, opts),
1311
- enum: (name, description, options, opts) => withLookup({ data_type: "enum", name, description, enum_options: options }, opts),
1312
- multiSelect: (name, description, options, opts) => withLookup({ data_type: "multi_select", name, description, enum_options: options }, opts),
1313
- object: (name, description, fields, opts) => withLookup({ data_type: "object", name, description, nested_fields: fields }, opts),
1832
+ string: (name, description, opts) => withOpts({ data_type: "string", name, description }, opts),
1833
+ integer: (name, description, opts) => withOpts({ data_type: "integer", name, description }, opts),
1834
+ float: (name, description, opts) => withOpts({ data_type: "float", name, description }, opts),
1835
+ boolean: (name, description, opts) => withOpts({ data_type: "boolean", name, description }, opts),
1836
+ date: (name, description, opts) => withOpts({ data_type: "date", name, description }, opts),
1837
+ datetime: (name, description, opts) => withOpts({ data_type: "datetime", name, description }, opts),
1838
+ enum: (name, description, options, opts) => withOpts({ data_type: "enum", name, description, enum_options: options }, opts),
1839
+ multiSelect: (name, description, options, opts) => withOpts({ data_type: "multi_select", name, description, enum_options: options }, opts),
1840
+ object: (name, description, fields, opts) => withOpts({ data_type: "object", name, description, nested_fields: fields }, opts),
1314
1841
  option: (name, description) => ({ name, description })
1315
1842
  };
1316
1843
  // Annotate the CommonJS export names for ESM import in node:
@@ -1318,19 +1845,28 @@ var Schema = {
1318
1845
  APIError,
1319
1846
  Anyformat,
1320
1847
  AnyformatError,
1321
- BadRequest,
1322
- Forbidden,
1323
- NotFound,
1848
+ BadRequestError,
1849
+ DatasetUpload,
1850
+ ExtractionCancelledError,
1851
+ ExtractionFailedError,
1852
+ ForbiddenError,
1853
+ InsufficientScopeError,
1854
+ NotFoundError,
1324
1855
  ParseView,
1325
- RateLimited,
1856
+ PaymentRequiredError,
1857
+ RateLimitedError,
1326
1858
  Result,
1327
1859
  Run,
1328
- SDKTimeout,
1860
+ RunFailedError,
1861
+ SDKTimeoutError,
1329
1862
  Schema,
1330
1863
  ServerError,
1331
- Unauthorized,
1864
+ TermsAcceptanceRequiredError,
1865
+ UnauthorizedError,
1866
+ Upload,
1332
1867
  Workflow,
1333
1868
  WorkflowBuilder,
1334
- WorkflowBuilderError
1869
+ WorkflowBuilderError,
1870
+ WorkflowNameConflictError
1335
1871
  });
1336
1872
  //# sourceMappingURL=index.cjs.map