@assinafy/cli 2.6.0 → 2.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api.cjs +23 -3
- package/dist/api.cjs.map +1 -1
- package/dist/api.js +23 -3
- package/dist/api.js.map +1 -1
- package/dist/cli.cjs +24 -4
- package/dist/types/api/resources/assignments.d.ts.map +1 -1
- package/dist/types/api/resources/documents.d.ts +1 -0
- package/dist/types/api/resources/documents.d.ts.map +1 -1
- package/dist/types/api/utils.d.ts +5 -1
- package/dist/types/api/utils.d.ts.map +1 -1
- package/docs/api-operations.json +1 -1
- package/docs/api-reference.md +10 -2
- package/docs/sdk-reference.md +3 -3
- package/package.json +1 -1
package/dist/api.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/api/client.ts","../src/api/errors.ts","../src/api/utils.ts","../src/api/resources/base.ts","../src/api/resources/assignments.ts","../src/api/resources/authentication.ts","../src/api/resources/documents.ts","../src/api/resources/fields.ts","../src/api/resources/oauth.ts","../src/api/resources/signer-documents.ts","../src/api/resources/signers.ts","../src/api/resources/tags.ts","../src/api/resources/templates.ts","../src/api/types.ts","../src/api/resources/users.ts","../src/api/resources/webhooks.ts","../src/api/resources/workspaces.ts","../src/api/support/webhook-verifier.ts"],"sourcesContent":["import axios, { type AxiosInstance } from 'axios';\nimport { PartialWorkflowError, ValidationError } from './errors.js';\nimport { AssignmentResource } from './resources/assignments.js';\nimport { AuthenticationResource } from './resources/authentication.js';\nimport { DocumentResource, type DocumentUploadSource } from './resources/documents.js';\nimport { FieldsResource } from './resources/fields.js';\nimport { OAuthResource } from './resources/oauth.js';\nimport { SignerDocumentsResource } from './resources/signer-documents.js';\nimport { SignerResource, validateCreateSignerPayload } from './resources/signers.js';\nimport { TagResource } from './resources/tags.js';\nimport { TemplateResource } from './resources/templates.js';\nimport { UsersResource } from './resources/users.js';\nimport { WebhookResource } from './resources/webhooks.js';\nimport { WorkspaceResource } from './resources/workspaces.js';\nimport { WebhookVerifier } from './support/webhook-verifier.js';\nimport type {\n\tAssinafyClientOptions,\n\tICreateAssignmentPayload,\n\tICreateSignerPayload,\n\tIUploadAndRequestSignaturesResult,\n\tIUploadAndRequestSignaturesSigner,\n\tLogger,\n\tSignerReference,\n} from './types.js';\nimport {\n\tcreateNoopLogger,\n\tnormalizeBaseUrl,\n\trequireIso8601,\n\tvalidateSignerOptions,\n\tvalidateSigningSteps,\n} from './utils.js';\n\n/** Flexible input accepted by {@link AssinafyClient.fromConfig} (snake_case or camelCase). */\nexport interface ClientConfigInput {\n\tapi_key?: string;\n\tapiKey?: string;\n\ttoken?: string;\n\taccess_token?: string;\n\taccessToken?: string;\n\taccount_id?: string;\n\taccountId?: string;\n\tbase_url?: string;\n\tbaseUrl?: string;\n\twebhook_secret?: string;\n\twebhookSecret?: string;\n\ttimeout?: number;\n\tlogger?: Logger;\n\tallow_unauthenticated?: boolean;\n\tallowUnauthenticated?: boolean;\n\tallow_insecure_http?: boolean;\n\tallowInsecureHttp?: boolean;\n}\n\nconst DEFAULT_BASE_URL = 'https://api.assinafy.com.br/v1';\n\n/** Hosts that never leave the machine, so plaintext HTTP cannot expose a key. */\nfunction isLoopbackHost(hostname: string): boolean {\n\treturn (\n\t\thostname === 'localhost' ||\n\t\thostname === '[::1]' ||\n\t\t/^127(?:\\.(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)){3}$/.test(hostname)\n\t);\n}\n\n/**\n * Primary entry point for the Assinafy API.\n *\n * @example\n * ```ts\n * const client = new AssinafyClient({\n * apiKey: process.env.ASSINAFY_API_KEY!,\n * accountId: process.env.ASSINAFY_ACCOUNT_ID!,\n * webhookSecret: process.env.ASSINAFY_WEBHOOK_SECRET,\n * });\n *\n * const document = await client.documents.upload({ filePath: './contract.pdf' });\n * ```\n */\nexport class AssinafyClient {\n\tprivate readonly axiosInstance: AxiosInstance;\n\tprivate readonly defaultAccountId: string | undefined;\n\tprivate readonly logger: Logger;\n\tprivate readonly webhookSecret: string | undefined;\n\n\tpublic readonly documents: DocumentResource;\n\tpublic readonly signers: SignerResource;\n\tpublic readonly workspaces: WorkspaceResource;\n\tpublic readonly assignments: AssignmentResource;\n\tpublic readonly webhooks: WebhookResource;\n\tpublic readonly templates: TemplateResource;\n\tpublic readonly tags: TagResource;\n\tpublic readonly auth: AuthenticationResource;\n\tpublic readonly oauth: OAuthResource;\n\tpublic readonly fields: FieldsResource;\n\tpublic readonly users: UsersResource;\n\tpublic readonly signerDocuments: SignerDocumentsResource;\n\tpublic readonly webhookVerifier: WebhookVerifier;\n\n\tconstructor(options: AssinafyClientOptions) {\n\t\tif (!options.apiKey && !options.token && !options.allowUnauthenticated) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'An API key (options.apiKey) or access token (options.token) is required.',\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\toptions.timeout !== undefined &&\n\t\t\t(!Number.isFinite(options.timeout) || options.timeout <= 0)\n\t\t) {\n\t\t\tthrow new ValidationError('timeout must be a finite positive number');\n\t\t}\n\n\t\tthis.defaultAccountId = options.accountId;\n\t\tthis.logger = options.logger ?? createNoopLogger();\n\t\tthis.webhookSecret = options.webhookSecret;\n\n\t\tconst baseURL = normalizeBaseUrl(options.baseUrl ?? DEFAULT_BASE_URL);\n\t\tlet parsedBaseUrl: URL;\n\t\ttry {\n\t\t\tparsedBaseUrl = new URL(baseURL);\n\t\t} catch {\n\t\t\tthrow new ValidationError('baseUrl must be an absolute HTTP(S) URL');\n\t\t}\n\t\tif (parsedBaseUrl.protocol !== 'https:') {\n\t\t\tif (parsedBaseUrl.protocol !== 'http:' || !options.allowInsecureHttp) {\n\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t'baseUrl must use HTTPS; set allowInsecureHttp only for a loopback development server',\n\t\t\t\t);\n\t\t\t}\n\t\t\t// The escape hatch exists for a dev server on this machine. Allowing an\n\t\t\t// arbitrary host would put the API key on the wire in cleartext, so the\n\t\t\t// flag alone is not enough — the host has to be loopback.\n\t\t\tif (!isLoopbackHost(parsedBaseUrl.hostname)) {\n\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t'allowInsecureHttp only permits a loopback baseUrl (localhost, 127.0.0.0/8, or ::1)',\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (parsedBaseUrl.username || parsedBaseUrl.password) {\n\t\t\tthrow new ValidationError('baseUrl must not contain embedded credentials');\n\t\t}\n\t\tif (parsedBaseUrl.search || parsedBaseUrl.hash) {\n\t\t\tthrow new ValidationError('baseUrl must not contain a query string or fragment');\n\t\t}\n\t\tconst headers: Record<string, string> = {\n\t\t\t'Content-Type': 'application/json',\n\t\t\tAccept: 'application/json',\n\t\t\t'User-Agent': 'assinafy-cli',\n\t\t};\n\t\tif (options.apiKey) {\n\t\t\theaders['X-Api-Key'] = options.apiKey;\n\t\t} else if (options.token) {\n\t\t\theaders.Authorization = `Bearer ${options.token}`;\n\t\t}\n\n\t\tthis.axiosInstance = axios.create({\n\t\t\tbaseURL,\n\t\t\ttimeout: options.timeout ?? 30_000,\n\t\t\theaders,\n\t\t\tmaxRedirects: 0,\n\t\t});\n\n\t\tthis.documents = new DocumentResource(this.axiosInstance, this.defaultAccountId, this.logger);\n\t\tthis.signers = new SignerResource(this.axiosInstance, this.defaultAccountId, this.logger);\n\t\tthis.workspaces = new WorkspaceResource(this.axiosInstance, undefined, this.logger);\n\t\tthis.assignments = new AssignmentResource(\n\t\t\tthis.axiosInstance,\n\t\t\tthis.defaultAccountId,\n\t\t\tthis.logger,\n\t\t);\n\t\tthis.webhooks = new WebhookResource(this.axiosInstance, this.defaultAccountId, this.logger);\n\t\tthis.templates = new TemplateResource(this.axiosInstance, this.defaultAccountId, this.logger);\n\t\tthis.tags = new TagResource(this.axiosInstance, this.defaultAccountId, this.logger);\n\t\tthis.auth = new AuthenticationResource(this.axiosInstance, undefined, this.logger);\n\t\tthis.oauth = new OAuthResource(this.axiosInstance, undefined, this.logger);\n\t\tthis.fields = new FieldsResource(this.axiosInstance, this.defaultAccountId, this.logger);\n\t\tthis.users = new UsersResource(this.axiosInstance, undefined, this.logger);\n\t\tthis.signerDocuments = new SignerDocumentsResource(\n\t\t\tthis.axiosInstance,\n\t\t\tthis.defaultAccountId,\n\t\t\tthis.logger,\n\t\t);\n\t\tthis.webhookVerifier = new WebhookVerifier(this.webhookSecret);\n\t}\n\n\t/** Convenience factory for the common apiKey + accountId setup. */\n\tstatic create(\n\t\tapiKey: string,\n\t\taccountId: string,\n\t\toptions: Omit<AssinafyClientOptions, 'apiKey' | 'accountId'> = {},\n\t): AssinafyClient {\n\t\treturn new AssinafyClient({ ...options, apiKey, accountId });\n\t}\n\n\t/** Build a client from a plain object (supports snake_case and camelCase keys). */\n\tstatic fromConfig(config: ClientConfigInput): AssinafyClient {\n\t\tconst opts: AssinafyClientOptions = {};\n\t\tconst apiKey = config.api_key ?? config.apiKey;\n\t\tconst token = config.token ?? config.access_token ?? config.accessToken;\n\t\tconst accountId = config.account_id ?? config.accountId;\n\t\tconst baseUrl = config.base_url ?? config.baseUrl;\n\t\tconst webhookSecret = config.webhook_secret ?? config.webhookSecret;\n\t\tif (apiKey !== undefined) opts.apiKey = apiKey;\n\t\tif (token !== undefined) opts.token = token;\n\t\tif (accountId !== undefined) opts.accountId = accountId;\n\t\tif (baseUrl !== undefined) opts.baseUrl = baseUrl;\n\t\tif (webhookSecret !== undefined) opts.webhookSecret = webhookSecret;\n\t\tif (config.timeout !== undefined) opts.timeout = config.timeout;\n\t\tif (config.logger !== undefined) opts.logger = config.logger;\n\t\topts.allowInsecureHttp = config.allow_insecure_http ?? config.allowInsecureHttp ?? false;\n\t\topts.allowUnauthenticated =\n\t\t\tconfig.allow_unauthenticated ?? config.allowUnauthenticated ?? false;\n\t\treturn new AssinafyClient(opts);\n\t}\n\n\t/**\n\t * High-level helper that uploads a PDF, ensures it's processed, creates any\n\t * missing signers, and kicks off a virtual signature assignment.\n\t *\n\t * Once the upload succeeds the workflow owns real workspace resources, so any\n\t * later failure is rethrown as a {@link PartialWorkflowError} carrying the\n\t * document and signer IDs that already exist. Catch it to resume or clean up;\n\t * nothing is deleted automatically.\n\t */\n\tasync uploadAndRequestSignatures(options: {\n\t\tsource: DocumentUploadSource;\n\t\tsigners: IUploadAndRequestSignaturesSigner[];\n\t\tmessage?: string;\n\t\tmetadata?: Record<string, unknown>;\n\t\twaitForReady?: boolean;\n\t\texpiresAt?: string;\n\t\tcopyReceivers?: string[];\n\t\taccountId?: string;\n\t}): Promise<IUploadAndRequestSignaturesResult> {\n\t\tif (!Array.isArray(options.signers) || options.signers.length === 0) {\n\t\t\tthrow new ValidationError('At least one signer is required');\n\t\t}\n\t\tif (options.expiresAt !== undefined) requireIso8601(options.expiresAt, 'expiresAt');\n\t\tconst preparedSigners = options.signers.map((signer) => {\n\t\t\tif (!signer || typeof signer !== 'object') {\n\t\t\t\tthrow new ValidationError('Each signer must be an object');\n\t\t\t}\n\t\t\tvalidateSignerOptions(signer);\n\t\t\tconst payload: ICreateSignerPayload = { full_name: signer.name };\n\t\t\tif (signer.email !== undefined) payload.email = signer.email;\n\t\t\tconst phone = signer.whatsapp_phone_number ?? signer.phone;\n\t\t\tif (phone !== undefined) payload.whatsapp_phone_number = phone;\n\t\t\tif (signer.cpf !== undefined) payload.cpf = signer.cpf;\n\t\t\tif (signer.government_id !== undefined) payload.government_id = signer.government_id;\n\t\t\tif (signer.metadata !== undefined) payload.metadata = signer.metadata;\n\t\t\tvalidateCreateSignerPayload(payload);\n\t\t\treturn { signer, payload, phone };\n\t\t});\n\t\tvalidateSigningSteps(options.signers);\n\n\t\tthis.logger.info('Starting upload + signature workflow', {\n\t\t\tsignerCount: options.signers.length,\n\t\t});\n\n\t\tconst uploadOpts: { metadata?: Record<string, unknown>; accountId?: string } = {};\n\t\tif (options.metadata !== undefined) uploadOpts.metadata = options.metadata;\n\t\tif (options.accountId !== undefined) uploadOpts.accountId = options.accountId;\n\n\t\tconst document = await this.documents.upload(options.source, uploadOpts);\n\n\t\t// Past this point every step can fail with a document (and possibly\n\t\t// signers) already created. Track them so the failure can name them\n\t\t// instead of leaving the caller to hunt for orphans by name.\n\t\tconst signerIds: string[] = [];\n\t\ttry {\n\t\t\tif (options.waitForReady !== false) {\n\t\t\t\tawait this.documents.waitUntilReady(document.id);\n\t\t\t}\n\n\t\t\tconst assignmentSigners: SignerReference[] = [];\n\t\t\tfor (const { signer, payload, phone } of preparedSigners) {\n\t\t\t\tconst created = await this.signers.create(payload, options.accountId);\n\t\t\t\tsignerIds.push(created.id);\n\t\t\t\tconst useWhatsapp = phone !== undefined && signer.email === undefined;\n\t\t\t\tassignmentSigners.push({\n\t\t\t\t\tid: created.id,\n\t\t\t\t\tverification_method: signer.verification_method ?? (useWhatsapp ? 'Whatsapp' : undefined),\n\t\t\t\t\tnotification_methods:\n\t\t\t\t\t\tsigner.notification_methods ?? (useWhatsapp ? ['Whatsapp'] : undefined),\n\t\t\t\t\tstep: signer.step,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst assignmentPayload: ICreateAssignmentPayload = {\n\t\t\t\tmethod: 'virtual',\n\t\t\t\tsigners: assignmentSigners,\n\t\t\t};\n\t\t\tif (options.message !== undefined) assignmentPayload.message = options.message;\n\t\t\tif (options.expiresAt !== undefined) assignmentPayload.expires_at = options.expiresAt;\n\t\t\tif (options.copyReceivers !== undefined)\n\t\t\t\tassignmentPayload.copy_receivers = options.copyReceivers;\n\n\t\t\tconst assignment = await this.assignments.create(document.id, assignmentPayload);\n\n\t\t\tthis.logger.info('Upload + signature workflow completed', { documentId: document.id });\n\n\t\t\treturn { document, assignment, signer_ids: signerIds };\n\t\t} catch (err) {\n\t\t\tthis.logger.error('Upload + signature workflow failed after creating resources', {\n\t\t\t\tdocumentId: document.id,\n\t\t\t\tsignerIds,\n\t\t\t});\n\t\t\tconst reason = err instanceof Error ? err.message : String(err);\n\t\t\tthrow new PartialWorkflowError(\n\t\t\t\t`${reason} (document ${document.id} exists; ${signerIds.length} signer(s) created or reused)`,\n\t\t\t\t{ documentId: document.id, signerIds },\n\t\t\t\t{ cause: err },\n\t\t\t);\n\t\t}\n\t}\n\n\t/** Expose the underlying axios instance for advanced use cases (interceptors, custom endpoints). */\n\tgetAxiosInstance(): AxiosInstance {\n\t\treturn this.axiosInstance;\n\t}\n}\n","/** Base class for all Assinafy SDK errors. */\nexport class AssinafyError extends Error {\n\tpublic readonly context: Record<string, unknown>;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tcontext: Record<string, unknown> = {},\n\t\toptions?: { cause?: unknown },\n\t) {\n\t\tsuper(message, options?.cause !== undefined ? { cause: options.cause } : undefined);\n\t\tthis.name = 'AssinafyError';\n\t\tthis.context = context;\n\t}\n}\n\n/** `X-Rate-Limit-*` values reported with a response (window size, requests left, seconds to reset). */\nexport interface RateLimitInfo {\n\tlimit?: number;\n\tremaining?: number;\n\treset?: number;\n}\n\n/** Thrown when the API returns a non-success HTTP status. */\nexport class ApiError extends AssinafyError {\n\tpublic readonly statusCode: number;\n\tpublic readonly responseData: unknown;\n\t/** Bearer challenge, including insufficient_scope and resource_metadata when provided. */\n\tpublic readonly wwwAuthenticate: string | undefined;\n\t/** Server retry delay (seconds or HTTP date), when provided. */\n\tpublic readonly retryAfter: string | undefined;\n\t/** Rate-limit window reported by the API, when the headers are present. */\n\tpublic readonly rateLimit: RateLimitInfo | undefined;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tstatusCode: number,\n\t\tresponseData: unknown = null,\n\t\toptions?: {\n\t\t\tcause?: unknown;\n\t\t\twwwAuthenticate?: string;\n\t\t\tretryAfter?: string;\n\t\t\trateLimit?: RateLimitInfo;\n\t\t},\n\t) {\n\t\tsuper(message, { statusCode, responseData }, options);\n\t\tthis.name = 'ApiError';\n\t\tthis.statusCode = statusCode;\n\t\tthis.responseData = responseData;\n\t\tthis.wwwAuthenticate = options?.wwwAuthenticate;\n\t\tthis.retryAfter = options?.retryAfter;\n\t\tthis.rateLimit = options?.rateLimit;\n\t}\n\n\tstatic fromResponse(\n\t\tstatusCode: number,\n\t\tresponseData: unknown,\n\t\theaders: Record<string, unknown> = {},\n\t): ApiError {\n\t\tif (Buffer.isBuffer(responseData) || responseData instanceof ArrayBuffer) {\n\t\t\tconst text = (\n\t\t\t\tBuffer.isBuffer(responseData) ? responseData : Buffer.from(responseData)\n\t\t\t).toString('utf8');\n\t\t\ttry {\n\t\t\t\tresponseData = JSON.parse(text);\n\t\t\t} catch {\n\t\t\t\tresponseData = text;\n\t\t\t}\n\t\t}\n\t\tconst data = (responseData ?? {}) as Record<string, unknown>;\n\t\tconst rawMessage = data.message;\n\t\tconst rawError = data.error;\n\t\tconst description = data.error_description;\n\t\tconst message =\n\t\t\ttypeof rawMessage === 'string' && rawMessage.length > 0\n\t\t\t\t? rawMessage\n\t\t\t\t: typeof rawError === 'string'\n\t\t\t\t\t? typeof description === 'string' && description.length > 0\n\t\t\t\t\t\t? `${rawError}: ${description}`\n\t\t\t\t\t\t: rawError\n\t\t\t\t\t: 'API request failed';\n\t\treturn new ApiError(message, statusCode, responseData, {\n\t\t\twwwAuthenticate:\n\t\t\t\ttypeof headers['www-authenticate'] === 'string' ? headers['www-authenticate'] : undefined,\n\t\t\tretryAfter: typeof headers['retry-after'] === 'string' ? headers['retry-after'] : undefined,\n\t\t\trateLimit: parseRateLimit(headers),\n\t\t});\n\t}\n}\n\nfunction parseRateLimit(headers: Record<string, unknown>): RateLimitInfo | undefined {\n\tconst info: RateLimitInfo = {};\n\tfor (const key of ['limit', 'remaining', 'reset'] as const) {\n\t\tconst value = Number.parseInt(String(headers[`x-rate-limit-${key}`]), 10);\n\t\tif (Number.isFinite(value)) info[key] = value;\n\t}\n\treturn Object.keys(info).length > 0 ? info : undefined;\n}\n\n/** Thrown when client-side validation fails before the request is sent. */\nexport class ValidationError extends AssinafyError {\n\tpublic readonly errors: Record<string, unknown>;\n\n\tconstructor(message = 'Validation failed', errors: Record<string, unknown> = {}) {\n\t\tsuper(message, { errors });\n\t\tthis.name = 'ValidationError';\n\t\tthis.errors = errors;\n\t}\n}\n\n/** Thrown when the HTTP transport itself fails (DNS, timeout, etc.). */\nexport class NetworkError extends AssinafyError {\n\tconstructor(message: string, options?: { cause?: unknown }) {\n\t\tsuper(message, {}, options);\n\t\tthis.name = 'NetworkError';\n\t}\n}\n\n/**\n * Thrown when a multi-step workflow helper fails *after* it has already created\n * billable resources.\n *\n * Without this, a failure part-way through\n * {@link AssinafyClient.uploadAndRequestSignatures} would leave an uploaded\n * document and created or reused signers in the workspace with no handle for the\n * caller to resume from or clean up. The original failure is preserved in\n * {@link Error.cause}.\n *\n * @example\n * ```ts\n * try {\n * await client.uploadAndRequestSignatures({ source, signers });\n * } catch (err) {\n * if (err instanceof PartialWorkflowError) {\n * console.error({ documentId: err.documentId, signerIds: err.signerIds });\n * // Inspect the document before resuming. Signers may already be in use elsewhere.\n * }\n * throw err;\n * }\n * ```\n */\nexport class PartialWorkflowError extends AssinafyError {\n\t/** The document that was uploaded before the failure, if any. */\n\tpublic readonly documentId: string | undefined;\n\t/** IDs of every signer created (or reused) before the failure. */\n\tpublic readonly signerIds: string[];\n\n\tconstructor(\n\t\tmessage: string,\n\t\tcreated: { documentId?: string; signerIds?: string[] },\n\t\toptions?: { cause?: unknown },\n\t) {\n\t\tconst signerIds = created.signerIds ?? [];\n\t\tsuper(message, { documentId: created.documentId, signerIds }, options);\n\t\tthis.name = 'PartialWorkflowError';\n\t\tthis.documentId = created.documentId;\n\t\tthis.signerIds = signerIds;\n\t}\n}\n","import axios, { type AxiosRequestConfig } from 'axios';\nimport { ApiError, AssinafyError, NetworkError, ValidationError } from './errors.js';\nimport type {\n\tAssignmentNotificationMethod,\n\tAssignmentVerificationMethod,\n\tDocumentArtifactName,\n\tIDocumentStatsParams,\n\tLogger,\n} from './types.js';\n\nconst DOCUMENT_ARTIFACT_NAMES: readonly DocumentArtifactName[] = [\n\t'original',\n\t'certificated',\n\t'certificate-page',\n\t'pades',\n\t'bundle',\n];\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\nconst VERIFICATION_METHODS: readonly AssignmentVerificationMethod[] = [\n\t'Email',\n\t'Whatsapp',\n\t'DigitalCertificate',\n\t'IdDocumentFaceMatchBasic',\n];\nconst NOTIFICATION_METHODS: readonly AssignmentNotificationMethod[] = ['Email', 'Whatsapp'];\n\n/**\n * Unwrap the Assinafy API envelope `{ status, message, data }`.\n * Throws {@link ApiError} when the envelope reports a non-success status.\n */\nexport function handleAssinafyResponse<T>(response: unknown): T {\n\tconst resp = response as { status?: number; data?: T; message?: string } | null | undefined;\n\n\tif (resp && typeof resp === 'object' && resp.status !== undefined && 'data' in resp) {\n\t\tif ((resp.status as number) >= 200 && (resp.status as number) < 300) {\n\t\t\treturn resp.data as T;\n\t\t}\n\t\tthrow ApiError.fromResponse(resp.status as number, resp);\n\t}\n\n\treturn response as T;\n}\n\n/**\n * Convert an unknown thrown value into a typed SDK error.\n * Axios errors become {@link ApiError} / {@link NetworkError}; SDK errors pass through.\n */\nexport function toSdkError(error: unknown, fallbackMessage: string): AssinafyError {\n\tif (error instanceof AssinafyError) {\n\t\treturn error;\n\t}\n\n\tif (axios.isAxiosError(error)) {\n\t\tconst status = error.response?.status;\n\t\tif (status) {\n\t\t\treturn ApiError.fromResponse(status, error.response?.data ?? null, error.response?.headers);\n\t\t}\n\t\t// Axios errors retain the complete request config, including auth headers,\n\t\t// body, and query values. Never attach the raw error as a public cause.\n\t\treturn new NetworkError(`${fallbackMessage}: ${error.message}`);\n\t}\n\n\tif (error instanceof Error) {\n\t\treturn new AssinafyError(`${fallbackMessage}: ${error.message}`, {}, { cause: error });\n\t}\n\n\treturn new AssinafyError(fallbackMessage, { cause: error });\n}\n\n/** No-op logger used when the caller does not supply one. */\nexport function createNoopLogger(): Logger {\n\treturn {\n\t\tdebug: () => undefined,\n\t\tinfo: () => undefined,\n\t\twarn: () => undefined,\n\t\terror: () => undefined,\n\t};\n}\n\n/** Strip undefined values from a params record (Axios sends `undefined` as literal). */\nexport function cleanParams(params: Record<string, unknown>): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(params)) {\n\t\tif (value !== undefined && value !== null) {\n\t\t\tout[normalizeQueryKey(key)] = value;\n\t\t}\n\t}\n\treturn out;\n}\n\n/** Strip nullish values from a JSON request body without renaming any keys. */\nexport function stripEmpty(body: Record<string, unknown>): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(body)) {\n\t\tif (value !== undefined && value !== null) {\n\t\t\tout[key] = value;\n\t\t}\n\t}\n\treturn out;\n}\n\n/** Append a multipart file part over a copy-free view of the binary data. */\nexport function appendFilePart(\n\tform: FormData,\n\tdata: Uint8Array,\n\tcontentType: string,\n\tfileName: string,\n): void {\n\tconst view = new Uint8Array(data.buffer as ArrayBuffer, data.byteOffset, data.byteLength);\n\tform.append('file', new Blob([view], { type: contentType }), fileName);\n}\n\n/** Remove owner credentials from a request that is public or signer-authenticated. */\nexport function publicRequestConfig(config: AxiosRequestConfig = {}): AxiosRequestConfig {\n\treturn {\n\t\t...config,\n\t\theaders: { ...config.headers, Authorization: undefined, 'X-Api-Key': undefined },\n\t};\n}\n\n/** Build an isolated signer-access-code request config. */\nexport function signerAccessConfig(\n\tsignerAccessCode: string,\n\tparams: Record<string, unknown> = {},\n\theaders: Record<string, string> = {},\n): AxiosRequestConfig {\n\treturn publicRequestConfig({\n\t\tparams: cleanParams({ ...params, 'signer-access-code': signerAccessCode }),\n\t\theaders,\n\t});\n}\n\n/** Validate an RFC 3339 timestamp before it reaches an API request body. */\nexport function requireIso8601(value: string, name = 'timestamp'): string {\n\tconst match =\n\t\t/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\\.[0-9]+)?(?:Z|[+-]([0-9]{2}):([0-9]{2}))$/.exec(\n\t\t\tvalue,\n\t\t);\n\tif (!match) {\n\t\tthrow new ValidationError(`${name} must be a valid ISO 8601 timestamp`);\n\t}\n\n\tconst year = Number(match[1]);\n\tconst month = Number(match[2]);\n\tconst day = Number(match[3]);\n\tconst hour = Number(match[4]);\n\tconst minute = Number(match[5]);\n\tconst second = Number(match[6]);\n\tconst leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n\tconst daysInMonth = [31, leapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\tconst timezoneHour = match[7] === undefined ? 0 : Number(match[7]);\n\tconst timezoneMinute = match[8] === undefined ? 0 : Number(match[8]);\n\n\tif (\n\t\tmonth < 1 ||\n\t\tmonth > 12 ||\n\t\tday < 1 ||\n\t\tday > (daysInMonth[month - 1] ?? 0) ||\n\t\thour > 23 ||\n\t\tminute > 59 ||\n\t\tsecond > 59 ||\n\t\ttimezoneHour > 14 ||\n\t\t(timezoneHour === 14 && timezoneMinute !== 0) ||\n\t\ttimezoneMinute > 59 ||\n\t\t!Number.isFinite(Date.parse(value))\n\t) {\n\t\tthrow new ValidationError(`${name} must be a valid ISO 8601 timestamp`);\n\t}\n\treturn value;\n}\n\n/** Reject an invalid email before it reaches an API request body or query. */\nexport function requireEmail(value: string | null | undefined): string {\n\tif (!value || !EMAIL_RE.test(value)) {\n\t\tthrow new ValidationError('Invalid email address', { email: value });\n\t}\n\treturn value;\n}\n\n/** Validate the shared verification, notification, and step fields on signer entries. */\nexport function validateSignerOptions(input: {\n\tverification_method?: unknown;\n\tnotification_methods?: unknown;\n\tstep?: unknown;\n}): void {\n\tif (\n\t\tinput.verification_method !== undefined &&\n\t\t!VERIFICATION_METHODS.includes(input.verification_method as AssignmentVerificationMethod)\n\t) {\n\t\tthrow new ValidationError(\n\t\t\t`verification_method must be one of: ${VERIFICATION_METHODS.join(', ')}`,\n\t\t);\n\t}\n\tif (\n\t\tinput.notification_methods !== undefined &&\n\t\t(!Array.isArray(input.notification_methods) ||\n\t\t\tinput.notification_methods.some(\n\t\t\t\t(method) => !NOTIFICATION_METHODS.includes(method as AssignmentNotificationMethod),\n\t\t\t))\n\t) {\n\t\tthrow new ValidationError(\n\t\t\t`notification_methods must contain only: ${NOTIFICATION_METHODS.join(', ')}`,\n\t\t);\n\t}\n\tconst notifications = (input.notification_methods ?? []) as string[];\n\tif (notifications.length > 1) {\n\t\tthrow new ValidationError('notification_methods accepts exactly one method per signer');\n\t}\n\tconst [notification] = notifications;\n\tif (\n\t\tnotification !== undefined &&\n\t\t(input.verification_method === 'Email' || input.verification_method === 'Whatsapp') &&\n\t\tnotification !== input.verification_method\n\t) {\n\t\tthrow new ValidationError(\n\t\t\t`${input.verification_method} verification requires the ${input.verification_method} notification method`,\n\t\t);\n\t}\n\tif (input.step !== undefined && !Number.isInteger(input.step)) {\n\t\tthrow new ValidationError('step must be an integer');\n\t}\n}\n\n/** Validate the sequencing rules for assignments and template-document signers. */\nexport function validateSigningSteps(\n\tsigners: readonly { verification_method?: unknown; step?: unknown }[],\n): void {\n\tconst withSteps = signers.filter((signer) => signer.step !== undefined);\n\tif (withSteps.length > 0) {\n\t\tif (withSteps.length !== signers.length) {\n\t\t\tthrow new ValidationError('step must be supplied for every signer when used');\n\t\t}\n\t\tconst steps = [...new Set(withSteps.map((signer) => signer.step as number))].sort(\n\t\t\t(a, b) => a - b,\n\t\t);\n\t\tif (steps.some((step, index) => step !== index + 1)) {\n\t\t\tthrow new ValidationError('steps must form a contiguous sequence starting at 1');\n\t\t}\n\t}\n\tvalidateDigitalCertificateSteps(signers);\n}\n\n/** Enforce the documented one-digital-certificate-signer-per-step constraint. */\nexport function validateDigitalCertificateSteps(\n\tsigners: readonly { verification_method?: unknown; step?: unknown }[],\n): void {\n\tfor (const signer of signers) {\n\t\tif (\n\t\t\tsigner.verification_method === 'DigitalCertificate' &&\n\t\t\tsigners.some((other) => other !== signer && (other.step ?? 1) === (signer.step ?? 1))\n\t\t) {\n\t\t\tthrow new ValidationError('a DigitalCertificate signer must be alone in its signing step');\n\t\t}\n\t}\n}\n\n/** Validate and serialize the query shared by account/user statistics endpoints. */\nexport function documentStatsParams(params: IDocumentStatsParams = {}): Record<string, unknown> {\n\tif (params.granularity !== undefined && !['monthly', 'daily'].includes(params.granularity)) {\n\t\tthrow new ValidationError('granularity must be monthly or daily');\n\t}\n\tif (params.month !== undefined && !/^\\d{4}-(0[1-9]|1[0-2])$/.test(params.month)) {\n\t\tthrow new ValidationError('month must use YYYY-MM format');\n\t}\n\tif (params.granularity === 'daily' && !params.month) {\n\t\tthrow new ValidationError('month is required for daily statistics');\n\t}\n\treturn cleanParams(params as Record<string, unknown>);\n}\n\n/** Validate an artifact before it is interpolated into a request path. */\nexport function requireDocumentArtifactName(value: string): DocumentArtifactName {\n\tif ((DOCUMENT_ARTIFACT_NAMES as readonly string[]).includes(value)) {\n\t\treturn value as DocumentArtifactName;\n\t}\n\tthrow new ValidationError(`artifact must be one of: ${DOCUMENT_ARTIFACT_NAMES.join(', ')}`);\n}\n\n/** Validate a signer image type before it is interpolated into a request path. */\nexport function requireSignerImageType(value: string): 'signature' | 'initial' {\n\tif (value === 'signature' || value === 'initial') return value;\n\tthrow new ValidationError('image type must be signature or initial');\n}\n\n/** Validate a live-supported sort value before sending it to an endpoint. */\nexport function requireSort<T extends string>(\n\tvalue: T | undefined,\n\tallowed: readonly T[],\n): T | undefined {\n\tif (value === undefined || allowed.includes(value)) return value;\n\tthrow new ValidationError(`sort must be one of: ${allowed.join(', ')}`);\n}\n\nfunction normalizeQueryKey(key: string): string {\n\treturn key === 'per_page' ? 'per-page' : key;\n}\n\n/** Strip a single trailing slash from a base URL, so paths can always join with a leading `/`. */\nexport function normalizeBaseUrl(raw: string): string {\n\treturn raw.endsWith('/') ? raw.slice(0, -1) : raw;\n}\n","import type { AxiosInstance, AxiosResponse, AxiosResponseHeaders } from 'axios';\nimport { ApiError, ValidationError } from '../errors.js';\nimport type { Logger, PaginatedResult, PaginationMeta } from '../types.js';\nimport { createNoopLogger, handleAssinafyResponse, toSdkError } from '../utils.js';\n\n/**\n * Shared plumbing for every Assinafy resource:\n *\n * - holds the axios instance, default account ID, and logger\n * - provides `accountId()` / `requireId()` argument guards\n * - wraps HTTP calls in a single `try/catch` → typed-error pipeline\n * - unwraps the Assinafy response envelope\n * - parses `X-Pagination-*` headers into a typed meta object\n *\n * Resources should never `try/catch` or touch the envelope directly — they call\n * one of `call` / `callBinary` / `callList` instead.\n */\nexport abstract class BaseResource {\n\tconstructor(\n\t\tprotected readonly http: AxiosInstance,\n\t\tprotected readonly defaultAccountId?: string,\n\t\tprotected readonly logger: Logger = createNoopLogger(),\n\t) {}\n\n\t/** Resolve the effective account id, throwing if none is available. */\n\tprotected accountId(explicit?: string): string {\n\t\tconst id = explicit ?? this.defaultAccountId;\n\t\tif (!id) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'Account ID is required. Provide it as a parameter or set a default in the client.',\n\t\t\t);\n\t\t}\n\t\treturn safeIdentifier(id, 'Account ID');\n\t}\n\n\t/** Guard required path arguments (documentId, signerId, …). */\n\tprotected requireId<T extends string>(value: T | undefined | null, name: string): T {\n\t\tif (!value) {\n\t\t\tthrow new ValidationError(`${name} is required`);\n\t\t}\n\t\treturn safeIdentifier(value, name) as T;\n\t}\n\n\t/** Execute an HTTP call and return the unwrapped envelope body. */\n\tprotected async call<T>(label: string, request: RequestFn): Promise<T> {\n\t\ttry {\n\t\t\tconst response = await request();\n\t\t\treturn handleAssinafyResponse<T>(response.data);\n\t\t} catch (err) {\n\t\t\tthrow toSdkError(err, label);\n\t\t}\n\t}\n\n\t/** Like {@link call} but returns `null` when the API responds with 404. */\n\tprotected async callOptional<T>(label: string, request: RequestFn): Promise<T | null> {\n\t\ttry {\n\t\t\treturn await this.call<T>(label, request);\n\t\t} catch (err) {\n\t\t\tif (err instanceof ApiError && err.statusCode === 404) return null;\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\t/** Execute an HTTP call that returns binary data (artifact downloads). */\n\tprotected async callBinary(\n\t\tlabel: string,\n\t\trequest: () => Promise<AxiosResponse<ArrayBuffer>>,\n\t): Promise<Buffer> {\n\t\ttry {\n\t\t\tconst response = await request();\n\t\t\treturn Buffer.from(response.data);\n\t\t} catch (err) {\n\t\t\tthrow toSdkError(err, label);\n\t\t}\n\t}\n\n\t/** Execute a paginated list call and attach meta from `X-Pagination-*` headers. */\n\tprotected async callList<T>(label: string, request: RequestFn): Promise<PaginatedResult<T>> {\n\t\ttry {\n\t\t\tconst response = await request();\n\t\t\tconst unwrapped = handleAssinafyResponse<T[] | { data?: T[] }>(response.data);\n\t\t\tlet data: T[];\n\t\t\tif (Array.isArray(unwrapped)) {\n\t\t\t\tdata = unwrapped;\n\t\t\t} else if (Array.isArray(unwrapped?.data)) {\n\t\t\t\tdata = (unwrapped as { data: T[] }).data;\n\t\t\t} else {\n\t\t\t\t// Fail loud: a shape we don't recognise means the API contract\n\t\t\t\t// drifted, not that there are genuinely zero results.\n\t\t\t\tthrow new ValidationError(`Unexpected list response shape for ${label}`, {\n\t\t\t\t\tresponse: unwrapped as unknown,\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst meta = parsePaginationMeta(response.headers);\n\t\t\treturn meta === undefined ? { data } : { data, meta };\n\t\t} catch (err) {\n\t\t\tthrow toSdkError(err, label);\n\t\t}\n\t}\n}\n\nfunction safeIdentifier(value: string, name: string): string {\n\tif (value === '.' || value === '..' || /[\\s/?#\\\\%]/.test(value)) {\n\t\tthrow new ValidationError(`${name} contains invalid URL characters`);\n\t}\n\treturn value;\n}\n\ntype RequestFn = () => Promise<AxiosResponse>;\n\nfunction parsePaginationMeta(\n\theaders: AxiosResponseHeaders | Record<string, unknown> | undefined,\n): PaginationMeta | undefined {\n\tif (!headers) return undefined;\n\n\tconst read = (key: string): string | undefined => {\n\t\tconst h = headers as Record<string, unknown>;\n\t\tconst raw = h[key] ?? h[key.toLowerCase()];\n\t\tif (raw === undefined || raw === null) return undefined;\n\t\treturn Array.isArray(raw) ? String(raw[0]) : String(raw);\n\t};\n\n\tconst current = toInt(read('x-pagination-current-page'));\n\tconst perPage = toInt(read('x-pagination-per-page'));\n\tconst total = toInt(read('x-pagination-total-count'));\n\tconst lastPage = toInt(read('x-pagination-page-count'));\n\n\tif (\n\t\tcurrent === undefined &&\n\t\tperPage === undefined &&\n\t\ttotal === undefined &&\n\t\tlastPage === undefined\n\t) {\n\t\treturn undefined;\n\t}\n\n\tconst meta: PaginationMeta = {};\n\tif (current !== undefined) meta.current_page = current;\n\tif (perPage !== undefined) meta.per_page = perPage;\n\tif (total !== undefined) meta.total = total;\n\tif (lastPage !== undefined) meta.last_page = lastPage;\n\treturn meta;\n}\n\nfunction toInt(value: string | undefined): number | undefined {\n\tif (value === undefined) return undefined;\n\tconst n = Number.parseInt(value, 10);\n\treturn Number.isFinite(n) ? n : undefined;\n}\n","import { ValidationError } from '../errors.js';\nimport type {\n\tIAssignment,\n\tIAssignmentListParams,\n\tICreateAssignmentPayload,\n\tICreateAssignmentResponse,\n\tIdentityVerificationImageName,\n\tIEstimateCostResponse,\n\tIIdentityReviewPayload,\n\tIResendCostEstimate,\n\tIResendEmailResponse,\n\tISignerIdentityReview,\n\tIWhatsAppNotification,\n\tPaginatedResult,\n\tSignerReference,\n} from '../types.js';\nimport {\n\tcleanParams,\n\trequireIso8601,\n\trequireSort,\n\tstripEmpty,\n\tvalidateSignerOptions,\n\tvalidateSigningSteps,\n} from '../utils.js';\nimport { BaseResource } from './base.js';\n\n/**\n * Normalise an assignment payload into the shape the API expects:\n * `signers: [{ id }]` plus optional docs-level fields.\n */\nexport function buildAssignmentPayload(\n\tpayload: ICreateAssignmentPayload,\n\toptions: {\n\t\tallowSignersWithoutId?: boolean;\n\t\tskipDigitalCertificateStepValidation?: boolean;\n\t} = {},\n): Record<string, unknown> {\n\tif (\n\t\tpayload.method !== undefined &&\n\t\tpayload.method !== 'virtual' &&\n\t\tpayload.method !== 'collect'\n\t) {\n\t\tthrow new ValidationError('method must be virtual or collect');\n\t}\n\tconst signers = extractSignerRefs(payload);\n\t// The docs mark `signers` \"Required for virtual\" only, but the API prices per signer in both\n\t// modes and answers a signer-less body with\n\t// 400 \"Pelo menos um signatários precisa ser informado.\" A collect estimate needs them too.\n\tif (signers.length === 0) {\n\t\tthrow new ValidationError('At least one signer is required', {\n\t\t\tsigners: payload.signers ?? payload.signer_ids ?? payload.signerIds,\n\t\t});\n\t}\n\tif (payload.method === 'collect' && !Array.isArray(payload.entries)) {\n\t\tthrow new ValidationError('entries are required for collect assignments');\n\t}\n\n\tconst normalisedSigners = signers.map((ref) => normaliseSignerRef(ref, options));\n\tif (!options.skipDigitalCertificateStepValidation) {\n\t\tvalidateSigningSteps(normalisedSigners);\n\t}\n\n\treturn stripEmpty({\n\t\tmethod: payload.method ?? 'virtual',\n\t\tsigners: normalisedSigners,\n\t\tmessage: payload.message,\n\t\texpires_at:\n\t\t\tpayload.expires_at === undefined\n\t\t\t\t? undefined\n\t\t\t\t: requireIso8601(payload.expires_at, 'expires_at'),\n\t\tcopy_receivers: payload.copy_receivers,\n\t\tentries: payload.entries,\n\t});\n}\n\nfunction extractSignerRefs(payload: ICreateAssignmentPayload): SignerReference[] {\n\tconst populatedAliases = [payload.signers, payload.signer_ids, payload.signerIds].filter(\n\t\t(value) => Array.isArray(value) && value.length > 0,\n\t);\n\tif (populatedAliases.length > 1) {\n\t\tthrow new ValidationError('Provide only one of signers, signer_ids, or signerIds');\n\t}\n\tif (Array.isArray(payload.signers) && payload.signers.length > 0) {\n\t\treturn payload.signers;\n\t}\n\n\tconst legacy = payload.signer_ids ?? payload.signerIds;\n\treturn Array.isArray(legacy) ? legacy : [];\n}\n\nfunction normaliseSignerRef(\n\tref: SignerReference,\n\toptions: { allowSignersWithoutId?: boolean },\n): { id?: string; verification_method?: string; notification_methods?: string[]; step?: number } {\n\tif (typeof ref === 'string') {\n\t\tif (!ref) throw new ValidationError('Signer ID cannot be empty');\n\t\treturn { id: ref };\n\t}\n\tif (ref && typeof ref === 'object') {\n\t\tconst input = ref as {\n\t\t\tid?: string;\n\t\t\tsigner_id?: string;\n\t\t\tverification_method?: string;\n\t\t\tnotification_methods?: string[];\n\t\t\tstep?: number;\n\t\t};\n\t\tconst id = input.id ?? input.signer_id;\n\t\tvalidateSignerOptions(input);\n\t\tconst normalised = stripEmpty({\n\t\t\tid,\n\t\t\tverification_method: input.verification_method,\n\t\t\tnotification_methods: input.notification_methods,\n\t\t\tstep: input.step,\n\t\t});\n\n\t\tif (typeof id === 'string' && id.length > 0) {\n\t\t\treturn normalised as {\n\t\t\t\tid: string;\n\t\t\t\tverification_method?: string;\n\t\t\t\tnotification_methods?: string[];\n\t\t\t};\n\t\t}\n\n\t\tif (options.allowSignersWithoutId && Object.keys(normalised).length > 0) {\n\t\t\treturn normalised as { verification_method?: string; notification_methods?: string[] };\n\t\t}\n\n\t\tif (options.allowSignersWithoutId && Object.keys(normalised).length === 0) {\n\t\t\treturn {};\n\t\t}\n\t}\n\tthrow new ValidationError('Invalid signer reference', { ref: ref as unknown });\n}\n\nexport class AssignmentResource extends BaseResource {\n\t/** Fetch an account review and available evidence for a signer's identity verification. */\n\tasync getIdentityVerification(\n\t\tdocumentId: string,\n\t\tassignmentId: string,\n\t\tsignerId: string,\n\t): Promise<ISignerIdentityReview> {\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\tconst asgId = this.requireId(assignmentId, 'Assignment ID');\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\treturn this.call('Failed to fetch signer identity review', () =>\n\t\t\tthis.http.get(\n\t\t\t\t`/documents/${docId}/assignments/${asgId}/signers/${sid}/identity-verification`,\n\t\t\t),\n\t\t);\n\t}\n\n\t/** Download JPEG/PNG evidence or the document PDF, available only while the review is open. */\n\tasync downloadIdentityVerificationImage(\n\t\tdocumentId: string,\n\t\tassignmentId: string,\n\t\tsignerId: string,\n\t\tname: IdentityVerificationImageName,\n\t): Promise<Buffer> {\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\tconst asgId = this.requireId(assignmentId, 'Assignment ID');\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\tif (!['document_front', 'document_back', 'document_pdf', 'face'].includes(name)) {\n\t\t\tthrow new ValidationError('Unknown identity verification image name');\n\t\t}\n\t\treturn this.callBinary('Failed to download identity review image', () =>\n\t\t\tthis.http.get<ArrayBuffer>(\n\t\t\t\t`/documents/${docId}/assignments/${asgId}/signers/${sid}/identity-verification/images/${name}`,\n\t\t\t\t{ responseType: 'arraybuffer' },\n\t\t\t),\n\t\t);\n\t}\n\n\t/** Approve certification or reject/cancel the document; the optional note is private to reviewers. */\n\tasync reviewIdentityVerification(\n\t\tdocumentId: string,\n\t\tassignmentId: string,\n\t\tsignerId: string,\n\t\tpayload: IIdentityReviewPayload,\n\t): Promise<ISignerIdentityReview> {\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\tconst asgId = this.requireId(assignmentId, 'Assignment ID');\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\tif (!payload || !['Approved', 'Rejected'].includes(payload.decision)) {\n\t\t\tthrow new ValidationError('decision must be Approved or Rejected');\n\t\t}\n\t\tif (\n\t\t\tpayload.note != null &&\n\t\t\t(typeof payload.note !== 'string' || [...payload.note].length > 2000)\n\t\t) {\n\t\t\tthrow new ValidationError('note must contain at most 2000 characters');\n\t\t}\n\t\treturn this.call('Failed to decide signer identity review', () =>\n\t\t\tthis.http.post(\n\t\t\t\t`/documents/${docId}/assignments/${asgId}/signers/${sid}/identity-verification/review`,\n\t\t\t\t{ decision: payload.decision, note: payload.note },\n\t\t\t),\n\t\t);\n\t}\n\n\t/**\n\t * List assignments across the account (`GET /assignments`).\n\t *\n\t * The endpoint is account-scoped via a required `accountId` query parameter\n\t * (note the camelCase — it differs from the path style used elsewhere).\n\t * Supports `page` / `per-page`; `created_at` sorting is live-verified.\n\t */\n\tasync list(\n\t\tparams: IAssignmentListParams = {},\n\t\taccountId?: string,\n\t): Promise<PaginatedResult<IAssignment>> {\n\t\tconst id = this.accountId(accountId);\n\t\tif ('search' in params) throw new ValidationError('assignment search is not supported');\n\t\trequireSort(params.sort, ['created_at', '-created_at']);\n\t\treturn this.callList<IAssignment>('Failed to list assignments', () =>\n\t\t\tthis.http.get('/assignments', { params: cleanParams({ ...params, accountId: id }) }),\n\t\t);\n\t}\n\n\t/** Create a signing assignment for a document. */\n\tasync create(\n\t\tdocumentId: string,\n\t\tpayload: ICreateAssignmentPayload,\n\t): Promise<ICreateAssignmentResponse> {\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\t// buildAssignmentPayload normalises (and validates non-empty) the signer\n\t\t// list; reuse its output for the count instead of extracting twice.\n\t\tconst body = buildAssignmentPayload(payload);\n\t\tthis.logger.info('Creating assignment', {\n\t\t\tdocumentId: docId,\n\t\t\tsigners: (body.signers as unknown[]).length,\n\t\t});\n\t\treturn this.call('Failed to create assignment', () =>\n\t\t\tthis.http.post(`/documents/${docId}/assignments`, body),\n\t\t);\n\t}\n\n\t/** Estimate the cost (in credits) of creating the assignment. */\n\tasync estimateCost(\n\t\tdocumentId: string,\n\t\tpayload: ICreateAssignmentPayload,\n\t): Promise<IEstimateCostResponse> {\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\treturn this.call('Failed to estimate assignment cost', () =>\n\t\t\tthis.http.post(\n\t\t\t\t`/documents/${docId}/assignments/estimate-cost`,\n\t\t\t\tbuildAssignmentPayload(payload, {\n\t\t\t\t\tallowSignersWithoutId: true,\n\t\t\t\t\tskipDigitalCertificateStepValidation: true,\n\t\t\t\t}),\n\t\t\t),\n\t\t);\n\t}\n\n\t/**\n\t * Update the expiration date of an existing assignment.\n\t * The published API accepts an ISO 8601 timestamp. Deployments that support\n\t * clearing an expiration also accept `null`.\n\t */\n\tasync resetExpiration(\n\t\tdocumentId: string,\n\t\tassignmentId: string,\n\t\texpiresAt: string | null,\n\t): Promise<IAssignment> {\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\tconst asgId = this.requireId(assignmentId, 'Assignment ID');\n\t\tif (expiresAt !== null) requireIso8601(expiresAt, 'expiresAt');\n\t\t// `null` is meaningful here (\"no expiration\"), so don't strip it.\n\t\treturn this.call('Failed to update assignment expiration', () =>\n\t\t\tthis.http.put(`/documents/${docId}/assignments/${asgId}/reset-expiration`, {\n\t\t\t\texpires_at: expiresAt,\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** Resend the signing notification to a single signer. */\n\tasync resendNotification(\n\t\tdocumentId: string,\n\t\tassignmentId: string,\n\t\tsignerId: string,\n\t): Promise<IResendEmailResponse> {\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\tconst asgId = this.requireId(assignmentId, 'Assignment ID');\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\treturn this.call('Failed to resend signer notification', () =>\n\t\t\tthis.http.put(`/documents/${docId}/assignments/${asgId}/signers/${sid}/resend`),\n\t\t);\n\t}\n\n\t/** Estimate the cost of resending a signer notification. */\n\tasync estimateResendCost(\n\t\tdocumentId: string,\n\t\tassignmentId: string,\n\t\tsignerId: string,\n\t): Promise<IResendCostEstimate> {\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\tconst asgId = this.requireId(assignmentId, 'Assignment ID');\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\treturn this.call('Failed to estimate resend cost', () =>\n\t\t\tthis.http.post(\n\t\t\t\t`/documents/${docId}/assignments/${asgId}/signers/${sid}/estimate-resend-cost`,\n\t\t\t),\n\t\t);\n\t}\n\n\t/**\n\t * `GET /documents/{documentId}/assignments/{assignmentId}/whatsapp-notifications`\n\t * — list every WhatsApp notification rendered + sent for an assignment.\n\t */\n\tasync listWhatsAppNotifications(\n\t\tdocumentId: string,\n\t\tassignmentId: string,\n\t): Promise<IWhatsAppNotification[]> {\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\tconst asgId = this.requireId(assignmentId, 'Assignment ID');\n\t\treturn this.call('Failed to list WhatsApp notifications', () =>\n\t\t\tthis.http.get(`/documents/${docId}/assignments/${asgId}/whatsapp-notifications`),\n\t\t);\n\t}\n}\n","import { ValidationError } from '../errors.js';\nimport type {\n\tIApiKeyResponse,\n\tIEmptyResult,\n\tILoginResponse,\n\tIMaskedApiKeyResponse,\n\tIMfaReauthPayload,\n\tIMfaRecoveryCodes,\n\tIMfaStatus,\n\tIMfaVerifyPayload,\n\tIStatusResponse,\n\tITotpConfirmPayload,\n\tITotpEnrollment,\n\tSocialLoginProvider,\n} from '../types.js';\nimport { publicRequestConfig } from '../utils.js';\nimport { BaseResource } from './base.js';\n\n/** Two-factor re-authentication requires the password or a live/recovery code. */\nfunction requireReauth(payload: IMfaReauthPayload): IMfaReauthPayload {\n\tif (!payload?.password && !payload?.code) {\n\t\tthrow new ValidationError('password or code is required');\n\t}\n\treturn payload;\n}\n\n/**\n * Authentication endpoints (login, two-factor, social login, password\n * management), personal API key management (`/users/api-keys`), and\n * two-factor enrollment (`/users/self/mfa`).\n *\n * Most of these endpoints are intended to bootstrap an authenticated session\n * for a human user. Production server-to-server integrations should use\n * `X-Api-Key` and skip this resource entirely.\n */\nexport class AuthenticationResource extends BaseResource {\n\t/** `POST /login` — exchange email + password for a JWT access token. */\n\tasync login(email: string, password: string): Promise<ILoginResponse> {\n\t\tif (!email) throw new ValidationError('email is required');\n\t\tif (!password) throw new ValidationError('password is required');\n\t\treturn this.call('Login failed', () =>\n\t\t\tthis.http.post('/login', { email, password }, publicRequestConfig()),\n\t\t);\n\t}\n\n\t/**\n\t * `POST /authentication/mfa/verify` — exchange the login `mfa_token` and an\n\t * authenticator or recovery code for an access token. The challenge is\n\t * single-use and expires 5 minutes after login.\n\t */\n\tasync verifyMfa(payload: IMfaVerifyPayload): Promise<ILoginResponse> {\n\t\tif (!payload?.mfa_token) throw new ValidationError('mfa_token is required');\n\t\tif (!payload.code?.trim()) throw new ValidationError('code is required');\n\t\treturn this.call('Two-factor verification failed', () =>\n\t\t\tthis.http.post(\n\t\t\t\t'/authentication/mfa/verify',\n\t\t\t\t{ mfa_token: payload.mfa_token, code: payload.code.trim() },\n\t\t\t\tpublicRequestConfig(),\n\t\t\t),\n\t\t);\n\t}\n\n\t/** `GET /users/self/mfa` — enrolled two-factor methods and remaining recovery codes. */\n\tasync listMfaMethods(): Promise<IMfaStatus> {\n\t\treturn this.call('Failed to list two-factor methods', () => this.http.get('/users/self/mfa'));\n\t}\n\n\t/**\n\t * `POST /users/self/mfa/totp` — start authenticator enrollment. The secret\n\t * and provisioning URI are returned only once; two-factor stays inactive\n\t * until {@link confirmTotpEnrollment}.\n\t */\n\tasync startTotpEnrollment(label?: string): Promise<ITotpEnrollment> {\n\t\treturn this.call('Failed to start authenticator enrollment', () =>\n\t\t\tthis.http.post('/users/self/mfa/totp', label ? { label } : {}),\n\t\t);\n\t}\n\n\t/**\n\t * `PUT /users/self/mfa/totp/confirm` — activate the method with a live code\n\t * and receive one-time recovery codes. Replacing a confirmed method also\n\t * requires `password` or `reauth_code`.\n\t */\n\tasync confirmTotpEnrollment(payload: ITotpConfirmPayload): Promise<IMfaRecoveryCodes> {\n\t\tif (!payload?.id) throw new ValidationError('id is required');\n\t\tif (!payload.code?.trim()) throw new ValidationError('code is required');\n\t\treturn this.call('Failed to confirm authenticator enrollment', () =>\n\t\t\tthis.http.put('/users/self/mfa/totp/confirm', payload),\n\t\t);\n\t}\n\n\t/** `POST /users/self/mfa/recovery-codes` — issue ten new recovery codes, invalidating the old set. */\n\tasync regenerateRecoveryCodes(payload: IMfaReauthPayload): Promise<IMfaRecoveryCodes> {\n\t\treturn this.call('Failed to regenerate recovery codes', () =>\n\t\t\tthis.http.post('/users/self/mfa/recovery-codes', requireReauth(payload)),\n\t\t);\n\t}\n\n\t/**\n\t * `DELETE /users/self/mfa/{methodId}` — remove a method. Removing the last\n\t * one also discards the recovery codes.\n\t */\n\tasync removeMfaMethod(\n\t\tmethodId: string,\n\t\tpayload: IMfaReauthPayload,\n\t): Promise<{ is_mfa_enabled: boolean }> {\n\t\tconst id = this.requireId(methodId, 'Method ID');\n\t\tconst data = requireReauth(payload);\n\t\treturn this.call('Failed to remove two-factor method', () =>\n\t\t\tthis.http.delete(`/users/self/mfa/${id}`, { data }),\n\t\t);\n\t}\n\n\t/** `POST /authentication/social-login` — exchange a provider token for an Assinafy JWT. */\n\tasync socialLogin(payload: {\n\t\tprovider: SocialLoginProvider;\n\t\ttoken: string;\n\t\thas_accepted_terms: boolean;\n\t}): Promise<ILoginResponse> {\n\t\tif (payload.provider !== 'google') throw new ValidationError('provider must be google');\n\t\tif (!payload.token) throw new ValidationError('token is required');\n\t\treturn this.call('Social login failed', () =>\n\t\t\tthis.http.post('/authentication/social-login', payload, publicRequestConfig()),\n\t\t);\n\t}\n\n\t/** `POST /auth/link-social-login` — link a Google identity to the current user. */\n\tasync linkSocialLogin(payload: {\n\t\tprovider: SocialLoginProvider;\n\t\ttoken: string;\n\t}): Promise<IStatusResponse> {\n\t\tif (payload.provider !== 'google') throw new ValidationError('provider must be google');\n\t\tif (!payload.token) throw new ValidationError('token is required');\n\t\treturn this.call('Failed to link social login', () =>\n\t\t\tthis.http.post('/auth/link-social-login', payload),\n\t\t);\n\t}\n\n\t/** `POST /users/api-keys` — generate (and rotate) the current user's API key. */\n\tasync createApiKey(password: string): Promise<IApiKeyResponse> {\n\t\tif (!password) throw new ValidationError('password is required');\n\t\treturn this.call('Failed to create API key', () =>\n\t\t\tthis.http.post('/users/api-keys', { password }),\n\t\t);\n\t}\n\n\t/**\n\t * `GET /users/api-keys` — fetch a masked version of the current API key, or\n\t * `null` if no key has been generated yet.\n\t */\n\tasync getApiKey(): Promise<IMaskedApiKeyResponse> {\n\t\t// Use callOptional so a 404 (\"no key generated yet\") resolves to null —\n\t\t// matching this method's documented contract — instead of throwing.\n\t\tconst result = await this.callOptional<IMaskedApiKeyResponse>('Failed to fetch API key', () =>\n\t\t\tthis.http.get('/users/api-keys'),\n\t\t);\n\t\treturn result ?? null;\n\t}\n\n\t/** `DELETE /users/api-keys` — revoke the current API key. */\n\tasync deleteApiKey(): Promise<IEmptyResult> {\n\t\treturn this.call('Failed to delete API key', () => this.http.delete('/users/api-keys'));\n\t}\n\n\t/** `PUT /authentication/change-password` — change the authenticated user's password. */\n\tasync changePassword(payload: {\n\t\temail: string;\n\t\tpassword: string;\n\t\tnew_password: string;\n\t}): Promise<{ email: string }> {\n\t\tif (!payload.email) throw new ValidationError('email is required');\n\t\tif (!payload.password) throw new ValidationError('password is required');\n\t\tif (!payload.new_password) throw new ValidationError('new_password is required');\n\t\treturn this.call('Failed to change password', () =>\n\t\t\tthis.http.put('/authentication/change-password', payload),\n\t\t);\n\t}\n\n\t/** `PUT /authentication/request-password-reset` — email a reset link to the user. */\n\tasync requestPasswordReset(email: string): Promise<{ email: string }> {\n\t\tif (!email) throw new ValidationError('email is required');\n\t\treturn this.call('Failed to request password reset', () =>\n\t\t\tthis.http.put('/authentication/request-password-reset', { email }, publicRequestConfig()),\n\t\t);\n\t}\n\n\t/** `PUT /authentication/reset-password` — complete a password reset using the emailed token. */\n\tasync resetPassword(payload: {\n\t\temail: string;\n\t\ttoken?: string;\n\t\tnew_password: string;\n\t}): Promise<{ email: string }> {\n\t\tif (!payload.email) throw new ValidationError('email is required');\n\t\tif (!payload.new_password) throw new ValidationError('new_password is required');\n\t\treturn this.call('Failed to reset password', () =>\n\t\t\tthis.http.put('/authentication/reset-password', payload, publicRequestConfig()),\n\t\t);\n\t}\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { ApiError, ValidationError } from '../errors.js';\nimport type {\n\tDocumentArtifactName,\n\tDocumentStatus,\n\tICreateDocumentFromTemplateOptions,\n\tIDetachTagResponse,\n\tIDocumentActivity,\n\tIDocumentDetailsResponse,\n\tIDocumentListItem,\n\tIDocumentListParams,\n\tIDocumentListResponse,\n\tIDocumentSearchParams,\n\tIDocumentStatusInfo,\n\tIDocumentUploadResponse,\n\tIDocumentVerifyResponse,\n\tIEmptyResult,\n\tIEstimateCostResponse,\n\tIPublicDocumentInfo,\n\tISendTokenResponse,\n\tISigningProgress,\n\tITag,\n\tITemplateCostSigner,\n\tITemplateSigner,\n\tSendTokenChannel,\n} from '../types.js';\nimport {\n\tappendFilePart,\n\tcleanParams,\n\tpublicRequestConfig,\n\trequireDocumentArtifactName,\n\trequireEmail,\n\trequireIso8601,\n\trequireSort,\n\tvalidateSignerOptions,\n\tvalidateSigningSteps,\n} from '../utils.js';\nimport { BaseResource } from './base.js';\n\nconst MAX_UPLOAD_BYTES = 25 * 1024 * 1024;\n\nconst DOCUMENT_SORTS = ['name', '-name', 'updated_at', '-updated_at'] as const;\n\nconst READY_STATUSES: ReadonlySet<DocumentStatus | string> = new Set([\n\t'metadata_ready',\n\t'pending_signature',\n\t'pending_identity_review',\n\t'certificated',\n]);\n\nconst FAILED_STATUSES: ReadonlySet<DocumentStatus | string> = new Set([\n\t'failed',\n\t'rejected_by_signer',\n\t'rejected_by_user',\n\t'expired',\n]);\n\n/** Input for uploading a document: either an on-disk file or an in-memory buffer. */\nexport type DocumentUploadSource =\n\t| { filePath: string; fileName?: string }\n\t| { buffer: Buffer; fileName: string };\n\nexport interface IDocumentUploadOptions {\n\t/** Document display name. Defaults to the source PDF file name. */\n\tname?: string;\n\t/** Optional metadata sent alongside the file (JSON-encoded). */\n\tmetadata?: Record<string, unknown>;\n\t/** Override the default account ID configured on the client. */\n\taccountId?: string;\n}\n\nexport class DocumentResource extends BaseResource {\n\t/**\n\t * Upload a PDF to the workspace.\n\t *\n\t * @example\n\t * ```ts\n\t * await client.documents.upload({ filePath: './contract.pdf' });\n\t * await client.documents.upload({ buffer, fileName: 'contract.pdf' }, { metadata });\n\t * ```\n\t */\n\tasync upload(\n\t\tsource: DocumentUploadSource,\n\t\toptions: IDocumentUploadOptions = {},\n\t): Promise<IDocumentUploadResponse> {\n\t\tconst { buffer, fileName } = await loadSource(source);\n\t\tvalidateUpload(buffer, fileName);\n\n\t\tconst accountId = this.accountId(options.accountId);\n\t\tconst form = buildUploadForm(buffer, fileName, options.name ?? fileName, options.metadata);\n\n\t\tthis.logger.info('Uploading document', { fileName, size: buffer.byteLength });\n\n\t\tconst document = await this.call<IDocumentUploadResponse>('Document upload failed', () =>\n\t\t\tthis.http.post(`/accounts/${accountId}/documents`, form, {\n\t\t\t\theaders: { 'Content-Type': 'multipart/form-data' },\n\t\t\t}),\n\t\t);\n\n\t\tif (!document?.id) {\n\t\t\tthrow new ValidationError('Upload succeeded but no document ID was returned', {\n\t\t\t\tresponse: document as unknown as Record<string, unknown>,\n\t\t\t});\n\t\t}\n\t\tthis.logger.info('Document uploaded', { documentId: document.id });\n\t\treturn document;\n\t}\n\n\t/**\n\t * List workspace documents. Pagination info (if any) is attached in `meta`.\n\t * Supports `status`, `method`, `tags`, `search`, `sort`, `page`, `per_page`.\n\t */\n\tasync list(params: IDocumentListParams = {}, accountId?: string): Promise<IDocumentListResponse> {\n\t\tconst id = this.accountId(accountId);\n\t\trequireSort(params.sort, DOCUMENT_SORTS);\n\t\treturn this.callList<IDocumentListItem>('Failed to list documents', () =>\n\t\t\tthis.http.get(`/accounts/${id}/documents`, {\n\t\t\t\tparams: cleanParams(params as unknown as Record<string, unknown>),\n\t\t\t}),\n\t\t);\n\t}\n\n\t/**\n\t * Lightweight document search (`GET /accounts/{id}/documents/search`).\n\t *\n\t * A slimmer counterpart to {@link list} exposed by the API for\n\t * type-ahead/autocomplete. The published spec documents only `search`,\n\t * `status`, `page`, `per-page`, but `sort` is also accepted and functional\n\t * (live-verified against the sandbox).\n\t */\n\tasync search(\n\t\tparams: IDocumentSearchParams = {},\n\t\taccountId?: string,\n\t): Promise<IDocumentListResponse> {\n\t\tconst id = this.accountId(accountId);\n\t\trequireSort(params.sort, DOCUMENT_SORTS);\n\t\treturn this.callList<IDocumentListItem>('Failed to search documents', () =>\n\t\t\tthis.http.get(`/accounts/${id}/documents/search`, {\n\t\t\t\tparams: cleanParams(params as unknown as Record<string, unknown>),\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** Get document details. */\n\tasync details(documentId: string): Promise<IDocumentDetailsResponse> {\n\t\tconst id = this.requireId(documentId, 'Document ID');\n\t\treturn this.fetchDetails(id);\n\t}\n\n\t/**\n\t * Rename a document (`PATCH /documents/{id}`).\n\t *\n\t * Only permitted before the signature process starts — the API returns a\n\t * 400 once an assignment is active.\n\t */\n\tasync rename(documentId: string, name: string): Promise<IDocumentDetailsResponse> {\n\t\tconst id = this.requireId(documentId, 'Document ID');\n\t\tif (!name?.trim()) throw new ValidationError('name is required');\n\t\treturn this.call('Failed to rename document', () =>\n\t\t\tthis.http.patch(`/documents/${id}`, { name }),\n\t\t);\n\t}\n\n\t/** Alias for {@link details}. */\n\tasync get(documentId: string): Promise<IDocumentDetailsResponse> {\n\t\treturn this.details(documentId);\n\t}\n\n\t/** Poll document status until ready (or a terminal status / timeout). */\n\tasync waitUntilReady(\n\t\tdocumentId: string,\n\t\toptions: { maxWaitMs?: number; pollIntervalMs?: number } = {},\n\t): Promise<IDocumentDetailsResponse> {\n\t\tconst id = this.requireId(documentId, 'Document ID');\n\t\tconst maxWaitMs = options.maxWaitMs ?? 30_000;\n\t\tconst pollIntervalMs = options.pollIntervalMs ?? 2_000;\n\t\tif (!Number.isFinite(maxWaitMs) || maxWaitMs <= 0) {\n\t\t\tthrow new ValidationError('maxWaitMs must be a positive finite number');\n\t\t}\n\t\tif (!Number.isFinite(pollIntervalMs) || pollIntervalMs <= 0) {\n\t\t\tthrow new ValidationError('pollIntervalMs must be a positive finite number');\n\t\t}\n\t\tconst start = Date.now();\n\t\tlet attempts = 0;\n\n\t\tthis.logger.info('Waiting for document to be ready', { documentId: id, maxWaitMs });\n\n\t\twhile (Date.now() - start < maxWaitMs) {\n\t\t\tattempts++;\n\t\t\ttry {\n\t\t\t\tconst requestTimeoutMs = Math.max(1, maxWaitMs - (Date.now() - start));\n\t\t\t\tconst details = await this.fetchDetails(id, requestTimeoutMs);\n\t\t\t\tconst status = details.status ?? 'unknown';\n\t\t\t\tthis.logger.debug('Document status check', { attempts, status });\n\n\t\t\t\tif (READY_STATUSES.has(status)) return details;\n\t\t\t\tif (FAILED_STATUSES.has(status)) {\n\t\t\t\t\tthrow new ValidationError(`Document processing failed with status: ${status}`, {\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tif (err instanceof ValidationError) throw err;\n\t\t\t\t// A client-side error (bad/unknown id, unauthorized, forbidden) will\n\t\t\t\t// never become \"ready\" — surface it immediately instead of masking it\n\t\t\t\t// as a timeout after the full maxWaitMs. Keep retrying transient\n\t\t\t\t// failures (network blips, 5xx).\n\t\t\t\tif (err instanceof ApiError && err.statusCode >= 400 && err.statusCode < 500) {\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t\tthis.logger.warn('Error checking document status', {\n\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst remainingMs = maxWaitMs - (Date.now() - start);\n\t\t\tif (remainingMs <= 0) break;\n\t\t\tawait sleep(Math.min(pollIntervalMs, remainingMs));\n\t\t}\n\n\t\tthrow new ValidationError('Timeout waiting for document to be ready', {\n\t\t\tdocumentId: id,\n\t\t\tattempts,\n\t\t});\n\t}\n\n\tprivate fetchDetails(documentId: string, timeout?: number): Promise<IDocumentDetailsResponse> {\n\t\treturn this.call('Failed to fetch document details', () =>\n\t\t\tthis.http.get(`/documents/${documentId}`, timeout === undefined ? undefined : { timeout }),\n\t\t);\n\t}\n\n\t/** Download a document artifact. Defaults to the certificated (signed) PDF. */\n\tasync download(\n\t\tdocumentId: string,\n\t\tartifactName: DocumentArtifactName = 'certificated',\n\t): Promise<Buffer> {\n\t\tconst id = this.requireId(documentId, 'Document ID');\n\t\tconst artifact = requireDocumentArtifactName(artifactName);\n\t\treturn this.callBinary('Failed to download document', () =>\n\t\t\tthis.http.get<ArrayBuffer>(`/documents/${id}/download/${artifact}`, {\n\t\t\t\tresponseType: 'arraybuffer',\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** Download the document thumbnail. */\n\tasync thumbnail(documentId: string): Promise<Buffer> {\n\t\tconst id = this.requireId(documentId, 'Document ID');\n\t\treturn this.callBinary('Failed to download document thumbnail', () =>\n\t\t\tthis.http.get<ArrayBuffer>(`/documents/${id}/thumbnail`, { responseType: 'arraybuffer' }),\n\t\t);\n\t}\n\n\t/** Download a single page as a JPEG. */\n\tasync downloadPage(documentId: string, pageId: string): Promise<Buffer> {\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\tconst pid = this.requireId(pageId, 'Page ID');\n\t\treturn this.callBinary('Failed to download page', () =>\n\t\t\tthis.http.get<ArrayBuffer>(`/documents/${docId}/pages/${pid}/download`, {\n\t\t\t\tresponseType: 'arraybuffer',\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** Fetch the document activity log. */\n\tasync activities(documentId: string): Promise<IDocumentActivity[]> {\n\t\tconst id = this.requireId(documentId, 'Document ID');\n\t\tconst result = await this.call<IDocumentActivity[] | null>(\n\t\t\t'Failed to fetch document activities',\n\t\t\t() => this.http.get(`/documents/${id}/activities`),\n\t\t);\n\t\treturn result ?? [];\n\t}\n\n\t/** Delete a document. */\n\tasync delete(documentId: string): Promise<IEmptyResult> {\n\t\tconst id = this.requireId(documentId, 'Document ID');\n\t\treturn this.call('Failed to delete document', () => this.http.delete(`/documents/${id}`));\n\t}\n\n\t/** List the tags attached to a document. */\n\tasync listTags(documentId: string, accountId?: string): Promise<ITag[]> {\n\t\tconst accId = this.accountId(accountId);\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\treturn this.call('Failed to list document tags', () =>\n\t\t\tthis.http.get(`/accounts/${accId}/documents/${docId}/tags`),\n\t\t);\n\t}\n\n\t/**\n\t * Replace the document's tag set. Production accepts tag names and creates missing tags.\n\t * An empty array detaches all tags. Values are forwarded unchanged.\n\t */\n\tasync replaceTags(documentId: string, tags: string[], accountId?: string): Promise<ITag[]> {\n\t\tconst accId = this.accountId(accountId);\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\tif (!Array.isArray(tags)) throw new ValidationError('tags must be an array');\n\t\treturn this.call('Failed to replace document tags', () =>\n\t\t\tthis.http.put(`/accounts/${accId}/documents/${docId}/tags`, { tags }),\n\t\t);\n\t}\n\n\t/** Attach additional tag names without removing existing ones. Production creates missing tags. */\n\tasync addTags(documentId: string, tags: string[], accountId?: string): Promise<ITag[]> {\n\t\tconst accId = this.accountId(accountId);\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\tif (!Array.isArray(tags) || tags.length === 0) {\n\t\t\tthrow new ValidationError('tags must be a non-empty array');\n\t\t}\n\t\treturn this.call('Failed to add document tags', () =>\n\t\t\tthis.http.post(`/accounts/${accId}/documents/${docId}/tags`, { tags }),\n\t\t);\n\t}\n\n\t/** Detach a single tag from a document (the tag itself is not deleted). */\n\tasync detachTag(\n\t\tdocumentId: string,\n\t\ttagId: string,\n\t\taccountId?: string,\n\t): Promise<IDetachTagResponse> {\n\t\tconst accId = this.accountId(accountId);\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\tconst tid = this.requireId(tagId, 'Tag ID');\n\t\treturn this.call('Failed to detach document tag', () =>\n\t\t\tthis.http.delete(`/accounts/${accId}/documents/${docId}/tags/${tid}`),\n\t\t);\n\t}\n\n\t/**\n\t * Create a document from a template.\n\t *\n\t * @example\n\t * ```ts\n\t * await client.documents.createFromTemplate('tmpl_id', [\n\t * { role_id: 'role_id', id: 'signer_id', verification_method: 'Email', notification_methods: ['Email'] },\n\t * ], { name: 'My Contract' });\n\t * ```\n\t */\n\tasync createFromTemplate(\n\t\ttemplateId: string,\n\t\tsigners: ITemplateSigner[],\n\t\toptions: ICreateDocumentFromTemplateOptions = {},\n\t\taccountId?: string,\n\t): Promise<IDocumentDetailsResponse> {\n\t\tconst tmplId = this.requireId(templateId, 'Template ID');\n\t\tconst accId = this.accountId(accountId);\n\t\tvalidateTemplateSigners(signers, { requireId: true });\n\t\tif (options.expires_at !== undefined) requireIso8601(options.expires_at, 'expires_at');\n\t\tif (\n\t\t\toptions.editor_fields !== undefined &&\n\t\t\t(!Array.isArray(options.editor_fields) ||\n\t\t\t\toptions.editor_fields.some((field) => !field?.field_id || typeof field.value !== 'string'))\n\t\t) {\n\t\t\tthrow new ValidationError('editor_fields must contain field_id and value');\n\t\t}\n\t\tif (\n\t\t\toptions.tags !== undefined &&\n\t\t\t(!Array.isArray(options.tags) || options.tags.some((tag) => typeof tag !== 'string' || !tag))\n\t\t) {\n\t\t\tthrow new ValidationError('tags must contain non-empty tag names');\n\t\t}\n\t\tconst body: Record<string, unknown> = { ...options, signers };\n\t\tthis.logger.info('Creating document from template', { templateId: tmplId, accountId: accId });\n\t\treturn this.call('Failed to create document from template', () =>\n\t\t\tthis.http.post(`/accounts/${accId}/templates/${tmplId}/documents`, body),\n\t\t);\n\t}\n\n\t/** Estimate the credit cost of creating a document from a template. */\n\tasync estimateCostFromTemplate(\n\t\ttemplateId: string,\n\t\tsigners: ITemplateCostSigner[],\n\t\taccountId?: string,\n\t): Promise<IEstimateCostResponse> {\n\t\tconst tmplId = this.requireId(templateId, 'Template ID');\n\t\tconst accId = this.accountId(accountId);\n\t\tvalidateTemplateSigners(signers, { requireId: false });\n\t\treturn this.call('Failed to estimate cost from template', () =>\n\t\t\tthis.http.post(`/accounts/${accId}/templates/${tmplId}/documents/estimate-cost`, { signers }),\n\t\t);\n\t}\n\n\t/**\n\t * Verify a document by its signature hash. Always resolves (the API\n\t * returns `200` even for an unknown hash, with `is_valid: false`).\n\t */\n\tasync verify(hash: string): Promise<IDocumentVerifyResponse> {\n\t\tconst h = this.requireId(hash, 'Signature hash');\n\t\treturn this.call('Failed to verify document', () =>\n\t\t\tthis.http.get(`/documents/${h}/verify`, publicRequestConfig()),\n\t\t);\n\t}\n\n\t/**\n\t * `GET /documents/statuses` — list every possible document status with\n\t * its description and whether documents in that status can be deleted.\n\t */\n\tasync statuses(): Promise<IDocumentStatusInfo[]> {\n\t\treturn this.call('Failed to list document statuses', () =>\n\t\t\tthis.http.get('/documents/statuses'),\n\t\t);\n\t}\n\n\t/**\n\t * `GET /public/documents/{document_id}` — public, unauthenticated lookup of\n\t * basic document info (used by the signing portal before the signer\n\t * authenticates via the access code).\n\t */\n\tasync getPublic(documentId: string): Promise<IPublicDocumentInfo> {\n\t\tconst id = this.requireId(documentId, 'Document ID');\n\t\treturn this.call('Failed to fetch public document info', () =>\n\t\t\tthis.http.get(`/public/documents/${id}`, publicRequestConfig()),\n\t\t);\n\t}\n\n\t/**\n\t * `PUT /public/documents/{document_id}/send-token` — email a one-time access\n\t * token to a signer who has not signed a pending document yet. The API sends\n\t * `{ channel: 'email', recipient }`; only the `email` channel is accepted.\n\t * The `{ email }` form is kept for existing callers and sends the same body.\n\t */\n\tasync sendToken(\n\t\tdocumentId: string,\n\t\trecipient: string | { email: string },\n\t\tchannel: SendTokenChannel = 'email',\n\t): Promise<ISendTokenResponse> {\n\t\tconst id = this.requireId(documentId, 'Document ID');\n\t\tconst email = typeof recipient === 'object' ? recipient?.email : recipient;\n\t\tif (channel !== 'email') throw new ValidationError('channel must be email');\n\t\trequireEmail(email);\n\t\treturn this.call('Failed to send signing token', () =>\n\t\t\tthis.http.put(\n\t\t\t\t`/public/documents/${id}/send-token`,\n\t\t\t\t{ channel, recipient: email },\n\t\t\t\tpublicRequestConfig(),\n\t\t\t),\n\t\t);\n\t}\n\n\t/** Quick check: has every signer completed their assignment? */\n\tasync isFullySigned(documentId: string): Promise<boolean> {\n\t\tconst details = await this.details(documentId);\n\t\tif (details.status === 'certificated') return true;\n\t\tconst summary = details.assignment?.summary;\n\t\tif (summary && typeof summary.signer_count === 'number') {\n\t\t\treturn summary.signer_count > 0 && summary.signer_count === summary.completed_count;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/** Summarise signing progress for UI display. */\n\tasync getSigningProgress(documentId: string): Promise<ISigningProgress> {\n\t\tconst details = await this.details(documentId);\n\t\tconst summary = details.assignment?.summary;\n\t\tconst total = summary?.signer_count ?? details.assignment?.signers?.length ?? 0;\n\t\tconst signed = summary?.completed_count ?? 0;\n\t\tconst pending = Math.max(total - signed, 0);\n\t\tconst percentage = total > 0 ? Math.round((signed / total) * 10_000) / 100 : 0;\n\t\treturn { signed, total, pending, percentage };\n\t}\n}\n\nfunction validateTemplateSigners(signers: unknown, options: { requireId: boolean }): void {\n\tif (!Array.isArray(signers)) throw new ValidationError('signers must be an array');\n\tfor (const value of signers) {\n\t\tif (!value || typeof value !== 'object') {\n\t\t\tthrow new ValidationError('each template signer must be an object');\n\t\t}\n\t\tconst signer = value as {\n\t\t\trole_id?: unknown;\n\t\t\tid?: unknown;\n\t\t\tverification_method?: unknown;\n\t\t\tnotification_methods?: unknown;\n\t\t\tstep?: unknown;\n\t\t};\n\t\tif (typeof signer.role_id !== 'string' || !signer.role_id) {\n\t\t\tthrow new ValidationError('each template signer requires role_id');\n\t\t}\n\t\tif (\n\t\t\t(options.requireId || signer.id !== undefined) &&\n\t\t\t(typeof signer.id !== 'string' || !signer.id)\n\t\t) {\n\t\t\tthrow new ValidationError('each template signer requires a valid id');\n\t\t}\n\t\tvalidateSignerOptions(signer);\n\t\tif (options.requireId && signer.step !== undefined && Number(signer.step) < 1) {\n\t\t\tthrow new ValidationError('template signer step must be a positive integer');\n\t\t}\n\t}\n\tif (options.requireId) {\n\t\tvalidateSigningSteps(signers as Array<{ verification_method?: unknown; step?: unknown }>);\n\t}\n}\n\nasync function loadSource(\n\tsource: DocumentUploadSource,\n): Promise<{ buffer: Buffer; fileName: string }> {\n\tif ('buffer' in source) {\n\t\tif (!source.fileName) {\n\t\t\tthrow new ValidationError('fileName is required when uploading a Buffer');\n\t\t}\n\t\treturn { buffer: source.buffer, fileName: source.fileName };\n\t}\n\tif (!source.filePath) {\n\t\tthrow new ValidationError('filePath is required');\n\t}\n\tconst { size } = await fs.stat(source.filePath);\n\tif (size > MAX_UPLOAD_BYTES) {\n\t\tthrow new ValidationError('File size exceeds maximum allowed (25MB)', {\n\t\t\tfileSize: size,\n\t\t\tmaxSize: MAX_UPLOAD_BYTES,\n\t\t});\n\t}\n\tconst buffer = await fs.readFile(source.filePath);\n\treturn { buffer, fileName: source.fileName ?? path.basename(source.filePath) };\n}\n\nfunction validateUpload(buffer: Buffer, fileName: string): void {\n\tif (!buffer || buffer.byteLength === 0) {\n\t\tthrow new ValidationError('File buffer is empty', { fileName });\n\t}\n\tif (!fileName.toLowerCase().endsWith('.pdf')) {\n\t\tthrow new ValidationError('Only PDF files are supported', { fileName });\n\t}\n\tif (buffer.byteLength > MAX_UPLOAD_BYTES) {\n\t\tthrow new ValidationError('File size exceeds maximum allowed (25MB)', {\n\t\t\tfileSize: buffer.byteLength,\n\t\t\tmaxSize: MAX_UPLOAD_BYTES,\n\t\t});\n\t}\n}\n\nfunction buildUploadForm(\n\tbuffer: Buffer,\n\tfileName: string,\n\tname: string,\n\tmetadata: Record<string, unknown> | undefined,\n): FormData {\n\tconst form = new FormData();\n\tappendFilePart(form, buffer, 'application/pdf', fileName);\n\tform.append('name', name);\n\tif (metadata) {\n\t\tform.append('metadata', JSON.stringify(metadata));\n\t}\n\treturn form;\n}\n\nfunction sleep(ms: number): Promise<void> {\n\treturn new Promise((resolve) => setTimeout(resolve, ms));\n}\n","import { ValidationError } from '../errors.js';\nimport type {\n\tICreateFieldPayload,\n\tIEmptyResult,\n\tIFieldDefinition,\n\tIFieldType,\n\tIFieldValidateMultipleEntry,\n\tIFieldValidationResult,\n\tIUpdateFieldPayload,\n} from '../types.js';\nimport { cleanParams, signerAccessConfig } from '../utils.js';\nimport { BaseResource } from './base.js';\n\n/**\n * Custom field definitions used by `collect` assignments.\n *\n * Covers the full Field Definition section of the API docs:\n * - `POST /accounts/{id}/fields`\n * - `GET /accounts/{id}/fields`\n * - `GET /accounts/{id}/fields/{id}`\n * - `PUT /accounts/{id}/fields/{id}`\n * - `DELETE /accounts/{id}/fields/{id}`\n * - `POST /accounts/{id}/fields/{id}/validate?signer-access-code=…`\n * - `POST /accounts/{id}/fields/validate-multiple?signer-access-code=…`\n * - `GET /field-types`\n *\n * The `signer-access-code` query param on the two `validate*` endpoints isn't\n * in the published OpenAPI spec but is live-verified against the sandbox: a\n * bogus code returns 401, matching every other signer-access-code endpoint.\n */\nexport class FieldsResource extends BaseResource {\n\t/** Create a field definition. */\n\tasync create(payload: ICreateFieldPayload, accountId?: string): Promise<IFieldDefinition> {\n\t\tif (!payload.type) throw new ValidationError('field type is required');\n\t\tif (!payload.name) throw new ValidationError('field name is required');\n\t\tconst id = this.accountId(accountId);\n\t\treturn this.call('Failed to create field definition', () =>\n\t\t\tthis.http.post(`/accounts/${id}/fields`, payload),\n\t\t);\n\t}\n\n\t/**\n\t * List field definitions for the workspace.\n\t *\n\t * @param params.include_inactive return inactive fields too\n\t * @param params.include_standard also return `signature`, `initial`, `signatureDate`\n\t */\n\tasync list(\n\t\tparams: { include_inactive?: boolean; include_standard?: boolean } = {},\n\t\taccountId?: string,\n\t): Promise<IFieldDefinition[]> {\n\t\tconst id = this.accountId(accountId);\n\t\treturn this.call('Failed to list field definitions', () =>\n\t\t\tthis.http.get(`/accounts/${id}/fields`, {\n\t\t\t\tparams: cleanParams(params as Record<string, unknown>),\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** Get a single field definition by ID. */\n\tasync get(fieldId: string, accountId?: string): Promise<IFieldDefinition> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst fid = this.requireId(fieldId, 'Field ID');\n\t\treturn this.call('Failed to fetch field definition', () =>\n\t\t\tthis.http.get(`/accounts/${id}/fields/${fid}`),\n\t\t);\n\t}\n\n\t/** Update a field definition. */\n\tasync update(\n\t\tfieldId: string,\n\t\tpayload: IUpdateFieldPayload,\n\t\taccountId?: string,\n\t): Promise<IFieldDefinition> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst fid = this.requireId(fieldId, 'Field ID');\n\t\treturn this.call('Failed to update field definition', () =>\n\t\t\tthis.http.put(`/accounts/${id}/fields/${fid}`, payload),\n\t\t);\n\t}\n\n\t/** Delete a field definition. Fails if the field has been used. */\n\tasync delete(fieldId: string, accountId?: string): Promise<IEmptyResult> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst fid = this.requireId(fieldId, 'Field ID');\n\t\treturn this.call('Failed to delete field definition', () =>\n\t\t\tthis.http.delete(`/accounts/${id}/fields/${fid}`),\n\t\t);\n\t}\n\n\t/**\n\t * Validate a single value against a field definition.\n\t *\n\t * Pass `signerAccessCode` for signer-side validation (the typical use case);\n\t * omit it when the caller is authenticated via API key.\n\t */\n\tasync validate(\n\t\tfieldId: string,\n\t\tvalue: unknown,\n\t\toptions: { signerAccessCode?: string; accountId?: string } = {},\n\t): Promise<IFieldValidationResult> {\n\t\tconst id = this.accountId(options.accountId);\n\t\tconst fid = this.requireId(fieldId, 'Field ID');\n\t\tif (value === undefined) throw new ValidationError('value is required');\n\t\treturn this.call('Failed to validate field value', () =>\n\t\t\tthis.http.post(\n\t\t\t\t`/accounts/${id}/fields/${fid}/validate`,\n\t\t\t\t{ value },\n\t\t\t\tvalidationConfig(options.signerAccessCode),\n\t\t\t),\n\t\t);\n\t}\n\n\t/** Validate multiple values at once. */\n\tasync validateMultiple(\n\t\tentries: IFieldValidateMultipleEntry[],\n\t\toptions: { signerAccessCode?: string; accountId?: string } = {},\n\t): Promise<IFieldValidationResult[]> {\n\t\tif (!Array.isArray(entries) || entries.length === 0) {\n\t\t\tthrow new ValidationError('entries must be a non-empty array');\n\t\t}\n\t\tif (\n\t\t\tentries.some(\n\t\t\t\t(entry) =>\n\t\t\t\t\t!entry ||\n\t\t\t\t\ttypeof entry !== 'object' ||\n\t\t\t\t\ttypeof entry.field_id !== 'string' ||\n\t\t\t\t\t!entry.field_id ||\n\t\t\t\t\tentry.value === undefined,\n\t\t\t)\n\t\t) {\n\t\t\tthrow new ValidationError('each entry must contain field_id and value');\n\t\t}\n\t\tconst id = this.accountId(options.accountId);\n\t\treturn this.call('Failed to validate field values', () =>\n\t\t\tthis.http.post(\n\t\t\t\t`/accounts/${id}/fields/validate-multiple`,\n\t\t\t\tentries,\n\t\t\t\tvalidationConfig(options.signerAccessCode),\n\t\t\t),\n\t\t);\n\t}\n\n\t/** List the platform's supported field types. */\n\tasync listTypes(): Promise<IFieldType[]> {\n\t\treturn this.call('Failed to list field types', () => this.http.get('/field-types'));\n\t}\n}\n\nfunction validationConfig(signerAccessCode?: string) {\n\tif (signerAccessCode === undefined) return undefined;\n\tif (typeof signerAccessCode !== 'string' || !signerAccessCode.trim()) {\n\t\tthrow new ValidationError('signerAccessCode is required when supplied');\n\t}\n\treturn signerAccessConfig(signerAccessCode);\n}\n","import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';\nimport type { AxiosRequestConfig } from 'axios';\nimport { ValidationError } from '../errors.js';\nimport type {\n\tIOAuthAuthorizationOptions,\n\tIOAuthAuthorizationRequest,\n\tIOAuthAuthorizationServer,\n\tIOAuthProtectedResource,\n\tIOAuthRevokePayload,\n\tIOAuthTokenPayload,\n\tIOAuthTokenResponse,\n\tIOAuthUserInfo,\n} from '../types.js';\nimport { publicRequestConfig } from '../utils.js';\nimport { BaseResource } from './base.js';\n\n/** Token and revocation bodies are form-encoded (RFC 6749/7009); Axios omits undefined fields. */\nfunction formRequestConfig(): AxiosRequestConfig {\n\treturn publicRequestConfig({\n\t\theaders: { 'Content-Type': 'application/x-www-form-urlencoded' },\n\t});\n}\n\n/** OAuth 2.1 with S256 PKCE. Tokens are returned to the caller, never saved or retried. */\nexport class OAuthResource extends BaseResource {\n\t/** `GET /.well-known/oauth-protected-resource` at the API origin, outside `/v1`. */\n\tasync metadata(): Promise<IOAuthProtectedResource> {\n\t\treturn this.call('Failed to discover OAuth resource', () => {\n\t\t\tconst baseURL = this.http.defaults.baseURL;\n\t\t\tif (!baseURL) {\n\t\t\t\tthrow new ValidationError('A base URL is required to discover OAuth metadata');\n\t\t\t}\n\t\t\treturn this.http.get(\n\t\t\t\t'/.well-known/oauth-protected-resource',\n\t\t\t\tpublicRequestConfig({\n\t\t\t\t\tbaseURL: new URL(baseURL).origin,\n\t\t\t\t}),\n\t\t\t);\n\t\t});\n\t}\n\n\t/** Read RFC 8414 metadata from an HTTPS issuer and verify its issuer identity. */\n\tasync discovery(issuer: string): Promise<IOAuthAuthorizationServer> {\n\t\tconst url = httpsUrl(issuer, 'issuer');\n\t\tif (url.search || url.pathname !== '/') {\n\t\t\tthrow new ValidationError('issuer must be an HTTPS origin');\n\t\t}\n\t\tconst metadata = await this.call<IOAuthAuthorizationServer>(\n\t\t\t'Failed to discover OAuth authorization server',\n\t\t\t() =>\n\t\t\t\tthis.http.get(\n\t\t\t\t\t`${url.origin}/.well-known/oauth-authorization-server`,\n\t\t\t\t\tpublicRequestConfig(),\n\t\t\t\t),\n\t\t);\n\t\tif (metadata.issuer !== issuer) throw new ValidationError('OAuth issuer mismatch');\n\t\thttpsUrl(metadata.authorization_endpoint, 'authorization_endpoint');\n\t\treturn metadata;\n\t}\n\n\t/** Discover endpoints and create a fresh authorization URL, PKCE verifier, and state. */\n\tasync authorize(options: IOAuthAuthorizationOptions): Promise<IOAuthAuthorizationRequest> {\n\t\trequired(options.clientId, 'clientId');\n\t\thttpsUrl(options.redirectUri, 'redirectUri');\n\t\tif (\n\t\t\t!Array.isArray(options.scopes) ||\n\t\t\toptions.scopes.length === 0 ||\n\t\t\toptions.scopes.some(\n\t\t\t\t(scope) => typeof scope !== 'string' || !/^[\\x21\\x23-\\x5B\\x5D-\\x7E]+$/.test(scope),\n\t\t\t)\n\t\t) {\n\t\t\tthrow new ValidationError('scopes must contain non-empty OAuth scope names');\n\t\t}\n\t\tconst resource = await this.metadata();\n\t\tconst issuer = resource.authorization_servers?.[0];\n\t\tif (!issuer) throw new ValidationError('OAuth metadata has no authorization server');\n\t\thttpsUrl(resource.resource, 'resource');\n\t\tconst server = await this.discovery(issuer);\n\t\tconst codeVerifier = randomBytes(32).toString('base64url');\n\t\tconst state = randomBytes(32).toString('base64url');\n\t\tconst nonce = options.scopes.includes('openid')\n\t\t\t? randomBytes(32).toString('base64url')\n\t\t\t: undefined;\n\t\tconst url = new URL(server.authorization_endpoint);\n\t\tconst params = {\n\t\t\tresponse_type: 'code',\n\t\t\tclient_id: options.clientId,\n\t\t\tredirect_uri: options.redirectUri,\n\t\t\tscope: options.scopes.join(' '),\n\t\t\tstate,\n\t\t\tcode_challenge: createHash('sha256').update(codeVerifier).digest('base64url'),\n\t\t\tcode_challenge_method: 'S256',\n\t\t\tresource: resource.resource,\n\t\t};\n\t\tfor (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);\n\t\tif (nonce) url.searchParams.set('nonce', nonce);\n\t\treturn {\n\t\t\tauthorization_url: url.toString(),\n\t\t\tcode_verifier: codeVerifier,\n\t\t\tstate,\n\t\t\tissuer,\n\t\t\tclient_id: options.clientId,\n\t\t\tredirect_uri: options.redirectUri,\n\t\t\tresource: resource.resource,\n\t\t\t...(nonce ? { nonce } : {}),\n\t\t};\n\t}\n\n\t/** Validate callback URI, state, and issuer before exchanging its one-time code. */\n\tasync exchangeCode(\n\t\tcallbackUrl: string,\n\t\trequest: IOAuthAuthorizationRequest,\n\t\tclientSecret?: string,\n\t): Promise<IOAuthTokenResponse> {\n\t\tconst callback = httpsUrl(callbackUrl, 'callbackUrl');\n\t\tconst redirect = httpsUrl(request.redirect_uri, 'redirect_uri');\n\t\tif (\n\t\t\tcallback.origin !== redirect.origin ||\n\t\t\tcallback.pathname !== redirect.pathname ||\n\t\t\t[...new Set(redirect.searchParams.keys())].some((key) => {\n\t\t\t\tconst expected = redirect.searchParams.getAll(key);\n\t\t\t\tconst actual = callback.searchParams.getAll(key);\n\t\t\t\treturn (\n\t\t\t\t\texpected.length !== actual.length || expected.some((value, i) => value !== actual[i])\n\t\t\t\t);\n\t\t\t})\n\t\t) {\n\t\t\tthrow new ValidationError('OAuth callback does not match the registered redirect URI');\n\t\t}\n\t\tfor (const key of ['state', 'iss', 'code', 'error']) {\n\t\t\tif (callback.searchParams.getAll(key).length > 1) {\n\t\t\t\tthrow new ValidationError(`Duplicate OAuth callback parameter: ${key}`);\n\t\t\t}\n\t\t}\n\t\tconst actual = Buffer.from(callback.searchParams.get('state') ?? '');\n\t\tconst expected = Buffer.from(required(request.state, 'state'));\n\t\tif (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {\n\t\t\tthrow new ValidationError('OAuth state mismatch');\n\t\t}\n\t\tif (callback.searchParams.get('iss') !== request.issuer) {\n\t\t\tthrow new ValidationError('OAuth issuer mismatch');\n\t\t}\n\t\tif (callback.searchParams.has('code') === callback.searchParams.has('error')) {\n\t\t\tthrow new ValidationError('OAuth callback must contain exactly one of code or error');\n\t\t}\n\t\tif (callback.searchParams.has('error')) {\n\t\t\tconst error = callback.searchParams.get('error')!;\n\t\t\tconst oauthError =\n\t\t\t\terror.length > 0 && error.length <= 64 && !/[^a-z_]/.test(error) ? error : 'unknown_error';\n\t\t\tthrow new ValidationError(`OAuth authorization was declined or failed: ${oauthError}`, {\n\t\t\t\toauthError,\n\t\t\t});\n\t\t}\n\t\treturn this.token({\n\t\t\tgrant_type: 'authorization_code',\n\t\t\tcode: required(callback.searchParams.get('code'), 'code'),\n\t\t\tclient_id: request.client_id,\n\t\t\tclient_secret: clientSecret,\n\t\t\tredirect_uri: request.redirect_uri,\n\t\t\tcode_verifier: request.code_verifier,\n\t\t\tresource: request.resource,\n\t\t});\n\t}\n\n\t/**\n\t * `POST /oauth/token` — code exchange, refresh, or RFC 8693 token exchange; returns the flat OAuth JSON body.\n\t * A refresh must return a new `refresh_token`; otherwise this throws `ValidationError`.\n\t */\n\tasync token(payload: IOAuthTokenPayload): Promise<IOAuthTokenResponse> {\n\t\trequired(payload.client_id, 'client_id');\n\t\tif (payload.client_secret !== undefined) required(payload.client_secret, 'client_secret');\n\t\tif (payload.resource !== undefined) httpsUrl(payload.resource, 'resource');\n\t\tif (payload.grant_type === 'authorization_code') {\n\t\t\trequired(payload.code, 'code');\n\t\t\thttpsUrl(payload.redirect_uri, 'redirect_uri');\n\t\t\tif (\n\t\t\t\ttypeof payload.code_verifier !== 'string' ||\n\t\t\t\t!/^[A-Za-z0-9._~-]{43,128}$/.test(payload.code_verifier)\n\t\t\t) {\n\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t'code_verifier must contain 43–128 RFC 7636 unreserved characters',\n\t\t\t\t);\n\t\t\t}\n\t\t} else if (payload.grant_type === 'refresh_token') {\n\t\t\trequired(payload.refresh_token, 'refresh_token');\n\t\t} else if (payload.grant_type === TOKEN_EXCHANGE) {\n\t\t\trequired(payload.client_secret, 'client_secret');\n\t\t\thttpsUrl(required(payload.resource, 'resource'), 'resource');\n\t\t\trequired(payload.subject_token, 'subject_token');\n\t\t\tfor (const field of ['subject_token_type', 'requested_token_type'] as const) {\n\t\t\t\tconst value = payload[field];\n\t\t\t\tif (\n\t\t\t\t\t(value !== undefined || field === 'subject_token_type') &&\n\t\t\t\t\tvalue !== ACCESS_TOKEN_TYPE\n\t\t\t\t) {\n\t\t\t\t\tthrow new ValidationError(`${field} must be ${ACCESS_TOKEN_TYPE}`);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new ValidationError(\n\t\t\t\t`grant_type must be authorization_code, refresh_token or ${TOKEN_EXCHANGE}`,\n\t\t\t);\n\t\t}\n\t\tconst tokens = await this.call<IOAuthTokenResponse>('OAuth token request failed', () =>\n\t\t\tthis.http.post('/oauth/token', payload, formRequestConfig()),\n\t\t);\n\t\t// Refresh tokens rotate: a successful refresh has already retired the submitted token.\n\t\tconst next = tokens?.refresh_token;\n\t\tif (\n\t\t\tpayload.grant_type === 'refresh_token' &&\n\t\t\t(typeof next !== 'string' || !next.trim() || next === payload.refresh_token)\n\t\t) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'OAuth refresh response has no new refresh_token; the submitted refresh token may ' +\n\t\t\t\t\t'already be retired, so do not reuse it: reconnect instead',\n\t\t\t\t{ field: 'refresh_token' },\n\t\t\t);\n\t\t}\n\t\treturn tokens;\n\t}\n\n\t/** `POST /oauth/revoke` — revoke an access/refresh token; success has no required body. */\n\tasync revoke(payload: IOAuthRevokePayload): Promise<void> {\n\t\trequired(payload.client_id, 'client_id');\n\t\trequired(payload.token, 'token');\n\t\tif (payload.client_secret !== undefined) required(payload.client_secret, 'client_secret');\n\t\tif (\n\t\t\tpayload.token_type_hint !== undefined &&\n\t\t\t!['access_token', 'refresh_token'].includes(payload.token_type_hint)\n\t\t) {\n\t\t\tthrow new ValidationError('token_type_hint must be access_token or refresh_token');\n\t\t}\n\t\tawait this.call('OAuth revocation failed', () =>\n\t\t\tthis.http.post('/oauth/revoke', payload, formRequestConfig()),\n\t\t);\n\t}\n\n\t/** `GET /oauth/userinfo` — flat OIDC claims; requires a bearer token with `openid`. */\n\tasync userinfo(): Promise<IOAuthUserInfo> {\n\t\treturn this.call('Failed to fetch OAuth userinfo', () => this.http.get('/oauth/userinfo'));\n\t}\n}\n\nconst TOKEN_EXCHANGE = 'urn:ietf:params:oauth:grant-type:token-exchange';\nconst ACCESS_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';\n\nfunction required(value: unknown, name: string): string {\n\tif (typeof value !== 'string' || !value.trim()) throw new ValidationError(`${name} is required`);\n\treturn value;\n}\n\nfunction httpsUrl(value: string, name: string): URL {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(value);\n\t} catch {\n\t\tthrow new ValidationError(`${name} must be an absolute HTTPS URL`);\n\t}\n\tif (url.protocol !== 'https:' || url.username || url.password || url.hash) {\n\t\tthrow new ValidationError(`${name} must use HTTPS without credentials or a fragment`);\n\t}\n\treturn url;\n}\n","import { ValidationError } from '../errors.js';\nimport type {\n\tDocumentArtifactName,\n\tICertificateCompleteResponse,\n\tICertificateStartResponse,\n\tIDocumentDetailsResponse,\n\tIDocumentListItem,\n\tIDocumentListResponse,\n\tIEmptyResult,\n\tIIdentityVerificationSession,\n\tIIdentityVerificationState,\n\tISigner,\n\tISignerDocumentListParams,\n\tISignerSelf,\n\tISignerTermsAcceptance,\n\tISignFieldEntry,\n\tIStartIdentityVerificationPayload,\n\tIStatusResponse,\n\tIVerifySignerCodePayload,\n} from '../types.js';\nimport {\n\tcleanParams,\n\tpublicRequestConfig,\n\trequireDocumentArtifactName,\n\trequireSignerImageType,\n\tsignerAccessConfig,\n} from '../utils.js';\nimport { BaseResource } from './base.js';\n\n/**\n * Signer-side endpoints use `signer-access-code` from the private signing link.\n * Explicit `listAsOwner`/`searchAsOwner` use workspace credentials, and artifact\n * downloads are public with an optional signer-identity preflight.\n */\nexport class SignerDocumentsResource extends BaseResource {\n\t/** `GET /signers/{signer_id}/document?signer-access-code=…` */\n\tasync getCurrent(signerId: string, signerAccessCode: string): Promise<IDocumentDetailsResponse> {\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\treturn this.call('Failed to fetch current signer document', () =>\n\t\t\tthis.http.get(`/signers/${sid}/document`, signerAccessConfig(code)),\n\t\t);\n\t}\n\n\t/** `GET /signers/{signer_id}/documents?signer-access-code=…` */\n\tasync list(\n\t\tsignerId: string,\n\t\tsignerAccessCode: string,\n\t\tparams: ISignerDocumentListParams = {},\n\t): Promise<IDocumentListResponse> {\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\treturn this.listDocuments(signerId, signerAccessConfig(code, { ...params }));\n\t}\n\n\t/**\n\t * `GET /signers/{signer_id}/documents` with the client's owner credentials\n\t * (API key or token) instead of a signer access code. The signer must belong\n\t * to that workspace.\n\t */\n\tasync listAsOwner(\n\t\tsignerId: string,\n\t\tparams: ISignerDocumentListParams = {},\n\t): Promise<IDocumentListResponse> {\n\t\treturn this.listDocuments(signerId, { params: cleanParams({ ...params }) });\n\t}\n\n\t/** `GET /signers/{signer_id}/documents/search?search=…&signer-access-code=…` */\n\tasync search(\n\t\tsignerId: string,\n\t\tsearch: string,\n\t\tsignerAccessCode: string,\n\t): Promise<IDocumentListResponse> {\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\treturn this.searchDocuments(signerId, signerAccessConfig(code, { search }));\n\t}\n\n\t/**\n\t * `GET /signers/{signer_id}/documents/search?search=…` with the client's owner\n\t * credentials instead of a signer access code. The signer must belong to that\n\t * workspace.\n\t */\n\tasync searchAsOwner(signerId: string, search: string): Promise<IDocumentListResponse> {\n\t\treturn this.searchDocuments(signerId, { params: cleanParams({ search }) });\n\t}\n\n\tprivate listDocuments(signerId: string, config: Parameters<typeof this.http.get>[1]) {\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\treturn this.callList<IDocumentListItem>('Failed to list signer documents', () =>\n\t\t\tthis.http.get(`/signers/${sid}/documents`, config),\n\t\t);\n\t}\n\n\tprivate searchDocuments(signerId: string, config: Parameters<typeof this.http.get>[1]) {\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\treturn this.callList<IDocumentListItem>('Failed to search signer documents', () =>\n\t\t\tthis.http.get(`/signers/${sid}/documents/search`, config),\n\t\t);\n\t}\n\n\t/**\n\t * Public `GET /signers/{signer_id}/documents/{document_id}/download/{artifact}`.\n\t * When an access code is supplied, the SDK first verifies that it belongs to\n\t * the requested signer for callers that want that additional check.\n\t */\n\tasync download(\n\t\tsignerId: string,\n\t\tdocumentId: string,\n\t\tartifactName: DocumentArtifactName,\n\t\tsignerAccessCode?: string,\n\t): Promise<Buffer> {\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\tconst did = this.requireId(documentId, 'Document ID');\n\t\tconst artifact = requireDocumentArtifactName(artifactName);\n\t\tlet config = publicRequestConfig();\n\t\tif (signerAccessCode !== undefined) {\n\t\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\t\tconst signer = await this.self(code);\n\t\t\tif (signer.id !== sid) {\n\t\t\t\tthrow new ValidationError('Signer access code does not match the signer ID');\n\t\t\t}\n\t\t\tconfig = signerAccessConfig(code);\n\t\t}\n\t\treturn this.callBinary('Failed to download signer document', () =>\n\t\t\tthis.http.get<ArrayBuffer>(`/signers/${sid}/documents/${did}/download/${artifact}`, {\n\t\t\t\t...config,\n\t\t\t\tresponseType: 'arraybuffer',\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** `PUT /signers/documents/sign-multiple?signer-access-code=…` */\n\tasync signMultiple(documentIds: string[], signerAccessCode: string): Promise<unknown[]> {\n\t\tif (!Array.isArray(documentIds) || documentIds.length === 0) {\n\t\t\tthrow new ValidationError('documentIds must be a non-empty array');\n\t\t}\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\treturn this.call('Failed to sign multiple documents', () =>\n\t\t\tthis.http.put(\n\t\t\t\t'/signers/documents/sign-multiple',\n\t\t\t\t{ document_ids: documentIds },\n\t\t\t\tsignerAccessConfig(code),\n\t\t\t),\n\t\t);\n\t}\n\n\t/** `PUT /signers/documents/decline-multiple?signer-access-code=…` */\n\tasync declineMultiple(\n\t\tdocumentIds: string[],\n\t\tdeclineReason: string,\n\t\tsignerAccessCode: string,\n\t): Promise<unknown[]> {\n\t\tif (!Array.isArray(documentIds) || documentIds.length === 0) {\n\t\t\tthrow new ValidationError('documentIds must be a non-empty array');\n\t\t}\n\t\tvalidateDeclineReason(declineReason);\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\treturn this.call('Failed to decline multiple documents', () =>\n\t\t\tthis.http.put(\n\t\t\t\t'/signers/documents/decline-multiple',\n\t\t\t\t{ document_ids: documentIds, decline_reason: declineReason },\n\t\t\t\tsignerAccessConfig(code),\n\t\t\t),\n\t\t);\n\t}\n\n\t/** `GET /signers/self?signer-access-code=…` — fetch the signer's own profile. */\n\tasync self(signerAccessCode: string): Promise<ISignerSelf> {\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\treturn this.call('Failed to fetch signer profile', () =>\n\t\t\tthis.http.get('/signers/self', signerAccessConfig(code)),\n\t\t);\n\t}\n\n\t/** `GET /signers/identity-verification` — session status, capture URL and restart eligibility. */\n\tasync getIdentityVerification(signerAccessCode: string): Promise<IIdentityVerificationState> {\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\treturn this.call('Failed to fetch identity verification', () =>\n\t\t\tthis.http.get('/signers/identity-verification', signerAccessConfig(code)),\n\t\t);\n\t}\n\n\t/** `POST /signers/identity-verification` — open a hosted session after the signer's explicit consent. */\n\tasync startIdentityVerification(\n\t\tsignerAccessCode: string,\n\t\tpayload: IStartIdentityVerificationPayload,\n\t): Promise<IIdentityVerificationSession> {\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\tif (payload?.consent !== true) {\n\t\t\tthrow new ValidationError('Explicit biometric-processing consent is required');\n\t\t}\n\t\treturn this.call('Failed to start identity verification', () =>\n\t\t\tthis.http.post('/signers/identity-verification', { consent: true }, signerAccessConfig(code)),\n\t\t);\n\t}\n\n\t/**\n\t * `PUT /signers/accept-terms?signer-access-code=…` — accept the platform\n\t * terms as the signer.\n\t *\n\t * The access code travels as the `signer-access-code` query parameter, like\n\t * every other signer-side endpoint (the spec under-documents this one, but\n\t * the query-param convention is uniform across the Signing API).\n\t */\n\tasync acceptTerms(signerAccessCode: string): Promise<ISignerTermsAcceptance | IStatusResponse> {\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\treturn this.call('Failed to accept terms', () =>\n\t\t\tthis.http.put('/signers/accept-terms', undefined, signerAccessConfig(code)),\n\t\t);\n\t}\n\n\t/** `POST /verify` — verify an email or WhatsApp OTP for a signer. */\n\tasync verifyCode(payload: IVerifySignerCodePayload): Promise<IEmptyResult | IStatusResponse> {\n\t\tconst code = this.requireId(payload.signerAccessCode, 'signer-access-code');\n\t\tconst otp = this.requireId(payload.verificationCode, 'verification-code');\n\t\treturn this.call('Failed to verify signer code', () =>\n\t\t\tthis.http.post('/verify', { 'verification-code': otp }, signerAccessConfig(code)),\n\t\t);\n\t}\n\n\t/** Compatibility alias for {@link verifyCode}; accepts email and WhatsApp OTPs. */\n\tasync verifyEmail(payload: IVerifySignerCodePayload): Promise<IEmptyResult | IStatusResponse> {\n\t\treturn this.verifyCode(payload);\n\t}\n\n\t/**\n\t * `POST /signers/certificate/start` — start an ICP-Brasil A1/A3 signature.\n\t * Returns `{ token }` for the signer's Web PKI client. This production route\n\t * is used by Assinafy's signing frontend but is absent from OpenAPI paths.\n\t */\n\tasync startCertificate(signerAccessCode: string): Promise<ICertificateStartResponse> {\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\treturn this.call('Failed to start certificate signature', () =>\n\t\t\tthis.http.post(\n\t\t\t\t'/signers/certificate/start',\n\t\t\t\t{ 'signer-access-code': code },\n\t\t\t\tsignerAccessConfig(code),\n\t\t\t),\n\t\t);\n\t}\n\n\t/**\n\t * `POST /signers/certificate/complete` — finish an ICP-Brasil A1/A3 signature.\n\t * Pass the same token returned by {@link startCertificate}, after Web PKI\n\t * successfully signs it. Returns `{ signerName }`; private keys stay local.\n\t * This production route is absent from OpenAPI paths.\n\t */\n\tasync completeCertificate(\n\t\tsignerAccessCode: string,\n\t\ttoken: string,\n\t): Promise<ICertificateCompleteResponse> {\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\tif (typeof token !== 'string' || !token.trim()) {\n\t\t\tthrow new ValidationError('Certificate token is required');\n\t\t}\n\t\treturn this.call('Failed to complete certificate signature', () =>\n\t\t\tthis.http.post(\n\t\t\t\t'/signers/certificate/complete',\n\t\t\t\t{ 'signer-access-code': code, token },\n\t\t\t\tsignerAccessConfig(code),\n\t\t\t),\n\t\t);\n\t}\n\n\t/**\n\t * `PUT /documents/{documentId}/signers/confirm-data?signer-access-code=…`\n\t *\n\t * The documented body fields are `full_name`, `email` and `government_id`;\n\t * `whatsapp_phone_number` / `has_accepted_terms` are also accepted for the\n\t * WhatsApp confirmation flow.\n\t */\n\tasync confirmData(\n\t\tdocumentId: string,\n\t\tsignerAccessCode: string,\n\t\tpayload: {\n\t\t\tfull_name?: string;\n\t\t\temail?: string;\n\t\t\tgovernment_id?: string;\n\t\t\twhatsapp_phone_number?: string;\n\t\t\thas_accepted_terms?: boolean;\n\t\t},\n\t): Promise<ISigner | IEmptyResult> {\n\t\tconst did = this.requireId(documentId, 'Document ID');\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\t// Build the JSON body explicitly (only defined fields). Don't route it\n\t\t// through cleanParams — that's a query-string helper and would rename a\n\t\t// body key like `per_page`.\n\t\tconst body: Record<string, unknown> = {};\n\t\tfor (const [key, value] of Object.entries(payload)) {\n\t\t\tif (value !== undefined) body[key] = value;\n\t\t}\n\t\tawait this.requireDocumentAccess(did, code);\n\t\treturn this.call('Failed to confirm signer data', () =>\n\t\t\tthis.http.put(`/documents/${did}/signers/confirm-data`, body, signerAccessConfig(code)),\n\t\t);\n\t}\n\n\t/**\n\t * `POST /signature?signer-access-code=…&type=…` — upload the signer's\n\t * signature or initial image. `imageType` defaults to `signature`.\n\t */\n\tasync uploadSignature(\n\t\tsignerAccessCode: string,\n\t\timage: Buffer,\n\t\toptions: { imageType?: 'signature' | 'initial'; contentType?: string; reuse?: boolean } = {},\n\t): Promise<IEmptyResult | IStatusResponse> {\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\tconst imageType = requireSignerImageType(options.imageType ?? 'signature');\n\t\tif (!Buffer.isBuffer(image) || image.byteLength === 0) {\n\t\t\tthrow new ValidationError('image buffer is required');\n\t\t}\n\t\treturn this.call('Failed to upload signer signature', () =>\n\t\t\tthis.http.post(\n\t\t\t\t'/signature',\n\t\t\t\timage,\n\t\t\t\tsignerAccessConfig(\n\t\t\t\t\tcode,\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: imageType,\n\t\t\t\t\t\t// Documented query flag controlling the signer's is_signature_reusable state.\n\t\t\t\t\t\treuse: options.reuse,\n\t\t\t\t\t},\n\t\t\t\t\t{ 'Content-Type': options.contentType ?? 'image/png' },\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\t}\n\n\t/** `GET /signature/{type}?signer-access-code=…` — download the signer's signature/initial. */\n\tasync downloadSignature(\n\t\tsignerAccessCode: string,\n\t\timageType: 'signature' | 'initial' = 'signature',\n\t): Promise<Buffer> {\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\tconst type = requireSignerImageType(imageType);\n\t\treturn this.callBinary('Failed to download signer signature', () =>\n\t\t\tthis.http.get<ArrayBuffer>(`/signature/${type}`, {\n\t\t\t\t...signerAccessConfig(code),\n\t\t\t\tresponseType: 'arraybuffer',\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** `GET /sign?signer-access-code=…` — fetch the assignment as the signer sees it. */\n\tasync getAssignment(\n\t\tsignerAccessCode: string,\n\t\thasAcceptedTerms?: boolean,\n\t): Promise<IDocumentDetailsResponse> {\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\treturn this.call('Failed to fetch signer assignment', () =>\n\t\t\tthis.http.get('/sign', signerAccessConfig(code, { has_accepted_terms: hasAcceptedTerms })),\n\t\t);\n\t}\n\n\t/**\n\t * `POST /documents/{documentId}/assignments/{assignmentId}?signer-access-code=…` — sign.\n\t * Virtual assignments accept `[]` after the signer confirms their data.\n\t */\n\tasync sign(\n\t\tdocumentId: string,\n\t\tassignmentId: string,\n\t\tsignerAccessCode: string,\n\t\tentries: ISignFieldEntry[],\n\t): Promise<Record<string, unknown>> {\n\t\tconst did = this.requireId(documentId, 'Document ID');\n\t\tconst aid = this.requireId(assignmentId, 'Assignment ID');\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\tif (!Array.isArray(entries)) {\n\t\t\tthrow new ValidationError('entries must be an array');\n\t\t}\n\t\tconst document = await this.requireDocumentAccess(did, code, aid);\n\t\tif (document.assignment?.method === 'collect' && entries.length === 0) {\n\t\t\tthrow new ValidationError('entries must be non-empty for collect assignments');\n\t\t}\n\t\treturn this.call('Failed to sign document', () =>\n\t\t\tthis.http.post(`/documents/${did}/assignments/${aid}`, entries, signerAccessConfig(code)),\n\t\t);\n\t}\n\n\t/**\n\t * `PUT /documents/{documentId}/assignments/{assignmentId}/reject?signer-access-code=…`\n\t * — signer-side decline using the access code from the signing link.\n\t */\n\tasync decline(\n\t\tdocumentId: string,\n\t\tassignmentId: string,\n\t\tsignerAccessCode: string,\n\t\tdeclineReason: string,\n\t): Promise<unknown[]> {\n\t\tconst did = this.requireId(documentId, 'Document ID');\n\t\tconst aid = this.requireId(assignmentId, 'Assignment ID');\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\tvalidateDeclineReason(declineReason);\n\t\tawait this.requireDocumentAccess(did, code, aid);\n\t\treturn this.call('Failed to decline assignment', () =>\n\t\t\tthis.http.put(\n\t\t\t\t`/documents/${did}/assignments/${aid}/reject`,\n\t\t\t\t{ decline_reason: declineReason },\n\t\t\t\tsignerAccessConfig(code),\n\t\t\t),\n\t\t);\n\t}\n\n\tprivate async requireDocumentAccess(\n\t\tdocumentId: string,\n\t\tsignerAccessCode: string,\n\t\tassignmentId?: string,\n\t): Promise<IDocumentDetailsResponse> {\n\t\tconst document = await this.getAssignment(signerAccessCode);\n\t\tif (\n\t\t\tdocument.id !== documentId ||\n\t\t\t(assignmentId !== undefined && document.assignment?.id !== assignmentId)\n\t\t) {\n\t\t\tthrow new ValidationError('Signer access code does not match the document or assignment');\n\t\t}\n\t\treturn document;\n\t}\n}\n\nfunction validateDeclineReason(value: string): void {\n\tif (typeof value !== 'string' || !value.trim()) {\n\t\tthrow new ValidationError('declineReason is required');\n\t}\n\tif ([...value].length > 2000) {\n\t\tthrow new ValidationError('declineReason must contain at most 2000 characters');\n\t}\n}\n","import { ApiError, ValidationError } from '../errors.js';\nimport type {\n\tICreateSignerPayload,\n\tICreateSignerResponse,\n\tIEmptyResult,\n\tISigner,\n\tISignerListParams,\n\tISignerListResponse,\n\tIUpdateSignerPayload,\n} from '../types.js';\nimport { cleanParams, requireEmail, requireSort, stripEmpty } from '../utils.js';\nimport { BaseResource } from './base.js';\n\n/** Validate the locally knowable fields before creating a signer. */\nexport function validateCreateSignerPayload(payload: ICreateSignerPayload): void {\n\tif (!payload.full_name?.trim()) throw new ValidationError('Signer full name is required');\n\tif (payload.email !== undefined) requireEmail(payload.email);\n}\n\nexport class SignerResource extends BaseResource {\n\t/**\n\t * Create a signer in the workspace.\n\t *\n\t * Only `full_name` is required. When an `email` is supplied the call is\n\t * idempotent by email: an existing signer with that address is reused instead\n\t * of duplicated.\n\t */\n\tasync create(payload: ICreateSignerPayload, accountId?: string): Promise<ICreateSignerResponse> {\n\t\tconst id = this.accountId(accountId);\n\t\tvalidateCreateSignerPayload(payload);\n\n\t\tif (payload.email) {\n\t\t\tconst existing = await this.findByEmail(payload.email, id);\n\t\t\tif (existing) {\n\t\t\t\tthis.logger.info('Using existing signer', { signerId: existing.id });\n\t\t\t\treturn existing;\n\t\t\t}\n\t\t}\n\n\t\tthis.logger.info('Creating signer', { hasEmail: Boolean(payload.email) });\n\t\ttry {\n\t\t\treturn await this.call('Failed to create signer', () =>\n\t\t\t\tthis.http.post(`/accounts/${id}/signers`, normaliseSignerPayload(payload)),\n\t\t\t);\n\t\t} catch (err) {\n\t\t\tif (err instanceof ApiError && err.statusCode === 409 && payload.email) {\n\t\t\t\tconst duplicate = await this.findByEmail(payload.email, id);\n\t\t\t\tif (duplicate) {\n\t\t\t\t\tthis.logger.info('Signer already exists, using existing signer', {\n\t\t\t\t\t\tsignerId: duplicate.id,\n\t\t\t\t\t});\n\t\t\t\t\treturn duplicate;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\t/** Get a signer by ID. */\n\tasync get(signerId: string, accountId?: string): Promise<ISigner> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\treturn this.call('Failed to fetch signer', () =>\n\t\t\tthis.http.get(`/accounts/${id}/signers/${sid}`),\n\t\t);\n\t}\n\n\t/** List signers (`sort` accepts the live-verified `full_name` / `-full_name`). */\n\tasync list(params: ISignerListParams = {}, accountId?: string): Promise<ISignerListResponse> {\n\t\tconst id = this.accountId(accountId);\n\t\trequireSort(params.sort, ['full_name', '-full_name']);\n\t\treturn this.callList<ISigner>('Failed to list signers', () =>\n\t\t\tthis.http.get(`/accounts/${id}/signers`, {\n\t\t\t\tparams: cleanParams(params as unknown as Record<string, unknown>),\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** Update a signer. Fails if the signer has active assignments. */\n\tasync update(\n\t\tsignerId: string,\n\t\tpayload: IUpdateSignerPayload,\n\t\taccountId?: string,\n\t): Promise<ICreateSignerResponse> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\tif (payload.full_name !== undefined && !payload.full_name.trim()) {\n\t\t\tthrow new ValidationError('Signer full name cannot be blank');\n\t\t}\n\t\tif (payload.email !== undefined) requireEmail(payload.email);\n\t\treturn this.call('Failed to update signer', () =>\n\t\t\tthis.http.put(`/accounts/${id}/signers/${sid}`, normaliseSignerPayload(payload, true)),\n\t\t);\n\t}\n\n\t/** Delete a signer. */\n\tasync delete(signerId: string, accountId?: string): Promise<IEmptyResult> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\treturn this.call('Failed to delete signer', () =>\n\t\t\tthis.http.delete(`/accounts/${id}/signers/${sid}`),\n\t\t);\n\t}\n\n\t/** Find a signer by email via the API's `search` parameter. Returns `null` if none match. */\n\tasync findByEmail(email: string, accountId?: string): Promise<ISigner | null> {\n\t\trequireEmail(email);\n\t\ttry {\n\t\t\tconst lower = email.toLowerCase();\n\t\t\tfor (let page = 1; page <= MAX_SEARCH_PAGES; page++) {\n\t\t\t\tconst { data, meta } = await this.list({ search: email, per_page: 100, page }, accountId);\n\t\t\t\tconst match = data.find((s) => (s.email ?? '').toLowerCase() === lower);\n\t\t\t\tif (match) return match;\n\t\t\t\tif (!data.length) return null;\n\t\t\t\tif (meta?.last_page !== undefined) {\n\t\t\t\t\tif (page >= meta.last_page) return null;\n\t\t\t\t} else if (data.length < 100) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow new ValidationError('Signer email search exceeded the maximum page count');\n\t\t} catch (err) {\n\t\t\tif (err instanceof ApiError && err.statusCode === 404) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t}\n}\n\nconst MAX_SEARCH_PAGES = 100;\n\nfunction normaliseSignerPayload(\n\tpayload: ICreateSignerPayload | IUpdateSignerPayload,\n\tuseGovernmentId = false,\n): Record<string, unknown> {\n\tconst normalised: Record<string, unknown> = {\n\t\tfull_name: payload.full_name,\n\t\temail: payload.email,\n\t\twhatsapp_phone_number: payload.whatsapp_phone_number ?? payload.phone,\n\t};\n\n\tif (payload.government_id !== undefined) {\n\t\tnormalised.government_id = payload.government_id;\n\t} else if (payload.cpf) {\n\t\t// Strip formatting; only forward a CPF when digits actually remain so a\n\t\t// value like \"---\" doesn't get sent as an empty string.\n\t\tconst digits = payload.cpf.replace(/\\D/g, '');\n\t\tif (digits) normalised[useGovernmentId ? 'government_id' : 'cpf'] = digits;\n\t}\n\n\tif ('metadata' in payload && payload.metadata !== undefined) {\n\t\tnormalised.metadata = payload.metadata;\n\t}\n\n\treturn stripEmpty(normalised);\n}\n","import { ValidationError } from '../errors.js';\nimport type { ICreateTagPayload, IDeleteTagResponse, ITag, IUpdateTagPayload } from '../types.js';\nimport { cleanParams, stripEmpty } from '../utils.js';\nimport { BaseResource } from './base.js';\n\n/**\n * Workspace-scoped tags used to label documents and templates.\n *\n * Covers the full Tag section of the API docs:\n * - `GET /accounts/{id}/tags` → {@link list}\n * - `POST /accounts/{id}/tags` → {@link create}\n * - `PUT /accounts/{id}/tags/{tag_id}` → {@link update}\n * - `DELETE /accounts/{id}/tags/{tag_id}` → {@link delete}\n *\n * Document-level attach/detach lives on {@link DocumentResource} (`listTags`,\n * `replaceTags`, `addTags`, `detachTag`).\n */\nexport class TagResource extends BaseResource {\n\t/** List the workspace's tags, ordered alphabetically. Optional case-insensitive `search`. */\n\tasync list(params: { search?: string } = {}, accountId?: string): Promise<ITag[]> {\n\t\tconst id = this.accountId(accountId);\n\t\treturn this.call('Failed to list tags', () =>\n\t\t\tthis.http.get(`/accounts/${id}/tags`, {\n\t\t\t\tparams: cleanParams(params as Record<string, unknown>),\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** Create a tag. Throws `ApiError` (409) if the name already exists (case-insensitive). */\n\tasync create(payload: ICreateTagPayload, accountId?: string): Promise<ITag> {\n\t\tif (!payload.name) throw new ValidationError('Tag name is required');\n\t\tconst id = this.accountId(accountId);\n\t\treturn this.call('Failed to create tag', () =>\n\t\t\tthis.http.post(`/accounts/${id}/tags`, stripEmpty({ ...payload })),\n\t\t);\n\t}\n\n\t/**\n\t * Update a tag's name and/or color. Omit a field to leave it unchanged;\n\t * pass `color: null` to clear the color. Throws `ApiError` (409) if another\n\t * tag already uses the new name.\n\t */\n\tasync update(tagId: string, payload: IUpdateTagPayload, accountId?: string): Promise<ITag> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst tid = this.requireId(tagId, 'Tag ID');\n\t\t// Don't strip `color: null` — null is the documented \"clear color\" signal.\n\t\tconst body: Record<string, unknown> = {};\n\t\tif (payload.name !== undefined) body.name = payload.name;\n\t\tif ('color' in payload) body.color = payload.color;\n\t\treturn this.call('Failed to update tag', () =>\n\t\t\tthis.http.put(`/accounts/${id}/tags/${tid}`, body),\n\t\t);\n\t}\n\n\t/**\n\t * Delete a tag. By default fails with `ApiError` (409) if the tag is still\n\t * attached to anything; pass `{ force: true }` to detach everywhere first.\n\t */\n\tasync delete(\n\t\ttagId: string,\n\t\toptions: { force?: boolean; accountId?: string } = {},\n\t): Promise<IDeleteTagResponse> {\n\t\tconst id = this.accountId(options.accountId);\n\t\tconst tid = this.requireId(tagId, 'Tag ID');\n\t\tconst params = options.force ? { force: 'true' } : undefined;\n\t\treturn this.call('Failed to delete tag', () =>\n\t\t\tthis.http.delete(`/accounts/${id}/tags/${tid}`, { params }),\n\t\t);\n\t}\n}\n","import type {\n\tITemplateDetailsResponse,\n\tITemplateListItem,\n\tITemplateListParams,\n\tITemplateListResponse,\n} from '../types.js';\nimport { cleanParams, requireSort } from '../utils.js';\nimport { BaseResource } from './base.js';\n\nexport class TemplateResource extends BaseResource {\n\t/** List templates for the workspace. */\n\tasync list(params: ITemplateListParams = {}, accountId?: string): Promise<ITemplateListResponse> {\n\t\tconst id = this.accountId(accountId);\n\t\trequireSort(params.sort, ['name', '-name']);\n\t\treturn this.callList<ITemplateListItem>('Failed to list templates', () =>\n\t\t\tthis.http.get(`/accounts/${id}/templates`, {\n\t\t\t\tparams: cleanParams(params as unknown as Record<string, unknown>),\n\t\t\t}),\n\t\t);\n\t}\n\n\t/**\n\t * Get a template by ID.\n\t *\n\t * Note: the swagger only documents the list endpoint; this single-resource\n\t * `GET /accounts/{id}/templates/{id}` is exposed by the platform and used\n\t * by the official PHP SDK.\n\t */\n\tasync get(templateId: string, accountId?: string): Promise<ITemplateDetailsResponse> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst tmplId = this.requireId(templateId, 'Template ID');\n\t\treturn this.call('Failed to fetch template', () =>\n\t\t\tthis.http.get(`/accounts/${id}/templates/${tmplId}`),\n\t\t);\n\t}\n\n\t/**\n\t * `GET /accounts/{id}/templates/{template_id}/pages/{page_id}/download` —\n\t * download a template page as a JPEG (used by template editors to render\n\t * thumbnails on the client).\n\t */\n\tasync downloadPage(templateId: string, pageId: string, accountId?: string): Promise<Buffer> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst tmplId = this.requireId(templateId, 'Template ID');\n\t\tconst pid = this.requireId(pageId, 'Page ID');\n\t\treturn this.callBinary('Failed to download template page', () =>\n\t\t\tthis.http.get<ArrayBuffer>(`/accounts/${id}/templates/${tmplId}/pages/${pid}/download`, {\n\t\t\t\tresponseType: 'arraybuffer',\n\t\t\t}),\n\t\t);\n\t}\n}\n","/** Document lifecycle states emitted by the API. */\nexport type DocumentStatus =\n\t| 'uploading'\n\t| 'uploaded'\n\t| 'metadata_processing'\n\t| 'metadata_ready'\n\t| 'pending_signature'\n\t| 'pending_identity_review'\n\t| 'expired'\n\t| 'certificating'\n\t| 'certificated'\n\t| 'rejected_by_signer'\n\t| 'rejected_by_user'\n\t| 'failed';\n\n/** Artifact names available for document download. */\nexport type DocumentArtifactName =\n\t| 'original'\n\t| 'certificated'\n\t| 'certificate-page'\n\t| 'pades'\n\t| 'bundle';\n\n/** Assignment methods supported by the API. */\nexport type AssignmentMethod = 'virtual' | 'collect';\n\n/** Verification methods accepted by assignment signer entries. */\nexport type AssignmentVerificationMethod =\n\t| 'Email'\n\t| 'Whatsapp'\n\t| 'DigitalCertificate'\n\t| 'IdDocumentFaceMatchBasic'\n\t| (string & {});\n\n/** Notification methods accepted by assignment signer entries. */\nexport type AssignmentNotificationMethod = 'Email' | 'Whatsapp' | (string & {});\n\n/** OAuth provider currently accepted by the Assinafy authentication API. */\nexport type SocialLoginProvider = 'google';\n\n/** Minimal logger contract (compatible with console, pino, winston, etc.). */\nexport interface Logger {\n\tdebug: (message: string, context?: Record<string, unknown>) => void;\n\tinfo: (message: string, context?: Record<string, unknown>) => void;\n\twarn: (message: string, context?: Record<string, unknown>) => void;\n\terror: (message: string, context?: Record<string, unknown>) => void;\n}\n\n/** Client configuration options. */\nexport interface AssinafyClientOptions {\n\t/** Assinafy API key. Preferred authentication method (sends `X-Api-Key` header). */\n\tapiKey?: string;\n\t/**\n\t * OAuth access token or user JWT. Sends `Authorization: Bearer <token>`.\n\t * `apiKey` takes precedence when both options are supplied.\n\t */\n\ttoken?: string;\n\t/**\n\t * Build a client without credentials for public, OAuth bootstrap, or signer-code calls.\n\t */\n\tallowUnauthenticated?: boolean;\n\t/** Default account (workspace) ID applied to account-scoped endpoints. */\n\taccountId?: string;\n\t/** Override the API base URL. Defaults to https://api.assinafy.com.br/v1. */\n\tbaseUrl?: string;\n\t/**\n\t * Allow a plaintext `http://` base URL. Restricted to loopback hosts\n\t * (`localhost`, `127.0.0.0/8`, `[::1]`) so the API key can never leave the\n\t * machine in cleartext; any other host is rejected even with this enabled.\n\t */\n\tallowInsecureHttp?: boolean;\n\t/**\n\t * Default `whsec_` endpoint signing secret for {@link WebhookVerifier}\n\t * (`client.webhookVerifier`). Each endpoint has its own secret; construct a\n\t * separate verifier per endpoint when several are signed.\n\t */\n\twebhookSecret?: string;\n\t/** Request timeout in milliseconds. Defaults to 30_000. */\n\ttimeout?: number;\n\t/** Optional logger. Defaults to a no-op logger. */\n\tlogger?: Logger;\n}\n\n/**\n * Payload for creating a signer.\n *\n * The official API requires only `full_name`; email and WhatsApp are optional\n * delivery channels.\n */\nexport interface ICreateSignerPayload {\n\tfull_name: string;\n\temail?: string;\n\twhatsapp_phone_number?: string;\n\t/** PHP SDK compatibility alias for `whatsapp_phone_number`. */\n\tphone?: string;\n\t/** CPF or numeric/alphanumeric CNPJ; forwarded unchanged for server normalization. */\n\tgovernment_id?: string;\n\t/** Compatibility extension for a Brazilian CPF; non-digits are stripped. */\n\tcpf?: string;\n\t/** Compatibility extension for integration-defined signer metadata. */\n\tmetadata?: Record<string, unknown>;\n}\n\n/** Payload for updating a signer. */\nexport interface IUpdateSignerPayload {\n\tfull_name?: string;\n\temail?: string;\n\twhatsapp_phone_number?: string;\n\t/** PHP SDK compatibility alias for `whatsapp_phone_number`. */\n\tphone?: string;\n\t/** CPF or numeric/alphanumeric CNPJ; forwarded unchanged for server normalization. */\n\tgovernment_id?: string;\n\t/** Backwards-compatible alias for `government_id`. */\n\tcpf?: string;\n}\n\n/** Signer object as returned by the API. */\nexport interface ISigner {\n\tresource?: string;\n\tid: string;\n\tfull_name: string;\n\temail: string | null;\n\twhatsapp_phone_number?: string | null;\n\tgovernment_id?: string | null;\n\tcpf?: string | null;\n\thas_accepted_terms?: boolean;\n\t/** Only returned by `GET /signers/self`. */\n\thas_signature?: boolean;\n\t/** Only returned by `GET /signers/self`. */\n\thas_initial?: boolean;\n\tmetadata?: Record<string, unknown>;\n}\n\n/** Signer profile returned by `GET /signers/self`. */\nexport interface ISignerSelf extends ISigner {\n\thas_signature: boolean;\n\thas_initial: boolean;\n\tis_signature_reusable: boolean;\n\tverification_method?: AssignmentVerificationMethod;\n}\n\n/** Identity-document provider session states. */\nexport type IdentityVerificationStatus =\n\t| 'Pending'\n\t| 'InReview'\n\t| 'Approved'\n\t| 'Declined'\n\t| 'Expired'\n\t| 'Abandoned';\n\n/** Signer-facing state from `GET /signers/identity-verification`. */\nexport interface IIdentityVerificationState {\n\tcan_start: boolean;\n\tstatus: IdentityVerificationStatus | null;\n\t/** Private capture link; preserve its fragment and never log it. */\n\turl: string | null;\n\texpires_at: string | null;\n\tcompleted_at: string | null;\n}\n\n/** Explicit signer consent required before opening a biometric provider session. */\nexport interface IStartIdentityVerificationPayload {\n\tconsent: true;\n}\n\n/** Hosted session from `POST /signers/identity-verification`. */\nexport interface IIdentityVerificationSession {\n\tid: string;\n\t/** Private capture link; open as-is, including any fragment. */\n\turl: string;\n\texpires_at: string | null;\n}\n\n/** Evidence names available only while an identity review is open. */\nexport type IdentityVerificationImageName =\n\t| 'document_front'\n\t| 'document_back'\n\t| 'document_pdf'\n\t| 'face';\n\n/** Account review of an `IdDocumentFaceMatchBasic` verification. */\nexport interface ISignerIdentityReview {\n\tid: string;\n\tstatus: IdentityVerificationStatus;\n\tprovider: 'AssinafyVerify';\n\tverification_method: 'IdDocumentFaceMatchBasic';\n\treason_codes: Array<{ code: string; description: string }>;\n\tevidence_available: boolean;\n\texpected: { name: string | null; cpf: string | null } | null;\n\tdocument: { type: string | null; name: string | null; cpf: string | null } | null;\n\tmatches: { cpf: boolean | null; name: number | null; birth_date: boolean | null } | null;\n\tchecks: Array<{ name: string; result: string; score: number | null; reasons: string[] }>;\n\timages: IdentityVerificationImageName[];\n\truleset_version: string | null;\n\tevidence_sha256: string | null;\n\treviewed_by: { id: string; name: string } | null;\n\treviewed_at: string | null;\n\treview_note: string | null;\n\tcompleted_at: string | null;\n}\n\n/** Approval releases certification; rejection cancels the document and notifies its recipients. */\nexport interface IIdentityReviewPayload {\n\tdecision: 'Approved' | 'Rejected';\n\t/** At most 2,000 Unicode characters; recorded privately and sent to the provider. */\n\tnote?: string | null;\n}\n\n/** Signer data returned after accepting the platform terms. */\nexport interface ISignerTermsAcceptance {\n\tfull_name: string;\n\temail: string | null;\n\thas_accepted_terms: boolean;\n}\n\n/** Email or WhatsApp OTP and the access code from the same verification message. */\nexport interface IVerifySignerCodePayload {\n\tsignerAccessCode: string;\n\tverificationCode: string;\n}\n\n/** Web PKI operation token returned when starting an ICP-Brasil A1/A3 signature. */\nexport interface ICertificateStartResponse {\n\ttoken: string;\n}\n\n/** Certificate identity returned after the Web PKI operation completes. */\nexport interface ICertificateCompleteResponse {\n\tsignerName: string;\n}\n\nexport type ICreateSignerResponse = ISigner;\n\n/** Pagination metadata extracted from `X-Pagination-*` response headers. */\nexport interface PaginationMeta {\n\tcurrent_page?: number;\n\tlast_page?: number;\n\tper_page?: number;\n\ttotal?: number;\n}\n\n/** Shape returned by every paginated list call in the SDK. */\nexport interface PaginatedResult<T> {\n\tdata: T[];\n\tmeta?: PaginationMeta;\n}\n\n/** Direct status body used by successful API operations without a `data` member. */\nexport interface IStatusResponse {\n\tstatus: number;\n\tmessage: string;\n}\n\n/** Unwrapped `data: []` returned by successful operations without result data. */\nexport type IEmptyResult = unknown[];\n\n/** @deprecated use {@link PaginatedResult} — retained for existing type imports. */\nexport type IPaginatedResponse<T> = PaginatedResult<T>;\n\nexport type ISignerListResponse = PaginatedResult<ISigner>;\n\n/** Signer reference accepted by the assignment endpoints. */\nexport type SignerReference =\n\t| string\n\t| {\n\t\t\tid?: string;\n\t\t\tsigner_id?: string;\n\t\t\tverification_method?: AssignmentVerificationMethod;\n\t\t\t/** Production defaults an empty array to Email; it does not disable invitations. */\n\t\t\tnotification_methods?: AssignmentNotificationMethod[];\n\t\t\t/** Integer signing-order value forwarded to the assignment API. */\n\t\t\tstep?: number;\n\t };\n\n/** Payload for creating an assignment. */\nexport interface ICreateAssignmentPayload {\n\tmethod?: AssignmentMethod;\n\t/**\n\t * List of signers. Each entry may be a signer id string, or an object with\n\t * `id` / `signer_id`. For cost estimation, entries may omit the ID and\n\t * specify only `verification_method` / `notification_methods`.\n\t *\n\t * The SDK normalises them to the docs-sanctioned `signers: [{ ... }]`\n\t * shape before sending.\n\t */\n\tsigners?: SignerReference[];\n\t/** Legacy field still accepted by the API docs and used by the PHP SDK. */\n\tsigner_ids?: string[];\n\t/** Camel-case legacy alias used by the quick-start docs. */\n\tsignerIds?: string[];\n\tmessage?: string;\n\texpires_at?: string;\n\tcopy_receivers?: string[];\n\t/** Field placement entries. Required when `method` is `collect`. */\n\tentries?: ICollectAssignmentEntry[];\n}\n\n/**\n * A field placement rectangle on a document page. Geometry values are pixels\n * in Assinafy's 150-DPI page image, measured from the upper-left corner.\n */\nexport interface IDisplaySettings {\n\tleft: number;\n\ttop: number;\n\twidth: number;\n\theight: number;\n\tfontSize: number;\n\tfontFamily?: string;\n\tbackgroundColor?: string;\n}\n\n/** One page's field placements, used by `collect`-method assignments. */\nexport interface ICollectAssignmentEntry {\n\tpage_id: string;\n\tfields: Array<{\n\t\tsigner_id: string;\n\t\tfield_id: string;\n\t\tdisplay_settings?: IDisplaySettings;\n\t}>;\n}\n\n/** Direct signing URL generated for one signer (inside `assignment.signing_urls`). */\nexport interface ISigningUrl {\n\tsigner_id: string;\n\turl: string;\n}\n\n/**\n * One tracked notification-delivery record, returned inside\n * `assignment.signers[].notification_history` (account-owner contexts only).\n */\nexport interface IAssignmentSignerNotification {\n\tevent: string;\n\tstatus: string;\n\terror_code?: string | null;\n\terror_message?: string | null;\n\tsent_at?: string | null;\n\tfailed_at?: string | null;\n}\n\n/**\n * Signer as embedded inside an assignment. Extends the base {@link ISigner}\n * with the per-assignment verification / notification / ordering fields the\n * API returns. `completed` and `notification_history` are only present in\n * account-owner contexts.\n */\nexport interface IAssignmentSigner extends ISigner {\n\tverification_method?: AssignmentVerificationMethod | null;\n\tnotification_methods?: AssignmentNotificationMethod[] | null;\n\tstep?: number | null;\n\tnotified?: boolean | null;\n\tcompleted?: boolean | null;\n\tidentity_verification_status?: IdentityVerificationStatus | null;\n\tnotification_history?: IAssignmentSignerNotification[];\n}\n\n/**\n * One item (field placement instance) inside an assignment. `signer` and\n * `field` are embedded objects whose exact shape varies by context (the API's\n * own spec leaves them generic); `display_settings` is populated for\n * `collect`-method items and an empty array for `virtual`/legacy ones.\n */\nexport interface IAssignmentItem {\n\tid: string;\n\tpage: { id: string; number: number; height: number; width: number; download_url: string } | null;\n\tsigner: Partial<ISigner> & Record<string, unknown>;\n\tfield: Partial<IFieldDefinition> & Record<string, unknown>;\n\tdisplay_settings: IDisplaySettings | unknown[] | null;\n\tvalue: string | null;\n\tcompleted: boolean;\n}\n\n/** Signer summary entry inside `assignment.summary.signers` (account-owner contexts). */\nexport interface IAssignmentSummarySigner extends ISigner {\n\tcompleted: boolean;\n}\n\n/** Assignment object as returned by the API. */\nexport interface IAssignment {\n\t/** Resource type (`assignment`); present in single-resource responses. */\n\tresource?: string;\n\tid: string;\n\tsender_email?: string;\n\t/** `virtual` or `collect`. Documented as `null` for some `collect` responses. */\n\tmethod: AssignmentMethod | null;\n\t/** ISO 8601 timestamp, or `null` when the assignment does not expire. */\n\texpires_at?: string | null;\n\texpiration?: string;\n\tmessage?: string | null;\n\tsigners: IAssignmentSigner[];\n\t/** Request payloads use signer IDs; responses may expand them to objects. */\n\tcopy_receivers?: Array<string | Record<string, unknown>>;\n\titems?: IAssignmentItem[];\n\tsummary?: {\n\t\tsigner_count: number;\n\t\tcompleted_count: number;\n\t\tsigners: IAssignmentSummarySigner[];\n\t};\n\tsigning_urls?: ISigningUrl[];\n}\n\nexport type ICreateAssignmentResponse = IAssignment;\n\nexport interface IResendEmailResponse {\n\tis_sent?: boolean;\n\tdocument_id?: string;\n\tsigner_id?: string;\n}\n\n/** One line item in a cost-estimation `breakdown`. */\nexport interface IEstimateCostBreakdownItem {\n\tcode: string;\n\tname: string;\n\tcost: number;\n\tquantity: number;\n\tunit_cost: number;\n}\n\n/**\n * Cost-estimation response shared by the assignment `estimate-cost` and the\n * template `documents/estimate-cost` endpoints (identical shape per the docs).\n */\nexport interface IEstimateCostResponse {\n\tdocuments: number;\n\tcredits: number;\n\tneeds_extra_document: boolean;\n\textra_document_cost: number;\n\ttotal_credits: number;\n\tbreakdown: IEstimateCostBreakdownItem[];\n\tdocument_balance: number;\n\tcredit_balance: number;\n\thas_sufficient_resources: boolean;\n\tblocking_reason: 'PendingPayment' | 'InsufficientDocuments' | 'InsufficientCredits' | null;\n\tmessage: string | null;\n}\n\n/** Cost-estimation response for resending a single signer notification. */\nexport type IResendCostEstimate =\n\t| IEstimateCostResponse\n\t| {\n\t\t\ttotal: number;\n\t\t\tbreakdown: Pick<IEstimateCostBreakdownItem, 'code' | 'name' | 'cost'>[];\n\t\t\tcredit_balance: number;\n\t\t\thas_sufficient_credits: boolean;\n\t };\n\n/** Webhook payload envelope. */\nexport interface IWebhookPayload {\n\tid?: number;\n\tevent?: string;\n\ttype?: string;\n\tmessage?: string | null;\n\tpayload?: Record<string, unknown> | null;\n\torigin?: Record<string, unknown> | null;\n\tsubject?: Record<string, unknown>;\n\tobject?: Record<string, unknown>;\n\taccount_id?: string;\n\tdata?: {\n\t\tdocument_uuid?: string;\n\t\tdocument_id?: string;\n\t\t[key: string]: unknown;\n\t};\n\t[key: string]: unknown;\n}\n\n/** Known webhook event names. */\nexport type WebhookEventType =\n\t| 'document_uploaded'\n\t| 'document_metadata_ready'\n\t| 'document_prepared'\n\t| 'assignment_created'\n\t| 'document_ready'\n\t| 'signature_requested'\n\t| 'signer_created'\n\t| 'signer_email_verified'\n\t| 'signer_whatsapp_verified'\n\t| 'signer_identity_verified'\n\t| 'signer_identity_verification_failed'\n\t| 'signer_identity_review_required'\n\t| 'signer_identity_review_approved'\n\t| 'signer_identity_review_rejected'\n\t| 'signer_data_confirmed'\n\t| 'signer_viewed_document'\n\t| 'signer_signed_document'\n\t| 'signer_rejected_document'\n\t| 'user_rejected_document'\n\t| 'document_processing_failed'\n\t| 'template_created'\n\t| 'template_processed'\n\t| 'template_processing_failed';\n\n/** Rendered document-page metadata returned by document and template endpoints. */\nexport interface IDocumentPage {\n\tid: string;\n\tnumber: number;\n\theight: number;\n\twidth: number;\n\tdownload_url: string;\n}\n\n/** Artifact URLs embedded in document responses. */\nexport interface IDocumentArtifacts {\n\toriginal: string;\n\tcertificated?: string;\n\t'certificate-page'?: string;\n\tpades?: string;\n\tbundle?: string;\n\tthumbnail?: string;\n}\n\n/**\n * Document listing item (paginated).\n *\n * The list endpoint auto-expands `assignment` and `pages`, so live list items\n * carry the full document shape — `artifacts`, `pages`, `assignment`,\n * `signing_url`, `decline_reason` and `declined_by` are all present (verified\n * against the sandbox). They are optional here because the exact set can vary\n * by document status.\n */\nexport interface IDocumentListItem {\n\tresource?: string;\n\tid: string;\n\tname: string;\n\tstatus: DocumentStatus;\n\taccount_id?: string;\n\ttemplate_id?: string | null;\n\t/** Tags attached to the document (inline `{ id, name, color }` shape). */\n\ttags?: IInlineTag[];\n\t/** Downloadable artifact URLs (`original` always present once processed). */\n\tartifacts?: IDocumentArtifacts;\n\t/** Rendered page metadata (auto-expanded by the list endpoint). */\n\tpages?: IDocumentPage[];\n\t/** Embedded assignment (auto-expanded); `null` before signatures are requested. */\n\tassignment?: IAssignment | null;\n\t/** Direct signing URL when an assignment is active. */\n\tsigning_url?: string | null;\n\tdecline_reason?: string | null;\n\tdeclined_by?: ISigner | string | null;\n\tcreated_at: string;\n\tupdated_at?: string;\n\tis_closed?: boolean;\n}\n\nexport type IDocumentListResponse = PaginatedResult<IDocumentListItem>;\n\n/** Query parameters accepted by `documents.list`. */\nexport interface IDocumentListParams extends IPaginationParams {\n\t/** Filter by document status, e.g. `pending_signature`. */\n\tstatus?: DocumentStatus | string;\n\t/** Filter by signature method (`virtual` or `collect`). */\n\tmethod?: AssignmentMethod;\n\t/** Comma-separated list of tag IDs (AND semantics). */\n\ttags?: string;\n\tsearch?: string;\n\tsort?: 'name' | '-name' | 'updated_at' | '-updated_at';\n}\n\n/** Query parameters accepted by the lightweight document search endpoint. */\nexport interface IDocumentSearchParams extends IPaginationParams {\n\tstatus?: DocumentStatus | string;\n\tsearch?: string;\n\t/** Live-verified extension; absent from the published OpenAPI. */\n\tsort?: 'name' | '-name' | 'updated_at' | '-updated_at';\n}\n\n/** Document upload response. */\nexport interface IDocumentUploadResponse {\n\tresource?: string;\n\tid: string;\n\taccount_id: string;\n\ttemplate_id: string | null;\n\tname: string;\n\tstatus: DocumentStatus;\n\t/** Absent immediately after upload; present once a signature request is active. */\n\tassignment?: IAssignment | null;\n\t/** Direct signing URL; present once the document has been processed. */\n\tsigning_url?: string | null;\n\tartifacts: IDocumentArtifacts;\n\tpages: IDocumentPage[];\n\t/** Tags attached to the document (inline `{ id, name, color }` shape). */\n\ttags?: IInlineTag[];\n\tcreated_at: string;\n\tupdated_at: string;\n\tis_closed: boolean;\n\tdecline_reason: string | null;\n\tdeclined_by: ISigner | null;\n}\n\n/** Detailed document response. */\nexport interface IDocumentDetailsResponse {\n\tresource?: string;\n\tid: string;\n\taccount_id: string;\n\ttemplate_id?: string | null;\n\tname: string;\n\tstatus: DocumentStatus;\n\tassignment: IAssignment | null;\n\tdownload_url?: string;\n\tdownload_final_url?: string;\n\tsigning_url?: string;\n\tartifacts?: IDocumentArtifacts;\n\t/** Omitted by the signer-side `GET /signers/{id}/document` endpoint. */\n\tpages?: IDocumentPage[];\n\t/** Tags attached to the document (inline `{ id, name, color }` shape). */\n\ttags?: IInlineTag[];\n\tcreated_at: string;\n\tupdated_at: string;\n\tis_closed: boolean;\n\tdecline_reason?: string | null;\n\tdeclined_by?: ISigner | null;\n\tactivities?: Array<IDocumentActivity>;\n}\n\nexport interface IDocumentActivity {\n\tid: number;\n\tevent: string;\n\tmessage: string;\n\t/** Event-specific payload snapshot. Object for most events, occasionally `[]`. */\n\tpayload?: Record<string, unknown> | unknown[];\n\t/** Request origin (`ip` / `user-agent`) when available; `null` for system events. */\n\torigin: { ip?: string; 'user-agent'?: string } | string | null;\n\tcreated_at: string;\n}\n\n/** Progress summary returned by `documents.getSigningProgress`. */\nexport interface ISigningProgress {\n\tsigned: number;\n\ttotal: number;\n\tpercentage: number;\n\tpending: number;\n}\n\n/** Pagination keys shared by current list endpoints. */\nexport interface IPaginationParams {\n\tpage?: number;\n\tper_page?: number;\n\t'per-page'?: number;\n}\n\n/**\n * @deprecated Use the endpoint-specific list parameter type. Retained for\n * source compatibility with existing integrations.\n */\nexport interface IListParams extends IPaginationParams {\n\tsearch?: string;\n\tsort?: string;\n\t[key: string]: string | number | boolean | undefined;\n}\n\n/** Live-verified assignment list extension; absent from the published OpenAPI. */\nexport interface IAssignmentListParams extends IPaginationParams {\n\tsort?: 'created_at' | '-created_at';\n}\n\n/** Published template filters plus a live-verified name sort extension. */\nexport interface ITemplateListParams extends IPaginationParams {\n\tsearch?: string;\n\tsort?: 'name' | '-name';\n}\n\n/** Published signer filters plus a live-verified full-name sort extension. */\nexport interface ISignerListParams extends IPaginationParams {\n\tsearch?: string;\n\tsort?: 'full_name' | '-full_name';\n}\n\n/** Signer-side document list compatibility filters. */\nexport interface ISignerDocumentListParams extends IPaginationParams {\n\tsearch?: string;\n\tsort?: string;\n}\n\n/** Workspace creation payload. */\nexport interface ICreateWorkspacePayload {\n\tname: string;\n\tnotification_sender_type?: NotificationSenderType;\n\t/** Undocumented compatibility field retained until sandbox support is disproved. */\n\tprimary_color?: string;\n\t/** Undocumented compatibility field retained until sandbox support is disproved. */\n\tsecondary_color?: string;\n}\n\nexport interface IUpdateWorkspacePayload {\n\tname?: string;\n\tnotification_sender_type?: NotificationSenderType;\n\t/** Undocumented compatibility field retained until sandbox support is disproved. */\n\tprimary_color?: string | null;\n\t/** Undocumented compatibility field retained until sandbox support is disproved. */\n\tsecondary_color?: string | null;\n}\n\nexport interface IWorkspaceResponse {\n\tresource?: string;\n\tid: string;\n\tname: string;\n\tprimary_color?: string | null;\n\tsecondary_color?: string | null;\n\tnotification_sender_type?: NotificationSenderType;\n\troles?: string[];\n\tis_delete_allowed?: boolean;\n\tcreated_at: string;\n}\n\nexport interface IWorkspaceListItem extends IWorkspaceResponse {\n\tis_delete_allowed: boolean;\n\troles: string[];\n}\n\nexport type IWorkspaceListResponse = PaginatedResult<IWorkspaceListItem>;\n\nexport type NotificationSenderType = 'User' | 'Account';\n\n/** Branding details returned by `GET /accounts/{accountId}/theme`. */\nexport interface IAccountTheme {\n\taccount_name: string;\n\tprimary_color: string;\n\tsecondary_color: string | null;\n\tlogo: string | null;\n}\n\n/** Query parameters shared by account and user document statistics. */\nexport interface IDocumentStatsParams {\n\tgranularity?: 'monthly' | 'daily';\n\t/** Required in `YYYY-MM` form when `granularity` is `daily`. */\n\tmonth?: string;\n}\n\n/** One period in an account/user document-funnel statistics response. */\nexport interface IDocumentStatsRow {\n\tperiod: string;\n\tdocuments_uploaded: number;\n\tdocuments_sent: number;\n\tsignature_requests: number;\n\t/** Requests notified by email; multi-channel requests count in each notification channel. */\n\tsignature_requests_notification_email: number;\n\t/** Requests notified by WhatsApp; multi-channel requests count in each notification channel. */\n\tsignature_requests_notification_whatsapp: number;\n\t/** Requests created without a notification. */\n\tsignature_requests_notification_bypass: number;\n\t/** Requests verified with an email token. */\n\tsignature_requests_verification_email: number;\n\t/** Requests verified with a WhatsApp token. */\n\tsignature_requests_verification_whatsapp: number;\n\t/** Requests signed without token verification. */\n\tsignature_requests_verification_bypass: number;\n\t/** Requests signed with the signer's ICP-Brasil digital certificate. */\n\tsignature_requests_verification_digital_certificate: number;\n\tsignature_requests_viewed: number;\n\tsignature_requests_completed: number;\n\tdocuments_certified: number;\n}\n\n/** Options for uploading a workspace logo. */\nexport interface IUploadAccountLogoOptions {\n\tfileName?: string;\n\tcontentType?: string;\n}\n\n/** Webhook subscription payload. */\nexport interface IWebhookRegisterPayload {\n\turl: string;\n\temail: string;\n\tevents?: WebhookEventType[] | string[];\n\tis_active?: boolean;\n}\n\nexport interface IWebhookSubscription {\n\tid?: string;\n\t/** Documented as `string|null` — `null` when no endpoint URL is configured. */\n\turl: string | null;\n\t/** Documented as `string|null` — `null` when no contact email is configured. */\n\temail: string | null;\n\tevents: string[];\n\tis_active: boolean;\n\tcreated_at?: string | null;\n\tupdated_at?: string | null;\n}\n\n/** A webhook endpoint (`/accounts/{accountId}/webhooks/endpoints`). */\nexport interface IWebhookEndpoint {\n\tid: string;\n\tname: string | null;\n\turl: string;\n\temail: string;\n\tevents: string[];\n\tis_active: boolean;\n\t/** `true` when deliveries carry a Standard Webhooks `webhook-signature` header. */\n\tsigning_enabled: boolean;\n\tcreated_at: string;\n\tupdated_at: string;\n}\n\n/** Endpoint creation includes its signing secret only when signing is enabled. */\nexport interface IWebhookEndpointCreateResponse extends IWebhookEndpoint {\n\t/** Save securely on creation; OAuth applications cannot read or rotate it later. */\n\tsecret?: string;\n}\n\n/** `POST /accounts/{accountId}/webhooks/endpoints` body. */\nexport interface IWebhookEndpointCreatePayload {\n\turl: string;\n\temail: string;\n\t/** Defaults to the SDK's standard event set when omitted. */\n\tevents?: WebhookEventType[] | string[];\n\tname?: string;\n\t/** Server default: `true`. */\n\tis_active?: boolean;\n\t/** Server default: `false`. */\n\tsigning_enabled?: boolean;\n}\n\n/** `PUT /accounts/{accountId}/webhooks/endpoints/{endpointId}` body; only sent fields change. */\nexport type IWebhookEndpointUpdatePayload = Partial<IWebhookEndpointCreatePayload>;\n\n/** Endpoint signing secret, prefixed `whsec_`. */\nexport interface IWebhookEndpointSecret {\n\tsecret: string;\n}\n\nexport interface IWebhookEventTypeInfo {\n\tid: WebhookEventType | string;\n\tdescription: string;\n}\n\nexport interface IWebhookDispatch {\n\tresource?: string;\n\tid: string;\n\tevent: WebhookEventType | string;\n\tactivity_id: number;\n\t/** Endpoint that received this delivery. */\n\tendpoint_id?: string | null;\n\tendpoint: string | null;\n\tpayload: IWebhookPayload | Record<string, unknown> | null;\n\tdelivered: boolean;\n\thttp_status: number | null;\n\tresponse_body: string | null;\n\terror: string | null;\n\t/** ISO 8601 timestamp (verified against the sandbox — not a unix epoch number). */\n\tcreated_at: string;\n\t/** ISO 8601 timestamp (verified against the sandbox — not a unix epoch number). */\n\tupdated_at?: string;\n}\n\nexport interface IWebhookDispatchListParams extends IPaginationParams {\n\t/** Only deliveries to this webhook endpoint. */\n\tendpoint_id?: string;\n\tevent?: WebhookEventType | string;\n\tdelivered?: boolean | 'true' | 'false';\n\tfrom?: number;\n\tto?: number;\n\t/** Live-verified extension; absent from the published OpenAPI. */\n\tsort?: 'created_at' | '-created_at';\n}\n\n/** Shape of the high-level `uploadAndRequestSignatures` helper result. */\nexport interface IUploadAndRequestSignaturesResult {\n\tdocument: IDocumentUploadResponse;\n\tassignment: IAssignment;\n\tsigner_ids: string[];\n}\n\n/** Input for a signer in `uploadAndRequestSignatures`. */\nexport interface IUploadAndRequestSignaturesSigner {\n\tname: string;\n\temail?: string;\n\twhatsapp_phone_number?: string;\n\t/** PHP SDK compatibility alias for `whatsapp_phone_number`. */\n\tphone?: string;\n\t/** CPF or numeric/alphanumeric CNPJ; existing email matches are reused without updating it. */\n\tgovernment_id?: string;\n\t/** Compatibility extension for a Brazilian CPF; non-digits are stripped. */\n\tcpf?: string;\n\t/** Compatibility extension for integration-defined signer metadata. */\n\tmetadata?: Record<string, unknown>;\n\tverification_method?: AssignmentVerificationMethod;\n\tnotification_methods?: AssignmentNotificationMethod[];\n\t/** Integer signing-order value forwarded to the assignment signer reference. */\n\tstep?: number;\n}\n\n/** Template role definition. */\nexport interface ITemplateRole {\n\tid: string;\n\tname: string;\n\tassignment_type?: string;\n\tcreated_at?: string;\n\tupdated_at?: string;\n\t[key: string]: unknown;\n}\n\n/** One template field placement returned inside a template page. */\nexport interface ITemplateField {\n\tid: string;\n\tfield_id: string;\n\trole_id: string;\n\tlabel: string;\n\tdisplay_settings: IDisplaySettings | unknown[] | null;\n\tcreated_at: string;\n\tupdated_at: string;\n}\n\n/** One rendered page and its editor/signer field placements. */\nexport interface ITemplatePage extends IDocumentPage {\n\tfields: ITemplateField[];\n}\n\n/** Template list item (paginated). */\nexport interface ITemplateListItem {\n\tresource?: string;\n\tid: string;\n\tname: string;\n\tdocument_name?: string | null;\n\tmessage?: string | null;\n\tstatus: string;\n\taccount_id?: string;\n\tpages?: ITemplatePage[];\n\troles?: ITemplateRole[];\n\t/** Tags attached to the template itself (inline `{ id, name }` shape). */\n\ttags?: IInlineTag[];\n\t/** Tags auto-applied to documents created from this template. */\n\tdefault_document_tags?: IInlineTag[];\n\tcreated_at: string;\n\tupdated_at?: string;\n}\n\nexport type ITemplateListResponse = PaginatedResult<ITemplateListItem>;\n\n/** Full template details, including any platform-specific extension fields. */\nexport interface ITemplateDetailsResponse extends ITemplateListItem {\n\t[key: string]: unknown;\n}\n\n/**\n * Signer assignment for creating a document from a template. `id` is required\n * here; for cost estimation it is optional — see {@link ITemplateCostSigner}.\n */\nexport interface ITemplateSigner {\n\trole_id: string;\n\tid: string;\n\tverification_method?: AssignmentVerificationMethod;\n\tnotification_methods?: AssignmentNotificationMethod[];\n\t/**\n\t * Positive signing order. If used for any role, every role needs a step and\n\t * the distinct values must form a contiguous sequence starting at 1.\n\t */\n\tstep?: number;\n}\n\n/** Signer entry accepted by the template cost-estimation endpoint. */\nexport interface ITemplateCostSigner {\n\trole_id: string;\n\tverification_method?: AssignmentVerificationMethod;\n\tnotification_methods?: AssignmentNotificationMethod[];\n\t/** Compatibility extension retained for integrations that already send a signer ID. */\n\tid?: string;\n\t/** Compatibility extension retained for integrations that already send a signing step. */\n\tstep?: number;\n}\n\n/** One editor field value baked into a generated document. */\nexport interface ITemplateEditorField {\n\tfield_id: string;\n\tvalue: string;\n}\n\n/** Options for creating a document from a template. */\nexport interface ICreateDocumentFromTemplateOptions {\n\tname?: string;\n\tmessage?: string;\n\texpires_at?: string;\n\teditor_fields?: ITemplateEditorField[];\n\t/**\n\t * Tag names to attach to the new document. Names that don't exist yet are\n\t * auto-created; the template's default-document-tags are always merged in.\n\t */\n\ttags?: string[];\n}\n\n/**\n * Item returned by `GET /documents/statuses`.\n *\n * The API uses `code` (the status name); we mirror that field. `description`\n * is documented in the table but is not currently present in the JSON payload.\n */\nexport interface IDocumentStatusInfo {\n\tcode: DocumentStatus | string;\n\tdeletable: boolean;\n\tdescription?: string;\n}\n\n/**\n * Response from `GET /documents/{signatureHash}/verify` (live-verified against\n * the sandbox). Always a `200`: an unknown/unsigned hash comes back with\n * `is_valid: false`, every other field `null` (except `hash`/`verified_at`),\n * and `message` explaining why.\n */\nexport interface IDocumentVerifyResponse {\n\thash: string;\n\tid: string | null;\n\t/** Agreement code printed on the document certificate. */\n\tagreement_code?: string | null;\n\tstatus: DocumentStatus | string | null;\n\tpage_count: string | null;\n\tsigner_count: string | null;\n\tcompleted_count: number | null;\n\tcompleted_at: string | null;\n\tverified_at: string;\n\tis_valid: boolean;\n\t/** Reason when not valid; empty string on success. */\n\tmessage: string;\n}\n\n/** Item returned by `GET /public/documents/{id}`. */\nexport interface IPublicDocumentInfo {\n\tresource?: string;\n\tid: string;\n\taccount_id: string;\n\ttemplate_id: string | null;\n\tname: string;\n\tstatus: DocumentStatus | string;\n\tartifacts: IDocumentArtifacts;\n\tis_closed: boolean;\n\tsigning_url: string | null;\n\tdecline_reason: string | null;\n\tdeclined_by: ISigner | null;\n\ttags: IInlineTag[];\n\tassignment: IAssignment | null;\n\tpages: IDocumentPage[];\n\tcreated_at: string;\n\tupdated_at: string;\n\t/** Live-compatible fields returned by older sandbox deployments. */\n\tpage_count?: string | number;\n\tcreated_by?: string;\n}\n\n/** Channel accepted by the `send-token` endpoint. Only `email` is supported. */\nexport type SendTokenChannel = 'email';\n\n/** `data` of `PUT /public/documents/{id}/send-token`. */\nexport interface ISendTokenResponse {\n\t/** Compact document; sandbox returns `page_count` as a numeric string. */\n\tdocument: {\n\t\tresource: 'document';\n\t\tid: string;\n\t\tname: string;\n\t\tpage_count: number | string;\n\t\tcreated_by: string;\n\t};\n\tchannel: SendTokenChannel;\n\t/** The signer email the token was sent to. */\n\trecipient: string;\n}\n\n/** Authentication: login response (also returned by social login). */\nexport interface IAuthUser {\n\tid: string;\n\tname: string;\n\temail: string;\n\ttelephone?: string | null;\n\tgovernment_id?: string | null;\n\tis_email_verified?: boolean;\n\thas_accepted_terms?: boolean;\n\tcreated_at?: string;\n\tto_be_deleted_at?: string | null;\n}\n\nexport interface IAuthAccount {\n\tid: string;\n\tname: string;\n\troles: string[];\n\tis_delete_allowed: boolean;\n\tcreated_at: string;\n}\n\nexport interface ILoginResponse {\n\taccess_token: string;\n\tuser: IAuthUser;\n\taccounts: IAuthAccount[];\n\t/**\n\t * Two-factor challenge returned by `POST /login` when the user has a\n\t * confirmed method. Complete it with `auth.verifyMfa` within 5 minutes.\n\t */\n\tmfa_token?: string;\n}\n\n/** `POST /authentication/mfa/verify` body. */\nexport interface IMfaVerifyPayload {\n\tmfa_token: string;\n\t/** 6-digit authenticator code or a recovery code such as `ABCD-EFGH-JKMN`. */\n\tcode: string;\n}\n\n/** An enrolled two-factor method. */\nexport interface IMfaMethod {\n\tid: string;\n\ttype: 'Totp' | (string & {});\n\tlabel: string | null;\n\tconfirmed_at: string | null;\n\tlast_used_at: string | null;\n}\n\n/** `GET /users/self/mfa` response. */\nexport interface IMfaStatus {\n\tmethods: IMfaMethod[];\n\trecovery_codes_remaining: number;\n}\n\n/** `POST /users/self/mfa/totp` response; `secret` is returned only once. */\nexport interface ITotpEnrollment {\n\tid: string;\n\tsecret: string;\n\tprovisioning_uri: string;\n}\n\n/** `PUT /users/self/mfa/totp/confirm` body. */\nexport interface ITotpConfirmPayload {\n\tid: string;\n\t/** Live code from the device being enrolled. */\n\tcode: string;\n\t/** Re-authentication, required only when replacing a confirmed method. */\n\tpassword?: string;\n\t/** Alternative re-authentication: a code from the current device or a recovery code. */\n\treauth_code?: string;\n}\n\n/** Re-authentication proof: the current password, or a live/recovery `code`. */\nexport interface IMfaReauthPayload {\n\tpassword?: string;\n\tcode?: string;\n}\n\n/** One-time recovery codes. */\nexport interface IMfaRecoveryCodes {\n\trecovery_codes: string[];\n}\n\n/**\n * `GET /users/self` is documented as a direct user, while the sandbox has also\n * returned the login-style `{ user, accounts }` object. Preserve either shape.\n */\nexport type IUserSelfResponse = IAuthUser | { user: IAuthUser; accounts: IAuthAccount[] };\n\nexport const NOTIFICATION_PREFERENCE_CODES = [\n\t'DocumentCompleted',\n\t'SignerDeclined',\n\t'DocumentCancelled',\n\t'DocumentAboutToExpire',\n\t'DocumentExpired',\n\t'DocumentExpirationReset',\n\t'DocumentProcessingFailed',\n\t'TemplateProcessingFailed',\n\t'SignerWhatsappFailed',\n] as const;\n\nexport type NotificationPreferenceCode = (typeof NOTIFICATION_PREFERENCE_CODES)[number];\nexport type INotificationPreferences = Record<NotificationPreferenceCode, boolean>;\nexport type IUpdateNotificationPreferencesPayload = Partial<INotificationPreferences>;\n\n/** Authentication: API key payload returned by `POST /users/api-keys`. */\nexport interface IApiKeyResponse {\n\tapi_key: string | null;\n}\n\n/** Authentication: masked API key returned by `GET /users/api-keys` (or null when never generated). */\nexport type IMaskedApiKeyResponse = IApiKeyResponse | null;\n\n/** Field definition object. */\nexport interface IFieldDefinition {\n\tresource?: string;\n\tid: string;\n\tname: string;\n\ttype: string;\n\tregex?: string | null;\n\tis_pre_defined?: boolean;\n\tis_active: boolean;\n\tis_required?: boolean;\n\tis_standard?: boolean;\n\tis_read_only?: boolean;\n\tis_visible?: boolean;\n}\n\n/** Payload for creating a field definition. */\nexport interface ICreateFieldPayload {\n\ttype: string;\n\tname: string;\n\t/** Validation regex; `null` or omitted for none. */\n\tregex?: string | null;\n\tis_required?: boolean;\n\t/** Compatibility extension; not present in the published create schema. */\n\tis_active?: boolean;\n}\n\n/** Payload for updating a field definition. */\nexport interface IUpdateFieldPayload {\n\t/** Compatibility extension; not present in the published update schema. */\n\ttype?: string;\n\tname?: string;\n\tregex?: string | null;\n\t/** Compatibility extension; not present in the published update schema. */\n\tis_required?: boolean;\n\tis_active?: boolean;\n}\n\n/** Field type description returned by `GET /field-types`. */\nexport interface IFieldType {\n\ttype: string;\n\tname: string;\n}\n\n/** Single result returned by `POST /accounts/{id}/fields/{id}/validate`. */\nexport interface IFieldValidationResult {\n\ttype?: string;\n\tfield_id?: string;\n\tsuccess: boolean;\n\terror_message: string;\n}\n\n/** Payload entry for `POST /accounts/{id}/fields/validate-multiple`. */\nexport interface IFieldValidateMultipleEntry {\n\tfield_id: string;\n\tvalue: unknown;\n}\n\n/** Item returned by `GET /documents/{id}/assignments/{id}/whatsapp-notifications`. */\nexport interface IWhatsAppNotification {\n\tsent_at: number;\n\theader: string;\n\tbody: string;\n\tbuttons: Array<{ text: string; url?: string }>;\n\tphone_number: string;\n\tsigner_id: string;\n}\n\n/** Body entry for the signer-side `POST /documents/{id}/assignments/{id}` sign endpoint. */\nexport interface ISignFieldEntry {\n\titemId: string;\n\tfieldId: string;\n\tpageId: string;\n\tvalue: string;\n}\n\n/**\n * Workspace tag object. Tag names are unique per workspace (case-insensitive)\n * and `color` is an optional 6-char hex string (without the leading `#`).\n */\nexport interface ITag {\n\tresource?: string;\n\tid: string;\n\tname: string;\n\tcolor: string | null;\n\tcreated_at: string;\n\tupdated_at: string;\n}\n\n/** Inline tag shape embedded inside documents/templates (`{ id, name, color? }`). */\nexport interface IInlineTag {\n\tid: string;\n\tname: string;\n\tcolor?: string | null;\n}\n\n/** Payload for `POST /accounts/{id}/tags`. */\nexport interface ICreateTagPayload {\n\tname: string;\n\t/** 6-char hex color, with or without a leading `#`. Omit/`null` for none. */\n\tcolor?: string | null;\n}\n\n/** Payload for `PUT /accounts/{id}/tags/{id}`. Omit a field to leave it unchanged. */\nexport interface IUpdateTagPayload {\n\tname?: string;\n\t/** Pass `null` to clear the color; omit to leave unchanged. */\n\tcolor?: string | null;\n}\n\n/** Confirmation returned after detaching a tag from a document. */\nexport interface IDetachTagResponse {\n\tdetached: boolean;\n}\n\n/** Confirmation returned after deleting a tag. */\nexport interface IDeleteTagResponse {\n\tdeleted: boolean;\n}\n\n/** RFC 9728 metadata served at the API origin (outside `/v1`). */\nexport interface IOAuthProtectedResource {\n\tresource: string;\n\tauthorization_servers: string[];\n\tscopes_supported: string[];\n\tbearer_methods_supported: string[];\n}\n\n/** RFC 8414 metadata served by the authorization server. */\nexport interface IOAuthAuthorizationServer {\n\tissuer: string;\n\tauthorization_endpoint: string;\n\ttoken_endpoint: string;\n\trevocation_endpoint?: string;\n\tuserinfo_endpoint?: string;\n\tjwks_uri?: string;\n\tresponse_types_supported: string[];\n\tscopes_supported?: string[];\n\tgrant_types_supported?: string[];\n\tcode_challenge_methods_supported?: string[];\n\ttoken_endpoint_auth_methods_supported?: string[];\n\tauthorization_response_iss_parameter_supported?: boolean;\n\tclient_id_metadata_document_supported?: boolean;\n\t[key: string]: unknown;\n}\n\n/** Input to `oauth.authorize`; redirectUri must exactly match an HTTPS registered URI. */\nexport interface IOAuthAuthorizationOptions {\n\tclientId: string;\n\tredirectUri: string;\n\tscopes: string[];\n}\n\n/** Store server-side per user connection attempt; consume once when handling the callback. */\nexport interface IOAuthAuthorizationRequest {\n\tauthorization_url: string;\n\tcode_verifier: string;\n\tstate: string;\n\tissuer: string;\n\tclient_id: string;\n\tredirect_uri: string;\n\tresource: string;\n\t/** Generated when requesting openid. Validate it when verifying the ID token. */\n\tnonce?: string;\n}\n\n/** Form fields for `POST /oauth/token`. PKCE is mandatory for all code exchanges. */\nexport type IOAuthTokenPayload = {\n\tclient_id: string;\n\t/** Confidential applications only; public applications omit this field. */\n\tclient_secret?: string;\n\tresource?: string;\n} & (\n\t| { grant_type: 'authorization_code'; code: string; redirect_uri: string; code_verifier: string }\n\t| { grant_type: 'refresh_token'; refresh_token: string }\n\t| {\n\t\t\t/** RFC 8693; Assinafy internal-service confidential clients only (others get `invalid_client`). */\n\t\t\tgrant_type: 'urn:ietf:params:oauth:grant-type:token-exchange';\n\t\t\tclient_secret: string;\n\t\t\t/** Required for this grant: this API's own resource identifier. */\n\t\t\tresource: string;\n\t\t\tsubject_token: string;\n\t\t\tsubject_token_type: 'urn:ietf:params:oauth:token-type:access_token';\n\t\t\trequested_token_type?: 'urn:ietf:params:oauth:token-type:access_token';\n\t }\n);\n\n/** Flat OAuth response. Persist rotated tokens atomically before making further requests. */\nexport interface IOAuthTokenResponse {\n\taccess_token: string;\n\ttoken_type: string;\n\texpires_in: number;\n\t/** Granted access-token scopes. Never lists `offline_access`; check `refresh_token` instead. */\n\tscope: string;\n\t/**\n\t * Present only with offline_access consent; always a new value after a refresh-grant `token()`.\n\t * Reusing the old token revokes the connection.\n\t */\n\trefresh_token?: string | null;\n\t/** Present only with openid. Must be verified by an OIDC library before use as identity. */\n\tid_token?: string | null;\n}\n\n/** Form fields for `POST /oauth/revoke`; failed client authentication still returns 401. */\nexport interface IOAuthRevokePayload {\n\ttoken: string;\n\tclient_id: string;\n\tclient_secret?: string;\n\ttoken_type_hint?: 'access_token' | 'refresh_token';\n}\n\n/** Flat `GET /oauth/userinfo` claims. Additional claims depend on consented scopes. */\nexport interface IOAuthUserInfo {\n\tsub: string;\n\tname?: string | null;\n\temail?: string | null;\n\temail_verified?: boolean | null;\n}\n","import { ValidationError } from '../errors.js';\nimport {\n\ttype IDocumentStatsParams,\n\ttype IDocumentStatsRow,\n\ttype INotificationPreferences,\n\ttype IUpdateNotificationPreferencesPayload,\n\ttype IUserSelfResponse,\n\tNOTIFICATION_PREFERENCE_CODES,\n} from '../types.js';\nimport { documentStatsParams } from '../utils.js';\nimport { BaseResource } from './base.js';\n\nconst NOTIFICATION_PREFERENCES = new Set<string>(NOTIFICATION_PREFERENCE_CODES);\n\n/** Authenticated user profile, statistics, and notification preferences. */\nexport class UsersResource extends BaseResource {\n\t/** Fetch the authenticated user's profile. */\n\tasync self(): Promise<IUserSelfResponse> {\n\t\treturn this.call('Failed to fetch authenticated user', () => this.http.get('/users/self'));\n\t}\n\n\t/** Fetch monthly or daily document-funnel statistics across the user's accounts. */\n\tasync stats(params: IDocumentStatsParams = {}): Promise<IDocumentStatsRow[]> {\n\t\treturn this.call('Failed to fetch user statistics', () =>\n\t\t\tthis.http.get('/users/self/stats', { params: documentStatsParams(params) }),\n\t\t);\n\t}\n\n\t/** Fetch all owner-facing email notification preferences. */\n\tasync getNotificationPreferences(): Promise<INotificationPreferences> {\n\t\treturn this.call('Failed to fetch notification preferences', () =>\n\t\t\tthis.http.get('/users/self/notification-preferences'),\n\t\t);\n\t}\n\n\t/** Merge one or more owner-facing email notification preferences. */\n\tasync updateNotificationPreferences(\n\t\tpayload: IUpdateNotificationPreferencesPayload,\n\t): Promise<INotificationPreferences> {\n\t\tif (!payload || typeof payload !== 'object' || Array.isArray(payload)) {\n\t\t\tthrow new ValidationError('Notification preferences must be an object');\n\t\t}\n\t\tconst entries = Object.entries(payload);\n\t\tif (entries.length === 0) {\n\t\t\tthrow new ValidationError('At least one notification preference is required');\n\t\t}\n\t\tfor (const [key, value] of entries) {\n\t\t\tif (!NOTIFICATION_PREFERENCES.has(key)) {\n\t\t\t\tthrow new ValidationError(`Unknown notification preference: ${key}`);\n\t\t\t}\n\t\t\tif (typeof value !== 'boolean') {\n\t\t\t\tthrow new ValidationError(`${key} must be a boolean`);\n\t\t\t}\n\t\t}\n\n\t\treturn this.call('Failed to update notification preferences', () =>\n\t\t\tthis.http.put('/users/self/notification-preferences', payload),\n\t\t);\n\t}\n}\n","import { ValidationError } from '../errors.js';\nimport type {\n\tIEmptyResult,\n\tIWebhookDispatch,\n\tIWebhookDispatchListParams,\n\tIWebhookEndpoint,\n\tIWebhookEndpointCreatePayload,\n\tIWebhookEndpointCreateResponse,\n\tIWebhookEndpointSecret,\n\tIWebhookEndpointUpdatePayload,\n\tIWebhookEventTypeInfo,\n\tIWebhookRegisterPayload,\n\tIWebhookSubscription,\n\tPaginatedResult,\n\tWebhookEventType,\n} from '../types.js';\nimport { cleanParams, requireEmail, requireSort } from '../utils.js';\nimport { BaseResource } from './base.js';\n\nconst DEFAULT_EVENTS: WebhookEventType[] = [\n\t'document_ready',\n\t'document_prepared',\n\t'signer_signed_document',\n\t'signer_rejected_document',\n\t'document_processing_failed',\n];\n\n/** Validate the webhook fields that are present; omitted fields are left to the caller. */\nfunction validateWebhookFields(payload: IWebhookEndpointUpdatePayload): void {\n\tif (payload.url !== undefined) {\n\t\tlet webhookUrl: URL;\n\t\ttry {\n\t\t\twebhookUrl = new URL(payload.url);\n\t\t} catch {\n\t\t\tthrow new ValidationError('Webhook URL must be a valid HTTP(S) URL');\n\t\t}\n\t\tif (webhookUrl.protocol !== 'http:' && webhookUrl.protocol !== 'https:') {\n\t\t\tthrow new ValidationError('Webhook URL must be a valid HTTP(S) URL');\n\t\t}\n\t}\n\tif (payload.email !== undefined) requireEmail(payload.email);\n\tif (\n\t\tpayload.events !== undefined &&\n\t\t(!Array.isArray(payload.events) ||\n\t\t\tpayload.events.some((event) => typeof event !== 'string' || !event))\n\t) {\n\t\tthrow new ValidationError('Webhook events must contain non-empty strings');\n\t}\n\tif (payload.name !== undefined && typeof payload.name !== 'string') {\n\t\tthrow new ValidationError('Webhook name must be a string');\n\t}\n\tfor (const key of ['is_active', 'signing_enabled'] as const) {\n\t\tif (payload[key] !== undefined && typeof payload[key] !== 'boolean') {\n\t\t\tthrow new ValidationError(`Webhook ${key} must be a boolean`);\n\t\t}\n\t}\n}\n\nexport class WebhookResource extends BaseResource {\n\t/**\n\t * `PUT /accounts/{accountId}/webhooks/subscriptions` — create or replace the\n\t * account's oldest webhook endpoint. Use the endpoint methods for accounts\n\t * with several endpoints or for signed deliveries.\n\t */\n\tasync register(\n\t\tpayload: IWebhookRegisterPayload,\n\t\taccountId?: string,\n\t): Promise<IWebhookSubscription> {\n\t\tif (!payload.url) throw new ValidationError('Webhook URL is required');\n\t\tvalidateWebhookFields({ ...payload, email: payload.email ?? '' });\n\n\t\tconst id = this.accountId(accountId);\n\t\tconst body = {\n\t\t\turl: payload.url,\n\t\t\temail: payload.email,\n\t\t\t// Distinguish \"omitted\" (use the sensible default set) from an\n\t\t\t// explicit empty array (the caller wants zero events).\n\t\t\tevents: payload.events ?? DEFAULT_EVENTS,\n\t\t\tis_active: payload.is_active ?? true,\n\t\t};\n\n\t\tthis.logger.info('Registering webhook', { eventCount: body.events.length });\n\n\t\treturn this.call('Failed to register webhook', () =>\n\t\t\tthis.http.put(`/accounts/${id}/webhooks/subscriptions`, body),\n\t\t);\n\t}\n\n\t/** Fetch the account's oldest webhook endpoint. Returns `null` if none exists. */\n\tasync get(accountId?: string): Promise<IWebhookSubscription | null> {\n\t\tconst id = this.accountId(accountId);\n\t\treturn this.callOptional<IWebhookSubscription>('Failed to fetch webhook subscription', () =>\n\t\t\tthis.http.get(`/accounts/${id}/webhooks/subscriptions`),\n\t\t);\n\t}\n\n\t/** Inactivate the account's oldest webhook endpoint without deleting it. */\n\tasync inactivate(accountId?: string): Promise<IWebhookSubscription> {\n\t\tconst id = this.accountId(accountId);\n\t\tthis.logger.info('Inactivating webhook subscription');\n\t\treturn this.call('Failed to inactivate webhook subscription', () =>\n\t\t\tthis.http.put(`/accounts/${id}/webhooks/inactivate`),\n\t\t);\n\t}\n\n\t/** List webhook endpoints, oldest first; `url` matches the registered value exactly. */\n\tasync listEndpoints(\n\t\taccountId?: string,\n\t\tparams: { url?: string } = {},\n\t): Promise<IWebhookEndpoint[]> {\n\t\tconst id = this.accountId(accountId);\n\t\tvalidateWebhookFields(params);\n\t\treturn this.call('Failed to list webhook endpoints', () =>\n\t\t\tthis.http.get(`/accounts/${id}/webhooks/endpoints`, { params: cleanParams({ ...params }) }),\n\t\t);\n\t}\n\n\t/**\n\t * `POST /accounts/{accountId}/webhooks/endpoints` — register another\n\t * endpoint. Accounts allow 1 endpoint, or up to 3 on paid plans (`403` past\n\t * the limit); URLs must be unique per workspace. Omitted `events` uses the\n\t * same default set as {@link register}. Signed creation returns `secret`\n\t * once, including to OAuth applications; save it securely.\n\t */\n\tasync createEndpoint(\n\t\tpayload: IWebhookEndpointCreatePayload,\n\t\taccountId?: string,\n\t): Promise<IWebhookEndpointCreateResponse> {\n\t\tif (!payload.url) throw new ValidationError('Webhook URL is required');\n\t\tvalidateWebhookFields({ ...payload, email: payload.email ?? '' });\n\t\tconst id = this.accountId(accountId);\n\t\tconst body = { ...payload, events: payload.events ?? DEFAULT_EVENTS };\n\t\tthis.logger.info('Creating webhook endpoint', { eventCount: body.events.length });\n\t\treturn this.call('Failed to create webhook endpoint', () =>\n\t\t\tthis.http.post(`/accounts/${id}/webhooks/endpoints`, body),\n\t\t);\n\t}\n\n\t/** `GET /accounts/{accountId}/webhooks/endpoints/{endpointId}` — fetch one endpoint. */\n\tasync getEndpoint(endpointId: string, accountId?: string): Promise<IWebhookEndpoint> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst eid = this.requireId(endpointId, 'Endpoint ID');\n\t\treturn this.call('Failed to fetch webhook endpoint', () =>\n\t\t\tthis.http.get(`/accounts/${id}/webhooks/endpoints/${eid}`),\n\t\t);\n\t}\n\n\t/**\n\t * `PUT /accounts/{accountId}/webhooks/endpoints/{endpointId}` — update only\n\t * the fields sent. Enabling signing creates a secret when none exists;\n\t * disabling it discards the secret.\n\t */\n\tasync updateEndpoint(\n\t\tendpointId: string,\n\t\tpayload: IWebhookEndpointUpdatePayload,\n\t\taccountId?: string,\n\t): Promise<IWebhookEndpoint> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst eid = this.requireId(endpointId, 'Endpoint ID');\n\t\tif (!payload || typeof payload !== 'object' || Object.keys(payload).length === 0) {\n\t\t\tthrow new ValidationError('At least one webhook endpoint field is required');\n\t\t}\n\t\tvalidateWebhookFields(payload);\n\t\treturn this.call('Failed to update webhook endpoint', () =>\n\t\t\tthis.http.put(`/accounts/${id}/webhooks/endpoints/${eid}`, payload),\n\t\t);\n\t}\n\n\t/** `DELETE /accounts/{accountId}/webhooks/endpoints/{endpointId}` — delete an endpoint and free its slot. */\n\tasync deleteEndpoint(endpointId: string, accountId?: string): Promise<IEmptyResult> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst eid = this.requireId(endpointId, 'Endpoint ID');\n\t\treturn this.call('Failed to delete webhook endpoint', () =>\n\t\t\tthis.http.delete(`/accounts/${id}/webhooks/endpoints/${eid}`),\n\t\t);\n\t}\n\n\t/** Delete the endpoint whose URL exactly matches `url`; returns 404 when none matches. */\n\tasync deleteEndpointByUrl(url: string, accountId?: string): Promise<IEmptyResult> {\n\t\tif (!url) throw new ValidationError('Webhook URL is required');\n\t\tvalidateWebhookFields({ url });\n\t\tconst id = this.accountId(accountId);\n\t\treturn this.call('Failed to delete webhook endpoint by URL', () =>\n\t\t\tthis.http.delete(`/accounts/${id}/webhooks/endpoints`, { params: { url } }),\n\t\t);\n\t}\n\n\t/**\n\t * `GET …/endpoints/{endpointId}/secret` — the `whsec_` signing secret.\n\t * Returns `400` when signing is disabled. Not available to OAuth applications.\n\t */\n\tasync getEndpointSecret(endpointId: string, accountId?: string): Promise<IWebhookEndpointSecret> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst eid = this.requireId(endpointId, 'Endpoint ID');\n\t\treturn this.call('Failed to fetch webhook endpoint secret', () =>\n\t\t\tthis.http.get(`/accounts/${id}/webhooks/endpoints/${eid}/secret`),\n\t\t);\n\t}\n\n\t/**\n\t * `POST …/endpoints/{endpointId}/secret/rotate` — replace the signing secret.\n\t * The old secret stops working immediately. Not available to OAuth applications.\n\t */\n\tasync rotateEndpointSecret(\n\t\tendpointId: string,\n\t\taccountId?: string,\n\t): Promise<IWebhookEndpointSecret> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst eid = this.requireId(endpointId, 'Endpoint ID');\n\t\tthis.logger.info('Rotating webhook endpoint secret');\n\t\treturn this.call('Failed to rotate webhook endpoint secret', () =>\n\t\t\tthis.http.post(`/accounts/${id}/webhooks/endpoints/${eid}/secret/rotate`),\n\t\t);\n\t}\n\n\t/** List currently supported webhook event types. */\n\tasync listEventTypes(): Promise<IWebhookEventTypeInfo[]> {\n\t\treturn this.call('Failed to list webhook event types', () =>\n\t\t\tthis.http.get('/webhooks/event-types'),\n\t\t);\n\t}\n\n\t/** List webhook delivery history for the workspace, optionally for one endpoint. */\n\tasync listDispatches(\n\t\tparams: IWebhookDispatchListParams = {},\n\t\taccountId?: string,\n\t): Promise<PaginatedResult<IWebhookDispatch>> {\n\t\tconst id = this.accountId(accountId);\n\t\tif ('search' in params) throw new ValidationError('webhook dispatch search is not supported');\n\t\trequireSort(params.sort, ['created_at', '-created_at']);\n\t\treturn this.callList<IWebhookDispatch>('Failed to list webhook dispatches', () =>\n\t\t\tthis.http.get(`/accounts/${id}/webhooks`, {\n\t\t\t\tparams: cleanParams(params as unknown as Record<string, unknown>),\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** Retry delivery of a specific webhook dispatch to that entry's endpoint. */\n\tasync retryDispatch(dispatchId: string, accountId?: string): Promise<IWebhookDispatch> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst did = this.requireId(dispatchId, 'Dispatch ID');\n\t\treturn this.call('Failed to retry webhook dispatch', () =>\n\t\t\tthis.http.post(`/accounts/${id}/webhooks/${did}/retry`),\n\t\t);\n\t}\n}\n","import { ValidationError } from '../errors.js';\nimport type {\n\tIAccountTheme,\n\tICreateWorkspacePayload,\n\tIDocumentStatsParams,\n\tIDocumentStatsRow,\n\tIEmptyResult,\n\tIStatusResponse,\n\tIUpdateWorkspacePayload,\n\tIUploadAccountLogoOptions,\n\tIWorkspaceListItem,\n\tIWorkspaceListResponse,\n\tIWorkspaceResponse,\n} from '../types.js';\nimport { appendFilePart, documentStatsParams } from '../utils.js';\nimport { BaseResource } from './base.js';\n\nexport class WorkspaceResource extends BaseResource {\n\t/** Create a new workspace. */\n\tasync create(payload: ICreateWorkspacePayload): Promise<IWorkspaceResponse> {\n\t\tif (!payload.name?.trim()) {\n\t\t\tthrow new ValidationError('Workspace name is required');\n\t\t}\n\t\tvalidateNotificationSender(payload.notification_sender_type);\n\t\treturn this.call('Failed to create workspace', () => this.http.post('/accounts', payload));\n\t}\n\n\t/** List workspaces the authenticated user can access. */\n\tasync list(): Promise<IWorkspaceListResponse> {\n\t\treturn this.callList<IWorkspaceListItem>('Failed to list workspaces', () =>\n\t\t\tthis.http.get('/accounts'),\n\t\t);\n\t}\n\n\t/** Fetch a single workspace. */\n\tasync get(accountId: string): Promise<IWorkspaceResponse> {\n\t\tconst id = this.requireId(accountId, 'Account ID');\n\t\treturn this.call('Failed to fetch workspace', () => this.http.get(`/accounts/${id}`));\n\t}\n\n\t/** Fetch the workspace's public branding theme. */\n\tasync getTheme(accountId: string): Promise<IAccountTheme> {\n\t\tconst id = this.requireId(accountId, 'Account ID');\n\t\treturn this.call('Failed to fetch workspace theme', () =>\n\t\t\tthis.http.get(`/accounts/${id}/theme`),\n\t\t);\n\t}\n\n\t/** Download the workspace logo image. */\n\tasync downloadLogo(accountId: string): Promise<Buffer> {\n\t\tconst id = this.requireId(accountId, 'Account ID');\n\t\treturn this.callBinary('Failed to download workspace logo', () =>\n\t\t\tthis.http.get<ArrayBuffer>(`/accounts/${id}/logo`, { responseType: 'arraybuffer' }),\n\t\t);\n\t}\n\n\t/** Upload or replace the workspace logo image. */\n\tasync uploadLogo(\n\t\taccountId: string,\n\t\tlogo: Buffer,\n\t\toptions: IUploadAccountLogoOptions = {},\n\t): Promise<IStatusResponse> {\n\t\tconst id = this.requireId(accountId, 'Account ID');\n\t\tif (!Buffer.isBuffer(logo) || logo.byteLength === 0) {\n\t\t\tthrow new ValidationError('Logo buffer is required');\n\t\t}\n\n\t\tconst contentType = options.contentType ?? 'image/png';\n\t\tconst form = new FormData();\n\t\tappendFilePart(form, logo, contentType, options.fileName ?? 'logo.png');\n\n\t\treturn this.call('Failed to upload workspace logo', () =>\n\t\t\tthis.http.post(`/accounts/${id}/logo`, form, {\n\t\t\t\theaders: { 'Content-Type': 'multipart/form-data' },\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** Delete the workspace logo. */\n\tasync deleteLogo(accountId: string): Promise<IStatusResponse> {\n\t\tconst id = this.requireId(accountId, 'Account ID');\n\t\treturn this.call('Failed to delete workspace logo', () =>\n\t\t\tthis.http.delete(`/accounts/${id}/logo`),\n\t\t);\n\t}\n\n\t/** Fetch monthly or daily document-funnel statistics for a workspace. */\n\tasync stats(accountId: string, params: IDocumentStatsParams = {}): Promise<IDocumentStatsRow[]> {\n\t\tconst id = this.requireId(accountId, 'Account ID');\n\t\treturn this.call('Failed to fetch workspace statistics', () =>\n\t\t\tthis.http.get(`/accounts/${id}/stats`, { params: documentStatsParams(params) }),\n\t\t);\n\t}\n\n\t/** Update a workspace. */\n\tasync update(accountId: string, payload: IUpdateWorkspacePayload): Promise<IWorkspaceResponse> {\n\t\tconst id = this.requireId(accountId, 'Account ID');\n\t\tvalidateNotificationSender(payload.notification_sender_type);\n\t\treturn this.call('Failed to update workspace', () => this.http.put(`/accounts/${id}`, payload));\n\t}\n\n\t/**\n\t * Delete a workspace.\n\t *\n\t * By default fails with `ApiError` (400) if the workspace has an active\n\t * paid subscription; pass `{ force: true }` to cancel it and delete anyway.\n\t */\n\tasync delete(accountId: string, options: { force?: boolean } = {}): Promise<IEmptyResult> {\n\t\tconst id = this.requireId(accountId, 'Account ID');\n\t\treturn this.call('Failed to delete workspace', () =>\n\t\t\tthis.http.delete(`/accounts/${id}`, options.force ? { data: { force: true } } : undefined),\n\t\t);\n\t}\n}\n\nfunction validateNotificationSender(value: string | undefined): void {\n\tif (value !== undefined && value !== 'User' && value !== 'Account') {\n\t\tthrow new ValidationError('notification_sender_type must be User or Account');\n\t}\n}\n","import { createHmac, timingSafeEqual } from 'node:crypto';\nimport type { IWebhookPayload } from '../types.js';\n\n/** Options for the legacy {@link WebhookVerifier.verify} body-only HMAC. */\nexport interface WebhookVerifierOptions {\n\t/** HMAC hash algorithm. Defaults to `sha256`. */\n\talgorithm?: string;\n\t/** Digest encoding of the signature value. Defaults to `hex`. */\n\tencoding?: 'hex' | 'base64';\n}\n\n/** Request headers as Node (`IncomingHttpHeaders`), a plain record, or a Fetch `Headers`. */\nexport type WebhookHeaders = Headers | Record<string, string | string[] | undefined>;\n\n/** Options for {@link WebhookVerifier.verifyDelivery}. */\nexport interface WebhookDeliveryOptions {\n\t/** Maximum clock difference accepted for `webhook-timestamp`. Defaults to 300 seconds. */\n\ttoleranceSeconds?: number;\n\t/** Current time in milliseconds. Defaults to `Date.now()`. */\n\tnow?: number;\n}\n\n/** Case-insensitive single-value header lookup; repeated headers are rejected. */\nfunction readHeader(headers: WebhookHeaders, name: string): string | undefined {\n\tif (typeof (headers as Headers).get === 'function') {\n\t\treturn (headers as Headers).get(name) ?? undefined;\n\t}\n\tconst matches = Object.entries(headers).filter(([key]) => key.toLowerCase() === name);\n\tif (matches.length !== 1) return undefined;\n\tconst value = matches[0]?.[1];\n\treturn Array.isArray(value) ? (value.length === 1 ? value[0] : undefined) : value;\n}\n\n/**\n * Verifies Assinafy webhook deliveries and parses their JSON envelope.\n *\n * Endpoints with `signing_enabled: true` sign each delivery following the\n * Standard Webhooks specification: `webhook-signature` carries one or more\n * space-separated `v1,<base64>` HMAC-SHA256 values over\n * `{webhook-id}.{webhook-timestamp}.{raw body}`, keyed with the base64 part of\n * the endpoint's `whsec_` secret. Use {@link verifyDelivery} with the raw\n * request body and headers; deduplicate accepted deliveries by `webhook-id`.\n */\nexport class WebhookVerifier {\n\tprivate readonly algorithm: string;\n\tprivate readonly encoding: 'hex' | 'base64';\n\n\tconstructor(\n\t\tprivate readonly webhookSecret?: string,\n\t\toptions: WebhookVerifierOptions = {},\n\t) {\n\t\tthis.algorithm = options.algorithm ?? 'sha256';\n\t\tthis.encoding = options.encoding ?? 'hex';\n\t}\n\n\t/**\n\t * Returns `true` when `headers` carry a Standard Webhooks signature that\n\t * matches the raw `payload` under this verifier's `whsec_` secret and the\n\t * `webhook-timestamp` is within the tolerance window. Pass the body exactly\n\t * as received; re-serialized JSON does not verify.\n\t */\n\tverifyDelivery(\n\t\tpayload: string | Buffer,\n\t\theaders: WebhookHeaders,\n\t\toptions: WebhookDeliveryOptions = {},\n\t): boolean {\n\t\tif (!this.webhookSecret || !headers) return false;\n\t\tconst id = readHeader(headers, 'webhook-id');\n\t\tconst timestamp = readHeader(headers, 'webhook-timestamp');\n\t\tconst signatures = readHeader(headers, 'webhook-signature');\n\t\tif (!id || !timestamp || !signatures || !/^\\d+$/.test(timestamp)) return false;\n\n\t\tconst tolerance = options.toleranceSeconds ?? 300;\n\t\tconst now = Math.floor((options.now ?? Date.now()) / 1000);\n\t\tif (\n\t\t\t!Number.isFinite(tolerance) ||\n\t\t\ttolerance < 0 ||\n\t\t\t!Number.isSafeInteger(now) ||\n\t\t\tnow < 0 ||\n\t\t\t!Number.isSafeInteger(Number(timestamp)) ||\n\t\t\tMath.abs(now - Number(timestamp)) > tolerance\n\t\t)\n\t\t\treturn false;\n\n\t\tconst secret = this.webhookSecret.startsWith('whsec_')\n\t\t\t? this.webhookSecret.slice('whsec_'.length)\n\t\t\t: this.webhookSecret;\n\t\tconst key = Buffer.from(secret, 'base64');\n\t\tif (key.length === 0) return false;\n\t\tconst expected = Buffer.from(\n\t\t\tcreateHmac('sha256', key)\n\t\t\t\t.update(`${id}.${timestamp}.`)\n\t\t\t\t.update(typeof payload === 'string' ? Buffer.from(payload, 'utf8') : payload)\n\t\t\t\t.digest('base64'),\n\t\t);\n\n\t\treturn signatures.split(' ').some((entry) => {\n\t\t\tconst [version, value, extra] = entry.split(',');\n\t\t\tif (version !== 'v1' || !value || extra !== undefined) return false;\n\t\t\tconst provided = Buffer.from(value);\n\t\t\treturn provided.length === expected.length && timingSafeEqual(provided, expected);\n\t\t});\n\t}\n\n\t/**\n\t * Returns `true` if `signature` is an HMAC of `payload` keyed with the raw\n\t * secret string under the configured algorithm/encoding.\n\t *\n\t * @deprecated Assinafy signs deliveries with Standard Webhooks headers; use\n\t * {@link verifyDelivery}. Retained for existing callers.\n\t */\n\tverify(payload: string | Buffer, signature: string): boolean {\n\t\tif (!this.webhookSecret || !signature) return false;\n\t\ttry {\n\t\t\tconst buf = typeof payload === 'string' ? Buffer.from(payload, 'utf8') : payload;\n\t\t\tconst expected = createHmac(this.algorithm, this.webhookSecret)\n\t\t\t\t.update(buf)\n\t\t\t\t.digest(this.encoding);\n\t\t\tconst a = Buffer.from(expected, 'utf8');\n\t\t\tconst b = Buffer.from(signature.trim(), 'utf8');\n\t\t\tif (a.length !== b.length) return false;\n\t\t\treturn timingSafeEqual(a, b);\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/** Parse the raw webhook body into a JSON event envelope. */\n\textractEvent(payload: string | Buffer): IWebhookPayload | null {\n\t\ttry {\n\t\t\tconst text = typeof payload === 'string' ? payload : payload.toString('utf8');\n\t\t\tconst parsed = JSON.parse(text) as IWebhookPayload;\n\t\t\t// Only a JSON object is a valid envelope — reject arrays and primitives.\n\t\t\treturn parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/** Extract the event name (`event` or `type`) from an event envelope. */\n\tgetEventType(event: IWebhookPayload | null | undefined): string | null {\n\t\tif (!event || typeof event !== 'object') return null;\n\t\tconst e = event as IWebhookPayload & { type?: unknown };\n\t\tif (typeof e.event === 'string') return e.event;\n\t\treturn typeof e.type === 'string' ? e.type : null;\n\t}\n\n\t/**\n\t * Extract the event data from an event envelope.\n\t *\n\t * The per-event data may live under `payload`, `data`, or `object`; only a\n\t * non-array JSON object is returned.\n\t */\n\tgetEventData(event: IWebhookPayload | null | undefined): Record<string, unknown> {\n\t\tif (!event || typeof event !== 'object') return {};\n\t\tconst e = event as IWebhookPayload & { object?: Record<string, unknown> };\n\t\tfor (const candidate of [e.payload, e.data, e.object]) {\n\t\t\tif (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\t\treturn {};\n\t}\n}\n"],"mappings":";AAAA,OAAOA,YAAmC;;;ACCnC,IAAM,gBAAN,cAA4B,MAAM;AAAA,EACxB;AAAA,EAEhB,YACC,SACA,UAAmC,CAAC,GAC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S,QAAQ,SAAS;AACpE,kBAAU,KAAK,QAAQ,EAAE;AACzB,cAAM,cAAc,UAAU,UAAa,OAAO,UAAU;AAC5D,0BAAkB,KAAK;AAAA,UACtB,IAAI,QAAQ;AAAA,UACZ,qBAAqB,OAAO,wBAAwB,cAAc,aAAa;AAAA,UAC/E,sBACC,OAAO,yBAAyB,cAAc,CAAC,UAAU,IAAI;AAAA,UAC9D,MAAM,OAAO;AAAA,QACd,CAAC;AAAA,MACF;AAEA,YAAM,oBAA8C;AAAA,QACnD,QAAQ;AAAA,QACR,SAAS;AAAA,MACV;AACA,UAAI,QAAQ,YAAY,OAAW,mBAAkB,UAAU,QAAQ;AACvE,UAAI,QAAQ,cAAc,OAAW,mBAAkB,aAAa,QAAQ;AAC5E,UAAI,QAAQ,kBAAkB;AAC7B,0BAAkB,iBAAiB,QAAQ;AAE5C,YAAM,aAAa,MAAM,KAAK,YAAY,OAAO,SAAS,IAAI,iBAAiB;AAE/E,WAAK,OAAO,KAAK,yCAAyC,EAAE,YAAY,SAAS,GAAG,CAAC;AAErF,aAAO,EAAE,UAAU,YAAY,YAAY,UAAU;AAAA,IACtD,SAAS,KAAK;AACb,WAAK,OAAO,MAAM,+DAA+D;AAAA,QAChF,YAAY,SAAS;AAAA,QACrB;AAAA,MACD,CAAC;AACD,YAAM,SAAS,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC9D,YAAM,IAAI;AAAA,QACT,GAAG,MAAM,cAAc,SAAS,EAAE,YAAY,UAAU,MAAM;AAAA,QAC9D,EAAE,YAAY,SAAS,IAAI,UAAU;AAAA,QACrC,EAAE,OAAO,IAAI;AAAA,MACd;AAAA,IACD;AAAA,EACD;AAAA;AAAA,EAGA,mBAAkC;AACjC,WAAO,KAAK;AAAA,EACb;AACD;","names":["axios","expected","actual","timingSafeEqual","axios"]}
|
|
1
|
+
{"version":3,"sources":["../src/api/client.ts","../src/api/errors.ts","../src/api/utils.ts","../src/api/resources/base.ts","../src/api/resources/assignments.ts","../src/api/resources/authentication.ts","../src/api/resources/documents.ts","../src/api/resources/fields.ts","../src/api/resources/oauth.ts","../src/api/resources/signer-documents.ts","../src/api/resources/signers.ts","../src/api/resources/tags.ts","../src/api/resources/templates.ts","../src/api/types.ts","../src/api/resources/users.ts","../src/api/resources/webhooks.ts","../src/api/resources/workspaces.ts","../src/api/support/webhook-verifier.ts"],"sourcesContent":["import axios, { type AxiosInstance } from 'axios';\nimport { PartialWorkflowError, ValidationError } from './errors.js';\nimport { AssignmentResource } from './resources/assignments.js';\nimport { AuthenticationResource } from './resources/authentication.js';\nimport { DocumentResource, type DocumentUploadSource } from './resources/documents.js';\nimport { FieldsResource } from './resources/fields.js';\nimport { OAuthResource } from './resources/oauth.js';\nimport { SignerDocumentsResource } from './resources/signer-documents.js';\nimport { SignerResource, validateCreateSignerPayload } from './resources/signers.js';\nimport { TagResource } from './resources/tags.js';\nimport { TemplateResource } from './resources/templates.js';\nimport { UsersResource } from './resources/users.js';\nimport { WebhookResource } from './resources/webhooks.js';\nimport { WorkspaceResource } from './resources/workspaces.js';\nimport { WebhookVerifier } from './support/webhook-verifier.js';\nimport type {\n\tAssinafyClientOptions,\n\tICreateAssignmentPayload,\n\tICreateSignerPayload,\n\tIUploadAndRequestSignaturesResult,\n\tIUploadAndRequestSignaturesSigner,\n\tLogger,\n\tSignerReference,\n} from './types.js';\nimport {\n\tcreateNoopLogger,\n\tnormalizeBaseUrl,\n\trequireIso8601,\n\tvalidateSignerOptions,\n\tvalidateSigningSteps,\n} from './utils.js';\n\n/** Flexible input accepted by {@link AssinafyClient.fromConfig} (snake_case or camelCase). */\nexport interface ClientConfigInput {\n\tapi_key?: string;\n\tapiKey?: string;\n\ttoken?: string;\n\taccess_token?: string;\n\taccessToken?: string;\n\taccount_id?: string;\n\taccountId?: string;\n\tbase_url?: string;\n\tbaseUrl?: string;\n\twebhook_secret?: string;\n\twebhookSecret?: string;\n\ttimeout?: number;\n\tlogger?: Logger;\n\tallow_unauthenticated?: boolean;\n\tallowUnauthenticated?: boolean;\n\tallow_insecure_http?: boolean;\n\tallowInsecureHttp?: boolean;\n}\n\nconst DEFAULT_BASE_URL = 'https://api.assinafy.com.br/v1';\n\n/** Hosts that never leave the machine, so plaintext HTTP cannot expose a key. */\nfunction isLoopbackHost(hostname: string): boolean {\n\treturn (\n\t\thostname === 'localhost' ||\n\t\thostname === '[::1]' ||\n\t\t/^127(?:\\.(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)){3}$/.test(hostname)\n\t);\n}\n\n/**\n * Primary entry point for the Assinafy API.\n *\n * @example\n * ```ts\n * const client = new AssinafyClient({\n * apiKey: process.env.ASSINAFY_API_KEY!,\n * accountId: process.env.ASSINAFY_ACCOUNT_ID!,\n * webhookSecret: process.env.ASSINAFY_WEBHOOK_SECRET,\n * });\n *\n * const document = await client.documents.upload({ filePath: './contract.pdf' });\n * ```\n */\nexport class AssinafyClient {\n\tprivate readonly axiosInstance: AxiosInstance;\n\tprivate readonly defaultAccountId: string | undefined;\n\tprivate readonly logger: Logger;\n\tprivate readonly webhookSecret: string | undefined;\n\n\tpublic readonly documents: DocumentResource;\n\tpublic readonly signers: SignerResource;\n\tpublic readonly workspaces: WorkspaceResource;\n\tpublic readonly assignments: AssignmentResource;\n\tpublic readonly webhooks: WebhookResource;\n\tpublic readonly templates: TemplateResource;\n\tpublic readonly tags: TagResource;\n\tpublic readonly auth: AuthenticationResource;\n\tpublic readonly oauth: OAuthResource;\n\tpublic readonly fields: FieldsResource;\n\tpublic readonly users: UsersResource;\n\tpublic readonly signerDocuments: SignerDocumentsResource;\n\tpublic readonly webhookVerifier: WebhookVerifier;\n\n\tconstructor(options: AssinafyClientOptions) {\n\t\tif (!options.apiKey && !options.token && !options.allowUnauthenticated) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'An API key (options.apiKey) or access token (options.token) is required.',\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\toptions.timeout !== undefined &&\n\t\t\t(!Number.isFinite(options.timeout) || options.timeout <= 0)\n\t\t) {\n\t\t\tthrow new ValidationError('timeout must be a finite positive number');\n\t\t}\n\n\t\tthis.defaultAccountId = options.accountId;\n\t\tthis.logger = options.logger ?? createNoopLogger();\n\t\tthis.webhookSecret = options.webhookSecret;\n\n\t\tconst baseURL = normalizeBaseUrl(options.baseUrl ?? DEFAULT_BASE_URL);\n\t\tlet parsedBaseUrl: URL;\n\t\ttry {\n\t\t\tparsedBaseUrl = new URL(baseURL);\n\t\t} catch {\n\t\t\tthrow new ValidationError('baseUrl must be an absolute HTTP(S) URL');\n\t\t}\n\t\tif (parsedBaseUrl.protocol !== 'https:') {\n\t\t\tif (parsedBaseUrl.protocol !== 'http:' || !options.allowInsecureHttp) {\n\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t'baseUrl must use HTTPS; set allowInsecureHttp only for a loopback development server',\n\t\t\t\t);\n\t\t\t}\n\t\t\t// The escape hatch exists for a dev server on this machine. Allowing an\n\t\t\t// arbitrary host would put the API key on the wire in cleartext, so the\n\t\t\t// flag alone is not enough — the host has to be loopback.\n\t\t\tif (!isLoopbackHost(parsedBaseUrl.hostname)) {\n\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t'allowInsecureHttp only permits a loopback baseUrl (localhost, 127.0.0.0/8, or ::1)',\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (parsedBaseUrl.username || parsedBaseUrl.password) {\n\t\t\tthrow new ValidationError('baseUrl must not contain embedded credentials');\n\t\t}\n\t\tif (parsedBaseUrl.search || parsedBaseUrl.hash) {\n\t\t\tthrow new ValidationError('baseUrl must not contain a query string or fragment');\n\t\t}\n\t\tconst headers: Record<string, string> = {\n\t\t\t'Content-Type': 'application/json',\n\t\t\tAccept: 'application/json',\n\t\t\t'User-Agent': 'assinafy-cli',\n\t\t};\n\t\tif (options.apiKey) {\n\t\t\theaders['X-Api-Key'] = options.apiKey;\n\t\t} else if (options.token) {\n\t\t\theaders.Authorization = `Bearer ${options.token}`;\n\t\t}\n\n\t\tthis.axiosInstance = axios.create({\n\t\t\tbaseURL,\n\t\t\ttimeout: options.timeout ?? 30_000,\n\t\t\theaders,\n\t\t\tmaxRedirects: 0,\n\t\t});\n\n\t\tthis.documents = new DocumentResource(this.axiosInstance, this.defaultAccountId, this.logger);\n\t\tthis.signers = new SignerResource(this.axiosInstance, this.defaultAccountId, this.logger);\n\t\tthis.workspaces = new WorkspaceResource(this.axiosInstance, undefined, this.logger);\n\t\tthis.assignments = new AssignmentResource(\n\t\t\tthis.axiosInstance,\n\t\t\tthis.defaultAccountId,\n\t\t\tthis.logger,\n\t\t);\n\t\tthis.webhooks = new WebhookResource(this.axiosInstance, this.defaultAccountId, this.logger);\n\t\tthis.templates = new TemplateResource(this.axiosInstance, this.defaultAccountId, this.logger);\n\t\tthis.tags = new TagResource(this.axiosInstance, this.defaultAccountId, this.logger);\n\t\tthis.auth = new AuthenticationResource(this.axiosInstance, undefined, this.logger);\n\t\tthis.oauth = new OAuthResource(this.axiosInstance, undefined, this.logger);\n\t\tthis.fields = new FieldsResource(this.axiosInstance, this.defaultAccountId, this.logger);\n\t\tthis.users = new UsersResource(this.axiosInstance, undefined, this.logger);\n\t\tthis.signerDocuments = new SignerDocumentsResource(\n\t\t\tthis.axiosInstance,\n\t\t\tthis.defaultAccountId,\n\t\t\tthis.logger,\n\t\t);\n\t\tthis.webhookVerifier = new WebhookVerifier(this.webhookSecret);\n\t}\n\n\t/** Convenience factory for the common apiKey + accountId setup. */\n\tstatic create(\n\t\tapiKey: string,\n\t\taccountId: string,\n\t\toptions: Omit<AssinafyClientOptions, 'apiKey' | 'accountId'> = {},\n\t): AssinafyClient {\n\t\treturn new AssinafyClient({ ...options, apiKey, accountId });\n\t}\n\n\t/** Build a client from a plain object (supports snake_case and camelCase keys). */\n\tstatic fromConfig(config: ClientConfigInput): AssinafyClient {\n\t\tconst opts: AssinafyClientOptions = {};\n\t\tconst apiKey = config.api_key ?? config.apiKey;\n\t\tconst token = config.token ?? config.access_token ?? config.accessToken;\n\t\tconst accountId = config.account_id ?? config.accountId;\n\t\tconst baseUrl = config.base_url ?? config.baseUrl;\n\t\tconst webhookSecret = config.webhook_secret ?? config.webhookSecret;\n\t\tif (apiKey !== undefined) opts.apiKey = apiKey;\n\t\tif (token !== undefined) opts.token = token;\n\t\tif (accountId !== undefined) opts.accountId = accountId;\n\t\tif (baseUrl !== undefined) opts.baseUrl = baseUrl;\n\t\tif (webhookSecret !== undefined) opts.webhookSecret = webhookSecret;\n\t\tif (config.timeout !== undefined) opts.timeout = config.timeout;\n\t\tif (config.logger !== undefined) opts.logger = config.logger;\n\t\topts.allowInsecureHttp = config.allow_insecure_http ?? config.allowInsecureHttp ?? false;\n\t\topts.allowUnauthenticated =\n\t\t\tconfig.allow_unauthenticated ?? config.allowUnauthenticated ?? false;\n\t\treturn new AssinafyClient(opts);\n\t}\n\n\t/**\n\t * High-level helper that uploads a PDF, ensures it's processed, creates any\n\t * missing signers, and kicks off a virtual signature assignment.\n\t *\n\t * Once the upload succeeds the workflow owns real workspace resources, so any\n\t * later failure is rethrown as a {@link PartialWorkflowError} carrying the\n\t * document and signer IDs that already exist. Catch it to resume or clean up;\n\t * nothing is deleted automatically.\n\t */\n\tasync uploadAndRequestSignatures(options: {\n\t\tsource: DocumentUploadSource;\n\t\tsigners: IUploadAndRequestSignaturesSigner[];\n\t\tmessage?: string;\n\t\tmetadata?: Record<string, unknown>;\n\t\twaitForReady?: boolean;\n\t\texpiresAt?: string;\n\t\tcopyReceivers?: string[];\n\t\taccountId?: string;\n\t}): Promise<IUploadAndRequestSignaturesResult> {\n\t\tif (!Array.isArray(options.signers) || options.signers.length === 0) {\n\t\t\tthrow new ValidationError('At least one signer is required');\n\t\t}\n\t\tif (options.expiresAt !== undefined) requireIso8601(options.expiresAt, 'expiresAt');\n\t\tconst preparedSigners = options.signers.map((signer) => {\n\t\t\tif (!signer || typeof signer !== 'object') {\n\t\t\t\tthrow new ValidationError('Each signer must be an object');\n\t\t\t}\n\t\t\tvalidateSignerOptions(signer);\n\t\t\tconst payload: ICreateSignerPayload = { full_name: signer.name };\n\t\t\tif (signer.email !== undefined) payload.email = signer.email;\n\t\t\tconst phone = signer.whatsapp_phone_number ?? signer.phone;\n\t\t\tif (phone !== undefined) payload.whatsapp_phone_number = phone;\n\t\t\tif (signer.cpf !== undefined) payload.cpf = signer.cpf;\n\t\t\tif (signer.government_id !== undefined) payload.government_id = signer.government_id;\n\t\t\tif (signer.metadata !== undefined) payload.metadata = signer.metadata;\n\t\t\tvalidateCreateSignerPayload(payload);\n\t\t\treturn { signer, payload, phone };\n\t\t});\n\t\tvalidateSigningSteps(options.signers);\n\n\t\tthis.logger.info('Starting upload + signature workflow', {\n\t\t\tsignerCount: options.signers.length,\n\t\t});\n\n\t\tconst uploadOpts: { metadata?: Record<string, unknown>; accountId?: string } = {};\n\t\tif (options.metadata !== undefined) uploadOpts.metadata = options.metadata;\n\t\tif (options.accountId !== undefined) uploadOpts.accountId = options.accountId;\n\n\t\tconst document = await this.documents.upload(options.source, uploadOpts);\n\n\t\t// Past this point every step can fail with a document (and possibly\n\t\t// signers) already created. Track them so the failure can name them\n\t\t// instead of leaving the caller to hunt for orphans by name.\n\t\tconst signerIds: string[] = [];\n\t\ttry {\n\t\t\tif (options.waitForReady !== false) {\n\t\t\t\tawait this.documents.waitUntilReady(document.id);\n\t\t\t}\n\n\t\t\tconst assignmentSigners: SignerReference[] = [];\n\t\t\tfor (const { signer, payload, phone } of preparedSigners) {\n\t\t\t\tconst created = await this.signers.create(payload, options.accountId);\n\t\t\t\tsignerIds.push(created.id);\n\t\t\t\tconst useWhatsapp = phone !== undefined && signer.email === undefined;\n\t\t\t\tassignmentSigners.push({\n\t\t\t\t\tid: created.id,\n\t\t\t\t\tverification_method: signer.verification_method ?? (useWhatsapp ? 'Whatsapp' : undefined),\n\t\t\t\t\tnotification_methods:\n\t\t\t\t\t\tsigner.notification_methods ?? (useWhatsapp ? ['Whatsapp'] : undefined),\n\t\t\t\t\tstep: signer.step,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst assignmentPayload: ICreateAssignmentPayload = {\n\t\t\t\tmethod: 'virtual',\n\t\t\t\tsigners: assignmentSigners,\n\t\t\t};\n\t\t\tif (options.message !== undefined) assignmentPayload.message = options.message;\n\t\t\tif (options.expiresAt !== undefined) assignmentPayload.expires_at = options.expiresAt;\n\t\t\tif (options.copyReceivers !== undefined)\n\t\t\t\tassignmentPayload.copy_receivers = options.copyReceivers;\n\n\t\t\tconst assignment = await this.assignments.create(document.id, assignmentPayload);\n\n\t\t\tthis.logger.info('Upload + signature workflow completed', { documentId: document.id });\n\n\t\t\treturn { document, assignment, signer_ids: signerIds };\n\t\t} catch (err) {\n\t\t\tthis.logger.error('Upload + signature workflow failed after creating resources', {\n\t\t\t\tdocumentId: document.id,\n\t\t\t\tsignerIds,\n\t\t\t});\n\t\t\tconst reason = err instanceof Error ? err.message : String(err);\n\t\t\tthrow new PartialWorkflowError(\n\t\t\t\t`${reason} (document ${document.id} exists; ${signerIds.length} signer(s) created or reused)`,\n\t\t\t\t{ documentId: document.id, signerIds },\n\t\t\t\t{ cause: err },\n\t\t\t);\n\t\t}\n\t}\n\n\t/** Expose the underlying axios instance for advanced use cases (interceptors, custom endpoints). */\n\tgetAxiosInstance(): AxiosInstance {\n\t\treturn this.axiosInstance;\n\t}\n}\n","/** Base class for all Assinafy SDK errors. */\nexport class AssinafyError extends Error {\n\tpublic readonly context: Record<string, unknown>;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tcontext: Record<string, unknown> = {},\n\t\toptions?: { cause?: unknown },\n\t) {\n\t\tsuper(message, options?.cause !== undefined ? { cause: options.cause } : undefined);\n\t\tthis.name = 'AssinafyError';\n\t\tthis.context = context;\n\t}\n}\n\n/** `X-Rate-Limit-*` values reported with a response (window size, requests left, seconds to reset). */\nexport interface RateLimitInfo {\n\tlimit?: number;\n\tremaining?: number;\n\treset?: number;\n}\n\n/** Thrown when the API returns a non-success HTTP status. */\nexport class ApiError extends AssinafyError {\n\tpublic readonly statusCode: number;\n\tpublic readonly responseData: unknown;\n\t/** Bearer challenge, including insufficient_scope and resource_metadata when provided. */\n\tpublic readonly wwwAuthenticate: string | undefined;\n\t/** Server retry delay (seconds or HTTP date), when provided. */\n\tpublic readonly retryAfter: string | undefined;\n\t/** Rate-limit window reported by the API, when the headers are present. */\n\tpublic readonly rateLimit: RateLimitInfo | undefined;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tstatusCode: number,\n\t\tresponseData: unknown = null,\n\t\toptions?: {\n\t\t\tcause?: unknown;\n\t\t\twwwAuthenticate?: string;\n\t\t\tretryAfter?: string;\n\t\t\trateLimit?: RateLimitInfo;\n\t\t},\n\t) {\n\t\tsuper(message, { statusCode, responseData }, options);\n\t\tthis.name = 'ApiError';\n\t\tthis.statusCode = statusCode;\n\t\tthis.responseData = responseData;\n\t\tthis.wwwAuthenticate = options?.wwwAuthenticate;\n\t\tthis.retryAfter = options?.retryAfter;\n\t\tthis.rateLimit = options?.rateLimit;\n\t}\n\n\tstatic fromResponse(\n\t\tstatusCode: number,\n\t\tresponseData: unknown,\n\t\theaders: Record<string, unknown> = {},\n\t): ApiError {\n\t\tif (Buffer.isBuffer(responseData) || responseData instanceof ArrayBuffer) {\n\t\t\tconst text = (\n\t\t\t\tBuffer.isBuffer(responseData) ? responseData : Buffer.from(responseData)\n\t\t\t).toString('utf8');\n\t\t\ttry {\n\t\t\t\tresponseData = JSON.parse(text);\n\t\t\t} catch {\n\t\t\t\tresponseData = text;\n\t\t\t}\n\t\t}\n\t\tconst data = (responseData ?? {}) as Record<string, unknown>;\n\t\tconst rawMessage = data.message;\n\t\tconst rawError = data.error;\n\t\tconst description = data.error_description;\n\t\tconst message =\n\t\t\ttypeof rawMessage === 'string' && rawMessage.length > 0\n\t\t\t\t? rawMessage\n\t\t\t\t: typeof rawError === 'string'\n\t\t\t\t\t? typeof description === 'string' && description.length > 0\n\t\t\t\t\t\t? `${rawError}: ${description}`\n\t\t\t\t\t\t: rawError\n\t\t\t\t\t: 'API request failed';\n\t\treturn new ApiError(message, statusCode, responseData, {\n\t\t\twwwAuthenticate:\n\t\t\t\ttypeof headers['www-authenticate'] === 'string' ? headers['www-authenticate'] : undefined,\n\t\t\tretryAfter: typeof headers['retry-after'] === 'string' ? headers['retry-after'] : undefined,\n\t\t\trateLimit: parseRateLimit(headers),\n\t\t});\n\t}\n}\n\nfunction parseRateLimit(headers: Record<string, unknown>): RateLimitInfo | undefined {\n\tconst info: RateLimitInfo = {};\n\tfor (const key of ['limit', 'remaining', 'reset'] as const) {\n\t\tconst value = Number.parseInt(String(headers[`x-rate-limit-${key}`]), 10);\n\t\tif (Number.isFinite(value)) info[key] = value;\n\t}\n\treturn Object.keys(info).length > 0 ? info : undefined;\n}\n\n/** Thrown when client-side validation fails before the request is sent. */\nexport class ValidationError extends AssinafyError {\n\tpublic readonly errors: Record<string, unknown>;\n\n\tconstructor(message = 'Validation failed', errors: Record<string, unknown> = {}) {\n\t\tsuper(message, { errors });\n\t\tthis.name = 'ValidationError';\n\t\tthis.errors = errors;\n\t}\n}\n\n/** Thrown when the HTTP transport itself fails (DNS, timeout, etc.). */\nexport class NetworkError extends AssinafyError {\n\tconstructor(message: string, options?: { cause?: unknown }) {\n\t\tsuper(message, {}, options);\n\t\tthis.name = 'NetworkError';\n\t}\n}\n\n/**\n * Thrown when a multi-step workflow helper fails *after* it has already created\n * billable resources.\n *\n * Without this, a failure part-way through\n * {@link AssinafyClient.uploadAndRequestSignatures} would leave an uploaded\n * document and created or reused signers in the workspace with no handle for the\n * caller to resume from or clean up. The original failure is preserved in\n * {@link Error.cause}.\n *\n * @example\n * ```ts\n * try {\n * await client.uploadAndRequestSignatures({ source, signers });\n * } catch (err) {\n * if (err instanceof PartialWorkflowError) {\n * console.error({ documentId: err.documentId, signerIds: err.signerIds });\n * // Inspect the document before resuming. Signers may already be in use elsewhere.\n * }\n * throw err;\n * }\n * ```\n */\nexport class PartialWorkflowError extends AssinafyError {\n\t/** The document that was uploaded before the failure, if any. */\n\tpublic readonly documentId: string | undefined;\n\t/** IDs of every signer created (or reused) before the failure. */\n\tpublic readonly signerIds: string[];\n\n\tconstructor(\n\t\tmessage: string,\n\t\tcreated: { documentId?: string; signerIds?: string[] },\n\t\toptions?: { cause?: unknown },\n\t) {\n\t\tconst signerIds = created.signerIds ?? [];\n\t\tsuper(message, { documentId: created.documentId, signerIds }, options);\n\t\tthis.name = 'PartialWorkflowError';\n\t\tthis.documentId = created.documentId;\n\t\tthis.signerIds = signerIds;\n\t}\n}\n","import axios, { type AxiosRequestConfig } from 'axios';\nimport { ApiError, AssinafyError, NetworkError, ValidationError } from './errors.js';\nimport type {\n\tAssignmentMethod,\n\tAssignmentNotificationMethod,\n\tAssignmentVerificationMethod,\n\tDocumentArtifactName,\n\tIDocumentStatsParams,\n\tLogger,\n} from './types.js';\n\nconst DOCUMENT_ARTIFACT_NAMES: readonly DocumentArtifactName[] = [\n\t'original',\n\t'certificated',\n\t'certificate-page',\n\t'pades',\n\t'bundle',\n];\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\nconst VERIFICATION_METHODS: readonly AssignmentVerificationMethod[] = [\n\t'Email',\n\t'Whatsapp',\n\t'DigitalCertificate',\n\t'IdDocumentFaceMatchBasic',\n];\nconst NOTIFICATION_METHODS: readonly AssignmentNotificationMethod[] = ['Email', 'Whatsapp'];\n\n/**\n * Unwrap the Assinafy API envelope `{ status, message, data }`.\n * Throws {@link ApiError} when the envelope reports a non-success status.\n */\nexport function handleAssinafyResponse<T>(response: unknown): T {\n\tconst resp = response as { status?: number; data?: T; message?: string } | null | undefined;\n\n\tif (resp && typeof resp === 'object' && resp.status !== undefined && 'data' in resp) {\n\t\tif ((resp.status as number) >= 200 && (resp.status as number) < 300) {\n\t\t\treturn resp.data as T;\n\t\t}\n\t\tthrow ApiError.fromResponse(resp.status as number, resp);\n\t}\n\n\treturn response as T;\n}\n\n/**\n * Convert an unknown thrown value into a typed SDK error.\n * Axios errors become {@link ApiError} / {@link NetworkError}; SDK errors pass through.\n */\nexport function toSdkError(error: unknown, fallbackMessage: string): AssinafyError {\n\tif (error instanceof AssinafyError) {\n\t\treturn error;\n\t}\n\n\tif (axios.isAxiosError(error)) {\n\t\tconst status = error.response?.status;\n\t\tif (status) {\n\t\t\treturn ApiError.fromResponse(status, error.response?.data ?? null, error.response?.headers);\n\t\t}\n\t\t// Axios errors retain the complete request config, including auth headers,\n\t\t// body, and query values. Never attach the raw error as a public cause.\n\t\treturn new NetworkError(`${fallbackMessage}: ${error.message}`);\n\t}\n\n\tif (error instanceof Error) {\n\t\treturn new AssinafyError(`${fallbackMessage}: ${error.message}`, {}, { cause: error });\n\t}\n\n\treturn new AssinafyError(fallbackMessage, { cause: error });\n}\n\n/** No-op logger used when the caller does not supply one. */\nexport function createNoopLogger(): Logger {\n\treturn {\n\t\tdebug: () => undefined,\n\t\tinfo: () => undefined,\n\t\twarn: () => undefined,\n\t\terror: () => undefined,\n\t};\n}\n\n/** Strip undefined values from a params record (Axios sends `undefined` as literal). */\nexport function cleanParams(params: Record<string, unknown>): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(params)) {\n\t\tif (value !== undefined && value !== null) {\n\t\t\tout[normalizeQueryKey(key)] = value;\n\t\t}\n\t}\n\treturn out;\n}\n\n/** Strip nullish values from a JSON request body without renaming any keys. */\nexport function stripEmpty(body: Record<string, unknown>): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(body)) {\n\t\tif (value !== undefined && value !== null) {\n\t\t\tout[key] = value;\n\t\t}\n\t}\n\treturn out;\n}\n\n/** Append a multipart file part over a copy-free view of the binary data. */\nexport function appendFilePart(\n\tform: FormData,\n\tdata: Uint8Array,\n\tcontentType: string,\n\tfileName: string,\n): void {\n\tconst view = new Uint8Array(data.buffer as ArrayBuffer, data.byteOffset, data.byteLength);\n\tform.append('file', new Blob([view], { type: contentType }), fileName);\n}\n\n/** Remove owner credentials from a request that is public or signer-authenticated. */\nexport function publicRequestConfig(config: AxiosRequestConfig = {}): AxiosRequestConfig {\n\treturn {\n\t\t...config,\n\t\theaders: { ...config.headers, Authorization: undefined, 'X-Api-Key': undefined },\n\t};\n}\n\n/** Build an isolated signer-access-code request config. */\nexport function signerAccessConfig(\n\tsignerAccessCode: string,\n\tparams: Record<string, unknown> = {},\n\theaders: Record<string, string> = {},\n): AxiosRequestConfig {\n\treturn publicRequestConfig({\n\t\tparams: cleanParams({ ...params, 'signer-access-code': signerAccessCode }),\n\t\theaders,\n\t});\n}\n\n/** Validate an RFC 3339 timestamp before it reaches an API request body. */\nexport function requireIso8601(value: string, name = 'timestamp'): string {\n\tconst match =\n\t\t/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\\.[0-9]+)?(?:Z|[+-]([0-9]{2}):([0-9]{2}))$/.exec(\n\t\t\tvalue,\n\t\t);\n\tif (!match) {\n\t\tthrow new ValidationError(`${name} must be a valid ISO 8601 timestamp`);\n\t}\n\n\tconst year = Number(match[1]);\n\tconst month = Number(match[2]);\n\tconst day = Number(match[3]);\n\tconst hour = Number(match[4]);\n\tconst minute = Number(match[5]);\n\tconst second = Number(match[6]);\n\tconst leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n\tconst daysInMonth = [31, leapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\tconst timezoneHour = match[7] === undefined ? 0 : Number(match[7]);\n\tconst timezoneMinute = match[8] === undefined ? 0 : Number(match[8]);\n\n\tif (\n\t\tmonth < 1 ||\n\t\tmonth > 12 ||\n\t\tday < 1 ||\n\t\tday > (daysInMonth[month - 1] ?? 0) ||\n\t\thour > 23 ||\n\t\tminute > 59 ||\n\t\tsecond > 59 ||\n\t\ttimezoneHour > 14 ||\n\t\t(timezoneHour === 14 && timezoneMinute !== 0) ||\n\t\ttimezoneMinute > 59 ||\n\t\t!Number.isFinite(Date.parse(value))\n\t) {\n\t\tthrow new ValidationError(`${name} must be a valid ISO 8601 timestamp`);\n\t}\n\treturn value;\n}\n\n/** Reject an invalid email before it reaches an API request body or query. */\nexport function requireEmail(value: string | null | undefined): string {\n\tif (!value || !EMAIL_RE.test(value)) {\n\t\tthrow new ValidationError('Invalid email address', { email: value });\n\t}\n\treturn value;\n}\n\n/** Validate the shared verification, notification, and step fields on signer entries. */\nexport function validateSignerOptions(input: {\n\tverification_method?: unknown;\n\tnotification_methods?: unknown;\n\tstep?: unknown;\n}): void {\n\tif (\n\t\tinput.verification_method !== undefined &&\n\t\t!VERIFICATION_METHODS.includes(input.verification_method as AssignmentVerificationMethod)\n\t) {\n\t\tthrow new ValidationError(\n\t\t\t`verification_method must be one of: ${VERIFICATION_METHODS.join(', ')}`,\n\t\t);\n\t}\n\tif (\n\t\tinput.notification_methods !== undefined &&\n\t\t(!Array.isArray(input.notification_methods) ||\n\t\t\tinput.notification_methods.some(\n\t\t\t\t(method) => !NOTIFICATION_METHODS.includes(method as AssignmentNotificationMethod),\n\t\t\t))\n\t) {\n\t\tthrow new ValidationError(\n\t\t\t`notification_methods must contain only: ${NOTIFICATION_METHODS.join(', ')}`,\n\t\t);\n\t}\n\tconst notifications = (input.notification_methods ?? []) as string[];\n\tif (notifications.length > 1) {\n\t\tthrow new ValidationError('notification_methods accepts exactly one method per signer');\n\t}\n\tconst [notification] = notifications;\n\tif (\n\t\tnotification !== undefined &&\n\t\t(input.verification_method === 'Email' || input.verification_method === 'Whatsapp') &&\n\t\tnotification !== input.verification_method\n\t) {\n\t\tthrow new ValidationError(\n\t\t\t`${input.verification_method} verification requires the ${input.verification_method} notification method`,\n\t\t);\n\t}\n\tif (input.step !== undefined && !Number.isInteger(input.step)) {\n\t\tthrow new ValidationError('step must be an integer');\n\t}\n}\n\n/** Certificate signing completes a virtual item and cannot complete placed fields. */\nexport function validateDigitalCertificateMethod(\n\tmethod: AssignmentMethod,\n\tsigners: readonly { verification_method?: unknown }[],\n): void {\n\tif (\n\t\tmethod !== 'virtual' &&\n\t\tsigners.some((signer) => signer.verification_method === 'DigitalCertificate')\n\t) {\n\t\tthrow new ValidationError('DigitalCertificate signers require method: virtual', {\n\t\t\tcode: 'digital_certificate_requires_virtual',\n\t\t});\n\t}\n}\n\n/** Validate the sequencing rules for assignments and template-document signers. */\nexport function validateSigningSteps(\n\tsigners: readonly { verification_method?: unknown; step?: unknown }[],\n): void {\n\tconst withSteps = signers.filter((signer) => signer.step !== undefined);\n\tif (withSteps.length > 0) {\n\t\tif (withSteps.length !== signers.length) {\n\t\t\tthrow new ValidationError('step must be supplied for every signer when used');\n\t\t}\n\t\tconst steps = [...new Set(withSteps.map((signer) => signer.step as number))].sort(\n\t\t\t(a, b) => a - b,\n\t\t);\n\t\tif (steps.some((step, index) => step !== index + 1)) {\n\t\t\tthrow new ValidationError('steps must form a contiguous sequence starting at 1');\n\t\t}\n\t}\n\tvalidateDigitalCertificateSteps(signers);\n}\n\n/** Enforce the documented one-digital-certificate-signer-per-step constraint. */\nexport function validateDigitalCertificateSteps(\n\tsigners: readonly { verification_method?: unknown; step?: unknown }[],\n): void {\n\tfor (const signer of signers) {\n\t\tif (\n\t\t\tsigner.verification_method === 'DigitalCertificate' &&\n\t\t\tsigners.some((other) => other !== signer && (other.step ?? 1) === (signer.step ?? 1))\n\t\t) {\n\t\t\tthrow new ValidationError('a DigitalCertificate signer must be alone in its signing step');\n\t\t}\n\t}\n}\n\n/** Validate and serialize the query shared by account/user statistics endpoints. */\nexport function documentStatsParams(params: IDocumentStatsParams = {}): Record<string, unknown> {\n\tif (params.granularity !== undefined && !['monthly', 'daily'].includes(params.granularity)) {\n\t\tthrow new ValidationError('granularity must be monthly or daily');\n\t}\n\tif (params.month !== undefined && !/^\\d{4}-(0[1-9]|1[0-2])$/.test(params.month)) {\n\t\tthrow new ValidationError('month must use YYYY-MM format');\n\t}\n\tif (params.granularity === 'daily' && !params.month) {\n\t\tthrow new ValidationError('month is required for daily statistics');\n\t}\n\treturn cleanParams(params as Record<string, unknown>);\n}\n\n/** Validate an artifact before it is interpolated into a request path. */\nexport function requireDocumentArtifactName(value: string): DocumentArtifactName {\n\tif ((DOCUMENT_ARTIFACT_NAMES as readonly string[]).includes(value)) {\n\t\treturn value as DocumentArtifactName;\n\t}\n\tthrow new ValidationError(`artifact must be one of: ${DOCUMENT_ARTIFACT_NAMES.join(', ')}`);\n}\n\n/** Validate a signer image type before it is interpolated into a request path. */\nexport function requireSignerImageType(value: string): 'signature' | 'initial' {\n\tif (value === 'signature' || value === 'initial') return value;\n\tthrow new ValidationError('image type must be signature or initial');\n}\n\n/** Validate a live-supported sort value before sending it to an endpoint. */\nexport function requireSort<T extends string>(\n\tvalue: T | undefined,\n\tallowed: readonly T[],\n): T | undefined {\n\tif (value === undefined || allowed.includes(value)) return value;\n\tthrow new ValidationError(`sort must be one of: ${allowed.join(', ')}`);\n}\n\nfunction normalizeQueryKey(key: string): string {\n\treturn key === 'per_page' ? 'per-page' : key;\n}\n\n/** Strip a single trailing slash from a base URL, so paths can always join with a leading `/`. */\nexport function normalizeBaseUrl(raw: string): string {\n\treturn raw.endsWith('/') ? raw.slice(0, -1) : raw;\n}\n","import type { AxiosInstance, AxiosResponse, AxiosResponseHeaders } from 'axios';\nimport { ApiError, ValidationError } from '../errors.js';\nimport type { Logger, PaginatedResult, PaginationMeta } from '../types.js';\nimport { createNoopLogger, handleAssinafyResponse, toSdkError } from '../utils.js';\n\n/**\n * Shared plumbing for every Assinafy resource:\n *\n * - holds the axios instance, default account ID, and logger\n * - provides `accountId()` / `requireId()` argument guards\n * - wraps HTTP calls in a single `try/catch` → typed-error pipeline\n * - unwraps the Assinafy response envelope\n * - parses `X-Pagination-*` headers into a typed meta object\n *\n * Resources should never `try/catch` or touch the envelope directly — they call\n * one of `call` / `callBinary` / `callList` instead.\n */\nexport abstract class BaseResource {\n\tconstructor(\n\t\tprotected readonly http: AxiosInstance,\n\t\tprotected readonly defaultAccountId?: string,\n\t\tprotected readonly logger: Logger = createNoopLogger(),\n\t) {}\n\n\t/** Resolve the effective account id, throwing if none is available. */\n\tprotected accountId(explicit?: string): string {\n\t\tconst id = explicit ?? this.defaultAccountId;\n\t\tif (!id) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'Account ID is required. Provide it as a parameter or set a default in the client.',\n\t\t\t);\n\t\t}\n\t\treturn safeIdentifier(id, 'Account ID');\n\t}\n\n\t/** Guard required path arguments (documentId, signerId, …). */\n\tprotected requireId<T extends string>(value: T | undefined | null, name: string): T {\n\t\tif (!value) {\n\t\t\tthrow new ValidationError(`${name} is required`);\n\t\t}\n\t\treturn safeIdentifier(value, name) as T;\n\t}\n\n\t/** Execute an HTTP call and return the unwrapped envelope body. */\n\tprotected async call<T>(label: string, request: RequestFn): Promise<T> {\n\t\ttry {\n\t\t\tconst response = await request();\n\t\t\treturn handleAssinafyResponse<T>(response.data);\n\t\t} catch (err) {\n\t\t\tthrow toSdkError(err, label);\n\t\t}\n\t}\n\n\t/** Like {@link call} but returns `null` when the API responds with 404. */\n\tprotected async callOptional<T>(label: string, request: RequestFn): Promise<T | null> {\n\t\ttry {\n\t\t\treturn await this.call<T>(label, request);\n\t\t} catch (err) {\n\t\t\tif (err instanceof ApiError && err.statusCode === 404) return null;\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\t/** Execute an HTTP call that returns binary data (artifact downloads). */\n\tprotected async callBinary(\n\t\tlabel: string,\n\t\trequest: () => Promise<AxiosResponse<ArrayBuffer>>,\n\t): Promise<Buffer> {\n\t\ttry {\n\t\t\tconst response = await request();\n\t\t\treturn Buffer.from(response.data);\n\t\t} catch (err) {\n\t\t\tthrow toSdkError(err, label);\n\t\t}\n\t}\n\n\t/** Execute a paginated list call and attach meta from `X-Pagination-*` headers. */\n\tprotected async callList<T>(label: string, request: RequestFn): Promise<PaginatedResult<T>> {\n\t\ttry {\n\t\t\tconst response = await request();\n\t\t\tconst unwrapped = handleAssinafyResponse<T[] | { data?: T[] }>(response.data);\n\t\t\tlet data: T[];\n\t\t\tif (Array.isArray(unwrapped)) {\n\t\t\t\tdata = unwrapped;\n\t\t\t} else if (Array.isArray(unwrapped?.data)) {\n\t\t\t\tdata = (unwrapped as { data: T[] }).data;\n\t\t\t} else {\n\t\t\t\t// Fail loud: a shape we don't recognise means the API contract\n\t\t\t\t// drifted, not that there are genuinely zero results.\n\t\t\t\tthrow new ValidationError(`Unexpected list response shape for ${label}`, {\n\t\t\t\t\tresponse: unwrapped as unknown,\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst meta = parsePaginationMeta(response.headers);\n\t\t\treturn meta === undefined ? { data } : { data, meta };\n\t\t} catch (err) {\n\t\t\tthrow toSdkError(err, label);\n\t\t}\n\t}\n}\n\nfunction safeIdentifier(value: string, name: string): string {\n\tif (value === '.' || value === '..' || /[\\s/?#\\\\%]/.test(value)) {\n\t\tthrow new ValidationError(`${name} contains invalid URL characters`);\n\t}\n\treturn value;\n}\n\ntype RequestFn = () => Promise<AxiosResponse>;\n\nfunction parsePaginationMeta(\n\theaders: AxiosResponseHeaders | Record<string, unknown> | undefined,\n): PaginationMeta | undefined {\n\tif (!headers) return undefined;\n\n\tconst read = (key: string): string | undefined => {\n\t\tconst h = headers as Record<string, unknown>;\n\t\tconst raw = h[key] ?? h[key.toLowerCase()];\n\t\tif (raw === undefined || raw === null) return undefined;\n\t\treturn Array.isArray(raw) ? String(raw[0]) : String(raw);\n\t};\n\n\tconst current = toInt(read('x-pagination-current-page'));\n\tconst perPage = toInt(read('x-pagination-per-page'));\n\tconst total = toInt(read('x-pagination-total-count'));\n\tconst lastPage = toInt(read('x-pagination-page-count'));\n\n\tif (\n\t\tcurrent === undefined &&\n\t\tperPage === undefined &&\n\t\ttotal === undefined &&\n\t\tlastPage === undefined\n\t) {\n\t\treturn undefined;\n\t}\n\n\tconst meta: PaginationMeta = {};\n\tif (current !== undefined) meta.current_page = current;\n\tif (perPage !== undefined) meta.per_page = perPage;\n\tif (total !== undefined) meta.total = total;\n\tif (lastPage !== undefined) meta.last_page = lastPage;\n\treturn meta;\n}\n\nfunction toInt(value: string | undefined): number | undefined {\n\tif (value === undefined) return undefined;\n\tconst n = Number.parseInt(value, 10);\n\treturn Number.isFinite(n) ? n : undefined;\n}\n","import { ValidationError } from '../errors.js';\nimport type {\n\tIAssignment,\n\tIAssignmentListParams,\n\tICreateAssignmentPayload,\n\tICreateAssignmentResponse,\n\tIdentityVerificationImageName,\n\tIEstimateCostResponse,\n\tIIdentityReviewPayload,\n\tIResendCostEstimate,\n\tIResendEmailResponse,\n\tISignerIdentityReview,\n\tIWhatsAppNotification,\n\tPaginatedResult,\n\tSignerReference,\n} from '../types.js';\nimport {\n\tcleanParams,\n\trequireIso8601,\n\trequireSort,\n\tstripEmpty,\n\tvalidateDigitalCertificateMethod,\n\tvalidateSignerOptions,\n\tvalidateSigningSteps,\n} from '../utils.js';\nimport { BaseResource } from './base.js';\n\n/**\n * Normalise an assignment payload into the shape the API expects:\n * `signers: [{ id }]` plus optional docs-level fields.\n */\nexport function buildAssignmentPayload(\n\tpayload: ICreateAssignmentPayload,\n\toptions: {\n\t\tallowSignersWithoutId?: boolean;\n\t\tskipDigitalCertificateStepValidation?: boolean;\n\t} = {},\n): Record<string, unknown> {\n\tif (\n\t\tpayload.method !== undefined &&\n\t\tpayload.method !== 'virtual' &&\n\t\tpayload.method !== 'collect'\n\t) {\n\t\tthrow new ValidationError('method must be virtual or collect');\n\t}\n\tconst signers = extractSignerRefs(payload);\n\t// The docs mark `signers` \"Required for virtual\" only, but the API prices per signer in both\n\t// modes and answers a signer-less body with\n\t// 400 \"Pelo menos um signatários precisa ser informado.\" A collect estimate needs them too.\n\tif (signers.length === 0) {\n\t\tthrow new ValidationError('At least one signer is required', {\n\t\t\tsigners: payload.signers ?? payload.signer_ids ?? payload.signerIds,\n\t\t});\n\t}\n\tconst method = payload.method ?? 'virtual';\n\tconst normalisedSigners = signers.map((ref) => normaliseSignerRef(ref, options));\n\tvalidateDigitalCertificateMethod(method, normalisedSigners);\n\tif (method === 'collect' && !Array.isArray(payload.entries)) {\n\t\tthrow new ValidationError('entries are required for collect assignments');\n\t}\n\tif (!options.skipDigitalCertificateStepValidation) {\n\t\tvalidateSigningSteps(normalisedSigners);\n\t}\n\n\treturn stripEmpty({\n\t\tmethod,\n\t\tsigners: normalisedSigners,\n\t\tmessage: payload.message,\n\t\texpires_at:\n\t\t\tpayload.expires_at === undefined\n\t\t\t\t? undefined\n\t\t\t\t: requireIso8601(payload.expires_at, 'expires_at'),\n\t\tcopy_receivers: payload.copy_receivers,\n\t\tentries: payload.entries,\n\t});\n}\n\nfunction extractSignerRefs(payload: ICreateAssignmentPayload): SignerReference[] {\n\tconst populatedAliases = [payload.signers, payload.signer_ids, payload.signerIds].filter(\n\t\t(value) => Array.isArray(value) && value.length > 0,\n\t);\n\tif (populatedAliases.length > 1) {\n\t\tthrow new ValidationError('Provide only one of signers, signer_ids, or signerIds');\n\t}\n\tif (Array.isArray(payload.signers) && payload.signers.length > 0) {\n\t\treturn payload.signers;\n\t}\n\n\tconst legacy = payload.signer_ids ?? payload.signerIds;\n\treturn Array.isArray(legacy) ? legacy : [];\n}\n\nfunction normaliseSignerRef(\n\tref: SignerReference,\n\toptions: { allowSignersWithoutId?: boolean },\n): { id?: string; verification_method?: string; notification_methods?: string[]; step?: number } {\n\tif (typeof ref === 'string') {\n\t\tif (!ref) throw new ValidationError('Signer ID cannot be empty');\n\t\treturn { id: ref };\n\t}\n\tif (ref && typeof ref === 'object') {\n\t\tconst input = ref as {\n\t\t\tid?: string;\n\t\t\tsigner_id?: string;\n\t\t\tverification_method?: string;\n\t\t\tnotification_methods?: string[];\n\t\t\tstep?: number;\n\t\t};\n\t\tconst id = input.id ?? input.signer_id;\n\t\tvalidateSignerOptions(input);\n\t\tconst normalised = stripEmpty({\n\t\t\tid,\n\t\t\tverification_method: input.verification_method,\n\t\t\tnotification_methods: input.notification_methods,\n\t\t\tstep: input.step,\n\t\t});\n\n\t\tif (typeof id === 'string' && id.length > 0) {\n\t\t\treturn normalised as {\n\t\t\t\tid: string;\n\t\t\t\tverification_method?: string;\n\t\t\t\tnotification_methods?: string[];\n\t\t\t};\n\t\t}\n\n\t\tif (options.allowSignersWithoutId && Object.keys(normalised).length > 0) {\n\t\t\treturn normalised as { verification_method?: string; notification_methods?: string[] };\n\t\t}\n\n\t\tif (options.allowSignersWithoutId && Object.keys(normalised).length === 0) {\n\t\t\treturn {};\n\t\t}\n\t}\n\tthrow new ValidationError('Invalid signer reference', { ref: ref as unknown });\n}\n\nexport class AssignmentResource extends BaseResource {\n\t/** Fetch an account review and available evidence for a signer's identity verification. */\n\tasync getIdentityVerification(\n\t\tdocumentId: string,\n\t\tassignmentId: string,\n\t\tsignerId: string,\n\t): Promise<ISignerIdentityReview> {\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\tconst asgId = this.requireId(assignmentId, 'Assignment ID');\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\treturn this.call('Failed to fetch signer identity review', () =>\n\t\t\tthis.http.get(\n\t\t\t\t`/documents/${docId}/assignments/${asgId}/signers/${sid}/identity-verification`,\n\t\t\t),\n\t\t);\n\t}\n\n\t/** Download JPEG/PNG evidence or the document PDF, available only while the review is open. */\n\tasync downloadIdentityVerificationImage(\n\t\tdocumentId: string,\n\t\tassignmentId: string,\n\t\tsignerId: string,\n\t\tname: IdentityVerificationImageName,\n\t): Promise<Buffer> {\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\tconst asgId = this.requireId(assignmentId, 'Assignment ID');\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\tif (!['document_front', 'document_back', 'document_pdf', 'face'].includes(name)) {\n\t\t\tthrow new ValidationError('Unknown identity verification image name');\n\t\t}\n\t\treturn this.callBinary('Failed to download identity review image', () =>\n\t\t\tthis.http.get<ArrayBuffer>(\n\t\t\t\t`/documents/${docId}/assignments/${asgId}/signers/${sid}/identity-verification/images/${name}`,\n\t\t\t\t{ responseType: 'arraybuffer' },\n\t\t\t),\n\t\t);\n\t}\n\n\t/** Approve certification or reject/cancel the document; the optional note is private to reviewers. */\n\tasync reviewIdentityVerification(\n\t\tdocumentId: string,\n\t\tassignmentId: string,\n\t\tsignerId: string,\n\t\tpayload: IIdentityReviewPayload,\n\t): Promise<ISignerIdentityReview> {\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\tconst asgId = this.requireId(assignmentId, 'Assignment ID');\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\tif (!payload || !['Approved', 'Rejected'].includes(payload.decision)) {\n\t\t\tthrow new ValidationError('decision must be Approved or Rejected');\n\t\t}\n\t\tif (\n\t\t\tpayload.note != null &&\n\t\t\t(typeof payload.note !== 'string' || [...payload.note].length > 2000)\n\t\t) {\n\t\t\tthrow new ValidationError('note must contain at most 2000 characters');\n\t\t}\n\t\treturn this.call('Failed to decide signer identity review', () =>\n\t\t\tthis.http.post(\n\t\t\t\t`/documents/${docId}/assignments/${asgId}/signers/${sid}/identity-verification/review`,\n\t\t\t\t{ decision: payload.decision, note: payload.note },\n\t\t\t),\n\t\t);\n\t}\n\n\t/**\n\t * List assignments across the account (`GET /assignments`).\n\t *\n\t * The endpoint is account-scoped via a required `accountId` query parameter\n\t * (note the camelCase — it differs from the path style used elsewhere).\n\t * Supports `page` / `per-page`; `created_at` sorting is live-verified.\n\t */\n\tasync list(\n\t\tparams: IAssignmentListParams = {},\n\t\taccountId?: string,\n\t): Promise<PaginatedResult<IAssignment>> {\n\t\tconst id = this.accountId(accountId);\n\t\tif ('search' in params) throw new ValidationError('assignment search is not supported');\n\t\trequireSort(params.sort, ['created_at', '-created_at']);\n\t\treturn this.callList<IAssignment>('Failed to list assignments', () =>\n\t\t\tthis.http.get('/assignments', { params: cleanParams({ ...params, accountId: id }) }),\n\t\t);\n\t}\n\n\t/** Create a signing assignment for a document. */\n\tasync create(\n\t\tdocumentId: string,\n\t\tpayload: ICreateAssignmentPayload,\n\t): Promise<ICreateAssignmentResponse> {\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\t// buildAssignmentPayload normalises (and validates non-empty) the signer\n\t\t// list; reuse its output for the count instead of extracting twice.\n\t\tconst body = buildAssignmentPayload(payload);\n\t\tthis.logger.info('Creating assignment', {\n\t\t\tdocumentId: docId,\n\t\t\tsigners: (body.signers as unknown[]).length,\n\t\t});\n\t\treturn this.call('Failed to create assignment', () =>\n\t\t\tthis.http.post(`/documents/${docId}/assignments`, body),\n\t\t);\n\t}\n\n\t/** Estimate the cost (in credits) of creating the assignment. */\n\tasync estimateCost(\n\t\tdocumentId: string,\n\t\tpayload: ICreateAssignmentPayload,\n\t): Promise<IEstimateCostResponse> {\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\treturn this.call('Failed to estimate assignment cost', () =>\n\t\t\tthis.http.post(\n\t\t\t\t`/documents/${docId}/assignments/estimate-cost`,\n\t\t\t\tbuildAssignmentPayload(payload, {\n\t\t\t\t\tallowSignersWithoutId: true,\n\t\t\t\t\tskipDigitalCertificateStepValidation: true,\n\t\t\t\t}),\n\t\t\t),\n\t\t);\n\t}\n\n\t/**\n\t * Update the expiration date of an existing assignment.\n\t * The published API accepts an ISO 8601 timestamp. Deployments that support\n\t * clearing an expiration also accept `null`.\n\t */\n\tasync resetExpiration(\n\t\tdocumentId: string,\n\t\tassignmentId: string,\n\t\texpiresAt: string | null,\n\t): Promise<IAssignment> {\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\tconst asgId = this.requireId(assignmentId, 'Assignment ID');\n\t\tif (expiresAt !== null) requireIso8601(expiresAt, 'expiresAt');\n\t\t// `null` is meaningful here (\"no expiration\"), so don't strip it.\n\t\treturn this.call('Failed to update assignment expiration', () =>\n\t\t\tthis.http.put(`/documents/${docId}/assignments/${asgId}/reset-expiration`, {\n\t\t\t\texpires_at: expiresAt,\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** Resend the signing notification to a single signer. */\n\tasync resendNotification(\n\t\tdocumentId: string,\n\t\tassignmentId: string,\n\t\tsignerId: string,\n\t): Promise<IResendEmailResponse> {\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\tconst asgId = this.requireId(assignmentId, 'Assignment ID');\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\treturn this.call('Failed to resend signer notification', () =>\n\t\t\tthis.http.put(`/documents/${docId}/assignments/${asgId}/signers/${sid}/resend`),\n\t\t);\n\t}\n\n\t/** Estimate the cost of resending a signer notification. */\n\tasync estimateResendCost(\n\t\tdocumentId: string,\n\t\tassignmentId: string,\n\t\tsignerId: string,\n\t): Promise<IResendCostEstimate> {\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\tconst asgId = this.requireId(assignmentId, 'Assignment ID');\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\treturn this.call('Failed to estimate resend cost', () =>\n\t\t\tthis.http.post(\n\t\t\t\t`/documents/${docId}/assignments/${asgId}/signers/${sid}/estimate-resend-cost`,\n\t\t\t),\n\t\t);\n\t}\n\n\t/**\n\t * `GET /documents/{documentId}/assignments/{assignmentId}/whatsapp-notifications`\n\t * — list every WhatsApp notification rendered + sent for an assignment.\n\t */\n\tasync listWhatsAppNotifications(\n\t\tdocumentId: string,\n\t\tassignmentId: string,\n\t): Promise<IWhatsAppNotification[]> {\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\tconst asgId = this.requireId(assignmentId, 'Assignment ID');\n\t\treturn this.call('Failed to list WhatsApp notifications', () =>\n\t\t\tthis.http.get(`/documents/${docId}/assignments/${asgId}/whatsapp-notifications`),\n\t\t);\n\t}\n}\n","import { ValidationError } from '../errors.js';\nimport type {\n\tIApiKeyResponse,\n\tIEmptyResult,\n\tILoginResponse,\n\tIMaskedApiKeyResponse,\n\tIMfaReauthPayload,\n\tIMfaRecoveryCodes,\n\tIMfaStatus,\n\tIMfaVerifyPayload,\n\tIStatusResponse,\n\tITotpConfirmPayload,\n\tITotpEnrollment,\n\tSocialLoginProvider,\n} from '../types.js';\nimport { publicRequestConfig } from '../utils.js';\nimport { BaseResource } from './base.js';\n\n/** Two-factor re-authentication requires the password or a live/recovery code. */\nfunction requireReauth(payload: IMfaReauthPayload): IMfaReauthPayload {\n\tif (!payload?.password && !payload?.code) {\n\t\tthrow new ValidationError('password or code is required');\n\t}\n\treturn payload;\n}\n\n/**\n * Authentication endpoints (login, two-factor, social login, password\n * management), personal API key management (`/users/api-keys`), and\n * two-factor enrollment (`/users/self/mfa`).\n *\n * Most of these endpoints are intended to bootstrap an authenticated session\n * for a human user. Production server-to-server integrations should use\n * `X-Api-Key` and skip this resource entirely.\n */\nexport class AuthenticationResource extends BaseResource {\n\t/** `POST /login` — exchange email + password for a JWT access token. */\n\tasync login(email: string, password: string): Promise<ILoginResponse> {\n\t\tif (!email) throw new ValidationError('email is required');\n\t\tif (!password) throw new ValidationError('password is required');\n\t\treturn this.call('Login failed', () =>\n\t\t\tthis.http.post('/login', { email, password }, publicRequestConfig()),\n\t\t);\n\t}\n\n\t/**\n\t * `POST /authentication/mfa/verify` — exchange the login `mfa_token` and an\n\t * authenticator or recovery code for an access token. The challenge is\n\t * single-use and expires 5 minutes after login.\n\t */\n\tasync verifyMfa(payload: IMfaVerifyPayload): Promise<ILoginResponse> {\n\t\tif (!payload?.mfa_token) throw new ValidationError('mfa_token is required');\n\t\tif (!payload.code?.trim()) throw new ValidationError('code is required');\n\t\treturn this.call('Two-factor verification failed', () =>\n\t\t\tthis.http.post(\n\t\t\t\t'/authentication/mfa/verify',\n\t\t\t\t{ mfa_token: payload.mfa_token, code: payload.code.trim() },\n\t\t\t\tpublicRequestConfig(),\n\t\t\t),\n\t\t);\n\t}\n\n\t/** `GET /users/self/mfa` — enrolled two-factor methods and remaining recovery codes. */\n\tasync listMfaMethods(): Promise<IMfaStatus> {\n\t\treturn this.call('Failed to list two-factor methods', () => this.http.get('/users/self/mfa'));\n\t}\n\n\t/**\n\t * `POST /users/self/mfa/totp` — start authenticator enrollment. The secret\n\t * and provisioning URI are returned only once; two-factor stays inactive\n\t * until {@link confirmTotpEnrollment}.\n\t */\n\tasync startTotpEnrollment(label?: string): Promise<ITotpEnrollment> {\n\t\treturn this.call('Failed to start authenticator enrollment', () =>\n\t\t\tthis.http.post('/users/self/mfa/totp', label ? { label } : {}),\n\t\t);\n\t}\n\n\t/**\n\t * `PUT /users/self/mfa/totp/confirm` — activate the method with a live code\n\t * and receive one-time recovery codes. Replacing a confirmed method also\n\t * requires `password` or `reauth_code`.\n\t */\n\tasync confirmTotpEnrollment(payload: ITotpConfirmPayload): Promise<IMfaRecoveryCodes> {\n\t\tif (!payload?.id) throw new ValidationError('id is required');\n\t\tif (!payload.code?.trim()) throw new ValidationError('code is required');\n\t\treturn this.call('Failed to confirm authenticator enrollment', () =>\n\t\t\tthis.http.put('/users/self/mfa/totp/confirm', payload),\n\t\t);\n\t}\n\n\t/** `POST /users/self/mfa/recovery-codes` — issue ten new recovery codes, invalidating the old set. */\n\tasync regenerateRecoveryCodes(payload: IMfaReauthPayload): Promise<IMfaRecoveryCodes> {\n\t\treturn this.call('Failed to regenerate recovery codes', () =>\n\t\t\tthis.http.post('/users/self/mfa/recovery-codes', requireReauth(payload)),\n\t\t);\n\t}\n\n\t/**\n\t * `DELETE /users/self/mfa/{methodId}` — remove a method. Removing the last\n\t * one also discards the recovery codes.\n\t */\n\tasync removeMfaMethod(\n\t\tmethodId: string,\n\t\tpayload: IMfaReauthPayload,\n\t): Promise<{ is_mfa_enabled: boolean }> {\n\t\tconst id = this.requireId(methodId, 'Method ID');\n\t\tconst data = requireReauth(payload);\n\t\treturn this.call('Failed to remove two-factor method', () =>\n\t\t\tthis.http.delete(`/users/self/mfa/${id}`, { data }),\n\t\t);\n\t}\n\n\t/** `POST /authentication/social-login` — exchange a provider token for an Assinafy JWT. */\n\tasync socialLogin(payload: {\n\t\tprovider: SocialLoginProvider;\n\t\ttoken: string;\n\t\thas_accepted_terms: boolean;\n\t}): Promise<ILoginResponse> {\n\t\tif (payload.provider !== 'google') throw new ValidationError('provider must be google');\n\t\tif (!payload.token) throw new ValidationError('token is required');\n\t\treturn this.call('Social login failed', () =>\n\t\t\tthis.http.post('/authentication/social-login', payload, publicRequestConfig()),\n\t\t);\n\t}\n\n\t/** `POST /auth/link-social-login` — link a Google identity to the current user. */\n\tasync linkSocialLogin(payload: {\n\t\tprovider: SocialLoginProvider;\n\t\ttoken: string;\n\t}): Promise<IStatusResponse> {\n\t\tif (payload.provider !== 'google') throw new ValidationError('provider must be google');\n\t\tif (!payload.token) throw new ValidationError('token is required');\n\t\treturn this.call('Failed to link social login', () =>\n\t\t\tthis.http.post('/auth/link-social-login', payload),\n\t\t);\n\t}\n\n\t/** `POST /users/api-keys` — generate (and rotate) the current user's API key. */\n\tasync createApiKey(password: string): Promise<IApiKeyResponse> {\n\t\tif (!password) throw new ValidationError('password is required');\n\t\treturn this.call('Failed to create API key', () =>\n\t\t\tthis.http.post('/users/api-keys', { password }),\n\t\t);\n\t}\n\n\t/**\n\t * `GET /users/api-keys` — fetch a masked version of the current API key, or\n\t * `null` if no key has been generated yet.\n\t */\n\tasync getApiKey(): Promise<IMaskedApiKeyResponse> {\n\t\t// Use callOptional so a 404 (\"no key generated yet\") resolves to null —\n\t\t// matching this method's documented contract — instead of throwing.\n\t\tconst result = await this.callOptional<IMaskedApiKeyResponse>('Failed to fetch API key', () =>\n\t\t\tthis.http.get('/users/api-keys'),\n\t\t);\n\t\treturn result ?? null;\n\t}\n\n\t/** `DELETE /users/api-keys` — revoke the current API key. */\n\tasync deleteApiKey(): Promise<IEmptyResult> {\n\t\treturn this.call('Failed to delete API key', () => this.http.delete('/users/api-keys'));\n\t}\n\n\t/** `PUT /authentication/change-password` — change the authenticated user's password. */\n\tasync changePassword(payload: {\n\t\temail: string;\n\t\tpassword: string;\n\t\tnew_password: string;\n\t}): Promise<{ email: string }> {\n\t\tif (!payload.email) throw new ValidationError('email is required');\n\t\tif (!payload.password) throw new ValidationError('password is required');\n\t\tif (!payload.new_password) throw new ValidationError('new_password is required');\n\t\treturn this.call('Failed to change password', () =>\n\t\t\tthis.http.put('/authentication/change-password', payload),\n\t\t);\n\t}\n\n\t/** `PUT /authentication/request-password-reset` — email a reset link to the user. */\n\tasync requestPasswordReset(email: string): Promise<{ email: string }> {\n\t\tif (!email) throw new ValidationError('email is required');\n\t\treturn this.call('Failed to request password reset', () =>\n\t\t\tthis.http.put('/authentication/request-password-reset', { email }, publicRequestConfig()),\n\t\t);\n\t}\n\n\t/** `PUT /authentication/reset-password` — complete a password reset using the emailed token. */\n\tasync resetPassword(payload: {\n\t\temail: string;\n\t\ttoken?: string;\n\t\tnew_password: string;\n\t}): Promise<{ email: string }> {\n\t\tif (!payload.email) throw new ValidationError('email is required');\n\t\tif (!payload.new_password) throw new ValidationError('new_password is required');\n\t\treturn this.call('Failed to reset password', () =>\n\t\t\tthis.http.put('/authentication/reset-password', payload, publicRequestConfig()),\n\t\t);\n\t}\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { ApiError, ValidationError } from '../errors.js';\nimport type {\n\tDocumentArtifactName,\n\tDocumentStatus,\n\tICreateDocumentFromTemplateOptions,\n\tIDetachTagResponse,\n\tIDocumentActivity,\n\tIDocumentDetailsResponse,\n\tIDocumentListItem,\n\tIDocumentListParams,\n\tIDocumentListResponse,\n\tIDocumentSearchParams,\n\tIDocumentStatusInfo,\n\tIDocumentUploadResponse,\n\tIDocumentVerifyResponse,\n\tIEmptyResult,\n\tIEstimateCostResponse,\n\tIPublicDocumentInfo,\n\tISendTokenResponse,\n\tISigningProgress,\n\tITag,\n\tITemplateCostSigner,\n\tITemplateDetailsResponse,\n\tITemplateSigner,\n\tSendTokenChannel,\n} from '../types.js';\nimport {\n\tappendFilePart,\n\tcleanParams,\n\tpublicRequestConfig,\n\trequireDocumentArtifactName,\n\trequireEmail,\n\trequireIso8601,\n\trequireSort,\n\tvalidateDigitalCertificateMethod,\n\tvalidateSignerOptions,\n\tvalidateSigningSteps,\n} from '../utils.js';\nimport { BaseResource } from './base.js';\n\nconst MAX_UPLOAD_BYTES = 25 * 1024 * 1024;\n\nconst DOCUMENT_SORTS = ['name', '-name', 'updated_at', '-updated_at'] as const;\n\nconst READY_STATUSES: ReadonlySet<DocumentStatus | string> = new Set([\n\t'metadata_ready',\n\t'pending_signature',\n\t'pending_identity_review',\n\t'certificated',\n]);\n\nconst FAILED_STATUSES: ReadonlySet<DocumentStatus | string> = new Set([\n\t'failed',\n\t'rejected_by_signer',\n\t'rejected_by_user',\n\t'expired',\n]);\n\n/** Input for uploading a document: either an on-disk file or an in-memory buffer. */\nexport type DocumentUploadSource =\n\t| { filePath: string; fileName?: string }\n\t| { buffer: Buffer; fileName: string };\n\nexport interface IDocumentUploadOptions {\n\t/** Document display name. Defaults to the source PDF file name. */\n\tname?: string;\n\t/** Optional metadata sent alongside the file (JSON-encoded). */\n\tmetadata?: Record<string, unknown>;\n\t/** Override the default account ID configured on the client. */\n\taccountId?: string;\n}\n\nexport class DocumentResource extends BaseResource {\n\t/**\n\t * Upload a PDF to the workspace.\n\t *\n\t * @example\n\t * ```ts\n\t * await client.documents.upload({ filePath: './contract.pdf' });\n\t * await client.documents.upload({ buffer, fileName: 'contract.pdf' }, { metadata });\n\t * ```\n\t */\n\tasync upload(\n\t\tsource: DocumentUploadSource,\n\t\toptions: IDocumentUploadOptions = {},\n\t): Promise<IDocumentUploadResponse> {\n\t\tconst { buffer, fileName } = await loadSource(source);\n\t\tvalidateUpload(buffer, fileName);\n\n\t\tconst accountId = this.accountId(options.accountId);\n\t\tconst form = buildUploadForm(buffer, fileName, options.name ?? fileName, options.metadata);\n\n\t\tthis.logger.info('Uploading document', { fileName, size: buffer.byteLength });\n\n\t\tconst document = await this.call<IDocumentUploadResponse>('Document upload failed', () =>\n\t\t\tthis.http.post(`/accounts/${accountId}/documents`, form, {\n\t\t\t\theaders: { 'Content-Type': 'multipart/form-data' },\n\t\t\t}),\n\t\t);\n\n\t\tif (!document?.id) {\n\t\t\tthrow new ValidationError('Upload succeeded but no document ID was returned', {\n\t\t\t\tresponse: document as unknown as Record<string, unknown>,\n\t\t\t});\n\t\t}\n\t\tthis.logger.info('Document uploaded', { documentId: document.id });\n\t\treturn document;\n\t}\n\n\t/**\n\t * List workspace documents. Pagination info (if any) is attached in `meta`.\n\t * Supports `status`, `method`, `tags`, `search`, `sort`, `page`, `per_page`.\n\t */\n\tasync list(params: IDocumentListParams = {}, accountId?: string): Promise<IDocumentListResponse> {\n\t\tconst id = this.accountId(accountId);\n\t\trequireSort(params.sort, DOCUMENT_SORTS);\n\t\treturn this.callList<IDocumentListItem>('Failed to list documents', () =>\n\t\t\tthis.http.get(`/accounts/${id}/documents`, {\n\t\t\t\tparams: cleanParams(params as unknown as Record<string, unknown>),\n\t\t\t}),\n\t\t);\n\t}\n\n\t/**\n\t * Lightweight document search (`GET /accounts/{id}/documents/search`).\n\t *\n\t * A slimmer counterpart to {@link list} exposed by the API for\n\t * type-ahead/autocomplete. The published spec documents only `search`,\n\t * `status`, `page`, `per-page`, but `sort` is also accepted and functional\n\t * (live-verified against the sandbox).\n\t */\n\tasync search(\n\t\tparams: IDocumentSearchParams = {},\n\t\taccountId?: string,\n\t): Promise<IDocumentListResponse> {\n\t\tconst id = this.accountId(accountId);\n\t\trequireSort(params.sort, DOCUMENT_SORTS);\n\t\treturn this.callList<IDocumentListItem>('Failed to search documents', () =>\n\t\t\tthis.http.get(`/accounts/${id}/documents/search`, {\n\t\t\t\tparams: cleanParams(params as unknown as Record<string, unknown>),\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** Get document details. */\n\tasync details(documentId: string): Promise<IDocumentDetailsResponse> {\n\t\tconst id = this.requireId(documentId, 'Document ID');\n\t\treturn this.fetchDetails(id);\n\t}\n\n\t/**\n\t * Rename a document (`PATCH /documents/{id}`).\n\t *\n\t * Only permitted before the signature process starts — the API returns a\n\t * 400 once an assignment is active.\n\t */\n\tasync rename(documentId: string, name: string): Promise<IDocumentDetailsResponse> {\n\t\tconst id = this.requireId(documentId, 'Document ID');\n\t\tif (!name?.trim()) throw new ValidationError('name is required');\n\t\treturn this.call('Failed to rename document', () =>\n\t\t\tthis.http.patch(`/documents/${id}`, { name }),\n\t\t);\n\t}\n\n\t/** Alias for {@link details}. */\n\tasync get(documentId: string): Promise<IDocumentDetailsResponse> {\n\t\treturn this.details(documentId);\n\t}\n\n\t/** Poll document status until ready (or a terminal status / timeout). */\n\tasync waitUntilReady(\n\t\tdocumentId: string,\n\t\toptions: { maxWaitMs?: number; pollIntervalMs?: number } = {},\n\t): Promise<IDocumentDetailsResponse> {\n\t\tconst id = this.requireId(documentId, 'Document ID');\n\t\tconst maxWaitMs = options.maxWaitMs ?? 30_000;\n\t\tconst pollIntervalMs = options.pollIntervalMs ?? 2_000;\n\t\tif (!Number.isFinite(maxWaitMs) || maxWaitMs <= 0) {\n\t\t\tthrow new ValidationError('maxWaitMs must be a positive finite number');\n\t\t}\n\t\tif (!Number.isFinite(pollIntervalMs) || pollIntervalMs <= 0) {\n\t\t\tthrow new ValidationError('pollIntervalMs must be a positive finite number');\n\t\t}\n\t\tconst start = Date.now();\n\t\tlet attempts = 0;\n\n\t\tthis.logger.info('Waiting for document to be ready', { documentId: id, maxWaitMs });\n\n\t\twhile (Date.now() - start < maxWaitMs) {\n\t\t\tattempts++;\n\t\t\ttry {\n\t\t\t\tconst requestTimeoutMs = Math.max(1, maxWaitMs - (Date.now() - start));\n\t\t\t\tconst details = await this.fetchDetails(id, requestTimeoutMs);\n\t\t\t\tconst status = details.status ?? 'unknown';\n\t\t\t\tthis.logger.debug('Document status check', { attempts, status });\n\n\t\t\t\tif (READY_STATUSES.has(status)) return details;\n\t\t\t\tif (FAILED_STATUSES.has(status)) {\n\t\t\t\t\tthrow new ValidationError(`Document processing failed with status: ${status}`, {\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tif (err instanceof ValidationError) throw err;\n\t\t\t\t// A client-side error (bad/unknown id, unauthorized, forbidden) will\n\t\t\t\t// never become \"ready\" — surface it immediately instead of masking it\n\t\t\t\t// as a timeout after the full maxWaitMs. Keep retrying transient\n\t\t\t\t// failures (network blips, 5xx).\n\t\t\t\tif (err instanceof ApiError && err.statusCode >= 400 && err.statusCode < 500) {\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t\tthis.logger.warn('Error checking document status', {\n\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst remainingMs = maxWaitMs - (Date.now() - start);\n\t\t\tif (remainingMs <= 0) break;\n\t\t\tawait sleep(Math.min(pollIntervalMs, remainingMs));\n\t\t}\n\n\t\tthrow new ValidationError('Timeout waiting for document to be ready', {\n\t\t\tdocumentId: id,\n\t\t\tattempts,\n\t\t});\n\t}\n\n\tprivate fetchDetails(documentId: string, timeout?: number): Promise<IDocumentDetailsResponse> {\n\t\treturn this.call('Failed to fetch document details', () =>\n\t\t\tthis.http.get(`/documents/${documentId}`, timeout === undefined ? undefined : { timeout }),\n\t\t);\n\t}\n\n\t/** Download a document artifact. Defaults to the certificated (signed) PDF. */\n\tasync download(\n\t\tdocumentId: string,\n\t\tartifactName: DocumentArtifactName = 'certificated',\n\t): Promise<Buffer> {\n\t\tconst id = this.requireId(documentId, 'Document ID');\n\t\tconst artifact = requireDocumentArtifactName(artifactName);\n\t\treturn this.callBinary('Failed to download document', () =>\n\t\t\tthis.http.get<ArrayBuffer>(`/documents/${id}/download/${artifact}`, {\n\t\t\t\tresponseType: 'arraybuffer',\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** Download the document thumbnail. */\n\tasync thumbnail(documentId: string): Promise<Buffer> {\n\t\tconst id = this.requireId(documentId, 'Document ID');\n\t\treturn this.callBinary('Failed to download document thumbnail', () =>\n\t\t\tthis.http.get<ArrayBuffer>(`/documents/${id}/thumbnail`, { responseType: 'arraybuffer' }),\n\t\t);\n\t}\n\n\t/** Download a single page as a JPEG. */\n\tasync downloadPage(documentId: string, pageId: string): Promise<Buffer> {\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\tconst pid = this.requireId(pageId, 'Page ID');\n\t\treturn this.callBinary('Failed to download page', () =>\n\t\t\tthis.http.get<ArrayBuffer>(`/documents/${docId}/pages/${pid}/download`, {\n\t\t\t\tresponseType: 'arraybuffer',\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** Fetch the document activity log. */\n\tasync activities(documentId: string): Promise<IDocumentActivity[]> {\n\t\tconst id = this.requireId(documentId, 'Document ID');\n\t\tconst result = await this.call<IDocumentActivity[] | null>(\n\t\t\t'Failed to fetch document activities',\n\t\t\t() => this.http.get(`/documents/${id}/activities`),\n\t\t);\n\t\treturn result ?? [];\n\t}\n\n\t/** Delete a document. */\n\tasync delete(documentId: string): Promise<IEmptyResult> {\n\t\tconst id = this.requireId(documentId, 'Document ID');\n\t\treturn this.call('Failed to delete document', () => this.http.delete(`/documents/${id}`));\n\t}\n\n\t/** List the tags attached to a document. */\n\tasync listTags(documentId: string, accountId?: string): Promise<ITag[]> {\n\t\tconst accId = this.accountId(accountId);\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\treturn this.call('Failed to list document tags', () =>\n\t\t\tthis.http.get(`/accounts/${accId}/documents/${docId}/tags`),\n\t\t);\n\t}\n\n\t/**\n\t * Replace the document's tag set. Production accepts tag names and creates missing tags.\n\t * An empty array detaches all tags. Values are forwarded unchanged.\n\t */\n\tasync replaceTags(documentId: string, tags: string[], accountId?: string): Promise<ITag[]> {\n\t\tconst accId = this.accountId(accountId);\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\tif (!Array.isArray(tags)) throw new ValidationError('tags must be an array');\n\t\treturn this.call('Failed to replace document tags', () =>\n\t\t\tthis.http.put(`/accounts/${accId}/documents/${docId}/tags`, { tags }),\n\t\t);\n\t}\n\n\t/** Attach additional tag names without removing existing ones. Production creates missing tags. */\n\tasync addTags(documentId: string, tags: string[], accountId?: string): Promise<ITag[]> {\n\t\tconst accId = this.accountId(accountId);\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\tif (!Array.isArray(tags) || tags.length === 0) {\n\t\t\tthrow new ValidationError('tags must be a non-empty array');\n\t\t}\n\t\treturn this.call('Failed to add document tags', () =>\n\t\t\tthis.http.post(`/accounts/${accId}/documents/${docId}/tags`, { tags }),\n\t\t);\n\t}\n\n\t/** Detach a single tag from a document (the tag itself is not deleted). */\n\tasync detachTag(\n\t\tdocumentId: string,\n\t\ttagId: string,\n\t\taccountId?: string,\n\t): Promise<IDetachTagResponse> {\n\t\tconst accId = this.accountId(accountId);\n\t\tconst docId = this.requireId(documentId, 'Document ID');\n\t\tconst tid = this.requireId(tagId, 'Tag ID');\n\t\treturn this.call('Failed to detach document tag', () =>\n\t\t\tthis.http.delete(`/accounts/${accId}/documents/${docId}/tags/${tid}`),\n\t\t);\n\t}\n\n\t/**\n\t * Create a document from a template.\n\t *\n\t * @example\n\t * ```ts\n\t * await client.documents.createFromTemplate('tmpl_id', [\n\t * { role_id: 'role_id', id: 'signer_id', verification_method: 'Email', notification_methods: ['Email'] },\n\t * ], { name: 'My Contract' });\n\t * ```\n\t */\n\tasync createFromTemplate(\n\t\ttemplateId: string,\n\t\tsigners: ITemplateSigner[],\n\t\toptions: ICreateDocumentFromTemplateOptions = {},\n\t\taccountId?: string,\n\t): Promise<IDocumentDetailsResponse> {\n\t\tconst tmplId = this.requireId(templateId, 'Template ID');\n\t\tconst accId = this.accountId(accountId);\n\t\tvalidateTemplateSigners(signers, { requireId: true });\n\t\tif (options.expires_at !== undefined) requireIso8601(options.expires_at, 'expires_at');\n\t\tif (\n\t\t\toptions.editor_fields !== undefined &&\n\t\t\t(!Array.isArray(options.editor_fields) ||\n\t\t\t\toptions.editor_fields.some((field) => !field?.field_id || typeof field.value !== 'string'))\n\t\t) {\n\t\t\tthrow new ValidationError('editor_fields must contain field_id and value');\n\t\t}\n\t\tif (\n\t\t\toptions.tags !== undefined &&\n\t\t\t(!Array.isArray(options.tags) || options.tags.some((tag) => typeof tag !== 'string' || !tag))\n\t\t) {\n\t\t\tthrow new ValidationError('tags must contain non-empty tag names');\n\t\t}\n\t\tawait this.validateCertificateTemplateMethod(tmplId, accId, signers);\n\t\tconst body: Record<string, unknown> = { ...options, signers };\n\t\tthis.logger.info('Creating document from template', { templateId: tmplId, accountId: accId });\n\t\treturn this.call('Failed to create document from template', () =>\n\t\t\tthis.http.post(`/accounts/${accId}/templates/${tmplId}/documents`, body),\n\t\t);\n\t}\n\n\t/** Estimate the credit cost of creating a document from a template. */\n\tasync estimateCostFromTemplate(\n\t\ttemplateId: string,\n\t\tsigners: ITemplateCostSigner[],\n\t\taccountId?: string,\n\t): Promise<IEstimateCostResponse> {\n\t\tconst tmplId = this.requireId(templateId, 'Template ID');\n\t\tconst accId = this.accountId(accountId);\n\t\tvalidateTemplateSigners(signers, { requireId: false });\n\t\tawait this.validateCertificateTemplateMethod(tmplId, accId, signers);\n\t\treturn this.call('Failed to estimate cost from template', () =>\n\t\t\tthis.http.post(`/accounts/${accId}/templates/${tmplId}/documents/estimate-cost`, { signers }),\n\t\t);\n\t}\n\n\t/**\n\t * Verify a document by its signature hash. Always resolves (the API\n\t * returns `200` even for an unknown hash, with `is_valid: false`).\n\t */\n\tasync verify(hash: string): Promise<IDocumentVerifyResponse> {\n\t\tconst h = this.requireId(hash, 'Signature hash');\n\t\treturn this.call('Failed to verify document', () =>\n\t\t\tthis.http.get(`/documents/${h}/verify`, publicRequestConfig()),\n\t\t);\n\t}\n\n\t/**\n\t * `GET /documents/statuses` — list every possible document status with\n\t * its description and whether documents in that status can be deleted.\n\t */\n\tasync statuses(): Promise<IDocumentStatusInfo[]> {\n\t\treturn this.call('Failed to list document statuses', () =>\n\t\t\tthis.http.get('/documents/statuses'),\n\t\t);\n\t}\n\n\t/**\n\t * `GET /public/documents/{document_id}` — public, unauthenticated lookup of\n\t * basic document info (used by the signing portal before the signer\n\t * authenticates via the access code).\n\t */\n\tasync getPublic(documentId: string): Promise<IPublicDocumentInfo> {\n\t\tconst id = this.requireId(documentId, 'Document ID');\n\t\treturn this.call('Failed to fetch public document info', () =>\n\t\t\tthis.http.get(`/public/documents/${id}`, publicRequestConfig()),\n\t\t);\n\t}\n\n\t/**\n\t * `PUT /public/documents/{document_id}/send-token` — email a one-time access\n\t * token to a signer who has not signed a pending document yet. The API sends\n\t * `{ channel: 'email', recipient }`; only the `email` channel is accepted.\n\t * The `{ email }` form is kept for existing callers and sends the same body.\n\t */\n\tasync sendToken(\n\t\tdocumentId: string,\n\t\trecipient: string | { email: string },\n\t\tchannel: SendTokenChannel = 'email',\n\t): Promise<ISendTokenResponse> {\n\t\tconst id = this.requireId(documentId, 'Document ID');\n\t\tconst email = typeof recipient === 'object' ? recipient?.email : recipient;\n\t\tif (channel !== 'email') throw new ValidationError('channel must be email');\n\t\trequireEmail(email);\n\t\treturn this.call('Failed to send signing token', () =>\n\t\t\tthis.http.put(\n\t\t\t\t`/public/documents/${id}/send-token`,\n\t\t\t\t{ channel, recipient: email },\n\t\t\t\tpublicRequestConfig(),\n\t\t\t),\n\t\t);\n\t}\n\n\t/** Quick check: has every signer completed their assignment? */\n\tasync isFullySigned(documentId: string): Promise<boolean> {\n\t\tconst details = await this.details(documentId);\n\t\tif (details.status === 'certificated') return true;\n\t\tconst summary = details.assignment?.summary;\n\t\tif (summary && typeof summary.signer_count === 'number') {\n\t\t\treturn summary.signer_count > 0 && summary.signer_count === summary.completed_count;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/** Summarise signing progress for UI display. */\n\tasync getSigningProgress(documentId: string): Promise<ISigningProgress> {\n\t\tconst details = await this.details(documentId);\n\t\tconst summary = details.assignment?.summary;\n\t\tconst total = summary?.signer_count ?? details.assignment?.signers?.length ?? 0;\n\t\tconst signed = summary?.completed_count ?? 0;\n\t\tconst pending = Math.max(total - signed, 0);\n\t\tconst percentage = total > 0 ? Math.round((signed / total) * 10_000) / 100 : 0;\n\t\treturn { signed, total, pending, percentage };\n\t}\n\n\tprivate async validateCertificateTemplateMethod(\n\t\ttemplateId: string,\n\t\taccountId: string,\n\t\tsigners: readonly { verification_method?: unknown }[],\n\t): Promise<void> {\n\t\tif (!signers.some((signer) => signer.verification_method === 'DigitalCertificate')) return;\n\t\tconst template = await this.call<ITemplateDetailsResponse>('Failed to fetch template', () =>\n\t\t\tthis.http.get(`/accounts/${accountId}/templates/${templateId}`),\n\t\t);\n\t\tconst method = template.pages?.some((page) => page.fields.length > 0) ? 'collect' : 'virtual';\n\t\tvalidateDigitalCertificateMethod(method, signers);\n\t}\n}\n\nfunction validateTemplateSigners(signers: unknown, options: { requireId: boolean }): void {\n\tif (!Array.isArray(signers)) throw new ValidationError('signers must be an array');\n\tfor (const value of signers) {\n\t\tif (!value || typeof value !== 'object') {\n\t\t\tthrow new ValidationError('each template signer must be an object');\n\t\t}\n\t\tconst signer = value as {\n\t\t\trole_id?: unknown;\n\t\t\tid?: unknown;\n\t\t\tverification_method?: unknown;\n\t\t\tnotification_methods?: unknown;\n\t\t\tstep?: unknown;\n\t\t};\n\t\tif (typeof signer.role_id !== 'string' || !signer.role_id) {\n\t\t\tthrow new ValidationError('each template signer requires role_id');\n\t\t}\n\t\tif (\n\t\t\t(options.requireId || signer.id !== undefined) &&\n\t\t\t(typeof signer.id !== 'string' || !signer.id)\n\t\t) {\n\t\t\tthrow new ValidationError('each template signer requires a valid id');\n\t\t}\n\t\tvalidateSignerOptions(signer);\n\t\tif (options.requireId && signer.step !== undefined && Number(signer.step) < 1) {\n\t\t\tthrow new ValidationError('template signer step must be a positive integer');\n\t\t}\n\t}\n\tif (options.requireId) {\n\t\tvalidateSigningSteps(signers as Array<{ verification_method?: unknown; step?: unknown }>);\n\t}\n}\n\nasync function loadSource(\n\tsource: DocumentUploadSource,\n): Promise<{ buffer: Buffer; fileName: string }> {\n\tif ('buffer' in source) {\n\t\tif (!source.fileName) {\n\t\t\tthrow new ValidationError('fileName is required when uploading a Buffer');\n\t\t}\n\t\treturn { buffer: source.buffer, fileName: source.fileName };\n\t}\n\tif (!source.filePath) {\n\t\tthrow new ValidationError('filePath is required');\n\t}\n\tconst { size } = await fs.stat(source.filePath);\n\tif (size > MAX_UPLOAD_BYTES) {\n\t\tthrow new ValidationError('File size exceeds maximum allowed (25MB)', {\n\t\t\tfileSize: size,\n\t\t\tmaxSize: MAX_UPLOAD_BYTES,\n\t\t});\n\t}\n\tconst buffer = await fs.readFile(source.filePath);\n\treturn { buffer, fileName: source.fileName ?? path.basename(source.filePath) };\n}\n\nfunction validateUpload(buffer: Buffer, fileName: string): void {\n\tif (!buffer || buffer.byteLength === 0) {\n\t\tthrow new ValidationError('File buffer is empty', { fileName });\n\t}\n\tif (!fileName.toLowerCase().endsWith('.pdf')) {\n\t\tthrow new ValidationError('Only PDF files are supported', { fileName });\n\t}\n\tif (buffer.byteLength > MAX_UPLOAD_BYTES) {\n\t\tthrow new ValidationError('File size exceeds maximum allowed (25MB)', {\n\t\t\tfileSize: buffer.byteLength,\n\t\t\tmaxSize: MAX_UPLOAD_BYTES,\n\t\t});\n\t}\n}\n\nfunction buildUploadForm(\n\tbuffer: Buffer,\n\tfileName: string,\n\tname: string,\n\tmetadata: Record<string, unknown> | undefined,\n): FormData {\n\tconst form = new FormData();\n\tappendFilePart(form, buffer, 'application/pdf', fileName);\n\tform.append('name', name);\n\tif (metadata) {\n\t\tform.append('metadata', JSON.stringify(metadata));\n\t}\n\treturn form;\n}\n\nfunction sleep(ms: number): Promise<void> {\n\treturn new Promise((resolve) => setTimeout(resolve, ms));\n}\n","import { ValidationError } from '../errors.js';\nimport type {\n\tICreateFieldPayload,\n\tIEmptyResult,\n\tIFieldDefinition,\n\tIFieldType,\n\tIFieldValidateMultipleEntry,\n\tIFieldValidationResult,\n\tIUpdateFieldPayload,\n} from '../types.js';\nimport { cleanParams, signerAccessConfig } from '../utils.js';\nimport { BaseResource } from './base.js';\n\n/**\n * Custom field definitions used by `collect` assignments.\n *\n * Covers the full Field Definition section of the API docs:\n * - `POST /accounts/{id}/fields`\n * - `GET /accounts/{id}/fields`\n * - `GET /accounts/{id}/fields/{id}`\n * - `PUT /accounts/{id}/fields/{id}`\n * - `DELETE /accounts/{id}/fields/{id}`\n * - `POST /accounts/{id}/fields/{id}/validate?signer-access-code=…`\n * - `POST /accounts/{id}/fields/validate-multiple?signer-access-code=…`\n * - `GET /field-types`\n *\n * The `signer-access-code` query param on the two `validate*` endpoints isn't\n * in the published OpenAPI spec but is live-verified against the sandbox: a\n * bogus code returns 401, matching every other signer-access-code endpoint.\n */\nexport class FieldsResource extends BaseResource {\n\t/** Create a field definition. */\n\tasync create(payload: ICreateFieldPayload, accountId?: string): Promise<IFieldDefinition> {\n\t\tif (!payload.type) throw new ValidationError('field type is required');\n\t\tif (!payload.name) throw new ValidationError('field name is required');\n\t\tconst id = this.accountId(accountId);\n\t\treturn this.call('Failed to create field definition', () =>\n\t\t\tthis.http.post(`/accounts/${id}/fields`, payload),\n\t\t);\n\t}\n\n\t/**\n\t * List field definitions for the workspace.\n\t *\n\t * @param params.include_inactive return inactive fields too\n\t * @param params.include_standard also return `signature`, `initial`, `signatureDate`\n\t */\n\tasync list(\n\t\tparams: { include_inactive?: boolean; include_standard?: boolean } = {},\n\t\taccountId?: string,\n\t): Promise<IFieldDefinition[]> {\n\t\tconst id = this.accountId(accountId);\n\t\treturn this.call('Failed to list field definitions', () =>\n\t\t\tthis.http.get(`/accounts/${id}/fields`, {\n\t\t\t\tparams: cleanParams(params as Record<string, unknown>),\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** Get a single field definition by ID. */\n\tasync get(fieldId: string, accountId?: string): Promise<IFieldDefinition> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst fid = this.requireId(fieldId, 'Field ID');\n\t\treturn this.call('Failed to fetch field definition', () =>\n\t\t\tthis.http.get(`/accounts/${id}/fields/${fid}`),\n\t\t);\n\t}\n\n\t/** Update a field definition. */\n\tasync update(\n\t\tfieldId: string,\n\t\tpayload: IUpdateFieldPayload,\n\t\taccountId?: string,\n\t): Promise<IFieldDefinition> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst fid = this.requireId(fieldId, 'Field ID');\n\t\treturn this.call('Failed to update field definition', () =>\n\t\t\tthis.http.put(`/accounts/${id}/fields/${fid}`, payload),\n\t\t);\n\t}\n\n\t/** Delete a field definition. Fails if the field has been used. */\n\tasync delete(fieldId: string, accountId?: string): Promise<IEmptyResult> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst fid = this.requireId(fieldId, 'Field ID');\n\t\treturn this.call('Failed to delete field definition', () =>\n\t\t\tthis.http.delete(`/accounts/${id}/fields/${fid}`),\n\t\t);\n\t}\n\n\t/**\n\t * Validate a single value against a field definition.\n\t *\n\t * Pass `signerAccessCode` for signer-side validation (the typical use case);\n\t * omit it when the caller is authenticated via API key.\n\t */\n\tasync validate(\n\t\tfieldId: string,\n\t\tvalue: unknown,\n\t\toptions: { signerAccessCode?: string; accountId?: string } = {},\n\t): Promise<IFieldValidationResult> {\n\t\tconst id = this.accountId(options.accountId);\n\t\tconst fid = this.requireId(fieldId, 'Field ID');\n\t\tif (value === undefined) throw new ValidationError('value is required');\n\t\treturn this.call('Failed to validate field value', () =>\n\t\t\tthis.http.post(\n\t\t\t\t`/accounts/${id}/fields/${fid}/validate`,\n\t\t\t\t{ value },\n\t\t\t\tvalidationConfig(options.signerAccessCode),\n\t\t\t),\n\t\t);\n\t}\n\n\t/** Validate multiple values at once. */\n\tasync validateMultiple(\n\t\tentries: IFieldValidateMultipleEntry[],\n\t\toptions: { signerAccessCode?: string; accountId?: string } = {},\n\t): Promise<IFieldValidationResult[]> {\n\t\tif (!Array.isArray(entries) || entries.length === 0) {\n\t\t\tthrow new ValidationError('entries must be a non-empty array');\n\t\t}\n\t\tif (\n\t\t\tentries.some(\n\t\t\t\t(entry) =>\n\t\t\t\t\t!entry ||\n\t\t\t\t\ttypeof entry !== 'object' ||\n\t\t\t\t\ttypeof entry.field_id !== 'string' ||\n\t\t\t\t\t!entry.field_id ||\n\t\t\t\t\tentry.value === undefined,\n\t\t\t)\n\t\t) {\n\t\t\tthrow new ValidationError('each entry must contain field_id and value');\n\t\t}\n\t\tconst id = this.accountId(options.accountId);\n\t\treturn this.call('Failed to validate field values', () =>\n\t\t\tthis.http.post(\n\t\t\t\t`/accounts/${id}/fields/validate-multiple`,\n\t\t\t\tentries,\n\t\t\t\tvalidationConfig(options.signerAccessCode),\n\t\t\t),\n\t\t);\n\t}\n\n\t/** List the platform's supported field types. */\n\tasync listTypes(): Promise<IFieldType[]> {\n\t\treturn this.call('Failed to list field types', () => this.http.get('/field-types'));\n\t}\n}\n\nfunction validationConfig(signerAccessCode?: string) {\n\tif (signerAccessCode === undefined) return undefined;\n\tif (typeof signerAccessCode !== 'string' || !signerAccessCode.trim()) {\n\t\tthrow new ValidationError('signerAccessCode is required when supplied');\n\t}\n\treturn signerAccessConfig(signerAccessCode);\n}\n","import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';\nimport type { AxiosRequestConfig } from 'axios';\nimport { ValidationError } from '../errors.js';\nimport type {\n\tIOAuthAuthorizationOptions,\n\tIOAuthAuthorizationRequest,\n\tIOAuthAuthorizationServer,\n\tIOAuthProtectedResource,\n\tIOAuthRevokePayload,\n\tIOAuthTokenPayload,\n\tIOAuthTokenResponse,\n\tIOAuthUserInfo,\n} from '../types.js';\nimport { publicRequestConfig } from '../utils.js';\nimport { BaseResource } from './base.js';\n\n/** Token and revocation bodies are form-encoded (RFC 6749/7009); Axios omits undefined fields. */\nfunction formRequestConfig(): AxiosRequestConfig {\n\treturn publicRequestConfig({\n\t\theaders: { 'Content-Type': 'application/x-www-form-urlencoded' },\n\t});\n}\n\n/** OAuth 2.1 with S256 PKCE. Tokens are returned to the caller, never saved or retried. */\nexport class OAuthResource extends BaseResource {\n\t/** `GET /.well-known/oauth-protected-resource` at the API origin, outside `/v1`. */\n\tasync metadata(): Promise<IOAuthProtectedResource> {\n\t\treturn this.call('Failed to discover OAuth resource', () => {\n\t\t\tconst baseURL = this.http.defaults.baseURL;\n\t\t\tif (!baseURL) {\n\t\t\t\tthrow new ValidationError('A base URL is required to discover OAuth metadata');\n\t\t\t}\n\t\t\treturn this.http.get(\n\t\t\t\t'/.well-known/oauth-protected-resource',\n\t\t\t\tpublicRequestConfig({\n\t\t\t\t\tbaseURL: new URL(baseURL).origin,\n\t\t\t\t}),\n\t\t\t);\n\t\t});\n\t}\n\n\t/** Read RFC 8414 metadata from an HTTPS issuer and verify its issuer identity. */\n\tasync discovery(issuer: string): Promise<IOAuthAuthorizationServer> {\n\t\tconst url = httpsUrl(issuer, 'issuer');\n\t\tif (url.search || url.pathname !== '/') {\n\t\t\tthrow new ValidationError('issuer must be an HTTPS origin');\n\t\t}\n\t\tconst metadata = await this.call<IOAuthAuthorizationServer>(\n\t\t\t'Failed to discover OAuth authorization server',\n\t\t\t() =>\n\t\t\t\tthis.http.get(\n\t\t\t\t\t`${url.origin}/.well-known/oauth-authorization-server`,\n\t\t\t\t\tpublicRequestConfig(),\n\t\t\t\t),\n\t\t);\n\t\tif (metadata.issuer !== issuer) throw new ValidationError('OAuth issuer mismatch');\n\t\thttpsUrl(metadata.authorization_endpoint, 'authorization_endpoint');\n\t\treturn metadata;\n\t}\n\n\t/** Discover endpoints and create a fresh authorization URL, PKCE verifier, and state. */\n\tasync authorize(options: IOAuthAuthorizationOptions): Promise<IOAuthAuthorizationRequest> {\n\t\trequired(options.clientId, 'clientId');\n\t\thttpsUrl(options.redirectUri, 'redirectUri');\n\t\tif (\n\t\t\t!Array.isArray(options.scopes) ||\n\t\t\toptions.scopes.length === 0 ||\n\t\t\toptions.scopes.some(\n\t\t\t\t(scope) => typeof scope !== 'string' || !/^[\\x21\\x23-\\x5B\\x5D-\\x7E]+$/.test(scope),\n\t\t\t)\n\t\t) {\n\t\t\tthrow new ValidationError('scopes must contain non-empty OAuth scope names');\n\t\t}\n\t\tconst resource = await this.metadata();\n\t\tconst issuer = resource.authorization_servers?.[0];\n\t\tif (!issuer) throw new ValidationError('OAuth metadata has no authorization server');\n\t\thttpsUrl(resource.resource, 'resource');\n\t\tconst server = await this.discovery(issuer);\n\t\tconst codeVerifier = randomBytes(32).toString('base64url');\n\t\tconst state = randomBytes(32).toString('base64url');\n\t\tconst nonce = options.scopes.includes('openid')\n\t\t\t? randomBytes(32).toString('base64url')\n\t\t\t: undefined;\n\t\tconst url = new URL(server.authorization_endpoint);\n\t\tconst params = {\n\t\t\tresponse_type: 'code',\n\t\t\tclient_id: options.clientId,\n\t\t\tredirect_uri: options.redirectUri,\n\t\t\tscope: options.scopes.join(' '),\n\t\t\tstate,\n\t\t\tcode_challenge: createHash('sha256').update(codeVerifier).digest('base64url'),\n\t\t\tcode_challenge_method: 'S256',\n\t\t\tresource: resource.resource,\n\t\t};\n\t\tfor (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);\n\t\tif (nonce) url.searchParams.set('nonce', nonce);\n\t\treturn {\n\t\t\tauthorization_url: url.toString(),\n\t\t\tcode_verifier: codeVerifier,\n\t\t\tstate,\n\t\t\tissuer,\n\t\t\tclient_id: options.clientId,\n\t\t\tredirect_uri: options.redirectUri,\n\t\t\tresource: resource.resource,\n\t\t\t...(nonce ? { nonce } : {}),\n\t\t};\n\t}\n\n\t/** Validate callback URI, state, and issuer before exchanging its one-time code. */\n\tasync exchangeCode(\n\t\tcallbackUrl: string,\n\t\trequest: IOAuthAuthorizationRequest,\n\t\tclientSecret?: string,\n\t): Promise<IOAuthTokenResponse> {\n\t\tconst callback = httpsUrl(callbackUrl, 'callbackUrl');\n\t\tconst redirect = httpsUrl(request.redirect_uri, 'redirect_uri');\n\t\tif (\n\t\t\tcallback.origin !== redirect.origin ||\n\t\t\tcallback.pathname !== redirect.pathname ||\n\t\t\t[...new Set(redirect.searchParams.keys())].some((key) => {\n\t\t\t\tconst expected = redirect.searchParams.getAll(key);\n\t\t\t\tconst actual = callback.searchParams.getAll(key);\n\t\t\t\treturn (\n\t\t\t\t\texpected.length !== actual.length || expected.some((value, i) => value !== actual[i])\n\t\t\t\t);\n\t\t\t})\n\t\t) {\n\t\t\tthrow new ValidationError('OAuth callback does not match the registered redirect URI');\n\t\t}\n\t\tfor (const key of ['state', 'iss', 'code', 'error']) {\n\t\t\tif (callback.searchParams.getAll(key).length > 1) {\n\t\t\t\tthrow new ValidationError(`Duplicate OAuth callback parameter: ${key}`);\n\t\t\t}\n\t\t}\n\t\tconst actual = Buffer.from(callback.searchParams.get('state') ?? '');\n\t\tconst expected = Buffer.from(required(request.state, 'state'));\n\t\tif (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {\n\t\t\tthrow new ValidationError('OAuth state mismatch');\n\t\t}\n\t\tif (callback.searchParams.get('iss') !== request.issuer) {\n\t\t\tthrow new ValidationError('OAuth issuer mismatch');\n\t\t}\n\t\tif (callback.searchParams.has('code') === callback.searchParams.has('error')) {\n\t\t\tthrow new ValidationError('OAuth callback must contain exactly one of code or error');\n\t\t}\n\t\tif (callback.searchParams.has('error')) {\n\t\t\tconst error = callback.searchParams.get('error')!;\n\t\t\tconst oauthError =\n\t\t\t\terror.length > 0 && error.length <= 64 && !/[^a-z_]/.test(error) ? error : 'unknown_error';\n\t\t\tthrow new ValidationError(`OAuth authorization was declined or failed: ${oauthError}`, {\n\t\t\t\toauthError,\n\t\t\t});\n\t\t}\n\t\treturn this.token({\n\t\t\tgrant_type: 'authorization_code',\n\t\t\tcode: required(callback.searchParams.get('code'), 'code'),\n\t\t\tclient_id: request.client_id,\n\t\t\tclient_secret: clientSecret,\n\t\t\tredirect_uri: request.redirect_uri,\n\t\t\tcode_verifier: request.code_verifier,\n\t\t\tresource: request.resource,\n\t\t});\n\t}\n\n\t/**\n\t * `POST /oauth/token` — code exchange, refresh, or RFC 8693 token exchange; returns the flat OAuth JSON body.\n\t * A refresh must return a new `refresh_token`; otherwise this throws `ValidationError`.\n\t */\n\tasync token(payload: IOAuthTokenPayload): Promise<IOAuthTokenResponse> {\n\t\trequired(payload.client_id, 'client_id');\n\t\tif (payload.client_secret !== undefined) required(payload.client_secret, 'client_secret');\n\t\tif (payload.resource !== undefined) httpsUrl(payload.resource, 'resource');\n\t\tif (payload.grant_type === 'authorization_code') {\n\t\t\trequired(payload.code, 'code');\n\t\t\thttpsUrl(payload.redirect_uri, 'redirect_uri');\n\t\t\tif (\n\t\t\t\ttypeof payload.code_verifier !== 'string' ||\n\t\t\t\t!/^[A-Za-z0-9._~-]{43,128}$/.test(payload.code_verifier)\n\t\t\t) {\n\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t'code_verifier must contain 43–128 RFC 7636 unreserved characters',\n\t\t\t\t);\n\t\t\t}\n\t\t} else if (payload.grant_type === 'refresh_token') {\n\t\t\trequired(payload.refresh_token, 'refresh_token');\n\t\t} else if (payload.grant_type === TOKEN_EXCHANGE) {\n\t\t\trequired(payload.client_secret, 'client_secret');\n\t\t\thttpsUrl(required(payload.resource, 'resource'), 'resource');\n\t\t\trequired(payload.subject_token, 'subject_token');\n\t\t\tfor (const field of ['subject_token_type', 'requested_token_type'] as const) {\n\t\t\t\tconst value = payload[field];\n\t\t\t\tif (\n\t\t\t\t\t(value !== undefined || field === 'subject_token_type') &&\n\t\t\t\t\tvalue !== ACCESS_TOKEN_TYPE\n\t\t\t\t) {\n\t\t\t\t\tthrow new ValidationError(`${field} must be ${ACCESS_TOKEN_TYPE}`);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new ValidationError(\n\t\t\t\t`grant_type must be authorization_code, refresh_token or ${TOKEN_EXCHANGE}`,\n\t\t\t);\n\t\t}\n\t\tconst tokens = await this.call<IOAuthTokenResponse>('OAuth token request failed', () =>\n\t\t\tthis.http.post('/oauth/token', payload, formRequestConfig()),\n\t\t);\n\t\t// Refresh tokens rotate: a successful refresh has already retired the submitted token.\n\t\tconst next = tokens?.refresh_token;\n\t\tif (\n\t\t\tpayload.grant_type === 'refresh_token' &&\n\t\t\t(typeof next !== 'string' || !next.trim() || next === payload.refresh_token)\n\t\t) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'OAuth refresh response has no new refresh_token; the submitted refresh token may ' +\n\t\t\t\t\t'already be retired, so do not reuse it: reconnect instead',\n\t\t\t\t{ field: 'refresh_token' },\n\t\t\t);\n\t\t}\n\t\treturn tokens;\n\t}\n\n\t/** `POST /oauth/revoke` — revoke an access/refresh token; success has no required body. */\n\tasync revoke(payload: IOAuthRevokePayload): Promise<void> {\n\t\trequired(payload.client_id, 'client_id');\n\t\trequired(payload.token, 'token');\n\t\tif (payload.client_secret !== undefined) required(payload.client_secret, 'client_secret');\n\t\tif (\n\t\t\tpayload.token_type_hint !== undefined &&\n\t\t\t!['access_token', 'refresh_token'].includes(payload.token_type_hint)\n\t\t) {\n\t\t\tthrow new ValidationError('token_type_hint must be access_token or refresh_token');\n\t\t}\n\t\tawait this.call('OAuth revocation failed', () =>\n\t\t\tthis.http.post('/oauth/revoke', payload, formRequestConfig()),\n\t\t);\n\t}\n\n\t/** `GET /oauth/userinfo` — flat OIDC claims; requires a bearer token with `openid`. */\n\tasync userinfo(): Promise<IOAuthUserInfo> {\n\t\treturn this.call('Failed to fetch OAuth userinfo', () => this.http.get('/oauth/userinfo'));\n\t}\n}\n\nconst TOKEN_EXCHANGE = 'urn:ietf:params:oauth:grant-type:token-exchange';\nconst ACCESS_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';\n\nfunction required(value: unknown, name: string): string {\n\tif (typeof value !== 'string' || !value.trim()) throw new ValidationError(`${name} is required`);\n\treturn value;\n}\n\nfunction httpsUrl(value: string, name: string): URL {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(value);\n\t} catch {\n\t\tthrow new ValidationError(`${name} must be an absolute HTTPS URL`);\n\t}\n\tif (url.protocol !== 'https:' || url.username || url.password || url.hash) {\n\t\tthrow new ValidationError(`${name} must use HTTPS without credentials or a fragment`);\n\t}\n\treturn url;\n}\n","import { ValidationError } from '../errors.js';\nimport type {\n\tDocumentArtifactName,\n\tICertificateCompleteResponse,\n\tICertificateStartResponse,\n\tIDocumentDetailsResponse,\n\tIDocumentListItem,\n\tIDocumentListResponse,\n\tIEmptyResult,\n\tIIdentityVerificationSession,\n\tIIdentityVerificationState,\n\tISigner,\n\tISignerDocumentListParams,\n\tISignerSelf,\n\tISignerTermsAcceptance,\n\tISignFieldEntry,\n\tIStartIdentityVerificationPayload,\n\tIStatusResponse,\n\tIVerifySignerCodePayload,\n} from '../types.js';\nimport {\n\tcleanParams,\n\tpublicRequestConfig,\n\trequireDocumentArtifactName,\n\trequireSignerImageType,\n\tsignerAccessConfig,\n} from '../utils.js';\nimport { BaseResource } from './base.js';\n\n/**\n * Signer-side endpoints use `signer-access-code` from the private signing link.\n * Explicit `listAsOwner`/`searchAsOwner` use workspace credentials, and artifact\n * downloads are public with an optional signer-identity preflight.\n */\nexport class SignerDocumentsResource extends BaseResource {\n\t/** `GET /signers/{signer_id}/document?signer-access-code=…` */\n\tasync getCurrent(signerId: string, signerAccessCode: string): Promise<IDocumentDetailsResponse> {\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\treturn this.call('Failed to fetch current signer document', () =>\n\t\t\tthis.http.get(`/signers/${sid}/document`, signerAccessConfig(code)),\n\t\t);\n\t}\n\n\t/** `GET /signers/{signer_id}/documents?signer-access-code=…` */\n\tasync list(\n\t\tsignerId: string,\n\t\tsignerAccessCode: string,\n\t\tparams: ISignerDocumentListParams = {},\n\t): Promise<IDocumentListResponse> {\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\treturn this.listDocuments(signerId, signerAccessConfig(code, { ...params }));\n\t}\n\n\t/**\n\t * `GET /signers/{signer_id}/documents` with the client's owner credentials\n\t * (API key or token) instead of a signer access code. The signer must belong\n\t * to that workspace.\n\t */\n\tasync listAsOwner(\n\t\tsignerId: string,\n\t\tparams: ISignerDocumentListParams = {},\n\t): Promise<IDocumentListResponse> {\n\t\treturn this.listDocuments(signerId, { params: cleanParams({ ...params }) });\n\t}\n\n\t/** `GET /signers/{signer_id}/documents/search?search=…&signer-access-code=…` */\n\tasync search(\n\t\tsignerId: string,\n\t\tsearch: string,\n\t\tsignerAccessCode: string,\n\t): Promise<IDocumentListResponse> {\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\treturn this.searchDocuments(signerId, signerAccessConfig(code, { search }));\n\t}\n\n\t/**\n\t * `GET /signers/{signer_id}/documents/search?search=…` with the client's owner\n\t * credentials instead of a signer access code. The signer must belong to that\n\t * workspace.\n\t */\n\tasync searchAsOwner(signerId: string, search: string): Promise<IDocumentListResponse> {\n\t\treturn this.searchDocuments(signerId, { params: cleanParams({ search }) });\n\t}\n\n\tprivate listDocuments(signerId: string, config: Parameters<typeof this.http.get>[1]) {\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\treturn this.callList<IDocumentListItem>('Failed to list signer documents', () =>\n\t\t\tthis.http.get(`/signers/${sid}/documents`, config),\n\t\t);\n\t}\n\n\tprivate searchDocuments(signerId: string, config: Parameters<typeof this.http.get>[1]) {\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\treturn this.callList<IDocumentListItem>('Failed to search signer documents', () =>\n\t\t\tthis.http.get(`/signers/${sid}/documents/search`, config),\n\t\t);\n\t}\n\n\t/**\n\t * Public `GET /signers/{signer_id}/documents/{document_id}/download/{artifact}`.\n\t * When an access code is supplied, the SDK first verifies that it belongs to\n\t * the requested signer for callers that want that additional check.\n\t */\n\tasync download(\n\t\tsignerId: string,\n\t\tdocumentId: string,\n\t\tartifactName: DocumentArtifactName,\n\t\tsignerAccessCode?: string,\n\t): Promise<Buffer> {\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\tconst did = this.requireId(documentId, 'Document ID');\n\t\tconst artifact = requireDocumentArtifactName(artifactName);\n\t\tlet config = publicRequestConfig();\n\t\tif (signerAccessCode !== undefined) {\n\t\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\t\tconst signer = await this.self(code);\n\t\t\tif (signer.id !== sid) {\n\t\t\t\tthrow new ValidationError('Signer access code does not match the signer ID');\n\t\t\t}\n\t\t\tconfig = signerAccessConfig(code);\n\t\t}\n\t\treturn this.callBinary('Failed to download signer document', () =>\n\t\t\tthis.http.get<ArrayBuffer>(`/signers/${sid}/documents/${did}/download/${artifact}`, {\n\t\t\t\t...config,\n\t\t\t\tresponseType: 'arraybuffer',\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** `PUT /signers/documents/sign-multiple?signer-access-code=…` */\n\tasync signMultiple(documentIds: string[], signerAccessCode: string): Promise<unknown[]> {\n\t\tif (!Array.isArray(documentIds) || documentIds.length === 0) {\n\t\t\tthrow new ValidationError('documentIds must be a non-empty array');\n\t\t}\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\treturn this.call('Failed to sign multiple documents', () =>\n\t\t\tthis.http.put(\n\t\t\t\t'/signers/documents/sign-multiple',\n\t\t\t\t{ document_ids: documentIds },\n\t\t\t\tsignerAccessConfig(code),\n\t\t\t),\n\t\t);\n\t}\n\n\t/** `PUT /signers/documents/decline-multiple?signer-access-code=…` */\n\tasync declineMultiple(\n\t\tdocumentIds: string[],\n\t\tdeclineReason: string,\n\t\tsignerAccessCode: string,\n\t): Promise<unknown[]> {\n\t\tif (!Array.isArray(documentIds) || documentIds.length === 0) {\n\t\t\tthrow new ValidationError('documentIds must be a non-empty array');\n\t\t}\n\t\tvalidateDeclineReason(declineReason);\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\treturn this.call('Failed to decline multiple documents', () =>\n\t\t\tthis.http.put(\n\t\t\t\t'/signers/documents/decline-multiple',\n\t\t\t\t{ document_ids: documentIds, decline_reason: declineReason },\n\t\t\t\tsignerAccessConfig(code),\n\t\t\t),\n\t\t);\n\t}\n\n\t/** `GET /signers/self?signer-access-code=…` — fetch the signer's own profile. */\n\tasync self(signerAccessCode: string): Promise<ISignerSelf> {\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\treturn this.call('Failed to fetch signer profile', () =>\n\t\t\tthis.http.get('/signers/self', signerAccessConfig(code)),\n\t\t);\n\t}\n\n\t/** `GET /signers/identity-verification` — session status, capture URL and restart eligibility. */\n\tasync getIdentityVerification(signerAccessCode: string): Promise<IIdentityVerificationState> {\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\treturn this.call('Failed to fetch identity verification', () =>\n\t\t\tthis.http.get('/signers/identity-verification', signerAccessConfig(code)),\n\t\t);\n\t}\n\n\t/** `POST /signers/identity-verification` — open a hosted session after the signer's explicit consent. */\n\tasync startIdentityVerification(\n\t\tsignerAccessCode: string,\n\t\tpayload: IStartIdentityVerificationPayload,\n\t): Promise<IIdentityVerificationSession> {\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\tif (payload?.consent !== true) {\n\t\t\tthrow new ValidationError('Explicit biometric-processing consent is required');\n\t\t}\n\t\treturn this.call('Failed to start identity verification', () =>\n\t\t\tthis.http.post('/signers/identity-verification', { consent: true }, signerAccessConfig(code)),\n\t\t);\n\t}\n\n\t/**\n\t * `PUT /signers/accept-terms?signer-access-code=…` — accept the platform\n\t * terms as the signer.\n\t *\n\t * The access code travels as the `signer-access-code` query parameter, like\n\t * every other signer-side endpoint (the spec under-documents this one, but\n\t * the query-param convention is uniform across the Signing API).\n\t */\n\tasync acceptTerms(signerAccessCode: string): Promise<ISignerTermsAcceptance | IStatusResponse> {\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\treturn this.call('Failed to accept terms', () =>\n\t\t\tthis.http.put('/signers/accept-terms', undefined, signerAccessConfig(code)),\n\t\t);\n\t}\n\n\t/** `POST /verify` — verify an email or WhatsApp OTP for a signer. */\n\tasync verifyCode(payload: IVerifySignerCodePayload): Promise<IEmptyResult | IStatusResponse> {\n\t\tconst code = this.requireId(payload.signerAccessCode, 'signer-access-code');\n\t\tconst otp = this.requireId(payload.verificationCode, 'verification-code');\n\t\treturn this.call('Failed to verify signer code', () =>\n\t\t\tthis.http.post('/verify', { 'verification-code': otp }, signerAccessConfig(code)),\n\t\t);\n\t}\n\n\t/** Compatibility alias for {@link verifyCode}; accepts email and WhatsApp OTPs. */\n\tasync verifyEmail(payload: IVerifySignerCodePayload): Promise<IEmptyResult | IStatusResponse> {\n\t\treturn this.verifyCode(payload);\n\t}\n\n\t/**\n\t * `POST /signers/certificate/start` — start an ICP-Brasil A1/A3 signature.\n\t * Returns `{ token }` for the signer's Web PKI client. This production route\n\t * is used by Assinafy's signing frontend but is absent from OpenAPI paths.\n\t */\n\tasync startCertificate(signerAccessCode: string): Promise<ICertificateStartResponse> {\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\treturn this.call('Failed to start certificate signature', () =>\n\t\t\tthis.http.post(\n\t\t\t\t'/signers/certificate/start',\n\t\t\t\t{ 'signer-access-code': code },\n\t\t\t\tsignerAccessConfig(code),\n\t\t\t),\n\t\t);\n\t}\n\n\t/**\n\t * `POST /signers/certificate/complete` — finish an ICP-Brasil A1/A3 signature.\n\t * Pass the same token returned by {@link startCertificate}, after Web PKI\n\t * successfully signs it. Returns `{ signerName }`; private keys stay local.\n\t * This production route is absent from OpenAPI paths.\n\t */\n\tasync completeCertificate(\n\t\tsignerAccessCode: string,\n\t\ttoken: string,\n\t): Promise<ICertificateCompleteResponse> {\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\tif (typeof token !== 'string' || !token.trim()) {\n\t\t\tthrow new ValidationError('Certificate token is required');\n\t\t}\n\t\treturn this.call('Failed to complete certificate signature', () =>\n\t\t\tthis.http.post(\n\t\t\t\t'/signers/certificate/complete',\n\t\t\t\t{ 'signer-access-code': code, token },\n\t\t\t\tsignerAccessConfig(code),\n\t\t\t),\n\t\t);\n\t}\n\n\t/**\n\t * `PUT /documents/{documentId}/signers/confirm-data?signer-access-code=…`\n\t *\n\t * The documented body fields are `full_name`, `email` and `government_id`;\n\t * `whatsapp_phone_number` / `has_accepted_terms` are also accepted for the\n\t * WhatsApp confirmation flow.\n\t */\n\tasync confirmData(\n\t\tdocumentId: string,\n\t\tsignerAccessCode: string,\n\t\tpayload: {\n\t\t\tfull_name?: string;\n\t\t\temail?: string;\n\t\t\tgovernment_id?: string;\n\t\t\twhatsapp_phone_number?: string;\n\t\t\thas_accepted_terms?: boolean;\n\t\t},\n\t): Promise<ISigner | IEmptyResult> {\n\t\tconst did = this.requireId(documentId, 'Document ID');\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\t// Build the JSON body explicitly (only defined fields). Don't route it\n\t\t// through cleanParams — that's a query-string helper and would rename a\n\t\t// body key like `per_page`.\n\t\tconst body: Record<string, unknown> = {};\n\t\tfor (const [key, value] of Object.entries(payload)) {\n\t\t\tif (value !== undefined) body[key] = value;\n\t\t}\n\t\tawait this.requireDocumentAccess(did, code);\n\t\treturn this.call('Failed to confirm signer data', () =>\n\t\t\tthis.http.put(`/documents/${did}/signers/confirm-data`, body, signerAccessConfig(code)),\n\t\t);\n\t}\n\n\t/**\n\t * `POST /signature?signer-access-code=…&type=…` — upload the signer's\n\t * signature or initial image. `imageType` defaults to `signature`.\n\t */\n\tasync uploadSignature(\n\t\tsignerAccessCode: string,\n\t\timage: Buffer,\n\t\toptions: { imageType?: 'signature' | 'initial'; contentType?: string; reuse?: boolean } = {},\n\t): Promise<IEmptyResult | IStatusResponse> {\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\tconst imageType = requireSignerImageType(options.imageType ?? 'signature');\n\t\tif (!Buffer.isBuffer(image) || image.byteLength === 0) {\n\t\t\tthrow new ValidationError('image buffer is required');\n\t\t}\n\t\treturn this.call('Failed to upload signer signature', () =>\n\t\t\tthis.http.post(\n\t\t\t\t'/signature',\n\t\t\t\timage,\n\t\t\t\tsignerAccessConfig(\n\t\t\t\t\tcode,\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: imageType,\n\t\t\t\t\t\t// Documented query flag controlling the signer's is_signature_reusable state.\n\t\t\t\t\t\treuse: options.reuse,\n\t\t\t\t\t},\n\t\t\t\t\t{ 'Content-Type': options.contentType ?? 'image/png' },\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\t}\n\n\t/** `GET /signature/{type}?signer-access-code=…` — download the signer's signature/initial. */\n\tasync downloadSignature(\n\t\tsignerAccessCode: string,\n\t\timageType: 'signature' | 'initial' = 'signature',\n\t): Promise<Buffer> {\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\tconst type = requireSignerImageType(imageType);\n\t\treturn this.callBinary('Failed to download signer signature', () =>\n\t\t\tthis.http.get<ArrayBuffer>(`/signature/${type}`, {\n\t\t\t\t...signerAccessConfig(code),\n\t\t\t\tresponseType: 'arraybuffer',\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** `GET /sign?signer-access-code=…` — fetch the assignment as the signer sees it. */\n\tasync getAssignment(\n\t\tsignerAccessCode: string,\n\t\thasAcceptedTerms?: boolean,\n\t): Promise<IDocumentDetailsResponse> {\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\treturn this.call('Failed to fetch signer assignment', () =>\n\t\t\tthis.http.get('/sign', signerAccessConfig(code, { has_accepted_terms: hasAcceptedTerms })),\n\t\t);\n\t}\n\n\t/**\n\t * `POST /documents/{documentId}/assignments/{assignmentId}?signer-access-code=…` — sign.\n\t * Virtual assignments accept `[]` after the signer confirms their data.\n\t */\n\tasync sign(\n\t\tdocumentId: string,\n\t\tassignmentId: string,\n\t\tsignerAccessCode: string,\n\t\tentries: ISignFieldEntry[],\n\t): Promise<Record<string, unknown>> {\n\t\tconst did = this.requireId(documentId, 'Document ID');\n\t\tconst aid = this.requireId(assignmentId, 'Assignment ID');\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\tif (!Array.isArray(entries)) {\n\t\t\tthrow new ValidationError('entries must be an array');\n\t\t}\n\t\tconst document = await this.requireDocumentAccess(did, code, aid);\n\t\tif (document.assignment?.method === 'collect' && entries.length === 0) {\n\t\t\tthrow new ValidationError('entries must be non-empty for collect assignments');\n\t\t}\n\t\treturn this.call('Failed to sign document', () =>\n\t\t\tthis.http.post(`/documents/${did}/assignments/${aid}`, entries, signerAccessConfig(code)),\n\t\t);\n\t}\n\n\t/**\n\t * `PUT /documents/{documentId}/assignments/{assignmentId}/reject?signer-access-code=…`\n\t * — signer-side decline using the access code from the signing link.\n\t */\n\tasync decline(\n\t\tdocumentId: string,\n\t\tassignmentId: string,\n\t\tsignerAccessCode: string,\n\t\tdeclineReason: string,\n\t): Promise<unknown[]> {\n\t\tconst did = this.requireId(documentId, 'Document ID');\n\t\tconst aid = this.requireId(assignmentId, 'Assignment ID');\n\t\tconst code = this.requireId(signerAccessCode, 'signer-access-code');\n\t\tvalidateDeclineReason(declineReason);\n\t\tawait this.requireDocumentAccess(did, code, aid);\n\t\treturn this.call('Failed to decline assignment', () =>\n\t\t\tthis.http.put(\n\t\t\t\t`/documents/${did}/assignments/${aid}/reject`,\n\t\t\t\t{ decline_reason: declineReason },\n\t\t\t\tsignerAccessConfig(code),\n\t\t\t),\n\t\t);\n\t}\n\n\tprivate async requireDocumentAccess(\n\t\tdocumentId: string,\n\t\tsignerAccessCode: string,\n\t\tassignmentId?: string,\n\t): Promise<IDocumentDetailsResponse> {\n\t\tconst document = await this.getAssignment(signerAccessCode);\n\t\tif (\n\t\t\tdocument.id !== documentId ||\n\t\t\t(assignmentId !== undefined && document.assignment?.id !== assignmentId)\n\t\t) {\n\t\t\tthrow new ValidationError('Signer access code does not match the document or assignment');\n\t\t}\n\t\treturn document;\n\t}\n}\n\nfunction validateDeclineReason(value: string): void {\n\tif (typeof value !== 'string' || !value.trim()) {\n\t\tthrow new ValidationError('declineReason is required');\n\t}\n\tif ([...value].length > 2000) {\n\t\tthrow new ValidationError('declineReason must contain at most 2000 characters');\n\t}\n}\n","import { ApiError, ValidationError } from '../errors.js';\nimport type {\n\tICreateSignerPayload,\n\tICreateSignerResponse,\n\tIEmptyResult,\n\tISigner,\n\tISignerListParams,\n\tISignerListResponse,\n\tIUpdateSignerPayload,\n} from '../types.js';\nimport { cleanParams, requireEmail, requireSort, stripEmpty } from '../utils.js';\nimport { BaseResource } from './base.js';\n\n/** Validate the locally knowable fields before creating a signer. */\nexport function validateCreateSignerPayload(payload: ICreateSignerPayload): void {\n\tif (!payload.full_name?.trim()) throw new ValidationError('Signer full name is required');\n\tif (payload.email !== undefined) requireEmail(payload.email);\n}\n\nexport class SignerResource extends BaseResource {\n\t/**\n\t * Create a signer in the workspace.\n\t *\n\t * Only `full_name` is required. When an `email` is supplied the call is\n\t * idempotent by email: an existing signer with that address is reused instead\n\t * of duplicated.\n\t */\n\tasync create(payload: ICreateSignerPayload, accountId?: string): Promise<ICreateSignerResponse> {\n\t\tconst id = this.accountId(accountId);\n\t\tvalidateCreateSignerPayload(payload);\n\n\t\tif (payload.email) {\n\t\t\tconst existing = await this.findByEmail(payload.email, id);\n\t\t\tif (existing) {\n\t\t\t\tthis.logger.info('Using existing signer', { signerId: existing.id });\n\t\t\t\treturn existing;\n\t\t\t}\n\t\t}\n\n\t\tthis.logger.info('Creating signer', { hasEmail: Boolean(payload.email) });\n\t\ttry {\n\t\t\treturn await this.call('Failed to create signer', () =>\n\t\t\t\tthis.http.post(`/accounts/${id}/signers`, normaliseSignerPayload(payload)),\n\t\t\t);\n\t\t} catch (err) {\n\t\t\tif (err instanceof ApiError && err.statusCode === 409 && payload.email) {\n\t\t\t\tconst duplicate = await this.findByEmail(payload.email, id);\n\t\t\t\tif (duplicate) {\n\t\t\t\t\tthis.logger.info('Signer already exists, using existing signer', {\n\t\t\t\t\t\tsignerId: duplicate.id,\n\t\t\t\t\t});\n\t\t\t\t\treturn duplicate;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\t/** Get a signer by ID. */\n\tasync get(signerId: string, accountId?: string): Promise<ISigner> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\treturn this.call('Failed to fetch signer', () =>\n\t\t\tthis.http.get(`/accounts/${id}/signers/${sid}`),\n\t\t);\n\t}\n\n\t/** List signers (`sort` accepts the live-verified `full_name` / `-full_name`). */\n\tasync list(params: ISignerListParams = {}, accountId?: string): Promise<ISignerListResponse> {\n\t\tconst id = this.accountId(accountId);\n\t\trequireSort(params.sort, ['full_name', '-full_name']);\n\t\treturn this.callList<ISigner>('Failed to list signers', () =>\n\t\t\tthis.http.get(`/accounts/${id}/signers`, {\n\t\t\t\tparams: cleanParams(params as unknown as Record<string, unknown>),\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** Update a signer. Fails if the signer has active assignments. */\n\tasync update(\n\t\tsignerId: string,\n\t\tpayload: IUpdateSignerPayload,\n\t\taccountId?: string,\n\t): Promise<ICreateSignerResponse> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\tif (payload.full_name !== undefined && !payload.full_name.trim()) {\n\t\t\tthrow new ValidationError('Signer full name cannot be blank');\n\t\t}\n\t\tif (payload.email !== undefined) requireEmail(payload.email);\n\t\treturn this.call('Failed to update signer', () =>\n\t\t\tthis.http.put(`/accounts/${id}/signers/${sid}`, normaliseSignerPayload(payload, true)),\n\t\t);\n\t}\n\n\t/** Delete a signer. */\n\tasync delete(signerId: string, accountId?: string): Promise<IEmptyResult> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst sid = this.requireId(signerId, 'Signer ID');\n\t\treturn this.call('Failed to delete signer', () =>\n\t\t\tthis.http.delete(`/accounts/${id}/signers/${sid}`),\n\t\t);\n\t}\n\n\t/** Find a signer by email via the API's `search` parameter. Returns `null` if none match. */\n\tasync findByEmail(email: string, accountId?: string): Promise<ISigner | null> {\n\t\trequireEmail(email);\n\t\ttry {\n\t\t\tconst lower = email.toLowerCase();\n\t\t\tfor (let page = 1; page <= MAX_SEARCH_PAGES; page++) {\n\t\t\t\tconst { data, meta } = await this.list({ search: email, per_page: 100, page }, accountId);\n\t\t\t\tconst match = data.find((s) => (s.email ?? '').toLowerCase() === lower);\n\t\t\t\tif (match) return match;\n\t\t\t\tif (!data.length) return null;\n\t\t\t\tif (meta?.last_page !== undefined) {\n\t\t\t\t\tif (page >= meta.last_page) return null;\n\t\t\t\t} else if (data.length < 100) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow new ValidationError('Signer email search exceeded the maximum page count');\n\t\t} catch (err) {\n\t\t\tif (err instanceof ApiError && err.statusCode === 404) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t}\n}\n\nconst MAX_SEARCH_PAGES = 100;\n\nfunction normaliseSignerPayload(\n\tpayload: ICreateSignerPayload | IUpdateSignerPayload,\n\tuseGovernmentId = false,\n): Record<string, unknown> {\n\tconst normalised: Record<string, unknown> = {\n\t\tfull_name: payload.full_name,\n\t\temail: payload.email,\n\t\twhatsapp_phone_number: payload.whatsapp_phone_number ?? payload.phone,\n\t};\n\n\tif (payload.government_id !== undefined) {\n\t\tnormalised.government_id = payload.government_id;\n\t} else if (payload.cpf) {\n\t\t// Strip formatting; only forward a CPF when digits actually remain so a\n\t\t// value like \"---\" doesn't get sent as an empty string.\n\t\tconst digits = payload.cpf.replace(/\\D/g, '');\n\t\tif (digits) normalised[useGovernmentId ? 'government_id' : 'cpf'] = digits;\n\t}\n\n\tif ('metadata' in payload && payload.metadata !== undefined) {\n\t\tnormalised.metadata = payload.metadata;\n\t}\n\n\treturn stripEmpty(normalised);\n}\n","import { ValidationError } from '../errors.js';\nimport type { ICreateTagPayload, IDeleteTagResponse, ITag, IUpdateTagPayload } from '../types.js';\nimport { cleanParams, stripEmpty } from '../utils.js';\nimport { BaseResource } from './base.js';\n\n/**\n * Workspace-scoped tags used to label documents and templates.\n *\n * Covers the full Tag section of the API docs:\n * - `GET /accounts/{id}/tags` → {@link list}\n * - `POST /accounts/{id}/tags` → {@link create}\n * - `PUT /accounts/{id}/tags/{tag_id}` → {@link update}\n * - `DELETE /accounts/{id}/tags/{tag_id}` → {@link delete}\n *\n * Document-level attach/detach lives on {@link DocumentResource} (`listTags`,\n * `replaceTags`, `addTags`, `detachTag`).\n */\nexport class TagResource extends BaseResource {\n\t/** List the workspace's tags, ordered alphabetically. Optional case-insensitive `search`. */\n\tasync list(params: { search?: string } = {}, accountId?: string): Promise<ITag[]> {\n\t\tconst id = this.accountId(accountId);\n\t\treturn this.call('Failed to list tags', () =>\n\t\t\tthis.http.get(`/accounts/${id}/tags`, {\n\t\t\t\tparams: cleanParams(params as Record<string, unknown>),\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** Create a tag. Throws `ApiError` (409) if the name already exists (case-insensitive). */\n\tasync create(payload: ICreateTagPayload, accountId?: string): Promise<ITag> {\n\t\tif (!payload.name) throw new ValidationError('Tag name is required');\n\t\tconst id = this.accountId(accountId);\n\t\treturn this.call('Failed to create tag', () =>\n\t\t\tthis.http.post(`/accounts/${id}/tags`, stripEmpty({ ...payload })),\n\t\t);\n\t}\n\n\t/**\n\t * Update a tag's name and/or color. Omit a field to leave it unchanged;\n\t * pass `color: null` to clear the color. Throws `ApiError` (409) if another\n\t * tag already uses the new name.\n\t */\n\tasync update(tagId: string, payload: IUpdateTagPayload, accountId?: string): Promise<ITag> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst tid = this.requireId(tagId, 'Tag ID');\n\t\t// Don't strip `color: null` — null is the documented \"clear color\" signal.\n\t\tconst body: Record<string, unknown> = {};\n\t\tif (payload.name !== undefined) body.name = payload.name;\n\t\tif ('color' in payload) body.color = payload.color;\n\t\treturn this.call('Failed to update tag', () =>\n\t\t\tthis.http.put(`/accounts/${id}/tags/${tid}`, body),\n\t\t);\n\t}\n\n\t/**\n\t * Delete a tag. By default fails with `ApiError` (409) if the tag is still\n\t * attached to anything; pass `{ force: true }` to detach everywhere first.\n\t */\n\tasync delete(\n\t\ttagId: string,\n\t\toptions: { force?: boolean; accountId?: string } = {},\n\t): Promise<IDeleteTagResponse> {\n\t\tconst id = this.accountId(options.accountId);\n\t\tconst tid = this.requireId(tagId, 'Tag ID');\n\t\tconst params = options.force ? { force: 'true' } : undefined;\n\t\treturn this.call('Failed to delete tag', () =>\n\t\t\tthis.http.delete(`/accounts/${id}/tags/${tid}`, { params }),\n\t\t);\n\t}\n}\n","import type {\n\tITemplateDetailsResponse,\n\tITemplateListItem,\n\tITemplateListParams,\n\tITemplateListResponse,\n} from '../types.js';\nimport { cleanParams, requireSort } from '../utils.js';\nimport { BaseResource } from './base.js';\n\nexport class TemplateResource extends BaseResource {\n\t/** List templates for the workspace. */\n\tasync list(params: ITemplateListParams = {}, accountId?: string): Promise<ITemplateListResponse> {\n\t\tconst id = this.accountId(accountId);\n\t\trequireSort(params.sort, ['name', '-name']);\n\t\treturn this.callList<ITemplateListItem>('Failed to list templates', () =>\n\t\t\tthis.http.get(`/accounts/${id}/templates`, {\n\t\t\t\tparams: cleanParams(params as unknown as Record<string, unknown>),\n\t\t\t}),\n\t\t);\n\t}\n\n\t/**\n\t * Get a template by ID.\n\t *\n\t * Note: the swagger only documents the list endpoint; this single-resource\n\t * `GET /accounts/{id}/templates/{id}` is exposed by the platform and used\n\t * by the official PHP SDK.\n\t */\n\tasync get(templateId: string, accountId?: string): Promise<ITemplateDetailsResponse> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst tmplId = this.requireId(templateId, 'Template ID');\n\t\treturn this.call('Failed to fetch template', () =>\n\t\t\tthis.http.get(`/accounts/${id}/templates/${tmplId}`),\n\t\t);\n\t}\n\n\t/**\n\t * `GET /accounts/{id}/templates/{template_id}/pages/{page_id}/download` —\n\t * download a template page as a JPEG (used by template editors to render\n\t * thumbnails on the client).\n\t */\n\tasync downloadPage(templateId: string, pageId: string, accountId?: string): Promise<Buffer> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst tmplId = this.requireId(templateId, 'Template ID');\n\t\tconst pid = this.requireId(pageId, 'Page ID');\n\t\treturn this.callBinary('Failed to download template page', () =>\n\t\t\tthis.http.get<ArrayBuffer>(`/accounts/${id}/templates/${tmplId}/pages/${pid}/download`, {\n\t\t\t\tresponseType: 'arraybuffer',\n\t\t\t}),\n\t\t);\n\t}\n}\n","/** Document lifecycle states emitted by the API. */\nexport type DocumentStatus =\n\t| 'uploading'\n\t| 'uploaded'\n\t| 'metadata_processing'\n\t| 'metadata_ready'\n\t| 'pending_signature'\n\t| 'pending_identity_review'\n\t| 'expired'\n\t| 'certificating'\n\t| 'certificated'\n\t| 'rejected_by_signer'\n\t| 'rejected_by_user'\n\t| 'failed';\n\n/** Artifact names available for document download. */\nexport type DocumentArtifactName =\n\t| 'original'\n\t| 'certificated'\n\t| 'certificate-page'\n\t| 'pades'\n\t| 'bundle';\n\n/** Assignment methods supported by the API. */\nexport type AssignmentMethod = 'virtual' | 'collect';\n\n/** Verification methods accepted by assignment signer entries. */\nexport type AssignmentVerificationMethod =\n\t| 'Email'\n\t| 'Whatsapp'\n\t| 'DigitalCertificate'\n\t| 'IdDocumentFaceMatchBasic'\n\t| (string & {});\n\n/** Notification methods accepted by assignment signer entries. */\nexport type AssignmentNotificationMethod = 'Email' | 'Whatsapp' | (string & {});\n\n/** OAuth provider currently accepted by the Assinafy authentication API. */\nexport type SocialLoginProvider = 'google';\n\n/** Minimal logger contract (compatible with console, pino, winston, etc.). */\nexport interface Logger {\n\tdebug: (message: string, context?: Record<string, unknown>) => void;\n\tinfo: (message: string, context?: Record<string, unknown>) => void;\n\twarn: (message: string, context?: Record<string, unknown>) => void;\n\terror: (message: string, context?: Record<string, unknown>) => void;\n}\n\n/** Client configuration options. */\nexport interface AssinafyClientOptions {\n\t/** Assinafy API key. Preferred authentication method (sends `X-Api-Key` header). */\n\tapiKey?: string;\n\t/**\n\t * OAuth access token or user JWT. Sends `Authorization: Bearer <token>`.\n\t * `apiKey` takes precedence when both options are supplied.\n\t */\n\ttoken?: string;\n\t/**\n\t * Build a client without credentials for public, OAuth bootstrap, or signer-code calls.\n\t */\n\tallowUnauthenticated?: boolean;\n\t/** Default account (workspace) ID applied to account-scoped endpoints. */\n\taccountId?: string;\n\t/** Override the API base URL. Defaults to https://api.assinafy.com.br/v1. */\n\tbaseUrl?: string;\n\t/**\n\t * Allow a plaintext `http://` base URL. Restricted to loopback hosts\n\t * (`localhost`, `127.0.0.0/8`, `[::1]`) so the API key can never leave the\n\t * machine in cleartext; any other host is rejected even with this enabled.\n\t */\n\tallowInsecureHttp?: boolean;\n\t/**\n\t * Default `whsec_` endpoint signing secret for {@link WebhookVerifier}\n\t * (`client.webhookVerifier`). Each endpoint has its own secret; construct a\n\t * separate verifier per endpoint when several are signed.\n\t */\n\twebhookSecret?: string;\n\t/** Request timeout in milliseconds. Defaults to 30_000. */\n\ttimeout?: number;\n\t/** Optional logger. Defaults to a no-op logger. */\n\tlogger?: Logger;\n}\n\n/**\n * Payload for creating a signer.\n *\n * The official API requires only `full_name`; email and WhatsApp are optional\n * delivery channels.\n */\nexport interface ICreateSignerPayload {\n\tfull_name: string;\n\temail?: string;\n\twhatsapp_phone_number?: string;\n\t/** PHP SDK compatibility alias for `whatsapp_phone_number`. */\n\tphone?: string;\n\t/** CPF or numeric/alphanumeric CNPJ; forwarded unchanged for server normalization. */\n\tgovernment_id?: string;\n\t/** Compatibility extension for a Brazilian CPF; non-digits are stripped. */\n\tcpf?: string;\n\t/** Compatibility extension for integration-defined signer metadata. */\n\tmetadata?: Record<string, unknown>;\n}\n\n/** Payload for updating a signer. */\nexport interface IUpdateSignerPayload {\n\tfull_name?: string;\n\temail?: string;\n\twhatsapp_phone_number?: string;\n\t/** PHP SDK compatibility alias for `whatsapp_phone_number`. */\n\tphone?: string;\n\t/** CPF or numeric/alphanumeric CNPJ; forwarded unchanged for server normalization. */\n\tgovernment_id?: string;\n\t/** Backwards-compatible alias for `government_id`. */\n\tcpf?: string;\n}\n\n/** Signer object as returned by the API. */\nexport interface ISigner {\n\tresource?: string;\n\tid: string;\n\tfull_name: string;\n\temail: string | null;\n\twhatsapp_phone_number?: string | null;\n\tgovernment_id?: string | null;\n\tcpf?: string | null;\n\thas_accepted_terms?: boolean;\n\t/** Only returned by `GET /signers/self`. */\n\thas_signature?: boolean;\n\t/** Only returned by `GET /signers/self`. */\n\thas_initial?: boolean;\n\tmetadata?: Record<string, unknown>;\n}\n\n/** Signer profile returned by `GET /signers/self`. */\nexport interface ISignerSelf extends ISigner {\n\thas_signature: boolean;\n\thas_initial: boolean;\n\tis_signature_reusable: boolean;\n\tverification_method?: AssignmentVerificationMethod;\n}\n\n/** Identity-document provider session states. */\nexport type IdentityVerificationStatus =\n\t| 'Pending'\n\t| 'InReview'\n\t| 'Approved'\n\t| 'Declined'\n\t| 'Expired'\n\t| 'Abandoned';\n\n/** Signer-facing state from `GET /signers/identity-verification`. */\nexport interface IIdentityVerificationState {\n\tcan_start: boolean;\n\tstatus: IdentityVerificationStatus | null;\n\t/** Private capture link; preserve its fragment and never log it. */\n\turl: string | null;\n\texpires_at: string | null;\n\tcompleted_at: string | null;\n}\n\n/** Explicit signer consent required before opening a biometric provider session. */\nexport interface IStartIdentityVerificationPayload {\n\tconsent: true;\n}\n\n/** Hosted session from `POST /signers/identity-verification`. */\nexport interface IIdentityVerificationSession {\n\tid: string;\n\t/** Private capture link; open as-is, including any fragment. */\n\turl: string;\n\texpires_at: string | null;\n}\n\n/** Evidence names available only while an identity review is open. */\nexport type IdentityVerificationImageName =\n\t| 'document_front'\n\t| 'document_back'\n\t| 'document_pdf'\n\t| 'face';\n\n/** Account review of an `IdDocumentFaceMatchBasic` verification. */\nexport interface ISignerIdentityReview {\n\tid: string;\n\tstatus: IdentityVerificationStatus;\n\tprovider: 'AssinafyVerify';\n\tverification_method: 'IdDocumentFaceMatchBasic';\n\treason_codes: Array<{ code: string; description: string }>;\n\tevidence_available: boolean;\n\texpected: { name: string | null; cpf: string | null } | null;\n\tdocument: { type: string | null; name: string | null; cpf: string | null } | null;\n\tmatches: { cpf: boolean | null; name: number | null; birth_date: boolean | null } | null;\n\tchecks: Array<{ name: string; result: string; score: number | null; reasons: string[] }>;\n\timages: IdentityVerificationImageName[];\n\truleset_version: string | null;\n\tevidence_sha256: string | null;\n\treviewed_by: { id: string; name: string } | null;\n\treviewed_at: string | null;\n\treview_note: string | null;\n\tcompleted_at: string | null;\n}\n\n/** Approval releases certification; rejection cancels the document and notifies its recipients. */\nexport interface IIdentityReviewPayload {\n\tdecision: 'Approved' | 'Rejected';\n\t/** At most 2,000 Unicode characters; recorded privately and sent to the provider. */\n\tnote?: string | null;\n}\n\n/** Signer data returned after accepting the platform terms. */\nexport interface ISignerTermsAcceptance {\n\tfull_name: string;\n\temail: string | null;\n\thas_accepted_terms: boolean;\n}\n\n/** Email or WhatsApp OTP and the access code from the same verification message. */\nexport interface IVerifySignerCodePayload {\n\tsignerAccessCode: string;\n\tverificationCode: string;\n}\n\n/** Web PKI operation token returned when starting an ICP-Brasil A1/A3 signature. */\nexport interface ICertificateStartResponse {\n\ttoken: string;\n}\n\n/** Certificate identity returned after the Web PKI operation completes. */\nexport interface ICertificateCompleteResponse {\n\tsignerName: string;\n}\n\nexport type ICreateSignerResponse = ISigner;\n\n/** Pagination metadata extracted from `X-Pagination-*` response headers. */\nexport interface PaginationMeta {\n\tcurrent_page?: number;\n\tlast_page?: number;\n\tper_page?: number;\n\ttotal?: number;\n}\n\n/** Shape returned by every paginated list call in the SDK. */\nexport interface PaginatedResult<T> {\n\tdata: T[];\n\tmeta?: PaginationMeta;\n}\n\n/** Direct status body used by successful API operations without a `data` member. */\nexport interface IStatusResponse {\n\tstatus: number;\n\tmessage: string;\n}\n\n/** Unwrapped `data: []` returned by successful operations without result data. */\nexport type IEmptyResult = unknown[];\n\n/** @deprecated use {@link PaginatedResult} — retained for existing type imports. */\nexport type IPaginatedResponse<T> = PaginatedResult<T>;\n\nexport type ISignerListResponse = PaginatedResult<ISigner>;\n\n/** Signer reference accepted by the assignment endpoints. */\nexport type SignerReference =\n\t| string\n\t| {\n\t\t\tid?: string;\n\t\t\tsigner_id?: string;\n\t\t\tverification_method?: AssignmentVerificationMethod;\n\t\t\t/** Production defaults an empty array to Email; it does not disable invitations. */\n\t\t\tnotification_methods?: AssignmentNotificationMethod[];\n\t\t\t/** Integer signing-order value forwarded to the assignment API. */\n\t\t\tstep?: number;\n\t };\n\n/** Payload for creating an assignment. */\nexport interface ICreateAssignmentPayload {\n\tmethod?: AssignmentMethod;\n\t/**\n\t * List of signers. Each entry may be a signer id string, or an object with\n\t * `id` / `signer_id`. For cost estimation, entries may omit the ID and\n\t * specify only `verification_method` / `notification_methods`.\n\t *\n\t * The SDK normalises them to the docs-sanctioned `signers: [{ ... }]`\n\t * shape before sending.\n\t */\n\tsigners?: SignerReference[];\n\t/** Legacy field still accepted by the API docs and used by the PHP SDK. */\n\tsigner_ids?: string[];\n\t/** Camel-case legacy alias used by the quick-start docs. */\n\tsignerIds?: string[];\n\tmessage?: string;\n\texpires_at?: string;\n\tcopy_receivers?: string[];\n\t/** Field placement entries. Required when `method` is `collect`. */\n\tentries?: ICollectAssignmentEntry[];\n}\n\n/**\n * A field placement rectangle on a document page. Geometry values are pixels\n * in Assinafy's 150-DPI page image, measured from the upper-left corner.\n */\nexport interface IDisplaySettings {\n\tleft: number;\n\ttop: number;\n\twidth: number;\n\theight: number;\n\tfontSize: number;\n\tfontFamily?: string;\n\tbackgroundColor?: string;\n}\n\n/** One page's field placements, used by `collect`-method assignments. */\nexport interface ICollectAssignmentEntry {\n\tpage_id: string;\n\tfields: Array<{\n\t\tsigner_id: string;\n\t\tfield_id: string;\n\t\tdisplay_settings?: IDisplaySettings;\n\t}>;\n}\n\n/** Direct signing URL generated for one signer (inside `assignment.signing_urls`). */\nexport interface ISigningUrl {\n\tsigner_id: string;\n\turl: string;\n}\n\n/**\n * One tracked notification-delivery record, returned inside\n * `assignment.signers[].notification_history` (account-owner contexts only).\n */\nexport interface IAssignmentSignerNotification {\n\tevent: string;\n\tstatus: string;\n\terror_code?: string | null;\n\terror_message?: string | null;\n\tsent_at?: string | null;\n\tfailed_at?: string | null;\n}\n\n/**\n * Signer as embedded inside an assignment. Extends the base {@link ISigner}\n * with the per-assignment verification / notification / ordering fields the\n * API returns. `completed` and `notification_history` are only present in\n * account-owner contexts.\n */\nexport interface IAssignmentSigner extends ISigner {\n\tverification_method?: AssignmentVerificationMethod | null;\n\tnotification_methods?: AssignmentNotificationMethod[] | null;\n\tstep?: number | null;\n\tnotified?: boolean | null;\n\tcompleted?: boolean | null;\n\tidentity_verification_status?: IdentityVerificationStatus | null;\n\tnotification_history?: IAssignmentSignerNotification[];\n}\n\n/**\n * One item (field placement instance) inside an assignment. `signer` and\n * `field` are embedded objects whose exact shape varies by context (the API's\n * own spec leaves them generic); `display_settings` is populated for\n * `collect`-method items and an empty array for `virtual`/legacy ones.\n */\nexport interface IAssignmentItem {\n\tid: string;\n\tpage: { id: string; number: number; height: number; width: number; download_url: string } | null;\n\tsigner: Partial<ISigner> & Record<string, unknown>;\n\tfield: Partial<IFieldDefinition> & Record<string, unknown>;\n\tdisplay_settings: IDisplaySettings | unknown[] | null;\n\tvalue: string | null;\n\tcompleted: boolean;\n}\n\n/** Signer summary entry inside `assignment.summary.signers` (account-owner contexts). */\nexport interface IAssignmentSummarySigner extends ISigner {\n\tcompleted: boolean;\n}\n\n/** Assignment object as returned by the API. */\nexport interface IAssignment {\n\t/** Resource type (`assignment`); present in single-resource responses. */\n\tresource?: string;\n\tid: string;\n\tsender_email?: string;\n\t/** `virtual` or `collect`. Documented as `null` for some `collect` responses. */\n\tmethod: AssignmentMethod | null;\n\t/** ISO 8601 timestamp, or `null` when the assignment does not expire. */\n\texpires_at?: string | null;\n\texpiration?: string;\n\tmessage?: string | null;\n\tsigners: IAssignmentSigner[];\n\t/** Request payloads use signer IDs; responses may expand them to objects. */\n\tcopy_receivers?: Array<string | Record<string, unknown>>;\n\titems?: IAssignmentItem[];\n\tsummary?: {\n\t\tsigner_count: number;\n\t\tcompleted_count: number;\n\t\tsigners: IAssignmentSummarySigner[];\n\t};\n\tsigning_urls?: ISigningUrl[];\n}\n\nexport type ICreateAssignmentResponse = IAssignment;\n\nexport interface IResendEmailResponse {\n\tis_sent?: boolean;\n\tdocument_id?: string;\n\tsigner_id?: string;\n}\n\n/** One line item in a cost-estimation `breakdown`. */\nexport interface IEstimateCostBreakdownItem {\n\tcode: string;\n\tname: string;\n\tcost: number;\n\tquantity: number;\n\tunit_cost: number;\n}\n\n/**\n * Cost-estimation response shared by the assignment `estimate-cost` and the\n * template `documents/estimate-cost` endpoints (identical shape per the docs).\n */\nexport interface IEstimateCostResponse {\n\tdocuments: number;\n\tcredits: number;\n\tneeds_extra_document: boolean;\n\textra_document_cost: number;\n\ttotal_credits: number;\n\tbreakdown: IEstimateCostBreakdownItem[];\n\tdocument_balance: number;\n\tcredit_balance: number;\n\thas_sufficient_resources: boolean;\n\tblocking_reason: 'PendingPayment' | 'InsufficientDocuments' | 'InsufficientCredits' | null;\n\tmessage: string | null;\n}\n\n/** Cost-estimation response for resending a single signer notification. */\nexport type IResendCostEstimate =\n\t| IEstimateCostResponse\n\t| {\n\t\t\ttotal: number;\n\t\t\tbreakdown: Pick<IEstimateCostBreakdownItem, 'code' | 'name' | 'cost'>[];\n\t\t\tcredit_balance: number;\n\t\t\thas_sufficient_credits: boolean;\n\t };\n\n/** Webhook payload envelope. */\nexport interface IWebhookPayload {\n\tid?: number;\n\tevent?: string;\n\ttype?: string;\n\tmessage?: string | null;\n\tpayload?: Record<string, unknown> | null;\n\torigin?: Record<string, unknown> | null;\n\tsubject?: Record<string, unknown>;\n\tobject?: Record<string, unknown>;\n\taccount_id?: string;\n\tdata?: {\n\t\tdocument_uuid?: string;\n\t\tdocument_id?: string;\n\t\t[key: string]: unknown;\n\t};\n\t[key: string]: unknown;\n}\n\n/** Known webhook event names. */\nexport type WebhookEventType =\n\t| 'document_uploaded'\n\t| 'document_metadata_ready'\n\t| 'document_prepared'\n\t| 'assignment_created'\n\t| 'document_ready'\n\t| 'signature_requested'\n\t| 'signer_created'\n\t| 'signer_email_verified'\n\t| 'signer_whatsapp_verified'\n\t| 'signer_identity_verified'\n\t| 'signer_identity_verification_failed'\n\t| 'signer_identity_review_required'\n\t| 'signer_identity_review_approved'\n\t| 'signer_identity_review_rejected'\n\t| 'signer_data_confirmed'\n\t| 'signer_viewed_document'\n\t| 'signer_signed_document'\n\t| 'signer_rejected_document'\n\t| 'user_rejected_document'\n\t| 'document_processing_failed'\n\t| 'template_created'\n\t| 'template_processed'\n\t| 'template_processing_failed';\n\n/** Rendered document-page metadata returned by document and template endpoints. */\nexport interface IDocumentPage {\n\tid: string;\n\tnumber: number;\n\theight: number;\n\twidth: number;\n\tdownload_url: string;\n}\n\n/** Artifact URLs embedded in document responses. */\nexport interface IDocumentArtifacts {\n\toriginal: string;\n\tcertificated?: string;\n\t'certificate-page'?: string;\n\tpades?: string;\n\tbundle?: string;\n\tthumbnail?: string;\n}\n\n/**\n * Document listing item (paginated).\n *\n * The list endpoint auto-expands `assignment` and `pages`, so live list items\n * carry the full document shape — `artifacts`, `pages`, `assignment`,\n * `signing_url`, `decline_reason` and `declined_by` are all present (verified\n * against the sandbox). They are optional here because the exact set can vary\n * by document status.\n */\nexport interface IDocumentListItem {\n\tresource?: string;\n\tid: string;\n\tname: string;\n\tstatus: DocumentStatus;\n\taccount_id?: string;\n\ttemplate_id?: string | null;\n\t/** Tags attached to the document (inline `{ id, name, color }` shape). */\n\ttags?: IInlineTag[];\n\t/** Downloadable artifact URLs (`original` always present once processed). */\n\tartifacts?: IDocumentArtifacts;\n\t/** Rendered page metadata (auto-expanded by the list endpoint). */\n\tpages?: IDocumentPage[];\n\t/** Embedded assignment (auto-expanded); `null` before signatures are requested. */\n\tassignment?: IAssignment | null;\n\t/** Direct signing URL when an assignment is active. */\n\tsigning_url?: string | null;\n\tdecline_reason?: string | null;\n\tdeclined_by?: ISigner | string | null;\n\tcreated_at: string;\n\tupdated_at?: string;\n\tis_closed?: boolean;\n}\n\nexport type IDocumentListResponse = PaginatedResult<IDocumentListItem>;\n\n/** Query parameters accepted by `documents.list`. */\nexport interface IDocumentListParams extends IPaginationParams {\n\t/** Filter by document status, e.g. `pending_signature`. */\n\tstatus?: DocumentStatus | string;\n\t/** Filter by signature method (`virtual` or `collect`). */\n\tmethod?: AssignmentMethod;\n\t/** Comma-separated list of tag IDs (AND semantics). */\n\ttags?: string;\n\tsearch?: string;\n\tsort?: 'name' | '-name' | 'updated_at' | '-updated_at';\n}\n\n/** Query parameters accepted by the lightweight document search endpoint. */\nexport interface IDocumentSearchParams extends IPaginationParams {\n\tstatus?: DocumentStatus | string;\n\tsearch?: string;\n\t/** Live-verified extension; absent from the published OpenAPI. */\n\tsort?: 'name' | '-name' | 'updated_at' | '-updated_at';\n}\n\n/** Document upload response. */\nexport interface IDocumentUploadResponse {\n\tresource?: string;\n\tid: string;\n\taccount_id: string;\n\ttemplate_id: string | null;\n\tname: string;\n\tstatus: DocumentStatus;\n\t/** Absent immediately after upload; present once a signature request is active. */\n\tassignment?: IAssignment | null;\n\t/** Direct signing URL; present once the document has been processed. */\n\tsigning_url?: string | null;\n\tartifacts: IDocumentArtifacts;\n\tpages: IDocumentPage[];\n\t/** Tags attached to the document (inline `{ id, name, color }` shape). */\n\ttags?: IInlineTag[];\n\tcreated_at: string;\n\tupdated_at: string;\n\tis_closed: boolean;\n\tdecline_reason: string | null;\n\tdeclined_by: ISigner | null;\n}\n\n/** Detailed document response. */\nexport interface IDocumentDetailsResponse {\n\tresource?: string;\n\tid: string;\n\taccount_id: string;\n\ttemplate_id?: string | null;\n\tname: string;\n\tstatus: DocumentStatus;\n\tassignment: IAssignment | null;\n\tdownload_url?: string;\n\tdownload_final_url?: string;\n\tsigning_url?: string;\n\tartifacts?: IDocumentArtifacts;\n\t/** Omitted by the signer-side `GET /signers/{id}/document` endpoint. */\n\tpages?: IDocumentPage[];\n\t/** Tags attached to the document (inline `{ id, name, color }` shape). */\n\ttags?: IInlineTag[];\n\tcreated_at: string;\n\tupdated_at: string;\n\tis_closed: boolean;\n\tdecline_reason?: string | null;\n\tdeclined_by?: ISigner | null;\n\tactivities?: Array<IDocumentActivity>;\n}\n\nexport interface IDocumentActivity {\n\tid: number;\n\tevent: string;\n\tmessage: string;\n\t/** Event-specific payload snapshot. Object for most events, occasionally `[]`. */\n\tpayload?: Record<string, unknown> | unknown[];\n\t/** Request origin (`ip` / `user-agent`) when available; `null` for system events. */\n\torigin: { ip?: string; 'user-agent'?: string } | string | null;\n\tcreated_at: string;\n}\n\n/** Progress summary returned by `documents.getSigningProgress`. */\nexport interface ISigningProgress {\n\tsigned: number;\n\ttotal: number;\n\tpercentage: number;\n\tpending: number;\n}\n\n/** Pagination keys shared by current list endpoints. */\nexport interface IPaginationParams {\n\tpage?: number;\n\tper_page?: number;\n\t'per-page'?: number;\n}\n\n/**\n * @deprecated Use the endpoint-specific list parameter type. Retained for\n * source compatibility with existing integrations.\n */\nexport interface IListParams extends IPaginationParams {\n\tsearch?: string;\n\tsort?: string;\n\t[key: string]: string | number | boolean | undefined;\n}\n\n/** Live-verified assignment list extension; absent from the published OpenAPI. */\nexport interface IAssignmentListParams extends IPaginationParams {\n\tsort?: 'created_at' | '-created_at';\n}\n\n/** Published template filters plus a live-verified name sort extension. */\nexport interface ITemplateListParams extends IPaginationParams {\n\tsearch?: string;\n\tsort?: 'name' | '-name';\n}\n\n/** Published signer filters plus a live-verified full-name sort extension. */\nexport interface ISignerListParams extends IPaginationParams {\n\tsearch?: string;\n\tsort?: 'full_name' | '-full_name';\n}\n\n/** Signer-side document list compatibility filters. */\nexport interface ISignerDocumentListParams extends IPaginationParams {\n\tsearch?: string;\n\tsort?: string;\n}\n\n/** Workspace creation payload. */\nexport interface ICreateWorkspacePayload {\n\tname: string;\n\tnotification_sender_type?: NotificationSenderType;\n\t/** Undocumented compatibility field retained until sandbox support is disproved. */\n\tprimary_color?: string;\n\t/** Undocumented compatibility field retained until sandbox support is disproved. */\n\tsecondary_color?: string;\n}\n\nexport interface IUpdateWorkspacePayload {\n\tname?: string;\n\tnotification_sender_type?: NotificationSenderType;\n\t/** Undocumented compatibility field retained until sandbox support is disproved. */\n\tprimary_color?: string | null;\n\t/** Undocumented compatibility field retained until sandbox support is disproved. */\n\tsecondary_color?: string | null;\n}\n\nexport interface IWorkspaceResponse {\n\tresource?: string;\n\tid: string;\n\tname: string;\n\tprimary_color?: string | null;\n\tsecondary_color?: string | null;\n\tnotification_sender_type?: NotificationSenderType;\n\troles?: string[];\n\tis_delete_allowed?: boolean;\n\tcreated_at: string;\n}\n\nexport interface IWorkspaceListItem extends IWorkspaceResponse {\n\tis_delete_allowed: boolean;\n\troles: string[];\n}\n\nexport type IWorkspaceListResponse = PaginatedResult<IWorkspaceListItem>;\n\nexport type NotificationSenderType = 'User' | 'Account';\n\n/** Branding details returned by `GET /accounts/{accountId}/theme`. */\nexport interface IAccountTheme {\n\taccount_name: string;\n\tprimary_color: string;\n\tsecondary_color: string | null;\n\tlogo: string | null;\n}\n\n/** Query parameters shared by account and user document statistics. */\nexport interface IDocumentStatsParams {\n\tgranularity?: 'monthly' | 'daily';\n\t/** Required in `YYYY-MM` form when `granularity` is `daily`. */\n\tmonth?: string;\n}\n\n/** One period in an account/user document-funnel statistics response. */\nexport interface IDocumentStatsRow {\n\tperiod: string;\n\tdocuments_uploaded: number;\n\tdocuments_sent: number;\n\tsignature_requests: number;\n\t/** Requests notified by email; multi-channel requests count in each notification channel. */\n\tsignature_requests_notification_email: number;\n\t/** Requests notified by WhatsApp; multi-channel requests count in each notification channel. */\n\tsignature_requests_notification_whatsapp: number;\n\t/** Requests created without a notification. */\n\tsignature_requests_notification_bypass: number;\n\t/** Requests verified with an email token. */\n\tsignature_requests_verification_email: number;\n\t/** Requests verified with a WhatsApp token. */\n\tsignature_requests_verification_whatsapp: number;\n\t/** Requests signed without token verification. */\n\tsignature_requests_verification_bypass: number;\n\t/** Requests signed with the signer's ICP-Brasil digital certificate. */\n\tsignature_requests_verification_digital_certificate: number;\n\tsignature_requests_viewed: number;\n\tsignature_requests_completed: number;\n\tdocuments_certified: number;\n}\n\n/** Options for uploading a workspace logo. */\nexport interface IUploadAccountLogoOptions {\n\tfileName?: string;\n\tcontentType?: string;\n}\n\n/** Webhook subscription payload. */\nexport interface IWebhookRegisterPayload {\n\turl: string;\n\temail: string;\n\tevents?: WebhookEventType[] | string[];\n\tis_active?: boolean;\n}\n\nexport interface IWebhookSubscription {\n\tid?: string;\n\t/** Documented as `string|null` — `null` when no endpoint URL is configured. */\n\turl: string | null;\n\t/** Documented as `string|null` — `null` when no contact email is configured. */\n\temail: string | null;\n\tevents: string[];\n\tis_active: boolean;\n\tcreated_at?: string | null;\n\tupdated_at?: string | null;\n}\n\n/** A webhook endpoint (`/accounts/{accountId}/webhooks/endpoints`). */\nexport interface IWebhookEndpoint {\n\tid: string;\n\tname: string | null;\n\turl: string;\n\temail: string;\n\tevents: string[];\n\tis_active: boolean;\n\t/** `true` when deliveries carry a Standard Webhooks `webhook-signature` header. */\n\tsigning_enabled: boolean;\n\tcreated_at: string;\n\tupdated_at: string;\n}\n\n/** Endpoint creation includes its signing secret only when signing is enabled. */\nexport interface IWebhookEndpointCreateResponse extends IWebhookEndpoint {\n\t/** Save securely on creation; OAuth applications cannot read or rotate it later. */\n\tsecret?: string;\n}\n\n/** `POST /accounts/{accountId}/webhooks/endpoints` body. */\nexport interface IWebhookEndpointCreatePayload {\n\turl: string;\n\temail: string;\n\t/** Defaults to the SDK's standard event set when omitted. */\n\tevents?: WebhookEventType[] | string[];\n\tname?: string;\n\t/** Server default: `true`. */\n\tis_active?: boolean;\n\t/** Server default: `false`. */\n\tsigning_enabled?: boolean;\n}\n\n/** `PUT /accounts/{accountId}/webhooks/endpoints/{endpointId}` body; only sent fields change. */\nexport type IWebhookEndpointUpdatePayload = Partial<IWebhookEndpointCreatePayload>;\n\n/** Endpoint signing secret, prefixed `whsec_`. */\nexport interface IWebhookEndpointSecret {\n\tsecret: string;\n}\n\nexport interface IWebhookEventTypeInfo {\n\tid: WebhookEventType | string;\n\tdescription: string;\n}\n\nexport interface IWebhookDispatch {\n\tresource?: string;\n\tid: string;\n\tevent: WebhookEventType | string;\n\tactivity_id: number;\n\t/** Endpoint that received this delivery. */\n\tendpoint_id?: string | null;\n\tendpoint: string | null;\n\tpayload: IWebhookPayload | Record<string, unknown> | null;\n\tdelivered: boolean;\n\thttp_status: number | null;\n\tresponse_body: string | null;\n\terror: string | null;\n\t/** ISO 8601 timestamp (verified against the sandbox — not a unix epoch number). */\n\tcreated_at: string;\n\t/** ISO 8601 timestamp (verified against the sandbox — not a unix epoch number). */\n\tupdated_at?: string;\n}\n\nexport interface IWebhookDispatchListParams extends IPaginationParams {\n\t/** Only deliveries to this webhook endpoint. */\n\tendpoint_id?: string;\n\tevent?: WebhookEventType | string;\n\tdelivered?: boolean | 'true' | 'false';\n\tfrom?: number;\n\tto?: number;\n\t/** Live-verified extension; absent from the published OpenAPI. */\n\tsort?: 'created_at' | '-created_at';\n}\n\n/** Shape of the high-level `uploadAndRequestSignatures` helper result. */\nexport interface IUploadAndRequestSignaturesResult {\n\tdocument: IDocumentUploadResponse;\n\tassignment: IAssignment;\n\tsigner_ids: string[];\n}\n\n/** Input for a signer in `uploadAndRequestSignatures`. */\nexport interface IUploadAndRequestSignaturesSigner {\n\tname: string;\n\temail?: string;\n\twhatsapp_phone_number?: string;\n\t/** PHP SDK compatibility alias for `whatsapp_phone_number`. */\n\tphone?: string;\n\t/** CPF or numeric/alphanumeric CNPJ; existing email matches are reused without updating it. */\n\tgovernment_id?: string;\n\t/** Compatibility extension for a Brazilian CPF; non-digits are stripped. */\n\tcpf?: string;\n\t/** Compatibility extension for integration-defined signer metadata. */\n\tmetadata?: Record<string, unknown>;\n\tverification_method?: AssignmentVerificationMethod;\n\tnotification_methods?: AssignmentNotificationMethod[];\n\t/** Integer signing-order value forwarded to the assignment signer reference. */\n\tstep?: number;\n}\n\n/** Template role definition. */\nexport interface ITemplateRole {\n\tid: string;\n\tname: string;\n\tassignment_type?: string;\n\tcreated_at?: string;\n\tupdated_at?: string;\n\t[key: string]: unknown;\n}\n\n/** One template field placement returned inside a template page. */\nexport interface ITemplateField {\n\tid: string;\n\tfield_id: string;\n\trole_id: string;\n\tlabel: string;\n\tdisplay_settings: IDisplaySettings | unknown[] | null;\n\tcreated_at: string;\n\tupdated_at: string;\n}\n\n/** One rendered page and its editor/signer field placements. */\nexport interface ITemplatePage extends IDocumentPage {\n\tfields: ITemplateField[];\n}\n\n/** Template list item (paginated). */\nexport interface ITemplateListItem {\n\tresource?: string;\n\tid: string;\n\tname: string;\n\tdocument_name?: string | null;\n\tmessage?: string | null;\n\tstatus: string;\n\taccount_id?: string;\n\tpages?: ITemplatePage[];\n\troles?: ITemplateRole[];\n\t/** Tags attached to the template itself (inline `{ id, name }` shape). */\n\ttags?: IInlineTag[];\n\t/** Tags auto-applied to documents created from this template. */\n\tdefault_document_tags?: IInlineTag[];\n\tcreated_at: string;\n\tupdated_at?: string;\n}\n\nexport type ITemplateListResponse = PaginatedResult<ITemplateListItem>;\n\n/** Full template details, including any platform-specific extension fields. */\nexport interface ITemplateDetailsResponse extends ITemplateListItem {\n\t[key: string]: unknown;\n}\n\n/**\n * Signer assignment for creating a document from a template. `id` is required\n * here; for cost estimation it is optional — see {@link ITemplateCostSigner}.\n */\nexport interface ITemplateSigner {\n\trole_id: string;\n\tid: string;\n\tverification_method?: AssignmentVerificationMethod;\n\tnotification_methods?: AssignmentNotificationMethod[];\n\t/**\n\t * Positive signing order. If used for any role, every role needs a step and\n\t * the distinct values must form a contiguous sequence starting at 1.\n\t */\n\tstep?: number;\n}\n\n/** Signer entry accepted by the template cost-estimation endpoint. */\nexport interface ITemplateCostSigner {\n\trole_id: string;\n\tverification_method?: AssignmentVerificationMethod;\n\tnotification_methods?: AssignmentNotificationMethod[];\n\t/** Compatibility extension retained for integrations that already send a signer ID. */\n\tid?: string;\n\t/** Compatibility extension retained for integrations that already send a signing step. */\n\tstep?: number;\n}\n\n/** One editor field value baked into a generated document. */\nexport interface ITemplateEditorField {\n\tfield_id: string;\n\tvalue: string;\n}\n\n/** Options for creating a document from a template. */\nexport interface ICreateDocumentFromTemplateOptions {\n\tname?: string;\n\tmessage?: string;\n\texpires_at?: string;\n\teditor_fields?: ITemplateEditorField[];\n\t/**\n\t * Tag names to attach to the new document. Names that don't exist yet are\n\t * auto-created; the template's default-document-tags are always merged in.\n\t */\n\ttags?: string[];\n}\n\n/**\n * Item returned by `GET /documents/statuses`.\n *\n * The API uses `code` (the status name); we mirror that field. `description`\n * is documented in the table but is not currently present in the JSON payload.\n */\nexport interface IDocumentStatusInfo {\n\tcode: DocumentStatus | string;\n\tdeletable: boolean;\n\tdescription?: string;\n}\n\n/**\n * Response from `GET /documents/{signatureHash}/verify` (live-verified against\n * the sandbox). Always a `200`: an unknown/unsigned hash comes back with\n * `is_valid: false`, every other field `null` (except `hash`/`verified_at`),\n * and `message` explaining why.\n */\nexport interface IDocumentVerifyResponse {\n\thash: string;\n\tid: string | null;\n\t/** Agreement code printed on the document certificate. */\n\tagreement_code?: string | null;\n\tstatus: DocumentStatus | string | null;\n\tpage_count: string | null;\n\tsigner_count: string | null;\n\tcompleted_count: number | null;\n\tcompleted_at: string | null;\n\tverified_at: string;\n\tis_valid: boolean;\n\t/** Reason when not valid; empty string on success. */\n\tmessage: string;\n}\n\n/** Item returned by `GET /public/documents/{id}`. */\nexport interface IPublicDocumentInfo {\n\tresource?: string;\n\tid: string;\n\taccount_id: string;\n\ttemplate_id: string | null;\n\tname: string;\n\tstatus: DocumentStatus | string;\n\tartifacts: IDocumentArtifacts;\n\tis_closed: boolean;\n\tsigning_url: string | null;\n\tdecline_reason: string | null;\n\tdeclined_by: ISigner | null;\n\ttags: IInlineTag[];\n\tassignment: IAssignment | null;\n\tpages: IDocumentPage[];\n\tcreated_at: string;\n\tupdated_at: string;\n\t/** Live-compatible fields returned by older sandbox deployments. */\n\tpage_count?: string | number;\n\tcreated_by?: string;\n}\n\n/** Channel accepted by the `send-token` endpoint. Only `email` is supported. */\nexport type SendTokenChannel = 'email';\n\n/** `data` of `PUT /public/documents/{id}/send-token`. */\nexport interface ISendTokenResponse {\n\t/** Compact document; sandbox returns `page_count` as a numeric string. */\n\tdocument: {\n\t\tresource: 'document';\n\t\tid: string;\n\t\tname: string;\n\t\tpage_count: number | string;\n\t\tcreated_by: string;\n\t};\n\tchannel: SendTokenChannel;\n\t/** The signer email the token was sent to. */\n\trecipient: string;\n}\n\n/** Authentication: login response (also returned by social login). */\nexport interface IAuthUser {\n\tid: string;\n\tname: string;\n\temail: string;\n\ttelephone?: string | null;\n\tgovernment_id?: string | null;\n\tis_email_verified?: boolean;\n\thas_accepted_terms?: boolean;\n\tcreated_at?: string;\n\tto_be_deleted_at?: string | null;\n}\n\nexport interface IAuthAccount {\n\tid: string;\n\tname: string;\n\troles: string[];\n\tis_delete_allowed: boolean;\n\tcreated_at: string;\n}\n\nexport interface ILoginResponse {\n\taccess_token: string;\n\tuser: IAuthUser;\n\taccounts: IAuthAccount[];\n\t/**\n\t * Two-factor challenge returned by `POST /login` when the user has a\n\t * confirmed method. Complete it with `auth.verifyMfa` within 5 minutes.\n\t */\n\tmfa_token?: string;\n}\n\n/** `POST /authentication/mfa/verify` body. */\nexport interface IMfaVerifyPayload {\n\tmfa_token: string;\n\t/** 6-digit authenticator code or a recovery code such as `ABCD-EFGH-JKMN`. */\n\tcode: string;\n}\n\n/** An enrolled two-factor method. */\nexport interface IMfaMethod {\n\tid: string;\n\ttype: 'Totp' | (string & {});\n\tlabel: string | null;\n\tconfirmed_at: string | null;\n\tlast_used_at: string | null;\n}\n\n/** `GET /users/self/mfa` response. */\nexport interface IMfaStatus {\n\tmethods: IMfaMethod[];\n\trecovery_codes_remaining: number;\n}\n\n/** `POST /users/self/mfa/totp` response; `secret` is returned only once. */\nexport interface ITotpEnrollment {\n\tid: string;\n\tsecret: string;\n\tprovisioning_uri: string;\n}\n\n/** `PUT /users/self/mfa/totp/confirm` body. */\nexport interface ITotpConfirmPayload {\n\tid: string;\n\t/** Live code from the device being enrolled. */\n\tcode: string;\n\t/** Re-authentication, required only when replacing a confirmed method. */\n\tpassword?: string;\n\t/** Alternative re-authentication: a code from the current device or a recovery code. */\n\treauth_code?: string;\n}\n\n/** Re-authentication proof: the current password, or a live/recovery `code`. */\nexport interface IMfaReauthPayload {\n\tpassword?: string;\n\tcode?: string;\n}\n\n/** One-time recovery codes. */\nexport interface IMfaRecoveryCodes {\n\trecovery_codes: string[];\n}\n\n/**\n * `GET /users/self` is documented as a direct user, while the sandbox has also\n * returned the login-style `{ user, accounts }` object. Preserve either shape.\n */\nexport type IUserSelfResponse = IAuthUser | { user: IAuthUser; accounts: IAuthAccount[] };\n\nexport const NOTIFICATION_PREFERENCE_CODES = [\n\t'DocumentCompleted',\n\t'SignerDeclined',\n\t'DocumentCancelled',\n\t'DocumentAboutToExpire',\n\t'DocumentExpired',\n\t'DocumentExpirationReset',\n\t'DocumentProcessingFailed',\n\t'TemplateProcessingFailed',\n\t'SignerWhatsappFailed',\n] as const;\n\nexport type NotificationPreferenceCode = (typeof NOTIFICATION_PREFERENCE_CODES)[number];\nexport type INotificationPreferences = Record<NotificationPreferenceCode, boolean>;\nexport type IUpdateNotificationPreferencesPayload = Partial<INotificationPreferences>;\n\n/** Authentication: API key payload returned by `POST /users/api-keys`. */\nexport interface IApiKeyResponse {\n\tapi_key: string | null;\n}\n\n/** Authentication: masked API key returned by `GET /users/api-keys` (or null when never generated). */\nexport type IMaskedApiKeyResponse = IApiKeyResponse | null;\n\n/** Field definition object. */\nexport interface IFieldDefinition {\n\tresource?: string;\n\tid: string;\n\tname: string;\n\ttype: string;\n\tregex?: string | null;\n\tis_pre_defined?: boolean;\n\tis_active: boolean;\n\tis_required?: boolean;\n\tis_standard?: boolean;\n\tis_read_only?: boolean;\n\tis_visible?: boolean;\n}\n\n/** Payload for creating a field definition. */\nexport interface ICreateFieldPayload {\n\ttype: string;\n\tname: string;\n\t/** Validation regex; `null` or omitted for none. */\n\tregex?: string | null;\n\tis_required?: boolean;\n\t/** Compatibility extension; not present in the published create schema. */\n\tis_active?: boolean;\n}\n\n/** Payload for updating a field definition. */\nexport interface IUpdateFieldPayload {\n\t/** Compatibility extension; not present in the published update schema. */\n\ttype?: string;\n\tname?: string;\n\tregex?: string | null;\n\t/** Compatibility extension; not present in the published update schema. */\n\tis_required?: boolean;\n\tis_active?: boolean;\n}\n\n/** Field type description returned by `GET /field-types`. */\nexport interface IFieldType {\n\ttype: string;\n\tname: string;\n}\n\n/** Single result returned by `POST /accounts/{id}/fields/{id}/validate`. */\nexport interface IFieldValidationResult {\n\ttype?: string;\n\tfield_id?: string;\n\tsuccess: boolean;\n\terror_message: string;\n}\n\n/** Payload entry for `POST /accounts/{id}/fields/validate-multiple`. */\nexport interface IFieldValidateMultipleEntry {\n\tfield_id: string;\n\tvalue: unknown;\n}\n\n/** Item returned by `GET /documents/{id}/assignments/{id}/whatsapp-notifications`. */\nexport interface IWhatsAppNotification {\n\tsent_at: number;\n\theader: string;\n\tbody: string;\n\tbuttons: Array<{ text: string; url?: string }>;\n\tphone_number: string;\n\tsigner_id: string;\n}\n\n/** Body entry for the signer-side `POST /documents/{id}/assignments/{id}` sign endpoint. */\nexport interface ISignFieldEntry {\n\titemId: string;\n\tfieldId: string;\n\tpageId: string;\n\tvalue: string;\n}\n\n/**\n * Workspace tag object. Tag names are unique per workspace (case-insensitive)\n * and `color` is an optional 6-char hex string (without the leading `#`).\n */\nexport interface ITag {\n\tresource?: string;\n\tid: string;\n\tname: string;\n\tcolor: string | null;\n\tcreated_at: string;\n\tupdated_at: string;\n}\n\n/** Inline tag shape embedded inside documents/templates (`{ id, name, color? }`). */\nexport interface IInlineTag {\n\tid: string;\n\tname: string;\n\tcolor?: string | null;\n}\n\n/** Payload for `POST /accounts/{id}/tags`. */\nexport interface ICreateTagPayload {\n\tname: string;\n\t/** 6-char hex color, with or without a leading `#`. Omit/`null` for none. */\n\tcolor?: string | null;\n}\n\n/** Payload for `PUT /accounts/{id}/tags/{id}`. Omit a field to leave it unchanged. */\nexport interface IUpdateTagPayload {\n\tname?: string;\n\t/** Pass `null` to clear the color; omit to leave unchanged. */\n\tcolor?: string | null;\n}\n\n/** Confirmation returned after detaching a tag from a document. */\nexport interface IDetachTagResponse {\n\tdetached: boolean;\n}\n\n/** Confirmation returned after deleting a tag. */\nexport interface IDeleteTagResponse {\n\tdeleted: boolean;\n}\n\n/** RFC 9728 metadata served at the API origin (outside `/v1`). */\nexport interface IOAuthProtectedResource {\n\tresource: string;\n\tauthorization_servers: string[];\n\tscopes_supported: string[];\n\tbearer_methods_supported: string[];\n}\n\n/** RFC 8414 metadata served by the authorization server. */\nexport interface IOAuthAuthorizationServer {\n\tissuer: string;\n\tauthorization_endpoint: string;\n\ttoken_endpoint: string;\n\trevocation_endpoint?: string;\n\tuserinfo_endpoint?: string;\n\tjwks_uri?: string;\n\tresponse_types_supported: string[];\n\tscopes_supported?: string[];\n\tgrant_types_supported?: string[];\n\tcode_challenge_methods_supported?: string[];\n\ttoken_endpoint_auth_methods_supported?: string[];\n\tauthorization_response_iss_parameter_supported?: boolean;\n\tclient_id_metadata_document_supported?: boolean;\n\t[key: string]: unknown;\n}\n\n/** Input to `oauth.authorize`; redirectUri must exactly match an HTTPS registered URI. */\nexport interface IOAuthAuthorizationOptions {\n\tclientId: string;\n\tredirectUri: string;\n\tscopes: string[];\n}\n\n/** Store server-side per user connection attempt; consume once when handling the callback. */\nexport interface IOAuthAuthorizationRequest {\n\tauthorization_url: string;\n\tcode_verifier: string;\n\tstate: string;\n\tissuer: string;\n\tclient_id: string;\n\tredirect_uri: string;\n\tresource: string;\n\t/** Generated when requesting openid. Validate it when verifying the ID token. */\n\tnonce?: string;\n}\n\n/** Form fields for `POST /oauth/token`. PKCE is mandatory for all code exchanges. */\nexport type IOAuthTokenPayload = {\n\tclient_id: string;\n\t/** Confidential applications only; public applications omit this field. */\n\tclient_secret?: string;\n\tresource?: string;\n} & (\n\t| { grant_type: 'authorization_code'; code: string; redirect_uri: string; code_verifier: string }\n\t| { grant_type: 'refresh_token'; refresh_token: string }\n\t| {\n\t\t\t/** RFC 8693; Assinafy internal-service confidential clients only (others get `invalid_client`). */\n\t\t\tgrant_type: 'urn:ietf:params:oauth:grant-type:token-exchange';\n\t\t\tclient_secret: string;\n\t\t\t/** Required for this grant: this API's own resource identifier. */\n\t\t\tresource: string;\n\t\t\tsubject_token: string;\n\t\t\tsubject_token_type: 'urn:ietf:params:oauth:token-type:access_token';\n\t\t\trequested_token_type?: 'urn:ietf:params:oauth:token-type:access_token';\n\t }\n);\n\n/** Flat OAuth response. Persist rotated tokens atomically before making further requests. */\nexport interface IOAuthTokenResponse {\n\taccess_token: string;\n\ttoken_type: string;\n\texpires_in: number;\n\t/** Granted access-token scopes. Never lists `offline_access`; check `refresh_token` instead. */\n\tscope: string;\n\t/**\n\t * Present only with offline_access consent; always a new value after a refresh-grant `token()`.\n\t * Reusing the old token revokes the connection.\n\t */\n\trefresh_token?: string | null;\n\t/** Present only with openid. Must be verified by an OIDC library before use as identity. */\n\tid_token?: string | null;\n}\n\n/** Form fields for `POST /oauth/revoke`; failed client authentication still returns 401. */\nexport interface IOAuthRevokePayload {\n\ttoken: string;\n\tclient_id: string;\n\tclient_secret?: string;\n\ttoken_type_hint?: 'access_token' | 'refresh_token';\n}\n\n/** Flat `GET /oauth/userinfo` claims. Additional claims depend on consented scopes. */\nexport interface IOAuthUserInfo {\n\tsub: string;\n\tname?: string | null;\n\temail?: string | null;\n\temail_verified?: boolean | null;\n}\n","import { ValidationError } from '../errors.js';\nimport {\n\ttype IDocumentStatsParams,\n\ttype IDocumentStatsRow,\n\ttype INotificationPreferences,\n\ttype IUpdateNotificationPreferencesPayload,\n\ttype IUserSelfResponse,\n\tNOTIFICATION_PREFERENCE_CODES,\n} from '../types.js';\nimport { documentStatsParams } from '../utils.js';\nimport { BaseResource } from './base.js';\n\nconst NOTIFICATION_PREFERENCES = new Set<string>(NOTIFICATION_PREFERENCE_CODES);\n\n/** Authenticated user profile, statistics, and notification preferences. */\nexport class UsersResource extends BaseResource {\n\t/** Fetch the authenticated user's profile. */\n\tasync self(): Promise<IUserSelfResponse> {\n\t\treturn this.call('Failed to fetch authenticated user', () => this.http.get('/users/self'));\n\t}\n\n\t/** Fetch monthly or daily document-funnel statistics across the user's accounts. */\n\tasync stats(params: IDocumentStatsParams = {}): Promise<IDocumentStatsRow[]> {\n\t\treturn this.call('Failed to fetch user statistics', () =>\n\t\t\tthis.http.get('/users/self/stats', { params: documentStatsParams(params) }),\n\t\t);\n\t}\n\n\t/** Fetch all owner-facing email notification preferences. */\n\tasync getNotificationPreferences(): Promise<INotificationPreferences> {\n\t\treturn this.call('Failed to fetch notification preferences', () =>\n\t\t\tthis.http.get('/users/self/notification-preferences'),\n\t\t);\n\t}\n\n\t/** Merge one or more owner-facing email notification preferences. */\n\tasync updateNotificationPreferences(\n\t\tpayload: IUpdateNotificationPreferencesPayload,\n\t): Promise<INotificationPreferences> {\n\t\tif (!payload || typeof payload !== 'object' || Array.isArray(payload)) {\n\t\t\tthrow new ValidationError('Notification preferences must be an object');\n\t\t}\n\t\tconst entries = Object.entries(payload);\n\t\tif (entries.length === 0) {\n\t\t\tthrow new ValidationError('At least one notification preference is required');\n\t\t}\n\t\tfor (const [key, value] of entries) {\n\t\t\tif (!NOTIFICATION_PREFERENCES.has(key)) {\n\t\t\t\tthrow new ValidationError(`Unknown notification preference: ${key}`);\n\t\t\t}\n\t\t\tif (typeof value !== 'boolean') {\n\t\t\t\tthrow new ValidationError(`${key} must be a boolean`);\n\t\t\t}\n\t\t}\n\n\t\treturn this.call('Failed to update notification preferences', () =>\n\t\t\tthis.http.put('/users/self/notification-preferences', payload),\n\t\t);\n\t}\n}\n","import { ValidationError } from '../errors.js';\nimport type {\n\tIEmptyResult,\n\tIWebhookDispatch,\n\tIWebhookDispatchListParams,\n\tIWebhookEndpoint,\n\tIWebhookEndpointCreatePayload,\n\tIWebhookEndpointCreateResponse,\n\tIWebhookEndpointSecret,\n\tIWebhookEndpointUpdatePayload,\n\tIWebhookEventTypeInfo,\n\tIWebhookRegisterPayload,\n\tIWebhookSubscription,\n\tPaginatedResult,\n\tWebhookEventType,\n} from '../types.js';\nimport { cleanParams, requireEmail, requireSort } from '../utils.js';\nimport { BaseResource } from './base.js';\n\nconst DEFAULT_EVENTS: WebhookEventType[] = [\n\t'document_ready',\n\t'document_prepared',\n\t'signer_signed_document',\n\t'signer_rejected_document',\n\t'document_processing_failed',\n];\n\n/** Validate the webhook fields that are present; omitted fields are left to the caller. */\nfunction validateWebhookFields(payload: IWebhookEndpointUpdatePayload): void {\n\tif (payload.url !== undefined) {\n\t\tlet webhookUrl: URL;\n\t\ttry {\n\t\t\twebhookUrl = new URL(payload.url);\n\t\t} catch {\n\t\t\tthrow new ValidationError('Webhook URL must be a valid HTTP(S) URL');\n\t\t}\n\t\tif (webhookUrl.protocol !== 'http:' && webhookUrl.protocol !== 'https:') {\n\t\t\tthrow new ValidationError('Webhook URL must be a valid HTTP(S) URL');\n\t\t}\n\t}\n\tif (payload.email !== undefined) requireEmail(payload.email);\n\tif (\n\t\tpayload.events !== undefined &&\n\t\t(!Array.isArray(payload.events) ||\n\t\t\tpayload.events.some((event) => typeof event !== 'string' || !event))\n\t) {\n\t\tthrow new ValidationError('Webhook events must contain non-empty strings');\n\t}\n\tif (payload.name !== undefined && typeof payload.name !== 'string') {\n\t\tthrow new ValidationError('Webhook name must be a string');\n\t}\n\tfor (const key of ['is_active', 'signing_enabled'] as const) {\n\t\tif (payload[key] !== undefined && typeof payload[key] !== 'boolean') {\n\t\t\tthrow new ValidationError(`Webhook ${key} must be a boolean`);\n\t\t}\n\t}\n}\n\nexport class WebhookResource extends BaseResource {\n\t/**\n\t * `PUT /accounts/{accountId}/webhooks/subscriptions` — create or replace the\n\t * account's oldest webhook endpoint. Use the endpoint methods for accounts\n\t * with several endpoints or for signed deliveries.\n\t */\n\tasync register(\n\t\tpayload: IWebhookRegisterPayload,\n\t\taccountId?: string,\n\t): Promise<IWebhookSubscription> {\n\t\tif (!payload.url) throw new ValidationError('Webhook URL is required');\n\t\tvalidateWebhookFields({ ...payload, email: payload.email ?? '' });\n\n\t\tconst id = this.accountId(accountId);\n\t\tconst body = {\n\t\t\turl: payload.url,\n\t\t\temail: payload.email,\n\t\t\t// Distinguish \"omitted\" (use the sensible default set) from an\n\t\t\t// explicit empty array (the caller wants zero events).\n\t\t\tevents: payload.events ?? DEFAULT_EVENTS,\n\t\t\tis_active: payload.is_active ?? true,\n\t\t};\n\n\t\tthis.logger.info('Registering webhook', { eventCount: body.events.length });\n\n\t\treturn this.call('Failed to register webhook', () =>\n\t\t\tthis.http.put(`/accounts/${id}/webhooks/subscriptions`, body),\n\t\t);\n\t}\n\n\t/** Fetch the account's oldest webhook endpoint. Returns `null` if none exists. */\n\tasync get(accountId?: string): Promise<IWebhookSubscription | null> {\n\t\tconst id = this.accountId(accountId);\n\t\treturn this.callOptional<IWebhookSubscription>('Failed to fetch webhook subscription', () =>\n\t\t\tthis.http.get(`/accounts/${id}/webhooks/subscriptions`),\n\t\t);\n\t}\n\n\t/** Inactivate the account's oldest webhook endpoint without deleting it. */\n\tasync inactivate(accountId?: string): Promise<IWebhookSubscription> {\n\t\tconst id = this.accountId(accountId);\n\t\tthis.logger.info('Inactivating webhook subscription');\n\t\treturn this.call('Failed to inactivate webhook subscription', () =>\n\t\t\tthis.http.put(`/accounts/${id}/webhooks/inactivate`),\n\t\t);\n\t}\n\n\t/** List webhook endpoints, oldest first; `url` matches the registered value exactly. */\n\tasync listEndpoints(\n\t\taccountId?: string,\n\t\tparams: { url?: string } = {},\n\t): Promise<IWebhookEndpoint[]> {\n\t\tconst id = this.accountId(accountId);\n\t\tvalidateWebhookFields(params);\n\t\treturn this.call('Failed to list webhook endpoints', () =>\n\t\t\tthis.http.get(`/accounts/${id}/webhooks/endpoints`, { params: cleanParams({ ...params }) }),\n\t\t);\n\t}\n\n\t/**\n\t * `POST /accounts/{accountId}/webhooks/endpoints` — register another\n\t * endpoint. Accounts allow 1 endpoint, or up to 3 on paid plans (`403` past\n\t * the limit); URLs must be unique per workspace. Omitted `events` uses the\n\t * same default set as {@link register}. Signed creation returns `secret`\n\t * once, including to OAuth applications; save it securely.\n\t */\n\tasync createEndpoint(\n\t\tpayload: IWebhookEndpointCreatePayload,\n\t\taccountId?: string,\n\t): Promise<IWebhookEndpointCreateResponse> {\n\t\tif (!payload.url) throw new ValidationError('Webhook URL is required');\n\t\tvalidateWebhookFields({ ...payload, email: payload.email ?? '' });\n\t\tconst id = this.accountId(accountId);\n\t\tconst body = { ...payload, events: payload.events ?? DEFAULT_EVENTS };\n\t\tthis.logger.info('Creating webhook endpoint', { eventCount: body.events.length });\n\t\treturn this.call('Failed to create webhook endpoint', () =>\n\t\t\tthis.http.post(`/accounts/${id}/webhooks/endpoints`, body),\n\t\t);\n\t}\n\n\t/** `GET /accounts/{accountId}/webhooks/endpoints/{endpointId}` — fetch one endpoint. */\n\tasync getEndpoint(endpointId: string, accountId?: string): Promise<IWebhookEndpoint> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst eid = this.requireId(endpointId, 'Endpoint ID');\n\t\treturn this.call('Failed to fetch webhook endpoint', () =>\n\t\t\tthis.http.get(`/accounts/${id}/webhooks/endpoints/${eid}`),\n\t\t);\n\t}\n\n\t/**\n\t * `PUT /accounts/{accountId}/webhooks/endpoints/{endpointId}` — update only\n\t * the fields sent. Enabling signing creates a secret when none exists;\n\t * disabling it discards the secret.\n\t */\n\tasync updateEndpoint(\n\t\tendpointId: string,\n\t\tpayload: IWebhookEndpointUpdatePayload,\n\t\taccountId?: string,\n\t): Promise<IWebhookEndpoint> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst eid = this.requireId(endpointId, 'Endpoint ID');\n\t\tif (!payload || typeof payload !== 'object' || Object.keys(payload).length === 0) {\n\t\t\tthrow new ValidationError('At least one webhook endpoint field is required');\n\t\t}\n\t\tvalidateWebhookFields(payload);\n\t\treturn this.call('Failed to update webhook endpoint', () =>\n\t\t\tthis.http.put(`/accounts/${id}/webhooks/endpoints/${eid}`, payload),\n\t\t);\n\t}\n\n\t/** `DELETE /accounts/{accountId}/webhooks/endpoints/{endpointId}` — delete an endpoint and free its slot. */\n\tasync deleteEndpoint(endpointId: string, accountId?: string): Promise<IEmptyResult> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst eid = this.requireId(endpointId, 'Endpoint ID');\n\t\treturn this.call('Failed to delete webhook endpoint', () =>\n\t\t\tthis.http.delete(`/accounts/${id}/webhooks/endpoints/${eid}`),\n\t\t);\n\t}\n\n\t/** Delete the endpoint whose URL exactly matches `url`; returns 404 when none matches. */\n\tasync deleteEndpointByUrl(url: string, accountId?: string): Promise<IEmptyResult> {\n\t\tif (!url) throw new ValidationError('Webhook URL is required');\n\t\tvalidateWebhookFields({ url });\n\t\tconst id = this.accountId(accountId);\n\t\treturn this.call('Failed to delete webhook endpoint by URL', () =>\n\t\t\tthis.http.delete(`/accounts/${id}/webhooks/endpoints`, { params: { url } }),\n\t\t);\n\t}\n\n\t/**\n\t * `GET …/endpoints/{endpointId}/secret` — the `whsec_` signing secret.\n\t * Returns `400` when signing is disabled. Not available to OAuth applications.\n\t */\n\tasync getEndpointSecret(endpointId: string, accountId?: string): Promise<IWebhookEndpointSecret> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst eid = this.requireId(endpointId, 'Endpoint ID');\n\t\treturn this.call('Failed to fetch webhook endpoint secret', () =>\n\t\t\tthis.http.get(`/accounts/${id}/webhooks/endpoints/${eid}/secret`),\n\t\t);\n\t}\n\n\t/**\n\t * `POST …/endpoints/{endpointId}/secret/rotate` — replace the signing secret.\n\t * The old secret stops working immediately. Not available to OAuth applications.\n\t */\n\tasync rotateEndpointSecret(\n\t\tendpointId: string,\n\t\taccountId?: string,\n\t): Promise<IWebhookEndpointSecret> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst eid = this.requireId(endpointId, 'Endpoint ID');\n\t\tthis.logger.info('Rotating webhook endpoint secret');\n\t\treturn this.call('Failed to rotate webhook endpoint secret', () =>\n\t\t\tthis.http.post(`/accounts/${id}/webhooks/endpoints/${eid}/secret/rotate`),\n\t\t);\n\t}\n\n\t/** List currently supported webhook event types. */\n\tasync listEventTypes(): Promise<IWebhookEventTypeInfo[]> {\n\t\treturn this.call('Failed to list webhook event types', () =>\n\t\t\tthis.http.get('/webhooks/event-types'),\n\t\t);\n\t}\n\n\t/** List webhook delivery history for the workspace, optionally for one endpoint. */\n\tasync listDispatches(\n\t\tparams: IWebhookDispatchListParams = {},\n\t\taccountId?: string,\n\t): Promise<PaginatedResult<IWebhookDispatch>> {\n\t\tconst id = this.accountId(accountId);\n\t\tif ('search' in params) throw new ValidationError('webhook dispatch search is not supported');\n\t\trequireSort(params.sort, ['created_at', '-created_at']);\n\t\treturn this.callList<IWebhookDispatch>('Failed to list webhook dispatches', () =>\n\t\t\tthis.http.get(`/accounts/${id}/webhooks`, {\n\t\t\t\tparams: cleanParams(params as unknown as Record<string, unknown>),\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** Retry delivery of a specific webhook dispatch to that entry's endpoint. */\n\tasync retryDispatch(dispatchId: string, accountId?: string): Promise<IWebhookDispatch> {\n\t\tconst id = this.accountId(accountId);\n\t\tconst did = this.requireId(dispatchId, 'Dispatch ID');\n\t\treturn this.call('Failed to retry webhook dispatch', () =>\n\t\t\tthis.http.post(`/accounts/${id}/webhooks/${did}/retry`),\n\t\t);\n\t}\n}\n","import { ValidationError } from '../errors.js';\nimport type {\n\tIAccountTheme,\n\tICreateWorkspacePayload,\n\tIDocumentStatsParams,\n\tIDocumentStatsRow,\n\tIEmptyResult,\n\tIStatusResponse,\n\tIUpdateWorkspacePayload,\n\tIUploadAccountLogoOptions,\n\tIWorkspaceListItem,\n\tIWorkspaceListResponse,\n\tIWorkspaceResponse,\n} from '../types.js';\nimport { appendFilePart, documentStatsParams } from '../utils.js';\nimport { BaseResource } from './base.js';\n\nexport class WorkspaceResource extends BaseResource {\n\t/** Create a new workspace. */\n\tasync create(payload: ICreateWorkspacePayload): Promise<IWorkspaceResponse> {\n\t\tif (!payload.name?.trim()) {\n\t\t\tthrow new ValidationError('Workspace name is required');\n\t\t}\n\t\tvalidateNotificationSender(payload.notification_sender_type);\n\t\treturn this.call('Failed to create workspace', () => this.http.post('/accounts', payload));\n\t}\n\n\t/** List workspaces the authenticated user can access. */\n\tasync list(): Promise<IWorkspaceListResponse> {\n\t\treturn this.callList<IWorkspaceListItem>('Failed to list workspaces', () =>\n\t\t\tthis.http.get('/accounts'),\n\t\t);\n\t}\n\n\t/** Fetch a single workspace. */\n\tasync get(accountId: string): Promise<IWorkspaceResponse> {\n\t\tconst id = this.requireId(accountId, 'Account ID');\n\t\treturn this.call('Failed to fetch workspace', () => this.http.get(`/accounts/${id}`));\n\t}\n\n\t/** Fetch the workspace's public branding theme. */\n\tasync getTheme(accountId: string): Promise<IAccountTheme> {\n\t\tconst id = this.requireId(accountId, 'Account ID');\n\t\treturn this.call('Failed to fetch workspace theme', () =>\n\t\t\tthis.http.get(`/accounts/${id}/theme`),\n\t\t);\n\t}\n\n\t/** Download the workspace logo image. */\n\tasync downloadLogo(accountId: string): Promise<Buffer> {\n\t\tconst id = this.requireId(accountId, 'Account ID');\n\t\treturn this.callBinary('Failed to download workspace logo', () =>\n\t\t\tthis.http.get<ArrayBuffer>(`/accounts/${id}/logo`, { responseType: 'arraybuffer' }),\n\t\t);\n\t}\n\n\t/** Upload or replace the workspace logo image. */\n\tasync uploadLogo(\n\t\taccountId: string,\n\t\tlogo: Buffer,\n\t\toptions: IUploadAccountLogoOptions = {},\n\t): Promise<IStatusResponse> {\n\t\tconst id = this.requireId(accountId, 'Account ID');\n\t\tif (!Buffer.isBuffer(logo) || logo.byteLength === 0) {\n\t\t\tthrow new ValidationError('Logo buffer is required');\n\t\t}\n\n\t\tconst contentType = options.contentType ?? 'image/png';\n\t\tconst form = new FormData();\n\t\tappendFilePart(form, logo, contentType, options.fileName ?? 'logo.png');\n\n\t\treturn this.call('Failed to upload workspace logo', () =>\n\t\t\tthis.http.post(`/accounts/${id}/logo`, form, {\n\t\t\t\theaders: { 'Content-Type': 'multipart/form-data' },\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** Delete the workspace logo. */\n\tasync deleteLogo(accountId: string): Promise<IStatusResponse> {\n\t\tconst id = this.requireId(accountId, 'Account ID');\n\t\treturn this.call('Failed to delete workspace logo', () =>\n\t\t\tthis.http.delete(`/accounts/${id}/logo`),\n\t\t);\n\t}\n\n\t/** Fetch monthly or daily document-funnel statistics for a workspace. */\n\tasync stats(accountId: string, params: IDocumentStatsParams = {}): Promise<IDocumentStatsRow[]> {\n\t\tconst id = this.requireId(accountId, 'Account ID');\n\t\treturn this.call('Failed to fetch workspace statistics', () =>\n\t\t\tthis.http.get(`/accounts/${id}/stats`, { params: documentStatsParams(params) }),\n\t\t);\n\t}\n\n\t/** Update a workspace. */\n\tasync update(accountId: string, payload: IUpdateWorkspacePayload): Promise<IWorkspaceResponse> {\n\t\tconst id = this.requireId(accountId, 'Account ID');\n\t\tvalidateNotificationSender(payload.notification_sender_type);\n\t\treturn this.call('Failed to update workspace', () => this.http.put(`/accounts/${id}`, payload));\n\t}\n\n\t/**\n\t * Delete a workspace.\n\t *\n\t * By default fails with `ApiError` (400) if the workspace has an active\n\t * paid subscription; pass `{ force: true }` to cancel it and delete anyway.\n\t */\n\tasync delete(accountId: string, options: { force?: boolean } = {}): Promise<IEmptyResult> {\n\t\tconst id = this.requireId(accountId, 'Account ID');\n\t\treturn this.call('Failed to delete workspace', () =>\n\t\t\tthis.http.delete(`/accounts/${id}`, options.force ? { data: { force: true } } : undefined),\n\t\t);\n\t}\n}\n\nfunction validateNotificationSender(value: string | undefined): void {\n\tif (value !== undefined && value !== 'User' && value !== 'Account') {\n\t\tthrow new ValidationError('notification_sender_type must be User or Account');\n\t}\n}\n","import { createHmac, timingSafeEqual } from 'node:crypto';\nimport type { IWebhookPayload } from '../types.js';\n\n/** Options for the legacy {@link WebhookVerifier.verify} body-only HMAC. */\nexport interface WebhookVerifierOptions {\n\t/** HMAC hash algorithm. Defaults to `sha256`. */\n\talgorithm?: string;\n\t/** Digest encoding of the signature value. Defaults to `hex`. */\n\tencoding?: 'hex' | 'base64';\n}\n\n/** Request headers as Node (`IncomingHttpHeaders`), a plain record, or a Fetch `Headers`. */\nexport type WebhookHeaders = Headers | Record<string, string | string[] | undefined>;\n\n/** Options for {@link WebhookVerifier.verifyDelivery}. */\nexport interface WebhookDeliveryOptions {\n\t/** Maximum clock difference accepted for `webhook-timestamp`. Defaults to 300 seconds. */\n\ttoleranceSeconds?: number;\n\t/** Current time in milliseconds. Defaults to `Date.now()`. */\n\tnow?: number;\n}\n\n/** Case-insensitive single-value header lookup; repeated headers are rejected. */\nfunction readHeader(headers: WebhookHeaders, name: string): string | undefined {\n\tif (typeof (headers as Headers).get === 'function') {\n\t\treturn (headers as Headers).get(name) ?? undefined;\n\t}\n\tconst matches = Object.entries(headers).filter(([key]) => key.toLowerCase() === name);\n\tif (matches.length !== 1) return undefined;\n\tconst value = matches[0]?.[1];\n\treturn Array.isArray(value) ? (value.length === 1 ? value[0] : undefined) : value;\n}\n\n/**\n * Verifies Assinafy webhook deliveries and parses their JSON envelope.\n *\n * Endpoints with `signing_enabled: true` sign each delivery following the\n * Standard Webhooks specification: `webhook-signature` carries one or more\n * space-separated `v1,<base64>` HMAC-SHA256 values over\n * `{webhook-id}.{webhook-timestamp}.{raw body}`, keyed with the base64 part of\n * the endpoint's `whsec_` secret. Use {@link verifyDelivery} with the raw\n * request body and headers; deduplicate accepted deliveries by `webhook-id`.\n */\nexport class WebhookVerifier {\n\tprivate readonly algorithm: string;\n\tprivate readonly encoding: 'hex' | 'base64';\n\n\tconstructor(\n\t\tprivate readonly webhookSecret?: string,\n\t\toptions: WebhookVerifierOptions = {},\n\t) {\n\t\tthis.algorithm = options.algorithm ?? 'sha256';\n\t\tthis.encoding = options.encoding ?? 'hex';\n\t}\n\n\t/**\n\t * Returns `true` when `headers` carry a Standard Webhooks signature that\n\t * matches the raw `payload` under this verifier's `whsec_` secret and the\n\t * `webhook-timestamp` is within the tolerance window. Pass the body exactly\n\t * as received; re-serialized JSON does not verify.\n\t */\n\tverifyDelivery(\n\t\tpayload: string | Buffer,\n\t\theaders: WebhookHeaders,\n\t\toptions: WebhookDeliveryOptions = {},\n\t): boolean {\n\t\tif (!this.webhookSecret || !headers) return false;\n\t\tconst id = readHeader(headers, 'webhook-id');\n\t\tconst timestamp = readHeader(headers, 'webhook-timestamp');\n\t\tconst signatures = readHeader(headers, 'webhook-signature');\n\t\tif (!id || !timestamp || !signatures || !/^\\d+$/.test(timestamp)) return false;\n\n\t\tconst tolerance = options.toleranceSeconds ?? 300;\n\t\tconst now = Math.floor((options.now ?? Date.now()) / 1000);\n\t\tif (\n\t\t\t!Number.isFinite(tolerance) ||\n\t\t\ttolerance < 0 ||\n\t\t\t!Number.isSafeInteger(now) ||\n\t\t\tnow < 0 ||\n\t\t\t!Number.isSafeInteger(Number(timestamp)) ||\n\t\t\tMath.abs(now - Number(timestamp)) > tolerance\n\t\t)\n\t\t\treturn false;\n\n\t\tconst secret = this.webhookSecret.startsWith('whsec_')\n\t\t\t? this.webhookSecret.slice('whsec_'.length)\n\t\t\t: this.webhookSecret;\n\t\tconst key = Buffer.from(secret, 'base64');\n\t\tif (key.length === 0) return false;\n\t\tconst expected = Buffer.from(\n\t\t\tcreateHmac('sha256', key)\n\t\t\t\t.update(`${id}.${timestamp}.`)\n\t\t\t\t.update(typeof payload === 'string' ? Buffer.from(payload, 'utf8') : payload)\n\t\t\t\t.digest('base64'),\n\t\t);\n\n\t\treturn signatures.split(' ').some((entry) => {\n\t\t\tconst [version, value, extra] = entry.split(',');\n\t\t\tif (version !== 'v1' || !value || extra !== undefined) return false;\n\t\t\tconst provided = Buffer.from(value);\n\t\t\treturn provided.length === expected.length && timingSafeEqual(provided, expected);\n\t\t});\n\t}\n\n\t/**\n\t * Returns `true` if `signature` is an HMAC of `payload` keyed with the raw\n\t * secret string under the configured algorithm/encoding.\n\t *\n\t * @deprecated Assinafy signs deliveries with Standard Webhooks headers; use\n\t * {@link verifyDelivery}. Retained for existing callers.\n\t */\n\tverify(payload: string | Buffer, signature: string): boolean {\n\t\tif (!this.webhookSecret || !signature) return false;\n\t\ttry {\n\t\t\tconst buf = typeof payload === 'string' ? Buffer.from(payload, 'utf8') : payload;\n\t\t\tconst expected = createHmac(this.algorithm, this.webhookSecret)\n\t\t\t\t.update(buf)\n\t\t\t\t.digest(this.encoding);\n\t\t\tconst a = Buffer.from(expected, 'utf8');\n\t\t\tconst b = Buffer.from(signature.trim(), 'utf8');\n\t\t\tif (a.length !== b.length) return false;\n\t\t\treturn timingSafeEqual(a, b);\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/** Parse the raw webhook body into a JSON event envelope. */\n\textractEvent(payload: string | Buffer): IWebhookPayload | null {\n\t\ttry {\n\t\t\tconst text = typeof payload === 'string' ? payload : payload.toString('utf8');\n\t\t\tconst parsed = JSON.parse(text) as IWebhookPayload;\n\t\t\t// Only a JSON object is a valid envelope — reject arrays and primitives.\n\t\t\treturn parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/** Extract the event name (`event` or `type`) from an event envelope. */\n\tgetEventType(event: IWebhookPayload | null | undefined): string | null {\n\t\tif (!event || typeof event !== 'object') return null;\n\t\tconst e = event as IWebhookPayload & { type?: unknown };\n\t\tif (typeof e.event === 'string') return e.event;\n\t\treturn typeof e.type === 'string' ? e.type : null;\n\t}\n\n\t/**\n\t * Extract the event data from an event envelope.\n\t *\n\t * The per-event data may live under `payload`, `data`, or `object`; only a\n\t * non-array JSON object is returned.\n\t */\n\tgetEventData(event: IWebhookPayload | null | undefined): Record<string, unknown> {\n\t\tif (!event || typeof event !== 'object') return {};\n\t\tconst e = event as IWebhookPayload & { object?: Record<string, unknown> };\n\t\tfor (const candidate of [e.payload, e.data, e.object]) {\n\t\t\tif (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\t\treturn {};\n\t}\n}\n"],"mappings":";AAAA,OAAOA,YAAmC;;;ACCnC,IAAM,gBAAN,cAA4B,MAAM;AAAA,EACxB;AAAA,EAEhB,YACC,SACA,UAAmC,CAAC,GACpC,SACC;AACD,UAAM,SAAS,SAAS,UAAU,SAAY,EAAE,OAAO,QAAQ,MAAM,IAAI,MAAS;AAClF,SAAK,OAAO;AACZ,SAAK,UAAU;AAAA,EAChB;AACD;AAUO,IAAM,WAAN,MAAM,kBAAiB,cAAc;AAAA,EAC3B;AAAA,EACA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA,EAEhB,YACC,SACA,YACA,eAAwB,MACxB,SAMC;AACD,UAAM,SAAS,EAAE,YAAY,aAAa,GAAG,OAAO;AACpD,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,eAAe;AACpB,SAAK,kBAAkB,SAAS;AAChC,SAAK,aAAa,SAAS;AAC3B,SAAK,YAAY,SAAS;AAAA,EAC3B;AAAA,EAEA,OAAO,aACN,YACA,cACA,UAAmC,CAAC,GACzB;AACX,QAAI,OAAO,SAAS,YAAY,KAAK,wBAAwB,aAAa;AACzE,YAAM,QACL,OAAO,SAAS,YAAY,IAAI,eAAe,OAAO,KAAK,YAAY,GACtE,SAAS,MAAM;AACjB,UAAI;AACH,uBAAe,KAAK,MAAM,IAAI;AAAA,MAC/B,QAAQ;AACP,uBAAe;AAAA,MAChB;AAAA,IACD;AACA,UAAM,OAAQ,gBAAgB,CAAC;AAC/B,UAAM,aAAa,KAAK;AACxB,UAAM,WAAW,KAAK;AACtB,UAAM,cAAc,KAAK;AACzB,UAAM,UACL,OAAO,eAAe,YAAY,WAAW,SAAS,IACnD,aACA,OAAO,aAAa,WACnB,OAAO,gBAAgB,YAAY,YAAY,S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