@anyformat/sdk 0.2.3 → 1.0.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.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // package.json
2
2
  var package_default = {
3
3
  name: "@anyformat/sdk",
4
- version: "0.2.3",
4
+ version: "1.0.0",
5
5
  description: "TypeScript SDK for the AnyFormat API",
6
6
  license: "MIT",
7
7
  author: "Anyformat <info@anyformat.ai>",
@@ -23,10 +23,10 @@ var package_default = {
23
23
  node: ">=18"
24
24
  },
25
25
  scripts: {
26
- "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"',
26
+ "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',
27
27
  "gen:client": "openapi-ts",
28
28
  gen: "bun run gen:spec && bun run gen:client",
29
- "gen:check": "bun run gen && git diff --exit-code -- openapi/v2.json src/sdk",
29
+ "gen:check": "bun run gen && git diff --exit-code -- openapi src/sdk",
30
30
  build: "tsup",
31
31
  typecheck: "tsc --noEmit",
32
32
  test: "vitest run",
@@ -84,8 +84,8 @@ var Result = class {
84
84
  }
85
85
  raw;
86
86
  _parse;
87
- get collectionId() {
88
- return this.raw.collection_id;
87
+ get documentPacketId() {
88
+ return this.raw.document_packet_id;
89
89
  }
90
90
  get extractions() {
91
91
  return this.raw.extractions ?? [];
@@ -102,16 +102,21 @@ var Result = class {
102
102
  return this._parse;
103
103
  }
104
104
  /**
105
- * Convenience accessor for a top-level scalar field on the first
106
- * extraction (linear workflows). Returns `undefined` for missing fields
107
- * or list-valued fields — read `extractions` directly for those.
105
+ * Convenience accessor for a top-level field on the untagged (linear)
106
+ * extraction. Returns the scalar `ExtractedField` for a scalar field, or
107
+ * the array of row records (`ExtractedRows`) for a list/object field such
108
+ * as `line_items`. `undefined` only when the field is absent.
108
109
  *
109
- * Parameterise with the declared schema type to type `.value`:
110
+ * Parameterise with the declared schema type to type a scalar's `.value`:
110
111
  * `result.field<number>("total").value` is `number | null`.
111
112
  */
112
113
  field(name) {
113
- const value = this.extractions[0]?.fields?.[name];
114
- if (value === void 0 || Array.isArray(value)) return void 0;
114
+ const untagged = this.extractions.find(
115
+ (e) => e.split_name == null && e.partition == null
116
+ );
117
+ const value = untagged?.fields?.[name];
118
+ if (value === void 0) return void 0;
119
+ if (Array.isArray(value)) return value;
115
120
  return value;
116
121
  }
117
122
  };
@@ -125,45 +130,116 @@ var APIError = class extends AnyformatError {
125
130
  this.status = status;
126
131
  this.body = body;
127
132
  this.name = new.target.name;
133
+ if (body && typeof body === "object") {
134
+ const envelope = body;
135
+ if (typeof envelope.error_code === "string") this.errorCode = envelope.error_code;
136
+ if (envelope.detail !== void 0) this.detail = envelope.detail;
137
+ if (typeof envelope.retryable === "boolean") this.retryable = envelope.retryable;
138
+ if (typeof envelope.request_id === "string") this.requestId = envelope.request_id;
139
+ if (envelope.params && typeof envelope.params === "object") {
140
+ this.params = envelope.params;
141
+ }
142
+ }
128
143
  }
129
144
  status;
130
145
  body;
146
+ /** Stable identifier for programmatic handling, e.g. `PAYMENT_REQUIRED`. */
147
+ errorCode;
148
+ /** Developer-facing explanation; not surfaced in `message` (ADR platform/0053 §2). Often a `ValidationItem[]`. */
149
+ detail;
150
+ /** Named substitutions the `error` summary refers to, e.g. `{ required_scope }`. */
151
+ params;
152
+ /** Whether the API says retrying the same request can succeed. */
153
+ retryable;
154
+ /** Correlation id to quote in support requests. */
155
+ requestId;
131
156
  };
132
157
  var BadRequestError = class extends APIError {
133
158
  };
134
159
  var UnauthorizedError = class extends APIError {
135
160
  };
161
+ var PaymentRequiredError = class extends APIError {
162
+ };
136
163
  var ForbiddenError = class extends APIError {
137
164
  };
138
165
  var NotFoundError = class extends APIError {
139
166
  };
140
167
  var RateLimitedError = class extends APIError {
168
+ constructor(status, message, body, retryAfter) {
169
+ super(status, message, body);
170
+ this.retryAfter = retryAfter;
171
+ }
172
+ retryAfter;
141
173
  };
142
174
  var ServerError = class extends APIError {
143
175
  };
144
- var BadRequest = BadRequestError;
145
- var Unauthorized = UnauthorizedError;
146
- var Forbidden = ForbiddenError;
147
- var NotFound = NotFoundError;
148
- var RateLimited = RateLimitedError;
176
+ function parseRetryAfter(raw) {
177
+ if (raw == null || raw.trim() === "") return void 0;
178
+ const seconds = Number(raw);
179
+ if (!Number.isNaN(seconds)) return seconds;
180
+ const when = Date.parse(raw);
181
+ if (Number.isNaN(when)) return void 0;
182
+ return Math.max((when - Date.now()) / 1e3, 0);
183
+ }
184
+ var InsufficientScopeError = class extends ForbiddenError {
185
+ };
186
+ var TermsAcceptanceRequiredError = class extends ForbiddenError {
187
+ };
188
+ var WorkflowNameConflictError = class extends APIError {
189
+ };
149
190
  var SDKTimeoutError = class extends AnyformatError {
150
191
  };
151
- var SDKTimeout = SDKTimeoutError;
192
+ var RunFailedError = class extends AnyformatError {
193
+ constructor(runId, status) {
194
+ super(`Run ${runId} ended with status "${status}"`);
195
+ this.runId = runId;
196
+ this.status = status;
197
+ this.name = new.target.name;
198
+ }
199
+ runId;
200
+ status;
201
+ };
202
+ var ExtractionFailedError = class extends RunFailedError {
203
+ constructor(runId) {
204
+ super(runId, "error");
205
+ }
206
+ };
207
+ var ExtractionCancelledError = class extends RunFailedError {
208
+ constructor(runId) {
209
+ super(runId, "cancelled");
210
+ }
211
+ };
152
212
  var WorkflowBuilderError = class extends AnyformatError {
153
213
  };
154
- function toApiError(status, body) {
155
- const message = `AnyFormat API error (${status})`;
214
+ function messageFrom(status, body) {
215
+ const fallback = `AnyFormat API error (${status})`;
216
+ if (!body || typeof body !== "object") return fallback;
217
+ const envelope = body;
218
+ return typeof envelope.error === "string" && envelope.error ? envelope.error : fallback;
219
+ }
220
+ var BY_ERROR_CODE = {
221
+ insufficient_api_key_scope: InsufficientScopeError,
222
+ terms_acceptance_required: TermsAcceptanceRequiredError,
223
+ WORKFLOW_NAME_CONFLICT: WorkflowNameConflictError
224
+ };
225
+ function toApiError(status, body, headers) {
226
+ const message = messageFrom(status, body);
227
+ const errorCode = body && typeof body === "object" && typeof body.error_code === "string" ? body.error_code : void 0;
228
+ const ByCode = errorCode ? BY_ERROR_CODE[errorCode] : void 0;
229
+ if (ByCode) return new ByCode(status, message, body);
156
230
  switch (status) {
157
231
  case 400:
158
232
  return new BadRequestError(status, message, body);
159
233
  case 401:
160
234
  return new UnauthorizedError(status, message, body);
235
+ case 402:
236
+ return new PaymentRequiredError(status, message, body);
161
237
  case 403:
162
238
  return new ForbiddenError(status, message, body);
163
239
  case 404:
164
240
  return new NotFoundError(status, message, body);
165
241
  case 429:
166
- return new RateLimitedError(status, message, body);
242
+ return new RateLimitedError(status, message, body, parseRetryAfter(headers?.get("Retry-After")));
167
243
  default:
168
244
  return status >= 500 ? new ServerError(status, message, body) : new APIError(status, message, body);
169
245
  }
@@ -223,7 +299,7 @@ function createSseClient({
223
299
  ...options
224
300
  }) {
225
301
  let lastEventId;
226
- const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
302
+ const sleep2 = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
227
303
  const createStream = async function* () {
228
304
  let retryDelay = sseDefaultRetryDelay ?? 3e3;
229
305
  let attempt = 0;
@@ -327,7 +403,7 @@ function createSseClient({
327
403
  break;
328
404
  }
329
405
  const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
330
- await sleep(backoff);
406
+ await sleep2(backoff);
331
407
  }
332
408
  }
333
409
  };
@@ -983,73 +1059,112 @@ var createClient = (config = {}) => {
983
1059
  var client = createClient(createConfig({ baseUrl: "https://api.anyformat.dev" }));
984
1060
 
985
1061
  // src/sdk/sdk.gen.ts
986
- var v2Parse = (options) => (options.client ?? client).post({
1062
+ var v3DeleteDocumentPacket = (options) => (options.client ?? client).delete({
1063
+ security: [{ scheme: "bearer", type: "http" }],
1064
+ url: "/v3/document-packets/{document_packet_id}/",
1065
+ ...options
1066
+ });
1067
+ var v3GetDocumentPacket = (options) => (options.client ?? client).get({
1068
+ security: [{ scheme: "bearer", type: "http" }],
1069
+ url: "/v3/document-packets/{document_packet_id}/",
1070
+ ...options
1071
+ });
1072
+ var v3RunDocumentPacket = (options) => (options.client ?? client).post({
1073
+ security: [{ scheme: "bearer", type: "http" }],
1074
+ url: "/v3/document-packets/{document_packet_id}/run/",
1075
+ ...options
1076
+ });
1077
+ var v3Parse = (options) => (options.client ?? client).post({
987
1078
  ...formDataBodySerializer,
988
1079
  security: [{ scheme: "bearer", type: "http" }],
989
- url: "/v2/operations/parse",
1080
+ url: "/v3/parse/",
990
1081
  ...options,
991
1082
  headers: {
992
1083
  "Content-Type": null,
993
1084
  ...options.headers
994
1085
  }
995
1086
  });
996
- var v2ParseResult = (options) => (options.client ?? client).get({
1087
+ var v3GetRun = (options) => (options.client ?? client).get({
997
1088
  security: [{ scheme: "bearer", type: "http" }],
998
- url: "/v2/operations/parse/{job_id}",
1089
+ url: "/v3/runs/{run_id}/",
999
1090
  ...options
1000
1091
  });
1001
- var v2ListWorkflows = (options) => (options?.client ?? client).get({
1092
+ var v3ListWorkflows = (options) => (options?.client ?? client).get({
1002
1093
  security: [{ scheme: "bearer", type: "http" }],
1003
- url: "/v2/workflows/",
1094
+ url: "/v3/workflows/",
1004
1095
  ...options
1005
1096
  });
1006
- var v2CreateWorkflow = (options) => (options.client ?? client).post({
1097
+ var v3CreateWorkflow = (options) => (options.client ?? client).post({
1007
1098
  security: [{ scheme: "bearer", type: "http" }],
1008
- url: "/v2/workflows/",
1099
+ url: "/v3/workflows/",
1009
1100
  ...options,
1010
1101
  headers: {
1011
1102
  "Content-Type": "application/json",
1012
1103
  ...options.headers
1013
1104
  }
1014
1105
  });
1015
- var v2DeleteWorkflow = (options) => (options.client ?? client).delete({
1106
+ var v3DeleteWorkflow = (options) => (options.client ?? client).delete({
1107
+ security: [{ scheme: "bearer", type: "http" }],
1108
+ url: "/v3/workflows/{workflow_id}/",
1109
+ ...options
1110
+ });
1111
+ var v3GetWorkflow = (options) => (options.client ?? client).get({
1016
1112
  security: [{ scheme: "bearer", type: "http" }],
1017
- url: "/v2/workflows/{workflow_id}/",
1113
+ url: "/v3/workflows/{workflow_id}/",
1018
1114
  ...options
1019
1115
  });
1020
- var v2UpdateWorkflow = (options) => (options.client ?? client).put({
1116
+ var v3UpdateWorkflow = (options) => (options.client ?? client).patch({
1021
1117
  security: [{ scheme: "bearer", type: "http" }],
1022
- url: "/v2/workflows/{workflow_id}/",
1118
+ url: "/v3/workflows/{workflow_id}/",
1023
1119
  ...options,
1024
1120
  headers: {
1025
1121
  "Content-Type": "application/json",
1026
1122
  ...options.headers
1027
1123
  }
1028
1124
  });
1029
- var v2GetFileResults = (options) => (options.client ?? client).get({
1125
+ var v3UploadToDataset = (options) => (options.client ?? client).post({
1126
+ ...formDataBodySerializer,
1127
+ security: [{ scheme: "bearer", type: "http" }],
1128
+ url: "/v3/workflows/{workflow_id}/dataset/upload/",
1129
+ ...options,
1130
+ headers: {
1131
+ "Content-Type": null,
1132
+ ...options.headers
1133
+ }
1134
+ });
1135
+ var v3ListWorkflowDocumentPackets = (options) => (options.client ?? client).get({
1030
1136
  security: [{ scheme: "bearer", type: "http" }],
1031
- url: "/v2/workflows/{workflow_id}/files/{collection_id}/results/",
1137
+ url: "/v3/workflows/{workflow_id}/document-packets/",
1032
1138
  ...options
1033
1139
  });
1034
- var v2RunFile = (options) => (options.client ?? client).post({
1140
+ var v3ListWorkflowRuns = (options) => (options.client ?? client).get({
1035
1141
  security: [{ scheme: "bearer", type: "http" }],
1036
- url: "/v2/workflows/{workflow_id}/files/{file_id}/run/",
1142
+ url: "/v3/workflows/{workflow_id}/runs/",
1037
1143
  ...options
1038
1144
  });
1039
- var v2RunWorkflow = (options) => (options.client ?? client).post({
1145
+ var v3UploadToWorkflow = (options) => (options.client ?? client).post({
1040
1146
  ...formDataBodySerializer,
1041
1147
  security: [{ scheme: "bearer", type: "http" }],
1042
- url: "/v2/workflows/{workflow_id}/run/",
1148
+ url: "/v3/workflows/{workflow_id}/upload/",
1043
1149
  ...options,
1044
1150
  headers: {
1045
1151
  "Content-Type": null,
1046
1152
  ...options.headers
1047
1153
  }
1048
1154
  });
1049
- var v2UploadFile = (options) => (options.client ?? client).post({
1155
+ var v3UploadFromUrl = (options) => (options.client ?? client).post({
1156
+ security: [{ scheme: "bearer", type: "http" }],
1157
+ url: "/v3/workflows/{workflow_id}/upload/from-url/",
1158
+ ...options,
1159
+ headers: {
1160
+ "Content-Type": "application/json",
1161
+ ...options.headers
1162
+ }
1163
+ });
1164
+ var v3UploadAndRunWorkflow = (options) => (options.client ?? client).post({
1050
1165
  ...formDataBodySerializer,
1051
1166
  security: [{ scheme: "bearer", type: "http" }],
1052
- url: "/v2/workflows/{workflow_id}/upload/",
1167
+ url: "/v3/workflows/{workflow_id}/upload/run/",
1053
1168
  ...options,
1054
1169
  headers: {
1055
1170
  "Content-Type": null,
@@ -1058,73 +1173,128 @@ var v2UploadFile = (options) => (options.client ?? client).post({
1058
1173
  });
1059
1174
 
1060
1175
  // src/run.ts
1176
+ function isTransientStatus(status) {
1177
+ return status === 429 || status >= 500;
1178
+ }
1179
+ var RETRY_BASE_MS = 1e3;
1180
+ var RETRY_MAX_MS = 3e4;
1181
+ function retryDelayMs(response, attempt) {
1182
+ const retryAfter = parseRetryAfter(response?.headers?.get("Retry-After"));
1183
+ if (retryAfter !== void 0) return Math.min(retryAfter * 1e3, RETRY_MAX_MS);
1184
+ const base = Math.min(RETRY_BASE_MS * 2 ** attempt, RETRY_MAX_MS);
1185
+ return base * (0.75 + Math.random() * 0.5);
1186
+ }
1187
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1061
1188
  var Run = class {
1062
1189
  /** @internal */
1063
- constructor(client2, workflowId, id) {
1190
+ constructor(client2, id, workflowId, documentPacketId, status = "queued") {
1064
1191
  this.client = client2;
1065
- this.workflowId = workflowId;
1066
1192
  this.id = id;
1193
+ this.workflowId = workflowId;
1194
+ this.documentPacketId = documentPacketId;
1195
+ this.status = status;
1067
1196
  }
1068
1197
  client;
1069
- workflowId;
1070
1198
  id;
1199
+ workflowId;
1200
+ documentPacketId;
1201
+ /** Status at trigger time, refreshed on every `wait()` poll. */
1202
+ status;
1071
1203
  async wait(opts = {}) {
1072
1204
  const timeoutMs = opts.timeoutMs ?? 3e5;
1073
1205
  const pollMs = opts.pollMs ?? 3e3;
1074
1206
  const deadline = Date.now() + timeoutMs;
1075
- while (Date.now() < deadline) {
1076
- const results = await v2GetFileResults({
1077
- client: this.client,
1078
- path: { workflow_id: this.workflowId, collection_id: this.id }
1079
- });
1080
- if (!results.error) return new Result(results.data);
1081
- if (results.response?.status !== 412) {
1082
- throw toApiError(results.response?.status ?? 500, results.error);
1207
+ let transientFailures = 0;
1208
+ for (; ; ) {
1209
+ const res = await v3GetRun({ client: this.client, path: { run_id: this.id } });
1210
+ if (res.error) {
1211
+ const status = res.response?.status ?? 500;
1212
+ if (!isTransientStatus(status)) throw toApiError(status, res.error, res.response?.headers);
1213
+ const remainingMs = deadline - Date.now();
1214
+ if (remainingMs <= 0) {
1215
+ throw new SDKTimeoutError(`Extraction did not complete within ${timeoutMs}ms`);
1216
+ }
1217
+ await sleep(Math.min(retryDelayMs(res.response, transientFailures), remainingMs));
1218
+ transientFailures += 1;
1219
+ continue;
1220
+ }
1221
+ transientFailures = 0;
1222
+ const detail = res.data;
1223
+ this.status = detail.status;
1224
+ if (detail.status === "processed") {
1225
+ if (!detail.results) {
1226
+ throw new AnyformatError(`Run ${this.id} is processed but the API returned no results`);
1227
+ }
1228
+ return new Result(detail.results);
1229
+ }
1230
+ if (detail.status === "error") throw new ExtractionFailedError(this.id);
1231
+ if (detail.status === "cancelled") throw new ExtractionCancelledError(this.id);
1232
+ if (Date.now() >= deadline) {
1233
+ throw new SDKTimeoutError(`Extraction did not complete within ${timeoutMs}ms`);
1083
1234
  }
1084
- await new Promise((resolve) => setTimeout(resolve, pollMs));
1235
+ await sleep(pollMs);
1085
1236
  }
1086
- throw new SDKTimeoutError(`Extraction did not complete within ${timeoutMs}ms`);
1087
1237
  }
1088
1238
  };
1089
1239
 
1090
1240
  // src/upload.ts
1241
+ var DatasetUpload = class {
1242
+ /** @internal */
1243
+ constructor(workflowId, documentPacketId, files, groundTruthSaved) {
1244
+ this.workflowId = workflowId;
1245
+ this.documentPacketId = documentPacketId;
1246
+ this.files = files;
1247
+ this.groundTruthSaved = groundTruthSaved;
1248
+ }
1249
+ workflowId;
1250
+ documentPacketId;
1251
+ files;
1252
+ groundTruthSaved;
1253
+ };
1091
1254
  var Upload = class {
1092
1255
  /** @internal */
1093
- constructor(client2, workflowId, collectionId, fileId) {
1256
+ constructor(client2, workflowId, documentPacketId, files) {
1094
1257
  this.client = client2;
1095
1258
  this.workflowId = workflowId;
1096
- this.collectionId = collectionId;
1097
- this.fileId = fileId;
1259
+ this.documentPacketId = documentPacketId;
1260
+ this.files = files;
1098
1261
  }
1099
1262
  client;
1100
1263
  workflowId;
1101
- collectionId;
1102
- fileId;
1103
- /** Trigger extraction on the staged file and return a pending `Run`. */
1104
- async run() {
1105
- if (!this.fileId) {
1106
- throw new WorkflowBuilderError("This upload has no file_id \u2014 cannot run it");
1107
- }
1108
- const res = await v2RunFile({
1264
+ documentPacketId;
1265
+ files;
1266
+ /** Trigger extraction on the staged packet and return a pending `Run`. */
1267
+ async run(opts = {}) {
1268
+ const res = await v3RunDocumentPacket({
1109
1269
  client: this.client,
1110
- path: { workflow_id: this.workflowId, file_id: this.fileId }
1270
+ path: { document_packet_id: this.documentPacketId },
1271
+ ...opts.idempotencyKey ? { headers: { "Idempotency-Key": opts.idempotencyKey } } : {}
1111
1272
  });
1112
- if (res.error) throw toApiError(res.response?.status ?? 500, res.error);
1113
- return new Run(this.client, this.workflowId, res.data.id ?? this.collectionId);
1273
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1274
+ const data = res.data;
1275
+ return new Run(this.client, data.run_id, data.workflow_id, data.document_packet_id, data.status);
1114
1276
  }
1115
1277
  };
1116
1278
 
1117
1279
  // src/workflow.ts
1118
- function validateDocument(file, op) {
1119
- if (file === null) {
1120
- throw new WorkflowBuilderError(`${op}() requires a named file`);
1121
- }
1122
- const filename = file.name;
1123
- if (typeof filename !== "string" || filename.length === 0) {
1124
- throw new WorkflowBuilderError(
1125
- `${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`
1126
- );
1280
+ var MAX_FILES_PER_PACKET = 100;
1281
+ function normalizeFiles(files, op) {
1282
+ const list = files == null ? [] : Array.isArray(files) ? files : [files];
1283
+ if (list.length === 0) {
1284
+ throw new WorkflowBuilderError(`${op}() requires at least one named file`);
1285
+ }
1286
+ if (list.length > MAX_FILES_PER_PACKET) {
1287
+ throw new WorkflowBuilderError(`${op}() accepts at most ${MAX_FILES_PER_PACKET} files per document packet`);
1288
+ }
1289
+ for (const file of list) {
1290
+ const filename = file.name;
1291
+ if (typeof filename !== "string" || filename.length === 0) {
1292
+ throw new WorkflowBuilderError(
1293
+ `${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`
1294
+ );
1295
+ }
1127
1296
  }
1297
+ return list;
1128
1298
  }
1129
1299
  var Workflow = class {
1130
1300
  /** @internal */
@@ -1136,36 +1306,90 @@ var Workflow = class {
1136
1306
  client;
1137
1307
  id;
1138
1308
  name;
1139
- /** Submit a document against this workflow and return a pending `Run`. */
1140
- async run(file = null) {
1141
- validateDocument(file, "run");
1142
- const submitted = await v2RunWorkflow({
1309
+ /** Upload 1..100 files as one document packet and run it. Returns a pending `Run`. */
1310
+ async run(files = null, opts = {}) {
1311
+ const list = normalizeFiles(files, "run");
1312
+ const submitted = await v3UploadAndRunWorkflow({
1143
1313
  client: this.client,
1144
1314
  path: { workflow_id: this.id },
1145
- body: { file }
1315
+ body: { files: list, ...opts.onConflict ? { on_conflict: opts.onConflict } : {} },
1316
+ ...opts.idempotencyKey ? { headers: { "Idempotency-Key": opts.idempotencyKey } } : {}
1146
1317
  });
1147
- if (submitted.error) throw toApiError(submitted.response?.status ?? 500, submitted.error);
1148
- return new Run(this.client, this.id, submitted.data.id);
1318
+ if (submitted.error) throw toApiError(submitted.response?.status ?? 500, submitted.error, submitted.response?.headers);
1319
+ const data = submitted.data;
1320
+ return new Run(this.client, data.run_id, data.workflow_id, data.document_packet_id, data.status);
1149
1321
  }
1150
1322
  /**
1151
- * Stage a document in this workflow WITHOUT running it (no credits spent).
1152
- * Returns an `Upload`; call `.run()` on it to start extraction.
1323
+ * Stage 1..100 files as one document packet WITHOUT running it (no credits
1324
+ * spent). Returns an `Upload`; call `.run()` on it to start extraction.
1153
1325
  */
1154
- async upload(file = null) {
1155
- validateDocument(file, "upload");
1156
- const staged = await v2UploadFile({
1326
+ async upload(files = null, opts = {}) {
1327
+ const list = normalizeFiles(files, "upload");
1328
+ const staged = await v3UploadToWorkflow({
1157
1329
  client: this.client,
1158
1330
  path: { workflow_id: this.id },
1159
- body: { file }
1331
+ body: { files: list, ...opts.onConflict ? { on_conflict: opts.onConflict } : {} },
1332
+ ...opts.idempotencyKey ? { headers: { "Idempotency-Key": opts.idempotencyKey } } : {}
1160
1333
  });
1161
- if (staged.error) throw toApiError(staged.response?.status ?? 500, staged.error);
1162
- const collectionId = staged.data.file_collection_id;
1163
- if (!collectionId) {
1164
- throw new WorkflowBuilderError(
1165
- "Upload succeeded but the server did not return a file_collection_id \u2014 cannot build an Upload handle"
1334
+ if (staged.error) throw toApiError(staged.response?.status ?? 500, staged.error, staged.response?.headers);
1335
+ const data = staged.data;
1336
+ return new Upload(this.client, data.workflow_id, data.document_packet_id, data.files);
1337
+ }
1338
+ /**
1339
+ * Upload 1..100 files as ONE document (+ optional ground truth) into the
1340
+ * workflow's dataset, as one document packet. Atomic: any rejected file or a
1341
+ * ground-truth failure fails the call and stores nothing. By default a
1342
+ * colliding filename fails with `409`; pass `onConflict: "rename"` to
1343
+ * auto-rename instead.
1344
+ */
1345
+ async uploadToDataset(files = null, opts = {}) {
1346
+ const list = normalizeFiles(files, "uploadToDataset");
1347
+ const registered = await v3UploadToDataset({
1348
+ client: this.client,
1349
+ path: { workflow_id: this.id },
1350
+ body: {
1351
+ files: list,
1352
+ ...opts.groundTruth != null ? { ground_truth: JSON.stringify(opts.groundTruth) } : {},
1353
+ ...opts.onConflict ? { on_conflict: opts.onConflict } : {}
1354
+ },
1355
+ ...opts.idempotencyKey ? { headers: { "Idempotency-Key": opts.idempotencyKey } } : {}
1356
+ });
1357
+ if (registered.error) throw toApiError(registered.response?.status ?? 500, registered.error, registered.response?.headers);
1358
+ const data = registered.data;
1359
+ return new DatasetUpload(this.id, data.document_packet_id, data.files, data.ground_truth_saved);
1360
+ }
1361
+ /**
1362
+ * Client-orchestrated bulk dataset upload: one atomic call per document,
1363
+ * in order. There is no batch endpoint — each document is bounded and
1364
+ * independently retryable. On failure the call rejects; documents already
1365
+ * uploaded stay registered.
1366
+ */
1367
+ async uploadDocumentsToDataset(documents) {
1368
+ const uploaded = [];
1369
+ for (const doc of documents) {
1370
+ uploaded.push(
1371
+ await this.uploadToDataset(doc.files, {
1372
+ groundTruth: doc.groundTruth,
1373
+ idempotencyKey: doc.idempotencyKey,
1374
+ onConflict: doc.onConflict
1375
+ })
1166
1376
  );
1167
1377
  }
1168
- return new Upload(this.client, this.id, collectionId, staged.data.file_id ?? null);
1378
+ return uploaded;
1379
+ }
1380
+ /**
1381
+ * Import 1..10 HTTPS URLs server-side into one document packet, atomically.
1382
+ * Returns an `Upload`; call `.run()` on it to start extraction.
1383
+ */
1384
+ async uploadFromUrls(urls, opts = {}) {
1385
+ const staged = await v3UploadFromUrl({
1386
+ client: this.client,
1387
+ path: { workflow_id: this.id },
1388
+ body: { urls, ...opts.onConflict ? { on_conflict: opts.onConflict } : {} }
1389
+ });
1390
+ if (staged.error) throw toApiError(staged.response?.status ?? 500, staged.error, staged.response?.headers);
1391
+ const data = staged.data;
1392
+ return new Upload(this.client, data.workflow_id, data.document_packet_id, data.files);
1169
1393
  }
1170
1394
  };
1171
1395
 
@@ -1204,12 +1428,7 @@ var WorkflowBuilder = class {
1204
1428
  figure_enhancement: o.figureEnhancement ?? false,
1205
1429
  cache: o.cache ?? true,
1206
1430
  ...o.effort !== void 0 ? { effort: o.effort } : {},
1207
- ...o.ocrEffort !== void 0 ? { ocr_effort: o.ocrEffort } : {},
1208
- ...o.region !== void 0 ? { region: o.region } : {},
1209
- ...o.skipRoutingReview !== void 0 ? { skip_routing_review: o.skipRoutingReview } : {},
1210
- ...o.figures !== void 0 ? { figures: o.figures } : {},
1211
- ...o.textFormatting !== void 0 ? { text_formatting: o.textFormatting } : {},
1212
- ...o.routingEffort !== void 0 ? { routing_effort: o.routingEffort } : {}
1431
+ ...o.scannedPages !== void 0 ? { scanned_pages: o.scannedPages } : {}
1213
1432
  };
1214
1433
  return this;
1215
1434
  }
@@ -1343,16 +1562,16 @@ var WorkflowBuilder = class {
1343
1562
  }
1344
1563
  return { name: this.name, description: this.description, nodes, edges };
1345
1564
  }
1346
- /** Persist the workflow and return a handle you can `.run(file)` on. */
1565
+ /** Persist the workflow and return a handle you can `.run(files)` on. */
1347
1566
  async create() {
1348
- const res = await v2CreateWorkflow({ client: this.client, body: this.build() });
1349
- if (res.error) throw toApiError(res.response?.status ?? 500, res.error);
1567
+ const res = await v3CreateWorkflow({ client: this.client, body: this.build() });
1568
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1350
1569
  return new Workflow(this.client, res.data.id, res.data.name);
1351
1570
  }
1352
- /** Replace an existing workflow's definition and return a handle you can `.run(file)` on. */
1571
+ /** Replace an existing workflow's typed graph and return a handle you can `.run(files)` on. */
1353
1572
  async update(workflowId) {
1354
- const res = await v2UpdateWorkflow({ client: this.client, path: { workflow_id: workflowId }, body: this.build() });
1355
- if (res.error) throw toApiError(res.response?.status ?? 500, res.error);
1573
+ const res = await v3UpdateWorkflow({ client: this.client, path: { workflow_id: workflowId }, body: this.build() });
1574
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1356
1575
  return new Workflow(this.client, res.data.id, res.data.name);
1357
1576
  }
1358
1577
  };
@@ -1380,101 +1599,222 @@ var Anyformat = class {
1380
1599
  workflow(name, description) {
1381
1600
  return new WorkflowBuilder(this._client, name, description);
1382
1601
  }
1383
- async listWorkflows(opts) {
1384
- const res = await v2ListWorkflows({
1602
+ async listWorkflows(opts = {}) {
1603
+ const res = await v3ListWorkflows({
1604
+ client: this._client,
1605
+ query: { limit: opts.limit, cursor: opts.cursor }
1606
+ });
1607
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1608
+ return {
1609
+ items: res.data.items.map((r) => new Workflow(this._client, r.id, r.name)),
1610
+ nextCursor: res.data.next_cursor ?? null
1611
+ };
1612
+ }
1613
+ /** Retrieve a workflow with its complete typed graph inline (round-trippable into `updateWorkflow`). */
1614
+ async getWorkflow(workflowId) {
1615
+ const res = await v3GetWorkflow({ client: this._client, path: { workflow_id: workflowId } });
1616
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1617
+ return res.data;
1618
+ }
1619
+ /**
1620
+ * Replace a workflow's typed graph (atomic). Accepts the shape `getWorkflow`
1621
+ * returns — echo each field's `persistent_id` unchanged (including across
1622
+ * renames) to keep the field's identity; omit it for new fields.
1623
+ */
1624
+ async updateWorkflow(workflowId, definition) {
1625
+ const res = await v3UpdateWorkflow({
1385
1626
  client: this._client,
1386
- query: { page: opts?.page, page_size: opts?.pageSize, status: opts?.status }
1627
+ path: { workflow_id: workflowId },
1628
+ // The PATCH body forbids unknown keys, so a fetched detail's read-only
1629
+ // fields (id, timestamps) must not be forwarded.
1630
+ body: {
1631
+ name: definition.name,
1632
+ description: definition.description,
1633
+ nodes: definition.nodes,
1634
+ edges: definition.edges
1635
+ }
1387
1636
  });
1388
- if (res.error) throw toApiError(res.response?.status ?? 500, res.error);
1389
- return res.data.results.map((r) => new Workflow(this._client, r.id, r.name ?? ""));
1637
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1638
+ return res.data;
1390
1639
  }
1391
1640
  async deleteWorkflow(workflowId) {
1392
- const res = await v2DeleteWorkflow({
1641
+ const res = await v3DeleteWorkflow({
1393
1642
  client: this._client,
1394
1643
  path: { workflow_id: workflowId }
1395
1644
  });
1396
- if (res.error) throw toApiError(res.response?.status ?? 500, res.error);
1645
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1397
1646
  return workflowId;
1398
1647
  }
1399
- /** Stage a document in a workflow without running it. Returns an `Upload`. */
1400
- upload(workflowId, file = null) {
1401
- return new Workflow(this._client, workflowId, "").upload(file);
1402
- }
1403
- /** Trigger extraction on already-uploaded files. Returns a pending `Run` per file_id. */
1404
- async runWorkflow(workflowId, fileIds) {
1405
- const runs = [];
1406
- for (const fileId of fileIds) {
1407
- const res = await v2RunFile({
1408
- client: this._client,
1409
- path: { workflow_id: workflowId, file_id: fileId }
1410
- });
1411
- if (res.error) throw toApiError(res.response?.status ?? 500, res.error);
1412
- runs.push(new Run(this._client, workflowId, res.data.id ?? fileId));
1648
+ /** Stage 1..100 files as one document packet without running it. Returns an `Upload`. */
1649
+ upload(workflowId, files, opts = {}) {
1650
+ return new Workflow(this._client, workflowId, "").upload(files, opts);
1651
+ }
1652
+ /** Upload 1..100 files (+ optional ground truth) as one dataset collection. Returns a `DatasetUpload`. */
1653
+ uploadToDataset(workflowId, files, opts = {}) {
1654
+ return new Workflow(this._client, workflowId, "").uploadToDataset(files, opts);
1655
+ }
1656
+ /** Bulk-upload documents into a workflow's dataset, one atomic call per document. */
1657
+ uploadDocumentsToDataset(workflowId, documents) {
1658
+ return new Workflow(this._client, workflowId, "").uploadDocumentsToDataset(documents);
1659
+ }
1660
+ async getDocumentPacket(documentPacketId) {
1661
+ const res = await v3GetDocumentPacket({
1662
+ client: this._client,
1663
+ path: { document_packet_id: documentPacketId }
1664
+ });
1665
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1666
+ return res.data;
1667
+ }
1668
+ /** Delete a document packet and all its files. Irreversible. */
1669
+ async deleteDocumentPacket(documentPacketId) {
1670
+ const res = await v3DeleteDocumentPacket({
1671
+ client: this._client,
1672
+ path: { document_packet_id: documentPacketId }
1673
+ });
1674
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1675
+ return documentPacketId;
1676
+ }
1677
+ /** Run (or re-run) a document packet on the latest version of its workflow. */
1678
+ async runDocumentPacket(documentPacketId, opts = {}) {
1679
+ const res = await v3RunDocumentPacket({
1680
+ client: this._client,
1681
+ path: { document_packet_id: documentPacketId },
1682
+ ...opts.idempotencyKey ? { headers: { "Idempotency-Key": opts.idempotencyKey } } : {}
1683
+ });
1684
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1685
+ const data = res.data;
1686
+ return new Run(this._client, data.run_id, data.workflow_id, data.document_packet_id, data.status);
1687
+ }
1688
+ async listDocumentPackets(workflowId, opts = {}) {
1689
+ const res = await v3ListWorkflowDocumentPackets({
1690
+ client: this._client,
1691
+ path: { workflow_id: workflowId },
1692
+ query: { limit: opts.limit, cursor: opts.cursor }
1693
+ });
1694
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1695
+ return { items: res.data.items, nextCursor: res.data.next_cursor ?? null };
1696
+ }
1697
+ async listRuns(workflowId, opts = {}) {
1698
+ const res = await v3ListWorkflowRuns({
1699
+ client: this._client,
1700
+ path: { workflow_id: workflowId },
1701
+ query: { limit: opts.limit, cursor: opts.cursor }
1702
+ });
1703
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1704
+ return { items: res.data.items, nextCursor: res.data.next_cursor ?? null };
1705
+ }
1706
+ /**
1707
+ * Every workflow, following `nextCursor` across pages so no rows are silently
1708
+ * truncated. Lazy — each page is fetched on demand as the iterator advances.
1709
+ */
1710
+ async *iterWorkflows(opts = {}) {
1711
+ let cursor;
1712
+ for (; ; ) {
1713
+ const page = await this.listWorkflows({ limit: opts.limit, cursor });
1714
+ yield* page.items;
1715
+ if (page.nextCursor === null) return;
1716
+ cursor = page.nextCursor;
1413
1717
  }
1414
- return runs;
1718
+ }
1719
+ /** Every document packet of a workflow, following `nextCursor` across pages. Lazy. */
1720
+ async *iterDocumentPackets(workflowId, opts = {}) {
1721
+ let cursor;
1722
+ for (; ; ) {
1723
+ const page = await this.listDocumentPackets(workflowId, { limit: opts.limit, cursor });
1724
+ yield* page.items;
1725
+ if (page.nextCursor === null) return;
1726
+ cursor = page.nextCursor;
1727
+ }
1728
+ }
1729
+ /** Every run of a workflow, following `nextCursor` across pages. Lazy. */
1730
+ async *iterRuns(workflowId, opts = {}) {
1731
+ let cursor;
1732
+ for (; ; ) {
1733
+ const page = await this.listRuns(workflowId, { limit: opts.limit, cursor });
1734
+ yield* page.items;
1735
+ if (page.nextCursor === null) return;
1736
+ cursor = page.nextCursor;
1737
+ }
1738
+ }
1739
+ /** Retrieve one run: lifecycle status plus results inline once `processed`. */
1740
+ async getRun(runId) {
1741
+ const res = await v3GetRun({ client: this._client, path: { run_id: runId } });
1742
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1743
+ return res.data;
1415
1744
  }
1416
1745
  /**
1417
- * Parse a document with the platform's atomic `/parse` operation (fast lite
1418
- * parse). Returns an opaque `jobId`; poll `getParseMarkdown(jobId)` for the
1419
- * parsed markdown.
1746
+ * Parse a document with the platform's atomic parse operation (fast lite
1747
+ * parse). Returns the run id; poll `getParseMarkdown(runId)` for the parsed
1748
+ * markdown.
1420
1749
  */
1421
1750
  async parse(file) {
1422
- const res = await v2Parse({ client: this._client, body: { file } });
1423
- if (res.error) throw toApiError(res.response?.status ?? 500, res.error);
1424
- return res.data.job_id;
1751
+ const res = await v3Parse({ client: this._client, body: { file } });
1752
+ if (res.error !== void 0) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1753
+ return res.data.run_id;
1425
1754
  }
1426
1755
  /**
1427
- * Poll a parse job. Returns the parsed markdown once the job is done, or
1428
- * `null` while it is still processing.
1756
+ * Poll a parse run. Returns the parsed markdown once the run is `processed`,
1757
+ * or `null` while it is still queued or in progress.
1429
1758
  */
1430
- async getParseMarkdown(jobId) {
1431
- const res = await v2ParseResult({ client: this._client, path: { job_id: jobId } });
1432
- if (res.error) throw toApiError(res.response?.status ?? 500, res.error);
1433
- return res.data.status === "done" ? res.data.markdown ?? "" : null;
1759
+ async getParseMarkdown(runId) {
1760
+ const run = await this.getRun(runId);
1761
+ if (run.status === "processed") {
1762
+ const markdown = run.results?.parse?.markdown;
1763
+ if (markdown == null) throw new AnyformatError(`Run ${runId} is processed but the API returned no results`);
1764
+ return markdown;
1765
+ }
1766
+ if (run.status === "error") throw new ExtractionFailedError(runId);
1767
+ if (run.status === "cancelled") throw new ExtractionCancelledError(runId);
1768
+ return null;
1434
1769
  }
1435
1770
  };
1436
1771
 
1437
1772
  // src/schema.ts
1438
- function withLookup(base, opts) {
1439
- if (opts?.lookup) return { ...base, lookup: true };
1440
- return base;
1773
+ function withOpts(base, opts) {
1774
+ return {
1775
+ ...base,
1776
+ ...opts?.source && opts.source !== "extraction" ? { source: opts.source } : {},
1777
+ ...opts?.persistentId !== void 0 ? { persistent_id: opts.persistentId } : {}
1778
+ };
1441
1779
  }
1442
1780
  var Schema = {
1443
- string: (name, description, opts) => withLookup({ data_type: "string", name, description }, opts),
1444
- integer: (name, description, opts) => withLookup({ data_type: "integer", name, description }, opts),
1445
- float: (name, description, opts) => withLookup({ data_type: "float", name, description }, opts),
1446
- boolean: (name, description, opts) => withLookup({ data_type: "boolean", name, description }, opts),
1447
- date: (name, description, opts) => withLookup({ data_type: "date", name, description }, opts),
1448
- datetime: (name, description, opts) => withLookup({ data_type: "datetime", name, description }, opts),
1449
- enum: (name, description, options, opts) => withLookup({ data_type: "enum", name, description, enum_options: options }, opts),
1450
- multiSelect: (name, description, options, opts) => withLookup({ data_type: "multi_select", name, description, enum_options: options }, opts),
1451
- object: (name, description, fields, opts) => withLookup({ data_type: "object", name, description, nested_fields: fields }, opts),
1781
+ string: (name, description, opts) => withOpts({ data_type: "string", name, description }, opts),
1782
+ integer: (name, description, opts) => withOpts({ data_type: "integer", name, description }, opts),
1783
+ float: (name, description, opts) => withOpts({ data_type: "float", name, description }, opts),
1784
+ boolean: (name, description, opts) => withOpts({ data_type: "boolean", name, description }, opts),
1785
+ date: (name, description, opts) => withOpts({ data_type: "date", name, description }, opts),
1786
+ datetime: (name, description, opts) => withOpts({ data_type: "datetime", name, description }, opts),
1787
+ enum: (name, description, options, opts) => withOpts({ data_type: "enum", name, description, enum_options: options }, opts),
1788
+ multiSelect: (name, description, options, opts) => withOpts({ data_type: "multi_select", name, description, enum_options: options }, opts),
1789
+ object: (name, description, fields, opts) => withOpts({ data_type: "object", name, description, nested_fields: fields }, opts),
1452
1790
  option: (name, description) => ({ name, description })
1453
1791
  };
1454
1792
  export {
1455
1793
  APIError,
1456
1794
  Anyformat,
1457
1795
  AnyformatError,
1458
- BadRequest,
1459
1796
  BadRequestError,
1460
- Forbidden,
1797
+ DatasetUpload,
1798
+ ExtractionCancelledError,
1799
+ ExtractionFailedError,
1461
1800
  ForbiddenError,
1462
- NotFound,
1801
+ InsufficientScopeError,
1463
1802
  NotFoundError,
1464
1803
  ParseView,
1465
- RateLimited,
1804
+ PaymentRequiredError,
1466
1805
  RateLimitedError,
1467
1806
  Result,
1468
1807
  Run,
1469
- SDKTimeout,
1808
+ RunFailedError,
1470
1809
  SDKTimeoutError,
1471
1810
  Schema,
1472
1811
  ServerError,
1473
- Unauthorized,
1812
+ TermsAcceptanceRequiredError,
1474
1813
  UnauthorizedError,
1475
1814
  Upload,
1476
1815
  Workflow,
1477
1816
  WorkflowBuilder,
1478
- WorkflowBuilderError
1817
+ WorkflowBuilderError,
1818
+ WorkflowNameConflictError
1479
1819
  };
1480
1820
  //# sourceMappingURL=index.js.map