@assinafy/cli 2.0.3 → 2.1.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/api.js CHANGED
@@ -13,18 +13,35 @@ var AssinafyError = class extends Error {
13
13
  var ApiError = class _ApiError extends AssinafyError {
14
14
  statusCode;
15
15
  responseData;
16
+ /** Bearer challenge, including insufficient_scope and resource_metadata when provided. */
17
+ wwwAuthenticate;
18
+ /** Server retry delay (seconds or HTTP date), when provided. */
19
+ retryAfter;
16
20
  constructor(message, statusCode, responseData = null, options) {
17
21
  super(message, { statusCode, responseData }, options);
18
22
  this.name = "ApiError";
19
23
  this.statusCode = statusCode;
20
24
  this.responseData = responseData;
25
+ this.wwwAuthenticate = options?.wwwAuthenticate;
26
+ this.retryAfter = options?.retryAfter;
21
27
  }
22
- static fromResponse(statusCode, responseData) {
28
+ static fromResponse(statusCode, responseData, headers = {}) {
29
+ if (Buffer.isBuffer(responseData) || responseData instanceof ArrayBuffer) {
30
+ const text = (Buffer.isBuffer(responseData) ? responseData : Buffer.from(responseData)).toString("utf8");
31
+ try {
32
+ responseData = JSON.parse(text);
33
+ } catch {
34
+ responseData = text;
35
+ }
36
+ }
23
37
  const data = responseData ?? {};
24
38
  const rawMessage = data.message;
25
39
  const rawError = data.error;
26
40
  const message = typeof rawMessage === "string" && rawMessage.length > 0 ? rawMessage : typeof rawError === "string" ? rawError : "API request failed";
27
- return new _ApiError(message, statusCode, responseData);
41
+ return new _ApiError(message, statusCode, responseData, {
42
+ wwwAuthenticate: typeof headers["www-authenticate"] === "string" ? headers["www-authenticate"] : void 0,
43
+ retryAfter: typeof headers["retry-after"] === "string" ? headers["retry-after"] : void 0
44
+ });
28
45
  }
29
46
  };
30
47
  var ValidationError = class extends AssinafyError {
@@ -41,6 +58,19 @@ var NetworkError = class extends AssinafyError {
41
58
  this.name = "NetworkError";
42
59
  }
43
60
  };
61
+ var PartialWorkflowError = class extends AssinafyError {
62
+ /** The document that was uploaded before the failure, if any. */
63
+ documentId;
64
+ /** IDs of every signer created (or reused) before the failure. */
65
+ signerIds;
66
+ constructor(message, created, options) {
67
+ const signerIds = created.signerIds ?? [];
68
+ super(message, { documentId: created.documentId, signerIds }, options);
69
+ this.name = "PartialWorkflowError";
70
+ this.documentId = created.documentId;
71
+ this.signerIds = signerIds;
72
+ }
73
+ };
44
74
 
45
75
  // src/api/utils.ts
46
76
  import axios from "axios";
@@ -75,7 +105,7 @@ function toSdkError(error, fallbackMessage) {
75
105
  if (axios.isAxiosError(error)) {
76
106
  const status = error.response?.status;
77
107
  if (status) {
78
- return ApiError.fromResponse(status, error.response?.data ?? null);
108
+ return ApiError.fromResponse(status, error.response?.data ?? null, error.response?.headers);
79
109
  }
80
110
  return new NetworkError(`${fallbackMessage}: ${error.message}`);
81
111
  }
@@ -339,7 +369,7 @@ function buildAssignmentPayload(payload, options = {}) {
339
369
  }
340
370
  const normalisedSigners = signers.map((ref) => normaliseSignerRef(ref, options));
341
371
  if (!options.skipDigitalCertificateStepValidation) {
342
- validateDigitalCertificateSteps(normalisedSigners);
372
+ validateSigningSteps(normalisedSigners);
343
373
  }
344
374
  return cleanParams({
345
375
  method: payload.method ?? "virtual",
@@ -1106,6 +1136,174 @@ function validationConfig(signerAccessCode) {
1106
1136
  return signerAccessCode ? signerAccessConfig(signerAccessCode) : void 0;
1107
1137
  }
1108
1138
 
1139
+ // src/api/resources/oauth.ts
1140
+ import { createHash, randomBytes, timingSafeEqual } from "crypto";
1141
+ var OAuthResource = class extends BaseResource {
1142
+ /** `GET /.well-known/oauth-protected-resource` at the API origin, outside `/v1`. */
1143
+ async metadata() {
1144
+ return this.call(
1145
+ "Failed to discover OAuth resource",
1146
+ () => this.http.get(
1147
+ "/.well-known/oauth-protected-resource",
1148
+ publicRequestConfig({
1149
+ baseURL: new URL(this.http.defaults.baseURL).origin
1150
+ })
1151
+ )
1152
+ );
1153
+ }
1154
+ /** Read RFC 8414 metadata from an HTTPS issuer and verify its issuer identity. */
1155
+ async discovery(issuer) {
1156
+ const url = httpsUrl(issuer, "issuer");
1157
+ if (url.search || url.pathname !== "/") {
1158
+ throw new ValidationError("issuer must be an HTTPS origin");
1159
+ }
1160
+ const metadata = await this.call(
1161
+ "Failed to discover OAuth authorization server",
1162
+ () => this.http.get(
1163
+ `${url.origin}/.well-known/oauth-authorization-server`,
1164
+ publicRequestConfig()
1165
+ )
1166
+ );
1167
+ if (metadata.issuer !== issuer) throw new ValidationError("OAuth issuer mismatch");
1168
+ httpsUrl(metadata.authorization_endpoint, "authorization_endpoint");
1169
+ return metadata;
1170
+ }
1171
+ /** Discover endpoints and create a fresh authorization URL, PKCE verifier, and state. */
1172
+ async authorize(options) {
1173
+ required(options.clientId, "clientId");
1174
+ httpsUrl(options.redirectUri, "redirectUri");
1175
+ if (!Array.isArray(options.scopes) || options.scopes.length === 0 || options.scopes.some(
1176
+ (scope) => typeof scope !== "string" || !/^[\x21\x23-\x5B\x5D-\x7E]+$/.test(scope)
1177
+ )) {
1178
+ throw new ValidationError("scopes must contain non-empty OAuth scope names");
1179
+ }
1180
+ const resource = await this.metadata();
1181
+ const issuer = resource.authorization_servers?.[0];
1182
+ if (!issuer) throw new ValidationError("OAuth metadata has no authorization server");
1183
+ httpsUrl(resource.resource, "resource");
1184
+ const server = await this.discovery(issuer);
1185
+ const codeVerifier = randomBytes(32).toString("base64url");
1186
+ const state = randomBytes(32).toString("base64url");
1187
+ const nonce = options.scopes.includes("openid") ? randomBytes(32).toString("base64url") : void 0;
1188
+ const url = new URL(server.authorization_endpoint);
1189
+ const params = {
1190
+ response_type: "code",
1191
+ client_id: options.clientId,
1192
+ redirect_uri: options.redirectUri,
1193
+ scope: options.scopes.join(" "),
1194
+ state,
1195
+ code_challenge: createHash("sha256").update(codeVerifier).digest("base64url"),
1196
+ code_challenge_method: "S256",
1197
+ resource: resource.resource
1198
+ };
1199
+ for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
1200
+ if (nonce) url.searchParams.set("nonce", nonce);
1201
+ return {
1202
+ authorization_url: url.toString(),
1203
+ code_verifier: codeVerifier,
1204
+ state,
1205
+ issuer,
1206
+ client_id: options.clientId,
1207
+ redirect_uri: options.redirectUri,
1208
+ resource: resource.resource,
1209
+ ...nonce ? { nonce } : {}
1210
+ };
1211
+ }
1212
+ /** Validate callback URI, state, and issuer before exchanging its one-time code. */
1213
+ async exchangeCode(callbackUrl, request, clientSecret) {
1214
+ const callback = httpsUrl(callbackUrl, "callbackUrl");
1215
+ const redirect = httpsUrl(request.redirect_uri, "redirect_uri");
1216
+ if (callback.origin !== redirect.origin || callback.pathname !== redirect.pathname || [...new Set(redirect.searchParams.keys())].some((key) => {
1217
+ const expected2 = redirect.searchParams.getAll(key);
1218
+ const actual2 = callback.searchParams.getAll(key);
1219
+ return expected2.length !== actual2.length || expected2.some((value, i) => value !== actual2[i]);
1220
+ })) {
1221
+ throw new ValidationError("OAuth callback does not match the registered redirect URI");
1222
+ }
1223
+ for (const key of ["state", "iss", "code", "error"]) {
1224
+ if (callback.searchParams.getAll(key).length > 1) {
1225
+ throw new ValidationError(`Duplicate OAuth callback parameter: ${key}`);
1226
+ }
1227
+ }
1228
+ const actual = Buffer.from(callback.searchParams.get("state") ?? "");
1229
+ const expected = Buffer.from(required(request.state, "state"));
1230
+ if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
1231
+ throw new ValidationError("OAuth state mismatch");
1232
+ }
1233
+ if (callback.searchParams.get("iss") !== request.issuer) {
1234
+ throw new ValidationError("OAuth issuer mismatch");
1235
+ }
1236
+ if (callback.searchParams.has("error")) {
1237
+ throw new ValidationError("OAuth authorization was declined or failed");
1238
+ }
1239
+ return this.token({
1240
+ grant_type: "authorization_code",
1241
+ code: required(callback.searchParams.get("code"), "code"),
1242
+ client_id: request.client_id,
1243
+ client_secret: clientSecret,
1244
+ redirect_uri: request.redirect_uri,
1245
+ code_verifier: request.code_verifier,
1246
+ resource: request.resource
1247
+ });
1248
+ }
1249
+ /** `POST /oauth/token` — code exchange or refresh; returns the flat OAuth JSON body. */
1250
+ async token(payload) {
1251
+ required(payload.client_id, "client_id");
1252
+ if (payload.client_secret !== void 0) required(payload.client_secret, "client_secret");
1253
+ if (payload.resource !== void 0) httpsUrl(payload.resource, "resource");
1254
+ if (payload.grant_type === "authorization_code") {
1255
+ required(payload.code, "code");
1256
+ httpsUrl(payload.redirect_uri, "redirect_uri");
1257
+ if (typeof payload.code_verifier !== "string" || !/^[A-Za-z0-9._~-]{43,128}$/.test(payload.code_verifier)) {
1258
+ throw new ValidationError(
1259
+ "code_verifier must contain 43\u2013128 RFC 7636 unreserved characters"
1260
+ );
1261
+ }
1262
+ } else if (payload.grant_type === "refresh_token") {
1263
+ required(payload.refresh_token, "refresh_token");
1264
+ } else {
1265
+ throw new ValidationError("grant_type must be authorization_code or refresh_token");
1266
+ }
1267
+ return this.call(
1268
+ "OAuth token request failed",
1269
+ () => this.http.post("/oauth/token", payload, publicRequestConfig())
1270
+ );
1271
+ }
1272
+ /** `POST /oauth/revoke` — revoke an access/refresh token; success has no required body. */
1273
+ async revoke(payload) {
1274
+ required(payload.client_id, "client_id");
1275
+ required(payload.token, "token");
1276
+ if (payload.client_secret !== void 0) required(payload.client_secret, "client_secret");
1277
+ if (payload.token_type_hint !== void 0 && !["access_token", "refresh_token"].includes(payload.token_type_hint)) {
1278
+ throw new ValidationError("token_type_hint must be access_token or refresh_token");
1279
+ }
1280
+ await this.call(
1281
+ "OAuth revocation failed",
1282
+ () => this.http.post("/oauth/revoke", payload, publicRequestConfig())
1283
+ );
1284
+ }
1285
+ /** `GET /oauth/userinfo` — flat OIDC claims; requires a bearer token with `openid`. */
1286
+ async userinfo() {
1287
+ return this.call("Failed to fetch OAuth userinfo", () => this.http.get("/oauth/userinfo"));
1288
+ }
1289
+ };
1290
+ function required(value, name) {
1291
+ if (typeof value !== "string" || !value.trim()) throw new ValidationError(`${name} is required`);
1292
+ return value;
1293
+ }
1294
+ function httpsUrl(value, name) {
1295
+ let url;
1296
+ try {
1297
+ url = new URL(value);
1298
+ } catch {
1299
+ throw new ValidationError(`${name} must be an absolute HTTPS URL`);
1300
+ }
1301
+ if (url.protocol !== "https:" || url.username || url.password || url.hash) {
1302
+ throw new ValidationError(`${name} must use HTTPS without credentials or a fragment`);
1303
+ }
1304
+ return url;
1305
+ }
1306
+
1109
1307
  // src/api/resources/signer-documents.ts
1110
1308
  var SignerDocumentsResource = class extends BaseResource {
1111
1309
  /** `GET /signers/{signer_id}/document?signer-access-code=…` */
@@ -1184,7 +1382,7 @@ var SignerDocumentsResource = class extends BaseResource {
1184
1382
  if (!Array.isArray(documentIds) || documentIds.length === 0) {
1185
1383
  throw new ValidationError("documentIds must be a non-empty array");
1186
1384
  }
1187
- if (!declineReason) throw new ValidationError("declineReason is required");
1385
+ validateDeclineReason(declineReason);
1188
1386
  const code = this.requireId(signerAccessCode, "signer-access-code");
1189
1387
  return this.call(
1190
1388
  "Failed to decline multiple documents",
@@ -1314,7 +1512,7 @@ var SignerDocumentsResource = class extends BaseResource {
1314
1512
  const did = this.requireId(documentId, "Document ID");
1315
1513
  const aid = this.requireId(assignmentId, "Assignment ID");
1316
1514
  const code = this.requireId(signerAccessCode, "signer-access-code");
1317
- if (!declineReason) throw new ValidationError("declineReason is required");
1515
+ validateDeclineReason(declineReason);
1318
1516
  return this.call(
1319
1517
  "Failed to decline assignment",
1320
1518
  () => this.http.put(
@@ -1325,6 +1523,14 @@ var SignerDocumentsResource = class extends BaseResource {
1325
1523
  );
1326
1524
  }
1327
1525
  };
1526
+ function validateDeclineReason(value) {
1527
+ if (typeof value !== "string" || !value.trim()) {
1528
+ throw new ValidationError("declineReason is required");
1529
+ }
1530
+ if ([...value].length > 2e3) {
1531
+ throw new ValidationError("declineReason must contain at most 2000 characters");
1532
+ }
1533
+ }
1328
1534
 
1329
1535
  // src/api/resources/signers.ts
1330
1536
  function validateCreateSignerPayload(payload) {
@@ -1414,9 +1620,13 @@ var SignerResource = class extends BaseResource {
1414
1620
  async findByEmail(email, accountId) {
1415
1621
  requireEmail(email);
1416
1622
  try {
1417
- const { data } = await this.list({ search: email, per_page: 100 }, accountId);
1418
1623
  const lower = email.toLowerCase();
1419
- return data.find((s) => (s.email ?? "").toLowerCase() === lower) ?? null;
1624
+ for (let page = 1; ; page++) {
1625
+ const { data, meta } = await this.list({ search: email, per_page: 100, page }, accountId);
1626
+ const match = data.find((s) => (s.email ?? "").toLowerCase() === lower);
1627
+ if (match) return match;
1628
+ if (!data.length || !meta?.last_page || page >= meta.last_page) return null;
1629
+ }
1420
1630
  } catch (err) {
1421
1631
  if (err instanceof ApiError && err.statusCode === 404) {
1422
1632
  return null;
@@ -1786,7 +1996,7 @@ function validateNotificationSender(value) {
1786
1996
  }
1787
1997
 
1788
1998
  // src/api/support/webhook-verifier.ts
1789
- import { createHmac, timingSafeEqual } from "crypto";
1999
+ import { createHmac, timingSafeEqual as timingSafeEqual2 } from "crypto";
1790
2000
  var WebhookVerifier = class {
1791
2001
  constructor(webhookSecret, options = {}) {
1792
2002
  this.webhookSecret = webhookSecret;
@@ -1806,7 +2016,7 @@ var WebhookVerifier = class {
1806
2016
  const a = Buffer.from(expected, "utf8");
1807
2017
  const b = Buffer.from(provided, "utf8");
1808
2018
  if (a.length !== b.length) return false;
1809
- return timingSafeEqual(a, b);
2019
+ return timingSafeEqual2(a, b);
1810
2020
  } catch {
1811
2021
  return false;
1812
2022
  }
@@ -1848,6 +2058,9 @@ var WebhookVerifier = class {
1848
2058
 
1849
2059
  // src/api/client.ts
1850
2060
  var DEFAULT_BASE_URL = "https://api.assinafy.com.br/v1";
2061
+ function isLoopbackHost(hostname) {
2062
+ return hostname === "localhost" || hostname === "[::1]" || /^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/.test(hostname);
2063
+ }
1851
2064
  var AssinafyClient = class _AssinafyClient {
1852
2065
  axiosInstance;
1853
2066
  defaultAccountId;
@@ -1861,6 +2074,7 @@ var AssinafyClient = class _AssinafyClient {
1861
2074
  templates;
1862
2075
  tags;
1863
2076
  auth;
2077
+ oauth;
1864
2078
  fields;
1865
2079
  users;
1866
2080
  signerDocuments;
@@ -1868,7 +2082,7 @@ var AssinafyClient = class _AssinafyClient {
1868
2082
  constructor(options) {
1869
2083
  if (!options.apiKey && !options.token && !options.allowUnauthenticated) {
1870
2084
  throw new ValidationError(
1871
- "An API key (options.apiKey) or legacy access token (options.token) is required."
2085
+ "An API key (options.apiKey) or access token (options.token) is required."
1872
2086
  );
1873
2087
  }
1874
2088
  if (options.timeout !== void 0 && (!Number.isFinite(options.timeout) || options.timeout <= 0)) {
@@ -1884,13 +2098,17 @@ var AssinafyClient = class _AssinafyClient {
1884
2098
  } catch {
1885
2099
  throw new ValidationError("baseUrl must be an absolute HTTP(S) URL");
1886
2100
  }
1887
- if (!["https:", "http:"].includes(parsedBaseUrl.protocol)) {
1888
- throw new ValidationError("baseUrl must use HTTPS");
1889
- }
1890
- if (parsedBaseUrl.protocol !== "https:" && !options.allowInsecureHttp) {
1891
- throw new ValidationError(
1892
- "baseUrl must use HTTPS; set allowInsecureHttp only for isolated local development"
1893
- );
2101
+ if (parsedBaseUrl.protocol !== "https:") {
2102
+ if (parsedBaseUrl.protocol !== "http:" || !options.allowInsecureHttp) {
2103
+ throw new ValidationError(
2104
+ "baseUrl must use HTTPS; set allowInsecureHttp only for a loopback development server"
2105
+ );
2106
+ }
2107
+ if (!isLoopbackHost(parsedBaseUrl.hostname)) {
2108
+ throw new ValidationError(
2109
+ "allowInsecureHttp only permits a loopback baseUrl (localhost, 127.0.0.0/8, or ::1)"
2110
+ );
2111
+ }
1894
2112
  }
1895
2113
  if (parsedBaseUrl.username || parsedBaseUrl.password) {
1896
2114
  throw new ValidationError("baseUrl must not contain embedded credentials");
@@ -1926,6 +2144,7 @@ var AssinafyClient = class _AssinafyClient {
1926
2144
  this.templates = new TemplateResource(this.axiosInstance, this.defaultAccountId, this.logger);
1927
2145
  this.tags = new TagResource(this.axiosInstance, this.defaultAccountId, this.logger);
1928
2146
  this.auth = new AuthenticationResource(this.axiosInstance, void 0, this.logger);
2147
+ this.oauth = new OAuthResource(this.axiosInstance, void 0, this.logger);
1929
2148
  this.fields = new FieldsResource(this.axiosInstance, this.defaultAccountId, this.logger);
1930
2149
  this.users = new UsersResource(this.axiosInstance, void 0, this.logger);
1931
2150
  this.signerDocuments = new SignerDocumentsResource(
@@ -1961,13 +2180,22 @@ var AssinafyClient = class _AssinafyClient {
1961
2180
  /**
1962
2181
  * High-level helper that uploads a PDF, ensures it's processed, creates any
1963
2182
  * missing signers, and kicks off a virtual signature assignment.
2183
+ *
2184
+ * Once the upload succeeds the workflow owns real workspace resources, so any
2185
+ * later failure is rethrown as a {@link PartialWorkflowError} carrying the
2186
+ * document and signer IDs that already exist. Catch it to resume or clean up;
2187
+ * nothing is deleted automatically.
1964
2188
  */
1965
2189
  async uploadAndRequestSignatures(options) {
1966
- if (!options.signers || options.signers.length === 0) {
2190
+ if (!Array.isArray(options.signers) || options.signers.length === 0) {
1967
2191
  throw new ValidationError("At least one signer is required");
1968
2192
  }
1969
2193
  if (options.expiresAt !== void 0) requireIso8601(options.expiresAt, "expiresAt");
1970
2194
  const preparedSigners = options.signers.map((signer) => {
2195
+ if (!signer || typeof signer !== "object") {
2196
+ throw new ValidationError("Each signer must be an object");
2197
+ }
2198
+ validateSignerOptions(signer);
1971
2199
  const payload = { full_name: signer.name };
1972
2200
  if (signer.email !== void 0) payload.email = signer.email;
1973
2201
  const phone = signer.whatsapp_phone_number ?? signer.phone;
@@ -1977,6 +2205,7 @@ var AssinafyClient = class _AssinafyClient {
1977
2205
  validateCreateSignerPayload(payload);
1978
2206
  return { signer, payload, phone };
1979
2207
  });
2208
+ validateSigningSteps(options.signers);
1980
2209
  this.logger.info("Starting upload + signature workflow", {
1981
2210
  signerCount: options.signers.length
1982
2211
  });
@@ -1984,33 +2213,46 @@ var AssinafyClient = class _AssinafyClient {
1984
2213
  if (options.metadata !== void 0) uploadOpts.metadata = options.metadata;
1985
2214
  if (options.accountId !== void 0) uploadOpts.accountId = options.accountId;
1986
2215
  const document = await this.documents.upload(options.source, uploadOpts);
1987
- if (options.waitForReady !== false) {
1988
- await this.documents.waitUntilReady(document.id);
1989
- }
1990
2216
  const signerIds = [];
1991
- const assignmentSigners = [];
1992
- for (const { signer, payload, phone } of preparedSigners) {
1993
- const created = await this.signers.create(payload, options.accountId);
1994
- signerIds.push(created.id);
1995
- const useWhatsapp = phone !== void 0 && signer.email === void 0;
1996
- assignmentSigners.push({
1997
- id: created.id,
1998
- verification_method: signer.verification_method ?? (useWhatsapp ? "Whatsapp" : void 0),
1999
- notification_methods: signer.notification_methods ?? (useWhatsapp ? ["Whatsapp"] : void 0),
2000
- step: signer.step
2217
+ try {
2218
+ if (options.waitForReady !== false) {
2219
+ await this.documents.waitUntilReady(document.id);
2220
+ }
2221
+ const assignmentSigners = [];
2222
+ for (const { signer, payload, phone } of preparedSigners) {
2223
+ const created = await this.signers.create(payload, options.accountId);
2224
+ signerIds.push(created.id);
2225
+ const useWhatsapp = phone !== void 0 && signer.email === void 0;
2226
+ assignmentSigners.push({
2227
+ id: created.id,
2228
+ verification_method: signer.verification_method ?? (useWhatsapp ? "Whatsapp" : void 0),
2229
+ notification_methods: signer.notification_methods ?? (useWhatsapp ? ["Whatsapp"] : void 0),
2230
+ step: signer.step
2231
+ });
2232
+ }
2233
+ const assignmentPayload = {
2234
+ method: "virtual",
2235
+ signers: assignmentSigners
2236
+ };
2237
+ if (options.message !== void 0) assignmentPayload.message = options.message;
2238
+ if (options.expiresAt !== void 0) assignmentPayload.expires_at = options.expiresAt;
2239
+ if (options.copyReceivers !== void 0)
2240
+ assignmentPayload.copy_receivers = options.copyReceivers;
2241
+ const assignment = await this.assignments.create(document.id, assignmentPayload);
2242
+ this.logger.info("Upload + signature workflow completed", { documentId: document.id });
2243
+ return { document, assignment, signer_ids: signerIds };
2244
+ } catch (err) {
2245
+ this.logger.error("Upload + signature workflow failed after creating resources", {
2246
+ documentId: document.id,
2247
+ signerIds
2001
2248
  });
2249
+ const reason = err instanceof Error ? err.message : String(err);
2250
+ throw new PartialWorkflowError(
2251
+ `${reason} (document ${document.id} exists; ${signerIds.length} signer(s) created or reused)`,
2252
+ { documentId: document.id, signerIds },
2253
+ { cause: err }
2254
+ );
2002
2255
  }
2003
- const assignmentPayload = {
2004
- method: "virtual",
2005
- signers: assignmentSigners
2006
- };
2007
- if (options.message !== void 0) assignmentPayload.message = options.message;
2008
- if (options.expiresAt !== void 0) assignmentPayload.expires_at = options.expiresAt;
2009
- if (options.copyReceivers !== void 0)
2010
- assignmentPayload.copy_receivers = options.copyReceivers;
2011
- const assignment = await this.assignments.create(document.id, assignmentPayload);
2012
- this.logger.info("Upload + signature workflow completed", { documentId: document.id });
2013
- return { document, assignment, signer_ids: signerIds };
2014
2256
  }
2015
2257
  /** Expose the underlying axios instance for advanced use cases (interceptors, custom endpoints). */
2016
2258
  getAxiosInstance() {
@@ -2027,6 +2269,8 @@ export {
2027
2269
  FieldsResource,
2028
2270
  NOTIFICATION_PREFERENCE_CODES,
2029
2271
  NetworkError,
2272
+ OAuthResource,
2273
+ PartialWorkflowError,
2030
2274
  SignerDocumentsResource,
2031
2275
  SignerResource,
2032
2276
  TagResource,