@xberg-io/sdk 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["errorInit: ErrorOptions","options: XbergErrorOptions","payloads: string[]","TERMINAL_JOB_STATUSES: readonly JobStatus[]","SUCCESS_JOB_STATUSES: readonly JobStatus[]","DEFAULT_RETRY_STATUSES: readonly number[]","CRAWL_EVENT_KINDS: ReadonlySet<string>","extractParams: ExtractParams","waitOptions: WaitOptions","init: RequestParts","requestInit: RequestInit","response: Response","body: FormData | string | Uint8Array | undefined","body: unknown","headers: Record<string, string>"],"sources":["../src/errors.ts","../src/_internal.ts","../src/types.ts","../src/version.ts","../src/client.ts"],"sourcesContent":["/**\n * Error class hierarchy for the Xberg SDK (Enterprise + Pro).\n *\n * Every non-2xx HTTP response is mapped to a subclass of {@link XbergError}.\n * `TimeoutError` is also raised when {@link XbergClient.waitForJob} exceeds its\n * configured deadline (distinct from a network/fetch timeout).\n */\n\nexport interface XbergErrorOptions {\n status: number;\n body: unknown;\n cause?: unknown;\n}\n\nexport class XbergError extends Error {\n public readonly status: number;\n public readonly body: unknown;\n\n public constructor(message: string, options: XbergErrorOptions) {\n const errorInit: ErrorOptions = options.cause === undefined ? {} : { cause: options.cause };\n super(message, errorInit);\n this.name = \"XbergError\";\n this.status = options.status;\n this.body = options.body;\n }\n}\n\nexport class AuthError extends XbergError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"AuthError\";\n }\n}\n\nexport interface RateLimitErrorOptions extends XbergErrorOptions {\n retryAfter?: number;\n}\n\nexport class RateLimitError extends XbergError {\n public readonly retryAfter?: number;\n\n public constructor(message: string, options: RateLimitErrorOptions) {\n super(message, options);\n this.name = \"RateLimitError\";\n if (options.retryAfter !== undefined) {\n this.retryAfter = options.retryAfter;\n }\n }\n}\n\nexport class ValidationError extends XbergError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"ValidationError\";\n }\n}\n\nexport class NotFoundError extends XbergError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"NotFoundError\";\n }\n}\n\nexport class ServerError extends XbergError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"ServerError\";\n }\n}\n\nexport class TimeoutError extends XbergError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"TimeoutError\";\n }\n}\n\n/**\n * Map an HTTP response status to the matching error subclass and throw it.\n *\n * Always throws — call as `throw await raiseForStatus(response)` if you want\n * the type system to see the unreachable code, otherwise just `await`. Both\n * 401 and 403 map to {@link AuthError} — the API uses 403 for a\n * valid-but-forbidden principal.\n */\nexport async function raiseForStatus(response: Response): Promise<never> {\n const body = await readBody(response);\n const message = extractErrorMessage(body) ?? `Request failed with status ${response.status}`;\n const options: XbergErrorOptions = { status: response.status, body };\n\n if (response.status === 401 || response.status === 403) {\n throw new AuthError(message, options);\n }\n if (response.status === 404) {\n throw new NotFoundError(message, options);\n }\n if (response.status === 429) {\n const retryAfterRaw = response.headers.get(\"retry-after\");\n const retryAfter = parseRetryAfter(retryAfterRaw);\n const opts: RateLimitErrorOptions = retryAfter === undefined ? options : { ...options, retryAfter };\n throw new RateLimitError(message, opts);\n }\n if (response.status >= 400 && response.status < 500) {\n throw new ValidationError(message, options);\n }\n if (response.status >= 500) {\n throw new ServerError(message, options);\n }\n throw new XbergError(message, options);\n}\n\nasync function readBody(response: Response): Promise<unknown> {\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (contentType.includes(\"application/json\")) {\n try {\n return await response.json();\n } catch {\n return undefined;\n }\n }\n try {\n const text = await response.text();\n return text === \"\" ? undefined : text;\n } catch {\n return undefined;\n }\n}\n\nfunction extractErrorMessage(body: unknown): string | undefined {\n if (typeof body === \"string\" && body.length > 0) {\n return body;\n }\n if (body !== null && typeof body === \"object\") {\n const record = body as Record<string, unknown>;\n const error = record[\"error\"];\n if (typeof error === \"string\" && error.length > 0) {\n return error;\n }\n const message = record[\"message\"];\n if (typeof message === \"string\" && message.length > 0) {\n return message;\n }\n }\n return undefined;\n}\n\nfunction parseRetryAfter(value: string | null): number | undefined {\n if (value === null) {\n return undefined;\n }\n const seconds = Number(value);\n if (Number.isFinite(seconds) && seconds >= 0) {\n return seconds;\n }\n const parsed = Date.parse(value);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n const delta = Math.max(0, Math.ceil((parsed - Date.now()) / 1000));\n return delta;\n}\n","/**\n * Internal helpers for {@link XbergClient}: base-URL resolution, query-string\n * and backoff arithmetic, the file-to-`Blob` conversion the multipart request\n * paths need, and the event-stream frame decoder `streamCrawlEvents` reads its\n * response through. Not part of the public API — of the names here only\n * {@link FileLike} and {@link BackoffStrategy} are re-exported, via `client.ts`,\n * because they appear in public client signatures.\n */\n\nimport { XbergError } from \"./errors.js\";\n\nexport const DEFAULT_ENTERPRISE_BASE_URL = \"https://api.xberg.io\";\nexport const DEFAULT_RETRY_BACKOFF_CAP_MS = 30_000;\nexport const DEFAULT_BACKOFF_FACTOR = 2;\n\n/**\n * Caps an event-stream frame. The frames this endpoint sends are a few hundred\n * bytes; the cap exists so a server that never closes a frame cannot grow this\n * decoder without bound.\n *\n * It is applied twice, because one application does not cover the other: to the\n * pending line, so one endless line cannot fill memory, and to the running\n * total of a frame's `data:` fields, so an endless succession of shorter lines\n * never followed by the blank line that would close the frame cannot either.\n */\nexport const MAX_EVENT_STREAM_FRAME_BYTES = 1 << 20;\n\n/**\n * Backoff strategy for retries and `waitForJob` polling.\n *\n * - `exponential` — interval doubles after every attempt, capped at 30s.\n * - `constant` — interval stays the same on every attempt.\n */\nexport type BackoffStrategy = \"exponential\" | \"constant\";\n\n/** Which product the client targets. */\nexport type Target = \"enterprise\" | \"pro\";\n\n/** Query-string values accepted by the internal request engine. */\nexport type QueryParams = Record<string, string | number | undefined>;\n\n/** Anything the client accepts as an uploadable file. */\nexport type FileLike = File | Blob | Uint8Array | { name?: string; data: Blob | Uint8Array; mimeType?: string };\n\n/**\n * Resolve the effective base URL, enforcing that Pro requires an explicit one.\n */\nexport function resolveBaseUrl(baseUrl: string | undefined, target: Target | undefined): string {\n if (baseUrl !== undefined) {\n return baseUrl.replace(/\\/+$/, \"\");\n }\n if (target === \"pro\") {\n throw new XbergError(\n \"Xberg Pro has no default base URL (its spec ships no servers block); pass baseUrl pointing at your Pro instance.\",\n { status: 0, body: null },\n );\n }\n return DEFAULT_ENTERPRISE_BASE_URL;\n}\n\n/**\n * Resolve the base URL of the Enterprise control plane, defaulting to the data plane's.\n *\n * Enterprise runs the control plane (projects, API keys, integrations, RAG\n * config, members, invitations, managed webhooks, usage, analytics, billing) as\n * a second binary on its own origin; Pro serves it from the same one. The\n * default therefore has to be `baseUrl`, exactly as the console's\n * `NEXT_PUBLIC_BACKEND_API_URL` is same-origin unless set — anything else would\n * break every Pro control-plane call the moment this option existed.\n */\nexport function resolveControlPlaneBaseUrl(controlPlaneBaseUrl: string | undefined, baseUrl: string): string {\n if (controlPlaneBaseUrl !== undefined) {\n return controlPlaneBaseUrl.replace(/\\/+$/, \"\");\n }\n return baseUrl;\n}\n\nexport function defaultSleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\nexport function buildQueryString(params: QueryParams | undefined): string {\n if (params === undefined) {\n return \"\";\n }\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n search.append(key, String(value));\n }\n }\n const query = search.toString();\n return query.length > 0 ? `?${query}` : \"\";\n}\n\nexport function nextBackoffInterval(current: number, strategy: BackoffStrategy): number {\n if (strategy === \"constant\") {\n return current;\n }\n return Math.min(current * DEFAULT_BACKOFF_FACTOR, DEFAULT_RETRY_BACKOFF_CAP_MS);\n}\n\nexport function parseRetryAfterHeader(value: string | null): number | undefined {\n if (value === null) {\n return undefined;\n }\n const seconds = Number(value);\n if (Number.isFinite(seconds) && seconds >= 0) {\n return seconds;\n }\n const parsed = Date.parse(value);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n return Math.max(0, Math.ceil((parsed - Date.now()) / 1000));\n}\n\n/** Convert a {@link FileLike} input into a `Blob` plus best-guess filename. */\nexport function toBlob(file: FileLike): { blob: Blob; filename: string } {\n if (typeof File !== \"undefined\" && file instanceof File) {\n return { blob: file, filename: file.name };\n }\n if (file instanceof Blob) {\n return { blob: file, filename: \"upload.bin\" };\n }\n if (file instanceof Uint8Array) {\n return {\n blob: new Blob([blobBytes(file)], { type: \"application/octet-stream\" }),\n filename: \"upload.bin\",\n };\n }\n const wrapper = file;\n const name = wrapper.name ?? \"upload.bin\";\n const mimeType = wrapper.mimeType ?? guessMimeType(name);\n if (wrapper.data instanceof Blob) {\n return { blob: wrapper.data, filename: name };\n }\n return {\n blob: new Blob([blobBytes(wrapper.data)], { type: mimeType }),\n filename: name,\n };\n}\n\nfunction blobBytes(bytes: Uint8Array): Uint8Array<ArrayBuffer> {\n // ~keep Blob snapshots its input. A view avoids a second payload copy; shared backing requires an ordinary buffer.\n return bytes.buffer instanceof ArrayBuffer\n ? new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n : new Uint8Array(bytes);\n}\n\nfunction guessMimeType(filename: string): string {\n const lower = filename.toLowerCase();\n if (lower.endsWith(\".csv\")) {\n return \"text/csv\";\n }\n if (lower.endsWith(\".md\")) {\n return \"text/markdown\";\n }\n if (lower.endsWith(\".pdf\")) {\n return \"application/pdf\";\n }\n if (lower.endsWith(\".txt\")) {\n return \"text/plain\";\n }\n if (lower.endsWith(\".docx\")) {\n return \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\";\n }\n return \"application/octet-stream\";\n}\n\n/** Guess a display name for a file (used to populate `Job.filename`). */\nexport function describeFile(file: FileLike): string {\n if (typeof File !== \"undefined\" && file instanceof File) {\n return file.name;\n }\n if (file instanceof Blob || file instanceof Uint8Array) {\n return \"upload.bin\";\n }\n return file.name ?? \"upload.bin\";\n}\n\n/**\n * Incremental decoder for a `text/event-stream` body, fed the decoded text of\n * each network chunk.\n *\n * Implements the parts of the WHATWG event-stream parser this endpoint can\n * exercise. A frame is terminated by a *blank line*, not by a newline: its\n * payload is every `data:` field it carried, joined with `\\n`. Lines opening\n * with `:` are comments — the endpoint's 15s heartbeat is one — and\n * `event:`/`id:`/`retry:` fields are accepted and ignored. A single space\n * after a field's colon is framing, not value, so it is stripped.\n *\n * All of which is why this exists instead of `JSON.parse` per line: against a\n * server that happens to emit one compact frame per line the naive version\n * passes every test, then silently drops every multi-line payload and throws\n * on the first heartbeat against a real one. Chunk boundaries fall wherever\n * the network puts them, so lines are also reassembled here rather than\n * assumed to arrive whole.\n */\nexport class EventStreamDecoder {\n private buffer = \"\";\n private data: string[] = [];\n /** Running length of the frame being assembled, reset with `data` on dispatch. */\n private size = 0;\n\n /** Consume one chunk of decoded text, returning the payload of every frame it completed. */\n public push(chunk: string): string[] {\n this.buffer += chunk;\n const payloads: string[] = [];\n for (;;) {\n const boundary = this.nextLineBoundary();\n if (boundary === undefined) {\n if (this.buffer.length > MAX_EVENT_STREAM_FRAME_BYTES) {\n throw new XbergError(`Crawl event stream sent a line longer than ${MAX_EVENT_STREAM_FRAME_BYTES} bytes`, {\n status: 0,\n body: null,\n });\n }\n return payloads;\n }\n const line = this.buffer.slice(0, boundary.index);\n this.buffer = this.buffer.slice(boundary.index + boundary.width);\n const payload = this.feed(line);\n if (payload !== undefined) {\n payloads.push(payload);\n }\n }\n }\n\n /**\n * Locate the next `\\n`, `\\r\\n` or `\\r` in the buffer. A trailing `\\r` is\n * reported as \"no boundary yet\": it may be the first half of a `\\r\\n` the\n * network split across two chunks, and treating it as a terminator there\n * would dispatch a frame one line early.\n */\n private nextLineBoundary(): { index: number; width: number } | undefined {\n for (let index = 0; index < this.buffer.length; index += 1) {\n const character = this.buffer[index];\n if (character === \"\\n\") {\n return { index, width: 1 };\n }\n if (character === \"\\r\") {\n if (index === this.buffer.length - 1) {\n return undefined;\n }\n return { index, width: this.buffer[index + 1] === \"\\n\" ? 2 : 1 };\n }\n }\n return undefined;\n }\n\n /** Consume one terminator-stripped line, returning a payload if it completed a frame. */\n private feed(line: string): string | undefined {\n if (line === \"\") {\n return this.dispatch();\n }\n if (line.startsWith(\":\")) {\n return undefined;\n }\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n let value = colon === -1 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) {\n value = value.slice(1);\n }\n if (field === \"data\") {\n this.size += value.length + 1; // +1 for the \"\\n\" dispatch joins with\n if (this.size > MAX_EVENT_STREAM_FRAME_BYTES) {\n throw new XbergError(\n `Crawl event frame exceeded ${MAX_EVENT_STREAM_FRAME_BYTES} bytes before the stream closed it`,\n { status: 0, body: null },\n );\n }\n this.data.push(value);\n }\n return undefined;\n }\n\n /** Emit the buffered `data` payload, or nothing when the blank line closed no frame. */\n private dispatch(): string | undefined {\n if (this.data.length === 0) {\n return undefined;\n }\n const payload = this.data.join(\"\\n\");\n this.data = [];\n this.size = 0;\n return payload;\n }\n}\n\n/** Encode a path identifier without allowing the HTTP client to change its route. */\nexport function encodePathSegment(value: string): string {\n // ~keep WHATWG URL normalizes even percent-encoded dot segments, so encoding alone is insufficient.\n if (value === \".\" || value === \"..\") {\n throw new XbergError(\"Path identifiers must not be '.' or '..'\", { status: 400, body: null });\n }\n return encodeURIComponent(value);\n}\n","/**\n * Friendly re-exports of the independently generated API, Pro and backend schema sets.\n *\n * Shared and Enterprise-only types key off `_generated/api.d.ts` (the Xberg\n * Enterprise managed API); Pro-only response types key off\n * `_generated/pro.d.ts`; Backend-prefixed types use `_generated/backend.d.ts`.\n * Schema sets are generated separately and never merged — mirrors ADR-0072.\n */\n\nimport type { components } from \"./_generated/api.js\";\nimport type { components as proComponents } from \"./_generated/pro.js\";\nimport type { components as backendComponents } from \"./_generated/backend.js\";\n\n// -- Shared surface (present in both schema sets; typed off the Enterprise API) --\nexport type ExtractionOptions = components[\"schemas\"][\"ExtractionOptions\"];\nexport type ExtractionConfig = components[\"schemas\"][\"ExtractionConfig\"];\n/** A per-file extraction override, carried by `DocumentInput.config` and the `config-<filename>` multipart part. */\nexport type FileExtractionConfig = components[\"schemas\"][\"FileExtractionConfig\"];\nexport type ExtractedDocument = components[\"schemas\"][\"ExtractedDocument\"];\nexport type ExtractionResult = ExtractedDocument;\nexport type Job = components[\"schemas\"][\"JobResponse\"];\nexport type JobStatus = components[\"schemas\"][\"JobStatus\"];\nexport type WebhookConfig = components[\"schemas\"][\"WebhookConfig\"];\nexport type ExtractResponse = components[\"schemas\"][\"ExtractResponse\"];\nexport type DocumentInput = components[\"schemas\"][\"DocumentInput\"];\nexport type ListJobsResponse = components[\"schemas\"][\"ListJobsResponse\"];\nexport type ListAuditEntriesResponse = components[\"schemas\"][\"ListAuditEntriesResponse\"];\nexport type PresetSummary = components[\"schemas\"][\"PresetSummary\"];\nexport type PresetDetail = components[\"schemas\"][\"PresetDetail\"];\n\n/**\n * The stored result document of a terminal job, returned by\n * `GET /v1/jobs/{id}/result` on both tiers. Distinct from {@link Job}, which is\n * the job's metadata record from `GET /v1/jobs/{id}`.\n */\nexport type JobResult = components[\"schemas\"][\"JobResult\"];\n/** A non-fatal per-document error attached to a {@link JobResult}. */\nexport type JobResultError = components[\"schemas\"][\"JobResultError\"];\n\n// -- Shared saved presets (both specs declare these identically) --\nexport type ListSavedPresetsResponse = components[\"schemas\"][\"ListSavedPresetsResponse\"];\nexport type SavedPresetSummary = components[\"schemas\"][\"SavedPresetSummary\"];\nexport type SavedPresetDetail = components[\"schemas\"][\"SavedPresetDetail\"];\nexport type CreateSavedPresetRequest = components[\"schemas\"][\"CreateSavedPresetRequest\"];\nexport type CreateSavedPresetResponse = components[\"schemas\"][\"CreateSavedPresetResponse\"];\nexport type UpdateSavedPresetRequest = components[\"schemas\"][\"UpdateSavedPresetRequest\"];\nexport type UpdateSavedPresetResponse = components[\"schemas\"][\"UpdateSavedPresetResponse\"];\n\n// -- Shared auto-tune surface (both specs declare these identically) --\nexport type ListAutoTuneJobsResponse = components[\"schemas\"][\"ListAutoTuneJobsResponse\"];\nexport type AutoTuneJobSummary = components[\"schemas\"][\"AutoTuneJobSummary\"];\nexport type CreateAutoTuneJobRequest = components[\"schemas\"][\"CreateAutoTuneJobRequest\"];\nexport type CreateAutoTuneJobResponse = components[\"schemas\"][\"CreateAutoTuneJobResponse\"];\nexport type AutoTuneCapabilitiesResponse = components[\"schemas\"][\"AutoTuneCapabilitiesResponse\"];\nexport type AutoTuneJobStatus = components[\"schemas\"][\"AutoTuneJobStatus\"];\nexport type AutoTuneResult = components[\"schemas\"][\"AutoTuneResult\"];\nexport type PromoteProfileRequest = components[\"schemas\"][\"PromoteProfileRequest\"];\n\n// -- Shared tuning profiles (both specs declare these identically) --\nexport type ListTuningProfilesResponse = components[\"schemas\"][\"ListTuningProfilesResponse\"];\nexport type TuningProfileSummary = components[\"schemas\"][\"TuningProfileSummary\"];\nexport type TuningProfileDetail = components[\"schemas\"][\"TuningProfileDetail\"];\n\n// -- Enterprise-only surface (api schema) --\nexport type UsageResponse = components[\"schemas\"][\"UsageResponse\"];\nexport type DiffResponse = components[\"schemas\"][\"DiffResponse\"];\n/** The async-pending envelope `diff`/`getDiffJob` return in place of {@link DiffResponse} while a diff is still computing. */\nexport type DiffAsyncAccepted = components[\"schemas\"][\"DiffAsyncAccepted\"];\n\n/**\n * Result of {@link XbergClient.diff} and {@link XbergClient.getDiffJob}.\n *\n * Both operations answer `200` with the computed {@link DiffResponse} or\n * `202` with the {@link DiffAsyncAccepted} polling envelope when the server\n * falls back to async computation — the same fallback `getDiffJob` exists to\n * poll. The two schemas share no field to discriminate on, so `status` here\n * is not part of either wire schema: it is the HTTP status code the response\n * actually carried, reattached so callers can narrow with a plain\n * `if (result.status === 200)` / `else` instead of a type assertion.\n */\nexport type DiffResult =\n | { readonly status: 200; readonly body: DiffResponse }\n | { readonly status: 202; readonly body: DiffAsyncAccepted };\nexport type DocumentVersionEntry = components[\"schemas\"][\"DocumentVersionEntry\"];\nexport type PresignUploadRequest = components[\"schemas\"][\"PresignUploadRequest\"];\nexport type PresignUploadResponse = components[\"schemas\"][\"PresignUploadResponse\"];\nexport type ConfirmUploadRequest = components[\"schemas\"][\"ConfirmUploadRequest\"];\nexport type ConfirmUploadResponse = components[\"schemas\"][\"ConfirmUploadResponse\"];\nexport type EnrichTextRequest = components[\"schemas\"][\"EnrichTextRequest\"];\nexport type EnrichRequestOptions = components[\"schemas\"][\"EnrichRequestOptions\"];\nexport type EnrichJobSubmitted = components[\"schemas\"][\"EnrichJobSubmitted\"];\nexport type EnrichJobStatus = components[\"schemas\"][\"EnrichJobStatus\"];\nexport type ListExtractionEventsResponse = components[\"schemas\"][\"ListExtractionEventsResponse\"];\nexport type ExtractionEventSummary = components[\"schemas\"][\"ExtractionEventSummary\"];\n\n/**\n * One event from {@link XbergClient.streamCrawlEvents}.\n *\n * A tagged union discriminated on `kind`, the same shape {@link DiffResult}\n * uses — except the discriminant here is a real wire field, not a reattached\n * HTTP status. Narrow before touching a variant-specific field:\n *\n * ```ts\n * for await (const event of client.streamCrawlEvents(crawlJobId)) {\n * if (event.kind === \"page\") {\n * // event.status_code, event.depth, event.url\n * } else if (event.kind === \"complete\") {\n * break;\n * }\n * }\n * ```\n *\n * `crawl_job_id` and `ts` are carried by every variant, so they read without\n * narrowing.\n */\nexport type CrawlEvent = components[\"schemas\"][\"CrawlEventV1\"];\n/** The `kind` discriminator of a {@link CrawlEvent}. */\nexport type CrawlEventKind = CrawlEvent[\"kind\"];\n/** A page was successfully crawled and indexed. */\nexport type CrawlPageEvent = Extract<CrawlEvent, { kind: \"page\" }>;\n/** A new URL was discovered during crawling. */\nexport type CrawlDiscoveredEvent = Extract<CrawlEvent, { kind: \"discovered\" }>;\n/** The crawl job finished; the stream closes after this event. */\nexport type CrawlCompleteEvent = Extract<CrawlEvent, { kind: \"complete\" }>;\n/** A single URL failed. The crawl continues; this is not a stream-level error. */\nexport type CrawlErrorEvent = Extract<CrawlEvent, { kind: \"error\" }>;\n\n// -- Pro-only surface (pro schema) --\nexport type GetJobResponse = proComponents[\"schemas\"][\"GetJobResponse\"];\nexport type AuthConfigResponse = proComponents[\"schemas\"][\"AuthConfigResponse\"];\nexport type LoginRequest = proComponents[\"schemas\"][\"LoginRequest\"];\nexport type LoginResponse = proComponents[\"schemas\"][\"LoginResponse\"];\nexport type SetRagConfigRequest = proComponents[\"schemas\"][\"SetRagConfigRequest\"];\nexport type RagConfigResponse = proComponents[\"schemas\"][\"RagConfigResponse\"];\n\n// -- Pro-only control plane (projects, API keys, integrations) --\nexport type ListProjectsResponse = proComponents[\"schemas\"][\"ListProjectsResponse\"];\nexport type CreateProjectRequest = proComponents[\"schemas\"][\"CreateProjectRequest\"];\nexport type ProjectResponse = proComponents[\"schemas\"][\"ProjectResponse\"];\nexport type ApiKeyResponse = proComponents[\"schemas\"][\"ApiKeyResponse\"];\nexport type ApiKeyScope = proComponents[\"schemas\"][\"ApiKeyScope\"];\nexport type ListApiKeysResponse = proComponents[\"schemas\"][\"ListApiKeysResponse\"];\nexport type CreateApiKeyRequest = proComponents[\"schemas\"][\"CreateApiKeyRequest\"];\nexport type CreateApiKeyResponse = proComponents[\"schemas\"][\"CreateApiKeyResponse\"];\nexport type ListIntegrationsResponse = proComponents[\"schemas\"][\"ListIntegrationsResponse\"];\nexport type CreateIntegrationRequest = proComponents[\"schemas\"][\"CreateIntegrationRequest\"];\nexport type IntegrationResponse = proComponents[\"schemas\"][\"IntegrationResponse\"];\nexport type BeginOAuthResponse = proComponents[\"schemas\"][\"BeginOAuthResponse\"];\nexport type ListDocumentsResponse = proComponents[\"schemas\"][\"ListDocumentsResponse\"];\nexport type DocumentResponse = proComponents[\"schemas\"][\"DocumentResponse\"];\n\n/**\n * Terminal job statuses — once observed, polling stops and the job result is\n * returned (or thrown, for `failed`/`cancelled`).\n */\nexport const TERMINAL_JOB_STATUSES: readonly JobStatus[] = [\n \"completed\",\n \"partial_success\",\n \"failed\",\n \"cancelled\",\n] as const;\n\n/**\n * Job statuses that indicate a successful extraction. Used to distinguish a\n * \"completed but check warnings\" result from a hard failure.\n */\nexport const SUCCESS_JOB_STATUSES: readonly JobStatus[] = [\"completed\", \"partial_success\"] as const;\n\nexport type BackendAcceptInvitationRequest = backendComponents[\"schemas\"][\"AcceptInvitationRequest\"];\nexport type BackendAnalyticsResponse = backendComponents[\"schemas\"][\"AnalyticsResponse\"];\nexport type BackendAuthConfigResponse = backendComponents[\"schemas\"][\"AuthConfigResponse\"];\nexport type BackendBeginConnectResponse = backendComponents[\"schemas\"][\"BeginConnectResponse\"];\nexport type BackendBillingResponse = backendComponents[\"schemas\"][\"BillingResponse\"];\nexport type BackendCheckoutResponse = backendComponents[\"schemas\"][\"CheckoutResponse\"];\nexport type BackendCreateApiKeyRequest = backendComponents[\"schemas\"][\"CreateApiKeyRequest\"];\nexport type BackendCreateApiKeyResponse = backendComponents[\"schemas\"][\"CreateApiKeyResponse\"];\n/** Backend integration configuration accepts arbitrary JSON object properties. */\nexport type BackendCreateIntegrationRequest = Omit<\n backendComponents[\"schemas\"][\"CreateIntegrationRequest\"],\n \"config\" | \"credentials\"\n> & { config?: Record<string, unknown>; credentials?: Record<string, unknown> };\nexport type BackendCreateInvitationRequest = backendComponents[\"schemas\"][\"CreateInvitationRequest\"];\nexport type BackendCreateInvitationResponse = backendComponents[\"schemas\"][\"CreateInvitationResponse\"];\nexport type BackendCreateProjectRequest = backendComponents[\"schemas\"][\"CreateProjectRequest\"];\nexport type BackendCreateWebhookRequest = backendComponents[\"schemas\"][\"CreateWebhookRequest\"];\nexport type BackendHealthResponse = backendComponents[\"schemas\"][\"HealthResponse\"];\nexport type BackendIntegrationResponse = backendComponents[\"schemas\"][\"IntegrationResponse\"];\nexport type BackendListApiKeysResponse = backendComponents[\"schemas\"][\"ListApiKeysResponse\"];\nexport type BackendListAuditEntriesResponse = backendComponents[\"schemas\"][\"ListAuditEntriesResponse\"];\nexport type BackendListDocumentsResponse = backendComponents[\"schemas\"][\"ListDocumentsResponse\"];\nexport type BackendListIntegrationsResponse = backendComponents[\"schemas\"][\"ListIntegrationsResponse\"];\nexport type BackendListInvitationsResponse = backendComponents[\"schemas\"][\"ListInvitationsResponse\"];\nexport type BackendListMembersResponse = backendComponents[\"schemas\"][\"ListMembersResponse\"];\nexport type BackendListProjectsResponse = backendComponents[\"schemas\"][\"ListProjectsResponse\"];\nexport type BackendListWebhookDeliveriesResponse = backendComponents[\"schemas\"][\"ListWebhookDeliveriesResponse\"];\nexport type BackendListWebhooksResponse = backendComponents[\"schemas\"][\"ListWebhooksResponse\"];\nexport type BackendLoginRequest = backendComponents[\"schemas\"][\"LoginRequest\"];\nexport type BackendLoginResponse = backendComponents[\"schemas\"][\"LoginResponse\"];\nexport type BackendMemberResponse = backendComponents[\"schemas\"][\"MemberResponse\"];\nexport type BackendPortalResponse = backendComponents[\"schemas\"][\"PortalResponse\"];\nexport type BackendProjectResponse = backendComponents[\"schemas\"][\"ProjectResponse\"];\nexport type BackendRagConfigResponse = backendComponents[\"schemas\"][\"RagConfigResponse\"];\nexport type BackendReadinessResponse = backendComponents[\"schemas\"][\"ReadinessResponse\"];\nexport type BackendRetryWebhookDeliveryResponse = backendComponents[\"schemas\"][\"RetryWebhookDeliveryResponse\"];\nexport type BackendSandboxExtractResponse = backendComponents[\"schemas\"][\"SandboxExtractResponse\"];\nexport type BackendSetRagConfigRequest = backendComponents[\"schemas\"][\"SetRagConfigRequest\"];\nexport type BackendUpdateMemberRoleRequest = backendComponents[\"schemas\"][\"UpdateMemberRoleRequest\"];\nexport type BackendUpdateProjectRequest = backendComponents[\"schemas\"][\"UpdateProjectRequest\"];\nexport type BackendUpdateWebhookRequest = backendComponents[\"schemas\"][\"UpdateWebhookRequest\"];\nexport type BackendUsageResponse = backendComponents[\"schemas\"][\"UsageResponse\"];\nexport type BackendWebhookResponse = backendComponents[\"schemas\"][\"WebhookResponse\"];\nexport type BackendWebhookTestResponse = backendComponents[\"schemas\"][\"WebhookTestResponse\"];\n","/**\n * Package version, synced from the repo-root `VERSION` file by\n * `scripts/sync-versions.py`. Used to build the `User-Agent` header. ~keep\n */\nexport const VERSION = \"0.5.0\";\n","/**\n * High-level dual-target client for the Xberg Enterprise and Xberg Pro HTTP APIs.\n *\n * One {@link XbergClient} speaks to either product. The shared surface —\n * extraction, jobs (including job results), audit, curated presets, and the RAG\n * API — is written once and carries no tier gate. Tier-specific methods are\n * capability-gated: they probe the connected instance (`GET /healthz`'s `tier`,\n * or an explicit `target`) and throw a clear error instead of a raw 404 when\n * invoked against the wrong tier.\n *\n * Both products authenticate identically: `Authorization: Bearer {apiKey}`.\n * Enterprise defaults `baseUrl` to `https://api.xberg.io`; Pro has no default\n * (its spec ships no servers block) and requires an explicit one.\n *\n * Enterprise splits into two binaries — the data plane `baseUrl` addresses and a\n * control plane (projects, API keys, integrations) on its own origin — while Pro\n * serves both from one. `controlPlaneBaseUrl` records the origin of the second\n * and defaults to `baseUrl`. The backend methods use that origin and an optional\n * separate `controlPlaneToken`; existing Pro methods retain their data-plane routing.\n */\n\nimport createOpenApiClient, { type Client } from \"openapi-fetch\";\nimport type { paths } from \"./_generated/api.js\";\nimport {\n DEFAULT_BACKOFF_FACTOR,\n DEFAULT_ENTERPRISE_BASE_URL,\n DEFAULT_RETRY_BACKOFF_CAP_MS,\n EventStreamDecoder,\n encodePathSegment,\n buildQueryString,\n defaultSleep,\n describeFile,\n nextBackoffInterval,\n parseRetryAfterHeader,\n resolveBaseUrl,\n resolveControlPlaneBaseUrl,\n toBlob,\n} from \"./_internal.js\";\nimport type { BackoffStrategy, FileLike, QueryParams, Target } from \"./_internal.js\";\nimport { RateLimitError, TimeoutError, XbergError, raiseForStatus } from \"./errors.js\";\nimport type {\n AuthConfigResponse,\n BackendAcceptInvitationRequest,\n BackendAnalyticsResponse,\n BackendAuthConfigResponse,\n BackendBeginConnectResponse,\n BackendBillingResponse,\n BackendCheckoutResponse,\n BackendCreateApiKeyRequest,\n BackendCreateApiKeyResponse,\n BackendCreateIntegrationRequest,\n BackendCreateInvitationRequest,\n BackendCreateInvitationResponse,\n BackendCreateProjectRequest,\n BackendCreateWebhookRequest,\n BackendHealthResponse,\n BackendIntegrationResponse,\n BackendListApiKeysResponse,\n BackendListAuditEntriesResponse,\n BackendListDocumentsResponse,\n BackendListIntegrationsResponse,\n BackendListInvitationsResponse,\n BackendListMembersResponse,\n BackendListProjectsResponse,\n BackendListWebhookDeliveriesResponse,\n BackendListWebhooksResponse,\n BackendLoginRequest,\n BackendLoginResponse,\n BackendMemberResponse,\n BackendPortalResponse,\n BackendProjectResponse,\n BackendRagConfigResponse,\n BackendReadinessResponse,\n BackendRetryWebhookDeliveryResponse,\n BackendSandboxExtractResponse,\n BackendSetRagConfigRequest,\n BackendUpdateMemberRoleRequest,\n BackendUpdateProjectRequest,\n BackendUpdateWebhookRequest,\n BackendUsageResponse,\n BackendWebhookResponse,\n BackendWebhookTestResponse,\n AutoTuneCapabilitiesResponse,\n AutoTuneJobStatus,\n AutoTuneResult,\n BeginOAuthResponse,\n ConfirmUploadRequest,\n ConfirmUploadResponse,\n CrawlEvent,\n CreateApiKeyRequest,\n CreateApiKeyResponse,\n CreateAutoTuneJobRequest,\n CreateAutoTuneJobResponse,\n CreateIntegrationRequest,\n CreateProjectRequest,\n CreateSavedPresetRequest,\n CreateSavedPresetResponse,\n DiffAsyncAccepted,\n DiffResponse,\n DiffResult,\n DocumentVersionEntry,\n EnrichJobStatus,\n EnrichJobSubmitted,\n EnrichTextRequest,\n ExtractResponse,\n ExtractionOptions,\n FileExtractionConfig,\n IntegrationResponse,\n Job,\n JobResult,\n ListApiKeysResponse,\n ListAuditEntriesResponse,\n ListAutoTuneJobsResponse,\n ListDocumentsResponse,\n ListExtractionEventsResponse,\n ListIntegrationsResponse,\n ListJobsResponse,\n ListProjectsResponse,\n ListSavedPresetsResponse,\n ListTuningProfilesResponse,\n LoginRequest,\n LoginResponse,\n PresetDetail,\n PresetSummary,\n PresignUploadRequest,\n PresignUploadResponse,\n ProjectResponse,\n PromoteProfileRequest,\n RagConfigResponse,\n SavedPresetDetail,\n SetRagConfigRequest,\n TuningProfileDetail,\n UpdateSavedPresetRequest,\n UpdateSavedPresetResponse,\n UsageResponse,\n WebhookConfig,\n} from \"./types.js\";\nimport { SUCCESS_JOB_STATUSES, TERMINAL_JOB_STATUSES } from \"./types.js\";\nimport { VERSION } from \"./version.js\";\n\n/**\n * Public types that live in the internal helper module because the helpers\n * there operate on them; re-exported so `./client.js` stays their import site.\n */\nexport type { BackoffStrategy, FileLike, Target } from \"./_internal.js\";\n\nconst USER_AGENT = `xberg-io-sdk-typescript/${VERSION}`;\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_POLL_INTERVAL_MS = 1_000;\nconst DEFAULT_WAIT_TIMEOUT_MS = 5 * 60_000;\nconst DEFAULT_RETRY_STATUSES: readonly number[] = [429, 502, 503, 504];\nconst DEFAULT_RETRY_BACKOFF_BASE_MS = 200;\n\n/**\n * Saved presets are the one shared resource whose *path* differs per tier:\n * Enterprise serves `/v1/saved_presets` (underscore), Pro `/v1/saved-presets`\n * (hyphen). The request and response schemas are identical.\n */\nconst SAVED_PRESETS_PATH_ENTERPRISE = \"/v1/saved_presets\";\nconst SAVED_PRESETS_PATH_PRO = \"/v1/saved-presets\";\nconst AUTO_TUNE_PATH = \"/v1/auto-tune\";\nconst TUNING_PROFILES_PATH = \"/v1/tuning-profiles\";\nconst ENRICH_PATH = \"/v1/enrich\";\nconst EXTRACTIONS_PATH = \"/v1/extractions\";\nconst DOCUMENTS_PATH = \"/v1/documents\";\nconst JOBS_PATH = \"/v1/jobs\";\nconst CRAWL_JOBS_PATH = \"/v1/crawl-jobs\";\n\n/** Media type of the crawl-event stream, sent as `Accept` and served as `Content-Type`. */\nconst EVENT_STREAM_MEDIA_TYPE = \"text/event-stream\";\n\n/** The `kind` values `CrawlEventV1` declares. A frame carrying anything else is rejected. */\nconst CRAWL_EVENT_KINDS: ReadonlySet<string> = new Set([\"page\", \"discovered\", \"complete\", \"error\"]);\n\nexport interface XbergClientOptions {\n apiKey?: string;\n baseUrl?: string;\n /**\n * Origin of the Enterprise control plane, which runs as a second binary\n * alongside the data plane. Defaults to `baseUrl` — Pro serves both planes\n * from one binary, so every Pro call keeps working untouched.\n *\n */\n controlPlaneBaseUrl?: string;\n /** Bearer token for protected backend calls; defaults to `apiKey`. */\n controlPlaneToken?: string;\n /** Product for tier-specific data-plane methods; discovered lazily when omitted. */\n target?: Target;\n fetch?: typeof fetch;\n headers?: Record<string, string>;\n timeoutMs?: number;\n retries?: number;\n retryOn?: readonly number[];\n retryBackoff?: BackoffStrategy;\n /** Sleep helper, swappable in tests. Defaults to `setTimeout`. */\n sleep?: (ms: number) => Promise<void>;\n}\n\nexport interface ExtractParams {\n /** Enterprise document lineage UUID; omitted for a new document. */\n documentId?: string;\n file: FileLike;\n options?: ExtractionOptions;\n webhook?: WebhookConfig;\n /**\n * Per-file extraction override for this document, sent as the\n * `config-<filename>` part. The server resolves it against\n * `options.extraction_config`, any preset and the project default.\n */\n config?: FileExtractionConfig;\n}\n\nexport interface ExtractBatchParams {\n /** Enterprise lineage UUIDs aligned with files; null entries omit lineage. */\n documentIds?: readonly (string | null)[];\n files: readonly FileLike[];\n options?: ExtractionOptions;\n webhook?: WebhookConfig;\n /**\n * One optional per-file override per entry of `files`, in the same order —\n * `null` for no override. Must be the same length as `files` when given.\n *\n * The override travels as a `config-<filename>` part, so two documents sharing\n * a filename cannot carry different overrides; that combination throws rather\n * than dropping one silently.\n */\n configs?: readonly (FileExtractionConfig | null)[];\n}\n\nexport interface WaitOptions {\n /** Total time to wait before throwing TimeoutError. Default 5 minutes. */\n timeoutMs?: number;\n /** Initial poll interval. Default 1000ms. */\n pollIntervalMs?: number;\n /** `exponential` doubles the interval each cycle (capped). Default exponential. */\n backoff?: BackoffStrategy;\n}\n\nexport interface ExtractAndWaitParams extends ExtractParams, WaitOptions {}\n\nexport interface ListJobsParams {\n limit?: number;\n offset?: number;\n}\n\nexport interface AuditParams {\n action?: string;\n limit?: number;\n offset?: number;\n}\n\n/** Offset pagination accepted by the paginated list endpoints. */\nexport interface PaginationParams {\n limit?: number;\n offset?: number;\n}\n\n/** Filters accepted by `listExtractionEvents`. */\nexport interface ListExtractionEventsParams extends PaginationParams {\n /** How many days to look back. Defaults to 30 server-side, clamped to 1..=365. */\n days?: number;\n}\n\n/** The two multipart parts `submitAutoTune` sends. */\nexport interface SubmitAutoTuneParams {\n /** JSON-encoded into the required `request` part. */\n request: CreateAutoTuneJobRequest;\n /** One binary `file` part per document referenced by `request.documents[].filename`. */\n files: readonly FileLike[];\n}\n\n/** Options accepted by `streamCrawlEvents`. */\nexport interface StreamCrawlEventsOptions {\n /**\n * Aborts the stream from outside the loop. Breaking out of the `for await`\n * already closes the response body, so this is only needed to hang up from\n * somewhere else — a React effect teardown, a shutdown handler.\n */\n signal?: AbortSignal;\n}\n\n/** Filters accepted by `listIntegrationDocuments`. */\nexport interface ListIntegrationDocumentsParams {\n /** Comma-separated MIME types to restrict the listing to. */\n mimeTypes?: string;\n /** Source-specific folder to list instead of the connection root. */\n folderId?: string;\n /** Upper bound on the number of documents returned. */\n maxResults?: number;\n}\n\nexport interface BackendDateRange {\n startDate: string;\n endDate: string;\n}\nexport interface BackendOAuthCallbackParams {\n code: string;\n state: string;\n}\nexport interface BackendAuditParams {\n action?: string;\n limit?: number;\n offset?: number;\n}\nexport interface BackendSandboxExtractParams {\n file: FileLike;\n}\nexport interface PublicSandboxExtractParams {\n file?: FileLike;\n mode?: string;\n preset?: string;\n url?: string;\n sandboxToken?: string;\n}\n\n/** Underlying `openapi-fetch` client, typed over the Enterprise API schema. */\nexport type XbergRawClient = Client<paths>;\n\n/**\n * High-level dual-target client. Construct with `new XbergClient({ apiKey })`.\n */\nexport class XbergClient {\n private readonly baseUrl: string;\n /**\n * Origin used by the Enterprise backend methods. Defaults to `baseUrl`.\n */\n public readonly controlPlaneBaseUrl: string;\n private readonly controlPlaneToken: string | undefined;\n private readonly headers: Record<string, string>;\n private readonly fetchImpl: typeof fetch;\n private readonly timeoutMs: number;\n private readonly retries: number;\n private readonly retryOn: readonly number[];\n private readonly retryBackoff: BackoffStrategy;\n private readonly sleep: (ms: number) => Promise<void>;\n private readonly target?: Target;\n private probedTier: Target | undefined;\n /** In-flight `/healthz` probe, memoised so concurrent callers share one request (single-flight). */\n private tierProbe: Promise<Target> | undefined;\n /** Underlying `openapi-fetch` client — exposed for advanced use. */\n public readonly raw: XbergRawClient;\n\n public constructor(options: XbergClientOptions = {}) {\n if (options.target !== undefined) {\n this.target = options.target;\n }\n this.baseUrl = resolveBaseUrl(options.baseUrl, options.target);\n this.controlPlaneBaseUrl = resolveControlPlaneBaseUrl(options.controlPlaneBaseUrl, this.baseUrl);\n this.controlPlaneToken = options.controlPlaneToken ?? options.apiKey;\n this.fetchImpl = options.fetch ?? fetch;\n this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.retries = options.retries ?? 0;\n this.retryOn = options.retryOn ?? DEFAULT_RETRY_STATUSES;\n this.retryBackoff = options.retryBackoff ?? \"exponential\";\n this.sleep = options.sleep ?? defaultSleep;\n\n this.headers = {\n \"User-Agent\": USER_AGENT,\n ...options.headers,\n };\n if (options.apiKey !== undefined) {\n this.headers[\"Authorization\"] = `Bearer ${options.apiKey}`;\n }\n\n this.raw = createOpenApiClient<paths>({\n baseUrl: this.baseUrl,\n headers: this.headers,\n fetch: this.fetchImpl,\n });\n }\n\n /** Enterprise backend `DELETE /auth/account`. */\n public async deleteAccount(): Promise<void> {\n return await this.backendRequest<void>(\"DELETE\", `/auth/account`);\n }\n /** Enterprise backend `GET /auth/config`. */\n public async getAuthConfig(): Promise<BackendAuthConfigResponse> {\n return await this.backendRequest<BackendAuthConfigResponse>(\"GET\", `/auth/config`, { backendPublic: true });\n }\n /** Enterprise backend `POST /auth/login`. */\n public async backendLogin(body: BackendLoginRequest): Promise<BackendLoginResponse> {\n return await this.backendRequest<BackendLoginResponse>(\"POST\", `/auth/login`, { json: body, backendPublic: true });\n }\n /** Enterprise backend `GET /healthz`. */\n public async healthz(): Promise<BackendHealthResponse> {\n return await this.backendRequest<BackendHealthResponse>(\"GET\", `/healthz`, { backendPublic: true });\n }\n /** Enterprise backend `GET /readyz`. */\n public async readyz(): Promise<BackendReadinessResponse> {\n return await this.backendRequest<BackendReadinessResponse>(\"GET\", `/readyz`, { backendPublic: true });\n }\n /** Enterprise backend `POST /v1/invitations/accept`. */\n public async acceptInvitation(body: BackendAcceptInvitationRequest): Promise<BackendMemberResponse> {\n return await this.backendRequest<BackendMemberResponse>(\"POST\", `/v1/invitations/accept`, { json: body });\n }\n /** Enterprise backend `GET /v1/oauth/callback`. */\n public async oauthCallback(params: BackendOAuthCallbackParams): Promise<string> {\n const response = await this.requestWithRetry(\"GET\", \"/v1/oauth/callback\", {\n controlPlane: true,\n backendPublic: true,\n acceptRedirect: true,\n params: { code: params.code, state: params.state },\n });\n const location = response.headers.get(\"location\");\n await response.body?.cancel();\n if (response.status !== 303 || location === null || location.length === 0) {\n throw new XbergError(\"OAuth callback did not return a 303 Location\", { status: response.status, body: null });\n }\n return location;\n }\n /** Enterprise backend `GET /v1/projects`. */\n public async backendListProjects(params: PaginationParams = {}): Promise<BackendListProjectsResponse> {\n return await this.backendRequest<BackendListProjectsResponse>(\"GET\", `/v1/projects`, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n /** Enterprise backend `POST /v1/projects`. */\n public async backendCreateProject(body: BackendCreateProjectRequest): Promise<BackendProjectResponse> {\n return await this.backendRequest<BackendProjectResponse>(\"POST\", `/v1/projects`, { json: body });\n }\n /** Enterprise backend `GET /v1/projects/{id}`. */\n public async getProject(projectId: string): Promise<BackendProjectResponse> {\n return await this.backendRequest<BackendProjectResponse>(\"GET\", `/v1/projects/${encodePathSegment(projectId)}`);\n }\n /** Enterprise backend `DELETE /v1/projects/{id}`. */\n public async deleteProject(projectId: string, params: { erase?: boolean } = {}): Promise<void> {\n return await this.backendRequest<void>(\"DELETE\", `/v1/projects/${encodePathSegment(projectId)}`, {\n params: { erase: params.erase === undefined ? undefined : String(params.erase) },\n });\n }\n /** Enterprise backend `PATCH /v1/projects/{id}`. */\n public async updateProject(projectId: string, body: BackendUpdateProjectRequest): Promise<BackendProjectResponse> {\n return await this.backendRequest<BackendProjectResponse>(\"PATCH\", `/v1/projects/${encodePathSegment(projectId)}`, {\n json: body,\n });\n }\n /** Enterprise backend `GET /v1/projects/{id}/analytics`. */\n public async getAnalytics(projectId: string, params: BackendDateRange): Promise<BackendAnalyticsResponse> {\n return await this.backendRequest<BackendAnalyticsResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/analytics`,\n { params: { start_date: params.startDate, end_date: params.endDate } },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/api-keys`. */\n public async backendListApiKeys(\n projectId: string,\n params: PaginationParams = {},\n ): Promise<BackendListApiKeysResponse> {\n return await this.backendRequest<BackendListApiKeysResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/api-keys`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/api-keys`. */\n public async backendCreateApiKey(\n projectId: string,\n body: BackendCreateApiKeyRequest,\n ): Promise<BackendCreateApiKeyResponse> {\n return await this.backendRequest<BackendCreateApiKeyResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/api-keys`,\n { json: body },\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{id}/api-keys/{key_id}`. */\n public async backendRevokeApiKey(projectId: string, apiKeyId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"DELETE\",\n `/v1/projects/${encodePathSegment(projectId)}/api-keys/${encodePathSegment(apiKeyId)}`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/api-keys/{key_id}/regenerate`. */\n public async regenerateApiKey(projectId: string, apiKeyId: string): Promise<BackendCreateApiKeyResponse> {\n return await this.backendRequest<BackendCreateApiKeyResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/api-keys/${encodePathSegment(apiKeyId)}/regenerate`,\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/audit`. */\n public async listProjectAudit(\n projectId: string,\n params: BackendAuditParams = {},\n ): Promise<BackendListAuditEntriesResponse> {\n return await this.backendRequest<BackendListAuditEntriesResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/audit`,\n { params: { action: params.action, limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/billing`. */\n public async getBilling(projectId: string): Promise<BackendBillingResponse> {\n return await this.backendRequest<BackendBillingResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/billing`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/billing/checkout`. */\n public async createCheckout(projectId: string): Promise<BackendCheckoutResponse> {\n return await this.backendRequest<BackendCheckoutResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/billing/checkout`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/billing/portal`. */\n public async createPortal(projectId: string): Promise<BackendPortalResponse> {\n return await this.backendRequest<BackendPortalResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/billing/portal`,\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/integrations`. */\n public async backendListIntegrations(\n projectId: string,\n params: PaginationParams = {},\n ): Promise<BackendListIntegrationsResponse> {\n return await this.backendRequest<BackendListIntegrationsResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/integrations`. */\n public async backendCreateIntegration(\n projectId: string,\n body: BackendCreateIntegrationRequest,\n ): Promise<BackendIntegrationResponse> {\n return await this.backendRequest<BackendIntegrationResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations`,\n { json: body },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/integrations/{iid}`. */\n public async backendGetIntegration(projectId: string, integrationId: string): Promise<BackendIntegrationResponse> {\n return await this.backendRequest<BackendIntegrationResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}`,\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{id}/integrations/{iid}`. */\n public async backendDeleteIntegration(projectId: string, integrationId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"DELETE\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/integrations/{iid}/connect`. */\n public async oauthConnect(projectId: string, integrationId: string): Promise<BackendBeginConnectResponse> {\n return await this.backendRequest<BackendBeginConnectResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/connect`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/integrations/{iid}/disconnect`. */\n public async backendDisconnectIntegration(projectId: string, integrationId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/disconnect`,\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/integrations/{iid}/documents`. */\n public async backendListIntegrationDocuments(\n projectId: string,\n integrationId: string,\n params: ListIntegrationDocumentsParams = {},\n ): Promise<BackendListDocumentsResponse> {\n return await this.backendRequest<BackendListDocumentsResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/documents`,\n { params: { mime_types: params.mimeTypes, folder_id: params.folderId, max_results: params.maxResults } },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/integrations/{iid}/documents/{doc_id}`. */\n public async backendFetchIntegrationDocument(\n projectId: string,\n integrationId: string,\n documentId: string,\n ): Promise<Uint8Array> {\n return await this.requestBytes(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/documents/${encodePathSegment(documentId)}`,\n { controlPlane: true },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/invitations`. */\n public async listInvitations(\n projectId: string,\n params: PaginationParams = {},\n ): Promise<BackendListInvitationsResponse> {\n return await this.backendRequest<BackendListInvitationsResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/invitations`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/invitations`. */\n public async inviteUser(\n projectId: string,\n body: BackendCreateInvitationRequest,\n ): Promise<BackendCreateInvitationResponse> {\n return await this.backendRequest<BackendCreateInvitationResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/invitations`,\n { json: body },\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{id}/invitations/{inv_id}`. */\n public async revokeInvitation(projectId: string, invitationId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"DELETE\",\n `/v1/projects/${encodePathSegment(projectId)}/invitations/${encodePathSegment(invitationId)}`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/leave`. */\n public async leaveProject(projectId: string): Promise<void> {\n return await this.backendRequest<void>(\"POST\", `/v1/projects/${encodePathSegment(projectId)}/leave`);\n }\n /** Enterprise backend `GET /v1/projects/{id}/members`. */\n public async listMembers(projectId: string, params: PaginationParams = {}): Promise<BackendListMembersResponse> {\n return await this.backendRequest<BackendListMembersResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/members`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{id}/members/{user_id}`. */\n public async removeMember(projectId: string, userId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"DELETE\",\n `/v1/projects/${encodePathSegment(projectId)}/members/${encodePathSegment(userId)}`,\n );\n }\n /** Enterprise backend `PATCH /v1/projects/{id}/members/{user_id}`. */\n public async updateMemberRole(\n projectId: string,\n userId: string,\n body: BackendUpdateMemberRoleRequest,\n ): Promise<BackendMemberResponse> {\n return await this.backendRequest<BackendMemberResponse>(\n \"PATCH\",\n `/v1/projects/${encodePathSegment(projectId)}/members/${encodePathSegment(userId)}`,\n { json: body },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/rag-config`. */\n public async backendGetRagConfig(projectId: string): Promise<BackendRagConfigResponse> {\n return await this.backendRequest<BackendRagConfigResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/rag-config`,\n );\n }\n /** Enterprise backend `PUT /v1/projects/{id}/rag-config`. */\n public async backendSetRagConfig(\n projectId: string,\n body: BackendSetRagConfigRequest,\n ): Promise<BackendRagConfigResponse> {\n return await this.backendRequest<BackendRagConfigResponse>(\n \"PUT\",\n `/v1/projects/${encodePathSegment(projectId)}/rag-config`,\n { json: body },\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/sandbox/extract`. */\n public async sandboxExtract(\n projectId: string,\n params: BackendSandboxExtractParams,\n ): Promise<BackendSandboxExtractResponse> {\n return await this.backendRequest<BackendSandboxExtractResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/sandbox/extract`,\n { body: sandboxForm(params) },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/usage`. */\n public async getUsage(projectId: string, params: BackendDateRange): Promise<BackendUsageResponse> {\n return await this.backendRequest<BackendUsageResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/usage`,\n { params: { start_date: params.startDate, end_date: params.endDate } },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/webhooks`. */\n public async listWebhooks(projectId: string, params: PaginationParams = {}): Promise<BackendListWebhooksResponse> {\n return await this.backendRequest<BackendListWebhooksResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/webhooks`. */\n public async createWebhook(projectId: string, body: BackendCreateWebhookRequest): Promise<BackendWebhookResponse> {\n return await this.backendRequest<BackendWebhookResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks`,\n { json: body },\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{id}/webhooks/{wh_id}`. */\n public async deleteWebhook(projectId: string, webhookId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"DELETE\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}`,\n );\n }\n /** Enterprise backend `PATCH /v1/projects/{id}/webhooks/{wh_id}`. */\n public async updateWebhook(\n projectId: string,\n webhookId: string,\n body: BackendUpdateWebhookRequest,\n ): Promise<BackendWebhookResponse> {\n return await this.backendRequest<BackendWebhookResponse>(\n \"PATCH\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}`,\n { json: body },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/webhooks/{wh_id}/deliveries`. */\n public async listWebhookDeliveries(\n projectId: string,\n webhookId: string,\n params: PaginationParams = {},\n ): Promise<BackendListWebhookDeliveriesResponse> {\n return await this.backendRequest<BackendListWebhookDeliveriesResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}/deliveries`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/webhooks/{wh_id}/deliveries/{delivery_id}/retry`. */\n public async retryWebhookDelivery(\n projectId: string,\n webhookId: string,\n deliveryId: string,\n ): Promise<BackendRetryWebhookDeliveryResponse> {\n return await this.backendRequest<BackendRetryWebhookDeliveryResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}/deliveries/${encodePathSegment(deliveryId)}/retry`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/webhooks/{wh_id}/test`. */\n public async testWebhook(projectId: string, webhookId: string): Promise<BackendWebhookTestResponse> {\n return await this.backendRequest<BackendWebhookTestResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}/test`,\n );\n }\n /** Enterprise backend `POST /v1/sandbox/public/extract`. */\n public async publicSandboxExtract(params: PublicSandboxExtractParams): Promise<BackendSandboxExtractResponse> {\n return await this.backendRequest<BackendSandboxExtractResponse>(\"POST\", `/v1/sandbox/public/extract`, {\n body: sandboxForm(params),\n ...(params.sandboxToken !== undefined ? { sandboxToken: params.sandboxToken } : {}),\n backendPublic: true,\n });\n }\n\n // -- Shared surface (Enterprise + Pro) ---------------------------------\n\n /**\n * Submit a single document for extraction. Returns the initial {@link Job}\n * record (still pending — call `waitForJob` to await completion).\n */\n public async extract(params: ExtractParams): Promise<Job> {\n const jobs = await this.extractBatch({\n files: [params.file],\n ...(params.documentId !== undefined ? { documentIds: [params.documentId] } : {}),\n ...(params.options !== undefined ? { options: params.options } : {}),\n ...(params.webhook !== undefined ? { webhook: params.webhook } : {}),\n ...(params.config !== undefined ? { configs: [params.config] } : {}),\n });\n const first = jobs[0];\n if (first === undefined) {\n throw new XbergError(\"Server did not return any job IDs\", { status: 500, body: { jobs } });\n }\n return first;\n }\n\n /**\n * Submit multiple documents in a single multipart request. Returns one\n * {@link Job} per file, in the same order.\n */\n public async extractBatch(params: ExtractBatchParams): Promise<Job[]> {\n if (params.files.length === 0) {\n throw new XbergError(\"extractBatch called with no files\", { status: 400, body: null });\n }\n\n const filenames = params.files.map(describeFile);\n const documentIds = prepareDocumentLineage(filenames, params.documentIds);\n if (documentIds.size > 0) await this.requireTier(\"enterprise\", \"extract document lineage\");\n const form = new FormData();\n // ~keep The Enterprise parser captures lineage when reading each file part.\n for (const [filename, documentId] of documentIds) form.append(`document_id-${filename}`, documentId);\n for (const file of params.files) {\n const { blob, filename } = toBlob(file);\n form.append(\"file\", blob, filename);\n }\n if (params.options !== undefined) {\n form.append(\"options\", JSON.stringify(params.options));\n }\n if (params.webhook !== undefined) {\n form.append(\"webhook\", JSON.stringify(params.webhook));\n }\n appendPerFileConfigs(form, filenames, params.configs);\n\n const body = await this.requestJson<ExtractResponse>(\"POST\", \"/v1/extract\", { body: form });\n const jobIds = body.job_ids ?? [];\n const now = new Date().toISOString();\n return params.files.map((file, index) => {\n const id = jobIds[index];\n if (id === undefined) {\n throw new XbergError(`Server returned ${jobIds.length} job IDs for ${params.files.length} files`, {\n status: 500,\n body,\n });\n }\n return { id, filename: describeFile(file), status: \"pending\", created_at: now };\n });\n }\n\n /** Fetch the current state of a job. */\n public async getJob(jobId: string): Promise<Job> {\n return await this.requestJson<Job>(\"GET\", `${JOBS_PATH}/${encodePathSegment(jobId)}`);\n }\n\n /**\n * Fetch a job's stored result document (`GET /v1/jobs/{id}/result`).\n *\n * Declared by both tiers with an identical `JobResult` envelope; the\n * extracted documents live in `results`. Distinct from {@link getJob}, which\n * returns the job's metadata record.\n */\n public async getJobResult(jobId: string): Promise<JobResult> {\n return await this.requestJson<JobResult>(\"GET\", `${JOBS_PATH}/${encodePathSegment(jobId)}/result`);\n }\n\n /** List jobs (paginated) via `GET /v1/jobs`. */\n public async listJobs(params: ListJobsParams = {}): Promise<ListJobsResponse> {\n return await this.requestJson<ListJobsResponse>(\"GET\", JOBS_PATH, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Cancel a job (`DELETE /v1/jobs/{id}`). Idempotent: both a successful\n * cancellation and a job that already reached a terminal status answer\n * `204`.\n */\n public async cancelJob(jobId: string): Promise<void> {\n await this.requestJson(\"DELETE\", `${JOBS_PATH}/${encodePathSegment(jobId)}`);\n }\n\n /**\n * Poll {@link getJob} until the job reaches a terminal status. Throws\n * {@link TimeoutError} if the wait exceeds `timeoutMs`. Throws\n * {@link XbergError} if the terminal status is `failed` or `cancelled`.\n */\n public async waitForJob(jobId: string, options: WaitOptions = {}): Promise<Job> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;\n const initialInterval = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const backoff = options.backoff ?? \"exponential\";\n const start = Date.now();\n let interval = initialInterval;\n\n for (;;) {\n const job = await this.getJob(jobId);\n if (TERMINAL_JOB_STATUSES.includes(job.status)) {\n if (SUCCESS_JOB_STATUSES.includes(job.status)) {\n return job;\n }\n throw new XbergError(`Job ${jobId} ended with status ${job.status}`, { status: 200, body: job });\n }\n\n const elapsed = Date.now() - start;\n const remaining = timeoutMs - elapsed;\n if (remaining <= 0) {\n throw new TimeoutError(`Timed out waiting for job ${jobId} after ${timeoutMs}ms`, { status: 408, body: job });\n }\n const delay = Math.min(interval, remaining);\n await this.sleep(delay);\n if (backoff === \"exponential\") {\n interval = Math.min(interval * DEFAULT_BACKOFF_FACTOR, DEFAULT_RETRY_BACKOFF_CAP_MS);\n }\n }\n }\n\n /** Wait for many jobs in parallel. */\n public async waitForJobs(jobIds: readonly string[], options: WaitOptions = {}): Promise<Job[]> {\n return await Promise.all(jobIds.map((id) => this.waitForJob(id, options)));\n }\n\n /** Convenience: extract one file and await its result. */\n public async extractAndWait(params: ExtractAndWaitParams): Promise<Job> {\n const extractParams: ExtractParams = {\n file: params.file,\n ...(params.documentId !== undefined ? { documentId: params.documentId } : {}),\n ...(params.options !== undefined ? { options: params.options } : {}),\n ...(params.webhook !== undefined ? { webhook: params.webhook } : {}),\n ...(params.config !== undefined ? { config: params.config } : {}),\n };\n const job = await this.extract(extractParams);\n const waitOptions: WaitOptions = {\n ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs } : {}),\n ...(params.pollIntervalMs !== undefined ? { pollIntervalMs: params.pollIntervalMs } : {}),\n ...(params.backoff !== undefined ? { backoff: params.backoff } : {}),\n };\n return this.waitForJob(job.id, waitOptions);\n }\n\n /** Fetch audit-log entries via `GET /v1/audit`. */\n public async audit(params: AuditParams = {}): Promise<ListAuditEntriesResponse> {\n return await this.requestJson<ListAuditEntriesResponse>(\"GET\", \"/v1/audit\", {\n params: { action: params.action, limit: params.limit, offset: params.offset },\n });\n }\n\n // -- Shared preset catalogue -------------------------------------------\n\n /** List the read-only curated presets (`GET /v1/presets`). */\n public async presets(): Promise<PresetSummary[]> {\n return await this.requestJson<PresetSummary[]>(\"GET\", \"/v1/presets\");\n }\n\n /** Fetch one curated preset in full (`GET /v1/presets/{id}`). */\n public async getPreset(presetId: string): Promise<PresetDetail> {\n return await this.requestJson<PresetDetail>(\"GET\", `/v1/presets/${encodePathSegment(presetId)}`);\n }\n\n /**\n * Download a preset's bundled sample file\n * (`GET /v1/presets/{id}/sample/{name}`). The response is raw bytes, not\n * JSON.\n */\n public async getPresetSample(presetId: string, name: string): Promise<Uint8Array> {\n const path = `/v1/presets/${encodePathSegment(presetId)}/sample/${encodePathSegment(name)}`;\n return await this.requestBytes(\"GET\", path);\n }\n\n // -- Shared RAG surface ------------------------------------------------\n\n /** List RAG collections (`GET /v1/rag/collections`). */\n public async listRagCollections(): Promise<unknown> {\n return await this.requestJson(\"GET\", \"/v1/rag/collections\");\n }\n\n /** Create a RAG collection (`POST /v1/rag/collections`). */\n public async createRagCollection(body: Record<string, unknown>): Promise<unknown> {\n return await this.requestJson(\"POST\", \"/v1/rag/collections\", { json: body });\n }\n\n /** Fetch a RAG collection (`GET /v1/rag/collections/{name}`). */\n public async getRagCollection(name: string): Promise<unknown> {\n return await this.requestJson(\"GET\", `/v1/rag/collections/${encodePathSegment(name)}`);\n }\n\n /** Delete a RAG collection (`DELETE /v1/rag/collections/{name}`). The spec documents a 204 with no content. */\n public async deleteRagCollection(name: string): Promise<void> {\n await this.requestJson(\"DELETE\", `/v1/rag/collections/${encodePathSegment(name)}`);\n }\n\n /** Add documents to a RAG collection (`POST /v1/rag/collections/{name}/documents`). */\n public async addRagDocuments(name: string, body: Record<string, unknown>): Promise<unknown> {\n return await this.requestJson(\"POST\", `/v1/rag/collections/${encodePathSegment(name)}/documents`, { json: body });\n }\n\n /**\n * Delete documents from a RAG collection, by ID list or metadata filter\n * (`DELETE /v1/rag/collections/{name}/documents`). Unlike\n * {@link deleteRagCollection}, this answers `200` with a body reporting how\n * many documents were removed.\n */\n public async deleteRagDocuments(name: string, body: Record<string, unknown>): Promise<unknown> {\n return await this.requestJson(\"DELETE\", `/v1/rag/collections/${encodePathSegment(name)}/documents`, {\n json: body,\n });\n }\n\n /** Reindex a RAG document (`POST /v1/rag/collections/{name}/documents/{id}/reindex`). */\n public async reindexRagDocument(name: string, documentId: string, body?: Record<string, unknown>): Promise<unknown> {\n const path = `/v1/rag/collections/${encodePathSegment(name)}/documents/${encodePathSegment(documentId)}/reindex`;\n return await this.requestJson(\"POST\", path, body !== undefined ? { json: body } : {});\n }\n\n /** Retrieve chunks from a RAG collection (`POST /v1/rag/collections/{name}/retrieve`). */\n public async ragRetrieve(name: string, body: Record<string, unknown>): Promise<unknown> {\n return await this.requestJson(\"POST\", `/v1/rag/collections/${encodePathSegment(name)}/retrieve`, { json: body });\n }\n\n /** Kick off an embedding migration (`POST /v1/rag/collections/{name}/migrate-embeddings`). */\n public async migrateRagEmbeddings(name: string, body: Record<string, unknown>): Promise<unknown> {\n return await this.requestJson(\"POST\", `/v1/rag/collections/${encodePathSegment(name)}/migrate-embeddings`, {\n json: body,\n });\n }\n\n /** Poll an embedding-migration job (`GET .../migrate-embeddings/{jobId}`). */\n public async getRagMigrationJob(name: string, jobId: string): Promise<unknown> {\n const path = `/v1/rag/collections/${encodePathSegment(name)}/migrate-embeddings/${encodePathSegment(jobId)}`;\n return await this.requestJson(\"GET\", path);\n }\n\n /** Fetch a RAG job's status (`GET /v1/rag/jobs/{jobId}`). */\n public async getRagJob(jobId: string): Promise<unknown> {\n return await this.requestJson(\"GET\", `/v1/rag/jobs/${encodePathSegment(jobId)}`);\n }\n\n // -- Shared saved presets ----------------------------------------------\n //\n // Both tiers serve the same schemas under a different spelling, so every\n // method here resolves the tier and renders its path from it.\n\n /** List the project's saved presets (`GET /v1/saved_presets`, `/v1/saved-presets` on Pro). */\n public async listSavedPresets(params: PaginationParams = {}): Promise<ListSavedPresetsResponse> {\n const path = await this.savedPresetsPath();\n return await this.requestJson<ListSavedPresetsResponse>(\"GET\", path, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /** Create a saved preset (`POST /v1/saved_presets`, `/v1/saved-presets` on Pro). */\n public async createSavedPreset(body: CreateSavedPresetRequest): Promise<CreateSavedPresetResponse> {\n const path = await this.savedPresetsPath();\n return await this.requestJson<CreateSavedPresetResponse>(\"POST\", path, { json: body });\n }\n\n /** Fetch one saved preset (`GET /v1/saved_presets/{presetId}`, `/v1/saved-presets/{id}` on Pro). */\n public async getSavedPreset(presetId: string): Promise<SavedPresetDetail> {\n const path = await this.savedPresetsPath(presetId);\n return await this.requestJson<SavedPresetDetail>(\"GET\", path);\n }\n\n /** Update a saved preset (`PATCH /v1/saved_presets/{presetId}`, `/v1/saved-presets/{id}` on Pro). */\n public async updateSavedPreset(presetId: string, body: UpdateSavedPresetRequest): Promise<UpdateSavedPresetResponse> {\n const path = await this.savedPresetsPath(presetId);\n return await this.requestJson<UpdateSavedPresetResponse>(\"PATCH\", path, { json: body });\n }\n\n /** Delete a saved preset (`DELETE /v1/saved_presets/{presetId}`, `/v1/saved-presets/{id}` on Pro). */\n public async deleteSavedPreset(presetId: string): Promise<void> {\n const path = await this.savedPresetsPath(presetId);\n await this.requestJson(\"DELETE\", path);\n }\n\n // -- Shared auto-tune surface ------------------------------------------\n\n /** List the project's auto-tune jobs (`GET /v1/auto-tune`). */\n public async listAutoTuneJobs(params: PaginationParams = {}): Promise<ListAutoTuneJobsResponse> {\n return await this.requestJson<ListAutoTuneJobsResponse>(\"GET\", AUTO_TUNE_PATH, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Submit an auto-tune job (`POST /v1/auto-tune`). Sent as `multipart/form-data`:\n * a JSON `request` part plus one binary `file` part per document.\n */\n public async submitAutoTune(params: SubmitAutoTuneParams): Promise<CreateAutoTuneJobResponse> {\n if (params.files.length === 0) {\n throw new XbergError(\"submitAutoTune called with no files\", { status: 400, body: null });\n }\n const form = new FormData();\n form.append(\"request\", JSON.stringify(params.request));\n for (const file of params.files) {\n const { blob, filename } = toBlob(file);\n form.append(\"file\", blob, filename);\n }\n return await this.requestJson<CreateAutoTuneJobResponse>(\"POST\", AUTO_TUNE_PATH, { body: form });\n }\n\n /** Fetch the deployment's tunable knobs and OCR backends (`GET /v1/auto-tune/capabilities`). */\n public async getAutoTuneCapabilities(): Promise<AutoTuneCapabilitiesResponse> {\n return await this.requestJson<AutoTuneCapabilitiesResponse>(\"GET\", `${AUTO_TUNE_PATH}/capabilities`);\n }\n\n /** Fetch an auto-tune job's status (`GET /v1/auto-tune/{id}`). */\n public async getAutoTuneStatus(autoTuneJobId: string): Promise<AutoTuneJobStatus> {\n return await this.requestJson<AutoTuneJobStatus>(\"GET\", this.autoTunePath(autoTuneJobId));\n }\n\n /** Delete an auto-tune job (`DELETE /v1/auto-tune/{id}`). */\n public async deleteAutoTuneJob(autoTuneJobId: string): Promise<void> {\n await this.requestJson(\"DELETE\", this.autoTunePath(autoTuneJobId));\n }\n\n /** Promote an auto-tune result to a named tuning profile (`POST /v1/auto-tune/{id}/promote`). */\n public async promoteAutoTuneProfile(\n autoTuneJobId: string,\n body: PromoteProfileRequest,\n ): Promise<TuningProfileDetail> {\n return await this.requestJson<TuningProfileDetail>(\"POST\", `${this.autoTunePath(autoTuneJobId)}/promote`, {\n json: body,\n });\n }\n\n /** Fetch a completed auto-tune job's result (`GET /v1/auto-tune/{id}/result`). */\n public async getAutoTuneResult(autoTuneJobId: string): Promise<AutoTuneResult> {\n return await this.requestJson<AutoTuneResult>(\"GET\", `${this.autoTunePath(autoTuneJobId)}/result`);\n }\n\n // -- Shared tuning profiles --------------------------------------------\n\n /** List the project's tuning profiles (`GET /v1/tuning-profiles`). */\n public async listTuningProfiles(params: PaginationParams = {}): Promise<ListTuningProfilesResponse> {\n return await this.requestJson<ListTuningProfilesResponse>(\"GET\", TUNING_PROFILES_PATH, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /** Fetch one tuning profile (`GET /v1/tuning-profiles/{id}`). */\n public async getTuningProfile(profileId: string): Promise<TuningProfileDetail> {\n return await this.requestJson<TuningProfileDetail>(\"GET\", this.tuningProfilePath(profileId));\n }\n\n /** Delete a tuning profile (`DELETE /v1/tuning-profiles/{id}`). */\n public async deleteTuningProfile(profileId: string): Promise<void> {\n await this.requestJson(\"DELETE\", this.tuningProfilePath(profileId));\n }\n\n // -- Pro-only surface --------------------------------------------------\n\n /** Pro only: fetch the instance's accepted auth methods (`GET /auth/config`). */\n public async authConfig(): Promise<AuthConfigResponse> {\n await this.requireTier(\"pro\", \"authConfig\");\n return this.requestJson<AuthConfigResponse>(\"GET\", \"/auth/config\");\n }\n\n /** Pro only: exchange a verified OIDC ID token for a Pro session JWT (`POST /auth/login`). */\n public async login(body: LoginRequest): Promise<LoginResponse> {\n await this.requireTier(\"pro\", \"login\");\n return this.requestJson<LoginResponse>(\"POST\", \"/auth/login\", { json: body });\n }\n\n /** Pro only: fetch a project's RAG config (`GET /v1/projects/{projectId}/rag-config`). */\n public async getRagConfig(projectId: string): Promise<RagConfigResponse> {\n await this.requireTier(\"pro\", \"getRagConfig\");\n return this.requestJson<RagConfigResponse>(\"GET\", `/v1/projects/${encodePathSegment(projectId)}/rag-config`);\n }\n\n /** Pro only: update a project's RAG config (`PUT /v1/projects/{projectId}/rag-config`). */\n public async setRagConfig(projectId: string, body: SetRagConfigRequest): Promise<RagConfigResponse> {\n await this.requireTier(\"pro\", \"setRagConfig\");\n return this.requestJson<RagConfigResponse>(\"PUT\", `/v1/projects/${encodePathSegment(projectId)}/rag-config`, {\n json: body,\n });\n }\n\n // -- Pro-only control plane (projects, API keys, integrations) ---------\n\n /** Pro only: list the caller's projects (`GET /v1/projects`). */\n public async listProjects(params: PaginationParams = {}): Promise<ListProjectsResponse> {\n await this.requireTier(\"pro\", \"listProjects\");\n return this.requestJson<ListProjectsResponse>(\"GET\", \"/v1/projects\", {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /** Pro only: create a project owned by the caller (`POST /v1/projects`). */\n public async createProject(body: CreateProjectRequest): Promise<ProjectResponse> {\n await this.requireTier(\"pro\", \"createProject\");\n return this.requestJson<ProjectResponse>(\"POST\", \"/v1/projects\", { json: body });\n }\n\n /** Pro only: list a project's API keys (`GET /v1/projects/{projectId}/api-keys`). */\n public async listApiKeys(projectId: string, params: PaginationParams = {}): Promise<ListApiKeysResponse> {\n await this.requireTier(\"pro\", \"listApiKeys\");\n return this.requestJson<ListApiKeysResponse>(\"GET\", `${this.projectPath(projectId)}/api-keys`, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /** Pro only: mint an API key for a project (`POST /v1/projects/{projectId}/api-keys`). */\n public async createApiKey(projectId: string, body: CreateApiKeyRequest): Promise<CreateApiKeyResponse> {\n await this.requireTier(\"pro\", \"createApiKey\");\n return this.requestJson<CreateApiKeyResponse>(\"POST\", `${this.projectPath(projectId)}/api-keys`, { json: body });\n }\n\n /** Pro only: revoke an API key (`DELETE /v1/projects/{projectId}/api-keys/{keyId}`). */\n public async revokeApiKey(projectId: string, keyId: string): Promise<void> {\n await this.requireTier(\"pro\", \"revokeApiKey\");\n await this.requestJson(\"DELETE\", `${this.projectPath(projectId)}/api-keys/${encodePathSegment(keyId)}`);\n }\n\n /** Pro only: list a project's integrations (`GET /v1/projects/{projectId}/integrations`). */\n public async listIntegrations(projectId: string, params: PaginationParams = {}): Promise<ListIntegrationsResponse> {\n await this.requireTier(\"pro\", \"listIntegrations\");\n return this.requestJson<ListIntegrationsResponse>(\"GET\", `${this.projectPath(projectId)}/integrations`, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /** Pro only: create an integration (`POST /v1/projects/{projectId}/integrations`). */\n public async createIntegration(projectId: string, body: CreateIntegrationRequest): Promise<IntegrationResponse> {\n await this.requireTier(\"pro\", \"createIntegration\");\n return this.requestJson<IntegrationResponse>(\"POST\", `${this.projectPath(projectId)}/integrations`, {\n json: body,\n });\n }\n\n /** Pro only: fetch one integration (`GET .../integrations/{integrationId}`). */\n public async getIntegration(projectId: string, integrationId: string): Promise<IntegrationResponse> {\n await this.requireTier(\"pro\", \"getIntegration\");\n return this.requestJson<IntegrationResponse>(\"GET\", this.integrationPath(projectId, integrationId));\n }\n\n /** Pro only: delete an integration (`DELETE .../integrations/{integrationId}`). */\n public async deleteIntegration(projectId: string, integrationId: string): Promise<void> {\n await this.requireTier(\"pro\", \"deleteIntegration\");\n await this.requestJson(\"DELETE\", this.integrationPath(projectId, integrationId));\n }\n\n /**\n * Pro only: begin the OAuth flow for an integration\n * (`POST .../integrations/{integrationId}/connect`). Returns the provider\n * authorize URL to redirect the user to.\n */\n public async connectIntegration(projectId: string, integrationId: string): Promise<BeginOAuthResponse> {\n await this.requireTier(\"pro\", \"connectIntegration\");\n return this.requestJson<BeginOAuthResponse>(\"POST\", `${this.integrationPath(projectId, integrationId)}/connect`);\n }\n\n /** Pro only: revoke an integration's OAuth connection (`POST .../disconnect`). */\n public async disconnectIntegration(projectId: string, integrationId: string): Promise<void> {\n await this.requireTier(\"pro\", \"disconnectIntegration\");\n await this.requestJson(\"POST\", `${this.integrationPath(projectId, integrationId)}/disconnect`);\n }\n\n /** Pro only: list the documents an integration exposes (`GET .../documents`). */\n public async listIntegrationDocuments(\n projectId: string,\n integrationId: string,\n params: ListIntegrationDocumentsParams = {},\n ): Promise<ListDocumentsResponse> {\n await this.requireTier(\"pro\", \"listIntegrationDocuments\");\n return this.requestJson<ListDocumentsResponse>(\n \"GET\",\n `${this.integrationPath(projectId, integrationId)}/documents`,\n {\n params: {\n mime_types: params.mimeTypes,\n folder_id: params.folderId,\n max_results: params.maxResults,\n },\n },\n );\n }\n\n /**\n * Pro only: download one document from an integration\n * (`GET .../documents/{documentId}`). The response is raw bytes, not JSON.\n */\n public async fetchIntegrationDocument(\n projectId: string,\n integrationId: string,\n documentId: string,\n ): Promise<Uint8Array> {\n await this.requireTier(\"pro\", \"fetchIntegrationDocument\");\n const path = `${this.integrationPath(projectId, integrationId)}/documents/${encodePathSegment(documentId)}`;\n return this.requestBytes(\"GET\", path);\n }\n\n // -- Enterprise-only surface ------------------------------------------\n\n /**\n * Enterprise only: fetch a document's latest version with its extraction\n * result (`GET /v1/documents/{documentId}`). The spec declares an inline\n * schema, so the body is returned untyped.\n */\n public async getDocument(documentId: string): Promise<unknown> {\n await this.requireTier(\"enterprise\", \"getDocument\");\n return this.requestJson(\"GET\", this.documentPath(documentId));\n }\n\n /** Enterprise only: list a document's versions (`GET /v1/documents/{id}/versions`). */\n public async versions(documentId: string): Promise<DocumentVersionEntry[]> {\n await this.requireTier(\"enterprise\", \"versions\");\n return this.requestJson<DocumentVersionEntry[]>(\"GET\", `${this.documentPath(documentId)}/versions`);\n }\n\n /**\n * Enterprise only: diff document versions (`GET /v1/documents/{id}/diff`).\n *\n * Computed inline when the server can afford it (`200`, {@link DiffResponse}\n * in `result.body`), or queued for async computation when it can't (`202`,\n * a {@link DiffAsyncAccepted} job envelope in `result.body`) — the same\n * fallback {@link getDiffJob} polls. Narrow on `result.status`:\n *\n * ```ts\n * const result = await client.diff(documentId);\n * if (result.status === 200) {\n * // result.body: DiffResponse\n * } else {\n * // result.body: DiffAsyncAccepted — poll getDiffJob(documentId, result.body.diff_job_id)\n * }\n * ```\n */\n public async diff(documentId: string, params?: QueryParams): Promise<DiffResult> {\n await this.requireTier(\"enterprise\", \"diff\");\n const init: RequestParts = params !== undefined ? { params } : {};\n const { status, body } = await this.requestJsonWithStatus<DiffResponse | DiffAsyncAccepted>(\n \"GET\",\n `${this.documentPath(documentId)}/diff`,\n init,\n );\n return toDiffResult(status, body);\n }\n\n /**\n * Enterprise only: poll a diff job (`GET /v1/documents/{id}/diff/{diffJobId}`).\n *\n * Returns the same {@link DiffResult} union as {@link diff}: `200` once the\n * job has finished (`result.body`: {@link DiffResponse}), `202` while it is\n * still pending (`result.body`: {@link DiffAsyncAccepted}). Narrow on\n * `result.status` as shown in {@link diff}'s TSDoc.\n */\n public async getDiffJob(documentId: string, diffJobId: string): Promise<DiffResult> {\n await this.requireTier(\"enterprise\", \"getDiffJob\");\n const path = `${this.documentPath(documentId)}/diff/${encodePathSegment(diffJobId)}`;\n const { status, body } = await this.requestJsonWithStatus<DiffResponse | DiffAsyncAccepted>(\"GET\", path);\n return toDiffResult(status, body);\n }\n\n /** Enterprise only: list the project's extraction events (`GET /v1/extractions`). */\n public async listExtractionEvents(params: ListExtractionEventsParams = {}): Promise<ListExtractionEventsResponse> {\n await this.requireTier(\"enterprise\", \"listExtractionEvents\");\n return this.requestJson<ListExtractionEventsResponse>(\"GET\", EXTRACTIONS_PATH, {\n params: { days: params.days, limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Enterprise only: download one rendered page of an extraction job\n * (`GET /v1/jobs/{jobId}/pages/{pageNumber}`). The response is a PNG image —\n * raw bytes, not JSON. `pageNumber` is 1-indexed.\n */\n public async getJobPage(jobId: string, pageNumber: number): Promise<Uint8Array> {\n await this.requireTier(\"enterprise\", \"getJobPage\");\n const path = `${JOBS_PATH}/${encodePathSegment(jobId)}/pages/${encodePathSegment(String(pageNumber))}`;\n return this.requestBytes(\"GET\", path);\n }\n\n /** Enterprise only: submit text for enrichment (`POST /v1/enrich`). */\n public async submitEnrich(body: EnrichTextRequest): Promise<EnrichJobSubmitted> {\n await this.requireTier(\"enterprise\", \"submitEnrich\");\n return this.requestJson<EnrichJobSubmitted>(\"POST\", ENRICH_PATH, { json: body });\n }\n\n /** Enterprise only: fetch an enrichment job's status (`GET /v1/enrich/{jobId}`). */\n public async getEnrichStatus(jobId: string): Promise<EnrichJobStatus> {\n await this.requireTier(\"enterprise\", \"getEnrichStatus\");\n return this.requestJson<EnrichJobStatus>(\"GET\", `${ENRICH_PATH}/${encodePathSegment(jobId)}`);\n }\n\n /**\n * Enterprise only: stream a crawl job's events\n * (`GET /v1/crawl-jobs/{crawlJobId}/events`, Server-Sent Events).\n *\n * Returns an `AsyncIterable` of the `kind`-discriminated {@link CrawlEvent}\n * union; the server closes the stream after the `complete` event.\n *\n * ```ts\n * for await (const event of client.streamCrawlEvents(crawlJobId)) {\n * if (event.kind === \"page\") {\n * console.log(event.url, event.status_code);\n * }\n * }\n * ```\n *\n * Nothing is requested — not even the `/healthz` tier probe — until\n * iteration begins, and the response body is cancelled when iteration ends:\n * on `complete`, on `break`/`return` out of the loop, on a thrown error, or\n * when `options.signal` aborts. A stream is idle between events by design,\n * so unlike every other method here it carries no request timeout and is not\n * routed through the retry engine — a retried subscription would redeliver\n * every event the caller had already handled.\n */\n public streamCrawlEvents(crawlJobId: string, options: StreamCrawlEventsOptions = {}): AsyncIterable<CrawlEvent> {\n const path = `${CRAWL_JOBS_PATH}/${encodePathSegment(crawlJobId)}/events`;\n const open = async (): Promise<Response> => {\n await this.requireTier(\"enterprise\", \"streamCrawlEvents\");\n return this.openEventStream(path, options.signal);\n };\n return { [Symbol.asyncIterator]: (): AsyncIterator<CrawlEvent> => iterateCrawlEvents(open) };\n }\n\n /** Enterprise only: request a presigned upload URL (`POST /v1/uploads/presign`). */\n public async presignUpload(body: PresignUploadRequest): Promise<PresignUploadResponse> {\n await this.requireTier(\"enterprise\", \"presignUpload\");\n return this.requestJson<PresignUploadResponse>(\"POST\", \"/v1/uploads/presign\", { json: body });\n }\n\n /** Enterprise only: confirm a presigned upload (`POST /v1/uploads/confirm`). */\n public async confirmUpload(body: ConfirmUploadRequest): Promise<ConfirmUploadResponse> {\n await this.requireTier(\"enterprise\", \"confirmUpload\");\n return this.requestJson<ConfirmUploadResponse>(\"POST\", \"/v1/uploads/confirm\", { json: body });\n }\n\n /** Enterprise only: fetch usage/metering data (`GET /v1/usage`). */\n public async usage(params?: QueryParams): Promise<UsageResponse> {\n await this.requireTier(\"enterprise\", \"usage\");\n const init: RequestParts = params !== undefined ? { params } : {};\n return this.requestJson<UsageResponse>(\"GET\", \"/v1/usage\", init);\n }\n\n // -- Internals ---------------------------------------------------------\n\n /** Build `/v1/projects/{projectId}` with the id percent-encoded. */\n private projectPath(projectId: string): string {\n return `/v1/projects/${encodePathSegment(projectId)}`;\n }\n\n /** Build `/v1/projects/{projectId}/integrations/{integrationId}`. */\n private integrationPath(projectId: string, integrationId: string): string {\n return `${this.projectPath(projectId)}/integrations/${encodePathSegment(integrationId)}`;\n }\n\n /** Build `/v1/documents/{documentId}` with the id percent-encoded. */\n private documentPath(documentId: string): string {\n return `${DOCUMENTS_PATH}/${encodePathSegment(documentId)}`;\n }\n\n /** Build `/v1/auto-tune/{id}` with the id percent-encoded. */\n private autoTunePath(autoTuneJobId: string): string {\n return `${AUTO_TUNE_PATH}/${encodePathSegment(autoTuneJobId)}`;\n }\n\n /** Build `/v1/tuning-profiles/{id}` with the id percent-encoded. */\n private tuningProfilePath(profileId: string): string {\n return `${TUNING_PROFILES_PATH}/${encodePathSegment(profileId)}`;\n }\n\n /**\n * Resolve the tier and render the saved-preset path in that tier's spelling:\n * `/v1/saved-presets` on Pro, `/v1/saved_presets` everywhere else. Pass a\n * `presetId` for the single-preset routes.\n */\n private async savedPresetsPath(presetId?: string): Promise<string> {\n const tier = await this.resolveTier();\n const base = tier === \"pro\" ? SAVED_PRESETS_PATH_PRO : SAVED_PRESETS_PATH_ENTERPRISE;\n return presetId === undefined ? base : `${base}/${encodePathSegment(presetId)}`;\n }\n\n /**\n * Return the effective tier — an explicit `target` if set, else probed from\n * `/healthz` and cached after the first *successful* probe. A probe that\n * fails (missing, `null`, or unrecognised `tier`) is not cached, so the\n * next call retries instead of being stuck with a poisoned result for the\n * client's lifetime. Concurrent callers share a single in-flight probe.\n */\n private async resolveTier(): Promise<Target> {\n if (this.target !== undefined) {\n return this.target;\n }\n if (this.probedTier !== undefined) {\n return this.probedTier;\n }\n if (this.tierProbe === undefined) {\n this.tierProbe = this.probeTier();\n }\n try {\n const tier = await this.tierProbe;\n this.probedTier = tier;\n return tier;\n } finally {\n this.tierProbe = undefined;\n }\n }\n\n /**\n * Issue the `/healthz` capability probe. Only `\"enterprise\"` and `\"pro\"` —\n * the tier values the specs actually declare — are accepted; anything else\n * (missing `tier`, `null`, or an unrecognised string) throws instead of\n * being treated as a usable result.\n */\n private async probeTier(): Promise<Target> {\n const body = await this.requestJson<{ tier?: unknown }>(\"GET\", \"/healthz\");\n const tier = body?.tier;\n if (tier === \"enterprise\" || tier === \"pro\") {\n return tier;\n }\n throw new XbergError(\n `/healthz returned an unrecognised tier (${JSON.stringify(tier ?? null)}); expected \"enterprise\" or \"pro\"`,\n { status: 0, body },\n );\n }\n\n /** Throw a clear error when the connected tier does not match the required one. */\n private async requireTier(required: Target, methodName: string): Promise<void> {\n const tier = await this.resolveTier();\n if (tier !== required) {\n throw new XbergError(`${methodName}() is not available on the '${tier}' tier (requires the '${required}' tier)`, {\n status: 0,\n body: null,\n });\n }\n }\n\n private backendRequest<T>(method: string, path: string, init: RequestParts = {}): Promise<T> {\n return this.requestJson<T>(method, path, { ...init, controlPlane: true });\n }\n\n private backendHeaders(init: RequestParts): Record<string, string> {\n const headers = new Headers({ ...this.headers, ...init.headers });\n for (const name of [\"authorization\", \"proxy-authorization\", \"cookie\", \"x-api-key\"]) headers.delete(name);\n const token = init.backendPublic ? init.sandboxToken : this.controlPlaneToken;\n if (token !== undefined && token.length > 0) headers.set(\"Authorization\", `Bearer ${token}`);\n if (init.body instanceof FormData || init.json !== undefined) headers.delete(\"content-type\");\n return Object.fromEntries(headers);\n }\n\n /** Issue a request, raise on non-2xx, and decode the JSON body (undefined for empty bodies). */\n private async requestJson<T = unknown>(method: string, path: string, init: RequestParts = {}): Promise<T> {\n const { body } = await this.requestJsonWithStatus<T>(method, path, init);\n return body;\n }\n\n /**\n * Like {@link requestJson}, but also returns the response's status code.\n * Used by endpoints whose 2xx responses carry different schemas per status\n * (currently only `diff`/`getDiffJob`'s `200`/`202` split).\n */\n private async requestJsonWithStatus<T = unknown>(\n method: string,\n path: string,\n init: RequestParts = {},\n ): Promise<{ status: number; body: T }> {\n const response = await this.requestWithRetry(method, path, init);\n if (response.status === 204) {\n return { status: response.status, body: undefined as T };\n }\n const text = await response.text();\n const body = (text.length > 0 ? JSON.parse(text) : undefined) as T;\n return { status: response.status, body };\n }\n\n /**\n * Open a `text/event-stream` response, deliberately bypassing\n * {@link requestWithRetry}.\n *\n * Two of that method's behaviours are wrong for a subscription. Its retry\n * loop would re-open a partly-consumed stream and redeliver every event the\n * caller already handled — indistinguishable, from the caller's side, from\n * the server sending them twice. And its `AbortSignal.timeout(timeoutMs)`\n * bounds a request/response round trip, while this response stays open for\n * the length of a crawl and is idle between events by design; the caller's\n * own `signal` is the only deadline.\n */\n private async openEventStream(path: string, signal?: AbortSignal): Promise<Response> {\n const url = `${this.baseUrl}${path}`;\n const requestInit: RequestInit = {\n method: \"GET\",\n headers: { ...this.headers, Accept: EVENT_STREAM_MEDIA_TYPE },\n };\n if (signal !== undefined) {\n requestInit.signal = signal;\n }\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, requestInit);\n } catch (cause) {\n throw new XbergError(`Network error contacting ${url}`, { status: 0, body: null, cause });\n }\n if (!response.ok) {\n await raiseForStatus(response);\n throw new XbergError(\"Unreachable\", { status: response.status, body: null });\n }\n return response;\n }\n\n /** Issue a request, raise on non-2xx, and return the response body as raw bytes. */\n private async requestBytes(method: string, path: string, init: RequestParts = {}): Promise<Uint8Array> {\n const response = await this.requestWithRetry(method, path, init);\n return new Uint8Array(await response.arrayBuffer());\n }\n\n /**\n * Issue a raw HTTP request with auth, timeout, query params, and retry\n * handling. Returns the raw (2xx) {@link Response}; non-2xx responses are\n * mapped to a thrown {@link XbergError} subclass.\n */\n private prepareRequest(method: string, init: RequestParts): RequestInit {\n const headers = init.controlPlane ? this.backendHeaders(init) : { ...this.headers, ...init.headers };\n let body: FormData | string | Uint8Array | undefined = init.body;\n if (init.json !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(init.json);\n }\n const requestInit: RequestInit = {\n method,\n headers,\n signal: AbortSignal.timeout(this.timeoutMs),\n ...(init.controlPlane ? ({ credentials: \"omit\", redirect: \"manual\" } as const) : {}),\n };\n if (body !== undefined) {\n requestInit.body = body;\n }\n return requestInit;\n }\n\n private async requestWithRetry(method: string, path: string, init: RequestParts = {}): Promise<Response> {\n if (init.controlPlane && (this.target ?? this.probedTier) === \"pro\") {\n throw new XbergError(\"Enterprise backend methods are not available on the 'pro' tier\", { status: 0, body: null });\n }\n const origin = init.controlPlane ? this.controlPlaneBaseUrl : this.baseUrl;\n const url = `${origin}${path}${buildQueryString(init.params)}`;\n let attempt = 0;\n let interval = DEFAULT_RETRY_BACKOFF_BASE_MS;\n for (;;) {\n const requestInit = this.prepareRequest(method, init);\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, requestInit);\n } catch (cause) {\n if (attempt < this.retries) {\n attempt += 1;\n await this.sleep(interval);\n interval = nextBackoffInterval(interval, this.retryBackoff);\n continue;\n }\n if (init.controlPlane) {\n throw new XbergError(`Network error contacting Enterprise control plane (${method} ${path})`, {\n status: 0,\n body: null,\n });\n }\n throw new XbergError(`Network error contacting ${url}`, { status: 0, body: null, cause });\n }\n\n if (response.ok || (init.acceptRedirect && response.status === 303)) {\n return response;\n }\n\n if (this.retryOn.includes(response.status) && attempt < this.retries) {\n attempt += 1;\n const retryAfter = parseRetryAfterHeader(response.headers.get(\"retry-after\"));\n const wait = retryAfter !== undefined ? retryAfter * 1000 : interval;\n await this.sleep(wait);\n interval = nextBackoffInterval(interval, this.retryBackoff);\n continue;\n }\n\n try {\n await raiseForStatus(response);\n } catch (error) {\n if (error instanceof RateLimitError && error.retryAfter !== undefined && attempt < this.retries) {\n attempt += 1;\n await this.sleep(error.retryAfter * 1000);\n interval = nextBackoffInterval(interval, this.retryBackoff);\n continue;\n }\n throw error;\n }\n throw new XbergError(\"Unreachable\", { status: response.status, body: null });\n }\n }\n}\n\n/** Parts accepted by the internal request engine. */\ninterface RequestParts {\n controlPlane?: boolean;\n backendPublic?: boolean;\n sandboxToken?: string;\n acceptRedirect?: boolean;\n body?: FormData | string | Uint8Array;\n json?: unknown;\n headers?: Record<string, string>;\n params?: QueryParams;\n}\n\n/**\n * Pair a diff response's status code with its body to build the\n * {@link DiffResult} union `diff`/`getDiffJob` return. `202` is the only\n * status carrying {@link DiffAsyncAccepted}; everything else (in practice\n * only `200`) carries the computed {@link DiffResponse}.\n */\nfunction toDiffResult(status: number, body: DiffResponse | DiffAsyncAccepted): DiffResult {\n if (status === 202) {\n return { status: 202, body: body as DiffAsyncAccepted };\n }\n return { status: 200, body: body as DiffResponse };\n}\n\n/**\n * Serialize a value with object keys sorted, so two configs that differ only in\n * key order compare equal when {@link appendPerFileConfigs} looks for a conflict.\n * Only ever used for that comparison — the value actually appended to the form is\n * a plain `JSON.stringify`, matching the `options` and `webhook` parts.\n */\nfunction canonicalJson(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map((entry) => canonicalJson(entry)).join(\",\")}]`;\n }\n if (typeof value === \"object\" && value !== null) {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, entry]) => entry !== undefined)\n .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));\n return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n\n/**\n * Append one `config-<filename>` part per document carrying a per-file override.\n *\n * Appended after the `file`, `options` and `webhook` parts, and skipped entirely\n * when `configs` is undefined, so a request without overrides is byte-identical\n * to one built before this existed.\n *\n * The part is keyed on the filename, mirroring the `document_id-<filename>`\n * convention. Two documents submitted under the same filename therefore have one\n * slot for two overrides: rather than let the later `append` win and lose the\n * other with no signal, that case throws and names the file.\n */\nfunction appendPerFileConfigs(\n form: FormData,\n filenames: readonly string[],\n configs: readonly (FileExtractionConfig | null)[] | undefined,\n): void {\n if (configs === undefined) {\n return;\n }\n if (configs.length !== filenames.length) {\n throw new XbergError(\n `configs has ${configs.length} entries but ${filenames.length} files were supplied; ` +\n \"pass exactly one entry per file (null for no override)\",\n { status: 400, body: null },\n );\n }\n const seen = new Map<string, string>();\n filenames.forEach((filename, index) => {\n const config = configs[index] ?? null;\n const canonical = canonicalJson(config);\n const prior = seen.get(filename);\n if (prior !== undefined && prior !== canonical) {\n throw new XbergError(\n `per-file config conflict for \"${filename}\": the same filename appears more than once in ` +\n \"this batch with different configs, but a multipart request carries at most one config \" +\n \"part per filename. Give the copies distinct filenames.\",\n { status: 400, body: null },\n );\n }\n if (prior === undefined && config !== null) {\n form.append(`config-${filename}`, JSON.stringify(config));\n }\n seen.set(filename, canonical);\n });\n}\n\n/** Parse one SSE frame payload into the `kind`-discriminated {@link CrawlEvent} it names. */\nfunction parseCrawlEvent(payload: string): CrawlEvent {\n let body: unknown;\n try {\n body = JSON.parse(payload);\n } catch (cause) {\n throw new XbergError(`Crawl event stream sent a non-JSON frame: ${payload}`, {\n status: 0,\n body: payload,\n cause,\n });\n }\n const kind = (body as { kind?: unknown } | null)?.kind;\n if (typeof kind !== \"string\" || !CRAWL_EVENT_KINDS.has(kind)) {\n throw new XbergError(`Crawl event stream sent an unrecognised kind (${JSON.stringify(kind ?? null)})`, {\n status: 0,\n body,\n });\n }\n return body as CrawlEvent;\n}\n\n/**\n * Drive one crawl-event subscription: open it, decode its frames, and cancel\n * the response body on every exit path.\n *\n * `open` is a thunk rather than an already-opened `Response` so that a caller\n * who never iterates opens nothing — the tier gate and the request both live\n * inside the generator. The `finally` runs when the consumer `break`s or\n * `return`s out of its `for await` as much as when the stream ends, which is\n * what makes the subscription cancellable without a separate handle.\n */\nasync function* iterateCrawlEvents(open: () => Promise<Response>): AsyncGenerator<CrawlEvent> {\n const response = await open();\n if (response.body === null) {\n throw new XbergError(\"Crawl event stream response carried no body\", {\n status: response.status,\n body: null,\n });\n }\n const reader = response.body.getReader();\n const text = new TextDecoder();\n const frames = new EventStreamDecoder();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n return;\n }\n for (const payload of frames.push(text.decode(value, { stream: true }))) {\n yield parseCrawlEvent(payload);\n }\n }\n } finally {\n // Never let a teardown failure mask the error that caused the teardown.\n await reader.cancel().catch(() => undefined);\n }\n}\n\n/** Backwards-compatible factory returning the low-level `openapi-fetch` client. */\nexport interface CreateClientOptions {\n baseUrl?: string;\n apiKey?: string;\n headers?: Record<string, string>;\n fetch?: typeof fetch;\n}\n\nexport function createClient(options: CreateClientOptions = {}): XbergRawClient {\n const headers: Record<string, string> = {\n \"User-Agent\": USER_AGENT,\n ...options.headers,\n };\n if (options.apiKey !== undefined) {\n headers[\"Authorization\"] = `Bearer ${options.apiKey}`;\n }\n return createOpenApiClient<paths>({\n baseUrl: options.baseUrl ?? DEFAULT_ENTERPRISE_BASE_URL,\n headers,\n ...(options.fetch !== undefined ? { fetch: options.fetch } : {}),\n });\n}\n\nfunction sandboxForm(params: PublicSandboxExtractParams): FormData {\n if (params.file === undefined && !(params.mode === \"web\" && params.url !== undefined && params.url.length > 0)) {\n throw new XbergError(\"Sandbox extraction requires a file or web mode with a URL\", { status: 400, body: null });\n }\n const form = new FormData();\n if (params.file !== undefined) {\n const { blob, filename } = toBlob(params.file);\n form.append(\"file\", blob, filename);\n }\n for (const name of [\"mode\", \"preset\", \"url\"] as const) {\n const value = params[name];\n if (value !== undefined) form.append(name, value);\n }\n return form;\n}\n\nfunction prepareDocumentLineage(\n filenames: readonly string[],\n ids: readonly (string | null)[] | undefined,\n): Map<string, string> {\n const fields = new Map<string, string>();\n if (ids === undefined) return fields;\n if (ids.length !== filenames.length)\n throw new XbergError(\"documentIds must contain one entry per file\", { status: 400, body: null });\n const seen = new Map<string, string | null>();\n for (const [index, filename] of filenames.entries()) {\n const id = ids[index];\n if (\n id !== null &&\n (typeof id !== \"string\" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id))\n ) {\n throw new XbergError(\"documentIds must contain UUID strings or null\", { status: 400, body: null });\n }\n const canonical = id === null ? null : id.toLowerCase();\n if (seen.has(filename) && seen.get(filename) !== canonical)\n throw new XbergError(\"Conflicting document IDs for the same filename\", { status: 400, body: null });\n seen.set(filename, canonical);\n if (canonical !== null) fields.set(filename, canonical);\n }\n return fields;\n}\n"],"mappings":";;;AAcA,IAAa,aAAb,cAAgC,MAAM;CACpC,AAAgB;CAChB,AAAgB;CAEhB,AAAO,YAAY,SAAiB,SAA4B;EAC9D,MAAMA,YAA0B,QAAQ,UAAU,SAAY,EAAE,GAAG,EAAE,OAAO,QAAQ,OAAO;AAC3F,QAAM,SAAS,UAAU;AACzB,OAAK,OAAO;AACZ,OAAK,SAAS,QAAQ;AACtB,OAAK,OAAO,QAAQ;;;AAIxB,IAAa,YAAb,cAA+B,WAAW;CACxC,AAAO,YAAY,SAAiB,SAA4B;AAC9D,QAAM,SAAS,QAAQ;AACvB,OAAK,OAAO;;;AAQhB,IAAa,iBAAb,cAAoC,WAAW;CAC7C,AAAgB;CAEhB,AAAO,YAAY,SAAiB,SAAgC;AAClE,QAAM,SAAS,QAAQ;AACvB,OAAK,OAAO;AACZ,MAAI,QAAQ,eAAe,OACzB,MAAK,aAAa,QAAQ;;;AAKhC,IAAa,kBAAb,cAAqC,WAAW;CAC9C,AAAO,YAAY,SAAiB,SAA4B;AAC9D,QAAM,SAAS,QAAQ;AACvB,OAAK,OAAO;;;AAIhB,IAAa,gBAAb,cAAmC,WAAW;CAC5C,AAAO,YAAY,SAAiB,SAA4B;AAC9D,QAAM,SAAS,QAAQ;AACvB,OAAK,OAAO;;;AAIhB,IAAa,cAAb,cAAiC,WAAW;CAC1C,AAAO,YAAY,SAAiB,SAA4B;AAC9D,QAAM,SAAS,QAAQ;AACvB,OAAK,OAAO;;;AAIhB,IAAa,eAAb,cAAkC,WAAW;CAC3C,AAAO,YAAY,SAAiB,SAA4B;AAC9D,QAAM,SAAS,QAAQ;AACvB,OAAK,OAAO;;;;;;;;;;;AAYhB,eAAsB,eAAe,UAAoC;CACvE,M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MAAM;;AAEnD,QAAO;;AAGT,SAAS,uBACP,WACA,KACqB;CACrB,MAAM,yBAAS,IAAI,KAAqB;AACxC,KAAI,QAAQ,OAAW,QAAO;AAC9B,KAAI,IAAI,WAAW,UAAU,OAC3B,OAAM,IAAI,WAAW,+CAA+C;EAAE,QAAQ;EAAK,MAAM;EAAM,CAAC;CAClG,MAAM,uBAAO,IAAI,KAA4B;AAC7C,MAAK,MAAM,CAAC,OAAO,aAAa,UAAU,SAAS,EAAE;EACnD,MAAM,KAAK,IAAI;AACf,MACE,OAAO,SACN,OAAO,OAAO,YAAY,CAAC,kEAAkE,KAAK,GAAG,EAEtG,OAAM,IAAI,WAAW,iDAAiD;GAAE,QAAQ;GAAK,MAAM;GAAM,CAAC;EAEpG,MAAM,YAAY,OAAO,OAAO,OAAO,GAAG,aAAa;AACvD,MAAI,KAAK,IAAI,SAAS,IAAI,KAAK,IAAI,SAAS,KAAK,UAC/C,OAAM,IAAI,WAAW,kDAAkD;GAAE,QAAQ;GAAK,MAAM;GAAM,CAAC;AACrG,OAAK,IAAI,UAAU,UAAU;AAC7B,MAAI,cAAc,KAAM,QAAO,IAAI,UAAU,UAAU;;AAEzD,QAAO"}
1
+ {"version":3,"file":"index.js","names":["errorInit: ErrorOptions","options: XbergErrorOptions","payloads: string[]","TERMINAL_JOB_STATUSES: readonly JobStatus[]","SUCCESS_JOB_STATUSES: readonly JobStatus[]","DEFAULT_RETRY_STATUSES: readonly number[]","CRAWL_EVENT_KINDS: ReadonlySet<string>","extractParams: ExtractParams","waitOptions: WaitOptions","init: RequestParts","requestInit: RequestInit","response: Response","body: FormData | string | Uint8Array | undefined","body: unknown","headers: Record<string, string>"],"sources":["../src/errors.ts","../src/_internal.ts","../src/types.ts","../src/version.ts","../src/client.ts"],"sourcesContent":["/**\n * Error class hierarchy for the Xberg SDK (Enterprise + Pro).\n *\n * Every non-2xx HTTP response is mapped to a subclass of {@link XbergError}.\n * `TimeoutError` is also raised when {@link XbergClient.waitForJob} exceeds its\n * configured deadline (distinct from a network/fetch timeout).\n */\n\nexport interface XbergErrorOptions {\n status: number;\n body: unknown;\n cause?: unknown;\n}\n\nexport class XbergError extends Error {\n public readonly status: number;\n public readonly body: unknown;\n\n public constructor(message: string, options: XbergErrorOptions) {\n const errorInit: ErrorOptions = options.cause === undefined ? {} : { cause: options.cause };\n super(message, errorInit);\n this.name = \"XbergError\";\n this.status = options.status;\n this.body = options.body;\n }\n}\n\nexport class AuthError extends XbergError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"AuthError\";\n }\n}\n\nexport interface RateLimitErrorOptions extends XbergErrorOptions {\n retryAfter?: number;\n}\n\nexport class RateLimitError extends XbergError {\n public readonly retryAfter?: number;\n\n public constructor(message: string, options: RateLimitErrorOptions) {\n super(message, options);\n this.name = \"RateLimitError\";\n if (options.retryAfter !== undefined) {\n this.retryAfter = options.retryAfter;\n }\n }\n}\n\nexport class ValidationError extends XbergError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"ValidationError\";\n }\n}\n\nexport class NotFoundError extends XbergError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"NotFoundError\";\n }\n}\n\nexport class ServerError extends XbergError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"ServerError\";\n }\n}\n\nexport class TimeoutError extends XbergError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"TimeoutError\";\n }\n}\n\n/**\n * Map an HTTP response status to the matching error subclass and throw it.\n *\n * Always throws — call as `throw await raiseForStatus(response)` if you want\n * the type system to see the unreachable code, otherwise just `await`. Both\n * 401 and 403 map to {@link AuthError} — the API uses 403 for a\n * valid-but-forbidden principal.\n */\nexport async function raiseForStatus(response: Response): Promise<never> {\n const body = await readBody(response);\n const message = extractErrorMessage(body) ?? `Request failed with status ${response.status}`;\n const options: XbergErrorOptions = { status: response.status, body };\n\n if (response.status === 401 || response.status === 403) {\n throw new AuthError(message, options);\n }\n if (response.status === 404) {\n throw new NotFoundError(message, options);\n }\n if (response.status === 429) {\n const retryAfterRaw = response.headers.get(\"retry-after\");\n const retryAfter = parseRetryAfter(retryAfterRaw);\n const opts: RateLimitErrorOptions = retryAfter === undefined ? options : { ...options, retryAfter };\n throw new RateLimitError(message, opts);\n }\n if (response.status >= 400 && response.status < 500) {\n throw new ValidationError(message, options);\n }\n if (response.status >= 500) {\n throw new ServerError(message, options);\n }\n throw new XbergError(message, options);\n}\n\nasync function readBody(response: Response): Promise<unknown> {\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (contentType.includes(\"application/json\")) {\n try {\n return await response.json();\n } catch {\n return undefined;\n }\n }\n try {\n const text = await response.text();\n return text === \"\" ? undefined : text;\n } catch {\n return undefined;\n }\n}\n\nfunction extractErrorMessage(body: unknown): string | undefined {\n if (typeof body === \"string\" && body.length > 0) {\n return body;\n }\n if (body !== null && typeof body === \"object\") {\n const record = body as Record<string, unknown>;\n const error = record[\"error\"];\n if (typeof error === \"string\" && error.length > 0) {\n return error;\n }\n const message = record[\"message\"];\n if (typeof message === \"string\" && message.length > 0) {\n return message;\n }\n }\n return undefined;\n}\n\nfunction parseRetryAfter(value: string | null): number | undefined {\n if (value === null) {\n return undefined;\n }\n const seconds = Number(value);\n if (Number.isFinite(seconds) && seconds >= 0) {\n return seconds;\n }\n const parsed = Date.parse(value);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n const delta = Math.max(0, Math.ceil((parsed - Date.now()) / 1000));\n return delta;\n}\n","/**\n * Internal helpers for {@link XbergClient}: base-URL resolution, query-string\n * and backoff arithmetic, the file-to-`Blob` conversion the multipart request\n * paths need, and the event-stream frame decoder `streamCrawlEvents` reads its\n * response through. Not part of the public API — of the names here only\n * {@link FileLike} and {@link BackoffStrategy} are re-exported, via `client.ts`,\n * because they appear in public client signatures.\n */\n\nimport { XbergError } from \"./errors.js\";\n\nexport const DEFAULT_ENTERPRISE_BASE_URL = \"https://api.xberg.io\";\nexport const DEFAULT_RETRY_BACKOFF_CAP_MS = 30_000;\nexport const DEFAULT_BACKOFF_FACTOR = 2;\n\n/**\n * Caps an event-stream frame. The frames this endpoint sends are a few hundred\n * bytes; the cap exists so a server that never closes a frame cannot grow this\n * decoder without bound.\n *\n * It is applied twice, because one application does not cover the other: to the\n * pending line, so one endless line cannot fill memory, and to the running\n * total of a frame's `data:` fields, so an endless succession of shorter lines\n * never followed by the blank line that would close the frame cannot either.\n */\nexport const MAX_EVENT_STREAM_FRAME_BYTES = 1 << 20;\n\n/**\n * Backoff strategy for retries and `waitForJob` polling.\n *\n * - `exponential` — interval doubles after every attempt, capped at 30s.\n * - `constant` — interval stays the same on every attempt.\n */\nexport type BackoffStrategy = \"exponential\" | \"constant\";\n\n/** Which product the client targets. */\nexport type Target = \"enterprise\" | \"pro\";\n\n/** Query-string values accepted by the internal request engine. */\nexport type QueryParams = Record<string, string | number | undefined>;\n\n/** Anything the client accepts as an uploadable file. */\nexport type FileLike = File | Blob | Uint8Array | { name?: string; data: Blob | Uint8Array; mimeType?: string };\n\n/**\n * Resolve the effective base URL, enforcing that Pro requires an explicit one.\n */\nexport function resolveBaseUrl(baseUrl: string | undefined, target: Target | undefined): string {\n if (baseUrl !== undefined) {\n return baseUrl.replace(/\\/+$/, \"\");\n }\n if (target === \"pro\") {\n throw new XbergError(\n \"Xberg Pro has no default base URL (its spec ships no servers block); pass baseUrl pointing at your Pro instance.\",\n { status: 0, body: null },\n );\n }\n return DEFAULT_ENTERPRISE_BASE_URL;\n}\n\n/**\n * Resolve the base URL of the Enterprise control plane, defaulting to the data plane's.\n *\n * Enterprise runs the control plane (projects, API keys, integrations, RAG\n * config, members, invitations, managed webhooks, usage, analytics, billing) as\n * a second binary on its own origin; Pro serves it from the same one. The\n * default therefore has to be `baseUrl`, exactly as the console's\n * `NEXT_PUBLIC_BACKEND_API_URL` is same-origin unless set — anything else would\n * break every Pro control-plane call the moment this option existed.\n */\nexport function resolveControlPlaneBaseUrl(controlPlaneBaseUrl: string | undefined, baseUrl: string): string {\n if (controlPlaneBaseUrl !== undefined) {\n return controlPlaneBaseUrl.replace(/\\/+$/, \"\");\n }\n return baseUrl;\n}\n\nexport function defaultSleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\nexport function buildQueryString(params: QueryParams | undefined): string {\n if (params === undefined) {\n return \"\";\n }\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n search.append(key, String(value));\n }\n }\n const query = search.toString();\n return query.length > 0 ? `?${query}` : \"\";\n}\n\nexport function nextBackoffInterval(current: number, strategy: BackoffStrategy): number {\n if (strategy === \"constant\") {\n return current;\n }\n return Math.min(current * DEFAULT_BACKOFF_FACTOR, DEFAULT_RETRY_BACKOFF_CAP_MS);\n}\n\nexport function parseRetryAfterHeader(value: string | null): number | undefined {\n if (value === null) {\n return undefined;\n }\n const seconds = Number(value);\n if (Number.isFinite(seconds) && seconds >= 0) {\n return seconds;\n }\n const parsed = Date.parse(value);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n return Math.max(0, Math.ceil((parsed - Date.now()) / 1000));\n}\n\n/** Convert a {@link FileLike} input into a `Blob` plus best-guess filename. */\nexport function toBlob(file: FileLike): { blob: Blob; filename: string } {\n if (typeof File !== \"undefined\" && file instanceof File) {\n return { blob: file, filename: file.name };\n }\n if (file instanceof Blob) {\n return { blob: file, filename: \"upload.bin\" };\n }\n if (file instanceof Uint8Array) {\n return {\n blob: new Blob([blobBytes(file)], { type: \"application/octet-stream\" }),\n filename: \"upload.bin\",\n };\n }\n const wrapper = file;\n const name = wrapper.name ?? \"upload.bin\";\n const mimeType = wrapper.mimeType ?? guessMimeType(name);\n if (wrapper.data instanceof Blob) {\n return { blob: wrapper.data, filename: name };\n }\n return {\n blob: new Blob([blobBytes(wrapper.data)], { type: mimeType }),\n filename: name,\n };\n}\n\nfunction blobBytes(bytes: Uint8Array): Uint8Array<ArrayBuffer> {\n // ~keep Blob snapshots its input. A view avoids a second payload copy; shared backing requires an ordinary buffer.\n return bytes.buffer instanceof ArrayBuffer\n ? new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n : new Uint8Array(bytes);\n}\n\nfunction guessMimeType(filename: string): string {\n const lower = filename.toLowerCase();\n if (lower.endsWith(\".csv\")) {\n return \"text/csv\";\n }\n if (lower.endsWith(\".md\")) {\n return \"text/markdown\";\n }\n if (lower.endsWith(\".pdf\")) {\n return \"application/pdf\";\n }\n if (lower.endsWith(\".txt\")) {\n return \"text/plain\";\n }\n if (lower.endsWith(\".docx\")) {\n return \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\";\n }\n return \"application/octet-stream\";\n}\n\n/** Guess a display name for a file (used to populate `Job.filename`). */\nexport function describeFile(file: FileLike): string {\n if (typeof File !== \"undefined\" && file instanceof File) {\n return file.name;\n }\n if (file instanceof Blob || file instanceof Uint8Array) {\n return \"upload.bin\";\n }\n return file.name ?? \"upload.bin\";\n}\n\n/**\n * Incremental decoder for a `text/event-stream` body, fed the decoded text of\n * each network chunk.\n *\n * Implements the parts of the WHATWG event-stream parser this endpoint can\n * exercise. A frame is terminated by a *blank line*, not by a newline: its\n * payload is every `data:` field it carried, joined with `\\n`. Lines opening\n * with `:` are comments — the endpoint's 15s heartbeat is one — and\n * `event:`/`id:`/`retry:` fields are accepted and ignored. A single space\n * after a field's colon is framing, not value, so it is stripped.\n *\n * All of which is why this exists instead of `JSON.parse` per line: against a\n * server that happens to emit one compact frame per line the naive version\n * passes every test, then silently drops every multi-line payload and throws\n * on the first heartbeat against a real one. Chunk boundaries fall wherever\n * the network puts them, so lines are also reassembled here rather than\n * assumed to arrive whole.\n */\nexport class EventStreamDecoder {\n private buffer = \"\";\n private data: string[] = [];\n /** Running length of the frame being assembled, reset with `data` on dispatch. */\n private size = 0;\n\n /** Consume one chunk of decoded text, returning the payload of every frame it completed. */\n public push(chunk: string): string[] {\n this.buffer += chunk;\n const payloads: string[] = [];\n for (;;) {\n const boundary = this.nextLineBoundary();\n if (boundary === undefined) {\n if (this.buffer.length > MAX_EVENT_STREAM_FRAME_BYTES) {\n throw new XbergError(`Crawl event stream sent a line longer than ${MAX_EVENT_STREAM_FRAME_BYTES} bytes`, {\n status: 0,\n body: null,\n });\n }\n return payloads;\n }\n const line = this.buffer.slice(0, boundary.index);\n this.buffer = this.buffer.slice(boundary.index + boundary.width);\n const payload = this.feed(line);\n if (payload !== undefined) {\n payloads.push(payload);\n }\n }\n }\n\n /**\n * Locate the next `\\n`, `\\r\\n` or `\\r` in the buffer. A trailing `\\r` is\n * reported as \"no boundary yet\": it may be the first half of a `\\r\\n` the\n * network split across two chunks, and treating it as a terminator there\n * would dispatch a frame one line early.\n */\n private nextLineBoundary(): { index: number; width: number } | undefined {\n for (let index = 0; index < this.buffer.length; index += 1) {\n const character = this.buffer[index];\n if (character === \"\\n\") {\n return { index, width: 1 };\n }\n if (character === \"\\r\") {\n if (index === this.buffer.length - 1) {\n return undefined;\n }\n return { index, width: this.buffer[index + 1] === \"\\n\" ? 2 : 1 };\n }\n }\n return undefined;\n }\n\n /** Consume one terminator-stripped line, returning a payload if it completed a frame. */\n private feed(line: string): string | undefined {\n if (line === \"\") {\n return this.dispatch();\n }\n if (line.startsWith(\":\")) {\n return undefined;\n }\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n let value = colon === -1 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) {\n value = value.slice(1);\n }\n if (field === \"data\") {\n this.size += value.length + 1; // +1 for the \"\\n\" dispatch joins with\n if (this.size > MAX_EVENT_STREAM_FRAME_BYTES) {\n throw new XbergError(\n `Crawl event frame exceeded ${MAX_EVENT_STREAM_FRAME_BYTES} bytes before the stream closed it`,\n { status: 0, body: null },\n );\n }\n this.data.push(value);\n }\n return undefined;\n }\n\n /** Emit the buffered `data` payload, or nothing when the blank line closed no frame. */\n private dispatch(): string | undefined {\n if (this.data.length === 0) {\n return undefined;\n }\n const payload = this.data.join(\"\\n\");\n this.data = [];\n this.size = 0;\n return payload;\n }\n}\n\n/** Encode a path identifier without allowing the HTTP client to change its route. */\nexport function encodePathSegment(value: string): string {\n // ~keep WHATWG URL normalizes even percent-encoded dot segments, so encoding alone is insufficient.\n if (value === \".\" || value === \"..\") {\n throw new XbergError(\"Path identifiers must not be '.' or '..'\", { status: 400, body: null });\n }\n return encodeURIComponent(value);\n}\n","/**\n * Friendly re-exports of the independently generated API, Pro and backend schema sets.\n *\n * Shared and Enterprise-only types key off `_generated/api.d.ts` (the Xberg\n * Enterprise managed API); Pro-only response types key off\n * `_generated/pro.d.ts`; Backend-prefixed types use `_generated/backend.d.ts`.\n * Schema sets are generated separately and never merged — mirrors ADR-0072.\n */\n\nimport type { components } from \"./_generated/api.js\";\nimport type { components as proComponents } from \"./_generated/pro.js\";\nimport type { components as backendComponents } from \"./_generated/backend.js\";\n\n// -- Shared surface (present in both schema sets; typed off the Enterprise API) --\nexport type ExtractionOptions = components[\"schemas\"][\"ExtractionOptions\"];\nexport type ExtractionConfig = components[\"schemas\"][\"ExtractionConfig\"];\n/** A per-file extraction override, carried by `DocumentInput.config` and the `config-<filename>` multipart part. */\nexport type FileExtractionConfig = components[\"schemas\"][\"FileExtractionConfig\"];\nexport type ExtractedDocument = components[\"schemas\"][\"ExtractedDocument\"];\nexport type ExtractionResult = ExtractedDocument;\n// ~keep Upstream renamed this schema `JobResponse` -> `ExtractionJobResponse`; `Job` is public API and stays.\nexport type Job = components[\"schemas\"][\"ExtractionJobResponse\"];\nexport type JobStatus = components[\"schemas\"][\"JobStatus\"];\nexport type WebhookConfig = components[\"schemas\"][\"WebhookConfig\"];\nexport type ExtractResponse = components[\"schemas\"][\"ExtractResponse\"];\nexport type DocumentInput = components[\"schemas\"][\"DocumentInput\"];\nexport type ListJobsResponse = components[\"schemas\"][\"ListJobsResponse\"];\nexport type ListAuditEntriesResponse = components[\"schemas\"][\"ListAuditEntriesResponse\"];\nexport type PresetSummary = components[\"schemas\"][\"PresetSummary\"];\nexport type PresetDetail = components[\"schemas\"][\"PresetDetail\"];\n\n/**\n * The stored result document of a terminal job, returned by\n * `GET /v1/jobs/{id}/result` on both tiers. Distinct from {@link Job}, which is\n * the job's metadata record from `GET /v1/jobs/{id}`.\n */\nexport type JobResult = components[\"schemas\"][\"JobResult\"];\n/** A non-fatal per-document error attached to a {@link JobResult}. */\nexport type JobResultError = components[\"schemas\"][\"JobResultError\"];\n\n// -- Shared saved presets (both specs declare these identically) --\nexport type ListSavedPresetsResponse = components[\"schemas\"][\"ListSavedPresetsResponse\"];\nexport type SavedPresetSummary = components[\"schemas\"][\"SavedPresetSummary\"];\nexport type SavedPresetDetail = components[\"schemas\"][\"SavedPresetDetail\"];\nexport type CreateSavedPresetRequest = components[\"schemas\"][\"CreateSavedPresetRequest\"];\nexport type CreateSavedPresetResponse = components[\"schemas\"][\"CreateSavedPresetResponse\"];\nexport type UpdateSavedPresetRequest = components[\"schemas\"][\"UpdateSavedPresetRequest\"];\nexport type UpdateSavedPresetResponse = components[\"schemas\"][\"UpdateSavedPresetResponse\"];\n\n// -- Shared auto-tune surface (both specs declare these identically) --\nexport type ListAutoTuneJobsResponse = components[\"schemas\"][\"ListAutoTuneJobsResponse\"];\nexport type AutoTuneJobSummary = components[\"schemas\"][\"AutoTuneJobSummary\"];\nexport type CreateAutoTuneJobRequest = components[\"schemas\"][\"CreateAutoTuneJobRequest\"];\nexport type CreateAutoTuneJobResponse = components[\"schemas\"][\"CreateAutoTuneJobResponse\"];\nexport type AutoTuneCapabilitiesResponse = components[\"schemas\"][\"AutoTuneCapabilitiesResponse\"];\nexport type AutoTuneJobStatus = components[\"schemas\"][\"AutoTuneJobStatus\"];\nexport type AutoTuneResult = components[\"schemas\"][\"AutoTuneResult\"];\nexport type PromoteProfileRequest = components[\"schemas\"][\"PromoteProfileRequest\"];\n\n// -- Shared tuning profiles (both specs declare these identically) --\nexport type ListTuningProfilesResponse = components[\"schemas\"][\"ListTuningProfilesResponse\"];\nexport type TuningProfileSummary = components[\"schemas\"][\"TuningProfileSummary\"];\nexport type TuningProfileDetail = components[\"schemas\"][\"TuningProfileDetail\"];\n\n// -- Shared managed embedding presets (both specs declare these identically) --\nexport type ListManagedEmbeddingPresetsResponse = components[\"schemas\"][\"ListManagedEmbeddingPresetsResponse\"];\nexport type ManagedEmbeddingPreset = components[\"schemas\"][\"ManagedEmbeddingPreset\"];\n\n// -- Shared uploads, usage and enrichment (both specs declare these) --\nexport type UsageResponse = components[\"schemas\"][\"UsageResponse\"];\nexport type PresignUploadRequest = components[\"schemas\"][\"PresignUploadRequest\"];\nexport type PresignUploadResponse = components[\"schemas\"][\"PresignUploadResponse\"];\nexport type ConfirmUploadRequest = components[\"schemas\"][\"ConfirmUploadRequest\"];\nexport type ConfirmUploadResponse = components[\"schemas\"][\"ConfirmUploadResponse\"];\nexport type EnrichTextRequest = components[\"schemas\"][\"EnrichTextRequest\"];\nexport type EnrichRequestOptions = components[\"schemas\"][\"EnrichRequestOptions\"];\nexport type EnrichJobSubmitted = components[\"schemas\"][\"EnrichJobSubmitted\"];\nexport type EnrichJobStatus = components[\"schemas\"][\"EnrichJobStatus\"];\n\n// -- Enterprise-only surface (api schema) --\nexport type DiffResponse = components[\"schemas\"][\"DiffResponse\"];\n/** The async-pending envelope `diff`/`getDiffJob` return in place of {@link DiffResponse} while a diff is still computing. */\nexport type DiffAsyncAccepted = components[\"schemas\"][\"DiffAsyncAccepted\"];\n\n/**\n * Result of {@link XbergClient.diff} and {@link XbergClient.getDiffJob}.\n *\n * Both operations answer `200` with the computed {@link DiffResponse} or\n * `202` with the {@link DiffAsyncAccepted} polling envelope when the server\n * falls back to async computation — the same fallback `getDiffJob` exists to\n * poll. The two schemas share no field to discriminate on, so `status` here\n * is not part of either wire schema: it is the HTTP status code the response\n * actually carried, reattached so callers can narrow with a plain\n * `if (result.status === 200)` / `else` instead of a type assertion.\n */\nexport type DiffResult =\n | { readonly status: 200; readonly body: DiffResponse }\n | { readonly status: 202; readonly body: DiffAsyncAccepted };\nexport type DocumentVersionEntry = components[\"schemas\"][\"DocumentVersionEntry\"];\nexport type ListExtractionEventsResponse = components[\"schemas\"][\"ListExtractionEventsResponse\"];\nexport type ExtractionEventSummary = components[\"schemas\"][\"ExtractionEventSummary\"];\n/** Delivery attempts of a data-plane webhook subscription, without payload previews. */\nexport type ListWebhookDeliveriesResponse = components[\"schemas\"][\"ListWebhookDeliveriesResponse\"];\n/** One delivery attempt with its bounded request and response previews. */\nexport type WebhookDeliveryDetailResponse = components[\"schemas\"][\"WebhookDeliveryDetailResponse\"];\n\n/**\n * One event from {@link XbergClient.streamCrawlEvents}.\n *\n * A tagged union discriminated on `kind`, the same shape {@link DiffResult}\n * uses — except the discriminant here is a real wire field, not a reattached\n * HTTP status. Narrow before touching a variant-specific field:\n *\n * ```ts\n * for await (const event of client.streamCrawlEvents(crawlJobId)) {\n * if (event.kind === \"page\") {\n * // event.status_code, event.depth, event.url\n * } else if (event.kind === \"complete\") {\n * break;\n * }\n * }\n * ```\n *\n * `crawl_job_id` and `ts` are carried by every variant, so they read without\n * narrowing.\n */\nexport type CrawlEvent = components[\"schemas\"][\"CrawlEventV1\"];\n/** The `kind` discriminator of a {@link CrawlEvent}. */\nexport type CrawlEventKind = CrawlEvent[\"kind\"];\n/** A page was successfully crawled and indexed. */\nexport type CrawlPageEvent = Extract<CrawlEvent, { kind: \"page\" }>;\n/** A new URL was discovered during crawling. */\nexport type CrawlDiscoveredEvent = Extract<CrawlEvent, { kind: \"discovered\" }>;\n/** The crawl job finished; the stream closes after this event. */\nexport type CrawlCompleteEvent = Extract<CrawlEvent, { kind: \"complete\" }>;\n/** A single URL failed. The crawl continues; this is not a stream-level error. */\nexport type CrawlErrorEvent = Extract<CrawlEvent, { kind: \"error\" }>;\n\n// -- Pro-only surface (pro schema) --\nexport type GetJobResponse = proComponents[\"schemas\"][\"GetJobResponse\"];\nexport type AuthConfigResponse = proComponents[\"schemas\"][\"AuthConfigResponse\"];\nexport type LoginRequest = proComponents[\"schemas\"][\"LoginRequest\"];\nexport type LoginResponse = proComponents[\"schemas\"][\"LoginResponse\"];\nexport type SetRagConfigRequest = proComponents[\"schemas\"][\"SetRagConfigRequest\"];\nexport type RagConfigResponse = proComponents[\"schemas\"][\"RagConfigResponse\"];\n/** Licensee, plan, expiry and grace window of the running Pro instance. */\nexport type LicenseInfoResponse = proComponents[\"schemas\"][\"LicenseInfoResponse\"];\n\n// -- Pro-only control plane (projects, API keys, integrations) --\nexport type ListProjectsResponse = proComponents[\"schemas\"][\"ListProjectsResponse\"];\nexport type CreateProjectRequest = proComponents[\"schemas\"][\"CreateProjectRequest\"];\nexport type ProjectResponse = proComponents[\"schemas\"][\"ProjectResponse\"];\nexport type ApiKeyResponse = proComponents[\"schemas\"][\"ApiKeyResponse\"];\nexport type ApiKeyScope = proComponents[\"schemas\"][\"ApiKeyScope\"];\nexport type ListApiKeysResponse = proComponents[\"schemas\"][\"ListApiKeysResponse\"];\nexport type CreateApiKeyRequest = proComponents[\"schemas\"][\"CreateApiKeyRequest\"];\nexport type CreateApiKeyResponse = proComponents[\"schemas\"][\"CreateApiKeyResponse\"];\nexport type ListIntegrationsResponse = proComponents[\"schemas\"][\"ListIntegrationsResponse\"];\nexport type CreateIntegrationRequest = proComponents[\"schemas\"][\"CreateIntegrationRequest\"];\nexport type IntegrationResponse = proComponents[\"schemas\"][\"IntegrationResponse\"];\nexport type BeginOAuthResponse = proComponents[\"schemas\"][\"BeginOAuthResponse\"];\nexport type ListDocumentsResponse = proComponents[\"schemas\"][\"ListDocumentsResponse\"];\nexport type DocumentResponse = proComponents[\"schemas\"][\"DocumentResponse\"];\n\n/**\n * Terminal job statuses — once observed, polling stops and the job result is\n * returned (or thrown, for `failed`/`cancelled`).\n */\nexport const TERMINAL_JOB_STATUSES: readonly JobStatus[] = [\n \"completed\",\n \"partial_success\",\n \"failed\",\n \"cancelled\",\n] as const;\n\n/**\n * Job statuses that indicate a successful extraction. Used to distinguish a\n * \"completed but check warnings\" result from a hard failure.\n */\nexport const SUCCESS_JOB_STATUSES: readonly JobStatus[] = [\"completed\", \"partial_success\"] as const;\n\nexport type BackendAcceptInvitationRequest = backendComponents[\"schemas\"][\"AcceptInvitationRequest\"];\nexport type BackendAnalyticsResponse = backendComponents[\"schemas\"][\"AnalyticsResponse\"];\nexport type BackendAuthConfigResponse = backendComponents[\"schemas\"][\"AuthConfigResponse\"];\nexport type BackendBeginConnectResponse = backendComponents[\"schemas\"][\"BeginConnectResponse\"];\nexport type BackendBillingResponse = backendComponents[\"schemas\"][\"BillingResponse\"];\nexport type BackendCheckoutResponse = backendComponents[\"schemas\"][\"CheckoutResponse\"];\nexport type BackendCreateApiKeyRequest = backendComponents[\"schemas\"][\"CreateApiKeyRequest\"];\nexport type BackendCreateApiKeyResponse = backendComponents[\"schemas\"][\"CreateApiKeyResponse\"];\n/** Backend integration configuration accepts arbitrary JSON object properties. */\nexport type BackendCreateIntegrationRequest = Omit<\n backendComponents[\"schemas\"][\"CreateIntegrationRequest\"],\n \"config\" | \"credentials\"\n> & { config?: Record<string, unknown>; credentials?: Record<string, unknown> };\nexport type BackendCreateInvitationRequest = backendComponents[\"schemas\"][\"CreateInvitationRequest\"];\nexport type BackendCreateInvitationResponse = backendComponents[\"schemas\"][\"CreateInvitationResponse\"];\nexport type BackendCreateProjectRequest = backendComponents[\"schemas\"][\"CreateProjectRequest\"];\nexport type BackendCreateWebhookRequest = backendComponents[\"schemas\"][\"CreateWebhookRequest\"];\nexport type BackendHealthResponse = backendComponents[\"schemas\"][\"HealthResponse\"];\nexport type BackendIntegrationResponse = backendComponents[\"schemas\"][\"IntegrationResponse\"];\nexport type BackendListApiKeysResponse = backendComponents[\"schemas\"][\"ListApiKeysResponse\"];\nexport type BackendListAuditEntriesResponse = backendComponents[\"schemas\"][\"ListAuditEntriesResponse\"];\nexport type BackendListDocumentsResponse = backendComponents[\"schemas\"][\"ListDocumentsResponse\"];\nexport type BackendListIntegrationsResponse = backendComponents[\"schemas\"][\"ListIntegrationsResponse\"];\nexport type BackendListInvitationsResponse = backendComponents[\"schemas\"][\"ListInvitationsResponse\"];\nexport type BackendListMembersResponse = backendComponents[\"schemas\"][\"ListMembersResponse\"];\nexport type BackendListProjectsResponse = backendComponents[\"schemas\"][\"ListProjectsResponse\"];\nexport type BackendListWebhookDeliveriesResponse = backendComponents[\"schemas\"][\"ListWebhookDeliveriesResponse\"];\nexport type BackendListWebhooksResponse = backendComponents[\"schemas\"][\"ListWebhooksResponse\"];\nexport type BackendLoginRequest = backendComponents[\"schemas\"][\"LoginRequest\"];\nexport type BackendLoginResponse = backendComponents[\"schemas\"][\"LoginResponse\"];\nexport type BackendMemberResponse = backendComponents[\"schemas\"][\"MemberResponse\"];\nexport type BackendPortalResponse = backendComponents[\"schemas\"][\"PortalResponse\"];\nexport type BackendProjectResponse = backendComponents[\"schemas\"][\"ProjectResponse\"];\nexport type BackendRagConfigResponse = backendComponents[\"schemas\"][\"RagConfigResponse\"];\nexport type BackendReadinessResponse = backendComponents[\"schemas\"][\"ReadinessResponse\"];\nexport type BackendRetryWebhookDeliveryResponse = backendComponents[\"schemas\"][\"RetryWebhookDeliveryResponse\"];\nexport type BackendSandboxExtractResponse = backendComponents[\"schemas\"][\"SandboxExtractResponse\"];\nexport type BackendSetRagConfigRequest = backendComponents[\"schemas\"][\"SetRagConfigRequest\"];\nexport type BackendUpdateMemberRoleRequest = backendComponents[\"schemas\"][\"UpdateMemberRoleRequest\"];\nexport type BackendUpdateProjectRequest = backendComponents[\"schemas\"][\"UpdateProjectRequest\"];\nexport type BackendUpdateWebhookRequest = backendComponents[\"schemas\"][\"UpdateWebhookRequest\"];\nexport type BackendUsageResponse = backendComponents[\"schemas\"][\"UsageResponse\"];\nexport type BackendWebhookDeliveryDetailResponse = backendComponents[\"schemas\"][\"WebhookDeliveryDetailResponse\"];\nexport type BackendWebhookResponse = backendComponents[\"schemas\"][\"WebhookResponse\"];\nexport type BackendWebhookTestResponse = backendComponents[\"schemas\"][\"WebhookTestResponse\"];\n","/**\n * Package version, synced from the repo-root `VERSION` file by\n * `scripts/sync-versions.py`. Used to build the `User-Agent` header. ~keep\n */\nexport const VERSION = \"0.6.0\";\n","/**\n * High-level dual-target client for the Xberg Enterprise and Xberg Pro HTTP APIs.\n *\n * One {@link XbergClient} speaks to either product. The shared surface —\n * extraction, jobs (including job results), audit, curated presets, and the RAG\n * API — is written once and carries no tier gate. Tier-specific methods are\n * capability-gated: they probe the connected instance (`GET /healthz`'s `tier`,\n * or an explicit `target`) and throw a clear error instead of a raw 404 when\n * invoked against the wrong tier.\n *\n * Both products authenticate identically: `Authorization: Bearer {apiKey}`.\n * Enterprise defaults `baseUrl` to `https://api.xberg.io`; Pro has no default\n * (its spec ships no servers block) and requires an explicit one.\n *\n * Enterprise splits into two binaries — the data plane `baseUrl` addresses and a\n * control plane (projects, API keys, integrations) on its own origin — while Pro\n * serves both from one. `controlPlaneBaseUrl` records the origin of the second\n * and defaults to `baseUrl`. The backend methods use that origin and an optional\n * separate `controlPlaneToken`; existing Pro methods retain their data-plane routing.\n */\n\nimport createOpenApiClient, { type Client } from \"openapi-fetch\";\nimport type { paths } from \"./_generated/api.js\";\nimport {\n DEFAULT_BACKOFF_FACTOR,\n DEFAULT_ENTERPRISE_BASE_URL,\n DEFAULT_RETRY_BACKOFF_CAP_MS,\n EventStreamDecoder,\n encodePathSegment,\n buildQueryString,\n defaultSleep,\n describeFile,\n nextBackoffInterval,\n parseRetryAfterHeader,\n resolveBaseUrl,\n resolveControlPlaneBaseUrl,\n toBlob,\n} from \"./_internal.js\";\nimport type { BackoffStrategy, FileLike, QueryParams, Target } from \"./_internal.js\";\nimport { RateLimitError, TimeoutError, XbergError, raiseForStatus } from \"./errors.js\";\nimport type {\n AuthConfigResponse,\n BackendAcceptInvitationRequest,\n BackendAnalyticsResponse,\n BackendAuthConfigResponse,\n BackendBeginConnectResponse,\n BackendBillingResponse,\n BackendCheckoutResponse,\n BackendCreateApiKeyRequest,\n BackendCreateApiKeyResponse,\n BackendCreateIntegrationRequest,\n BackendCreateInvitationRequest,\n BackendCreateInvitationResponse,\n BackendCreateProjectRequest,\n BackendCreateWebhookRequest,\n BackendHealthResponse,\n BackendIntegrationResponse,\n BackendListApiKeysResponse,\n BackendListAuditEntriesResponse,\n BackendListDocumentsResponse,\n BackendListIntegrationsResponse,\n BackendListInvitationsResponse,\n BackendListMembersResponse,\n BackendListProjectsResponse,\n BackendListWebhookDeliveriesResponse,\n BackendListWebhooksResponse,\n BackendLoginRequest,\n BackendLoginResponse,\n BackendMemberResponse,\n BackendPortalResponse,\n BackendProjectResponse,\n BackendRagConfigResponse,\n BackendReadinessResponse,\n BackendRetryWebhookDeliveryResponse,\n BackendSandboxExtractResponse,\n BackendSetRagConfigRequest,\n BackendUpdateMemberRoleRequest,\n BackendUpdateProjectRequest,\n BackendUpdateWebhookRequest,\n BackendUsageResponse,\n BackendWebhookDeliveryDetailResponse,\n BackendWebhookResponse,\n BackendWebhookTestResponse,\n AutoTuneCapabilitiesResponse,\n AutoTuneJobStatus,\n AutoTuneResult,\n BeginOAuthResponse,\n ConfirmUploadRequest,\n ConfirmUploadResponse,\n CrawlEvent,\n CreateApiKeyRequest,\n CreateApiKeyResponse,\n CreateAutoTuneJobRequest,\n CreateAutoTuneJobResponse,\n CreateIntegrationRequest,\n CreateProjectRequest,\n CreateSavedPresetRequest,\n CreateSavedPresetResponse,\n DiffAsyncAccepted,\n DiffResponse,\n DiffResult,\n DocumentVersionEntry,\n EnrichJobStatus,\n EnrichJobSubmitted,\n EnrichTextRequest,\n ExtractResponse,\n ExtractionOptions,\n FileExtractionConfig,\n IntegrationResponse,\n Job,\n JobResult,\n LicenseInfoResponse,\n ListApiKeysResponse,\n ListAuditEntriesResponse,\n ListAutoTuneJobsResponse,\n ListDocumentsResponse,\n ListExtractionEventsResponse,\n ListIntegrationsResponse,\n ListJobsResponse,\n ListManagedEmbeddingPresetsResponse,\n ListProjectsResponse,\n ListSavedPresetsResponse,\n ListTuningProfilesResponse,\n ListWebhookDeliveriesResponse,\n LoginRequest,\n LoginResponse,\n PresetDetail,\n PresetSummary,\n PresignUploadRequest,\n PresignUploadResponse,\n ProjectResponse,\n PromoteProfileRequest,\n RagConfigResponse,\n SavedPresetDetail,\n SetRagConfigRequest,\n TuningProfileDetail,\n UpdateSavedPresetRequest,\n UpdateSavedPresetResponse,\n UsageResponse,\n WebhookConfig,\n WebhookDeliveryDetailResponse,\n} from \"./types.js\";\nimport { SUCCESS_JOB_STATUSES, TERMINAL_JOB_STATUSES } from \"./types.js\";\nimport { VERSION } from \"./version.js\";\n\n/**\n * Public types that live in the internal helper module because the helpers\n * there operate on them; re-exported so `./client.js` stays their import site.\n */\nexport type { BackoffStrategy, FileLike, Target } from \"./_internal.js\";\n\nconst USER_AGENT = `xberg-io-sdk-typescript/${VERSION}`;\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_POLL_INTERVAL_MS = 1_000;\nconst DEFAULT_WAIT_TIMEOUT_MS = 5 * 60_000;\nconst DEFAULT_RETRY_STATUSES: readonly number[] = [429, 502, 503, 504];\nconst DEFAULT_RETRY_BACKOFF_BASE_MS = 200;\n\n/**\n * ~keep `saved-presets` is an OpenAPI *tag* name, not a route: both specs serve\n * `/v1/saved_presets`, so there is no per-tier spelling to select between.\n */\nconst SAVED_PRESETS_PATH = \"/v1/saved_presets\";\nconst AUTO_TUNE_PATH = \"/v1/auto-tune\";\nconst TUNING_PROFILES_PATH = \"/v1/tuning-profiles\";\nconst ENRICH_PATH = \"/v1/enrich\";\nconst EXTRACTIONS_PATH = \"/v1/extractions\";\nconst DOCUMENTS_PATH = \"/v1/documents\";\nconst JOBS_PATH = \"/v1/jobs\";\nconst CRAWL_JOBS_PATH = \"/v1/crawl-jobs\";\nconst WEBHOOKS_PATH = \"/v1/webhooks\";\n\n/** Media type of a raw upload body, and the fallback when a submitted file declares none. */\nconst OCTET_STREAM_MEDIA_TYPE = \"application/octet-stream\";\n\n/** Media type of the crawl-event stream, sent as `Accept` and served as `Content-Type`. */\nconst EVENT_STREAM_MEDIA_TYPE = \"text/event-stream\";\n\n/** The `kind` values `CrawlEventV1` declares. A frame carrying anything else is rejected. */\nconst CRAWL_EVENT_KINDS: ReadonlySet<string> = new Set([\"page\", \"discovered\", \"complete\", \"error\"]);\n\nexport interface XbergClientOptions {\n apiKey?: string;\n baseUrl?: string;\n /**\n * Origin of the Enterprise control plane, which runs as a second binary\n * alongside the data plane. Defaults to `baseUrl` — Pro serves both planes\n * from one binary, so every Pro call keeps working untouched.\n *\n */\n controlPlaneBaseUrl?: string;\n /** Bearer token for protected backend calls; defaults to `apiKey`. */\n controlPlaneToken?: string;\n /** Product for tier-specific data-plane methods; discovered lazily when omitted. */\n target?: Target;\n fetch?: typeof fetch;\n headers?: Record<string, string>;\n timeoutMs?: number;\n retries?: number;\n retryOn?: readonly number[];\n retryBackoff?: BackoffStrategy;\n /** Sleep helper, swappable in tests. Defaults to `setTimeout`. */\n sleep?: (ms: number) => Promise<void>;\n}\n\nexport interface ExtractParams {\n /** Enterprise document lineage UUID; omitted for a new document. */\n documentId?: string;\n file: FileLike;\n options?: ExtractionOptions;\n webhook?: WebhookConfig;\n /**\n * Per-file extraction override for this document, sent as the\n * `config-<filename>` part. The server resolves it against\n * `options.extraction_config`, any preset and the project default.\n */\n config?: FileExtractionConfig;\n}\n\nexport interface ExtractBatchParams {\n /** Enterprise lineage UUIDs aligned with files; null entries omit lineage. */\n documentIds?: readonly (string | null)[];\n files: readonly FileLike[];\n options?: ExtractionOptions;\n webhook?: WebhookConfig;\n /**\n * One optional per-file override per entry of `files`, in the same order —\n * `null` for no override. Must be the same length as `files` when given.\n *\n * The override travels as a `config-<filename>` part, so two documents sharing\n * a filename cannot carry different overrides; that combination throws rather\n * than dropping one silently.\n */\n configs?: readonly (FileExtractionConfig | null)[];\n}\n\nexport interface WaitOptions {\n /** Total time to wait before throwing TimeoutError. Default 5 minutes. */\n timeoutMs?: number;\n /** Initial poll interval. Default 1000ms. */\n pollIntervalMs?: number;\n /** `exponential` doubles the interval each cycle (capped). Default exponential. */\n backoff?: BackoffStrategy;\n}\n\nexport interface ExtractAndWaitParams extends ExtractParams, WaitOptions {}\n\nexport interface ListJobsParams {\n limit?: number;\n offset?: number;\n}\n\nexport interface AuditParams {\n action?: string;\n limit?: number;\n offset?: number;\n}\n\n/** Offset pagination accepted by the paginated list endpoints. */\nexport interface PaginationParams {\n limit?: number;\n offset?: number;\n}\n\n/** Filters accepted by `listExtractionEvents`. */\nexport interface ListExtractionEventsParams extends PaginationParams {\n /** How many days to look back. Defaults to 30 server-side, clamped to 1..=365. */\n days?: number;\n}\n\n/** The two multipart parts `submitAutoTune` sends. */\nexport interface SubmitAutoTuneParams {\n /** JSON-encoded into the required `request` part. */\n request: CreateAutoTuneJobRequest;\n /** One binary `file` part per document referenced by `request.documents[].filename`. */\n files: readonly FileLike[];\n}\n\n/** Options accepted by `streamCrawlEvents`. */\nexport interface StreamCrawlEventsOptions {\n /**\n * Aborts the stream from outside the loop. Breaking out of the `for await`\n * already closes the response body, so this is only needed to hang up from\n * somewhere else — a React effect teardown, a shutdown handler.\n */\n signal?: AbortSignal;\n}\n\n/** Filters accepted by `listIntegrationDocuments`. */\nexport interface ListIntegrationDocumentsParams {\n /** Comma-separated MIME types to restrict the listing to. */\n mimeTypes?: string;\n /** Source-specific folder to list instead of the connection root. */\n folderId?: string;\n /** Upper bound on the number of documents returned. */\n limit?: number;\n /** Number of documents to skip before returning results. */\n offset?: number;\n}\n\nexport interface BackendDateRange {\n startDate: string;\n endDate: string;\n}\nexport interface BackendOAuthCallbackParams {\n code: string;\n state: string;\n}\nexport interface BackendAuditParams {\n action?: string;\n limit?: number;\n offset?: number;\n}\nexport interface BackendSandboxExtractParams {\n file: FileLike;\n}\nexport interface PublicSandboxExtractParams {\n file?: FileLike;\n mode?: string;\n preset?: string;\n url?: string;\n sandboxToken?: string;\n}\n\n/** Underlying `openapi-fetch` client, typed over the Enterprise API schema. */\nexport type XbergRawClient = Client<paths>;\n\n/**\n * High-level dual-target client. Construct with `new XbergClient({ apiKey })`.\n */\nexport class XbergClient {\n private readonly baseUrl: string;\n /**\n * Origin used by the Enterprise backend methods. Defaults to `baseUrl`.\n */\n public readonly controlPlaneBaseUrl: string;\n private readonly controlPlaneToken: string | undefined;\n private readonly headers: Record<string, string>;\n private readonly fetchImpl: typeof fetch;\n private readonly timeoutMs: number;\n private readonly retries: number;\n private readonly retryOn: readonly number[];\n private readonly retryBackoff: BackoffStrategy;\n private readonly sleep: (ms: number) => Promise<void>;\n private readonly target?: Target;\n private probedTier: Target | undefined;\n /** In-flight `/healthz` probe, memoised so concurrent callers share one request (single-flight). */\n private tierProbe: Promise<Target> | undefined;\n /** Underlying `openapi-fetch` client — exposed for advanced use. */\n public readonly raw: XbergRawClient;\n\n public constructor(options: XbergClientOptions = {}) {\n if (options.target !== undefined) {\n this.target = options.target;\n }\n this.baseUrl = resolveBaseUrl(options.baseUrl, options.target);\n this.controlPlaneBaseUrl = resolveControlPlaneBaseUrl(options.controlPlaneBaseUrl, this.baseUrl);\n this.controlPlaneToken = options.controlPlaneToken ?? options.apiKey;\n this.fetchImpl = options.fetch ?? fetch;\n this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.retries = options.retries ?? 0;\n this.retryOn = options.retryOn ?? DEFAULT_RETRY_STATUSES;\n this.retryBackoff = options.retryBackoff ?? \"exponential\";\n this.sleep = options.sleep ?? defaultSleep;\n\n this.headers = {\n \"User-Agent\": USER_AGENT,\n ...options.headers,\n };\n if (options.apiKey !== undefined) {\n this.headers[\"Authorization\"] = `Bearer ${options.apiKey}`;\n }\n\n this.raw = createOpenApiClient<paths>({\n baseUrl: this.baseUrl,\n headers: this.headers,\n fetch: this.fetchImpl,\n });\n }\n\n /** Enterprise backend `DELETE /auth/account`. */\n public async deleteAccount(): Promise<void> {\n return await this.backendRequest<void>(\"DELETE\", `/auth/account`);\n }\n /** Enterprise backend `GET /auth/config`. */\n public async getAuthConfig(): Promise<BackendAuthConfigResponse> {\n return await this.backendRequest<BackendAuthConfigResponse>(\"GET\", `/auth/config`, { backendPublic: true });\n }\n /** Enterprise backend `POST /auth/login`. */\n public async backendLogin(body: BackendLoginRequest): Promise<BackendLoginResponse> {\n return await this.backendRequest<BackendLoginResponse>(\"POST\", `/auth/login`, { json: body, backendPublic: true });\n }\n /** Enterprise backend `GET /healthz`. */\n public async healthz(): Promise<BackendHealthResponse> {\n return await this.backendRequest<BackendHealthResponse>(\"GET\", `/healthz`, { backendPublic: true });\n }\n /** Enterprise backend `GET /readyz`. */\n public async readyz(): Promise<BackendReadinessResponse> {\n return await this.backendRequest<BackendReadinessResponse>(\"GET\", `/readyz`, { backendPublic: true });\n }\n /** Enterprise backend `POST /v1/invitations/accept`. */\n public async acceptInvitation(body: BackendAcceptInvitationRequest): Promise<BackendMemberResponse> {\n return await this.backendRequest<BackendMemberResponse>(\"POST\", `/v1/invitations/accept`, { json: body });\n }\n /** Enterprise backend `GET /v1/oauth/callback`. */\n public async oauthCallback(params: BackendOAuthCallbackParams): Promise<string> {\n const response = await this.requestWithRetry(\"GET\", \"/v1/oauth/callback\", {\n controlPlane: true,\n backendPublic: true,\n acceptRedirect: true,\n params: { code: params.code, state: params.state },\n });\n const location = response.headers.get(\"location\");\n await response.body?.cancel();\n if (response.status !== 303 || location === null || location.length === 0) {\n throw new XbergError(\"OAuth callback did not return a 303 Location\", { status: response.status, body: null });\n }\n return location;\n }\n /** Enterprise backend `GET /v1/projects`. */\n public async backendListProjects(params: PaginationParams = {}): Promise<BackendListProjectsResponse> {\n return await this.backendRequest<BackendListProjectsResponse>(\"GET\", `/v1/projects`, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n /** Enterprise backend `POST /v1/projects`. */\n public async backendCreateProject(body: BackendCreateProjectRequest): Promise<BackendProjectResponse> {\n return await this.backendRequest<BackendProjectResponse>(\"POST\", `/v1/projects`, { json: body });\n }\n /** Enterprise backend `GET /v1/projects/{id}`. */\n public async getProject(projectId: string): Promise<BackendProjectResponse> {\n return await this.backendRequest<BackendProjectResponse>(\"GET\", `/v1/projects/${encodePathSegment(projectId)}`);\n }\n /** Enterprise backend `DELETE /v1/projects/{id}`. */\n public async deleteProject(projectId: string, params: { erase?: boolean } = {}): Promise<void> {\n return await this.backendRequest<void>(\"DELETE\", `/v1/projects/${encodePathSegment(projectId)}`, {\n params: { erase: params.erase === undefined ? undefined : String(params.erase) },\n });\n }\n /** Enterprise backend `PATCH /v1/projects/{id}`. */\n public async updateProject(projectId: string, body: BackendUpdateProjectRequest): Promise<BackendProjectResponse> {\n return await this.backendRequest<BackendProjectResponse>(\"PATCH\", `/v1/projects/${encodePathSegment(projectId)}`, {\n json: body,\n });\n }\n /** Enterprise backend `GET /v1/projects/{id}/analytics`. */\n public async getAnalytics(projectId: string, params: BackendDateRange): Promise<BackendAnalyticsResponse> {\n return await this.backendRequest<BackendAnalyticsResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/analytics`,\n { params: { start_date: params.startDate, end_date: params.endDate } },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/api-keys`. */\n public async backendListApiKeys(\n projectId: string,\n params: PaginationParams = {},\n ): Promise<BackendListApiKeysResponse> {\n return await this.backendRequest<BackendListApiKeysResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/api-keys`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/api-keys`. */\n public async backendCreateApiKey(\n projectId: string,\n body: BackendCreateApiKeyRequest,\n ): Promise<BackendCreateApiKeyResponse> {\n return await this.backendRequest<BackendCreateApiKeyResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/api-keys`,\n { json: body },\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{id}/api-keys/{key_id}`. */\n public async backendRevokeApiKey(projectId: string, apiKeyId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"DELETE\",\n `/v1/projects/${encodePathSegment(projectId)}/api-keys/${encodePathSegment(apiKeyId)}`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/api-keys/{key_id}/regenerate`. */\n public async regenerateApiKey(projectId: string, apiKeyId: string): Promise<BackendCreateApiKeyResponse> {\n return await this.backendRequest<BackendCreateApiKeyResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/api-keys/${encodePathSegment(apiKeyId)}/regenerate`,\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/audit`. */\n public async listProjectAudit(\n projectId: string,\n params: BackendAuditParams = {},\n ): Promise<BackendListAuditEntriesResponse> {\n return await this.backendRequest<BackendListAuditEntriesResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/audit`,\n { params: { action: params.action, limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/billing`. */\n public async getBilling(projectId: string): Promise<BackendBillingResponse> {\n return await this.backendRequest<BackendBillingResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/billing`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/billing/checkout`. */\n public async createCheckout(projectId: string): Promise<BackendCheckoutResponse> {\n return await this.backendRequest<BackendCheckoutResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/billing/checkout`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/billing/portal`. */\n public async createPortal(projectId: string): Promise<BackendPortalResponse> {\n return await this.backendRequest<BackendPortalResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/billing/portal`,\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/integrations`. */\n public async backendListIntegrations(\n projectId: string,\n params: PaginationParams = {},\n ): Promise<BackendListIntegrationsResponse> {\n return await this.backendRequest<BackendListIntegrationsResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/integrations`. */\n public async backendCreateIntegration(\n projectId: string,\n body: BackendCreateIntegrationRequest,\n ): Promise<BackendIntegrationResponse> {\n return await this.backendRequest<BackendIntegrationResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations`,\n { json: body },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/integrations/{iid}`. */\n public async backendGetIntegration(projectId: string, integrationId: string): Promise<BackendIntegrationResponse> {\n return await this.backendRequest<BackendIntegrationResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}`,\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{id}/integrations/{iid}`. */\n public async backendDeleteIntegration(projectId: string, integrationId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"DELETE\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/integrations/{iid}/connect`. */\n public async oauthConnect(projectId: string, integrationId: string): Promise<BackendBeginConnectResponse> {\n return await this.backendRequest<BackendBeginConnectResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/connect`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/integrations/{iid}/disconnect`. */\n public async backendDisconnectIntegration(projectId: string, integrationId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/disconnect`,\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/integrations/{iid}/documents`. */\n public async backendListIntegrationDocuments(\n projectId: string,\n integrationId: string,\n params: ListIntegrationDocumentsParams = {},\n ): Promise<BackendListDocumentsResponse> {\n return await this.backendRequest<BackendListDocumentsResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/documents`,\n {\n params: {\n mime_types: params.mimeTypes,\n folder_id: params.folderId,\n limit: params.limit,\n offset: params.offset,\n },\n },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/integrations/{iid}/documents/{doc_id}`. */\n public async backendFetchIntegrationDocument(\n projectId: string,\n integrationId: string,\n documentId: string,\n ): Promise<Uint8Array> {\n return await this.requestBytes(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/documents/${encodePathSegment(documentId)}`,\n { controlPlane: true },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/invitations`. */\n public async listInvitations(\n projectId: string,\n params: PaginationParams = {},\n ): Promise<BackendListInvitationsResponse> {\n return await this.backendRequest<BackendListInvitationsResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/invitations`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/invitations`. */\n public async inviteUser(\n projectId: string,\n body: BackendCreateInvitationRequest,\n ): Promise<BackendCreateInvitationResponse> {\n return await this.backendRequest<BackendCreateInvitationResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/invitations`,\n { json: body },\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{id}/invitations/{inv_id}`. */\n public async revokeInvitation(projectId: string, invitationId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"DELETE\",\n `/v1/projects/${encodePathSegment(projectId)}/invitations/${encodePathSegment(invitationId)}`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/leave`. */\n public async leaveProject(projectId: string): Promise<void> {\n return await this.backendRequest<void>(\"POST\", `/v1/projects/${encodePathSegment(projectId)}/leave`);\n }\n /** Enterprise backend `GET /v1/projects/{id}/members`. */\n public async listMembers(projectId: string, params: PaginationParams = {}): Promise<BackendListMembersResponse> {\n return await this.backendRequest<BackendListMembersResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/members`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{id}/members/{user_id}`. */\n public async removeMember(projectId: string, userId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"DELETE\",\n `/v1/projects/${encodePathSegment(projectId)}/members/${encodePathSegment(userId)}`,\n );\n }\n /** Enterprise backend `PATCH /v1/projects/{id}/members/{user_id}`. */\n public async updateMemberRole(\n projectId: string,\n userId: string,\n body: BackendUpdateMemberRoleRequest,\n ): Promise<BackendMemberResponse> {\n return await this.backendRequest<BackendMemberResponse>(\n \"PATCH\",\n `/v1/projects/${encodePathSegment(projectId)}/members/${encodePathSegment(userId)}`,\n { json: body },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/rag-config`. */\n public async backendGetRagConfig(projectId: string): Promise<BackendRagConfigResponse> {\n return await this.backendRequest<BackendRagConfigResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/rag-config`,\n );\n }\n /** Enterprise backend `PUT /v1/projects/{id}/rag-config`. */\n public async backendSetRagConfig(\n projectId: string,\n body: BackendSetRagConfigRequest,\n ): Promise<BackendRagConfigResponse> {\n return await this.backendRequest<BackendRagConfigResponse>(\n \"PUT\",\n `/v1/projects/${encodePathSegment(projectId)}/rag-config`,\n { json: body },\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/sandbox/extract`. */\n public async sandboxExtract(\n projectId: string,\n params: BackendSandboxExtractParams,\n ): Promise<BackendSandboxExtractResponse> {\n return await this.backendRequest<BackendSandboxExtractResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/sandbox/extract`,\n { body: sandboxForm(params) },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/usage`. */\n public async getUsage(projectId: string, params: BackendDateRange): Promise<BackendUsageResponse> {\n return await this.backendRequest<BackendUsageResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/usage`,\n { params: { start_date: params.startDate, end_date: params.endDate } },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/webhooks`. */\n public async listWebhooks(projectId: string, params: PaginationParams = {}): Promise<BackendListWebhooksResponse> {\n return await this.backendRequest<BackendListWebhooksResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/webhooks`. */\n public async createWebhook(projectId: string, body: BackendCreateWebhookRequest): Promise<BackendWebhookResponse> {\n return await this.backendRequest<BackendWebhookResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks`,\n { json: body },\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{id}/webhooks/{wh_id}`. */\n public async deleteWebhook(projectId: string, webhookId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"DELETE\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}`,\n );\n }\n /** Enterprise backend `PATCH /v1/projects/{id}/webhooks/{wh_id}`. */\n public async updateWebhook(\n projectId: string,\n webhookId: string,\n body: BackendUpdateWebhookRequest,\n ): Promise<BackendWebhookResponse> {\n return await this.backendRequest<BackendWebhookResponse>(\n \"PATCH\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}`,\n { json: body },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/webhooks/{wh_id}/deliveries`. */\n public async listWebhookDeliveries(\n projectId: string,\n webhookId: string,\n params: PaginationParams = {},\n ): Promise<BackendListWebhookDeliveriesResponse> {\n return await this.backendRequest<BackendListWebhookDeliveriesResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}/deliveries`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/webhooks/{wh_id}/deliveries/{delivery_id}`. */\n public async getWebhookDelivery(\n projectId: string,\n webhookId: string,\n deliveryId: string,\n ): Promise<BackendWebhookDeliveryDetailResponse> {\n return await this.backendRequest<BackendWebhookDeliveryDetailResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}/deliveries/${encodePathSegment(deliveryId)}`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/webhooks/{wh_id}/deliveries/{delivery_id}/retry`. */\n public async retryWebhookDelivery(\n projectId: string,\n webhookId: string,\n deliveryId: string,\n ): Promise<BackendRetryWebhookDeliveryResponse> {\n return await this.backendRequest<BackendRetryWebhookDeliveryResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}/deliveries/${encodePathSegment(deliveryId)}/retry`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/webhooks/{wh_id}/test`. */\n public async testWebhook(projectId: string, webhookId: string): Promise<BackendWebhookTestResponse> {\n return await this.backendRequest<BackendWebhookTestResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}/test`,\n );\n }\n /** Enterprise backend `POST /v1/sandbox/public/extract`. */\n public async publicSandboxExtract(params: PublicSandboxExtractParams): Promise<BackendSandboxExtractResponse> {\n return await this.backendRequest<BackendSandboxExtractResponse>(\"POST\", `/v1/sandbox/public/extract`, {\n body: sandboxForm(params),\n ...(params.sandboxToken !== undefined ? { sandboxToken: params.sandboxToken } : {}),\n backendPublic: true,\n });\n }\n\n // -- Shared surface (Enterprise + Pro) ---------------------------------\n\n /**\n * Submit a single document for extraction. Returns the initial {@link Job}\n * record (still pending — call `waitForJob` to await completion).\n */\n public async extract(params: ExtractParams): Promise<Job> {\n const jobs = await this.extractBatch({\n files: [params.file],\n ...(params.documentId !== undefined ? { documentIds: [params.documentId] } : {}),\n ...(params.options !== undefined ? { options: params.options } : {}),\n ...(params.webhook !== undefined ? { webhook: params.webhook } : {}),\n ...(params.config !== undefined ? { configs: [params.config] } : {}),\n });\n const first = jobs[0];\n if (first === undefined) {\n throw new XbergError(\"Server did not return any job IDs\", { status: 500, body: { jobs } });\n }\n return first;\n }\n\n /**\n * Submit multiple documents in a single multipart request. Returns one\n * {@link Job} per file, in the same order.\n */\n public async extractBatch(params: ExtractBatchParams): Promise<Job[]> {\n if (params.files.length === 0) {\n throw new XbergError(\"extractBatch called with no files\", { status: 400, body: null });\n }\n\n const filenames = params.files.map(describeFile);\n const documentIds = prepareDocumentLineage(filenames, params.documentIds);\n if (documentIds.size > 0) await this.requireTier(\"enterprise\", \"extract document lineage\");\n const form = new FormData();\n // ~keep The Enterprise parser captures lineage when reading each file part.\n for (const [filename, documentId] of documentIds) form.append(`document_id-${filename}`, documentId);\n const parts = params.files.map(toBlob);\n for (const { blob, filename } of parts) {\n form.append(\"file\", blob, filename);\n }\n if (params.options !== undefined) {\n form.append(\"options\", JSON.stringify(params.options));\n }\n if (params.webhook !== undefined) {\n form.append(\"webhook\", JSON.stringify(params.webhook));\n }\n appendPerFileConfigs(form, filenames, params.configs);\n\n const body = await this.requestJson<ExtractResponse>(\"POST\", \"/v1/extract\", { body: form });\n const jobIds = body.job_ids ?? [];\n const now = new Date().toISOString();\n // ~keep `POST /v1/extract` answers with job IDs alone, so the rest of each record is\n // synthesized from what was submitted; `mime_type` is the type the file was uploaded under.\n return parts.map(({ blob, filename }, index) => {\n const id = jobIds[index];\n if (id === undefined) {\n throw new XbergError(`Server returned ${jobIds.length} job IDs for ${params.files.length} files`, {\n status: 500,\n body,\n });\n }\n return {\n id,\n filename,\n mime_type: blob.type.length > 0 ? blob.type : OCTET_STREAM_MEDIA_TYPE,\n status: \"pending\",\n created_at: now,\n };\n });\n }\n\n /** Fetch the current state of a job. */\n public async getJob(jobId: string): Promise<Job> {\n return await this.requestJson<Job>(\"GET\", `${JOBS_PATH}/${encodePathSegment(jobId)}`);\n }\n\n /**\n * Fetch a job's stored result document (`GET /v1/jobs/{id}/result`).\n *\n * Declared by both tiers with an identical `JobResult` envelope; the\n * extracted documents live in `results`. Distinct from {@link getJob}, which\n * returns the job's metadata record.\n */\n public async getJobResult(jobId: string): Promise<JobResult> {\n return await this.requestJson<JobResult>(\"GET\", `${JOBS_PATH}/${encodePathSegment(jobId)}/result`);\n }\n\n /** List jobs (paginated) via `GET /v1/jobs`. */\n public async listJobs(params: ListJobsParams = {}): Promise<ListJobsResponse> {\n return await this.requestJson<ListJobsResponse>(\"GET\", JOBS_PATH, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Cancel a job (`DELETE /v1/jobs/{id}`). Idempotent: both a successful\n * cancellation and a job that already reached a terminal status answer\n * `204`.\n */\n public async cancelJob(jobId: string): Promise<void> {\n await this.requestJson(\"DELETE\", `${JOBS_PATH}/${encodePathSegment(jobId)}`);\n }\n\n /**\n * Poll {@link getJob} until the job reaches a terminal status. Throws\n * {@link TimeoutError} if the wait exceeds `timeoutMs`. Throws\n * {@link XbergError} if the terminal status is `failed` or `cancelled`.\n */\n public async waitForJob(jobId: string, options: WaitOptions = {}): Promise<Job> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;\n const initialInterval = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const backoff = options.backoff ?? \"exponential\";\n const start = Date.now();\n let interval = initialInterval;\n\n for (;;) {\n const job = await this.getJob(jobId);\n if (TERMINAL_JOB_STATUSES.includes(job.status)) {\n if (SUCCESS_JOB_STATUSES.includes(job.status)) {\n return job;\n }\n throw new XbergError(`Job ${jobId} ended with status ${job.status}`, { status: 200, body: job });\n }\n\n const elapsed = Date.now() - start;\n const remaining = timeoutMs - elapsed;\n if (remaining <= 0) {\n throw new TimeoutError(`Timed out waiting for job ${jobId} after ${timeoutMs}ms`, { status: 408, body: job });\n }\n const delay = Math.min(interval, remaining);\n await this.sleep(delay);\n if (backoff === \"exponential\") {\n interval = Math.min(interval * DEFAULT_BACKOFF_FACTOR, DEFAULT_RETRY_BACKOFF_CAP_MS);\n }\n }\n }\n\n /** Wait for many jobs in parallel. */\n public async waitForJobs(jobIds: readonly string[], options: WaitOptions = {}): Promise<Job[]> {\n return await Promise.all(jobIds.map((id) => this.waitForJob(id, options)));\n }\n\n /** Convenience: extract one file and await its result. */\n public async extractAndWait(params: ExtractAndWaitParams): Promise<Job> {\n const extractParams: ExtractParams = {\n file: params.file,\n ...(params.documentId !== undefined ? { documentId: params.documentId } : {}),\n ...(params.options !== undefined ? { options: params.options } : {}),\n ...(params.webhook !== undefined ? { webhook: params.webhook } : {}),\n ...(params.config !== undefined ? { config: params.config } : {}),\n };\n const job = await this.extract(extractParams);\n const waitOptions: WaitOptions = {\n ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs } : {}),\n ...(params.pollIntervalMs !== undefined ? { pollIntervalMs: params.pollIntervalMs } : {}),\n ...(params.backoff !== undefined ? { backoff: params.backoff } : {}),\n };\n return this.waitForJob(job.id, waitOptions);\n }\n\n /** Fetch audit-log entries via `GET /v1/audit`. */\n public async audit(params: AuditParams = {}): Promise<ListAuditEntriesResponse> {\n return await this.requestJson<ListAuditEntriesResponse>(\"GET\", \"/v1/audit\", {\n params: { action: params.action, limit: params.limit, offset: params.offset },\n });\n }\n\n // -- Shared preset catalogue -------------------------------------------\n\n /** List the read-only curated presets (`GET /v1/presets`). */\n public async presets(): Promise<PresetSummary[]> {\n return await this.requestJson<PresetSummary[]>(\"GET\", \"/v1/presets\");\n }\n\n /** Fetch one curated preset in full (`GET /v1/presets/{id}`). */\n public async getPreset(presetId: string): Promise<PresetDetail> {\n return await this.requestJson<PresetDetail>(\"GET\", `/v1/presets/${encodePathSegment(presetId)}`);\n }\n\n /**\n * Download a preset's bundled sample file\n * (`GET /v1/presets/{id}/sample/{name}`). The response is raw bytes, not\n * JSON.\n */\n public async getPresetSample(presetId: string, name: string): Promise<Uint8Array> {\n const path = `/v1/presets/${encodePathSegment(presetId)}/sample/${encodePathSegment(name)}`;\n return await this.requestBytes(\"GET\", path);\n }\n\n // -- Shared RAG surface ------------------------------------------------\n\n /** List RAG collections (`GET /v1/rag/collections`). */\n public async listRagCollections(): Promise<unknown> {\n return await this.requestJson(\"GET\", \"/v1/rag/collections\");\n }\n\n /** Create a RAG collection (`POST /v1/rag/collections`). */\n public async createRagCollection(body: Record<string, unknown>): Promise<unknown> {\n return await this.requestJson(\"POST\", \"/v1/rag/collections\", { json: body });\n }\n\n /** Fetch a RAG collection (`GET /v1/rag/collections/{name}`). */\n public async getRagCollection(name: string): Promise<unknown> {\n return await this.requestJson(\"GET\", `/v1/rag/collections/${encodePathSegment(name)}`);\n }\n\n /** Delete a RAG collection (`DELETE /v1/rag/collections/{name}`). The spec documents a 204 with no content. */\n public async deleteRagCollection(name: string): Promise<void> {\n await this.requestJson(\"DELETE\", `/v1/rag/collections/${encodePathSegment(name)}`);\n }\n\n /** Add documents to a RAG collection (`POST /v1/rag/collections/{name}/documents`). */\n public async addRagDocuments(name: string, body: Record<string, unknown>): Promise<unknown> {\n return await this.requestJson(\"POST\", `/v1/rag/collections/${encodePathSegment(name)}/documents`, { json: body });\n }\n\n /**\n * Delete documents from a RAG collection, by ID list or metadata filter\n * (`DELETE /v1/rag/collections/{name}/documents`). Unlike\n * {@link deleteRagCollection}, this answers `200` with a body reporting how\n * many documents were removed.\n */\n public async deleteRagDocuments(name: string, body: Record<string, unknown>): Promise<unknown> {\n return await this.requestJson(\"DELETE\", `/v1/rag/collections/${encodePathSegment(name)}/documents`, {\n json: body,\n });\n }\n\n /** Reindex a RAG document (`POST /v1/rag/collections/{name}/documents/{id}/reindex`). */\n public async reindexRagDocument(name: string, documentId: string, body?: Record<string, unknown>): Promise<unknown> {\n const path = `/v1/rag/collections/${encodePathSegment(name)}/documents/${encodePathSegment(documentId)}/reindex`;\n return await this.requestJson(\"POST\", path, body !== undefined ? { json: body } : {});\n }\n\n /** Retrieve chunks from a RAG collection (`POST /v1/rag/collections/{name}/retrieve`). */\n public async ragRetrieve(name: string, body: Record<string, unknown>): Promise<unknown> {\n return await this.requestJson(\"POST\", `/v1/rag/collections/${encodePathSegment(name)}/retrieve`, { json: body });\n }\n\n /** Kick off an embedding migration (`POST /v1/rag/collections/{name}/migrate-embeddings`). */\n public async migrateRagEmbeddings(name: string, body: Record<string, unknown>): Promise<unknown> {\n return await this.requestJson(\"POST\", `/v1/rag/collections/${encodePathSegment(name)}/migrate-embeddings`, {\n json: body,\n });\n }\n\n /** Poll an embedding-migration job (`GET .../migrate-embeddings/{jobId}`). */\n public async getRagMigrationJob(name: string, jobId: string): Promise<unknown> {\n const path = `/v1/rag/collections/${encodePathSegment(name)}/migrate-embeddings/${encodePathSegment(jobId)}`;\n return await this.requestJson(\"GET\", path);\n }\n\n /** Fetch a RAG job's status (`GET /v1/rag/jobs/{jobId}`). */\n public async getRagJob(jobId: string): Promise<unknown> {\n return await this.requestJson(\"GET\", `/v1/rag/jobs/${encodePathSegment(jobId)}`);\n }\n\n /**\n * List the managed embedding presets this server build ships\n * (`GET /v1/rag/embedding-presets`), in the canonical backend order.\n */\n public async listManagedEmbeddingPresets(): Promise<ListManagedEmbeddingPresetsResponse> {\n return await this.requestJson<ListManagedEmbeddingPresetsResponse>(\"GET\", \"/v1/rag/embedding-presets\");\n }\n\n // -- Shared saved presets ----------------------------------------------\n //\n // Both tiers serve the same routes under the same spelling and the same\n // schemas, so nothing here is tier-dependent.\n\n /** List the project's saved presets (`GET /v1/saved_presets`). */\n public async listSavedPresets(params: PaginationParams = {}): Promise<ListSavedPresetsResponse> {\n return await this.requestJson<ListSavedPresetsResponse>(\"GET\", SAVED_PRESETS_PATH, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /** Create a saved preset (`POST /v1/saved_presets`). */\n public async createSavedPreset(body: CreateSavedPresetRequest): Promise<CreateSavedPresetResponse> {\n return await this.requestJson<CreateSavedPresetResponse>(\"POST\", SAVED_PRESETS_PATH, { json: body });\n }\n\n /** Fetch one saved preset (`GET /v1/saved_presets/{preset_id}`). */\n public async getSavedPreset(presetId: string): Promise<SavedPresetDetail> {\n return await this.requestJson<SavedPresetDetail>(\"GET\", this.savedPresetPath(presetId));\n }\n\n /** Update a saved preset (`PATCH /v1/saved_presets/{preset_id}`). */\n public async updateSavedPreset(presetId: string, body: UpdateSavedPresetRequest): Promise<UpdateSavedPresetResponse> {\n return await this.requestJson<UpdateSavedPresetResponse>(\"PATCH\", this.savedPresetPath(presetId), { json: body });\n }\n\n /** Delete a saved preset (`DELETE /v1/saved_presets/{preset_id}`). */\n public async deleteSavedPreset(presetId: string): Promise<void> {\n await this.requestJson(\"DELETE\", this.savedPresetPath(presetId));\n }\n\n // -- Shared auto-tune surface ------------------------------------------\n\n /** List the project's auto-tune jobs (`GET /v1/auto-tune`). */\n public async listAutoTuneJobs(params: PaginationParams = {}): Promise<ListAutoTuneJobsResponse> {\n return await this.requestJson<ListAutoTuneJobsResponse>(\"GET\", AUTO_TUNE_PATH, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Submit an auto-tune job (`POST /v1/auto-tune`). Sent as `multipart/form-data`:\n * a JSON `request` part plus one binary `file` part per document.\n */\n public async submitAutoTune(params: SubmitAutoTuneParams): Promise<CreateAutoTuneJobResponse> {\n if (params.files.length === 0) {\n throw new XbergError(\"submitAutoTune called with no files\", { status: 400, body: null });\n }\n const form = new FormData();\n form.append(\"request\", JSON.stringify(params.request));\n for (const file of params.files) {\n const { blob, filename } = toBlob(file);\n form.append(\"file\", blob, filename);\n }\n return await this.requestJson<CreateAutoTuneJobResponse>(\"POST\", AUTO_TUNE_PATH, { body: form });\n }\n\n /** Fetch the deployment's tunable knobs and OCR backends (`GET /v1/auto-tune/capabilities`). */\n public async getAutoTuneCapabilities(): Promise<AutoTuneCapabilitiesResponse> {\n return await this.requestJson<AutoTuneCapabilitiesResponse>(\"GET\", `${AUTO_TUNE_PATH}/capabilities`);\n }\n\n /** Fetch an auto-tune job's status (`GET /v1/auto-tune/{id}`). */\n public async getAutoTuneStatus(autoTuneJobId: string): Promise<AutoTuneJobStatus> {\n return await this.requestJson<AutoTuneJobStatus>(\"GET\", this.autoTunePath(autoTuneJobId));\n }\n\n /** Delete an auto-tune job (`DELETE /v1/auto-tune/{id}`). */\n public async deleteAutoTuneJob(autoTuneJobId: string): Promise<void> {\n await this.requestJson(\"DELETE\", this.autoTunePath(autoTuneJobId));\n }\n\n /**\n * Stop a running auto-tune job (`POST /v1/auto-tune/{id}/stop`).\n *\n * The run finishes the trial in flight and then completes with the partial\n * leaderboard, so {@link getAutoTuneResult} still serves the best configuration\n * the search found. Idempotent: a job that already reached a terminal state\n * answers `204` and nothing changes.\n */\n public async stopAutoTuneJob(autoTuneJobId: string): Promise<void> {\n await this.requestJson(\"POST\", `${this.autoTunePath(autoTuneJobId)}/stop`);\n }\n\n /** Promote an auto-tune result to a named tuning profile (`POST /v1/auto-tune/{id}/promote`). */\n public async promoteAutoTuneProfile(\n autoTuneJobId: string,\n body: PromoteProfileRequest,\n ): Promise<TuningProfileDetail> {\n return await this.requestJson<TuningProfileDetail>(\"POST\", `${this.autoTunePath(autoTuneJobId)}/promote`, {\n json: body,\n });\n }\n\n /** Fetch a completed auto-tune job's result (`GET /v1/auto-tune/{id}/result`). */\n public async getAutoTuneResult(autoTuneJobId: string): Promise<AutoTuneResult> {\n return await this.requestJson<AutoTuneResult>(\"GET\", `${this.autoTunePath(autoTuneJobId)}/result`);\n }\n\n // -- Shared tuning profiles --------------------------------------------\n\n /** List the project's tuning profiles (`GET /v1/tuning-profiles`). */\n public async listTuningProfiles(params: PaginationParams = {}): Promise<ListTuningProfilesResponse> {\n return await this.requestJson<ListTuningProfilesResponse>(\"GET\", TUNING_PROFILES_PATH, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /** Fetch one tuning profile (`GET /v1/tuning-profiles/{id}`). */\n public async getTuningProfile(profileId: string): Promise<TuningProfileDetail> {\n return await this.requestJson<TuningProfileDetail>(\"GET\", this.tuningProfilePath(profileId));\n }\n\n /** Delete a tuning profile (`DELETE /v1/tuning-profiles/{id}`). */\n public async deleteTuningProfile(profileId: string): Promise<void> {\n await this.requestJson(\"DELETE\", this.tuningProfilePath(profileId));\n }\n\n // -- Shared uploads, usage, pages, enrichment and crawl streams ---------\n //\n // ~keep Every route below is declared by both specs; the Enterprise gate these\n // once carried denied Pro callers endpoints Pro serves.\n\n /**\n * Request presigned upload URLs (`POST /v1/uploads/presign`).\n *\n * The request body is typed off the Enterprise schema, whose `config` is a full\n * `ExtractionConfig`; Pro declares that field as an open object and accepts the\n * same payload.\n */\n public async presignUpload(body: PresignUploadRequest): Promise<PresignUploadResponse> {\n return await this.requestJson<PresignUploadResponse>(\"POST\", \"/v1/uploads/presign\", { json: body });\n }\n\n /** Confirm presigned uploads and start processing (`POST /v1/uploads/confirm`). */\n public async confirmUpload(body: ConfirmUploadRequest): Promise<ConfirmUploadResponse> {\n return await this.requestJson<ConfirmUploadResponse>(\"POST\", \"/v1/uploads/confirm\", { json: body });\n }\n\n /** Fetch usage/metering data for a date window (`GET /v1/usage`). */\n public async usage(params?: QueryParams): Promise<UsageResponse> {\n const init: RequestParts = params !== undefined ? { params } : {};\n return await this.requestJson<UsageResponse>(\"GET\", \"/v1/usage\", init);\n }\n\n /**\n * Download one rendered page of an extraction job\n * (`GET /v1/jobs/{job_id}/pages/{page_number}`). The response is a PNG image —\n * raw bytes, not JSON. `pageNumber` is 1-indexed.\n */\n public async getJobPage(jobId: string, pageNumber: number): Promise<Uint8Array> {\n const path = `${JOBS_PATH}/${encodePathSegment(jobId)}/pages/${encodePathSegment(String(pageNumber))}`;\n return await this.requestBytes(\"GET\", path);\n }\n\n /** Submit text for enrichment (`POST /v1/enrich`). */\n public async submitEnrich(body: EnrichTextRequest): Promise<EnrichJobSubmitted> {\n return await this.requestJson<EnrichJobSubmitted>(\"POST\", ENRICH_PATH, { json: body });\n }\n\n /** Fetch an enrichment job's status (`GET /v1/enrich/{job_id}`). */\n public async getEnrichStatus(jobId: string): Promise<EnrichJobStatus> {\n return await this.requestJson<EnrichJobStatus>(\"GET\", `${ENRICH_PATH}/${encodePathSegment(jobId)}`);\n }\n\n /**\n * Stream a crawl job's events (`GET /v1/crawl-jobs/{crawl_job_id}/events`,\n * Server-Sent Events).\n *\n * Returns an `AsyncIterable` of the `kind`-discriminated {@link CrawlEvent}\n * union; the server closes the stream after the `complete` event.\n *\n * ```ts\n * for await (const event of client.streamCrawlEvents(crawlJobId)) {\n * if (event.kind === \"page\") {\n * console.log(event.url, event.status_code);\n * }\n * }\n * ```\n *\n * Nothing is requested until iteration begins, and the response body is\n * cancelled when iteration ends: on `complete`, on `break`/`return` out of the\n * loop, on a thrown error, or when `options.signal` aborts. A stream is idle\n * between events by design, so unlike every other method here it carries no\n * request timeout and is not routed through the retry engine — a retried\n * subscription would redeliver every event the caller had already handled.\n */\n public streamCrawlEvents(crawlJobId: string, options: StreamCrawlEventsOptions = {}): AsyncIterable<CrawlEvent> {\n const path = `${CRAWL_JOBS_PATH}/${encodePathSegment(crawlJobId)}/events`;\n const open = (): Promise<Response> => this.openEventStream(path, options.signal);\n return { [Symbol.asyncIterator]: (): AsyncIterator<CrawlEvent> => iterateCrawlEvents(open) };\n }\n\n // -- Pro-only surface --------------------------------------------------\n\n /** Pro only: fetch the instance's accepted auth methods (`GET /auth/config`). */\n public async authConfig(): Promise<AuthConfigResponse> {\n await this.requireTier(\"pro\", \"authConfig\");\n return this.requestJson<AuthConfigResponse>(\"GET\", \"/auth/config\");\n }\n\n /** Pro only: exchange a verified OIDC ID token for a Pro session JWT (`POST /auth/login`). */\n public async login(body: LoginRequest): Promise<LoginResponse> {\n await this.requireTier(\"pro\", \"login\");\n return this.requestJson<LoginResponse>(\"POST\", \"/auth/login\", { json: body });\n }\n\n /**\n * Pro only: read the running instance's license detail (`GET /v1/license`) —\n * licensee, plan, expiry, grace window and days remaining. Requires an admin\n * API key or an admin session.\n */\n public async getLicenseInfo(): Promise<LicenseInfoResponse> {\n await this.requireTier(\"pro\", \"getLicenseInfo\");\n return this.requestJson<LicenseInfoResponse>(\"GET\", \"/v1/license\");\n }\n\n /**\n * Pro only: upload a document's bytes against a presigned local capability\n * (`PUT /v1/uploads/local/{project_id}/{token}`).\n *\n * `projectId` and `token` come from the `upload_url` {@link presignUpload}\n * returns when the instance stages uploads locally. The capability is one-use,\n * expiring, and bounded by the size limit recorded when it was issued; the\n * body is sent as raw bytes.\n */\n public async putLocalUpload(projectId: string, token: string, file: FileLike): Promise<void> {\n await this.requireTier(\"pro\", \"putLocalUpload\");\n const { blob } = toBlob(file);\n const path = `/v1/uploads/local/${encodePathSegment(projectId)}/${encodePathSegment(token)}`;\n await this.requestJson(\"PUT\", path, {\n body: new Uint8Array(await blob.arrayBuffer()),\n headers: { \"Content-Type\": OCTET_STREAM_MEDIA_TYPE },\n });\n }\n\n /** Pro only: fetch a project's RAG config (`GET /v1/projects/{projectId}/rag-config`). */\n public async getRagConfig(projectId: string): Promise<RagConfigResponse> {\n await this.requireTier(\"pro\", \"getRagConfig\");\n return this.requestJson<RagConfigResponse>(\"GET\", `/v1/projects/${encodePathSegment(projectId)}/rag-config`);\n }\n\n /** Pro only: update a project's RAG config (`PUT /v1/projects/{projectId}/rag-config`). */\n public async setRagConfig(projectId: string, body: SetRagConfigRequest): Promise<RagConfigResponse> {\n await this.requireTier(\"pro\", \"setRagConfig\");\n return this.requestJson<RagConfigResponse>(\"PUT\", `/v1/projects/${encodePathSegment(projectId)}/rag-config`, {\n json: body,\n });\n }\n\n // -- Pro-only control plane (projects, API keys, integrations) ---------\n\n /** Pro only: list the caller's projects (`GET /v1/projects`). */\n public async listProjects(params: PaginationParams = {}): Promise<ListProjectsResponse> {\n await this.requireTier(\"pro\", \"listProjects\");\n return this.requestJson<ListProjectsResponse>(\"GET\", \"/v1/projects\", {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /** Pro only: create a project owned by the caller (`POST /v1/projects`). */\n public async createProject(body: CreateProjectRequest): Promise<ProjectResponse> {\n await this.requireTier(\"pro\", \"createProject\");\n return this.requestJson<ProjectResponse>(\"POST\", \"/v1/projects\", { json: body });\n }\n\n /** Pro only: list a project's API keys (`GET /v1/projects/{projectId}/api-keys`). */\n public async listApiKeys(projectId: string, params: PaginationParams = {}): Promise<ListApiKeysResponse> {\n await this.requireTier(\"pro\", \"listApiKeys\");\n return this.requestJson<ListApiKeysResponse>(\"GET\", `${this.projectPath(projectId)}/api-keys`, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /** Pro only: mint an API key for a project (`POST /v1/projects/{projectId}/api-keys`). */\n public async createApiKey(projectId: string, body: CreateApiKeyRequest): Promise<CreateApiKeyResponse> {\n await this.requireTier(\"pro\", \"createApiKey\");\n return this.requestJson<CreateApiKeyResponse>(\"POST\", `${this.projectPath(projectId)}/api-keys`, { json: body });\n }\n\n /** Pro only: revoke an API key (`DELETE /v1/projects/{projectId}/api-keys/{keyId}`). */\n public async revokeApiKey(projectId: string, keyId: string): Promise<void> {\n await this.requireTier(\"pro\", \"revokeApiKey\");\n await this.requestJson(\"DELETE\", `${this.projectPath(projectId)}/api-keys/${encodePathSegment(keyId)}`);\n }\n\n /** Pro only: list a project's integrations (`GET /v1/projects/{projectId}/integrations`). */\n public async listIntegrations(projectId: string, params: PaginationParams = {}): Promise<ListIntegrationsResponse> {\n await this.requireTier(\"pro\", \"listIntegrations\");\n return this.requestJson<ListIntegrationsResponse>(\"GET\", `${this.projectPath(projectId)}/integrations`, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /** Pro only: create an integration (`POST /v1/projects/{projectId}/integrations`). */\n public async createIntegration(projectId: string, body: CreateIntegrationRequest): Promise<IntegrationResponse> {\n await this.requireTier(\"pro\", \"createIntegration\");\n return this.requestJson<IntegrationResponse>(\"POST\", `${this.projectPath(projectId)}/integrations`, {\n json: body,\n });\n }\n\n /** Pro only: fetch one integration (`GET .../integrations/{integrationId}`). */\n public async getIntegration(projectId: string, integrationId: string): Promise<IntegrationResponse> {\n await this.requireTier(\"pro\", \"getIntegration\");\n return this.requestJson<IntegrationResponse>(\"GET\", this.integrationPath(projectId, integrationId));\n }\n\n /** Pro only: delete an integration (`DELETE .../integrations/{integrationId}`). */\n public async deleteIntegration(projectId: string, integrationId: string): Promise<void> {\n await this.requireTier(\"pro\", \"deleteIntegration\");\n await this.requestJson(\"DELETE\", this.integrationPath(projectId, integrationId));\n }\n\n /**\n * Pro only: begin the OAuth flow for an integration\n * (`POST .../integrations/{integrationId}/connect`). Returns the provider\n * authorize URL to redirect the user to.\n */\n public async connectIntegration(projectId: string, integrationId: string): Promise<BeginOAuthResponse> {\n await this.requireTier(\"pro\", \"connectIntegration\");\n return this.requestJson<BeginOAuthResponse>(\"POST\", `${this.integrationPath(projectId, integrationId)}/connect`);\n }\n\n /** Pro only: revoke an integration's OAuth connection (`POST .../disconnect`). */\n public async disconnectIntegration(projectId: string, integrationId: string): Promise<void> {\n await this.requireTier(\"pro\", \"disconnectIntegration\");\n await this.requestJson(\"POST\", `${this.integrationPath(projectId, integrationId)}/disconnect`);\n }\n\n /** Pro only: list the documents an integration exposes (`GET .../documents`). */\n public async listIntegrationDocuments(\n projectId: string,\n integrationId: string,\n params: ListIntegrationDocumentsParams = {},\n ): Promise<ListDocumentsResponse> {\n await this.requireTier(\"pro\", \"listIntegrationDocuments\");\n return this.requestJson<ListDocumentsResponse>(\n \"GET\",\n `${this.integrationPath(projectId, integrationId)}/documents`,\n {\n params: {\n mime_types: params.mimeTypes,\n folder_id: params.folderId,\n limit: params.limit,\n offset: params.offset,\n },\n },\n );\n }\n\n /**\n * Pro only: download one document from an integration\n * (`GET .../documents/{documentId}`). The response is raw bytes, not JSON.\n */\n public async fetchIntegrationDocument(\n projectId: string,\n integrationId: string,\n documentId: string,\n ): Promise<Uint8Array> {\n await this.requireTier(\"pro\", \"fetchIntegrationDocument\");\n const path = `${this.integrationPath(projectId, integrationId)}/documents/${encodePathSegment(documentId)}`;\n return this.requestBytes(\"GET\", path);\n }\n\n // -- Enterprise-only surface ------------------------------------------\n\n /**\n * Enterprise only: fetch a document's latest version with its extraction\n * result (`GET /v1/documents/{documentId}`). The spec declares an inline\n * schema, so the body is returned untyped.\n */\n public async getDocument(documentId: string): Promise<unknown> {\n await this.requireTier(\"enterprise\", \"getDocument\");\n return this.requestJson(\"GET\", this.documentPath(documentId));\n }\n\n /** Enterprise only: list a document's versions (`GET /v1/documents/{id}/versions`). */\n public async versions(documentId: string): Promise<DocumentVersionEntry[]> {\n await this.requireTier(\"enterprise\", \"versions\");\n return this.requestJson<DocumentVersionEntry[]>(\"GET\", `${this.documentPath(documentId)}/versions`);\n }\n\n /**\n * Enterprise only: diff document versions (`GET /v1/documents/{id}/diff`).\n *\n * Computed inline when the server can afford it (`200`, {@link DiffResponse}\n * in `result.body`), or queued for async computation when it can't (`202`,\n * a {@link DiffAsyncAccepted} job envelope in `result.body`) — the same\n * fallback {@link getDiffJob} polls. Narrow on `result.status`:\n *\n * ```ts\n * const result = await client.diff(documentId);\n * if (result.status === 200) {\n * // result.body: DiffResponse\n * } else {\n * // result.body: DiffAsyncAccepted — poll getDiffJob(documentId, result.body.diff_job_id)\n * }\n * ```\n */\n public async diff(documentId: string, params?: QueryParams): Promise<DiffResult> {\n await this.requireTier(\"enterprise\", \"diff\");\n const init: RequestParts = params !== undefined ? { params } : {};\n const { status, body } = await this.requestJsonWithStatus<DiffResponse | DiffAsyncAccepted>(\n \"GET\",\n `${this.documentPath(documentId)}/diff`,\n init,\n );\n return toDiffResult(status, body);\n }\n\n /**\n * Enterprise only: poll a diff job (`GET /v1/documents/{id}/diff/{diffJobId}`).\n *\n * Returns the same {@link DiffResult} union as {@link diff}: `200` once the\n * job has finished (`result.body`: {@link DiffResponse}), `202` while it is\n * still pending (`result.body`: {@link DiffAsyncAccepted}). Narrow on\n * `result.status` as shown in {@link diff}'s TSDoc.\n */\n public async getDiffJob(documentId: string, diffJobId: string): Promise<DiffResult> {\n await this.requireTier(\"enterprise\", \"getDiffJob\");\n const path = `${this.documentPath(documentId)}/diff/${encodePathSegment(diffJobId)}`;\n const { status, body } = await this.requestJsonWithStatus<DiffResponse | DiffAsyncAccepted>(\"GET\", path);\n return toDiffResult(status, body);\n }\n\n /** Enterprise only: list the project's extraction events (`GET /v1/extractions`). */\n public async listExtractionEvents(params: ListExtractionEventsParams = {}): Promise<ListExtractionEventsResponse> {\n await this.requireTier(\"enterprise\", \"listExtractionEvents\");\n return this.requestJson<ListExtractionEventsResponse>(\"GET\", EXTRACTIONS_PATH, {\n params: { days: params.days, limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Enterprise only: list a webhook subscription's delivery attempts\n * (`GET /v1/webhooks/{webhook_id}/deliveries`). Metadata only — call\n * {@link getSubscriptionDelivery} for an attempt's payload previews.\n *\n * ~keep Distinct from {@link listWebhookDeliveries}, which reads the same\n * history through the control plane's project-scoped route.\n */\n public async listSubscriptionDeliveries(\n webhookId: string,\n params: PaginationParams = {},\n ): Promise<ListWebhookDeliveriesResponse> {\n await this.requireTier(\"enterprise\", \"listSubscriptionDeliveries\");\n return this.requestJson<ListWebhookDeliveriesResponse>(\"GET\", this.webhookDeliveriesPath(webhookId), {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Enterprise only: fetch one delivery attempt with its bounded request and\n * response previews (`GET /v1/webhooks/{webhook_id}/deliveries/{delivery_id}`).\n * The previews can carry project document content.\n */\n public async getSubscriptionDelivery(webhookId: string, deliveryId: string): Promise<WebhookDeliveryDetailResponse> {\n await this.requireTier(\"enterprise\", \"getSubscriptionDelivery\");\n const path = `${this.webhookDeliveriesPath(webhookId)}/${encodePathSegment(deliveryId)}`;\n return this.requestJson<WebhookDeliveryDetailResponse>(\"GET\", path);\n }\n\n // -- Internals ---------------------------------------------------------\n\n /** Build `/v1/projects/{projectId}` with the id percent-encoded. */\n private projectPath(projectId: string): string {\n return `/v1/projects/${encodePathSegment(projectId)}`;\n }\n\n /** Build `/v1/projects/{projectId}/integrations/{integrationId}`. */\n private integrationPath(projectId: string, integrationId: string): string {\n return `${this.projectPath(projectId)}/integrations/${encodePathSegment(integrationId)}`;\n }\n\n /** Build `/v1/documents/{documentId}` with the id percent-encoded. */\n private documentPath(documentId: string): string {\n return `${DOCUMENTS_PATH}/${encodePathSegment(documentId)}`;\n }\n\n /** Build `/v1/saved_presets/{preset_id}` with the id percent-encoded. */\n private savedPresetPath(presetId: string): string {\n return `${SAVED_PRESETS_PATH}/${encodePathSegment(presetId)}`;\n }\n\n /** Build `/v1/auto-tune/{id}` with the id percent-encoded. */\n private autoTunePath(autoTuneJobId: string): string {\n return `${AUTO_TUNE_PATH}/${encodePathSegment(autoTuneJobId)}`;\n }\n\n /** Build `/v1/tuning-profiles/{id}` with the id percent-encoded. */\n private tuningProfilePath(profileId: string): string {\n return `${TUNING_PROFILES_PATH}/${encodePathSegment(profileId)}`;\n }\n\n /** Build `/v1/webhooks/{webhook_id}/deliveries` with the id percent-encoded. */\n private webhookDeliveriesPath(webhookId: string): string {\n return `${WEBHOOKS_PATH}/${encodePathSegment(webhookId)}/deliveries`;\n }\n\n /**\n * Return the effective tier — an explicit `target` if set, else probed from\n * `/healthz` and cached after the first *successful* probe. A probe that\n * fails (missing, `null`, or unrecognised `tier`) is not cached, so the\n * next call retries instead of being stuck with a poisoned result for the\n * client's lifetime. Concurrent callers share a single in-flight probe.\n */\n private async resolveTier(): Promise<Target> {\n if (this.target !== undefined) {\n return this.target;\n }\n if (this.probedTier !== undefined) {\n return this.probedTier;\n }\n if (this.tierProbe === undefined) {\n this.tierProbe = this.probeTier();\n }\n try {\n const tier = await this.tierProbe;\n this.probedTier = tier;\n return tier;\n } finally {\n this.tierProbe = undefined;\n }\n }\n\n /**\n * Issue the `/healthz` capability probe. Only `\"enterprise\"` and `\"pro\"` —\n * the tier values the specs actually declare — are accepted; anything else\n * (missing `tier`, `null`, or an unrecognised string) throws instead of\n * being treated as a usable result.\n */\n private async probeTier(): Promise<Target> {\n const body = await this.requestJson<{ tier?: unknown }>(\"GET\", \"/healthz\");\n const tier = body?.tier;\n if (tier === \"enterprise\" || tier === \"pro\") {\n return tier;\n }\n throw new XbergError(\n `/healthz returned an unrecognised tier (${JSON.stringify(tier ?? null)}); expected \"enterprise\" or \"pro\"`,\n { status: 0, body },\n );\n }\n\n /** Throw a clear error when the connected tier does not match the required one. */\n private async requireTier(required: Target, methodName: string): Promise<void> {\n const tier = await this.resolveTier();\n if (tier !== required) {\n throw new XbergError(`${methodName}() is not available on the '${tier}' tier (requires the '${required}' tier)`, {\n status: 0,\n body: null,\n });\n }\n }\n\n private backendRequest<T>(method: string, path: string, init: RequestParts = {}): Promise<T> {\n return this.requestJson<T>(method, path, { ...init, controlPlane: true });\n }\n\n private backendHeaders(init: RequestParts): Record<string, string> {\n const headers = new Headers({ ...this.headers, ...init.headers });\n for (const name of [\"authorization\", \"proxy-authorization\", \"cookie\", \"x-api-key\"]) headers.delete(name);\n const token = init.backendPublic ? init.sandboxToken : this.controlPlaneToken;\n if (token !== undefined && token.length > 0) headers.set(\"Authorization\", `Bearer ${token}`);\n if (init.body instanceof FormData || init.json !== undefined) headers.delete(\"content-type\");\n return Object.fromEntries(headers);\n }\n\n /** Issue a request, raise on non-2xx, and decode the JSON body (undefined for empty bodies). */\n private async requestJson<T = unknown>(method: string, path: string, init: RequestParts = {}): Promise<T> {\n const { body } = await this.requestJsonWithStatus<T>(method, path, init);\n return body;\n }\n\n /**\n * Like {@link requestJson}, but also returns the response's status code.\n * Used by endpoints whose 2xx responses carry different schemas per status\n * (currently only `diff`/`getDiffJob`'s `200`/`202` split).\n */\n private async requestJsonWithStatus<T = unknown>(\n method: string,\n path: string,\n init: RequestParts = {},\n ): Promise<{ status: number; body: T }> {\n const response = await this.requestWithRetry(method, path, init);\n if (response.status === 204) {\n return { status: response.status, body: undefined as T };\n }\n const text = await response.text();\n const body = (text.length > 0 ? JSON.parse(text) : undefined) as T;\n return { status: response.status, body };\n }\n\n /**\n * Open a `text/event-stream` response, deliberately bypassing\n * {@link requestWithRetry}.\n *\n * Two of that method's behaviours are wrong for a subscription. Its retry\n * loop would re-open a partly-consumed stream and redeliver every event the\n * caller already handled — indistinguishable, from the caller's side, from\n * the server sending them twice. And its `AbortSignal.timeout(timeoutMs)`\n * bounds a request/response round trip, while this response stays open for\n * the length of a crawl and is idle between events by design; the caller's\n * own `signal` is the only deadline.\n */\n private async openEventStream(path: string, signal?: AbortSignal): Promise<Response> {\n const url = `${this.baseUrl}${path}`;\n const requestInit: RequestInit = {\n method: \"GET\",\n headers: { ...this.headers, Accept: EVENT_STREAM_MEDIA_TYPE },\n };\n if (signal !== undefined) {\n requestInit.signal = signal;\n }\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, requestInit);\n } catch (cause) {\n throw new XbergError(`Network error contacting ${url}`, { status: 0, body: null, cause });\n }\n if (!response.ok) {\n await raiseForStatus(response);\n throw new XbergError(\"Unreachable\", { status: response.status, body: null });\n }\n return response;\n }\n\n /** Issue a request, raise on non-2xx, and return the response body as raw bytes. */\n private async requestBytes(method: string, path: string, init: RequestParts = {}): Promise<Uint8Array> {\n const response = await this.requestWithRetry(method, path, init);\n return new Uint8Array(await response.arrayBuffer());\n }\n\n /**\n * Issue a raw HTTP request with auth, timeout, query params, and retry\n * handling. Returns the raw (2xx) {@link Response}; non-2xx responses are\n * mapped to a thrown {@link XbergError} subclass.\n */\n private prepareRequest(method: string, init: RequestParts): RequestInit {\n const headers = init.controlPlane ? this.backendHeaders(init) : { ...this.headers, ...init.headers };\n let body: FormData | string | Uint8Array | undefined = init.body;\n if (init.json !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(init.json);\n }\n const requestInit: RequestInit = {\n method,\n headers,\n signal: AbortSignal.timeout(this.timeoutMs),\n ...(init.controlPlane ? ({ credentials: \"omit\", redirect: \"manual\" } as const) : {}),\n };\n if (body !== undefined) {\n requestInit.body = body;\n }\n return requestInit;\n }\n\n private async requestWithRetry(method: string, path: string, init: RequestParts = {}): Promise<Response> {\n if (init.controlPlane && (this.target ?? this.probedTier) === \"pro\") {\n throw new XbergError(\"Enterprise backend methods are not available on the 'pro' tier\", { status: 0, body: null });\n }\n const origin = init.controlPlane ? this.controlPlaneBaseUrl : this.baseUrl;\n const url = `${origin}${path}${buildQueryString(init.params)}`;\n let attempt = 0;\n let interval = DEFAULT_RETRY_BACKOFF_BASE_MS;\n for (;;) {\n const requestInit = this.prepareRequest(method, init);\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, requestInit);\n } catch (cause) {\n if (attempt < this.retries) {\n attempt += 1;\n await this.sleep(interval);\n interval = nextBackoffInterval(interval, this.retryBackoff);\n continue;\n }\n if (init.controlPlane) {\n throw new XbergError(`Network error contacting Enterprise control plane (${method} ${path})`, {\n status: 0,\n body: null,\n });\n }\n throw new XbergError(`Network error contacting ${url}`, { status: 0, body: null, cause });\n }\n\n if (response.ok || (init.acceptRedirect && response.status === 303)) {\n return response;\n }\n\n if (this.retryOn.includes(response.status) && attempt < this.retries) {\n attempt += 1;\n const retryAfter = parseRetryAfterHeader(response.headers.get(\"retry-after\"));\n const wait = retryAfter !== undefined ? retryAfter * 1000 : interval;\n await this.sleep(wait);\n interval = nextBackoffInterval(interval, this.retryBackoff);\n continue;\n }\n\n try {\n await raiseForStatus(response);\n } catch (error) {\n if (error instanceof RateLimitError && error.retryAfter !== undefined && attempt < this.retries) {\n attempt += 1;\n await this.sleep(error.retryAfter * 1000);\n interval = nextBackoffInterval(interval, this.retryBackoff);\n continue;\n }\n throw error;\n }\n throw new XbergError(\"Unreachable\", { status: response.status, body: null });\n }\n }\n}\n\n/** Parts accepted by the internal request engine. */\ninterface RequestParts {\n controlPlane?: boolean;\n backendPublic?: boolean;\n sandboxToken?: string;\n acceptRedirect?: boolean;\n body?: FormData | string | Uint8Array;\n json?: unknown;\n headers?: Record<string, string>;\n params?: QueryParams;\n}\n\n/**\n * Pair a diff response's status code with its body to build the\n * {@link DiffResult} union `diff`/`getDiffJob` return. `202` is the only\n * status carrying {@link DiffAsyncAccepted}; everything else (in practice\n * only `200`) carries the computed {@link DiffResponse}.\n */\nfunction toDiffResult(status: number, body: DiffResponse | DiffAsyncAccepted): DiffResult {\n if (status === 202) {\n return { status: 202, body: body as DiffAsyncAccepted };\n }\n return { status: 200, body: body as DiffResponse };\n}\n\n/**\n * Serialize a value with object keys sorted, so two configs that differ only in\n * key order compare equal when {@link appendPerFileConfigs} looks for a conflict.\n * Only ever used for that comparison — the value actually appended to the form is\n * a plain `JSON.stringify`, matching the `options` and `webhook` parts.\n */\nfunction canonicalJson(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map((entry) => canonicalJson(entry)).join(\",\")}]`;\n }\n if (typeof value === \"object\" && value !== null) {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, entry]) => entry !== undefined)\n .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));\n return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n\n/**\n * Append one `config-<filename>` part per document carrying a per-file override.\n *\n * Appended after the `file`, `options` and `webhook` parts, and skipped entirely\n * when `configs` is undefined, so a request without overrides is byte-identical\n * to one built before this existed.\n *\n * The part is keyed on the filename, mirroring the `document_id-<filename>`\n * convention. Two documents submitted under the same filename therefore have one\n * slot for two overrides: rather than let the later `append` win and lose the\n * other with no signal, that case throws and names the file.\n */\nfunction appendPerFileConfigs(\n form: FormData,\n filenames: readonly string[],\n configs: readonly (FileExtractionConfig | null)[] | undefined,\n): void {\n if (configs === undefined) {\n return;\n }\n if (configs.length !== filenames.length) {\n throw new XbergError(\n `configs has ${configs.length} entries but ${filenames.length} files were supplied; ` +\n \"pass exactly one entry per file (null for no override)\",\n { status: 400, body: null },\n );\n }\n const seen = new Map<string, string>();\n filenames.forEach((filename, index) => {\n const config = configs[index] ?? null;\n const canonical = canonicalJson(config);\n const prior = seen.get(filename);\n if (prior !== undefined && prior !== canonical) {\n throw new XbergError(\n `per-file config conflict for \"${filename}\": the same filename appears more than once in ` +\n \"this batch with different configs, but a multipart request carries at most one config \" +\n \"part per filename. Give the copies distinct filenames.\",\n { status: 400, body: null },\n );\n }\n if (prior === undefined && config !== null) {\n form.append(`config-${filename}`, JSON.stringify(config));\n }\n seen.set(filename, canonical);\n });\n}\n\n/** Parse one SSE frame payload into the `kind`-discriminated {@link CrawlEvent} it names. */\nfunction parseCrawlEvent(payload: string): CrawlEvent {\n let body: unknown;\n try {\n body = JSON.parse(payload);\n } catch (cause) {\n throw new XbergError(`Crawl event stream sent a non-JSON frame: ${payload}`, {\n status: 0,\n body: payload,\n cause,\n });\n }\n const kind = (body as { kind?: unknown } | null)?.kind;\n if (typeof kind !== \"string\" || !CRAWL_EVENT_KINDS.has(kind)) {\n throw new XbergError(`Crawl event stream sent an unrecognised kind (${JSON.stringify(kind ?? null)})`, {\n status: 0,\n body,\n });\n }\n return body as CrawlEvent;\n}\n\n/**\n * Drive one crawl-event subscription: open it, decode its frames, and cancel\n * the response body on every exit path.\n *\n * `open` is a thunk rather than an already-opened `Response` so that a caller\n * who never iterates opens nothing — the tier gate and the request both live\n * inside the generator. The `finally` runs when the consumer `break`s or\n * `return`s out of its `for await` as much as when the stream ends, which is\n * what makes the subscription cancellable without a separate handle.\n */\nasync function* iterateCrawlEvents(open: () => Promise<Response>): AsyncGenerator<CrawlEvent> {\n const response = await open();\n if (response.body === null) {\n throw new XbergError(\"Crawl event stream response carried no body\", {\n status: response.status,\n body: null,\n });\n }\n const reader = response.body.getReader();\n const text = new TextDecoder();\n const frames = new EventStreamDecoder();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n return;\n }\n for (const payload of frames.push(text.decode(value, { stream: true }))) {\n yield parseCrawlEvent(payload);\n }\n }\n } finally {\n // Never let a teardown failure mask the error that caused the teardown.\n await reader.cancel().catch(() => undefined);\n }\n}\n\n/** Backwards-compatible factory returning the low-level `openapi-fetch` client. */\nexport interface CreateClientOptions {\n baseUrl?: string;\n apiKey?: string;\n headers?: Record<string, string>;\n fetch?: typeof fetch;\n}\n\nexport function createClient(options: CreateClientOptions = {}): XbergRawClient {\n const headers: Record<string, string> = {\n \"User-Agent\": USER_AGENT,\n ...options.headers,\n };\n if (options.apiKey !== undefined) {\n headers[\"Authorization\"] = `Bearer ${options.apiKey}`;\n }\n return createOpenApiClient<paths>({\n baseUrl: options.baseUrl ?? DEFAULT_ENTERPRISE_BASE_URL,\n headers,\n ...(options.fetch !== undefined ? { fetch: options.fetch } : {}),\n });\n}\n\nfunction sandboxForm(params: PublicSandboxExtractParams): FormData {\n if (params.file === undefined && !(params.mode === \"web\" && params.url !== undefined && params.url.length > 0)) {\n throw new XbergError(\"Sandbox extraction requires a file or web mode with a URL\", { status: 400, body: null });\n }\n const form = new FormData();\n if (params.file !== undefined) {\n const { blob, filename } = toBlob(params.file);\n form.append(\"file\", blob, filename);\n }\n for (const name of [\"mode\", \"preset\", \"url\"] as const) {\n const value = params[name];\n if (value !== undefined) form.append(name, value);\n }\n return form;\n}\n\nfunction prepareDocumentLineage(\n filenames: readonly string[],\n ids: readonly (string | null)[] | undefined,\n): Map<string, string> {\n const fields = new Map<string, string>();\n if (ids === undefined) return fields;\n if (ids.length !== filenames.length)\n throw new XbergError(\"documentIds must contain one entry per file\", { status: 400, body: null });\n const seen = new Map<string, string | null>();\n for (const [index, filename] of filenames.entries()) {\n const id = ids[index];\n if (\n id !== null &&\n (typeof id !== \"string\" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id))\n ) {\n throw new XbergError(\"documentIds must contain UUID strings or null\", { status: 400, body: null });\n }\n const canonical = id === null ? null : id.toLowerCase();\n if (seen.has(filename) && seen.get(filename) !== canonical)\n throw new XbergError(\"Conflicting document IDs for the same filename\", { status: 400, body: null });\n seen.set(filename, canonical);\n if (canonical !== null) fields.set(filename, canonical);\n }\n return fields;\n}\n"],"mappings":";;;AAcA,IAAa,aAAb,cAAgC,MAAM;CACpC,AAAgB;CAChB,AAAgB;CAEhB,AAAO,YAAY,SAAiB,SAA4B;EAC9D,MAAMA,YAA0B,QAAQ,UAAU,SAAY,EAAE,GAAG,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