@delegance/sdk 0.1.0 → 0.2.1

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.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  // src/types/index.ts
2
2
  import { z } from "zod";
3
- var CompanySizeSchema = z.enum(["1", "2-10", "11-25", "26-50", "51-100", "100-499", "500+"]);
3
+ var CompanySizeSchema = z.enum(["0", "1", "2-10", "11-25", "26-50", "51-100", "100-499", "500+"]);
4
4
  var CreateCompanySchema = z.object({
5
5
  name: z.string().min(1).max(255),
6
6
  legalName: z.string().max(255).optional(),
@@ -22,7 +22,7 @@ var CreateCompanySchema = z.object({
22
22
  zip: z.string().regex(/^\d{5}(-\d{4})?$/)
23
23
  }).optional(),
24
24
  externalId: z.string().max(255).optional(),
25
- metadata: z.record(z.unknown()).optional()
25
+ metadata: z.record(z.string(), z.unknown()).optional()
26
26
  });
27
27
  var DocumentTypeSchema = z.enum([
28
28
  "policy",
@@ -77,13 +77,29 @@ var RateLimitError = class extends DeleganceError {
77
77
  this.name = "RateLimitError";
78
78
  }
79
79
  };
80
+ var ForbiddenError = class extends DeleganceError {
81
+ constructor(message, traceId) {
82
+ super(message, 403, traceId);
83
+ this.name = "ForbiddenError";
84
+ }
85
+ };
86
+ var NotImplementedError = class extends DeleganceError {
87
+ constructor(message, traceId) {
88
+ super(message, 501, traceId);
89
+ this.name = "NotImplementedError";
90
+ }
91
+ };
80
92
 
81
93
  // src/utils/http.ts
82
- var SDK_VERSION = "0.1.0";
94
+ var SDK_VERSION = "0.2.1";
95
+ var DEFAULT_BASE_URL = "https://portal.delegancebrokerage.com";
96
+ function isRetryableStatus(status) {
97
+ return status >= 500 && status !== 501;
98
+ }
83
99
  var HttpClient = class {
84
100
  constructor(config) {
85
101
  this.config = {
86
- baseUrl: (config.baseUrl || "https://app.delegance.ai").replace(/\/$/, ""),
102
+ baseUrl: (config.baseUrl || DEFAULT_BASE_URL).replace(/\/$/, ""),
87
103
  apiKey: config.apiKey,
88
104
  timeout: config.timeout || 3e4,
89
105
  retries: config.retries ?? 3,
@@ -94,7 +110,8 @@ var HttpClient = class {
94
110
  const { method, path, body, headers = {}, timeout, isFormData } = options;
95
111
  const url = `${this.config.baseUrl}${path}`;
96
112
  const requestHeaders = {
97
- "Authorization": `Bearer ${this.config.apiKey}`,
113
+ // No key = an unauthenticated call (signup, the key exchange).
114
+ ...this.config.apiKey ? { "Authorization": `Bearer ${this.config.apiKey}` } : {},
98
115
  "User-Agent": `delegance-sdk/${SDK_VERSION}`,
99
116
  ...this.config.headers,
100
117
  ...headers
@@ -157,6 +174,7 @@ var HttpClient = class {
157
174
  */
158
175
  async executeWithRetry(buildRequest, timeoutMs) {
159
176
  let lastError = null;
177
+ let lastInformative = null;
160
178
  let attempts = 0;
161
179
  while (attempts <= this.config.retries) {
162
180
  const controller = new AbortController();
@@ -165,21 +183,35 @@ var HttpClient = class {
165
183
  const { url, init } = buildRequest();
166
184
  const response = await fetch(url, { ...init, signal: controller.signal });
167
185
  const data = await response.json().catch(() => ({}));
168
- const traceId = data.traceId;
186
+ const { traceId } = data;
169
187
  if (!response.ok) {
170
- throw this.handleErrorResponse(response.status, data, traceId);
188
+ const err = this.handleErrorResponse(response.status, data, traceId);
189
+ if (typeof data.reason === "string") err.reason = data.reason;
190
+ if (typeof data.code === "string") err.code = data.code;
191
+ if (data && typeof data === "object") err.body = data;
192
+ if (err instanceof RateLimitError && err.retryAfter === void 0) {
193
+ const header = Number(response.headers?.get?.("Retry-After"));
194
+ if (Number.isFinite(header) && header > 0) err.retryAfter = header;
195
+ }
196
+ throw err;
171
197
  }
172
198
  return data;
173
199
  } catch (error) {
174
200
  lastError = error;
175
- if (error instanceof AuthenticationError || error instanceof ValidationError || error instanceof NotFoundError || error instanceof RateLimitError) {
201
+ if (error instanceof DeleganceError && error.message && error.message !== "Unknown error") {
202
+ lastInformative = error;
203
+ }
204
+ if (error instanceof DeleganceError && (!isRetryableStatus(error.statusCode) || error.reason === "not_available")) {
176
205
  throw error;
177
206
  }
178
207
  if (attempts < this.config.retries) {
179
208
  attempts++;
180
- await this.delay(Math.pow(2, attempts) * 1e3);
209
+ await this.delay(2 ** attempts * 1e3);
181
210
  continue;
182
211
  }
212
+ if (error instanceof DeleganceError && error.message === "Unknown error" && lastInformative) {
213
+ throw lastInformative;
214
+ }
183
215
  throw error;
184
216
  } finally {
185
217
  clearTimeout(timeoutId);
@@ -189,12 +221,14 @@ var HttpClient = class {
189
221
  }
190
222
  handleErrorResponse(status, data, traceId) {
191
223
  const message = data.message || data.error || "Unknown error";
192
- const details = data.details;
224
+ const { details } = data;
193
225
  switch (status) {
194
226
  case 401:
195
227
  return new AuthenticationError(message, traceId);
196
228
  case 400:
197
229
  return new ValidationError(message, details, traceId);
230
+ case 403:
231
+ return new ForbiddenError(message, traceId);
198
232
  case 404:
199
233
  return new NotFoundError(message, traceId);
200
234
  case 429:
@@ -203,6 +237,8 @@ var HttpClient = class {
203
237
  data.retryAfter,
204
238
  traceId
205
239
  );
240
+ case 501:
241
+ return new NotImplementedError(message, traceId);
206
242
  default:
207
243
  return new DeleganceError(message, status, traceId, details);
208
244
  }
@@ -218,7 +254,11 @@ var CompaniesModule = class {
218
254
  this.http = http;
219
255
  }
220
256
  /**
221
- * Create a new company
257
+ * Create a new company.
258
+ *
259
+ * @deprecated A customer API key cannot create companies (403
260
+ * `tenant_key_cannot_create`). To open a new account, use
261
+ * `createSignup().createAccount()`.
222
262
  *
223
263
  * @example
224
264
  * ```typescript
@@ -247,14 +287,11 @@ var CompaniesModule = class {
247
287
  return response.company;
248
288
  }
249
289
  /**
250
- * List companies accessible to this API key
251
- *
290
+ * List the company this API key belongs to. A key belongs to one company.
291
+ *
252
292
  * @example
253
293
  * ```typescript
254
- * const companies = await client.companies.list();
255
- *
256
- * // Include companies created via this API key
257
- * const allCompanies = await client.companies.list({ includeCreated: true });
294
+ * const [company] = await client.companies.list();
258
295
  * ```
259
296
  */
260
297
  async list(options = {}) {
@@ -271,7 +308,10 @@ var CompaniesModule = class {
271
308
  return response.companies;
272
309
  }
273
310
  /**
274
- * Get a company by ID
311
+ * Get a company by ID.
312
+ *
313
+ * @deprecated The server has no `GET /api/v1/companies/{id}` route, so this
314
+ * returns 404. Use `list()`, which returns the key's own company.
275
315
  *
276
316
  * @example
277
317
  * ```typescript
@@ -286,7 +326,10 @@ var CompaniesModule = class {
286
326
  return response.company;
287
327
  }
288
328
  /**
289
- * Create a company if it doesn't exist (using externalId for deduplication)
329
+ * Create a company if it doesn't exist (using externalId for deduplication).
330
+ *
331
+ * @deprecated A customer API key cannot create companies. Use
332
+ * `createSignup().createAccount()` for a new account.
290
333
  *
291
334
  * @example
292
335
  * ```typescript
@@ -332,7 +375,6 @@ var DocumentsModule = class {
332
375
  * import fs from 'fs';
333
376
  *
334
377
  * const doc = await client.documents.upload({
335
- * companyId: 'company-uuid',
336
378
  * file: fs.readFileSync('./policy.pdf'),
337
379
  * fileName: 'GL-2025.pdf',
338
380
  * documentType: 'policy'
@@ -342,9 +384,6 @@ var DocumentsModule = class {
342
384
  * ```
343
385
  */
344
386
  async upload(input) {
345
- if (!input.companyId) {
346
- throw new ValidationError("companyId is required");
347
- }
348
387
  if (!input.file) {
349
388
  throw new ValidationError("file is required");
350
389
  }
@@ -357,9 +396,10 @@ var DocumentsModule = class {
357
396
  } else {
358
397
  fileData = input.file;
359
398
  }
360
- const additionalFields = {
361
- companyId: input.companyId
362
- };
399
+ const additionalFields = {};
400
+ if (input.companyId) {
401
+ additionalFields.companyId = input.companyId;
402
+ }
363
403
  if (input.documentType) {
364
404
  additionalFields.documentType = input.documentType;
365
405
  }
@@ -383,8 +423,8 @@ var DocumentsModule = class {
383
423
  * @example
384
424
  * ```typescript
385
425
  * const docs = await client.documents.uploadBatch([
386
- * { companyId, file: buffer1, fileName: 'policy1.pdf' },
387
- * { companyId, file: buffer2, fileName: 'policy2.pdf' }
426
+ * { file: buffer1, fileName: 'policy1.pdf' },
427
+ * { file: buffer2, fileName: 'policy2.pdf' }
388
428
  * ]);
389
429
  * ```
390
430
  */
@@ -804,6 +844,7 @@ var QuotesModule = class {
804
844
  };
805
845
 
806
846
  // src/modules/policies.ts
847
+ import { randomUUID } from "crypto";
807
848
  var PoliciesModule = class {
808
849
  constructor(http) {
809
850
  this.http = http;
@@ -868,6 +909,40 @@ var PoliciesModule = class {
868
909
  throw error;
869
910
  }
870
911
  }
912
+ /**
913
+ * Ask to cancel a policy. The request waits for the insured's signature,
914
+ * collected at `signatureUrl` by an owner or admin; a broker reviews the
915
+ * claims-made continuity check before anything reaches the carrier.
916
+ */
917
+ async requestCancellation(policyId, input, opts = {}) {
918
+ return this.http.request({
919
+ method: "POST",
920
+ path: `/api/v1/policies/${encodeURIComponent(policyId)}/cancellation`,
921
+ body: input,
922
+ headers: { "Idempotency-Key": opts.idempotencyKey ?? randomUUID() }
923
+ });
924
+ }
925
+ /**
926
+ * Sign a cancellation request as an owner or admin. Signing needs a step-up
927
+ * code: call once without `code` to email it (202 with `stepUpId`), then
928
+ * again with `stepUpId` and `code`.
929
+ */
930
+ async signCancellation(requestId, input, opts = {}) {
931
+ return this.http.request({
932
+ method: "POST",
933
+ path: `/api/v1/policy-cancellations/${encodeURIComponent(requestId)}/sign`,
934
+ body: input,
935
+ headers: { "Idempotency-Key": opts.idempotencyKey ?? randomUUID() }
936
+ });
937
+ }
938
+ /** One cancellation request's status. */
939
+ async getCancellation(requestId) {
940
+ const res = await this.http.request({
941
+ method: "GET",
942
+ path: `/api/v1/policy-cancellations/${encodeURIComponent(requestId)}`
943
+ });
944
+ return res.request;
945
+ }
871
946
  };
872
947
 
873
948
  // src/modules/coi.ts
@@ -1023,6 +1098,7 @@ var SOVModule = class {
1023
1098
  };
1024
1099
 
1025
1100
  // src/modules/api-keys.ts
1101
+ var API_KEY_SCOPES = ["read", "write", "admin", "appetite:read", "mcp:read", "mcp:orin", "claims:write"];
1026
1102
  var ApiKeysModule = class {
1027
1103
  constructor(http) {
1028
1104
  this.http = http;
@@ -1135,8 +1211,18 @@ var ApiKeysModule = class {
1135
1211
  if (idempotency?.idempotencyKey) {
1136
1212
  requestOptions.headers = { "Idempotency-Key": idempotency.idempotencyKey };
1137
1213
  }
1138
- const response = await this.http.request(requestOptions);
1139
- return response.data;
1214
+ try {
1215
+ const response = await this.http.request(requestOptions);
1216
+ return response.data;
1217
+ } catch (error) {
1218
+ if (error instanceof NotFoundError) {
1219
+ throw new NotImplementedError(
1220
+ "Server-side key rotation is not available yet. Create a replacement key with apiKeys.create() using the same scopes, then revoke the old key in the portal.",
1221
+ error.traceId
1222
+ );
1223
+ }
1224
+ throw error;
1225
+ }
1140
1226
  }
1141
1227
  };
1142
1228
 
@@ -1326,6 +1412,519 @@ var OnboardingModule = class {
1326
1412
  });
1327
1413
  return response.data;
1328
1414
  }
1415
+ /** Poll the canonical onboarding state machine. Callable pre-verification. */
1416
+ async state() {
1417
+ const response = await this.http.request({
1418
+ method: "GET",
1419
+ path: "/api/v1/onboarding/state"
1420
+ });
1421
+ return response.data;
1422
+ }
1423
+ /**
1424
+ * Issue (or re-issue) the human verification challenge. Delegance emails a
1425
+ * confirmation link to the company contact email. Hand that link to a human;
1426
+ * the agent cannot self-verify.
1427
+ */
1428
+ async requestVerification() {
1429
+ const response = await this.http.request({
1430
+ method: "POST",
1431
+ path: "/api/v1/onboarding/verification"
1432
+ });
1433
+ return { state: response.data.state, sentTo: response.data.sentTo };
1434
+ }
1435
+ /** Poll state() until `target` is reached or `timeoutMs` elapses. */
1436
+ async waitForState(target, options = {}) {
1437
+ const intervalMs = options.intervalMs ?? 5e3;
1438
+ const timeoutMs = options.timeoutMs ?? 10 * 60 * 1e3;
1439
+ if (!Number.isFinite(intervalMs) || intervalMs <= 0 || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {
1440
+ throw new ValidationError("intervalMs and timeoutMs must be positive numbers");
1441
+ }
1442
+ const deadline = Date.now() + timeoutMs;
1443
+ for (; ; ) {
1444
+ const current = await this.state();
1445
+ if (current.state === target) return current;
1446
+ if (Date.now() + intervalMs > deadline) {
1447
+ throw new Error(
1448
+ `waitForState('${target}') timed out after ${timeoutMs}ms (last state: ${current.state})`
1449
+ );
1450
+ }
1451
+ await new Promise((r) => setTimeout(r, intervalMs));
1452
+ }
1453
+ }
1454
+ };
1455
+
1456
+ // src/modules/appetite.ts
1457
+ function withoutEnvelope(response) {
1458
+ const copy = { ...response };
1459
+ delete copy.success;
1460
+ return copy;
1461
+ }
1462
+ var AppetiteModule = class {
1463
+ constructor(http) {
1464
+ this.http = http;
1465
+ }
1466
+ /**
1467
+ * Start an appetite match. Returns the result directly on a warm cache hit,
1468
+ * or a queued job to poll with `getMatch()`.
1469
+ *
1470
+ * @example
1471
+ * ```typescript
1472
+ * const start = await client.appetite.match({ state: 'CA', industry: 'restaurant' });
1473
+ * const result = start.status === 'succeeded'
1474
+ * ? start
1475
+ * : await client.appetite.waitForMatch(start.jobId);
1476
+ * ```
1477
+ */
1478
+ async match(input) {
1479
+ if (!input.state || input.state.trim().length !== 2) {
1480
+ throw new ValidationError("state must be a two-letter code");
1481
+ }
1482
+ if (!input.industry && !input.businessDescription && !input.naicsCode && !input.sicCode) {
1483
+ throw new ValidationError("One of industry, businessDescription, naicsCode, or sicCode is required");
1484
+ }
1485
+ const response = await this.http.request({
1486
+ method: "POST",
1487
+ path: "/api/v1/appetite/match",
1488
+ body: input
1489
+ });
1490
+ if (typeof response.jobId === "string" && typeof response.statusUrl === "string") {
1491
+ return {
1492
+ status: "queued",
1493
+ jobId: response.jobId,
1494
+ statusUrl: response.statusUrl,
1495
+ estimatedSeconds: response.estimatedSeconds ?? 20,
1496
+ traceId: response.traceId
1497
+ };
1498
+ }
1499
+ return {
1500
+ ...withoutEnvelope(response),
1501
+ status: "succeeded",
1502
+ cached: true,
1503
+ jobId: null,
1504
+ traceId: response.traceId
1505
+ };
1506
+ }
1507
+ /** Read a match job. Unknown, expired, and other-tenant ids all raise NotFoundError. */
1508
+ async getMatch(jobId) {
1509
+ const response = await this.http.request({
1510
+ method: "GET",
1511
+ path: `/api/v1/appetite/match/${encodeURIComponent(jobId)}`
1512
+ });
1513
+ return withoutEnvelope(response);
1514
+ }
1515
+ /**
1516
+ * Poll a job until it succeeds. Throws on a failed job (with the sanitized
1517
+ * errorCode) or on timeout.
1518
+ */
1519
+ async waitForMatch(jobId, options = {}) {
1520
+ const intervalMs = options.intervalMs ?? 3e3;
1521
+ const timeoutMs = options.timeoutMs ?? 2 * 60 * 1e3;
1522
+ if (!Number.isFinite(intervalMs) || intervalMs <= 0 || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {
1523
+ throw new ValidationError("intervalMs and timeoutMs must be positive numbers");
1524
+ }
1525
+ const deadline = Date.now() + timeoutMs;
1526
+ for (; ; ) {
1527
+ const job = await this.getMatch(jobId);
1528
+ if (job.status === "succeeded") return job;
1529
+ if (job.status === "failed") {
1530
+ throw new DeleganceError(
1531
+ `Appetite match failed: ${job.errorCode}${job.retryable ? " (retryable)" : ""}`,
1532
+ 500,
1533
+ job.traceId
1534
+ );
1535
+ }
1536
+ if (Date.now() + intervalMs > deadline) {
1537
+ throw new DeleganceError(`Appetite match ${jobId} still ${job.status} after ${timeoutMs}ms`, 408);
1538
+ }
1539
+ await new Promise((r) => setTimeout(r, intervalMs));
1540
+ }
1541
+ }
1542
+ };
1543
+
1544
+ // src/modules/leads.ts
1545
+ var LeadsModule = class {
1546
+ constructor(http) {
1547
+ this.http = http;
1548
+ }
1549
+ /**
1550
+ * Create a lead.
1551
+ *
1552
+ * @example
1553
+ * ```typescript
1554
+ * const { companyId } = await client.leads.create({
1555
+ * name: 'Riverbend Bakery',
1556
+ * contactEmail: 'owner@riverbend.example',
1557
+ * state: 'TX',
1558
+ * externalId: 'crm-4411',
1559
+ * });
1560
+ * ```
1561
+ */
1562
+ async create(input) {
1563
+ return this.http.request({
1564
+ method: "POST",
1565
+ path: "/api/v1/leads",
1566
+ body: input
1567
+ });
1568
+ }
1569
+ };
1570
+
1571
+ // src/modules/instant-quotes.ts
1572
+ import { randomUUID as randomUUID2 } from "crypto";
1573
+ var InstantQuotesModule = class {
1574
+ constructor(http) {
1575
+ this.http = http;
1576
+ }
1577
+ /**
1578
+ * `fresh: true` always mints a new submission instead of reusing a warm
1579
+ * session for the same coverages. Use it with `submit({ replace: true })`
1580
+ * to re-quote coverage that already has a request with carriers.
1581
+ */
1582
+ async start(coverages, opts = {}) {
1583
+ const res = await this.http.request({
1584
+ method: "POST",
1585
+ path: "/api/v1/quotes/instant/session",
1586
+ body: opts.fresh ? { coverages, fresh: true } : { coverages }
1587
+ });
1588
+ return res.data;
1589
+ }
1590
+ async submit(input, opts = {}) {
1591
+ const res = await this.http.request({
1592
+ method: "POST",
1593
+ path: "/api/v1/quotes/instant/submit",
1594
+ body: input,
1595
+ headers: { "Idempotency-Key": opts.idempotencyKey ?? randomUUID2() }
1596
+ });
1597
+ return res.data;
1598
+ }
1599
+ async status(submissionId) {
1600
+ const res = await this.http.request({
1601
+ method: "GET",
1602
+ path: `/api/v1/quotes/instant/${encodeURIComponent(submissionId)}`
1603
+ });
1604
+ return res.data;
1605
+ }
1606
+ /** Polls `status` until every visible carrier resolved, or the timeout. */
1607
+ async waitForQuotes(submissionId, opts = {}) {
1608
+ const timeoutMs = opts.timeoutMs ?? 10 * 60 * 1e3;
1609
+ const intervalMs = opts.intervalMs ?? 1e4;
1610
+ const deadline = Date.now() + timeoutMs;
1611
+ for (; ; ) {
1612
+ const s = await this.status(submissionId);
1613
+ opts.onPoll?.(s);
1614
+ const remaining = deadline - Date.now();
1615
+ if (s.allCarriersResolved || remaining <= 0) return s;
1616
+ await new Promise((resolve) => setTimeout(resolve, Math.min(intervalMs, remaining)));
1617
+ }
1618
+ }
1619
+ /**
1620
+ * After a `no_carriers` submit: the ACORD questions a broker needs to place
1621
+ * the risk with a non-instant market. Pass the answers you submitted so
1622
+ * facts you already gave are not asked again.
1623
+ */
1624
+ async brokerHandoffQuestions(submissionId, instantAnswers = {}) {
1625
+ const res = await this.http.request({
1626
+ method: "POST",
1627
+ path: `/api/v1/quotes/instant/${encodeURIComponent(submissionId)}/broker-handoff/questions`,
1628
+ body: { instantAnswers }
1629
+ });
1630
+ return res.data;
1631
+ }
1632
+ /**
1633
+ * Hands a `no_carriers` submission to a Delegance broker as a non-instant
1634
+ * request, with whatever ACORD answers you have. `complete: false` says you
1635
+ * stopped early; the broker asks the rest. A repeat call returns the same
1636
+ * broker task.
1637
+ */
1638
+ async brokerHandoff(submissionId, input, opts = {}) {
1639
+ const res = await this.http.request({
1640
+ method: "POST",
1641
+ path: `/api/v1/quotes/instant/${encodeURIComponent(submissionId)}/broker-handoff`,
1642
+ body: input,
1643
+ headers: { "Idempotency-Key": opts.idempotencyKey ?? randomUUID2() }
1644
+ });
1645
+ return res.data;
1646
+ }
1647
+ /** Requests a bind on one offer. A licensed broker reviews it; nothing is charged. */
1648
+ async bind(submissionId, opportunityId, opts = {}) {
1649
+ const res = await this.http.request({
1650
+ method: "POST",
1651
+ path: `/api/v1/quotes/instant/${encodeURIComponent(submissionId)}/bind`,
1652
+ body: { opportunityId },
1653
+ headers: { "Idempotency-Key": opts.idempotencyKey ?? randomUUID2() }
1654
+ });
1655
+ return res.data;
1656
+ }
1657
+ /**
1658
+ * Bind through fast bind: an owner or admin attests the answers, gets a
1659
+ * 6-digit code by email (the first call returns `stepUpRequired`), then calls
1660
+ * again with `stepUpId` and `code`. A tier A offer returns `checkoutUrl`;
1661
+ * any other offer goes to a broker.
1662
+ */
1663
+ async bindWithStepUp(submissionId, opportunityId, input = {}) {
1664
+ const { idempotencyKey, ...rest } = input;
1665
+ const res = await this.http.request({
1666
+ method: "POST",
1667
+ path: `/api/v1/quotes/instant/${encodeURIComponent(submissionId)}/bind`,
1668
+ body: { opportunityId, ...rest },
1669
+ headers: { "Idempotency-Key": idempotencyKey ?? randomUUID2() }
1670
+ });
1671
+ if (res.stepUpRequired && res.stepUpId) {
1672
+ return { stepUpRequired: true, stepUpId: res.stepUpId, channel: "email", sentTo: res.sentTo ?? "", expiresAt: res.expiresAt ?? null };
1673
+ }
1674
+ return res.data;
1675
+ }
1676
+ };
1677
+
1678
+ // src/modules/payments.ts
1679
+ import { randomUUID as randomUUID3 } from "crypto";
1680
+ var PaymentsModule = class {
1681
+ constructor(http) {
1682
+ this.http = http;
1683
+ }
1684
+ async list() {
1685
+ const res = await this.http.request({ method: "GET", path: "/api/v1/payments" });
1686
+ return res.data.payments;
1687
+ }
1688
+ async checkout(paymentRequestId, opts = {}) {
1689
+ const res = await this.http.request({
1690
+ method: "POST",
1691
+ path: `/api/v1/payments/${encodeURIComponent(paymentRequestId)}/checkout`,
1692
+ headers: { "Idempotency-Key": opts.idempotencyKey ?? randomUUID3() }
1693
+ });
1694
+ return res.data;
1695
+ }
1696
+ };
1697
+
1698
+ // src/modules/bonds.ts
1699
+ import { randomUUID as randomUUID4 } from "crypto";
1700
+ var BondsModule = class {
1701
+ constructor(http) {
1702
+ this.http = http;
1703
+ }
1704
+ async start(input) {
1705
+ const res = await this.http.request({ method: "POST", path: "/api/v1/bonds/quote", body: input });
1706
+ return res.data;
1707
+ }
1708
+ async answer(sessionId, answers, opts = {}) {
1709
+ const res = await this.http.request({
1710
+ method: "POST",
1711
+ path: `/api/v1/bonds/quote/${encodeURIComponent(sessionId)}/answers`,
1712
+ body: { answers },
1713
+ headers: { "Idempotency-Key": opts.idempotencyKey ?? randomUUID4() }
1714
+ });
1715
+ return res.data;
1716
+ }
1717
+ async status(sessionId) {
1718
+ const res = await this.http.request({
1719
+ method: "GET",
1720
+ path: `/api/v1/bonds/quote/${encodeURIComponent(sessionId)}`
1721
+ });
1722
+ return res.data;
1723
+ }
1724
+ };
1725
+
1726
+ // src/modules/claims.ts
1727
+ import { randomUUID as randomUUID5 } from "crypto";
1728
+ var ClaimsModule = class {
1729
+ constructor(http) {
1730
+ this.http = http;
1731
+ }
1732
+ async file(input, opts = {}) {
1733
+ const res = await this.http.request({
1734
+ method: "POST",
1735
+ path: "/api/v1/claims",
1736
+ body: input,
1737
+ headers: { "Idempotency-Key": opts.idempotencyKey ?? randomUUID5() }
1738
+ });
1739
+ return res.data;
1740
+ }
1741
+ async list(opts = {}) {
1742
+ const q = new URLSearchParams();
1743
+ if (opts.status) q.set("status", opts.status);
1744
+ if (opts.limit) q.set("limit", String(opts.limit));
1745
+ const qs = q.toString();
1746
+ const res = await this.http.request({ method: "GET", path: `/api/v1/claims${qs ? `?${qs}` : ""}` });
1747
+ return res.data.claims;
1748
+ }
1749
+ async get(claimId) {
1750
+ const res = await this.http.request({ method: "GET", path: `/api/v1/claims/${encodeURIComponent(claimId)}` });
1751
+ return res.data;
1752
+ }
1753
+ };
1754
+
1755
+ // src/modules/feedback.ts
1756
+ import { randomUUID as randomUUID6 } from "crypto";
1757
+ var FEEDBACK_MESSAGE_MAX = 500;
1758
+ var FeedbackModule = class {
1759
+ constructor(http) {
1760
+ this.http = http;
1761
+ }
1762
+ /**
1763
+ * File a report. Returns the reference id Delegance uses to find it.
1764
+ *
1765
+ * Each call sends one Idempotency-Key, and the client's automatic retries of
1766
+ * that call reuse it, so a lost response never files the report twice. Pass
1767
+ * your own key to make a retry of your own (a second call) safe as well.
1768
+ */
1769
+ async submit(input, opts = {}) {
1770
+ const message = (input.message ?? "").trim();
1771
+ if (!message) throw new Error("Feedback needs a message.");
1772
+ if (message.length > FEEDBACK_MESSAGE_MAX) {
1773
+ throw new Error(`Keep the message to ${FEEDBACK_MESSAGE_MAX} characters or fewer.`);
1774
+ }
1775
+ const body = { type: input.type ?? "bug", message };
1776
+ if (input.context && Object.keys(input.context).length > 0) body.context = input.context;
1777
+ const res = await this.http.request({
1778
+ method: "POST",
1779
+ path: "/api/v1/feedback",
1780
+ body,
1781
+ headers: { "Idempotency-Key": opts.idempotencyKey ?? randomUUID6() }
1782
+ });
1783
+ return { id: res.data.id };
1784
+ }
1785
+ };
1786
+
1787
+ // src/modules/signup.ts
1788
+ import { createHash, randomBytes, randomUUID as randomUUID7 } from "crypto";
1789
+
1790
+ // src/utils/poll.ts
1791
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1792
+ async function pollUntilReady(poll, opts = {}) {
1793
+ const timeoutMs = opts.timeoutMs ?? 15 * 60 * 1e3;
1794
+ const intervalMs = opts.intervalMs ?? 5e3;
1795
+ const deadline = Date.now() + timeoutMs;
1796
+ for (; ; ) {
1797
+ let wait = intervalMs;
1798
+ try {
1799
+ const r = await poll();
1800
+ if (r.status !== "pending") return r;
1801
+ } catch (err) {
1802
+ if (!(err instanceof RateLimitError)) throw err;
1803
+ wait = Math.max(intervalMs, (err.retryAfter ?? 60) * 1e3);
1804
+ }
1805
+ opts.onPoll?.();
1806
+ const remaining = deadline - Date.now();
1807
+ if (remaining <= 0) return { status: "pending" };
1808
+ await sleep(Math.min(wait, remaining));
1809
+ }
1810
+ }
1811
+
1812
+ // src/modules/signup.ts
1813
+ function newDeviceSecret() {
1814
+ const secret = randomBytes(32).toString("hex");
1815
+ return { secret, hash: createHash("sha256").update(secret).digest("hex") };
1816
+ }
1817
+ var SignupModule = class {
1818
+ constructor(makeHttp) {
1819
+ this.makeHttp = makeHttp;
1820
+ }
1821
+ /** Creates the unverified company. Retries safely: sends an Idempotency-Key. */
1822
+ async createAccount(input, opts = {}) {
1823
+ const res = await this.makeHttp("").request({
1824
+ method: "POST",
1825
+ path: "/api/v1/companies",
1826
+ body: input,
1827
+ headers: { "Idempotency-Key": opts.idempotencyKey ?? randomUUID7() }
1828
+ });
1829
+ if (!res.bootstrapKey) {
1830
+ throw new Error("The signup was already created by an earlier attempt; its key is shown only once. Start again with a new signup.");
1831
+ }
1832
+ return {
1833
+ companyId: res.company.id,
1834
+ bootstrapKey: res.bootstrapKey,
1835
+ ...res.warnings?.length ? { warnings: res.warnings } : {}
1836
+ };
1837
+ }
1838
+ async enroll(bootstrapKey, input) {
1839
+ const res = await this.makeHttp(bootstrapKey).request({
1840
+ method: "POST",
1841
+ path: "/api/v1/onboarding/cli-enroll",
1842
+ body: input
1843
+ });
1844
+ return res.data;
1845
+ }
1846
+ async requestVerification(bootstrapKey) {
1847
+ const res = await this.makeHttp(bootstrapKey).request({
1848
+ method: "POST",
1849
+ path: "/api/v1/onboarding/verification",
1850
+ body: {}
1851
+ });
1852
+ return { sentTo: res.data?.sentTo };
1853
+ }
1854
+ /**
1855
+ * One poll. `pending` until the email link is clicked. Throws with
1856
+ * `reason` = already_collected | account_exists (409) or expired (410).
1857
+ */
1858
+ async exchange(enrollmentId, deviceSecret) {
1859
+ const res = await this.makeHttp("").request({
1860
+ method: "POST",
1861
+ path: "/api/v1/onboarding/cli-exchange",
1862
+ body: { enrollmentId, deviceSecret }
1863
+ });
1864
+ if (res.data?.apiKey && res.data.keyPrefix && res.data.companyId) {
1865
+ return { status: "ready", apiKey: res.data.apiKey, keyPrefix: res.data.keyPrefix, companyId: res.data.companyId };
1866
+ }
1867
+ if (res.data?.status === "pending") return { status: "pending" };
1868
+ throw new Error('Unexpected response from the key exchange. Run "delegance verify" to retry.');
1869
+ }
1870
+ /**
1871
+ * Polls `exchange` until the key is ready or `timeoutMs` passes. A 429 waits
1872
+ * the server's Retry-After and keeps polling.
1873
+ */
1874
+ async waitForKey(enrollmentId, deviceSecret, opts = {}) {
1875
+ return pollUntilReady(() => this.exchange(enrollmentId, deviceSecret), opts);
1876
+ }
1877
+ };
1878
+
1879
+ // src/modules/auth.ts
1880
+ var DeviceLoginModule = class {
1881
+ constructor(makeHttp) {
1882
+ this.makeHttp = makeHttp;
1883
+ }
1884
+ async start(input) {
1885
+ const res = await this.makeHttp("").request({
1886
+ method: "POST",
1887
+ path: "/api/v1/auth/device",
1888
+ body: input
1889
+ });
1890
+ return res.data;
1891
+ }
1892
+ /**
1893
+ * One poll. `pending` until the portal user approves. Throws with `reason`
1894
+ * = access_denied (403), already_collected (409), or expired (410).
1895
+ */
1896
+ async poll(loginId, deviceSecret) {
1897
+ const res = await this.makeHttp("").request({
1898
+ method: "POST",
1899
+ path: "/api/v1/auth/device/token",
1900
+ body: { loginId, deviceSecret }
1901
+ });
1902
+ const d = res.data ?? {};
1903
+ if (d.apiKey && d.keyPrefix && d.companyId) {
1904
+ return { status: "ready", apiKey: d.apiKey, keyPrefix: d.keyPrefix, companyId: d.companyId, scopes: d.scopes ?? [], expiresAt: d.expiresAt ?? null };
1905
+ }
1906
+ if (d.status === "pending") return { status: "pending" };
1907
+ throw new Error('Unexpected response from the login poll. Run "delegance auth login" again.');
1908
+ }
1909
+ /** Polls until the key is ready or `timeoutMs` passes (then returns `pending`). */
1910
+ async waitForKey(loginId, deviceSecret, opts = {}) {
1911
+ return pollUntilReady(() => this.poll(loginId, deviceSecret), opts);
1912
+ }
1913
+ };
1914
+ var AuthModule = class {
1915
+ constructor(http) {
1916
+ this.http = http;
1917
+ }
1918
+ /** The calling key: prefix, origin, scopes, company, and expiry. */
1919
+ async keyInfo() {
1920
+ const res = await this.http.request({ method: "GET", path: "/api/v1/auth/key" });
1921
+ return res.data;
1922
+ }
1923
+ /** Extend a CLI key to 90 days from now. Throws `not_refreshable` (400) for portal keys. */
1924
+ async refresh() {
1925
+ const res = await this.http.request({ method: "POST", path: "/api/v1/auth/refresh", body: {} });
1926
+ return res.data;
1927
+ }
1329
1928
  };
1330
1929
 
1331
1930
  // src/client.ts
@@ -1358,6 +1957,14 @@ var DeleganceClient = class {
1358
1957
  this.usage = new UsageModule(this.http);
1359
1958
  this.knowledge = new KnowledgeModule(this.http);
1360
1959
  this.onboarding = new OnboardingModule(this.http);
1960
+ this.appetite = new AppetiteModule(this.http);
1961
+ this.leads = new LeadsModule(this.http);
1962
+ this.instantQuotes = new InstantQuotesModule(this.http);
1963
+ this.payments = new PaymentsModule(this.http);
1964
+ this.bonds = new BondsModule(this.http);
1965
+ this.claims = new ClaimsModule(this.http);
1966
+ this.feedback = new FeedbackModule(this.http);
1967
+ this.auth = new AuthModule(this.http);
1361
1968
  }
1362
1969
  /**
1363
1970
  * Get the SDK version
@@ -1398,28 +2005,52 @@ function createClientFromEnv() {
1398
2005
  baseUrl
1399
2006
  });
1400
2007
  }
2008
+ function createSignup(config = {}) {
2009
+ return new SignupModule((apiKey) => new HttpClient({ apiKey, ...config }));
2010
+ }
2011
+ function createDeviceLogin(config = {}) {
2012
+ return new DeviceLoginModule((apiKey) => new HttpClient({ apiKey, ...config }));
2013
+ }
1401
2014
  export {
2015
+ API_KEY_SCOPES,
1402
2016
  ApiKeysModule,
2017
+ AppetiteModule,
2018
+ AuthModule,
1403
2019
  AuthenticationError,
2020
+ BondsModule,
1404
2021
  COIModule,
1405
2022
  ChatModule,
2023
+ ClaimsModule,
1406
2024
  CompaniesModule,
1407
2025
  CompanySizeSchema,
1408
2026
  CreateCompanySchema,
2027
+ DEFAULT_BASE_URL,
1409
2028
  DeleganceClient,
1410
2029
  DeleganceError,
2030
+ DeviceLoginModule,
1411
2031
  DocumentStatusSchema,
1412
2032
  DocumentTypeSchema,
1413
2033
  DocumentsModule,
2034
+ FEEDBACK_MESSAGE_MAX,
2035
+ FeedbackModule,
2036
+ ForbiddenError,
2037
+ InstantQuotesModule,
1414
2038
  KnowledgeModule,
2039
+ LeadsModule,
1415
2040
  NotFoundError,
2041
+ NotImplementedError,
1416
2042
  OnboardingModule,
2043
+ PaymentsModule,
1417
2044
  PoliciesModule,
1418
2045
  QuotesModule,
1419
2046
  RateLimitError,
1420
2047
  SDK_VERSION,
1421
2048
  SOVModule,
2049
+ SignupModule,
1422
2050
  UsageModule,
1423
2051
  ValidationError,
1424
- createClientFromEnv
2052
+ createClientFromEnv,
2053
+ createDeviceLogin,
2054
+ createSignup,
2055
+ newDeviceSecret
1425
2056
  };