@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.js CHANGED
@@ -39,6 +39,8 @@ __export(index_exports, {
39
39
  DEFAULT_WEBHOOK_EVENTS: () => DEFAULT_WEBHOOK_EVENTS,
40
40
  DIGITAL_CERTIFICATE_REQUIRES_VIRTUAL_METHOD: () => DIGITAL_CERTIFICATE_REQUIRES_VIRTUAL_METHOD,
41
41
  DocumentResource: () => DocumentResource,
42
+ EmbedResource: () => EmbedResource,
43
+ EnvelopeResource: () => EnvelopeResource,
42
44
  FieldsResource: () => FieldsResource,
43
45
  MAX_LIST_PAGE_SIZE: () => MAX_LIST_PAGE_SIZE,
44
46
  MAX_UPLOAD_BYTES: () => MAX_UPLOAD_BYTES,
@@ -94,6 +96,24 @@ var AssinafyError = class extends Error {
94
96
  var ApiError = class _ApiError extends AssinafyError {
95
97
  statusCode;
96
98
  responseData;
99
+ /**
100
+ * Machine-readable refusal code from the error body, on the refusals a
101
+ * client can act on: `PlanRestricted` (offer the upgrade, don't retry),
102
+ * `InsufficientScope`, `DocumentNotReady`, `CreditCeilingExceeded`,
103
+ * `IdempotencyKeyInUse`, `EnvelopeOpen`, `EnvelopeClosed`, `DocumentClosed`,
104
+ * `ContractChanged`, `NoContractTerms`, `TagInUse`, `embed_origins_missing`, ….
105
+ * `undefined` when the body has none.
106
+ *
107
+ * @example
108
+ * ```ts
109
+ * if (error instanceof ApiError && error.code === 'IdempotencyKeyInUse') {
110
+ * await sleep(1000); // the first request with this key is still running
111
+ * }
112
+ * ```
113
+ */
114
+ code;
115
+ /** Each field a `400` refused, in the order the API reports them. */
116
+ fieldErrors;
97
117
  /**
98
118
  * Parsed `WWW-Authenticate` challenge, when the response carried one.
99
119
  *
@@ -101,8 +121,8 @@ var ApiError = class _ApiError extends AssinafyError {
101
121
  * means the OAuth token is valid but was never granted that permission:
102
122
  * send the user through the authorization flow again asking for the scope
103
123
  * named in `scope`. A `403` without a challenge has a different cause —
104
- * another workspace, the user's role, or a surface OAuth tokens never
105
- * reach — and reconnecting will not fix it.
124
+ * another workspace, the user's role, the plan (`code: 'PlanRestricted'`),
125
+ * or a surface OAuth tokens never reach — and reconnecting will not fix it.
106
126
  *
107
127
  * @example
108
128
  * ```ts
@@ -149,6 +169,14 @@ var ApiError = class _ApiError extends AssinafyError {
149
169
  this.name = "ApiError";
150
170
  this.statusCode = statusCode;
151
171
  this.responseData = responseData;
172
+ if (responseData !== null && typeof responseData === "object") {
173
+ const body = responseData;
174
+ if (typeof body["code"] === "string" && body["code"].length > 0) this.code = body["code"];
175
+ if (Array.isArray(body["errors"])) {
176
+ const fieldErrors = body["errors"].filter(isFieldError);
177
+ if (fieldErrors.length > 0) this.fieldErrors = fieldErrors;
178
+ }
179
+ }
152
180
  }
153
181
  /**
154
182
  * Convert a status/body pair into an {@link ApiError}.
@@ -281,6 +309,11 @@ var NetworkError = class extends AssinafyError {
281
309
  this.name = "NetworkError";
282
310
  }
283
311
  };
312
+ function isFieldError(value) {
313
+ if (value === null || typeof value !== "object") return false;
314
+ const entry = value;
315
+ return (entry["field"] === null || typeof entry["field"] === "string") && typeof entry["code"] === "string" && typeof entry["message"] === "string";
316
+ }
284
317
 
285
318
  // src/utils.ts
286
319
  var import_axios = __toESM(require("axios"));
@@ -341,6 +374,7 @@ var SAFE_LOG_NUMBER_FIELDS = /* @__PURE__ */ new Set([
341
374
  "delayMs",
342
375
  "maxRetries",
343
376
  "signerCount",
377
+ "documentCount",
344
378
  "size"
345
379
  ]);
346
380
  function handleAssinafyResponse(response) {
@@ -516,6 +550,45 @@ function assertDateTime(value, label) {
516
550
  throw new ValidationError(`${label} must be an ISO-8601 date-time`);
517
551
  }
518
552
  }
553
+ function assertExpirationDate(value, label) {
554
+ if (typeof value !== "string") {
555
+ throw new ValidationError(`${label} must be an ISO-8601 date or date-time`);
556
+ }
557
+ 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;
558
+ try {
559
+ assertDateTime(normalized, label);
560
+ } catch {
561
+ throw new ValidationError(`${label} must be an ISO-8601 date or date-time`);
562
+ }
563
+ }
564
+ function assertCreditCeiling(value) {
565
+ if (value !== void 0 && (typeof value !== "number" || !Number.isFinite(value) || value < 0)) {
566
+ throw new ValidationError("max_total_credits must be a finite number of credits, zero or more");
567
+ }
568
+ }
569
+ function idempotencyConfig(key) {
570
+ if (key === void 0) return {};
571
+ if (typeof key !== "string" || key.trim().length === 0) {
572
+ throw new ValidationError("idempotencyKey must be a non-empty string");
573
+ }
574
+ return { headers: { "Idempotency-Key": key } };
575
+ }
576
+ function assertBooleanMap(value, label, known) {
577
+ assertRecord(value, label);
578
+ const entries = Object.entries(value);
579
+ if (entries.length === 0) throw new ValidationError(`${label} must set at least one key`);
580
+ for (const [key, item] of entries) {
581
+ if (known && !known.has(key)) throw new ValidationError(`unknown ${label} key: ${key}`);
582
+ if (typeof item !== "boolean") throw new ValidationError(`${label}.${key} must be a boolean`);
583
+ }
584
+ }
585
+ function expandParam(value, allowed) {
586
+ if (value === void 0) return {};
587
+ if (!Array.isArray(value) || value.some((item) => !allowed.has(item))) {
588
+ throw new ValidationError(`expand must list only ${[...allowed].join(", ")}`);
589
+ }
590
+ return value.length > 0 ? { expand: value.join(",") } : {};
591
+ }
519
592
  function cleanParams(params) {
520
593
  assertRecord(params, "params");
521
594
  const out = {};
@@ -690,7 +763,7 @@ var import_axios2 = __toESM(require("axios"));
690
763
  // package.json
691
764
  var package_default = {
692
765
  name: "@assinafy/sdk",
693
- version: "2.10.0",
766
+ version: "3.0.0",
694
767
  packageManager: "bun@1.4.4",
695
768
  description: "TypeScript SDK for Assinafy API - Digital signature platform",
696
769
  type: "commonjs",
@@ -774,7 +847,8 @@ var package_default = {
774
847
  overrides: {
775
848
  esbuild: "0.28.2",
776
849
  "follow-redirects": "1.16.2",
777
- "brace-expansion": "5.0.12"
850
+ "brace-expansion": "5.0.12",
851
+ minimatch: "11.0.3"
778
852
  },
779
853
  files: [
780
854
  "dist",
@@ -1041,14 +1115,23 @@ function toInt(value) {
1041
1115
 
1042
1116
  // src/resources/assignments.ts
1043
1117
  var ASSIGNMENT_METHODS = /* @__PURE__ */ new Set(["virtual", "collect"]);
1044
- var VERIFICATION_METHODS = /* @__PURE__ */ new Set(["Email", "Whatsapp", "DigitalCertificate", "IdDocumentFaceMatchBasic"]);
1045
- var NOTIFICATION_METHODS = /* @__PURE__ */ new Set(["Email", "Whatsapp"]);
1118
+ var VERIFICATION_METHODS = /* @__PURE__ */ new Set([
1119
+ "Email",
1120
+ "Whatsapp",
1121
+ "DigitalCertificate",
1122
+ "IdDocumentFaceMatchBasic",
1123
+ "Bypass"
1124
+ ]);
1125
+ var MESSAGE_CHANNELS = /* @__PURE__ */ new Set(["Email", "Whatsapp"]);
1126
+ var NOTIFICATION_METHODS = /* @__PURE__ */ new Set([...MESSAGE_CHANNELS, "Bypass"]);
1127
+ var EMBEDDED_VERIFICATION_METHODS = /* @__PURE__ */ new Set(["Email", "Whatsapp", "Bypass"]);
1046
1128
  var DIGITAL_CERTIFICATE_REQUIRES_VIRTUAL_METHOD = "digital_certificate_requires_virtual_method";
1047
1129
  var ALLOWED_NOTIFICATION_METHODS = {
1048
1130
  Email: /* @__PURE__ */ new Set(["Email"]),
1049
1131
  Whatsapp: /* @__PURE__ */ new Set(["Whatsapp"]),
1050
- DigitalCertificate: NOTIFICATION_METHODS,
1051
- IdDocumentFaceMatchBasic: NOTIFICATION_METHODS
1132
+ DigitalCertificate: MESSAGE_CHANNELS,
1133
+ IdDocumentFaceMatchBasic: MESSAGE_CHANNELS,
1134
+ Bypass: NOTIFICATION_METHODS
1052
1135
  };
1053
1136
  function validateAssignmentSignerOptions(signer, label = "signer") {
1054
1137
  if (signer.verification_method !== void 0 && (typeof signer.verification_method !== "string" || !VERIFICATION_METHODS.has(signer.verification_method))) {
@@ -1074,6 +1157,14 @@ function validateAssignmentSignerOptions(signer, label = "signer") {
1074
1157
  }
1075
1158
  }
1076
1159
  }
1160
+ if (signer.embedded !== void 0 && typeof signer.embedded !== "boolean") {
1161
+ throw new ValidationError(`${label} embedded must be a boolean`);
1162
+ }
1163
+ if (signer.embedded === true && typeof signer.verification_method === "string" && !EMBEDDED_VERIFICATION_METHODS.has(signer.verification_method)) {
1164
+ throw new ValidationError(
1165
+ `${label} embedded signing supports only Email, Whatsapp and Bypass verification`
1166
+ );
1167
+ }
1077
1168
  if (signer.step !== void 0 && (typeof signer.step !== "number" || !Number.isSafeInteger(signer.step) || signer.step < 1)) {
1078
1169
  throw new ValidationError(`${label} step must be a positive safe integer`);
1079
1170
  }
@@ -1128,12 +1219,13 @@ function buildAssignmentPayload(payload) {
1128
1219
  if (payload.message !== void 0 && typeof payload.message !== "string") {
1129
1220
  throw new ValidationError("message must be a string");
1130
1221
  }
1131
- if (payload.expires_at !== void 0) assertDateTime(payload.expires_at, "expires_at");
1222
+ if (payload.expires_at !== void 0) assertExpirationDate(payload.expires_at, "expires_at");
1132
1223
  if (payload.copy_receivers !== void 0 && (!Array.isArray(payload.copy_receivers) || payload.copy_receivers.some(
1133
1224
  (id) => typeof id !== "string" || !id.trim()
1134
1225
  ))) {
1135
1226
  throw new ValidationError("copy_receivers must be an array of non-empty signer IDs");
1136
1227
  }
1228
+ assertCreditCeiling(payload.max_total_credits);
1137
1229
  const normalisedSigners = signers.map((ref) => normaliseSignerRef(ref));
1138
1230
  validateDigitalCertificateMethod(method, normalisedSigners);
1139
1231
  validateSigningOrder(normalisedSigners, "assignment signers");
@@ -1143,7 +1235,8 @@ function buildAssignmentPayload(payload) {
1143
1235
  message: payload.message,
1144
1236
  expires_at: payload.expires_at,
1145
1237
  copy_receivers: payload.copy_receivers,
1146
- entries
1238
+ entries,
1239
+ max_total_credits: payload.max_total_credits
1147
1240
  });
1148
1241
  }
1149
1242
  function buildAssignmentEstimatePayload(payload) {
@@ -1188,6 +1281,7 @@ function normaliseSignerRef(ref) {
1188
1281
  id,
1189
1282
  verification_method: input.verification_method,
1190
1283
  notification_methods: input.notification_methods,
1284
+ embedded: input.embedded,
1191
1285
  step: input.step
1192
1286
  });
1193
1287
  if (typeof id === "string" && id.trim().length > 0) {
@@ -1295,12 +1389,13 @@ var AssignmentResource = class extends BaseResource {
1295
1389
  /**
1296
1390
  * List assignments across the workspace (`GET /assignments`).
1297
1391
  *
1298
- * The account is passed as an `accountId` **query parameter** — the API
1299
- * responds `400` ("Um contexto de conta é necessário e não foi fornecido")
1300
- * without it. Note the camelCase spelling: `account_id` and an
1301
- * `X-Account-Id` header are both rejected.
1392
+ * The account is passed as the camelCase `accountId` **query parameter**,
1393
+ * required unless an OAuth token names the workspace (the SDK always sends
1394
+ * it; for a token, its own workspace). `account_id` and an `X-Account-Id`
1395
+ * header are ignored.
1302
1396
  *
1303
- * @param params - `page`, `per-page`.
1397
+ * @param params - `page`, `per-page` (at most 50), and `sort`: `created_at`
1398
+ * (default, oldest first), `expires_at` or `id`, `-` prefix for descending.
1304
1399
  * @param accountId - Override the client's default account ID.
1305
1400
  * @returns Assignments, with pagination in `meta`. Each item is a full
1306
1401
  * {@link IAssignment} (same shape as {@link AssignmentResource.create}
@@ -1368,13 +1463,15 @@ var AssignmentResource = class extends BaseResource {
1368
1463
  * "signing_urls": [
1369
1464
  * {
1370
1465
  * "signer_id": "19e6b92e7895332ed9708535d8c",
1371
- * "url": "https://app.assinafy.com.br/sign/103033c950d865a248a11c5cf96c?email=signer%40example.com"
1466
+ * "url": "https://app.assinafy.com.br/sign/103033c950d865a248a11c5cf96c?email=signer%40example.com",
1467
+ * "embedded": false
1372
1468
  * }
1373
1469
  * ]
1374
1470
  * }
1375
1471
  * ```
1376
1472
  * @throws {ValidationError} If no account ID is available.
1377
- * @throws {ApiError} If the API rejects the request.
1473
+ * @throws {ApiError} `400` when no workspace is named, `403` when a role or
1474
+ * OAuth scope refuses it, `404` for an unknown workspace.
1378
1475
  *
1379
1476
  * @example
1380
1477
  * ```ts
@@ -1433,6 +1530,14 @@ var AssignmentResource = class extends BaseResource {
1433
1530
  * @param payload - Signers plus optional `method` (defaults to `virtual`),
1434
1531
  * `message`, `expires_at`, `copy_receivers` (existing signer IDs, not
1435
1532
  * addresses), and `collect`-mode `entries` with page-image geometry.
1533
+ * `expires_at` accepts a date (ending at 23:59 UTC), a date-time without
1534
+ * an offset (UTC), or an offset-aware date-time, at least one hour ahead.
1535
+ * `max_total_credits` refuses the send above that many credits. Signers may
1536
+ * set `embedded: true` (Embed feature; `Email`, `Whatsapp` or `Bypass`
1537
+ * verification) to sign in your app through `embed.createSession()`.
1538
+ * This route takes no `Idempotency-Key`: a document takes one assignment,
1539
+ * so a retry after a lost response answers `400` and charges nothing —
1540
+ * read the document to see whether the first request went through.
1436
1541
  * @returns The created {@link IAssignment}: `signers` (rich, with `step` /
1437
1542
  * `notified` / `verification_method`), `items` (one row per signer × field),
1438
1543
  * a `summary` count block, and per-signer `signing_urls`. Response shape:
@@ -1497,7 +1602,8 @@ var AssignmentResource = class extends BaseResource {
1497
1602
  * "signing_urls": [
1498
1603
  * {
1499
1604
  * "signer_id": "19e6b92e7895332ed9708535d8c",
1500
- * "url": "https://app.assinafy.com.br/sign/103033c950d865a248a11c5cf96c?email=signer%40example.com"
1605
+ * "url": "https://app.assinafy.com.br/sign/103033c950d865a248a11c5cf96c?email=signer%40example.com",
1606
+ * "embedded": false // an embedded signer has "url": null
1501
1607
  * }
1502
1608
  * ]
1503
1609
  * }
@@ -1507,7 +1613,10 @@ var AssignmentResource = class extends BaseResource {
1507
1613
  * combined with `collect`. The last case has `errors.code ===
1508
1614
  * 'digital_certificate_requires_virtual_method'`.
1509
1615
  * @throws {ApiError} `400` for an invalid assignment or unmet verification
1510
- * precondition; otherwise if the API rejects the request.
1616
+ * precondition; `403` (`PlanRestricted` for a method or Embed the plan
1617
+ * lacks, `InsufficientScope`); `404` for a document outside the workspace;
1618
+ * `409` (`CreditCeilingExceeded`, with `total_credits` and
1619
+ * `max_total_credits` in `responseData`).
1511
1620
  *
1512
1621
  * @example
1513
1622
  * ```ts
@@ -1516,7 +1625,7 @@ var AssignmentResource = class extends BaseResource {
1516
1625
  * message: 'Please sign this contract',
1517
1626
  * });
1518
1627
  * // → wire body: { method: 'virtual', signers: [{ id: '19e6…' }], message: 'Please sign this contract' }
1519
- * console.log(assignment.signing_urls?.length); // one protected link per signer
1628
+ * console.log(assignment.signing_urls?.length); // one entry per notified signer; url is null for embedded or WhatsApp-only signers
1520
1629
  * ```
1521
1630
  */
1522
1631
  async create(documentId, payload) {
@@ -1620,9 +1729,10 @@ var AssignmentResource = class extends BaseResource {
1620
1729
  * (`PUT /documents/{documentId}/assignments/{assignmentId}/reset-expiration`).
1621
1730
  *
1622
1731
  * Sends `{ expires_at }` verbatim; the key itself is required by the
1623
- * contract. Use an ISO-8601 date/time string, or `null` to remove the
1624
- * expiration — `null` is the documented clear mechanism and, unlike
1625
- * ordinary nullable inputs, is intentionally not stripped from the body.
1732
+ * contract. Use an ISO-8601 date, a date-time with or without an offset,
1733
+ * or `null` to remove the expiration. Date-only values end at 23:59 UTC;
1734
+ * date-times without offsets are UTC. `null` is intentionally not stripped
1735
+ * from the body.
1626
1736
  *
1627
1737
  * Request body (`application/json`):
1628
1738
  * ```jsonc
@@ -1633,8 +1743,8 @@ var AssignmentResource = class extends BaseResource {
1633
1743
  *
1634
1744
  * @param documentId - The document the assignment belongs to.
1635
1745
  * @param assignmentId - The assignment to update.
1636
- * @param expiresAt - New expiry as an ISO-8601 date/time string, or `null`
1637
- * to remove the expiration.
1746
+ * @param expiresAt - New expiry as an ISO-8601 date or date-time string,
1747
+ * or `null` to remove the expiration.
1638
1748
  * @returns The updated {@link IAssignment} — the same full shape
1639
1749
  * {@link AssignmentResource.create} returns (`signers`, `items`, `summary`,
1640
1750
  * `signing_urls`), with `expires_at` reflecting the new value:
@@ -1678,7 +1788,7 @@ var AssignmentResource = class extends BaseResource {
1678
1788
  async resetExpiration(documentId, assignmentId, expiresAt) {
1679
1789
  const docId = this.requireId(documentId, "Document ID");
1680
1790
  const asgId = this.requireId(assignmentId, "Assignment ID");
1681
- if (expiresAt !== null) assertDateTime(expiresAt, "expiresAt");
1791
+ if (expiresAt !== null) assertExpirationDate(expiresAt, "expiresAt");
1682
1792
  return this.call(
1683
1793
  "Failed to update assignment expiration",
1684
1794
  () => this.http.put(
@@ -1707,7 +1817,11 @@ var AssignmentResource = class extends BaseResource {
1707
1817
  * }
1708
1818
  * ```
1709
1819
  * @throws {ValidationError} If any of the three IDs is missing.
1710
- * @throws {ApiError} If the API rejects the request.
1820
+ * @throws {ApiError} `400` when the document is not pending signature, the
1821
+ * signer already signed or waits for an earlier step, or credits are short;
1822
+ * `403`; `404`. The same verification code is resent, so an open embed frame
1823
+ * keeps working; envelope signers can be reminded of every document at once
1824
+ * with `envelopes.resendNotification()`.
1711
1825
  *
1712
1826
  * @example
1713
1827
  * ```ts
@@ -1736,26 +1850,20 @@ var AssignmentResource = class extends BaseResource {
1736
1850
  * @param documentId - The document the assignment belongs to.
1737
1851
  * @param assignmentId - The assignment containing the signer.
1738
1852
  * @param signerId - The signer whose notification would be resent.
1739
- * @returns An {@link IResendCostEstimate}: either the full
1740
- * {@link ICostEstimate} or the compact `total` /
1741
- * `has_sufficient_credits` compatibility shape:
1853
+ * @returns An {@link IResendCostEstimate}: the compact `total` /
1854
+ * `has_sufficient_credits` shape production returns, or the full
1855
+ * {@link ICostEstimate} on older deployments:
1742
1856
  * ```jsonc
1743
1857
  * {
1744
- * "documents": 1,
1745
- * "credits": 0,
1746
- * "needs_extra_document": false,
1747
- * "extra_document_cost": 0,
1748
- * "total_credits": 0,
1749
- * "breakdown": [],
1750
- * "document_balance": 67,
1751
- * "credit_balance": 0,
1752
- * "has_sufficient_resources": true,
1753
- * "blocking_reason": null,
1754
- * "message": null
1858
+ * "total": 0.45,
1859
+ * "breakdown": [{ "code": "NotificationWhatsappResend", "name": "WhatsApp Notification Resend", "cost": 0.45 }],
1860
+ * "credit_balance": 10, // null when credits are not limited
1861
+ * "has_sufficient_credits": true
1755
1862
  * }
1756
1863
  * ```
1757
1864
  * @throws {ValidationError} If any of the three IDs is missing.
1758
- * @throws {ApiError} If the API rejects the request.
1865
+ * @throws {ApiError} `400` when the signer cannot be reminded (signed, not
1866
+ * yet notified, or notified only by `Bypass`), `403`, `404`.
1759
1867
  *
1760
1868
  * @example
1761
1869
  * ```ts
@@ -1793,11 +1901,11 @@ var AssignmentResource = class extends BaseResource {
1793
1901
  * ```jsonc
1794
1902
  * [
1795
1903
  * {
1796
- * "sent_at": 1784145573,
1904
+ * "sent_at": "2026-10-19T19:05:48Z",
1797
1905
  * "header": "Assinafy",
1798
1906
  * "body": "Você tem um documento para assinar.",
1799
1907
  * "buttons": [
1800
- * { "text": "Assinar documento", "url": "https://app.assinafy.com.br/sign/103033c950d865a248a11c5cf96c" }
1908
+ * { "text": "Assinar documento" } // production strips button URLs
1801
1909
  * ],
1802
1910
  * "phone_number": "+5511999998888",
1803
1911
  * "signer_id": "19e6b92e7895332ed9708535d8c"
@@ -2138,7 +2246,7 @@ var DocumentResource = class extends BaseResource {
2138
2246
  * a compact representation with no expanded `assignment` or `pages`, so
2139
2247
  * prefer it for name lookups and pickers.
2140
2248
  *
2141
- * @param params - `search`, `status`, `page`, `per-page`.
2249
+ * @param params - `search`, `status`, `page`, `per-page`, and `sort`.
2142
2250
  * @param accountId - Override the client's default account ID.
2143
2251
  * @returns Matching documents, with pagination in `meta`. Each item:
2144
2252
  * ```jsonc
@@ -2256,7 +2364,11 @@ var DocumentResource = class extends BaseResource {
2256
2364
  * `null`), rendered `pages`, and `artifacts`. `decline_reason` is returned
2257
2365
  * only when the access token belongs to the document creator.
2258
2366
  *
2367
+ * `expand: ['envelope_id']` adds the envelope the document is in and
2368
+ * `expand: ['envelope']` its `{ id, name }` (each `null` outside one).
2369
+ *
2259
2370
  * @param documentId - The document to fetch.
2371
+ * @param options - `expand`: `envelope_id` and/or `envelope`.
2260
2372
  * @returns The document. Response shape (once `metadata_ready`):
2261
2373
  * ```jsonc
2262
2374
  * {
@@ -2285,30 +2397,38 @@ var DocumentResource = class extends BaseResource {
2285
2397
  * "download_url": "https://…/documents/103ad216…/pages/103ad216…/download"
2286
2398
  * }
2287
2399
  * ],
2400
+ * "has_contract": false,
2401
+ * "envelope_id": null, // with expand: ['envelope_id']
2402
+ * "envelope": null, // with expand: ['envelope']
2288
2403
  * "created_at": "2026-07-19T17:24:43Z",
2289
2404
  * "updated_at": "2026-07-19T17:24:46Z"
2290
2405
  * }
2291
2406
  * ```
2292
- * @throws {ValidationError} If `documentId` is missing.
2293
- * @throws {ApiError} `404` if the document does not exist.
2407
+ * @throws {ValidationError} If `documentId` is missing or `expand` is unknown.
2408
+ * @throws {ApiError} `403` when a role or OAuth scope refuses it, `404` if the
2409
+ * document does not exist.
2294
2410
  *
2295
2411
  * @example
2296
2412
  * ```ts
2297
- * const doc = await client.documents.details('103ad216846e6b90710cb9acef59');
2298
- * console.log(doc.status, doc.pages.length);
2413
+ * const doc = await client.documents.details('103ad216846e6b90710cb9acef59', {
2414
+ * expand: ['envelope'],
2415
+ * });
2416
+ * console.log(doc.status, doc.envelope?.name);
2299
2417
  * ```
2300
2418
  */
2301
- async details(documentId) {
2419
+ async details(documentId, options = {}) {
2302
2420
  const id = this.requireId(documentId, "Document ID");
2303
- return this.fetchDetails(id);
2304
- }
2305
- fetchDetails(id, signal) {
2421
+ return this.fetchDetails(id, void 0, options);
2422
+ }
2423
+ fetchDetails(id, signal, options = {}) {
2424
+ assertRecord(options, "document details options");
2425
+ const params = expandParam(options.expand, DETAIL_EXPANSIONS);
2426
+ const config = {};
2427
+ if (signal) config.signal = signal;
2428
+ if (params.expand) config.params = params;
2306
2429
  return this.call(
2307
2430
  "Failed to fetch document details",
2308
- () => this.http.get(
2309
- `/documents/${this.pathSegment(id, "Document ID")}`,
2310
- signal ? { signal } : void 0
2311
- )
2431
+ () => this.http.get(`/documents/${this.pathSegment(id, "Document ID")}`, config)
2312
2432
  );
2313
2433
  }
2314
2434
  /**
@@ -2316,18 +2436,19 @@ var DocumentResource = class extends BaseResource {
2316
2436
  * (`GET /documents/{documentId}`).
2317
2437
  *
2318
2438
  * @param documentId - The document to fetch.
2439
+ * @param options - `expand`, as on {@link DocumentResource.details}.
2319
2440
  * @returns The document details (see {@link DocumentResource.details} for
2320
2441
  * the response shape).
2321
2442
  * @throws {ValidationError} If `documentId` is missing.
2322
- * @throws {ApiError} `404` if the document does not exist.
2443
+ * @throws {ApiError} `403` or `404`, as on {@link DocumentResource.details}.
2323
2444
  *
2324
2445
  * @example
2325
2446
  * ```ts
2326
2447
  * const doc = await client.documents.get('103ad216846e6b90710cb9acef59');
2327
2448
  * ```
2328
2449
  */
2329
- async get(documentId) {
2330
- return this.details(documentId);
2450
+ async get(documentId, options = {}) {
2451
+ return this.details(documentId, options);
2331
2452
  }
2332
2453
  /**
2333
2454
  * Poll {@link DocumentResource.details} until the document reaches a ready
@@ -2441,10 +2562,15 @@ var DocumentResource = class extends BaseResource {
2441
2562
  * Download the document thumbnail image
2442
2563
  * (`GET /documents/{documentId}/thumbnail`).
2443
2564
  *
2565
+ * `artifact: 'certificated'` renders it as it is in the signed document.
2566
+ *
2444
2567
  * @param documentId - The document whose thumbnail to fetch.
2445
- * @returns A {@link Buffer} of the thumbnail image bytes.
2446
- * @throws {ValidationError} If `documentId` is missing.
2447
- * @throws {ApiError} `404` if the document or its thumbnail does not exist.
2568
+ * @param options - `artifact: 'certificated'` for the signed render.
2569
+ * @returns A {@link Buffer} of the thumbnail image bytes (`image/*`).
2570
+ * @throws {ValidationError} If `documentId` is missing or `artifact` is unknown.
2571
+ * @throws {ApiError} `404` if the document, its thumbnail, or (with
2572
+ * `certificated`) its certification does not exist; `503` while the signed
2573
+ * render is still being produced — wait `rateLimit.retryAfter` seconds.
2448
2574
  *
2449
2575
  * @example
2450
2576
  * ```ts
@@ -2452,28 +2578,29 @@ var DocumentResource = class extends BaseResource {
2452
2578
  * await fs.promises.writeFile('thumb.jpg', thumb);
2453
2579
  * ```
2454
2580
  */
2455
- async thumbnail(documentId) {
2581
+ async thumbnail(documentId, options = {}) {
2456
2582
  const id = this.requireId(documentId, "Document ID");
2583
+ const config = renderConfig(options);
2457
2584
  return this.callBinary(
2458
2585
  "Failed to download document thumbnail",
2459
- () => this.http.get(
2460
- `/documents/${this.pathSegment(id, "Document ID")}/thumbnail`,
2461
- { responseType: "arraybuffer" }
2462
- )
2586
+ () => this.http.get(`/documents/${this.pathSegment(id, "Document ID")}/thumbnail`, config)
2463
2587
  );
2464
2588
  }
2465
2589
  /**
2466
- * Download a single rendered page as a JPEG
2590
+ * Download a single rendered page image
2467
2591
  * (`GET /documents/{documentId}/pages/{pageId}/download`).
2468
2592
  *
2469
2593
  * The `pageId` comes from a page's `id` in {@link DocumentResource.details}
2470
- * or {@link DocumentResource.list} (`pages[].id`).
2594
+ * or {@link DocumentResource.list} (`pages[].id`). `artifact: 'certificated'`
2595
+ * renders the page as it is in the signed document.
2471
2596
  *
2472
2597
  * @param documentId - The document the page belongs to.
2473
2598
  * @param pageId - The page to download.
2474
- * @returns A {@link Buffer} of the page's JPEG bytes.
2475
- * @throws {ValidationError} If `documentId` or `pageId` is missing.
2476
- * @throws {ApiError} `404` if the document or page does not exist.
2599
+ * @param options - `artifact: 'certificated'` for the signed render.
2600
+ * @returns A {@link Buffer} of the page image bytes (`image/*`).
2601
+ * @throws {ValidationError} If `documentId` or `pageId` is missing, or `artifact` is unknown.
2602
+ * @throws {ApiError} `404` if the document or page does not exist (or, with
2603
+ * `certificated`, is not certified); `503` while the signed render is pending.
2477
2604
  *
2478
2605
  * @example
2479
2606
  * ```ts
@@ -2482,14 +2609,15 @@ var DocumentResource = class extends BaseResource {
2482
2609
  * await fs.promises.writeFile('page-1.jpg', page);
2483
2610
  * ```
2484
2611
  */
2485
- async downloadPage(documentId, pageId) {
2612
+ async downloadPage(documentId, pageId, options = {}) {
2486
2613
  const docId = this.requireId(documentId, "Document ID");
2487
2614
  const pid = this.requireId(pageId, "Page ID");
2615
+ const config = renderConfig(options);
2488
2616
  return this.callBinary(
2489
2617
  "Failed to download page",
2490
2618
  () => this.http.get(
2491
2619
  `/documents/${this.pathSegment(docId, "Document ID")}/pages/${this.pathSegment(pid, "Page ID")}/download`,
2492
- { responseType: "arraybuffer" }
2620
+ config
2493
2621
  )
2494
2622
  );
2495
2623
  }
@@ -2506,7 +2634,7 @@ var DocumentResource = class extends BaseResource {
2506
2634
  * @param documentId - The document whose activity log to fetch.
2507
2635
  * @param params - Optional pagination and sorting parameters.
2508
2636
  * @param params.page - Page number, starting at 1.
2509
- * @param params.per-page - Entries per page (production default 20, documented max 100).
2637
+ * @param params.per-page - Entries per page (default 20, at most 50; a larger value answers 50).
2510
2638
  * @param params.per_page - Alias for `per-page`; explicit `per-page` wins.
2511
2639
  * @param params.sort - `-id` (default, newest first) or `id` (oldest first).
2512
2640
  * @returns The requested page of activity entries, or `[]`:
@@ -2536,7 +2664,7 @@ var DocumentResource = class extends BaseResource {
2536
2664
  * @example
2537
2665
  * ```ts
2538
2666
  * const events = await client.documents.activities('doc-1', {
2539
- * page: 2, 'per-page': 100, sort: 'id',
2667
+ * page: 2, 'per-page': 50, sort: 'id',
2540
2668
  * });
2541
2669
  * console.log(events.map((e) => e.event));
2542
2670
  * ```
@@ -2556,7 +2684,7 @@ var DocumentResource = class extends BaseResource {
2556
2684
  * @param documentId - The document whose activity log to fetch.
2557
2685
  * @param params - Optional pagination and sorting parameters.
2558
2686
  * @param params.page - Page number, starting at 1.
2559
- * @param params.per-page - Entries per page (production default 20, documented max 100).
2687
+ * @param params.per-page - Entries per page (default 20, at most 50; a larger value answers 50).
2560
2688
  * @param params.per_page - Alias for `per-page`; explicit `per-page` wins.
2561
2689
  * @param params.sort - `-id` (default, newest first) or `id` (oldest first).
2562
2690
  * @returns Activity entries and pagination metadata when the server supplies it:
@@ -2597,13 +2725,16 @@ var DocumentResource = class extends BaseResource {
2597
2725
  * Only documents in a deletable status can be removed — the API returns
2598
2726
  * `400` while the document is still `uploading` / `metadata_processing`
2599
2727
  * (await {@link DocumentResource.waitUntilReady} first) or once it has been
2600
- * certificated.
2728
+ * certificated. Deleting a `pending_signature` or `pending_identity_review`
2729
+ * document cancels it and notifies its signers. A document of an envelope
2730
+ * with an open document cannot be deleted on its own: cancel the envelope.
2601
2731
  *
2602
2732
  * @param documentId - The document to delete.
2603
2733
  * @returns Nothing; resolves when the document is deleted.
2604
2734
  * @throws {ValidationError} If `documentId` is missing.
2605
2735
  * @throws {ApiError} `400` if the document is not in a deletable status;
2606
- * `404` if it does not exist.
2736
+ * `403` when a role or OAuth scope refuses it; `404` if it does not exist;
2737
+ * `409` (`EnvelopeOpen`) while its envelope has an open document.
2607
2738
  *
2608
2739
  * @example
2609
2740
  * ```ts
@@ -2800,9 +2931,11 @@ var DocumentResource = class extends BaseResource {
2800
2931
  *
2801
2932
  * Instantiates the template, binding each role to a signer, and returns the
2802
2933
  * new document. The request body is `{ signers, ...options }` — `signers`
2803
- * maps every template `role_id` to an existing account signer `id`, and
2804
- * `options` may add `name`, `message`, `expires_at`, `editor_fields`, and
2805
- * tag names in `tags` (unknown names are created automatically).
2934
+ * maps every template `role_id` to an existing signer `id` or an `email`.
2935
+ * An email reuses the matching account signer or creates one with `name`;
2936
+ * `id` wins when both are present. Options may add `name`, `message`,
2937
+ * `expires_at`, `editor_fields`, and tag names in `tags` (unknown names are
2938
+ * created automatically).
2806
2939
  *
2807
2940
  * Request body (`application/json`):
2808
2941
  * ```jsonc
@@ -2810,7 +2943,9 @@ var DocumentResource = class extends BaseResource {
2810
2943
  * "signers": [
2811
2944
  * {
2812
2945
  * "role_id": "signing_role_example",
2813
- * "id": "signer_example",
2946
+ * "email": "signer@example.com",
2947
+ * "name": "Example Signer",
2948
+ * "whatsapp_phone_number": "+15555550100",
2814
2949
  * "verification_method": "Email",
2815
2950
  * "notification_methods": [
2816
2951
  * "Email"
@@ -2834,27 +2969,33 @@ var DocumentResource = class extends BaseResource {
2834
2969
  * ```
2835
2970
  *
2836
2971
  * @param templateId - The template to instantiate.
2837
- * @param signers - Role-to-signer bindings (each with `role_id` and `id`,
2838
- * plus optional `verification_method`, `notification_methods`, `step`).
2972
+ * @param signers - Role-to-signer bindings (each with `role_id` and either
2973
+ * an existing `id` or an `email`; email creation also accepts `name` and
2974
+ * `whatsapp_phone_number`). `verification_method`, `notification_methods`,
2975
+ * and `step` are optional.
2839
2976
  * Only one notification method is allowed per signer; when only one of the
2840
2977
  * verification/notification fields is supplied, the API infers the other.
2841
2978
  * `DigitalCertificate` costs 0.5 credits, requires the feature plus a
2842
2979
  * signer `government_id`, and that signer must be alone in its step. The
2843
- * server derives the assignment method from placed template fields but
2844
- * does not yet reject unusable certificate/`collect` combinations, so the
2845
- * SDK temporarily refuses certificate signers on this template route.
2980
+ * server derives the assignment method from placed template fields and
2981
+ * rejects certificate signers when those fields produce a `collect`
2982
+ * assignment. Use a template without placed signer fields for certificate
2983
+ * signing.
2846
2984
  * `IdDocumentFaceMatchBasic` needs the ID Document + Face Match feature
2847
2985
  * and a valid CPF in `government_id`; estimate the per-signer fee first.
2848
2986
  * @param options - Optional `name`, `message`, `expires_at`,
2849
2987
  * `editor_fields`, `tags`.
2850
2988
  * @param options.name - Generated document display name.
2851
2989
  * @param options.message - Signing invitation message.
2852
- * @param options.expires_at - ISO-8601 signature deadline.
2990
+ * @param options.expires_at - ISO-8601 deadline: date-only (ends at 23:59
2991
+ * UTC), date-time without an offset (treated as UTC), or an offset-aware
2992
+ * date-time.
2853
2993
  * @param options.editor_fields - Template editor values as `{ field_id, value }` entries.
2854
2994
  * @param options.tags - Tag names attached to the generated document.
2855
2995
  * @param accountId - Override the client's default account ID.
2856
- * @returns The created document (an {@link IDocumentDetailsResponse} with
2857
- * `template_id` set and its `assignment` populated):
2996
+ * @returns The uploaded document. Assignment creation continues in the
2997
+ * background; follow `GET /documents/{documentId}` or webhooks until the
2998
+ * document becomes `pending_signature` or `failed`:
2858
2999
  * ```jsonc
2859
3000
  * {
2860
3001
  * "resource": "document",
@@ -2862,22 +3003,21 @@ var DocumentResource = class extends BaseResource {
2862
3003
  * "account_id": "acc_example",
2863
3004
  * "template_id": "103a0991a5cde83518e5672aa9aa",
2864
3005
  * "name": "Service agreement from template",
2865
- * "status": "pending_signature",
2866
- * "artifacts": { "original": "https://…/download/original", "thumbnail": "https://…/thumbnail" },
3006
+ * "status": "uploaded",
3007
+ * "artifacts": { "original": "https://…/download/original" },
2867
3008
  * "is_closed": false,
2868
3009
  * "signing_url": "https://app.assinafy.com.br/sign/19f675b7…",
2869
3010
  * "tags": [{ "id": "103a0992…", "name": "agreements", "color": null }],
2870
- * "assignment": { "id": "103a09a1…", "method": "virtual", "summary": { "signer_count": 1, "completed_count": 0 } },
2871
- * "pages": [{ "id": "103a0992…", "number": 1, "height": 1651, "width": 1275, "download_url": "https://…/download" }],
3011
+ * "assignment": null,
3012
+ * "pages": [],
2872
3013
  * "created_at": "2026-07-15T19:57:55Z",
2873
3014
  * "updated_at": "2026-07-15T19:59:33Z"
2874
3015
  * }
2875
3016
  * ```
2876
- * @throws {ValidationError} If `templateId` is missing, no account ID is
2877
- * available, or a signer uses `DigitalCertificate`. Certificate refusals
2878
- * have `errors.code === 'digital_certificate_requires_virtual_method'`.
2879
- * @throws {ApiError} `400` if the signers/roles are invalid or the template
2880
- * is not ready.
3017
+ * @throws {ValidationError} If `templateId`, an account ID, signer identity,
3018
+ * channel, order, deadline, editor field, or tag is invalid.
3019
+ * @throws {ApiError} `400` if the signers/roles are invalid, the template
3020
+ * is not ready, or placed signer fields conflict with `DigitalCertificate`.
2881
3021
  *
2882
3022
  * @example
2883
3023
  * ```ts
@@ -2894,11 +3034,13 @@ var DocumentResource = class extends BaseResource {
2894
3034
  if (options.message !== void 0 && typeof options.message !== "string") {
2895
3035
  throw new ValidationError("message must be a string");
2896
3036
  }
2897
- if (options.expires_at !== void 0) assertDateTime(options.expires_at, "expires_at");
3037
+ if (options.expires_at !== void 0) assertExpirationDate(options.expires_at, "expires_at");
2898
3038
  const editorFields = options.editor_fields === void 0 ? void 0 : normaliseTemplateEditorFields(options.editor_fields);
2899
3039
  if (options.tags !== void 0 && (!Array.isArray(options.tags) || options.tags.some((tag) => typeof tag !== "string" || !tag.trim()))) {
2900
3040
  throw new ValidationError("tags must be an array of non-empty tag names");
2901
3041
  }
3042
+ assertCreditCeiling(options.max_total_credits);
3043
+ const config = idempotencyConfig(options.idempotencyKey);
2902
3044
  const tmplId = this.requireId(templateId, "Template ID");
2903
3045
  const accId = this.accountId(accountId);
2904
3046
  const body = {
@@ -2909,12 +3051,14 @@ var DocumentResource = class extends BaseResource {
2909
3051
  if (options.expires_at !== void 0) body["expires_at"] = options.expires_at;
2910
3052
  if (editorFields !== void 0) body["editor_fields"] = editorFields;
2911
3053
  if (options.tags !== void 0) body["tags"] = [...options.tags];
3054
+ if (options.max_total_credits !== void 0) body["max_total_credits"] = options.max_total_credits;
2912
3055
  this.logger.info("Creating document from template", { templateId: tmplId, accountId: accId });
2913
3056
  return this.call(
2914
3057
  "Failed to create document from template",
2915
3058
  () => this.http.post(
2916
3059
  `/accounts/${this.pathSegment(accId, "Account ID")}/templates/${this.pathSegment(tmplId, "Template ID")}/documents`,
2917
- body
3060
+ body,
3061
+ config
2918
3062
  )
2919
3063
  );
2920
3064
  }
@@ -2924,10 +3068,8 @@ var DocumentResource = class extends BaseResource {
2924
3068
  *
2925
3069
  * A dry run: sends only `{ signers }` and consumes nothing. Use it to check
2926
3070
  * balances before calling {@link DocumentResource.createFromTemplate}.
2927
- * `DigitalCertificate` requires a provably `virtual` assignment. Because
2928
- * this route leaves method detection to the server, the SDK temporarily
2929
- * refuses certificate signers instead of returning a price for an
2930
- * assignment that may charge credits but cannot be completed.
3071
+ * `DigitalCertificate` adds 0.5 credits per signer plus notification cost;
3072
+ * the API returns `400` when the template has placed signer fields.
2931
3073
  *
2932
3074
  * Request body (`application/json`):
2933
3075
  * ```jsonc
@@ -2969,10 +3111,10 @@ var DocumentResource = class extends BaseResource {
2969
3111
  * "message": null
2970
3112
  * }
2971
3113
  * ```
2972
- * @throws {ValidationError} If `templateId` is missing, no account ID is
2973
- * available, or a signer uses `DigitalCertificate`. Certificate refusals
2974
- * have `errors.code === 'digital_certificate_requires_virtual_method'`.
2975
- * @throws {ApiError} If the API rejects the request.
3114
+ * @throws {ValidationError} If `templateId`, an account ID, role, or
3115
+ * channel is invalid.
3116
+ * @throws {ApiError} `400` if the role is invalid or placed signer fields
3117
+ * conflict with `DigitalCertificate`; `403` when a feature is unavailable.
2976
3118
  *
2977
3119
  * @example
2978
3120
  * ```ts
@@ -3050,13 +3192,14 @@ var DocumentResource = class extends BaseResource {
3050
3192
  * { "code": "uploaded", "deletable": false },
3051
3193
  * { "code": "metadata_processing", "deletable": false },
3052
3194
  * { "code": "metadata_ready", "deletable": true },
3053
- * { "code": "pending_signature", "deletable": true },
3054
- * { "code": "expired", "deletable": false },
3195
+ * { "code": "expired", "deletable": true },
3055
3196
  * { "code": "certificating", "deletable": false },
3056
3197
  * { "code": "certificated", "deletable": false },
3057
- * { "code": "rejected_by_signer", "deletable": false },
3058
- * { "code": "rejected_by_user", "deletable": false },
3059
- * { "code": "failed", "deletable": false }
3198
+ * { "code": "rejected_by_signer", "deletable": true },
3199
+ * { "code": "pending_signature", "deletable": true },
3200
+ * { "code": "pending_identity_review", "deletable": true }, // deleting cancels and notifies signers
3201
+ * { "code": "rejected_by_user", "deletable": true },
3202
+ * { "code": "failed", "deletable": true }
3060
3203
  * ]
3061
3204
  * ```
3062
3205
  * @throws {ApiError} If the API rejects the request.
@@ -3252,23 +3395,54 @@ function normaliseTemplateSigners(signers) {
3252
3395
  if (typeof signer.role_id !== "string" || !signer.role_id.trim()) {
3253
3396
  throw new ValidationError(`Template signer ${index + 1} requires role_id`);
3254
3397
  }
3255
- if (typeof signer.id !== "string" || !signer.id.trim()) {
3256
- throw new ValidationError(`Template signer ${index + 1} requires id`);
3257
- }
3258
3398
  validateAssignmentSignerOptions(signer, `Template signer ${index + 1}`);
3259
- const projected = { role_id: signer.role_id, id: signer.id };
3399
+ const projected = { role_id: signer.role_id };
3400
+ if (signer.id !== void 0) {
3401
+ if (typeof signer.id !== "string" || !signer.id.trim()) {
3402
+ throw new ValidationError(`Template signer ${index + 1} id must be non-empty`);
3403
+ }
3404
+ projected.id = signer.id;
3405
+ } else {
3406
+ if (!isEmail(signer.email)) {
3407
+ throw new ValidationError(`Template signer ${index + 1} requires a valid id or email`);
3408
+ }
3409
+ projected.email = signer.email;
3410
+ if (signer.name !== void 0) {
3411
+ if (typeof signer.name !== "string" || !signer.name.trim()) {
3412
+ throw new ValidationError(`Template signer ${index + 1} name must be non-empty`);
3413
+ }
3414
+ projected.name = signer.name;
3415
+ }
3416
+ if (signer.whatsapp_phone_number !== void 0) {
3417
+ if (!isE164PhoneNumber(signer.whatsapp_phone_number)) {
3418
+ throw new ValidationError(
3419
+ `Template signer ${index + 1} whatsapp_phone_number must be E.164`
3420
+ );
3421
+ }
3422
+ projected.whatsapp_phone_number = signer.whatsapp_phone_number;
3423
+ }
3424
+ }
3260
3425
  if (signer.verification_method !== void 0) {
3261
3426
  projected.verification_method = signer.verification_method;
3262
3427
  }
3263
3428
  if (signer.notification_methods !== void 0) {
3264
3429
  projected.notification_methods = [...signer.notification_methods];
3265
3430
  }
3431
+ if (signer.embedded !== void 0) projected.embedded = signer.embedded;
3266
3432
  if (signer.step !== void 0) projected.step = signer.step;
3267
3433
  return projected;
3268
3434
  });
3269
- validateDigitalCertificateMethod(void 0, normalised);
3270
3435
  return normalised;
3271
3436
  }
3437
+ var DETAIL_EXPANSIONS = /* @__PURE__ */ new Set(["envelope_id", "envelope"]);
3438
+ function renderConfig(options) {
3439
+ assertRecord(options, "render options");
3440
+ if (options.artifact === void 0) return { responseType: "arraybuffer" };
3441
+ if (options.artifact !== "certificated") {
3442
+ throw new ValidationError("artifact must be certificated when given");
3443
+ }
3444
+ return { responseType: "arraybuffer", params: { artifact: options.artifact } };
3445
+ }
3272
3446
  function normaliseTemplateEditorFields(fields) {
3273
3447
  if (!Array.isArray(fields)) {
3274
3448
  throw new ValidationError("editor_fields must be an array");
@@ -3307,7 +3481,6 @@ function normaliseTemplateCostSigners(signers) {
3307
3481
  }
3308
3482
  return descriptor;
3309
3483
  });
3310
- validateDigitalCertificateMethod(void 0, normalised);
3311
3484
  return normalised;
3312
3485
  }
3313
3486
  function validateWaitOption(value, name) {
@@ -3550,7 +3723,7 @@ var SignerResource = class extends BaseResource {
3550
3723
  "Failed to update signer",
3551
3724
  () => this.http.put(
3552
3725
  `/accounts/${this.pathSegment(id, "Account ID")}/signers/${this.pathSegment(sid, "Signer ID")}`,
3553
- normaliseSignerPayload(payload)
3726
+ { ...normaliseSignerPayload(payload), ...clearedContacts(payload) }
3554
3727
  )
3555
3728
  );
3556
3729
  }
@@ -3676,13 +3849,19 @@ function validateUpdateSignerPayload(payload) {
3676
3849
  if (payload.full_name !== void 0 && (typeof payload.full_name !== "string" || !payload.full_name.trim())) {
3677
3850
  throw new ValidationError("full_name cannot be empty");
3678
3851
  }
3679
- if (payload.email !== void 0 && !isEmail(payload.email)) {
3852
+ if (payload.email !== void 0 && !isClear(payload.email) && !isEmail(payload.email)) {
3680
3853
  throw new ValidationError("Invalid email address", { email: payload.email });
3681
3854
  }
3682
- const phone = payload.whatsapp_phone_number ?? payload.phone;
3683
- validateOptionalPhone(phone);
3855
+ const phone = updatePhone(payload);
3856
+ if (!isClear(phone)) validateOptionalPhone(phone);
3684
3857
  validateOptionalDigits(payload.cpf, "cpf");
3685
- validateOptionalDigits(payload.government_id, "government_id");
3858
+ if (!isClear(payload.government_id)) validateOptionalDigits(payload.government_id, "government_id");
3859
+ }
3860
+ function isClear(value) {
3861
+ return value === null || value === "";
3862
+ }
3863
+ function updatePhone(payload) {
3864
+ return payload.whatsapp_phone_number !== void 0 ? payload.whatsapp_phone_number : payload.phone;
3686
3865
  }
3687
3866
  function validateOptionalDigits(value, field) {
3688
3867
  if (value === void 0) return;
@@ -3713,6 +3892,18 @@ function normaliseSignerPayload(payload) {
3713
3892
  }
3714
3893
  return cleanParams(normalised);
3715
3894
  }
3895
+ function clearedContacts(payload) {
3896
+ const cleared = {};
3897
+ const candidates = {
3898
+ email: payload.email,
3899
+ whatsapp_phone_number: updatePhone(payload),
3900
+ government_id: payload.government_id
3901
+ };
3902
+ for (const [key, value] of Object.entries(candidates)) {
3903
+ if (isClear(value)) cleared[key] = value;
3904
+ }
3905
+ return cleared;
3906
+ }
3716
3907
 
3717
3908
  // src/support/stats.ts
3718
3909
  var MONTH_RE = /^\d{4}-(0[1-9]|1[0-2])$/;
@@ -3833,7 +4024,13 @@ var WorkspaceResource = class extends BaseResource {
3833
4024
  /**
3834
4025
  * Fetch a single workspace (`GET /accounts/{accountId}`).
3835
4026
  *
4027
+ * `expand: 'signing_features'` adds which signing methods the plan allows
4028
+ * (OAuth: `account:read`). A `false` feature makes creating or estimating an
4029
+ * assignment, template document or envelope with that method answer `403`
4030
+ * (`PlanRestricted`); check it before offering the method.
4031
+ *
3836
4032
  * @param accountId - The workspace to fetch.
4033
+ * @param options - `expand: 'signing_features'`.
3837
4034
  * @returns The workspace. `primary_color` / `secondary_color` are `null`
3838
4035
  * until brand colours are set (6-char hex, no `#`, when present):
3839
4036
  * ```jsonc
@@ -3846,22 +4043,154 @@ var WorkspaceResource = class extends BaseResource {
3846
4043
  * "notification_sender_type": "User",
3847
4044
  * "roles": ["owner"],
3848
4045
  * "is_delete_allowed": true,
4046
+ * "limits": { "webhook_endpoints": 3 },
4047
+ * "signing_features": { // only with expand: 'signing_features'
4048
+ * "DigitalCertificate": true,
4049
+ * "VerificationIdDocumentFaceMatchBasic": true,
4050
+ * "WhatsappNotification": true,
4051
+ * "VerificationBypass": false,
4052
+ * "Embed": true
4053
+ * },
3849
4054
  * "created_at": "2026-05-12T18:05:11Z"
3850
4055
  * }
3851
4056
  * ```
3852
- * @throws {ValidationError} If `accountId` is missing.
3853
- * @throws {ApiError} `404` if the workspace does not exist.
4057
+ * @throws {ValidationError} If `accountId` is missing or `expand` is unknown.
4058
+ * @throws {ApiError} `403` for another workspace's token, `404` if the
4059
+ * workspace does not exist.
3854
4060
  *
3855
4061
  * @example
3856
4062
  * ```ts
3857
- * const ws = await client.workspaces.get('acc_example');
4063
+ * const ws = await client.workspaces.get('acc_example', { expand: 'signing_features' });
4064
+ * if (ws.signing_features?.Embed) await client.embed.listOrigins();
3858
4065
  * ```
3859
4066
  */
3860
- async get(accountId) {
4067
+ async get(accountId, options = {}) {
3861
4068
  const id = this.requireId(accountId, "Account ID");
4069
+ assertRecord(options, "workspace options");
4070
+ if (options.expand !== void 0 && options.expand !== "signing_features") {
4071
+ throw new ValidationError("expand must be signing_features");
4072
+ }
4073
+ const config = options.expand === void 0 ? {} : { params: { expand: options.expand } };
3862
4074
  return this.call(
3863
4075
  "Failed to fetch workspace",
3864
- () => this.http.get(`/accounts/${this.pathSegment(id, "Account ID")}`)
4076
+ () => this.http.get(`/accounts/${this.pathSegment(id, "Account ID")}`, config)
4077
+ );
4078
+ }
4079
+ /**
4080
+ * Read the workspace's plan and balances (`GET /accounts/{accountId}/usage`).
4081
+ *
4082
+ * For a plan and credit meter; prices and payments are not included. Not
4083
+ * available to third-party OAuth applications (`403`), whatever their scopes.
4084
+ *
4085
+ * @param accountId - The workspace to read.
4086
+ * @returns The plan meter:
4087
+ * ```jsonc
4088
+ * {
4089
+ * "plan": "Pro", // null without a current plan
4090
+ * "documents_renewal_date": "2026-12-11",
4091
+ * "balances": {
4092
+ * "documents": { "balance": 97, "limit": 100, "spent": 3 },
4093
+ * "credits": { "balance": 12.5, "limit": null, "spent": 0.9 } // null: unlimited / not cycle-limited
4094
+ * }
4095
+ * }
4096
+ * ```
4097
+ * @throws {ValidationError} If `accountId` is missing.
4098
+ * @throws {ApiError} `403` for an OAuth application token, `404` for an unknown workspace.
4099
+ *
4100
+ * @example
4101
+ * ```ts
4102
+ * const { balances } = await client.workspaces.getUsage('acc_example');
4103
+ * ```
4104
+ */
4105
+ async getUsage(accountId) {
4106
+ const id = this.requireId(accountId, "Account ID");
4107
+ return this.call(
4108
+ "Failed to fetch account usage",
4109
+ () => this.http.get(`/accounts/${this.pathSegment(id, "Account ID")}/usage`)
4110
+ );
4111
+ }
4112
+ /**
4113
+ * Read which document alerts the workspace sends
4114
+ * (`GET /accounts/{accountId}/notification-policy`).
4115
+ *
4116
+ * Every member can read it; `editable` says whether the caller (an owner)
4117
+ * can change it. Not available to third-party OAuth applications.
4118
+ *
4119
+ * @param accountId - The workspace to read.
4120
+ * @returns The policy; every event key is present:
4121
+ * ```jsonc
4122
+ * {
4123
+ * "editable": true,
4124
+ * "owners_receive_all": false, // owners also get push alerts for members' documents
4125
+ * "events": {
4126
+ * "DocumentCompleted": true, "SignerDeclined": true, "DocumentCancelled": true,
4127
+ * "DocumentAboutToExpire": true, "DocumentExpired": true, "DocumentExpirationReset": true,
4128
+ * "DocumentProcessingFailed": true, "TemplateProcessingFailed": true, "SignerWhatsappFailed": true,
4129
+ * "ContractRenewalNotice": true, "ContractExpiring": true, "ContractExpired": true,
4130
+ * "ContractRenewed": true, "SignerViewed": true, "SignerSigned": true,
4131
+ * "SignerIdentityReviewRequired": true
4132
+ * }
4133
+ * }
4134
+ * ```
4135
+ * @throws {ValidationError} If `accountId` is missing.
4136
+ * @throws {ApiError} `403` for an OAuth application token.
4137
+ *
4138
+ * @example
4139
+ * ```ts
4140
+ * const policy = await client.workspaces.getNotificationPolicy('acc_example');
4141
+ * ```
4142
+ */
4143
+ async getNotificationPolicy(accountId) {
4144
+ const id = this.requireId(accountId, "Account ID");
4145
+ return this.call(
4146
+ "Failed to fetch notification policy",
4147
+ () => this.http.get(`/accounts/${this.pathSegment(id, "Account ID")}/notification-policy`)
4148
+ );
4149
+ }
4150
+ /**
4151
+ * Change which document alerts the workspace sends
4152
+ * (`PUT /accounts/{accountId}/notification-policy`).
4153
+ *
4154
+ * Owners only. Merges what is sent: an event set to `false` reaches nobody
4155
+ * in the workspace on any channel, whatever each member's preferences. The
4156
+ * identity-review e-mail is always sent, because the signer cannot continue
4157
+ * without it.
4158
+ *
4159
+ * @param accountId - The workspace to change.
4160
+ * @param payload - `events` keys to change and/or `owners_receive_all`.
4161
+ * @returns The full policy, as {@link WorkspaceResource.getNotificationPolicy} returns.
4162
+ * @throws {ValidationError} If nothing would change or a value is not a boolean.
4163
+ * @throws {ApiError} `400` for an unknown event code, `403` for a non-owner or
4164
+ * an OAuth application token.
4165
+ *
4166
+ * @example
4167
+ * ```ts
4168
+ * await client.workspaces.updateNotificationPolicy('acc_example', {
4169
+ * events: { SignerViewed: false },
4170
+ * owners_receive_all: true,
4171
+ * });
4172
+ * ```
4173
+ */
4174
+ async updateNotificationPolicy(accountId, payload) {
4175
+ const id = this.requireId(accountId, "Account ID");
4176
+ assertRecord(payload, "notification policy");
4177
+ const body = {};
4178
+ if (payload.events !== void 0) {
4179
+ assertBooleanMap(payload.events, "events");
4180
+ body["events"] = { ...payload.events };
4181
+ }
4182
+ if (payload.owners_receive_all !== void 0) {
4183
+ if (typeof payload.owners_receive_all !== "boolean") {
4184
+ throw new ValidationError("owners_receive_all must be a boolean");
4185
+ }
4186
+ body["owners_receive_all"] = payload.owners_receive_all;
4187
+ }
4188
+ if (Object.keys(body).length === 0) {
4189
+ throw new ValidationError("notification policy update must change events or owners_receive_all");
4190
+ }
4191
+ return this.call(
4192
+ "Failed to update notification policy",
4193
+ () => this.http.put(`/accounts/${this.pathSegment(id, "Account ID")}/notification-policy`, body)
3865
4194
  );
3866
4195
  }
3867
4196
  /**
@@ -3870,13 +4199,13 @@ var WorkspaceResource = class extends BaseResource {
3870
4199
  * Request body/query: none.
3871
4200
  *
3872
4201
  * @param accountId - Account whose public branding should be returned.
3873
- * @returns The unwrapped theme:
4202
+ * @returns The unwrapped theme. Colours fall back to the platform default:
3874
4203
  * ```jsonc
3875
4204
  * {
3876
4205
  * "account_name": "Acme Inc.",
3877
- * "primary_color": "aabbcc",
3878
- * "secondary_color": "112233",
3879
- * "logo": "https://api.assinafy.com.br/v1/accounts/account-id/logo"
4206
+ * "primary_color": "aabbcc", // button background
4207
+ * "secondary_color": "112233", // button text
4208
+ * "logo": "https://api.assinafy.com.br/v1/accounts/account-id/logo" // null without a logo
3880
4209
  * }
3881
4210
  * ```
3882
4211
  * @throws {ValidationError} If `accountId` is empty.
@@ -4208,6 +4537,8 @@ var WebhookResource = class extends BaseResource {
4208
4537
  * "document_processing_failed"
4209
4538
  * ],
4210
4539
  * "is_active": true,
4540
+ * "is_held": false,
4541
+ * "held_since": null,
4211
4542
  * "updated_at": "2026-07-18T02:36:02Z" // no `id` / `created_at` are returned
4212
4543
  * }
4213
4544
  * ```
@@ -4377,11 +4708,12 @@ var WebhookResource = class extends BaseResource {
4377
4708
  * (`GET /accounts/{accountId}/webhooks`). Pagination info (if any) is
4378
4709
  * attached in `meta`.
4379
4710
  *
4380
- * Assinafy treats any `2xx` response as success. It makes at most two
4381
- * attempts per event with a three-second wait. After ten consecutive failed
4382
- * events, the circuit breaker pauses normal delivery and sends roughly 5%
4383
- * as recovery checks until one succeeds. The stored `response_body` is
4384
- * truncated to 2,000 characters.
4711
+ * Assinafy treats any `2xx` response as success. Retriable failures get up
4712
+ * to six attempts about ten minutes apart. After ten failed deliveries in
4713
+ * a row, the endpoint is paused and probed after 3, 15 and 60 minutes, then
4714
+ * every six hours. A successful delivery or probe resumes the endpoint and
4715
+ * replays missed events oldest first. Response bodies are truncated to
4716
+ * 2,000 characters and delivery entries are retained for seven days.
4385
4717
  *
4386
4718
  * @param params - Optional filters and pagination:
4387
4719
  * - `endpoint_id` — only deliveries to this webhook endpoint.
@@ -4408,6 +4740,10 @@ var WebhookResource = class extends BaseResource {
4408
4740
  * // subject: <User>, account_id, created_at }
4409
4741
  * },
4410
4742
  * "delivered": true,
4743
+ * "webhook_id": "9f86d081884c7d659a2feaa0c55ad015",
4744
+ * "attempt": 1,
4745
+ * "kind": "scheduled",
4746
+ * "will_retry": false,
4411
4747
  * "http_status": 200,
4412
4748
  * "response_body": "{ ... }", // receiving endpoint body, max 2,000 chars
4413
4749
  * "error": null,
@@ -4500,11 +4836,14 @@ var WebhookResource = class extends BaseResource {
4500
4836
  * [
4501
4837
  * {
4502
4838
  * "id": "65f1c2a9b3e4d5f60718293a4b5c6d7e",
4839
+ * "resource": "activity_event_subscription",
4503
4840
  * "name": "ERP",
4504
4841
  * "url": "https://example.com/webhooks/assinafy",
4505
4842
  * "email": "ops@example.com",
4506
4843
  * "events": ["document_ready", "signer_signed_document"],
4507
4844
  * "is_active": true,
4845
+ * "is_held": false,
4846
+ * "held_since": null,
4508
4847
  * "signing_enabled": true, // deliveries carry a `webhook-signature` header
4509
4848
  * "created_at": "2026-10-01T12:00:00Z",
4510
4849
  * "updated_at": "2026-10-01T12:00:00Z"
@@ -4522,7 +4861,7 @@ var WebhookResource = class extends BaseResource {
4522
4861
  */
4523
4862
  async listEndpoints(accountId, params = {}) {
4524
4863
  assertRecord(params, "webhook endpoint filters");
4525
- if (params.url !== void 0) validateWebhookUrl(params.url);
4864
+ if (params.url !== void 0) validateWebhookUrl(params.url, true);
4526
4865
  const path2 = this.endpointsPath(accountId);
4527
4866
  return this.call(
4528
4867
  "Failed to list webhook endpoints",
@@ -4536,8 +4875,8 @@ var WebhookResource = class extends BaseResource {
4536
4875
  * An account can have 1 endpoint, or up to 3 on paid plans. Each endpoint
4537
4876
  * of a workspace needs a different `url`. With `signing_enabled: true` the
4538
4877
  * API returns a signing `secret` in this creation response. Store it now:
4539
- * OAuth applications cannot call {@link WebhookResource.getEndpointSecret}
4540
- * or rotate it later. When `events` is omitted or
4878
+ * OAuth applications cannot call {@link WebhookResource.getEndpointSecret},
4879
+ * but they can rotate a lost secret. When `events` is omitted or
4541
4880
  * empty, {@link DEFAULT_WEBHOOK_EVENTS} is sent. OAuth tokens need the
4542
4881
  * `webhooks:write` scope.
4543
4882
  *
@@ -4553,19 +4892,22 @@ var WebhookResource = class extends BaseResource {
4553
4892
  * }
4554
4893
  * ```
4555
4894
  *
4556
- * @param payload - Endpoint details. `url` (absolute HTTP(S)) and `email`
4895
+ * @param payload - Endpoint details. `url` (absolute HTTPS) and `email`
4557
4896
  * are required; `events`, `name`, `is_active` and `signing_enabled` are
4558
4897
  * optional.
4559
4898
  * @param accountId - Override the client's default account ID.
4560
4899
  * @returns The created endpoint:
4561
4900
  * ```jsonc
4562
4901
  * {
4902
+ * "resource": "activity_event_subscription",
4563
4903
  * "id": "65f1c2a9b3e4d5f60718293a4b5c6d7e",
4564
4904
  * "name": "ERP",
4565
4905
  * "url": "https://example.com/webhooks/assinafy",
4566
4906
  * "email": "ops@example.com",
4567
4907
  * "events": ["document_ready", "signer_signed_document"],
4568
4908
  * "is_active": true,
4909
+ * "is_held": false,
4910
+ * "held_since": null,
4569
4911
  * "signing_enabled": true, // deliveries carry a `webhook-signature` header
4570
4912
  * "secret": "whsec_c2VjcmV0", // only in this response when signing is enabled
4571
4913
  * "created_at": "2026-10-01T12:00:00Z",
@@ -4609,12 +4951,15 @@ var WebhookResource = class extends BaseResource {
4609
4951
  * @returns The endpoint:
4610
4952
  * ```jsonc
4611
4953
  * {
4954
+ * "resource": "activity_event_subscription",
4612
4955
  * "id": "65f1c2a9b3e4d5f60718293a4b5c6d7e",
4613
4956
  * "name": "ERP",
4614
4957
  * "url": "https://example.com/webhooks/assinafy",
4615
4958
  * "email": "ops@example.com",
4616
4959
  * "events": ["document_ready", "signer_signed_document"],
4617
4960
  * "is_active": true,
4961
+ * "is_held": false,
4962
+ * "held_since": null,
4618
4963
  * "signing_enabled": true, // deliveries carry a `webhook-signature` header
4619
4964
  * "created_at": "2026-10-01T12:00:00Z",
4620
4965
  * "updated_at": "2026-10-01T12:00:00Z"
@@ -4636,12 +4981,13 @@ var WebhookResource = class extends BaseResource {
4636
4981
  /**
4637
4982
  * Change a webhook endpoint
4638
4983
  * (`PUT /accounts/{accountId}/webhooks/endpoints/{endpointId}`). Only the
4639
- * fields sent are updated; `url` cannot be one another endpoint of the
4640
- * workspace already uses.
4984
+ * fields sent are updated; a changed `url` must be HTTPS, publicly
4985
+ * routable, and different from every other endpoint in the workspace.
4641
4986
  *
4642
4987
  * `signing_enabled: true` generates a secret if the endpoint has none and
4643
- * keeps the current one otherwise; `false` discards the secret. OAuth
4644
- * tokens need the `webhooks:write` scope.
4988
+ * keeps the current one otherwise; `false` discards the secret. When this
4989
+ * request turns signing on, the response includes the new `secret` once.
4990
+ * OAuth tokens need the `webhooks:write` scope.
4645
4991
  *
4646
4992
  * Request body (`application/json`, every field optional):
4647
4993
  * ```jsonc
@@ -4661,13 +5007,17 @@ var WebhookResource = class extends BaseResource {
4661
5007
  * @returns The updated endpoint:
4662
5008
  * ```jsonc
4663
5009
  * {
5010
+ * "resource": "activity_event_subscription",
4664
5011
  * "id": "65f1c2a9b3e4d5f60718293a4b5c6d7e",
4665
5012
  * "name": "ERP",
4666
5013
  * "url": "https://example.com/webhooks/assinafy",
4667
5014
  * "email": "ops@example.com",
4668
5015
  * "events": ["document_ready", "signer_signed_document"],
4669
5016
  * "is_active": true,
5017
+ * "is_held": false,
5018
+ * "held_since": null,
4670
5019
  * "signing_enabled": true, // deliveries carry a `webhook-signature` header
5020
+ * "secret": "whsec_c2VjcmV0", // only when this request turned signing on
4671
5021
  * "created_at": "2026-10-01T12:00:00Z",
4672
5022
  * "updated_at": "2026-10-01T12:00:00Z"
4673
5023
  * }
@@ -4731,7 +5081,7 @@ var WebhookResource = class extends BaseResource {
4731
5081
  * ```
4732
5082
  */
4733
5083
  async deleteEndpointByUrl(url, accountId) {
4734
- validateWebhookUrl(url);
5084
+ validateWebhookUrl(url, true);
4735
5085
  const path2 = this.endpointsPath(accountId);
4736
5086
  return this.callVoid(
4737
5087
  "Failed to delete webhook endpoint",
@@ -4769,31 +5119,98 @@ var WebhookResource = class extends BaseResource {
4769
5119
  /**
4770
5120
  * Replace an endpoint's signing secret and return the new one
4771
5121
  * (`POST /accounts/{accountId}/webhooks/endpoints/{endpointId}/secret/rotate`).
4772
- * The old secret stops working immediately: deliveries sent after the
4773
- * rotation are signed only with the new secret, so update the receiver at
4774
- * once. Not available to OAuth applications; use an API key.
5122
+ *
5123
+ * Without `keep_previous` the old secret stops at once: update the receiver
5124
+ * immediately. With `keep_previous: true` both secrets sign deliveries for
5125
+ * 24 hours (each delivery carries one `v1,` entry per secret, which
5126
+ * `webhookVerifier.verifySignature()` already accepts), so the receiver can
5127
+ * switch without dropping events; rotating again ends the overlap. OAuth
5128
+ * tokens need the `webhooks:write` scope.
4775
5129
  *
4776
5130
  * @param endpointId - The endpoint ID.
4777
5131
  * @param accountId - Override the client's default account ID.
5132
+ * @param options - `keep_previous`: keep the old secret signing for 24 hours.
4778
5133
  * @returns The new secret:
4779
5134
  * ```jsonc
4780
- * { "secret": "whsec_bmV3LWtleS1iYXNlNjQtZW5jb2RlZA==" }
5135
+ * {
5136
+ * "secret": "whsec_bmV3LWtleS1iYXNlNjQtZW5jb2RlZA==",
5137
+ * "previous_secret_expires_at": "2026-11-12T14:00:00Z" // only with keep_previous: true
5138
+ * }
4781
5139
  * ```
4782
- * @throws {ValidationError} If `endpointId` is empty or no account ID is
4783
- * available.
5140
+ * @throws {ValidationError} If `endpointId` is empty, no account ID is
5141
+ * available, or `keep_previous` is not a boolean.
4784
5142
  * @throws {ApiError} `400` when signing is disabled on the endpoint; `404`
4785
5143
  * if it does not exist.
4786
5144
  *
4787
5145
  * @example
4788
5146
  * ```ts
4789
- * const { secret } = await client.webhooks.rotateEndpointSecret(endpoint.id);
5147
+ * const { secret } = await client.webhooks.rotateEndpointSecret(endpoint.id, undefined, {
5148
+ * keep_previous: true,
5149
+ * });
4790
5150
  * await secretStore.put('assinafy-webhook-secret', secret);
4791
5151
  * ```
4792
5152
  */
4793
- async rotateEndpointSecret(endpointId, accountId) {
5153
+ async rotateEndpointSecret(endpointId, accountId, options = {}) {
5154
+ assertRecord(options, "rotation options");
5155
+ if (options.keep_previous !== void 0 && typeof options.keep_previous !== "boolean") {
5156
+ throw new ValidationError("keep_previous must be a boolean");
5157
+ }
4794
5158
  const path2 = `${this.endpointPath(endpointId, accountId)}/secret/rotate`;
5159
+ const body = options.keep_previous === void 0 ? void 0 : { keep_previous: options.keep_previous };
4795
5160
  this.logger.info("Rotating webhook endpoint secret");
4796
- return this.call("Failed to rotate webhook endpoint secret", () => this.http.post(path2));
5161
+ return this.call("Failed to rotate webhook endpoint secret", () => this.http.post(path2, body));
5162
+ }
5163
+ /**
5164
+ * Send the endpoint one `webhook_test` event now
5165
+ * (`POST /accounts/{accountId}/webhooks/endpoints/{endpointId}/test`).
5166
+ *
5167
+ * Signed and sent like any delivery, to this endpoint only, also while it is
5168
+ * paused or inactive; it neither lifts nor counts toward a pause. The
5169
+ * endpoint has 10 seconds to answer. The event's `payload` and `origin` are
5170
+ * `null`, and its `subject`/`object` describe the endpoint (never its
5171
+ * secret). Up to 10 tests per user every 10 minutes; OAuth tokens need
5172
+ * `webhooks:write`.
5173
+ *
5174
+ * @param endpointId - The endpoint ID.
5175
+ * @param accountId - Override the client's default account ID.
5176
+ * @returns The delivery attempt, also listed in the delivery history:
5177
+ * ```jsonc
5178
+ * {
5179
+ * "resource": "activity_dispatching_history",
5180
+ * "id": "1052b3c4d5e6f7a8b9c0d1e2f3a4",
5181
+ * "event": "webhook_test",
5182
+ * "activity_id": 8240001,
5183
+ * "endpoint_id": "1052b0e1f2a3b4c5d6e7f8a9b0c1",
5184
+ * "endpoint": "https://hooks.example.com/assinafy",
5185
+ * "payload": { // the event as delivered
5186
+ * "id": 8240001, "event": "webhook_test", "payload": null, "origin": null,
5187
+ * "account_id": "acc_example", "subject": { "type": "ActivityEventSubscription" }
5188
+ * },
5189
+ * "delivered": true,
5190
+ * "webhook_id": "msg_2v9TQ0a7",
5191
+ * "attempt": 1,
5192
+ * "kind": "manual",
5193
+ * "will_retry": false,
5194
+ * "duration_ms": 182,
5195
+ * "http_status": 200,
5196
+ * "response_body": "ok",
5197
+ * "error": null,
5198
+ * "created_at": "2026-11-11T14:00:00Z",
5199
+ * "updated_at": "2026-11-11T14:00:00Z"
5200
+ * }
5201
+ * ```
5202
+ * @throws {ValidationError} If `endpointId` is empty or no account ID is available.
5203
+ * @throws {ApiError} `404` for an unknown endpoint, `429` past 10 tests in 10 minutes.
5204
+ *
5205
+ * @example
5206
+ * ```ts
5207
+ * const attempt = await client.webhooks.testEndpoint(endpoint.id);
5208
+ * if (!attempt.delivered) console.warn(attempt.http_status, attempt.error);
5209
+ * ```
5210
+ */
5211
+ async testEndpoint(endpointId, accountId) {
5212
+ const path2 = `${this.endpointPath(endpointId, accountId)}/test`;
5213
+ return this.call("Failed to send webhook test delivery", () => this.http.post(path2));
4797
5214
  }
4798
5215
  endpointsPath(accountId) {
4799
5216
  const id = this.pathSegment(this.accountId(accountId), "Account ID");
@@ -4832,15 +5249,15 @@ function validateWebhookFields(payload, required) {
4832
5249
  throw new ValidationError("Webhook name must be a string");
4833
5250
  }
4834
5251
  }
4835
- function validateWebhookUrl(value) {
5252
+ function validateWebhookUrl(value, allowStoredHttp = false) {
4836
5253
  let url;
4837
5254
  try {
4838
5255
  url = new URL(value ?? "");
4839
5256
  } catch {
4840
- throw new ValidationError("Webhook URL must be an absolute HTTP(S) URL", { url: value });
5257
+ throw new ValidationError("Webhook URL must be an absolute HTTPS URL", { url: value });
4841
5258
  }
4842
- if (url.protocol !== "https:" && url.protocol !== "http:" || !url.hostname) {
4843
- throw new ValidationError("Webhook URL must be an absolute HTTP(S) URL", { url: value });
5259
+ if (url.protocol !== "https:" && !(allowStoredHttp && url.protocol === "http:") || !url.hostname) {
5260
+ throw new ValidationError("Webhook URL must be an absolute HTTPS URL", { url: value });
4844
5261
  }
4845
5262
  }
4846
5263
 
@@ -6080,7 +6497,10 @@ var OAuthResource = class extends BaseResource {
6080
6497
  * `['documents:read', 'documents:write', 'offline_access']`. Ask for the
6081
6498
  * minimum: the user approves all of them or none. Add `offline_access` to
6082
6499
  * receive a refresh token and `openid` to receive an `id_token`.
6083
- * `webhooks:write` permits subscription updates and inactivation.
6500
+ * `account:read` reads the workspace profile, theme, logo, KPIs, webhook
6501
+ * subscription and endpoints, and its signing features; `webhooks:write`
6502
+ * changes the subscription, manages endpoints, re-sends and tests
6503
+ * deliveries, and can obtain a new signing secret (signing on, or rotation).
6084
6504
  * @param options.authorizationEndpoint - Skip discovery by supplying the
6085
6505
  * endpoint yourself. Defaults to the discovered
6086
6506
  * `authorization_endpoint`.
@@ -6306,6 +6726,8 @@ var OAuthResource = class extends BaseResource {
6306
6726
  * @throws {OAuthError} `invalid_grant` for a spent, expired, replayed or
6307
6727
  * mismatched code; `invalid_client` for a bad `client_id`/`client_secret`;
6308
6728
  * `invalid_target` for a `resource` mismatch.
6729
+ * @throws {ApiError} `429` when the caller's IP is rate limited; token calls
6730
+ * are never retried automatically, so wait `rateLimit.retryAfter` seconds.
6309
6731
  *
6310
6732
  * @example
6311
6733
  * ```ts
@@ -6380,6 +6802,8 @@ var OAuthResource = class extends BaseResource {
6380
6802
  * @throws {OAuthError} `invalid_grant` when the refresh token was already
6381
6803
  * used, expired, or the user reconnected with different permissions — ask
6382
6804
  * the user to reconnect. `invalid_client` for bad client credentials.
6805
+ * @throws {ApiError} `429` when the caller's IP is rate limited (not retried
6806
+ * automatically: a replayed refresh token ends the connection).
6383
6807
  *
6384
6808
  * @example
6385
6809
  * ```ts
@@ -6664,6 +7088,11 @@ function toSearchParams(params) {
6664
7088
 
6665
7089
  // src/resources/fields.ts
6666
7090
  var FieldsResource = class extends BaseResource {
7091
+ signerHttp;
7092
+ constructor(http, defaultAccountId, logger, publicHttp) {
7093
+ super(http, defaultAccountId, logger);
7094
+ this.signerHttp = withoutCredentials(publicHttp ?? http);
7095
+ }
6667
7096
  /**
6668
7097
  * Create a field definition (`POST /accounts/{accountId}/fields`).
6669
7098
  *
@@ -6915,9 +7344,9 @@ var FieldsResource = class extends BaseResource {
6915
7344
  * Validate a single value against a field definition
6916
7345
  * (`POST /accounts/{accountId}/fields/{fieldId}/validate`).
6917
7346
  *
6918
- * The operation uses the client's API-key/Bearer authentication.
6919
- * `signerAccessCode` is a compatibility query and is sent as
6920
- * `signer-access-code` when supplied.
7347
+ * Without `signerAccessCode` the call uses the workspace credentials. With
7348
+ * it, the code is sent as the `signer-access-code` query on the
7349
+ * credential-free transport, as a custom signing UI does.
6921
7350
  *
6922
7351
  * Request body (`application/json`):
6923
7352
  * ```jsonc
@@ -6929,9 +7358,9 @@ var FieldsResource = class extends BaseResource {
6929
7358
  * @param fieldId - The field definition to validate against.
6930
7359
  * @param value - The value to check (validated against the field's
6931
7360
  * type/regex). Sent as `{ value }` in the request body.
6932
- * @param options - Account override and optional legacy `signerAccessCode`.
7361
+ * @param options - Account override and optional `signerAccessCode`.
6933
7362
  * @param options.accountId - Override the client's default workspace.
6934
- * @param options.signerAccessCode - Legacy signer code sent as a query parameter.
7363
+ * @param options.signerAccessCode - Authenticate as the signer instead of the workspace.
6935
7364
  * @returns The validation result. Response shape:
6936
7365
  * ```jsonc
6937
7366
  * {
@@ -6942,7 +7371,9 @@ var FieldsResource = class extends BaseResource {
6942
7371
  * ```
6943
7372
  * @throws {ValidationError} If `fieldId` or the account ID is missing, or
6944
7373
  * `value` is `undefined`.
6945
- * @throws {ApiError} If the API rejects the request.
7374
+ * @throws {ApiError} `400` for a malformed request, `403` when the code or
7375
+ * credentials cannot reach the workspace, `404` for a field outside it, `410`
7376
+ * when the signer's access code is closed.
6946
7377
  *
6947
7378
  * @example
6948
7379
  * ```ts
@@ -6964,7 +7395,7 @@ var FieldsResource = class extends BaseResource {
6964
7395
  const params = options.signerAccessCode ? { "signer-access-code": options.signerAccessCode } : void 0;
6965
7396
  return this.call(
6966
7397
  "Failed to validate field value",
6967
- () => this.http.post(
7398
+ () => this.transportFor(options.signerAccessCode).post(
6968
7399
  `/accounts/${this.pathSegment(id, "Account ID")}/fields/${this.pathSegment(fid, "Field ID")}/validate`,
6969
7400
  { value },
6970
7401
  { params }
@@ -6976,9 +7407,8 @@ var FieldsResource = class extends BaseResource {
6976
7407
  * (`POST /accounts/{accountId}/fields/validate-multiple`).
6977
7408
  *
6978
7409
  * The request body is the array of `{ field_id, value }` entries itself
6979
- * (not wrapped in an object). The optional `signerAccessCode` query is the
6980
- * same compatibility extension described on
6981
- * {@link FieldsResource.validate}.
7410
+ * (not wrapped in an object). `signerAccessCode` authenticates as described
7411
+ * on {@link FieldsResource.validate}.
6982
7412
  *
6983
7413
  * Request body (`application/json`):
6984
7414
  * ```jsonc
@@ -6991,9 +7421,9 @@ var FieldsResource = class extends BaseResource {
6991
7421
  * ```
6992
7422
  *
6993
7423
  * @param entries - Non-empty array of `{ field_id, value }` pairs.
6994
- * @param options - Account override and optional legacy `signerAccessCode`.
7424
+ * @param options - Account override and optional `signerAccessCode`.
6995
7425
  * @param options.accountId - Override the client's default workspace.
6996
- * @param options.signerAccessCode - Legacy signer code sent as a query parameter.
7426
+ * @param options.signerAccessCode - Authenticate as the signer instead of the workspace.
6997
7427
  * @returns One validation result per entry. Response shape:
6998
7428
  * ```jsonc
6999
7429
  * [
@@ -7002,7 +7432,7 @@ var FieldsResource = class extends BaseResource {
7002
7432
  * ]
7003
7433
  * ```
7004
7434
  * @throws {ValidationError} If `entries` is empty or the account ID is missing.
7005
- * @throws {ApiError} If the API rejects the request.
7435
+ * @throws {ApiError} `400`, `403`, `404` or `410`, as for {@link FieldsResource.validate}.
7006
7436
  *
7007
7437
  * @example
7008
7438
  * ```ts
@@ -7030,7 +7460,7 @@ var FieldsResource = class extends BaseResource {
7030
7460
  }));
7031
7461
  return this.call(
7032
7462
  "Failed to validate field values",
7033
- () => this.http.post(
7463
+ () => this.transportFor(options.signerAccessCode).post(
7034
7464
  `/accounts/${this.pathSegment(id, "Account ID")}/fields/validate-multiple`,
7035
7465
  body,
7036
7466
  { params }
@@ -7064,6 +7494,10 @@ var FieldsResource = class extends BaseResource {
7064
7494
  async listTypes() {
7065
7495
  return this.call("Failed to list field types", () => this.http.get("/field-types"));
7066
7496
  }
7497
+ /** A signer access code must never travel with the workspace credentials. */
7498
+ transportFor(signerAccessCode) {
7499
+ return signerAccessCode === void 0 ? this.http : this.signerHttp;
7500
+ }
7067
7501
  };
7068
7502
  function validateFieldPayload(payload) {
7069
7503
  if (payload.regex !== void 0 && payload.regex !== null && typeof payload.regex !== "string") {
@@ -7096,11 +7530,17 @@ var SignerDocumentsResource = class extends BaseResource {
7096
7530
  * (`GET /signers/{signer_id}/document?signer-access-code=…`).
7097
7531
  *
7098
7532
  * The signer-side counterpart of {@link DocumentResource.details}, authorised
7099
- * by the signer's access code rather than the workspace API key.
7533
+ * by the signer's access code rather than the workspace API key. Unlike
7534
+ * {@link SignerDocumentsResource.getAssignment} it does not record a view and
7535
+ * answers before a certificate or identity-check signer confirms their data,
7536
+ * so a link learns its envelope here.
7100
7537
  *
7101
7538
  * @param signerId - The signer whose current document is fetched.
7102
7539
  * @param signerAccessCode - The signer's access code, from their signing link.
7103
- * @returns The document in the full {@link IDocumentDetailsResponse} shape:
7540
+ * @param options - `expand: ['envelope']` adds the code's envelope (`{ id, name }`, or `null`).
7541
+ * @returns The {@link ISigningDocument}. Once the code is closed (30 minutes
7542
+ * after the signer is done) only `id`, `name`, `status`, `current_signer`,
7543
+ * `certified_copy` and `envelope` remain, with `is_signer_access_closed: true`:
7104
7544
  * ```jsonc
7105
7545
  * {
7106
7546
  * "resource": "document",
@@ -7123,26 +7563,38 @@ var SignerDocumentsResource = class extends BaseResource {
7123
7563
  * { "id": "103acccd5c73...", "number": 1, "height": 1651, "width": 1275,
7124
7564
  * "download_url": "https://api.assinafy.com.br/v1/documents/103acccd.../pages/103acccd5c73.../download" }
7125
7565
  * ],
7566
+ * "current_signer": {
7567
+ * "id": "19e6b92e7895332ed9708535d8c",
7568
+ * "full_name": "Example Signer",
7569
+ * "email": "signer@example.com",
7570
+ * "verification_method": "Email",
7571
+ * "notification_methods": ["Email"],
7572
+ * "completed": false
7573
+ * },
7574
+ * "is_signer_access_closed": false,
7575
+ * "certified_copy": { "available": false, "notification_method": "Email", "resends_left": null },
7576
+ * "envelope": { "id": "1052a1f0c3d4e5f6a7b8c9d0e1f2", "name": "Admission kit" }, // with expand
7126
7577
  * "created_at": "2026-07-19T14:56:54Z",
7127
7578
  * "updated_at": "2026-07-19T14:56:56Z"
7128
7579
  * }
7129
7580
  * ```
7130
7581
  * @throws {ValidationError} If `signerId` or `signerAccessCode` is missing.
7131
- * @throws {ApiError} If the access code is invalid or expired.
7582
+ * @throws {ApiError} `400` while the signer's step has not started, `401` for an
7583
+ * invalid code, `404` for an unknown signer.
7132
7584
  *
7133
7585
  * @example
7134
7586
  * ```ts
7135
- * const doc = await client.signerDocuments.getCurrent(signerId, accessCode);
7136
- * console.log(doc.status, doc.pages.length);
7587
+ * const doc = await client.signerDocuments.getCurrent(signerId, accessCode, { expand: ['envelope'] });
7588
+ * if (doc.is_signer_access_closed) console.log(doc.certified_copy.available);
7137
7589
  * ```
7138
7590
  */
7139
- async getCurrent(signerId, signerAccessCode) {
7591
+ async getCurrent(signerId, signerAccessCode, options = {}) {
7140
7592
  const sid = this.requireId(signerId, "Signer ID");
7141
7593
  const code = this.requireId(signerAccessCode, "signer-access-code");
7142
7594
  return this.call(
7143
7595
  "Failed to fetch current signer document",
7144
7596
  () => this.http.get(`/signers/${this.pathSegment(sid, "Signer ID")}/document`, {
7145
- params: { "signer-access-code": code }
7597
+ params: { "signer-access-code": code, ...signingReadParams(options) }
7146
7598
  })
7147
7599
  );
7148
7600
  }
@@ -7157,9 +7609,10 @@ var SignerDocumentsResource = class extends BaseResource {
7157
7609
  *
7158
7610
  * @param signerId - The signer whose documents are listed.
7159
7611
  * @param signerAccessCode - The signer's access code, from their signing link.
7160
- * @param params - Pagination: `page`, `per-page` (also accepts `per_page`).
7161
- * @returns Matching documents in the compact {@link IDocumentListItem} shape,
7162
- * with pagination in `meta`:
7612
+ * @param params - `envelope_id` (only that envelope's documents) and pagination:
7613
+ * `page`, `per-page` (also accepts `per_page`).
7614
+ * @returns Matching documents with pagination in `meta`. Each carries its
7615
+ * `assignment` (without `signing_urls` when read with a code) and `pages`:
7163
7616
  * ```jsonc
7164
7617
  * {
7165
7618
  * "data": [
@@ -7183,11 +7636,13 @@ var SignerDocumentsResource = class extends BaseResource {
7183
7636
  * }
7184
7637
  * ```
7185
7638
  * @throws {ValidationError} If `signerId` or `signerAccessCode` is missing.
7186
- * @throws {ApiError} If the access code is invalid or expired.
7639
+ * @throws {ApiError} `400` for a non-text `envelope_id` or a pending step,
7640
+ * `403` for another signer's code, `410` once the code is closed.
7187
7641
  *
7188
7642
  * @example
7189
7643
  * ```ts
7190
7644
  * const { data, meta } = await client.signerDocuments.list(signerId, accessCode, {
7645
+ * envelope_id: envelopeId,
7191
7646
  * 'per-page': 20,
7192
7647
  * });
7193
7648
  * ```
@@ -7214,8 +7669,8 @@ var SignerDocumentsResource = class extends BaseResource {
7214
7669
  * @param signerId - The signer whose documents are searched.
7215
7670
  * @param signerAccessCode - The signer's access code, from their signing link.
7216
7671
  * @param search - Free-text term matched against the document name.
7217
- * @returns Matching documents for that signer, in the compact
7218
- * {@link IDocumentListItem} shape, with pagination in `meta`:
7672
+ * @param params - `envelope_id`: only that envelope's documents.
7673
+ * @returns Matching documents for that signer, with pagination in `meta`:
7219
7674
  * ```jsonc
7220
7675
  * {
7221
7676
  * "data": [
@@ -7239,7 +7694,7 @@ var SignerDocumentsResource = class extends BaseResource {
7239
7694
  * }
7240
7695
  * ```
7241
7696
  * @throws {ValidationError} If `signerId` or `signerAccessCode` is missing.
7242
- * @throws {ApiError} If the access code is invalid or expired.
7697
+ * @throws {ApiError} `400`, `403` or `410`, as for {@link SignerDocumentsResource.list}.
7243
7698
  *
7244
7699
  * @example
7245
7700
  * ```ts
@@ -7250,16 +7705,13 @@ var SignerDocumentsResource = class extends BaseResource {
7250
7705
  * );
7251
7706
  * ```
7252
7707
  */
7253
- async search(signerId, signerAccessCode, search) {
7708
+ async search(signerId, signerAccessCode, search, params = {}) {
7254
7709
  const sid = this.requireId(signerId, "Signer ID");
7255
7710
  const code = this.requireId(signerAccessCode, "signer-access-code");
7256
- if (search !== void 0 && typeof search !== "string") {
7257
- throw new ValidationError("search must be a string");
7258
- }
7259
7711
  return this.callList(
7260
7712
  "Failed to search signer documents",
7261
7713
  () => this.http.get(`/signers/${this.pathSegment(sid, "Signer ID")}/documents/search`, {
7262
- params: cleanParams({ "signer-access-code": code, search })
7714
+ params: { "signer-access-code": code, ...searchParams(search, params) }
7263
7715
  })
7264
7716
  );
7265
7717
  }
@@ -7272,8 +7724,8 @@ var SignerDocumentsResource = class extends BaseResource {
7272
7724
  * code. No `signer-access-code` is sent.
7273
7725
  *
7274
7726
  * @param signerId - The signer whose documents are listed.
7275
- * @param params - Pagination: `page`, `per-page` (also accepts `per_page`).
7276
- * @returns Documents in the compact {@link IDocumentListItem} shape, with
7727
+ * @param params - `envelope_id` and pagination: `page`, `per-page` (also accepts `per_page`).
7728
+ * @returns Documents in the {@link IDocumentListItem} shape, with
7277
7729
  * pagination in `meta` (same shape as {@link SignerDocumentsResource.list}):
7278
7730
  * ```jsonc
7279
7731
  * {
@@ -7282,7 +7734,8 @@ var SignerDocumentsResource = class extends BaseResource {
7282
7734
  * }
7283
7735
  * ```
7284
7736
  * @throws {ValidationError} If `signerId` is missing.
7285
- * @throws {ApiError} `401` if the workspace credentials are rejected.
7737
+ * @throws {ApiError} `401` if the workspace credentials are rejected, `403` when a
7738
+ * role or OAuth scope refuses it, `404` for a signer outside the workspace.
7286
7739
  *
7287
7740
  * @example
7288
7741
  * ```ts
@@ -7291,11 +7744,11 @@ var SignerDocumentsResource = class extends BaseResource {
7291
7744
  */
7292
7745
  async listAsWorkspace(signerId, params = {}) {
7293
7746
  const sid = this.pathSegment(signerId, "Signer ID");
7747
+ const query = cleanListParams(params);
7748
+ delete query["signer-access-code"];
7294
7749
  return this.callList(
7295
7750
  "Failed to list signer documents",
7296
- () => this.workspaceHttp.get(`/signers/${sid}/documents`, {
7297
- params: cleanListParams(params)
7298
- })
7751
+ () => this.workspaceHttp.get(`/signers/${sid}/documents`, { params: query })
7299
7752
  );
7300
7753
  }
7301
7754
  /**
@@ -7308,53 +7761,45 @@ var SignerDocumentsResource = class extends BaseResource {
7308
7761
  *
7309
7762
  * @param signerId - The signer whose documents are searched.
7310
7763
  * @param search - Free-text term matched against the document name.
7764
+ * @param params - `envelope_id`: only that envelope's documents.
7311
7765
  * @returns Matching documents with pagination in `meta`, as
7312
7766
  * {@link SignerDocumentsResource.listAsWorkspace} returns.
7313
7767
  * @throws {ValidationError} If `signerId` is missing or `search` is not a string.
7314
- * @throws {ApiError} `401` if the workspace credentials are rejected.
7768
+ * @throws {ApiError} `401`, `403` or `404`, as for {@link SignerDocumentsResource.listAsWorkspace}.
7315
7769
  *
7316
7770
  * @example
7317
7771
  * ```ts
7318
7772
  * const { data } = await client.signerDocuments.searchAsWorkspace(signerId, 'agreement');
7319
7773
  * ```
7320
7774
  */
7321
- async searchAsWorkspace(signerId, search) {
7775
+ async searchAsWorkspace(signerId, search, params = {}) {
7322
7776
  const sid = this.pathSegment(signerId, "Signer ID");
7323
- if (search !== void 0 && typeof search !== "string") {
7324
- throw new ValidationError("search must be a string");
7325
- }
7326
7777
  return this.callList(
7327
7778
  "Failed to search signer documents",
7328
7779
  () => this.workspaceHttp.get(`/signers/${sid}/documents/search`, {
7329
- params: cleanParams({ search })
7780
+ params: searchParams(search, params)
7330
7781
  })
7331
7782
  );
7332
7783
  }
7333
7784
  /**
7334
- * Download one of a signer's document artifacts as raw bytes
7335
- * (`GET /signers/{signer_id}/documents/{document_id}/download/{artifact}`).
7785
+ * Download the original PDF a signer is asked to sign
7786
+ * (`GET /signers/{signer_id}/documents/{document_id}/download/original`).
7336
7787
  *
7337
- * The signer-side counterpart of {@link DocumentResource.download}: same
7338
- * artifact names, exposed by the API as a public signer-link endpoint. The
7339
- * optional access-code argument is retained for compatibility with deployed
7340
- * environments that still accept or require the legacy query parameter. The
7341
- * `certificated` and `bundle` exist only once the document is fully signed.
7342
- * `pades` exists only when the document had a Digital Certificate signer.
7343
- * A bundle contains original, certificated, and certificate-page artifacts,
7344
- * plus PAdES when present.
7788
+ * Only `original` is available with an access code; the certified copy is
7789
+ * sent to the signer instead (see {@link SignerDocumentsResource.resendCertifiedCopy}).
7790
+ * The API redirects a request it cannot serve to its expired-link page, so
7791
+ * the SDK does not follow redirects here: that case throws instead of
7792
+ * returning the page's HTML.
7345
7793
  *
7346
7794
  * @param signerId - The signer requesting the download.
7347
7795
  * @param documentId - The document to download.
7348
- * @param artifactName - Which artifact to fetch (`original`, `certificated`,
7349
- * `certificate-page`, `pades`, or `bundle`).
7350
- * @param signerAccessCode - Optional legacy signer access code. Omit it for
7351
- * the official public request shape.
7352
- * @returns The raw artifact bytes as a Node `Buffer` (PDF except for the
7353
- * ZIP `bundle`).
7354
- * @throws {ValidationError} If `signerId` or `documentId` is missing,
7355
- * `artifactName` is not one of the five documented names, or an explicitly
7356
- * supplied legacy `signerAccessCode` is blank.
7357
- * @throws {ApiError} `404` if the artifact does not exist yet.
7796
+ * @param artifactName - `original`, the only artifact a signer can download.
7797
+ * @param signerAccessCode - The signer's access code, from their signing link.
7798
+ * @returns The PDF bytes as a Node `Buffer`.
7799
+ * @throws {ValidationError} If an ID or the code is missing, or the artifact is not `original`.
7800
+ * @throws {ApiError} `302` when the code is missing or closed, `400` while the
7801
+ * signer's step has not started, `403` for another artifact, `404` for a
7802
+ * document the code does not reach, `410` once the code is closed.
7358
7803
  *
7359
7804
  * @example
7360
7805
  * ```ts
@@ -7362,6 +7807,7 @@ var SignerDocumentsResource = class extends BaseResource {
7362
7807
  * signerId,
7363
7808
  * documentId,
7364
7809
  * 'original',
7810
+ * accessCode,
7365
7811
  * );
7366
7812
  * await fs.promises.writeFile('to-sign.pdf', pdf);
7367
7813
  * ```
@@ -7369,16 +7815,15 @@ var SignerDocumentsResource = class extends BaseResource {
7369
7815
  async download(signerId, documentId, artifactName, signerAccessCode) {
7370
7816
  const sid = this.requireId(signerId, "Signer ID");
7371
7817
  const did = this.requireId(documentId, "Document ID");
7372
- assertDocumentArtifactName(artifactName);
7373
- const code = signerAccessCode === void 0 ? void 0 : this.requireId(signerAccessCode, "signer-access-code");
7818
+ if (artifactName !== "original") {
7819
+ throw new ValidationError("A signer can download only the original artifact");
7820
+ }
7821
+ const code = this.requireId(signerAccessCode, "signer-access-code");
7374
7822
  return this.callBinary(
7375
7823
  "Failed to download signer document",
7376
7824
  () => this.http.get(
7377
- `/signers/${this.pathSegment(sid, "Signer ID")}/documents/${this.pathSegment(did, "Document ID")}/download/${this.pathSegment(artifactName, "Artifact name")}`,
7378
- code === void 0 ? { responseType: "arraybuffer" } : {
7379
- responseType: "arraybuffer",
7380
- params: { "signer-access-code": code }
7381
- }
7825
+ `/signers/${this.pathSegment(sid, "Signer ID")}/documents/${this.pathSegment(did, "Document ID")}/download/original`,
7826
+ { ...BINARY_NO_REDIRECT, params: { "signer-access-code": code } }
7382
7827
  )
7383
7828
  );
7384
7829
  }
@@ -7624,10 +8069,15 @@ var SignerDocumentsResource = class extends BaseResource {
7624
8069
  * flag.
7625
8070
  *
7626
8071
  * @param signerAccessCode - The signer's access code, from their signing link.
7627
- * @returns Resolves when the API acknowledges the operation. The response
7628
- * envelope has no `data` field and is intentionally discarded.
8072
+ * @returns The signer's acceptance state, or `null` from deployments that
8073
+ * acknowledge without data:
8074
+ * ```jsonc
8075
+ * { "full_name": "Example Signer", "email": "signer@example.com", "has_accepted_terms": true }
8076
+ * ```
7629
8077
  * @throws {ValidationError} If `signerAccessCode` is missing.
7630
- * @throws {ApiError} If the access code is invalid or expired.
8078
+ * @throws {ApiError} `400` while the signer's verification is not done (e.g.
8079
+ * the e-mail code) or their step has not started, `401` for an invalid code,
8080
+ * `410` once the code is closed.
7631
8081
  *
7632
8082
  * @example
7633
8083
  * ```ts
@@ -7637,12 +8087,13 @@ var SignerDocumentsResource = class extends BaseResource {
7637
8087
  */
7638
8088
  async acceptTerms(signerAccessCode) {
7639
8089
  const code = this.requireId(signerAccessCode, "signer-access-code");
7640
- return this.callVoid(
8090
+ const data = await this.call(
7641
8091
  "Failed to accept terms",
7642
8092
  () => this.http.put("/signers/accept-terms", void 0, {
7643
8093
  params: { "signer-access-code": code }
7644
8094
  })
7645
8095
  );
8096
+ return data ?? null;
7646
8097
  }
7647
8098
  /**
7648
8099
  * Verify the signer's email or WhatsApp one-time password
@@ -7693,12 +8144,56 @@ var SignerDocumentsResource = class extends BaseResource {
7693
8144
  )
7694
8145
  );
7695
8146
  }
8147
+ /**
8148
+ * Confirm the signer's contact data before signing
8149
+ * (`PUT /documents/{documentId}/signers/confirm-data?signer-access-code=…`).
8150
+ *
8151
+ * Send the contact the signer's channel needs: `email` for e-mail
8152
+ * verification or notification, `whatsapp_phone_number` for WhatsApp. Each
8153
+ * is saved when the signer has none; otherwise it must be theirs, so it
8154
+ * cannot change the record. `has_accepted_terms: true` also records the
8155
+ * terms, which opens `getAssignment()` for a `DigitalCertificate` signer.
8156
+ * With an envelope code it acts on the document the route names. Only the
8157
+ * fields provided are sent.
8158
+ *
8159
+ * Request body (`application/json`):
8160
+ * ```jsonc
8161
+ * {
8162
+ * "email": "signer@example.com",
8163
+ * "has_accepted_terms": true
8164
+ * }
8165
+ * ```
8166
+ *
8167
+ * @param documentId - The document the signer is confirming data for.
8168
+ * @param signerAccessCode - The signer's access code, from their signing link.
8169
+ * @param payload - `email`, `whatsapp_phone_number` and `has_accepted_terms`.
8170
+ * `full_name`/`government_id` are forwarded only for older deployments.
8171
+ * @returns `null` on production, which answers `data: []`; older deployments
8172
+ * return the signer:
8173
+ * ```jsonc
8174
+ * { "resource": "signer", "id": "19e6b92e7895332ed9708535d8c", "full_name": "Example Signer",
8175
+ * "email": "signer@example.com", "whatsapp_phone_number": null, "has_accepted_terms": true }
8176
+ * ```
8177
+ * @throws {ValidationError} If `documentId` or `signerAccessCode` is missing,
8178
+ * or a supplied value is malformed.
8179
+ * @throws {ApiError} `400` when a contact the signer's methods need is missing,
8180
+ * invalid or not theirs, or their step has not started; `404` for a document
8181
+ * the code does not reach; `410` once the code is closed.
8182
+ *
8183
+ * @example
8184
+ * ```ts
8185
+ * await client.signerDocuments.confirmData(documentId, accessCode, {
8186
+ * email: 'signer@example.com',
8187
+ * has_accepted_terms: true,
8188
+ * });
8189
+ * ```
8190
+ */
7696
8191
  async confirmData(documentId, signerAccessCode, payload) {
7697
8192
  assertRecord(payload, "signer confirmation payload");
7698
8193
  validateConfirmDataPayload(payload);
7699
8194
  const did = this.requireId(documentId, "Document ID");
7700
8195
  const code = this.requireId(signerAccessCode, "signer-access-code");
7701
- return this.call(
8196
+ const data = await this.call(
7702
8197
  "Failed to confirm signer data",
7703
8198
  () => this.http.put(
7704
8199
  `/documents/${this.pathSegment(did, "Document ID")}/signers/confirm-data`,
@@ -7712,6 +8207,7 @@ var SignerDocumentsResource = class extends BaseResource {
7712
8207
  { params: { "signer-access-code": code } }
7713
8208
  )
7714
8209
  );
8210
+ return data !== null && typeof data === "object" && !Array.isArray(data) ? data : null;
7715
8211
  }
7716
8212
  async uploadSignature(signerAccessCode, image, options = {}) {
7717
8213
  const code = this.requireId(signerAccessCode, "signer-access-code");
@@ -7792,14 +8288,17 @@ var SignerDocumentsResource = class extends BaseResource {
7792
8288
  * the SDK never automatically replays this particular `GET` after a `429`.
7793
8289
  *
7794
8290
  * @param signerAccessCode - The signer's access code, from their signing link.
7795
- * @param hasAcceptedTerms - Maps to the `has_accepted_terms` query param
7796
- * (server default `false`); pass `true` once the signer has accepted terms.
7797
- * `false`/`undefined` is omitted only when `undefined` (an explicit `false`
7798
- * is still sent).
7799
- * @returns The document to sign, including its `assignment` (the
7800
- * {@link IAssignment} shape: `signers`, `items`, `summary`, `signing_urls`)
7801
- * from which the `itemId` / `fieldId` / `pageId` values for
7802
- * {@link SignerDocumentsResource.sign} are read:
8291
+ * @param options - `true`/`false` (the `has_accepted_terms` query, kept for
8292
+ * existing calls) or an options object:
8293
+ * `hasAcceptedTerms` (an explicit `false` is still sent), `expand:
8294
+ * ['envelope']` (adds the code's envelope), and `documentId` (with an
8295
+ * envelope code, open another document of that envelope the signer is on).
8296
+ * @returns The {@link ISigningDocument}. Its `assignment` carries only this
8297
+ * signer's items — no other signers, `signing_urls`, copy receivers or
8298
+ * `summary` — from which the `itemId` / `fieldId` / `pageId` values for
8299
+ * {@link SignerDocumentsResource.sign} are read. A closed code returns
8300
+ * only `id`, `name`, `status`, `current_signer`, `certified_copy` and
8301
+ * `envelope`, with `is_signer_access_closed: true`:
7803
8302
  * ```jsonc
7804
8303
  * {
7805
8304
  * "resource": "document",
@@ -7830,9 +8329,12 @@ var SignerDocumentsResource = class extends BaseResource {
7830
8329
  * { "id": "item-1", "page": { "id": "page-1", "number": 1, "height": 1651, "width": 1275,
7831
8330
  * "download_url": "https://..." }, "signer": { "id": "19e6b92e..." },
7832
8331
  * "field": { "id": "field-1", "type": "signature" }, "value": null, "completed": false }
7833
- * ],
7834
- * "summary": { "signer_count": 1, "completed_count": 0, "signers": [] }
8332
+ * ]
7835
8333
  * },
8334
+ * "current_signer": { "id": "19e6b92e7895332ed9708535d8c", "verification_method": "Email",
8335
+ * "notification_methods": ["Email"], "completed": false },
8336
+ * "is_signer_access_closed": false,
8337
+ * "certified_copy": { "available": false, "notification_method": "Email", "resends_left": null },
7836
8338
  * "pages": [
7837
8339
  * { "id": "103acccd5c73...", "number": 1, "height": 1651, "width": 1275,
7838
8340
  * "download_url": "https://api.assinafy.com.br/v1/documents/103acccd.../pages/103acccd5c73.../download" }
@@ -7841,53 +8343,211 @@ var SignerDocumentsResource = class extends BaseResource {
7841
8343
  * "updated_at": "2026-07-19T14:56:56Z"
7842
8344
  * }
7843
8345
  * ```
7844
- * @throws {ValidationError} If `signerAccessCode` is missing.
7845
- * @throws {ApiError} `400` when DigitalCertificate identity/terms are not
7846
- * confirmed; `401`/`403` if the access code is invalid or expired; `409`
7847
- * while the document is still being prepared.
8346
+ * @throws {ValidationError} If `signerAccessCode` is missing or an option is malformed.
8347
+ * @throws {ApiError} `400` when a DigitalCertificate signer has not confirmed
8348
+ * data and terms, the signer's step has not started, or `documentId` is
8349
+ * not an ID; `401` for an invalid code; `404` when `documentId` is outside
8350
+ * the code's envelope; `409` (`DocumentNotReady`) while the document is
8351
+ * still being prepared.
7848
8352
  *
7849
8353
  * @example
7850
8354
  * ```ts
7851
- * // query → ?signer-access-code=<code>&has_accepted_terms=true
7852
- * const assignment = await client.signerDocuments.getAssignment(accessCode, true);
8355
+ * // query → ?signer-access-code=<code>&has_accepted_terms=true&expand=envelope
8356
+ * const doc = await client.signerDocuments.getAssignment(accessCode, {
8357
+ * hasAcceptedTerms: true,
8358
+ * expand: ['envelope'],
8359
+ * });
7853
8360
  * ```
7854
8361
  */
7855
- async getAssignment(signerAccessCode, hasAcceptedTerms) {
8362
+ async getAssignment(signerAccessCode, options) {
7856
8363
  const code = this.requireId(signerAccessCode, "signer-access-code");
7857
- if (hasAcceptedTerms !== void 0 && typeof hasAcceptedTerms !== "boolean") {
8364
+ const read = typeof options === "object" && options !== null ? options : options === void 0 ? {} : { hasAcceptedTerms: options };
8365
+ assertRecord(read, "signing read options");
8366
+ if (read.hasAcceptedTerms !== void 0 && typeof read.hasAcceptedTerms !== "boolean") {
7858
8367
  throw new ValidationError("hasAcceptedTerms must be a boolean");
7859
8368
  }
8369
+ if (read.documentId !== void 0) this.requireId(read.documentId, "documentId");
7860
8370
  return this.call(
7861
8371
  "Failed to fetch signer assignment",
7862
8372
  () => this.http.get("/sign", {
7863
8373
  params: cleanParams({
7864
8374
  "signer-access-code": code,
7865
- has_accepted_terms: hasAcceptedTerms
8375
+ has_accepted_terms: read.hasAcceptedTerms,
8376
+ document_id: read.documentId,
8377
+ ...signingReadParams(read)
7866
8378
  })
7867
8379
  })
7868
8380
  );
7869
8381
  }
7870
8382
  /**
7871
- * Submit the signer's field values to sign an assignment
7872
- * (`POST /documents/{documentId}/assignments/{assignmentId}?signer-access-code=…`).
8383
+ * Read the sending workspace's brand for the signing page (`GET /sign/theme`).
7873
8384
  *
7874
- * The precise, field-by-field counterpart of
7875
- * {@link SignerDocumentsResource.signMultiple}: the `entries` array is sent as
7876
- * the request body, each entry addressing one item resolved from
7877
- * {@link SignerDocumentsResource.getAssignment}. The access code
7878
- * authenticates via the `signer-access-code` query param.
7879
- * Virtual signers must call {@link SignerDocumentsResource.confirmData}
7880
- * first. Digital Certificate signers cannot use this endpoint; use the
7881
- * certificate start/complete API flow instead.
8385
+ * Available before verification and after the document is deleted.
8386
+ * `primary_color` is the button background and `secondary_color` its text
8387
+ * (6-digit hex without `#`). The `logo` URL carries no access code: fetch it
8388
+ * with {@link SignerDocumentsResource.downloadLogo}.
7882
8389
  *
7883
- * Request body (`application/json`):
8390
+ * @param signerAccessCode - The signer's access code, from their signing link.
8391
+ * @returns The brand:
7884
8392
  * ```jsonc
7885
- * [
7886
- * {
7887
- * "itemId": "item_example",
7888
- * "fieldId": "field_example",
7889
- * "pageId": "page_example",
7890
- * "value": "Example Signer"
8393
+ * {
8394
+ * "account_name": "Example Ltda",
8395
+ * "primary_color": "1F6FEB",
8396
+ * "secondary_color": "FFFFFF",
8397
+ * "logo": "https://api.assinafy.com.br/v1/sign/logo" // null when the account has none
8398
+ * }
8399
+ * ```
8400
+ * @throws {ValidationError} If `signerAccessCode` is missing.
8401
+ * @throws {ApiError} `400` while the signer's step has not started, `401` for an invalid code.
8402
+ *
8403
+ * @example
8404
+ * ```ts
8405
+ * const theme = await client.signerDocuments.getTheme(accessCode);
8406
+ * ```
8407
+ */
8408
+ async getTheme(signerAccessCode) {
8409
+ const code = this.requireId(signerAccessCode, "signer-access-code");
8410
+ return this.call(
8411
+ "Failed to fetch signing theme",
8412
+ () => this.http.get("/sign/theme", { params: { "signer-access-code": code } })
8413
+ );
8414
+ }
8415
+ /**
8416
+ * Download the sending workspace's logo for the signing page (`GET /sign/logo`).
8417
+ *
8418
+ * @param signerAccessCode - The signer's access code, from their signing link.
8419
+ * @returns The image bytes (`image/*`).
8420
+ * @throws {ValidationError} If `signerAccessCode` is missing.
8421
+ * @throws {ApiError} `400` while the signer's step has not started, `401` for an
8422
+ * invalid code, `404` when the workspace has no logo.
8423
+ *
8424
+ * @example
8425
+ * ```ts
8426
+ * const logo = await client.signerDocuments.downloadLogo(accessCode);
8427
+ * ```
8428
+ */
8429
+ async downloadLogo(signerAccessCode) {
8430
+ const code = this.requireId(signerAccessCode, "signer-access-code");
8431
+ return this.callBinary(
8432
+ "Failed to download signing logo",
8433
+ () => this.http.get("/sign/logo", {
8434
+ responseType: "arraybuffer",
8435
+ params: { "signer-access-code": code }
8436
+ })
8437
+ );
8438
+ }
8439
+ /**
8440
+ * Send the signer their certified copy again (`POST /sign/certified-copy`).
8441
+ *
8442
+ * The copy goes, with a download link valid for 30 minutes, on the signature
8443
+ * request's channel and only to the contact the signing messages went to.
8444
+ * Works after the signer signed, also once the code is closed. E-mail: once
8445
+ * every 2 minutes and 10 times a day; WhatsApp: once per request.
8446
+ * `certified_copy` on {@link SignerDocumentsResource.getAssignment} says
8447
+ * whether it is available.
8448
+ *
8449
+ * @param signerAccessCode - The signer's access code, from their signing link.
8450
+ * @param documentId - With an envelope code, another document of that envelope.
8451
+ * @returns What was sent:
8452
+ * ```jsonc
8453
+ * { "available": true, "notification_method": "Email", "resends_left": null, "sent_to": "j***@example.com" }
8454
+ * ```
8455
+ * @throws {ValidationError} If the code or `documentId` is blank.
8456
+ * @throws {ApiError} `400` while the signer's step has not started, `404` for a
8457
+ * document outside the envelope, `409` when the signer has not signed or the
8458
+ * document is not certified, `429` within the resend limits, `500` when the
8459
+ * message could not be sent (nothing used up; ask again).
8460
+ *
8461
+ * @example
8462
+ * ```ts
8463
+ * const { sent_to } = await client.signerDocuments.resendCertifiedCopy(accessCode);
8464
+ * ```
8465
+ */
8466
+ async resendCertifiedCopy(signerAccessCode, documentId) {
8467
+ const code = this.requireId(signerAccessCode, "signer-access-code");
8468
+ const body = documentId === void 0 ? {} : { document_id: this.requireId(documentId, "documentId") };
8469
+ return this.call(
8470
+ "Failed to resend certified copy",
8471
+ () => this.http.post("/sign/certified-copy", body, { params: { "signer-access-code": code } })
8472
+ );
8473
+ }
8474
+ /**
8475
+ * Download the certified copy from a sent link (`GET /signers/downloads/{token}`).
8476
+ *
8477
+ * The token is the last path segment of the link in the completion and
8478
+ * re-send messages; it is a credential. Links last 7 days (completion) or
8479
+ * 30 minutes (re-send). An expired or unknown link redirects to the
8480
+ * expired-link page; the SDK does not follow it and throws instead.
8481
+ *
8482
+ * @param token - Link token.
8483
+ * @param artifact - `pades` for the PAdES version, when the document has one.
8484
+ * @returns The PDF bytes.
8485
+ * @throws {ValidationError} If `token` is blank or `artifact` is not `pades`.
8486
+ * @throws {ApiError} `302` for an expired or unknown link (ask for a new one
8487
+ * with {@link SignerDocumentsResource.resendCertifiedCopyFromLink}), `404`
8488
+ * for `pades` on a document without it.
8489
+ *
8490
+ * @example
8491
+ * ```ts
8492
+ * const pdf = await client.signerDocuments.downloadCertifiedCopy(token);
8493
+ * ```
8494
+ */
8495
+ async downloadCertifiedCopy(token, artifact) {
8496
+ if (artifact !== void 0 && artifact !== "pades") {
8497
+ throw new ValidationError("artifact must be pades when given");
8498
+ }
8499
+ const path2 = `/signers/downloads/${this.pathSegment(token, "Download token")}`;
8500
+ return this.callBinary(
8501
+ "Failed to download certified copy",
8502
+ () => this.http.get(artifact ? `${path2}/pades` : path2, BINARY_NO_REDIRECT)
8503
+ );
8504
+ }
8505
+ /**
8506
+ * Send the certified copy again from an expired link
8507
+ * (`POST /signers/downloads/{token}/resend`).
8508
+ *
8509
+ * Works with the link's token after it expired, on the same terms as
8510
+ * {@link SignerDocumentsResource.resendCertifiedCopy}.
8511
+ *
8512
+ * @param token - Link token, from the expired link.
8513
+ * @returns What was sent, as {@link SignerDocumentsResource.resendCertifiedCopy} returns.
8514
+ * @throws {ValidationError} If `token` is blank.
8515
+ * @throws {ApiError} `404` for an unknown link, `409` when nothing can be sent
8516
+ * from it (copy receiver, Bypass signer, no contact, not certified), `429`
8517
+ * within the resend limits.
8518
+ *
8519
+ * @example
8520
+ * ```ts
8521
+ * await client.signerDocuments.resendCertifiedCopyFromLink(token);
8522
+ * ```
8523
+ */
8524
+ async resendCertifiedCopyFromLink(token) {
8525
+ return this.call(
8526
+ "Failed to resend certified copy",
8527
+ () => this.http.post(`/signers/downloads/${this.pathSegment(token, "Download token")}/resend`)
8528
+ );
8529
+ }
8530
+ /**
8531
+ * Submit the signer's field values to sign an assignment
8532
+ * (`POST /documents/{documentId}/assignments/{assignmentId}?signer-access-code=…`).
8533
+ *
8534
+ * The precise, field-by-field counterpart of
8535
+ * {@link SignerDocumentsResource.signMultiple}: the `entries` array is sent as
8536
+ * the request body, each entry addressing one item resolved from
8537
+ * {@link SignerDocumentsResource.getAssignment}. The access code
8538
+ * authenticates via the `signer-access-code` query param.
8539
+ * Virtual signers must call {@link SignerDocumentsResource.confirmData}
8540
+ * first. Digital Certificate signers cannot use this endpoint; use the
8541
+ * certificate start/complete API flow instead.
8542
+ *
8543
+ * Request body (`application/json`):
8544
+ * ```jsonc
8545
+ * [
8546
+ * {
8547
+ * "itemId": "item_example",
8548
+ * "fieldId": "field_example",
8549
+ * "pageId": "page_example",
8550
+ * "value": "Example Signer"
7891
8551
  * }
7892
8552
  * ]
7893
8553
  * ```
@@ -7997,11 +8657,24 @@ function assertDocumentIds(documentIds) {
7997
8657
  throw new ValidationError("documentIds must be a non-empty array of non-empty IDs");
7998
8658
  }
7999
8659
  }
8660
+ var BINARY_NO_REDIRECT = { responseType: "arraybuffer", maxRedirects: 0 };
8661
+ var SIGNING_EXPANSIONS = /* @__PURE__ */ new Set(["envelope"]);
8662
+ function signingReadParams(options) {
8663
+ assertRecord(options, "signing read options");
8664
+ return expandParam(options.expand, SIGNING_EXPANSIONS);
8665
+ }
8666
+ function searchParams(search, params) {
8667
+ if (search !== void 0 && typeof search !== "string") {
8668
+ throw new ValidationError("search must be a string");
8669
+ }
8670
+ assertRecord(params, "search params");
8671
+ return cleanParams({ search, envelope_id: params.envelope_id });
8672
+ }
8000
8673
  function assertDeclineReason(declineReason) {
8001
8674
  if (typeof declineReason !== "string" || !declineReason.trim()) {
8002
8675
  throw new ValidationError("declineReason is required");
8003
8676
  }
8004
- if (declineReason.length > 2e3) {
8677
+ if ([...declineReason].length > 2e3) {
8005
8678
  throw new ValidationError("declineReason must be at most 2000 characters");
8006
8679
  }
8007
8680
  }
@@ -8218,12 +8891,70 @@ var UserResource = class extends BaseResource {
8218
8891
  * ```
8219
8892
  */
8220
8893
  async updateNotificationPreferences(preferences) {
8221
- validateNotificationPreferences(preferences);
8894
+ assertBooleanMap(preferences, "notification preferences", NOTIFICATION_PREFERENCE_KEYS);
8222
8895
  return this.call(
8223
8896
  "Failed to update notification preferences",
8224
8897
  () => this.http.put("/users/self/notification-preferences", preferences)
8225
8898
  );
8226
8899
  }
8900
+ /**
8901
+ * Read which document alerts reach the user as push notifications
8902
+ * (`GET /users/self/push-preferences`).
8903
+ *
8904
+ * Separate from the e-mail preferences. Every key is returned and defaults
8905
+ * to `true`; new keys may be added. Not available to third-party OAuth
8906
+ * applications (`403`).
8907
+ *
8908
+ * @returns The push preferences:
8909
+ * ```jsonc
8910
+ * {
8911
+ * "SignerViewed": true,
8912
+ * "SignerSigned": true,
8913
+ * "DocumentCompleted": true,
8914
+ * "SignerDeclined": true,
8915
+ * "DocumentAboutToExpire": true,
8916
+ * "DocumentExpired": true,
8917
+ * "SignerIdentityReviewRequired": true, // the review e-mail is always sent
8918
+ * "SignerWhatsappFailed": true
8919
+ * }
8920
+ * ```
8921
+ * @throws {ApiError} `401` for invalid credentials, `403` for an OAuth application token.
8922
+ *
8923
+ * @example
8924
+ * ```ts
8925
+ * const push = await client.users.getPushPreferences();
8926
+ * ```
8927
+ */
8928
+ async getPushPreferences() {
8929
+ return this.call(
8930
+ "Failed to fetch push preferences",
8931
+ () => this.http.get("/users/self/push-preferences")
8932
+ );
8933
+ }
8934
+ /**
8935
+ * Change which document alerts reach the user as push notifications
8936
+ * (`PUT /users/self/push-preferences`).
8937
+ *
8938
+ * Merges the keys sent; `false` stops that push in every workspace the user
8939
+ * belongs to. E-mail is not affected.
8940
+ *
8941
+ * @param preferences - Keys to change, e.g. `{ SignerViewed: false }`.
8942
+ * @returns The full map, as {@link UserResource.getPushPreferences} returns.
8943
+ * @throws {ValidationError} If the map is empty or a value is not a boolean.
8944
+ * @throws {ApiError} `400` for an unknown code, `403` for an OAuth application token.
8945
+ *
8946
+ * @example
8947
+ * ```ts
8948
+ * await client.users.updatePushPreferences({ SignerViewed: false });
8949
+ * ```
8950
+ */
8951
+ async updatePushPreferences(preferences) {
8952
+ assertBooleanMap(preferences, "push preferences");
8953
+ return this.call(
8954
+ "Failed to update push preferences",
8955
+ () => this.http.put("/users/self/push-preferences", { ...preferences })
8956
+ );
8957
+ }
8227
8958
  /**
8228
8959
  * List the user's enrolled two-factor methods (`GET /users/self/mfa`).
8229
8960
  *
@@ -8419,21 +9150,6 @@ var NOTIFICATION_PREFERENCE_KEYS = /* @__PURE__ */ new Set([
8419
9150
  "ContractExpired",
8420
9151
  "ContractRenewed"
8421
9152
  ]);
8422
- function validateNotificationPreferences(preferences) {
8423
- assertRecord(preferences, "notification preferences");
8424
- const entries = Object.entries(preferences);
8425
- if (entries.length === 0) {
8426
- throw new ValidationError("at least one notification preference is required");
8427
- }
8428
- for (const [key, value] of entries) {
8429
- if (!NOTIFICATION_PREFERENCE_KEYS.has(key)) {
8430
- throw new ValidationError(`unknown notification preference: ${key}`);
8431
- }
8432
- if (typeof value !== "boolean") {
8433
- throw new ValidationError(`${key} must be a boolean`);
8434
- }
8435
- }
8436
- }
8437
9153
 
8438
9154
  // src/resources/contracts.ts
8439
9155
  var CONTRACT_STATUSES = /* @__PURE__ */ new Set(["draft", "active", "expired", "terminated"]);
@@ -8563,14 +9279,14 @@ var ContractResource = class extends BaseResource {
8563
9279
  * }
8564
9280
  * ```
8565
9281
  * @throws {ValidationError} If an ID is missing or invalid.
8566
- * @throws {ApiError} `401` for invalid credentials, `404` when the document
8567
- * has no tracked terms, or `500` on a server error.
9282
+ * @throws {ApiError} `401` for invalid credentials, `404` (`code:
9283
+ * 'NoContractTerms'` when the document exists without terms), or `500`.
8568
9284
  *
8569
9285
  * @example
8570
9286
  * ```ts
8571
9287
  * const contract = await client.contracts.get(document.id);
8572
- * if (contract.resource === 'document_contract_amendment') {
8573
- * console.log(contract.parent_document_id);
9288
+ * if ('parent_document_id' in contract) {
9289
+ * console.log(contract.parent_document_id); // an amendment, renewal or termination
8574
9290
  * }
8575
9291
  * ```
8576
9292
  */
@@ -8629,9 +9345,10 @@ var ContractResource = class extends BaseResource {
8629
9345
  * }
8630
9346
  * ```
8631
9347
  * @throws {ValidationError} If the payload or an ID is malformed.
8632
- * @throws {ApiError} `400` for invalid terms, `403` when the plan does not
8633
- * include tracking, `404` for an unknown document, `409` after a concurrent
8634
- * change, or `500` on a server error.
9348
+ * @throws {ApiError} `400` for invalid terms (each in `fieldErrors`), `403`
9349
+ * (`PlanRestricted`) when the plan does not include tracking, `404` for an
9350
+ * unknown document or a `parent_document_id` outside the workspace, `409`
9351
+ * (`ContractChanged`) after a concurrent change, or `500` on a server error.
8635
9352
  *
8636
9353
  * @example
8637
9354
  * ```ts
@@ -8661,6 +9378,7 @@ var ContractResource = class extends BaseResource {
8661
9378
  *
8662
9379
  * @param documentId - Any document in the contract family.
8663
9380
  * @param accountId - Override the client's default account ID.
9381
+ * @param params - `expand: 'document'` embeds the root contract's document.
8664
9382
  * @returns The root contract and ordered instruments:
8665
9383
  * ```jsonc
8666
9384
  * {
@@ -8712,10 +9430,15 @@ var ContractResource = class extends BaseResource {
8712
9430
  * const family = await client.contracts.listRelated(amendmentDocument.id);
8713
9431
  * ```
8714
9432
  */
8715
- async listRelated(documentId, accountId) {
9433
+ async listRelated(documentId, accountId, params = {}) {
9434
+ assertRecord(params, "related contract params");
9435
+ if (params.expand !== void 0 && params.expand !== "document") {
9436
+ throw new ValidationError("expand must be document");
9437
+ }
9438
+ const config = params.expand === void 0 ? {} : { params: { expand: params.expand } };
8716
9439
  return this.call(
8717
9440
  "Failed to fetch related contracts",
8718
- () => this.http.get(`${this.contractPath(documentId, accountId)}/related`)
9441
+ () => this.http.get(`${this.contractPath(documentId, accountId)}/related`, config)
8719
9442
  );
8720
9443
  }
8721
9444
  /**
@@ -9018,15 +9741,708 @@ function validateExternalReferences(value) {
9018
9741
  }
9019
9742
  }
9020
9743
 
9744
+ // src/resources/envelopes.ts
9745
+ var EnvelopeResource = class extends BaseResource {
9746
+ /**
9747
+ * List the workspace's envelopes, most recent first
9748
+ * (`GET /accounts/{accountId}/envelopes`).
9749
+ *
9750
+ * @param params - Optional filters and pagination.
9751
+ * @param params.search - Part of the envelope name.
9752
+ * @param params.status - `open` (a document is still open) or `closed`
9753
+ * (every document signed, declined, cancelled, expired or failed).
9754
+ * @param params.page - One-based page number.
9755
+ * @param params.per-page - Page size: 20 by default, at most 50.
9756
+ * @param accountId - Override the client's default account ID.
9757
+ * @returns Envelopes and pagination metadata:
9758
+ * ```jsonc
9759
+ * {
9760
+ * "data": [{
9761
+ * "id": "1052a1f0c3d4e5f6a7b8c9d0e1f2",
9762
+ * "name": "Admission kit",
9763
+ * "message": "Please sign the documents below.",
9764
+ * "documents": [{
9765
+ * "id": "1052a1e9b8c7d6e5f4a3b2c1d0e9",
9766
+ * "position": 1,
9767
+ * "name": "contract.pdf",
9768
+ * "status": "pending_signature",
9769
+ * "artifacts": {
9770
+ * "original": "https://api.assinafy.com.br/v1/documents/1052a1e9b8c7d6e5f4a3b2c1d0e9/download/original",
9771
+ * "thumbnail": "https://api.assinafy.com.br/v1/documents/1052a1e9b8c7d6e5f4a3b2c1d0e9/thumbnail"
9772
+ * },
9773
+ * "signers": [{
9774
+ * "id": "1052a1d4c3b2a1f0e9d8c7b6a5f4",
9775
+ * "full_name": "Ana Souza",
9776
+ * "email": "ana@example.com",
9777
+ * "whatsapp_phone_number": null,
9778
+ * "completed": false,
9779
+ * "signed_at": null
9780
+ * }]
9781
+ * }],
9782
+ * "counts": { "pending_signature": 1 }, // documents per status; no envelope-level status
9783
+ * "signing_urls": [{
9784
+ * "signer_id": "1052a1d4c3b2a1f0e9d8c7b6a5f4",
9785
+ * "url": "https://app.assinafy.com.br/sign/1052a1e9b8c7d6e5f4a3b2c1d0e9?email=ana%40example.com",
9786
+ * "embedded": false
9787
+ * }],
9788
+ * "created_at": "2026-11-11T14:00:00Z"
9789
+ * }],
9790
+ * "meta": { "current_page": 1, "per_page": 20, "total": 1, "last_page": 1 }
9791
+ * }
9792
+ * ```
9793
+ * @throws {ValidationError} If no account ID is available.
9794
+ * @throws {ApiError} `400` for a filter of the wrong type, `403` for a token
9795
+ * without `documents:read`, `401` for invalid credentials.
9796
+ *
9797
+ * @example
9798
+ * ```ts
9799
+ * const { data: open } = await client.envelopes.list({ status: 'open' });
9800
+ * ```
9801
+ */
9802
+ async list(params = {}, accountId) {
9803
+ assertRecord(params, "envelope list params");
9804
+ if (params.status !== void 0 && params.status !== "open" && params.status !== "closed") {
9805
+ throw new ValidationError("status must be open or closed");
9806
+ }
9807
+ return this.callList(
9808
+ "Failed to list envelopes",
9809
+ () => this.http.get(this.envelopesPath(accountId), { params: cleanListParams(params) })
9810
+ );
9811
+ }
9812
+ /**
9813
+ * Read one envelope (`GET /accounts/{accountId}/envelopes/{envelopeId}`).
9814
+ *
9815
+ * @param envelopeId - Envelope ID.
9816
+ * @param accountId - Override the client's default account ID.
9817
+ * @returns The envelope: its documents in order (`position`), each with its
9818
+ * status and signers, the per-status `counts` and one `signing_urls` entry
9819
+ * per signer. Same shape as each item of {@link EnvelopeResource.list}.
9820
+ * @throws {ValidationError} If an ID is missing or invalid.
9821
+ * @throws {ApiError} `403` for a token without `documents:read`, `404` for an
9822
+ * unknown envelope.
9823
+ *
9824
+ * @example
9825
+ * ```ts
9826
+ * const envelope = await client.envelopes.get(envelopeId);
9827
+ * const pending = envelope.documents.filter((doc) => doc.status === 'pending_signature');
9828
+ * ```
9829
+ */
9830
+ async get(envelopeId, accountId) {
9831
+ return this.call(
9832
+ "Failed to fetch envelope",
9833
+ () => this.http.get(this.envelopePath(envelopeId, accountId))
9834
+ );
9835
+ }
9836
+ /**
9837
+ * Send several documents to the same signers at once
9838
+ * (`POST /accounts/{accountId}/envelopes`).
9839
+ *
9840
+ * Every document must be uploaded, `metadata_ready` and unassigned; every
9841
+ * signer must be on at least one document. Signers all sign at once (no
9842
+ * `step`); a `DigitalCertificate` signer signs only `virtual` documents and
9843
+ * is alone on each. One invitation goes to each signer, and `200` means the
9844
+ * envelope exists even when a send fails (see each signer's
9845
+ * `notification_history`). The envelope is charged as one document, each
9846
+ * signer's notification and identity check once, and each certificate
9847
+ * signature on every document it is made on. A refused request creates and
9848
+ * charges nothing. Pass an `idempotencyKey` to retry safely after a lost
9849
+ * response; the SDK then also replays a `429`.
9850
+ *
9851
+ * @param payload - Envelope definition.
9852
+ * @param payload.name - 1–255 characters without `<`; invitations use it in
9853
+ * place of document names.
9854
+ * @param payload.message - Optional message for every signer.
9855
+ * @param payload.max_total_credits - Refuse with `409 CreditCeilingExceeded`
9856
+ * above this many credits.
9857
+ * @param payload.signers - 1–20 `{ id, verification_method?, notification_methods?, embedded? }`.
9858
+ * @param payload.documents - 1–20 `{ id, signer_ids, method?, entries?, expires_at?, copy_receiver_ids? }`,
9859
+ * in envelope order. `collect` documents need `entries` whose signers are
9860
+ * exactly `signer_ids`.
9861
+ * @param options - `idempotencyKey`: new for each envelope you mean to create.
9862
+ * @param accountId - Override the client's default account ID.
9863
+ * @returns The created envelope (see {@link EnvelopeResource.list}). An
9864
+ * embedded or WhatsApp-only signer has `url: null` in `signing_urls`.
9865
+ * @throws {ValidationError} If the payload is malformed, a signer's channels
9866
+ * do not pair, or a `collect` document has no `entries`.
9867
+ * @throws {ApiError} `400` with `fieldErrors` naming each field at fault, `403`
9868
+ * (`PlanRestricted` or `InsufficientScope`), `409` (`CreditCeilingExceeded`,
9869
+ * or `IdempotencyKeyInUse` while the first request with that key runs).
9870
+ *
9871
+ * @example
9872
+ * ```ts
9873
+ * const envelope = await client.envelopes.create({
9874
+ * name: 'Admission kit',
9875
+ * signers: [{ id: signerId }],
9876
+ * documents: [
9877
+ * { id: contractId, signer_ids: [signerId] },
9878
+ * { id: policyId, signer_ids: [signerId], expires_at: '2026-12-31' },
9879
+ * ],
9880
+ * }, { idempotencyKey: crypto.randomUUID() });
9881
+ * ```
9882
+ */
9883
+ async create(payload, options = {}, accountId) {
9884
+ const body = buildEnvelopePayload(payload);
9885
+ assertRecord(options, "envelope options");
9886
+ const config = idempotencyConfig(options.idempotencyKey);
9887
+ this.logger.info("Creating envelope", {
9888
+ signerCount: body["signers"].length,
9889
+ documentCount: body["documents"].length
9890
+ });
9891
+ return this.call(
9892
+ "Failed to create envelope",
9893
+ () => this.http.post(this.envelopesPath(accountId), body, config)
9894
+ );
9895
+ }
9896
+ /**
9897
+ * Estimate what creating an envelope would cost
9898
+ * (`POST /accounts/{accountId}/envelopes/estimate-cost`).
9899
+ *
9900
+ * Takes the creation body and checks it the same way, creating and charging
9901
+ * nothing; `max_total_credits` is ignored. The envelope counts as one
9902
+ * document, each signer's notification and identity check once, and each
9903
+ * certificate signature per document.
9904
+ *
9905
+ * @param payload - The body {@link EnvelopeResource.create} would send.
9906
+ * @param accountId - Override the client's default account ID.
9907
+ * @returns A cost estimate:
9908
+ * ```jsonc
9909
+ * {
9910
+ * "documents": 1,
9911
+ * "credits": 1.45,
9912
+ * "needs_extra_document": false,
9913
+ * "extra_document_cost": 1,
9914
+ * "total_credits": 1.45,
9915
+ * "breakdown": [
9916
+ * { "code": "NotificationWhatsapp", "name": "WhatsApp notification", "cost": 0.45, "quantity": 1, "unit_cost": 0.45 },
9917
+ * { "code": "SignatureDigitalCertificate", "name": "Digital certificate signature", "cost": 1, "quantity": 2, "unit_cost": 0.5 }
9918
+ * ],
9919
+ * "document_balance": 97, // null when documents are not limited
9920
+ * "credit_balance": 10, // null when credits are not limited
9921
+ * "has_sufficient_resources": true,
9922
+ * "blocking_reason": null,
9923
+ * "message": null
9924
+ * }
9925
+ * ```
9926
+ * @throws {ValidationError} If the payload is malformed or a signer's channels do not pair.
9927
+ * @throws {ApiError} `400` for fields at fault, `403` (`PlanRestricted` or
9928
+ * `InsufficientScope`).
9929
+ *
9930
+ * @example
9931
+ * ```ts
9932
+ * const estimate = await client.envelopes.estimateCost(envelopeBody);
9933
+ * if (!estimate.has_sufficient_resources) console.warn(estimate.blocking_reason);
9934
+ * ```
9935
+ */
9936
+ async estimateCost(payload, accountId) {
9937
+ const body = buildEnvelopePayload(payload);
9938
+ return this.call(
9939
+ "Failed to estimate envelope cost",
9940
+ () => this.http.post(`${this.envelopesPath(accountId)}/estimate-cost`, body)
9941
+ );
9942
+ }
9943
+ /**
9944
+ * Rename an envelope, change its message or reorder its documents
9945
+ * (`PATCH /accounts/{accountId}/envelopes/{envelopeId}`).
9946
+ *
9947
+ * Send only what changes. Nothing is sent to anyone; later reminders,
9948
+ * cancellations and additions use the new values. Works on closed envelopes.
9949
+ *
9950
+ * @param envelopeId - Envelope ID.
9951
+ * @param payload - At least one change.
9952
+ * @param payload.name - 1–255 characters without `<`.
9953
+ * @param payload.message - New message, or `null` for none.
9954
+ * @param payload.document_ids - Every document of the envelope, each once, in the new order.
9955
+ * @param accountId - Override the client's default account ID.
9956
+ * @returns The updated envelope (see {@link EnvelopeResource.list}).
9957
+ * @throws {ValidationError} If nothing would change or a value is malformed.
9958
+ * @throws {ApiError} `400` for fields at fault, `403` for a token without
9959
+ * `documents:write`, `404` for an unknown envelope.
9960
+ *
9961
+ * @example
9962
+ * ```ts
9963
+ * await client.envelopes.update(envelopeId, { name: 'Admission kit 2026', message: null });
9964
+ * ```
9965
+ */
9966
+ async update(envelopeId, payload, accountId) {
9967
+ const body = buildUpdatePayload(payload);
9968
+ return this.call(
9969
+ "Failed to update envelope",
9970
+ () => this.http.patch(this.envelopePath(envelopeId, accountId), body)
9971
+ );
9972
+ }
9973
+ /**
9974
+ * Delete a closed envelope (`DELETE /accounts/{accountId}/envelopes/{envelopeId}`).
9975
+ *
9976
+ * Allowed once every document is certificated, declined, cancelled, expired
9977
+ * or failed; cancel it first otherwise. Its documents remain as ordinary
9978
+ * documents, and its `Idempotency-Key` no longer answers it.
9979
+ *
9980
+ * @param envelopeId - Envelope ID.
9981
+ * @param accountId - Override the client's default account ID.
9982
+ * @throws {ValidationError} If an ID is missing or invalid.
9983
+ * @throws {ApiError} `403` for a token without `documents:write`, `404` for an
9984
+ * unknown envelope, `409` (`EnvelopeOpen`) while a document is still open.
9985
+ *
9986
+ * @example
9987
+ * ```ts
9988
+ * await client.envelopes.cancel(envelopeId);
9989
+ * await client.envelopes.delete(envelopeId);
9990
+ * ```
9991
+ */
9992
+ async delete(envelopeId, accountId) {
9993
+ return this.callVoid(
9994
+ "Failed to delete envelope",
9995
+ () => this.http.delete(this.envelopePath(envelopeId, accountId))
9996
+ );
9997
+ }
9998
+ /**
9999
+ * Cancel every document that can still be cancelled
10000
+ * (`PUT /accounts/{accountId}/envelopes/{envelopeId}/cancel`).
10001
+ *
10002
+ * Each owner, signer and copy receiver is told once for the whole envelope.
10003
+ * Documents already closed, fully signed or being certificated are left as
10004
+ * they are. Safe to repeat: a second call cancels nothing.
10005
+ *
10006
+ * @param envelopeId - Envelope ID.
10007
+ * @param accountId - Override the client's default account ID.
10008
+ * @returns What happened to each document:
10009
+ * ```jsonc
10010
+ * [
10011
+ * { "id": "1052a1e9b8c7d6e5f4a3b2c1d0e9", "status": "cancelled", "cancelled": true },
10012
+ * { "id": "1052a1eaf9e8d7c6b5a4f3e2d1c0", "status": "certificated", "cancelled": false }
10013
+ * ]
10014
+ * ```
10015
+ * @throws {ValidationError} If an ID is missing or invalid.
10016
+ * @throws {ApiError} `403` for a token without `documents:write`, `404` for an
10017
+ * unknown envelope.
10018
+ *
10019
+ * @example
10020
+ * ```ts
10021
+ * const results = await client.envelopes.cancel(envelopeId);
10022
+ * ```
10023
+ */
10024
+ async cancel(envelopeId, accountId) {
10025
+ return this.call(
10026
+ "Failed to cancel envelope",
10027
+ () => this.http.put(`${this.envelopePath(envelopeId, accountId)}/cancel`)
10028
+ );
10029
+ }
10030
+ /**
10031
+ * Read the envelope's activity trail, newest first
10032
+ * (`GET /accounts/{accountId}/envelopes/{envelopeId}/activities`).
10033
+ *
10034
+ * Includes every document the envelope has had, including ones taken out;
10035
+ * each entry is a document activity that also names its document.
10036
+ *
10037
+ * @param envelopeId - Envelope ID.
10038
+ * @param params - `sort` (`-id`, the default, or `id` for oldest first),
10039
+ * `page`, and `per-page` (20 by default, at most 50).
10040
+ * @param accountId - Override the client's default account ID.
10041
+ * @returns Activity entries and pagination metadata:
10042
+ * ```jsonc
10043
+ * {
10044
+ * "data": [{
10045
+ * "id": 7731204,
10046
+ * "event": "signer_signed_document",
10047
+ * "message": "Ana Souza signed the document",
10048
+ * "payload": { "signer": { "id": "1052a1d4c3b2a1f0e9d8c7b6a5f4" } }, // same keys as that event's webhook
10049
+ * "origin": { "ip": "203.0.113.10", "user-agent": "Mozilla/5.0" },
10050
+ * "document_id": "1052a1e9b8c7d6e5f4a3b2c1d0e9",
10051
+ * "document_name": "contract.pdf",
10052
+ * "created_at": "2026-11-11T14:05:00Z"
10053
+ * }],
10054
+ * "meta": { "current_page": 1, "per_page": 20, "total": 1, "last_page": 1 }
10055
+ * }
10056
+ * ```
10057
+ * @throws {ValidationError} If an ID is missing or invalid.
10058
+ * @throws {ApiError} `403` for a token without `documents:read`, `404` for an
10059
+ * unknown envelope.
10060
+ *
10061
+ * @example
10062
+ * ```ts
10063
+ * const { data } = await client.envelopes.listActivities(envelopeId, { sort: 'id' });
10064
+ * ```
10065
+ */
10066
+ async listActivities(envelopeId, params = {}, accountId) {
10067
+ return this.callList(
10068
+ "Failed to fetch envelope activities",
10069
+ () => this.http.get(`${this.envelopePath(envelopeId, accountId)}/activities`, {
10070
+ params: cleanListParams(params)
10071
+ })
10072
+ );
10073
+ }
10074
+ /**
10075
+ * Download one artifact of every document as a zip
10076
+ * (`GET /accounts/{accountId}/envelopes/{envelopeId}/download/{artifactName}`).
10077
+ *
10078
+ * Files are named after their position (`1 - contract.pdf`); `bundle` gives
10079
+ * each document a folder. `certificated`, `certificate-page`, `pades` and
10080
+ * `bundle` include only the documents certified so far.
10081
+ *
10082
+ * @param envelopeId - Envelope ID.
10083
+ * @param artifactName - `original`, `certificated`, `certificate-page`, `pades` or `bundle`.
10084
+ * @param accountId - Override the client's default account ID.
10085
+ * @returns The zip archive bytes.
10086
+ * @throws {ValidationError} If an ID or the artifact name is invalid.
10087
+ * @throws {ApiError} `403` for a token without `documents:read`, `404` when no
10088
+ * document has the artifact.
10089
+ *
10090
+ * @example
10091
+ * ```ts
10092
+ * import { writeFile } from 'node:fs/promises';
10093
+ * await writeFile('envelope.zip', await client.envelopes.download(envelopeId, 'certificated'));
10094
+ * ```
10095
+ */
10096
+ async download(envelopeId, artifactName, accountId) {
10097
+ assertDocumentArtifactName(artifactName);
10098
+ return this.callBinary(
10099
+ "Failed to download envelope artifacts",
10100
+ () => this.http.get(
10101
+ `${this.envelopePath(envelopeId, accountId)}/download/${this.pathSegment(artifactName, "Artifact name")}`,
10102
+ { responseType: "arraybuffer" }
10103
+ )
10104
+ );
10105
+ }
10106
+ /**
10107
+ * Add a document to an open envelope for some of its signers
10108
+ * (`POST /accounts/{accountId}/envelopes/{envelopeId}/documents`).
10109
+ *
10110
+ * The document is checked as on creation and goes last. Only its
10111
+ * certificate signatures are charged; the chosen signers receive the
10112
+ * envelope invitation again, now listing it. No new signer can join, and an
10113
+ * envelope holds at most 20 documents.
10114
+ *
10115
+ * @param envelopeId - Envelope ID.
10116
+ * @param payload - `{ id, signer_ids, method?, entries?, expires_at?, copy_receiver_ids?, max_total_credits? }`.
10117
+ * @param accountId - Override the client's default account ID.
10118
+ * @returns The updated envelope (see {@link EnvelopeResource.list}).
10119
+ * @throws {ValidationError} If the document definition is malformed.
10120
+ * @throws {ApiError} `400` for fields at fault, `403` (`PlanRestricted` or
10121
+ * `InsufficientScope`), `409` (`EnvelopeClosed`, `CreditCeilingExceeded`).
10122
+ *
10123
+ * @example
10124
+ * ```ts
10125
+ * await client.envelopes.addDocument(envelopeId, { id: annexId, signer_ids: [signerId] });
10126
+ * ```
10127
+ */
10128
+ async addDocument(envelopeId, payload, accountId) {
10129
+ const body = buildEnvelopeDocument(payload, "document");
10130
+ assertCreditCeiling(payload.max_total_credits);
10131
+ if (payload.max_total_credits !== void 0) body["max_total_credits"] = payload.max_total_credits;
10132
+ return this.call(
10133
+ "Failed to add document to envelope",
10134
+ () => this.http.post(`${this.envelopePath(envelopeId, accountId)}/documents`, body)
10135
+ );
10136
+ }
10137
+ /**
10138
+ * Take an open document out of the envelope
10139
+ * (`DELETE /accounts/{accountId}/envelopes/{envelopeId}/documents/{documentId}`).
10140
+ *
10141
+ * The document is cancelled and its people are told; the other documents
10142
+ * carry on, and links sent from it keep opening them.
10143
+ *
10144
+ * @param envelopeId - Envelope ID.
10145
+ * @param documentId - Document to take out.
10146
+ * @param accountId - Override the client's default account ID.
10147
+ * @returns The updated envelope (see {@link EnvelopeResource.list}).
10148
+ * @throws {ValidationError} If an ID is missing or invalid.
10149
+ * @throws {ApiError} `403` for a token without `documents:write`, `404` when the
10150
+ * document is not in the envelope, `409` (`DocumentClosed`) when it can no
10151
+ * longer be cancelled.
10152
+ *
10153
+ * @example
10154
+ * ```ts
10155
+ * await client.envelopes.removeDocument(envelopeId, documentId);
10156
+ * ```
10157
+ */
10158
+ async removeDocument(envelopeId, documentId, accountId) {
10159
+ return this.call(
10160
+ "Failed to remove document from envelope",
10161
+ () => this.http.delete(
10162
+ `${this.envelopePath(envelopeId, accountId)}/documents/${this.pathSegment(documentId, "Document ID")}`
10163
+ )
10164
+ );
10165
+ }
10166
+ /**
10167
+ * Remind a signer of the whole envelope
10168
+ * (`PUT /accounts/{accountId}/envelopes/{envelopeId}/signers/{signerId}/resend`).
10169
+ *
10170
+ * One message from their first link, listing the documents still to sign;
10171
+ * paid channels are charged once. A document's own reminder
10172
+ * (`assignments.resendNotification`) still goes per document.
10173
+ *
10174
+ * @param envelopeId - Envelope ID.
10175
+ * @param signerId - Signer of the envelope.
10176
+ * @param accountId - Override the client's default account ID.
10177
+ * @returns Delivery acknowledgement:
10178
+ * ```jsonc
10179
+ * { "is_sent": true, "envelope_id": "1052a1f0c3d4e5f6a7b8c9d0e1f2", "signer_id": "1052a1d4c3b2a1f0e9d8c7b6a5f4" }
10180
+ * ```
10181
+ * @throws {ValidationError} If an ID is missing or invalid.
10182
+ * @throws {ApiError} `400` when the signer has nothing left to sign or credits
10183
+ * are short, `404` when the signer is not on the envelope, `409`
10184
+ * (`EnvelopeClosed`).
10185
+ *
10186
+ * @example
10187
+ * ```ts
10188
+ * await client.envelopes.resendNotification(envelopeId, signerId);
10189
+ * ```
10190
+ */
10191
+ async resendNotification(envelopeId, signerId, accountId) {
10192
+ return this.call(
10193
+ "Failed to remind envelope signer",
10194
+ () => this.http.put(
10195
+ `${this.envelopePath(envelopeId, accountId)}/signers/${this.pathSegment(signerId, "Signer ID")}/resend`
10196
+ )
10197
+ );
10198
+ }
10199
+ envelopesPath(accountId) {
10200
+ return `/accounts/${this.pathSegment(this.accountId(accountId), "Account ID")}/envelopes`;
10201
+ }
10202
+ envelopePath(envelopeId, accountId) {
10203
+ return `${this.envelopesPath(accountId)}/${this.pathSegment(envelopeId, "Envelope ID")}`;
10204
+ }
10205
+ };
10206
+ function buildEnvelopePayload(payload) {
10207
+ assertRecord(payload, "envelope payload");
10208
+ assertNonEmptyString(payload.name, "name");
10209
+ assertMessage(payload.message);
10210
+ assertCreditCeiling(payload.max_total_credits);
10211
+ const signers = records(payload.signers, "signers").map((signer, index) => {
10212
+ const label = `signers[${index}]`;
10213
+ assertNonEmptyString(signer["id"], `${label}.id`);
10214
+ validateAssignmentSignerOptions(signer, label);
10215
+ const projected = { id: signer["id"] };
10216
+ for (const key of ["verification_method", "notification_methods", "embedded", "step"]) {
10217
+ if (signer[key] !== void 0) projected[key] = signer[key];
10218
+ }
10219
+ return projected;
10220
+ });
10221
+ const documents = records(payload.documents, "documents").map((document, index) => buildEnvelopeDocument(document, `documents[${index}]`));
10222
+ const body = { name: payload.name, signers, documents };
10223
+ if (payload.message !== void 0) body["message"] = payload.message;
10224
+ if (payload.max_total_credits !== void 0) body["max_total_credits"] = payload.max_total_credits;
10225
+ return body;
10226
+ }
10227
+ function buildEnvelopeDocument(document, label) {
10228
+ assertRecord(document, label);
10229
+ const input = document;
10230
+ assertNonEmptyString(input.id, `${label}.id`);
10231
+ const method = input.method ?? "virtual";
10232
+ if (method !== "virtual" && method !== "collect") {
10233
+ throw new ValidationError(`${label}.method must be virtual or collect`);
10234
+ }
10235
+ const entries = input.entries === void 0 ? void 0 : normaliseAssignmentEntries(input.entries);
10236
+ if (method === "collect" && !entries?.length) {
10237
+ throw new ValidationError(`${label}.entries is required for collect documents`);
10238
+ }
10239
+ if (input.expires_at !== void 0 && input.expires_at !== null) {
10240
+ assertExpirationDate(input.expires_at, `${label}.expires_at`);
10241
+ }
10242
+ const projected = {
10243
+ id: input.id,
10244
+ method,
10245
+ signer_ids: idList(input.signer_ids, `${label}.signer_ids`)
10246
+ };
10247
+ if (entries !== void 0) projected["entries"] = entries;
10248
+ if (input.expires_at !== void 0) projected["expires_at"] = input.expires_at;
10249
+ if (input.copy_receiver_ids !== void 0) {
10250
+ projected["copy_receiver_ids"] = idList(input.copy_receiver_ids, `${label}.copy_receiver_ids`);
10251
+ }
10252
+ return projected;
10253
+ }
10254
+ function buildUpdatePayload(payload) {
10255
+ assertRecord(payload, "envelope update");
10256
+ const body = {};
10257
+ if (payload.name !== void 0) {
10258
+ assertNonEmptyString(payload.name, "name");
10259
+ body["name"] = payload.name;
10260
+ }
10261
+ if (payload.message !== void 0) {
10262
+ assertMessage(payload.message);
10263
+ body["message"] = payload.message;
10264
+ }
10265
+ if (payload.document_ids !== void 0) {
10266
+ body["document_ids"] = idList(payload.document_ids, "document_ids");
10267
+ }
10268
+ if (Object.keys(body).length === 0) {
10269
+ throw new ValidationError("envelope update must change name, message or document_ids");
10270
+ }
10271
+ return body;
10272
+ }
10273
+ function assertMessage(message) {
10274
+ if (message !== void 0 && message !== null && typeof message !== "string") {
10275
+ throw new ValidationError("message must be a string or null");
10276
+ }
10277
+ }
10278
+ function records(value, label) {
10279
+ if (!Array.isArray(value)) throw new ValidationError(`${label} must be an array`);
10280
+ value.forEach((item, index) => assertRecord(item, `${label}[${index}]`));
10281
+ return value;
10282
+ }
10283
+ function idList(value, label) {
10284
+ if (!Array.isArray(value) || value.some((id) => typeof id !== "string" || !id.trim())) {
10285
+ throw new ValidationError(`${label} must be an array of IDs`);
10286
+ }
10287
+ return [...value];
10288
+ }
10289
+
10290
+ // src/resources/embed.ts
10291
+ var EmbedResource = class extends BaseResource {
10292
+ /**
10293
+ * List the origins allowed to embed signing pages, oldest first
10294
+ * (`GET /accounts/{accountId}/embed-origins`).
10295
+ *
10296
+ * @param accountId - Override the client's default account ID.
10297
+ * @returns Registered origins:
10298
+ * ```jsonc
10299
+ * [{ "id": "1052c7d8e9f0a1b2c3d4e5f6a7b8", "origin": "https://app.example.com", "created_at": "2026-11-04T12:05:00Z" }]
10300
+ * ```
10301
+ * @throws {ValidationError} If no account ID is available.
10302
+ * @throws {ApiError} `403` (`PlanRestricted`, or an OAuth application token).
10303
+ *
10304
+ * @example
10305
+ * ```ts
10306
+ * const origins = await client.embed.listOrigins();
10307
+ * ```
10308
+ */
10309
+ async listOrigins(accountId) {
10310
+ return this.call("Failed to list embed origins", () => this.http.get(this.originsPath(accountId)));
10311
+ }
10312
+ /**
10313
+ * Allow one more origin to embed signing pages
10314
+ * (`POST /accounts/{accountId}/embed-origins`).
10315
+ *
10316
+ * An origin is an exact `https://host[:port]` (`http` only for `localhost`
10317
+ * and `127.0.0.1`) without path, query, fragment, credentials or wildcard;
10318
+ * the API lowercases the host and drops a default port. Up to 10 per account.
10319
+ *
10320
+ * @param origin - Origin of the page that will host the iframe.
10321
+ * @param accountId - Override the client's default account ID.
10322
+ * @returns The stored origin, e.g.
10323
+ * `{ "id": "1052c7d8e9f0a1b2c3d4e5f6a7b8", "origin": "https://app.example.com", "created_at": "2026-11-04T12:05:00Z" }`.
10324
+ * @throws {ValidationError} If `origin` is blank.
10325
+ * @throws {ApiError} `400` when it is invalid, already registered, or the
10326
+ * account has 10; `403` (`PlanRestricted`, or an OAuth application token).
10327
+ *
10328
+ * @example
10329
+ * ```ts
10330
+ * await client.embed.addOrigin('https://app.example.com');
10331
+ * ```
10332
+ */
10333
+ async addOrigin(origin, accountId) {
10334
+ assertNonEmptyString(origin, "origin");
10335
+ return this.call(
10336
+ "Failed to add embed origin",
10337
+ () => this.http.post(this.originsPath(accountId), { origin })
10338
+ );
10339
+ }
10340
+ /**
10341
+ * Replace an allowed origin, keeping its ID
10342
+ * (`PUT /accounts/{accountId}/embed-origins/{originId}`).
10343
+ *
10344
+ * @param originId - Embed origin ID.
10345
+ * @param origin - New origin, with the rules of {@link EmbedResource.addOrigin}.
10346
+ * @param accountId - Override the client's default account ID.
10347
+ * @returns The updated origin.
10348
+ * @throws {ValidationError} If an ID or the origin is blank.
10349
+ * @throws {ApiError} `400` for an invalid or duplicate origin, `403`, `404` for
10350
+ * an unknown origin ID.
10351
+ *
10352
+ * @example
10353
+ * ```ts
10354
+ * await client.embed.updateOrigin(originId, 'https://sign.example.com');
10355
+ * ```
10356
+ */
10357
+ async updateOrigin(originId, origin, accountId) {
10358
+ assertNonEmptyString(origin, "origin");
10359
+ return this.call(
10360
+ "Failed to update embed origin",
10361
+ () => this.http.put(this.originPath(originId, accountId), { origin })
10362
+ );
10363
+ }
10364
+ /**
10365
+ * Stop allowing an origin (`DELETE /accounts/{accountId}/embed-origins/{originId}`).
10366
+ *
10367
+ * Removing the last origin disables embedding: new sessions answer `409`
10368
+ * (`embed_origins_missing`).
10369
+ *
10370
+ * @param originId - Embed origin ID.
10371
+ * @param accountId - Override the client's default account ID.
10372
+ * @throws {ValidationError} If an ID is missing or invalid.
10373
+ * @throws {ApiError} `403`, or `404` for an unknown origin ID.
10374
+ *
10375
+ * @example
10376
+ * ```ts
10377
+ * await client.embed.deleteOrigin(originId);
10378
+ * ```
10379
+ */
10380
+ async deleteOrigin(originId, accountId) {
10381
+ return this.callVoid(
10382
+ "Failed to remove embed origin",
10383
+ () => this.http.delete(this.originPath(originId, accountId))
10384
+ );
10385
+ }
10386
+ /**
10387
+ * Mint a single-use embed URL for an `embedded` signer
10388
+ * (`POST /documents/{documentId}/assignments/{assignmentId}/signers/{signerId}/embed-sessions`).
10389
+ *
10390
+ * Load the URL in an iframe on a registered origin within 5 minutes;
10391
+ * opening it spends the token, so mint a new one each time the frame is
10392
+ * shown, including reloads. Treat it as a credential: hand it only to that
10393
+ * signer's page and never store or log it. Limited to 30 sessions per signer
10394
+ * per hour. For an envelope signer, mint on any of their documents still
10395
+ * waiting for them; the frame lists every document they still have to sign.
10396
+ * Frame events are UI hints: confirm the outcome from webhooks.
10397
+ *
10398
+ * @param documentId - Document ID.
10399
+ * @param assignmentId - Assignment ID.
10400
+ * @param signerId - Signer created with `embedded: true`.
10401
+ * @returns The session:
10402
+ * ```jsonc
10403
+ * {
10404
+ * "url": "https://app.assinafy.com.br/embed/3b1f0c7e9a2d4c58b6e1f4a07d93c2e85a1b0f6d4c7e2a9183b5d6f0e4c8a712",
10405
+ * "expires_at": "2026-11-04T12:05:00Z"
10406
+ * }
10407
+ * ```
10408
+ * @throws {ValidationError} If an ID is missing or invalid.
10409
+ * @throws {ApiError} `400` (`embed_not_enabled_for_signer`), `403`
10410
+ * (`PlanRestricted`), `404` for an unknown document, assignment or signer,
10411
+ * `409` (`already_signed`, `document_not_ready` — retry shortly,
10412
+ * `document_unavailable`, `embed_origins_missing`), `429` past 30 per hour.
10413
+ *
10414
+ * @example
10415
+ * ```ts
10416
+ * const { url } = await client.embed.createSession(document.id, assignment.id, signer.id);
10417
+ * response.json({ url }); // to the signer's browser only
10418
+ * ```
10419
+ */
10420
+ async createSession(documentId, assignmentId, signerId) {
10421
+ return this.call(
10422
+ "Failed to create embed session",
10423
+ () => this.http.post(
10424
+ `/documents/${this.pathSegment(documentId, "Document ID")}/assignments/${this.pathSegment(assignmentId, "Assignment ID")}/signers/${this.pathSegment(signerId, "Signer ID")}/embed-sessions`
10425
+ )
10426
+ );
10427
+ }
10428
+ originsPath(accountId) {
10429
+ return `/accounts/${this.pathSegment(this.accountId(accountId), "Account ID")}/embed-origins`;
10430
+ }
10431
+ originPath(originId, accountId) {
10432
+ return `${this.originsPath(accountId)}/${this.pathSegment(originId, "Embed origin ID")}`;
10433
+ }
10434
+ };
10435
+
9021
10436
  // src/support/webhook-verifier.ts
9022
10437
  var import_node_crypto2 = require("crypto");
9023
10438
  var DEFAULT_TOLERANCE_SECONDS = 300;
9024
10439
  var WebhookVerifier = class {
9025
10440
  webhookSecret;
9026
10441
  /**
9027
- * @param webhookSecret - The endpoint's `whsec_…` secret from
9028
- * `webhooks.getEndpointSecret()`. Omit it to keep verification disabled
9029
- * (every check returns `false`).
10442
+ * @param webhookSecret - The endpoint's `whsec_…` secret, as returned by
10443
+ * `webhooks.createEndpoint()` / `updateEndpoint()` when signing turns on,
10444
+ * `rotateEndpointSecret()`, or (API key only) `getEndpointSecret()`. Omit it
10445
+ * to keep verification disabled (every check returns `false`).
9030
10446
  *
9031
10447
  * @example
9032
10448
  * ```ts
@@ -9079,6 +10495,7 @@ var WebhookVerifier = class {
9079
10495
  const [version, signature] = entry.split(",", 2);
9080
10496
  if (version !== "v1" || !signature) return false;
9081
10497
  const actual = Buffer.from(signature, "base64");
10498
+ if (actual.toString("base64") !== signature) return false;
9082
10499
  return actual.length === expected.length && (0, import_node_crypto2.timingSafeEqual)(actual, expected);
9083
10500
  });
9084
10501
  }
@@ -9206,6 +10623,8 @@ var AssinafyClient = class _AssinafyClient {
9206
10623
  signerDocuments;
9207
10624
  users;
9208
10625
  contracts;
10626
+ envelopes;
10627
+ embed;
9209
10628
  webhookVerifier;
9210
10629
  /**
9211
10630
  * Create a client. Supply `apiKey` (preferred, sent as `X-Api-Key`) or a
@@ -9315,7 +10734,12 @@ var AssinafyClient = class _AssinafyClient {
9315
10734
  this.logger,
9316
10735
  this.publicAxiosInstance
9317
10736
  );
9318
- this.fields = new FieldsResource(this.axiosInstance, this.defaultAccountId, this.logger);
10737
+ this.fields = new FieldsResource(
10738
+ this.axiosInstance,
10739
+ this.defaultAccountId,
10740
+ this.logger,
10741
+ this.publicAxiosInstance
10742
+ );
9319
10743
  this.signerDocuments = new SignerDocumentsResource(
9320
10744
  this.axiosInstance,
9321
10745
  this.defaultAccountId,
@@ -9328,6 +10752,8 @@ var AssinafyClient = class _AssinafyClient {
9328
10752
  this.defaultAccountId,
9329
10753
  this.logger
9330
10754
  );
10755
+ this.envelopes = new EnvelopeResource(this.axiosInstance, this.defaultAccountId, this.logger);
10756
+ this.embed = new EmbedResource(this.axiosInstance, this.defaultAccountId, this.logger);
9331
10757
  this.webhookVerifier = new WebhookVerifier(this.webhookSecret);
9332
10758
  }
9333
10759
  /**
@@ -9432,8 +10858,9 @@ var AssinafyClient = class _AssinafyClient {
9432
10858
  * the API; only `collect` assignments require pre-rendered pages.
9433
10859
  * @param options.waitOptions - Optional `maxWaitMs` / `pollIntervalMs`
9434
10860
  * forwarded to {@link DocumentResource.waitUntilReady}.
9435
- * @param options.expiresAt - Optional ISO-8601 assignment expiry, e.g.
9436
- * `'2026-08-01T00:00:00Z'`.
10861
+ * @param options.expiresAt - Optional ISO-8601 assignment expiry. A date
10862
+ * ends at 23:59 UTC; a date-time without an offset is interpreted as UTC;
10863
+ * an explicit offset is honored.
9437
10864
  * @param options.copyReceivers - Optional existing signer IDs (not email
9438
10865
  * addresses) that receive a copy. See the caveat on
9439
10866
  * {@link ICreateAssignmentPayload.copy_receivers}; some plans silently drop
@@ -9499,7 +10926,7 @@ var AssinafyClient = class _AssinafyClient {
9499
10926
  * });
9500
10927
  * console.log(document.status); // usually 'pending_signature'
9501
10928
  * console.log(signer_ids.length); // 2
9502
- * console.log(assignment.signing_urls?.length); // one protected link per signer
10929
+ * console.log(assignment.signing_urls?.length); // one entry per notified signer; url is null for embedded or WhatsApp-only signers
9503
10930
  * ```
9504
10931
  */
9505
10932
  async uploadAndRequestSignatures(options) {
@@ -9519,7 +10946,7 @@ var AssinafyClient = class _AssinafyClient {
9519
10946
  if (options.metadata !== void 0) {
9520
10947
  assertRecord(options.metadata, "metadata");
9521
10948
  }
9522
- if (options.expiresAt !== void 0) assertDateTime(options.expiresAt, "expiresAt");
10949
+ if (options.expiresAt !== void 0) assertExpirationDate(options.expiresAt, "expiresAt");
9523
10950
  if (options.copyReceivers !== void 0 && (!Array.isArray(options.copyReceivers) || options.copyReceivers.some(
9524
10951
  (id) => typeof id !== "string" || id.trim().length === 0
9525
10952
  ))) {
@@ -9758,6 +11185,8 @@ function hasIdempotencyKey(headers) {
9758
11185
  DEFAULT_WEBHOOK_EVENTS,
9759
11186
  DIGITAL_CERTIFICATE_REQUIRES_VIRTUAL_METHOD,
9760
11187
  DocumentResource,
11188
+ EmbedResource,
11189
+ EnvelopeResource,
9761
11190
  FieldsResource,
9762
11191
  MAX_LIST_PAGE_SIZE,
9763
11192
  MAX_UPLOAD_BYTES,