@assinafy/sdk 2.7.1 → 2.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -36,6 +36,7 @@ __export(index_exports, {
36
36
  AssinafyError: () => AssinafyError,
37
37
  AuthenticationResource: () => AuthenticationResource,
38
38
  DEFAULT_WEBHOOK_EVENTS: () => DEFAULT_WEBHOOK_EVENTS,
39
+ DIGITAL_CERTIFICATE_REQUIRES_VIRTUAL_METHOD: () => DIGITAL_CERTIFICATE_REQUIRES_VIRTUAL_METHOD,
39
40
  DocumentResource: () => DocumentResource,
40
41
  FieldsResource: () => FieldsResource,
41
42
  MAX_LIST_PAGE_SIZE: () => MAX_LIST_PAGE_SIZE,
@@ -565,6 +566,7 @@ var import_axios3 = require("axios");
565
566
 
566
567
  // src/support/path.ts
567
568
  function encodePathSegment(value) {
569
+ if (value === "." || value === "..") throw new Error("Dot segments are not resource IDs");
568
570
  return encodeURIComponent(value).replace(
569
571
  /[!'()*]/g,
570
572
  (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`
@@ -687,7 +689,7 @@ var import_axios2 = __toESM(require("axios"));
687
689
  // package.json
688
690
  var package_default = {
689
691
  name: "@assinafy/sdk",
690
- version: "2.7.1",
692
+ version: "2.8.1",
691
693
  packageManager: "bun@1.4.0",
692
694
  description: "TypeScript SDK for Assinafy API - Digital signature platform",
693
695
  type: "commonjs",
@@ -819,7 +821,13 @@ function applySdkTransportDefaults(http) {
819
821
  const guarded = (options, response, request) => {
820
822
  guardRedirect(options, response, request);
821
823
  if (current && typeof options["href"] === "string" && new URL(request.url).origin === new URL(options["href"]).origin) {
824
+ const destinationKeys = ["protocol", "host", "hostname", "port", "socketPath", "servername"];
825
+ const destination = destinationKeys.map((key) => options[key]);
826
+ const host = readHeader(options["headers"], "host");
822
827
  current(options, response, request);
828
+ if (destinationKeys.some((key, index) => options[key] !== destination[index]) || readHeader(options["headers"], "host") !== host) {
829
+ throw new Error("Redirect hooks must not change the destination");
830
+ }
823
831
  guardRedirect(options, response, request);
824
832
  }
825
833
  };
@@ -1027,12 +1035,14 @@ function toInt(value) {
1027
1035
 
1028
1036
  // src/resources/assignments.ts
1029
1037
  var ASSIGNMENT_METHODS = /* @__PURE__ */ new Set(["virtual", "collect"]);
1030
- var VERIFICATION_METHODS = /* @__PURE__ */ new Set(["Email", "Whatsapp", "DigitalCertificate"]);
1038
+ var VERIFICATION_METHODS = /* @__PURE__ */ new Set(["Email", "Whatsapp", "DigitalCertificate", "IdDocumentFaceMatchBasic"]);
1031
1039
  var NOTIFICATION_METHODS = /* @__PURE__ */ new Set(["Email", "Whatsapp"]);
1040
+ var DIGITAL_CERTIFICATE_REQUIRES_VIRTUAL_METHOD = "digital_certificate_requires_virtual_method";
1032
1041
  var ALLOWED_NOTIFICATION_METHODS = {
1033
1042
  Email: /* @__PURE__ */ new Set(["Email"]),
1034
1043
  Whatsapp: /* @__PURE__ */ new Set(["Whatsapp"]),
1035
- DigitalCertificate: NOTIFICATION_METHODS
1044
+ DigitalCertificate: NOTIFICATION_METHODS,
1045
+ IdDocumentFaceMatchBasic: NOTIFICATION_METHODS
1036
1046
  };
1037
1047
  function validateAssignmentSignerOptions(signer, label = "signer") {
1038
1048
  if (signer.verification_method !== void 0 && (typeof signer.verification_method !== "string" || !VERIFICATION_METHODS.has(signer.verification_method))) {
@@ -1082,6 +1092,15 @@ function validateSigningOrder(signers, label = "signers") {
1082
1092
  }
1083
1093
  }
1084
1094
  }
1095
+ function validateDigitalCertificateMethod(method, signers) {
1096
+ if (method === "virtual" || !signers.some((signer) => signer.verification_method === "DigitalCertificate")) {
1097
+ return;
1098
+ }
1099
+ throw new ValidationError("DigitalCertificate signers require method: virtual", {
1100
+ code: DIGITAL_CERTIFICATE_REQUIRES_VIRTUAL_METHOD,
1101
+ method: method ?? null
1102
+ });
1103
+ }
1085
1104
  function buildAssignmentPayload(payload) {
1086
1105
  assertRecord(payload, "assignment payload");
1087
1106
  const method = payload.method ?? "virtual";
@@ -1110,6 +1129,7 @@ function buildAssignmentPayload(payload) {
1110
1129
  throw new ValidationError("copy_receivers must be an array of non-empty signer IDs");
1111
1130
  }
1112
1131
  const normalisedSigners = signers.map((ref) => normaliseSignerRef(ref));
1132
+ validateDigitalCertificateMethod(method, normalisedSigners);
1113
1133
  validateSigningOrder(normalisedSigners, "assignment signers");
1114
1134
  return cleanParams({
1115
1135
  method,
@@ -1134,9 +1154,11 @@ function buildAssignmentEstimatePayload(payload) {
1134
1154
  if (method === "collect" && (!entries || entries.length === 0)) {
1135
1155
  throw new ValidationError("At least one field-placement entry is required for a collect cost estimate");
1136
1156
  }
1157
+ const normalisedSigners = signers.map((signer) => normaliseEstimateSigner(signer));
1158
+ validateDigitalCertificateMethod(method, normalisedSigners);
1137
1159
  return cleanParams({
1138
1160
  method,
1139
- signers: signers.map((signer) => normaliseEstimateSigner(signer)),
1161
+ signers: normalisedSigners,
1140
1162
  entries
1141
1163
  });
1142
1164
  }
@@ -1372,8 +1394,12 @@ var AssignmentResource = class extends BaseResource {
1372
1394
  * {@link buildAssignmentPayload}. A `virtual` assignment may be created at
1373
1395
  * `uploaded`, `metadata_processing`, or `metadata_ready` and is promoted
1374
1396
  * automatically; `collect` requires rendered pages at `metadata_ready`.
1375
- * `DigitalCertificate` costs two credits, requires the feature plus a
1376
- * signer `government_id`, and that signer must be alone in its step.
1397
+ * `DigitalCertificate` costs 0.5 credits, requires the feature plus a
1398
+ * signer `government_id`, that signer must be alone in its step, and the
1399
+ * assignment must use `method: 'virtual'`. Certificate completion marks a
1400
+ * virtual item complete; it cannot submit placed `collect` fields.
1401
+ * `IdDocumentFaceMatchBasic` needs the ID Document + Face Match feature
1402
+ * and a valid CPF in the signer's `government_id`; estimate its fee first.
1377
1403
  *
1378
1404
  * Request body (`application/json`):
1379
1405
  * ```jsonc
@@ -1471,7 +1497,9 @@ var AssignmentResource = class extends BaseResource {
1471
1497
  * }
1472
1498
  * ```
1473
1499
  * @throws {ValidationError} If `documentId` is missing, no signer is
1474
- * supplied, or a signer reference is invalid.
1500
+ * supplied, a signer reference is invalid, or `DigitalCertificate` is
1501
+ * combined with `collect`. The last case has `errors.code ===
1502
+ * 'digital_certificate_requires_virtual_method'`.
1475
1503
  * @throws {ApiError} `400` for an invalid assignment or unmet verification
1476
1504
  * precondition; otherwise if the API rejects the request.
1477
1505
  *
@@ -1509,8 +1537,10 @@ var AssignmentResource = class extends BaseResource {
1509
1537
  * only `verification_method` / `notification_methods` (or `{}` for the
1510
1538
  * default Email channel). {@link buildAssignmentEstimatePayload} projects
1511
1539
  * exactly the fields permitted by the estimate schema.
1512
- * `DigitalCertificate` is priced at two credits per signer and remains
1513
- * subject to the feature, identity, and one-signer-per-step requirements.
1540
+ * `DigitalCertificate` is priced at 0.5 credits per signer and remains
1541
+ * subject to the feature and identity requirements. It is valid only with
1542
+ * `method: 'virtual'`; the SDK refuses to quote a certificate/`collect`
1543
+ * request because that assignment cannot be completed.
1514
1544
  * Current documented unit prices are 1 credit for an extra document, 0 for
1515
1545
  * email notification, and 0.45 for WhatsApp notification; a digital
1516
1546
  * certificate charge is added on top of its notification cost.
@@ -1555,7 +1585,9 @@ var AssignmentResource = class extends BaseResource {
1555
1585
  * ```
1556
1586
  * @throws {ValidationError} If `documentId` is missing, a `virtual` request
1557
1587
  * has no signer entry, or a `collect` request has no signer entry or no
1558
- * field-placement entry.
1588
+ * field-placement entry, or combines `DigitalCertificate` with `collect`.
1589
+ * The last case has `errors.code ===
1590
+ * 'digital_certificate_requires_virtual_method'`.
1559
1591
  * @throws {ApiError} If the API rejects the request.
1560
1592
  *
1561
1593
  * @example
@@ -1785,6 +1817,148 @@ var AssignmentResource = class extends BaseResource {
1785
1817
  )
1786
1818
  );
1787
1819
  }
1820
+ /**
1821
+ * Read the account's signer identity review
1822
+ * (`GET /documents/{documentId}/assignments/{assignmentId}/signers/{signerId}/identity-verification`).
1823
+ *
1824
+ * No request body. `InReview` lets the signer continue signing but holds
1825
+ * certification. Evidence is a summary without images or biometrics; a
1826
+ * directly approved verification exposes evidence on its activity instead.
1827
+ *
1828
+ * @param documentId - Document owning the assignment.
1829
+ * @param assignmentId - Assignment containing the signer.
1830
+ * @param signerId - Signer whose identity is under review.
1831
+ * @returns The complete review summary:
1832
+ * ```jsonc
1833
+ * {
1834
+ * "id": "verification_example", "status": "InReview",
1835
+ * "provider": "AssinafyVerify", "verification_method": "IdDocumentFaceMatchBasic",
1836
+ * "reason_codes": [{ "code": "NAME_MISMATCH", "description": "Name differs" }],
1837
+ * "evidence_available": true,
1838
+ * "expected": { "name": "Example Signer", "cpf": null },
1839
+ * "document": { "type": "CNH", "name": "EXAMPLE SIGNER", "cpf": null },
1840
+ * "matches": { "cpf": null, "name": 0.52, "birth_date": null },
1841
+ * "checks": [{ "name": "name", "result": "review", "score": 0.52, "reasons": ["NAME_MISMATCH"] }],
1842
+ * "images": ["document_front", "face"], // available only while InReview
1843
+ * "ruleset_version": "2026-10-12.2", "evidence_sha256": null,
1844
+ * "reviewed_by": null, "reviewed_at": null, "review_note": null, "completed_at": null
1845
+ * }
1846
+ * ```
1847
+ * @throws {ValidationError} If any ID is blank or invalid for a URL.
1848
+ * @throws {ApiError} `401` for invalid credentials; `404` for an unknown
1849
+ * assignment, signer or verification; `500` for a server failure.
1850
+ * @example
1851
+ * ```ts
1852
+ * const review = await client.assignments.getIdentityVerification('doc-1', 'asg-1', 'signer-1');
1853
+ * console.log(review.status, review.images.length);
1854
+ * ```
1855
+ */
1856
+ async getIdentityVerification(documentId, assignmentId, signerId) {
1857
+ const path2 = this.identityVerificationPath(documentId, assignmentId, signerId);
1858
+ return this.call("Failed to fetch signer identity review", () => this.http.get(path2));
1859
+ }
1860
+ /**
1861
+ * Download identity review evidence
1862
+ * (`GET /documents/{documentId}/assignments/{assignmentId}/signers/{signerId}/identity-verification/images/{name}`).
1863
+ *
1864
+ * No request body. The provider supplies the bytes on each request; Assinafy
1865
+ * never stores them. Available only while the review is open. Keep these
1866
+ * sensitive bytes out of caches and logs (`Cache-Control: no-store`).
1867
+ *
1868
+ * @param documentId - Document owning the assignment.
1869
+ * @param assignmentId - Assignment containing the signer.
1870
+ * @param signerId - Signer whose evidence to view.
1871
+ * @param name - One of the review's `images`: `document_front`,
1872
+ * `document_back`, `document_pdf`, or `face`.
1873
+ * @returns Raw JPEG, PNG or PDF bytes as a `Buffer`.
1874
+ * @throws {ValidationError} If an ID or image name is invalid.
1875
+ * @throws {ApiError} `401` for invalid credentials; `404` for absent evidence
1876
+ * or a decided review; `500` for a provider/server failure.
1877
+ * @example
1878
+ * ```ts
1879
+ * const bytes = await client.assignments.downloadIdentityVerificationImage('doc-1', 'asg-1', 'signer-1', 'face');
1880
+ * ```
1881
+ */
1882
+ async downloadIdentityVerificationImage(documentId, assignmentId, signerId, name) {
1883
+ const path2 = this.identityVerificationPath(documentId, assignmentId, signerId);
1884
+ if (!["document_front", "document_back", "document_pdf", "face"].includes(name)) {
1885
+ throw new ValidationError("Invalid identity verification image name");
1886
+ }
1887
+ return this.callBinary(
1888
+ "Failed to download identity review evidence",
1889
+ () => this.http.get(`${path2}/images/${name}`, { responseType: "arraybuffer" })
1890
+ );
1891
+ }
1892
+ /**
1893
+ * Decide a signer identity review
1894
+ * (`POST /documents/{documentId}/assignments/{assignmentId}/signers/{signerId}/identity-verification/review`).
1895
+ *
1896
+ * Requires `InReview` and a document at `pending_signature` or
1897
+ * `pending_identity_review`. Approval allows certification once all signers
1898
+ * sign and every review is approved. Rejection cancels the document as
1899
+ * `rejected_by_user` and sends cancellation notices to signers and copy
1900
+ * receivers. The note is hidden from them; the provider receives the decision.
1901
+ *
1902
+ * Request body (`application/json`):
1903
+ * ```jsonc
1904
+ * { "decision": "Approved", "note": "Verified independently." }
1905
+ * ```
1906
+ * @param documentId - Document owning the assignment.
1907
+ * @param assignmentId - Assignment containing the signer.
1908
+ * @param signerId - Signer whose review to decide.
1909
+ * @param payload - Explicit account review decision.
1910
+ * @param payload.decision - `Approved` or `Rejected`.
1911
+ * @param payload.note - Optional nullable note, at most 2000 characters.
1912
+ * @returns The updated review, in the full
1913
+ * {@link AssignmentResource.getIdentityVerification} shape:
1914
+ * ```jsonc
1915
+ * {
1916
+ * "id": "verification_example", "status": "Approved",
1917
+ * "provider": "AssinafyVerify", "verification_method": "IdDocumentFaceMatchBasic",
1918
+ * "reason_codes": [{ "code": "NAME_MISMATCH", "description": "Name differs" }],
1919
+ * "evidence_available": true,
1920
+ * "expected": { "name": "Example Signer", "cpf": null },
1921
+ * "document": { "type": "CNH", "name": "EXAMPLE SIGNER", "cpf": null },
1922
+ * "matches": { "cpf": null, "name": 0.52, "birth_date": null },
1923
+ * "checks": [{ "name": "name", "result": "review", "score": 0.52, "reasons": ["NAME_MISMATCH"] }],
1924
+ * "images": [], "ruleset_version": "2026-10-12.2", "evidence_sha256": null,
1925
+ * "reviewed_by": { "id": "user_example", "name": "Example Reviewer" },
1926
+ * "reviewed_at": "2026-10-16T12:00:00Z", "review_note": "Verified independently.",
1927
+ * "completed_at": "2026-10-16T12:00:00Z"
1928
+ * }
1929
+ * ```
1930
+ * @throws {ValidationError} If IDs, decision or note are invalid.
1931
+ * @throws {ApiError} `400` for a closed review or invalid document state;
1932
+ * `401` for invalid credentials; `404` if absent; `500` for a server failure.
1933
+ * @example
1934
+ * ```ts
1935
+ * await client.assignments.reviewIdentityVerification('doc-1', 'asg-1', 'signer-1', {
1936
+ * decision: 'Approved', note: 'Verified independently.',
1937
+ * });
1938
+ * ```
1939
+ */
1940
+ async reviewIdentityVerification(documentId, assignmentId, signerId, payload) {
1941
+ const path2 = this.identityVerificationPath(documentId, assignmentId, signerId);
1942
+ assertRecord(payload, "identity review payload");
1943
+ if (payload.decision !== "Approved" && payload.decision !== "Rejected") {
1944
+ throw new ValidationError("decision must be Approved or Rejected");
1945
+ }
1946
+ if (payload.note !== void 0 && payload.note !== null && (typeof payload.note !== "string" || [...payload.note].length > 2e3)) {
1947
+ throw new ValidationError("note must be a string of at most 2000 characters, or null");
1948
+ }
1949
+ const body = { decision: payload.decision };
1950
+ if (payload.note !== void 0) body.note = payload.note;
1951
+ return this.call(
1952
+ "Failed to decide signer identity review",
1953
+ () => this.http.post(`${path2}/review`, body)
1954
+ );
1955
+ }
1956
+ identityVerificationPath(documentId, assignmentId, signerId) {
1957
+ const docId = this.pathSegment(documentId, "Document ID");
1958
+ const asgId = this.pathSegment(assignmentId, "Assignment ID");
1959
+ const sid = this.pathSegment(signerId, "Signer ID");
1960
+ return `/documents/${docId}/assignments/${asgId}/signers/${sid}/identity-verification`;
1961
+ }
1788
1962
  };
1789
1963
 
1790
1964
  // src/resources/documents.ts
@@ -1798,6 +1972,7 @@ function validateDocumentWaitOptions(options) {
1798
1972
  var READY_STATUSES = /* @__PURE__ */ new Set([
1799
1973
  "metadata_ready",
1800
1974
  "pending_signature",
1975
+ "pending_identity_review",
1801
1976
  "certificated"
1802
1977
  ]);
1803
1978
  var FAILED_STATUSES = /* @__PURE__ */ new Set([
@@ -1824,6 +1999,9 @@ var DocumentResource = class extends BaseResource {
1824
1999
  *
1825
2000
  * @param source - The PDF to upload, as a file path or an in-memory buffer.
1826
2001
  * @param options - Display name, metadata, and account override.
2002
+ * @param options.name - Multipart filename override; the API derives the display name from it.
2003
+ * @param options.metadata - JSON metadata (compatibility multipart part).
2004
+ * @param options.accountId - Override the client's default workspace.
1827
2005
  * @returns The created document, freshly uploaded (`status: 'uploaded'`,
1828
2006
  * empty `pages` until `metadata_ready`). Response shape:
1829
2007
  * ```jsonc
@@ -1934,7 +2112,7 @@ var DocumentResource = class extends BaseResource {
1934
2112
  * method: 'virtual',
1935
2113
  * 'per-page': 50,
1936
2114
  * });
1937
- * console.log(data[0]?.pages.length, meta?.total);
2115
+ * console.log(data[0]?.pages?.length, meta?.total);
1938
2116
  * ```
1939
2117
  */
1940
2118
  async list(params = {}, accountId) {
@@ -2147,7 +2325,8 @@ var DocumentResource = class extends BaseResource {
2147
2325
  }
2148
2326
  /**
2149
2327
  * Poll {@link DocumentResource.details} until the document reaches a ready
2150
- * status (`metadata_ready`, `pending_signature`, or `certificated`),
2328
+ * status (`metadata_ready`, `pending_signature`, `pending_identity_review`,
2329
+ * or `certificated`),
2151
2330
  * throwing on a terminal failure status or timeout.
2152
2331
  *
2153
2332
  * Transient errors are tolerated — a `5xx` or `429` is retried on the next
@@ -2157,6 +2336,8 @@ var DocumentResource = class extends BaseResource {
2157
2336
  * @param documentId - The document to wait on.
2158
2337
  * @param options - `maxWaitMs` (default `30_000`) and `pollIntervalMs`
2159
2338
  * (default `2_000`).
2339
+ * @param options.maxWaitMs - Finite non-negative wait budget in milliseconds; default `30_000`.
2340
+ * @param options.pollIntervalMs - Finite positive polling interval in milliseconds; default `2_000`.
2160
2341
  * @returns The document details once it reaches a ready status (see
2161
2342
  * {@link DocumentResource.details} for the shape).
2162
2343
  * @throws {ValidationError} If `documentId` is missing, the document enters
@@ -2424,6 +2605,9 @@ var DocumentResource = class extends BaseResource {
2424
2605
  * names are not portable identifiers and should not be used here. This
2425
2606
  * overwrites the existing set — use
2426
2607
  * {@link DocumentResource.addTags} to append.
2608
+ * Older sandbox deployments interpret these strings as names and create
2609
+ * ID-named tags for ID inputs; pass existing names intentionally there.
2610
+ * Strings are sent unchanged. See `docs/COMPATIBILITY.md` for this variant.
2427
2611
  *
2428
2612
  * Request body (`application/json`):
2429
2613
  * ```jsonc
@@ -2475,6 +2659,8 @@ var DocumentResource = class extends BaseResource {
2475
2659
  * `tags` is a non-empty array of tag **IDs**. Attaching an ID already
2476
2660
  * present is a no-op. To replace the whole set instead, use
2477
2661
  * {@link DocumentResource.replaceTags}.
2662
+ * On older name-based sandbox deployments, pass existing tag names
2663
+ * intentionally; ID inputs create ID-named tags. No automatic remapping occurs.
2478
2664
  *
2479
2665
  * Request body (`application/json`):
2480
2666
  * ```jsonc
@@ -2594,10 +2780,20 @@ var DocumentResource = class extends BaseResource {
2594
2780
  * plus optional `verification_method`, `notification_methods`, `step`).
2595
2781
  * Only one notification method is allowed per signer; when only one of the
2596
2782
  * verification/notification fields is supplied, the API infers the other.
2597
- * `DigitalCertificate` costs two credits, requires the feature plus a
2598
- * signer `government_id`, and that signer must be alone in its step.
2783
+ * `DigitalCertificate` costs 0.5 credits, requires the feature plus a
2784
+ * signer `government_id`, and that signer must be alone in its step. The
2785
+ * server derives the assignment method from placed template fields but
2786
+ * does not yet reject unusable certificate/`collect` combinations, so the
2787
+ * SDK temporarily refuses certificate signers on this template route.
2788
+ * `IdDocumentFaceMatchBasic` needs the ID Document + Face Match feature
2789
+ * and a valid CPF in `government_id`; estimate the per-signer fee first.
2599
2790
  * @param options - Optional `name`, `message`, `expires_at`,
2600
2791
  * `editor_fields`, `tags`.
2792
+ * @param options.name - Generated document display name.
2793
+ * @param options.message - Signing invitation message.
2794
+ * @param options.expires_at - ISO-8601 signature deadline.
2795
+ * @param options.editor_fields - Template editor values as `{ field_id, value }` entries.
2796
+ * @param options.tags - Tag names attached to the generated document.
2601
2797
  * @param accountId - Override the client's default account ID.
2602
2798
  * @returns The created document (an {@link IDocumentDetailsResponse} with
2603
2799
  * `template_id` set and its `assignment` populated):
@@ -2619,15 +2815,16 @@ var DocumentResource = class extends BaseResource {
2619
2815
  * "updated_at": "2026-07-15T19:59:33Z"
2620
2816
  * }
2621
2817
  * ```
2622
- * @throws {ValidationError} If `templateId` is missing or no account ID is
2623
- * available.
2818
+ * @throws {ValidationError} If `templateId` is missing, no account ID is
2819
+ * available, or a signer uses `DigitalCertificate`. Certificate refusals
2820
+ * have `errors.code === 'digital_certificate_requires_virtual_method'`.
2624
2821
  * @throws {ApiError} `400` if the signers/roles are invalid or the template
2625
2822
  * is not ready.
2626
2823
  *
2627
2824
  * @example
2628
2825
  * ```ts
2629
2826
  * await client.documents.createFromTemplate('tmpl_id', [
2630
- * { role_id: 'role_id', id: 'signer_id', verification_method: 'DigitalCertificate' },
2827
+ * { role_id: 'role_id', id: 'signer_id', verification_method: 'Email' },
2631
2828
  * ], { name: 'My Contract' });
2632
2829
  * ```
2633
2830
  */
@@ -2669,8 +2866,10 @@ var DocumentResource = class extends BaseResource {
2669
2866
  *
2670
2867
  * A dry run: sends only `{ signers }` and consumes nothing. Use it to check
2671
2868
  * balances before calling {@link DocumentResource.createFromTemplate}.
2672
- * `DigitalCertificate` adds two credits per signer and has the same feature,
2673
- * `government_id`, and signing-step prerequisites as document creation.
2869
+ * `DigitalCertificate` requires a provably `virtual` assignment. Because
2870
+ * this route leaves method detection to the server, the SDK temporarily
2871
+ * refuses certificate signers instead of returning a price for an
2872
+ * assignment that may charge credits but cannot be completed.
2674
2873
  *
2675
2874
  * Request body (`application/json`):
2676
2875
  * ```jsonc
@@ -2712,14 +2911,15 @@ var DocumentResource = class extends BaseResource {
2712
2911
  * "message": null
2713
2912
  * }
2714
2913
  * ```
2715
- * @throws {ValidationError} If `templateId` is missing or no account ID is
2716
- * available.
2914
+ * @throws {ValidationError} If `templateId` is missing, no account ID is
2915
+ * available, or a signer uses `DigitalCertificate`. Certificate refusals
2916
+ * have `errors.code === 'digital_certificate_requires_virtual_method'`.
2717
2917
  * @throws {ApiError} If the API rejects the request.
2718
2918
  *
2719
2919
  * @example
2720
2920
  * ```ts
2721
2921
  * const estimate = await client.documents.estimateCostFromTemplate('tmpl_id', [
2722
- * { role_id: 'role_id', verification_method: 'DigitalCertificate' },
2922
+ * { role_id: 'role_id', verification_method: 'Email' },
2723
2923
  * ]);
2724
2924
  * if (!estimate.has_sufficient_resources) throw new Error(estimate.blocking_reason ?? 'insufficient');
2725
2925
  * ```
@@ -3008,7 +3208,7 @@ function normaliseTemplateSigners(signers) {
3008
3208
  if (signer.step !== void 0) projected.step = signer.step;
3009
3209
  return projected;
3010
3210
  });
3011
- validateSigningOrder(normalised, "template signers");
3211
+ validateDigitalCertificateMethod(void 0, normalised);
3012
3212
  return normalised;
3013
3213
  }
3014
3214
  function normaliseTemplateEditorFields(fields) {
@@ -3032,7 +3232,7 @@ function normaliseTemplateCostSigners(signers) {
3032
3232
  if (!Array.isArray(signers) || signers.length === 0) {
3033
3233
  throw new ValidationError("At least one template role is required for cost estimation");
3034
3234
  }
3035
- return signers.map((signer, index) => {
3235
+ const normalised = signers.map((signer, index) => {
3036
3236
  if (!signer || typeof signer !== "object") {
3037
3237
  throw new ValidationError(`Template cost signer ${index + 1} is invalid`);
3038
3238
  }
@@ -3049,6 +3249,8 @@ function normaliseTemplateCostSigners(signers) {
3049
3249
  }
3050
3250
  return descriptor;
3051
3251
  });
3252
+ validateDigitalCertificateMethod(void 0, normalised);
3253
+ return normalised;
3052
3254
  }
3053
3255
  function validateWaitOption(value, name) {
3054
3256
  if (!Number.isFinite(value) || value < 0 || name === "pollIntervalMs" && value === 0) {
@@ -3328,9 +3530,8 @@ var SignerResource = class extends BaseResource {
3328
3530
  * re-filtered here for an exact, case-insensitive email match.
3329
3531
  *
3330
3532
  * Page size is pinned to {@link MAX_LIST_PAGE_SIZE}, the largest page the
3331
- * server actually returns. An exact address realistically matches one
3332
- * signer, but a search term that matched more than that could in principle
3333
- * miss one — the API exposes no exact-email filter to rule that out.
3533
+ * server actually returns. Pages are searched until an exact match is found
3534
+ * or the result set ends, so substring matches cannot hide an existing signer.
3334
3535
  *
3335
3536
  * A `404` from the underlying list is treated as "no match" and mapped to
3336
3537
  * `null`; any other {@link ApiError} propagates.
@@ -3360,12 +3561,16 @@ var SignerResource = class extends BaseResource {
3360
3561
  async findByEmail(email, accountId) {
3361
3562
  this.assertEmail(email);
3362
3563
  try {
3363
- const { data } = await this.list(
3364
- { search: email, "per-page": MAX_LIST_PAGE_SIZE },
3365
- accountId
3366
- );
3367
3564
  const lower = email.toLowerCase();
3368
- return data.find((s) => (s.email ?? "").toLowerCase() === lower) ?? null;
3565
+ for (let page = 1; ; page++) {
3566
+ const { data, meta } = await this.list(
3567
+ { search: email, "per-page": MAX_LIST_PAGE_SIZE, page },
3568
+ accountId
3569
+ );
3570
+ const match = data.find((s) => (s.email ?? "").toLowerCase() === lower);
3571
+ if (match) return match;
3572
+ if (data.length === 0 || (meta?.last_page !== void 0 ? page >= meta.last_page : data.length < MAX_LIST_PAGE_SIZE)) return null;
3573
+ }
3369
3574
  } catch (err) {
3370
3575
  if (err instanceof ApiError && err.statusCode === 404) {
3371
3576
  return null;
@@ -3720,6 +3925,8 @@ var WorkspaceResource = class extends BaseResource {
3720
3925
  * @param accountId - Account to aggregate.
3721
3926
  * @param params - Omit for 12 monthly rows, or request daily rows with
3722
3927
  * `{ granularity: 'daily', month: '2026-06' }`.
3928
+ * @param params.granularity - `monthly` (default) or `daily`.
3929
+ * @param params.month - Month in `YYYY-MM` format; required for daily rows.
3723
3930
  * @returns Zero-filled KPI rows:
3724
3931
  * ```jsonc
3725
3932
  * [{
@@ -3845,6 +4052,7 @@ var WorkspaceResource = class extends BaseResource {
3845
4052
  * @param accountId - The workspace to delete.
3846
4053
  * @param options - Set `force: true` to cancel an active paid subscription
3847
4054
  * and proceed with deletion.
4055
+ * @param options.force - Cancel an active subscription and bypass deletion restrictions.
3848
4056
  * @returns Nothing on success (`200` with no meaningful body).
3849
4057
  * @throws {ValidationError} If `accountId` is missing.
3850
4058
  * @throws {ApiError} `400` (with a `restrictions` list) when the workspace
@@ -4227,6 +4435,8 @@ var WebhookResource = class extends BaseResource {
4227
4435
  * `account:read` scope.
4228
4436
  *
4229
4437
  * @param accountId - Override the client's default account ID.
4438
+ * @param params - Optional endpoint filters.
4439
+ * @param params.url - Match the exact registered endpoint URL.
4230
4440
  * @returns Every endpoint (1 on free plans, up to 3 on paid plans):
4231
4441
  * ```jsonc
4232
4442
  * [
@@ -4252,9 +4462,14 @@ var WebhookResource = class extends BaseResource {
4252
4462
  * const signed = endpoints.filter((endpoint) => endpoint.signing_enabled);
4253
4463
  * ```
4254
4464
  */
4255
- async listEndpoints(accountId) {
4465
+ async listEndpoints(accountId, params = {}) {
4466
+ assertRecord(params, "webhook endpoint filters");
4467
+ if (params.url !== void 0) validateWebhookUrl(params.url);
4256
4468
  const path2 = this.endpointsPath(accountId);
4257
- return this.call("Failed to list webhook endpoints", () => this.http.get(path2));
4469
+ return this.call(
4470
+ "Failed to list webhook endpoints",
4471
+ () => this.http.get(path2, params.url === void 0 ? void 0 : { params: { url: params.url } })
4472
+ );
4258
4473
  }
4259
4474
  /**
4260
4475
  * Register a URL to receive the account's webhook events
@@ -4262,8 +4477,9 @@ var WebhookResource = class extends BaseResource {
4262
4477
  *
4263
4478
  * An account can have 1 endpoint, or up to 3 on paid plans. Each endpoint
4264
4479
  * of a workspace needs a different `url`. With `signing_enabled: true` the
4265
- * API generates a signing secret; read it with
4266
- * {@link WebhookResource.getEndpointSecret}. When `events` is omitted or
4480
+ * API returns a signing `secret` in this creation response. Store it now:
4481
+ * OAuth applications cannot call {@link WebhookResource.getEndpointSecret}
4482
+ * or rotate it later. When `events` is omitted or
4267
4483
  * empty, {@link DEFAULT_WEBHOOK_EVENTS} is sent. OAuth tokens need the
4268
4484
  * `webhooks:write` scope.
4269
4485
  *
@@ -4293,6 +4509,7 @@ var WebhookResource = class extends BaseResource {
4293
4509
  * "events": ["document_ready", "signer_signed_document"],
4294
4510
  * "is_active": true,
4295
4511
  * "signing_enabled": true, // deliveries carry a `webhook-signature` header
4512
+ * "secret": "whsec_c2VjcmV0", // only in this response when signing is enabled
4296
4513
  * "created_at": "2026-10-01T12:00:00Z",
4297
4514
  * "updated_at": "2026-10-01T12:00:00Z"
4298
4515
  * }
@@ -4312,7 +4529,7 @@ var WebhookResource = class extends BaseResource {
4312
4529
  * events: ['document_ready', 'signer_signed_document'],
4313
4530
  * signing_enabled: true,
4314
4531
  * });
4315
- * const { secret } = await client.webhooks.getEndpointSecret(endpoint.id);
4532
+ * if (endpoint.secret) await secretStore.save(endpoint.id, endpoint.secret);
4316
4533
  * ```
4317
4534
  */
4318
4535
  async createEndpoint(payload, accountId) {
@@ -4437,6 +4654,32 @@ var WebhookResource = class extends BaseResource {
4437
4654
  this.logger.info("Deleting webhook endpoint");
4438
4655
  await this.callVoid("Failed to delete webhook endpoint", () => this.http.delete(path2));
4439
4656
  }
4657
+ /**
4658
+ * Delete a webhook endpoint using its registered URL
4659
+ * (`DELETE /accounts/{accountId}/webhooks/endpoints?url=…`).
4660
+ *
4661
+ * No request body. The query URL must match the registered value exactly.
4662
+ * Frees its plan slot; OAuth applications need `webhooks:write`.
4663
+ *
4664
+ * @param url - Exact registered HTTP(S) endpoint URL, including its query.
4665
+ * @param accountId - Override the client's default workspace.
4666
+ * @returns Resolves on acknowledgement (`{ "status": 200, "data": [] }`).
4667
+ * @throws {ValidationError} If the URL is invalid or the account is missing.
4668
+ * @throws {ApiError} `400` for a missing URL; `401` for invalid credentials;
4669
+ * `403` for missing scope; `404` if no endpoint uses the URL; `500` on failure.
4670
+ * @example
4671
+ * ```ts
4672
+ * await client.webhooks.deleteEndpointByUrl('https://example.com/webhooks/assinafy');
4673
+ * ```
4674
+ */
4675
+ async deleteEndpointByUrl(url, accountId) {
4676
+ validateWebhookUrl(url);
4677
+ const path2 = this.endpointsPath(accountId);
4678
+ return this.callVoid(
4679
+ "Failed to delete webhook endpoint",
4680
+ () => this.http.delete(path2, { params: { url } })
4681
+ );
4682
+ }
4440
4683
  /**
4441
4684
  * Return the secret that signs deliveries to an endpoint
4442
4685
  * (`GET /accounts/{accountId}/webhooks/endpoints/{endpointId}/secret`).
@@ -4559,6 +4802,8 @@ var TemplateResource = class extends BaseResource {
4559
4802
  *
4560
4803
  * @param source - The PDF to upload, as a file path or an in-memory buffer.
4561
4804
  * @param options - `name` (display name) and an optional `accountId` override.
4805
+ * @param options.name - Multipart filename override, with a `.pdf` extension.
4806
+ * @param options.accountId - Override the client's default workspace.
4562
4807
  * @returns The created template (envelope unwrapped). Response shape:
4563
4808
  * ```jsonc
4564
4809
  * {
@@ -4724,7 +4969,7 @@ var TemplateResource = class extends BaseResource {
4724
4969
  * @example
4725
4970
  * ```ts
4726
4971
  * const tmpl = await client.templates.get('103ad2171db7979468c3e97eb067');
4727
- * if (tmpl.status === 'Ready') console.log(tmpl.pages.length);
4972
+ * if (tmpl.status === 'Ready') console.log(tmpl.pages?.length ?? 0);
4728
4973
  * ```
4729
4974
  */
4730
4975
  async get(templateId, accountId) {
@@ -4886,6 +5131,7 @@ var TagResource = class extends BaseResource {
4886
5131
  *
4887
5132
  * @param params - Optional filters. `search` matches tag names
4888
5133
  * case-insensitively (substring).
5134
+ * @param params.search - Optional case-insensitive tag-name substring.
4889
5135
  * @param accountId - Override the client's default account ID.
4890
5136
  * @returns The matching tags (list items carry no `resource` field):
4891
5137
  * ```jsonc
@@ -5059,6 +5305,8 @@ var TagResource = class extends BaseResource {
5059
5305
  * @param tagId - The tag to delete.
5060
5306
  * @param options - `force` to detach-and-delete when the tag is still in
5061
5307
  * use, and `accountId` to override the client's default account ID.
5308
+ * @param options.force - Detach the tag from documents before deletion.
5309
+ * @param options.accountId - Override the client's default workspace.
5062
5310
  * @returns `{ deleted: true }` when the tag was deleted.
5063
5311
  * @throws {ValidationError} If `tagId` is missing, or no account ID is available.
5064
5312
  * @throws {ApiError} `404` if the tag does not exist; `409` if the tag is
@@ -6624,6 +6872,8 @@ var FieldsResource = class extends BaseResource {
6624
6872
  * @param value - The value to check (validated against the field's
6625
6873
  * type/regex). Sent as `{ value }` in the request body.
6626
6874
  * @param options - Account override and optional legacy `signerAccessCode`.
6875
+ * @param options.accountId - Override the client's default workspace.
6876
+ * @param options.signerAccessCode - Legacy signer code sent as a query parameter.
6627
6877
  * @returns The validation result. Response shape:
6628
6878
  * ```jsonc
6629
6879
  * {
@@ -6684,6 +6934,8 @@ var FieldsResource = class extends BaseResource {
6684
6934
  *
6685
6935
  * @param entries - Non-empty array of `{ field_id, value }` pairs.
6686
6936
  * @param options - Account override and optional legacy `signerAccessCode`.
6937
+ * @param options.accountId - Override the client's default workspace.
6938
+ * @param options.signerAccessCode - Legacy signer code sent as a query parameter.
6687
6939
  * @returns One validation result per entry. Response shape:
6688
6940
  * ```jsonc
6689
6941
  * [
@@ -7194,7 +7446,8 @@ var SignerDocumentsResource = class extends BaseResource {
7194
7446
  * "has_accepted_terms": false,
7195
7447
  * "has_signature": false,
7196
7448
  * "has_initial": false,
7197
- * "is_signature_reusable": false
7449
+ * "is_signature_reusable": false,
7450
+ * "verification_method": "IdDocumentFaceMatchBasic"
7198
7451
  * }
7199
7452
  * ```
7200
7453
  * @throws {ValidationError} If `signerAccessCode` is missing.
@@ -7215,6 +7468,92 @@ var SignerDocumentsResource = class extends BaseResource {
7215
7468
  () => this.http.get("/signers/self", { params: { "signer-access-code": code } })
7216
7469
  );
7217
7470
  }
7471
+ /**
7472
+ * Read the signer's identity verification state
7473
+ * (`GET /signers/identity-verification?signer-access-code=…`).
7474
+ *
7475
+ * No request body or workspace credentials. Reads a pending provider
7476
+ * decision when available. A new session can start before the first capture
7477
+ * or after `Expired`; `Declined` and `Abandoned` require a new document and
7478
+ * assignment. `InReview` lets the signer continue; account approval gates
7479
+ * certification, with `pending_identity_review` after everyone signs.
7480
+ *
7481
+ * @param signerAccessCode - Access code from the signer's signing link.
7482
+ * @returns Provider state, with nullable fields before a session exists:
7483
+ * ```jsonc
7484
+ * {
7485
+ * "can_start": false, "status": "Pending",
7486
+ * "url": "https://verify.example.com/c/session#t=opaque",
7487
+ * "expires_at": "2026-10-16T12:30:00Z", "completed_at": null
7488
+ * }
7489
+ * ```
7490
+ * `url` exists only while Pending. It is a bearer link: open it intact,
7491
+ * including its fragment, and keep it out of logs and browser storage.
7492
+ * @throws {ValidationError} If the access code is blank.
7493
+ * @throws {ApiError} `401` for an invalid/expired code; `500` for a server failure.
7494
+ * @example
7495
+ * ```ts
7496
+ * const state = await client.signerDocuments.getIdentityVerification(accessCode);
7497
+ * console.log(state.status, state.can_start);
7498
+ * ```
7499
+ */
7500
+ async getIdentityVerification(signerAccessCode) {
7501
+ const code = this.requireId(signerAccessCode, "signer-access-code");
7502
+ return this.call(
7503
+ "Failed to fetch signer identity verification",
7504
+ () => this.http.get("/signers/identity-verification", { params: { "signer-access-code": code } })
7505
+ );
7506
+ }
7507
+ /**
7508
+ * Record biometric consent and open an identity verification session
7509
+ * (`POST /signers/identity-verification?signer-access-code=…`).
7510
+ *
7511
+ * Send only after the signer explicitly consents. Starts a session when
7512
+ * none exists or replaces an Expired session. Other states return `400`;
7513
+ * resending a notification never replaces a live session. The account is
7514
+ * billed at assignment creation, with no new charge for a restart.
7515
+ *
7516
+ * Request body (`application/json`):
7517
+ * ```jsonc
7518
+ * { "consent": true }
7519
+ * ```
7520
+ * @param signerAccessCode - Access code from the signer's signing link.
7521
+ * @param payload - Explicit consent from the signer.
7522
+ * @param payload.consent - Must be `true`; never default or infer consent.
7523
+ * @returns The newly opened provider session:
7524
+ * ```jsonc
7525
+ * {
7526
+ * "id": "verification_example",
7527
+ * "url": "https://verify.example.com/c/session#t=opaque",
7528
+ * "expires_at": "2026-10-16T12:30:00Z"
7529
+ * }
7530
+ * ```
7531
+ * `expires_at` can be null. Open the URL as-is; it is a bearer credential
7532
+ * and its fragment must survive navigation. Do not log or persist it in
7533
+ * browser storage. No workspace credential is attached to this call.
7534
+ * @throws {ValidationError} If the code is blank or consent is not `true`.
7535
+ * @throws {ApiError} `400` when a non-expired session already exists;
7536
+ * `401` for an invalid/expired code; `500` for a provider/server failure.
7537
+ * @example
7538
+ * ```ts
7539
+ * // Inside the handler for the signer's explicit consent action:
7540
+ * const session = await client.signerDocuments.startIdentityVerification(accessCode, { consent: true });
7541
+ * response.redirect(session.url);
7542
+ * ```
7543
+ */
7544
+ async startIdentityVerification(signerAccessCode, payload) {
7545
+ const code = this.requireId(signerAccessCode, "signer-access-code");
7546
+ assertRecord(payload, "identity verification payload");
7547
+ if (payload.consent !== true) {
7548
+ throw new ValidationError("Explicit biometric-processing consent is required");
7549
+ }
7550
+ return this.call(
7551
+ "Failed to start signer identity verification",
7552
+ () => this.http.post("/signers/identity-verification", { consent: true }, {
7553
+ params: { "signer-access-code": code }
7554
+ })
7555
+ );
7556
+ }
7218
7557
  /**
7219
7558
  * Accept the platform terms of use as the signer
7220
7559
  * (`PUT /signers/accept-terms?signer-access-code=…`).
@@ -7248,10 +7587,10 @@ var SignerDocumentsResource = class extends BaseResource {
7248
7587
  );
7249
7588
  }
7250
7589
  /**
7251
- * Verify the signer's email one-time password
7590
+ * Verify the signer's email or WhatsApp one-time password
7252
7591
  * (`POST /verify?signer-access-code=…`).
7253
7592
  *
7254
- * Confirms the 6-digit OTP the platform emailed the signer. The access code
7593
+ * Confirms the 6-digit OTP sent through the selected channel. The access code
7255
7594
  * authenticates via the `signer-access-code` **query param**; the request
7256
7595
  * **body carries only `verification-code`** (putting the access code in the
7257
7596
  * body leaves the request unauthenticated → `401`).
@@ -7265,6 +7604,8 @@ var SignerDocumentsResource = class extends BaseResource {
7265
7604
  *
7266
7605
  * @param payload - `signerAccessCode` (the signing-link code) and
7267
7606
  * `verificationCode` (the OTP the signer received).
7607
+ * @param payload.signerAccessCode - Signing-link code sent only in the query.
7608
+ * @param payload.verificationCode - Email or WhatsApp OTP sent as `verification-code`.
7268
7609
  * @returns Resolves when the API acknowledges the operation. The response
7269
7610
  * envelope has no `data` field and is intentionally discarded.
7270
7611
  * @throws {ValidationError} If `signerAccessCode` or `verificationCode` is
@@ -7425,7 +7766,7 @@ var SignerDocumentsResource = class extends BaseResource {
7425
7766
  * "expires_at": null,
7426
7767
  * "signers": [
7427
7768
  * { "id": "19e6b92e7895332ed9708535d8c", "step": 1, "email": "signer@example.com",
7428
- * "full_name": "Example Signer", "notified": true, "completed": false }
7769
+ * "full_name": "Example Signer", "notified": true }
7429
7770
  * ],
7430
7771
  * "items": [
7431
7772
  * { "id": "item-1", "page": { "id": "page-1", "number": 1, "height": 1651, "width": 1275,
@@ -8038,7 +8379,8 @@ var WebhookVerifier = class {
8038
8379
  * @param toleranceSeconds - Accepted clock distance. Defaults to `300`.
8039
8380
  * @returns `true` only when a signature entry matches (constant-time) and
8040
8381
  * the timestamp is fresh; `false` when verification is disabled, a header
8041
- * is missing, or anything does not match.
8382
+ * is missing, the tolerance is not finite and non-negative, or anything
8383
+ * does not match.
8042
8384
  *
8043
8385
  * @example
8044
8386
  * ```ts
@@ -8054,7 +8396,7 @@ var WebhookVerifier = class {
8054
8396
  */
8055
8397
  verifySignature(payload, headers, toleranceSeconds = DEFAULT_TOLERANCE_SECONDS) {
8056
8398
  const key = decodeSecret(this.webhookSecret);
8057
- if (!key || typeof payload !== "string" && !Buffer.isBuffer(payload) || !headers) {
8399
+ if (!key || typeof payload !== "string" && !Buffer.isBuffer(payload) || !headers || !Number.isFinite(toleranceSeconds) || toleranceSeconds < 0) {
8058
8400
  return false;
8059
8401
  }
8060
8402
  const id = header(headers, "webhook-id");
@@ -8741,6 +9083,7 @@ function hasIdempotencyKey(headers) {
8741
9083
  AssinafyError,
8742
9084
  AuthenticationResource,
8743
9085
  DEFAULT_WEBHOOK_EVENTS,
9086
+ DIGITAL_CERTIFICATE_REQUIRES_VIRTUAL_METHOD,
8744
9087
  DocumentResource,
8745
9088
  FieldsResource,
8746
9089
  MAX_LIST_PAGE_SIZE,