@spreadspace/embed 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,682 @@
1
+ import { C as CursorPaginated, R as RequestOptions, v as verifyWebhookSignature, a as verifyAndParseWebhook } from './webhooks-D6PW9fcE.cjs';
2
+ export { D as DocumentFailedPayload, b as DocumentProcessedPayload, E as ExtractionReadyPayload, J as JobCompletedPayload, L as LoanClassifiedPayload, V as VerifyAndParseResult, c as VerifyOptions, W as WebhookEvent, d as WebhookEventType, e as WebhookSignatureError } from './webhooks-D6PW9fcE.cjs';
3
+
4
+ /**
5
+ * Public error hierarchy for the SpreadSpace SDK.
6
+ *
7
+ * Any non-2xx response from the API is thrown as an instance of one of the
8
+ * subclasses below so integrators can pattern-match on the error type without
9
+ * parsing response bodies. The shape mirrors the canonical
10
+ * `ApiErrorResponse` envelope:
11
+ *
12
+ * { error: { type, message, request_id, details? } }
13
+ *
14
+ * `request_id` is preserved on every thrown error so customers can quote it
15
+ * in support tickets.
16
+ */
17
+ interface SpreadSpaceErrorParams {
18
+ type: string;
19
+ message: string;
20
+ statusCode: number;
21
+ requestId?: string;
22
+ rawBody?: unknown;
23
+ details?: Record<string, string>;
24
+ }
25
+ /**
26
+ * Base class for every error thrown by the SDK in response to a non-2xx
27
+ * API response. Network-layer failures (DNS, TCP reset, fetch abort) are
28
+ * surfaced as `NetworkError`.
29
+ */
30
+ declare class SpreadSpaceError extends Error {
31
+ /**
32
+ * The canonical `error.type` string from the API envelope, e.g.
33
+ * `invalid_request`, `rate_limited`, `idempotency_request_mismatch`.
34
+ * Stable across versions — clients pattern-match on this.
35
+ */
36
+ readonly type: string;
37
+ /** HTTP status code. */
38
+ readonly statusCode: number;
39
+ /** `X-Request-ID` echoed from the server. Quote in support tickets. */
40
+ readonly requestId?: string;
41
+ /** Raw response body for debugging. May be the parsed JSON or a string. */
42
+ readonly rawBody?: unknown;
43
+ /** Optional structured details (e.g. `borrower_id` on `pii_claim_required`). */
44
+ readonly details?: Record<string, string>;
45
+ constructor(params: SpreadSpaceErrorParams);
46
+ }
47
+ /** 400 Bad Request — typically schema validation. */
48
+ declare class InvalidRequestError extends SpreadSpaceError {
49
+ }
50
+ /** 401 Unauthorized — missing, expired, or invalid API key. */
51
+ declare class AuthenticationError extends SpreadSpaceError {
52
+ }
53
+ /**
54
+ * 403 Forbidden — caller is authenticated but lacks permission. Includes
55
+ * the PII-claim-required and business-email-required cases.
56
+ */
57
+ declare class PermissionError extends SpreadSpaceError {
58
+ }
59
+ /** 404 Not Found. */
60
+ declare class NotFoundError extends SpreadSpaceError {
61
+ }
62
+ /**
63
+ * 409 Conflict — typically `idempotency_request_mismatch` (same key, different
64
+ * body) or a domain-specific conflict (duplicate resource).
65
+ */
66
+ declare class ConflictError extends SpreadSpaceError {
67
+ }
68
+ /**
69
+ * 429 Too Many Requests. The SDK retries automatically up to `maxRetries`,
70
+ * honoring `Retry-After`; this error is only thrown when retries are
71
+ * exhausted.
72
+ */
73
+ declare class RateLimitError extends SpreadSpaceError {
74
+ }
75
+ /**
76
+ * 5xx Server Error. Retries are exhausted by the time this surfaces.
77
+ */
78
+ declare class ServerError extends SpreadSpaceError {
79
+ }
80
+ /**
81
+ * Transport-level failure — DNS, TCP reset, fetch abort, JSON parse failure
82
+ * on a 2xx response. Distinct from API-shaped errors so integrators can
83
+ * decide to retry differently.
84
+ */
85
+ declare class NetworkError extends Error {
86
+ readonly cause?: unknown;
87
+ constructor(message: string, cause?: unknown);
88
+ }
89
+
90
+ /**
91
+ * Pager handed back from resource `.list()` methods. Three ways to consume:
92
+ *
93
+ * 1. **`for await`** — iterate every item across all pages. The most common.
94
+ *
95
+ * for await (const loan of client.loans.list()) { ... }
96
+ *
97
+ * 2. **`.toArray()`** — eagerly drain into a single array. Convenient for
98
+ * small result sets; avoid for unbounded queries (the entire result
99
+ * must fit in memory).
100
+ *
101
+ * const loans = await client.loans.list().toArray();
102
+ *
103
+ * 3. **`for await ... of pager.pages()`** — iterate page-at-a-time, one
104
+ * network round-trip per loop body. Useful when the integrator wants to
105
+ * batch-process results (e.g. write a chunk to a DB, then continue).
106
+ *
107
+ * for await (const page of client.loans.list().pages()) { ... }
108
+ */
109
+ interface AsyncPager<T> extends AsyncIterableIterator<T> {
110
+ /**
111
+ * Eagerly consume every page and return all items as a single array.
112
+ * Throws if any underlying request fails.
113
+ */
114
+ toArray(): Promise<T[]>;
115
+ /**
116
+ * Page-by-page async iterator. Each yielded value is a
117
+ * `CursorPaginated<T>` envelope — useful when you want to control
118
+ * batch-size flow rather than per-item flow.
119
+ */
120
+ pages(): AsyncIterableIterator<CursorPaginated<T>>;
121
+ }
122
+
123
+ /**
124
+ * Resource facade for `/api/borrowers`. Includes both the standard CRUD
125
+ * verbs and the borrower-specific flows that don't fit `update()` —
126
+ * `claim()` (PII-claim flow, SOC 2 / GLBA) and `grantAudit()` (audit
127
+ * delegation).
128
+ */
129
+ declare class BorrowersResource {
130
+ private readonly client;
131
+ constructor(client: SpreadSpaceClient);
132
+ /**
133
+ * Retrieve a borrower by id.
134
+ *
135
+ * GET /api/borrowers/{id}
136
+ */
137
+ retrieve<T = unknown>(borrowerId: string, options?: RequestOptions): Promise<T>;
138
+ /**
139
+ * Create a new borrower.
140
+ *
141
+ * POST /api/borrowers
142
+ */
143
+ create<T = unknown>(params: Record<string, unknown>, options?: RequestOptions): Promise<T>;
144
+ /**
145
+ * Iterate every borrower visible to the calling principal.
146
+ *
147
+ * GET /api/borrowers
148
+ */
149
+ list<T = unknown>(params?: {
150
+ limit?: number;
151
+ cursor?: string;
152
+ }, options?: RequestOptions): AsyncPager<T>;
153
+ /**
154
+ * Assign a lender to this borrower.
155
+ *
156
+ * POST /api/borrowers/{id}/assign
157
+ */
158
+ assign<T = unknown>(borrowerId: string, params: Record<string, unknown>, options?: RequestOptions): Promise<T>;
159
+ /**
160
+ * Claim PII access on a borrower. Required by SOC 2 / GLBA before an
161
+ * admin can view the borrower's extracted financials. Surfaced as a verb
162
+ * method (rather than `update()`) because the audit log records this as
163
+ * a distinct event and integrators reading the SDK want to see the flow
164
+ * by name.
165
+ *
166
+ * POST /api/borrowers/{id}/claim
167
+ */
168
+ claim<T = unknown>(borrowerId: string, params: Record<string, unknown>, options?: RequestOptions): Promise<T>;
169
+ /**
170
+ * Fetch the audit log for a borrower (PII access events, claim grants,
171
+ * etc.).
172
+ *
173
+ * GET /api/borrowers/{id}/audit-log
174
+ */
175
+ auditLog<T = unknown>(borrowerId: string, options?: RequestOptions): Promise<T>;
176
+ /**
177
+ * List loans associated with a borrower.
178
+ *
179
+ * GET /api/borrowers/{borrowerId}/loans
180
+ */
181
+ loans<T = unknown>(borrowerId: string, params?: {
182
+ limit?: number;
183
+ cursor?: string;
184
+ }, options?: RequestOptions): AsyncPager<T>;
185
+ /**
186
+ * List jobs (document packages) for a borrower.
187
+ *
188
+ * GET /api/borrowers/{id}/jobs
189
+ */
190
+ jobs<T = unknown>(borrowerId: string, params?: {
191
+ limit?: number;
192
+ cursor?: string;
193
+ }, options?: RequestOptions): AsyncPager<T>;
194
+ /**
195
+ * Fetch results for a specific job under a borrower.
196
+ *
197
+ * GET /api/borrowers/{id}/jobs/{jobId}/results
198
+ */
199
+ jobResults<T = unknown>(borrowerId: string, jobId: string, options?: RequestOptions): Promise<T>;
200
+ }
201
+
202
+ /**
203
+ * Resource facade for the document upload pipeline. Documents flow:
204
+ *
205
+ * 1. `presignedUrl()` to get a signed S3 PUT URL
206
+ * 2. The integrator's backend uploads bytes directly to S3
207
+ * 3. `confirmUpload()` to kick off the extraction pipeline
208
+ * 4. Webhook `extraction.ready` fires when results are queryable
209
+ *
210
+ * No `update()` — once uploaded, document content is immutable; metadata
211
+ * lives on the parent borrower / loan / job.
212
+ */
213
+ declare class DocumentsResource {
214
+ private readonly client;
215
+ constructor(client: SpreadSpaceClient);
216
+ /**
217
+ * Request a presigned S3 PUT URL for a single document upload.
218
+ *
219
+ * POST /api/documents/presigned-url
220
+ */
221
+ presignedUrl<T = unknown>(params: Record<string, unknown>, options?: RequestOptions): Promise<T>;
222
+ /**
223
+ * Confirm a single uploaded document, kicking off the extraction
224
+ * pipeline.
225
+ *
226
+ * POST /api/documents/{jobId}/confirm-upload
227
+ */
228
+ confirmUpload<T = unknown>(jobId: string, params?: Record<string, unknown>, options?: RequestOptions): Promise<T>;
229
+ /**
230
+ * Confirm a batch of uploaded documents in a single request. Faster than
231
+ * looping `confirmUpload()` when the integrator has many files in one
232
+ * package.
233
+ *
234
+ * POST /api/documents/confirm-uploads
235
+ */
236
+ batchConfirm<T = unknown>(params: Record<string, unknown>, options?: RequestOptions): Promise<T>;
237
+ /**
238
+ * Get a presigned S3 GET URL to download a previously-uploaded document.
239
+ *
240
+ * GET /api/documents/{jobId}/download-url
241
+ */
242
+ downloadUrl<T = unknown>(jobId: string, options?: RequestOptions): Promise<T>;
243
+ /**
244
+ * Fetch processing status for a document upload.
245
+ *
246
+ * GET /api/documents/{jobId}/status
247
+ */
248
+ status<T = unknown>(jobId: string, options?: RequestOptions): Promise<T>;
249
+ }
250
+
251
+ /**
252
+ * Resource facade for embed sessions — short-lived tokens scoped to a
253
+ * single loan. Mint server-side via the integrator's API key, then pass
254
+ * the resulting `embed_token` to the browser to bootstrap the SpreadSpace
255
+ * review widget.
256
+ *
257
+ * Sub-namespace structure (`embed.sessions.create(...)`) mirrors the route
258
+ * shape (`/api/embed/sessions`) and leaves room for future embed
259
+ * resources without crowding the top-level `embed` object.
260
+ */
261
+ declare class EmbedSessionsResource {
262
+ private readonly client;
263
+ constructor(client: SpreadSpaceClient);
264
+ /**
265
+ * Mint an embed-session token for a loan. The minted token has a strict
266
+ * subset of the calling API key's scopes and is locked to the supplied
267
+ * `loan_id` — it cannot be used to access other loans or to mint further
268
+ * tokens.
269
+ *
270
+ * POST /api/embed/sessions
271
+ *
272
+ * Body: { loan_id, scopes?, expires_in_seconds? }
273
+ * Returns: { embed_token, expires_at, ... }
274
+ */
275
+ create<T = unknown>(params: Record<string, unknown>, options?: RequestOptions): Promise<T>;
276
+ /**
277
+ * Revoke an embed session early — useful when the integrator's UI flow
278
+ * ends before the natural expiry, or when reissuing after a logout.
279
+ *
280
+ * DELETE /api/embed/sessions/{sessionId}
281
+ */
282
+ revoke<T = unknown>(sessionId: string, options?: RequestOptions): Promise<T>;
283
+ }
284
+ /**
285
+ * Top-level `client.embed` namespace. Currently surfaces only the
286
+ * `sessions` sub-resource; future phases (e.g. embed-only audit logs)
287
+ * land here.
288
+ */
289
+ declare class EmbedResource {
290
+ readonly sessions: EmbedSessionsResource;
291
+ constructor(client: SpreadSpaceClient);
292
+ }
293
+
294
+ /**
295
+ * Resource facade for extracted document data. Extractions are scoped under
296
+ * a borrower (the canonical PII boundary) — every endpoint takes a
297
+ * `borrowerId` path segment so the multi-tenant access checks have an
298
+ * unambiguous scope.
299
+ *
300
+ * Per-document-type endpoints (`balanceSheet`, `pl`, etc.) return
301
+ * roll-ups across all documents of that type uploaded for the borrower.
302
+ * The generic `query()` is the structured-search endpoint —
303
+ * integrators that build their own UIs on top of the extraction data
304
+ * typically want this one.
305
+ *
306
+ * `move()` reassigns a document's loan binding — shipped as a verb method
307
+ * (not `update()`) because it traverses the loan-membership tables, not
308
+ * the extraction row.
309
+ */
310
+ declare class ExtractionsResource {
311
+ private readonly client;
312
+ constructor(client: SpreadSpaceClient);
313
+ /**
314
+ * Iterate every extraction for a borrower.
315
+ *
316
+ * GET /api/borrowers/{borrowerId}/extractions
317
+ */
318
+ list<T = unknown>(borrowerId: string, params?: {
319
+ limit?: number;
320
+ cursor?: string;
321
+ }, options?: RequestOptions): AsyncPager<T>;
322
+ /**
323
+ * Structured query across a borrower's extractions. Filter by document
324
+ * type, period, and other metadata.
325
+ *
326
+ * POST /api/borrowers/{borrowerId}/extractions/query
327
+ */
328
+ query<T = unknown>(borrowerId: string, params: Record<string, unknown>, options?: RequestOptions): Promise<T>;
329
+ /**
330
+ * Move an extracted document to a different loan under the same
331
+ * borrower. Use when the user uploaded a doc to the wrong package.
332
+ *
333
+ * POST /api/borrowers/{borrowerId}/extractions/{docId}/move
334
+ */
335
+ move<T = unknown>(borrowerId: string, docId: string, params: Record<string, unknown>, options?: RequestOptions): Promise<T>;
336
+ /**
337
+ * Roll-up of the borrower's bank-statement analyses across all
338
+ * uploaded statements.
339
+ *
340
+ * GET /api/borrowers/{borrowerId}/extractions/bank-statement-analysis
341
+ */
342
+ bankStatementAnalysis<T = unknown>(borrowerId: string, options?: RequestOptions): Promise<T>;
343
+ /**
344
+ * Roll-up of the borrower's balance sheet across all uploaded
345
+ * balance-sheet documents.
346
+ */
347
+ balanceSheet<T = unknown>(borrowerId: string, options?: RequestOptions): Promise<T>;
348
+ /** P&L roll-up across uploaded P&L documents. */
349
+ pl<T = unknown>(borrowerId: string, options?: RequestOptions): Promise<T>;
350
+ /** Cash-flow roll-up. */
351
+ cashFlow<T = unknown>(borrowerId: string, options?: RequestOptions): Promise<T>;
352
+ /** Accounts payable roll-up. */
353
+ accountsPayable<T = unknown>(borrowerId: string, options?: RequestOptions): Promise<T>;
354
+ /** Accounts receivable roll-up. */
355
+ accountsReceivable<T = unknown>(borrowerId: string, options?: RequestOptions): Promise<T>;
356
+ /**
357
+ * Generic report endpoint — pass the report type as a path segment.
358
+ * Useful for report types added after this SDK release.
359
+ *
360
+ * GET /api/borrowers/{borrowerId}/extractions/reports/{reportType}
361
+ */
362
+ report<T = unknown>(borrowerId: string, reportType: string, options?: RequestOptions): Promise<T>;
363
+ }
364
+
365
+ /**
366
+ * Resource facade for `/api/jobs`. A "job" is a document package — a
367
+ * batch of files uploaded together. Read-only from this surface; jobs
368
+ * are created implicitly by the upload pipeline.
369
+ */
370
+ declare class JobsResource {
371
+ private readonly client;
372
+ constructor(client: SpreadSpaceClient);
373
+ /**
374
+ * Iterate jobs visible to the calling principal.
375
+ *
376
+ * GET /api/jobs
377
+ */
378
+ list<T = unknown>(params?: {
379
+ limit?: number;
380
+ cursor?: string;
381
+ }, options?: RequestOptions): AsyncPager<T>;
382
+ /**
383
+ * Fetch processing status for a job.
384
+ *
385
+ * GET /api/jobs/{jobId}/status
386
+ */
387
+ status<T = unknown>(jobId: string, options?: RequestOptions): Promise<T>;
388
+ /**
389
+ * Fetch results for a job — the rolled-up extraction outcomes.
390
+ *
391
+ * GET /api/jobs/{jobId}/results
392
+ */
393
+ results<T = unknown>(jobId: string, options?: RequestOptions): Promise<T>;
394
+ }
395
+
396
+ /**
397
+ * Resource facade for `/api/loans`. Loans are the top-level package unit —
398
+ * a borrower has many loans, each loan is the scope of a documents bundle.
399
+ */
400
+ declare class LoansResource {
401
+ private readonly client;
402
+ constructor(client: SpreadSpaceClient);
403
+ /**
404
+ * Retrieve a loan by id.
405
+ *
406
+ * GET /api/loans/{loanId}
407
+ */
408
+ retrieve<T = unknown>(loanId: string, options?: RequestOptions): Promise<T>;
409
+ /**
410
+ * Create a new loan.
411
+ *
412
+ * POST /api/loans
413
+ */
414
+ create<T = unknown>(params: Record<string, unknown>, options?: RequestOptions): Promise<T>;
415
+ /**
416
+ * Update an existing loan.
417
+ *
418
+ * PATCH /api/loans/{loanId}
419
+ */
420
+ update<T = unknown>(loanId: string, params: Record<string, unknown>, options?: RequestOptions): Promise<T>;
421
+ /**
422
+ * Iterate every loan visible to the calling principal. Returns an
423
+ * `AsyncPager<T>` — consume with `for await`, `.toArray()`, or
424
+ * `.pages()`.
425
+ *
426
+ * GET /api/loans
427
+ */
428
+ list<T = unknown>(params?: {
429
+ limit?: number;
430
+ cursor?: string;
431
+ borrower_id?: string;
432
+ }, options?: RequestOptions): AsyncPager<T>;
433
+ /**
434
+ * Assign a lender to this loan. Calls `POST /api/loans/{id}/assign`.
435
+ * Surfaced as a verb method rather than forcing it through `update()`
436
+ * because the assignment flow is semantically distinct from a generic
437
+ * field patch (it touches the lender-access table, not the loan row).
438
+ */
439
+ assign<T = unknown>(loanId: string, params: Record<string, unknown>, options?: RequestOptions): Promise<T>;
440
+ /**
441
+ * Fetch the audit log for a loan.
442
+ *
443
+ * GET /api/loans/{loanId}/audit-log
444
+ */
445
+ auditLog<T = unknown>(loanId: string, options?: RequestOptions): Promise<T>;
446
+ }
447
+
448
+ /**
449
+ * Resource facade for webhook endpoints (`/api/webhooks/*`) plus the
450
+ * webhook signature helpers as static methods for discoverability.
451
+ *
452
+ * The verification helpers are also exported as bare functions from
453
+ * `@spreadspace/embed/webhooks` for tree-shakeable import paths in
454
+ * webhook receiver Lambdas (where `SpreadSpaceClient` would otherwise pull
455
+ * in the entire resource layer).
456
+ */
457
+ declare class WebhooksResource {
458
+ private readonly client;
459
+ /**
460
+ * Verify a `SpreadSpace-Signature` header against a body and signing
461
+ * secret. Throws `WebhookSignatureError` on any failure.
462
+ */
463
+ static readonly verifySignature: typeof verifyWebhookSignature;
464
+ /**
465
+ * Verify a webhook signature and JSON-parse the body into a typed
466
+ * `WebhookEvent`. Throws `WebhookSignatureError` on signature failure or
467
+ * invalid JSON.
468
+ */
469
+ static readonly verifyAndParse: typeof verifyAndParseWebhook;
470
+ constructor(client: SpreadSpaceClient);
471
+ /**
472
+ * List configured webhook endpoints for this organization.
473
+ *
474
+ * GET /api/webhooks
475
+ */
476
+ list<T = unknown>(params?: {
477
+ limit?: number;
478
+ cursor?: string;
479
+ }, options?: RequestOptions): AsyncPager<T>;
480
+ /**
481
+ * Retrieve a single webhook endpoint.
482
+ *
483
+ * GET /api/webhooks/{id}
484
+ */
485
+ retrieve<T = unknown>(endpointId: string, options?: RequestOptions): Promise<T>;
486
+ /**
487
+ * Create a new webhook endpoint. The response carries the plaintext
488
+ * signing secret exactly once — store it server-side, do not log it.
489
+ *
490
+ * POST /api/webhooks
491
+ */
492
+ create<T = unknown>(params: Record<string, unknown>, options?: RequestOptions): Promise<T>;
493
+ /**
494
+ * Update endpoint metadata (URL, subscribed event types, enabled flag).
495
+ *
496
+ * PATCH /api/webhooks/{id}
497
+ */
498
+ update<T = unknown>(endpointId: string, params: Record<string, unknown>, options?: RequestOptions): Promise<T>;
499
+ /**
500
+ * Delete a webhook endpoint.
501
+ *
502
+ * DELETE /api/webhooks/{id}
503
+ */
504
+ delete<T = unknown>(endpointId: string, options?: RequestOptions): Promise<T>;
505
+ /**
506
+ * Rotate an endpoint's signing secret. The old secret remains valid for
507
+ * a grace window so deliveries in flight aren't dropped. Returns the new
508
+ * plaintext secret exactly once.
509
+ *
510
+ * POST /api/webhooks/{id}/rotate
511
+ */
512
+ rotateSecret<T = unknown>(endpointId: string, params?: Record<string, unknown>, options?: RequestOptions): Promise<T>;
513
+ /**
514
+ * Iterate delivery attempts for an endpoint.
515
+ *
516
+ * GET /api/webhooks/{id}/deliveries
517
+ */
518
+ deliveries<T = unknown>(endpointId: string, params?: {
519
+ limit?: number;
520
+ cursor?: string;
521
+ }, options?: RequestOptions): AsyncPager<T>;
522
+ /**
523
+ * Manually replay a delivery (e.g. after fixing a downstream outage).
524
+ *
525
+ * POST /api/webhooks/{id}/deliveries/{deliveryId}/replay
526
+ */
527
+ replayDelivery<T = unknown>(endpointId: string, deliveryId: string, params?: Record<string, unknown>, options?: RequestOptions): Promise<T>;
528
+ }
529
+
530
+ interface SpreadSpaceClientOptions {
531
+ /**
532
+ * The API key for authentication. Live keys begin with `ss_live_`, test
533
+ * keys with `ss_test_`. Issue and manage keys from the SpreadSpace
534
+ * dashboard.
535
+ */
536
+ apiKey: string;
537
+ /**
538
+ * Base URL for the API. Defaults to `https://api.spreadspace.app`.
539
+ * Override for staging (`https://staging-api.spreadspace.app`) or for
540
+ * local development (`http://localhost:8080`).
541
+ */
542
+ baseUrl?: string;
543
+ /**
544
+ * Override the SDK-pinned `SpreadSpace-Version` header. Defaults to the
545
+ * version this SDK release was built against. Set this only when
546
+ * intentionally targeting a different surface version than the SDK was
547
+ * tested against.
548
+ */
549
+ apiVersion?: string;
550
+ /**
551
+ * Request timeout in milliseconds. Default: 30000 (30s). The timeout is
552
+ * applied per individual HTTP attempt — retries get a fresh window each.
553
+ */
554
+ timeout?: number;
555
+ /**
556
+ * Maximum number of retry attempts after the initial request. Default: 3.
557
+ * Retries trigger on:
558
+ * - 429 Rate Limited (honors `Retry-After` if present)
559
+ * - 5xx Server Errors
560
+ * - Transport-level network failures
561
+ * 4xx other than 429 do not retry.
562
+ */
563
+ maxRetries?: number;
564
+ /**
565
+ * Custom `fetch` implementation. Defaults to `globalThis.fetch`. Inject a
566
+ * mock here to write hermetic tests without monkey-patching the global.
567
+ */
568
+ fetch?: typeof fetch;
569
+ /**
570
+ * Custom idempotency-key generator. Defaults to `crypto.randomUUID()`.
571
+ */
572
+ idempotencyKeyGenerator?: () => string;
573
+ }
574
+ /**
575
+ * Internal options for the low-level `request()` method. Resource methods
576
+ * compose these on top of the public `RequestOptions`.
577
+ */
578
+ interface InternalRequestOptions extends RequestOptions {
579
+ /**
580
+ * JSON-serializable request body. Encoded as `application/json` with
581
+ * `Content-Type: application/json; charset=utf-8`.
582
+ */
583
+ body?: unknown;
584
+ /**
585
+ * Query parameters appended to the URL. `undefined` values are skipped.
586
+ */
587
+ query?: Record<string, string | number | boolean | undefined>;
588
+ }
589
+ /**
590
+ * Top-level entry point of the SpreadSpace SDK.
591
+ *
592
+ * Single instance per integrator process — the resources hanging off it are
593
+ * thin facades, not separate clients, so spinning up multiple
594
+ * `SpreadSpaceClient`s only matters when juggling multiple API keys.
595
+ *
596
+ * Wire-format invariants the client guarantees on every request:
597
+ * - `Authorization: Bearer <apiKey>`
598
+ * - `SpreadSpace-Version: <apiVersion>`
599
+ * - `User-Agent: spreadspace-node/<sdkVersion> node/<nodeVersion>`
600
+ * - `Idempotency-Key: <auto-generated UUID>` on every POST/PATCH/PUT/DELETE
601
+ * unless the caller supplies one explicitly or sets `idempotencyKey: null`
602
+ *
603
+ * Retries on 429, 5xx, and transport failures up to `maxRetries` times with
604
+ * exponential backoff (capped) and jitter; honors `Retry-After`.
605
+ */
606
+ declare class SpreadSpaceClient {
607
+ /** Resolved base URL (no trailing slash). */
608
+ readonly baseUrl: string;
609
+ /** Resolved API version string (the `SpreadSpace-Version` header value). */
610
+ readonly apiVersion: string;
611
+ /** Public so resource files can pull it for `paginate()` URL construction. */
612
+ readonly maxRetries: number;
613
+ readonly loans: LoansResource;
614
+ readonly borrowers: BorrowersResource;
615
+ readonly documents: DocumentsResource;
616
+ readonly extractions: ExtractionsResource;
617
+ readonly jobs: JobsResource;
618
+ readonly webhooks: WebhooksResource;
619
+ readonly embed: EmbedResource;
620
+ private readonly apiKey;
621
+ private readonly timeoutMs;
622
+ private readonly fetchImpl;
623
+ private readonly idempotencyKeyGenerator;
624
+ constructor(options: SpreadSpaceClientOptions);
625
+ /**
626
+ * Low-level request method. Resource layer wraps this with ergonomic
627
+ * method names; integrators can call it directly to hit endpoints not yet
628
+ * surfaced via a typed resource.
629
+ *
630
+ * Returns the parsed JSON body. For 204 No Content responses (currently
631
+ * none in the API but reserved), returns `undefined as T`.
632
+ */
633
+ request<T>(method: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE', path: string, options?: InternalRequestOptions): Promise<T>;
634
+ /**
635
+ * Convenience wrapper around `paginate()` for resource list methods. Lets
636
+ * each resource simply do `return this.client.paginate(...)` rather than
637
+ * importing the helper directly.
638
+ */
639
+ paginate<T>(path: string, params?: Record<string, string | number | boolean | undefined>, options?: RequestOptions): AsyncPager<T>;
640
+ private buildUrl;
641
+ private buildHeaders;
642
+ private buildUserAgent;
643
+ /**
644
+ * Compute the next retry delay. Exponential backoff with full jitter,
645
+ * floored by `Retry-After` if the server provided one (we never retry
646
+ * faster than the server asked us to).
647
+ *
648
+ * base = min(maxDelay, baseDelay * 2^attempt)
649
+ * delay = random(0, base)
650
+ *
651
+ * Full jitter (vs. equal jitter) is the AWS-recommended default — it
652
+ * minimizes thundering-herd across many concurrent retrying clients.
653
+ */
654
+ private computeRetryDelay;
655
+ private parseSuccessBody;
656
+ private buildErrorFromResponse;
657
+ }
658
+
659
+ /**
660
+ * The SDK package version. Sent on every outbound request as part of the
661
+ * `User-Agent` string so server-side telemetry can pick up which SDK release
662
+ * a customer is running.
663
+ *
664
+ * Hand-rolled rather than imported from `package.json` because tsup output
665
+ * doesn't include the package manifest — keeping it as a TS literal avoids a
666
+ * runtime `fs` read from the dist bundle.
667
+ *
668
+ * Bump in lockstep with `package.json`.
669
+ */
670
+ declare const SDK_VERSION = "0.1.0";
671
+ /**
672
+ * Default API surface version pinned by this SDK release. Sent as the
673
+ * `SpreadSpace-Version` header on every request unless the integrator
674
+ * overrides it via `SpreadSpaceClientOptions.apiVersion`.
675
+ *
676
+ * Once the SDK is published, this value is the contract: the SDK guarantees
677
+ * the request/response shapes match this dated surface. Bumping requires a
678
+ * new SDK release that codegens against the new spec.
679
+ */
680
+ declare const DEFAULT_API_VERSION = "2026-05-03";
681
+
682
+ export { type AsyncPager, AuthenticationError, BorrowersResource, ConflictError, CursorPaginated, DEFAULT_API_VERSION, DocumentsResource, EmbedResource, EmbedSessionsResource, ExtractionsResource, type InternalRequestOptions, InvalidRequestError, JobsResource, LoansResource, NetworkError, NotFoundError, PermissionError, RateLimitError, RequestOptions, SDK_VERSION, ServerError, SpreadSpaceClient, type SpreadSpaceClientOptions, SpreadSpaceError, WebhooksResource, verifyAndParseWebhook, verifyWebhookSignature };