@assinafy/cli 2.0.3 → 2.1.2

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,178 @@ 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
+ const error = callback.searchParams.get("error");
1238
+ const oauthError = error.length > 0 && error.length <= 64 && !/[^a-z_]/.test(error) ? error : "unknown_error";
1239
+ throw new ValidationError(`OAuth authorization was declined or failed: ${oauthError}`, {
1240
+ oauthError
1241
+ });
1242
+ }
1243
+ return this.token({
1244
+ grant_type: "authorization_code",
1245
+ code: required(callback.searchParams.get("code"), "code"),
1246
+ client_id: request.client_id,
1247
+ client_secret: clientSecret,
1248
+ redirect_uri: request.redirect_uri,
1249
+ code_verifier: request.code_verifier,
1250
+ resource: request.resource
1251
+ });
1252
+ }
1253
+ /** `POST /oauth/token` — code exchange or refresh; returns the flat OAuth JSON body. */
1254
+ async token(payload) {
1255
+ required(payload.client_id, "client_id");
1256
+ if (payload.client_secret !== void 0) required(payload.client_secret, "client_secret");
1257
+ if (payload.resource !== void 0) httpsUrl(payload.resource, "resource");
1258
+ if (payload.grant_type === "authorization_code") {
1259
+ required(payload.code, "code");
1260
+ httpsUrl(payload.redirect_uri, "redirect_uri");
1261
+ if (typeof payload.code_verifier !== "string" || !/^[A-Za-z0-9._~-]{43,128}$/.test(payload.code_verifier)) {
1262
+ throw new ValidationError(
1263
+ "code_verifier must contain 43\u2013128 RFC 7636 unreserved characters"
1264
+ );
1265
+ }
1266
+ } else if (payload.grant_type === "refresh_token") {
1267
+ required(payload.refresh_token, "refresh_token");
1268
+ } else {
1269
+ throw new ValidationError("grant_type must be authorization_code or refresh_token");
1270
+ }
1271
+ return this.call(
1272
+ "OAuth token request failed",
1273
+ () => this.http.post("/oauth/token", payload, publicRequestConfig())
1274
+ );
1275
+ }
1276
+ /** `POST /oauth/revoke` — revoke an access/refresh token; success has no required body. */
1277
+ async revoke(payload) {
1278
+ required(payload.client_id, "client_id");
1279
+ required(payload.token, "token");
1280
+ if (payload.client_secret !== void 0) required(payload.client_secret, "client_secret");
1281
+ if (payload.token_type_hint !== void 0 && !["access_token", "refresh_token"].includes(payload.token_type_hint)) {
1282
+ throw new ValidationError("token_type_hint must be access_token or refresh_token");
1283
+ }
1284
+ await this.call(
1285
+ "OAuth revocation failed",
1286
+ () => this.http.post("/oauth/revoke", payload, publicRequestConfig())
1287
+ );
1288
+ }
1289
+ /** `GET /oauth/userinfo` — flat OIDC claims; requires a bearer token with `openid`. */
1290
+ async userinfo() {
1291
+ return this.call("Failed to fetch OAuth userinfo", () => this.http.get("/oauth/userinfo"));
1292
+ }
1293
+ };
1294
+ function required(value, name) {
1295
+ if (typeof value !== "string" || !value.trim()) throw new ValidationError(`${name} is required`);
1296
+ return value;
1297
+ }
1298
+ function httpsUrl(value, name) {
1299
+ let url;
1300
+ try {
1301
+ url = new URL(value);
1302
+ } catch {
1303
+ throw new ValidationError(`${name} must be an absolute HTTPS URL`);
1304
+ }
1305
+ if (url.protocol !== "https:" || url.username || url.password || url.hash) {
1306
+ throw new ValidationError(`${name} must use HTTPS without credentials or a fragment`);
1307
+ }
1308
+ return url;
1309
+ }
1310
+
1109
1311
  // src/api/resources/signer-documents.ts
1110
1312
  var SignerDocumentsResource = class extends BaseResource {
1111
1313
  /** `GET /signers/{signer_id}/document?signer-access-code=…` */
@@ -1184,7 +1386,7 @@ var SignerDocumentsResource = class extends BaseResource {
1184
1386
  if (!Array.isArray(documentIds) || documentIds.length === 0) {
1185
1387
  throw new ValidationError("documentIds must be a non-empty array");
1186
1388
  }
1187
- if (!declineReason) throw new ValidationError("declineReason is required");
1389
+ validateDeclineReason(declineReason);
1188
1390
  const code = this.requireId(signerAccessCode, "signer-access-code");
1189
1391
  return this.call(
1190
1392
  "Failed to decline multiple documents",
@@ -1314,7 +1516,7 @@ var SignerDocumentsResource = class extends BaseResource {
1314
1516
  const did = this.requireId(documentId, "Document ID");
1315
1517
  const aid = this.requireId(assignmentId, "Assignment ID");
1316
1518
  const code = this.requireId(signerAccessCode, "signer-access-code");
1317
- if (!declineReason) throw new ValidationError("declineReason is required");
1519
+ validateDeclineReason(declineReason);
1318
1520
  return this.call(
1319
1521
  "Failed to decline assignment",
1320
1522
  () => this.http.put(
@@ -1325,6 +1527,14 @@ var SignerDocumentsResource = class extends BaseResource {
1325
1527
  );
1326
1528
  }
1327
1529
  };
1530
+ function validateDeclineReason(value) {
1531
+ if (typeof value !== "string" || !value.trim()) {
1532
+ throw new ValidationError("declineReason is required");
1533
+ }
1534
+ if ([...value].length > 2e3) {
1535
+ throw new ValidationError("declineReason must contain at most 2000 characters");
1536
+ }
1537
+ }
1328
1538
 
1329
1539
  // src/api/resources/signers.ts
1330
1540
  function validateCreateSignerPayload(payload) {
@@ -1414,9 +1624,13 @@ var SignerResource = class extends BaseResource {
1414
1624
  async findByEmail(email, accountId) {
1415
1625
  requireEmail(email);
1416
1626
  try {
1417
- const { data } = await this.list({ search: email, per_page: 100 }, accountId);
1418
1627
  const lower = email.toLowerCase();
1419
- return data.find((s) => (s.email ?? "").toLowerCase() === lower) ?? null;
1628
+ for (let page = 1; ; page++) {
1629
+ const { data, meta } = await this.list({ search: email, per_page: 100, page }, accountId);
1630
+ const match = data.find((s) => (s.email ?? "").toLowerCase() === lower);
1631
+ if (match) return match;
1632
+ if (!data.length || !meta?.last_page || page >= meta.last_page) return null;
1633
+ }
1420
1634
  } catch (err) {
1421
1635
  if (err instanceof ApiError && err.statusCode === 404) {
1422
1636
  return null;
@@ -1786,7 +2000,7 @@ function validateNotificationSender(value) {
1786
2000
  }
1787
2001
 
1788
2002
  // src/api/support/webhook-verifier.ts
1789
- import { createHmac, timingSafeEqual } from "crypto";
2003
+ import { createHmac, timingSafeEqual as timingSafeEqual2 } from "crypto";
1790
2004
  var WebhookVerifier = class {
1791
2005
  constructor(webhookSecret, options = {}) {
1792
2006
  this.webhookSecret = webhookSecret;
@@ -1806,7 +2020,7 @@ var WebhookVerifier = class {
1806
2020
  const a = Buffer.from(expected, "utf8");
1807
2021
  const b = Buffer.from(provided, "utf8");
1808
2022
  if (a.length !== b.length) return false;
1809
- return timingSafeEqual(a, b);
2023
+ return timingSafeEqual2(a, b);
1810
2024
  } catch {
1811
2025
  return false;
1812
2026
  }
@@ -1848,6 +2062,9 @@ var WebhookVerifier = class {
1848
2062
 
1849
2063
  // src/api/client.ts
1850
2064
  var DEFAULT_BASE_URL = "https://api.assinafy.com.br/v1";
2065
+ function isLoopbackHost(hostname) {
2066
+ return hostname === "localhost" || hostname === "[::1]" || /^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/.test(hostname);
2067
+ }
1851
2068
  var AssinafyClient = class _AssinafyClient {
1852
2069
  axiosInstance;
1853
2070
  defaultAccountId;
@@ -1861,6 +2078,7 @@ var AssinafyClient = class _AssinafyClient {
1861
2078
  templates;
1862
2079
  tags;
1863
2080
  auth;
2081
+ oauth;
1864
2082
  fields;
1865
2083
  users;
1866
2084
  signerDocuments;
@@ -1868,7 +2086,7 @@ var AssinafyClient = class _AssinafyClient {
1868
2086
  constructor(options) {
1869
2087
  if (!options.apiKey && !options.token && !options.allowUnauthenticated) {
1870
2088
  throw new ValidationError(
1871
- "An API key (options.apiKey) or legacy access token (options.token) is required."
2089
+ "An API key (options.apiKey) or access token (options.token) is required."
1872
2090
  );
1873
2091
  }
1874
2092
  if (options.timeout !== void 0 && (!Number.isFinite(options.timeout) || options.timeout <= 0)) {
@@ -1884,13 +2102,17 @@ var AssinafyClient = class _AssinafyClient {
1884
2102
  } catch {
1885
2103
  throw new ValidationError("baseUrl must be an absolute HTTP(S) URL");
1886
2104
  }
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
- );
2105
+ if (parsedBaseUrl.protocol !== "https:") {
2106
+ if (parsedBaseUrl.protocol !== "http:" || !options.allowInsecureHttp) {
2107
+ throw new ValidationError(
2108
+ "baseUrl must use HTTPS; set allowInsecureHttp only for a loopback development server"
2109
+ );
2110
+ }
2111
+ if (!isLoopbackHost(parsedBaseUrl.hostname)) {
2112
+ throw new ValidationError(
2113
+ "allowInsecureHttp only permits a loopback baseUrl (localhost, 127.0.0.0/8, or ::1)"
2114
+ );
2115
+ }
1894
2116
  }
1895
2117
  if (parsedBaseUrl.username || parsedBaseUrl.password) {
1896
2118
  throw new ValidationError("baseUrl must not contain embedded credentials");
@@ -1926,6 +2148,7 @@ var AssinafyClient = class _AssinafyClient {
1926
2148
  this.templates = new TemplateResource(this.axiosInstance, this.defaultAccountId, this.logger);
1927
2149
  this.tags = new TagResource(this.axiosInstance, this.defaultAccountId, this.logger);
1928
2150
  this.auth = new AuthenticationResource(this.axiosInstance, void 0, this.logger);
2151
+ this.oauth = new OAuthResource(this.axiosInstance, void 0, this.logger);
1929
2152
  this.fields = new FieldsResource(this.axiosInstance, this.defaultAccountId, this.logger);
1930
2153
  this.users = new UsersResource(this.axiosInstance, void 0, this.logger);
1931
2154
  this.signerDocuments = new SignerDocumentsResource(
@@ -1961,13 +2184,22 @@ var AssinafyClient = class _AssinafyClient {
1961
2184
  /**
1962
2185
  * High-level helper that uploads a PDF, ensures it's processed, creates any
1963
2186
  * missing signers, and kicks off a virtual signature assignment.
2187
+ *
2188
+ * Once the upload succeeds the workflow owns real workspace resources, so any
2189
+ * later failure is rethrown as a {@link PartialWorkflowError} carrying the
2190
+ * document and signer IDs that already exist. Catch it to resume or clean up;
2191
+ * nothing is deleted automatically.
1964
2192
  */
1965
2193
  async uploadAndRequestSignatures(options) {
1966
- if (!options.signers || options.signers.length === 0) {
2194
+ if (!Array.isArray(options.signers) || options.signers.length === 0) {
1967
2195
  throw new ValidationError("At least one signer is required");
1968
2196
  }
1969
2197
  if (options.expiresAt !== void 0) requireIso8601(options.expiresAt, "expiresAt");
1970
2198
  const preparedSigners = options.signers.map((signer) => {
2199
+ if (!signer || typeof signer !== "object") {
2200
+ throw new ValidationError("Each signer must be an object");
2201
+ }
2202
+ validateSignerOptions(signer);
1971
2203
  const payload = { full_name: signer.name };
1972
2204
  if (signer.email !== void 0) payload.email = signer.email;
1973
2205
  const phone = signer.whatsapp_phone_number ?? signer.phone;
@@ -1977,6 +2209,7 @@ var AssinafyClient = class _AssinafyClient {
1977
2209
  validateCreateSignerPayload(payload);
1978
2210
  return { signer, payload, phone };
1979
2211
  });
2212
+ validateSigningSteps(options.signers);
1980
2213
  this.logger.info("Starting upload + signature workflow", {
1981
2214
  signerCount: options.signers.length
1982
2215
  });
@@ -1984,33 +2217,46 @@ var AssinafyClient = class _AssinafyClient {
1984
2217
  if (options.metadata !== void 0) uploadOpts.metadata = options.metadata;
1985
2218
  if (options.accountId !== void 0) uploadOpts.accountId = options.accountId;
1986
2219
  const document = await this.documents.upload(options.source, uploadOpts);
1987
- if (options.waitForReady !== false) {
1988
- await this.documents.waitUntilReady(document.id);
1989
- }
1990
2220
  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
2221
+ try {
2222
+ if (options.waitForReady !== false) {
2223
+ await this.documents.waitUntilReady(document.id);
2224
+ }
2225
+ const assignmentSigners = [];
2226
+ for (const { signer, payload, phone } of preparedSigners) {
2227
+ const created = await this.signers.create(payload, options.accountId);
2228
+ signerIds.push(created.id);
2229
+ const useWhatsapp = phone !== void 0 && signer.email === void 0;
2230
+ assignmentSigners.push({
2231
+ id: created.id,
2232
+ verification_method: signer.verification_method ?? (useWhatsapp ? "Whatsapp" : void 0),
2233
+ notification_methods: signer.notification_methods ?? (useWhatsapp ? ["Whatsapp"] : void 0),
2234
+ step: signer.step
2235
+ });
2236
+ }
2237
+ const assignmentPayload = {
2238
+ method: "virtual",
2239
+ signers: assignmentSigners
2240
+ };
2241
+ if (options.message !== void 0) assignmentPayload.message = options.message;
2242
+ if (options.expiresAt !== void 0) assignmentPayload.expires_at = options.expiresAt;
2243
+ if (options.copyReceivers !== void 0)
2244
+ assignmentPayload.copy_receivers = options.copyReceivers;
2245
+ const assignment = await this.assignments.create(document.id, assignmentPayload);
2246
+ this.logger.info("Upload + signature workflow completed", { documentId: document.id });
2247
+ return { document, assignment, signer_ids: signerIds };
2248
+ } catch (err) {
2249
+ this.logger.error("Upload + signature workflow failed after creating resources", {
2250
+ documentId: document.id,
2251
+ signerIds
2001
2252
  });
2253
+ const reason = err instanceof Error ? err.message : String(err);
2254
+ throw new PartialWorkflowError(
2255
+ `${reason} (document ${document.id} exists; ${signerIds.length} signer(s) created or reused)`,
2256
+ { documentId: document.id, signerIds },
2257
+ { cause: err }
2258
+ );
2002
2259
  }
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
2260
  }
2015
2261
  /** Expose the underlying axios instance for advanced use cases (interceptors, custom endpoints). */
2016
2262
  getAxiosInstance() {
@@ -2027,6 +2273,8 @@ export {
2027
2273
  FieldsResource,
2028
2274
  NOTIFICATION_PREFERENCE_CODES,
2029
2275
  NetworkError,
2276
+ OAuthResource,
2277
+ PartialWorkflowError,
2030
2278
  SignerDocumentsResource,
2031
2279
  SignerResource,
2032
2280
  TagResource,