@superdurable/connector-docusign 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1270 @@
1
+ import {
2
+ CombinedDocumentSchema,
3
+ ConfigSchema,
4
+ Connection,
5
+ ConnectorID,
6
+ CreateEnvelopeFromTemplateBranch,
7
+ CreateEnvelopeFromTemplateBranchCreated,
8
+ CreateEnvelopeFromTemplateBranchDefect,
9
+ CreateEnvelopeFromTemplateBranchProviderRejected,
10
+ CreateEnvelopeFromTemplateBranchUncertain,
11
+ CreateEnvelopeFromTemplateDefinition,
12
+ CreateEnvelopeFromTemplateInputSchema,
13
+ CreateEnvelopeFromTemplateMetadata,
14
+ CreatedEnvelopeSchema,
15
+ DownloadCombinedDocumentBranch,
16
+ DownloadCombinedDocumentBranchDefect,
17
+ DownloadCombinedDocumentBranchDownloaded,
18
+ DownloadCombinedDocumentBranchInvalidResponse,
19
+ DownloadCombinedDocumentBranchNotFound,
20
+ DownloadCombinedDocumentBranchProviderRejected,
21
+ DownloadCombinedDocumentBranchTooLarge,
22
+ DownloadCombinedDocumentDefinition,
23
+ DownloadCombinedDocumentInputSchema,
24
+ DownloadCombinedDocumentMetadata,
25
+ EnvelopeCustomFieldSchema,
26
+ EnvelopeRecipientsSchema,
27
+ EnvelopeSchema,
28
+ GetEnvelopeBranch,
29
+ GetEnvelopeBranchDefect,
30
+ GetEnvelopeBranchFound,
31
+ GetEnvelopeBranchInvalidResponse,
32
+ GetEnvelopeBranchNotFound,
33
+ GetEnvelopeBranchProviderRejected,
34
+ GetEnvelopeDefinition,
35
+ GetEnvelopeInputSchema,
36
+ GetEnvelopeMetadata,
37
+ ListEnvelopeRecipientsBranch,
38
+ ListEnvelopeRecipientsBranchDefect,
39
+ ListEnvelopeRecipientsBranchInvalidResponse,
40
+ ListEnvelopeRecipientsBranchListed,
41
+ ListEnvelopeRecipientsBranchNotFound,
42
+ ListEnvelopeRecipientsBranchProviderRejected,
43
+ ListEnvelopeRecipientsDefinition,
44
+ ListEnvelopeRecipientsInputSchema,
45
+ ListEnvelopeRecipientsMetadata,
46
+ ProviderID,
47
+ RecipientSchema,
48
+ TemplateRoleSchema,
49
+ VoidEnvelopeBranch,
50
+ VoidEnvelopeBranchDefect,
51
+ VoidEnvelopeBranchInvalidResponse,
52
+ VoidEnvelopeBranchNotFound,
53
+ VoidEnvelopeBranchNotVoidable,
54
+ VoidEnvelopeBranchProviderRejected,
55
+ VoidEnvelopeBranchVoided,
56
+ VoidEnvelopeDefinition,
57
+ VoidEnvelopeInputSchema,
58
+ VoidEnvelopeMetadata,
59
+ VoidedEnvelopeSchema,
60
+ decodeCredentials,
61
+ decodeSharedCredentials,
62
+ newConnection,
63
+ newConnectionWithOperations,
64
+ newProjectConnection,
65
+ newProjectCredentialProvider
66
+ } from "./chunk-42O7OZRV.js";
67
+
68
+ // src/generated/steps.ts
69
+ import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
70
+ function newCreateEnvelopeFromTemplateStep(configuration) {
71
+ const { connection, connectionName, created, providerRejected, uncertain, defect, ...stepConfiguration } = configuration;
72
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
73
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.createEnvelopeFromTemplate(), connection: connection.reference, branches: [
74
+ goToBranch("created", created),
75
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
76
+ ...uncertain ? [goToBranch("uncertain", uncertain)] : [],
77
+ ...defect ? [goToBranch("defect", defect)] : []
78
+ ] });
79
+ }
80
+ function newGetEnvelopeStep(configuration) {
81
+ const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
82
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
83
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.getEnvelope(), connection: connection.reference, branches: [
84
+ goToBranch("found", found),
85
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
86
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
87
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
88
+ ...defect ? [goToBranch("defect", defect)] : []
89
+ ] });
90
+ }
91
+ function newListEnvelopeRecipientsStep(configuration) {
92
+ const { connection, connectionName, listed, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
93
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
94
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listEnvelopeRecipients(), connection: connection.reference, branches: [
95
+ goToBranch("listed", listed),
96
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
97
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
98
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
99
+ ...defect ? [goToBranch("defect", defect)] : []
100
+ ] });
101
+ }
102
+ function newVoidEnvelopeStep(configuration) {
103
+ const { connection, connectionName, voided, notVoidable, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
104
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
105
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.voidEnvelope(), connection: connection.reference, branches: [
106
+ goToBranch("voided", voided),
107
+ ...notVoidable ? [goToBranch("notVoidable", notVoidable)] : [],
108
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
109
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
110
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
111
+ ...defect ? [goToBranch("defect", defect)] : []
112
+ ] });
113
+ }
114
+ function newDownloadCombinedDocumentStep(configuration) {
115
+ const { connection, connectionName, downloaded, notFound, tooLarge: tooLarge2, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
116
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
117
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.downloadCombinedDocument(), connection: connection.reference, branches: [
118
+ goToBranch("downloaded", downloaded),
119
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
120
+ ...tooLarge2 ? [goToBranch("tooLarge", tooLarge2)] : [],
121
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
122
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
123
+ ...defect ? [goToBranch("defect", defect)] : []
124
+ ] });
125
+ }
126
+
127
+ // src/client.ts
128
+ import { createHash as createHash2 } from "crypto";
129
+ import { BodyTooLargeError, isHeaderSafeCredential, parseRetryAfter, readErrorTokens, sendProviderRequest } from "@superdurable/connectors-sdk/providerhttp";
130
+ import { ManifestCredentialRefreshDriver } from "@superdurable/connectors-sdk/oauthtoken";
131
+ import { resolveCredential, resolveCredentialAfterRejection } from "@superdurable/connectors-sdk";
132
+
133
+ // src/generated/refresh.ts
134
+ var Authorization = {
135
+ "defaultMethod": "docusign-oauth",
136
+ "methods": [
137
+ {
138
+ "fields": [
139
+ {
140
+ "name": "oauth_client_id",
141
+ "required": true,
142
+ "type": "string"
143
+ },
144
+ {
145
+ "name": "oauth_client_secret",
146
+ "required": true,
147
+ "type": "secretString"
148
+ },
149
+ {
150
+ "name": "access_token",
151
+ "required": true,
152
+ "type": "secretString"
153
+ },
154
+ {
155
+ "name": "refresh_token",
156
+ "required": true,
157
+ "type": "secretString"
158
+ },
159
+ {
160
+ "name": "connect_hmac_key",
161
+ "required": false,
162
+ "type": "secretString"
163
+ }
164
+ ],
165
+ "id": "docusign-oauth",
166
+ "oauth2": {
167
+ "clientIDCredential": "oauth_client_id",
168
+ "clientSecretCredential": "oauth_client_secret",
169
+ "credentialMappings": [
170
+ {
171
+ "credential": "access_token",
172
+ "source": "access_token"
173
+ },
174
+ {
175
+ "credential": "refresh_token",
176
+ "source": "refresh_token"
177
+ }
178
+ ],
179
+ "refresh": {
180
+ "missingExpiry": "reject",
181
+ "responseScopes": "ignore",
182
+ "storedMissingExpiry": "refresh",
183
+ "terminalErrorCodes": [
184
+ "invalid_request",
185
+ "invalid_client",
186
+ "invalid_grant",
187
+ "unauthorized_client"
188
+ ]
189
+ },
190
+ "scopes": [
191
+ "signature",
192
+ "extended"
193
+ ],
194
+ "tokenEndpoint": "https://account.docusign.com/oauth/token",
195
+ "tokenEndpointAuthMethod": "client_secret_basic"
196
+ },
197
+ "type": "oauth2"
198
+ },
199
+ {
200
+ "fields": [
201
+ {
202
+ "name": "oauth_client_id",
203
+ "required": true,
204
+ "type": "string"
205
+ },
206
+ {
207
+ "name": "oauth_client_secret",
208
+ "required": true,
209
+ "type": "secretString"
210
+ },
211
+ {
212
+ "name": "access_token",
213
+ "required": true,
214
+ "type": "secretString"
215
+ },
216
+ {
217
+ "name": "refresh_token",
218
+ "required": true,
219
+ "type": "secretString"
220
+ },
221
+ {
222
+ "name": "connect_hmac_key",
223
+ "required": false,
224
+ "type": "secretString"
225
+ }
226
+ ],
227
+ "id": "docusign-developer-oauth",
228
+ "oauth2": {
229
+ "clientIDCredential": "oauth_client_id",
230
+ "clientSecretCredential": "oauth_client_secret",
231
+ "credentialMappings": [
232
+ {
233
+ "credential": "access_token",
234
+ "source": "access_token"
235
+ },
236
+ {
237
+ "credential": "refresh_token",
238
+ "source": "refresh_token"
239
+ }
240
+ ],
241
+ "refresh": {
242
+ "missingExpiry": "reject",
243
+ "responseScopes": "ignore",
244
+ "storedMissingExpiry": "refresh",
245
+ "terminalErrorCodes": [
246
+ "invalid_request",
247
+ "invalid_client",
248
+ "invalid_grant",
249
+ "unauthorized_client"
250
+ ]
251
+ },
252
+ "scopes": [
253
+ "signature",
254
+ "extended"
255
+ ],
256
+ "tokenEndpoint": "https://account-d.docusign.com/oauth/token",
257
+ "tokenEndpointAuthMethod": "client_secret_basic"
258
+ },
259
+ "type": "oauth2"
260
+ }
261
+ ],
262
+ "refreshable": true
263
+ };
264
+ var CredentialFields = {
265
+ "access_token": "accessToken",
266
+ "connect_hmac_key": "connectHmacKey",
267
+ "oauth_client_id": "oauthClientId",
268
+ "oauth_client_secret": "oauthClientSecret",
269
+ "refresh_token": "refreshToken"
270
+ };
271
+
272
+ // src/operations.ts
273
+ import { createHash } from "crypto";
274
+ import { AddressRefusal } from "@superdurable/connectors-sdk/providerhttp";
275
+ import { newMutationBranch, newMutationRetry, newMutationUncertain, newQueryBranch, newQueryRetry, zeroReceipt } from "@superdurable/connectors-sdk";
276
+ var zeroCreated = { envelopeId: "", status: "" };
277
+ var zeroEnvelope = { envelopeId: "", status: "" };
278
+ var zeroRecipients = { envelopeId: "", recipients: [] };
279
+ var zeroVoided = { envelopeId: "" };
280
+ var zeroDocument = { envelopeId: "", contentType: "", byteCount: 0, sha256: "" };
281
+ var malformed = "DocuSign returned a malformed response";
282
+ var tooLarge = "DocuSign response exceeds the configured maxResponseBytes";
283
+ var CreateEnvelopeFromTemplateOperation = class {
284
+ /** Bind the authenticated DocuSign client. */
285
+ constructor(client) {
286
+ this.client = client;
287
+ }
288
+ client;
289
+ /** Return manifest routes and Execute defaults. */
290
+ definition() {
291
+ return CreateEnvelopeFromTemplateDefinition;
292
+ }
293
+ /** Use the stable Dex Call ID as the hidden deduplication marker. */
294
+ idempotencyKey(callId) {
295
+ return callId;
296
+ }
297
+ /** Invoke one safe-to-classify create attempt. */
298
+ async invoke(call, input) {
299
+ const operation = "createEnvelopeFromTemplate";
300
+ const marker = call.idempotencyKey || call.id;
301
+ let body;
302
+ try {
303
+ body = buildCreateBody(input, marker);
304
+ } catch (error) {
305
+ return newMutationBranch("defect", zeroCreated, zeroReceipt(), failure(operation, "VALIDATION", errorMessage(error)));
306
+ }
307
+ const prior = readCreateCheckpoint(call);
308
+ let session;
309
+ try {
310
+ session = await this.client.openSession(call, operation);
311
+ } catch (error) {
312
+ if (!(error instanceof SessionError)) throw error;
313
+ if (prior) {
314
+ await recordCheckpoint(call, prior);
315
+ return error.route === "retry" ? newMutationRetry(error.failure, error.retryAfterMs) : newMutationUncertain(zeroCreated, { ...error.failure, message: `an earlier attempt sent the DocuSign create request and its outcome is unknown; ${error.failure.message}` }, this.client.receipt(""));
316
+ }
317
+ return sessionMutationFailure(error, zeroCreated, "providerRejected", "providerRejected");
318
+ }
319
+ if (prior) return recoverCreated(this.client, call, session, marker, prior, true, failure(operation, "TRANSPORT", "an earlier attempt sent the DocuSign create request and its outcome is unknown"));
320
+ if (call.context.attempt > 1) {
321
+ const found = await findBeforeResend(this.client, call, session, marker);
322
+ if (found) return found;
323
+ }
324
+ const checkpoint = { isDispatched: true, dispatchedAt: goTimestamp(this.client.currentTime()) };
325
+ try {
326
+ await call.context.recordHeartbeat(checkpoint);
327
+ } catch {
328
+ return newMutationRetry(failure(operation, "AVAILABILITY", "the create checkpoint could not be recorded, so nothing was sent to DocuSign"));
329
+ }
330
+ let response;
331
+ try {
332
+ response = await this.client.requestAPI(call, session, "POST", "/envelopes", void 0, body, "application/json", this.client.maxResponseBytes, 4e4);
333
+ } catch (error) {
334
+ if (isProvablyNotSent(error)) {
335
+ await clearCheckpoint(call);
336
+ return newMutationRetry(failure(operation, "TRANSPORT", "DocuSign could not be reached, so no envelope was created"));
337
+ }
338
+ return recoverCreated(this.client, call, session, marker, checkpoint, false, failure(operation, "TRANSPORT", "DocuSign's answer to the create request was lost"));
339
+ }
340
+ if (response.status === 200 || response.status === 201) {
341
+ try {
342
+ const created = decodeCreated(response.body, input.isDraft ?? false);
343
+ return newMutationBranch("created", created, this.client.receipt(created.envelopeId));
344
+ } catch {
345
+ return recoverCreated(this.client, call, session, marker, checkpoint, false, failure(operation, "PROTOCOL", "DocuSign accepted the create request but returned an unusable envelope summary"));
346
+ }
347
+ }
348
+ const outcome = this.client.classify(operation, response);
349
+ if (outcome.retry && response.status < 500 && response.status !== 408) {
350
+ await clearCheckpoint(call);
351
+ return newMutationRetry(outcome.failure, outcome.retryAfterMs);
352
+ }
353
+ if (response.status >= 400 && response.status < 500 && response.status !== 408) return newMutationBranch("providerRejected", zeroCreated, this.client.receipt("", outcome.errorCode), outcome.failure);
354
+ return recoverCreated(this.client, call, session, marker, checkpoint, false, outcome.failure);
355
+ }
356
+ };
357
+ var GetEnvelopeOperation = class {
358
+ /** Bind the authenticated DocuSign client. */
359
+ constructor(client) {
360
+ this.client = client;
361
+ }
362
+ client;
363
+ /** Return manifest routes and Execute defaults. */
364
+ definition() {
365
+ return GetEnvelopeDefinition;
366
+ }
367
+ /** Invoke one envelope read. */
368
+ async invoke(call, input) {
369
+ const operation = "getEnvelope";
370
+ if (!isGuid(input.envelopeId)) return newQueryBranch("defect", zeroEnvelope, zeroReceipt(), failure(operation, "VALIDATION", "envelopeId must be a DocuSign envelope ID GUID, such as 00000000-0000-0000-0000-000000000000"));
371
+ let session;
372
+ try {
373
+ session = await this.client.openSession(call, operation);
374
+ } catch (error) {
375
+ if (error instanceof SessionError) return sessionQueryFailure(error, zeroEnvelope);
376
+ throw error;
377
+ }
378
+ const read = await readEnvelope(this.client, call, session, input.envelopeId, operation);
379
+ if (read.error) return newQueryBranch("invalidResponse", zeroEnvelope, this.client.receipt(input.envelopeId), read.error);
380
+ if (read.outcome) return queryOutcome(this.client, read.outcome, input.envelopeId, zeroEnvelope);
381
+ if (!read.envelope) throw new Error("envelope read returned no value");
382
+ return newQueryBranch("found", read.envelope, this.client.receipt(read.envelope.envelopeId));
383
+ }
384
+ };
385
+ var ListEnvelopeRecipientsOperation = class {
386
+ /** Bind the authenticated DocuSign client. */
387
+ constructor(client) {
388
+ this.client = client;
389
+ }
390
+ client;
391
+ /** Return manifest routes and Execute defaults. */
392
+ definition() {
393
+ return ListEnvelopeRecipientsDefinition;
394
+ }
395
+ /** Invoke one recipients read. */
396
+ async invoke(call, input) {
397
+ const operation = "listEnvelopeRecipients";
398
+ if (!isGuid(input.envelopeId)) return newQueryBranch("defect", zeroRecipients, zeroReceipt(), failure(operation, "VALIDATION", "envelopeId must be a DocuSign envelope ID GUID, such as 00000000-0000-0000-0000-000000000000"));
399
+ let session;
400
+ try {
401
+ session = await this.client.openSession(call, operation);
402
+ } catch (error) {
403
+ if (error instanceof SessionError) return sessionQueryFailure(error, zeroRecipients);
404
+ throw error;
405
+ }
406
+ const envelopeId = input.envelopeId.toLowerCase();
407
+ let response;
408
+ try {
409
+ response = await this.client.requestAPI(call, session, "GET", `/envelopes/${escapePath(input.envelopeId)}/recipients`);
410
+ } catch (error) {
411
+ return error instanceof ResponseTooLargeError ? newQueryBranch("invalidResponse", zeroRecipients, this.client.receipt(envelopeId), failure(operation, "RESPONSE_TOO_LARGE", tooLarge)) : newQueryRetry(failure(operation, "TRANSPORT", "DocuSign could not be reached to list the recipients"));
412
+ }
413
+ if (response.status !== 200) return queryOutcome(this.client, this.client.classify(operation, response), envelopeId, zeroRecipients);
414
+ try {
415
+ return newQueryBranch("listed", decodeRecipients(response.body, envelopeId), this.client.receipt(envelopeId));
416
+ } catch {
417
+ return newQueryBranch("invalidResponse", zeroRecipients, this.client.receipt(envelopeId), failure(operation, "PROTOCOL", malformed));
418
+ }
419
+ }
420
+ };
421
+ var VoidEnvelopeOperation = class {
422
+ /** Bind the authenticated DocuSign client. */
423
+ constructor(client) {
424
+ this.client = client;
425
+ }
426
+ client;
427
+ /** Return manifest routes and Execute defaults. */
428
+ definition() {
429
+ return VoidEnvelopeDefinition;
430
+ }
431
+ /** Use the stable Call ID for this safely repeatable PUT. */
432
+ idempotencyKey(callId) {
433
+ return callId;
434
+ }
435
+ /** Invoke one void attempt. */
436
+ async invoke(call, input) {
437
+ const operation = "voidEnvelope";
438
+ if (!isGuid(input.envelopeId) || !input.voidedReason?.trim() || [...input.voidedReason].length > 200) return newMutationBranch("defect", zeroVoided, zeroReceipt(), failure(operation, "VALIDATION", !isGuid(input.envelopeId) ? "envelopeId must be a DocuSign envelope ID GUID, such as 00000000-0000-0000-0000-000000000000" : "voidedReason must be 1 to 200 characters of text"));
439
+ const envelopeId = input.envelopeId.toLowerCase();
440
+ let session;
441
+ try {
442
+ session = await this.client.openSession(call, operation);
443
+ } catch (error) {
444
+ if (error instanceof SessionError) return sessionMutationFailure(error, zeroVoided, "providerRejected", "invalidResponse");
445
+ throw error;
446
+ }
447
+ let response;
448
+ try {
449
+ response = await this.client.requestAPI(call, session, "PUT", `/envelopes/${escapePath(envelopeId)}`, void 0, { status: "voided", voidedReason: input.voidedReason });
450
+ } catch (error) {
451
+ if (error instanceof ResponseTooLargeError) return newMutationBranch("voided", { envelopeId }, this.client.receipt(envelopeId));
452
+ return newMutationRetry(failure(operation, "TRANSPORT", "DocuSign could not be reached to void the envelope; voiding again is safe"));
453
+ }
454
+ if (response.status === 200) return newMutationBranch("voided", { envelopeId }, this.client.receipt(envelopeId));
455
+ const outcome = this.client.classify(operation, response);
456
+ const receipt = this.client.receipt(envelopeId, outcome.errorCode);
457
+ if (outcome.retry) return newMutationRetry(outcome.failure, outcome.retryAfterMs);
458
+ if (outcome.notFound) return newMutationBranch("notFound", zeroVoided, receipt, outcome.failure);
459
+ if (!["ENVELOPE_CANNOT_VOID_INVALID_STATE", "ENVELOPE_INVALID_STATUS"].includes(outcome.errorCode.toUpperCase())) return newMutationBranch("providerRejected", zeroVoided, receipt, outcome.failure);
460
+ const read = await readEnvelope(this.client, call, session, envelopeId, operation);
461
+ if (read.error) return newMutationBranch("invalidResponse", zeroVoided, receipt, read.error);
462
+ if (read.outcome) return read.outcome.retry ? newMutationRetry(read.outcome.failure, read.outcome.retryAfterMs) : newMutationBranch(read.outcome.notFound ? "notFound" : "providerRejected", zeroVoided, this.client.receipt(envelopeId, read.outcome.errorCode), read.outcome.failure);
463
+ const envelope = read.envelope;
464
+ if (!envelope) throw new Error("envelope read returned no value");
465
+ if (envelope.status === "voided") return newMutationBranch("voided", { envelopeId, wasAlreadyVoided: true, status: envelope.status, ...envelope.voidedReason ? { voidedReason: envelope.voidedReason } : {} }, receipt);
466
+ if (["completed", "declined", "created"].includes(envelope.status)) return newMutationBranch("notVoidable", { envelopeId, status: envelope.status }, receipt, failure(operation, "CONFLICT", `DocuSign does not void an envelope whose status is ${envelope.status}`));
467
+ return newMutationBranch("providerRejected", { envelopeId: "", status: envelope.status }, receipt, outcome.failure);
468
+ }
469
+ };
470
+ var DownloadCombinedDocumentOperation = class {
471
+ /** Bind the authenticated DocuSign client. */
472
+ constructor(client) {
473
+ this.client = client;
474
+ }
475
+ client;
476
+ /** Return manifest routes and Execute defaults. */
477
+ definition() {
478
+ return DownloadCombinedDocumentDefinition;
479
+ }
480
+ /** Invoke one combined PDF read. */
481
+ async invoke(call, input) {
482
+ const operation = "downloadCombinedDocument";
483
+ if (!isGuid(input.envelopeId)) return newQueryBranch("defect", zeroDocument, zeroReceipt(), failure(operation, "VALIDATION", "envelopeId must be a DocuSign envelope ID GUID, such as 00000000-0000-0000-0000-000000000000"));
484
+ let session;
485
+ try {
486
+ session = await this.client.openSession(call, operation);
487
+ } catch (error) {
488
+ if (error instanceof SessionError) return sessionQueryFailure(error, zeroDocument);
489
+ throw error;
490
+ }
491
+ const envelopeId = input.envelopeId.toLowerCase();
492
+ let pendingHeartbeat = Promise.resolve();
493
+ const heartbeat = setInterval(() => {
494
+ pendingHeartbeat = pendingHeartbeat.then(() => call.context.recordHeartbeat(void 0)).catch(() => {
495
+ });
496
+ }, 5e3);
497
+ try {
498
+ let response;
499
+ try {
500
+ response = await this.client.openDocument(call, session, envelopeId, input.includeCertificate ?? false);
501
+ } catch (error) {
502
+ if (error instanceof ResponseTooLargeError) return newQueryBranch("tooLarge", zeroDocument, this.client.receipt(envelopeId), failure(operation, "RESPONSE_TOO_LARGE", "the combined PDF exceeds the configured maxDocumentBytes"));
503
+ return newQueryRetry(failure(operation, "TRANSPORT", "DocuSign could not be reached to download the combined PDF"));
504
+ }
505
+ if ("rejected" in response) return queryOutcome(this.client, this.client.classify(operation, response.rejected), envelopeId, zeroDocument);
506
+ try {
507
+ const mediaType = String(response.headers["content-type"] ?? "").split(";", 1)[0]?.trim().toLowerCase();
508
+ if (mediaType !== "application/pdf") return newQueryBranch("invalidResponse", zeroDocument, this.client.receipt(envelopeId), failure(operation, "PROTOCOL", "DocuSign returned something other than a PDF for the combined document"));
509
+ const lengthHeader = String(response.headers["content-length"] ?? "");
510
+ const contentLength = /^[0-9]+$/.test(lengthHeader) ? Number(lengthHeader) : 0;
511
+ if (Number.isSafeInteger(contentLength) && contentLength > this.client.maxDocumentBytes) return newQueryBranch("tooLarge", zeroDocument, this.client.receipt(envelopeId), failure(operation, "RESPONSE_TOO_LARGE", "the combined PDF exceeds the configured maxDocumentBytes"));
512
+ const digest = createHash("sha256");
513
+ let byteCount = 0;
514
+ let isComplete = false;
515
+ const maxBytes = this.client.maxDocumentBytes;
516
+ const content = (async function* () {
517
+ let prefix = Buffer.alloc(0);
518
+ try {
519
+ for await (const chunk of response.stream) {
520
+ const buffer = Buffer.from(chunk);
521
+ if (byteCount + buffer.length > maxBytes) throw new ResponseTooLargeError();
522
+ byteCount += buffer.length;
523
+ digest.update(buffer);
524
+ if (prefix.length < 5) {
525
+ prefix = Buffer.concat([prefix, buffer]);
526
+ if (prefix.length < 5) continue;
527
+ if (!prefix.subarray(0, 5).equals(Buffer.from("%PDF-"))) throw new InvalidPDFError();
528
+ yield prefix;
529
+ } else yield buffer;
530
+ }
531
+ } catch (error) {
532
+ if (error instanceof ResponseTooLargeError || error instanceof InvalidPDFError) throw error;
533
+ throw new DocumentUnreadError();
534
+ }
535
+ if (prefix.length < 5) throw new InvalidPDFError();
536
+ isComplete = true;
537
+ })();
538
+ let storedLocation = "";
539
+ if (this.client.documentStore) {
540
+ try {
541
+ storedLocation = await this.client.documentStore.storeCombinedDocument({ accountId: session.accountId, envelopeId, includesCertificate: input.includeCertificate ?? false }, content);
542
+ } catch (error) {
543
+ if (error instanceof ResponseTooLargeError || error instanceof InvalidPDFError || error instanceof DocumentUnreadError) throw error;
544
+ return newQueryBranch("invalidResponse", zeroDocument, this.client.receipt(envelopeId), failure(operation, "LOCAL_DEFECT", "the CombinedDocumentStore did not store the combined PDF"));
545
+ }
546
+ if (!isComplete) return newQueryBranch("invalidResponse", zeroDocument, this.client.receipt(envelopeId), failure(operation, "LOCAL_DEFECT", "the CombinedDocumentStore returned before reading the whole combined PDF"));
547
+ if (Buffer.byteLength(storedLocation) > 1024) return newQueryBranch("invalidResponse", zeroDocument, this.client.receipt(envelopeId), failure(operation, "LOCAL_DEFECT", "the CombinedDocumentStore did not store the combined PDF"));
548
+ } else for await (const chunk of content) {
549
+ void chunk;
550
+ }
551
+ const document = { envelopeId, contentType: "application/pdf", byteCount, sha256: digest.digest("hex"), ...input.includeCertificate ? { includesCertificate: true } : {}, ...storedLocation ? { storedLocation } : {} };
552
+ return newQueryBranch("downloaded", document, this.client.receipt(envelopeId));
553
+ } catch (error) {
554
+ if (error instanceof ResponseTooLargeError) return newQueryBranch("tooLarge", zeroDocument, this.client.receipt(envelopeId), failure(operation, "RESPONSE_TOO_LARGE", "the combined PDF exceeds the configured maxDocumentBytes"));
555
+ if (error instanceof InvalidPDFError) return newQueryBranch("invalidResponse", zeroDocument, this.client.receipt(envelopeId), failure(operation, "PROTOCOL", "DocuSign returned something other than a PDF for the combined document"));
556
+ return newQueryRetry(failure(operation, "TRANSPORT", "the combined PDF download was interrupted"));
557
+ } finally {
558
+ await response.close();
559
+ }
560
+ } finally {
561
+ clearInterval(heartbeat);
562
+ await pendingHeartbeat;
563
+ }
564
+ }
565
+ };
566
+ var InvalidPDFError = class extends Error {
567
+ };
568
+ var DocumentUnreadError = class extends Error {
569
+ };
570
+ function sessionQueryFailure(error, zero) {
571
+ if (error.route === "retry") return newQueryRetry(error.failure, error.retryAfterMs);
572
+ return newQueryBranch(error.route === "rejected" ? "providerRejected" : error.route, zero, zeroReceipt(), error.failure);
573
+ }
574
+ function sessionMutationFailure(error, zero, rejected, invalid) {
575
+ if (error.route === "retry") return newMutationRetry(error.failure, error.retryAfterMs);
576
+ return newMutationBranch(error.route === "rejected" ? rejected : error.route === "invalidResponse" ? invalid : "defect", zero, zeroReceipt(), error.failure);
577
+ }
578
+ function queryOutcome(client, outcome, envelopeId, zero) {
579
+ if (outcome.retry) return newQueryRetry(outcome.failure, outcome.retryAfterMs);
580
+ return newQueryBranch(outcome.notFound ? "notFound" : "providerRejected", zero, client.receipt(envelopeId, outcome.errorCode), outcome.failure);
581
+ }
582
+ function errorMessage(error) {
583
+ return error instanceof Error ? error.message : "invalid input";
584
+ }
585
+ function isProvablyNotSent(error) {
586
+ return error instanceof AddressRefusal || error instanceof Error && "isProvablyNotSent" in error && error.isProvablyNotSent === true;
587
+ }
588
+ async function clearCheckpoint(call) {
589
+ try {
590
+ await call.context.recordHeartbeat(void 0);
591
+ } catch {
592
+ }
593
+ }
594
+ async function recordCheckpoint(call, checkpoint) {
595
+ try {
596
+ await call.context.recordHeartbeat(checkpoint);
597
+ } catch {
598
+ }
599
+ }
600
+ function goTimestamp(value) {
601
+ return value.toISOString().replace(/\.([0-9]*?)0*Z$/, (_match, fraction) => fraction ? `.${fraction}Z` : "Z");
602
+ }
603
+ function readCreateCheckpoint(call) {
604
+ try {
605
+ if (!call.context.hasLastHeartbeatValue()) return void 0;
606
+ const marker = call.context.getLastHeartbeatValue();
607
+ if (marker === void 0 || marker === null) return void 0;
608
+ if (marker && typeof marker === "object" && "isDispatched" in marker && marker.isDispatched === false) return void 0;
609
+ if (marker && typeof marker === "object" && "isDispatched" in marker && marker.isDispatched === true && "dispatchedAt" in marker && typeof marker.dispatchedAt === "string" && !Number.isNaN(new Date(marker.dispatchedAt).getTime())) return marker;
610
+ return { isDispatched: true, dispatchedAt: goTimestamp(call.context.firstAttemptAt) };
611
+ } catch {
612
+ return { isDispatched: true, dispatchedAt: goTimestamp(call.context.firstAttemptAt) };
613
+ }
614
+ }
615
+ function buildCreateBody(input, marker) {
616
+ if (!isGuid(input.templateId)) throw new Error("templateId must be a DocuSign template ID GUID, such as 00000000-0000-0000-0000-000000000000");
617
+ if (!input.templateRoles || input.templateRoles.length < 1 || input.templateRoles.length > 100) throw new Error("templateRoles must fill 1 to 100 template roles");
618
+ if ([...input.emailSubject ?? ""].length > 100 || [...input.emailBlurb ?? ""].length > 1e4) throw new Error("emailSubject must be at most 100 characters and emailBlurb at most 10000");
619
+ const names = /* @__PURE__ */ new Set();
620
+ const roles = input.templateRoles.map((role, index) => {
621
+ if (!role.roleName?.trim() || [...role.roleName].length > 100) throw new Error(`templateRoles[${index}]: roleName must be 1 to 100 characters`);
622
+ if (!role.name?.trim() || [...role.name].length > 100) throw new Error(`templateRoles[${index}]: name must be 1 to 100 characters`);
623
+ const at = role.email.indexOf("@");
624
+ const domain = role.email.slice(at + 1);
625
+ if (at <= 0 || !domain.includes(".") || domain.includes("@") || Buffer.byteLength(role.email) > 100 || /[ \t\r\n<>,;]/.test(role.email)) throw new Error(`templateRoles[${index}]: email must be one email address of at most 100 characters`);
626
+ if ((role.routingOrder ?? 0) < 0 || (role.routingOrder ?? 0) > 999) throw new Error(`templateRoles[${index}]: routingOrder must be 1 to 999, or 0 to keep the template's order`);
627
+ if (names.has(role.roleName.toLowerCase())) throw new Error(`templateRoles[${index}]: role ${JSON.stringify(role.roleName)} is filled twice`);
628
+ names.add(role.roleName.toLowerCase());
629
+ return { roleName: role.roleName, name: role.name, email: role.email, ...role.routingOrder ? { routingOrder: String(role.routingOrder) } : {} };
630
+ });
631
+ if ((input.customFields?.length ?? 0) > 10) throw new Error("customFields holds at most 10 fields");
632
+ const fields = [{ name: "dexIdempotencyKey", value: marker, show: "false", required: "false" }];
633
+ const fieldNames = /* @__PURE__ */ new Set(["dexidempotencykey"]);
634
+ for (const [index, field] of (input.customFields ?? []).entries()) {
635
+ if (!field.name || [...field.name].length > 50 || [...field.value].length > 100) throw new Error(`customFields[${index}] needs a 1 to 50 character name and a value of at most 100 characters`);
636
+ if (fieldNames.has(field.name.toLowerCase())) throw new Error(`customFields[${index}]: name ${JSON.stringify(field.name)} is reserved or repeated`);
637
+ fieldNames.add(field.name.toLowerCase());
638
+ fields.push({ name: field.name, value: field.value, show: "false", required: "false" });
639
+ }
640
+ return { templateId: input.templateId.toLowerCase(), status: input.isDraft ? "created" : "sent", ...input.emailSubject ? { emailSubject: input.emailSubject } : {}, ...input.emailBlurb ? { emailBlurb: input.emailBlurb } : {}, templateRoles: roles, customFields: { textCustomFields: fields } };
641
+ }
642
+ function decodeCreated(body, isDraft) {
643
+ const raw = parseObject(body);
644
+ if (typeof raw.envelopeId !== "string" || !isGuid(raw.envelopeId) || typeof raw.status !== "string" || raw.status.toLowerCase() !== (isDraft ? "created" : "sent")) throw new Error(malformed);
645
+ const statusDateTime = optionalString(raw.statusDateTime);
646
+ return { envelopeId: raw.envelopeId.toLowerCase(), status: raw.status.toLowerCase(), ...statusDateTime ? { statusChangedAt: parseDocuSignTimestamp(statusDateTime) } : {} };
647
+ }
648
+ function parseObject(body) {
649
+ const value = JSON.parse(Buffer.from(body).toString("utf8"));
650
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(malformed);
651
+ return value;
652
+ }
653
+ function optionalString(value) {
654
+ if (value == null) return "";
655
+ if (typeof value !== "string") throw new Error(malformed);
656
+ return value;
657
+ }
658
+ function parseDocuSignTimestamp(value) {
659
+ const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:[.,](\d+))?(Z|[+-]\d{2}:\d{2})$/.exec(value);
660
+ if (!match) throw new Error(malformed);
661
+ const year = Number(match[1]);
662
+ const month = Number(match[2]);
663
+ const day = Number(match[3]);
664
+ const hour = Number(match[4]);
665
+ const minute = Number(match[5]);
666
+ const second = Number(match[6]);
667
+ const zone = match[8] ?? "Z";
668
+ if (month < 1 || month > 12 || day < 1 || day > 31 || hour > 23 || minute > 59 || second > 59 || zone !== "Z" && Number(zone.slice(4)) > 59) throw new Error(malformed);
669
+ const local = /* @__PURE__ */ new Date(0);
670
+ local.setUTCHours(0, 0, 0, 0);
671
+ local.setUTCFullYear(year, month - 1, day);
672
+ local.setUTCHours(hour, minute, second, 0);
673
+ if (local.getUTCFullYear() !== year || local.getUTCMonth() !== month - 1 || local.getUTCDate() !== day) throw new Error(malformed);
674
+ const offset = zone === "Z" ? 0 : (zone[0] === "+" ? 1 : -1) * (Number(zone.slice(1, 3)) * 60 + Number(zone.slice(4, 6)));
675
+ const utc = new Date(local.getTime() - offset * 6e4);
676
+ const seconds = utc.toISOString().slice(0, 19);
677
+ const fraction = (match[7] ?? "").slice(0, 9).replace(/0+$/, "");
678
+ return `${seconds}${fraction ? `.${fraction}` : ""}Z`;
679
+ }
680
+ function decodeEnvelope(body) {
681
+ const raw = parseObject(body);
682
+ const envelopeId = optionalString(raw.envelopeId);
683
+ const status = optionalString(raw.status).toLowerCase();
684
+ if (!isGuid(envelopeId) || !/^[a-z]{1,32}$/.test(status)) throw new Error(malformed);
685
+ const result = { envelopeId: envelopeId.toLowerCase(), status };
686
+ for (const [source, target] of [["emailSubject", "emailSubject"], ["voidedReason", "voidedReason"]]) {
687
+ const value = optionalString(raw[source]);
688
+ if (value) result[target] = value;
689
+ }
690
+ for (const [source, target] of [["createdDateTime", "createdAt"], ["sentDateTime", "sentAt"], ["deliveredDateTime", "deliveredAt"], ["completedDateTime", "completedAt"], ["declinedDateTime", "declinedAt"], ["voidedDateTime", "voidedAt"], ["statusChangedDateTime", "statusChangedAt"], ["expireDateTime", "expiresAt"]]) {
691
+ const value = optionalString(raw[source]);
692
+ if (value) result[target] = parseDocuSignTimestamp(value);
693
+ }
694
+ const fields = raw.customFields;
695
+ if (fields != null) {
696
+ if (typeof fields !== "object" || Array.isArray(fields)) throw new Error(malformed);
697
+ const text = fields.textCustomFields;
698
+ if (text != null && !Array.isArray(text)) throw new Error(malformed);
699
+ const customFields = (text ?? []).map((field) => {
700
+ if (!field || typeof field !== "object" || Array.isArray(field)) throw new Error(malformed);
701
+ const item = field;
702
+ return { name: optionalString(item.name), value: optionalString(item.value) };
703
+ }).filter((field) => field.name);
704
+ if (customFields.length) result.customFields = customFields;
705
+ }
706
+ return result;
707
+ }
708
+ async function readEnvelope(client, call, session, envelopeId, operation) {
709
+ let response;
710
+ try {
711
+ response = await client.requestAPI(call, session, "GET", `/envelopes/${escapePath(envelopeId)}`, { include: "custom_fields" });
712
+ } catch (error) {
713
+ return error instanceof ResponseTooLargeError ? { error: failure(operation, "RESPONSE_TOO_LARGE", tooLarge) } : { outcome: { retry: true, notFound: false, retryAfterMs: 0, errorCode: "", failure: failure(operation, "TRANSPORT", "DocuSign could not be reached to read the envelope") } };
714
+ }
715
+ if (response.status !== 200) return { outcome: client.classify(operation, response) };
716
+ try {
717
+ const envelope = decodeEnvelope(response.body);
718
+ if (envelope.envelopeId !== envelopeId.toLowerCase()) throw new Error(malformed);
719
+ return { envelope };
720
+ } catch {
721
+ return { error: failure(operation, "PROTOCOL", malformed) };
722
+ }
723
+ }
724
+ function decodeRecipients(body, envelopeId) {
725
+ const raw = parseObject(body);
726
+ const current = optionalString(raw.currentRoutingOrder);
727
+ const order = parseRoutingOrder(current);
728
+ const collections = [["signers", "signer"], ["carbonCopies", "carbonCopy"], ["certifiedDeliveries", "certifiedDelivery"], ["inPersonSigners", "inPersonSigner"], ["agents", "agent"], ["editors", "editor"], ["intermediaries", "intermediary"], ["witnesses", "witness"]];
729
+ const recipients = [];
730
+ for (const [source, type] of collections) {
731
+ const entries = raw[source];
732
+ if (entries != null && !Array.isArray(entries)) throw new Error(malformed);
733
+ for (const entry of entries ?? []) {
734
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) throw new Error(malformed);
735
+ const value = entry;
736
+ const recipientId = optionalString(value.recipientId);
737
+ const status = optionalString(value.status);
738
+ const routing = optionalString(value.routingOrder);
739
+ const routingOrder = parseRoutingOrder(routing);
740
+ if (!recipientId || !status) throw new Error(malformed);
741
+ const recipient = { recipientId, type, routingOrder, status: status.toLowerCase() };
742
+ for (const [from, to] of [["name", "name"], ["email", "email"], ["roleName", "roleName"], ["declinedReason", "declinedReason"]]) {
743
+ const text = optionalString(value[from]);
744
+ if (text) recipient[to] = text;
745
+ }
746
+ for (const [from, to] of [["sentDateTime", "sentAt"], ["deliveredDateTime", "deliveredAt"], ["signedDateTime", "signedAt"], ["declinedDateTime", "declinedAt"]]) {
747
+ const text = optionalString(value[from]);
748
+ if (text) recipient[to] = parseDocuSignTimestamp(text);
749
+ }
750
+ recipients.push(recipient);
751
+ }
752
+ }
753
+ recipients.sort((a, b) => a.routingOrder - b.routingOrder || compareRecipientId(a.recipientId, b.recipientId));
754
+ return { envelopeId, ...order ? { currentRoutingOrder: order } : {}, recipients };
755
+ }
756
+ function parseRoutingOrder(value) {
757
+ if (!value) return 0;
758
+ if (!/^[+-]?\d+$/.test(value)) throw new Error(malformed);
759
+ const parsed = Number(value);
760
+ if (!Number.isSafeInteger(parsed) || parsed < 0) throw new Error(malformed);
761
+ return parsed;
762
+ }
763
+ function compareRecipientId(a, b) {
764
+ const number = /^[+-]?\d+$/.test(a);
765
+ const other = /^[+-]?\d+$/.test(b);
766
+ return number && other ? Number(a) - Number(b) : number ? -1 : other ? 1 : a < b ? -1 : a > b ? 1 : 0;
767
+ }
768
+ async function recoverCreated(client, call, session, marker, checkpoint, retryable, unknown) {
769
+ const uncertain = newMutationUncertain(zeroCreated, unknown, client.receipt(""));
770
+ const timeoutMs = recoveryRequestTimeout(call);
771
+ if (timeoutMs === void 0) return uncertain;
772
+ let response;
773
+ try {
774
+ response = await listTagged(client, call, session, marker, checkpoint.dispatchedAt, timeoutMs);
775
+ } catch (error) {
776
+ if (retryable && !(error instanceof ResponseTooLargeError)) {
777
+ await recordCheckpoint(call, checkpoint);
778
+ return newMutationRetry(failure("createEnvelopeFromTemplate", "AVAILABILITY", "DocuSign could not list envelopes to find the one an earlier attempt may have created"));
779
+ }
780
+ return uncertain;
781
+ }
782
+ if (response.status !== 200) {
783
+ const outcome = client.classify("createEnvelopeFromTemplate", response);
784
+ if (retryable && outcome.retry) {
785
+ await recordCheckpoint(call, checkpoint);
786
+ return newMutationRetry(outcome.failure, outcome.retryAfterMs);
787
+ }
788
+ return uncertain;
789
+ }
790
+ try {
791
+ const matches = findTagged(response.body, marker);
792
+ if (matches.length !== 1) return uncertain;
793
+ const recovered = matches[0];
794
+ if (!recovered) return uncertain;
795
+ return newMutationBranch("created", { ...recovered, wasRecovered: true }, client.receipt(recovered.envelopeId));
796
+ } catch {
797
+ return uncertain;
798
+ }
799
+ }
800
+ async function findBeforeResend(client, call, session, marker) {
801
+ const timeoutMs = recoveryRequestTimeout(call);
802
+ if (timeoutMs === void 0) return void 0;
803
+ let response;
804
+ try {
805
+ response = await listTagged(client, call, session, marker, call.context.firstAttemptAt.toISOString(), timeoutMs);
806
+ } catch (error) {
807
+ return error instanceof ResponseTooLargeError ? void 0 : newMutationRetry(failure("createEnvelopeFromTemplate", "AVAILABILITY", "DocuSign could not list envelopes to find the one an earlier attempt may have created"));
808
+ }
809
+ if (response.status !== 200) {
810
+ const outcome = client.classify("createEnvelopeFromTemplate", response);
811
+ return outcome.retry ? newMutationRetry(outcome.failure, outcome.retryAfterMs) : void 0;
812
+ }
813
+ try {
814
+ const matches = findTagged(response.body, marker);
815
+ if (matches.length === 1 && matches[0]) return newMutationBranch("created", { ...matches[0], wasRecovered: true }, client.receipt(matches[0].envelopeId));
816
+ if (matches.length > 1) return newMutationUncertain(zeroCreated, failure("createEnvelopeFromTemplate", "CONFLICT", "several DocuSign envelopes carry this Step's dexIdempotencyKey, so none was adopted and none was sent"), client.receipt(""));
817
+ } catch {
818
+ }
819
+ return void 0;
820
+ }
821
+ function listTagged(client, call, session, marker, since, timeoutMs) {
822
+ const from = new Date(new Date(since).getTime() - 36e5).toISOString().replace(/\.\d{3}Z$/, "Z");
823
+ return client.requestAPI(call, session, "GET", "/envelopes", { from_date: from, custom_field: `dexIdempotencyKey=${marker}`, include: "custom_fields" }, void 0, "application/json", client.maxResponseBytes, timeoutMs);
824
+ }
825
+ function recoveryRequestTimeout(call) {
826
+ const timeoutMs = call.context.deadline ? Math.min(25e3, call.context.deadline.getTime() - Date.now() - 2e3) : 25e3;
827
+ return timeoutMs >= 2e3 ? timeoutMs : void 0;
828
+ }
829
+ function findTagged(body, marker) {
830
+ const raw = parseObject(body);
831
+ if (raw.envelopes != null && !Array.isArray(raw.envelopes)) throw new Error(malformed);
832
+ return (raw.envelopes ?? []).map((entry) => decodeEnvelope(Buffer.from(JSON.stringify(entry)))).filter((envelope) => envelope.customFields?.some((field) => field.name === "dexIdempotencyKey" && field.value === marker)).map((envelope) => ({ envelopeId: envelope.envelopeId, status: envelope.status, ...envelope.statusChangedAt ? { statusChangedAt: envelope.statusChangedAt } : {} }));
833
+ }
834
+
835
+ // src/client.ts
836
+ var guidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
837
+ var productionHostPattern = /^(?!demo\.)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.docusign\.net$/;
838
+ var maximumErrorBodyBytes = 65536;
839
+ var defaultResponseBytes = 1048576;
840
+ var defaultDocumentBytes = 67108864;
841
+ var rateLimitCodes = /* @__PURE__ */ new Set([
842
+ "HOURLY_APIINVOCATION_LIMIT_EXCEEDED",
843
+ "BURST_APIINVOCATION_LIMIT_EXCEEDED",
844
+ "HOURLY_ENVELOPE_POLLING_LIMIT_EXCEEDED",
845
+ "BURST_ENVELOPE_POLLING_LIMIT_EXCEEDED",
846
+ "HOURLY_APIINVOCATION_ENVELOPE_LIMIT_EXCEEDED",
847
+ "BURST_APIINVOCATION_ENVELOPE_LIMIT_EXCEEDED"
848
+ ]);
849
+ var SessionError = class extends Error {
850
+ /** Keep the route and sanitized failure for an operation. */
851
+ constructor(route, failure2, retryAfterMs = 0) {
852
+ super(failure2.message);
853
+ this.route = route;
854
+ this.failure = failure2;
855
+ this.retryAfterMs = retryAfterMs;
856
+ }
857
+ route;
858
+ failure;
859
+ retryAfterMs;
860
+ };
861
+ var ResponseTooLargeError = class extends Error {
862
+ };
863
+ function isGuid(value) {
864
+ return guidPattern.test(value);
865
+ }
866
+ function escapePath(value) {
867
+ return Array.from(Buffer.from(value)).map((byte) => {
868
+ const character = String.fromCharCode(byte);
869
+ return /^[A-Za-z0-9\-._~$&+=:@]$/.test(character) ? character : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`;
870
+ }).join("");
871
+ }
872
+ function failure(operation, kind, message) {
873
+ return { kind, provider: "docusign", operation, message };
874
+ }
875
+ var DocuSignClient2 = class {
876
+ /** Validate connection settings and bind host-owned renewable credentials. */
877
+ constructor(config, credentials, options = {}) {
878
+ this.credentials = credentials;
879
+ if (!credentials) throw new TypeError("DocuSign credential provider is required");
880
+ this.accountId = config.accountId ?? "";
881
+ if (this.accountId && !isGuid(this.accountId)) throw new TypeError("configuration accountId must be a DocuSign API account ID GUID, such as 00000000-0000-0000-0000-000000000000");
882
+ this.maxResponseBytes = config.maxResponseBytes || defaultResponseBytes;
883
+ this.maxDocumentBytes = config.maxDocumentBytes || defaultDocumentBytes;
884
+ if (!Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0) throw new TypeError("maxResponseBytes must be positive");
885
+ if (!Number.isSafeInteger(this.maxDocumentBytes) || this.maxDocumentBytes <= 0) throw new TypeError("maxDocumentBytes must be positive");
886
+ if (config.connectMaxBodyBytes !== void 0 && (!Number.isSafeInteger(config.connectMaxBodyBytes) || config.connectMaxBodyBytes < 0)) throw new TypeError("connectMaxBodyBytes must be non-negative");
887
+ this.send = options.send ?? sendProviderRequest;
888
+ this.hasCustomSend = options.send !== void 0;
889
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
890
+ this.documentStore = options.documentStore;
891
+ }
892
+ credentials;
893
+ maxResponseBytes;
894
+ maxDocumentBytes;
895
+ documentStore;
896
+ accountId;
897
+ send;
898
+ hasCustomSend;
899
+ now;
900
+ accountCache = /* @__PURE__ */ new Map();
901
+ refreshDriver = new ManifestCredentialRefreshDriver({ providerName: "DocuSign", auth: Authorization, credentialFields: CredentialFields });
902
+ /** Bind the template creation Mutation. */
903
+ createEnvelopeFromTemplate() {
904
+ return new CreateEnvelopeFromTemplateOperation(this);
905
+ }
906
+ /** Bind the envelope Query. */
907
+ getEnvelope() {
908
+ return new GetEnvelopeOperation(this);
909
+ }
910
+ /** Bind the recipients Query. */
911
+ listEnvelopeRecipients() {
912
+ return new ListEnvelopeRecipientsOperation(this);
913
+ }
914
+ /** Bind the void Mutation. */
915
+ voidEnvelope() {
916
+ return new VoidEnvelopeOperation(this);
917
+ }
918
+ /** Bind the combined PDF Query. */
919
+ downloadCombinedDocument() {
920
+ return new DownloadCombinedDocumentOperation(this);
921
+ }
922
+ /** Resolve renewable credentials and DocuSign's own account host. */
923
+ async openSession(call, operation) {
924
+ let credentials;
925
+ try {
926
+ credentials = await resolveCredential(this.credentials, call, this.refreshDriver, call.context.cancellationSignal);
927
+ } catch (error) {
928
+ const isTerminal = error instanceof Error && error.name === "ReauthorizationRequiredError";
929
+ throw new SessionError(isTerminal ? "defect" : "retry", failure(operation, isTerminal ? "AUTHENTICATION" : "AVAILABILITY", isTerminal ? "the DocuSign connection needs reauthorization; authorize it again in Dex Web Connections" : "the DocuSign access token could not be loaded or refreshed yet"));
930
+ }
931
+ if (!isHeaderSafeCredential(credentials.accessToken.reveal())) throw new SessionError("defect", failure(operation, "AUTHENTICATION", "the DocuSign access token is blank or contains characters a header cannot carry"));
932
+ const method = credentials.authMethodId ?? "docusign-oauth";
933
+ if (method !== "docusign-oauth" && method !== "docusign-developer-oauth") throw new SessionError("defect", failure(operation, "LOCAL_DEFECT", "the DocuSign connection names no known environment; authorize it again in Dex Web Connections"));
934
+ const key = `${call.connection.provider}/${call.connection.name}/${createHash2("sha256").update(credentials.accessToken.reveal()).digest("hex")}`;
935
+ const cached = this.accountCache.get(key);
936
+ if (cached && this.now().getTime() - cached.at < 36e5) return { credentials, accountId: cached.accountId, baseUri: cached.baseUri };
937
+ const accountServer = method === "docusign-developer-oauth" ? "https://account-d.docusign.com" : "https://account.docusign.com";
938
+ let response;
939
+ try {
940
+ response = await this.request(call, credentials, "GET", `${accountServer}/oauth/userinfo`, void 0, "application/json", this.maxResponseBytes);
941
+ } catch (error) {
942
+ if (error instanceof ResponseTooLargeError) throw new SessionError("invalidResponse", failure(operation, "RESPONSE_TOO_LARGE", "DocuSign account information exceeds the configured maxResponseBytes"));
943
+ throw new SessionError("retry", failure(operation, "TRANSPORT", "DocuSign account information could not be read"));
944
+ }
945
+ if (response.status === 429) throw new SessionError("retry", failure(operation, "RATE_LIMIT", "DocuSign limited the hourly account information requests for this user or integration key"), nextHour(this.now()));
946
+ if (response.status >= 500 || response.status === 408) throw new SessionError("retry", failure(operation, "AVAILABILITY", `DocuSign account information answered HTTP ${response.status}`));
947
+ if (response.status === 401) throw new SessionError("rejected", failure(operation, "AUTHENTICATION", "DocuSign rejected the access token; authorize the connection again"));
948
+ if (response.status !== 200) throw new SessionError("rejected", failure(operation, "PROVIDER_REJECTION", `DocuSign account information answered HTTP ${response.status}`));
949
+ let accounts;
950
+ try {
951
+ accounts = JSON.parse(Buffer.from(response.body).toString("utf8")).accounts;
952
+ } catch {
953
+ throw new SessionError("invalidResponse", failure(operation, "PROTOCOL", "DocuSign returned a malformed response: account information lists no accounts"));
954
+ }
955
+ if (!Array.isArray(accounts) || accounts.length === 0) throw new SessionError("invalidResponse", failure(operation, "PROTOCOL", "DocuSign returned a malformed response: account information lists no accounts"));
956
+ for (const entry of accounts) {
957
+ if (entry === null) continue;
958
+ if (typeof entry !== "object" || Array.isArray(entry)) throw new SessionError("invalidResponse", failure(operation, "PROTOCOL", "DocuSign returned a malformed response: account information lists no accounts"));
959
+ const account = entry;
960
+ if ([account.account_id, account.base_uri].some((value) => value !== void 0 && value !== null && typeof value !== "string")) {
961
+ throw new SessionError("invalidResponse", failure(operation, "PROTOCOL", "DocuSign returned a malformed response: account information lists no accounts"));
962
+ }
963
+ }
964
+ const selected = accounts.find((entry) => {
965
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) return false;
966
+ const account = entry;
967
+ return this.accountId ? typeof account.account_id === "string" && account.account_id.toLowerCase() === this.accountId.toLowerCase() : account.is_default === true || account.is_default === "true";
968
+ });
969
+ if (!selected) throw new SessionError("defect", failure(operation, "VALIDATION", this.accountId ? "the authorizing DocuSign user does not belong to the configured accountId; correct accountId or authorize as a member of that account" : "DocuSign reports no default account for the authorizing user; set the connection's accountId"));
970
+ if (typeof selected.account_id !== "string" || !isGuid(selected.account_id) || typeof selected.base_uri !== "string") throw new SessionError("invalidResponse", failure(operation, "PROTOCOL", "DocuSign returned a malformed response: the account ID is not a GUID"));
971
+ const baseUriMatch = /^https:\/\/([a-z0-9.-]+)\/?$/.exec(selected.base_uri);
972
+ const host = baseUriMatch?.[1];
973
+ if (!host || !(method === "docusign-developer-oauth" ? host === "demo.docusign.net" : productionHostPattern.test(host))) {
974
+ throw new SessionError("invalidResponse", failure(operation, "PROTOCOL", "DocuSign returned a malformed response: the account base URI is not a DocuSign eSignature host of this environment"));
975
+ }
976
+ const baseUri = `https://${host}`;
977
+ const accountId = selected.account_id.toLowerCase();
978
+ this.accountCache.set(key, { accountId, baseUri, at: this.now().getTime() });
979
+ return { credentials, accountId, baseUri };
980
+ }
981
+ /** Send one eSignature request after account selection. */
982
+ requestAPI(call, session, method, path, query, body, accept = "application/json", limit = this.maxResponseBytes, timeoutMs = 25e3) {
983
+ const suffix = query ? `?${Object.entries(query).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, value]) => `${goQueryEscape(key)}=${goQueryEscape(value)}`).join("&")}` : "";
984
+ return this.request(call, session.credentials, method, `${session.baseUri}/restapi/v2.1/accounts/${escapePath(session.accountId)}${path}${suffix}`, body, accept, limit, timeoutMs);
985
+ }
986
+ /** Open the combined PDF without buffering a successful response in Dex memory. */
987
+ async openDocument(call, session, envelopeId, includeCertificate) {
988
+ const path = `/restapi/v2.1/accounts/${escapePath(session.accountId)}/envelopes/${escapePath(envelopeId)}/documents/combined?certificate=${includeCertificate}`;
989
+ if (this.hasCustomSend) {
990
+ const response = await this.requestAPI(call, session, "GET", `/envelopes/${escapePath(envelopeId)}/documents/combined`, { certificate: String(includeCertificate) }, void 0, "application/pdf", this.maxDocumentBytes, 11e4);
991
+ if (response.status < 200 || response.status >= 300) return { rejected: response };
992
+ return { headers: response.headers, stream: (async function* () {
993
+ yield response.body;
994
+ })(), async close() {
995
+ } };
996
+ }
997
+ let credentials = session.credentials;
998
+ for (let attempt = 0; attempt < 2; attempt++) {
999
+ const controller = new AbortController();
1000
+ const timeout = setTimeout(() => controller.abort(), 11e4);
1001
+ const onCancel = () => controller.abort(call.context.cancellationSignal.reason);
1002
+ call.context.cancellationSignal.addEventListener("abort", onCancel, { once: true });
1003
+ let response;
1004
+ try {
1005
+ response = await fetch(`${session.baseUri}${path}`, {
1006
+ method: "GET",
1007
+ headers: { Authorization: `Bearer ${credentials.accessToken.reveal()}`, Accept: "application/pdf" },
1008
+ redirect: "manual",
1009
+ signal: controller.signal
1010
+ });
1011
+ } catch (error) {
1012
+ clearTimeout(timeout);
1013
+ call.context.cancellationSignal.removeEventListener("abort", onCancel);
1014
+ throw error;
1015
+ }
1016
+ const headers = {};
1017
+ response.headers.forEach((value, name) => {
1018
+ headers[name] = value;
1019
+ });
1020
+ const rejectedBody = response.status < 200 || response.status >= 300 ? await readErrorBody(response, maximumErrorBodyBytes) : void 0;
1021
+ if (response.status === 401 && attempt === 0 && "resolveAfterRejection" in this.credentials) {
1022
+ clearTimeout(timeout);
1023
+ call.context.cancellationSignal.removeEventListener("abort", onCancel);
1024
+ try {
1025
+ credentials = await resolveCredentialAfterRejection(this.credentials, call, this.refreshDriver, call.context.cancellationSignal);
1026
+ } catch {
1027
+ return { rejected: { status: 401, headers, body: rejectedBody ?? new Uint8Array(), isTooLarge: false } };
1028
+ }
1029
+ if (!isHeaderSafeCredential(credentials.accessToken.reveal())) return { rejected: { status: 401, headers, body: rejectedBody ?? new Uint8Array(), isTooLarge: false } };
1030
+ continue;
1031
+ }
1032
+ if (response.status < 200 || response.status >= 300) {
1033
+ clearTimeout(timeout);
1034
+ call.context.cancellationSignal.removeEventListener("abort", onCancel);
1035
+ return { rejected: { status: response.status, headers, body: rejectedBody ?? new Uint8Array(), isTooLarge: false } };
1036
+ }
1037
+ const reader = response.body?.getReader();
1038
+ if (!reader) {
1039
+ clearTimeout(timeout);
1040
+ call.context.cancellationSignal.removeEventListener("abort", onCancel);
1041
+ throw new Error("DocuSign PDF body was unreadable");
1042
+ }
1043
+ const stream = (async function* () {
1044
+ while (true) {
1045
+ const chunk = await reader.read();
1046
+ if (chunk.done) return;
1047
+ yield chunk.value;
1048
+ }
1049
+ })();
1050
+ return { headers, stream, async close() {
1051
+ await reader.cancel().catch(() => {
1052
+ });
1053
+ clearTimeout(timeout);
1054
+ call.context.cancellationSignal.removeEventListener("abort", onCancel);
1055
+ } };
1056
+ }
1057
+ throw new Error("DocuSign PDF authentication retry exhausted");
1058
+ }
1059
+ /** Classify one conclusive refusal without exposing provider messages. */
1060
+ classify(operation, response) {
1061
+ const errorCode = readErrorTokens(response.body, ["/errorCode", "/error"])[0] ?? "";
1062
+ const code = errorCode.toUpperCase();
1063
+ const status = response.status;
1064
+ let retry = false;
1065
+ let notFound = false;
1066
+ let retryAfterMs = 0;
1067
+ let kind;
1068
+ let message;
1069
+ if (rateLimitCodes.has(code) || status === 429) {
1070
+ retry = true;
1071
+ kind = "RATE_LIMIT";
1072
+ message = "DocuSign rate limited the request";
1073
+ const resetHeader = String(response.headers["x-ratelimit-reset"] ?? "");
1074
+ const reset = /^[0-9]+$/.test(resetHeader) ? Number(resetHeader) : 0;
1075
+ const resetDelay = Number.isSafeInteger(reset) && reset > 0 ? Math.max(0, reset * 1e3 - this.now().getTime()) : 0;
1076
+ retryAfterMs = code.startsWith("BURST_") ? 3e4 : Math.min(resetDelay || parseRetryAfter(String(response.headers["retry-after"] ?? ""), this.now()) || (code.startsWith("HOURLY_") ? nextHour(this.now()) : 0), 36e5);
1077
+ } else if (status >= 500 || status === 408) {
1078
+ retry = true;
1079
+ kind = "AVAILABILITY";
1080
+ message = `DocuSign answered HTTP ${status}`;
1081
+ } else if (code === "ENVELOPE_ALLOWANCE_EXCEEDED") {
1082
+ kind = "QUOTA_EXHAUSTED";
1083
+ message = "the DocuSign account has no envelope allowance left";
1084
+ } else if (status === 401 || ["USER_AUTHENTICATION_FAILED", "AUTHORIZATION_INVALID_TOKEN", "PARTNER_AUTHENTICATION_FAILED"].includes(code)) {
1085
+ kind = "AUTHENTICATION";
1086
+ message = "DocuSign rejected the access token; authorize the connection again";
1087
+ } else if (status === 403 || ["ACCOUNT_LACKS_PERMISSIONS", "USER_LACKS_PERMISSIONS", "USER_DOES_NOT_BELONG_TO_SPECIFIED_ACCOUNT", "ACCOUNT_NOT_AUTHORIZED_FOR_ENVELOPE", "USER_NOT_ENVELOPE_SENDER_OR_RECIPIENT", "USER_LACKS_MEMBERSHIP", "USER_NOT_ACCOUNT_ADMIN"].includes(code)) {
1088
+ kind = "AUTHORIZATION";
1089
+ message = "DocuSign denied permission for this account, user, or envelope";
1090
+ } else if (status === 404 || ["ENVELOPE_DOES_NOT_EXIST", "RESOURCE_NOT_FOUND", "DOCUMENT_DOES_NOT_EXIST"].includes(code)) {
1091
+ notFound = true;
1092
+ kind = "NOT_FOUND";
1093
+ message = "the DocuSign envelope or document was not found";
1094
+ } else {
1095
+ kind = "PROVIDER_REJECTION";
1096
+ message = `DocuSign rejected the request with HTTP ${status}`;
1097
+ }
1098
+ return { retry, notFound, retryAfterMs, errorCode, failure: failure(operation, kind, errorCode ? `${message} (${errorCode})` : message) };
1099
+ }
1100
+ /** Build a provider receipt with only safe envelope identity and error code. */
1101
+ receipt(envelopeId, errorCode = "") {
1102
+ return { provider: "docusign", providerObjectId: envelopeId, observedAt: this.now().toISOString(), ...errorCode ? { metadata: { errorCode } } : {} };
1103
+ }
1104
+ /** Return the injected clock for recovery windows and receipts. */
1105
+ currentTime() {
1106
+ return this.now();
1107
+ }
1108
+ async request(call, credentials, method, url, body, accept, limit, timeoutMs = 25e3) {
1109
+ const encoded = body === void 0 ? void 0 : Buffer.from(JSON.stringify(body));
1110
+ let current = credentials;
1111
+ for (let attempt = 0; attempt < 2; attempt++) {
1112
+ const request = {
1113
+ url,
1114
+ method,
1115
+ headers: { Authorization: `Bearer ${current.accessToken.reveal()}`, Accept: accept, ...encoded ? { "Content-Type": "application/json" } : {} },
1116
+ ...encoded ? { body: encoded } : {},
1117
+ maxResponseBytes: Math.max(limit, maximumErrorBodyBytes),
1118
+ addressPolicy: "publicHTTPS",
1119
+ timeoutMs,
1120
+ signal: call.context.cancellationSignal
1121
+ };
1122
+ let response;
1123
+ try {
1124
+ response = await this.send(request);
1125
+ } catch (error) {
1126
+ if (error instanceof BodyTooLargeError && error.status !== void 0 && error.headers !== void 0 && (error.status < 200 || error.status >= 300)) return { status: error.status, headers: error.headers, body: new Uint8Array(), isTooLarge: false };
1127
+ if (error instanceof BodyTooLargeError) throw new ResponseTooLargeError();
1128
+ throw error;
1129
+ }
1130
+ const answer = { ...response, isTooLarge: response.status >= 200 && response.status < 300 && response.body.length > limit };
1131
+ if (answer.isTooLarge) throw new ResponseTooLargeError();
1132
+ if (response.status !== 401 || attempt !== 0 || !("resolveAfterRejection" in this.credentials)) return answer;
1133
+ try {
1134
+ current = await resolveCredentialAfterRejection(this.credentials, call, this.refreshDriver, call.context.cancellationSignal);
1135
+ } catch {
1136
+ return answer;
1137
+ }
1138
+ if (!isHeaderSafeCredential(current.accessToken.reveal())) return answer;
1139
+ }
1140
+ throw new Error("DocuSign authenticated request retry was exhausted");
1141
+ }
1142
+ };
1143
+ function nextHour(now) {
1144
+ return 36e5 - now.getTime() % 36e5;
1145
+ }
1146
+ function goQueryEscape(value) {
1147
+ return encodeURIComponent(value).replace(/%20/g, "+").replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
1148
+ }
1149
+ async function readErrorBody(response, maximumBytes) {
1150
+ const reader = response.body?.getReader();
1151
+ if (!reader) return new Uint8Array();
1152
+ const chunks = [];
1153
+ let length = 0;
1154
+ try {
1155
+ while (length < maximumBytes) {
1156
+ const chunk = await reader.read();
1157
+ if (chunk.done) break;
1158
+ const bounded = chunk.value.subarray(0, maximumBytes - length);
1159
+ chunks.push(bounded);
1160
+ length += bounded.length;
1161
+ }
1162
+ } catch {
1163
+ } finally {
1164
+ await reader.cancel().catch(() => {
1165
+ });
1166
+ }
1167
+ return Buffer.concat(chunks, length);
1168
+ }
1169
+
1170
+ // src/project.ts
1171
+ function encodeCredentials(credentials) {
1172
+ return {
1173
+ auth_method: credentials.authMethodId ?? "docusign-oauth",
1174
+ oauth_client_id: credentials.oauthClientId,
1175
+ oauth_client_secret: credentials.oauthClientSecret?.reveal() ?? "",
1176
+ access_token: credentials.accessToken.reveal(),
1177
+ refresh_token: credentials.refreshToken?.reveal() ?? "",
1178
+ connect_hmac_key: credentials.connectHmacKey?.reveal() ?? ""
1179
+ };
1180
+ }
1181
+ function newProjectConnection2(project, connectionName, options = {}) {
1182
+ return newProjectConnection(project, connectionName, (loadedProject, name) => {
1183
+ const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "docusign" && entry.connectionName === name);
1184
+ if (!selected) throw new TypeError("DocuSign project connection is not configured");
1185
+ const parsed = ConfigSchema.parse(selected.configuration);
1186
+ const config = {
1187
+ ...parsed.accountId !== void 0 ? { accountId: parsed.accountId } : {},
1188
+ ...parsed.maxResponseBytes !== void 0 ? { maxResponseBytes: parsed.maxResponseBytes } : {},
1189
+ ...parsed.maxDocumentBytes !== void 0 ? { maxDocumentBytes: parsed.maxDocumentBytes } : {},
1190
+ ...parsed.connectMaxBodyBytes !== void 0 ? { connectMaxBodyBytes: parsed.connectMaxBodyBytes } : {}
1191
+ };
1192
+ return new DocuSignClient2(config, newProjectCredentialProvider(loadedProject, name, decodeCredentials, encodeCredentials, decodeSharedCredentials), options);
1193
+ });
1194
+ }
1195
+ export {
1196
+ CombinedDocumentSchema,
1197
+ ConfigSchema,
1198
+ Connection,
1199
+ ConnectorID,
1200
+ CreateEnvelopeFromTemplateBranch,
1201
+ CreateEnvelopeFromTemplateBranchCreated,
1202
+ CreateEnvelopeFromTemplateBranchDefect,
1203
+ CreateEnvelopeFromTemplateBranchProviderRejected,
1204
+ CreateEnvelopeFromTemplateBranchUncertain,
1205
+ CreateEnvelopeFromTemplateDefinition,
1206
+ CreateEnvelopeFromTemplateInputSchema,
1207
+ CreateEnvelopeFromTemplateMetadata,
1208
+ CreateEnvelopeFromTemplateOperation,
1209
+ CreatedEnvelopeSchema,
1210
+ DocuSignClient2 as DocuSignClient,
1211
+ DownloadCombinedDocumentBranch,
1212
+ DownloadCombinedDocumentBranchDefect,
1213
+ DownloadCombinedDocumentBranchDownloaded,
1214
+ DownloadCombinedDocumentBranchInvalidResponse,
1215
+ DownloadCombinedDocumentBranchNotFound,
1216
+ DownloadCombinedDocumentBranchProviderRejected,
1217
+ DownloadCombinedDocumentBranchTooLarge,
1218
+ DownloadCombinedDocumentDefinition,
1219
+ DownloadCombinedDocumentInputSchema,
1220
+ DownloadCombinedDocumentMetadata,
1221
+ DownloadCombinedDocumentOperation,
1222
+ EnvelopeCustomFieldSchema,
1223
+ EnvelopeRecipientsSchema,
1224
+ EnvelopeSchema,
1225
+ GetEnvelopeBranch,
1226
+ GetEnvelopeBranchDefect,
1227
+ GetEnvelopeBranchFound,
1228
+ GetEnvelopeBranchInvalidResponse,
1229
+ GetEnvelopeBranchNotFound,
1230
+ GetEnvelopeBranchProviderRejected,
1231
+ GetEnvelopeDefinition,
1232
+ GetEnvelopeInputSchema,
1233
+ GetEnvelopeMetadata,
1234
+ GetEnvelopeOperation,
1235
+ ListEnvelopeRecipientsBranch,
1236
+ ListEnvelopeRecipientsBranchDefect,
1237
+ ListEnvelopeRecipientsBranchInvalidResponse,
1238
+ ListEnvelopeRecipientsBranchListed,
1239
+ ListEnvelopeRecipientsBranchNotFound,
1240
+ ListEnvelopeRecipientsBranchProviderRejected,
1241
+ ListEnvelopeRecipientsDefinition,
1242
+ ListEnvelopeRecipientsInputSchema,
1243
+ ListEnvelopeRecipientsMetadata,
1244
+ ListEnvelopeRecipientsOperation,
1245
+ ProviderID,
1246
+ RecipientSchema,
1247
+ TemplateRoleSchema,
1248
+ VoidEnvelopeBranch,
1249
+ VoidEnvelopeBranchDefect,
1250
+ VoidEnvelopeBranchInvalidResponse,
1251
+ VoidEnvelopeBranchNotFound,
1252
+ VoidEnvelopeBranchNotVoidable,
1253
+ VoidEnvelopeBranchProviderRejected,
1254
+ VoidEnvelopeBranchVoided,
1255
+ VoidEnvelopeDefinition,
1256
+ VoidEnvelopeInputSchema,
1257
+ VoidEnvelopeMetadata,
1258
+ VoidEnvelopeOperation,
1259
+ VoidedEnvelopeSchema,
1260
+ decodeCredentials,
1261
+ decodeSharedCredentials,
1262
+ newConnection,
1263
+ newConnectionWithOperations,
1264
+ newCreateEnvelopeFromTemplateStep,
1265
+ newDownloadCombinedDocumentStep,
1266
+ newGetEnvelopeStep,
1267
+ newListEnvelopeRecipientsStep,
1268
+ newProjectConnection2 as newProjectConnection,
1269
+ newVoidEnvelopeStep
1270
+ };