@xberg-io/sdk 0.0.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +163 -9
- package/dist/index.d.ts +30306 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1303 -0
- package/dist/index.js.map +1 -0
- package/package.json +41 -4
|
@@ -0,0 +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>","filenames: 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([new Uint8Array(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([new Uint8Array(wrapper.data)], { type: mimeType }),\n filename: name,\n };\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(\n `Crawl event stream sent a line longer than ${MAX_EVENT_STREAM_FRAME_BYTES} bytes`,\n { status: 0, 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 * Friendly re-exports of the two generated 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`. The two schema sets are generated separately and never\n * merged — mirrors xberg-enterprise ADR-0072.\n */\n\nimport type { components } from \"./_generated/api.js\";\nimport type { components as proComponents } from \"./_generated/pro.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","/**\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.4.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`; no method routes there yet, so today it is\n * configuration held for the control-plane operations that have not landed.\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 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 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 * No method routes to it yet. The control-plane operations are vendored but\n * unimplemented (xberg-io/sdks#22), and every control-plane method this\n * client does have is Pro-only and tier-gated, so today this option only\n * records an origin that {@link XbergClient.controlPlaneBaseUrl} reads back.\n * It ships ahead of those methods so the constructor does not change shape\n * when they land.\n */\n controlPlaneBaseUrl?: string;\n /**\n * Which product to talk to. When omitted, the tier is discovered lazily from\n * `GET /healthz` before the first tier-specific call. Enterprise defaults\n * `baseUrl`; `target: \"pro\"` requires an explicit `baseUrl`.\n */\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 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 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\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 the control-plane surface will be addressed at. Same as `baseUrl`\n * unless overridden. No request is routed there yet — see\n * {@link XbergClientOptions.controlPlaneBaseUrl}.\n */\n public readonly controlPlaneBaseUrl: string;\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.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 // -- 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.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 form = new FormData();\n const filenames: string[] = [];\n for (const file of params.files) {\n const { blob, filename } = toBlob(file);\n form.append(\"file\", blob, filename);\n filenames.push(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}/${encodeURIComponent(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}/${encodeURIComponent(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}/${encodeURIComponent(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.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/${encodeURIComponent(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/${encodeURIComponent(presetId)}/sample/${encodeURIComponent(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/${encodeURIComponent(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/${encodeURIComponent(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/${encodeURIComponent(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/${encodeURIComponent(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/${encodeURIComponent(name)}/documents/${encodeURIComponent(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/${encodeURIComponent(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/${encodeURIComponent(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/${encodeURIComponent(name)}/migrate-embeddings/${encodeURIComponent(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/${encodeURIComponent(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/${encodeURIComponent(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/${encodeURIComponent(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/${encodeURIComponent(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/${encodeURIComponent(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/${encodeURIComponent(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}/${encodeURIComponent(jobId)}/pages/${encodeURIComponent(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}/${encodeURIComponent(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}/${encodeURIComponent(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/${encodeURIComponent(projectId)}`;\n }\n\n /** Build `/v1/projects/{projectId}/integrations/{integrationId}`. */\n private integrationPath(projectId: string, integrationId: string): string {\n return `${this.projectPath(projectId)}/integrations/${encodeURIComponent(integrationId)}`;\n }\n\n /** Build `/v1/documents/{documentId}` with the id percent-encoded. */\n private documentPath(documentId: string): string {\n return `${DOCUMENTS_PATH}/${encodeURIComponent(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}/${encodeURIComponent(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}/${encodeURIComponent(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}/${encodeURIComponent(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 /** 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 async requestWithRetry(method: string, path: string, init: RequestParts = {}): Promise<Response> {\n const url = `${this.baseUrl}${path}${buildQueryString(init.params)}`;\n let attempt = 0;\n let interval = DEFAULT_RETRY_BACKOFF_BASE_MS;\n for (;;) {\n const headers = { ...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 = { method, headers, signal: AbortSignal.timeout(this.timeoutMs) };\n if (body !== undefined) {\n requestInit.body = body;\n }\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 throw new XbergError(`Network error contacting ${url}`, { status: 0, body: null, cause });\n }\n\n if (response.ok) {\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 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"],"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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WAAW,+CAA+C;EAClE,QAAQ,SAAS;EACjB,MAAM;EACP,CAAC;CAEJ,MAAM,SAAS,SAAS,KAAK,WAAW;CACxC,MAAM,OAAO,IAAI,aAAa;CAC9B,MAAM,SAAS,IAAI,oBAAoB;AACvC,KAAI;AACF,WAAS;GACP,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,MAAM;AAC3C,OAAI,KACF;AAEF,QAAK,MAAM,WAAW,OAAO,KAAK,KAAK,OAAO,OAAO,EAAE,QAAQ,MAAM,CAAC,CAAC,CACrE,OAAM,gBAAgB,QAAQ;;WAG1B;AAER,QAAM,OAAO,QAAQ,CAAC,YAAY,OAAU;;;AAYhD,SAAgB,aAAa,UAA+B,EAAE,EAAkB;CAC9E,MAAMC,UAAkC;EACtC,cAAc;EACd,GAAG,QAAQ;EACZ;AACD,KAAI,QAAQ,WAAW,OACrB,SAAQ,mBAAmB,UAAU,QAAQ;AAE/C,QAAO,oBAA2B;EAChC,SAAS,QAAQ,WAAW;EAC5B;EACA,GAAI,QAAQ,UAAU,SAAY,EAAE,OAAO,QAAQ,OAAO,GAAG,EAAE;EAChE,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xberg-io/sdk",
|
|
3
|
-
"version": "0.0
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "Official TypeScript client for the Xberg Enterprise and Xberg Pro document-processing APIs.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Kreuzberg, Inc. <contact@xberg.io>",
|
|
7
7
|
"homepage": "https://enterprise.xberg.io",
|
|
@@ -23,7 +23,18 @@
|
|
|
23
23
|
"document-extraction"
|
|
24
24
|
],
|
|
25
25
|
"type": "module",
|
|
26
|
+
"main": "./dist/index.js",
|
|
27
|
+
"module": "./dist/index.js",
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"import": "./dist/index.js"
|
|
33
|
+
},
|
|
34
|
+
"./package.json": "./package.json"
|
|
35
|
+
},
|
|
26
36
|
"files": [
|
|
37
|
+
"dist",
|
|
27
38
|
"README.md",
|
|
28
39
|
"LICENSE"
|
|
29
40
|
],
|
|
@@ -31,6 +42,32 @@
|
|
|
31
42
|
"node": ">=22"
|
|
32
43
|
},
|
|
33
44
|
"publishConfig": {
|
|
34
|
-
"access": "public"
|
|
45
|
+
"access": "public",
|
|
46
|
+
"provenance": true
|
|
47
|
+
},
|
|
48
|
+
"dependencies": {
|
|
49
|
+
"openapi-fetch": "^0.17.0"
|
|
50
|
+
},
|
|
51
|
+
"devDependencies": {
|
|
52
|
+
"@types/node": "^25.9.1",
|
|
53
|
+
"@vitest/coverage-v8": "^4.1.7",
|
|
54
|
+
"msw": "^2.14.6",
|
|
55
|
+
"openapi-typescript": "^7.13.0",
|
|
56
|
+
"oxfmt": "^0.47.0",
|
|
57
|
+
"oxlint": "^1.66.0",
|
|
58
|
+
"tsdown": "^0.18.4",
|
|
59
|
+
"typescript": "^6.0.3",
|
|
60
|
+
"vitest": "^4.1.7"
|
|
61
|
+
},
|
|
62
|
+
"scripts": {
|
|
63
|
+
"build": "pnpm run generate && tsdown",
|
|
64
|
+
"generate": "bash scripts/generate.sh",
|
|
65
|
+
"typecheck": "tsc --noEmit",
|
|
66
|
+
"lint": "oxlint src tests && tsc --noEmit",
|
|
67
|
+
"format": "oxfmt --write src tests",
|
|
68
|
+
"format:check": "oxfmt --check src tests",
|
|
69
|
+
"test": "vitest run",
|
|
70
|
+
"test:watch": "vitest",
|
|
71
|
+
"test:coverage": "vitest run --coverage"
|
|
35
72
|
}
|
|
36
|
-
}
|
|
73
|
+
}
|