@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/SECURITY.md ADDED
@@ -0,0 +1,10 @@
1
+ # Security policy
2
+
3
+ Security fixes are supported on the latest published version.
4
+
5
+ Report vulnerabilities through the repository's private **Security → Report a
6
+ vulnerability** form. If private reporting is unavailable, ask a project maintainer
7
+ for a private reporting channel without disclosing details in a public issue.
8
+
9
+ Include affected versions, reproduction steps, impact, and any suggested mitigation.
10
+ Do not include real API keys, signer access codes, documents, or personal data.
package/dist/api.cjs CHANGED
@@ -39,6 +39,8 @@ __export(api_exports, {
39
39
  FieldsResource: () => FieldsResource,
40
40
  NOTIFICATION_PREFERENCE_CODES: () => NOTIFICATION_PREFERENCE_CODES,
41
41
  NetworkError: () => NetworkError,
42
+ OAuthResource: () => OAuthResource,
43
+ PartialWorkflowError: () => PartialWorkflowError,
42
44
  SignerDocumentsResource: () => SignerDocumentsResource,
43
45
  SignerResource: () => SignerResource,
44
46
  TagResource: () => TagResource,
@@ -68,18 +70,35 @@ var AssinafyError = class extends Error {
68
70
  var ApiError = class _ApiError extends AssinafyError {
69
71
  statusCode;
70
72
  responseData;
73
+ /** Bearer challenge, including insufficient_scope and resource_metadata when provided. */
74
+ wwwAuthenticate;
75
+ /** Server retry delay (seconds or HTTP date), when provided. */
76
+ retryAfter;
71
77
  constructor(message, statusCode, responseData = null, options) {
72
78
  super(message, { statusCode, responseData }, options);
73
79
  this.name = "ApiError";
74
80
  this.statusCode = statusCode;
75
81
  this.responseData = responseData;
82
+ this.wwwAuthenticate = options?.wwwAuthenticate;
83
+ this.retryAfter = options?.retryAfter;
76
84
  }
77
- static fromResponse(statusCode, responseData) {
85
+ static fromResponse(statusCode, responseData, headers = {}) {
86
+ if (Buffer.isBuffer(responseData) || responseData instanceof ArrayBuffer) {
87
+ const text = (Buffer.isBuffer(responseData) ? responseData : Buffer.from(responseData)).toString("utf8");
88
+ try {
89
+ responseData = JSON.parse(text);
90
+ } catch {
91
+ responseData = text;
92
+ }
93
+ }
78
94
  const data = responseData ?? {};
79
95
  const rawMessage = data.message;
80
96
  const rawError = data.error;
81
97
  const message = typeof rawMessage === "string" && rawMessage.length > 0 ? rawMessage : typeof rawError === "string" ? rawError : "API request failed";
82
- return new _ApiError(message, statusCode, responseData);
98
+ return new _ApiError(message, statusCode, responseData, {
99
+ wwwAuthenticate: typeof headers["www-authenticate"] === "string" ? headers["www-authenticate"] : void 0,
100
+ retryAfter: typeof headers["retry-after"] === "string" ? headers["retry-after"] : void 0
101
+ });
83
102
  }
84
103
  };
85
104
  var ValidationError = class extends AssinafyError {
@@ -96,6 +115,19 @@ var NetworkError = class extends AssinafyError {
96
115
  this.name = "NetworkError";
97
116
  }
98
117
  };
118
+ var PartialWorkflowError = class extends AssinafyError {
119
+ /** The document that was uploaded before the failure, if any. */
120
+ documentId;
121
+ /** IDs of every signer created (or reused) before the failure. */
122
+ signerIds;
123
+ constructor(message, created, options) {
124
+ const signerIds = created.signerIds ?? [];
125
+ super(message, { documentId: created.documentId, signerIds }, options);
126
+ this.name = "PartialWorkflowError";
127
+ this.documentId = created.documentId;
128
+ this.signerIds = signerIds;
129
+ }
130
+ };
99
131
 
100
132
  // src/api/utils.ts
101
133
  var import_axios = __toESM(require("axios"), 1);
@@ -130,7 +162,7 @@ function toSdkError(error, fallbackMessage) {
130
162
  if (import_axios.default.isAxiosError(error)) {
131
163
  const status = error.response?.status;
132
164
  if (status) {
133
- return ApiError.fromResponse(status, error.response?.data ?? null);
165
+ return ApiError.fromResponse(status, error.response?.data ?? null, error.response?.headers);
134
166
  }
135
167
  return new NetworkError(`${fallbackMessage}: ${error.message}`);
136
168
  }
@@ -394,7 +426,7 @@ function buildAssignmentPayload(payload, options = {}) {
394
426
  }
395
427
  const normalisedSigners = signers.map((ref) => normaliseSignerRef(ref, options));
396
428
  if (!options.skipDigitalCertificateStepValidation) {
397
- validateDigitalCertificateSteps(normalisedSigners);
429
+ validateSigningSteps(normalisedSigners);
398
430
  }
399
431
  return cleanParams({
400
432
  method: payload.method ?? "virtual",
@@ -1161,6 +1193,174 @@ function validationConfig(signerAccessCode) {
1161
1193
  return signerAccessCode ? signerAccessConfig(signerAccessCode) : void 0;
1162
1194
  }
1163
1195
 
1196
+ // src/api/resources/oauth.ts
1197
+ var import_node_crypto = require("crypto");
1198
+ var OAuthResource = class extends BaseResource {
1199
+ /** `GET /.well-known/oauth-protected-resource` at the API origin, outside `/v1`. */
1200
+ async metadata() {
1201
+ return this.call(
1202
+ "Failed to discover OAuth resource",
1203
+ () => this.http.get(
1204
+ "/.well-known/oauth-protected-resource",
1205
+ publicRequestConfig({
1206
+ baseURL: new URL(this.http.defaults.baseURL).origin
1207
+ })
1208
+ )
1209
+ );
1210
+ }
1211
+ /** Read RFC 8414 metadata from an HTTPS issuer and verify its issuer identity. */
1212
+ async discovery(issuer) {
1213
+ const url = httpsUrl(issuer, "issuer");
1214
+ if (url.search || url.pathname !== "/") {
1215
+ throw new ValidationError("issuer must be an HTTPS origin");
1216
+ }
1217
+ const metadata = await this.call(
1218
+ "Failed to discover OAuth authorization server",
1219
+ () => this.http.get(
1220
+ `${url.origin}/.well-known/oauth-authorization-server`,
1221
+ publicRequestConfig()
1222
+ )
1223
+ );
1224
+ if (metadata.issuer !== issuer) throw new ValidationError("OAuth issuer mismatch");
1225
+ httpsUrl(metadata.authorization_endpoint, "authorization_endpoint");
1226
+ return metadata;
1227
+ }
1228
+ /** Discover endpoints and create a fresh authorization URL, PKCE verifier, and state. */
1229
+ async authorize(options) {
1230
+ required(options.clientId, "clientId");
1231
+ httpsUrl(options.redirectUri, "redirectUri");
1232
+ if (!Array.isArray(options.scopes) || options.scopes.length === 0 || options.scopes.some(
1233
+ (scope) => typeof scope !== "string" || !/^[\x21\x23-\x5B\x5D-\x7E]+$/.test(scope)
1234
+ )) {
1235
+ throw new ValidationError("scopes must contain non-empty OAuth scope names");
1236
+ }
1237
+ const resource = await this.metadata();
1238
+ const issuer = resource.authorization_servers?.[0];
1239
+ if (!issuer) throw new ValidationError("OAuth metadata has no authorization server");
1240
+ httpsUrl(resource.resource, "resource");
1241
+ const server = await this.discovery(issuer);
1242
+ const codeVerifier = (0, import_node_crypto.randomBytes)(32).toString("base64url");
1243
+ const state = (0, import_node_crypto.randomBytes)(32).toString("base64url");
1244
+ const nonce = options.scopes.includes("openid") ? (0, import_node_crypto.randomBytes)(32).toString("base64url") : void 0;
1245
+ const url = new URL(server.authorization_endpoint);
1246
+ const params = {
1247
+ response_type: "code",
1248
+ client_id: options.clientId,
1249
+ redirect_uri: options.redirectUri,
1250
+ scope: options.scopes.join(" "),
1251
+ state,
1252
+ code_challenge: (0, import_node_crypto.createHash)("sha256").update(codeVerifier).digest("base64url"),
1253
+ code_challenge_method: "S256",
1254
+ resource: resource.resource
1255
+ };
1256
+ for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
1257
+ if (nonce) url.searchParams.set("nonce", nonce);
1258
+ return {
1259
+ authorization_url: url.toString(),
1260
+ code_verifier: codeVerifier,
1261
+ state,
1262
+ issuer,
1263
+ client_id: options.clientId,
1264
+ redirect_uri: options.redirectUri,
1265
+ resource: resource.resource,
1266
+ ...nonce ? { nonce } : {}
1267
+ };
1268
+ }
1269
+ /** Validate callback URI, state, and issuer before exchanging its one-time code. */
1270
+ async exchangeCode(callbackUrl, request, clientSecret) {
1271
+ const callback = httpsUrl(callbackUrl, "callbackUrl");
1272
+ const redirect = httpsUrl(request.redirect_uri, "redirect_uri");
1273
+ if (callback.origin !== redirect.origin || callback.pathname !== redirect.pathname || [...new Set(redirect.searchParams.keys())].some((key) => {
1274
+ const expected2 = redirect.searchParams.getAll(key);
1275
+ const actual2 = callback.searchParams.getAll(key);
1276
+ return expected2.length !== actual2.length || expected2.some((value, i) => value !== actual2[i]);
1277
+ })) {
1278
+ throw new ValidationError("OAuth callback does not match the registered redirect URI");
1279
+ }
1280
+ for (const key of ["state", "iss", "code", "error"]) {
1281
+ if (callback.searchParams.getAll(key).length > 1) {
1282
+ throw new ValidationError(`Duplicate OAuth callback parameter: ${key}`);
1283
+ }
1284
+ }
1285
+ const actual = Buffer.from(callback.searchParams.get("state") ?? "");
1286
+ const expected = Buffer.from(required(request.state, "state"));
1287
+ if (actual.length !== expected.length || !(0, import_node_crypto.timingSafeEqual)(actual, expected)) {
1288
+ throw new ValidationError("OAuth state mismatch");
1289
+ }
1290
+ if (callback.searchParams.get("iss") !== request.issuer) {
1291
+ throw new ValidationError("OAuth issuer mismatch");
1292
+ }
1293
+ if (callback.searchParams.has("error")) {
1294
+ throw new ValidationError("OAuth authorization was declined or failed");
1295
+ }
1296
+ return this.token({
1297
+ grant_type: "authorization_code",
1298
+ code: required(callback.searchParams.get("code"), "code"),
1299
+ client_id: request.client_id,
1300
+ client_secret: clientSecret,
1301
+ redirect_uri: request.redirect_uri,
1302
+ code_verifier: request.code_verifier,
1303
+ resource: request.resource
1304
+ });
1305
+ }
1306
+ /** `POST /oauth/token` — code exchange or refresh; returns the flat OAuth JSON body. */
1307
+ async token(payload) {
1308
+ required(payload.client_id, "client_id");
1309
+ if (payload.client_secret !== void 0) required(payload.client_secret, "client_secret");
1310
+ if (payload.resource !== void 0) httpsUrl(payload.resource, "resource");
1311
+ if (payload.grant_type === "authorization_code") {
1312
+ required(payload.code, "code");
1313
+ httpsUrl(payload.redirect_uri, "redirect_uri");
1314
+ if (typeof payload.code_verifier !== "string" || !/^[A-Za-z0-9._~-]{43,128}$/.test(payload.code_verifier)) {
1315
+ throw new ValidationError(
1316
+ "code_verifier must contain 43\u2013128 RFC 7636 unreserved characters"
1317
+ );
1318
+ }
1319
+ } else if (payload.grant_type === "refresh_token") {
1320
+ required(payload.refresh_token, "refresh_token");
1321
+ } else {
1322
+ throw new ValidationError("grant_type must be authorization_code or refresh_token");
1323
+ }
1324
+ return this.call(
1325
+ "OAuth token request failed",
1326
+ () => this.http.post("/oauth/token", payload, publicRequestConfig())
1327
+ );
1328
+ }
1329
+ /** `POST /oauth/revoke` — revoke an access/refresh token; success has no required body. */
1330
+ async revoke(payload) {
1331
+ required(payload.client_id, "client_id");
1332
+ required(payload.token, "token");
1333
+ if (payload.client_secret !== void 0) required(payload.client_secret, "client_secret");
1334
+ if (payload.token_type_hint !== void 0 && !["access_token", "refresh_token"].includes(payload.token_type_hint)) {
1335
+ throw new ValidationError("token_type_hint must be access_token or refresh_token");
1336
+ }
1337
+ await this.call(
1338
+ "OAuth revocation failed",
1339
+ () => this.http.post("/oauth/revoke", payload, publicRequestConfig())
1340
+ );
1341
+ }
1342
+ /** `GET /oauth/userinfo` — flat OIDC claims; requires a bearer token with `openid`. */
1343
+ async userinfo() {
1344
+ return this.call("Failed to fetch OAuth userinfo", () => this.http.get("/oauth/userinfo"));
1345
+ }
1346
+ };
1347
+ function required(value, name) {
1348
+ if (typeof value !== "string" || !value.trim()) throw new ValidationError(`${name} is required`);
1349
+ return value;
1350
+ }
1351
+ function httpsUrl(value, name) {
1352
+ let url;
1353
+ try {
1354
+ url = new URL(value);
1355
+ } catch {
1356
+ throw new ValidationError(`${name} must be an absolute HTTPS URL`);
1357
+ }
1358
+ if (url.protocol !== "https:" || url.username || url.password || url.hash) {
1359
+ throw new ValidationError(`${name} must use HTTPS without credentials or a fragment`);
1360
+ }
1361
+ return url;
1362
+ }
1363
+
1164
1364
  // src/api/resources/signer-documents.ts
1165
1365
  var SignerDocumentsResource = class extends BaseResource {
1166
1366
  /** `GET /signers/{signer_id}/document?signer-access-code=…` */
@@ -1239,7 +1439,7 @@ var SignerDocumentsResource = class extends BaseResource {
1239
1439
  if (!Array.isArray(documentIds) || documentIds.length === 0) {
1240
1440
  throw new ValidationError("documentIds must be a non-empty array");
1241
1441
  }
1242
- if (!declineReason) throw new ValidationError("declineReason is required");
1442
+ validateDeclineReason(declineReason);
1243
1443
  const code = this.requireId(signerAccessCode, "signer-access-code");
1244
1444
  return this.call(
1245
1445
  "Failed to decline multiple documents",
@@ -1369,7 +1569,7 @@ var SignerDocumentsResource = class extends BaseResource {
1369
1569
  const did = this.requireId(documentId, "Document ID");
1370
1570
  const aid = this.requireId(assignmentId, "Assignment ID");
1371
1571
  const code = this.requireId(signerAccessCode, "signer-access-code");
1372
- if (!declineReason) throw new ValidationError("declineReason is required");
1572
+ validateDeclineReason(declineReason);
1373
1573
  return this.call(
1374
1574
  "Failed to decline assignment",
1375
1575
  () => this.http.put(
@@ -1380,6 +1580,14 @@ var SignerDocumentsResource = class extends BaseResource {
1380
1580
  );
1381
1581
  }
1382
1582
  };
1583
+ function validateDeclineReason(value) {
1584
+ if (typeof value !== "string" || !value.trim()) {
1585
+ throw new ValidationError("declineReason is required");
1586
+ }
1587
+ if ([...value].length > 2e3) {
1588
+ throw new ValidationError("declineReason must contain at most 2000 characters");
1589
+ }
1590
+ }
1383
1591
 
1384
1592
  // src/api/resources/signers.ts
1385
1593
  function validateCreateSignerPayload(payload) {
@@ -1469,9 +1677,13 @@ var SignerResource = class extends BaseResource {
1469
1677
  async findByEmail(email, accountId) {
1470
1678
  requireEmail(email);
1471
1679
  try {
1472
- const { data } = await this.list({ search: email, per_page: 100 }, accountId);
1473
1680
  const lower = email.toLowerCase();
1474
- return data.find((s) => (s.email ?? "").toLowerCase() === lower) ?? null;
1681
+ for (let page = 1; ; page++) {
1682
+ const { data, meta } = await this.list({ search: email, per_page: 100, page }, accountId);
1683
+ const match = data.find((s) => (s.email ?? "").toLowerCase() === lower);
1684
+ if (match) return match;
1685
+ if (!data.length || !meta?.last_page || page >= meta.last_page) return null;
1686
+ }
1475
1687
  } catch (err) {
1476
1688
  if (err instanceof ApiError && err.statusCode === 404) {
1477
1689
  return null;
@@ -1841,7 +2053,7 @@ function validateNotificationSender(value) {
1841
2053
  }
1842
2054
 
1843
2055
  // src/api/support/webhook-verifier.ts
1844
- var import_node_crypto = require("crypto");
2056
+ var import_node_crypto2 = require("crypto");
1845
2057
  var WebhookVerifier = class {
1846
2058
  constructor(webhookSecret, options = {}) {
1847
2059
  this.webhookSecret = webhookSecret;
@@ -1856,12 +2068,12 @@ var WebhookVerifier = class {
1856
2068
  if (!this.webhookSecret || !signature) return false;
1857
2069
  try {
1858
2070
  const buf = typeof payload === "string" ? Buffer.from(payload, "utf8") : payload;
1859
- const expected = (0, import_node_crypto.createHmac)(this.algorithm, this.webhookSecret).update(buf).digest(this.encoding);
2071
+ const expected = (0, import_node_crypto2.createHmac)(this.algorithm, this.webhookSecret).update(buf).digest(this.encoding);
1860
2072
  const provided = signature.trim();
1861
2073
  const a = Buffer.from(expected, "utf8");
1862
2074
  const b = Buffer.from(provided, "utf8");
1863
2075
  if (a.length !== b.length) return false;
1864
- return (0, import_node_crypto.timingSafeEqual)(a, b);
2076
+ return (0, import_node_crypto2.timingSafeEqual)(a, b);
1865
2077
  } catch {
1866
2078
  return false;
1867
2079
  }
@@ -1903,6 +2115,9 @@ var WebhookVerifier = class {
1903
2115
 
1904
2116
  // src/api/client.ts
1905
2117
  var DEFAULT_BASE_URL = "https://api.assinafy.com.br/v1";
2118
+ function isLoopbackHost(hostname) {
2119
+ return hostname === "localhost" || hostname === "[::1]" || /^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/.test(hostname);
2120
+ }
1906
2121
  var AssinafyClient = class _AssinafyClient {
1907
2122
  axiosInstance;
1908
2123
  defaultAccountId;
@@ -1916,6 +2131,7 @@ var AssinafyClient = class _AssinafyClient {
1916
2131
  templates;
1917
2132
  tags;
1918
2133
  auth;
2134
+ oauth;
1919
2135
  fields;
1920
2136
  users;
1921
2137
  signerDocuments;
@@ -1923,7 +2139,7 @@ var AssinafyClient = class _AssinafyClient {
1923
2139
  constructor(options) {
1924
2140
  if (!options.apiKey && !options.token && !options.allowUnauthenticated) {
1925
2141
  throw new ValidationError(
1926
- "An API key (options.apiKey) or legacy access token (options.token) is required."
2142
+ "An API key (options.apiKey) or access token (options.token) is required."
1927
2143
  );
1928
2144
  }
1929
2145
  if (options.timeout !== void 0 && (!Number.isFinite(options.timeout) || options.timeout <= 0)) {
@@ -1939,13 +2155,17 @@ var AssinafyClient = class _AssinafyClient {
1939
2155
  } catch {
1940
2156
  throw new ValidationError("baseUrl must be an absolute HTTP(S) URL");
1941
2157
  }
1942
- if (!["https:", "http:"].includes(parsedBaseUrl.protocol)) {
1943
- throw new ValidationError("baseUrl must use HTTPS");
1944
- }
1945
- if (parsedBaseUrl.protocol !== "https:" && !options.allowInsecureHttp) {
1946
- throw new ValidationError(
1947
- "baseUrl must use HTTPS; set allowInsecureHttp only for isolated local development"
1948
- );
2158
+ if (parsedBaseUrl.protocol !== "https:") {
2159
+ if (parsedBaseUrl.protocol !== "http:" || !options.allowInsecureHttp) {
2160
+ throw new ValidationError(
2161
+ "baseUrl must use HTTPS; set allowInsecureHttp only for a loopback development server"
2162
+ );
2163
+ }
2164
+ if (!isLoopbackHost(parsedBaseUrl.hostname)) {
2165
+ throw new ValidationError(
2166
+ "allowInsecureHttp only permits a loopback baseUrl (localhost, 127.0.0.0/8, or ::1)"
2167
+ );
2168
+ }
1949
2169
  }
1950
2170
  if (parsedBaseUrl.username || parsedBaseUrl.password) {
1951
2171
  throw new ValidationError("baseUrl must not contain embedded credentials");
@@ -1981,6 +2201,7 @@ var AssinafyClient = class _AssinafyClient {
1981
2201
  this.templates = new TemplateResource(this.axiosInstance, this.defaultAccountId, this.logger);
1982
2202
  this.tags = new TagResource(this.axiosInstance, this.defaultAccountId, this.logger);
1983
2203
  this.auth = new AuthenticationResource(this.axiosInstance, void 0, this.logger);
2204
+ this.oauth = new OAuthResource(this.axiosInstance, void 0, this.logger);
1984
2205
  this.fields = new FieldsResource(this.axiosInstance, this.defaultAccountId, this.logger);
1985
2206
  this.users = new UsersResource(this.axiosInstance, void 0, this.logger);
1986
2207
  this.signerDocuments = new SignerDocumentsResource(
@@ -2016,13 +2237,22 @@ var AssinafyClient = class _AssinafyClient {
2016
2237
  /**
2017
2238
  * High-level helper that uploads a PDF, ensures it's processed, creates any
2018
2239
  * missing signers, and kicks off a virtual signature assignment.
2240
+ *
2241
+ * Once the upload succeeds the workflow owns real workspace resources, so any
2242
+ * later failure is rethrown as a {@link PartialWorkflowError} carrying the
2243
+ * document and signer IDs that already exist. Catch it to resume or clean up;
2244
+ * nothing is deleted automatically.
2019
2245
  */
2020
2246
  async uploadAndRequestSignatures(options) {
2021
- if (!options.signers || options.signers.length === 0) {
2247
+ if (!Array.isArray(options.signers) || options.signers.length === 0) {
2022
2248
  throw new ValidationError("At least one signer is required");
2023
2249
  }
2024
2250
  if (options.expiresAt !== void 0) requireIso8601(options.expiresAt, "expiresAt");
2025
2251
  const preparedSigners = options.signers.map((signer) => {
2252
+ if (!signer || typeof signer !== "object") {
2253
+ throw new ValidationError("Each signer must be an object");
2254
+ }
2255
+ validateSignerOptions(signer);
2026
2256
  const payload = { full_name: signer.name };
2027
2257
  if (signer.email !== void 0) payload.email = signer.email;
2028
2258
  const phone = signer.whatsapp_phone_number ?? signer.phone;
@@ -2032,6 +2262,7 @@ var AssinafyClient = class _AssinafyClient {
2032
2262
  validateCreateSignerPayload(payload);
2033
2263
  return { signer, payload, phone };
2034
2264
  });
2265
+ validateSigningSteps(options.signers);
2035
2266
  this.logger.info("Starting upload + signature workflow", {
2036
2267
  signerCount: options.signers.length
2037
2268
  });
@@ -2039,33 +2270,46 @@ var AssinafyClient = class _AssinafyClient {
2039
2270
  if (options.metadata !== void 0) uploadOpts.metadata = options.metadata;
2040
2271
  if (options.accountId !== void 0) uploadOpts.accountId = options.accountId;
2041
2272
  const document = await this.documents.upload(options.source, uploadOpts);
2042
- if (options.waitForReady !== false) {
2043
- await this.documents.waitUntilReady(document.id);
2044
- }
2045
2273
  const signerIds = [];
2046
- const assignmentSigners = [];
2047
- for (const { signer, payload, phone } of preparedSigners) {
2048
- const created = await this.signers.create(payload, options.accountId);
2049
- signerIds.push(created.id);
2050
- const useWhatsapp = phone !== void 0 && signer.email === void 0;
2051
- assignmentSigners.push({
2052
- id: created.id,
2053
- verification_method: signer.verification_method ?? (useWhatsapp ? "Whatsapp" : void 0),
2054
- notification_methods: signer.notification_methods ?? (useWhatsapp ? ["Whatsapp"] : void 0),
2055
- step: signer.step
2274
+ try {
2275
+ if (options.waitForReady !== false) {
2276
+ await this.documents.waitUntilReady(document.id);
2277
+ }
2278
+ const assignmentSigners = [];
2279
+ for (const { signer, payload, phone } of preparedSigners) {
2280
+ const created = await this.signers.create(payload, options.accountId);
2281
+ signerIds.push(created.id);
2282
+ const useWhatsapp = phone !== void 0 && signer.email === void 0;
2283
+ assignmentSigners.push({
2284
+ id: created.id,
2285
+ verification_method: signer.verification_method ?? (useWhatsapp ? "Whatsapp" : void 0),
2286
+ notification_methods: signer.notification_methods ?? (useWhatsapp ? ["Whatsapp"] : void 0),
2287
+ step: signer.step
2288
+ });
2289
+ }
2290
+ const assignmentPayload = {
2291
+ method: "virtual",
2292
+ signers: assignmentSigners
2293
+ };
2294
+ if (options.message !== void 0) assignmentPayload.message = options.message;
2295
+ if (options.expiresAt !== void 0) assignmentPayload.expires_at = options.expiresAt;
2296
+ if (options.copyReceivers !== void 0)
2297
+ assignmentPayload.copy_receivers = options.copyReceivers;
2298
+ const assignment = await this.assignments.create(document.id, assignmentPayload);
2299
+ this.logger.info("Upload + signature workflow completed", { documentId: document.id });
2300
+ return { document, assignment, signer_ids: signerIds };
2301
+ } catch (err) {
2302
+ this.logger.error("Upload + signature workflow failed after creating resources", {
2303
+ documentId: document.id,
2304
+ signerIds
2056
2305
  });
2306
+ const reason = err instanceof Error ? err.message : String(err);
2307
+ throw new PartialWorkflowError(
2308
+ `${reason} (document ${document.id} exists; ${signerIds.length} signer(s) created or reused)`,
2309
+ { documentId: document.id, signerIds },
2310
+ { cause: err }
2311
+ );
2057
2312
  }
2058
- const assignmentPayload = {
2059
- method: "virtual",
2060
- signers: assignmentSigners
2061
- };
2062
- if (options.message !== void 0) assignmentPayload.message = options.message;
2063
- if (options.expiresAt !== void 0) assignmentPayload.expires_at = options.expiresAt;
2064
- if (options.copyReceivers !== void 0)
2065
- assignmentPayload.copy_receivers = options.copyReceivers;
2066
- const assignment = await this.assignments.create(document.id, assignmentPayload);
2067
- this.logger.info("Upload + signature workflow completed", { documentId: document.id });
2068
- return { document, assignment, signer_ids: signerIds };
2069
2313
  }
2070
2314
  /** Expose the underlying axios instance for advanced use cases (interceptors, custom endpoints). */
2071
2315
  getAxiosInstance() {
@@ -2083,6 +2327,8 @@ var AssinafyClient = class _AssinafyClient {
2083
2327
  FieldsResource,
2084
2328
  NOTIFICATION_PREFERENCE_CODES,
2085
2329
  NetworkError,
2330
+ OAuthResource,
2331
+ PartialWorkflowError,
2086
2332
  SignerDocumentsResource,
2087
2333
  SignerResource,
2088
2334
  TagResource,