@anyformat/sdk 1.0.0-rc.2 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -6
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../package.json","../src/builder.ts","../src/parse-view.ts","../src/result.ts","../src/errors.ts","../src/sdk/core/bodySerializer.gen.ts","../src/sdk/core/params.gen.ts","../src/sdk/core/serverSentEvents.gen.ts","../src/sdk/core/pathSerializer.gen.ts","../src/sdk/core/utils.gen.ts","../src/sdk/core/auth.gen.ts","../src/sdk/client/utils.gen.ts","../src/sdk/client/client.gen.ts","../src/sdk/client.gen.ts","../src/sdk/sdk.gen.ts","../src/run.ts","../src/upload.ts","../src/workflow.ts","../src/client.ts","../src/schema.ts"],"sourcesContent":["{\n \"name\": \"@anyformat/sdk\",\n \"version\": \"1.0.0-rc.2\",\n \"description\": \"TypeScript SDK for the AnyFormat API\",\n \"license\": \"MIT\",\n \"author\": \"Anyformat <info@anyformat.ai>\",\n \"type\": \"module\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n }\n },\n \"files\": [\n \"dist\"\n ],\n \"engines\": {\n \"node\": \">=18\"\n },\n \"scripts\": {\n \"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\",\n \"gen:client\": \"openapi-ts\",\n \"gen\": \"bun run gen:spec && bun run gen:client\",\n \"gen:check\": \"bun run gen && git diff --exit-code -- openapi src/sdk\",\n \"build\": \"tsup\",\n \"typecheck\": \"tsc --noEmit\",\n \"test\": \"vitest run\",\n \"prepublishOnly\": \"bun run build\"\n },\n \"devDependencies\": {\n \"@hey-api/openapi-ts\": \"^0.99.0\",\n \"@types/node\": \"^25.9.1\",\n \"tsup\": \"^8.3.0\",\n \"typescript\": \"^5.6.0\",\n \"vitest\": \"^4.1.7\"\n }\n}\n","import { readFileSync } from \"node:fs\";\nimport { basename } from \"node:path\";\nimport { Workflow } from \"./workflow\";\nimport { toApiError, WorkflowBuilderError } from \"./errors\";\nimport { v3CreateWorkflow, v3UpdateWorkflow } from \"./sdk\";\nimport type { Client as HeyClient } from \"./sdk/client\";\nimport type {\n ClassifyCategory,\n ClassifyNode,\n Edge,\n LookupFileUpload,\n PublicExtractNode as ExtractNode,\n PublicParseNode as ParseNode,\n PublicValidateNode as ValidateNode,\n SplitterNode,\n SplitterRule,\n ValidationRule,\n WorkflowCreateRequest,\n} from \"./sdk\";\nimport type { Field } from \"./schema\";\n\ntype ParseMode = \"standard\" | \"agentic\" | \"lite\" | \"flash\";\ntype ExtractMode = \"standard\" | \"agentic\" | \"lite\";\ntype AgenticEffort = \"low\" | \"mid\" | \"accurate\";\ntype ScannedPages = \"ocr\" | \"skip\" | \"fail\";\n/** How much reasoning a node asks a model for. Taken from the generated wire types, which\n * follow the Python `ReasoningEffort` alias, so a new level needs no edit here.\n * The Python gives `ExtractNode.lookup_reasoning_effort`\n * that same alias, so one of the two fields derives the type for both. */\ntype ReasoningEffort = NonNullable<ExtractNode[\"lookup_reasoning_effort\"]>;\n\n/** Source-port label routing into an extract/validate node. */\nexport type Branch = string | ClassifyCategory | SplitterRule;\n\n/** Knobs shared by every parse mode. */\ninterface ParseOptionsBase {\n figureEnhancement?: boolean;\n cache?: boolean;\n id?: string;\n}\n\n/**\n * Parse options as a `mode`-discriminated union: each mode only accepts its own knobs, so a lite\n * knob on `{ mode: \"standard\" }` is a compile-time error rather than a silent no-op. `mode` is\n * optional only on the standard variant (the default), required on agentic/lite. Lite has no\n * knobs of its own — one recipe, OCR-only — and never reads `promptHint`.\n */\ntype ParseOptions =\n | (ParseOptionsBase & { mode?: \"standard\"; promptHint?: string })\n | (ParseOptionsBase & { mode: \"agentic\"; effort?: AgenticEffort; promptHint?: string })\n | (ParseOptionsBase & { mode: \"lite\" })\n | (ParseOptionsBase & { mode: \"flash\"; scannedPages?: ScannedPages; promptHint?: string });\n\n/**\n * Fluent assembler for a typed workflow graph — a faithful TS port of the\n * Python `WorkflowBuilder`. `parse`/`classify`/`split` are singletons;\n * `extract`/`validate` are repeatable and carry their edge metadata. Call\n * `build()` (or `create()`) to emit the wire request — submit with\n * `Workflow.run(file)` on the handle that `create()` returns.\n */\nexport class WorkflowBuilder {\n private parseNode: ParseNode | null = null;\n private classifyNode: ClassifyNode | null = null;\n private splitNode: SplitterNode | null = null;\n private splitRouteFrom: string | null = null;\n private readonly extracts: Array<[ExtractNode, string | null]> = [];\n private readonly validates: Array<[ValidateNode, string]> = [];\n private readonly idCounters: Record<string, number> = {};\n\n constructor(\n private readonly client: HeyClient,\n private readonly name: string,\n private readonly description?: string,\n ) {}\n\n private nextId(kind: string): string {\n this.idCounters[kind] = (this.idCounters[kind] ?? 0) + 1;\n return `${kind}_${this.idCounters[kind]}`;\n }\n\n private require(condition: unknown, message: string): void {\n if (!condition) throw new WorkflowBuilderError(message);\n }\n\n parse(opts: ParseOptions = {}): this {\n this.require(this.parseNode === null, \"parse() can only be called once\");\n // Widen to read every optional knob; the union already guaranteed only mode-valid ones are set.\n const o = opts as ParseOptionsBase & {\n mode?: ParseMode;\n promptHint?: string;\n effort?: AgenticEffort;\n scannedPages?: ScannedPages;\n };\n this.parseNode = {\n type: \"parse\",\n id: o.id ?? this.nextId(\"parse\"),\n mode: o.mode ?? \"standard\",\n ...(o.promptHint !== undefined ? { prompt_hint: o.promptHint } : {}),\n figure_enhancement: o.figureEnhancement ?? false,\n cache: o.cache ?? true,\n ...(o.effort !== undefined ? { effort: o.effort } : {}),\n ...(o.scannedPages !== undefined\n ? { scanned_pages: o.scannedPages }\n : {}),\n };\n return this;\n }\n\n classify(categories: ClassifyCategory[], opts: { id?: string } = {}): this {\n this.require(this.parseNode !== null, \"classify() requires parse() first\");\n this.require(this.classifyNode === null, \"classify() can only be called once\");\n this.require(categories.length > 0, \"classify() requires at least one category\");\n this.classifyNode = { type: \"classify\", id: opts.id ?? this.nextId(\"classify\"), categories };\n return this;\n }\n\n split(rules: SplitterRule[], opts: { routeFrom?: string | ClassifyCategory; id?: string } = {}): this {\n this.require(this.parseNode !== null, \"split() requires parse() first\");\n this.require(this.splitNode === null, \"split() can only be called once\");\n this.require(rules.length > 0, \"split() requires at least one rule\");\n this.require(\n !(opts.routeFrom !== undefined && this.classifyNode === null),\n \"routeFrom is only valid after classify()\",\n );\n this.require(\n !(this.classifyNode !== null && opts.routeFrom === undefined),\n \"split(rules, { routeFrom }) is required when chaining after classify() — specify which classify branch routes into the splitter\",\n );\n this.splitRouteFrom = this.normalizeClassifyBranch(opts.routeFrom, \"routeFrom\");\n this.splitNode = { type: \"splitter\", id: opts.id ?? this.nextId(\"split\"), rules };\n return this;\n }\n\n extract(\n fields: Field[],\n opts: {\n branch?: Branch;\n id?: string;\n mode?: ExtractMode;\n lookupFiles?: string[];\n lookupSuggestion?: string;\n lookupReasoningEffort?: ReasoningEffort;\n useImages?: boolean;\n } = {},\n ): this {\n this.require(this.parseNode !== null, \"extract() requires parse() first\");\n this.require(fields.length > 0, \"extract() requires at least one field\");\n const hasRouter = this.classifyNode !== null || this.splitNode !== null;\n this.require(\n !(hasRouter && opts.branch === undefined),\n \"extract(fields, { branch }) is required when classify() or split() is used\",\n );\n this.require(\n !(!hasRouter && opts.branch !== undefined),\n \"extract(fields, { branch }) is only valid after classify() or split()\",\n );\n const branchId = this.normalizeExtractBranch(opts.branch);\n const lookupFileUploads: LookupFileUpload[] = (opts.lookupFiles ?? []).map((filePath) => ({\n filename: basename(filePath),\n content: readFileSync(filePath).toString(\"base64\"),\n }));\n const node: ExtractNode = {\n type: \"extract\",\n id: opts.id ?? this.nextId(\"extract\"),\n ...(opts.mode !== undefined ? { mode: opts.mode } : {}),\n extraction_schema: { fields },\n ...(lookupFileUploads.length > 0 ? { lookup_file_uploads: lookupFileUploads } : {}),\n ...(opts.lookupSuggestion !== undefined ? { lookup_suggestion: opts.lookupSuggestion } : {}),\n ...(opts.lookupReasoningEffort !== undefined\n ? { lookup_reasoning_effort: opts.lookupReasoningEffort }\n : {}),\n ...(opts.useImages !== undefined ? { use_images: opts.useImages } : {}),\n };\n this.extracts.push([node, branchId]);\n return this;\n }\n\n validate(rules: ValidationRule[], opts: { branch?: Branch; id?: string } = {}): this {\n this.require(this.parseNode !== null, \"validate() requires parse() first\");\n this.require(this.extracts.length > 0, \"validate() requires extract() first\");\n this.require(rules.length > 0, \"validate() requires at least one rule\");\n\n let sourceExtractId: string;\n if (opts.branch !== undefined) {\n const branchId = this.normalizeExtractBranch(opts.branch);\n const matching = this.extracts.filter(([, b]) => b === branchId);\n this.require(matching.length > 0, `validate(branch) did not match any extract`);\n sourceExtractId = matching[matching.length - 1]![0].id;\n } else {\n sourceExtractId = this.extracts[this.extracts.length - 1]![0].id;\n }\n const node: ValidateNode = { type: \"validate\", id: opts.id ?? this.nextId(\"validate\"), rules };\n this.validates.push([node, sourceExtractId]);\n return this;\n }\n\n private normalizeClassifyBranch(value: string | ClassifyCategory | undefined, kwarg: string): string | null {\n if (value === undefined) return null;\n const categories = this.classifyNode?.categories ?? [];\n if (typeof value !== \"string\") {\n if (!categories.some((c) => c.id === value.id)) {\n throw new WorkflowBuilderError(`${kwarg}=${value.id} is not one of the registered classify categories`);\n }\n return value.id;\n }\n if (!categories.some((c) => c.id === value)) {\n throw new WorkflowBuilderError(`${kwarg}=${value} does not match any classify category id`);\n }\n return value;\n }\n\n private normalizeExtractBranch(value: Branch | undefined): string | null {\n if (value === undefined) return null;\n const router: Array<{ id: string }> = this.splitNode?.rules ?? this.classifyNode?.categories ?? [];\n if (typeof value !== \"string\") {\n if (!router.some((item) => item.id === value.id)) {\n const expected = this.splitNode ? \"splitter rule\" : \"classify category\";\n throw new WorkflowBuilderError(`branch=${value.id} is not one of the registered ${expected} objects`);\n }\n return value.id;\n }\n if (!router.some((item) => item.id === value)) {\n throw new WorkflowBuilderError(`branch=${value} does not match any router id`);\n }\n return value;\n }\n\n /** Assemble the wire request (branch-routed edges). Pure — no network. */\n build(): WorkflowCreateRequest {\n if (this.parseNode === null) throw new WorkflowBuilderError(\"build() requires parse()\");\n const parseId = this.parseNode.id;\n const nodes: WorkflowCreateRequest[\"nodes\"] = [this.parseNode];\n const edges: Edge[] = [];\n\n if (this.classifyNode !== null) {\n nodes.push(this.classifyNode);\n edges.push({ source: parseId, target: this.classifyNode.id });\n }\n\n if (this.splitNode !== null) {\n nodes.push(this.splitNode);\n if (this.classifyNode !== null) {\n edges.push({ source: this.classifyNode.id, target: this.splitNode.id, branch: this.splitRouteFrom });\n } else {\n edges.push({ source: parseId, target: this.splitNode.id });\n }\n }\n\n const routerId = this.splitNode?.id ?? this.classifyNode?.id ?? null;\n for (const [node, branchId] of this.extracts) {\n nodes.push(node);\n edges.push(\n routerId === null\n ? { source: parseId, target: node.id }\n : { source: routerId, target: node.id, branch: branchId },\n );\n }\n\n for (const [node, sourceExtractId] of this.validates) {\n nodes.push(node);\n edges.push({ source: sourceExtractId, target: node.id });\n }\n\n return { name: this.name, description: this.description, nodes, edges };\n }\n\n /** Persist the workflow and return a handle you can `.run(files)` on. */\n async create(): Promise<Workflow> {\n const res = await v3CreateWorkflow({ client: this.client, body: this.build() });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return new Workflow(this.client, res.data!.id, res.data!.name);\n }\n\n /** Replace an existing workflow's typed graph and return a handle you can `.run(files)` on. */\n async update(workflowId: string): Promise<Workflow> {\n const res = await v3UpdateWorkflow({ client: this.client, path: { workflow_id: workflowId }, body: this.build() });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return new Workflow(this.client, res.data!.id, res.data!.name);\n }\n}\n","import type { Block, ParseResult } from \"./sdk\";\n\n/**\n * Typed view over the parse node's output. Returned by `Result.parse` — readers\n * use it for `.markdown`, `.text`, `.blocks`, `.parseConfidence`, and\n * `.layoutConfidence` without having to walk `result.raw.parse`.\n *\n * No `.draw()` here: rasterising pages requires PDF rendering (pdfium); the\n * Python SDK ships that, the TS SDK does not.\n */\nexport class ParseView {\n /** @internal */\n constructor(private readonly parse: ParseResult) {}\n\n get markdown(): string | null {\n return this.parse.markdown ?? null;\n }\n\n get text(): string | null {\n return this.parse.text ?? null;\n }\n\n get blocks(): Block[] {\n return this.parse.blocks ?? [];\n }\n\n /**\n * Document-level confidence (0-100) in the parsed content. May be `null` for\n * some parse modes — fall back to `layoutConfidence`.\n */\n get parseConfidence(): number | null {\n return this.parse.parse_confidence ?? null;\n }\n\n /**\n * Document-level confidence (0-100) in the page layout (block positions).\n * `null` when not available.\n */\n get layoutConfidence(): number | null {\n return this.parse.layout_confidence ?? null;\n }\n}\n","import { ParseView } from \"./parse-view\";\nimport type { ExtractedField as GenExtractedField, Extraction, ResultsResponseV3 } from \"./sdk\";\n\n/**\n * One extracted field — generic over the value type so callers get real\n * types at the access site (`result.field<number>(\"total\").value` is\n * `number | null`, not `unknown`). Wire shape identical to the codegen type.\n */\nexport type ExtractedField<T = unknown> = Omit<GenExtractedField, \"value\" | \"value_override\"> & {\n value: T | null;\n value_override?: T | null;\n};\n\n/**\n * A list/object-array field (e.g. `line_items`): one entry per row, each row a\n * record of named `ExtractedField`s. This is the shape `field()` returns for a\n * non-scalar field.\n */\nexport type ExtractedRows = Array<Record<string, ExtractedField>>;\n\n/** Typed wrapper over a completed run's results. */\nexport class Result {\n private _parse: ParseView | null | undefined;\n\n constructor(readonly raw: ResultsResponseV3) {}\n\n get documentPacketId(): string {\n return this.raw.document_packet_id;\n }\n\n get extractions(): Extraction[] {\n return this.raw.extractions ?? [];\n }\n\n /**\n * Typed view over the parse node's output, or `null` when the workflow has\n * no parse node. Cached so repeated access doesn't re-wrap.\n */\n get parse(): ParseView | null {\n if (this._parse === undefined) {\n const raw = this.raw.parse;\n this._parse = raw ? new ParseView(raw) : null;\n }\n return this._parse;\n }\n\n /**\n * Convenience accessor for a top-level field on the untagged (linear)\n * extraction. Returns the scalar `ExtractedField` for a scalar field, or\n * the array of row records (`ExtractedRows`) for a list/object field such\n * as `line_items`. `undefined` only when the field is absent.\n *\n * Parameterise with the declared schema type to type a scalar's `.value`:\n * `result.field<number>(\"total\").value` is `number | null`.\n */\n field<T = unknown>(name: string): ExtractedField<T> | ExtractedRows | undefined {\n // Filter to the untagged extraction so a split/mixed payload — where\n // partition extractions can precede the linear one in ``extractions[]`` —\n // still resolves the top-level field. Mirrors the Python SDK's\n // ``parse_results`` untagged filter.\n const untagged = this.extractions.find(\n (e) => e.split_name == null && e.partition == null,\n );\n const value = untagged?.fields?.[name];\n if (value === undefined) return undefined;\n if (Array.isArray(value)) return value as ExtractedRows;\n return value as ExtractedField<T>;\n }\n}\n","export class AnyformatError extends Error {}\n\n/** Any JSON value the envelope's free-shaped `detail` may carry. */\nexport type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\n\n/** One field-level failure; the `detail` convention of validation errors. */\nexport interface ValidationItem {\n type: string;\n loc: (string | number)[];\n msg: string;\n}\n\n/** A `params` value: a scalar, `null`, or an array of those. */\nexport type ScalarOrList = string | number | boolean | null | (string | number | boolean | null)[];\n\n/** Fields of the API's error envelope: `{error, detail, error_code, retryable, request_id, params}`. */\ninterface ErrorEnvelopeBody {\n error?: unknown;\n detail?: unknown;\n error_code?: unknown;\n retryable?: unknown;\n request_id?: unknown;\n params?: unknown;\n}\n\nexport class APIError extends AnyformatError {\n /** Stable identifier for programmatic handling, e.g. `PAYMENT_REQUIRED`. */\n readonly errorCode?: string;\n /** Developer-facing explanation; not surfaced in `message` (ADR platform/0053 §2). Often a `ValidationItem[]`. */\n readonly detail?: JsonValue;\n /** Named substitutions the `error` summary refers to, e.g. `{ required_scope }`. */\n readonly params?: Record<string, ScalarOrList>;\n /** Whether the API says retrying the same request can succeed. */\n readonly retryable?: boolean;\n /** Correlation id to quote in support requests. */\n readonly requestId?: string;\n\n constructor(\n readonly status: number,\n message: string,\n readonly body?: unknown,\n ) {\n super(message);\n this.name = new.target.name;\n if (body && typeof body === \"object\") {\n const envelope = body as ErrorEnvelopeBody;\n if (typeof envelope.error_code === \"string\") this.errorCode = envelope.error_code;\n if (envelope.detail !== undefined) this.detail = envelope.detail as JsonValue;\n if (typeof envelope.retryable === \"boolean\") this.retryable = envelope.retryable;\n if (typeof envelope.request_id === \"string\") this.requestId = envelope.request_id;\n if (envelope.params && typeof envelope.params === \"object\") {\n this.params = envelope.params as Record<string, ScalarOrList>;\n }\n }\n }\n}\n\nexport class BadRequestError extends APIError {}\nexport class UnauthorizedError extends APIError {}\nexport class PaymentRequiredError extends APIError {}\nexport class ForbiddenError extends APIError {}\nexport class NotFoundError extends APIError {}\nexport class RateLimitedError extends APIError {\n constructor(\n status: number,\n message: string,\n body?: unknown,\n /** Seconds the API asks the caller to wait, from the `Retry-After` header; `undefined` when absent. */\n readonly retryAfter?: number,\n ) {\n super(status, message, body);\n }\n}\nexport class ServerError extends APIError {}\n\n/** `Retry-After` in seconds: delay-seconds or an HTTP-date (RFC 7231 §7.1.3). */\nexport function parseRetryAfter(raw: string | null | undefined): number | undefined {\n if (raw == null || raw.trim() === \"\") return undefined;\n const seconds = Number(raw);\n if (!Number.isNaN(seconds)) return seconds;\n const when = Date.parse(raw);\n if (Number.isNaN(when)) return undefined;\n return Math.max((when - Date.now()) / 1_000, 0);\n}\n\n// Status classes refined by `error_code`, aligned with the Python SDK's taxonomy.\n\n/** The API key lacks the scope this call needs (`insufficient_api_key_scope`). */\nexport class InsufficientScopeError extends ForbiddenError {}\n/** The caller must accept the terms of service first (`terms_acceptance_required`). */\nexport class TermsAcceptanceRequiredError extends ForbiddenError {}\n/** A workflow with that name already exists (`WORKFLOW_NAME_CONFLICT`). */\nexport class WorkflowNameConflictError extends APIError {}\n\nexport class SDKTimeoutError extends AnyformatError {}\n\n/** Thrown by `Run.wait()` when the run reaches a terminal failure status. */\nexport class RunFailedError extends AnyformatError {\n constructor(\n readonly runId: string,\n readonly status: \"error\" | \"cancelled\",\n ) {\n super(`Run ${runId} ended with status \"${status}\"`);\n this.name = new.target.name;\n }\n}\n\n/** The run ended in the terminal `error` status. */\nexport class ExtractionFailedError extends RunFailedError {\n constructor(runId: string) {\n super(runId, \"error\");\n }\n}\n\n/** The run ended in the terminal `cancelled` status. */\nexport class ExtractionCancelledError extends RunFailedError {\n constructor(runId: string) {\n super(runId, \"cancelled\");\n }\n}\n\n/** Raised by the fluent `WorkflowBuilder` for builder-API misuse. */\nexport class WorkflowBuilderError extends AnyformatError {}\n\n// `detail` is developer-facing and never lands in `message` (ADR platform/0053\n// §2); it stays reachable on `err.detail`.\nfunction messageFrom(status: number, body?: unknown): string {\n const fallback = `AnyFormat API error (${status})`;\n if (!body || typeof body !== \"object\") return fallback;\n const envelope = body as ErrorEnvelopeBody;\n return typeof envelope.error === \"string\" && envelope.error ? envelope.error : fallback;\n}\n\n/** `error_code` values that earn a class more specific than their HTTP status. */\nconst BY_ERROR_CODE: Record<string, new (status: number, message: string, body?: unknown) => APIError> = {\n insufficient_api_key_scope: InsufficientScopeError,\n terms_acceptance_required: TermsAcceptanceRequiredError,\n WORKFLOW_NAME_CONFLICT: WorkflowNameConflictError,\n};\n\nexport function toApiError(status: number, body?: unknown, headers?: Headers): APIError {\n const message = messageFrom(status, body);\n const errorCode =\n body && typeof body === \"object\" && typeof (body as ErrorEnvelopeBody).error_code === \"string\"\n ? ((body as ErrorEnvelopeBody).error_code as string)\n : undefined;\n const ByCode = errorCode ? BY_ERROR_CODE[errorCode] : undefined;\n if (ByCode) return new ByCode(status, message, body);\n switch (status) {\n case 400:\n return new BadRequestError(status, message, body);\n case 401:\n return new UnauthorizedError(status, message, body);\n case 402:\n return new PaymentRequiredError(status, message, body);\n case 403:\n return new ForbiddenError(status, message, body);\n case 404:\n return new NotFoundError(status, message, body);\n case 429:\n return new RateLimitedError(status, message, body, parseRetryAfter(headers?.get(\"Retry-After\")));\n default:\n return status >= 500\n ? new ServerError(status, message, body)\n : new APIError(status, message, body);\n }\n}\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen';\n\nexport type QuerySerializer = (query: Record<string, unknown>) => string;\n\nexport type BodySerializer = (body: unknown) => unknown;\n\ntype QuerySerializerOptionsObject = {\n allowReserved?: boolean;\n array?: Partial<SerializerOptions<ArrayStyle>>;\n object?: Partial<SerializerOptions<ObjectStyle>>;\n};\n\nexport type QuerySerializerOptions = QuerySerializerOptionsObject & {\n /**\n * Per-parameter serialization overrides. When provided, these settings\n * override the global array/object settings for specific parameter names.\n */\n parameters?: Record<string, QuerySerializerOptionsObject>;\n};\n\nconst serializeFormDataPair = (data: FormData, key: string, value: unknown): void => {\n if (typeof value === 'string' || value instanceof Blob) {\n data.append(key, value);\n } else if (value instanceof Date) {\n data.append(key, value.toISOString());\n } else {\n data.append(key, JSON.stringify(value));\n }\n};\n\nconst serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => {\n if (typeof value === 'string') {\n data.append(key, value);\n } else {\n data.append(key, JSON.stringify(value));\n }\n};\n\nexport const formDataBodySerializer = {\n bodySerializer: (body: unknown): FormData => {\n const data = new FormData();\n\n Object.entries(body as Record<string, unknown>).forEach(([key, value]) => {\n if (value === undefined || value === null) {\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((v) => serializeFormDataPair(data, key, v));\n } else {\n serializeFormDataPair(data, key, value);\n }\n });\n\n return data;\n },\n};\n\nexport const jsonBodySerializer = {\n bodySerializer: (body: unknown): string =>\n JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)),\n};\n\nexport const urlSearchParamsBodySerializer = {\n bodySerializer: (body: unknown): string => {\n const data = new URLSearchParams();\n\n Object.entries(body as Record<string, unknown>).forEach(([key, value]) => {\n if (value === undefined || value === null) {\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));\n } else {\n serializeUrlSearchParamsPair(data, key, value);\n }\n });\n\n return data.toString();\n },\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\ntype Slot = 'body' | 'headers' | 'path' | 'query';\n\nexport type Field =\n | {\n in: Exclude<Slot, 'body'>;\n /**\n * Field name. This is the name we want the user to see and use.\n */\n key: string;\n /**\n * Field mapped name. This is the name we want to use in the request.\n * If omitted, we use the same value as `key`.\n */\n map?: string;\n }\n | {\n in: Extract<Slot, 'body'>;\n /**\n * Key isn't required for bodies.\n */\n key?: string;\n map?: string;\n }\n | {\n /**\n * Field name. This is the name we want the user to see and use.\n */\n key: string;\n /**\n * Field mapped name. This is the name we want to use in the request.\n * If `in` is omitted, `map` aliases `key` to the transport layer.\n */\n map: Slot;\n };\n\nexport interface Fields {\n allowExtra?: Partial<Record<Slot, boolean>>;\n args?: ReadonlyArray<Field>;\n}\n\nexport type FieldsConfig = ReadonlyArray<Field | Fields>;\n\nconst extraPrefixesMap: Record<string, Slot> = {\n $body_: 'body',\n $headers_: 'headers',\n $path_: 'path',\n $query_: 'query',\n};\nconst extraPrefixes = Object.entries(extraPrefixesMap);\n\ntype KeyMap = Map<\n string,\n | {\n in: Slot;\n map?: string;\n }\n | {\n in?: never;\n map: Slot;\n }\n>;\n\nfunction buildKeyMap(fields: FieldsConfig, map?: KeyMap): KeyMap {\n if (!map) {\n map = new Map();\n }\n\n for (const config of fields) {\n if ('in' in config) {\n if (config.key) {\n map.set(config.key, {\n in: config.in,\n map: config.map,\n });\n }\n } else if ('key' in config) {\n map.set(config.key, {\n map: config.map,\n });\n } else if (config.args) {\n buildKeyMap(config.args, map);\n }\n }\n\n return map;\n}\n\ninterface Params {\n body?: unknown;\n headers: Record<string, unknown>;\n path: Record<string, unknown>;\n query: Record<string, unknown>;\n}\n\nfunction stripEmptySlots(params: Params): void {\n for (const [slot, value] of Object.entries(params)) {\n if (slot === 'body') continue;\n if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) {\n delete params[slot as Slot];\n }\n }\n}\n\nexport function buildClientParams(args: ReadonlyArray<unknown>, fields: FieldsConfig): Params {\n const params: Params = {\n headers: Object.create(null),\n path: Object.create(null),\n query: Object.create(null),\n };\n\n const map = buildKeyMap(fields);\n\n function writeSlot(slot: Slot, key: string, value: unknown): void {\n let record = params[slot] as Record<string, unknown> | undefined;\n if (record === undefined) {\n record = Object.create(null) as Record<string, unknown>;\n params[slot] = record;\n }\n record[key] = value;\n }\n\n let config: FieldsConfig[number] | undefined;\n\n for (const [index, arg] of args.entries()) {\n if (fields[index]) {\n config = fields[index];\n }\n\n if (!config) {\n continue;\n }\n\n if ('in' in config) {\n if (config.key) {\n const field = map.get(config.key)!;\n const name = field.map || config.key;\n if (field.in) {\n writeSlot(field.in, name, arg);\n }\n } else {\n params.body = arg;\n }\n } else {\n for (const [key, value] of Object.entries(arg ?? {})) {\n const field = map.get(key);\n\n if (field) {\n if (field.in) {\n const name = field.map || key;\n writeSlot(field.in, name, value);\n } else {\n params[field.map] = value;\n }\n } else {\n const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix));\n\n if (extra) {\n const [prefix, slot] = extra;\n writeSlot(slot, key.slice(prefix.length), value);\n } else if ('allowExtra' in config && config.allowExtra) {\n for (const [slot, allowed] of Object.entries(config.allowExtra)) {\n if (allowed) {\n writeSlot(slot as Slot, key, value);\n break;\n }\n }\n }\n }\n }\n }\n }\n\n stripEmptySlots(params);\n\n return params;\n}\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport type { Config } from './types.gen';\n\nexport type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, 'method'> &\n Pick<Config, 'method' | 'responseTransformer' | 'responseValidator'> & {\n /**\n * Fetch API implementation. You can use this option to provide a custom\n * fetch instance.\n *\n * @default globalThis.fetch\n */\n fetch?: typeof fetch;\n /**\n * Implementing clients can call request interceptors inside this hook.\n */\n onRequest?: (url: string, init: RequestInit) => Promise<Request>;\n /**\n * Callback invoked when a network or parsing error occurs during streaming.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @param error The error that occurred.\n */\n onSseError?: (error: unknown) => void;\n /**\n * Callback invoked when an event is streamed from the server.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @param event Event streamed from the server.\n * @returns Nothing (void).\n */\n onSseEvent?: (event: StreamEvent<TData>) => void;\n serializedBody?: RequestInit['body'];\n /**\n * Default retry delay in milliseconds.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @default 3000\n */\n sseDefaultRetryDelay?: number;\n /**\n * Maximum number of retry attempts before giving up.\n */\n sseMaxRetryAttempts?: number;\n /**\n * Maximum retry delay in milliseconds.\n *\n * Applies only when exponential backoff is used.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @default 30000\n */\n sseMaxRetryDelay?: number;\n /**\n * Optional sleep function for retry backoff.\n *\n * Defaults to using `setTimeout`.\n */\n sseSleepFn?: (ms: number) => Promise<void>;\n url: string;\n };\n\nexport interface StreamEvent<TData = unknown> {\n data: TData;\n event?: string;\n id?: string;\n retry?: number;\n}\n\nexport type ServerSentEventsResult<TData = unknown, TReturn = void, TNext = unknown> = {\n stream: AsyncGenerator<\n TData extends Record<string, unknown> ? TData[keyof TData] : TData,\n TReturn,\n TNext\n >;\n};\n\nexport function createSseClient<TData = unknown>({\n onRequest,\n onSseError,\n onSseEvent,\n responseTransformer,\n responseValidator,\n sseDefaultRetryDelay,\n sseMaxRetryAttempts,\n sseMaxRetryDelay,\n sseSleepFn,\n url,\n ...options\n}: ServerSentEventsOptions): ServerSentEventsResult<TData> {\n let lastEventId: string | undefined;\n\n const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));\n\n const createStream = async function* () {\n let retryDelay: number = sseDefaultRetryDelay ?? 3000;\n let attempt = 0;\n const signal = options.signal ?? new AbortController().signal;\n\n while (true) {\n if (signal.aborted) break;\n\n attempt++;\n\n const headers =\n options.headers instanceof Headers\n ? options.headers\n : new Headers(options.headers as Record<string, string> | undefined);\n\n if (lastEventId !== undefined) {\n headers.set('Last-Event-ID', lastEventId);\n }\n\n try {\n const requestInit: RequestInit = {\n redirect: 'follow',\n ...options,\n body: options.serializedBody,\n headers,\n signal,\n };\n let request = new Request(url, requestInit);\n if (onRequest) {\n request = await onRequest(url, requestInit);\n }\n // fetch must be assigned here, otherwise it would throw the error:\n // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation\n const _fetch = options.fetch ?? globalThis.fetch;\n const response = await _fetch(request);\n\n if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);\n\n if (!response.body) throw new Error('No body in SSE response');\n\n const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();\n\n let buffer = '';\n\n const abortHandler = () => {\n try {\n reader.cancel();\n } catch {\n // noop\n }\n };\n\n signal.addEventListener('abort', abortHandler);\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += value;\n buffer = buffer.replace(/\\r\\n?/g, '\\n'); // normalize line endings\n\n const chunks = buffer.split('\\n\\n');\n buffer = chunks.pop() ?? '';\n\n for (const chunk of chunks) {\n const lines = chunk.split('\\n');\n const dataLines: Array<string> = [];\n let eventName: string | undefined;\n\n for (const line of lines) {\n if (line.startsWith('data:')) {\n dataLines.push(line.replace(/^data:\\s*/, ''));\n } else if (line.startsWith('event:')) {\n eventName = line.replace(/^event:\\s*/, '');\n } else if (line.startsWith('id:')) {\n lastEventId = line.replace(/^id:\\s*/, '');\n } else if (line.startsWith('retry:')) {\n const parsed = Number.parseInt(line.replace(/^retry:\\s*/, ''), 10);\n if (!Number.isNaN(parsed)) {\n retryDelay = parsed;\n }\n }\n }\n\n let data: unknown;\n let parsedJson = false;\n\n if (dataLines.length) {\n const rawData = dataLines.join('\\n');\n try {\n data = JSON.parse(rawData);\n parsedJson = true;\n } catch {\n data = rawData;\n }\n }\n\n if (parsedJson) {\n if (responseValidator) {\n await responseValidator(data);\n }\n\n if (responseTransformer) {\n data = await responseTransformer(data);\n }\n }\n\n onSseEvent?.({\n data,\n event: eventName,\n id: lastEventId,\n retry: retryDelay,\n });\n\n if (dataLines.length) {\n yield data as any;\n }\n }\n }\n } finally {\n signal.removeEventListener('abort', abortHandler);\n reader.releaseLock();\n }\n\n break; // exit loop on normal completion\n } catch (error) {\n // connection failed or aborted; retry after delay\n onSseError?.(error);\n\n if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) {\n break; // stop after firing error\n }\n\n // exponential backoff: double retry each attempt, cap at 30s\n const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000);\n await sleep(backoff);\n }\n }\n };\n\n const stream = createStream();\n\n return { stream };\n}\n","// This file is auto-generated by @hey-api/openapi-ts\n\ninterface SerializeOptions<T> extends SerializePrimitiveOptions, SerializerOptions<T> {}\n\ninterface SerializePrimitiveOptions {\n allowReserved?: boolean;\n name: string;\n}\n\nexport interface SerializerOptions<T> {\n /**\n * @default true\n */\n explode: boolean;\n style: T;\n}\n\nexport type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';\nexport type ArraySeparatorStyle = ArrayStyle | MatrixStyle;\ntype MatrixStyle = 'label' | 'matrix' | 'simple';\nexport type ObjectStyle = 'form' | 'deepObject';\ntype ObjectSeparatorStyle = ObjectStyle | MatrixStyle;\n\ninterface SerializePrimitiveParam extends SerializePrimitiveOptions {\n value: string;\n}\n\nexport const separatorArrayExplode = (style: ArraySeparatorStyle): '.' | ';' | ',' | '&' => {\n switch (style) {\n case 'label':\n return '.';\n case 'matrix':\n return ';';\n case 'simple':\n return ',';\n default:\n return '&';\n }\n};\n\nexport const separatorArrayNoExplode = (style: ArraySeparatorStyle): ',' | '|' | '%20' => {\n switch (style) {\n case 'form':\n return ',';\n case 'pipeDelimited':\n return '|';\n case 'spaceDelimited':\n return '%20';\n default:\n return ',';\n }\n};\n\nexport const separatorObjectExplode = (style: ObjectSeparatorStyle): '.' | ';' | ',' | '&' => {\n switch (style) {\n case 'label':\n return '.';\n case 'matrix':\n return ';';\n case 'simple':\n return ',';\n default:\n return '&';\n }\n};\n\nexport const serializeArrayParam = ({\n allowReserved,\n explode,\n name,\n style,\n value,\n}: SerializeOptions<ArraySeparatorStyle> & {\n value: unknown[];\n}): string => {\n if (!explode) {\n const joinedValues = (\n allowReserved ? value : value.map((v) => encodeURIComponent(v as string))\n ).join(separatorArrayNoExplode(style));\n switch (style) {\n case 'label':\n return `.${joinedValues}`;\n case 'matrix':\n return `;${name}=${joinedValues}`;\n case 'simple':\n return joinedValues;\n default:\n return `${name}=${joinedValues}`;\n }\n }\n\n const separator = separatorArrayExplode(style);\n const joinedValues = value\n .map((v) => {\n if (style === 'label' || style === 'simple') {\n return allowReserved ? v : encodeURIComponent(v as string);\n }\n\n return serializePrimitiveParam({\n allowReserved,\n name,\n value: v as string,\n });\n })\n .join(separator);\n return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues;\n};\n\nexport const serializePrimitiveParam = ({\n allowReserved,\n name,\n value,\n}: SerializePrimitiveParam): string => {\n if (value === undefined || value === null) {\n return '';\n }\n\n if (typeof value === 'object') {\n throw new Error(\n 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.',\n );\n }\n\n return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;\n};\n\nexport const serializeObjectParam = ({\n allowReserved,\n explode,\n name,\n style,\n value,\n valueOnly,\n}: SerializeOptions<ObjectSeparatorStyle> & {\n value: Record<string, unknown> | Date;\n valueOnly?: boolean;\n}): string => {\n if (value instanceof Date) {\n return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;\n }\n\n if (style !== 'deepObject' && !explode) {\n let values: string[] = [];\n Object.entries(value).forEach(([key, v]) => {\n values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)];\n });\n const joinedValues = values.join(',');\n switch (style) {\n case 'form':\n return `${name}=${joinedValues}`;\n case 'label':\n return `.${joinedValues}`;\n case 'matrix':\n return `;${name}=${joinedValues}`;\n default:\n return joinedValues;\n }\n }\n\n const separator = separatorObjectExplode(style);\n const joinedValues = Object.entries(value)\n .map(([key, v]) =>\n serializePrimitiveParam({\n allowReserved,\n name: style === 'deepObject' ? `${name}[${key}]` : key,\n value: v as string,\n }),\n )\n .join(separator);\n return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues;\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport type { BodySerializer, QuerySerializer } from './bodySerializer.gen';\nimport {\n type ArraySeparatorStyle,\n serializeArrayParam,\n serializeObjectParam,\n serializePrimitiveParam,\n} from './pathSerializer.gen';\n\nexport interface PathSerializer {\n path: Record<string, unknown>;\n url: string;\n}\n\nexport const PATH_PARAM_RE: RegExp = /\\{[^{}]+\\}/g;\n\nexport const defaultPathSerializer = ({ path, url: _url }: PathSerializer): string => {\n let url = _url;\n const matches = _url.match(PATH_PARAM_RE);\n if (matches) {\n for (const match of matches) {\n let explode = false;\n let name = match.substring(1, match.length - 1);\n let style: ArraySeparatorStyle = 'simple';\n\n if (name.endsWith('*')) {\n explode = true;\n name = name.substring(0, name.length - 1);\n }\n\n if (name.startsWith('.')) {\n name = name.substring(1);\n style = 'label';\n } else if (name.startsWith(';')) {\n name = name.substring(1);\n style = 'matrix';\n }\n\n const value = path[name];\n\n if (value === undefined || value === null) {\n continue;\n }\n\n if (Array.isArray(value)) {\n url = url.replace(match, serializeArrayParam({ explode, name, style, value }));\n continue;\n }\n\n if (typeof value === 'object') {\n url = url.replace(\n match,\n serializeObjectParam({\n explode,\n name,\n style,\n value: value as Record<string, unknown>,\n valueOnly: true,\n }),\n );\n continue;\n }\n\n if (style === 'matrix') {\n url = url.replace(\n match,\n `;${serializePrimitiveParam({\n name,\n value: value as string,\n })}`,\n );\n continue;\n }\n\n const replaceValue = encodeURIComponent(\n style === 'label' ? `.${value as string}` : (value as string),\n );\n url = url.replace(match, replaceValue);\n }\n }\n return url;\n};\n\nexport const getUrl = ({\n baseUrl,\n path,\n query,\n querySerializer,\n url: _url,\n}: {\n baseUrl?: string;\n path?: Record<string, unknown>;\n query?: Record<string, unknown>;\n querySerializer: QuerySerializer;\n url: string;\n}): string => {\n const pathUrl = _url.startsWith('/') ? _url : `/${_url}`;\n let url = (baseUrl ?? '') + pathUrl;\n if (path) {\n url = defaultPathSerializer({ path, url });\n }\n let search = query ? querySerializer(query) : '';\n if (search.startsWith('?')) {\n search = search.substring(1);\n }\n if (search) {\n url += `?${search}`;\n }\n return url;\n};\n\nexport function getValidRequestBody(options: {\n body?: unknown;\n bodySerializer?: BodySerializer | null;\n serializedBody?: unknown;\n}): unknown {\n const hasBody = options.body !== undefined;\n const isSerializedBody = hasBody && options.bodySerializer;\n\n if (isSerializedBody) {\n if ('serializedBody' in options) {\n const hasSerializedBody =\n options.serializedBody !== undefined && options.serializedBody !== '';\n\n return hasSerializedBody ? options.serializedBody : null;\n }\n\n // not all clients implement a serializedBody property (i.e., client-axios)\n return options.body !== '' ? options.body : null;\n }\n\n // plain/text body\n if (hasBody) {\n return options.body;\n }\n\n // no body was provided\n return undefined;\n}\n","// This file is auto-generated by @hey-api/openapi-ts\n\nexport type AuthToken = string | undefined;\n\nexport interface Auth {\n /**\n * Which part of the request do we use to send the auth?\n *\n * @default 'header'\n */\n in?: 'header' | 'query' | 'cookie';\n /**\n * A unique identifier for the security scheme.\n *\n * Defined only when there are multiple security schemes whose `Auth`\n * shape would otherwise be identical.\n */\n key?: string;\n /**\n * Header or query parameter name.\n *\n * @default 'Authorization'\n */\n name?: string;\n scheme?: 'basic' | 'bearer';\n type: 'apiKey' | 'http';\n}\n\nexport const getAuthToken = async (\n auth: Auth,\n callback: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken,\n): Promise<string | undefined> => {\n const token = typeof callback === 'function' ? await callback(auth) : callback;\n\n if (!token) {\n return;\n }\n\n if (auth.scheme === 'bearer') {\n return `Bearer ${token}`;\n }\n\n if (auth.scheme === 'basic') {\n return `Basic ${btoa(token)}`;\n }\n\n return token;\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { getAuthToken } from '../core/auth.gen';\nimport type { QuerySerializerOptions } from '../core/bodySerializer.gen';\nimport { jsonBodySerializer } from '../core/bodySerializer.gen';\nimport {\n serializeArrayParam,\n serializeObjectParam,\n serializePrimitiveParam,\n} from '../core/pathSerializer.gen';\nimport { getUrl } from '../core/utils.gen';\nimport type { Client, ClientOptions, Config, RequestOptions } from './types.gen';\n\nexport const createQuerySerializer = <T = unknown>({\n parameters = {},\n ...args\n}: QuerySerializerOptions = {}): ((queryParams: T) => string) => {\n const querySerializer = (queryParams: T): string => {\n const search: string[] = [];\n if (queryParams && typeof queryParams === 'object') {\n for (const name in queryParams) {\n const value = queryParams[name];\n\n if (value === undefined || value === null) {\n continue;\n }\n\n const options = parameters[name] || args;\n\n if (Array.isArray(value)) {\n const serializedArray = serializeArrayParam({\n allowReserved: options.allowReserved,\n explode: true,\n name,\n style: 'form',\n value,\n ...options.array,\n });\n if (serializedArray) search.push(serializedArray);\n } else if (typeof value === 'object') {\n const serializedObject = serializeObjectParam({\n allowReserved: options.allowReserved,\n explode: true,\n name,\n style: 'deepObject',\n value: value as Record<string, unknown>,\n ...options.object,\n });\n if (serializedObject) search.push(serializedObject);\n } else {\n const serializedPrimitive = serializePrimitiveParam({\n allowReserved: options.allowReserved,\n name,\n value: value as string,\n });\n if (serializedPrimitive) search.push(serializedPrimitive);\n }\n }\n }\n return search.join('&');\n };\n return querySerializer;\n};\n\n/**\n * Infers parseAs value from provided Content-Type header.\n */\nexport const getParseAs = (contentType: string | null): Exclude<Config['parseAs'], 'auto'> => {\n if (!contentType) {\n // If no Content-Type header is provided, the best we can do is return the raw response body,\n // which is effectively the same as the 'stream' option.\n return 'stream';\n }\n\n const cleanContent = contentType.split(';')[0]?.trim();\n\n if (!cleanContent) {\n return;\n }\n\n if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) {\n return 'json';\n }\n\n if (cleanContent === 'multipart/form-data') {\n return 'formData';\n }\n\n if (\n ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type))\n ) {\n return 'blob';\n }\n\n if (cleanContent.startsWith('text/')) {\n return 'text';\n }\n\n return;\n};\n\nconst checkForExistence = (\n options: Pick<RequestOptions, 'auth' | 'query'> & {\n headers: Headers;\n },\n name?: string,\n): boolean => {\n if (!name) {\n return false;\n }\n if (\n options.headers.has(name) ||\n options.query?.[name] ||\n options.headers.get('Cookie')?.includes(`${name}=`)\n ) {\n return true;\n }\n return false;\n};\n\nexport async function setAuthParams(\n options: Pick<RequestOptions, 'auth' | 'query' | 'security'> & {\n headers: Headers;\n },\n): Promise<void> {\n for (const auth of options.security ?? []) {\n if (checkForExistence(options, auth.name)) {\n continue;\n }\n\n const token = await getAuthToken(auth, options.auth);\n\n if (!token) {\n continue;\n }\n\n const name = auth.name ?? 'Authorization';\n\n switch (auth.in) {\n case 'query':\n if (!options.query) {\n options.query = {};\n }\n options.query[name] = token;\n break;\n case 'cookie':\n options.headers.append('Cookie', `${name}=${token}`);\n break;\n case 'header':\n default:\n options.headers.set(name, token);\n break;\n }\n }\n}\n\nexport const buildUrl: Client['buildUrl'] = (options) =>\n getUrl({\n baseUrl: options.baseUrl as string,\n path: options.path,\n query: options.query,\n querySerializer:\n typeof options.querySerializer === 'function'\n ? options.querySerializer\n : createQuerySerializer(options.querySerializer),\n url: options.url,\n });\n\nexport const mergeConfigs = (a: Config, b: Config): Config => {\n const config = { ...a, ...b };\n if (config.baseUrl?.endsWith('/')) {\n config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);\n }\n config.headers = mergeHeaders(a.headers, b.headers);\n return config;\n};\n\nconst headersEntries = (headers: Headers): Array<[string, string]> => {\n const entries: Array<[string, string]> = [];\n headers.forEach((value, key) => {\n entries.push([key, value]);\n });\n return entries;\n};\n\nexport const mergeHeaders = (\n ...headers: Array<Required<Config>['headers'] | undefined>\n): Headers => {\n const mergedHeaders = new Headers();\n for (const header of headers) {\n if (!header) {\n continue;\n }\n\n const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);\n\n for (const [key, value] of iterator) {\n if (value === null) {\n mergedHeaders.delete(key);\n } else if (Array.isArray(value)) {\n for (const v of value) {\n mergedHeaders.append(key, v as string);\n }\n } else if (value !== undefined) {\n // assume object headers are meant to be JSON stringified, i.e., their\n // content value in OpenAPI specification is 'application/json'\n mergedHeaders.set(\n key,\n typeof value === 'object' ? JSON.stringify(value) : (value as string),\n );\n }\n }\n }\n return mergedHeaders;\n};\n\ntype ErrInterceptor<Err, Res, Req, Options> = (\n error: Err,\n /** response may be undefined due to a network error where no response object is produced */\n response: Res | undefined,\n /** request may be undefined, because error may be from building the request object itself */\n request: Req | undefined,\n options: Options,\n) => Err | Promise<Err>;\n\ntype ReqInterceptor<Req, Options> = (request: Req, options: Options) => Req | Promise<Req>;\n\ntype ResInterceptor<Res, Req, Options> = (\n response: Res,\n request: Req,\n options: Options,\n) => Res | Promise<Res>;\n\nclass Interceptors<Interceptor> {\n fns: Array<Interceptor | null> = [];\n\n clear(): void {\n this.fns = [];\n }\n\n eject(id: number | Interceptor): void {\n const index = this.getInterceptorIndex(id);\n if (this.fns[index]) {\n this.fns[index] = null;\n }\n }\n\n exists(id: number | Interceptor): boolean {\n const index = this.getInterceptorIndex(id);\n return Boolean(this.fns[index]);\n }\n\n getInterceptorIndex(id: number | Interceptor): number {\n if (typeof id === 'number') {\n return this.fns[id] ? id : -1;\n }\n return this.fns.indexOf(id);\n }\n\n update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false {\n const index = this.getInterceptorIndex(id);\n if (this.fns[index]) {\n this.fns[index] = fn;\n return id;\n }\n return false;\n }\n\n use(fn: Interceptor): number {\n this.fns.push(fn);\n return this.fns.length - 1;\n }\n}\n\nexport interface Middleware<Req, Res, Err, Options> {\n error: Interceptors<ErrInterceptor<Err, Res, Req, Options>>;\n request: Interceptors<ReqInterceptor<Req, Options>>;\n response: Interceptors<ResInterceptor<Res, Req, Options>>;\n}\n\nexport const createInterceptors = <Req, Res, Err, Options>(): Middleware<\n Req,\n Res,\n Err,\n Options\n> => ({\n error: new Interceptors<ErrInterceptor<Err, Res, Req, Options>>(),\n request: new Interceptors<ReqInterceptor<Req, Options>>(),\n response: new Interceptors<ResInterceptor<Res, Req, Options>>(),\n});\n\nconst defaultQuerySerializer = createQuerySerializer({\n allowReserved: false,\n array: {\n explode: true,\n style: 'form',\n },\n object: {\n explode: true,\n style: 'deepObject',\n },\n});\n\nconst defaultHeaders = {\n 'Content-Type': 'application/json',\n};\n\nexport const createConfig = <T extends ClientOptions = ClientOptions>(\n override: Config<Omit<ClientOptions, keyof T> & T> = {},\n): Config<Omit<ClientOptions, keyof T> & T> => ({\n ...jsonBodySerializer,\n headers: defaultHeaders,\n parseAs: 'auto',\n querySerializer: defaultQuerySerializer,\n ...override,\n});\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { createSseClient } from '../core/serverSentEvents.gen';\nimport type { HttpMethod } from '../core/types.gen';\nimport { getValidRequestBody } from '../core/utils.gen';\nimport type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen';\nimport {\n buildUrl,\n createConfig,\n createInterceptors,\n getParseAs,\n mergeConfigs,\n mergeHeaders,\n setAuthParams,\n} from './utils.gen';\n\ntype ReqInit = Omit<RequestInit, 'body' | 'headers'> & {\n body?: any;\n headers: ReturnType<typeof mergeHeaders>;\n};\n\nexport const createClient = (config: Config = {}): Client => {\n let _config = mergeConfigs(createConfig(), config);\n\n const getConfig = (): Config => ({ ..._config });\n\n const setConfig = (config: Config): Config => {\n _config = mergeConfigs(_config, config);\n return getConfig();\n };\n\n const interceptors = createInterceptors<Request, Response, unknown, ResolvedRequestOptions>();\n\n const beforeRequest = async <\n TData = unknown,\n TResponseStyle extends 'data' | 'fields' = 'fields',\n ThrowOnError extends boolean = boolean,\n Url extends string = string,\n >(\n options: RequestOptions<TData, TResponseStyle, ThrowOnError, Url>,\n ) => {\n const opts = {\n ..._config,\n ...options,\n fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,\n headers: mergeHeaders(_config.headers, options.headers),\n serializedBody: undefined as string | undefined,\n };\n\n if (opts.security) {\n await setAuthParams(opts);\n }\n\n if (opts.requestValidator) {\n await opts.requestValidator(opts);\n }\n\n if (opts.body !== undefined && opts.bodySerializer) {\n opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined;\n }\n\n // remove Content-Type header if body is empty to avoid sending invalid requests\n if (opts.body === undefined || opts.serializedBody === '') {\n opts.headers.delete('Content-Type');\n }\n\n const resolvedOpts = opts as typeof opts &\n ResolvedRequestOptions<TResponseStyle, ThrowOnError, Url>;\n const url = buildUrl(resolvedOpts);\n\n return { opts: resolvedOpts, url };\n };\n\n const request: Client['request'] = async (options) => {\n const throwOnError = options.throwOnError ?? _config.throwOnError;\n const responseStyle = options.responseStyle ?? _config.responseStyle;\n\n let request: Request | undefined;\n let response: Response | undefined;\n\n try {\n const { opts, url } = await beforeRequest(options);\n const requestInit: ReqInit = {\n redirect: 'follow',\n ...opts,\n body: getValidRequestBody(opts),\n };\n\n request = new Request(url, requestInit);\n\n for (const fn of interceptors.request.fns) {\n if (fn) {\n request = await fn(request, opts);\n }\n }\n\n // fetch must be assigned here, otherwise it would throw the error:\n // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation\n const _fetch = opts.fetch!;\n\n response = await _fetch(request);\n\n for (const fn of interceptors.response.fns) {\n if (fn) {\n response = await fn(response, request, opts);\n }\n }\n\n const result = {\n request,\n response,\n };\n\n if (response.ok) {\n const parseAs =\n (opts.parseAs === 'auto'\n ? getParseAs(response.headers.get('Content-Type'))\n : opts.parseAs) ?? 'json';\n\n if (response.status === 204 || response.headers.get('Content-Length') === '0') {\n let emptyData: any;\n switch (parseAs) {\n case 'arrayBuffer':\n case 'blob':\n case 'text':\n emptyData = await response[parseAs]();\n break;\n case 'formData':\n emptyData = new FormData();\n break;\n case 'stream':\n emptyData = response.body;\n break;\n case 'json':\n default:\n emptyData = {};\n break;\n }\n return opts.responseStyle === 'data'\n ? emptyData\n : {\n data: emptyData,\n ...result,\n };\n }\n\n let data: any;\n switch (parseAs) {\n case 'arrayBuffer':\n case 'blob':\n case 'formData':\n case 'text':\n data = await response[parseAs]();\n break;\n case 'json': {\n // Some servers return 200 with no Content-Length and empty body.\n // response.json() would throw; read as text and parse if non-empty.\n const text = await response.text();\n data = text ? JSON.parse(text) : {};\n break;\n }\n case 'stream':\n return opts.responseStyle === 'data'\n ? response.body\n : {\n data: response.body,\n ...result,\n };\n }\n\n if (parseAs === 'json') {\n if (opts.responseValidator) {\n await opts.responseValidator(data);\n }\n\n if (opts.responseTransformer) {\n data = await opts.responseTransformer(data);\n }\n }\n\n return opts.responseStyle === 'data'\n ? data\n : {\n data,\n ...result,\n };\n }\n\n const textError = await response.text();\n let jsonError: unknown;\n\n try {\n jsonError = JSON.parse(textError);\n } catch {\n // noop\n }\n\n throw jsonError ?? textError;\n } catch (error) {\n let finalError = error;\n\n for (const fn of interceptors.error.fns) {\n if (fn) {\n finalError = await fn(finalError, response, request, options as ResolvedRequestOptions);\n }\n }\n\n finalError = finalError || {};\n\n if (throwOnError) {\n throw finalError;\n }\n\n // TODO: we probably want to return error and improve types\n return responseStyle === 'data'\n ? undefined\n : {\n error: finalError,\n request,\n response,\n };\n }\n };\n\n const makeMethodFn = (method: Uppercase<HttpMethod>) => (options: RequestOptions) =>\n request({ ...options, method });\n\n const makeSseFn = (method: Uppercase<HttpMethod>) => async (options: RequestOptions) => {\n const { opts, url } = await beforeRequest(options);\n return createSseClient({\n ...opts,\n body: opts.body as BodyInit | null | undefined,\n method,\n onRequest: async (url, init) => {\n let request = new Request(url, init);\n for (const fn of interceptors.request.fns) {\n if (fn) {\n request = await fn(request, opts);\n }\n }\n return request;\n },\n serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined,\n url,\n });\n };\n\n const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options });\n\n return {\n buildUrl: _buildUrl,\n connect: makeMethodFn('CONNECT'),\n delete: makeMethodFn('DELETE'),\n get: makeMethodFn('GET'),\n getConfig,\n head: makeMethodFn('HEAD'),\n interceptors,\n options: makeMethodFn('OPTIONS'),\n patch: makeMethodFn('PATCH'),\n post: makeMethodFn('POST'),\n put: makeMethodFn('PUT'),\n request,\n setConfig,\n sse: {\n connect: makeSseFn('CONNECT'),\n delete: makeSseFn('DELETE'),\n get: makeSseFn('GET'),\n head: makeSseFn('HEAD'),\n options: makeSseFn('OPTIONS'),\n patch: makeSseFn('PATCH'),\n post: makeSseFn('POST'),\n put: makeSseFn('PUT'),\n trace: makeSseFn('TRACE'),\n },\n trace: makeMethodFn('TRACE'),\n } as Client;\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { type Client, type ClientOptions, type Config, createClient, createConfig } from './client';\nimport type { ClientOptions as ClientOptions2 } from './types.gen';\n\n/**\n * The `createClientConfig()` function will be called on client initialization\n * and the returned object will become the client's initial configuration.\n *\n * You may want to initialize your client this way instead of calling\n * `setConfig()`. This is useful for example if you're using Next.js\n * to ensure your client always has the correct values.\n */\nexport type CreateClientConfig<T extends ClientOptions = ClientOptions2> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;\n\nexport const client: Client = createClient(createConfig<ClientOptions2>({ baseUrl: 'https://api.anyformat.dev' }));\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { type Client, type ClientMeta, formDataBodySerializer, type Options as Options2, type RequestResult, type TDataShape } from './client';\nimport { client } from './client.gen';\nimport type { V3AskKnowledgeData, V3AskKnowledgeErrors, V3AskKnowledgeResponses, V3CreateBlobSlotsData, V3CreateBlobSlotsErrors, V3CreateBlobSlotsResponses, V3CreateWorkflowData, V3CreateWorkflowErrors, V3CreateWorkflowResponses, V3DeleteDocumentPacketData, V3DeleteDocumentPacketErrors, V3DeleteDocumentPacketResponses, V3DeleteEditReferenceData, V3DeleteEditReferenceErrors, V3DeleteEditReferenceResponses, V3DeleteWorkflowData, V3DeleteWorkflowErrors, V3DeleteWorkflowResponses, V3DownloadKnowledgeData, V3DownloadKnowledgeErrors, V3DownloadKnowledgeResponses, V3GetDocumentPacketData, V3GetDocumentPacketErrors, V3GetDocumentPacketResponses, V3GetEvalData, V3GetEvalErrors, V3GetEvalResponses, V3GetRunData, V3GetRunErrors, V3GetRunResponses, V3GetWorkflowData, V3GetWorkflowErrors, V3GetWorkflowResponses, V3LaunchEvalData, V3LaunchEvalErrors, V3LaunchEvalResponses, V3ListEditReferencesData, V3ListEditReferencesErrors, V3ListEditReferencesResponses, V3ListEvalsData, V3ListEvalsErrors, V3ListEvalsResponses, V3ListKnowledgeData, V3ListKnowledgeErrors, V3ListKnowledgeResponses, V3ListWorkflowDocumentPacketsData, V3ListWorkflowDocumentPacketsErrors, V3ListWorkflowDocumentPacketsResponses, V3ListWorkflowRunsData, V3ListWorkflowRunsErrors, V3ListWorkflowRunsResponses, V3ListWorkflowsData, V3ListWorkflowsErrors, V3ListWorkflowsResponses, V3ListWorkflowVersionsData, V3ListWorkflowVersionsErrors, V3ListWorkflowVersionsResponses, V3ParseData, V3ParseErrors, V3ParseFromUrlData, V3ParseFromUrlErrors, V3ParseFromUrlResponses, V3ParseResponses, V3ReadKnowledgeData, V3ReadKnowledgeErrors, V3ReadKnowledgeResponses, V3RunDocumentPacketData, V3RunDocumentPacketErrors, V3RunDocumentPacketResponses, V3SearchKnowledgeData, V3SearchKnowledgeErrors, V3SearchKnowledgeResponses, V3UpdateWorkflowData, V3UpdateWorkflowErrors, V3UpdateWorkflowResponses, V3UploadAndRunWorkflowData, V3UploadAndRunWorkflowErrors, V3UploadAndRunWorkflowResponses, V3UploadEditReferencesData, V3UploadEditReferencesErrors, V3UploadEditReferencesResponses, V3UploadFromUrlData, V3UploadFromUrlErrors, V3UploadFromUrlResponses, V3UploadToDatasetData, V3UploadToDatasetErrors, V3UploadToDatasetResponses, V3UploadToWorkflowData, V3UploadToWorkflowErrors, V3UploadToWorkflowResponses } from './types.gen';\n\nexport type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {\n /**\n * You can provide a client instance returned by `createClient()` instead of\n * individual options. This might be also useful if you want to implement a\n * custom client.\n */\n client?: Client;\n /**\n * You can pass arbitrary values through the `meta` object. This can be\n * used to access values that aren't defined as part of the SDK function.\n */\n meta?: keyof ClientMeta extends never ? Record<string, unknown> : ClientMeta;\n};\n\n/**\n * Stage a file you hold, and get the URL it will be readable at\n *\n * Get somewhere to put a file you hold, plus the URL it will read back at.\n *\n * Every other ingestion path takes a URL this API can fetch, which a file on\n * your own machine is not. Staging closes that gap in one call: the bytes go\n * straight from you to storage without passing through this API, and the\n * `read_url` is minted here because the destination is known before a byte\n * moves.\n *\n * Per slot, POST `upload.fields` verbatim followed by the file part as\n * multipart/form-data to `upload.url`. Then refer to the file by its\n * `object_id` — `POST /v3/parse/from-url/` takes `{object_id, filename}` and\n * `POST /v3/workflows/{id}/upload/from-url/` takes `staged_files` — or hand\n * `read_url` to something outside this API; the filename is signed into that\n * URL, so the file is named correctly on the other side.\n *\n * Each policy pins the destination, the content type and the exact\n * `declared_size`, so a slot accepts one intended file and nothing else. A\n * batch is all-or-nothing: a file above your plan's size limit fails the whole\n * call with a 422 and mints no slots, before a byte moves.\n *\n * Staged bytes are scratch: they belong to no workflow, and storage deletes\n * them within a day. Anything that must outlive that belongs in a workflow.\n */\nexport const v3CreateBlobSlots = <ThrowOnError extends boolean = false>(options: Options<V3CreateBlobSlotsData, ThrowOnError>): RequestResult<V3CreateBlobSlotsResponses, V3CreateBlobSlotsErrors, ThrowOnError> => (options.client ?? client).post<V3CreateBlobSlotsResponses, V3CreateBlobSlotsErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/blobs/slots/',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Delete document packet\n *\n * Delete a document packet and all its files.\n *\n * Same semantics as `DELETE /v2/files/{collection_id}/`: the packet and\n * every file in it are removed together, along with any extraction\n * results. This action is irreversible.\n */\nexport const v3DeleteDocumentPacket = <ThrowOnError extends boolean = false>(options: Options<V3DeleteDocumentPacketData, ThrowOnError>): RequestResult<V3DeleteDocumentPacketResponses, V3DeleteDocumentPacketErrors, ThrowOnError> => (options.client ?? client).delete<V3DeleteDocumentPacketResponses, V3DeleteDocumentPacketErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/document-packets/{document_packet_id}/',\n ...options\n});\n\n/**\n * Get document packet\n *\n * Retrieve one document packet flat: status, timestamps, the files it\n * groups, and `latest_run_id` (`null` until the packet has been run).\n *\n * Unknown ids — including packets belonging to another organization —\n * return 404.\n */\nexport const v3GetDocumentPacket = <ThrowOnError extends boolean = false>(options: Options<V3GetDocumentPacketData, ThrowOnError>): RequestResult<V3GetDocumentPacketResponses, V3GetDocumentPacketErrors, ThrowOnError> => (options.client ?? client).get<V3GetDocumentPacketResponses, V3GetDocumentPacketErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/document-packets/{document_packet_id}/',\n ...options\n});\n\n/**\n * Run document packet\n *\n * Run (or re-run) a document packet on the latest version of its\n * workflow.\n *\n * Every call creates a NEW run — re-running after editing the workflow\n * is the intended flow; earlier runs stay readable at\n * `GET /v3/runs/{run_id}/`. The only exception is an `Idempotency-Key`\n * replay, which returns the original run.\n *\n * Unknown ids — including packets belonging to another organization —\n * return 404. An organization without extraction credit gets 402.\n */\nexport const v3RunDocumentPacket = <ThrowOnError extends boolean = false>(options: Options<V3RunDocumentPacketData, ThrowOnError>): RequestResult<V3RunDocumentPacketResponses, V3RunDocumentPacketErrors, ThrowOnError> => (options.client ?? client).post<V3RunDocumentPacketResponses, V3RunDocumentPacketErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/document-packets/{document_packet_id}/run/',\n ...options\n});\n\n/**\n * Parse a document\n *\n * Parse one document with the platform's fast lite parse (atomic).\n *\n * One file per call. The upload runs against your organization's system\n * parse workflow, provisioned automatically on first use. Poll\n * `GET /v3/runs/{run_id}/` until `status` is `processed`; the markdown is\n * at `results.parse.markdown`.\n *\n * Honors `Idempotency-Key`: a retried request with the same key replays\n * the original packet and run.\n */\nexport const v3Parse = <ThrowOnError extends boolean = false>(options: Options<V3ParseData, ThrowOnError>): RequestResult<V3ParseResponses, V3ParseErrors, ThrowOnError> => (options.client ?? client).post<V3ParseResponses, V3ParseErrors, ThrowOnError>({\n ...formDataBodySerializer,\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/parse/',\n ...options,\n headers: {\n 'Content-Type': null,\n ...options.headers\n }\n});\n\n/**\n * Parse a document from a URL\n *\n * Parse one document fetched from a URL with the platform's fast lite\n * parse (atomic).\n *\n * One document per call: an HTTPS `url`, or the `object_id` (plus\n * `filename`) of a file staged via `POST /v3/blobs/slots/`. The upload runs\n * against your organization's system parse workflow, provisioned\n * automatically on first use. Poll `GET /v3/runs/{run_id}/` until `status`\n * is `processed`; the markdown is at `results.parse.markdown`.\n *\n * A URL-fetched file is named by the response's `Content-Disposition`\n * filename when present, else by the last segment of the URL's path.\n *\n * Not idempotent: every call fetches the document, creates a packet and starts\n * a new run. For a retry-safe flow use `POST /v3/workflows/{id}/upload/from-url/`\n * and then `POST /v3/document-packets/{id}/run/` with an `Idempotency-Key`.\n */\nexport const v3ParseFromUrl = <ThrowOnError extends boolean = false>(options: Options<V3ParseFromUrlData, ThrowOnError>): RequestResult<V3ParseFromUrlResponses, V3ParseFromUrlErrors, ThrowOnError> => (options.client ?? client).post<V3ParseFromUrlResponses, V3ParseFromUrlErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/parse/from-url/',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Get run\n *\n * Retrieve one run flat: lifecycle status plus results inline.\n *\n * Always 200 while the run exists — no precondition errors while the\n * extraction is in flight. `results` is `null` until `status` reaches\n * `processed`, then carries the extraction results envelope (the same\n * shape as the v2 results endpoint). A run that ended in `error` or\n * `cancelled` stays readable with `results: null`.\n *\n * Unknown ids — including runs belonging to another organization —\n * return 404.\n */\nexport const v3GetRun = <ThrowOnError extends boolean = false>(options: Options<V3GetRunData, ThrowOnError>): RequestResult<V3GetRunResponses, V3GetRunErrors, ThrowOnError> => (options.client ?? client).get<V3GetRunResponses, V3GetRunErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/runs/{run_id}/',\n ...options\n});\n\n/**\n * List workflows\n *\n * List your organization's workflows, newest first.\n *\n * Keyset-paginated: follow `next_cursor` until it is `null`. The sort\n * order is fixed (`-created_at, -id`); there are no totals or page numbers.\n */\nexport const v3ListWorkflows = <ThrowOnError extends boolean = false>(options?: Options<V3ListWorkflowsData, ThrowOnError>): RequestResult<V3ListWorkflowsResponses, V3ListWorkflowsErrors, ThrowOnError> => (options?.client ?? client).get<V3ListWorkflowsResponses, V3ListWorkflowsErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/',\n ...options\n});\n\n/**\n * Create workflow\n *\n * Create a workflow from a strongly-typed graph (atomic).\n *\n * Provide an explicit list of typed `nodes` (parse / classify / splitter /\n * extract / validate) and `edges` between them — the same body shape\n * `POST /v2/workflows/` accepts. Returns the stored graph, so the\n * server-assigned `persistent_id`s a later `PATCH` must echo arrive with the\n * create rather than needing a second call.\n */\nexport const v3CreateWorkflow = <ThrowOnError extends boolean = false>(options: Options<V3CreateWorkflowData, ThrowOnError>): RequestResult<V3CreateWorkflowResponses, V3CreateWorkflowErrors, ThrowOnError> => (options.client ?? client).post<V3CreateWorkflowResponses, V3CreateWorkflowErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Delete workflow\n *\n * Delete a workflow and all associated document packets and runs.\n *\n * This action is irreversible.\n */\nexport const v3DeleteWorkflow = <ThrowOnError extends boolean = false>(options: Options<V3DeleteWorkflowData, ThrowOnError>): RequestResult<V3DeleteWorkflowResponses, V3DeleteWorkflowErrors, ThrowOnError> => (options.client ?? client).delete<V3DeleteWorkflowResponses, V3DeleteWorkflowErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/',\n ...options\n});\n\n/**\n * Get workflow\n *\n * Retrieve a workflow with its complete typed graph inline.\n *\n * `{name, description, nodes, edges}` is the exact shape\n * `POST /v3/workflows/` accepts — mutate it and feed it back to\n * `PATCH /v3/workflows/{workflow_id}/` to edit.\n *\n * Pass `version` to read one version for comparison or audit; any other\n * query parameter is rejected, so a misspelled `version` cannot silently\n * read the latest. Versions are read-only: runs always use the latest\n * version, and a PATCH always builds on the latest version.\n */\nexport const v3GetWorkflow = <ThrowOnError extends boolean = false>(options: Options<V3GetWorkflowData, ThrowOnError>): RequestResult<V3GetWorkflowResponses, V3GetWorkflowErrors, ThrowOnError> => (options.client ?? client).get<V3GetWorkflowResponses, V3GetWorkflowErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/',\n ...options\n});\n\n/**\n * Update workflow\n *\n * Replace a workflow's typed graph (atomic).\n *\n * The body is the `{name, description, nodes, edges}` sub-shape of\n * `GET /v3/workflows/{workflow_id}/` — GET, mutate, PATCH. Echo each\n * existing field's `persistent_id` unchanged (including across\n * renames) to keep the field's identity, so analytics, ground truth\n * and quality metrics stay attached; omit `persistent_id` only for\n * genuinely new fields (a pidless field is always treated as new —\n * name coincidence with a prior field does NOT confer identity). An\n * echoed `persistent_id` that doesn't match any field in the current\n * version is a 400. Responds with the updated workflow in the exact\n * `GET /v3/workflows/{workflow_id}/` shape, so the result can be\n * edited and PATCHed again. The returned graph is this request's own\n * write result — including the `persistent_id`s assigned to new\n * fields — never the state left by a concurrent update.\n */\nexport const v3UpdateWorkflow = <ThrowOnError extends boolean = false>(options: Options<V3UpdateWorkflowData, ThrowOnError>): RequestResult<V3UpdateWorkflowResponses, V3UpdateWorkflowErrors, ThrowOnError> => (options.client ?? client).patch<V3UpdateWorkflowResponses, V3UpdateWorkflowErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Upload a document (+ ground truth) to a workflow dataset\n *\n * Upload one document (1..N files) plus optional ground truth as ONE\n * document packet in the dataset (atomic).\n *\n * All-or-nothing: any rejected file (unsupported type, disguised bytes) or a\n * ground-truth failure fails the whole request and nothing is stored.\n *\n * Filenames are unique within a workflow. By default (`on_conflict=error`) a\n * file whose name collides with an existing file fails the request with `409`\n * before anything is uploaded; pass `on_conflict=rename` to auto-rename the\n * collision instead (`invoice.pdf` -> `invoice (1).pdf`), each returned file's\n * ``name`` being the name it landed under and ``original_name`` holding the\n * uploaded name when a rename happened.\n *\n * Bulk ingestion loops this endpoint, one call per document; each call is\n * bounded and independently retryable.\n */\nexport const v3UploadToDataset = <ThrowOnError extends boolean = false>(options: Options<V3UploadToDatasetData, ThrowOnError>): RequestResult<V3UploadToDatasetResponses, V3UploadToDatasetErrors, ThrowOnError> => (options.client ?? client).post<V3UploadToDatasetResponses, V3UploadToDatasetErrors, ThrowOnError>({\n ...formDataBodySerializer,\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/dataset/upload/',\n ...options,\n headers: {\n 'Content-Type': null,\n ...options.headers\n }\n});\n\n/**\n * List workflow document packets\n *\n * List a workflow's document packets, newest first.\n *\n * Keyset-paginated: follow `next_cursor` until it is `null`. The sort\n * order is fixed (`-created_at, -id`); there are no totals or page\n * numbers. Items are slim — fetch\n * `GET /v3/document-packets/{document_packet_id}/` for the per-file\n * breakdown and `latest_run_id`.\n */\nexport const v3ListWorkflowDocumentPackets = <ThrowOnError extends boolean = false>(options: Options<V3ListWorkflowDocumentPacketsData, ThrowOnError>): RequestResult<V3ListWorkflowDocumentPacketsResponses, V3ListWorkflowDocumentPacketsErrors, ThrowOnError> => (options.client ?? client).get<V3ListWorkflowDocumentPacketsResponses, V3ListWorkflowDocumentPacketsErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/document-packets/',\n ...options\n});\n\n/**\n * List a workflow's reference documents\n *\n * List the reference documents on a workflow, with their parse status.\n *\n * Poll this after uploading a PDF reference until its `status` leaves\n * `pending`.\n */\nexport const v3ListEditReferences = <ThrowOnError extends boolean = false>(options: Options<V3ListEditReferencesData, ThrowOnError>): RequestResult<V3ListEditReferencesResponses, V3ListEditReferencesErrors, ThrowOnError> => (options.client ?? client).get<V3ListEditReferencesResponses, V3ListEditReferencesErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/edit-references/',\n ...options\n});\n\n/**\n * Upload reference documents to a workflow\n *\n * Upload the standing data an Edit node fills forms from.\n *\n * Returns one document per file, each with the `id` to put in an Edit node's\n * `reference_document_ids`.\n *\n * A text reference is usable immediately (`status: ready`). A PDF is parsed\n * once, here — never on a run — so it comes back `pending` and reaches\n * `ready` shortly after; poll `GET /v3/workflows/{workflow_id}/edit-references/`\n * until it settles. Starting a run whose Edit node names a reference that is\n * not yet `ready` is refused rather than filled from a partial reference.\n *\n * Upload once, reuse forever: every later run reads the already-parsed text,\n * so the parse is neither repeated nor re-billed.\n */\nexport const v3UploadEditReferences = <ThrowOnError extends boolean = false>(options: Options<V3UploadEditReferencesData, ThrowOnError>): RequestResult<V3UploadEditReferencesResponses, V3UploadEditReferencesErrors, ThrowOnError> => (options.client ?? client).post<V3UploadEditReferencesResponses, V3UploadEditReferencesErrors, ThrowOnError>({\n ...formDataBodySerializer,\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/edit-references/',\n ...options,\n headers: {\n 'Content-Type': null,\n ...options.headers\n }\n});\n\n/**\n * Delete a reference document\n *\n * Delete a reference document and its stored objects.\n *\n * An Edit node still naming the deleted id will refuse to run rather than\n * fill from a reference that no longer exists — remove the id from the node\n * in the same change.\n */\nexport const v3DeleteEditReference = <ThrowOnError extends boolean = false>(options: Options<V3DeleteEditReferenceData, ThrowOnError>): RequestResult<V3DeleteEditReferenceResponses, V3DeleteEditReferenceErrors, ThrowOnError> => (options.client ?? client).delete<V3DeleteEditReferenceResponses, V3DeleteEditReferenceErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/edit-references/{document_id}/',\n ...options\n});\n\n/**\n * List evals\n *\n * List a workflow's evals, newest first.\n *\n * Keyset-paginated: follow `next_cursor` until it is `null`. The sort order is\n * fixed (`-created_at, -id`); there are no totals or page numbers. Each item is\n * the same headline `GET /v3/workflows/{workflow_id}/evals/{eval_id}/` returns.\n *\n * An unknown or cross-org workflow returns 404.\n */\nexport const v3ListEvals = <ThrowOnError extends boolean = false>(options: Options<V3ListEvalsData, ThrowOnError>): RequestResult<V3ListEvalsResponses, V3ListEvalsErrors, ThrowOnError> => (options.client ?? client).get<V3ListEvalsResponses, V3ListEvalsErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/evals/',\n ...options\n});\n\n/**\n * Launch an eval\n *\n * Launch an eval over a workflow's whole dataset (async, fire-and-forget).\n *\n * Enqueues one fresh extraction per dataset document on the target version and\n * pins the realized cohort into a new eval, then returns `202` immediately with\n * `eval_id` and `run_number` to poll. Grading finalizes on a worker path — read\n * the eval by `eval_id` for the headline once it leaves `in_progress`.\n *\n * Without an `Idempotency-Key` every launch creates a NEW eval — re-launching\n * runs a fresh cohort. Supplying the header replays: a retry with the same key\n * returns the original eval instead of launching a second run. Omit `version_id`\n * to evaluate the workflow's current version; pass one to override. (With an\n * omitted version, a replayed key sent after a new version was published targets\n * a different version than the first call, so the backend answers `422` for the\n * key reuse — pass an explicit `version_id` for a stable replay.)\n *\n * A run that enqueues zero documents (empty dataset, or every document failed\n * to enqueue) creates no eval and returns `422 EMPTY_EVAL`.\n */\nexport const v3LaunchEval = <ThrowOnError extends boolean = false>(options: Options<V3LaunchEvalData, ThrowOnError>): RequestResult<V3LaunchEvalResponses, V3LaunchEvalErrors, ThrowOnError> => (options.client ?? client).post<V3LaunchEvalResponses, V3LaunchEvalErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/evals/',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Get eval\n *\n * Retrieve one eval's frozen headline — poll this until `status` leaves\n * `in_progress`.\n *\n * `accuracy`, `matched`, `mismatched` and `ungraded` are `null` while the eval\n * is `in_progress`; `accuracy` also stays `null` on a `processed` eval with a 0\n * graded denominator. `id` here equals the launch's `eval_id`.\n *\n * An unknown eval, or one on another workflow or organization, returns 404\n * (existence never leaks).\n */\nexport const v3GetEval = <ThrowOnError extends boolean = false>(options: Options<V3GetEvalData, ThrowOnError>): RequestResult<V3GetEvalResponses, V3GetEvalErrors, ThrowOnError> => (options.client ?? client).get<V3GetEvalResponses, V3GetEvalErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/evals/{eval_id}/',\n ...options\n});\n\n/**\n * Ask a question about a workflow's documents\n *\n * Answer a question from the content of this workflow's documents.\n *\n * The answer is grounded: every claim comes back with the exact quote it\n * rests on, resolved to a page and a region in the source PDF, so you can\n * show a customer where a number came from instead of asking them to trust\n * it. `path` reports the route the agent took to get there.\n *\n * The workflow needs a knowledge node — that is what indexes its documents.\n * Without one this returns 409.\n *\n * Billed per question against the organization's credits, on the text the\n * agent actually reads. A question the organization cannot pay for is\n * refused before it runs, not after.\n *\n * Pass a `thread_id` you mint yourself (starting with `kb-`) to ask a\n * follow-up in context; omit it and each question stands alone.\n */\nexport const v3AskKnowledge = <ThrowOnError extends boolean = false>(options: Options<V3AskKnowledgeData, ThrowOnError>): RequestResult<V3AskKnowledgeResponses, V3AskKnowledgeErrors, ThrowOnError> => (options.client ?? client).post<V3AskKnowledgeResponses, V3AskKnowledgeErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/knowledge/ask',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * List a workflow's knowledge corpus\n *\n * List a workflow's knowledge corpus tree: source documents plus the\n * generated navigation pages, sorted by path. Needs a knowledge node\n * (409 otherwise); see `folder`/`cursor` and knowledge/list.mdx for the\n * rest.\n */\nexport const v3ListKnowledge = <ThrowOnError extends boolean = false>(options: Options<V3ListKnowledgeData, ThrowOnError>): RequestResult<V3ListKnowledgeResponses, V3ListKnowledgeErrors, ThrowOnError> => (options.client ?? client).get<V3ListKnowledgeResponses, V3ListKnowledgeErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/knowledge/entries',\n ...options\n});\n\n/**\n * Read one document from a workflow's knowledge corpus\n *\n * Read one document's or navigation page's text from a workflow's\n * knowledge corpus.\n *\n * The workflow needs a knowledge node — that is what indexes its\n * documents. Without one this returns 409. An unknown `path` is a 404 —\n * list entries with `list_knowledge` or find one with `search_knowledge`\n * first.\n *\n * `content` is capped; `truncated` is `true` when it was cut off.\n */\nexport const v3ReadKnowledge = <ThrowOnError extends boolean = false>(options: Options<V3ReadKnowledgeData, ThrowOnError>): RequestResult<V3ReadKnowledgeResponses, V3ReadKnowledgeErrors, ThrowOnError> => (options.client ?? client).get<V3ReadKnowledgeResponses, V3ReadKnowledgeErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/knowledge/entry',\n ...options\n});\n\n/**\n * Search a workflow's knowledge corpus\n *\n * Rank a workflow's knowledge corpus by relevance (BM25) to `query`.\n * Needs a knowledge node (409 otherwise); see `query`/`folder`/`limit`\n * and knowledge/search.mdx for the rest.\n */\nexport const v3SearchKnowledge = <ThrowOnError extends boolean = false>(options: Options<V3SearchKnowledgeData, ThrowOnError>): RequestResult<V3SearchKnowledgeResponses, V3SearchKnowledgeErrors, ThrowOnError> => (options.client ?? client).get<V3SearchKnowledgeResponses, V3SearchKnowledgeErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/knowledge/search',\n ...options\n});\n\n/**\n * Get a presigned URL for a workflow's whole knowledge corpus\n *\n * Get a presigned URL for the whole knowledge corpus tar.\n *\n * Possession of the URL is read permission for the workflow's corpus\n * until it expires — prefer `list_knowledge`/`read_knowledge` for\n * anything that stays inside this API; this is for handing the whole\n * archive to something outside it.\n */\nexport const v3DownloadKnowledge = <ThrowOnError extends boolean = false>(options: Options<V3DownloadKnowledgeData, ThrowOnError>): RequestResult<V3DownloadKnowledgeResponses, V3DownloadKnowledgeErrors, ThrowOnError> => (options.client ?? client).get<V3DownloadKnowledgeResponses, V3DownloadKnowledgeErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/knowledge/snapshot',\n ...options\n});\n\n/**\n * List workflow runs\n *\n * List a workflow's runs, newest first.\n *\n * Keyset-paginated: follow `next_cursor` until it is `null`. The sort\n * order is fixed (`-created_at, -id`); there are no totals or page\n * numbers. Items are slim — fetch `GET /v3/runs/{run_id}/` for the\n * results.\n *\n * Optional half-open interval on the packet's `created_at`:\n * `document_packet_created_after` (inclusive) /\n * `document_packet_created_before` (exclusive). Typical daily-batch\n * workflow: upload day N, fetch day N+1 with\n * `after=<N>T00:00:00 & before=<N+1>T00:00:00`.\n */\nexport const v3ListWorkflowRuns = <ThrowOnError extends boolean = false>(options: Options<V3ListWorkflowRunsData, ThrowOnError>): RequestResult<V3ListWorkflowRunsResponses, V3ListWorkflowRunsErrors, ThrowOnError> => (options.client ?? client).get<V3ListWorkflowRunsResponses, V3ListWorkflowRunsErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/runs/',\n ...options\n});\n\n/**\n * Upload document packet to workflow\n *\n * Upload one or more files as a single document packet (atomic).\n *\n * All files are grouped into ONE packet — the unit later runs address.\n * Creation is all-or-nothing: any rejected file (unsupported type,\n * disguised bytes) fails the whole request and nothing is stored.\n *\n * Filenames are unique within a workflow. By default (`on_conflict=error`) a\n * file whose name collides with an existing file fails the request with\n * ``409`` before anything is uploaded; pass `on_conflict=rename` to auto-rename\n * the collision instead (`contract.pdf` -> `contract (1).pdf`); each returned\n * file's ``name`` is then the name it landed under, with ``original_name``\n * holding the uploaded name when a rename happened.\n *\n * Upload without running; trigger extraction via\n * `POST /v3/document-packets/{document_packet_id}/run/`.\n */\nexport const v3UploadToWorkflow = <ThrowOnError extends boolean = false>(options: Options<V3UploadToWorkflowData, ThrowOnError>): RequestResult<V3UploadToWorkflowResponses, V3UploadToWorkflowErrors, ThrowOnError> => (options.client ?? client).post<V3UploadToWorkflowResponses, V3UploadToWorkflowErrors, ThrowOnError>({\n ...formDataBodySerializer,\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/upload/',\n ...options,\n headers: {\n 'Content-Type': null,\n ...options.headers\n }\n});\n\n/**\n * Create document packet from URLs\n *\n * Import every URL into a single document packet, atomically.\n *\n * The backend fetches each HTTPS URL server-side (10s timeout, 20 MB cap\n * per file) and registers the packet in one transaction only after every\n * fetch succeeded — any failure imports nothing (no partial packet, no\n * orphan files).\n *\n * Files arrive as fetchable `urls`, as `staged_files` ids from\n * `POST /v3/blobs/slots/`, or a mix (1..10 in total); staged files land\n * after the `urls` entries.\n *\n * Each URL-fetched file is named by its response's `Content-Disposition`\n * filename when present, else by the last segment of the URL's path. A\n * presigned URL can sign the header in (S3: `ResponseContentDisposition`),\n * which is how a caller names a file whose URL path is opaque. A staged file\n * is named by its `filename`.\n *\n * Filenames are unique within a workflow. By default (`on_conflict=error`)\n * a colliding filename fails the request with ``409`` — surfaced once\n * the atomic import settles, not before it starts; pass `on_conflict=rename`\n * to auto-rename instead (``report.pdf`` -> ``report (1).pdf``). Each returned\n * `name` is the name the file actually landed under; ``original_name`` holds\n * the name it was fetched under when a rename happened.\n */\nexport const v3UploadFromUrl = <ThrowOnError extends boolean = false>(options: Options<V3UploadFromUrlData, ThrowOnError>): RequestResult<V3UploadFromUrlResponses, V3UploadFromUrlErrors, ThrowOnError> => (options.client ?? client).post<V3UploadFromUrlResponses, V3UploadFromUrlErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/upload/from-url/',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Upload and run workflow\n *\n * Upload one document packet and run it in a single call.\n *\n * Composes `POST /v3/workflows/{workflow_id}/upload/` and\n * `POST /v3/document-packets/{document_packet_id}/run/`: the files are\n * grouped into ONE packet (all-or-nothing) and an extraction is enqueued\n * on the workflow's latest version. Poll `GET /v3/runs/{run_id}/` until\n * `status` is terminal.\n *\n * Filenames are unique within a workflow. By default (`on_conflict=error`) a\n * colliding filename fails the request with ``409`` before anything is\n * uploaded or run; pass `on_conflict=rename` to auto-rename instead.\n */\nexport const v3UploadAndRunWorkflow = <ThrowOnError extends boolean = false>(options: Options<V3UploadAndRunWorkflowData, ThrowOnError>): RequestResult<V3UploadAndRunWorkflowResponses, V3UploadAndRunWorkflowErrors, ThrowOnError> => (options.client ?? client).post<V3UploadAndRunWorkflowResponses, V3UploadAndRunWorkflowErrors, ThrowOnError>({\n ...formDataBodySerializer,\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/upload/run/',\n ...options,\n headers: {\n 'Content-Type': null,\n ...options.headers\n }\n});\n\n/**\n * List workflow versions\n *\n * List a workflow's versions, newest first.\n *\n * Versions are read-only: they exist for comparison and audit, and runs\n * always use the latest version (item 0 of the first page). Read a\n * version's graph with `GET /v3/workflows/{workflow_id}/?version=`.\n *\n * Keyset-paginated: follow `next_cursor` until it is `null`. The sort\n * order is fixed (`-created_at, -id`); there are no totals or page numbers.\n */\nexport const v3ListWorkflowVersions = <ThrowOnError extends boolean = false>(options: Options<V3ListWorkflowVersionsData, ThrowOnError>): RequestResult<V3ListWorkflowVersionsResponses, V3ListWorkflowVersionsErrors, ThrowOnError> => (options.client ?? client).get<V3ListWorkflowVersionsResponses, V3ListWorkflowVersionsErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/versions/',\n ...options\n});\n","import { Result } from \"./result\";\nimport {\n AnyformatError,\n ExtractionCancelledError,\n ExtractionFailedError,\n parseRetryAfter,\n SDKTimeoutError,\n toApiError,\n} from \"./errors\";\nimport { v3GetRun } from \"./sdk\";\nimport type { RunStatus } from \"./sdk\";\nimport type { Client as HeyClient } from \"./sdk/client\";\n\nexport interface WaitOptions {\n /** Overall budget before giving up. Default 300 000 ms (300s). */\n timeoutMs?: number;\n /** Delay between status polls. Default 3 000 ms (3s). */\n pollMs?: number;\n}\n\n/** A 429/5xx during polling is transient — a short spike must not abort a long wait(). */\nfunction isTransientStatus(status: number): boolean {\n return status === 429 || status >= 500;\n}\n\nconst RETRY_BASE_MS = 1_000;\nconst RETRY_MAX_MS = 30_000;\n\n/**\n * Backoff before re-polling after a transient failure: honour `Retry-After`\n * (delay-seconds or HTTP-date, RFC 7231 §7.1.3), else jittered exponential.\n */\nfunction retryDelayMs(response: Response | undefined, attempt: number): number {\n const retryAfter = parseRetryAfter(response?.headers?.get(\"Retry-After\"));\n if (retryAfter !== undefined) return Math.min(retryAfter * 1_000, RETRY_MAX_MS);\n const base = Math.min(RETRY_BASE_MS * 2 ** attempt, RETRY_MAX_MS);\n return base * (0.75 + Math.random() * 0.5); // ±25 % jitter so retry waves don't re-collide\n}\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * One execution attempt of a workflow against a document packet. Created\n * eagerly by the run triggers — the extraction is already enqueued by the\n * time you hold a `Run`. `wait()` polls `GET /v3/runs/{run_id}/` until the\n * status is terminal and returns the inline results.\n */\nexport class Run {\n /** Status at trigger time, refreshed on every `wait()` poll. */\n status: RunStatus;\n\n /** @internal */\n constructor(\n private readonly client: HeyClient,\n readonly id: string,\n readonly workflowId: string,\n readonly documentPacketId: string,\n status: RunStatus = \"queued\",\n ) {\n this.status = status;\n }\n\n async wait(opts: WaitOptions = {}): Promise<Result> {\n const timeoutMs = opts.timeoutMs ?? 300_000;\n const pollMs = opts.pollMs ?? 3_000;\n const deadline = Date.now() + timeoutMs;\n let transientFailures = 0;\n\n for (;;) {\n const res = await v3GetRun({ client: this.client, path: { run_id: this.id } });\n if (res.error) {\n const status = res.response?.status ?? 500;\n if (!isTransientStatus(status)) throw toApiError(status, res.error, res.response?.headers);\n const remainingMs = deadline - Date.now();\n if (remainingMs <= 0) {\n throw new SDKTimeoutError(`Extraction did not complete within ${timeoutMs}ms`);\n }\n // Cap so a long ``Retry-After`` on a near-deadline poll can't sleep\n // past the caller's timeout before raising.\n await sleep(Math.min(retryDelayMs(res.response, transientFailures), remainingMs));\n transientFailures += 1;\n continue;\n }\n transientFailures = 0;\n const detail = res.data!;\n this.status = detail.status;\n\n if (detail.status === \"processed\") {\n if (!detail.results) {\n throw new AnyformatError(`Run ${this.id} is processed but the API returned no results`);\n }\n return new Result(detail.results);\n }\n if (detail.status === \"error\") throw new ExtractionFailedError(this.id);\n if (detail.status === \"cancelled\") throw new ExtractionCancelledError(this.id);\n if (Date.now() >= deadline) {\n throw new SDKTimeoutError(`Extraction did not complete within ${timeoutMs}ms`);\n }\n await sleep(pollMs);\n }\n }\n}\n","import { Run } from \"./run\";\nimport { toApiError } from \"./errors\";\nimport { v3RunDocumentPacket } from \"./sdk\";\nimport type { DatasetUploadFileV3, DocumentPacketFileV3 } from \"./sdk\";\nimport type { Client as HeyClient } from \"./sdk/client\";\n\nexport interface RunTriggerOptions {\n /**\n * Caller-supplied key (Stripe convention). Retrying with the same key\n * returns the original run instead of triggering (and billing) a second\n * extraction.\n */\n idempotencyKey?: string;\n}\n\n/**\n * Options for the methods that stage an upload (`Workflow.run`,\n * `Workflow.upload`). Adds the filename-conflict policy on top of the\n * run-trigger options — it only applies where files are actually uploaded,\n * which is why the run-only paths (`Upload.run`, `Anyformat.runDocumentPacket`)\n * take {@link RunTriggerOptions} instead and don't accept it.\n */\nexport interface UploadOptions extends RunTriggerOptions {\n /**\n * How the server resolves an uploaded filename that already exists in the\n * workflow (filenames are unique within a workflow). `\"error\"` (the server\n * default) rejects the whole upload with `409`; `\"rename\"` auto-renames\n * (`invoice.pdf` → `invoice (1).pdf`). Omit to use the server default.\n */\n onConflict?: \"error\" | \"rename\";\n}\n\n/**\n * Options for URL imports. The server derives the filename from each URL, so\n * there is no idempotency key — only the conflict policy applies.\n */\nexport interface UploadFromUrlsOptions {\n /** See {@link UploadOptions.onConflict}. Omit to use the server default. */\n onConflict?: \"error\" | \"rename\";\n}\n\n/**\n * Options for a dataset upload (`Workflow.uploadToDataset`), mirroring the\n * regular upload's conflict policy.\n */\nexport interface DatasetUploadOptions {\n /**\n * The expected document (ground truth) for this document packet, as a plain\n * object — the SDK JSON-encodes it for the multipart field. Keys are the\n * workflow schema's field identifiers (advertise `persistent_id`); a scalar\n * field maps to `string | null`, a table/object field to an array of row\n * objects. Ground truth attaches to the workflow's current version.\n */\n groundTruth?: Record<string, unknown> | null;\n /**\n * Caller-supplied key (Stripe convention). Retrying with the same key\n * replays the original document packet instead of registering a duplicate\n * document.\n */\n idempotencyKey?: string;\n /**\n * Filename-collision policy. Omit to use the server default (`error`): a\n * colliding name fails with `409`. `rename` auto-renames the collision and\n * the returned file's `original_name` holds the name you sent.\n */\n onConflict?: \"error\" | \"rename\";\n}\n\n/**\n * One document for a bulk dataset upload: 1..100 files plus optional\n * ground truth. Mirrors the arguments of `Workflow.uploadToDataset`.\n */\nexport interface DatasetDocument {\n /** 1..10 named files forming ONE document (one document packet in the dataset). */\n files: File | File[];\n /** See {@link DatasetUploadOptions.groundTruth}. */\n groundTruth?: Record<string, unknown> | null;\n /** See {@link DatasetUploadOptions.idempotencyKey}. */\n idempotencyKey?: string;\n /** See {@link DatasetUploadOptions.onConflict}. */\n onConflict?: \"error\" | \"rename\";\n}\n\n/**\n * One document registered into a workflow's dataset as one\n * document packet. Returned by `Workflow.uploadToDataset()`. `documentPacketId` is the\n * stable handle for the document; `groundTruthSaved` is `true` only when\n * ground truth was supplied and stored.\n */\nexport class DatasetUpload {\n /** @internal */\n constructor(\n readonly workflowId: string,\n readonly documentPacketId: string,\n readonly files: DatasetUploadFileV3[],\n readonly groundTruthSaved: boolean,\n ) {}\n}\n\n/**\n * A document packet staged in a workflow but not yet run. Returned by\n * `Workflow.upload()` / `Workflow.uploadFromUrls()`. Call `run()` to start\n * extraction — uploading alone spends no credits.\n */\nexport class Upload {\n /** @internal */\n constructor(\n private readonly client: HeyClient,\n readonly workflowId: string,\n readonly documentPacketId: string,\n readonly files: DocumentPacketFileV3[],\n ) {}\n\n /** Trigger extraction on the staged packet and return a pending `Run`. */\n async run(opts: RunTriggerOptions = {}): Promise<Run> {\n const res = await v3RunDocumentPacket({\n client: this.client,\n path: { document_packet_id: this.documentPacketId },\n ...(opts.idempotencyKey ? { headers: { \"Idempotency-Key\": opts.idempotencyKey } } : {}),\n });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n const data = res.data!;\n return new Run(this.client, data.run_id, data.workflow_id, data.document_packet_id, data.status);\n }\n}\n","import { Run } from \"./run\";\nimport { DatasetUpload, Upload } from \"./upload\";\nimport type { DatasetDocument, DatasetUploadOptions, UploadFromUrlsOptions, UploadOptions } from \"./upload\";\nimport { toApiError, WorkflowBuilderError } from \"./errors\";\nimport { v3UploadAndRunWorkflow, v3UploadFromUrl, v3UploadToDataset, v3UploadToWorkflow } from \"./sdk\";\nimport type { Client as HeyClient } from \"./sdk/client\";\n\nconst MAX_FILES_PER_PACKET = 100;\n\n/** Enforce the named-file requirement shared by run/upload, per file. */\nfunction normalizeFiles(files: File | File[] | null | undefined, op: string): File[] {\n const list = files == null ? [] : Array.isArray(files) ? files : [files];\n if (list.length === 0) {\n throw new WorkflowBuilderError(`${op}() requires at least one named file`);\n }\n if (list.length > MAX_FILES_PER_PACKET) {\n throw new WorkflowBuilderError(`${op}() accepts at most ${MAX_FILES_PER_PACKET} files per document packet`);\n }\n for (const file of list) {\n // A nameless file uploads as application/octet-stream, so the worker can't\n // detect its type. Duck-typed on `.name` since `File` isn't a Node 18 global.\n const filename = (file as { name?: unknown }).name;\n if (typeof filename !== \"string\" || filename.length === 0) {\n throw new WorkflowBuilderError(\n `${op}() needs a named file so the server can detect its type — pass a File, e.g. new File([bytes], \"invoice.pdf\"), not a bare Blob`,\n );\n }\n }\n return list;\n}\n\n/**\n * A persisted workflow on the server. Returned by `WorkflowBuilder.create()`.\n * `run(files)` uploads a document packet and starts extraction, returning a\n * `Run` you can `.wait()` on. `upload(files)` stages a packet without\n * running it; call `.run()` on the returned `Upload` to extract.\n */\nexport class Workflow {\n /** @internal */\n constructor(\n private readonly client: HeyClient,\n readonly id: string,\n readonly name: string,\n ) {}\n\n /** Upload 1..100 files as one document packet and run it. Returns a pending `Run`. */\n async run(files: File | File[] | null = null, opts: UploadOptions = {}): Promise<Run> {\n const list = normalizeFiles(files, \"run\");\n const submitted = await v3UploadAndRunWorkflow({\n client: this.client,\n path: { workflow_id: this.id },\n body: { files: list, ...(opts.onConflict ? { on_conflict: opts.onConflict } : {}) },\n ...(opts.idempotencyKey ? { headers: { \"Idempotency-Key\": opts.idempotencyKey } } : {}),\n });\n if (submitted.error) throw toApiError(submitted.response?.status ?? 500, submitted.error, submitted.response?.headers);\n const data = submitted.data!;\n return new Run(this.client, data.run_id, data.workflow_id, data.document_packet_id, data.status);\n }\n\n /**\n * Stage 1..100 files as one document packet WITHOUT running it (no credits\n * spent). Returns an `Upload`; call `.run()` on it to start extraction.\n */\n async upload(files: File | File[] | null = null, opts: UploadOptions = {}): Promise<Upload> {\n const list = normalizeFiles(files, \"upload\");\n const staged = await v3UploadToWorkflow({\n client: this.client,\n path: { workflow_id: this.id },\n body: { files: list, ...(opts.onConflict ? { on_conflict: opts.onConflict } : {}) },\n ...(opts.idempotencyKey ? { headers: { \"Idempotency-Key\": opts.idempotencyKey } } : {}),\n });\n if (staged.error) throw toApiError(staged.response?.status ?? 500, staged.error, staged.response?.headers);\n const data = staged.data!;\n return new Upload(this.client, data.workflow_id, data.document_packet_id, data.files);\n }\n\n /**\n * Upload 1..100 files as ONE document (+ optional ground truth) into the\n * workflow's dataset, as one document packet. Atomic: any rejected file or a\n * ground-truth failure fails the call and stores nothing. By default a\n * colliding filename fails with `409`; pass `onConflict: \"rename\"` to\n * auto-rename instead.\n */\n async uploadToDataset(files: File | File[] | null = null, opts: DatasetUploadOptions = {}): Promise<DatasetUpload> {\n const list = normalizeFiles(files, \"uploadToDataset\");\n const registered = await v3UploadToDataset({\n client: this.client,\n path: { workflow_id: this.id },\n body: {\n files: list,\n ...(opts.groundTruth != null ? { ground_truth: JSON.stringify(opts.groundTruth) } : {}),\n ...(opts.onConflict ? { on_conflict: opts.onConflict } : {}),\n },\n ...(opts.idempotencyKey ? { headers: { \"Idempotency-Key\": opts.idempotencyKey } } : {}),\n });\n if (registered.error) throw toApiError(registered.response?.status ?? 500, registered.error, registered.response?.headers);\n const data = registered.data!;\n return new DatasetUpload(this.id, data.document_packet_id, data.files, data.ground_truth_saved);\n }\n\n /**\n * Client-orchestrated bulk dataset upload: one atomic call per document,\n * in order. There is no batch endpoint — each document is bounded and\n * independently retryable. On failure the call rejects; documents already\n * uploaded stay registered.\n */\n async uploadDocumentsToDataset(documents: DatasetDocument[]): Promise<DatasetUpload[]> {\n const uploaded: DatasetUpload[] = [];\n for (const doc of documents) {\n uploaded.push(\n await this.uploadToDataset(doc.files, {\n groundTruth: doc.groundTruth,\n idempotencyKey: doc.idempotencyKey,\n onConflict: doc.onConflict,\n }),\n );\n }\n return uploaded;\n }\n\n /**\n * Import 1..10 HTTPS URLs server-side into one document packet, atomically.\n * Returns an `Upload`; call `.run()` on it to start extraction.\n */\n async uploadFromUrls(urls: string[], opts: UploadFromUrlsOptions = {}): Promise<Upload> {\n const staged = await v3UploadFromUrl({\n client: this.client,\n path: { workflow_id: this.id },\n body: { urls, ...(opts.onConflict ? { on_conflict: opts.onConflict } : {}) },\n });\n if (staged.error) throw toApiError(staged.response?.status ?? 500, staged.error, staged.response?.headers);\n const data = staged.data!;\n return new Upload(this.client, data.workflow_id, data.document_packet_id, data.files);\n }\n}\n","import pkg from \"../package.json\" with { type: \"json\" };\nimport { WorkflowBuilder } from \"./builder\";\nimport { AnyformatError, ExtractionCancelledError, ExtractionFailedError, toApiError } from \"./errors\";\nimport { Run } from \"./run\";\nimport { DatasetUpload, Upload } from \"./upload\";\nimport type { DatasetDocument, DatasetUploadOptions, RunTriggerOptions, UploadOptions } from \"./upload\";\nimport {\n v3DeleteDocumentPacket,\n v3DeleteWorkflow,\n v3GetDocumentPacket,\n v3GetRun,\n v3GetWorkflow,\n v3ListWorkflowDocumentPackets,\n v3ListWorkflowRuns,\n v3ListWorkflows,\n v3Parse,\n v3RunDocumentPacket,\n v3UpdateWorkflow,\n} from \"./sdk\";\nimport type {\n DocumentPacketDetailV3,\n DocumentPacketSummaryV3,\n RunDetailV3,\n RunSummaryV3,\n WorkflowDetailV3,\n} from \"./sdk\";\nimport { createClient, createConfig } from \"./sdk/client\";\nimport type { Client as HeyClient } from \"./sdk/client\";\nimport { Workflow } from \"./workflow\";\n\n// ponytail: bundles full package.json (~1KB); esbuild lacks named JSON tree-shaking.\nexport const SDK_USER_AGENT = `anyformat-typescript-sdk-${pkg.version}`;\n\nexport interface AnyformatOptions {\n apiKey: string;\n /** Override the API base URL (defaults to production). */\n baseUrl?: string;\n}\n\n/** One keyset page. Follow `nextCursor` (pass it as `cursor`) until it is `null`. */\nexport interface Page<T> {\n items: T[];\n nextCursor: string | null;\n}\n\nexport interface ListOptions {\n /** Page size, capped at 100 by the API. */\n limit?: number;\n /** Opaque token from a previous page's `nextCursor`. */\n cursor?: string;\n}\n\nexport interface IterOptions {\n /** Page size the auto-pager fetches per underlying request, capped at 100 by the API. */\n limit?: number;\n}\n\n/**\n * The editable sub-shape of a workflow: exactly what `GET /v3/workflows/{id}/`\n * returns minus the read-only fields, and exactly what PATCH accepts — so a\n * fetched `WorkflowDetailV3` can be mutated and sent back as-is.\n */\nexport type WorkflowDefinition = Pick<WorkflowDetailV3, \"name\" | \"description\" | \"nodes\" | \"edges\">;\n\n/** Entry point. `new Anyformat({ apiKey }).workflow(\"name\").parse()...` */\nexport class Anyformat {\n /** @internal */\n readonly _client: HeyClient;\n\n constructor(opts: AnyformatOptions) {\n this._client = createClient(\n createConfig({\n baseUrl: opts.baseUrl ?? \"https://api.anyformat.ai\",\n auth: opts.apiKey,\n // Identifies the caller in our logs (Datadog facet). Plain HTTP callers\n // send no such header and are logged as origin \"api\". User-Agent is\n // ignored by browsers (forbidden header) but used by Node fetch.\n headers: {\n \"x-anyformat-origin\": \"js-sdk\",\n \"User-Agent\": SDK_USER_AGENT,\n },\n }),\n );\n }\n\n workflow(name: string, description?: string): WorkflowBuilder {\n return new WorkflowBuilder(this._client, name, description);\n }\n\n async listWorkflows(opts: ListOptions = {}): Promise<Page<Workflow>> {\n const res = await v3ListWorkflows({\n client: this._client,\n query: { limit: opts.limit, cursor: opts.cursor },\n });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return {\n items: res.data!.items.map((r) => new Workflow(this._client, r.id, r.name)),\n nextCursor: res.data!.next_cursor ?? null,\n };\n }\n\n /** Retrieve a workflow with its complete typed graph inline (round-trippable into `updateWorkflow`). */\n async getWorkflow(workflowId: string): Promise<WorkflowDetailV3> {\n const res = await v3GetWorkflow({ client: this._client, path: { workflow_id: workflowId } });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return res.data!;\n }\n\n /**\n * Replace a workflow's typed graph (atomic). Accepts the shape `getWorkflow`\n * returns — echo each field's `persistent_id` unchanged (including across\n * renames) to keep the field's identity; omit it for new fields.\n */\n async updateWorkflow(workflowId: string, definition: WorkflowDefinition): Promise<WorkflowDetailV3> {\n const res = await v3UpdateWorkflow({\n client: this._client,\n path: { workflow_id: workflowId },\n // The PATCH body forbids unknown keys, so a fetched detail's read-only\n // fields (id, timestamps) must not be forwarded.\n body: {\n name: definition.name,\n description: definition.description,\n nodes: definition.nodes,\n edges: definition.edges,\n },\n });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return res.data!;\n }\n\n async deleteWorkflow(workflowId: string): Promise<string> {\n const res = await v3DeleteWorkflow({\n client: this._client,\n path: { workflow_id: workflowId },\n });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return workflowId;\n }\n\n /** Stage 1..100 files as one document packet without running it. Returns an `Upload`. */\n upload(workflowId: string, files: File | File[], opts: UploadOptions = {}): Promise<Upload> {\n return new Workflow(this._client, workflowId, \"\").upload(files, opts);\n }\n\n /** Upload 1..100 files (+ optional ground truth) as one dataset collection. Returns a `DatasetUpload`. */\n uploadToDataset(\n workflowId: string,\n files: File | File[],\n opts: DatasetUploadOptions = {},\n ): Promise<DatasetUpload> {\n return new Workflow(this._client, workflowId, \"\").uploadToDataset(files, opts);\n }\n\n /** Bulk-upload documents into a workflow's dataset, one atomic call per document. */\n uploadDocumentsToDataset(workflowId: string, documents: DatasetDocument[]): Promise<DatasetUpload[]> {\n return new Workflow(this._client, workflowId, \"\").uploadDocumentsToDataset(documents);\n }\n\n async getDocumentPacket(documentPacketId: string): Promise<DocumentPacketDetailV3> {\n const res = await v3GetDocumentPacket({\n client: this._client,\n path: { document_packet_id: documentPacketId },\n });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return res.data!;\n }\n\n /** Delete a document packet and all its files. Irreversible. */\n async deleteDocumentPacket(documentPacketId: string): Promise<string> {\n const res = await v3DeleteDocumentPacket({\n client: this._client,\n path: { document_packet_id: documentPacketId },\n });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return documentPacketId;\n }\n\n /** Run (or re-run) a document packet on the latest version of its workflow. */\n async runDocumentPacket(documentPacketId: string, opts: RunTriggerOptions = {}): Promise<Run> {\n const res = await v3RunDocumentPacket({\n client: this._client,\n path: { document_packet_id: documentPacketId },\n ...(opts.idempotencyKey ? { headers: { \"Idempotency-Key\": opts.idempotencyKey } } : {}),\n });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n const data = res.data!;\n return new Run(this._client, data.run_id, data.workflow_id, data.document_packet_id, data.status);\n }\n\n async listDocumentPackets(workflowId: string, opts: ListOptions = {}): Promise<Page<DocumentPacketSummaryV3>> {\n const res = await v3ListWorkflowDocumentPackets({\n client: this._client,\n path: { workflow_id: workflowId },\n query: { limit: opts.limit, cursor: opts.cursor },\n });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return { items: res.data!.items, nextCursor: res.data!.next_cursor ?? null };\n }\n\n async listRuns(workflowId: string, opts: ListOptions = {}): Promise<Page<RunSummaryV3>> {\n const res = await v3ListWorkflowRuns({\n client: this._client,\n path: { workflow_id: workflowId },\n query: { limit: opts.limit, cursor: opts.cursor },\n });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return { items: res.data!.items, nextCursor: res.data!.next_cursor ?? null };\n }\n\n /**\n * Every workflow, following `nextCursor` across pages so no rows are silently\n * truncated. Lazy — each page is fetched on demand as the iterator advances.\n */\n async *iterWorkflows(opts: IterOptions = {}): AsyncIterableIterator<Workflow> {\n let cursor: string | undefined;\n for (;;) {\n const page = await this.listWorkflows({ limit: opts.limit, cursor });\n yield* page.items;\n if (page.nextCursor === null) return;\n cursor = page.nextCursor;\n }\n }\n\n /** Every document packet of a workflow, following `nextCursor` across pages. Lazy. */\n async *iterDocumentPackets(\n workflowId: string,\n opts: IterOptions = {},\n ): AsyncIterableIterator<DocumentPacketSummaryV3> {\n let cursor: string | undefined;\n for (;;) {\n const page = await this.listDocumentPackets(workflowId, { limit: opts.limit, cursor });\n yield* page.items;\n if (page.nextCursor === null) return;\n cursor = page.nextCursor;\n }\n }\n\n /** Every run of a workflow, following `nextCursor` across pages. Lazy. */\n async *iterRuns(workflowId: string, opts: IterOptions = {}): AsyncIterableIterator<RunSummaryV3> {\n let cursor: string | undefined;\n for (;;) {\n const page = await this.listRuns(workflowId, { limit: opts.limit, cursor });\n yield* page.items;\n if (page.nextCursor === null) return;\n cursor = page.nextCursor;\n }\n }\n\n /** Retrieve one run: lifecycle status plus results inline once `processed`. */\n async getRun(runId: string): Promise<RunDetailV3> {\n const res = await v3GetRun({ client: this._client, path: { run_id: runId } });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return res.data!;\n }\n\n /**\n * Parse a document with the platform's atomic parse operation (fast lite\n * parse). Returns the run id; poll `getParseMarkdown(runId)` for the parsed\n * markdown.\n */\n async parse(file: Blob | File): Promise<string> {\n const res = await v3Parse({ client: this._client, body: { file } });\n if (res.error !== undefined) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return res.data!.run_id;\n }\n\n /**\n * Poll a parse run. Returns the parsed markdown once the run is `processed`,\n * or `null` while it is still queued or in progress.\n */\n async getParseMarkdown(runId: string): Promise<string | null> {\n const run = await this.getRun(runId);\n if (run.status === \"processed\") {\n const markdown = run.results?.parse?.markdown;\n if (markdown == null) throw new AnyformatError(`Run ${runId} is processed but the API returned no results`);\n return markdown;\n }\n if (run.status === \"error\") throw new ExtractionFailedError(runId);\n if (run.status === \"cancelled\") throw new ExtractionCancelledError(runId);\n return null;\n }\n}\n","import type {\n BooleanField,\n DateField,\n DatetimeField,\n EnumField,\n EnumOption,\n ExtractionSchema,\n FloatField,\n IntegerField,\n MultiSelectField,\n ObjectField,\n StringField,\n} from \"./sdk\";\n\n/** Any extraction field — the discriminated union on `data_type`. */\nexport type Field = ExtractionSchema[\"fields\"][number];\n\n/**\n * A field that may appear inside an object. Excludes `object`: only one\n * level of nesting is supported, so objects cannot contain objects.\n */\nexport type NestedField = ObjectField[\"nested_fields\"][number];\n\ninterface FieldOpts {\n /**\n * How the field gets its value: `\"extraction\"` (from the document,\n * the default), `\"smart_lookup\"` (from the lookup file, always\n * overwrites) or `\"lookup_if_missing\"` (extracted too; the lookup only\n * fills it where extraction left no value).\n */\n source?: \"extraction\" | \"smart_lookup\" | \"lookup_if_missing\";\n /**\n * Server-assigned stable field identity from `GET /v3/workflows/{id}/`.\n * Echo it on updates — including across renames — to keep quality\n * metrics, ground truth and analytics attached to the field. Omit for\n * new fields.\n */\n persistentId?: string;\n}\n\nfunction withOpts<T extends object>(base: T, opts?: FieldOpts): T {\n return {\n ...base,\n ...(opts?.source && opts.source !== \"extraction\" ? { source: opts.source } : {}),\n ...(opts?.persistentId !== undefined ? { persistent_id: opts.persistentId } : {}),\n };\n}\n\n/**\n * Factory for extraction-schema fields — the TS mirror of the Python\n * `Schema` facade. Each method returns the typed wire model the API\n * validates against; the discriminator (`data_type`) is filled in for you.\n */\nexport const Schema = {\n string: (name: string, description: string, opts?: FieldOpts): StringField =>\n withOpts({ data_type: \"string\", name, description }, opts),\n integer: (name: string, description: string, opts?: FieldOpts): IntegerField =>\n withOpts({ data_type: \"integer\", name, description }, opts),\n float: (name: string, description: string, opts?: FieldOpts): FloatField =>\n withOpts({ data_type: \"float\", name, description }, opts),\n boolean: (name: string, description: string, opts?: FieldOpts): BooleanField =>\n withOpts({ data_type: \"boolean\", name, description }, opts),\n date: (name: string, description: string, opts?: FieldOpts): DateField =>\n withOpts({ data_type: \"date\", name, description }, opts),\n datetime: (name: string, description: string, opts?: FieldOpts): DatetimeField =>\n withOpts({ data_type: \"datetime\", name, description }, opts),\n enum: (name: string, description: string, options: EnumOption[], opts?: FieldOpts): EnumField =>\n withOpts({ data_type: \"enum\", name, description, enum_options: options }, opts),\n multiSelect: (name: string, description: string, options: EnumOption[], opts?: FieldOpts): MultiSelectField =>\n withOpts({ data_type: \"multi_select\", name, description, enum_options: options }, opts),\n object: (name: string, description: string, fields: NestedField[], opts?: FieldOpts): ObjectField =>\n withOpts({ data_type: \"object\", name, description, nested_fields: fields }, opts),\n option: (name: string, description: string): EnumOption => ({ name, description }),\n};\n"],"mappings":";AAAA;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,aAAe;AAAA,EACf,SAAW;AAAA,EACX,QAAU;AAAA,EACV,MAAQ;AAAA,EACR,MAAQ;AAAA,EACR,QAAU;AAAA,EACV,OAAS;AAAA,EACT,SAAW;AAAA,IACT,KAAK;AAAA,MACH,OAAS;AAAA,MACT,QAAU;AAAA,MACV,SAAW;AAAA,IACb;AAAA,EACF;AAAA,EACA,OAAS;AAAA,IACP;AAAA,EACF;AAAA,EACA,SAAW;AAAA,IACT,MAAQ;AAAA,EACV;AAAA,EACA,SAAW;AAAA,IACT,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,KAAO;AAAA,IACP,aAAa;AAAA,IACb,OAAS;AAAA,IACT,WAAa;AAAA,IACb,MAAQ;AAAA,IACR,gBAAkB;AAAA,EACpB;AAAA,EACA,iBAAmB;AAAA,IACjB,uB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,MAAM,aAAa,cAAc,QAAQ,GAAG,IAAI;AAAA,EAChF,aAAa,CAAC,MAAc,aAAqB,SAAuB,SACtE,SAAS,EAAE,WAAW,gBAAgB,MAAM,aAAa,cAAc,QAAQ,GAAG,IAAI;AAAA,EACxF,QAAQ,CAAC,MAAc,aAAqB,QAAuB,SACjE,SAAS,EAAE,WAAW,UAAU,MAAM,aAAa,eAAe,OAAO,GAAG,IAAI;AAAA,EAClF,QAAQ,CAAC,MAAc,iBAAqC,EAAE,MAAM,YAAY;AAClF;","names":["sleep","joinedValues","config","request","url","client","client","client","client"]}
|
|
1
|
+
{"version":3,"sources":["../package.json","../src/builder.ts","../src/parse-view.ts","../src/result.ts","../src/errors.ts","../src/sdk/core/bodySerializer.gen.ts","../src/sdk/core/params.gen.ts","../src/sdk/core/serverSentEvents.gen.ts","../src/sdk/core/pathSerializer.gen.ts","../src/sdk/core/utils.gen.ts","../src/sdk/core/auth.gen.ts","../src/sdk/client/utils.gen.ts","../src/sdk/client/client.gen.ts","../src/sdk/client.gen.ts","../src/sdk/sdk.gen.ts","../src/run.ts","../src/upload.ts","../src/workflow.ts","../src/client.ts","../src/schema.ts"],"sourcesContent":["{\n \"name\": \"@anyformat/sdk\",\n \"version\": \"1.1.0\",\n \"description\": \"TypeScript SDK for the AnyFormat API\",\n \"license\": \"MIT\",\n \"author\": \"Anyformat <info@anyformat.ai>\",\n \"type\": \"module\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n }\n },\n \"files\": [\n \"dist\"\n ],\n \"engines\": {\n \"node\": \">=18\"\n },\n \"scripts\": {\n \"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\",\n \"gen:client\": \"openapi-ts\",\n \"gen\": \"bun run gen:spec && bun run gen:client\",\n \"gen:check\": \"bun run gen && git diff --exit-code -- openapi src/sdk\",\n \"build\": \"tsup\",\n \"typecheck\": \"tsc --noEmit\",\n \"test\": \"vitest run\",\n \"prepublishOnly\": \"bun run build\"\n },\n \"devDependencies\": {\n \"@hey-api/openapi-ts\": \"^0.99.0\",\n \"@types/node\": \"^25.9.1\",\n \"tsup\": \"^8.3.0\",\n \"typescript\": \"^5.6.0\",\n \"vitest\": \"^4.1.7\"\n }\n}\n","import { readFileSync } from \"node:fs\";\nimport { basename } from \"node:path\";\nimport { Workflow } from \"./workflow\";\nimport { toApiError, WorkflowBuilderError } from \"./errors\";\nimport { v3CreateWorkflow, v3UpdateWorkflow } from \"./sdk\";\nimport type { Client as HeyClient } from \"./sdk/client\";\nimport type {\n ClassifyCategory,\n ClassifyNode,\n Edge,\n LookupFileUpload,\n PublicExtractNode as ExtractNode,\n PublicParseNode as ParseNode,\n PublicValidateNode as ValidateNode,\n SplitterNode,\n SplitterRule,\n ValidationRule,\n WorkflowCreateRequest,\n} from \"./sdk\";\nimport type { Field } from \"./schema\";\n\ntype ParseMode = \"standard\" | \"agentic\" | \"lite\" | \"flash\";\ntype ExtractMode = \"standard\" | \"agentic\" | \"lite\";\ntype AgenticEffort = \"low\" | \"mid\" | \"accurate\";\ntype ScannedPages = \"ocr\" | \"skip\" | \"fail\";\n/** How much reasoning a node asks a model for. Taken from the generated wire types, which\n * follow the Python `ReasoningEffort` alias, so a new level needs no edit here.\n * The Python gives `ExtractNode.lookup_reasoning_effort`\n * that same alias, so one of the two fields derives the type for both. */\ntype ReasoningEffort = NonNullable<ExtractNode[\"lookup_reasoning_effort\"]>;\n\n/** Source-port label routing into an extract/validate node. */\nexport type Branch = string | ClassifyCategory | SplitterRule;\n\n/** Knobs shared by every parse mode. */\ninterface ParseOptionsBase {\n figureEnhancement?: boolean;\n cache?: boolean;\n id?: string;\n}\n\n/**\n * Parse options as a `mode`-discriminated union: each mode only accepts its own knobs, so a lite\n * knob on `{ mode: \"standard\" }` is a compile-time error rather than a silent no-op. `mode` is\n * optional only on the standard variant (the default), required on agentic/lite. Lite has no\n * knobs of its own — one recipe, OCR-only — and never reads `promptHint`.\n */\ntype ParseOptions =\n | (ParseOptionsBase & { mode?: \"standard\"; promptHint?: string })\n | (ParseOptionsBase & { mode: \"agentic\"; effort?: AgenticEffort; promptHint?: string })\n | (ParseOptionsBase & { mode: \"lite\" })\n | (ParseOptionsBase & { mode: \"flash\"; scannedPages?: ScannedPages; promptHint?: string });\n\n/**\n * Fluent assembler for a typed workflow graph — a faithful TS port of the\n * Python `WorkflowBuilder`. `parse`/`classify`/`split` are singletons;\n * `extract`/`validate` are repeatable and carry their edge metadata. Call\n * `build()` (or `create()`) to emit the wire request — submit with\n * `Workflow.run(file)` on the handle that `create()` returns.\n */\nexport class WorkflowBuilder {\n private parseNode: ParseNode | null = null;\n private classifyNode: ClassifyNode | null = null;\n private splitNode: SplitterNode | null = null;\n private splitRouteFrom: string | null = null;\n private readonly extracts: Array<[ExtractNode, string | null]> = [];\n private readonly validates: Array<[ValidateNode, string]> = [];\n private readonly idCounters: Record<string, number> = {};\n\n constructor(\n private readonly client: HeyClient,\n private readonly name: string,\n private readonly description?: string,\n ) {}\n\n private nextId(kind: string): string {\n this.idCounters[kind] = (this.idCounters[kind] ?? 0) + 1;\n return `${kind}_${this.idCounters[kind]}`;\n }\n\n private require(condition: unknown, message: string): void {\n if (!condition) throw new WorkflowBuilderError(message);\n }\n\n parse(opts: ParseOptions = {}): this {\n this.require(this.parseNode === null, \"parse() can only be called once\");\n // Widen to read every optional knob; the union already guaranteed only mode-valid ones are set.\n const o = opts as ParseOptionsBase & {\n mode?: ParseMode;\n promptHint?: string;\n effort?: AgenticEffort;\n scannedPages?: ScannedPages;\n };\n this.parseNode = {\n type: \"parse\",\n id: o.id ?? this.nextId(\"parse\"),\n mode: o.mode ?? \"standard\",\n ...(o.promptHint !== undefined ? { prompt_hint: o.promptHint } : {}),\n figure_enhancement: o.figureEnhancement ?? false,\n cache: o.cache ?? true,\n ...(o.effort !== undefined ? { effort: o.effort } : {}),\n ...(o.scannedPages !== undefined\n ? { scanned_pages: o.scannedPages }\n : {}),\n };\n return this;\n }\n\n classify(categories: ClassifyCategory[], opts: { id?: string } = {}): this {\n this.require(this.parseNode !== null, \"classify() requires parse() first\");\n this.require(this.classifyNode === null, \"classify() can only be called once\");\n this.require(categories.length > 0, \"classify() requires at least one category\");\n this.classifyNode = { type: \"classify\", id: opts.id ?? this.nextId(\"classify\"), categories };\n return this;\n }\n\n split(rules: SplitterRule[], opts: { routeFrom?: string | ClassifyCategory; id?: string } = {}): this {\n this.require(this.parseNode !== null, \"split() requires parse() first\");\n this.require(this.splitNode === null, \"split() can only be called once\");\n this.require(rules.length > 0, \"split() requires at least one rule\");\n this.require(\n !(opts.routeFrom !== undefined && this.classifyNode === null),\n \"routeFrom is only valid after classify()\",\n );\n this.require(\n !(this.classifyNode !== null && opts.routeFrom === undefined),\n \"split(rules, { routeFrom }) is required when chaining after classify() — specify which classify branch routes into the splitter\",\n );\n this.splitRouteFrom = this.normalizeClassifyBranch(opts.routeFrom, \"routeFrom\");\n this.splitNode = { type: \"splitter\", id: opts.id ?? this.nextId(\"split\"), rules };\n return this;\n }\n\n extract(\n fields: Field[],\n opts: {\n branch?: Branch;\n id?: string;\n mode?: ExtractMode;\n lookupFiles?: string[];\n lookupSuggestion?: string;\n lookupReasoningEffort?: ReasoningEffort;\n useImages?: boolean;\n } = {},\n ): this {\n this.require(this.parseNode !== null, \"extract() requires parse() first\");\n this.require(fields.length > 0, \"extract() requires at least one field\");\n const hasRouter = this.classifyNode !== null || this.splitNode !== null;\n this.require(\n !(hasRouter && opts.branch === undefined),\n \"extract(fields, { branch }) is required when classify() or split() is used\",\n );\n this.require(\n !(!hasRouter && opts.branch !== undefined),\n \"extract(fields, { branch }) is only valid after classify() or split()\",\n );\n const branchId = this.normalizeExtractBranch(opts.branch);\n const lookupFileUploads: LookupFileUpload[] = (opts.lookupFiles ?? []).map((filePath) => ({\n filename: basename(filePath),\n content: readFileSync(filePath).toString(\"base64\"),\n }));\n const node: ExtractNode = {\n type: \"extract\",\n id: opts.id ?? this.nextId(\"extract\"),\n ...(opts.mode !== undefined ? { mode: opts.mode } : {}),\n extraction_schema: { fields },\n ...(lookupFileUploads.length > 0 ? { lookup_file_uploads: lookupFileUploads } : {}),\n ...(opts.lookupSuggestion !== undefined ? { lookup_suggestion: opts.lookupSuggestion } : {}),\n ...(opts.lookupReasoningEffort !== undefined\n ? { lookup_reasoning_effort: opts.lookupReasoningEffort }\n : {}),\n ...(opts.useImages !== undefined ? { use_images: opts.useImages } : {}),\n };\n this.extracts.push([node, branchId]);\n return this;\n }\n\n validate(rules: ValidationRule[], opts: { branch?: Branch; id?: string } = {}): this {\n this.require(this.parseNode !== null, \"validate() requires parse() first\");\n this.require(this.extracts.length > 0, \"validate() requires extract() first\");\n this.require(rules.length > 0, \"validate() requires at least one rule\");\n\n let sourceExtractId: string;\n if (opts.branch !== undefined) {\n const branchId = this.normalizeExtractBranch(opts.branch);\n const matching = this.extracts.filter(([, b]) => b === branchId);\n this.require(matching.length > 0, `validate(branch) did not match any extract`);\n sourceExtractId = matching[matching.length - 1]![0].id;\n } else {\n sourceExtractId = this.extracts[this.extracts.length - 1]![0].id;\n }\n const node: ValidateNode = { type: \"validate\", id: opts.id ?? this.nextId(\"validate\"), rules };\n this.validates.push([node, sourceExtractId]);\n return this;\n }\n\n private normalizeClassifyBranch(value: string | ClassifyCategory | undefined, kwarg: string): string | null {\n if (value === undefined) return null;\n const categories = this.classifyNode?.categories ?? [];\n if (typeof value !== \"string\") {\n if (!categories.some((c) => c.id === value.id)) {\n throw new WorkflowBuilderError(`${kwarg}=${value.id} is not one of the registered classify categories`);\n }\n return value.id;\n }\n if (!categories.some((c) => c.id === value)) {\n throw new WorkflowBuilderError(`${kwarg}=${value} does not match any classify category id`);\n }\n return value;\n }\n\n private normalizeExtractBranch(value: Branch | undefined): string | null {\n if (value === undefined) return null;\n const router: Array<{ id: string }> = this.splitNode?.rules ?? this.classifyNode?.categories ?? [];\n if (typeof value !== \"string\") {\n if (!router.some((item) => item.id === value.id)) {\n const expected = this.splitNode ? \"splitter rule\" : \"classify category\";\n throw new WorkflowBuilderError(`branch=${value.id} is not one of the registered ${expected} objects`);\n }\n return value.id;\n }\n if (!router.some((item) => item.id === value)) {\n throw new WorkflowBuilderError(`branch=${value} does not match any router id`);\n }\n return value;\n }\n\n /** Assemble the wire request (branch-routed edges). Pure — no network. */\n build(): WorkflowCreateRequest {\n if (this.parseNode === null) throw new WorkflowBuilderError(\"build() requires parse()\");\n const parseId = this.parseNode.id;\n const nodes: WorkflowCreateRequest[\"nodes\"] = [this.parseNode];\n const edges: Edge[] = [];\n\n if (this.classifyNode !== null) {\n nodes.push(this.classifyNode);\n edges.push({ source: parseId, target: this.classifyNode.id });\n }\n\n if (this.splitNode !== null) {\n nodes.push(this.splitNode);\n if (this.classifyNode !== null) {\n edges.push({ source: this.classifyNode.id, target: this.splitNode.id, branch: this.splitRouteFrom });\n } else {\n edges.push({ source: parseId, target: this.splitNode.id });\n }\n }\n\n const routerId = this.splitNode?.id ?? this.classifyNode?.id ?? null;\n for (const [node, branchId] of this.extracts) {\n nodes.push(node);\n edges.push(\n routerId === null\n ? { source: parseId, target: node.id }\n : { source: routerId, target: node.id, branch: branchId },\n );\n }\n\n for (const [node, sourceExtractId] of this.validates) {\n nodes.push(node);\n edges.push({ source: sourceExtractId, target: node.id });\n }\n\n return { name: this.name, description: this.description, nodes, edges };\n }\n\n /** Persist the workflow and return a handle you can `.run(files)` on. */\n async create(): Promise<Workflow> {\n const res = await v3CreateWorkflow({ client: this.client, body: this.build() });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return new Workflow(this.client, res.data!.id, res.data!.name);\n }\n\n /** Replace an existing workflow's typed graph and return a handle you can `.run(files)` on. */\n async update(workflowId: string): Promise<Workflow> {\n const res = await v3UpdateWorkflow({ client: this.client, path: { workflow_id: workflowId }, body: this.build() });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return new Workflow(this.client, res.data!.id, res.data!.name);\n }\n}\n","import type { Block, ParseResult } from \"./sdk\";\n\n/**\n * Typed view over the parse node's output. Returned by `Result.parse` — readers\n * use it for `.markdown`, `.text`, `.blocks`, `.parseConfidence`, and\n * `.layoutConfidence` without having to walk `result.raw.parse`.\n *\n * No `.draw()` here: rasterising pages requires PDF rendering (pdfium); the\n * Python SDK ships that, the TS SDK does not.\n */\nexport class ParseView {\n /** @internal */\n constructor(private readonly parse: ParseResult) {}\n\n get markdown(): string | null {\n return this.parse.markdown ?? null;\n }\n\n get text(): string | null {\n return this.parse.text ?? null;\n }\n\n get blocks(): Block[] {\n return this.parse.blocks ?? [];\n }\n\n /**\n * Document-level confidence (0-100) in the parsed content. May be `null` for\n * some parse modes — fall back to `layoutConfidence`.\n */\n get parseConfidence(): number | null {\n return this.parse.parse_confidence ?? null;\n }\n\n /**\n * Document-level confidence (0-100) in the page layout (block positions).\n * `null` when not available.\n */\n get layoutConfidence(): number | null {\n return this.parse.layout_confidence ?? null;\n }\n}\n","import { ParseView } from \"./parse-view\";\nimport type { ExtractedField as GenExtractedField, Extraction, ResultsResponseV3 } from \"./sdk\";\n\n/**\n * One extracted field — generic over the value type so callers get real\n * types at the access site (`result.field<number>(\"total\").value` is\n * `number | null`, not `unknown`). Wire shape identical to the codegen type.\n */\nexport type ExtractedField<T = unknown> = Omit<GenExtractedField, \"value\" | \"value_override\"> & {\n value: T | null;\n value_override?: T | null;\n};\n\n/**\n * A list/object-array field (e.g. `line_items`): one entry per row, each row a\n * record of named `ExtractedField`s. This is the shape `field()` returns for a\n * non-scalar field.\n */\nexport type ExtractedRows = Array<Record<string, ExtractedField>>;\n\n/** Typed wrapper over a completed run's results. */\nexport class Result {\n private _parse: ParseView | null | undefined;\n\n constructor(readonly raw: ResultsResponseV3) {}\n\n get documentPacketId(): string {\n return this.raw.document_packet_id;\n }\n\n get extractions(): Extraction[] {\n return this.raw.extractions ?? [];\n }\n\n /**\n * Typed view over the parse node's output, or `null` when the workflow has\n * no parse node. Cached so repeated access doesn't re-wrap.\n */\n get parse(): ParseView | null {\n if (this._parse === undefined) {\n const raw = this.raw.parse;\n this._parse = raw ? new ParseView(raw) : null;\n }\n return this._parse;\n }\n\n /**\n * Convenience accessor for a top-level field on the untagged (linear)\n * extraction. Returns the scalar `ExtractedField` for a scalar field, or\n * the array of row records (`ExtractedRows`) for a list/object field such\n * as `line_items`. `undefined` only when the field is absent.\n *\n * Parameterise with the declared schema type to type a scalar's `.value`:\n * `result.field<number>(\"total\").value` is `number | null`.\n */\n field<T = unknown>(name: string): ExtractedField<T> | ExtractedRows | undefined {\n // Filter to the untagged extraction so a split/mixed payload — where\n // partition extractions can precede the linear one in ``extractions[]`` —\n // still resolves the top-level field. Mirrors the Python SDK's\n // ``parse_results`` untagged filter.\n const untagged = this.extractions.find(\n (e) => e.split_name == null && e.partition == null,\n );\n const value = untagged?.fields?.[name];\n if (value === undefined) return undefined;\n if (Array.isArray(value)) return value as ExtractedRows;\n return value as ExtractedField<T>;\n }\n}\n","export class AnyformatError extends Error {}\n\n/** Any JSON value the envelope's free-shaped `detail` may carry. */\nexport type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\n\n/** One field-level failure; the `detail` convention of validation errors. */\nexport interface ValidationItem {\n type: string;\n loc: (string | number)[];\n msg: string;\n}\n\n/** A `params` value: a scalar, `null`, or an array of those. */\nexport type ScalarOrList = string | number | boolean | null | (string | number | boolean | null)[];\n\n/** Fields of the API's error envelope: `{error, detail, error_code, retryable, request_id, params}`. */\ninterface ErrorEnvelopeBody {\n error?: unknown;\n detail?: unknown;\n error_code?: unknown;\n retryable?: unknown;\n request_id?: unknown;\n params?: unknown;\n}\n\nexport class APIError extends AnyformatError {\n /** Stable identifier for programmatic handling, e.g. `PAYMENT_REQUIRED`. */\n readonly errorCode?: string;\n /** Developer-facing explanation; not surfaced in `message` (ADR platform/0053 §2). Often a `ValidationItem[]`. */\n readonly detail?: JsonValue;\n /** Named substitutions the `error` summary refers to, e.g. `{ required_scope }`. */\n readonly params?: Record<string, ScalarOrList>;\n /** Whether the API says retrying the same request can succeed. */\n readonly retryable?: boolean;\n /** Correlation id to quote in support requests. */\n readonly requestId?: string;\n\n constructor(\n readonly status: number,\n message: string,\n readonly body?: unknown,\n ) {\n super(message);\n this.name = new.target.name;\n if (body && typeof body === \"object\") {\n const envelope = body as ErrorEnvelopeBody;\n if (typeof envelope.error_code === \"string\") this.errorCode = envelope.error_code;\n if (envelope.detail !== undefined) this.detail = envelope.detail as JsonValue;\n if (typeof envelope.retryable === \"boolean\") this.retryable = envelope.retryable;\n if (typeof envelope.request_id === \"string\") this.requestId = envelope.request_id;\n if (envelope.params && typeof envelope.params === \"object\") {\n this.params = envelope.params as Record<string, ScalarOrList>;\n }\n }\n }\n}\n\nexport class BadRequestError extends APIError {}\nexport class UnauthorizedError extends APIError {}\nexport class PaymentRequiredError extends APIError {}\nexport class ForbiddenError extends APIError {}\nexport class NotFoundError extends APIError {}\nexport class RateLimitedError extends APIError {\n constructor(\n status: number,\n message: string,\n body?: unknown,\n /** Seconds the API asks the caller to wait, from the `Retry-After` header; `undefined` when absent. */\n readonly retryAfter?: number,\n ) {\n super(status, message, body);\n }\n}\nexport class ServerError extends APIError {}\n\n/** `Retry-After` in seconds: delay-seconds or an HTTP-date (RFC 7231 §7.1.3). */\nexport function parseRetryAfter(raw: string | null | undefined): number | undefined {\n if (raw == null || raw.trim() === \"\") return undefined;\n const seconds = Number(raw);\n if (!Number.isNaN(seconds)) return seconds;\n const when = Date.parse(raw);\n if (Number.isNaN(when)) return undefined;\n return Math.max((when - Date.now()) / 1_000, 0);\n}\n\n// Status classes refined by `error_code`, aligned with the Python SDK's taxonomy.\n\n/** The API key lacks the scope this call needs (`insufficient_api_key_scope`). */\nexport class InsufficientScopeError extends ForbiddenError {}\n/** The caller must accept the terms of service first (`terms_acceptance_required`). */\nexport class TermsAcceptanceRequiredError extends ForbiddenError {}\n/** A workflow with that name already exists (`WORKFLOW_NAME_CONFLICT`). */\nexport class WorkflowNameConflictError extends APIError {}\n\nexport class SDKTimeoutError extends AnyformatError {}\n\n/** Thrown by `Run.wait()` when the run reaches a terminal failure status. */\nexport class RunFailedError extends AnyformatError {\n constructor(\n readonly runId: string,\n readonly status: \"error\" | \"cancelled\",\n ) {\n super(`Run ${runId} ended with status \"${status}\"`);\n this.name = new.target.name;\n }\n}\n\n/** The run ended in the terminal `error` status. */\nexport class ExtractionFailedError extends RunFailedError {\n constructor(runId: string) {\n super(runId, \"error\");\n }\n}\n\n/** The run ended in the terminal `cancelled` status. */\nexport class ExtractionCancelledError extends RunFailedError {\n constructor(runId: string) {\n super(runId, \"cancelled\");\n }\n}\n\n/** Raised by the fluent `WorkflowBuilder` for builder-API misuse. */\nexport class WorkflowBuilderError extends AnyformatError {}\n\n// `detail` is developer-facing and never lands in `message` (ADR platform/0053\n// §2); it stays reachable on `err.detail`.\nfunction messageFrom(status: number, body?: unknown): string {\n const fallback = `AnyFormat API error (${status})`;\n if (!body || typeof body !== \"object\") return fallback;\n const envelope = body as ErrorEnvelopeBody;\n return typeof envelope.error === \"string\" && envelope.error ? envelope.error : fallback;\n}\n\n/** `error_code` values that earn a class more specific than their HTTP status. */\nconst BY_ERROR_CODE: Record<string, new (status: number, message: string, body?: unknown) => APIError> = {\n insufficient_api_key_scope: InsufficientScopeError,\n terms_acceptance_required: TermsAcceptanceRequiredError,\n WORKFLOW_NAME_CONFLICT: WorkflowNameConflictError,\n};\n\nexport function toApiError(status: number, body?: unknown, headers?: Headers): APIError {\n const message = messageFrom(status, body);\n const errorCode =\n body && typeof body === \"object\" && typeof (body as ErrorEnvelopeBody).error_code === \"string\"\n ? ((body as ErrorEnvelopeBody).error_code as string)\n : undefined;\n const ByCode = errorCode ? BY_ERROR_CODE[errorCode] : undefined;\n if (ByCode) return new ByCode(status, message, body);\n switch (status) {\n case 400:\n return new BadRequestError(status, message, body);\n case 401:\n return new UnauthorizedError(status, message, body);\n case 402:\n return new PaymentRequiredError(status, message, body);\n case 403:\n return new ForbiddenError(status, message, body);\n case 404:\n return new NotFoundError(status, message, body);\n case 429:\n return new RateLimitedError(status, message, body, parseRetryAfter(headers?.get(\"Retry-After\")));\n default:\n return status >= 500\n ? new ServerError(status, message, body)\n : new APIError(status, message, body);\n }\n}\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen';\n\nexport type QuerySerializer = (query: Record<string, unknown>) => string;\n\nexport type BodySerializer = (body: unknown) => unknown;\n\ntype QuerySerializerOptionsObject = {\n allowReserved?: boolean;\n array?: Partial<SerializerOptions<ArrayStyle>>;\n object?: Partial<SerializerOptions<ObjectStyle>>;\n};\n\nexport type QuerySerializerOptions = QuerySerializerOptionsObject & {\n /**\n * Per-parameter serialization overrides. When provided, these settings\n * override the global array/object settings for specific parameter names.\n */\n parameters?: Record<string, QuerySerializerOptionsObject>;\n};\n\nconst serializeFormDataPair = (data: FormData, key: string, value: unknown): void => {\n if (typeof value === 'string' || value instanceof Blob) {\n data.append(key, value);\n } else if (value instanceof Date) {\n data.append(key, value.toISOString());\n } else {\n data.append(key, JSON.stringify(value));\n }\n};\n\nconst serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => {\n if (typeof value === 'string') {\n data.append(key, value);\n } else {\n data.append(key, JSON.stringify(value));\n }\n};\n\nexport const formDataBodySerializer = {\n bodySerializer: (body: unknown): FormData => {\n const data = new FormData();\n\n Object.entries(body as Record<string, unknown>).forEach(([key, value]) => {\n if (value === undefined || value === null) {\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((v) => serializeFormDataPair(data, key, v));\n } else {\n serializeFormDataPair(data, key, value);\n }\n });\n\n return data;\n },\n};\n\nexport const jsonBodySerializer = {\n bodySerializer: (body: unknown): string =>\n JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)),\n};\n\nexport const urlSearchParamsBodySerializer = {\n bodySerializer: (body: unknown): string => {\n const data = new URLSearchParams();\n\n Object.entries(body as Record<string, unknown>).forEach(([key, value]) => {\n if (value === undefined || value === null) {\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));\n } else {\n serializeUrlSearchParamsPair(data, key, value);\n }\n });\n\n return data.toString();\n },\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\ntype Slot = 'body' | 'headers' | 'path' | 'query';\n\nexport type Field =\n | {\n in: Exclude<Slot, 'body'>;\n /**\n * Field name. This is the name we want the user to see and use.\n */\n key: string;\n /**\n * Field mapped name. This is the name we want to use in the request.\n * If omitted, we use the same value as `key`.\n */\n map?: string;\n }\n | {\n in: Extract<Slot, 'body'>;\n /**\n * Key isn't required for bodies.\n */\n key?: string;\n map?: string;\n }\n | {\n /**\n * Field name. This is the name we want the user to see and use.\n */\n key: string;\n /**\n * Field mapped name. This is the name we want to use in the request.\n * If `in` is omitted, `map` aliases `key` to the transport layer.\n */\n map: Slot;\n };\n\nexport interface Fields {\n allowExtra?: Partial<Record<Slot, boolean>>;\n args?: ReadonlyArray<Field>;\n}\n\nexport type FieldsConfig = ReadonlyArray<Field | Fields>;\n\nconst extraPrefixesMap: Record<string, Slot> = {\n $body_: 'body',\n $headers_: 'headers',\n $path_: 'path',\n $query_: 'query',\n};\nconst extraPrefixes = Object.entries(extraPrefixesMap);\n\ntype KeyMap = Map<\n string,\n | {\n in: Slot;\n map?: string;\n }\n | {\n in?: never;\n map: Slot;\n }\n>;\n\nfunction buildKeyMap(fields: FieldsConfig, map?: KeyMap): KeyMap {\n if (!map) {\n map = new Map();\n }\n\n for (const config of fields) {\n if ('in' in config) {\n if (config.key) {\n map.set(config.key, {\n in: config.in,\n map: config.map,\n });\n }\n } else if ('key' in config) {\n map.set(config.key, {\n map: config.map,\n });\n } else if (config.args) {\n buildKeyMap(config.args, map);\n }\n }\n\n return map;\n}\n\ninterface Params {\n body?: unknown;\n headers: Record<string, unknown>;\n path: Record<string, unknown>;\n query: Record<string, unknown>;\n}\n\nfunction stripEmptySlots(params: Params): void {\n for (const [slot, value] of Object.entries(params)) {\n if (slot === 'body') continue;\n if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) {\n delete params[slot as Slot];\n }\n }\n}\n\nexport function buildClientParams(args: ReadonlyArray<unknown>, fields: FieldsConfig): Params {\n const params: Params = {\n headers: Object.create(null),\n path: Object.create(null),\n query: Object.create(null),\n };\n\n const map = buildKeyMap(fields);\n\n function writeSlot(slot: Slot, key: string, value: unknown): void {\n let record = params[slot] as Record<string, unknown> | undefined;\n if (record === undefined) {\n record = Object.create(null) as Record<string, unknown>;\n params[slot] = record;\n }\n record[key] = value;\n }\n\n let config: FieldsConfig[number] | undefined;\n\n for (const [index, arg] of args.entries()) {\n if (fields[index]) {\n config = fields[index];\n }\n\n if (!config) {\n continue;\n }\n\n if ('in' in config) {\n if (config.key) {\n const field = map.get(config.key)!;\n const name = field.map || config.key;\n if (field.in) {\n writeSlot(field.in, name, arg);\n }\n } else {\n params.body = arg;\n }\n } else {\n for (const [key, value] of Object.entries(arg ?? {})) {\n const field = map.get(key);\n\n if (field) {\n if (field.in) {\n const name = field.map || key;\n writeSlot(field.in, name, value);\n } else {\n params[field.map] = value;\n }\n } else {\n const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix));\n\n if (extra) {\n const [prefix, slot] = extra;\n writeSlot(slot, key.slice(prefix.length), value);\n } else if ('allowExtra' in config && config.allowExtra) {\n for (const [slot, allowed] of Object.entries(config.allowExtra)) {\n if (allowed) {\n writeSlot(slot as Slot, key, value);\n break;\n }\n }\n }\n }\n }\n }\n }\n\n stripEmptySlots(params);\n\n return params;\n}\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport type { Config } from './types.gen';\n\nexport type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, 'method'> &\n Pick<Config, 'method' | 'responseTransformer' | 'responseValidator'> & {\n /**\n * Fetch API implementation. You can use this option to provide a custom\n * fetch instance.\n *\n * @default globalThis.fetch\n */\n fetch?: typeof fetch;\n /**\n * Implementing clients can call request interceptors inside this hook.\n */\n onRequest?: (url: string, init: RequestInit) => Promise<Request>;\n /**\n * Callback invoked when a network or parsing error occurs during streaming.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @param error The error that occurred.\n */\n onSseError?: (error: unknown) => void;\n /**\n * Callback invoked when an event is streamed from the server.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @param event Event streamed from the server.\n * @returns Nothing (void).\n */\n onSseEvent?: (event: StreamEvent<TData>) => void;\n serializedBody?: RequestInit['body'];\n /**\n * Default retry delay in milliseconds.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @default 3000\n */\n sseDefaultRetryDelay?: number;\n /**\n * Maximum number of retry attempts before giving up.\n */\n sseMaxRetryAttempts?: number;\n /**\n * Maximum retry delay in milliseconds.\n *\n * Applies only when exponential backoff is used.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @default 30000\n */\n sseMaxRetryDelay?: number;\n /**\n * Optional sleep function for retry backoff.\n *\n * Defaults to using `setTimeout`.\n */\n sseSleepFn?: (ms: number) => Promise<void>;\n url: string;\n };\n\nexport interface StreamEvent<TData = unknown> {\n data: TData;\n event?: string;\n id?: string;\n retry?: number;\n}\n\nexport type ServerSentEventsResult<TData = unknown, TReturn = void, TNext = unknown> = {\n stream: AsyncGenerator<\n TData extends Record<string, unknown> ? TData[keyof TData] : TData,\n TReturn,\n TNext\n >;\n};\n\nexport function createSseClient<TData = unknown>({\n onRequest,\n onSseError,\n onSseEvent,\n responseTransformer,\n responseValidator,\n sseDefaultRetryDelay,\n sseMaxRetryAttempts,\n sseMaxRetryDelay,\n sseSleepFn,\n url,\n ...options\n}: ServerSentEventsOptions): ServerSentEventsResult<TData> {\n let lastEventId: string | undefined;\n\n const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));\n\n const createStream = async function* () {\n let retryDelay: number = sseDefaultRetryDelay ?? 3000;\n let attempt = 0;\n const signal = options.signal ?? new AbortController().signal;\n\n while (true) {\n if (signal.aborted) break;\n\n attempt++;\n\n const headers =\n options.headers instanceof Headers\n ? options.headers\n : new Headers(options.headers as Record<string, string> | undefined);\n\n if (lastEventId !== undefined) {\n headers.set('Last-Event-ID', lastEventId);\n }\n\n try {\n const requestInit: RequestInit = {\n redirect: 'follow',\n ...options,\n body: options.serializedBody,\n headers,\n signal,\n };\n let request = new Request(url, requestInit);\n if (onRequest) {\n request = await onRequest(url, requestInit);\n }\n // fetch must be assigned here, otherwise it would throw the error:\n // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation\n const _fetch = options.fetch ?? globalThis.fetch;\n const response = await _fetch(request);\n\n if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);\n\n if (!response.body) throw new Error('No body in SSE response');\n\n const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();\n\n let buffer = '';\n\n const abortHandler = () => {\n try {\n reader.cancel();\n } catch {\n // noop\n }\n };\n\n signal.addEventListener('abort', abortHandler);\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += value;\n buffer = buffer.replace(/\\r\\n?/g, '\\n'); // normalize line endings\n\n const chunks = buffer.split('\\n\\n');\n buffer = chunks.pop() ?? '';\n\n for (const chunk of chunks) {\n const lines = chunk.split('\\n');\n const dataLines: Array<string> = [];\n let eventName: string | undefined;\n\n for (const line of lines) {\n if (line.startsWith('data:')) {\n dataLines.push(line.replace(/^data:\\s*/, ''));\n } else if (line.startsWith('event:')) {\n eventName = line.replace(/^event:\\s*/, '');\n } else if (line.startsWith('id:')) {\n lastEventId = line.replace(/^id:\\s*/, '');\n } else if (line.startsWith('retry:')) {\n const parsed = Number.parseInt(line.replace(/^retry:\\s*/, ''), 10);\n if (!Number.isNaN(parsed)) {\n retryDelay = parsed;\n }\n }\n }\n\n let data: unknown;\n let parsedJson = false;\n\n if (dataLines.length) {\n const rawData = dataLines.join('\\n');\n try {\n data = JSON.parse(rawData);\n parsedJson = true;\n } catch {\n data = rawData;\n }\n }\n\n if (parsedJson) {\n if (responseValidator) {\n await responseValidator(data);\n }\n\n if (responseTransformer) {\n data = await responseTransformer(data);\n }\n }\n\n onSseEvent?.({\n data,\n event: eventName,\n id: lastEventId,\n retry: retryDelay,\n });\n\n if (dataLines.length) {\n yield data as any;\n }\n }\n }\n } finally {\n signal.removeEventListener('abort', abortHandler);\n reader.releaseLock();\n }\n\n break; // exit loop on normal completion\n } catch (error) {\n // connection failed or aborted; retry after delay\n onSseError?.(error);\n\n if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) {\n break; // stop after firing error\n }\n\n // exponential backoff: double retry each attempt, cap at 30s\n const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000);\n await sleep(backoff);\n }\n }\n };\n\n const stream = createStream();\n\n return { stream };\n}\n","// This file is auto-generated by @hey-api/openapi-ts\n\ninterface SerializeOptions<T> extends SerializePrimitiveOptions, SerializerOptions<T> {}\n\ninterface SerializePrimitiveOptions {\n allowReserved?: boolean;\n name: string;\n}\n\nexport interface SerializerOptions<T> {\n /**\n * @default true\n */\n explode: boolean;\n style: T;\n}\n\nexport type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';\nexport type ArraySeparatorStyle = ArrayStyle | MatrixStyle;\ntype MatrixStyle = 'label' | 'matrix' | 'simple';\nexport type ObjectStyle = 'form' | 'deepObject';\ntype ObjectSeparatorStyle = ObjectStyle | MatrixStyle;\n\ninterface SerializePrimitiveParam extends SerializePrimitiveOptions {\n value: string;\n}\n\nexport const separatorArrayExplode = (style: ArraySeparatorStyle): '.' | ';' | ',' | '&' => {\n switch (style) {\n case 'label':\n return '.';\n case 'matrix':\n return ';';\n case 'simple':\n return ',';\n default:\n return '&';\n }\n};\n\nexport const separatorArrayNoExplode = (style: ArraySeparatorStyle): ',' | '|' | '%20' => {\n switch (style) {\n case 'form':\n return ',';\n case 'pipeDelimited':\n return '|';\n case 'spaceDelimited':\n return '%20';\n default:\n return ',';\n }\n};\n\nexport const separatorObjectExplode = (style: ObjectSeparatorStyle): '.' | ';' | ',' | '&' => {\n switch (style) {\n case 'label':\n return '.';\n case 'matrix':\n return ';';\n case 'simple':\n return ',';\n default:\n return '&';\n }\n};\n\nexport const serializeArrayParam = ({\n allowReserved,\n explode,\n name,\n style,\n value,\n}: SerializeOptions<ArraySeparatorStyle> & {\n value: unknown[];\n}): string => {\n if (!explode) {\n const joinedValues = (\n allowReserved ? value : value.map((v) => encodeURIComponent(v as string))\n ).join(separatorArrayNoExplode(style));\n switch (style) {\n case 'label':\n return `.${joinedValues}`;\n case 'matrix':\n return `;${name}=${joinedValues}`;\n case 'simple':\n return joinedValues;\n default:\n return `${name}=${joinedValues}`;\n }\n }\n\n const separator = separatorArrayExplode(style);\n const joinedValues = value\n .map((v) => {\n if (style === 'label' || style === 'simple') {\n return allowReserved ? v : encodeURIComponent(v as string);\n }\n\n return serializePrimitiveParam({\n allowReserved,\n name,\n value: v as string,\n });\n })\n .join(separator);\n return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues;\n};\n\nexport const serializePrimitiveParam = ({\n allowReserved,\n name,\n value,\n}: SerializePrimitiveParam): string => {\n if (value === undefined || value === null) {\n return '';\n }\n\n if (typeof value === 'object') {\n throw new Error(\n 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.',\n );\n }\n\n return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;\n};\n\nexport const serializeObjectParam = ({\n allowReserved,\n explode,\n name,\n style,\n value,\n valueOnly,\n}: SerializeOptions<ObjectSeparatorStyle> & {\n value: Record<string, unknown> | Date;\n valueOnly?: boolean;\n}): string => {\n if (value instanceof Date) {\n return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;\n }\n\n if (style !== 'deepObject' && !explode) {\n let values: string[] = [];\n Object.entries(value).forEach(([key, v]) => {\n values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)];\n });\n const joinedValues = values.join(',');\n switch (style) {\n case 'form':\n return `${name}=${joinedValues}`;\n case 'label':\n return `.${joinedValues}`;\n case 'matrix':\n return `;${name}=${joinedValues}`;\n default:\n return joinedValues;\n }\n }\n\n const separator = separatorObjectExplode(style);\n const joinedValues = Object.entries(value)\n .map(([key, v]) =>\n serializePrimitiveParam({\n allowReserved,\n name: style === 'deepObject' ? `${name}[${key}]` : key,\n value: v as string,\n }),\n )\n .join(separator);\n return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues;\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport type { BodySerializer, QuerySerializer } from './bodySerializer.gen';\nimport {\n type ArraySeparatorStyle,\n serializeArrayParam,\n serializeObjectParam,\n serializePrimitiveParam,\n} from './pathSerializer.gen';\n\nexport interface PathSerializer {\n path: Record<string, unknown>;\n url: string;\n}\n\nexport const PATH_PARAM_RE: RegExp = /\\{[^{}]+\\}/g;\n\nexport const defaultPathSerializer = ({ path, url: _url }: PathSerializer): string => {\n let url = _url;\n const matches = _url.match(PATH_PARAM_RE);\n if (matches) {\n for (const match of matches) {\n let explode = false;\n let name = match.substring(1, match.length - 1);\n let style: ArraySeparatorStyle = 'simple';\n\n if (name.endsWith('*')) {\n explode = true;\n name = name.substring(0, name.length - 1);\n }\n\n if (name.startsWith('.')) {\n name = name.substring(1);\n style = 'label';\n } else if (name.startsWith(';')) {\n name = name.substring(1);\n style = 'matrix';\n }\n\n const value = path[name];\n\n if (value === undefined || value === null) {\n continue;\n }\n\n if (Array.isArray(value)) {\n url = url.replace(match, serializeArrayParam({ explode, name, style, value }));\n continue;\n }\n\n if (typeof value === 'object') {\n url = url.replace(\n match,\n serializeObjectParam({\n explode,\n name,\n style,\n value: value as Record<string, unknown>,\n valueOnly: true,\n }),\n );\n continue;\n }\n\n if (style === 'matrix') {\n url = url.replace(\n match,\n `;${serializePrimitiveParam({\n name,\n value: value as string,\n })}`,\n );\n continue;\n }\n\n const replaceValue = encodeURIComponent(\n style === 'label' ? `.${value as string}` : (value as string),\n );\n url = url.replace(match, replaceValue);\n }\n }\n return url;\n};\n\nexport const getUrl = ({\n baseUrl,\n path,\n query,\n querySerializer,\n url: _url,\n}: {\n baseUrl?: string;\n path?: Record<string, unknown>;\n query?: Record<string, unknown>;\n querySerializer: QuerySerializer;\n url: string;\n}): string => {\n const pathUrl = _url.startsWith('/') ? _url : `/${_url}`;\n let url = (baseUrl ?? '') + pathUrl;\n if (path) {\n url = defaultPathSerializer({ path, url });\n }\n let search = query ? querySerializer(query) : '';\n if (search.startsWith('?')) {\n search = search.substring(1);\n }\n if (search) {\n url += `?${search}`;\n }\n return url;\n};\n\nexport function getValidRequestBody(options: {\n body?: unknown;\n bodySerializer?: BodySerializer | null;\n serializedBody?: unknown;\n}): unknown {\n const hasBody = options.body !== undefined;\n const isSerializedBody = hasBody && options.bodySerializer;\n\n if (isSerializedBody) {\n if ('serializedBody' in options) {\n const hasSerializedBody =\n options.serializedBody !== undefined && options.serializedBody !== '';\n\n return hasSerializedBody ? options.serializedBody : null;\n }\n\n // not all clients implement a serializedBody property (i.e., client-axios)\n return options.body !== '' ? options.body : null;\n }\n\n // plain/text body\n if (hasBody) {\n return options.body;\n }\n\n // no body was provided\n return undefined;\n}\n","// This file is auto-generated by @hey-api/openapi-ts\n\nexport type AuthToken = string | undefined;\n\nexport interface Auth {\n /**\n * Which part of the request do we use to send the auth?\n *\n * @default 'header'\n */\n in?: 'header' | 'query' | 'cookie';\n /**\n * A unique identifier for the security scheme.\n *\n * Defined only when there are multiple security schemes whose `Auth`\n * shape would otherwise be identical.\n */\n key?: string;\n /**\n * Header or query parameter name.\n *\n * @default 'Authorization'\n */\n name?: string;\n scheme?: 'basic' | 'bearer';\n type: 'apiKey' | 'http';\n}\n\nexport const getAuthToken = async (\n auth: Auth,\n callback: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken,\n): Promise<string | undefined> => {\n const token = typeof callback === 'function' ? await callback(auth) : callback;\n\n if (!token) {\n return;\n }\n\n if (auth.scheme === 'bearer') {\n return `Bearer ${token}`;\n }\n\n if (auth.scheme === 'basic') {\n return `Basic ${btoa(token)}`;\n }\n\n return token;\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { getAuthToken } from '../core/auth.gen';\nimport type { QuerySerializerOptions } from '../core/bodySerializer.gen';\nimport { jsonBodySerializer } from '../core/bodySerializer.gen';\nimport {\n serializeArrayParam,\n serializeObjectParam,\n serializePrimitiveParam,\n} from '../core/pathSerializer.gen';\nimport { getUrl } from '../core/utils.gen';\nimport type { Client, ClientOptions, Config, RequestOptions } from './types.gen';\n\nexport const createQuerySerializer = <T = unknown>({\n parameters = {},\n ...args\n}: QuerySerializerOptions = {}): ((queryParams: T) => string) => {\n const querySerializer = (queryParams: T): string => {\n const search: string[] = [];\n if (queryParams && typeof queryParams === 'object') {\n for (const name in queryParams) {\n const value = queryParams[name];\n\n if (value === undefined || value === null) {\n continue;\n }\n\n const options = parameters[name] || args;\n\n if (Array.isArray(value)) {\n const serializedArray = serializeArrayParam({\n allowReserved: options.allowReserved,\n explode: true,\n name,\n style: 'form',\n value,\n ...options.array,\n });\n if (serializedArray) search.push(serializedArray);\n } else if (typeof value === 'object') {\n const serializedObject = serializeObjectParam({\n allowReserved: options.allowReserved,\n explode: true,\n name,\n style: 'deepObject',\n value: value as Record<string, unknown>,\n ...options.object,\n });\n if (serializedObject) search.push(serializedObject);\n } else {\n const serializedPrimitive = serializePrimitiveParam({\n allowReserved: options.allowReserved,\n name,\n value: value as string,\n });\n if (serializedPrimitive) search.push(serializedPrimitive);\n }\n }\n }\n return search.join('&');\n };\n return querySerializer;\n};\n\n/**\n * Infers parseAs value from provided Content-Type header.\n */\nexport const getParseAs = (contentType: string | null): Exclude<Config['parseAs'], 'auto'> => {\n if (!contentType) {\n // If no Content-Type header is provided, the best we can do is return the raw response body,\n // which is effectively the same as the 'stream' option.\n return 'stream';\n }\n\n const cleanContent = contentType.split(';')[0]?.trim();\n\n if (!cleanContent) {\n return;\n }\n\n if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) {\n return 'json';\n }\n\n if (cleanContent === 'multipart/form-data') {\n return 'formData';\n }\n\n if (\n ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type))\n ) {\n return 'blob';\n }\n\n if (cleanContent.startsWith('text/')) {\n return 'text';\n }\n\n return;\n};\n\nconst checkForExistence = (\n options: Pick<RequestOptions, 'auth' | 'query'> & {\n headers: Headers;\n },\n name?: string,\n): boolean => {\n if (!name) {\n return false;\n }\n if (\n options.headers.has(name) ||\n options.query?.[name] ||\n options.headers.get('Cookie')?.includes(`${name}=`)\n ) {\n return true;\n }\n return false;\n};\n\nexport async function setAuthParams(\n options: Pick<RequestOptions, 'auth' | 'query' | 'security'> & {\n headers: Headers;\n },\n): Promise<void> {\n for (const auth of options.security ?? []) {\n if (checkForExistence(options, auth.name)) {\n continue;\n }\n\n const token = await getAuthToken(auth, options.auth);\n\n if (!token) {\n continue;\n }\n\n const name = auth.name ?? 'Authorization';\n\n switch (auth.in) {\n case 'query':\n if (!options.query) {\n options.query = {};\n }\n options.query[name] = token;\n break;\n case 'cookie':\n options.headers.append('Cookie', `${name}=${token}`);\n break;\n case 'header':\n default:\n options.headers.set(name, token);\n break;\n }\n }\n}\n\nexport const buildUrl: Client['buildUrl'] = (options) =>\n getUrl({\n baseUrl: options.baseUrl as string,\n path: options.path,\n query: options.query,\n querySerializer:\n typeof options.querySerializer === 'function'\n ? options.querySerializer\n : createQuerySerializer(options.querySerializer),\n url: options.url,\n });\n\nexport const mergeConfigs = (a: Config, b: Config): Config => {\n const config = { ...a, ...b };\n if (config.baseUrl?.endsWith('/')) {\n config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);\n }\n config.headers = mergeHeaders(a.headers, b.headers);\n return config;\n};\n\nconst headersEntries = (headers: Headers): Array<[string, string]> => {\n const entries: Array<[string, string]> = [];\n headers.forEach((value, key) => {\n entries.push([key, value]);\n });\n return entries;\n};\n\nexport const mergeHeaders = (\n ...headers: Array<Required<Config>['headers'] | undefined>\n): Headers => {\n const mergedHeaders = new Headers();\n for (const header of headers) {\n if (!header) {\n continue;\n }\n\n const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);\n\n for (const [key, value] of iterator) {\n if (value === null) {\n mergedHeaders.delete(key);\n } else if (Array.isArray(value)) {\n for (const v of value) {\n mergedHeaders.append(key, v as string);\n }\n } else if (value !== undefined) {\n // assume object headers are meant to be JSON stringified, i.e., their\n // content value in OpenAPI specification is 'application/json'\n mergedHeaders.set(\n key,\n typeof value === 'object' ? JSON.stringify(value) : (value as string),\n );\n }\n }\n }\n return mergedHeaders;\n};\n\ntype ErrInterceptor<Err, Res, Req, Options> = (\n error: Err,\n /** response may be undefined due to a network error where no response object is produced */\n response: Res | undefined,\n /** request may be undefined, because error may be from building the request object itself */\n request: Req | undefined,\n options: Options,\n) => Err | Promise<Err>;\n\ntype ReqInterceptor<Req, Options> = (request: Req, options: Options) => Req | Promise<Req>;\n\ntype ResInterceptor<Res, Req, Options> = (\n response: Res,\n request: Req,\n options: Options,\n) => Res | Promise<Res>;\n\nclass Interceptors<Interceptor> {\n fns: Array<Interceptor | null> = [];\n\n clear(): void {\n this.fns = [];\n }\n\n eject(id: number | Interceptor): void {\n const index = this.getInterceptorIndex(id);\n if (this.fns[index]) {\n this.fns[index] = null;\n }\n }\n\n exists(id: number | Interceptor): boolean {\n const index = this.getInterceptorIndex(id);\n return Boolean(this.fns[index]);\n }\n\n getInterceptorIndex(id: number | Interceptor): number {\n if (typeof id === 'number') {\n return this.fns[id] ? id : -1;\n }\n return this.fns.indexOf(id);\n }\n\n update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false {\n const index = this.getInterceptorIndex(id);\n if (this.fns[index]) {\n this.fns[index] = fn;\n return id;\n }\n return false;\n }\n\n use(fn: Interceptor): number {\n this.fns.push(fn);\n return this.fns.length - 1;\n }\n}\n\nexport interface Middleware<Req, Res, Err, Options> {\n error: Interceptors<ErrInterceptor<Err, Res, Req, Options>>;\n request: Interceptors<ReqInterceptor<Req, Options>>;\n response: Interceptors<ResInterceptor<Res, Req, Options>>;\n}\n\nexport const createInterceptors = <Req, Res, Err, Options>(): Middleware<\n Req,\n Res,\n Err,\n Options\n> => ({\n error: new Interceptors<ErrInterceptor<Err, Res, Req, Options>>(),\n request: new Interceptors<ReqInterceptor<Req, Options>>(),\n response: new Interceptors<ResInterceptor<Res, Req, Options>>(),\n});\n\nconst defaultQuerySerializer = createQuerySerializer({\n allowReserved: false,\n array: {\n explode: true,\n style: 'form',\n },\n object: {\n explode: true,\n style: 'deepObject',\n },\n});\n\nconst defaultHeaders = {\n 'Content-Type': 'application/json',\n};\n\nexport const createConfig = <T extends ClientOptions = ClientOptions>(\n override: Config<Omit<ClientOptions, keyof T> & T> = {},\n): Config<Omit<ClientOptions, keyof T> & T> => ({\n ...jsonBodySerializer,\n headers: defaultHeaders,\n parseAs: 'auto',\n querySerializer: defaultQuerySerializer,\n ...override,\n});\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { createSseClient } from '../core/serverSentEvents.gen';\nimport type { HttpMethod } from '../core/types.gen';\nimport { getValidRequestBody } from '../core/utils.gen';\nimport type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen';\nimport {\n buildUrl,\n createConfig,\n createInterceptors,\n getParseAs,\n mergeConfigs,\n mergeHeaders,\n setAuthParams,\n} from './utils.gen';\n\ntype ReqInit = Omit<RequestInit, 'body' | 'headers'> & {\n body?: any;\n headers: ReturnType<typeof mergeHeaders>;\n};\n\nexport const createClient = (config: Config = {}): Client => {\n let _config = mergeConfigs(createConfig(), config);\n\n const getConfig = (): Config => ({ ..._config });\n\n const setConfig = (config: Config): Config => {\n _config = mergeConfigs(_config, config);\n return getConfig();\n };\n\n const interceptors = createInterceptors<Request, Response, unknown, ResolvedRequestOptions>();\n\n const beforeRequest = async <\n TData = unknown,\n TResponseStyle extends 'data' | 'fields' = 'fields',\n ThrowOnError extends boolean = boolean,\n Url extends string = string,\n >(\n options: RequestOptions<TData, TResponseStyle, ThrowOnError, Url>,\n ) => {\n const opts = {\n ..._config,\n ...options,\n fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,\n headers: mergeHeaders(_config.headers, options.headers),\n serializedBody: undefined as string | undefined,\n };\n\n if (opts.security) {\n await setAuthParams(opts);\n }\n\n if (opts.requestValidator) {\n await opts.requestValidator(opts);\n }\n\n if (opts.body !== undefined && opts.bodySerializer) {\n opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined;\n }\n\n // remove Content-Type header if body is empty to avoid sending invalid requests\n if (opts.body === undefined || opts.serializedBody === '') {\n opts.headers.delete('Content-Type');\n }\n\n const resolvedOpts = opts as typeof opts &\n ResolvedRequestOptions<TResponseStyle, ThrowOnError, Url>;\n const url = buildUrl(resolvedOpts);\n\n return { opts: resolvedOpts, url };\n };\n\n const request: Client['request'] = async (options) => {\n const throwOnError = options.throwOnError ?? _config.throwOnError;\n const responseStyle = options.responseStyle ?? _config.responseStyle;\n\n let request: Request | undefined;\n let response: Response | undefined;\n\n try {\n const { opts, url } = await beforeRequest(options);\n const requestInit: ReqInit = {\n redirect: 'follow',\n ...opts,\n body: getValidRequestBody(opts),\n };\n\n request = new Request(url, requestInit);\n\n for (const fn of interceptors.request.fns) {\n if (fn) {\n request = await fn(request, opts);\n }\n }\n\n // fetch must be assigned here, otherwise it would throw the error:\n // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation\n const _fetch = opts.fetch!;\n\n response = await _fetch(request);\n\n for (const fn of interceptors.response.fns) {\n if (fn) {\n response = await fn(response, request, opts);\n }\n }\n\n const result = {\n request,\n response,\n };\n\n if (response.ok) {\n const parseAs =\n (opts.parseAs === 'auto'\n ? getParseAs(response.headers.get('Content-Type'))\n : opts.parseAs) ?? 'json';\n\n if (response.status === 204 || response.headers.get('Content-Length') === '0') {\n let emptyData: any;\n switch (parseAs) {\n case 'arrayBuffer':\n case 'blob':\n case 'text':\n emptyData = await response[parseAs]();\n break;\n case 'formData':\n emptyData = new FormData();\n break;\n case 'stream':\n emptyData = response.body;\n break;\n case 'json':\n default:\n emptyData = {};\n break;\n }\n return opts.responseStyle === 'data'\n ? emptyData\n : {\n data: emptyData,\n ...result,\n };\n }\n\n let data: any;\n switch (parseAs) {\n case 'arrayBuffer':\n case 'blob':\n case 'formData':\n case 'text':\n data = await response[parseAs]();\n break;\n case 'json': {\n // Some servers return 200 with no Content-Length and empty body.\n // response.json() would throw; read as text and parse if non-empty.\n const text = await response.text();\n data = text ? JSON.parse(text) : {};\n break;\n }\n case 'stream':\n return opts.responseStyle === 'data'\n ? response.body\n : {\n data: response.body,\n ...result,\n };\n }\n\n if (parseAs === 'json') {\n if (opts.responseValidator) {\n await opts.responseValidator(data);\n }\n\n if (opts.responseTransformer) {\n data = await opts.responseTransformer(data);\n }\n }\n\n return opts.responseStyle === 'data'\n ? data\n : {\n data,\n ...result,\n };\n }\n\n const textError = await response.text();\n let jsonError: unknown;\n\n try {\n jsonError = JSON.parse(textError);\n } catch {\n // noop\n }\n\n throw jsonError ?? textError;\n } catch (error) {\n let finalError = error;\n\n for (const fn of interceptors.error.fns) {\n if (fn) {\n finalError = await fn(finalError, response, request, options as ResolvedRequestOptions);\n }\n }\n\n finalError = finalError || {};\n\n if (throwOnError) {\n throw finalError;\n }\n\n // TODO: we probably want to return error and improve types\n return responseStyle === 'data'\n ? undefined\n : {\n error: finalError,\n request,\n response,\n };\n }\n };\n\n const makeMethodFn = (method: Uppercase<HttpMethod>) => (options: RequestOptions) =>\n request({ ...options, method });\n\n const makeSseFn = (method: Uppercase<HttpMethod>) => async (options: RequestOptions) => {\n const { opts, url } = await beforeRequest(options);\n return createSseClient({\n ...opts,\n body: opts.body as BodyInit | null | undefined,\n method,\n onRequest: async (url, init) => {\n let request = new Request(url, init);\n for (const fn of interceptors.request.fns) {\n if (fn) {\n request = await fn(request, opts);\n }\n }\n return request;\n },\n serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined,\n url,\n });\n };\n\n const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options });\n\n return {\n buildUrl: _buildUrl,\n connect: makeMethodFn('CONNECT'),\n delete: makeMethodFn('DELETE'),\n get: makeMethodFn('GET'),\n getConfig,\n head: makeMethodFn('HEAD'),\n interceptors,\n options: makeMethodFn('OPTIONS'),\n patch: makeMethodFn('PATCH'),\n post: makeMethodFn('POST'),\n put: makeMethodFn('PUT'),\n request,\n setConfig,\n sse: {\n connect: makeSseFn('CONNECT'),\n delete: makeSseFn('DELETE'),\n get: makeSseFn('GET'),\n head: makeSseFn('HEAD'),\n options: makeSseFn('OPTIONS'),\n patch: makeSseFn('PATCH'),\n post: makeSseFn('POST'),\n put: makeSseFn('PUT'),\n trace: makeSseFn('TRACE'),\n },\n trace: makeMethodFn('TRACE'),\n } as Client;\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { type Client, type ClientOptions, type Config, createClient, createConfig } from './client';\nimport type { ClientOptions as ClientOptions2 } from './types.gen';\n\n/**\n * The `createClientConfig()` function will be called on client initialization\n * and the returned object will become the client's initial configuration.\n *\n * You may want to initialize your client this way instead of calling\n * `setConfig()`. This is useful for example if you're using Next.js\n * to ensure your client always has the correct values.\n */\nexport type CreateClientConfig<T extends ClientOptions = ClientOptions2> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;\n\nexport const client: Client = createClient(createConfig<ClientOptions2>({ baseUrl: 'https://api.anyformat.dev' }));\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { type Client, type ClientMeta, formDataBodySerializer, type Options as Options2, type RequestResult, type TDataShape } from './client';\nimport { client } from './client.gen';\nimport type { V3AskKnowledgeData, V3AskKnowledgeErrors, V3AskKnowledgeResponses, V3CreateBlobSlotsData, V3CreateBlobSlotsErrors, V3CreateBlobSlotsResponses, V3CreateWorkflowData, V3CreateWorkflowErrors, V3CreateWorkflowResponses, V3DeleteDocumentPacketData, V3DeleteDocumentPacketErrors, V3DeleteDocumentPacketResponses, V3DeleteEditReferenceData, V3DeleteEditReferenceErrors, V3DeleteEditReferenceResponses, V3DeleteWorkflowData, V3DeleteWorkflowErrors, V3DeleteWorkflowResponses, V3DownloadKnowledgeData, V3DownloadKnowledgeErrors, V3DownloadKnowledgeResponses, V3GetDocumentPacketData, V3GetDocumentPacketErrors, V3GetDocumentPacketResponses, V3GetEvalData, V3GetEvalErrors, V3GetEvalResponses, V3GetRunData, V3GetRunErrors, V3GetRunResponses, V3GetWorkflowData, V3GetWorkflowErrors, V3GetWorkflowResponses, V3LaunchEvalData, V3LaunchEvalErrors, V3LaunchEvalResponses, V3ListEditReferencesData, V3ListEditReferencesErrors, V3ListEditReferencesResponses, V3ListEvalsData, V3ListEvalsErrors, V3ListEvalsResponses, V3ListKnowledgeData, V3ListKnowledgeErrors, V3ListKnowledgeResponses, V3ListWorkflowDocumentPacketsData, V3ListWorkflowDocumentPacketsErrors, V3ListWorkflowDocumentPacketsResponses, V3ListWorkflowRunsData, V3ListWorkflowRunsErrors, V3ListWorkflowRunsResponses, V3ListWorkflowsData, V3ListWorkflowsErrors, V3ListWorkflowsResponses, V3ListWorkflowVersionsData, V3ListWorkflowVersionsErrors, V3ListWorkflowVersionsResponses, V3ParseData, V3ParseErrors, V3ParseFromUrlData, V3ParseFromUrlErrors, V3ParseFromUrlResponses, V3ParseResponses, V3ReadKnowledgeData, V3ReadKnowledgeErrors, V3ReadKnowledgeResponses, V3RunDocumentPacketData, V3RunDocumentPacketErrors, V3RunDocumentPacketResponses, V3SearchKnowledgeData, V3SearchKnowledgeErrors, V3SearchKnowledgeResponses, V3UpdateWorkflowData, V3UpdateWorkflowErrors, V3UpdateWorkflowResponses, V3UploadAndRunWorkflowData, V3UploadAndRunWorkflowErrors, V3UploadAndRunWorkflowResponses, V3UploadEditReferencesData, V3UploadEditReferencesErrors, V3UploadEditReferencesResponses, V3UploadFromUrlData, V3UploadFromUrlErrors, V3UploadFromUrlResponses, V3UploadToDatasetData, V3UploadToDatasetErrors, V3UploadToDatasetResponses, V3UploadToWorkflowData, V3UploadToWorkflowErrors, V3UploadToWorkflowResponses } from './types.gen';\n\nexport type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {\n /**\n * You can provide a client instance returned by `createClient()` instead of\n * individual options. This might be also useful if you want to implement a\n * custom client.\n */\n client?: Client;\n /**\n * You can pass arbitrary values through the `meta` object. This can be\n * used to access values that aren't defined as part of the SDK function.\n */\n meta?: keyof ClientMeta extends never ? Record<string, unknown> : ClientMeta;\n};\n\n/**\n * Stage a file you hold, and get the URL it will be readable at\n *\n * Get somewhere to put a file you hold, plus the URL it will read back at.\n *\n * Every other ingestion path takes a URL this API can fetch, which a file on\n * your own machine is not. Staging closes that gap in one call: the bytes go\n * straight from you to storage without passing through this API, and the\n * `read_url` is minted here because the destination is known before a byte\n * moves.\n *\n * Per slot, POST `upload.fields` verbatim followed by the file part as\n * multipart/form-data to `upload.url`. Then refer to the file by its\n * `object_id` — `POST /v3/parse/from-url/` takes `{object_id, filename}` and\n * `POST /v3/workflows/{id}/upload/from-url/` takes `staged_files` — or hand\n * `read_url` to something outside this API; the filename is signed into that\n * URL, so the file is named correctly on the other side.\n *\n * Each policy pins the destination, the content type and the exact\n * `declared_size`, so a slot accepts one intended file and nothing else. A\n * batch is all-or-nothing: a file above your plan's size limit fails the whole\n * call with a 422 and mints no slots, before a byte moves.\n *\n * Staged bytes are scratch: they belong to no workflow, and storage deletes\n * them within a day. Anything that must outlive that belongs in a workflow.\n */\nexport const v3CreateBlobSlots = <ThrowOnError extends boolean = false>(options: Options<V3CreateBlobSlotsData, ThrowOnError>): RequestResult<V3CreateBlobSlotsResponses, V3CreateBlobSlotsErrors, ThrowOnError> => (options.client ?? client).post<V3CreateBlobSlotsResponses, V3CreateBlobSlotsErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/blobs/slots/',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Delete document packet\n *\n * Delete a document packet and all its files.\n *\n * Same semantics as `DELETE /v2/files/{collection_id}/`: the packet and\n * every file in it are removed together, along with any extraction\n * results. This action is irreversible.\n */\nexport const v3DeleteDocumentPacket = <ThrowOnError extends boolean = false>(options: Options<V3DeleteDocumentPacketData, ThrowOnError>): RequestResult<V3DeleteDocumentPacketResponses, V3DeleteDocumentPacketErrors, ThrowOnError> => (options.client ?? client).delete<V3DeleteDocumentPacketResponses, V3DeleteDocumentPacketErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/document-packets/{document_packet_id}/',\n ...options\n});\n\n/**\n * Get document packet\n *\n * Retrieve one document packet flat: status, timestamps, the files it\n * groups, and `latest_run_id` (`null` until the packet has been run).\n *\n * Unknown ids — including packets belonging to another organization —\n * return 404.\n */\nexport const v3GetDocumentPacket = <ThrowOnError extends boolean = false>(options: Options<V3GetDocumentPacketData, ThrowOnError>): RequestResult<V3GetDocumentPacketResponses, V3GetDocumentPacketErrors, ThrowOnError> => (options.client ?? client).get<V3GetDocumentPacketResponses, V3GetDocumentPacketErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/document-packets/{document_packet_id}/',\n ...options\n});\n\n/**\n * Run document packet\n *\n * Run (or re-run) a document packet on the latest version of its\n * workflow.\n *\n * Every call creates a NEW run — re-running after editing the workflow\n * is the intended flow; earlier runs stay readable at\n * `GET /v3/runs/{run_id}/`. The only exception is an `Idempotency-Key`\n * replay, which returns the original run.\n *\n * Unknown ids — including packets belonging to another organization —\n * return 404. An organization without extraction credit gets 402.\n */\nexport const v3RunDocumentPacket = <ThrowOnError extends boolean = false>(options: Options<V3RunDocumentPacketData, ThrowOnError>): RequestResult<V3RunDocumentPacketResponses, V3RunDocumentPacketErrors, ThrowOnError> => (options.client ?? client).post<V3RunDocumentPacketResponses, V3RunDocumentPacketErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/document-packets/{document_packet_id}/run/',\n ...options\n});\n\n/**\n * Parse a document\n *\n * Parse one document with the platform's fast lite parse (atomic).\n *\n * One file per call. The upload runs against your organization's system\n * parse workflow, provisioned automatically on first use. Poll\n * `GET /v3/runs/{run_id}/` until `status` is `processed`; the markdown is\n * at `results.parse.markdown`.\n *\n * Honors `Idempotency-Key`: a retried request with the same key replays\n * the original packet and run.\n */\nexport const v3Parse = <ThrowOnError extends boolean = false>(options: Options<V3ParseData, ThrowOnError>): RequestResult<V3ParseResponses, V3ParseErrors, ThrowOnError> => (options.client ?? client).post<V3ParseResponses, V3ParseErrors, ThrowOnError>({\n ...formDataBodySerializer,\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/parse/',\n ...options,\n headers: {\n 'Content-Type': null,\n ...options.headers\n }\n});\n\n/**\n * Parse a document from a URL\n *\n * Parse one document fetched from a URL with the platform's fast lite\n * parse (atomic).\n *\n * One document per call: an HTTPS `url`, or the `object_id` (plus\n * `filename`) of a file staged via `POST /v3/blobs/slots/`. The upload runs\n * against your organization's system parse workflow, provisioned\n * automatically on first use. Poll `GET /v3/runs/{run_id}/` until `status`\n * is `processed`; the markdown is at `results.parse.markdown`.\n *\n * A URL-fetched file is named by the response's `Content-Disposition`\n * filename when present, else by the last segment of the URL's path.\n *\n * Not idempotent: every call fetches the document, creates a packet and starts\n * a new run. For a retry-safe flow use `POST /v3/workflows/{id}/upload/from-url/`\n * and then `POST /v3/document-packets/{id}/run/` with an `Idempotency-Key`.\n */\nexport const v3ParseFromUrl = <ThrowOnError extends boolean = false>(options: Options<V3ParseFromUrlData, ThrowOnError>): RequestResult<V3ParseFromUrlResponses, V3ParseFromUrlErrors, ThrowOnError> => (options.client ?? client).post<V3ParseFromUrlResponses, V3ParseFromUrlErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/parse/from-url/',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Get run\n *\n * Retrieve one run flat: lifecycle status plus results inline.\n *\n * Always 200 while the run exists — no precondition errors while the\n * extraction is in flight. `results` is `null` until `status` reaches\n * `processed`, then carries the extraction results envelope (the same\n * shape as the v2 results endpoint). A run that ended in `error` or\n * `cancelled` stays readable with `results: null`.\n *\n * Unknown ids — including runs belonging to another organization —\n * return 404.\n */\nexport const v3GetRun = <ThrowOnError extends boolean = false>(options: Options<V3GetRunData, ThrowOnError>): RequestResult<V3GetRunResponses, V3GetRunErrors, ThrowOnError> => (options.client ?? client).get<V3GetRunResponses, V3GetRunErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/runs/{run_id}/',\n ...options\n});\n\n/**\n * List workflows\n *\n * List your organization's workflows, newest first.\n *\n * Keyset-paginated: follow `next_cursor` until it is `null`. The sort\n * order is fixed (`-created_at, -id`); there are no totals or page numbers.\n */\nexport const v3ListWorkflows = <ThrowOnError extends boolean = false>(options?: Options<V3ListWorkflowsData, ThrowOnError>): RequestResult<V3ListWorkflowsResponses, V3ListWorkflowsErrors, ThrowOnError> => (options?.client ?? client).get<V3ListWorkflowsResponses, V3ListWorkflowsErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/',\n ...options\n});\n\n/**\n * Create workflow\n *\n * Create a workflow from a strongly-typed graph (atomic).\n *\n * Provide an explicit list of typed `nodes` (parse / classify / splitter /\n * extract / validate) and `edges` between them — the same body shape\n * `POST /v2/workflows/` accepts. Returns the stored graph, so the\n * server-assigned `persistent_id`s a later `PATCH` must echo arrive with the\n * create rather than needing a second call.\n */\nexport const v3CreateWorkflow = <ThrowOnError extends boolean = false>(options: Options<V3CreateWorkflowData, ThrowOnError>): RequestResult<V3CreateWorkflowResponses, V3CreateWorkflowErrors, ThrowOnError> => (options.client ?? client).post<V3CreateWorkflowResponses, V3CreateWorkflowErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Delete workflow\n *\n * Delete a workflow and all associated document packets and runs.\n *\n * This action is irreversible.\n */\nexport const v3DeleteWorkflow = <ThrowOnError extends boolean = false>(options: Options<V3DeleteWorkflowData, ThrowOnError>): RequestResult<V3DeleteWorkflowResponses, V3DeleteWorkflowErrors, ThrowOnError> => (options.client ?? client).delete<V3DeleteWorkflowResponses, V3DeleteWorkflowErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/',\n ...options\n});\n\n/**\n * Get workflow\n *\n * Retrieve a workflow with its complete typed graph inline.\n *\n * `{name, description, nodes, edges}` is the exact shape\n * `POST /v3/workflows/` accepts — mutate it and feed it back to\n * `PATCH /v3/workflows/{workflow_id}/` to edit.\n *\n * Pass `version` to read one version for comparison or audit; any other\n * query parameter is rejected, so a misspelled `version` cannot silently\n * read the latest. Versions are read-only: runs always use the latest\n * version, and a PATCH always builds on the latest version.\n */\nexport const v3GetWorkflow = <ThrowOnError extends boolean = false>(options: Options<V3GetWorkflowData, ThrowOnError>): RequestResult<V3GetWorkflowResponses, V3GetWorkflowErrors, ThrowOnError> => (options.client ?? client).get<V3GetWorkflowResponses, V3GetWorkflowErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/',\n ...options\n});\n\n/**\n * Update workflow\n *\n * Replace a workflow's typed graph (atomic).\n *\n * The body is the `{name, description, nodes, edges}` sub-shape of\n * `GET /v3/workflows/{workflow_id}/` — GET, mutate, PATCH. Echo each\n * existing field's `persistent_id` unchanged (including across\n * renames) to keep the field's identity, so analytics, ground truth\n * and quality metrics stay attached; omit `persistent_id` only for\n * genuinely new fields (a pidless field is always treated as new —\n * name coincidence with a prior field does NOT confer identity). An\n * echoed `persistent_id` that doesn't match any field in the current\n * version is a 400. Responds with the updated workflow in the exact\n * `GET /v3/workflows/{workflow_id}/` shape, so the result can be\n * edited and PATCHed again. The returned graph is this request's own\n * write result — including the `persistent_id`s assigned to new\n * fields — never the state left by a concurrent update.\n */\nexport const v3UpdateWorkflow = <ThrowOnError extends boolean = false>(options: Options<V3UpdateWorkflowData, ThrowOnError>): RequestResult<V3UpdateWorkflowResponses, V3UpdateWorkflowErrors, ThrowOnError> => (options.client ?? client).patch<V3UpdateWorkflowResponses, V3UpdateWorkflowErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Upload a document (+ ground truth) to a workflow dataset\n *\n * Upload one document (1..N files) plus optional ground truth as ONE\n * document packet in the dataset (atomic).\n *\n * All-or-nothing: any rejected file (unsupported type, disguised bytes) or a\n * ground-truth failure fails the whole request and nothing is stored.\n *\n * Filenames are unique within a workflow. By default (`on_conflict=error`) a\n * file whose name collides with an existing file fails the request with `409`\n * before anything is uploaded; pass `on_conflict=rename` to auto-rename the\n * collision instead (`invoice.pdf` -> `invoice (1).pdf`), each returned file's\n * ``name`` being the name it landed under and ``original_name`` holding the\n * uploaded name when a rename happened.\n *\n * Bulk ingestion loops this endpoint, one call per document; each call is\n * bounded and independently retryable.\n */\nexport const v3UploadToDataset = <ThrowOnError extends boolean = false>(options: Options<V3UploadToDatasetData, ThrowOnError>): RequestResult<V3UploadToDatasetResponses, V3UploadToDatasetErrors, ThrowOnError> => (options.client ?? client).post<V3UploadToDatasetResponses, V3UploadToDatasetErrors, ThrowOnError>({\n ...formDataBodySerializer,\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/dataset/upload/',\n ...options,\n headers: {\n 'Content-Type': null,\n ...options.headers\n }\n});\n\n/**\n * List workflow document packets\n *\n * List a workflow's document packets, newest first.\n *\n * Keyset-paginated: follow `next_cursor` until it is `null`. The sort\n * order is fixed (`-created_at, -id`); there are no totals or page\n * numbers. Items are slim — fetch\n * `GET /v3/document-packets/{document_packet_id}/` for the per-file\n * breakdown and `latest_run_id`.\n */\nexport const v3ListWorkflowDocumentPackets = <ThrowOnError extends boolean = false>(options: Options<V3ListWorkflowDocumentPacketsData, ThrowOnError>): RequestResult<V3ListWorkflowDocumentPacketsResponses, V3ListWorkflowDocumentPacketsErrors, ThrowOnError> => (options.client ?? client).get<V3ListWorkflowDocumentPacketsResponses, V3ListWorkflowDocumentPacketsErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/document-packets/',\n ...options\n});\n\n/**\n * List a workflow's reference documents\n *\n * List the reference documents on a workflow, with their parse status.\n *\n * Poll this after uploading a PDF reference until its `status` leaves\n * `pending`.\n */\nexport const v3ListEditReferences = <ThrowOnError extends boolean = false>(options: Options<V3ListEditReferencesData, ThrowOnError>): RequestResult<V3ListEditReferencesResponses, V3ListEditReferencesErrors, ThrowOnError> => (options.client ?? client).get<V3ListEditReferencesResponses, V3ListEditReferencesErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/edit-references/',\n ...options\n});\n\n/**\n * Upload reference documents to a workflow\n *\n * Upload the standing data an Edit node fills forms from.\n *\n * Returns one document per file, each with the `id` to put in an Edit node's\n * `reference_document_ids`.\n *\n * A text reference is usable immediately (`status: ready`). A PDF is parsed\n * once, here — never on a run — so it comes back `pending` and reaches\n * `ready` shortly after; poll `GET /v3/workflows/{workflow_id}/edit-references/`\n * until it settles. Starting a run whose Edit node names a reference that is\n * not yet `ready` is refused rather than filled from a partial reference.\n *\n * Upload once, reuse forever: every later run reads the already-parsed text,\n * so the parse is neither repeated nor re-billed.\n */\nexport const v3UploadEditReferences = <ThrowOnError extends boolean = false>(options: Options<V3UploadEditReferencesData, ThrowOnError>): RequestResult<V3UploadEditReferencesResponses, V3UploadEditReferencesErrors, ThrowOnError> => (options.client ?? client).post<V3UploadEditReferencesResponses, V3UploadEditReferencesErrors, ThrowOnError>({\n ...formDataBodySerializer,\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/edit-references/',\n ...options,\n headers: {\n 'Content-Type': null,\n ...options.headers\n }\n});\n\n/**\n * Delete a reference document\n *\n * Delete a reference document and its stored objects.\n *\n * An Edit node still naming the deleted id will refuse to run rather than\n * fill from a reference that no longer exists — remove the id from the node\n * in the same change.\n */\nexport const v3DeleteEditReference = <ThrowOnError extends boolean = false>(options: Options<V3DeleteEditReferenceData, ThrowOnError>): RequestResult<V3DeleteEditReferenceResponses, V3DeleteEditReferenceErrors, ThrowOnError> => (options.client ?? client).delete<V3DeleteEditReferenceResponses, V3DeleteEditReferenceErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/edit-references/{document_id}/',\n ...options\n});\n\n/**\n * List evals\n *\n * List a workflow's evals, newest first.\n *\n * Keyset-paginated: follow `next_cursor` until it is `null`. The sort order is\n * fixed (`-created_at, -id`); there are no totals or page numbers. Each item is\n * the same headline `GET /v3/workflows/{workflow_id}/evals/{eval_id}/` returns.\n *\n * An unknown or cross-org workflow returns 404.\n */\nexport const v3ListEvals = <ThrowOnError extends boolean = false>(options: Options<V3ListEvalsData, ThrowOnError>): RequestResult<V3ListEvalsResponses, V3ListEvalsErrors, ThrowOnError> => (options.client ?? client).get<V3ListEvalsResponses, V3ListEvalsErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/evals/',\n ...options\n});\n\n/**\n * Launch an eval\n *\n * Launch an eval over a workflow's whole dataset (async, fire-and-forget).\n *\n * Enqueues one fresh extraction per dataset document on the target version and\n * pins the realized cohort into a new eval, then returns `202` immediately with\n * `eval_id` and `run_number` to poll. Grading finalizes on a worker path — read\n * the eval by `eval_id` for the headline once it leaves `in_progress`.\n *\n * Without an `Idempotency-Key` every launch creates a NEW eval — re-launching\n * runs a fresh cohort. Supplying the header replays: a retry with the same key\n * returns the original eval instead of launching a second run. Omit `version_id`\n * to evaluate the workflow's current version; pass one to override. (With an\n * omitted version, a replayed key sent after a new version was published targets\n * a different version than the first call, so the backend answers `422` for the\n * key reuse — pass an explicit `version_id` for a stable replay.)\n *\n * A run that enqueues zero documents (empty dataset, or every document failed\n * to enqueue) creates no eval and returns `422 EMPTY_EVAL`.\n */\nexport const v3LaunchEval = <ThrowOnError extends boolean = false>(options: Options<V3LaunchEvalData, ThrowOnError>): RequestResult<V3LaunchEvalResponses, V3LaunchEvalErrors, ThrowOnError> => (options.client ?? client).post<V3LaunchEvalResponses, V3LaunchEvalErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/evals/',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Get eval\n *\n * Retrieve one eval's frozen headline — poll this until `status` leaves\n * `in_progress`.\n *\n * `accuracy`, `matched`, `mismatched` and `ungraded` are `null` while the eval\n * is `in_progress`; `accuracy` also stays `null` on a `processed` eval with a 0\n * graded denominator. `id` here equals the launch's `eval_id`.\n *\n * An unknown eval, or one on another workflow or organization, returns 404\n * (existence never leaks).\n */\nexport const v3GetEval = <ThrowOnError extends boolean = false>(options: Options<V3GetEvalData, ThrowOnError>): RequestResult<V3GetEvalResponses, V3GetEvalErrors, ThrowOnError> => (options.client ?? client).get<V3GetEvalResponses, V3GetEvalErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/evals/{eval_id}/',\n ...options\n});\n\n/**\n * Ask a question about a workflow's documents\n *\n * Answer a question from the content of this workflow's documents.\n *\n * The answer is grounded: every claim comes back with the exact quote it\n * rests on, resolved to a page and a region in the source PDF, so you can\n * show a customer where a number came from instead of asking them to trust\n * it. `path` reports the route the agent took to get there.\n *\n * The workflow needs a knowledge node — that is what indexes its documents.\n * Without one this returns 409.\n *\n * Billed per question against the organization's credits, on the text the\n * agent actually reads. A question the organization cannot pay for is\n * refused before it runs, not after.\n *\n * Pass a `thread_id` you mint yourself (starting with `kb-`) to ask a\n * follow-up in context; omit it and each question stands alone.\n */\nexport const v3AskKnowledge = <ThrowOnError extends boolean = false>(options: Options<V3AskKnowledgeData, ThrowOnError>): RequestResult<V3AskKnowledgeResponses, V3AskKnowledgeErrors, ThrowOnError> => (options.client ?? client).post<V3AskKnowledgeResponses, V3AskKnowledgeErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/knowledge/ask',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * List a workflow's knowledge corpus\n *\n * List a workflow's knowledge corpus tree: source documents plus the\n * generated navigation pages, sorted by path. Needs a knowledge node\n * (409 otherwise); see `folder`/`cursor` and knowledge/list.mdx for the\n * rest.\n */\nexport const v3ListKnowledge = <ThrowOnError extends boolean = false>(options: Options<V3ListKnowledgeData, ThrowOnError>): RequestResult<V3ListKnowledgeResponses, V3ListKnowledgeErrors, ThrowOnError> => (options.client ?? client).get<V3ListKnowledgeResponses, V3ListKnowledgeErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/knowledge/entries',\n ...options\n});\n\n/**\n * Read one document from a workflow's knowledge corpus\n *\n * Read one document's or navigation page's text from a workflow's\n * knowledge corpus.\n *\n * The workflow needs a knowledge node — that is what indexes its\n * documents. Without one this returns 409. An unknown `path` is a 404 —\n * list entries with `list_knowledge` or find one with `search_knowledge`\n * first.\n *\n * `content` is capped; `truncated` is `true` when it was cut off.\n */\nexport const v3ReadKnowledge = <ThrowOnError extends boolean = false>(options: Options<V3ReadKnowledgeData, ThrowOnError>): RequestResult<V3ReadKnowledgeResponses, V3ReadKnowledgeErrors, ThrowOnError> => (options.client ?? client).get<V3ReadKnowledgeResponses, V3ReadKnowledgeErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/knowledge/entry',\n ...options\n});\n\n/**\n * Search a workflow's knowledge corpus\n *\n * Rank a workflow's knowledge corpus by relevance (BM25) to `query`.\n * Needs a knowledge node (409 otherwise); see `query`/`folder`/`limit`\n * and knowledge/search.mdx for the rest.\n */\nexport const v3SearchKnowledge = <ThrowOnError extends boolean = false>(options: Options<V3SearchKnowledgeData, ThrowOnError>): RequestResult<V3SearchKnowledgeResponses, V3SearchKnowledgeErrors, ThrowOnError> => (options.client ?? client).get<V3SearchKnowledgeResponses, V3SearchKnowledgeErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/knowledge/search',\n ...options\n});\n\n/**\n * Get a presigned URL for a workflow's whole knowledge corpus\n *\n * Get a presigned URL for the whole knowledge corpus tar.\n *\n * Possession of the URL is read permission for the workflow's corpus\n * until it expires — prefer `list_knowledge`/`read_knowledge` for\n * anything that stays inside this API; this is for handing the whole\n * archive to something outside it.\n */\nexport const v3DownloadKnowledge = <ThrowOnError extends boolean = false>(options: Options<V3DownloadKnowledgeData, ThrowOnError>): RequestResult<V3DownloadKnowledgeResponses, V3DownloadKnowledgeErrors, ThrowOnError> => (options.client ?? client).get<V3DownloadKnowledgeResponses, V3DownloadKnowledgeErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/knowledge/snapshot',\n ...options\n});\n\n/**\n * List workflow runs\n *\n * List a workflow's runs, newest first.\n *\n * Keyset-paginated: follow `next_cursor` until it is `null`. The sort\n * order is fixed (`-created_at, -id`); there are no totals or page\n * numbers. Items are slim — fetch `GET /v3/runs/{run_id}/` for the\n * results.\n *\n * Optional half-open interval on the packet's `created_at`:\n * `document_packet_created_after` (inclusive) /\n * `document_packet_created_before` (exclusive). Typical daily-batch\n * workflow: upload day N, fetch day N+1 with\n * `after=<N>T00:00:00 & before=<N+1>T00:00:00`.\n */\nexport const v3ListWorkflowRuns = <ThrowOnError extends boolean = false>(options: Options<V3ListWorkflowRunsData, ThrowOnError>): RequestResult<V3ListWorkflowRunsResponses, V3ListWorkflowRunsErrors, ThrowOnError> => (options.client ?? client).get<V3ListWorkflowRunsResponses, V3ListWorkflowRunsErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/runs/',\n ...options\n});\n\n/**\n * Upload document packet to workflow\n *\n * Upload one or more files as a single document packet (atomic).\n *\n * All files are grouped into ONE packet — the unit later runs address.\n * Creation is all-or-nothing: any rejected file (unsupported type,\n * disguised bytes) fails the whole request and nothing is stored.\n *\n * Filenames are unique within a workflow. By default (`on_conflict=error`) a\n * file whose name collides with an existing file fails the request with\n * ``409`` before anything is uploaded; pass `on_conflict=rename` to auto-rename\n * the collision instead (`contract.pdf` -> `contract (1).pdf`); each returned\n * file's ``name`` is then the name it landed under, with ``original_name``\n * holding the uploaded name when a rename happened.\n *\n * Upload without running; trigger extraction via\n * `POST /v3/document-packets/{document_packet_id}/run/`.\n */\nexport const v3UploadToWorkflow = <ThrowOnError extends boolean = false>(options: Options<V3UploadToWorkflowData, ThrowOnError>): RequestResult<V3UploadToWorkflowResponses, V3UploadToWorkflowErrors, ThrowOnError> => (options.client ?? client).post<V3UploadToWorkflowResponses, V3UploadToWorkflowErrors, ThrowOnError>({\n ...formDataBodySerializer,\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/upload/',\n ...options,\n headers: {\n 'Content-Type': null,\n ...options.headers\n }\n});\n\n/**\n * Create document packet from URLs\n *\n * Import every URL into a single document packet, atomically.\n *\n * The backend fetches each HTTPS URL server-side (10s timeout, 20 MB cap\n * per file) and registers the packet in one transaction only after every\n * fetch succeeded — any failure imports nothing (no partial packet, no\n * orphan files).\n *\n * Files arrive as fetchable `urls`, as `staged_files` ids from\n * `POST /v3/blobs/slots/`, or a mix (1..10 in total); staged files land\n * after the `urls` entries.\n *\n * Each URL-fetched file is named by its response's `Content-Disposition`\n * filename when present, else by the last segment of the URL's path. A\n * presigned URL can sign the header in (S3: `ResponseContentDisposition`),\n * which is how a caller names a file whose URL path is opaque. A staged file\n * is named by its `filename`.\n *\n * Filenames are unique within a workflow. By default (`on_conflict=error`)\n * a colliding filename fails the request with ``409`` — surfaced once\n * the atomic import settles, not before it starts; pass `on_conflict=rename`\n * to auto-rename instead (``report.pdf`` -> ``report (1).pdf``). Each returned\n * `name` is the name the file actually landed under; ``original_name`` holds\n * the name it was fetched under when a rename happened.\n */\nexport const v3UploadFromUrl = <ThrowOnError extends boolean = false>(options: Options<V3UploadFromUrlData, ThrowOnError>): RequestResult<V3UploadFromUrlResponses, V3UploadFromUrlErrors, ThrowOnError> => (options.client ?? client).post<V3UploadFromUrlResponses, V3UploadFromUrlErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/upload/from-url/',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * Upload and run workflow\n *\n * Upload one document packet and run it in a single call.\n *\n * Composes `POST /v3/workflows/{workflow_id}/upload/` and\n * `POST /v3/document-packets/{document_packet_id}/run/`: the files are\n * grouped into ONE packet (all-or-nothing) and an extraction is enqueued\n * on the workflow's latest version. Poll `GET /v3/runs/{run_id}/` until\n * `status` is terminal.\n *\n * Filenames are unique within a workflow. By default (`on_conflict=error`) a\n * colliding filename fails the request with ``409`` before anything is\n * uploaded or run; pass `on_conflict=rename` to auto-rename instead.\n */\nexport const v3UploadAndRunWorkflow = <ThrowOnError extends boolean = false>(options: Options<V3UploadAndRunWorkflowData, ThrowOnError>): RequestResult<V3UploadAndRunWorkflowResponses, V3UploadAndRunWorkflowErrors, ThrowOnError> => (options.client ?? client).post<V3UploadAndRunWorkflowResponses, V3UploadAndRunWorkflowErrors, ThrowOnError>({\n ...formDataBodySerializer,\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/upload/run/',\n ...options,\n headers: {\n 'Content-Type': null,\n ...options.headers\n }\n});\n\n/**\n * List workflow versions\n *\n * List a workflow's versions, newest first.\n *\n * Versions are read-only: they exist for comparison and audit, and runs\n * always use the latest version (item 0 of the first page). Read a\n * version's graph with `GET /v3/workflows/{workflow_id}/?version=`.\n *\n * Keyset-paginated: follow `next_cursor` until it is `null`. The sort\n * order is fixed (`-created_at, -id`); there are no totals or page numbers.\n */\nexport const v3ListWorkflowVersions = <ThrowOnError extends boolean = false>(options: Options<V3ListWorkflowVersionsData, ThrowOnError>): RequestResult<V3ListWorkflowVersionsResponses, V3ListWorkflowVersionsErrors, ThrowOnError> => (options.client ?? client).get<V3ListWorkflowVersionsResponses, V3ListWorkflowVersionsErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/v3/workflows/{workflow_id}/versions/',\n ...options\n});\n","import { Result } from \"./result\";\nimport {\n AnyformatError,\n ExtractionCancelledError,\n ExtractionFailedError,\n parseRetryAfter,\n SDKTimeoutError,\n toApiError,\n} from \"./errors\";\nimport { v3GetRun } from \"./sdk\";\nimport type { RunStatus } from \"./sdk\";\nimport type { Client as HeyClient } from \"./sdk/client\";\n\nexport interface WaitOptions {\n /** Overall budget before giving up. Default 300 000 ms (300s). */\n timeoutMs?: number;\n /** Delay between status polls. Default 3 000 ms (3s). */\n pollMs?: number;\n}\n\n/** A 429/5xx during polling is transient — a short spike must not abort a long wait(). */\nfunction isTransientStatus(status: number): boolean {\n return status === 429 || status >= 500;\n}\n\nconst RETRY_BASE_MS = 1_000;\nconst RETRY_MAX_MS = 30_000;\n\n/**\n * Backoff before re-polling after a transient failure: honour `Retry-After`\n * (delay-seconds or HTTP-date, RFC 7231 §7.1.3), else jittered exponential.\n */\nfunction retryDelayMs(response: Response | undefined, attempt: number): number {\n const retryAfter = parseRetryAfter(response?.headers?.get(\"Retry-After\"));\n if (retryAfter !== undefined) return Math.min(retryAfter * 1_000, RETRY_MAX_MS);\n const base = Math.min(RETRY_BASE_MS * 2 ** attempt, RETRY_MAX_MS);\n return base * (0.75 + Math.random() * 0.5); // ±25 % jitter so retry waves don't re-collide\n}\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * One execution attempt of a workflow against a document packet. Created\n * eagerly by the run triggers — the extraction is already enqueued by the\n * time you hold a `Run`. `wait()` polls `GET /v3/runs/{run_id}/` until the\n * status is terminal and returns the inline results.\n */\nexport class Run {\n /** Status at trigger time, refreshed on every `wait()` poll. */\n status: RunStatus;\n\n /** @internal */\n constructor(\n private readonly client: HeyClient,\n readonly id: string,\n readonly workflowId: string,\n readonly documentPacketId: string,\n status: RunStatus = \"queued\",\n ) {\n this.status = status;\n }\n\n async wait(opts: WaitOptions = {}): Promise<Result> {\n const timeoutMs = opts.timeoutMs ?? 300_000;\n const pollMs = opts.pollMs ?? 3_000;\n const deadline = Date.now() + timeoutMs;\n let transientFailures = 0;\n\n for (;;) {\n const res = await v3GetRun({ client: this.client, path: { run_id: this.id } });\n if (res.error) {\n const status = res.response?.status ?? 500;\n if (!isTransientStatus(status)) throw toApiError(status, res.error, res.response?.headers);\n const remainingMs = deadline - Date.now();\n if (remainingMs <= 0) {\n throw new SDKTimeoutError(`Extraction did not complete within ${timeoutMs}ms`);\n }\n // Cap so a long ``Retry-After`` on a near-deadline poll can't sleep\n // past the caller's timeout before raising.\n await sleep(Math.min(retryDelayMs(res.response, transientFailures), remainingMs));\n transientFailures += 1;\n continue;\n }\n transientFailures = 0;\n const detail = res.data!;\n this.status = detail.status;\n\n if (detail.status === \"processed\") {\n if (!detail.results) {\n throw new AnyformatError(`Run ${this.id} is processed but the API returned no results`);\n }\n return new Result(detail.results);\n }\n if (detail.status === \"error\") throw new ExtractionFailedError(this.id);\n if (detail.status === \"cancelled\") throw new ExtractionCancelledError(this.id);\n if (Date.now() >= deadline) {\n throw new SDKTimeoutError(`Extraction did not complete within ${timeoutMs}ms`);\n }\n await sleep(pollMs);\n }\n }\n}\n","import { Run } from \"./run\";\nimport { toApiError } from \"./errors\";\nimport { v3RunDocumentPacket } from \"./sdk\";\nimport type { DatasetUploadFileV3, DocumentPacketFileV3 } from \"./sdk\";\nimport type { Client as HeyClient } from \"./sdk/client\";\n\nexport interface RunTriggerOptions {\n /**\n * Caller-supplied key (Stripe convention). Retrying with the same key\n * returns the original run instead of triggering (and billing) a second\n * extraction.\n */\n idempotencyKey?: string;\n}\n\n/**\n * Options for the methods that stage an upload (`Workflow.run`,\n * `Workflow.upload`). Adds the filename-conflict policy on top of the\n * run-trigger options — it only applies where files are actually uploaded,\n * which is why the run-only paths (`Upload.run`, `Anyformat.runDocumentPacket`)\n * take {@link RunTriggerOptions} instead and don't accept it.\n */\nexport interface UploadOptions extends RunTriggerOptions {\n /**\n * How the server resolves an uploaded filename that already exists in the\n * workflow (filenames are unique within a workflow). `\"error\"` (the server\n * default) rejects the whole upload with `409`; `\"rename\"` auto-renames\n * (`invoice.pdf` → `invoice (1).pdf`). Omit to use the server default.\n */\n onConflict?: \"error\" | \"rename\";\n}\n\n/**\n * Options for URL imports. The server derives the filename from each URL, so\n * there is no idempotency key — only the conflict policy applies.\n */\nexport interface UploadFromUrlsOptions {\n /** See {@link UploadOptions.onConflict}. Omit to use the server default. */\n onConflict?: \"error\" | \"rename\";\n}\n\n/**\n * Options for a dataset upload (`Workflow.uploadToDataset`), mirroring the\n * regular upload's conflict policy.\n */\nexport interface DatasetUploadOptions {\n /**\n * The expected document (ground truth) for this document packet, as a plain\n * object — the SDK JSON-encodes it for the multipart field. Keys are the\n * workflow schema's field identifiers (advertise `persistent_id`); a scalar\n * field maps to `string | null`, a table/object field to an array of row\n * objects. Ground truth attaches to the workflow's current version.\n */\n groundTruth?: Record<string, unknown> | null;\n /**\n * Caller-supplied key (Stripe convention). Retrying with the same key\n * replays the original document packet instead of registering a duplicate\n * document.\n */\n idempotencyKey?: string;\n /**\n * Filename-collision policy. Omit to use the server default (`error`): a\n * colliding name fails with `409`. `rename` auto-renames the collision and\n * the returned file's `original_name` holds the name you sent.\n */\n onConflict?: \"error\" | \"rename\";\n}\n\n/**\n * One document for a bulk dataset upload: 1..100 files plus optional\n * ground truth. Mirrors the arguments of `Workflow.uploadToDataset`.\n */\nexport interface DatasetDocument {\n /** 1..10 named files forming ONE document (one document packet in the dataset). */\n files: File | File[];\n /** See {@link DatasetUploadOptions.groundTruth}. */\n groundTruth?: Record<string, unknown> | null;\n /** See {@link DatasetUploadOptions.idempotencyKey}. */\n idempotencyKey?: string;\n /** See {@link DatasetUploadOptions.onConflict}. */\n onConflict?: \"error\" | \"rename\";\n}\n\n/**\n * One document registered into a workflow's dataset as one\n * document packet. Returned by `Workflow.uploadToDataset()`. `documentPacketId` is the\n * stable handle for the document; `groundTruthSaved` is `true` only when\n * ground truth was supplied and stored.\n */\nexport class DatasetUpload {\n /** @internal */\n constructor(\n readonly workflowId: string,\n readonly documentPacketId: string,\n readonly files: DatasetUploadFileV3[],\n readonly groundTruthSaved: boolean,\n ) {}\n}\n\n/**\n * A document packet staged in a workflow but not yet run. Returned by\n * `Workflow.upload()` / `Workflow.uploadFromUrls()`. Call `run()` to start\n * extraction — uploading alone spends no credits.\n */\nexport class Upload {\n /** @internal */\n constructor(\n private readonly client: HeyClient,\n readonly workflowId: string,\n readonly documentPacketId: string,\n readonly files: DocumentPacketFileV3[],\n ) {}\n\n /** Trigger extraction on the staged packet and return a pending `Run`. */\n async run(opts: RunTriggerOptions = {}): Promise<Run> {\n const res = await v3RunDocumentPacket({\n client: this.client,\n path: { document_packet_id: this.documentPacketId },\n ...(opts.idempotencyKey ? { headers: { \"Idempotency-Key\": opts.idempotencyKey } } : {}),\n });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n const data = res.data!;\n return new Run(this.client, data.run_id, data.workflow_id, data.document_packet_id, data.status);\n }\n}\n","import { Run } from \"./run\";\nimport { DatasetUpload, Upload } from \"./upload\";\nimport type { DatasetDocument, DatasetUploadOptions, UploadFromUrlsOptions, UploadOptions } from \"./upload\";\nimport { toApiError, WorkflowBuilderError } from \"./errors\";\nimport { v3UploadAndRunWorkflow, v3UploadFromUrl, v3UploadToDataset, v3UploadToWorkflow } from \"./sdk\";\nimport type { Client as HeyClient } from \"./sdk/client\";\n\nconst MAX_FILES_PER_PACKET = 100;\n\n/** Enforce the named-file requirement shared by run/upload, per file. */\nfunction normalizeFiles(files: File | File[] | null | undefined, op: string): File[] {\n const list = files == null ? [] : Array.isArray(files) ? files : [files];\n if (list.length === 0) {\n throw new WorkflowBuilderError(`${op}() requires at least one named file`);\n }\n if (list.length > MAX_FILES_PER_PACKET) {\n throw new WorkflowBuilderError(`${op}() accepts at most ${MAX_FILES_PER_PACKET} files per document packet`);\n }\n for (const file of list) {\n // A nameless file uploads as application/octet-stream, so the worker can't\n // detect its type. Duck-typed on `.name` since `File` isn't a Node 18 global.\n const filename = (file as { name?: unknown }).name;\n if (typeof filename !== \"string\" || filename.length === 0) {\n throw new WorkflowBuilderError(\n `${op}() needs a named file so the server can detect its type — pass a File, e.g. new File([bytes], \"invoice.pdf\"), not a bare Blob`,\n );\n }\n }\n return list;\n}\n\n/**\n * A persisted workflow on the server. Returned by `WorkflowBuilder.create()`.\n * `run(files)` uploads a document packet and starts extraction, returning a\n * `Run` you can `.wait()` on. `upload(files)` stages a packet without\n * running it; call `.run()` on the returned `Upload` to extract.\n */\nexport class Workflow {\n /** @internal */\n constructor(\n private readonly client: HeyClient,\n readonly id: string,\n readonly name: string,\n ) {}\n\n /** Upload 1..100 files as one document packet and run it. Returns a pending `Run`. */\n async run(files: File | File[] | null = null, opts: UploadOptions = {}): Promise<Run> {\n const list = normalizeFiles(files, \"run\");\n const submitted = await v3UploadAndRunWorkflow({\n client: this.client,\n path: { workflow_id: this.id },\n body: { files: list, ...(opts.onConflict ? { on_conflict: opts.onConflict } : {}) },\n ...(opts.idempotencyKey ? { headers: { \"Idempotency-Key\": opts.idempotencyKey } } : {}),\n });\n if (submitted.error) throw toApiError(submitted.response?.status ?? 500, submitted.error, submitted.response?.headers);\n const data = submitted.data!;\n return new Run(this.client, data.run_id, data.workflow_id, data.document_packet_id, data.status);\n }\n\n /**\n * Stage 1..100 files as one document packet WITHOUT running it (no credits\n * spent). Returns an `Upload`; call `.run()` on it to start extraction.\n */\n async upload(files: File | File[] | null = null, opts: UploadOptions = {}): Promise<Upload> {\n const list = normalizeFiles(files, \"upload\");\n const staged = await v3UploadToWorkflow({\n client: this.client,\n path: { workflow_id: this.id },\n body: { files: list, ...(opts.onConflict ? { on_conflict: opts.onConflict } : {}) },\n ...(opts.idempotencyKey ? { headers: { \"Idempotency-Key\": opts.idempotencyKey } } : {}),\n });\n if (staged.error) throw toApiError(staged.response?.status ?? 500, staged.error, staged.response?.headers);\n const data = staged.data!;\n return new Upload(this.client, data.workflow_id, data.document_packet_id, data.files);\n }\n\n /**\n * Upload 1..100 files as ONE document (+ optional ground truth) into the\n * workflow's dataset, as one document packet. Atomic: any rejected file or a\n * ground-truth failure fails the call and stores nothing. By default a\n * colliding filename fails with `409`; pass `onConflict: \"rename\"` to\n * auto-rename instead.\n */\n async uploadToDataset(files: File | File[] | null = null, opts: DatasetUploadOptions = {}): Promise<DatasetUpload> {\n const list = normalizeFiles(files, \"uploadToDataset\");\n const registered = await v3UploadToDataset({\n client: this.client,\n path: { workflow_id: this.id },\n body: {\n files: list,\n ...(opts.groundTruth != null ? { ground_truth: JSON.stringify(opts.groundTruth) } : {}),\n ...(opts.onConflict ? { on_conflict: opts.onConflict } : {}),\n },\n ...(opts.idempotencyKey ? { headers: { \"Idempotency-Key\": opts.idempotencyKey } } : {}),\n });\n if (registered.error) throw toApiError(registered.response?.status ?? 500, registered.error, registered.response?.headers);\n const data = registered.data!;\n return new DatasetUpload(this.id, data.document_packet_id, data.files, data.ground_truth_saved);\n }\n\n /**\n * Client-orchestrated bulk dataset upload: one atomic call per document,\n * in order. There is no batch endpoint — each document is bounded and\n * independently retryable. On failure the call rejects; documents already\n * uploaded stay registered.\n */\n async uploadDocumentsToDataset(documents: DatasetDocument[]): Promise<DatasetUpload[]> {\n const uploaded: DatasetUpload[] = [];\n for (const doc of documents) {\n uploaded.push(\n await this.uploadToDataset(doc.files, {\n groundTruth: doc.groundTruth,\n idempotencyKey: doc.idempotencyKey,\n onConflict: doc.onConflict,\n }),\n );\n }\n return uploaded;\n }\n\n /**\n * Import 1..10 HTTPS URLs server-side into one document packet, atomically.\n * Returns an `Upload`; call `.run()` on it to start extraction.\n */\n async uploadFromUrls(urls: string[], opts: UploadFromUrlsOptions = {}): Promise<Upload> {\n const staged = await v3UploadFromUrl({\n client: this.client,\n path: { workflow_id: this.id },\n body: { urls, ...(opts.onConflict ? { on_conflict: opts.onConflict } : {}) },\n });\n if (staged.error) throw toApiError(staged.response?.status ?? 500, staged.error, staged.response?.headers);\n const data = staged.data!;\n return new Upload(this.client, data.workflow_id, data.document_packet_id, data.files);\n }\n}\n","import pkg from \"../package.json\" with { type: \"json\" };\nimport { WorkflowBuilder } from \"./builder\";\nimport { AnyformatError, ExtractionCancelledError, ExtractionFailedError, toApiError } from \"./errors\";\nimport { Run } from \"./run\";\nimport { DatasetUpload, Upload } from \"./upload\";\nimport type { DatasetDocument, DatasetUploadOptions, RunTriggerOptions, UploadOptions } from \"./upload\";\nimport {\n v3DeleteDocumentPacket,\n v3DeleteWorkflow,\n v3GetDocumentPacket,\n v3GetRun,\n v3GetWorkflow,\n v3ListWorkflowDocumentPackets,\n v3ListWorkflowRuns,\n v3ListWorkflows,\n v3Parse,\n v3RunDocumentPacket,\n v3UpdateWorkflow,\n} from \"./sdk\";\nimport type {\n DocumentPacketDetailV3,\n DocumentPacketSummaryV3,\n RunDetailV3,\n RunSummaryV3,\n WorkflowDetailV3,\n} from \"./sdk\";\nimport { createClient, createConfig } from \"./sdk/client\";\nimport type { Client as HeyClient } from \"./sdk/client\";\nimport { Workflow } from \"./workflow\";\n\n// ponytail: bundles full package.json (~1KB); esbuild lacks named JSON tree-shaking.\nexport const SDK_USER_AGENT = `anyformat-typescript-sdk-${pkg.version}`;\n\nexport interface AnyformatOptions {\n apiKey: string;\n /** Override the API base URL (defaults to production). */\n baseUrl?: string;\n}\n\n/** One keyset page. Follow `nextCursor` (pass it as `cursor`) until it is `null`. */\nexport interface Page<T> {\n items: T[];\n nextCursor: string | null;\n}\n\nexport interface ListOptions {\n /** Page size, capped at 100 by the API. */\n limit?: number;\n /** Opaque token from a previous page's `nextCursor`. */\n cursor?: string;\n}\n\nexport interface IterOptions {\n /** Page size the auto-pager fetches per underlying request, capped at 100 by the API. */\n limit?: number;\n}\n\n/**\n * The editable sub-shape of a workflow: exactly what `GET /v3/workflows/{id}/`\n * returns minus the read-only fields, and exactly what PATCH accepts — so a\n * fetched `WorkflowDetailV3` can be mutated and sent back as-is.\n */\nexport type WorkflowDefinition = Pick<WorkflowDetailV3, \"name\" | \"description\" | \"nodes\" | \"edges\">;\n\n/** Entry point. `new Anyformat({ apiKey }).workflow(\"name\").parse()...` */\nexport class Anyformat {\n /** @internal */\n readonly _client: HeyClient;\n\n constructor(opts: AnyformatOptions) {\n this._client = createClient(\n createConfig({\n baseUrl: opts.baseUrl ?? \"https://api.anyformat.ai\",\n auth: opts.apiKey,\n // Identifies the caller in our logs (Datadog facet). Plain HTTP callers\n // send no such header and are logged as origin \"api\". User-Agent is\n // ignored by browsers (forbidden header) but used by Node fetch.\n headers: {\n \"x-anyformat-origin\": \"js-sdk\",\n \"User-Agent\": SDK_USER_AGENT,\n },\n }),\n );\n }\n\n workflow(name: string, description?: string): WorkflowBuilder {\n return new WorkflowBuilder(this._client, name, description);\n }\n\n async listWorkflows(opts: ListOptions = {}): Promise<Page<Workflow>> {\n const res = await v3ListWorkflows({\n client: this._client,\n query: { limit: opts.limit, cursor: opts.cursor },\n });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return {\n items: res.data!.items.map((r) => new Workflow(this._client, r.id, r.name)),\n nextCursor: res.data!.next_cursor ?? null,\n };\n }\n\n /** Retrieve a workflow with its complete typed graph inline (round-trippable into `updateWorkflow`). */\n async getWorkflow(workflowId: string): Promise<WorkflowDetailV3> {\n const res = await v3GetWorkflow({ client: this._client, path: { workflow_id: workflowId } });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return res.data!;\n }\n\n /**\n * Replace a workflow's typed graph (atomic). Accepts the shape `getWorkflow`\n * returns — echo each field's `persistent_id` unchanged (including across\n * renames) to keep the field's identity; omit it for new fields.\n */\n async updateWorkflow(workflowId: string, definition: WorkflowDefinition): Promise<WorkflowDetailV3> {\n const res = await v3UpdateWorkflow({\n client: this._client,\n path: { workflow_id: workflowId },\n // The PATCH body forbids unknown keys, so a fetched detail's read-only\n // fields (id, timestamps) must not be forwarded.\n body: {\n name: definition.name,\n description: definition.description,\n nodes: definition.nodes,\n edges: definition.edges,\n },\n });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return res.data!;\n }\n\n async deleteWorkflow(workflowId: string): Promise<string> {\n const res = await v3DeleteWorkflow({\n client: this._client,\n path: { workflow_id: workflowId },\n });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return workflowId;\n }\n\n /** Stage 1..100 files as one document packet without running it. Returns an `Upload`. */\n upload(workflowId: string, files: File | File[], opts: UploadOptions = {}): Promise<Upload> {\n return new Workflow(this._client, workflowId, \"\").upload(files, opts);\n }\n\n /** Upload 1..100 files (+ optional ground truth) as one dataset collection. Returns a `DatasetUpload`. */\n uploadToDataset(\n workflowId: string,\n files: File | File[],\n opts: DatasetUploadOptions = {},\n ): Promise<DatasetUpload> {\n return new Workflow(this._client, workflowId, \"\").uploadToDataset(files, opts);\n }\n\n /** Bulk-upload documents into a workflow's dataset, one atomic call per document. */\n uploadDocumentsToDataset(workflowId: string, documents: DatasetDocument[]): Promise<DatasetUpload[]> {\n return new Workflow(this._client, workflowId, \"\").uploadDocumentsToDataset(documents);\n }\n\n async getDocumentPacket(documentPacketId: string): Promise<DocumentPacketDetailV3> {\n const res = await v3GetDocumentPacket({\n client: this._client,\n path: { document_packet_id: documentPacketId },\n });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return res.data!;\n }\n\n /** Delete a document packet and all its files. Irreversible. */\n async deleteDocumentPacket(documentPacketId: string): Promise<string> {\n const res = await v3DeleteDocumentPacket({\n client: this._client,\n path: { document_packet_id: documentPacketId },\n });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return documentPacketId;\n }\n\n /** Run (or re-run) a document packet on the latest version of its workflow. */\n async runDocumentPacket(documentPacketId: string, opts: RunTriggerOptions = {}): Promise<Run> {\n const res = await v3RunDocumentPacket({\n client: this._client,\n path: { document_packet_id: documentPacketId },\n ...(opts.idempotencyKey ? { headers: { \"Idempotency-Key\": opts.idempotencyKey } } : {}),\n });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n const data = res.data!;\n return new Run(this._client, data.run_id, data.workflow_id, data.document_packet_id, data.status);\n }\n\n async listDocumentPackets(workflowId: string, opts: ListOptions = {}): Promise<Page<DocumentPacketSummaryV3>> {\n const res = await v3ListWorkflowDocumentPackets({\n client: this._client,\n path: { workflow_id: workflowId },\n query: { limit: opts.limit, cursor: opts.cursor },\n });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return { items: res.data!.items, nextCursor: res.data!.next_cursor ?? null };\n }\n\n async listRuns(workflowId: string, opts: ListOptions = {}): Promise<Page<RunSummaryV3>> {\n const res = await v3ListWorkflowRuns({\n client: this._client,\n path: { workflow_id: workflowId },\n query: { limit: opts.limit, cursor: opts.cursor },\n });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return { items: res.data!.items, nextCursor: res.data!.next_cursor ?? null };\n }\n\n /**\n * Every workflow, following `nextCursor` across pages so no rows are silently\n * truncated. Lazy — each page is fetched on demand as the iterator advances.\n */\n async *iterWorkflows(opts: IterOptions = {}): AsyncIterableIterator<Workflow> {\n let cursor: string | undefined;\n for (;;) {\n const page = await this.listWorkflows({ limit: opts.limit, cursor });\n yield* page.items;\n if (page.nextCursor === null) return;\n cursor = page.nextCursor;\n }\n }\n\n /** Every document packet of a workflow, following `nextCursor` across pages. Lazy. */\n async *iterDocumentPackets(\n workflowId: string,\n opts: IterOptions = {},\n ): AsyncIterableIterator<DocumentPacketSummaryV3> {\n let cursor: string | undefined;\n for (;;) {\n const page = await this.listDocumentPackets(workflowId, { limit: opts.limit, cursor });\n yield* page.items;\n if (page.nextCursor === null) return;\n cursor = page.nextCursor;\n }\n }\n\n /** Every run of a workflow, following `nextCursor` across pages. Lazy. */\n async *iterRuns(workflowId: string, opts: IterOptions = {}): AsyncIterableIterator<RunSummaryV3> {\n let cursor: string | undefined;\n for (;;) {\n const page = await this.listRuns(workflowId, { limit: opts.limit, cursor });\n yield* page.items;\n if (page.nextCursor === null) return;\n cursor = page.nextCursor;\n }\n }\n\n /** Retrieve one run: lifecycle status plus results inline once `processed`. */\n async getRun(runId: string): Promise<RunDetailV3> {\n const res = await v3GetRun({ client: this._client, path: { run_id: runId } });\n if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return res.data!;\n }\n\n /**\n * Parse a document with the platform's atomic parse operation (fast lite\n * parse). Returns the run id; poll `getParseMarkdown(runId)` for the parsed\n * markdown.\n */\n async parse(file: Blob | File): Promise<string> {\n const res = await v3Parse({ client: this._client, body: { file } });\n if (res.error !== undefined) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);\n return res.data!.run_id;\n }\n\n /**\n * Poll a parse run. Returns the parsed markdown once the run is `processed`,\n * or `null` while it is still queued or in progress.\n */\n async getParseMarkdown(runId: string): Promise<string | null> {\n const run = await this.getRun(runId);\n if (run.status === \"processed\") {\n const markdown = run.results?.parse?.markdown;\n if (markdown == null) throw new AnyformatError(`Run ${runId} is processed but the API returned no results`);\n return markdown;\n }\n if (run.status === \"error\") throw new ExtractionFailedError(runId);\n if (run.status === \"cancelled\") throw new ExtractionCancelledError(runId);\n return null;\n }\n}\n","import type {\n BooleanField,\n DateField,\n DatetimeField,\n EnumField,\n EnumOption,\n ExtractionSchema,\n FloatField,\n IntegerField,\n MultiSelectField,\n ObjectField,\n StringField,\n} from \"./sdk\";\n\n/** Any extraction field — the discriminated union on `data_type`. */\nexport type Field = ExtractionSchema[\"fields\"][number];\n\n/**\n * A field that may appear inside an object. Excludes `object`: only one\n * level of nesting is supported, so objects cannot contain objects.\n */\nexport type NestedField = ObjectField[\"nested_fields\"][number];\n\ninterface FieldOpts {\n /**\n * How the field gets its value: `\"extraction\"` (from the document,\n * the default), `\"smart_lookup\"` (from the lookup file, always\n * overwrites) or `\"lookup_if_missing\"` (extracted too; the lookup only\n * fills it where extraction left no value).\n */\n source?: \"extraction\" | \"smart_lookup\" | \"lookup_if_missing\";\n /**\n * Server-assigned stable field identity from `GET /v3/workflows/{id}/`.\n * Echo it on updates — including across renames — to keep quality\n * metrics, ground truth and analytics attached to the field. Omit for\n * new fields.\n */\n persistentId?: string;\n}\n\nfunction withOpts<T extends object>(base: T, opts?: FieldOpts): T {\n return {\n ...base,\n ...(opts?.source && opts.source !== \"extraction\" ? { source: opts.source } : {}),\n ...(opts?.persistentId !== undefined ? { persistent_id: opts.persistentId } : {}),\n };\n}\n\n/**\n * Factory for extraction-schema fields — the TS mirror of the Python\n * `Schema` facade. Each method returns the typed wire model the API\n * validates against; the discriminator (`data_type`) is filled in for you.\n */\nexport const Schema = {\n string: (name: string, description: string, opts?: FieldOpts): StringField =>\n withOpts({ data_type: \"string\", name, description }, opts),\n integer: (name: string, description: string, opts?: FieldOpts): IntegerField =>\n withOpts({ data_type: \"integer\", name, description }, opts),\n float: (name: string, description: string, opts?: FieldOpts): FloatField =>\n withOpts({ data_type: \"float\", name, description }, opts),\n boolean: (name: string, description: string, opts?: FieldOpts): BooleanField =>\n withOpts({ data_type: \"boolean\", name, description }, opts),\n date: (name: string, description: string, opts?: FieldOpts): DateField =>\n withOpts({ data_type: \"date\", name, description }, opts),\n datetime: (name: string, description: string, opts?: FieldOpts): DatetimeField =>\n withOpts({ data_type: \"datetime\", name, description }, opts),\n enum: (name: string, description: string, options: EnumOption[], opts?: FieldOpts): EnumField =>\n withOpts({ data_type: \"enum\", name, description, enum_options: options }, opts),\n multiSelect: (name: string, description: string, options: EnumOption[], opts?: FieldOpts): MultiSelectField =>\n withOpts({ data_type: \"multi_select\", name, description, enum_options: options }, opts),\n object: (name: string, description: string, fields: NestedField[], opts?: FieldOpts): ObjectField =>\n withOpts({ data_type: \"object\", name, description, nested_fields: fields }, opts),\n option: (name: string, description: string): EnumOption => ({ name, description }),\n};\n"],"mappings":";AAAA;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,aAAe;AAAA,EACf,SAAW;AAAA,EACX,QAAU;AAAA,EACV,MAAQ;AAAA,EACR,MAAQ;AAAA,EACR,QAAU;AAAA,EACV,OAAS;AAAA,EACT,SAAW;AAAA,IACT,KAAK;AAAA,MACH,OAAS;AAAA,MACT,QAAU;AAAA,MACV,SAAW;AAAA,IACb;AAAA,EACF;AAAA,EACA,OAAS;AAAA,IACP;AAAA,EACF;AAAA,EACA,SAAW;AAAA,IACT,MAAQ;AAAA,EACV;AAAA,EACA,SAAW;AAAA,IACT,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,KAAO;AAAA,IACP,aAAa;AAAA,IACb,OAAS;AAAA,IAC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