@assinafy/sdk 2.10.0 → 3.0.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.mjs CHANGED
@@ -32,6 +32,24 @@ var AssinafyError = class extends Error {
32
32
  var ApiError = class _ApiError extends AssinafyError {
33
33
  statusCode;
34
34
  responseData;
35
+ /**
36
+ * Machine-readable refusal code from the error body, on the refusals a
37
+ * client can act on: `PlanRestricted` (offer the upgrade, don't retry),
38
+ * `InsufficientScope`, `DocumentNotReady`, `CreditCeilingExceeded`,
39
+ * `IdempotencyKeyInUse`, `EnvelopeOpen`, `EnvelopeClosed`, `DocumentClosed`,
40
+ * `ContractChanged`, `NoContractTerms`, `TagInUse`, `embed_origins_missing`, ….
41
+ * `undefined` when the body has none.
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * if (error instanceof ApiError && error.code === 'IdempotencyKeyInUse') {
46
+ * await sleep(1000); // the first request with this key is still running
47
+ * }
48
+ * ```
49
+ */
50
+ code;
51
+ /** Each field a `400` refused, in the order the API reports them. */
52
+ fieldErrors;
35
53
  /**
36
54
  * Parsed `WWW-Authenticate` challenge, when the response carried one.
37
55
  *
@@ -39,8 +57,8 @@ var ApiError = class _ApiError extends AssinafyError {
39
57
  * means the OAuth token is valid but was never granted that permission:
40
58
  * send the user through the authorization flow again asking for the scope
41
59
  * named in `scope`. A `403` without a challenge has a different cause —
42
- * another workspace, the user's role, or a surface OAuth tokens never
43
- * reach — and reconnecting will not fix it.
60
+ * another workspace, the user's role, the plan (`code: 'PlanRestricted'`),
61
+ * or a surface OAuth tokens never reach — and reconnecting will not fix it.
44
62
  *
45
63
  * @example
46
64
  * ```ts
@@ -87,6 +105,14 @@ var ApiError = class _ApiError extends AssinafyError {
87
105
  this.name = "ApiError";
88
106
  this.statusCode = statusCode;
89
107
  this.responseData = responseData;
108
+ if (responseData !== null && typeof responseData === "object") {
109
+ const body = responseData;
110
+ if (typeof body["code"] === "string" && body["code"].length > 0) this.code = body["code"];
111
+ if (Array.isArray(body["errors"])) {
112
+ const fieldErrors = body["errors"].filter(isFieldError);
113
+ if (fieldErrors.length > 0) this.fieldErrors = fieldErrors;
114
+ }
115
+ }
90
116
  }
91
117
  /**
92
118
  * Convert a status/body pair into an {@link ApiError}.
@@ -219,6 +245,11 @@ var NetworkError = class extends AssinafyError {
219
245
  this.name = "NetworkError";
220
246
  }
221
247
  };
248
+ function isFieldError(value) {
249
+ if (value === null || typeof value !== "object") return false;
250
+ const entry = value;
251
+ return (entry["field"] === null || typeof entry["field"] === "string") && typeof entry["code"] === "string" && typeof entry["message"] === "string";
252
+ }
222
253
 
223
254
  // src/utils.ts
224
255
  import axios from "axios";
@@ -279,6 +310,7 @@ var SAFE_LOG_NUMBER_FIELDS = /* @__PURE__ */ new Set([
279
310
  "delayMs",
280
311
  "maxRetries",
281
312
  "signerCount",
313
+ "documentCount",
282
314
  "size"
283
315
  ]);
284
316
  function handleAssinafyResponse(response) {
@@ -454,6 +486,45 @@ function assertDateTime(value, label) {
454
486
  throw new ValidationError(`${label} must be an ISO-8601 date-time`);
455
487
  }
456
488
  }
489
+ function assertExpirationDate(value, label) {
490
+ if (typeof value !== "string") {
491
+ throw new ValidationError(`${label} must be an ISO-8601 date or date-time`);
492
+ }
493
+ const normalized = /^\d{4}-\d{2}-\d{2}$/u.test(value) ? `${value}T00:00:00Z` : /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?$/u.test(value) ? `${value}Z` : value;
494
+ try {
495
+ assertDateTime(normalized, label);
496
+ } catch {
497
+ throw new ValidationError(`${label} must be an ISO-8601 date or date-time`);
498
+ }
499
+ }
500
+ function assertCreditCeiling(value) {
501
+ if (value !== void 0 && (typeof value !== "number" || !Number.isFinite(value) || value < 0)) {
502
+ throw new ValidationError("max_total_credits must be a finite number of credits, zero or more");
503
+ }
504
+ }
505
+ function idempotencyConfig(key) {
506
+ if (key === void 0) return {};
507
+ if (typeof key !== "string" || key.trim().length === 0) {
508
+ throw new ValidationError("idempotencyKey must be a non-empty string");
509
+ }
510
+ return { headers: { "Idempotency-Key": key } };
511
+ }
512
+ function assertBooleanMap(value, label, known) {
513
+ assertRecord(value, label);
514
+ const entries = Object.entries(value);
515
+ if (entries.length === 0) throw new ValidationError(`${label} must set at least one key`);
516
+ for (const [key, item] of entries) {
517
+ if (known && !known.has(key)) throw new ValidationError(`unknown ${label} key: ${key}`);
518
+ if (typeof item !== "boolean") throw new ValidationError(`${label}.${key} must be a boolean`);
519
+ }
520
+ }
521
+ function expandParam(value, allowed) {
522
+ if (value === void 0) return {};
523
+ if (!Array.isArray(value) || value.some((item) => !allowed.has(item))) {
524
+ throw new ValidationError(`expand must list only ${[...allowed].join(", ")}`);
525
+ }
526
+ return value.length > 0 ? { expand: value.join(",") } : {};
527
+ }
457
528
  function cleanParams(params) {
458
529
  assertRecord(params, "params");
459
530
  const out = {};
@@ -628,7 +699,7 @@ import axios2 from "axios";
628
699
  // package.json
629
700
  var package_default = {
630
701
  name: "@assinafy/sdk",
631
- version: "2.10.0",
702
+ version: "3.0.0",
632
703
  packageManager: "bun@1.4.4",
633
704
  description: "TypeScript SDK for Assinafy API - Digital signature platform",
634
705
  type: "commonjs",
@@ -712,7 +783,8 @@ var package_default = {
712
783
  overrides: {
713
784
  esbuild: "0.28.2",
714
785
  "follow-redirects": "1.16.2",
715
- "brace-expansion": "5.0.12"
786
+ "brace-expansion": "5.0.12",
787
+ minimatch: "11.0.3"
716
788
  },
717
789
  files: [
718
790
  "dist",
@@ -979,14 +1051,23 @@ function toInt(value) {
979
1051
 
980
1052
  // src/resources/assignments.ts
981
1053
  var ASSIGNMENT_METHODS = /* @__PURE__ */ new Set(["virtual", "collect"]);
982
- var VERIFICATION_METHODS = /* @__PURE__ */ new Set(["Email", "Whatsapp", "DigitalCertificate", "IdDocumentFaceMatchBasic"]);
983
- var NOTIFICATION_METHODS = /* @__PURE__ */ new Set(["Email", "Whatsapp"]);
1054
+ var VERIFICATION_METHODS = /* @__PURE__ */ new Set([
1055
+ "Email",
1056
+ "Whatsapp",
1057
+ "DigitalCertificate",
1058
+ "IdDocumentFaceMatchBasic",
1059
+ "Bypass"
1060
+ ]);
1061
+ var MESSAGE_CHANNELS = /* @__PURE__ */ new Set(["Email", "Whatsapp"]);
1062
+ var NOTIFICATION_METHODS = /* @__PURE__ */ new Set([...MESSAGE_CHANNELS, "Bypass"]);
1063
+ var EMBEDDED_VERIFICATION_METHODS = /* @__PURE__ */ new Set(["Email", "Whatsapp", "Bypass"]);
984
1064
  var DIGITAL_CERTIFICATE_REQUIRES_VIRTUAL_METHOD = "digital_certificate_requires_virtual_method";
985
1065
  var ALLOWED_NOTIFICATION_METHODS = {
986
1066
  Email: /* @__PURE__ */ new Set(["Email"]),
987
1067
  Whatsapp: /* @__PURE__ */ new Set(["Whatsapp"]),
988
- DigitalCertificate: NOTIFICATION_METHODS,
989
- IdDocumentFaceMatchBasic: NOTIFICATION_METHODS
1068
+ DigitalCertificate: MESSAGE_CHANNELS,
1069
+ IdDocumentFaceMatchBasic: MESSAGE_CHANNELS,
1070
+ Bypass: NOTIFICATION_METHODS
990
1071
  };
991
1072
  function validateAssignmentSignerOptions(signer, label = "signer") {
992
1073
  if (signer.verification_method !== void 0 && (typeof signer.verification_method !== "string" || !VERIFICATION_METHODS.has(signer.verification_method))) {
@@ -1012,6 +1093,14 @@ function validateAssignmentSignerOptions(signer, label = "signer") {
1012
1093
  }
1013
1094
  }
1014
1095
  }
1096
+ if (signer.embedded !== void 0 && typeof signer.embedded !== "boolean") {
1097
+ throw new ValidationError(`${label} embedded must be a boolean`);
1098
+ }
1099
+ if (signer.embedded === true && typeof signer.verification_method === "string" && !EMBEDDED_VERIFICATION_METHODS.has(signer.verification_method)) {
1100
+ throw new ValidationError(
1101
+ `${label} embedded signing supports only Email, Whatsapp and Bypass verification`
1102
+ );
1103
+ }
1015
1104
  if (signer.step !== void 0 && (typeof signer.step !== "number" || !Number.isSafeInteger(signer.step) || signer.step < 1)) {
1016
1105
  throw new ValidationError(`${label} step must be a positive safe integer`);
1017
1106
  }
@@ -1066,12 +1155,13 @@ function buildAssignmentPayload(payload) {
1066
1155
  if (payload.message !== void 0 && typeof payload.message !== "string") {
1067
1156
  throw new ValidationError("message must be a string");
1068
1157
  }
1069
- if (payload.expires_at !== void 0) assertDateTime(payload.expires_at, "expires_at");
1158
+ if (payload.expires_at !== void 0) assertExpirationDate(payload.expires_at, "expires_at");
1070
1159
  if (payload.copy_receivers !== void 0 && (!Array.isArray(payload.copy_receivers) || payload.copy_receivers.some(
1071
1160
  (id) => typeof id !== "string" || !id.trim()
1072
1161
  ))) {
1073
1162
  throw new ValidationError("copy_receivers must be an array of non-empty signer IDs");
1074
1163
  }
1164
+ assertCreditCeiling(payload.max_total_credits);
1075
1165
  const normalisedSigners = signers.map((ref) => normaliseSignerRef(ref));
1076
1166
  validateDigitalCertificateMethod(method, normalisedSigners);
1077
1167
  validateSigningOrder(normalisedSigners, "assignment signers");
@@ -1081,7 +1171,8 @@ function buildAssignmentPayload(payload) {
1081
1171
  message: payload.message,
1082
1172
  expires_at: payload.expires_at,
1083
1173
  copy_receivers: payload.copy_receivers,
1084
- entries
1174
+ entries,
1175
+ max_total_credits: payload.max_total_credits
1085
1176
  });
1086
1177
  }
1087
1178
  function buildAssignmentEstimatePayload(payload) {
@@ -1126,6 +1217,7 @@ function normaliseSignerRef(ref) {
1126
1217
  id,
1127
1218
  verification_method: input.verification_method,
1128
1219
  notification_methods: input.notification_methods,
1220
+ embedded: input.embedded,
1129
1221
  step: input.step
1130
1222
  });
1131
1223
  if (typeof id === "string" && id.trim().length > 0) {
@@ -1233,12 +1325,13 @@ var AssignmentResource = class extends BaseResource {
1233
1325
  /**
1234
1326
  * List assignments across the workspace (`GET /assignments`).
1235
1327
  *
1236
- * The account is passed as an `accountId` **query parameter** — the API
1237
- * responds `400` ("Um contexto de conta é necessário e não foi fornecido")
1238
- * without it. Note the camelCase spelling: `account_id` and an
1239
- * `X-Account-Id` header are both rejected.
1328
+ * The account is passed as the camelCase `accountId` **query parameter**,
1329
+ * required unless an OAuth token names the workspace (the SDK always sends
1330
+ * it; for a token, its own workspace). `account_id` and an `X-Account-Id`
1331
+ * header are ignored.
1240
1332
  *
1241
- * @param params - `page`, `per-page`.
1333
+ * @param params - `page`, `per-page` (at most 50), and `sort`: `created_at`
1334
+ * (default, oldest first), `expires_at` or `id`, `-` prefix for descending.
1242
1335
  * @param accountId - Override the client's default account ID.
1243
1336
  * @returns Assignments, with pagination in `meta`. Each item is a full
1244
1337
  * {@link IAssignment} (same shape as {@link AssignmentResource.create}
@@ -1306,13 +1399,15 @@ var AssignmentResource = class extends BaseResource {
1306
1399
  * "signing_urls": [
1307
1400
  * {
1308
1401
  * "signer_id": "19e6b92e7895332ed9708535d8c",
1309
- * "url": "https://app.assinafy.com.br/sign/103033c950d865a248a11c5cf96c?email=signer%40example.com"
1402
+ * "url": "https://app.assinafy.com.br/sign/103033c950d865a248a11c5cf96c?email=signer%40example.com",
1403
+ * "embedded": false
1310
1404
  * }
1311
1405
  * ]
1312
1406
  * }
1313
1407
  * ```
1314
1408
  * @throws {ValidationError} If no account ID is available.
1315
- * @throws {ApiError} If the API rejects the request.
1409
+ * @throws {ApiError} `400` when no workspace is named, `403` when a role or
1410
+ * OAuth scope refuses it, `404` for an unknown workspace.
1316
1411
  *
1317
1412
  * @example
1318
1413
  * ```ts
@@ -1371,6 +1466,14 @@ var AssignmentResource = class extends BaseResource {
1371
1466
  * @param payload - Signers plus optional `method` (defaults to `virtual`),
1372
1467
  * `message`, `expires_at`, `copy_receivers` (existing signer IDs, not
1373
1468
  * addresses), and `collect`-mode `entries` with page-image geometry.
1469
+ * `expires_at` accepts a date (ending at 23:59 UTC), a date-time without
1470
+ * an offset (UTC), or an offset-aware date-time, at least one hour ahead.
1471
+ * `max_total_credits` refuses the send above that many credits. Signers may
1472
+ * set `embedded: true` (Embed feature; `Email`, `Whatsapp` or `Bypass`
1473
+ * verification) to sign in your app through `embed.createSession()`.
1474
+ * This route takes no `Idempotency-Key`: a document takes one assignment,
1475
+ * so a retry after a lost response answers `400` and charges nothing —
1476
+ * read the document to see whether the first request went through.
1374
1477
  * @returns The created {@link IAssignment}: `signers` (rich, with `step` /
1375
1478
  * `notified` / `verification_method`), `items` (one row per signer × field),
1376
1479
  * a `summary` count block, and per-signer `signing_urls`. Response shape:
@@ -1435,7 +1538,8 @@ var AssignmentResource = class extends BaseResource {
1435
1538
  * "signing_urls": [
1436
1539
  * {
1437
1540
  * "signer_id": "19e6b92e7895332ed9708535d8c",
1438
- * "url": "https://app.assinafy.com.br/sign/103033c950d865a248a11c5cf96c?email=signer%40example.com"
1541
+ * "url": "https://app.assinafy.com.br/sign/103033c950d865a248a11c5cf96c?email=signer%40example.com",
1542
+ * "embedded": false // an embedded signer has "url": null
1439
1543
  * }
1440
1544
  * ]
1441
1545
  * }
@@ -1445,7 +1549,10 @@ var AssignmentResource = class extends BaseResource {
1445
1549
  * combined with `collect`. The last case has `errors.code ===
1446
1550
  * 'digital_certificate_requires_virtual_method'`.
1447
1551
  * @throws {ApiError} `400` for an invalid assignment or unmet verification
1448
- * precondition; otherwise if the API rejects the request.
1552
+ * precondition; `403` (`PlanRestricted` for a method or Embed the plan
1553
+ * lacks, `InsufficientScope`); `404` for a document outside the workspace;
1554
+ * `409` (`CreditCeilingExceeded`, with `total_credits` and
1555
+ * `max_total_credits` in `responseData`).
1449
1556
  *
1450
1557
  * @example
1451
1558
  * ```ts
@@ -1454,7 +1561,7 @@ var AssignmentResource = class extends BaseResource {
1454
1561
  * message: 'Please sign this contract',
1455
1562
  * });
1456
1563
  * // → wire body: { method: 'virtual', signers: [{ id: '19e6…' }], message: 'Please sign this contract' }
1457
- * console.log(assignment.signing_urls?.length); // one protected link per signer
1564
+ * console.log(assignment.signing_urls?.length); // one entry per notified signer; url is null for embedded or WhatsApp-only signers
1458
1565
  * ```
1459
1566
  */
1460
1567
  async create(documentId, payload) {
@@ -1558,9 +1665,10 @@ var AssignmentResource = class extends BaseResource {
1558
1665
  * (`PUT /documents/{documentId}/assignments/{assignmentId}/reset-expiration`).
1559
1666
  *
1560
1667
  * Sends `{ expires_at }` verbatim; the key itself is required by the
1561
- * contract. Use an ISO-8601 date/time string, or `null` to remove the
1562
- * expiration — `null` is the documented clear mechanism and, unlike
1563
- * ordinary nullable inputs, is intentionally not stripped from the body.
1668
+ * contract. Use an ISO-8601 date, a date-time with or without an offset,
1669
+ * or `null` to remove the expiration. Date-only values end at 23:59 UTC;
1670
+ * date-times without offsets are UTC. `null` is intentionally not stripped
1671
+ * from the body.
1564
1672
  *
1565
1673
  * Request body (`application/json`):
1566
1674
  * ```jsonc
@@ -1571,8 +1679,8 @@ var AssignmentResource = class extends BaseResource {
1571
1679
  *
1572
1680
  * @param documentId - The document the assignment belongs to.
1573
1681
  * @param assignmentId - The assignment to update.
1574
- * @param expiresAt - New expiry as an ISO-8601 date/time string, or `null`
1575
- * to remove the expiration.
1682
+ * @param expiresAt - New expiry as an ISO-8601 date or date-time string,
1683
+ * or `null` to remove the expiration.
1576
1684
  * @returns The updated {@link IAssignment} — the same full shape
1577
1685
  * {@link AssignmentResource.create} returns (`signers`, `items`, `summary`,
1578
1686
  * `signing_urls`), with `expires_at` reflecting the new value:
@@ -1616,7 +1724,7 @@ var AssignmentResource = class extends BaseResource {
1616
1724
  async resetExpiration(documentId, assignmentId, expiresAt) {
1617
1725
  const docId = this.requireId(documentId, "Document ID");
1618
1726
  const asgId = this.requireId(assignmentId, "Assignment ID");
1619
- if (expiresAt !== null) assertDateTime(expiresAt, "expiresAt");
1727
+ if (expiresAt !== null) assertExpirationDate(expiresAt, "expiresAt");
1620
1728
  return this.call(
1621
1729
  "Failed to update assignment expiration",
1622
1730
  () => this.http.put(
@@ -1645,7 +1753,11 @@ var AssignmentResource = class extends BaseResource {
1645
1753
  * }
1646
1754
  * ```
1647
1755
  * @throws {ValidationError} If any of the three IDs is missing.
1648
- * @throws {ApiError} If the API rejects the request.
1756
+ * @throws {ApiError} `400` when the document is not pending signature, the
1757
+ * signer already signed or waits for an earlier step, or credits are short;
1758
+ * `403`; `404`. The same verification code is resent, so an open embed frame
1759
+ * keeps working; envelope signers can be reminded of every document at once
1760
+ * with `envelopes.resendNotification()`.
1649
1761
  *
1650
1762
  * @example
1651
1763
  * ```ts
@@ -1674,26 +1786,20 @@ var AssignmentResource = class extends BaseResource {
1674
1786
  * @param documentId - The document the assignment belongs to.
1675
1787
  * @param assignmentId - The assignment containing the signer.
1676
1788
  * @param signerId - The signer whose notification would be resent.
1677
- * @returns An {@link IResendCostEstimate}: either the full
1678
- * {@link ICostEstimate} or the compact `total` /
1679
- * `has_sufficient_credits` compatibility shape:
1789
+ * @returns An {@link IResendCostEstimate}: the compact `total` /
1790
+ * `has_sufficient_credits` shape production returns, or the full
1791
+ * {@link ICostEstimate} on older deployments:
1680
1792
  * ```jsonc
1681
1793
  * {
1682
- * "documents": 1,
1683
- * "credits": 0,
1684
- * "needs_extra_document": false,
1685
- * "extra_document_cost": 0,
1686
- * "total_credits": 0,
1687
- * "breakdown": [],
1688
- * "document_balance": 67,
1689
- * "credit_balance": 0,
1690
- * "has_sufficient_resources": true,
1691
- * "blocking_reason": null,
1692
- * "message": null
1794
+ * "total": 0.45,
1795
+ * "breakdown": [{ "code": "NotificationWhatsappResend", "name": "WhatsApp Notification Resend", "cost": 0.45 }],
1796
+ * "credit_balance": 10, // null when credits are not limited
1797
+ * "has_sufficient_credits": true
1693
1798
  * }
1694
1799
  * ```
1695
1800
  * @throws {ValidationError} If any of the three IDs is missing.
1696
- * @throws {ApiError} If the API rejects the request.
1801
+ * @throws {ApiError} `400` when the signer cannot be reminded (signed, not
1802
+ * yet notified, or notified only by `Bypass`), `403`, `404`.
1697
1803
  *
1698
1804
  * @example
1699
1805
  * ```ts
@@ -1731,11 +1837,11 @@ var AssignmentResource = class extends BaseResource {
1731
1837
  * ```jsonc
1732
1838
  * [
1733
1839
  * {
1734
- * "sent_at": 1784145573,
1840
+ * "sent_at": "2026-10-19T19:05:48Z",
1735
1841
  * "header": "Assinafy",
1736
1842
  * "body": "Você tem um documento para assinar.",
1737
1843
  * "buttons": [
1738
- * { "text": "Assinar documento", "url": "https://app.assinafy.com.br/sign/103033c950d865a248a11c5cf96c" }
1844
+ * { "text": "Assinar documento" } // production strips button URLs
1739
1845
  * ],
1740
1846
  * "phone_number": "+5511999998888",
1741
1847
  * "signer_id": "19e6b92e7895332ed9708535d8c"
@@ -2076,7 +2182,7 @@ var DocumentResource = class extends BaseResource {
2076
2182
  * a compact representation with no expanded `assignment` or `pages`, so
2077
2183
  * prefer it for name lookups and pickers.
2078
2184
  *
2079
- * @param params - `search`, `status`, `page`, `per-page`.
2185
+ * @param params - `search`, `status`, `page`, `per-page`, and `sort`.
2080
2186
  * @param accountId - Override the client's default account ID.
2081
2187
  * @returns Matching documents, with pagination in `meta`. Each item:
2082
2188
  * ```jsonc
@@ -2194,7 +2300,11 @@ var DocumentResource = class extends BaseResource {
2194
2300
  * `null`), rendered `pages`, and `artifacts`. `decline_reason` is returned
2195
2301
  * only when the access token belongs to the document creator.
2196
2302
  *
2303
+ * `expand: ['envelope_id']` adds the envelope the document is in and
2304
+ * `expand: ['envelope']` its `{ id, name }` (each `null` outside one).
2305
+ *
2197
2306
  * @param documentId - The document to fetch.
2307
+ * @param options - `expand`: `envelope_id` and/or `envelope`.
2198
2308
  * @returns The document. Response shape (once `metadata_ready`):
2199
2309
  * ```jsonc
2200
2310
  * {
@@ -2223,30 +2333,38 @@ var DocumentResource = class extends BaseResource {
2223
2333
  * "download_url": "https://…/documents/103ad216…/pages/103ad216…/download"
2224
2334
  * }
2225
2335
  * ],
2336
+ * "has_contract": false,
2337
+ * "envelope_id": null, // with expand: ['envelope_id']
2338
+ * "envelope": null, // with expand: ['envelope']
2226
2339
  * "created_at": "2026-07-19T17:24:43Z",
2227
2340
  * "updated_at": "2026-07-19T17:24:46Z"
2228
2341
  * }
2229
2342
  * ```
2230
- * @throws {ValidationError} If `documentId` is missing.
2231
- * @throws {ApiError} `404` if the document does not exist.
2343
+ * @throws {ValidationError} If `documentId` is missing or `expand` is unknown.
2344
+ * @throws {ApiError} `403` when a role or OAuth scope refuses it, `404` if the
2345
+ * document does not exist.
2232
2346
  *
2233
2347
  * @example
2234
2348
  * ```ts
2235
- * const doc = await client.documents.details('103ad216846e6b90710cb9acef59');
2236
- * console.log(doc.status, doc.pages.length);
2349
+ * const doc = await client.documents.details('103ad216846e6b90710cb9acef59', {
2350
+ * expand: ['envelope'],
2351
+ * });
2352
+ * console.log(doc.status, doc.envelope?.name);
2237
2353
  * ```
2238
2354
  */
2239
- async details(documentId) {
2355
+ async details(documentId, options = {}) {
2240
2356
  const id = this.requireId(documentId, "Document ID");
2241
- return this.fetchDetails(id);
2242
- }
2243
- fetchDetails(id, signal) {
2357
+ return this.fetchDetails(id, void 0, options);
2358
+ }
2359
+ fetchDetails(id, signal, options = {}) {
2360
+ assertRecord(options, "document details options");
2361
+ const params = expandParam(options.expand, DETAIL_EXPANSIONS);
2362
+ const config = {};
2363
+ if (signal) config.signal = signal;
2364
+ if (params.expand) config.params = params;
2244
2365
  return this.call(
2245
2366
  "Failed to fetch document details",
2246
- () => this.http.get(
2247
- `/documents/${this.pathSegment(id, "Document ID")}`,
2248
- signal ? { signal } : void 0
2249
- )
2367
+ () => this.http.get(`/documents/${this.pathSegment(id, "Document ID")}`, config)
2250
2368
  );
2251
2369
  }
2252
2370
  /**
@@ -2254,18 +2372,19 @@ var DocumentResource = class extends BaseResource {
2254
2372
  * (`GET /documents/{documentId}`).
2255
2373
  *
2256
2374
  * @param documentId - The document to fetch.
2375
+ * @param options - `expand`, as on {@link DocumentResource.details}.
2257
2376
  * @returns The document details (see {@link DocumentResource.details} for
2258
2377
  * the response shape).
2259
2378
  * @throws {ValidationError} If `documentId` is missing.
2260
- * @throws {ApiError} `404` if the document does not exist.
2379
+ * @throws {ApiError} `403` or `404`, as on {@link DocumentResource.details}.
2261
2380
  *
2262
2381
  * @example
2263
2382
  * ```ts
2264
2383
  * const doc = await client.documents.get('103ad216846e6b90710cb9acef59');
2265
2384
  * ```
2266
2385
  */
2267
- async get(documentId) {
2268
- return this.details(documentId);
2386
+ async get(documentId, options = {}) {
2387
+ return this.details(documentId, options);
2269
2388
  }
2270
2389
  /**
2271
2390
  * Poll {@link DocumentResource.details} until the document reaches a ready
@@ -2379,10 +2498,15 @@ var DocumentResource = class extends BaseResource {
2379
2498
  * Download the document thumbnail image
2380
2499
  * (`GET /documents/{documentId}/thumbnail`).
2381
2500
  *
2501
+ * `artifact: 'certificated'` renders it as it is in the signed document.
2502
+ *
2382
2503
  * @param documentId - The document whose thumbnail to fetch.
2383
- * @returns A {@link Buffer} of the thumbnail image bytes.
2384
- * @throws {ValidationError} If `documentId` is missing.
2385
- * @throws {ApiError} `404` if the document or its thumbnail does not exist.
2504
+ * @param options - `artifact: 'certificated'` for the signed render.
2505
+ * @returns A {@link Buffer} of the thumbnail image bytes (`image/*`).
2506
+ * @throws {ValidationError} If `documentId` is missing or `artifact` is unknown.
2507
+ * @throws {ApiError} `404` if the document, its thumbnail, or (with
2508
+ * `certificated`) its certification does not exist; `503` while the signed
2509
+ * render is still being produced — wait `rateLimit.retryAfter` seconds.
2386
2510
  *
2387
2511
  * @example
2388
2512
  * ```ts
@@ -2390,28 +2514,29 @@ var DocumentResource = class extends BaseResource {
2390
2514
  * await fs.promises.writeFile('thumb.jpg', thumb);
2391
2515
  * ```
2392
2516
  */
2393
- async thumbnail(documentId) {
2517
+ async thumbnail(documentId, options = {}) {
2394
2518
  const id = this.requireId(documentId, "Document ID");
2519
+ const config = renderConfig(options);
2395
2520
  return this.callBinary(
2396
2521
  "Failed to download document thumbnail",
2397
- () => this.http.get(
2398
- `/documents/${this.pathSegment(id, "Document ID")}/thumbnail`,
2399
- { responseType: "arraybuffer" }
2400
- )
2522
+ () => this.http.get(`/documents/${this.pathSegment(id, "Document ID")}/thumbnail`, config)
2401
2523
  );
2402
2524
  }
2403
2525
  /**
2404
- * Download a single rendered page as a JPEG
2526
+ * Download a single rendered page image
2405
2527
  * (`GET /documents/{documentId}/pages/{pageId}/download`).
2406
2528
  *
2407
2529
  * The `pageId` comes from a page's `id` in {@link DocumentResource.details}
2408
- * or {@link DocumentResource.list} (`pages[].id`).
2530
+ * or {@link DocumentResource.list} (`pages[].id`). `artifact: 'certificated'`
2531
+ * renders the page as it is in the signed document.
2409
2532
  *
2410
2533
  * @param documentId - The document the page belongs to.
2411
2534
  * @param pageId - The page to download.
2412
- * @returns A {@link Buffer} of the page's JPEG bytes.
2413
- * @throws {ValidationError} If `documentId` or `pageId` is missing.
2414
- * @throws {ApiError} `404` if the document or page does not exist.
2535
+ * @param options - `artifact: 'certificated'` for the signed render.
2536
+ * @returns A {@link Buffer} of the page image bytes (`image/*`).
2537
+ * @throws {ValidationError} If `documentId` or `pageId` is missing, or `artifact` is unknown.
2538
+ * @throws {ApiError} `404` if the document or page does not exist (or, with
2539
+ * `certificated`, is not certified); `503` while the signed render is pending.
2415
2540
  *
2416
2541
  * @example
2417
2542
  * ```ts
@@ -2420,14 +2545,15 @@ var DocumentResource = class extends BaseResource {
2420
2545
  * await fs.promises.writeFile('page-1.jpg', page);
2421
2546
  * ```
2422
2547
  */
2423
- async downloadPage(documentId, pageId) {
2548
+ async downloadPage(documentId, pageId, options = {}) {
2424
2549
  const docId = this.requireId(documentId, "Document ID");
2425
2550
  const pid = this.requireId(pageId, "Page ID");
2551
+ const config = renderConfig(options);
2426
2552
  return this.callBinary(
2427
2553
  "Failed to download page",
2428
2554
  () => this.http.get(
2429
2555
  `/documents/${this.pathSegment(docId, "Document ID")}/pages/${this.pathSegment(pid, "Page ID")}/download`,
2430
- { responseType: "arraybuffer" }
2556
+ config
2431
2557
  )
2432
2558
  );
2433
2559
  }
@@ -2444,7 +2570,7 @@ var DocumentResource = class extends BaseResource {
2444
2570
  * @param documentId - The document whose activity log to fetch.
2445
2571
  * @param params - Optional pagination and sorting parameters.
2446
2572
  * @param params.page - Page number, starting at 1.
2447
- * @param params.per-page - Entries per page (production default 20, documented max 100).
2573
+ * @param params.per-page - Entries per page (default 20, at most 50; a larger value answers 50).
2448
2574
  * @param params.per_page - Alias for `per-page`; explicit `per-page` wins.
2449
2575
  * @param params.sort - `-id` (default, newest first) or `id` (oldest first).
2450
2576
  * @returns The requested page of activity entries, or `[]`:
@@ -2474,7 +2600,7 @@ var DocumentResource = class extends BaseResource {
2474
2600
  * @example
2475
2601
  * ```ts
2476
2602
  * const events = await client.documents.activities('doc-1', {
2477
- * page: 2, 'per-page': 100, sort: 'id',
2603
+ * page: 2, 'per-page': 50, sort: 'id',
2478
2604
  * });
2479
2605
  * console.log(events.map((e) => e.event));
2480
2606
  * ```
@@ -2494,7 +2620,7 @@ var DocumentResource = class extends BaseResource {
2494
2620
  * @param documentId - The document whose activity log to fetch.
2495
2621
  * @param params - Optional pagination and sorting parameters.
2496
2622
  * @param params.page - Page number, starting at 1.
2497
- * @param params.per-page - Entries per page (production default 20, documented max 100).
2623
+ * @param params.per-page - Entries per page (default 20, at most 50; a larger value answers 50).
2498
2624
  * @param params.per_page - Alias for `per-page`; explicit `per-page` wins.
2499
2625
  * @param params.sort - `-id` (default, newest first) or `id` (oldest first).
2500
2626
  * @returns Activity entries and pagination metadata when the server supplies it:
@@ -2535,13 +2661,16 @@ var DocumentResource = class extends BaseResource {
2535
2661
  * Only documents in a deletable status can be removed — the API returns
2536
2662
  * `400` while the document is still `uploading` / `metadata_processing`
2537
2663
  * (await {@link DocumentResource.waitUntilReady} first) or once it has been
2538
- * certificated.
2664
+ * certificated. Deleting a `pending_signature` or `pending_identity_review`
2665
+ * document cancels it and notifies its signers. A document of an envelope
2666
+ * with an open document cannot be deleted on its own: cancel the envelope.
2539
2667
  *
2540
2668
  * @param documentId - The document to delete.
2541
2669
  * @returns Nothing; resolves when the document is deleted.
2542
2670
  * @throws {ValidationError} If `documentId` is missing.
2543
2671
  * @throws {ApiError} `400` if the document is not in a deletable status;
2544
- * `404` if it does not exist.
2672
+ * `403` when a role or OAuth scope refuses it; `404` if it does not exist;
2673
+ * `409` (`EnvelopeOpen`) while its envelope has an open document.
2545
2674
  *
2546
2675
  * @example
2547
2676
  * ```ts
@@ -2738,9 +2867,11 @@ var DocumentResource = class extends BaseResource {
2738
2867
  *
2739
2868
  * Instantiates the template, binding each role to a signer, and returns the
2740
2869
  * new document. The request body is `{ signers, ...options }` — `signers`
2741
- * maps every template `role_id` to an existing account signer `id`, and
2742
- * `options` may add `name`, `message`, `expires_at`, `editor_fields`, and
2743
- * tag names in `tags` (unknown names are created automatically).
2870
+ * maps every template `role_id` to an existing signer `id` or an `email`.
2871
+ * An email reuses the matching account signer or creates one with `name`;
2872
+ * `id` wins when both are present. Options may add `name`, `message`,
2873
+ * `expires_at`, `editor_fields`, and tag names in `tags` (unknown names are
2874
+ * created automatically).
2744
2875
  *
2745
2876
  * Request body (`application/json`):
2746
2877
  * ```jsonc
@@ -2748,7 +2879,9 @@ var DocumentResource = class extends BaseResource {
2748
2879
  * "signers": [
2749
2880
  * {
2750
2881
  * "role_id": "signing_role_example",
2751
- * "id": "signer_example",
2882
+ * "email": "signer@example.com",
2883
+ * "name": "Example Signer",
2884
+ * "whatsapp_phone_number": "+15555550100",
2752
2885
  * "verification_method": "Email",
2753
2886
  * "notification_methods": [
2754
2887
  * "Email"
@@ -2772,27 +2905,33 @@ var DocumentResource = class extends BaseResource {
2772
2905
  * ```
2773
2906
  *
2774
2907
  * @param templateId - The template to instantiate.
2775
- * @param signers - Role-to-signer bindings (each with `role_id` and `id`,
2776
- * plus optional `verification_method`, `notification_methods`, `step`).
2908
+ * @param signers - Role-to-signer bindings (each with `role_id` and either
2909
+ * an existing `id` or an `email`; email creation also accepts `name` and
2910
+ * `whatsapp_phone_number`). `verification_method`, `notification_methods`,
2911
+ * and `step` are optional.
2777
2912
  * Only one notification method is allowed per signer; when only one of the
2778
2913
  * verification/notification fields is supplied, the API infers the other.
2779
2914
  * `DigitalCertificate` costs 0.5 credits, requires the feature plus a
2780
2915
  * signer `government_id`, and that signer must be alone in its step. The
2781
- * server derives the assignment method from placed template fields but
2782
- * does not yet reject unusable certificate/`collect` combinations, so the
2783
- * SDK temporarily refuses certificate signers on this template route.
2916
+ * server derives the assignment method from placed template fields and
2917
+ * rejects certificate signers when those fields produce a `collect`
2918
+ * assignment. Use a template without placed signer fields for certificate
2919
+ * signing.
2784
2920
  * `IdDocumentFaceMatchBasic` needs the ID Document + Face Match feature
2785
2921
  * and a valid CPF in `government_id`; estimate the per-signer fee first.
2786
2922
  * @param options - Optional `name`, `message`, `expires_at`,
2787
2923
  * `editor_fields`, `tags`.
2788
2924
  * @param options.name - Generated document display name.
2789
2925
  * @param options.message - Signing invitation message.
2790
- * @param options.expires_at - ISO-8601 signature deadline.
2926
+ * @param options.expires_at - ISO-8601 deadline: date-only (ends at 23:59
2927
+ * UTC), date-time without an offset (treated as UTC), or an offset-aware
2928
+ * date-time.
2791
2929
  * @param options.editor_fields - Template editor values as `{ field_id, value }` entries.
2792
2930
  * @param options.tags - Tag names attached to the generated document.
2793
2931
  * @param accountId - Override the client's default account ID.
2794
- * @returns The created document (an {@link IDocumentDetailsResponse} with
2795
- * `template_id` set and its `assignment` populated):
2932
+ * @returns The uploaded document. Assignment creation continues in the
2933
+ * background; follow `GET /documents/{documentId}` or webhooks until the
2934
+ * document becomes `pending_signature` or `failed`:
2796
2935
  * ```jsonc
2797
2936
  * {
2798
2937
  * "resource": "document",
@@ -2800,22 +2939,21 @@ var DocumentResource = class extends BaseResource {
2800
2939
  * "account_id": "acc_example",
2801
2940
  * "template_id": "103a0991a5cde83518e5672aa9aa",
2802
2941
  * "name": "Service agreement from template",
2803
- * "status": "pending_signature",
2804
- * "artifacts": { "original": "https://…/download/original", "thumbnail": "https://…/thumbnail" },
2942
+ * "status": "uploaded",
2943
+ * "artifacts": { "original": "https://…/download/original" },
2805
2944
  * "is_closed": false,
2806
2945
  * "signing_url": "https://app.assinafy.com.br/sign/19f675b7…",
2807
2946
  * "tags": [{ "id": "103a0992…", "name": "agreements", "color": null }],
2808
- * "assignment": { "id": "103a09a1…", "method": "virtual", "summary": { "signer_count": 1, "completed_count": 0 } },
2809
- * "pages": [{ "id": "103a0992…", "number": 1, "height": 1651, "width": 1275, "download_url": "https://…/download" }],
2947
+ * "assignment": null,
2948
+ * "pages": [],
2810
2949
  * "created_at": "2026-07-15T19:57:55Z",
2811
2950
  * "updated_at": "2026-07-15T19:59:33Z"
2812
2951
  * }
2813
2952
  * ```
2814
- * @throws {ValidationError} If `templateId` is missing, no account ID is
2815
- * available, or a signer uses `DigitalCertificate`. Certificate refusals
2816
- * have `errors.code === 'digital_certificate_requires_virtual_method'`.
2817
- * @throws {ApiError} `400` if the signers/roles are invalid or the template
2818
- * is not ready.
2953
+ * @throws {ValidationError} If `templateId`, an account ID, signer identity,
2954
+ * channel, order, deadline, editor field, or tag is invalid.
2955
+ * @throws {ApiError} `400` if the signers/roles are invalid, the template
2956
+ * is not ready, or placed signer fields conflict with `DigitalCertificate`.
2819
2957
  *
2820
2958
  * @example
2821
2959
  * ```ts
@@ -2832,11 +2970,13 @@ var DocumentResource = class extends BaseResource {
2832
2970
  if (options.message !== void 0 && typeof options.message !== "string") {
2833
2971
  throw new ValidationError("message must be a string");
2834
2972
  }
2835
- if (options.expires_at !== void 0) assertDateTime(options.expires_at, "expires_at");
2973
+ if (options.expires_at !== void 0) assertExpirationDate(options.expires_at, "expires_at");
2836
2974
  const editorFields = options.editor_fields === void 0 ? void 0 : normaliseTemplateEditorFields(options.editor_fields);
2837
2975
  if (options.tags !== void 0 && (!Array.isArray(options.tags) || options.tags.some((tag) => typeof tag !== "string" || !tag.trim()))) {
2838
2976
  throw new ValidationError("tags must be an array of non-empty tag names");
2839
2977
  }
2978
+ assertCreditCeiling(options.max_total_credits);
2979
+ const config = idempotencyConfig(options.idempotencyKey);
2840
2980
  const tmplId = this.requireId(templateId, "Template ID");
2841
2981
  const accId = this.accountId(accountId);
2842
2982
  const body = {
@@ -2847,12 +2987,14 @@ var DocumentResource = class extends BaseResource {
2847
2987
  if (options.expires_at !== void 0) body["expires_at"] = options.expires_at;
2848
2988
  if (editorFields !== void 0) body["editor_fields"] = editorFields;
2849
2989
  if (options.tags !== void 0) body["tags"] = [...options.tags];
2990
+ if (options.max_total_credits !== void 0) body["max_total_credits"] = options.max_total_credits;
2850
2991
  this.logger.info("Creating document from template", { templateId: tmplId, accountId: accId });
2851
2992
  return this.call(
2852
2993
  "Failed to create document from template",
2853
2994
  () => this.http.post(
2854
2995
  `/accounts/${this.pathSegment(accId, "Account ID")}/templates/${this.pathSegment(tmplId, "Template ID")}/documents`,
2855
- body
2996
+ body,
2997
+ config
2856
2998
  )
2857
2999
  );
2858
3000
  }
@@ -2862,10 +3004,8 @@ var DocumentResource = class extends BaseResource {
2862
3004
  *
2863
3005
  * A dry run: sends only `{ signers }` and consumes nothing. Use it to check
2864
3006
  * balances before calling {@link DocumentResource.createFromTemplate}.
2865
- * `DigitalCertificate` requires a provably `virtual` assignment. Because
2866
- * this route leaves method detection to the server, the SDK temporarily
2867
- * refuses certificate signers instead of returning a price for an
2868
- * assignment that may charge credits but cannot be completed.
3007
+ * `DigitalCertificate` adds 0.5 credits per signer plus notification cost;
3008
+ * the API returns `400` when the template has placed signer fields.
2869
3009
  *
2870
3010
  * Request body (`application/json`):
2871
3011
  * ```jsonc
@@ -2907,10 +3047,10 @@ var DocumentResource = class extends BaseResource {
2907
3047
  * "message": null
2908
3048
  * }
2909
3049
  * ```
2910
- * @throws {ValidationError} If `templateId` is missing, no account ID is
2911
- * available, or a signer uses `DigitalCertificate`. Certificate refusals
2912
- * have `errors.code === 'digital_certificate_requires_virtual_method'`.
2913
- * @throws {ApiError} If the API rejects the request.
3050
+ * @throws {ValidationError} If `templateId`, an account ID, role, or
3051
+ * channel is invalid.
3052
+ * @throws {ApiError} `400` if the role is invalid or placed signer fields
3053
+ * conflict with `DigitalCertificate`; `403` when a feature is unavailable.
2914
3054
  *
2915
3055
  * @example
2916
3056
  * ```ts
@@ -2988,13 +3128,14 @@ var DocumentResource = class extends BaseResource {
2988
3128
  * { "code": "uploaded", "deletable": false },
2989
3129
  * { "code": "metadata_processing", "deletable": false },
2990
3130
  * { "code": "metadata_ready", "deletable": true },
2991
- * { "code": "pending_signature", "deletable": true },
2992
- * { "code": "expired", "deletable": false },
3131
+ * { "code": "expired", "deletable": true },
2993
3132
  * { "code": "certificating", "deletable": false },
2994
3133
  * { "code": "certificated", "deletable": false },
2995
- * { "code": "rejected_by_signer", "deletable": false },
2996
- * { "code": "rejected_by_user", "deletable": false },
2997
- * { "code": "failed", "deletable": false }
3134
+ * { "code": "rejected_by_signer", "deletable": true },
3135
+ * { "code": "pending_signature", "deletable": true },
3136
+ * { "code": "pending_identity_review", "deletable": true }, // deleting cancels and notifies signers
3137
+ * { "code": "rejected_by_user", "deletable": true },
3138
+ * { "code": "failed", "deletable": true }
2998
3139
  * ]
2999
3140
  * ```
3000
3141
  * @throws {ApiError} If the API rejects the request.
@@ -3190,23 +3331,54 @@ function normaliseTemplateSigners(signers) {
3190
3331
  if (typeof signer.role_id !== "string" || !signer.role_id.trim()) {
3191
3332
  throw new ValidationError(`Template signer ${index + 1} requires role_id`);
3192
3333
  }
3193
- if (typeof signer.id !== "string" || !signer.id.trim()) {
3194
- throw new ValidationError(`Template signer ${index + 1} requires id`);
3195
- }
3196
3334
  validateAssignmentSignerOptions(signer, `Template signer ${index + 1}`);
3197
- const projected = { role_id: signer.role_id, id: signer.id };
3335
+ const projected = { role_id: signer.role_id };
3336
+ if (signer.id !== void 0) {
3337
+ if (typeof signer.id !== "string" || !signer.id.trim()) {
3338
+ throw new ValidationError(`Template signer ${index + 1} id must be non-empty`);
3339
+ }
3340
+ projected.id = signer.id;
3341
+ } else {
3342
+ if (!isEmail(signer.email)) {
3343
+ throw new ValidationError(`Template signer ${index + 1} requires a valid id or email`);
3344
+ }
3345
+ projected.email = signer.email;
3346
+ if (signer.name !== void 0) {
3347
+ if (typeof signer.name !== "string" || !signer.name.trim()) {
3348
+ throw new ValidationError(`Template signer ${index + 1} name must be non-empty`);
3349
+ }
3350
+ projected.name = signer.name;
3351
+ }
3352
+ if (signer.whatsapp_phone_number !== void 0) {
3353
+ if (!isE164PhoneNumber(signer.whatsapp_phone_number)) {
3354
+ throw new ValidationError(
3355
+ `Template signer ${index + 1} whatsapp_phone_number must be E.164`
3356
+ );
3357
+ }
3358
+ projected.whatsapp_phone_number = signer.whatsapp_phone_number;
3359
+ }
3360
+ }
3198
3361
  if (signer.verification_method !== void 0) {
3199
3362
  projected.verification_method = signer.verification_method;
3200
3363
  }
3201
3364
  if (signer.notification_methods !== void 0) {
3202
3365
  projected.notification_methods = [...signer.notification_methods];
3203
3366
  }
3367
+ if (signer.embedded !== void 0) projected.embedded = signer.embedded;
3204
3368
  if (signer.step !== void 0) projected.step = signer.step;
3205
3369
  return projected;
3206
3370
  });
3207
- validateDigitalCertificateMethod(void 0, normalised);
3208
3371
  return normalised;
3209
3372
  }
3373
+ var DETAIL_EXPANSIONS = /* @__PURE__ */ new Set(["envelope_id", "envelope"]);
3374
+ function renderConfig(options) {
3375
+ assertRecord(options, "render options");
3376
+ if (options.artifact === void 0) return { responseType: "arraybuffer" };
3377
+ if (options.artifact !== "certificated") {
3378
+ throw new ValidationError("artifact must be certificated when given");
3379
+ }
3380
+ return { responseType: "arraybuffer", params: { artifact: options.artifact } };
3381
+ }
3210
3382
  function normaliseTemplateEditorFields(fields) {
3211
3383
  if (!Array.isArray(fields)) {
3212
3384
  throw new ValidationError("editor_fields must be an array");
@@ -3245,7 +3417,6 @@ function normaliseTemplateCostSigners(signers) {
3245
3417
  }
3246
3418
  return descriptor;
3247
3419
  });
3248
- validateDigitalCertificateMethod(void 0, normalised);
3249
3420
  return normalised;
3250
3421
  }
3251
3422
  function validateWaitOption(value, name) {
@@ -3488,7 +3659,7 @@ var SignerResource = class extends BaseResource {
3488
3659
  "Failed to update signer",
3489
3660
  () => this.http.put(
3490
3661
  `/accounts/${this.pathSegment(id, "Account ID")}/signers/${this.pathSegment(sid, "Signer ID")}`,
3491
- normaliseSignerPayload(payload)
3662
+ { ...normaliseSignerPayload(payload), ...clearedContacts(payload) }
3492
3663
  )
3493
3664
  );
3494
3665
  }
@@ -3614,13 +3785,19 @@ function validateUpdateSignerPayload(payload) {
3614
3785
  if (payload.full_name !== void 0 && (typeof payload.full_name !== "string" || !payload.full_name.trim())) {
3615
3786
  throw new ValidationError("full_name cannot be empty");
3616
3787
  }
3617
- if (payload.email !== void 0 && !isEmail(payload.email)) {
3788
+ if (payload.email !== void 0 && !isClear(payload.email) && !isEmail(payload.email)) {
3618
3789
  throw new ValidationError("Invalid email address", { email: payload.email });
3619
3790
  }
3620
- const phone = payload.whatsapp_phone_number ?? payload.phone;
3621
- validateOptionalPhone(phone);
3791
+ const phone = updatePhone(payload);
3792
+ if (!isClear(phone)) validateOptionalPhone(phone);
3622
3793
  validateOptionalDigits(payload.cpf, "cpf");
3623
- validateOptionalDigits(payload.government_id, "government_id");
3794
+ if (!isClear(payload.government_id)) validateOptionalDigits(payload.government_id, "government_id");
3795
+ }
3796
+ function isClear(value) {
3797
+ return value === null || value === "";
3798
+ }
3799
+ function updatePhone(payload) {
3800
+ return payload.whatsapp_phone_number !== void 0 ? payload.whatsapp_phone_number : payload.phone;
3624
3801
  }
3625
3802
  function validateOptionalDigits(value, field) {
3626
3803
  if (value === void 0) return;
@@ -3651,6 +3828,18 @@ function normaliseSignerPayload(payload) {
3651
3828
  }
3652
3829
  return cleanParams(normalised);
3653
3830
  }
3831
+ function clearedContacts(payload) {
3832
+ const cleared = {};
3833
+ const candidates = {
3834
+ email: payload.email,
3835
+ whatsapp_phone_number: updatePhone(payload),
3836
+ government_id: payload.government_id
3837
+ };
3838
+ for (const [key, value] of Object.entries(candidates)) {
3839
+ if (isClear(value)) cleared[key] = value;
3840
+ }
3841
+ return cleared;
3842
+ }
3654
3843
 
3655
3844
  // src/support/stats.ts
3656
3845
  var MONTH_RE = /^\d{4}-(0[1-9]|1[0-2])$/;
@@ -3771,7 +3960,13 @@ var WorkspaceResource = class extends BaseResource {
3771
3960
  /**
3772
3961
  * Fetch a single workspace (`GET /accounts/{accountId}`).
3773
3962
  *
3963
+ * `expand: 'signing_features'` adds which signing methods the plan allows
3964
+ * (OAuth: `account:read`). A `false` feature makes creating or estimating an
3965
+ * assignment, template document or envelope with that method answer `403`
3966
+ * (`PlanRestricted`); check it before offering the method.
3967
+ *
3774
3968
  * @param accountId - The workspace to fetch.
3969
+ * @param options - `expand: 'signing_features'`.
3775
3970
  * @returns The workspace. `primary_color` / `secondary_color` are `null`
3776
3971
  * until brand colours are set (6-char hex, no `#`, when present):
3777
3972
  * ```jsonc
@@ -3784,22 +3979,154 @@ var WorkspaceResource = class extends BaseResource {
3784
3979
  * "notification_sender_type": "User",
3785
3980
  * "roles": ["owner"],
3786
3981
  * "is_delete_allowed": true,
3982
+ * "limits": { "webhook_endpoints": 3 },
3983
+ * "signing_features": { // only with expand: 'signing_features'
3984
+ * "DigitalCertificate": true,
3985
+ * "VerificationIdDocumentFaceMatchBasic": true,
3986
+ * "WhatsappNotification": true,
3987
+ * "VerificationBypass": false,
3988
+ * "Embed": true
3989
+ * },
3787
3990
  * "created_at": "2026-05-12T18:05:11Z"
3788
3991
  * }
3789
3992
  * ```
3790
- * @throws {ValidationError} If `accountId` is missing.
3791
- * @throws {ApiError} `404` if the workspace does not exist.
3993
+ * @throws {ValidationError} If `accountId` is missing or `expand` is unknown.
3994
+ * @throws {ApiError} `403` for another workspace's token, `404` if the
3995
+ * workspace does not exist.
3792
3996
  *
3793
3997
  * @example
3794
3998
  * ```ts
3795
- * const ws = await client.workspaces.get('acc_example');
3999
+ * const ws = await client.workspaces.get('acc_example', { expand: 'signing_features' });
4000
+ * if (ws.signing_features?.Embed) await client.embed.listOrigins();
3796
4001
  * ```
3797
4002
  */
3798
- async get(accountId) {
4003
+ async get(accountId, options = {}) {
3799
4004
  const id = this.requireId(accountId, "Account ID");
4005
+ assertRecord(options, "workspace options");
4006
+ if (options.expand !== void 0 && options.expand !== "signing_features") {
4007
+ throw new ValidationError("expand must be signing_features");
4008
+ }
4009
+ const config = options.expand === void 0 ? {} : { params: { expand: options.expand } };
3800
4010
  return this.call(
3801
4011
  "Failed to fetch workspace",
3802
- () => this.http.get(`/accounts/${this.pathSegment(id, "Account ID")}`)
4012
+ () => this.http.get(`/accounts/${this.pathSegment(id, "Account ID")}`, config)
4013
+ );
4014
+ }
4015
+ /**
4016
+ * Read the workspace's plan and balances (`GET /accounts/{accountId}/usage`).
4017
+ *
4018
+ * For a plan and credit meter; prices and payments are not included. Not
4019
+ * available to third-party OAuth applications (`403`), whatever their scopes.
4020
+ *
4021
+ * @param accountId - The workspace to read.
4022
+ * @returns The plan meter:
4023
+ * ```jsonc
4024
+ * {
4025
+ * "plan": "Pro", // null without a current plan
4026
+ * "documents_renewal_date": "2026-12-11",
4027
+ * "balances": {
4028
+ * "documents": { "balance": 97, "limit": 100, "spent": 3 },
4029
+ * "credits": { "balance": 12.5, "limit": null, "spent": 0.9 } // null: unlimited / not cycle-limited
4030
+ * }
4031
+ * }
4032
+ * ```
4033
+ * @throws {ValidationError} If `accountId` is missing.
4034
+ * @throws {ApiError} `403` for an OAuth application token, `404` for an unknown workspace.
4035
+ *
4036
+ * @example
4037
+ * ```ts
4038
+ * const { balances } = await client.workspaces.getUsage('acc_example');
4039
+ * ```
4040
+ */
4041
+ async getUsage(accountId) {
4042
+ const id = this.requireId(accountId, "Account ID");
4043
+ return this.call(
4044
+ "Failed to fetch account usage",
4045
+ () => this.http.get(`/accounts/${this.pathSegment(id, "Account ID")}/usage`)
4046
+ );
4047
+ }
4048
+ /**
4049
+ * Read which document alerts the workspace sends
4050
+ * (`GET /accounts/{accountId}/notification-policy`).
4051
+ *
4052
+ * Every member can read it; `editable` says whether the caller (an owner)
4053
+ * can change it. Not available to third-party OAuth applications.
4054
+ *
4055
+ * @param accountId - The workspace to read.
4056
+ * @returns The policy; every event key is present:
4057
+ * ```jsonc
4058
+ * {
4059
+ * "editable": true,
4060
+ * "owners_receive_all": false, // owners also get push alerts for members' documents
4061
+ * "events": {
4062
+ * "DocumentCompleted": true, "SignerDeclined": true, "DocumentCancelled": true,
4063
+ * "DocumentAboutToExpire": true, "DocumentExpired": true, "DocumentExpirationReset": true,
4064
+ * "DocumentProcessingFailed": true, "TemplateProcessingFailed": true, "SignerWhatsappFailed": true,
4065
+ * "ContractRenewalNotice": true, "ContractExpiring": true, "ContractExpired": true,
4066
+ * "ContractRenewed": true, "SignerViewed": true, "SignerSigned": true,
4067
+ * "SignerIdentityReviewRequired": true
4068
+ * }
4069
+ * }
4070
+ * ```
4071
+ * @throws {ValidationError} If `accountId` is missing.
4072
+ * @throws {ApiError} `403` for an OAuth application token.
4073
+ *
4074
+ * @example
4075
+ * ```ts
4076
+ * const policy = await client.workspaces.getNotificationPolicy('acc_example');
4077
+ * ```
4078
+ */
4079
+ async getNotificationPolicy(accountId) {
4080
+ const id = this.requireId(accountId, "Account ID");
4081
+ return this.call(
4082
+ "Failed to fetch notification policy",
4083
+ () => this.http.get(`/accounts/${this.pathSegment(id, "Account ID")}/notification-policy`)
4084
+ );
4085
+ }
4086
+ /**
4087
+ * Change which document alerts the workspace sends
4088
+ * (`PUT /accounts/{accountId}/notification-policy`).
4089
+ *
4090
+ * Owners only. Merges what is sent: an event set to `false` reaches nobody
4091
+ * in the workspace on any channel, whatever each member's preferences. The
4092
+ * identity-review e-mail is always sent, because the signer cannot continue
4093
+ * without it.
4094
+ *
4095
+ * @param accountId - The workspace to change.
4096
+ * @param payload - `events` keys to change and/or `owners_receive_all`.
4097
+ * @returns The full policy, as {@link WorkspaceResource.getNotificationPolicy} returns.
4098
+ * @throws {ValidationError} If nothing would change or a value is not a boolean.
4099
+ * @throws {ApiError} `400` for an unknown event code, `403` for a non-owner or
4100
+ * an OAuth application token.
4101
+ *
4102
+ * @example
4103
+ * ```ts
4104
+ * await client.workspaces.updateNotificationPolicy('acc_example', {
4105
+ * events: { SignerViewed: false },
4106
+ * owners_receive_all: true,
4107
+ * });
4108
+ * ```
4109
+ */
4110
+ async updateNotificationPolicy(accountId, payload) {
4111
+ const id = this.requireId(accountId, "Account ID");
4112
+ assertRecord(payload, "notification policy");
4113
+ const body = {};
4114
+ if (payload.events !== void 0) {
4115
+ assertBooleanMap(payload.events, "events");
4116
+ body["events"] = { ...payload.events };
4117
+ }
4118
+ if (payload.owners_receive_all !== void 0) {
4119
+ if (typeof payload.owners_receive_all !== "boolean") {
4120
+ throw new ValidationError("owners_receive_all must be a boolean");
4121
+ }
4122
+ body["owners_receive_all"] = payload.owners_receive_all;
4123
+ }
4124
+ if (Object.keys(body).length === 0) {
4125
+ throw new ValidationError("notification policy update must change events or owners_receive_all");
4126
+ }
4127
+ return this.call(
4128
+ "Failed to update notification policy",
4129
+ () => this.http.put(`/accounts/${this.pathSegment(id, "Account ID")}/notification-policy`, body)
3803
4130
  );
3804
4131
  }
3805
4132
  /**
@@ -3808,13 +4135,13 @@ var WorkspaceResource = class extends BaseResource {
3808
4135
  * Request body/query: none.
3809
4136
  *
3810
4137
  * @param accountId - Account whose public branding should be returned.
3811
- * @returns The unwrapped theme:
4138
+ * @returns The unwrapped theme. Colours fall back to the platform default:
3812
4139
  * ```jsonc
3813
4140
  * {
3814
4141
  * "account_name": "Acme Inc.",
3815
- * "primary_color": "aabbcc",
3816
- * "secondary_color": "112233",
3817
- * "logo": "https://api.assinafy.com.br/v1/accounts/account-id/logo"
4142
+ * "primary_color": "aabbcc", // button background
4143
+ * "secondary_color": "112233", // button text
4144
+ * "logo": "https://api.assinafy.com.br/v1/accounts/account-id/logo" // null without a logo
3818
4145
  * }
3819
4146
  * ```
3820
4147
  * @throws {ValidationError} If `accountId` is empty.
@@ -4146,6 +4473,8 @@ var WebhookResource = class extends BaseResource {
4146
4473
  * "document_processing_failed"
4147
4474
  * ],
4148
4475
  * "is_active": true,
4476
+ * "is_held": false,
4477
+ * "held_since": null,
4149
4478
  * "updated_at": "2026-07-18T02:36:02Z" // no `id` / `created_at` are returned
4150
4479
  * }
4151
4480
  * ```
@@ -4315,11 +4644,12 @@ var WebhookResource = class extends BaseResource {
4315
4644
  * (`GET /accounts/{accountId}/webhooks`). Pagination info (if any) is
4316
4645
  * attached in `meta`.
4317
4646
  *
4318
- * Assinafy treats any `2xx` response as success. It makes at most two
4319
- * attempts per event with a three-second wait. After ten consecutive failed
4320
- * events, the circuit breaker pauses normal delivery and sends roughly 5%
4321
- * as recovery checks until one succeeds. The stored `response_body` is
4322
- * truncated to 2,000 characters.
4647
+ * Assinafy treats any `2xx` response as success. Retriable failures get up
4648
+ * to six attempts about ten minutes apart. After ten failed deliveries in
4649
+ * a row, the endpoint is paused and probed after 3, 15 and 60 minutes, then
4650
+ * every six hours. A successful delivery or probe resumes the endpoint and
4651
+ * replays missed events oldest first. Response bodies are truncated to
4652
+ * 2,000 characters and delivery entries are retained for seven days.
4323
4653
  *
4324
4654
  * @param params - Optional filters and pagination:
4325
4655
  * - `endpoint_id` — only deliveries to this webhook endpoint.
@@ -4346,6 +4676,10 @@ var WebhookResource = class extends BaseResource {
4346
4676
  * // subject: <User>, account_id, created_at }
4347
4677
  * },
4348
4678
  * "delivered": true,
4679
+ * "webhook_id": "9f86d081884c7d659a2feaa0c55ad015",
4680
+ * "attempt": 1,
4681
+ * "kind": "scheduled",
4682
+ * "will_retry": false,
4349
4683
  * "http_status": 200,
4350
4684
  * "response_body": "{ ... }", // receiving endpoint body, max 2,000 chars
4351
4685
  * "error": null,
@@ -4438,11 +4772,14 @@ var WebhookResource = class extends BaseResource {
4438
4772
  * [
4439
4773
  * {
4440
4774
  * "id": "65f1c2a9b3e4d5f60718293a4b5c6d7e",
4775
+ * "resource": "activity_event_subscription",
4441
4776
  * "name": "ERP",
4442
4777
  * "url": "https://example.com/webhooks/assinafy",
4443
4778
  * "email": "ops@example.com",
4444
4779
  * "events": ["document_ready", "signer_signed_document"],
4445
4780
  * "is_active": true,
4781
+ * "is_held": false,
4782
+ * "held_since": null,
4446
4783
  * "signing_enabled": true, // deliveries carry a `webhook-signature` header
4447
4784
  * "created_at": "2026-10-01T12:00:00Z",
4448
4785
  * "updated_at": "2026-10-01T12:00:00Z"
@@ -4460,7 +4797,7 @@ var WebhookResource = class extends BaseResource {
4460
4797
  */
4461
4798
  async listEndpoints(accountId, params = {}) {
4462
4799
  assertRecord(params, "webhook endpoint filters");
4463
- if (params.url !== void 0) validateWebhookUrl(params.url);
4800
+ if (params.url !== void 0) validateWebhookUrl(params.url, true);
4464
4801
  const path2 = this.endpointsPath(accountId);
4465
4802
  return this.call(
4466
4803
  "Failed to list webhook endpoints",
@@ -4474,8 +4811,8 @@ var WebhookResource = class extends BaseResource {
4474
4811
  * An account can have 1 endpoint, or up to 3 on paid plans. Each endpoint
4475
4812
  * of a workspace needs a different `url`. With `signing_enabled: true` the
4476
4813
  * API returns a signing `secret` in this creation response. Store it now:
4477
- * OAuth applications cannot call {@link WebhookResource.getEndpointSecret}
4478
- * or rotate it later. When `events` is omitted or
4814
+ * OAuth applications cannot call {@link WebhookResource.getEndpointSecret},
4815
+ * but they can rotate a lost secret. When `events` is omitted or
4479
4816
  * empty, {@link DEFAULT_WEBHOOK_EVENTS} is sent. OAuth tokens need the
4480
4817
  * `webhooks:write` scope.
4481
4818
  *
@@ -4491,19 +4828,22 @@ var WebhookResource = class extends BaseResource {
4491
4828
  * }
4492
4829
  * ```
4493
4830
  *
4494
- * @param payload - Endpoint details. `url` (absolute HTTP(S)) and `email`
4831
+ * @param payload - Endpoint details. `url` (absolute HTTPS) and `email`
4495
4832
  * are required; `events`, `name`, `is_active` and `signing_enabled` are
4496
4833
  * optional.
4497
4834
  * @param accountId - Override the client's default account ID.
4498
4835
  * @returns The created endpoint:
4499
4836
  * ```jsonc
4500
4837
  * {
4838
+ * "resource": "activity_event_subscription",
4501
4839
  * "id": "65f1c2a9b3e4d5f60718293a4b5c6d7e",
4502
4840
  * "name": "ERP",
4503
4841
  * "url": "https://example.com/webhooks/assinafy",
4504
4842
  * "email": "ops@example.com",
4505
4843
  * "events": ["document_ready", "signer_signed_document"],
4506
4844
  * "is_active": true,
4845
+ * "is_held": false,
4846
+ * "held_since": null,
4507
4847
  * "signing_enabled": true, // deliveries carry a `webhook-signature` header
4508
4848
  * "secret": "whsec_c2VjcmV0", // only in this response when signing is enabled
4509
4849
  * "created_at": "2026-10-01T12:00:00Z",
@@ -4547,12 +4887,15 @@ var WebhookResource = class extends BaseResource {
4547
4887
  * @returns The endpoint:
4548
4888
  * ```jsonc
4549
4889
  * {
4890
+ * "resource": "activity_event_subscription",
4550
4891
  * "id": "65f1c2a9b3e4d5f60718293a4b5c6d7e",
4551
4892
  * "name": "ERP",
4552
4893
  * "url": "https://example.com/webhooks/assinafy",
4553
4894
  * "email": "ops@example.com",
4554
4895
  * "events": ["document_ready", "signer_signed_document"],
4555
4896
  * "is_active": true,
4897
+ * "is_held": false,
4898
+ * "held_since": null,
4556
4899
  * "signing_enabled": true, // deliveries carry a `webhook-signature` header
4557
4900
  * "created_at": "2026-10-01T12:00:00Z",
4558
4901
  * "updated_at": "2026-10-01T12:00:00Z"
@@ -4574,12 +4917,13 @@ var WebhookResource = class extends BaseResource {
4574
4917
  /**
4575
4918
  * Change a webhook endpoint
4576
4919
  * (`PUT /accounts/{accountId}/webhooks/endpoints/{endpointId}`). Only the
4577
- * fields sent are updated; `url` cannot be one another endpoint of the
4578
- * workspace already uses.
4920
+ * fields sent are updated; a changed `url` must be HTTPS, publicly
4921
+ * routable, and different from every other endpoint in the workspace.
4579
4922
  *
4580
4923
  * `signing_enabled: true` generates a secret if the endpoint has none and
4581
- * keeps the current one otherwise; `false` discards the secret. OAuth
4582
- * tokens need the `webhooks:write` scope.
4924
+ * keeps the current one otherwise; `false` discards the secret. When this
4925
+ * request turns signing on, the response includes the new `secret` once.
4926
+ * OAuth tokens need the `webhooks:write` scope.
4583
4927
  *
4584
4928
  * Request body (`application/json`, every field optional):
4585
4929
  * ```jsonc
@@ -4599,13 +4943,17 @@ var WebhookResource = class extends BaseResource {
4599
4943
  * @returns The updated endpoint:
4600
4944
  * ```jsonc
4601
4945
  * {
4946
+ * "resource": "activity_event_subscription",
4602
4947
  * "id": "65f1c2a9b3e4d5f60718293a4b5c6d7e",
4603
4948
  * "name": "ERP",
4604
4949
  * "url": "https://example.com/webhooks/assinafy",
4605
4950
  * "email": "ops@example.com",
4606
4951
  * "events": ["document_ready", "signer_signed_document"],
4607
4952
  * "is_active": true,
4953
+ * "is_held": false,
4954
+ * "held_since": null,
4608
4955
  * "signing_enabled": true, // deliveries carry a `webhook-signature` header
4956
+ * "secret": "whsec_c2VjcmV0", // only when this request turned signing on
4609
4957
  * "created_at": "2026-10-01T12:00:00Z",
4610
4958
  * "updated_at": "2026-10-01T12:00:00Z"
4611
4959
  * }
@@ -4669,7 +5017,7 @@ var WebhookResource = class extends BaseResource {
4669
5017
  * ```
4670
5018
  */
4671
5019
  async deleteEndpointByUrl(url, accountId) {
4672
- validateWebhookUrl(url);
5020
+ validateWebhookUrl(url, true);
4673
5021
  const path2 = this.endpointsPath(accountId);
4674
5022
  return this.callVoid(
4675
5023
  "Failed to delete webhook endpoint",
@@ -4707,31 +5055,98 @@ var WebhookResource = class extends BaseResource {
4707
5055
  /**
4708
5056
  * Replace an endpoint's signing secret and return the new one
4709
5057
  * (`POST /accounts/{accountId}/webhooks/endpoints/{endpointId}/secret/rotate`).
4710
- * The old secret stops working immediately: deliveries sent after the
4711
- * rotation are signed only with the new secret, so update the receiver at
4712
- * once. Not available to OAuth applications; use an API key.
5058
+ *
5059
+ * Without `keep_previous` the old secret stops at once: update the receiver
5060
+ * immediately. With `keep_previous: true` both secrets sign deliveries for
5061
+ * 24 hours (each delivery carries one `v1,` entry per secret, which
5062
+ * `webhookVerifier.verifySignature()` already accepts), so the receiver can
5063
+ * switch without dropping events; rotating again ends the overlap. OAuth
5064
+ * tokens need the `webhooks:write` scope.
4713
5065
  *
4714
5066
  * @param endpointId - The endpoint ID.
4715
5067
  * @param accountId - Override the client's default account ID.
5068
+ * @param options - `keep_previous`: keep the old secret signing for 24 hours.
4716
5069
  * @returns The new secret:
4717
5070
  * ```jsonc
4718
- * { "secret": "whsec_bmV3LWtleS1iYXNlNjQtZW5jb2RlZA==" }
5071
+ * {
5072
+ * "secret": "whsec_bmV3LWtleS1iYXNlNjQtZW5jb2RlZA==",
5073
+ * "previous_secret_expires_at": "2026-11-12T14:00:00Z" // only with keep_previous: true
5074
+ * }
4719
5075
  * ```
4720
- * @throws {ValidationError} If `endpointId` is empty or no account ID is
4721
- * available.
5076
+ * @throws {ValidationError} If `endpointId` is empty, no account ID is
5077
+ * available, or `keep_previous` is not a boolean.
4722
5078
  * @throws {ApiError} `400` when signing is disabled on the endpoint; `404`
4723
5079
  * if it does not exist.
4724
5080
  *
4725
5081
  * @example
4726
5082
  * ```ts
4727
- * const { secret } = await client.webhooks.rotateEndpointSecret(endpoint.id);
5083
+ * const { secret } = await client.webhooks.rotateEndpointSecret(endpoint.id, undefined, {
5084
+ * keep_previous: true,
5085
+ * });
4728
5086
  * await secretStore.put('assinafy-webhook-secret', secret);
4729
5087
  * ```
4730
5088
  */
4731
- async rotateEndpointSecret(endpointId, accountId) {
5089
+ async rotateEndpointSecret(endpointId, accountId, options = {}) {
5090
+ assertRecord(options, "rotation options");
5091
+ if (options.keep_previous !== void 0 && typeof options.keep_previous !== "boolean") {
5092
+ throw new ValidationError("keep_previous must be a boolean");
5093
+ }
4732
5094
  const path2 = `${this.endpointPath(endpointId, accountId)}/secret/rotate`;
5095
+ const body = options.keep_previous === void 0 ? void 0 : { keep_previous: options.keep_previous };
4733
5096
  this.logger.info("Rotating webhook endpoint secret");
4734
- return this.call("Failed to rotate webhook endpoint secret", () => this.http.post(path2));
5097
+ return this.call("Failed to rotate webhook endpoint secret", () => this.http.post(path2, body));
5098
+ }
5099
+ /**
5100
+ * Send the endpoint one `webhook_test` event now
5101
+ * (`POST /accounts/{accountId}/webhooks/endpoints/{endpointId}/test`).
5102
+ *
5103
+ * Signed and sent like any delivery, to this endpoint only, also while it is
5104
+ * paused or inactive; it neither lifts nor counts toward a pause. The
5105
+ * endpoint has 10 seconds to answer. The event's `payload` and `origin` are
5106
+ * `null`, and its `subject`/`object` describe the endpoint (never its
5107
+ * secret). Up to 10 tests per user every 10 minutes; OAuth tokens need
5108
+ * `webhooks:write`.
5109
+ *
5110
+ * @param endpointId - The endpoint ID.
5111
+ * @param accountId - Override the client's default account ID.
5112
+ * @returns The delivery attempt, also listed in the delivery history:
5113
+ * ```jsonc
5114
+ * {
5115
+ * "resource": "activity_dispatching_history",
5116
+ * "id": "1052b3c4d5e6f7a8b9c0d1e2f3a4",
5117
+ * "event": "webhook_test",
5118
+ * "activity_id": 8240001,
5119
+ * "endpoint_id": "1052b0e1f2a3b4c5d6e7f8a9b0c1",
5120
+ * "endpoint": "https://hooks.example.com/assinafy",
5121
+ * "payload": { // the event as delivered
5122
+ * "id": 8240001, "event": "webhook_test", "payload": null, "origin": null,
5123
+ * "account_id": "acc_example", "subject": { "type": "ActivityEventSubscription" }
5124
+ * },
5125
+ * "delivered": true,
5126
+ * "webhook_id": "msg_2v9TQ0a7",
5127
+ * "attempt": 1,
5128
+ * "kind": "manual",
5129
+ * "will_retry": false,
5130
+ * "duration_ms": 182,
5131
+ * "http_status": 200,
5132
+ * "response_body": "ok",
5133
+ * "error": null,
5134
+ * "created_at": "2026-11-11T14:00:00Z",
5135
+ * "updated_at": "2026-11-11T14:00:00Z"
5136
+ * }
5137
+ * ```
5138
+ * @throws {ValidationError} If `endpointId` is empty or no account ID is available.
5139
+ * @throws {ApiError} `404` for an unknown endpoint, `429` past 10 tests in 10 minutes.
5140
+ *
5141
+ * @example
5142
+ * ```ts
5143
+ * const attempt = await client.webhooks.testEndpoint(endpoint.id);
5144
+ * if (!attempt.delivered) console.warn(attempt.http_status, attempt.error);
5145
+ * ```
5146
+ */
5147
+ async testEndpoint(endpointId, accountId) {
5148
+ const path2 = `${this.endpointPath(endpointId, accountId)}/test`;
5149
+ return this.call("Failed to send webhook test delivery", () => this.http.post(path2));
4735
5150
  }
4736
5151
  endpointsPath(accountId) {
4737
5152
  const id = this.pathSegment(this.accountId(accountId), "Account ID");
@@ -4770,15 +5185,15 @@ function validateWebhookFields(payload, required) {
4770
5185
  throw new ValidationError("Webhook name must be a string");
4771
5186
  }
4772
5187
  }
4773
- function validateWebhookUrl(value) {
5188
+ function validateWebhookUrl(value, allowStoredHttp = false) {
4774
5189
  let url;
4775
5190
  try {
4776
5191
  url = new URL(value ?? "");
4777
5192
  } catch {
4778
- throw new ValidationError("Webhook URL must be an absolute HTTP(S) URL", { url: value });
5193
+ throw new ValidationError("Webhook URL must be an absolute HTTPS URL", { url: value });
4779
5194
  }
4780
- if (url.protocol !== "https:" && url.protocol !== "http:" || !url.hostname) {
4781
- throw new ValidationError("Webhook URL must be an absolute HTTP(S) URL", { url: value });
5195
+ if (url.protocol !== "https:" && !(allowStoredHttp && url.protocol === "http:") || !url.hostname) {
5196
+ throw new ValidationError("Webhook URL must be an absolute HTTPS URL", { url: value });
4782
5197
  }
4783
5198
  }
4784
5199
 
@@ -6018,7 +6433,10 @@ var OAuthResource = class extends BaseResource {
6018
6433
  * `['documents:read', 'documents:write', 'offline_access']`. Ask for the
6019
6434
  * minimum: the user approves all of them or none. Add `offline_access` to
6020
6435
  * receive a refresh token and `openid` to receive an `id_token`.
6021
- * `webhooks:write` permits subscription updates and inactivation.
6436
+ * `account:read` reads the workspace profile, theme, logo, KPIs, webhook
6437
+ * subscription and endpoints, and its signing features; `webhooks:write`
6438
+ * changes the subscription, manages endpoints, re-sends and tests
6439
+ * deliveries, and can obtain a new signing secret (signing on, or rotation).
6022
6440
  * @param options.authorizationEndpoint - Skip discovery by supplying the
6023
6441
  * endpoint yourself. Defaults to the discovered
6024
6442
  * `authorization_endpoint`.
@@ -6244,6 +6662,8 @@ var OAuthResource = class extends BaseResource {
6244
6662
  * @throws {OAuthError} `invalid_grant` for a spent, expired, replayed or
6245
6663
  * mismatched code; `invalid_client` for a bad `client_id`/`client_secret`;
6246
6664
  * `invalid_target` for a `resource` mismatch.
6665
+ * @throws {ApiError} `429` when the caller's IP is rate limited; token calls
6666
+ * are never retried automatically, so wait `rateLimit.retryAfter` seconds.
6247
6667
  *
6248
6668
  * @example
6249
6669
  * ```ts
@@ -6318,6 +6738,8 @@ var OAuthResource = class extends BaseResource {
6318
6738
  * @throws {OAuthError} `invalid_grant` when the refresh token was already
6319
6739
  * used, expired, or the user reconnected with different permissions — ask
6320
6740
  * the user to reconnect. `invalid_client` for bad client credentials.
6741
+ * @throws {ApiError} `429` when the caller's IP is rate limited (not retried
6742
+ * automatically: a replayed refresh token ends the connection).
6321
6743
  *
6322
6744
  * @example
6323
6745
  * ```ts
@@ -6602,6 +7024,11 @@ function toSearchParams(params) {
6602
7024
 
6603
7025
  // src/resources/fields.ts
6604
7026
  var FieldsResource = class extends BaseResource {
7027
+ signerHttp;
7028
+ constructor(http, defaultAccountId, logger, publicHttp) {
7029
+ super(http, defaultAccountId, logger);
7030
+ this.signerHttp = withoutCredentials(publicHttp ?? http);
7031
+ }
6605
7032
  /**
6606
7033
  * Create a field definition (`POST /accounts/{accountId}/fields`).
6607
7034
  *
@@ -6853,9 +7280,9 @@ var FieldsResource = class extends BaseResource {
6853
7280
  * Validate a single value against a field definition
6854
7281
  * (`POST /accounts/{accountId}/fields/{fieldId}/validate`).
6855
7282
  *
6856
- * The operation uses the client's API-key/Bearer authentication.
6857
- * `signerAccessCode` is a compatibility query and is sent as
6858
- * `signer-access-code` when supplied.
7283
+ * Without `signerAccessCode` the call uses the workspace credentials. With
7284
+ * it, the code is sent as the `signer-access-code` query on the
7285
+ * credential-free transport, as a custom signing UI does.
6859
7286
  *
6860
7287
  * Request body (`application/json`):
6861
7288
  * ```jsonc
@@ -6867,9 +7294,9 @@ var FieldsResource = class extends BaseResource {
6867
7294
  * @param fieldId - The field definition to validate against.
6868
7295
  * @param value - The value to check (validated against the field's
6869
7296
  * type/regex). Sent as `{ value }` in the request body.
6870
- * @param options - Account override and optional legacy `signerAccessCode`.
7297
+ * @param options - Account override and optional `signerAccessCode`.
6871
7298
  * @param options.accountId - Override the client's default workspace.
6872
- * @param options.signerAccessCode - Legacy signer code sent as a query parameter.
7299
+ * @param options.signerAccessCode - Authenticate as the signer instead of the workspace.
6873
7300
  * @returns The validation result. Response shape:
6874
7301
  * ```jsonc
6875
7302
  * {
@@ -6880,7 +7307,9 @@ var FieldsResource = class extends BaseResource {
6880
7307
  * ```
6881
7308
  * @throws {ValidationError} If `fieldId` or the account ID is missing, or
6882
7309
  * `value` is `undefined`.
6883
- * @throws {ApiError} If the API rejects the request.
7310
+ * @throws {ApiError} `400` for a malformed request, `403` when the code or
7311
+ * credentials cannot reach the workspace, `404` for a field outside it, `410`
7312
+ * when the signer's access code is closed.
6884
7313
  *
6885
7314
  * @example
6886
7315
  * ```ts
@@ -6902,7 +7331,7 @@ var FieldsResource = class extends BaseResource {
6902
7331
  const params = options.signerAccessCode ? { "signer-access-code": options.signerAccessCode } : void 0;
6903
7332
  return this.call(
6904
7333
  "Failed to validate field value",
6905
- () => this.http.post(
7334
+ () => this.transportFor(options.signerAccessCode).post(
6906
7335
  `/accounts/${this.pathSegment(id, "Account ID")}/fields/${this.pathSegment(fid, "Field ID")}/validate`,
6907
7336
  { value },
6908
7337
  { params }
@@ -6914,9 +7343,8 @@ var FieldsResource = class extends BaseResource {
6914
7343
  * (`POST /accounts/{accountId}/fields/validate-multiple`).
6915
7344
  *
6916
7345
  * The request body is the array of `{ field_id, value }` entries itself
6917
- * (not wrapped in an object). The optional `signerAccessCode` query is the
6918
- * same compatibility extension described on
6919
- * {@link FieldsResource.validate}.
7346
+ * (not wrapped in an object). `signerAccessCode` authenticates as described
7347
+ * on {@link FieldsResource.validate}.
6920
7348
  *
6921
7349
  * Request body (`application/json`):
6922
7350
  * ```jsonc
@@ -6929,9 +7357,9 @@ var FieldsResource = class extends BaseResource {
6929
7357
  * ```
6930
7358
  *
6931
7359
  * @param entries - Non-empty array of `{ field_id, value }` pairs.
6932
- * @param options - Account override and optional legacy `signerAccessCode`.
7360
+ * @param options - Account override and optional `signerAccessCode`.
6933
7361
  * @param options.accountId - Override the client's default workspace.
6934
- * @param options.signerAccessCode - Legacy signer code sent as a query parameter.
7362
+ * @param options.signerAccessCode - Authenticate as the signer instead of the workspace.
6935
7363
  * @returns One validation result per entry. Response shape:
6936
7364
  * ```jsonc
6937
7365
  * [
@@ -6940,7 +7368,7 @@ var FieldsResource = class extends BaseResource {
6940
7368
  * ]
6941
7369
  * ```
6942
7370
  * @throws {ValidationError} If `entries` is empty or the account ID is missing.
6943
- * @throws {ApiError} If the API rejects the request.
7371
+ * @throws {ApiError} `400`, `403`, `404` or `410`, as for {@link FieldsResource.validate}.
6944
7372
  *
6945
7373
  * @example
6946
7374
  * ```ts
@@ -6968,7 +7396,7 @@ var FieldsResource = class extends BaseResource {
6968
7396
  }));
6969
7397
  return this.call(
6970
7398
  "Failed to validate field values",
6971
- () => this.http.post(
7399
+ () => this.transportFor(options.signerAccessCode).post(
6972
7400
  `/accounts/${this.pathSegment(id, "Account ID")}/fields/validate-multiple`,
6973
7401
  body,
6974
7402
  { params }
@@ -7002,6 +7430,10 @@ var FieldsResource = class extends BaseResource {
7002
7430
  async listTypes() {
7003
7431
  return this.call("Failed to list field types", () => this.http.get("/field-types"));
7004
7432
  }
7433
+ /** A signer access code must never travel with the workspace credentials. */
7434
+ transportFor(signerAccessCode) {
7435
+ return signerAccessCode === void 0 ? this.http : this.signerHttp;
7436
+ }
7005
7437
  };
7006
7438
  function validateFieldPayload(payload) {
7007
7439
  if (payload.regex !== void 0 && payload.regex !== null && typeof payload.regex !== "string") {
@@ -7034,11 +7466,17 @@ var SignerDocumentsResource = class extends BaseResource {
7034
7466
  * (`GET /signers/{signer_id}/document?signer-access-code=…`).
7035
7467
  *
7036
7468
  * The signer-side counterpart of {@link DocumentResource.details}, authorised
7037
- * by the signer's access code rather than the workspace API key.
7469
+ * by the signer's access code rather than the workspace API key. Unlike
7470
+ * {@link SignerDocumentsResource.getAssignment} it does not record a view and
7471
+ * answers before a certificate or identity-check signer confirms their data,
7472
+ * so a link learns its envelope here.
7038
7473
  *
7039
7474
  * @param signerId - The signer whose current document is fetched.
7040
7475
  * @param signerAccessCode - The signer's access code, from their signing link.
7041
- * @returns The document in the full {@link IDocumentDetailsResponse} shape:
7476
+ * @param options - `expand: ['envelope']` adds the code's envelope (`{ id, name }`, or `null`).
7477
+ * @returns The {@link ISigningDocument}. Once the code is closed (30 minutes
7478
+ * after the signer is done) only `id`, `name`, `status`, `current_signer`,
7479
+ * `certified_copy` and `envelope` remain, with `is_signer_access_closed: true`:
7042
7480
  * ```jsonc
7043
7481
  * {
7044
7482
  * "resource": "document",
@@ -7061,26 +7499,38 @@ var SignerDocumentsResource = class extends BaseResource {
7061
7499
  * { "id": "103acccd5c73...", "number": 1, "height": 1651, "width": 1275,
7062
7500
  * "download_url": "https://api.assinafy.com.br/v1/documents/103acccd.../pages/103acccd5c73.../download" }
7063
7501
  * ],
7502
+ * "current_signer": {
7503
+ * "id": "19e6b92e7895332ed9708535d8c",
7504
+ * "full_name": "Example Signer",
7505
+ * "email": "signer@example.com",
7506
+ * "verification_method": "Email",
7507
+ * "notification_methods": ["Email"],
7508
+ * "completed": false
7509
+ * },
7510
+ * "is_signer_access_closed": false,
7511
+ * "certified_copy": { "available": false, "notification_method": "Email", "resends_left": null },
7512
+ * "envelope": { "id": "1052a1f0c3d4e5f6a7b8c9d0e1f2", "name": "Admission kit" }, // with expand
7064
7513
  * "created_at": "2026-07-19T14:56:54Z",
7065
7514
  * "updated_at": "2026-07-19T14:56:56Z"
7066
7515
  * }
7067
7516
  * ```
7068
7517
  * @throws {ValidationError} If `signerId` or `signerAccessCode` is missing.
7069
- * @throws {ApiError} If the access code is invalid or expired.
7518
+ * @throws {ApiError} `400` while the signer's step has not started, `401` for an
7519
+ * invalid code, `404` for an unknown signer.
7070
7520
  *
7071
7521
  * @example
7072
7522
  * ```ts
7073
- * const doc = await client.signerDocuments.getCurrent(signerId, accessCode);
7074
- * console.log(doc.status, doc.pages.length);
7523
+ * const doc = await client.signerDocuments.getCurrent(signerId, accessCode, { expand: ['envelope'] });
7524
+ * if (doc.is_signer_access_closed) console.log(doc.certified_copy.available);
7075
7525
  * ```
7076
7526
  */
7077
- async getCurrent(signerId, signerAccessCode) {
7527
+ async getCurrent(signerId, signerAccessCode, options = {}) {
7078
7528
  const sid = this.requireId(signerId, "Signer ID");
7079
7529
  const code = this.requireId(signerAccessCode, "signer-access-code");
7080
7530
  return this.call(
7081
7531
  "Failed to fetch current signer document",
7082
7532
  () => this.http.get(`/signers/${this.pathSegment(sid, "Signer ID")}/document`, {
7083
- params: { "signer-access-code": code }
7533
+ params: { "signer-access-code": code, ...signingReadParams(options) }
7084
7534
  })
7085
7535
  );
7086
7536
  }
@@ -7095,9 +7545,10 @@ var SignerDocumentsResource = class extends BaseResource {
7095
7545
  *
7096
7546
  * @param signerId - The signer whose documents are listed.
7097
7547
  * @param signerAccessCode - The signer's access code, from their signing link.
7098
- * @param params - Pagination: `page`, `per-page` (also accepts `per_page`).
7099
- * @returns Matching documents in the compact {@link IDocumentListItem} shape,
7100
- * with pagination in `meta`:
7548
+ * @param params - `envelope_id` (only that envelope's documents) and pagination:
7549
+ * `page`, `per-page` (also accepts `per_page`).
7550
+ * @returns Matching documents with pagination in `meta`. Each carries its
7551
+ * `assignment` (without `signing_urls` when read with a code) and `pages`:
7101
7552
  * ```jsonc
7102
7553
  * {
7103
7554
  * "data": [
@@ -7121,11 +7572,13 @@ var SignerDocumentsResource = class extends BaseResource {
7121
7572
  * }
7122
7573
  * ```
7123
7574
  * @throws {ValidationError} If `signerId` or `signerAccessCode` is missing.
7124
- * @throws {ApiError} If the access code is invalid or expired.
7575
+ * @throws {ApiError} `400` for a non-text `envelope_id` or a pending step,
7576
+ * `403` for another signer's code, `410` once the code is closed.
7125
7577
  *
7126
7578
  * @example
7127
7579
  * ```ts
7128
7580
  * const { data, meta } = await client.signerDocuments.list(signerId, accessCode, {
7581
+ * envelope_id: envelopeId,
7129
7582
  * 'per-page': 20,
7130
7583
  * });
7131
7584
  * ```
@@ -7152,8 +7605,8 @@ var SignerDocumentsResource = class extends BaseResource {
7152
7605
  * @param signerId - The signer whose documents are searched.
7153
7606
  * @param signerAccessCode - The signer's access code, from their signing link.
7154
7607
  * @param search - Free-text term matched against the document name.
7155
- * @returns Matching documents for that signer, in the compact
7156
- * {@link IDocumentListItem} shape, with pagination in `meta`:
7608
+ * @param params - `envelope_id`: only that envelope's documents.
7609
+ * @returns Matching documents for that signer, with pagination in `meta`:
7157
7610
  * ```jsonc
7158
7611
  * {
7159
7612
  * "data": [
@@ -7177,7 +7630,7 @@ var SignerDocumentsResource = class extends BaseResource {
7177
7630
  * }
7178
7631
  * ```
7179
7632
  * @throws {ValidationError} If `signerId` or `signerAccessCode` is missing.
7180
- * @throws {ApiError} If the access code is invalid or expired.
7633
+ * @throws {ApiError} `400`, `403` or `410`, as for {@link SignerDocumentsResource.list}.
7181
7634
  *
7182
7635
  * @example
7183
7636
  * ```ts
@@ -7188,16 +7641,13 @@ var SignerDocumentsResource = class extends BaseResource {
7188
7641
  * );
7189
7642
  * ```
7190
7643
  */
7191
- async search(signerId, signerAccessCode, search) {
7644
+ async search(signerId, signerAccessCode, search, params = {}) {
7192
7645
  const sid = this.requireId(signerId, "Signer ID");
7193
7646
  const code = this.requireId(signerAccessCode, "signer-access-code");
7194
- if (search !== void 0 && typeof search !== "string") {
7195
- throw new ValidationError("search must be a string");
7196
- }
7197
7647
  return this.callList(
7198
7648
  "Failed to search signer documents",
7199
7649
  () => this.http.get(`/signers/${this.pathSegment(sid, "Signer ID")}/documents/search`, {
7200
- params: cleanParams({ "signer-access-code": code, search })
7650
+ params: { "signer-access-code": code, ...searchParams(search, params) }
7201
7651
  })
7202
7652
  );
7203
7653
  }
@@ -7210,8 +7660,8 @@ var SignerDocumentsResource = class extends BaseResource {
7210
7660
  * code. No `signer-access-code` is sent.
7211
7661
  *
7212
7662
  * @param signerId - The signer whose documents are listed.
7213
- * @param params - Pagination: `page`, `per-page` (also accepts `per_page`).
7214
- * @returns Documents in the compact {@link IDocumentListItem} shape, with
7663
+ * @param params - `envelope_id` and pagination: `page`, `per-page` (also accepts `per_page`).
7664
+ * @returns Documents in the {@link IDocumentListItem} shape, with
7215
7665
  * pagination in `meta` (same shape as {@link SignerDocumentsResource.list}):
7216
7666
  * ```jsonc
7217
7667
  * {
@@ -7220,7 +7670,8 @@ var SignerDocumentsResource = class extends BaseResource {
7220
7670
  * }
7221
7671
  * ```
7222
7672
  * @throws {ValidationError} If `signerId` is missing.
7223
- * @throws {ApiError} `401` if the workspace credentials are rejected.
7673
+ * @throws {ApiError} `401` if the workspace credentials are rejected, `403` when a
7674
+ * role or OAuth scope refuses it, `404` for a signer outside the workspace.
7224
7675
  *
7225
7676
  * @example
7226
7677
  * ```ts
@@ -7229,11 +7680,11 @@ var SignerDocumentsResource = class extends BaseResource {
7229
7680
  */
7230
7681
  async listAsWorkspace(signerId, params = {}) {
7231
7682
  const sid = this.pathSegment(signerId, "Signer ID");
7683
+ const query = cleanListParams(params);
7684
+ delete query["signer-access-code"];
7232
7685
  return this.callList(
7233
7686
  "Failed to list signer documents",
7234
- () => this.workspaceHttp.get(`/signers/${sid}/documents`, {
7235
- params: cleanListParams(params)
7236
- })
7687
+ () => this.workspaceHttp.get(`/signers/${sid}/documents`, { params: query })
7237
7688
  );
7238
7689
  }
7239
7690
  /**
@@ -7246,53 +7697,45 @@ var SignerDocumentsResource = class extends BaseResource {
7246
7697
  *
7247
7698
  * @param signerId - The signer whose documents are searched.
7248
7699
  * @param search - Free-text term matched against the document name.
7700
+ * @param params - `envelope_id`: only that envelope's documents.
7249
7701
  * @returns Matching documents with pagination in `meta`, as
7250
7702
  * {@link SignerDocumentsResource.listAsWorkspace} returns.
7251
7703
  * @throws {ValidationError} If `signerId` is missing or `search` is not a string.
7252
- * @throws {ApiError} `401` if the workspace credentials are rejected.
7704
+ * @throws {ApiError} `401`, `403` or `404`, as for {@link SignerDocumentsResource.listAsWorkspace}.
7253
7705
  *
7254
7706
  * @example
7255
7707
  * ```ts
7256
7708
  * const { data } = await client.signerDocuments.searchAsWorkspace(signerId, 'agreement');
7257
7709
  * ```
7258
7710
  */
7259
- async searchAsWorkspace(signerId, search) {
7711
+ async searchAsWorkspace(signerId, search, params = {}) {
7260
7712
  const sid = this.pathSegment(signerId, "Signer ID");
7261
- if (search !== void 0 && typeof search !== "string") {
7262
- throw new ValidationError("search must be a string");
7263
- }
7264
7713
  return this.callList(
7265
7714
  "Failed to search signer documents",
7266
7715
  () => this.workspaceHttp.get(`/signers/${sid}/documents/search`, {
7267
- params: cleanParams({ search })
7716
+ params: searchParams(search, params)
7268
7717
  })
7269
7718
  );
7270
7719
  }
7271
7720
  /**
7272
- * Download one of a signer's document artifacts as raw bytes
7273
- * (`GET /signers/{signer_id}/documents/{document_id}/download/{artifact}`).
7721
+ * Download the original PDF a signer is asked to sign
7722
+ * (`GET /signers/{signer_id}/documents/{document_id}/download/original`).
7274
7723
  *
7275
- * The signer-side counterpart of {@link DocumentResource.download}: same
7276
- * artifact names, exposed by the API as a public signer-link endpoint. The
7277
- * optional access-code argument is retained for compatibility with deployed
7278
- * environments that still accept or require the legacy query parameter. The
7279
- * `certificated` and `bundle` exist only once the document is fully signed.
7280
- * `pades` exists only when the document had a Digital Certificate signer.
7281
- * A bundle contains original, certificated, and certificate-page artifacts,
7282
- * plus PAdES when present.
7724
+ * Only `original` is available with an access code; the certified copy is
7725
+ * sent to the signer instead (see {@link SignerDocumentsResource.resendCertifiedCopy}).
7726
+ * The API redirects a request it cannot serve to its expired-link page, so
7727
+ * the SDK does not follow redirects here: that case throws instead of
7728
+ * returning the page's HTML.
7283
7729
  *
7284
7730
  * @param signerId - The signer requesting the download.
7285
7731
  * @param documentId - The document to download.
7286
- * @param artifactName - Which artifact to fetch (`original`, `certificated`,
7287
- * `certificate-page`, `pades`, or `bundle`).
7288
- * @param signerAccessCode - Optional legacy signer access code. Omit it for
7289
- * the official public request shape.
7290
- * @returns The raw artifact bytes as a Node `Buffer` (PDF except for the
7291
- * ZIP `bundle`).
7292
- * @throws {ValidationError} If `signerId` or `documentId` is missing,
7293
- * `artifactName` is not one of the five documented names, or an explicitly
7294
- * supplied legacy `signerAccessCode` is blank.
7295
- * @throws {ApiError} `404` if the artifact does not exist yet.
7732
+ * @param artifactName - `original`, the only artifact a signer can download.
7733
+ * @param signerAccessCode - The signer's access code, from their signing link.
7734
+ * @returns The PDF bytes as a Node `Buffer`.
7735
+ * @throws {ValidationError} If an ID or the code is missing, or the artifact is not `original`.
7736
+ * @throws {ApiError} `302` when the code is missing or closed, `400` while the
7737
+ * signer's step has not started, `403` for another artifact, `404` for a
7738
+ * document the code does not reach, `410` once the code is closed.
7296
7739
  *
7297
7740
  * @example
7298
7741
  * ```ts
@@ -7300,6 +7743,7 @@ var SignerDocumentsResource = class extends BaseResource {
7300
7743
  * signerId,
7301
7744
  * documentId,
7302
7745
  * 'original',
7746
+ * accessCode,
7303
7747
  * );
7304
7748
  * await fs.promises.writeFile('to-sign.pdf', pdf);
7305
7749
  * ```
@@ -7307,16 +7751,15 @@ var SignerDocumentsResource = class extends BaseResource {
7307
7751
  async download(signerId, documentId, artifactName, signerAccessCode) {
7308
7752
  const sid = this.requireId(signerId, "Signer ID");
7309
7753
  const did = this.requireId(documentId, "Document ID");
7310
- assertDocumentArtifactName(artifactName);
7311
- const code = signerAccessCode === void 0 ? void 0 : this.requireId(signerAccessCode, "signer-access-code");
7754
+ if (artifactName !== "original") {
7755
+ throw new ValidationError("A signer can download only the original artifact");
7756
+ }
7757
+ const code = this.requireId(signerAccessCode, "signer-access-code");
7312
7758
  return this.callBinary(
7313
7759
  "Failed to download signer document",
7314
7760
  () => this.http.get(
7315
- `/signers/${this.pathSegment(sid, "Signer ID")}/documents/${this.pathSegment(did, "Document ID")}/download/${this.pathSegment(artifactName, "Artifact name")}`,
7316
- code === void 0 ? { responseType: "arraybuffer" } : {
7317
- responseType: "arraybuffer",
7318
- params: { "signer-access-code": code }
7319
- }
7761
+ `/signers/${this.pathSegment(sid, "Signer ID")}/documents/${this.pathSegment(did, "Document ID")}/download/original`,
7762
+ { ...BINARY_NO_REDIRECT, params: { "signer-access-code": code } }
7320
7763
  )
7321
7764
  );
7322
7765
  }
@@ -7562,10 +8005,15 @@ var SignerDocumentsResource = class extends BaseResource {
7562
8005
  * flag.
7563
8006
  *
7564
8007
  * @param signerAccessCode - The signer's access code, from their signing link.
7565
- * @returns Resolves when the API acknowledges the operation. The response
7566
- * envelope has no `data` field and is intentionally discarded.
8008
+ * @returns The signer's acceptance state, or `null` from deployments that
8009
+ * acknowledge without data:
8010
+ * ```jsonc
8011
+ * { "full_name": "Example Signer", "email": "signer@example.com", "has_accepted_terms": true }
8012
+ * ```
7567
8013
  * @throws {ValidationError} If `signerAccessCode` is missing.
7568
- * @throws {ApiError} If the access code is invalid or expired.
8014
+ * @throws {ApiError} `400` while the signer's verification is not done (e.g.
8015
+ * the e-mail code) or their step has not started, `401` for an invalid code,
8016
+ * `410` once the code is closed.
7569
8017
  *
7570
8018
  * @example
7571
8019
  * ```ts
@@ -7575,12 +8023,13 @@ var SignerDocumentsResource = class extends BaseResource {
7575
8023
  */
7576
8024
  async acceptTerms(signerAccessCode) {
7577
8025
  const code = this.requireId(signerAccessCode, "signer-access-code");
7578
- return this.callVoid(
8026
+ const data = await this.call(
7579
8027
  "Failed to accept terms",
7580
8028
  () => this.http.put("/signers/accept-terms", void 0, {
7581
8029
  params: { "signer-access-code": code }
7582
8030
  })
7583
8031
  );
8032
+ return data ?? null;
7584
8033
  }
7585
8034
  /**
7586
8035
  * Verify the signer's email or WhatsApp one-time password
@@ -7631,12 +8080,56 @@ var SignerDocumentsResource = class extends BaseResource {
7631
8080
  )
7632
8081
  );
7633
8082
  }
8083
+ /**
8084
+ * Confirm the signer's contact data before signing
8085
+ * (`PUT /documents/{documentId}/signers/confirm-data?signer-access-code=…`).
8086
+ *
8087
+ * Send the contact the signer's channel needs: `email` for e-mail
8088
+ * verification or notification, `whatsapp_phone_number` for WhatsApp. Each
8089
+ * is saved when the signer has none; otherwise it must be theirs, so it
8090
+ * cannot change the record. `has_accepted_terms: true` also records the
8091
+ * terms, which opens `getAssignment()` for a `DigitalCertificate` signer.
8092
+ * With an envelope code it acts on the document the route names. Only the
8093
+ * fields provided are sent.
8094
+ *
8095
+ * Request body (`application/json`):
8096
+ * ```jsonc
8097
+ * {
8098
+ * "email": "signer@example.com",
8099
+ * "has_accepted_terms": true
8100
+ * }
8101
+ * ```
8102
+ *
8103
+ * @param documentId - The document the signer is confirming data for.
8104
+ * @param signerAccessCode - The signer's access code, from their signing link.
8105
+ * @param payload - `email`, `whatsapp_phone_number` and `has_accepted_terms`.
8106
+ * `full_name`/`government_id` are forwarded only for older deployments.
8107
+ * @returns `null` on production, which answers `data: []`; older deployments
8108
+ * return the signer:
8109
+ * ```jsonc
8110
+ * { "resource": "signer", "id": "19e6b92e7895332ed9708535d8c", "full_name": "Example Signer",
8111
+ * "email": "signer@example.com", "whatsapp_phone_number": null, "has_accepted_terms": true }
8112
+ * ```
8113
+ * @throws {ValidationError} If `documentId` or `signerAccessCode` is missing,
8114
+ * or a supplied value is malformed.
8115
+ * @throws {ApiError} `400` when a contact the signer's methods need is missing,
8116
+ * invalid or not theirs, or their step has not started; `404` for a document
8117
+ * the code does not reach; `410` once the code is closed.
8118
+ *
8119
+ * @example
8120
+ * ```ts
8121
+ * await client.signerDocuments.confirmData(documentId, accessCode, {
8122
+ * email: 'signer@example.com',
8123
+ * has_accepted_terms: true,
8124
+ * });
8125
+ * ```
8126
+ */
7634
8127
  async confirmData(documentId, signerAccessCode, payload) {
7635
8128
  assertRecord(payload, "signer confirmation payload");
7636
8129
  validateConfirmDataPayload(payload);
7637
8130
  const did = this.requireId(documentId, "Document ID");
7638
8131
  const code = this.requireId(signerAccessCode, "signer-access-code");
7639
- return this.call(
8132
+ const data = await this.call(
7640
8133
  "Failed to confirm signer data",
7641
8134
  () => this.http.put(
7642
8135
  `/documents/${this.pathSegment(did, "Document ID")}/signers/confirm-data`,
@@ -7650,6 +8143,7 @@ var SignerDocumentsResource = class extends BaseResource {
7650
8143
  { params: { "signer-access-code": code } }
7651
8144
  )
7652
8145
  );
8146
+ return data !== null && typeof data === "object" && !Array.isArray(data) ? data : null;
7653
8147
  }
7654
8148
  async uploadSignature(signerAccessCode, image, options = {}) {
7655
8149
  const code = this.requireId(signerAccessCode, "signer-access-code");
@@ -7730,14 +8224,17 @@ var SignerDocumentsResource = class extends BaseResource {
7730
8224
  * the SDK never automatically replays this particular `GET` after a `429`.
7731
8225
  *
7732
8226
  * @param signerAccessCode - The signer's access code, from their signing link.
7733
- * @param hasAcceptedTerms - Maps to the `has_accepted_terms` query param
7734
- * (server default `false`); pass `true` once the signer has accepted terms.
7735
- * `false`/`undefined` is omitted only when `undefined` (an explicit `false`
7736
- * is still sent).
7737
- * @returns The document to sign, including its `assignment` (the
7738
- * {@link IAssignment} shape: `signers`, `items`, `summary`, `signing_urls`)
7739
- * from which the `itemId` / `fieldId` / `pageId` values for
7740
- * {@link SignerDocumentsResource.sign} are read:
8227
+ * @param options - `true`/`false` (the `has_accepted_terms` query, kept for
8228
+ * existing calls) or an options object:
8229
+ * `hasAcceptedTerms` (an explicit `false` is still sent), `expand:
8230
+ * ['envelope']` (adds the code's envelope), and `documentId` (with an
8231
+ * envelope code, open another document of that envelope the signer is on).
8232
+ * @returns The {@link ISigningDocument}. Its `assignment` carries only this
8233
+ * signer's items — no other signers, `signing_urls`, copy receivers or
8234
+ * `summary` — from which the `itemId` / `fieldId` / `pageId` values for
8235
+ * {@link SignerDocumentsResource.sign} are read. A closed code returns
8236
+ * only `id`, `name`, `status`, `current_signer`, `certified_copy` and
8237
+ * `envelope`, with `is_signer_access_closed: true`:
7741
8238
  * ```jsonc
7742
8239
  * {
7743
8240
  * "resource": "document",
@@ -7768,9 +8265,12 @@ var SignerDocumentsResource = class extends BaseResource {
7768
8265
  * { "id": "item-1", "page": { "id": "page-1", "number": 1, "height": 1651, "width": 1275,
7769
8266
  * "download_url": "https://..." }, "signer": { "id": "19e6b92e..." },
7770
8267
  * "field": { "id": "field-1", "type": "signature" }, "value": null, "completed": false }
7771
- * ],
7772
- * "summary": { "signer_count": 1, "completed_count": 0, "signers": [] }
8268
+ * ]
7773
8269
  * },
8270
+ * "current_signer": { "id": "19e6b92e7895332ed9708535d8c", "verification_method": "Email",
8271
+ * "notification_methods": ["Email"], "completed": false },
8272
+ * "is_signer_access_closed": false,
8273
+ * "certified_copy": { "available": false, "notification_method": "Email", "resends_left": null },
7774
8274
  * "pages": [
7775
8275
  * { "id": "103acccd5c73...", "number": 1, "height": 1651, "width": 1275,
7776
8276
  * "download_url": "https://api.assinafy.com.br/v1/documents/103acccd.../pages/103acccd5c73.../download" }
@@ -7779,53 +8279,211 @@ var SignerDocumentsResource = class extends BaseResource {
7779
8279
  * "updated_at": "2026-07-19T14:56:56Z"
7780
8280
  * }
7781
8281
  * ```
7782
- * @throws {ValidationError} If `signerAccessCode` is missing.
7783
- * @throws {ApiError} `400` when DigitalCertificate identity/terms are not
7784
- * confirmed; `401`/`403` if the access code is invalid or expired; `409`
7785
- * while the document is still being prepared.
8282
+ * @throws {ValidationError} If `signerAccessCode` is missing or an option is malformed.
8283
+ * @throws {ApiError} `400` when a DigitalCertificate signer has not confirmed
8284
+ * data and terms, the signer's step has not started, or `documentId` is
8285
+ * not an ID; `401` for an invalid code; `404` when `documentId` is outside
8286
+ * the code's envelope; `409` (`DocumentNotReady`) while the document is
8287
+ * still being prepared.
7786
8288
  *
7787
8289
  * @example
7788
8290
  * ```ts
7789
- * // query → ?signer-access-code=<code>&has_accepted_terms=true
7790
- * const assignment = await client.signerDocuments.getAssignment(accessCode, true);
8291
+ * // query → ?signer-access-code=<code>&has_accepted_terms=true&expand=envelope
8292
+ * const doc = await client.signerDocuments.getAssignment(accessCode, {
8293
+ * hasAcceptedTerms: true,
8294
+ * expand: ['envelope'],
8295
+ * });
7791
8296
  * ```
7792
8297
  */
7793
- async getAssignment(signerAccessCode, hasAcceptedTerms) {
8298
+ async getAssignment(signerAccessCode, options) {
7794
8299
  const code = this.requireId(signerAccessCode, "signer-access-code");
7795
- if (hasAcceptedTerms !== void 0 && typeof hasAcceptedTerms !== "boolean") {
8300
+ const read = typeof options === "object" && options !== null ? options : options === void 0 ? {} : { hasAcceptedTerms: options };
8301
+ assertRecord(read, "signing read options");
8302
+ if (read.hasAcceptedTerms !== void 0 && typeof read.hasAcceptedTerms !== "boolean") {
7796
8303
  throw new ValidationError("hasAcceptedTerms must be a boolean");
7797
8304
  }
8305
+ if (read.documentId !== void 0) this.requireId(read.documentId, "documentId");
7798
8306
  return this.call(
7799
8307
  "Failed to fetch signer assignment",
7800
8308
  () => this.http.get("/sign", {
7801
8309
  params: cleanParams({
7802
8310
  "signer-access-code": code,
7803
- has_accepted_terms: hasAcceptedTerms
8311
+ has_accepted_terms: read.hasAcceptedTerms,
8312
+ document_id: read.documentId,
8313
+ ...signingReadParams(read)
7804
8314
  })
7805
8315
  })
7806
8316
  );
7807
8317
  }
7808
8318
  /**
7809
- * Submit the signer's field values to sign an assignment
7810
- * (`POST /documents/{documentId}/assignments/{assignmentId}?signer-access-code=…`).
8319
+ * Read the sending workspace's brand for the signing page (`GET /sign/theme`).
7811
8320
  *
7812
- * The precise, field-by-field counterpart of
7813
- * {@link SignerDocumentsResource.signMultiple}: the `entries` array is sent as
7814
- * the request body, each entry addressing one item resolved from
7815
- * {@link SignerDocumentsResource.getAssignment}. The access code
7816
- * authenticates via the `signer-access-code` query param.
7817
- * Virtual signers must call {@link SignerDocumentsResource.confirmData}
7818
- * first. Digital Certificate signers cannot use this endpoint; use the
7819
- * certificate start/complete API flow instead.
8321
+ * Available before verification and after the document is deleted.
8322
+ * `primary_color` is the button background and `secondary_color` its text
8323
+ * (6-digit hex without `#`). The `logo` URL carries no access code: fetch it
8324
+ * with {@link SignerDocumentsResource.downloadLogo}.
7820
8325
  *
7821
- * Request body (`application/json`):
8326
+ * @param signerAccessCode - The signer's access code, from their signing link.
8327
+ * @returns The brand:
7822
8328
  * ```jsonc
7823
- * [
7824
- * {
7825
- * "itemId": "item_example",
7826
- * "fieldId": "field_example",
7827
- * "pageId": "page_example",
7828
- * "value": "Example Signer"
8329
+ * {
8330
+ * "account_name": "Example Ltda",
8331
+ * "primary_color": "1F6FEB",
8332
+ * "secondary_color": "FFFFFF",
8333
+ * "logo": "https://api.assinafy.com.br/v1/sign/logo" // null when the account has none
8334
+ * }
8335
+ * ```
8336
+ * @throws {ValidationError} If `signerAccessCode` is missing.
8337
+ * @throws {ApiError} `400` while the signer's step has not started, `401` for an invalid code.
8338
+ *
8339
+ * @example
8340
+ * ```ts
8341
+ * const theme = await client.signerDocuments.getTheme(accessCode);
8342
+ * ```
8343
+ */
8344
+ async getTheme(signerAccessCode) {
8345
+ const code = this.requireId(signerAccessCode, "signer-access-code");
8346
+ return this.call(
8347
+ "Failed to fetch signing theme",
8348
+ () => this.http.get("/sign/theme", { params: { "signer-access-code": code } })
8349
+ );
8350
+ }
8351
+ /**
8352
+ * Download the sending workspace's logo for the signing page (`GET /sign/logo`).
8353
+ *
8354
+ * @param signerAccessCode - The signer's access code, from their signing link.
8355
+ * @returns The image bytes (`image/*`).
8356
+ * @throws {ValidationError} If `signerAccessCode` is missing.
8357
+ * @throws {ApiError} `400` while the signer's step has not started, `401` for an
8358
+ * invalid code, `404` when the workspace has no logo.
8359
+ *
8360
+ * @example
8361
+ * ```ts
8362
+ * const logo = await client.signerDocuments.downloadLogo(accessCode);
8363
+ * ```
8364
+ */
8365
+ async downloadLogo(signerAccessCode) {
8366
+ const code = this.requireId(signerAccessCode, "signer-access-code");
8367
+ return this.callBinary(
8368
+ "Failed to download signing logo",
8369
+ () => this.http.get("/sign/logo", {
8370
+ responseType: "arraybuffer",
8371
+ params: { "signer-access-code": code }
8372
+ })
8373
+ );
8374
+ }
8375
+ /**
8376
+ * Send the signer their certified copy again (`POST /sign/certified-copy`).
8377
+ *
8378
+ * The copy goes, with a download link valid for 30 minutes, on the signature
8379
+ * request's channel and only to the contact the signing messages went to.
8380
+ * Works after the signer signed, also once the code is closed. E-mail: once
8381
+ * every 2 minutes and 10 times a day; WhatsApp: once per request.
8382
+ * `certified_copy` on {@link SignerDocumentsResource.getAssignment} says
8383
+ * whether it is available.
8384
+ *
8385
+ * @param signerAccessCode - The signer's access code, from their signing link.
8386
+ * @param documentId - With an envelope code, another document of that envelope.
8387
+ * @returns What was sent:
8388
+ * ```jsonc
8389
+ * { "available": true, "notification_method": "Email", "resends_left": null, "sent_to": "j***@example.com" }
8390
+ * ```
8391
+ * @throws {ValidationError} If the code or `documentId` is blank.
8392
+ * @throws {ApiError} `400` while the signer's step has not started, `404` for a
8393
+ * document outside the envelope, `409` when the signer has not signed or the
8394
+ * document is not certified, `429` within the resend limits, `500` when the
8395
+ * message could not be sent (nothing used up; ask again).
8396
+ *
8397
+ * @example
8398
+ * ```ts
8399
+ * const { sent_to } = await client.signerDocuments.resendCertifiedCopy(accessCode);
8400
+ * ```
8401
+ */
8402
+ async resendCertifiedCopy(signerAccessCode, documentId) {
8403
+ const code = this.requireId(signerAccessCode, "signer-access-code");
8404
+ const body = documentId === void 0 ? {} : { document_id: this.requireId(documentId, "documentId") };
8405
+ return this.call(
8406
+ "Failed to resend certified copy",
8407
+ () => this.http.post("/sign/certified-copy", body, { params: { "signer-access-code": code } })
8408
+ );
8409
+ }
8410
+ /**
8411
+ * Download the certified copy from a sent link (`GET /signers/downloads/{token}`).
8412
+ *
8413
+ * The token is the last path segment of the link in the completion and
8414
+ * re-send messages; it is a credential. Links last 7 days (completion) or
8415
+ * 30 minutes (re-send). An expired or unknown link redirects to the
8416
+ * expired-link page; the SDK does not follow it and throws instead.
8417
+ *
8418
+ * @param token - Link token.
8419
+ * @param artifact - `pades` for the PAdES version, when the document has one.
8420
+ * @returns The PDF bytes.
8421
+ * @throws {ValidationError} If `token` is blank or `artifact` is not `pades`.
8422
+ * @throws {ApiError} `302` for an expired or unknown link (ask for a new one
8423
+ * with {@link SignerDocumentsResource.resendCertifiedCopyFromLink}), `404`
8424
+ * for `pades` on a document without it.
8425
+ *
8426
+ * @example
8427
+ * ```ts
8428
+ * const pdf = await client.signerDocuments.downloadCertifiedCopy(token);
8429
+ * ```
8430
+ */
8431
+ async downloadCertifiedCopy(token, artifact) {
8432
+ if (artifact !== void 0 && artifact !== "pades") {
8433
+ throw new ValidationError("artifact must be pades when given");
8434
+ }
8435
+ const path2 = `/signers/downloads/${this.pathSegment(token, "Download token")}`;
8436
+ return this.callBinary(
8437
+ "Failed to download certified copy",
8438
+ () => this.http.get(artifact ? `${path2}/pades` : path2, BINARY_NO_REDIRECT)
8439
+ );
8440
+ }
8441
+ /**
8442
+ * Send the certified copy again from an expired link
8443
+ * (`POST /signers/downloads/{token}/resend`).
8444
+ *
8445
+ * Works with the link's token after it expired, on the same terms as
8446
+ * {@link SignerDocumentsResource.resendCertifiedCopy}.
8447
+ *
8448
+ * @param token - Link token, from the expired link.
8449
+ * @returns What was sent, as {@link SignerDocumentsResource.resendCertifiedCopy} returns.
8450
+ * @throws {ValidationError} If `token` is blank.
8451
+ * @throws {ApiError} `404` for an unknown link, `409` when nothing can be sent
8452
+ * from it (copy receiver, Bypass signer, no contact, not certified), `429`
8453
+ * within the resend limits.
8454
+ *
8455
+ * @example
8456
+ * ```ts
8457
+ * await client.signerDocuments.resendCertifiedCopyFromLink(token);
8458
+ * ```
8459
+ */
8460
+ async resendCertifiedCopyFromLink(token) {
8461
+ return this.call(
8462
+ "Failed to resend certified copy",
8463
+ () => this.http.post(`/signers/downloads/${this.pathSegment(token, "Download token")}/resend`)
8464
+ );
8465
+ }
8466
+ /**
8467
+ * Submit the signer's field values to sign an assignment
8468
+ * (`POST /documents/{documentId}/assignments/{assignmentId}?signer-access-code=…`).
8469
+ *
8470
+ * The precise, field-by-field counterpart of
8471
+ * {@link SignerDocumentsResource.signMultiple}: the `entries` array is sent as
8472
+ * the request body, each entry addressing one item resolved from
8473
+ * {@link SignerDocumentsResource.getAssignment}. The access code
8474
+ * authenticates via the `signer-access-code` query param.
8475
+ * Virtual signers must call {@link SignerDocumentsResource.confirmData}
8476
+ * first. Digital Certificate signers cannot use this endpoint; use the
8477
+ * certificate start/complete API flow instead.
8478
+ *
8479
+ * Request body (`application/json`):
8480
+ * ```jsonc
8481
+ * [
8482
+ * {
8483
+ * "itemId": "item_example",
8484
+ * "fieldId": "field_example",
8485
+ * "pageId": "page_example",
8486
+ * "value": "Example Signer"
7829
8487
  * }
7830
8488
  * ]
7831
8489
  * ```
@@ -7935,11 +8593,24 @@ function assertDocumentIds(documentIds) {
7935
8593
  throw new ValidationError("documentIds must be a non-empty array of non-empty IDs");
7936
8594
  }
7937
8595
  }
8596
+ var BINARY_NO_REDIRECT = { responseType: "arraybuffer", maxRedirects: 0 };
8597
+ var SIGNING_EXPANSIONS = /* @__PURE__ */ new Set(["envelope"]);
8598
+ function signingReadParams(options) {
8599
+ assertRecord(options, "signing read options");
8600
+ return expandParam(options.expand, SIGNING_EXPANSIONS);
8601
+ }
8602
+ function searchParams(search, params) {
8603
+ if (search !== void 0 && typeof search !== "string") {
8604
+ throw new ValidationError("search must be a string");
8605
+ }
8606
+ assertRecord(params, "search params");
8607
+ return cleanParams({ search, envelope_id: params.envelope_id });
8608
+ }
7938
8609
  function assertDeclineReason(declineReason) {
7939
8610
  if (typeof declineReason !== "string" || !declineReason.trim()) {
7940
8611
  throw new ValidationError("declineReason is required");
7941
8612
  }
7942
- if (declineReason.length > 2e3) {
8613
+ if ([...declineReason].length > 2e3) {
7943
8614
  throw new ValidationError("declineReason must be at most 2000 characters");
7944
8615
  }
7945
8616
  }
@@ -8156,12 +8827,70 @@ var UserResource = class extends BaseResource {
8156
8827
  * ```
8157
8828
  */
8158
8829
  async updateNotificationPreferences(preferences) {
8159
- validateNotificationPreferences(preferences);
8830
+ assertBooleanMap(preferences, "notification preferences", NOTIFICATION_PREFERENCE_KEYS);
8160
8831
  return this.call(
8161
8832
  "Failed to update notification preferences",
8162
8833
  () => this.http.put("/users/self/notification-preferences", preferences)
8163
8834
  );
8164
8835
  }
8836
+ /**
8837
+ * Read which document alerts reach the user as push notifications
8838
+ * (`GET /users/self/push-preferences`).
8839
+ *
8840
+ * Separate from the e-mail preferences. Every key is returned and defaults
8841
+ * to `true`; new keys may be added. Not available to third-party OAuth
8842
+ * applications (`403`).
8843
+ *
8844
+ * @returns The push preferences:
8845
+ * ```jsonc
8846
+ * {
8847
+ * "SignerViewed": true,
8848
+ * "SignerSigned": true,
8849
+ * "DocumentCompleted": true,
8850
+ * "SignerDeclined": true,
8851
+ * "DocumentAboutToExpire": true,
8852
+ * "DocumentExpired": true,
8853
+ * "SignerIdentityReviewRequired": true, // the review e-mail is always sent
8854
+ * "SignerWhatsappFailed": true
8855
+ * }
8856
+ * ```
8857
+ * @throws {ApiError} `401` for invalid credentials, `403` for an OAuth application token.
8858
+ *
8859
+ * @example
8860
+ * ```ts
8861
+ * const push = await client.users.getPushPreferences();
8862
+ * ```
8863
+ */
8864
+ async getPushPreferences() {
8865
+ return this.call(
8866
+ "Failed to fetch push preferences",
8867
+ () => this.http.get("/users/self/push-preferences")
8868
+ );
8869
+ }
8870
+ /**
8871
+ * Change which document alerts reach the user as push notifications
8872
+ * (`PUT /users/self/push-preferences`).
8873
+ *
8874
+ * Merges the keys sent; `false` stops that push in every workspace the user
8875
+ * belongs to. E-mail is not affected.
8876
+ *
8877
+ * @param preferences - Keys to change, e.g. `{ SignerViewed: false }`.
8878
+ * @returns The full map, as {@link UserResource.getPushPreferences} returns.
8879
+ * @throws {ValidationError} If the map is empty or a value is not a boolean.
8880
+ * @throws {ApiError} `400` for an unknown code, `403` for an OAuth application token.
8881
+ *
8882
+ * @example
8883
+ * ```ts
8884
+ * await client.users.updatePushPreferences({ SignerViewed: false });
8885
+ * ```
8886
+ */
8887
+ async updatePushPreferences(preferences) {
8888
+ assertBooleanMap(preferences, "push preferences");
8889
+ return this.call(
8890
+ "Failed to update push preferences",
8891
+ () => this.http.put("/users/self/push-preferences", { ...preferences })
8892
+ );
8893
+ }
8165
8894
  /**
8166
8895
  * List the user's enrolled two-factor methods (`GET /users/self/mfa`).
8167
8896
  *
@@ -8357,21 +9086,6 @@ var NOTIFICATION_PREFERENCE_KEYS = /* @__PURE__ */ new Set([
8357
9086
  "ContractExpired",
8358
9087
  "ContractRenewed"
8359
9088
  ]);
8360
- function validateNotificationPreferences(preferences) {
8361
- assertRecord(preferences, "notification preferences");
8362
- const entries = Object.entries(preferences);
8363
- if (entries.length === 0) {
8364
- throw new ValidationError("at least one notification preference is required");
8365
- }
8366
- for (const [key, value] of entries) {
8367
- if (!NOTIFICATION_PREFERENCE_KEYS.has(key)) {
8368
- throw new ValidationError(`unknown notification preference: ${key}`);
8369
- }
8370
- if (typeof value !== "boolean") {
8371
- throw new ValidationError(`${key} must be a boolean`);
8372
- }
8373
- }
8374
- }
8375
9089
 
8376
9090
  // src/resources/contracts.ts
8377
9091
  var CONTRACT_STATUSES = /* @__PURE__ */ new Set(["draft", "active", "expired", "terminated"]);
@@ -8501,14 +9215,14 @@ var ContractResource = class extends BaseResource {
8501
9215
  * }
8502
9216
  * ```
8503
9217
  * @throws {ValidationError} If an ID is missing or invalid.
8504
- * @throws {ApiError} `401` for invalid credentials, `404` when the document
8505
- * has no tracked terms, or `500` on a server error.
9218
+ * @throws {ApiError} `401` for invalid credentials, `404` (`code:
9219
+ * 'NoContractTerms'` when the document exists without terms), or `500`.
8506
9220
  *
8507
9221
  * @example
8508
9222
  * ```ts
8509
9223
  * const contract = await client.contracts.get(document.id);
8510
- * if (contract.resource === 'document_contract_amendment') {
8511
- * console.log(contract.parent_document_id);
9224
+ * if ('parent_document_id' in contract) {
9225
+ * console.log(contract.parent_document_id); // an amendment, renewal or termination
8512
9226
  * }
8513
9227
  * ```
8514
9228
  */
@@ -8567,9 +9281,10 @@ var ContractResource = class extends BaseResource {
8567
9281
  * }
8568
9282
  * ```
8569
9283
  * @throws {ValidationError} If the payload or an ID is malformed.
8570
- * @throws {ApiError} `400` for invalid terms, `403` when the plan does not
8571
- * include tracking, `404` for an unknown document, `409` after a concurrent
8572
- * change, or `500` on a server error.
9284
+ * @throws {ApiError} `400` for invalid terms (each in `fieldErrors`), `403`
9285
+ * (`PlanRestricted`) when the plan does not include tracking, `404` for an
9286
+ * unknown document or a `parent_document_id` outside the workspace, `409`
9287
+ * (`ContractChanged`) after a concurrent change, or `500` on a server error.
8573
9288
  *
8574
9289
  * @example
8575
9290
  * ```ts
@@ -8599,6 +9314,7 @@ var ContractResource = class extends BaseResource {
8599
9314
  *
8600
9315
  * @param documentId - Any document in the contract family.
8601
9316
  * @param accountId - Override the client's default account ID.
9317
+ * @param params - `expand: 'document'` embeds the root contract's document.
8602
9318
  * @returns The root contract and ordered instruments:
8603
9319
  * ```jsonc
8604
9320
  * {
@@ -8650,10 +9366,15 @@ var ContractResource = class extends BaseResource {
8650
9366
  * const family = await client.contracts.listRelated(amendmentDocument.id);
8651
9367
  * ```
8652
9368
  */
8653
- async listRelated(documentId, accountId) {
9369
+ async listRelated(documentId, accountId, params = {}) {
9370
+ assertRecord(params, "related contract params");
9371
+ if (params.expand !== void 0 && params.expand !== "document") {
9372
+ throw new ValidationError("expand must be document");
9373
+ }
9374
+ const config = params.expand === void 0 ? {} : { params: { expand: params.expand } };
8654
9375
  return this.call(
8655
9376
  "Failed to fetch related contracts",
8656
- () => this.http.get(`${this.contractPath(documentId, accountId)}/related`)
9377
+ () => this.http.get(`${this.contractPath(documentId, accountId)}/related`, config)
8657
9378
  );
8658
9379
  }
8659
9380
  /**
@@ -8956,15 +9677,708 @@ function validateExternalReferences(value) {
8956
9677
  }
8957
9678
  }
8958
9679
 
9680
+ // src/resources/envelopes.ts
9681
+ var EnvelopeResource = class extends BaseResource {
9682
+ /**
9683
+ * List the workspace's envelopes, most recent first
9684
+ * (`GET /accounts/{accountId}/envelopes`).
9685
+ *
9686
+ * @param params - Optional filters and pagination.
9687
+ * @param params.search - Part of the envelope name.
9688
+ * @param params.status - `open` (a document is still open) or `closed`
9689
+ * (every document signed, declined, cancelled, expired or failed).
9690
+ * @param params.page - One-based page number.
9691
+ * @param params.per-page - Page size: 20 by default, at most 50.
9692
+ * @param accountId - Override the client's default account ID.
9693
+ * @returns Envelopes and pagination metadata:
9694
+ * ```jsonc
9695
+ * {
9696
+ * "data": [{
9697
+ * "id": "1052a1f0c3d4e5f6a7b8c9d0e1f2",
9698
+ * "name": "Admission kit",
9699
+ * "message": "Please sign the documents below.",
9700
+ * "documents": [{
9701
+ * "id": "1052a1e9b8c7d6e5f4a3b2c1d0e9",
9702
+ * "position": 1,
9703
+ * "name": "contract.pdf",
9704
+ * "status": "pending_signature",
9705
+ * "artifacts": {
9706
+ * "original": "https://api.assinafy.com.br/v1/documents/1052a1e9b8c7d6e5f4a3b2c1d0e9/download/original",
9707
+ * "thumbnail": "https://api.assinafy.com.br/v1/documents/1052a1e9b8c7d6e5f4a3b2c1d0e9/thumbnail"
9708
+ * },
9709
+ * "signers": [{
9710
+ * "id": "1052a1d4c3b2a1f0e9d8c7b6a5f4",
9711
+ * "full_name": "Ana Souza",
9712
+ * "email": "ana@example.com",
9713
+ * "whatsapp_phone_number": null,
9714
+ * "completed": false,
9715
+ * "signed_at": null
9716
+ * }]
9717
+ * }],
9718
+ * "counts": { "pending_signature": 1 }, // documents per status; no envelope-level status
9719
+ * "signing_urls": [{
9720
+ * "signer_id": "1052a1d4c3b2a1f0e9d8c7b6a5f4",
9721
+ * "url": "https://app.assinafy.com.br/sign/1052a1e9b8c7d6e5f4a3b2c1d0e9?email=ana%40example.com",
9722
+ * "embedded": false
9723
+ * }],
9724
+ * "created_at": "2026-11-11T14:00:00Z"
9725
+ * }],
9726
+ * "meta": { "current_page": 1, "per_page": 20, "total": 1, "last_page": 1 }
9727
+ * }
9728
+ * ```
9729
+ * @throws {ValidationError} If no account ID is available.
9730
+ * @throws {ApiError} `400` for a filter of the wrong type, `403` for a token
9731
+ * without `documents:read`, `401` for invalid credentials.
9732
+ *
9733
+ * @example
9734
+ * ```ts
9735
+ * const { data: open } = await client.envelopes.list({ status: 'open' });
9736
+ * ```
9737
+ */
9738
+ async list(params = {}, accountId) {
9739
+ assertRecord(params, "envelope list params");
9740
+ if (params.status !== void 0 && params.status !== "open" && params.status !== "closed") {
9741
+ throw new ValidationError("status must be open or closed");
9742
+ }
9743
+ return this.callList(
9744
+ "Failed to list envelopes",
9745
+ () => this.http.get(this.envelopesPath(accountId), { params: cleanListParams(params) })
9746
+ );
9747
+ }
9748
+ /**
9749
+ * Read one envelope (`GET /accounts/{accountId}/envelopes/{envelopeId}`).
9750
+ *
9751
+ * @param envelopeId - Envelope ID.
9752
+ * @param accountId - Override the client's default account ID.
9753
+ * @returns The envelope: its documents in order (`position`), each with its
9754
+ * status and signers, the per-status `counts` and one `signing_urls` entry
9755
+ * per signer. Same shape as each item of {@link EnvelopeResource.list}.
9756
+ * @throws {ValidationError} If an ID is missing or invalid.
9757
+ * @throws {ApiError} `403` for a token without `documents:read`, `404` for an
9758
+ * unknown envelope.
9759
+ *
9760
+ * @example
9761
+ * ```ts
9762
+ * const envelope = await client.envelopes.get(envelopeId);
9763
+ * const pending = envelope.documents.filter((doc) => doc.status === 'pending_signature');
9764
+ * ```
9765
+ */
9766
+ async get(envelopeId, accountId) {
9767
+ return this.call(
9768
+ "Failed to fetch envelope",
9769
+ () => this.http.get(this.envelopePath(envelopeId, accountId))
9770
+ );
9771
+ }
9772
+ /**
9773
+ * Send several documents to the same signers at once
9774
+ * (`POST /accounts/{accountId}/envelopes`).
9775
+ *
9776
+ * Every document must be uploaded, `metadata_ready` and unassigned; every
9777
+ * signer must be on at least one document. Signers all sign at once (no
9778
+ * `step`); a `DigitalCertificate` signer signs only `virtual` documents and
9779
+ * is alone on each. One invitation goes to each signer, and `200` means the
9780
+ * envelope exists even when a send fails (see each signer's
9781
+ * `notification_history`). The envelope is charged as one document, each
9782
+ * signer's notification and identity check once, and each certificate
9783
+ * signature on every document it is made on. A refused request creates and
9784
+ * charges nothing. Pass an `idempotencyKey` to retry safely after a lost
9785
+ * response; the SDK then also replays a `429`.
9786
+ *
9787
+ * @param payload - Envelope definition.
9788
+ * @param payload.name - 1–255 characters without `<`; invitations use it in
9789
+ * place of document names.
9790
+ * @param payload.message - Optional message for every signer.
9791
+ * @param payload.max_total_credits - Refuse with `409 CreditCeilingExceeded`
9792
+ * above this many credits.
9793
+ * @param payload.signers - 1–20 `{ id, verification_method?, notification_methods?, embedded? }`.
9794
+ * @param payload.documents - 1–20 `{ id, signer_ids, method?, entries?, expires_at?, copy_receiver_ids? }`,
9795
+ * in envelope order. `collect` documents need `entries` whose signers are
9796
+ * exactly `signer_ids`.
9797
+ * @param options - `idempotencyKey`: new for each envelope you mean to create.
9798
+ * @param accountId - Override the client's default account ID.
9799
+ * @returns The created envelope (see {@link EnvelopeResource.list}). An
9800
+ * embedded or WhatsApp-only signer has `url: null` in `signing_urls`.
9801
+ * @throws {ValidationError} If the payload is malformed, a signer's channels
9802
+ * do not pair, or a `collect` document has no `entries`.
9803
+ * @throws {ApiError} `400` with `fieldErrors` naming each field at fault, `403`
9804
+ * (`PlanRestricted` or `InsufficientScope`), `409` (`CreditCeilingExceeded`,
9805
+ * or `IdempotencyKeyInUse` while the first request with that key runs).
9806
+ *
9807
+ * @example
9808
+ * ```ts
9809
+ * const envelope = await client.envelopes.create({
9810
+ * name: 'Admission kit',
9811
+ * signers: [{ id: signerId }],
9812
+ * documents: [
9813
+ * { id: contractId, signer_ids: [signerId] },
9814
+ * { id: policyId, signer_ids: [signerId], expires_at: '2026-12-31' },
9815
+ * ],
9816
+ * }, { idempotencyKey: crypto.randomUUID() });
9817
+ * ```
9818
+ */
9819
+ async create(payload, options = {}, accountId) {
9820
+ const body = buildEnvelopePayload(payload);
9821
+ assertRecord(options, "envelope options");
9822
+ const config = idempotencyConfig(options.idempotencyKey);
9823
+ this.logger.info("Creating envelope", {
9824
+ signerCount: body["signers"].length,
9825
+ documentCount: body["documents"].length
9826
+ });
9827
+ return this.call(
9828
+ "Failed to create envelope",
9829
+ () => this.http.post(this.envelopesPath(accountId), body, config)
9830
+ );
9831
+ }
9832
+ /**
9833
+ * Estimate what creating an envelope would cost
9834
+ * (`POST /accounts/{accountId}/envelopes/estimate-cost`).
9835
+ *
9836
+ * Takes the creation body and checks it the same way, creating and charging
9837
+ * nothing; `max_total_credits` is ignored. The envelope counts as one
9838
+ * document, each signer's notification and identity check once, and each
9839
+ * certificate signature per document.
9840
+ *
9841
+ * @param payload - The body {@link EnvelopeResource.create} would send.
9842
+ * @param accountId - Override the client's default account ID.
9843
+ * @returns A cost estimate:
9844
+ * ```jsonc
9845
+ * {
9846
+ * "documents": 1,
9847
+ * "credits": 1.45,
9848
+ * "needs_extra_document": false,
9849
+ * "extra_document_cost": 1,
9850
+ * "total_credits": 1.45,
9851
+ * "breakdown": [
9852
+ * { "code": "NotificationWhatsapp", "name": "WhatsApp notification", "cost": 0.45, "quantity": 1, "unit_cost": 0.45 },
9853
+ * { "code": "SignatureDigitalCertificate", "name": "Digital certificate signature", "cost": 1, "quantity": 2, "unit_cost": 0.5 }
9854
+ * ],
9855
+ * "document_balance": 97, // null when documents are not limited
9856
+ * "credit_balance": 10, // null when credits are not limited
9857
+ * "has_sufficient_resources": true,
9858
+ * "blocking_reason": null,
9859
+ * "message": null
9860
+ * }
9861
+ * ```
9862
+ * @throws {ValidationError} If the payload is malformed or a signer's channels do not pair.
9863
+ * @throws {ApiError} `400` for fields at fault, `403` (`PlanRestricted` or
9864
+ * `InsufficientScope`).
9865
+ *
9866
+ * @example
9867
+ * ```ts
9868
+ * const estimate = await client.envelopes.estimateCost(envelopeBody);
9869
+ * if (!estimate.has_sufficient_resources) console.warn(estimate.blocking_reason);
9870
+ * ```
9871
+ */
9872
+ async estimateCost(payload, accountId) {
9873
+ const body = buildEnvelopePayload(payload);
9874
+ return this.call(
9875
+ "Failed to estimate envelope cost",
9876
+ () => this.http.post(`${this.envelopesPath(accountId)}/estimate-cost`, body)
9877
+ );
9878
+ }
9879
+ /**
9880
+ * Rename an envelope, change its message or reorder its documents
9881
+ * (`PATCH /accounts/{accountId}/envelopes/{envelopeId}`).
9882
+ *
9883
+ * Send only what changes. Nothing is sent to anyone; later reminders,
9884
+ * cancellations and additions use the new values. Works on closed envelopes.
9885
+ *
9886
+ * @param envelopeId - Envelope ID.
9887
+ * @param payload - At least one change.
9888
+ * @param payload.name - 1–255 characters without `<`.
9889
+ * @param payload.message - New message, or `null` for none.
9890
+ * @param payload.document_ids - Every document of the envelope, each once, in the new order.
9891
+ * @param accountId - Override the client's default account ID.
9892
+ * @returns The updated envelope (see {@link EnvelopeResource.list}).
9893
+ * @throws {ValidationError} If nothing would change or a value is malformed.
9894
+ * @throws {ApiError} `400` for fields at fault, `403` for a token without
9895
+ * `documents:write`, `404` for an unknown envelope.
9896
+ *
9897
+ * @example
9898
+ * ```ts
9899
+ * await client.envelopes.update(envelopeId, { name: 'Admission kit 2026', message: null });
9900
+ * ```
9901
+ */
9902
+ async update(envelopeId, payload, accountId) {
9903
+ const body = buildUpdatePayload(payload);
9904
+ return this.call(
9905
+ "Failed to update envelope",
9906
+ () => this.http.patch(this.envelopePath(envelopeId, accountId), body)
9907
+ );
9908
+ }
9909
+ /**
9910
+ * Delete a closed envelope (`DELETE /accounts/{accountId}/envelopes/{envelopeId}`).
9911
+ *
9912
+ * Allowed once every document is certificated, declined, cancelled, expired
9913
+ * or failed; cancel it first otherwise. Its documents remain as ordinary
9914
+ * documents, and its `Idempotency-Key` no longer answers it.
9915
+ *
9916
+ * @param envelopeId - Envelope ID.
9917
+ * @param accountId - Override the client's default account ID.
9918
+ * @throws {ValidationError} If an ID is missing or invalid.
9919
+ * @throws {ApiError} `403` for a token without `documents:write`, `404` for an
9920
+ * unknown envelope, `409` (`EnvelopeOpen`) while a document is still open.
9921
+ *
9922
+ * @example
9923
+ * ```ts
9924
+ * await client.envelopes.cancel(envelopeId);
9925
+ * await client.envelopes.delete(envelopeId);
9926
+ * ```
9927
+ */
9928
+ async delete(envelopeId, accountId) {
9929
+ return this.callVoid(
9930
+ "Failed to delete envelope",
9931
+ () => this.http.delete(this.envelopePath(envelopeId, accountId))
9932
+ );
9933
+ }
9934
+ /**
9935
+ * Cancel every document that can still be cancelled
9936
+ * (`PUT /accounts/{accountId}/envelopes/{envelopeId}/cancel`).
9937
+ *
9938
+ * Each owner, signer and copy receiver is told once for the whole envelope.
9939
+ * Documents already closed, fully signed or being certificated are left as
9940
+ * they are. Safe to repeat: a second call cancels nothing.
9941
+ *
9942
+ * @param envelopeId - Envelope ID.
9943
+ * @param accountId - Override the client's default account ID.
9944
+ * @returns What happened to each document:
9945
+ * ```jsonc
9946
+ * [
9947
+ * { "id": "1052a1e9b8c7d6e5f4a3b2c1d0e9", "status": "cancelled", "cancelled": true },
9948
+ * { "id": "1052a1eaf9e8d7c6b5a4f3e2d1c0", "status": "certificated", "cancelled": false }
9949
+ * ]
9950
+ * ```
9951
+ * @throws {ValidationError} If an ID is missing or invalid.
9952
+ * @throws {ApiError} `403` for a token without `documents:write`, `404` for an
9953
+ * unknown envelope.
9954
+ *
9955
+ * @example
9956
+ * ```ts
9957
+ * const results = await client.envelopes.cancel(envelopeId);
9958
+ * ```
9959
+ */
9960
+ async cancel(envelopeId, accountId) {
9961
+ return this.call(
9962
+ "Failed to cancel envelope",
9963
+ () => this.http.put(`${this.envelopePath(envelopeId, accountId)}/cancel`)
9964
+ );
9965
+ }
9966
+ /**
9967
+ * Read the envelope's activity trail, newest first
9968
+ * (`GET /accounts/{accountId}/envelopes/{envelopeId}/activities`).
9969
+ *
9970
+ * Includes every document the envelope has had, including ones taken out;
9971
+ * each entry is a document activity that also names its document.
9972
+ *
9973
+ * @param envelopeId - Envelope ID.
9974
+ * @param params - `sort` (`-id`, the default, or `id` for oldest first),
9975
+ * `page`, and `per-page` (20 by default, at most 50).
9976
+ * @param accountId - Override the client's default account ID.
9977
+ * @returns Activity entries and pagination metadata:
9978
+ * ```jsonc
9979
+ * {
9980
+ * "data": [{
9981
+ * "id": 7731204,
9982
+ * "event": "signer_signed_document",
9983
+ * "message": "Ana Souza signed the document",
9984
+ * "payload": { "signer": { "id": "1052a1d4c3b2a1f0e9d8c7b6a5f4" } }, // same keys as that event's webhook
9985
+ * "origin": { "ip": "203.0.113.10", "user-agent": "Mozilla/5.0" },
9986
+ * "document_id": "1052a1e9b8c7d6e5f4a3b2c1d0e9",
9987
+ * "document_name": "contract.pdf",
9988
+ * "created_at": "2026-11-11T14:05:00Z"
9989
+ * }],
9990
+ * "meta": { "current_page": 1, "per_page": 20, "total": 1, "last_page": 1 }
9991
+ * }
9992
+ * ```
9993
+ * @throws {ValidationError} If an ID is missing or invalid.
9994
+ * @throws {ApiError} `403` for a token without `documents:read`, `404` for an
9995
+ * unknown envelope.
9996
+ *
9997
+ * @example
9998
+ * ```ts
9999
+ * const { data } = await client.envelopes.listActivities(envelopeId, { sort: 'id' });
10000
+ * ```
10001
+ */
10002
+ async listActivities(envelopeId, params = {}, accountId) {
10003
+ return this.callList(
10004
+ "Failed to fetch envelope activities",
10005
+ () => this.http.get(`${this.envelopePath(envelopeId, accountId)}/activities`, {
10006
+ params: cleanListParams(params)
10007
+ })
10008
+ );
10009
+ }
10010
+ /**
10011
+ * Download one artifact of every document as a zip
10012
+ * (`GET /accounts/{accountId}/envelopes/{envelopeId}/download/{artifactName}`).
10013
+ *
10014
+ * Files are named after their position (`1 - contract.pdf`); `bundle` gives
10015
+ * each document a folder. `certificated`, `certificate-page`, `pades` and
10016
+ * `bundle` include only the documents certified so far.
10017
+ *
10018
+ * @param envelopeId - Envelope ID.
10019
+ * @param artifactName - `original`, `certificated`, `certificate-page`, `pades` or `bundle`.
10020
+ * @param accountId - Override the client's default account ID.
10021
+ * @returns The zip archive bytes.
10022
+ * @throws {ValidationError} If an ID or the artifact name is invalid.
10023
+ * @throws {ApiError} `403` for a token without `documents:read`, `404` when no
10024
+ * document has the artifact.
10025
+ *
10026
+ * @example
10027
+ * ```ts
10028
+ * import { writeFile } from 'node:fs/promises';
10029
+ * await writeFile('envelope.zip', await client.envelopes.download(envelopeId, 'certificated'));
10030
+ * ```
10031
+ */
10032
+ async download(envelopeId, artifactName, accountId) {
10033
+ assertDocumentArtifactName(artifactName);
10034
+ return this.callBinary(
10035
+ "Failed to download envelope artifacts",
10036
+ () => this.http.get(
10037
+ `${this.envelopePath(envelopeId, accountId)}/download/${this.pathSegment(artifactName, "Artifact name")}`,
10038
+ { responseType: "arraybuffer" }
10039
+ )
10040
+ );
10041
+ }
10042
+ /**
10043
+ * Add a document to an open envelope for some of its signers
10044
+ * (`POST /accounts/{accountId}/envelopes/{envelopeId}/documents`).
10045
+ *
10046
+ * The document is checked as on creation and goes last. Only its
10047
+ * certificate signatures are charged; the chosen signers receive the
10048
+ * envelope invitation again, now listing it. No new signer can join, and an
10049
+ * envelope holds at most 20 documents.
10050
+ *
10051
+ * @param envelopeId - Envelope ID.
10052
+ * @param payload - `{ id, signer_ids, method?, entries?, expires_at?, copy_receiver_ids?, max_total_credits? }`.
10053
+ * @param accountId - Override the client's default account ID.
10054
+ * @returns The updated envelope (see {@link EnvelopeResource.list}).
10055
+ * @throws {ValidationError} If the document definition is malformed.
10056
+ * @throws {ApiError} `400` for fields at fault, `403` (`PlanRestricted` or
10057
+ * `InsufficientScope`), `409` (`EnvelopeClosed`, `CreditCeilingExceeded`).
10058
+ *
10059
+ * @example
10060
+ * ```ts
10061
+ * await client.envelopes.addDocument(envelopeId, { id: annexId, signer_ids: [signerId] });
10062
+ * ```
10063
+ */
10064
+ async addDocument(envelopeId, payload, accountId) {
10065
+ const body = buildEnvelopeDocument(payload, "document");
10066
+ assertCreditCeiling(payload.max_total_credits);
10067
+ if (payload.max_total_credits !== void 0) body["max_total_credits"] = payload.max_total_credits;
10068
+ return this.call(
10069
+ "Failed to add document to envelope",
10070
+ () => this.http.post(`${this.envelopePath(envelopeId, accountId)}/documents`, body)
10071
+ );
10072
+ }
10073
+ /**
10074
+ * Take an open document out of the envelope
10075
+ * (`DELETE /accounts/{accountId}/envelopes/{envelopeId}/documents/{documentId}`).
10076
+ *
10077
+ * The document is cancelled and its people are told; the other documents
10078
+ * carry on, and links sent from it keep opening them.
10079
+ *
10080
+ * @param envelopeId - Envelope ID.
10081
+ * @param documentId - Document to take out.
10082
+ * @param accountId - Override the client's default account ID.
10083
+ * @returns The updated envelope (see {@link EnvelopeResource.list}).
10084
+ * @throws {ValidationError} If an ID is missing or invalid.
10085
+ * @throws {ApiError} `403` for a token without `documents:write`, `404` when the
10086
+ * document is not in the envelope, `409` (`DocumentClosed`) when it can no
10087
+ * longer be cancelled.
10088
+ *
10089
+ * @example
10090
+ * ```ts
10091
+ * await client.envelopes.removeDocument(envelopeId, documentId);
10092
+ * ```
10093
+ */
10094
+ async removeDocument(envelopeId, documentId, accountId) {
10095
+ return this.call(
10096
+ "Failed to remove document from envelope",
10097
+ () => this.http.delete(
10098
+ `${this.envelopePath(envelopeId, accountId)}/documents/${this.pathSegment(documentId, "Document ID")}`
10099
+ )
10100
+ );
10101
+ }
10102
+ /**
10103
+ * Remind a signer of the whole envelope
10104
+ * (`PUT /accounts/{accountId}/envelopes/{envelopeId}/signers/{signerId}/resend`).
10105
+ *
10106
+ * One message from their first link, listing the documents still to sign;
10107
+ * paid channels are charged once. A document's own reminder
10108
+ * (`assignments.resendNotification`) still goes per document.
10109
+ *
10110
+ * @param envelopeId - Envelope ID.
10111
+ * @param signerId - Signer of the envelope.
10112
+ * @param accountId - Override the client's default account ID.
10113
+ * @returns Delivery acknowledgement:
10114
+ * ```jsonc
10115
+ * { "is_sent": true, "envelope_id": "1052a1f0c3d4e5f6a7b8c9d0e1f2", "signer_id": "1052a1d4c3b2a1f0e9d8c7b6a5f4" }
10116
+ * ```
10117
+ * @throws {ValidationError} If an ID is missing or invalid.
10118
+ * @throws {ApiError} `400` when the signer has nothing left to sign or credits
10119
+ * are short, `404` when the signer is not on the envelope, `409`
10120
+ * (`EnvelopeClosed`).
10121
+ *
10122
+ * @example
10123
+ * ```ts
10124
+ * await client.envelopes.resendNotification(envelopeId, signerId);
10125
+ * ```
10126
+ */
10127
+ async resendNotification(envelopeId, signerId, accountId) {
10128
+ return this.call(
10129
+ "Failed to remind envelope signer",
10130
+ () => this.http.put(
10131
+ `${this.envelopePath(envelopeId, accountId)}/signers/${this.pathSegment(signerId, "Signer ID")}/resend`
10132
+ )
10133
+ );
10134
+ }
10135
+ envelopesPath(accountId) {
10136
+ return `/accounts/${this.pathSegment(this.accountId(accountId), "Account ID")}/envelopes`;
10137
+ }
10138
+ envelopePath(envelopeId, accountId) {
10139
+ return `${this.envelopesPath(accountId)}/${this.pathSegment(envelopeId, "Envelope ID")}`;
10140
+ }
10141
+ };
10142
+ function buildEnvelopePayload(payload) {
10143
+ assertRecord(payload, "envelope payload");
10144
+ assertNonEmptyString(payload.name, "name");
10145
+ assertMessage(payload.message);
10146
+ assertCreditCeiling(payload.max_total_credits);
10147
+ const signers = records(payload.signers, "signers").map((signer, index) => {
10148
+ const label = `signers[${index}]`;
10149
+ assertNonEmptyString(signer["id"], `${label}.id`);
10150
+ validateAssignmentSignerOptions(signer, label);
10151
+ const projected = { id: signer["id"] };
10152
+ for (const key of ["verification_method", "notification_methods", "embedded", "step"]) {
10153
+ if (signer[key] !== void 0) projected[key] = signer[key];
10154
+ }
10155
+ return projected;
10156
+ });
10157
+ const documents = records(payload.documents, "documents").map((document, index) => buildEnvelopeDocument(document, `documents[${index}]`));
10158
+ const body = { name: payload.name, signers, documents };
10159
+ if (payload.message !== void 0) body["message"] = payload.message;
10160
+ if (payload.max_total_credits !== void 0) body["max_total_credits"] = payload.max_total_credits;
10161
+ return body;
10162
+ }
10163
+ function buildEnvelopeDocument(document, label) {
10164
+ assertRecord(document, label);
10165
+ const input = document;
10166
+ assertNonEmptyString(input.id, `${label}.id`);
10167
+ const method = input.method ?? "virtual";
10168
+ if (method !== "virtual" && method !== "collect") {
10169
+ throw new ValidationError(`${label}.method must be virtual or collect`);
10170
+ }
10171
+ const entries = input.entries === void 0 ? void 0 : normaliseAssignmentEntries(input.entries);
10172
+ if (method === "collect" && !entries?.length) {
10173
+ throw new ValidationError(`${label}.entries is required for collect documents`);
10174
+ }
10175
+ if (input.expires_at !== void 0 && input.expires_at !== null) {
10176
+ assertExpirationDate(input.expires_at, `${label}.expires_at`);
10177
+ }
10178
+ const projected = {
10179
+ id: input.id,
10180
+ method,
10181
+ signer_ids: idList(input.signer_ids, `${label}.signer_ids`)
10182
+ };
10183
+ if (entries !== void 0) projected["entries"] = entries;
10184
+ if (input.expires_at !== void 0) projected["expires_at"] = input.expires_at;
10185
+ if (input.copy_receiver_ids !== void 0) {
10186
+ projected["copy_receiver_ids"] = idList(input.copy_receiver_ids, `${label}.copy_receiver_ids`);
10187
+ }
10188
+ return projected;
10189
+ }
10190
+ function buildUpdatePayload(payload) {
10191
+ assertRecord(payload, "envelope update");
10192
+ const body = {};
10193
+ if (payload.name !== void 0) {
10194
+ assertNonEmptyString(payload.name, "name");
10195
+ body["name"] = payload.name;
10196
+ }
10197
+ if (payload.message !== void 0) {
10198
+ assertMessage(payload.message);
10199
+ body["message"] = payload.message;
10200
+ }
10201
+ if (payload.document_ids !== void 0) {
10202
+ body["document_ids"] = idList(payload.document_ids, "document_ids");
10203
+ }
10204
+ if (Object.keys(body).length === 0) {
10205
+ throw new ValidationError("envelope update must change name, message or document_ids");
10206
+ }
10207
+ return body;
10208
+ }
10209
+ function assertMessage(message) {
10210
+ if (message !== void 0 && message !== null && typeof message !== "string") {
10211
+ throw new ValidationError("message must be a string or null");
10212
+ }
10213
+ }
10214
+ function records(value, label) {
10215
+ if (!Array.isArray(value)) throw new ValidationError(`${label} must be an array`);
10216
+ value.forEach((item, index) => assertRecord(item, `${label}[${index}]`));
10217
+ return value;
10218
+ }
10219
+ function idList(value, label) {
10220
+ if (!Array.isArray(value) || value.some((id) => typeof id !== "string" || !id.trim())) {
10221
+ throw new ValidationError(`${label} must be an array of IDs`);
10222
+ }
10223
+ return [...value];
10224
+ }
10225
+
10226
+ // src/resources/embed.ts
10227
+ var EmbedResource = class extends BaseResource {
10228
+ /**
10229
+ * List the origins allowed to embed signing pages, oldest first
10230
+ * (`GET /accounts/{accountId}/embed-origins`).
10231
+ *
10232
+ * @param accountId - Override the client's default account ID.
10233
+ * @returns Registered origins:
10234
+ * ```jsonc
10235
+ * [{ "id": "1052c7d8e9f0a1b2c3d4e5f6a7b8", "origin": "https://app.example.com", "created_at": "2026-11-04T12:05:00Z" }]
10236
+ * ```
10237
+ * @throws {ValidationError} If no account ID is available.
10238
+ * @throws {ApiError} `403` (`PlanRestricted`, or an OAuth application token).
10239
+ *
10240
+ * @example
10241
+ * ```ts
10242
+ * const origins = await client.embed.listOrigins();
10243
+ * ```
10244
+ */
10245
+ async listOrigins(accountId) {
10246
+ return this.call("Failed to list embed origins", () => this.http.get(this.originsPath(accountId)));
10247
+ }
10248
+ /**
10249
+ * Allow one more origin to embed signing pages
10250
+ * (`POST /accounts/{accountId}/embed-origins`).
10251
+ *
10252
+ * An origin is an exact `https://host[:port]` (`http` only for `localhost`
10253
+ * and `127.0.0.1`) without path, query, fragment, credentials or wildcard;
10254
+ * the API lowercases the host and drops a default port. Up to 10 per account.
10255
+ *
10256
+ * @param origin - Origin of the page that will host the iframe.
10257
+ * @param accountId - Override the client's default account ID.
10258
+ * @returns The stored origin, e.g.
10259
+ * `{ "id": "1052c7d8e9f0a1b2c3d4e5f6a7b8", "origin": "https://app.example.com", "created_at": "2026-11-04T12:05:00Z" }`.
10260
+ * @throws {ValidationError} If `origin` is blank.
10261
+ * @throws {ApiError} `400` when it is invalid, already registered, or the
10262
+ * account has 10; `403` (`PlanRestricted`, or an OAuth application token).
10263
+ *
10264
+ * @example
10265
+ * ```ts
10266
+ * await client.embed.addOrigin('https://app.example.com');
10267
+ * ```
10268
+ */
10269
+ async addOrigin(origin, accountId) {
10270
+ assertNonEmptyString(origin, "origin");
10271
+ return this.call(
10272
+ "Failed to add embed origin",
10273
+ () => this.http.post(this.originsPath(accountId), { origin })
10274
+ );
10275
+ }
10276
+ /**
10277
+ * Replace an allowed origin, keeping its ID
10278
+ * (`PUT /accounts/{accountId}/embed-origins/{originId}`).
10279
+ *
10280
+ * @param originId - Embed origin ID.
10281
+ * @param origin - New origin, with the rules of {@link EmbedResource.addOrigin}.
10282
+ * @param accountId - Override the client's default account ID.
10283
+ * @returns The updated origin.
10284
+ * @throws {ValidationError} If an ID or the origin is blank.
10285
+ * @throws {ApiError} `400` for an invalid or duplicate origin, `403`, `404` for
10286
+ * an unknown origin ID.
10287
+ *
10288
+ * @example
10289
+ * ```ts
10290
+ * await client.embed.updateOrigin(originId, 'https://sign.example.com');
10291
+ * ```
10292
+ */
10293
+ async updateOrigin(originId, origin, accountId) {
10294
+ assertNonEmptyString(origin, "origin");
10295
+ return this.call(
10296
+ "Failed to update embed origin",
10297
+ () => this.http.put(this.originPath(originId, accountId), { origin })
10298
+ );
10299
+ }
10300
+ /**
10301
+ * Stop allowing an origin (`DELETE /accounts/{accountId}/embed-origins/{originId}`).
10302
+ *
10303
+ * Removing the last origin disables embedding: new sessions answer `409`
10304
+ * (`embed_origins_missing`).
10305
+ *
10306
+ * @param originId - Embed origin ID.
10307
+ * @param accountId - Override the client's default account ID.
10308
+ * @throws {ValidationError} If an ID is missing or invalid.
10309
+ * @throws {ApiError} `403`, or `404` for an unknown origin ID.
10310
+ *
10311
+ * @example
10312
+ * ```ts
10313
+ * await client.embed.deleteOrigin(originId);
10314
+ * ```
10315
+ */
10316
+ async deleteOrigin(originId, accountId) {
10317
+ return this.callVoid(
10318
+ "Failed to remove embed origin",
10319
+ () => this.http.delete(this.originPath(originId, accountId))
10320
+ );
10321
+ }
10322
+ /**
10323
+ * Mint a single-use embed URL for an `embedded` signer
10324
+ * (`POST /documents/{documentId}/assignments/{assignmentId}/signers/{signerId}/embed-sessions`).
10325
+ *
10326
+ * Load the URL in an iframe on a registered origin within 5 minutes;
10327
+ * opening it spends the token, so mint a new one each time the frame is
10328
+ * shown, including reloads. Treat it as a credential: hand it only to that
10329
+ * signer's page and never store or log it. Limited to 30 sessions per signer
10330
+ * per hour. For an envelope signer, mint on any of their documents still
10331
+ * waiting for them; the frame lists every document they still have to sign.
10332
+ * Frame events are UI hints: confirm the outcome from webhooks.
10333
+ *
10334
+ * @param documentId - Document ID.
10335
+ * @param assignmentId - Assignment ID.
10336
+ * @param signerId - Signer created with `embedded: true`.
10337
+ * @returns The session:
10338
+ * ```jsonc
10339
+ * {
10340
+ * "url": "https://app.assinafy.com.br/embed/3b1f0c7e9a2d4c58b6e1f4a07d93c2e85a1b0f6d4c7e2a9183b5d6f0e4c8a712",
10341
+ * "expires_at": "2026-11-04T12:05:00Z"
10342
+ * }
10343
+ * ```
10344
+ * @throws {ValidationError} If an ID is missing or invalid.
10345
+ * @throws {ApiError} `400` (`embed_not_enabled_for_signer`), `403`
10346
+ * (`PlanRestricted`), `404` for an unknown document, assignment or signer,
10347
+ * `409` (`already_signed`, `document_not_ready` — retry shortly,
10348
+ * `document_unavailable`, `embed_origins_missing`), `429` past 30 per hour.
10349
+ *
10350
+ * @example
10351
+ * ```ts
10352
+ * const { url } = await client.embed.createSession(document.id, assignment.id, signer.id);
10353
+ * response.json({ url }); // to the signer's browser only
10354
+ * ```
10355
+ */
10356
+ async createSession(documentId, assignmentId, signerId) {
10357
+ return this.call(
10358
+ "Failed to create embed session",
10359
+ () => this.http.post(
10360
+ `/documents/${this.pathSegment(documentId, "Document ID")}/assignments/${this.pathSegment(assignmentId, "Assignment ID")}/signers/${this.pathSegment(signerId, "Signer ID")}/embed-sessions`
10361
+ )
10362
+ );
10363
+ }
10364
+ originsPath(accountId) {
10365
+ return `/accounts/${this.pathSegment(this.accountId(accountId), "Account ID")}/embed-origins`;
10366
+ }
10367
+ originPath(originId, accountId) {
10368
+ return `${this.originsPath(accountId)}/${this.pathSegment(originId, "Embed origin ID")}`;
10369
+ }
10370
+ };
10371
+
8959
10372
  // src/support/webhook-verifier.ts
8960
10373
  import { createHmac, timingSafeEqual as timingSafeEqual2 } from "crypto";
8961
10374
  var DEFAULT_TOLERANCE_SECONDS = 300;
8962
10375
  var WebhookVerifier = class {
8963
10376
  webhookSecret;
8964
10377
  /**
8965
- * @param webhookSecret - The endpoint's `whsec_…` secret from
8966
- * `webhooks.getEndpointSecret()`. Omit it to keep verification disabled
8967
- * (every check returns `false`).
10378
+ * @param webhookSecret - The endpoint's `whsec_…` secret, as returned by
10379
+ * `webhooks.createEndpoint()` / `updateEndpoint()` when signing turns on,
10380
+ * `rotateEndpointSecret()`, or (API key only) `getEndpointSecret()`. Omit it
10381
+ * to keep verification disabled (every check returns `false`).
8968
10382
  *
8969
10383
  * @example
8970
10384
  * ```ts
@@ -9017,6 +10431,7 @@ var WebhookVerifier = class {
9017
10431
  const [version, signature] = entry.split(",", 2);
9018
10432
  if (version !== "v1" || !signature) return false;
9019
10433
  const actual = Buffer.from(signature, "base64");
10434
+ if (actual.toString("base64") !== signature) return false;
9020
10435
  return actual.length === expected.length && timingSafeEqual2(actual, expected);
9021
10436
  });
9022
10437
  }
@@ -9144,6 +10559,8 @@ var AssinafyClient = class _AssinafyClient {
9144
10559
  signerDocuments;
9145
10560
  users;
9146
10561
  contracts;
10562
+ envelopes;
10563
+ embed;
9147
10564
  webhookVerifier;
9148
10565
  /**
9149
10566
  * Create a client. Supply `apiKey` (preferred, sent as `X-Api-Key`) or a
@@ -9253,7 +10670,12 @@ var AssinafyClient = class _AssinafyClient {
9253
10670
  this.logger,
9254
10671
  this.publicAxiosInstance
9255
10672
  );
9256
- this.fields = new FieldsResource(this.axiosInstance, this.defaultAccountId, this.logger);
10673
+ this.fields = new FieldsResource(
10674
+ this.axiosInstance,
10675
+ this.defaultAccountId,
10676
+ this.logger,
10677
+ this.publicAxiosInstance
10678
+ );
9257
10679
  this.signerDocuments = new SignerDocumentsResource(
9258
10680
  this.axiosInstance,
9259
10681
  this.defaultAccountId,
@@ -9266,6 +10688,8 @@ var AssinafyClient = class _AssinafyClient {
9266
10688
  this.defaultAccountId,
9267
10689
  this.logger
9268
10690
  );
10691
+ this.envelopes = new EnvelopeResource(this.axiosInstance, this.defaultAccountId, this.logger);
10692
+ this.embed = new EmbedResource(this.axiosInstance, this.defaultAccountId, this.logger);
9269
10693
  this.webhookVerifier = new WebhookVerifier(this.webhookSecret);
9270
10694
  }
9271
10695
  /**
@@ -9370,8 +10794,9 @@ var AssinafyClient = class _AssinafyClient {
9370
10794
  * the API; only `collect` assignments require pre-rendered pages.
9371
10795
  * @param options.waitOptions - Optional `maxWaitMs` / `pollIntervalMs`
9372
10796
  * forwarded to {@link DocumentResource.waitUntilReady}.
9373
- * @param options.expiresAt - Optional ISO-8601 assignment expiry, e.g.
9374
- * `'2026-08-01T00:00:00Z'`.
10797
+ * @param options.expiresAt - Optional ISO-8601 assignment expiry. A date
10798
+ * ends at 23:59 UTC; a date-time without an offset is interpreted as UTC;
10799
+ * an explicit offset is honored.
9375
10800
  * @param options.copyReceivers - Optional existing signer IDs (not email
9376
10801
  * addresses) that receive a copy. See the caveat on
9377
10802
  * {@link ICreateAssignmentPayload.copy_receivers}; some plans silently drop
@@ -9437,7 +10862,7 @@ var AssinafyClient = class _AssinafyClient {
9437
10862
  * });
9438
10863
  * console.log(document.status); // usually 'pending_signature'
9439
10864
  * console.log(signer_ids.length); // 2
9440
- * console.log(assignment.signing_urls?.length); // one protected link per signer
10865
+ * console.log(assignment.signing_urls?.length); // one entry per notified signer; url is null for embedded or WhatsApp-only signers
9441
10866
  * ```
9442
10867
  */
9443
10868
  async uploadAndRequestSignatures(options) {
@@ -9457,7 +10882,7 @@ var AssinafyClient = class _AssinafyClient {
9457
10882
  if (options.metadata !== void 0) {
9458
10883
  assertRecord(options.metadata, "metadata");
9459
10884
  }
9460
- if (options.expiresAt !== void 0) assertDateTime(options.expiresAt, "expiresAt");
10885
+ if (options.expiresAt !== void 0) assertExpirationDate(options.expiresAt, "expiresAt");
9461
10886
  if (options.copyReceivers !== void 0 && (!Array.isArray(options.copyReceivers) || options.copyReceivers.some(
9462
10887
  (id) => typeof id !== "string" || id.trim().length === 0
9463
10888
  ))) {
@@ -9695,6 +11120,8 @@ export {
9695
11120
  DEFAULT_WEBHOOK_EVENTS,
9696
11121
  DIGITAL_CERTIFICATE_REQUIRES_VIRTUAL_METHOD,
9697
11122
  DocumentResource,
11123
+ EmbedResource,
11124
+ EnvelopeResource,
9698
11125
  FieldsResource,
9699
11126
  MAX_LIST_PAGE_SIZE,
9700
11127
  MAX_UPLOAD_BYTES,