@xberg-io/sdk 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -194,7 +194,7 @@ function toBlob(file) {
194
194
  filename: "upload.bin"
195
195
  };
196
196
  if (file instanceof Uint8Array) return {
197
- blob: new Blob([new Uint8Array(file)], { type: "application/octet-stream" }),
197
+ blob: new Blob([blobBytes(file)], { type: "application/octet-stream" }),
198
198
  filename: "upload.bin"
199
199
  };
200
200
  const wrapper = file;
@@ -205,10 +205,13 @@ function toBlob(file) {
205
205
  filename: name
206
206
  };
207
207
  return {
208
- blob: new Blob([new Uint8Array(wrapper.data)], { type: mimeType }),
208
+ blob: new Blob([blobBytes(wrapper.data)], { type: mimeType }),
209
209
  filename: name
210
210
  };
211
211
  }
212
+ function blobBytes(bytes) {
213
+ return bytes.buffer instanceof ArrayBuffer ? new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength) : new Uint8Array(bytes);
214
+ }
212
215
  function guessMimeType(filename) {
213
216
  const lower = filename.toLowerCase();
214
217
  if (lower.endsWith(".csv")) return "text/csv";
@@ -314,6 +317,14 @@ var EventStreamDecoder = class {
314
317
  return payload;
315
318
  }
316
319
  };
320
+ /** Encode a path identifier without allowing the HTTP client to change its route. */
321
+ function encodePathSegment(value) {
322
+ if (value === "." || value === "..") throw new XbergError("Path identifiers must not be '.' or '..'", {
323
+ status: 400,
324
+ body: null
325
+ });
326
+ return encodeURIComponent(value);
327
+ }
317
328
 
318
329
  //#endregion
319
330
  //#region src/types.ts
@@ -339,7 +350,7 @@ const SUCCESS_JOB_STATUSES = ["completed", "partial_success"];
339
350
  * Package version, synced from the repo-root `VERSION` file by
340
351
  * `scripts/sync-versions.py`. Used to build the `User-Agent` header. ~keep
341
352
  */
342
- const VERSION = "0.4.0";
353
+ const VERSION = "0.5.0";
343
354
 
344
355
  //#endregion
345
356
  //#region src/client.ts
@@ -360,8 +371,8 @@ const VERSION = "0.4.0";
360
371
  * Enterprise splits into two binaries — the data plane `baseUrl` addresses and a
361
372
  * control plane (projects, API keys, integrations) on its own origin — while Pro
362
373
  * serves both from one. `controlPlaneBaseUrl` records the origin of the second
363
- * and defaults to `baseUrl`; no method routes there yet, so today it is
364
- * configuration held for the control-plane operations that have not landed.
374
+ * and defaults to `baseUrl`. The backend methods use that origin and an optional
375
+ * separate `controlPlaneToken`; existing Pro methods retain their data-plane routing.
365
376
  */
366
377
  const USER_AGENT = `xberg-io-sdk-typescript/${VERSION}`;
367
378
  const DEFAULT_TIMEOUT_MS = 3e4;
@@ -403,11 +414,10 @@ const CRAWL_EVENT_KINDS = new Set([
403
414
  var XbergClient = class {
404
415
  baseUrl;
405
416
  /**
406
- * Origin the control-plane surface will be addressed at. Same as `baseUrl`
407
- * unless overridden. No request is routed there yet — see
408
- * {@link XbergClientOptions.controlPlaneBaseUrl}.
417
+ * Origin used by the Enterprise backend methods. Defaults to `baseUrl`.
409
418
  */
410
419
  controlPlaneBaseUrl;
420
+ controlPlaneToken;
411
421
  headers;
412
422
  fetchImpl;
413
423
  timeoutMs;
@@ -425,6 +435,7 @@ var XbergClient = class {
425
435
  if (options.target !== void 0) this.target = options.target;
426
436
  this.baseUrl = resolveBaseUrl(options.baseUrl, options.target);
427
437
  this.controlPlaneBaseUrl = resolveControlPlaneBaseUrl(options.controlPlaneBaseUrl, this.baseUrl);
438
+ this.controlPlaneToken = options.controlPlaneToken ?? options.apiKey;
428
439
  this.fetchImpl = options.fetch ?? fetch;
429
440
  this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
430
441
  this.retries = options.retries ?? 0;
@@ -442,6 +453,255 @@ var XbergClient = class {
442
453
  fetch: this.fetchImpl
443
454
  });
444
455
  }
456
+ /** Enterprise backend `DELETE /auth/account`. */
457
+ async deleteAccount() {
458
+ return await this.backendRequest("DELETE", `/auth/account`);
459
+ }
460
+ /** Enterprise backend `GET /auth/config`. */
461
+ async getAuthConfig() {
462
+ return await this.backendRequest("GET", `/auth/config`, { backendPublic: true });
463
+ }
464
+ /** Enterprise backend `POST /auth/login`. */
465
+ async backendLogin(body) {
466
+ return await this.backendRequest("POST", `/auth/login`, {
467
+ json: body,
468
+ backendPublic: true
469
+ });
470
+ }
471
+ /** Enterprise backend `GET /healthz`. */
472
+ async healthz() {
473
+ return await this.backendRequest("GET", `/healthz`, { backendPublic: true });
474
+ }
475
+ /** Enterprise backend `GET /readyz`. */
476
+ async readyz() {
477
+ return await this.backendRequest("GET", `/readyz`, { backendPublic: true });
478
+ }
479
+ /** Enterprise backend `POST /v1/invitations/accept`. */
480
+ async acceptInvitation(body) {
481
+ return await this.backendRequest("POST", `/v1/invitations/accept`, { json: body });
482
+ }
483
+ /** Enterprise backend `GET /v1/oauth/callback`. */
484
+ async oauthCallback(params) {
485
+ const response = await this.requestWithRetry("GET", "/v1/oauth/callback", {
486
+ controlPlane: true,
487
+ backendPublic: true,
488
+ acceptRedirect: true,
489
+ params: {
490
+ code: params.code,
491
+ state: params.state
492
+ }
493
+ });
494
+ const location = response.headers.get("location");
495
+ await response.body?.cancel();
496
+ if (response.status !== 303 || location === null || location.length === 0) throw new XbergError("OAuth callback did not return a 303 Location", {
497
+ status: response.status,
498
+ body: null
499
+ });
500
+ return location;
501
+ }
502
+ /** Enterprise backend `GET /v1/projects`. */
503
+ async backendListProjects(params = {}) {
504
+ return await this.backendRequest("GET", `/v1/projects`, { params: {
505
+ limit: params.limit,
506
+ offset: params.offset
507
+ } });
508
+ }
509
+ /** Enterprise backend `POST /v1/projects`. */
510
+ async backendCreateProject(body) {
511
+ return await this.backendRequest("POST", `/v1/projects`, { json: body });
512
+ }
513
+ /** Enterprise backend `GET /v1/projects/{id}`. */
514
+ async getProject(projectId) {
515
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}`);
516
+ }
517
+ /** Enterprise backend `DELETE /v1/projects/{id}`. */
518
+ async deleteProject(projectId, params = {}) {
519
+ return await this.backendRequest("DELETE", `/v1/projects/${encodePathSegment(projectId)}`, { params: { erase: params.erase === void 0 ? void 0 : String(params.erase) } });
520
+ }
521
+ /** Enterprise backend `PATCH /v1/projects/{id}`. */
522
+ async updateProject(projectId, body) {
523
+ return await this.backendRequest("PATCH", `/v1/projects/${encodePathSegment(projectId)}`, { json: body });
524
+ }
525
+ /** Enterprise backend `GET /v1/projects/{id}/analytics`. */
526
+ async getAnalytics(projectId, params) {
527
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/analytics`, { params: {
528
+ start_date: params.startDate,
529
+ end_date: params.endDate
530
+ } });
531
+ }
532
+ /** Enterprise backend `GET /v1/projects/{id}/api-keys`. */
533
+ async backendListApiKeys(projectId, params = {}) {
534
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/api-keys`, { params: {
535
+ limit: params.limit,
536
+ offset: params.offset
537
+ } });
538
+ }
539
+ /** Enterprise backend `POST /v1/projects/{id}/api-keys`. */
540
+ async backendCreateApiKey(projectId, body) {
541
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/api-keys`, { json: body });
542
+ }
543
+ /** Enterprise backend `DELETE /v1/projects/{id}/api-keys/{key_id}`. */
544
+ async backendRevokeApiKey(projectId, apiKeyId) {
545
+ return await this.backendRequest("DELETE", `/v1/projects/${encodePathSegment(projectId)}/api-keys/${encodePathSegment(apiKeyId)}`);
546
+ }
547
+ /** Enterprise backend `POST /v1/projects/{id}/api-keys/{key_id}/regenerate`. */
548
+ async regenerateApiKey(projectId, apiKeyId) {
549
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/api-keys/${encodePathSegment(apiKeyId)}/regenerate`);
550
+ }
551
+ /** Enterprise backend `GET /v1/projects/{id}/audit`. */
552
+ async listProjectAudit(projectId, params = {}) {
553
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/audit`, { params: {
554
+ action: params.action,
555
+ limit: params.limit,
556
+ offset: params.offset
557
+ } });
558
+ }
559
+ /** Enterprise backend `GET /v1/projects/{id}/billing`. */
560
+ async getBilling(projectId) {
561
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/billing`);
562
+ }
563
+ /** Enterprise backend `POST /v1/projects/{id}/billing/checkout`. */
564
+ async createCheckout(projectId) {
565
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/billing/checkout`);
566
+ }
567
+ /** Enterprise backend `POST /v1/projects/{id}/billing/portal`. */
568
+ async createPortal(projectId) {
569
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/billing/portal`);
570
+ }
571
+ /** Enterprise backend `GET /v1/projects/{id}/integrations`. */
572
+ async backendListIntegrations(projectId, params = {}) {
573
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/integrations`, { params: {
574
+ limit: params.limit,
575
+ offset: params.offset
576
+ } });
577
+ }
578
+ /** Enterprise backend `POST /v1/projects/{id}/integrations`. */
579
+ async backendCreateIntegration(projectId, body) {
580
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/integrations`, { json: body });
581
+ }
582
+ /** Enterprise backend `GET /v1/projects/{id}/integrations/{iid}`. */
583
+ async backendGetIntegration(projectId, integrationId) {
584
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}`);
585
+ }
586
+ /** Enterprise backend `DELETE /v1/projects/{id}/integrations/{iid}`. */
587
+ async backendDeleteIntegration(projectId, integrationId) {
588
+ return await this.backendRequest("DELETE", `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}`);
589
+ }
590
+ /** Enterprise backend `POST /v1/projects/{id}/integrations/{iid}/connect`. */
591
+ async oauthConnect(projectId, integrationId) {
592
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/connect`);
593
+ }
594
+ /** Enterprise backend `POST /v1/projects/{id}/integrations/{iid}/disconnect`. */
595
+ async backendDisconnectIntegration(projectId, integrationId) {
596
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/disconnect`);
597
+ }
598
+ /** Enterprise backend `GET /v1/projects/{id}/integrations/{iid}/documents`. */
599
+ async backendListIntegrationDocuments(projectId, integrationId, params = {}) {
600
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/documents`, { params: {
601
+ mime_types: params.mimeTypes,
602
+ folder_id: params.folderId,
603
+ max_results: params.maxResults
604
+ } });
605
+ }
606
+ /** Enterprise backend `GET /v1/projects/{id}/integrations/{iid}/documents/{doc_id}`. */
607
+ async backendFetchIntegrationDocument(projectId, integrationId, documentId) {
608
+ return await this.requestBytes("GET", `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/documents/${encodePathSegment(documentId)}`, { controlPlane: true });
609
+ }
610
+ /** Enterprise backend `GET /v1/projects/{id}/invitations`. */
611
+ async listInvitations(projectId, params = {}) {
612
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/invitations`, { params: {
613
+ limit: params.limit,
614
+ offset: params.offset
615
+ } });
616
+ }
617
+ /** Enterprise backend `POST /v1/projects/{id}/invitations`. */
618
+ async inviteUser(projectId, body) {
619
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/invitations`, { json: body });
620
+ }
621
+ /** Enterprise backend `DELETE /v1/projects/{id}/invitations/{inv_id}`. */
622
+ async revokeInvitation(projectId, invitationId) {
623
+ return await this.backendRequest("DELETE", `/v1/projects/${encodePathSegment(projectId)}/invitations/${encodePathSegment(invitationId)}`);
624
+ }
625
+ /** Enterprise backend `POST /v1/projects/{id}/leave`. */
626
+ async leaveProject(projectId) {
627
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/leave`);
628
+ }
629
+ /** Enterprise backend `GET /v1/projects/{id}/members`. */
630
+ async listMembers(projectId, params = {}) {
631
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/members`, { params: {
632
+ limit: params.limit,
633
+ offset: params.offset
634
+ } });
635
+ }
636
+ /** Enterprise backend `DELETE /v1/projects/{id}/members/{user_id}`. */
637
+ async removeMember(projectId, userId) {
638
+ return await this.backendRequest("DELETE", `/v1/projects/${encodePathSegment(projectId)}/members/${encodePathSegment(userId)}`);
639
+ }
640
+ /** Enterprise backend `PATCH /v1/projects/{id}/members/{user_id}`. */
641
+ async updateMemberRole(projectId, userId, body) {
642
+ return await this.backendRequest("PATCH", `/v1/projects/${encodePathSegment(projectId)}/members/${encodePathSegment(userId)}`, { json: body });
643
+ }
644
+ /** Enterprise backend `GET /v1/projects/{id}/rag-config`. */
645
+ async backendGetRagConfig(projectId) {
646
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/rag-config`);
647
+ }
648
+ /** Enterprise backend `PUT /v1/projects/{id}/rag-config`. */
649
+ async backendSetRagConfig(projectId, body) {
650
+ return await this.backendRequest("PUT", `/v1/projects/${encodePathSegment(projectId)}/rag-config`, { json: body });
651
+ }
652
+ /** Enterprise backend `POST /v1/projects/{id}/sandbox/extract`. */
653
+ async sandboxExtract(projectId, params) {
654
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/sandbox/extract`, { body: sandboxForm(params) });
655
+ }
656
+ /** Enterprise backend `GET /v1/projects/{id}/usage`. */
657
+ async getUsage(projectId, params) {
658
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/usage`, { params: {
659
+ start_date: params.startDate,
660
+ end_date: params.endDate
661
+ } });
662
+ }
663
+ /** Enterprise backend `GET /v1/projects/{id}/webhooks`. */
664
+ async listWebhooks(projectId, params = {}) {
665
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/webhooks`, { params: {
666
+ limit: params.limit,
667
+ offset: params.offset
668
+ } });
669
+ }
670
+ /** Enterprise backend `POST /v1/projects/{id}/webhooks`. */
671
+ async createWebhook(projectId, body) {
672
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/webhooks`, { json: body });
673
+ }
674
+ /** Enterprise backend `DELETE /v1/projects/{id}/webhooks/{wh_id}`. */
675
+ async deleteWebhook(projectId, webhookId) {
676
+ return await this.backendRequest("DELETE", `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}`);
677
+ }
678
+ /** Enterprise backend `PATCH /v1/projects/{id}/webhooks/{wh_id}`. */
679
+ async updateWebhook(projectId, webhookId, body) {
680
+ return await this.backendRequest("PATCH", `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}`, { json: body });
681
+ }
682
+ /** Enterprise backend `GET /v1/projects/{id}/webhooks/{wh_id}/deliveries`. */
683
+ async listWebhookDeliveries(projectId, webhookId, params = {}) {
684
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}/deliveries`, { params: {
685
+ limit: params.limit,
686
+ offset: params.offset
687
+ } });
688
+ }
689
+ /** Enterprise backend `POST /v1/projects/{id}/webhooks/{wh_id}/deliveries/{delivery_id}/retry`. */
690
+ async retryWebhookDelivery(projectId, webhookId, deliveryId) {
691
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}/deliveries/${encodePathSegment(deliveryId)}/retry`);
692
+ }
693
+ /** Enterprise backend `POST /v1/projects/{id}/webhooks/{wh_id}/test`. */
694
+ async testWebhook(projectId, webhookId) {
695
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}/test`);
696
+ }
697
+ /** Enterprise backend `POST /v1/sandbox/public/extract`. */
698
+ async publicSandboxExtract(params) {
699
+ return await this.backendRequest("POST", `/v1/sandbox/public/extract`, {
700
+ body: sandboxForm(params),
701
+ ...params.sandboxToken !== void 0 ? { sandboxToken: params.sandboxToken } : {},
702
+ backendPublic: true
703
+ });
704
+ }
445
705
  /**
446
706
  * Submit a single document for extraction. Returns the initial {@link Job}
447
707
  * record (still pending — call `waitForJob` to await completion).
@@ -449,6 +709,7 @@ var XbergClient = class {
449
709
  async extract(params) {
450
710
  const jobs = await this.extractBatch({
451
711
  files: [params.file],
712
+ ...params.documentId !== void 0 ? { documentIds: [params.documentId] } : {},
452
713
  ...params.options !== void 0 ? { options: params.options } : {},
453
714
  ...params.webhook !== void 0 ? { webhook: params.webhook } : {},
454
715
  ...params.config !== void 0 ? { configs: [params.config] } : {}
@@ -469,12 +730,14 @@ var XbergClient = class {
469
730
  status: 400,
470
731
  body: null
471
732
  });
733
+ const filenames = params.files.map(describeFile);
734
+ const documentIds = prepareDocumentLineage(filenames, params.documentIds);
735
+ if (documentIds.size > 0) await this.requireTier("enterprise", "extract document lineage");
472
736
  const form = new FormData();
473
- const filenames = [];
737
+ for (const [filename, documentId] of documentIds) form.append(`document_id-${filename}`, documentId);
474
738
  for (const file of params.files) {
475
739
  const { blob, filename } = toBlob(file);
476
740
  form.append("file", blob, filename);
477
- filenames.push(filename);
478
741
  }
479
742
  if (params.options !== void 0) form.append("options", JSON.stringify(params.options));
480
743
  if (params.webhook !== void 0) form.append("webhook", JSON.stringify(params.webhook));
@@ -498,7 +761,7 @@ var XbergClient = class {
498
761
  }
499
762
  /** Fetch the current state of a job. */
500
763
  async getJob(jobId) {
501
- return await this.requestJson("GET", `${JOBS_PATH}/${encodeURIComponent(jobId)}`);
764
+ return await this.requestJson("GET", `${JOBS_PATH}/${encodePathSegment(jobId)}`);
502
765
  }
503
766
  /**
504
767
  * Fetch a job's stored result document (`GET /v1/jobs/{id}/result`).
@@ -508,7 +771,7 @@ var XbergClient = class {
508
771
  * returns the job's metadata record.
509
772
  */
510
773
  async getJobResult(jobId) {
511
- return await this.requestJson("GET", `${JOBS_PATH}/${encodeURIComponent(jobId)}/result`);
774
+ return await this.requestJson("GET", `${JOBS_PATH}/${encodePathSegment(jobId)}/result`);
512
775
  }
513
776
  /** List jobs (paginated) via `GET /v1/jobs`. */
514
777
  async listJobs(params = {}) {
@@ -523,7 +786,7 @@ var XbergClient = class {
523
786
  * `204`.
524
787
  */
525
788
  async cancelJob(jobId) {
526
- await this.requestJson("DELETE", `${JOBS_PATH}/${encodeURIComponent(jobId)}`);
789
+ await this.requestJson("DELETE", `${JOBS_PATH}/${encodePathSegment(jobId)}`);
527
790
  }
528
791
  /**
529
792
  * Poll {@link getJob} until the job reaches a terminal status. Throws
@@ -563,6 +826,7 @@ var XbergClient = class {
563
826
  async extractAndWait(params) {
564
827
  const extractParams = {
565
828
  file: params.file,
829
+ ...params.documentId !== void 0 ? { documentId: params.documentId } : {},
566
830
  ...params.options !== void 0 ? { options: params.options } : {},
567
831
  ...params.webhook !== void 0 ? { webhook: params.webhook } : {},
568
832
  ...params.config !== void 0 ? { config: params.config } : {}
@@ -589,7 +853,7 @@ var XbergClient = class {
589
853
  }
590
854
  /** Fetch one curated preset in full (`GET /v1/presets/{id}`). */
591
855
  async getPreset(presetId) {
592
- return await this.requestJson("GET", `/v1/presets/${encodeURIComponent(presetId)}`);
856
+ return await this.requestJson("GET", `/v1/presets/${encodePathSegment(presetId)}`);
593
857
  }
594
858
  /**
595
859
  * Download a preset's bundled sample file
@@ -597,7 +861,7 @@ var XbergClient = class {
597
861
  * JSON.
598
862
  */
599
863
  async getPresetSample(presetId, name) {
600
- const path = `/v1/presets/${encodeURIComponent(presetId)}/sample/${encodeURIComponent(name)}`;
864
+ const path = `/v1/presets/${encodePathSegment(presetId)}/sample/${encodePathSegment(name)}`;
601
865
  return await this.requestBytes("GET", path);
602
866
  }
603
867
  /** List RAG collections (`GET /v1/rag/collections`). */
@@ -610,15 +874,15 @@ var XbergClient = class {
610
874
  }
611
875
  /** Fetch a RAG collection (`GET /v1/rag/collections/{name}`). */
612
876
  async getRagCollection(name) {
613
- return await this.requestJson("GET", `/v1/rag/collections/${encodeURIComponent(name)}`);
877
+ return await this.requestJson("GET", `/v1/rag/collections/${encodePathSegment(name)}`);
614
878
  }
615
879
  /** Delete a RAG collection (`DELETE /v1/rag/collections/{name}`). The spec documents a 204 with no content. */
616
880
  async deleteRagCollection(name) {
617
- await this.requestJson("DELETE", `/v1/rag/collections/${encodeURIComponent(name)}`);
881
+ await this.requestJson("DELETE", `/v1/rag/collections/${encodePathSegment(name)}`);
618
882
  }
619
883
  /** Add documents to a RAG collection (`POST /v1/rag/collections/{name}/documents`). */
620
884
  async addRagDocuments(name, body) {
621
- return await this.requestJson("POST", `/v1/rag/collections/${encodeURIComponent(name)}/documents`, { json: body });
885
+ return await this.requestJson("POST", `/v1/rag/collections/${encodePathSegment(name)}/documents`, { json: body });
622
886
  }
623
887
  /**
624
888
  * Delete documents from a RAG collection, by ID list or metadata filter
@@ -627,29 +891,29 @@ var XbergClient = class {
627
891
  * many documents were removed.
628
892
  */
629
893
  async deleteRagDocuments(name, body) {
630
- return await this.requestJson("DELETE", `/v1/rag/collections/${encodeURIComponent(name)}/documents`, { json: body });
894
+ return await this.requestJson("DELETE", `/v1/rag/collections/${encodePathSegment(name)}/documents`, { json: body });
631
895
  }
632
896
  /** Reindex a RAG document (`POST /v1/rag/collections/{name}/documents/{id}/reindex`). */
633
897
  async reindexRagDocument(name, documentId, body) {
634
- const path = `/v1/rag/collections/${encodeURIComponent(name)}/documents/${encodeURIComponent(documentId)}/reindex`;
898
+ const path = `/v1/rag/collections/${encodePathSegment(name)}/documents/${encodePathSegment(documentId)}/reindex`;
635
899
  return await this.requestJson("POST", path, body !== void 0 ? { json: body } : {});
636
900
  }
637
901
  /** Retrieve chunks from a RAG collection (`POST /v1/rag/collections/{name}/retrieve`). */
638
902
  async ragRetrieve(name, body) {
639
- return await this.requestJson("POST", `/v1/rag/collections/${encodeURIComponent(name)}/retrieve`, { json: body });
903
+ return await this.requestJson("POST", `/v1/rag/collections/${encodePathSegment(name)}/retrieve`, { json: body });
640
904
  }
641
905
  /** Kick off an embedding migration (`POST /v1/rag/collections/{name}/migrate-embeddings`). */
642
906
  async migrateRagEmbeddings(name, body) {
643
- return await this.requestJson("POST", `/v1/rag/collections/${encodeURIComponent(name)}/migrate-embeddings`, { json: body });
907
+ return await this.requestJson("POST", `/v1/rag/collections/${encodePathSegment(name)}/migrate-embeddings`, { json: body });
644
908
  }
645
909
  /** Poll an embedding-migration job (`GET .../migrate-embeddings/{jobId}`). */
646
910
  async getRagMigrationJob(name, jobId) {
647
- const path = `/v1/rag/collections/${encodeURIComponent(name)}/migrate-embeddings/${encodeURIComponent(jobId)}`;
911
+ const path = `/v1/rag/collections/${encodePathSegment(name)}/migrate-embeddings/${encodePathSegment(jobId)}`;
648
912
  return await this.requestJson("GET", path);
649
913
  }
650
914
  /** Fetch a RAG job's status (`GET /v1/rag/jobs/{jobId}`). */
651
915
  async getRagJob(jobId) {
652
- return await this.requestJson("GET", `/v1/rag/jobs/${encodeURIComponent(jobId)}`);
916
+ return await this.requestJson("GET", `/v1/rag/jobs/${encodePathSegment(jobId)}`);
653
917
  }
654
918
  /** List the project's saved presets (`GET /v1/saved_presets`, `/v1/saved-presets` on Pro). */
655
919
  async listSavedPresets(params = {}) {
@@ -751,12 +1015,12 @@ var XbergClient = class {
751
1015
  /** Pro only: fetch a project's RAG config (`GET /v1/projects/{projectId}/rag-config`). */
752
1016
  async getRagConfig(projectId) {
753
1017
  await this.requireTier("pro", "getRagConfig");
754
- return this.requestJson("GET", `/v1/projects/${encodeURIComponent(projectId)}/rag-config`);
1018
+ return this.requestJson("GET", `/v1/projects/${encodePathSegment(projectId)}/rag-config`);
755
1019
  }
756
1020
  /** Pro only: update a project's RAG config (`PUT /v1/projects/{projectId}/rag-config`). */
757
1021
  async setRagConfig(projectId, body) {
758
1022
  await this.requireTier("pro", "setRagConfig");
759
- return this.requestJson("PUT", `/v1/projects/${encodeURIComponent(projectId)}/rag-config`, { json: body });
1023
+ return this.requestJson("PUT", `/v1/projects/${encodePathSegment(projectId)}/rag-config`, { json: body });
760
1024
  }
761
1025
  /** Pro only: list the caller's projects (`GET /v1/projects`). */
762
1026
  async listProjects(params = {}) {
@@ -787,7 +1051,7 @@ var XbergClient = class {
787
1051
  /** Pro only: revoke an API key (`DELETE /v1/projects/{projectId}/api-keys/{keyId}`). */
788
1052
  async revokeApiKey(projectId, keyId) {
789
1053
  await this.requireTier("pro", "revokeApiKey");
790
- await this.requestJson("DELETE", `${this.projectPath(projectId)}/api-keys/${encodeURIComponent(keyId)}`);
1054
+ await this.requestJson("DELETE", `${this.projectPath(projectId)}/api-keys/${encodePathSegment(keyId)}`);
791
1055
  }
792
1056
  /** Pro only: list a project's integrations (`GET /v1/projects/{projectId}/integrations`). */
793
1057
  async listIntegrations(projectId, params = {}) {
@@ -841,7 +1105,7 @@ var XbergClient = class {
841
1105
  */
842
1106
  async fetchIntegrationDocument(projectId, integrationId, documentId) {
843
1107
  await this.requireTier("pro", "fetchIntegrationDocument");
844
- const path = `${this.integrationPath(projectId, integrationId)}/documents/${encodeURIComponent(documentId)}`;
1108
+ const path = `${this.integrationPath(projectId, integrationId)}/documents/${encodePathSegment(documentId)}`;
845
1109
  return this.requestBytes("GET", path);
846
1110
  }
847
1111
  /**
@@ -891,7 +1155,7 @@ var XbergClient = class {
891
1155
  */
892
1156
  async getDiffJob(documentId, diffJobId) {
893
1157
  await this.requireTier("enterprise", "getDiffJob");
894
- const path = `${this.documentPath(documentId)}/diff/${encodeURIComponent(diffJobId)}`;
1158
+ const path = `${this.documentPath(documentId)}/diff/${encodePathSegment(diffJobId)}`;
895
1159
  const { status, body } = await this.requestJsonWithStatus("GET", path);
896
1160
  return toDiffResult(status, body);
897
1161
  }
@@ -911,7 +1175,7 @@ var XbergClient = class {
911
1175
  */
912
1176
  async getJobPage(jobId, pageNumber) {
913
1177
  await this.requireTier("enterprise", "getJobPage");
914
- const path = `${JOBS_PATH}/${encodeURIComponent(jobId)}/pages/${encodeURIComponent(String(pageNumber))}`;
1178
+ const path = `${JOBS_PATH}/${encodePathSegment(jobId)}/pages/${encodePathSegment(String(pageNumber))}`;
915
1179
  return this.requestBytes("GET", path);
916
1180
  }
917
1181
  /** Enterprise only: submit text for enrichment (`POST /v1/enrich`). */
@@ -922,7 +1186,7 @@ var XbergClient = class {
922
1186
  /** Enterprise only: fetch an enrichment job's status (`GET /v1/enrich/{jobId}`). */
923
1187
  async getEnrichStatus(jobId) {
924
1188
  await this.requireTier("enterprise", "getEnrichStatus");
925
- return this.requestJson("GET", `${ENRICH_PATH}/${encodeURIComponent(jobId)}`);
1189
+ return this.requestJson("GET", `${ENRICH_PATH}/${encodePathSegment(jobId)}`);
926
1190
  }
927
1191
  /**
928
1192
  * Enterprise only: stream a crawl job's events
@@ -948,7 +1212,7 @@ var XbergClient = class {
948
1212
  * every event the caller had already handled.
949
1213
  */
950
1214
  streamCrawlEvents(crawlJobId, options = {}) {
951
- const path = `${CRAWL_JOBS_PATH}/${encodeURIComponent(crawlJobId)}/events`;
1215
+ const path = `${CRAWL_JOBS_PATH}/${encodePathSegment(crawlJobId)}/events`;
952
1216
  const open = async () => {
953
1217
  await this.requireTier("enterprise", "streamCrawlEvents");
954
1218
  return this.openEventStream(path, options.signal);
@@ -973,23 +1237,23 @@ var XbergClient = class {
973
1237
  }
974
1238
  /** Build `/v1/projects/{projectId}` with the id percent-encoded. */
975
1239
  projectPath(projectId) {
976
- return `/v1/projects/${encodeURIComponent(projectId)}`;
1240
+ return `/v1/projects/${encodePathSegment(projectId)}`;
977
1241
  }
978
1242
  /** Build `/v1/projects/{projectId}/integrations/{integrationId}`. */
979
1243
  integrationPath(projectId, integrationId) {
980
- return `${this.projectPath(projectId)}/integrations/${encodeURIComponent(integrationId)}`;
1244
+ return `${this.projectPath(projectId)}/integrations/${encodePathSegment(integrationId)}`;
981
1245
  }
982
1246
  /** Build `/v1/documents/{documentId}` with the id percent-encoded. */
983
1247
  documentPath(documentId) {
984
- return `${DOCUMENTS_PATH}/${encodeURIComponent(documentId)}`;
1248
+ return `${DOCUMENTS_PATH}/${encodePathSegment(documentId)}`;
985
1249
  }
986
1250
  /** Build `/v1/auto-tune/{id}` with the id percent-encoded. */
987
1251
  autoTunePath(autoTuneJobId) {
988
- return `${AUTO_TUNE_PATH}/${encodeURIComponent(autoTuneJobId)}`;
1252
+ return `${AUTO_TUNE_PATH}/${encodePathSegment(autoTuneJobId)}`;
989
1253
  }
990
1254
  /** Build `/v1/tuning-profiles/{id}` with the id percent-encoded. */
991
1255
  tuningProfilePath(profileId) {
992
- return `${TUNING_PROFILES_PATH}/${encodeURIComponent(profileId)}`;
1256
+ return `${TUNING_PROFILES_PATH}/${encodePathSegment(profileId)}`;
993
1257
  }
994
1258
  /**
995
1259
  * Resolve the tier and render the saved-preset path in that tier's spelling:
@@ -998,7 +1262,7 @@ var XbergClient = class {
998
1262
  */
999
1263
  async savedPresetsPath(presetId) {
1000
1264
  const base = await this.resolveTier() === "pro" ? SAVED_PRESETS_PATH_PRO : SAVED_PRESETS_PATH_ENTERPRISE;
1001
- return presetId === void 0 ? base : `${base}/${encodeURIComponent(presetId)}`;
1265
+ return presetId === void 0 ? base : `${base}/${encodePathSegment(presetId)}`;
1002
1266
  }
1003
1267
  /**
1004
1268
  * Return the effective tier — an explicit `target` if set, else probed from
@@ -1042,6 +1306,28 @@ var XbergClient = class {
1042
1306
  body: null
1043
1307
  });
1044
1308
  }
1309
+ backendRequest(method, path, init = {}) {
1310
+ return this.requestJson(method, path, {
1311
+ ...init,
1312
+ controlPlane: true
1313
+ });
1314
+ }
1315
+ backendHeaders(init) {
1316
+ const headers = new Headers({
1317
+ ...this.headers,
1318
+ ...init.headers
1319
+ });
1320
+ for (const name of [
1321
+ "authorization",
1322
+ "proxy-authorization",
1323
+ "cookie",
1324
+ "x-api-key"
1325
+ ]) headers.delete(name);
1326
+ const token = init.backendPublic ? init.sandboxToken : this.controlPlaneToken;
1327
+ if (token !== void 0 && token.length > 0) headers.set("Authorization", `Bearer ${token}`);
1328
+ if (init.body instanceof FormData || init.json !== void 0) headers.delete("content-type");
1329
+ return Object.fromEntries(headers);
1330
+ }
1045
1331
  /** Issue a request, raise on non-2xx, and decode the JSON body (undefined for empty bodies). */
1046
1332
  async requestJson(method, path, init = {}) {
1047
1333
  const { body } = await this.requestJsonWithStatus(method, path, init);
@@ -1116,26 +1402,38 @@ var XbergClient = class {
1116
1402
  * handling. Returns the raw (2xx) {@link Response}; non-2xx responses are
1117
1403
  * mapped to a thrown {@link XbergError} subclass.
1118
1404
  */
1405
+ prepareRequest(method, init) {
1406
+ const headers = init.controlPlane ? this.backendHeaders(init) : {
1407
+ ...this.headers,
1408
+ ...init.headers
1409
+ };
1410
+ let body = init.body;
1411
+ if (init.json !== void 0) {
1412
+ headers["Content-Type"] = "application/json";
1413
+ body = JSON.stringify(init.json);
1414
+ }
1415
+ const requestInit = {
1416
+ method,
1417
+ headers,
1418
+ signal: AbortSignal.timeout(this.timeoutMs),
1419
+ ...init.controlPlane ? {
1420
+ credentials: "omit",
1421
+ redirect: "manual"
1422
+ } : {}
1423
+ };
1424
+ if (body !== void 0) requestInit.body = body;
1425
+ return requestInit;
1426
+ }
1119
1427
  async requestWithRetry(method, path, init = {}) {
1120
- const url = `${this.baseUrl}${path}${buildQueryString(init.params)}`;
1428
+ if (init.controlPlane && (this.target ?? this.probedTier) === "pro") throw new XbergError("Enterprise backend methods are not available on the 'pro' tier", {
1429
+ status: 0,
1430
+ body: null
1431
+ });
1432
+ const url = `${init.controlPlane ? this.controlPlaneBaseUrl : this.baseUrl}${path}${buildQueryString(init.params)}`;
1121
1433
  let attempt = 0;
1122
1434
  let interval = DEFAULT_RETRY_BACKOFF_BASE_MS;
1123
1435
  for (;;) {
1124
- const headers = {
1125
- ...this.headers,
1126
- ...init.headers
1127
- };
1128
- let body = init.body;
1129
- if (init.json !== void 0) {
1130
- headers["Content-Type"] = "application/json";
1131
- body = JSON.stringify(init.json);
1132
- }
1133
- const requestInit = {
1134
- method,
1135
- headers,
1136
- signal: AbortSignal.timeout(this.timeoutMs)
1137
- };
1138
- if (body !== void 0) requestInit.body = body;
1436
+ const requestInit = this.prepareRequest(method, init);
1139
1437
  let response;
1140
1438
  try {
1141
1439
  response = await this.fetchImpl(url, requestInit);
@@ -1146,13 +1444,17 @@ var XbergClient = class {
1146
1444
  interval = nextBackoffInterval(interval, this.retryBackoff);
1147
1445
  continue;
1148
1446
  }
1447
+ if (init.controlPlane) throw new XbergError(`Network error contacting Enterprise control plane (${method} ${path})`, {
1448
+ status: 0,
1449
+ body: null
1450
+ });
1149
1451
  throw new XbergError(`Network error contacting ${url}`, {
1150
1452
  status: 0,
1151
1453
  body: null,
1152
1454
  cause
1153
1455
  });
1154
1456
  }
1155
- if (response.ok) return response;
1457
+ if (response.ok || init.acceptRedirect && response.status === 303) return response;
1156
1458
  if (this.retryOn.includes(response.status) && attempt < this.retries) {
1157
1459
  attempt += 1;
1158
1460
  const retryAfter = parseRetryAfterHeader(response.headers.get("retry-after"));
@@ -1297,6 +1599,50 @@ function createClient(options = {}) {
1297
1599
  ...options.fetch !== void 0 ? { fetch: options.fetch } : {}
1298
1600
  });
1299
1601
  }
1602
+ function sandboxForm(params) {
1603
+ if (params.file === void 0 && !(params.mode === "web" && params.url !== void 0 && params.url.length > 0)) throw new XbergError("Sandbox extraction requires a file or web mode with a URL", {
1604
+ status: 400,
1605
+ body: null
1606
+ });
1607
+ const form = new FormData();
1608
+ if (params.file !== void 0) {
1609
+ const { blob, filename } = toBlob(params.file);
1610
+ form.append("file", blob, filename);
1611
+ }
1612
+ for (const name of [
1613
+ "mode",
1614
+ "preset",
1615
+ "url"
1616
+ ]) {
1617
+ const value = params[name];
1618
+ if (value !== void 0) form.append(name, value);
1619
+ }
1620
+ return form;
1621
+ }
1622
+ function prepareDocumentLineage(filenames, ids) {
1623
+ const fields = /* @__PURE__ */ new Map();
1624
+ if (ids === void 0) return fields;
1625
+ if (ids.length !== filenames.length) throw new XbergError("documentIds must contain one entry per file", {
1626
+ status: 400,
1627
+ body: null
1628
+ });
1629
+ const seen = /* @__PURE__ */ new Map();
1630
+ for (const [index, filename] of filenames.entries()) {
1631
+ const id = ids[index];
1632
+ if (id !== null && (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))) throw new XbergError("documentIds must contain UUID strings or null", {
1633
+ status: 400,
1634
+ body: null
1635
+ });
1636
+ const canonical = id === null ? null : id.toLowerCase();
1637
+ if (seen.has(filename) && seen.get(filename) !== canonical) throw new XbergError("Conflicting document IDs for the same filename", {
1638
+ status: 400,
1639
+ body: null
1640
+ });
1641
+ seen.set(filename, canonical);
1642
+ if (canonical !== null) fields.set(filename, canonical);
1643
+ }
1644
+ return fields;
1645
+ }
1300
1646
 
1301
1647
  //#endregion
1302
1648
  export { AuthError, NotFoundError, RateLimitError, SUCCESS_JOB_STATUSES, ServerError, TERMINAL_JOB_STATUSES, TimeoutError, ValidationError, XbergClient, XbergError, createClient };