( apiBase: string, headers: Record<string, string>, params: Record<string, unknown>, userId: string, signal?: AbortSignal )
| 503 | } |
| 504 | |
| 505 | async function handleDownloadDocument( |
| 506 | apiBase: string, |
| 507 | headers: Record<string, string>, |
| 508 | params: Record<string, unknown>, |
| 509 | userId: string, |
| 510 | signal?: AbortSignal |
| 511 | ) { |
| 512 | const { envelopeId, documentId } = params |
| 513 | if (!envelopeId) { |
| 514 | return NextResponse.json({ success: false, error: 'envelopeId is required' }, { status: 400 }) |
| 515 | } |
| 516 | |
| 517 | const docId = (documentId as string) || 'combined' |
| 518 | |
| 519 | const response = await fetchDocusign( |
| 520 | `${apiBase}/envelopes/${(envelopeId as string).trim()}/documents/${docId}`, |
| 521 | { |
| 522 | headers: { Authorization: headers.Authorization }, |
| 523 | }, |
| 524 | signal |
| 525 | ) |
| 526 | |
| 527 | if (!response.ok) { |
| 528 | let errorText = '' |
| 529 | try { |
| 530 | errorText = await readResponseTextWithLimit(response, { |
| 531 | maxBytes: DEFAULT_MAX_ERROR_BODY_BYTES, |
| 532 | label: 'DocuSign document error response', |
| 533 | }) |
| 534 | } catch { |
| 535 | // ignore |
| 536 | } |
| 537 | return NextResponse.json( |
| 538 | { success: false, error: `Failed to download document: ${response.status} ${errorText}` }, |
| 539 | { status: response.status } |
| 540 | ) |
| 541 | } |
| 542 | |
| 543 | const contentType = response.headers.get('content-type') || 'application/pdf' |
| 544 | const contentDisposition = response.headers.get('content-disposition') || '' |
| 545 | let fileName = `document-${docId}.pdf` |
| 546 | |
| 547 | const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/) |
| 548 | if (filenameMatch) { |
| 549 | fileName = filenameMatch[1].replace(/['"]/g, '') |
| 550 | } |
| 551 | |
| 552 | const buffer = await readResponseToBufferWithLimit(response, { |
| 553 | maxBytes: MAX_DOCUSIGN_DOCUMENT_BYTES, |
| 554 | label: 'DocuSign document download', |
| 555 | }) |
| 556 | |
| 557 | const workspaceId = typeof params.workspaceId === 'string' ? params.workspaceId : undefined |
| 558 | const workflowId = typeof params.workflowId === 'string' ? params.workflowId : undefined |
| 559 | const executionId = typeof params.executionId === 'string' ? params.executionId : undefined |
| 560 | const legacyInlineContent = |
| 561 | buffer.length <= MAX_LEGACY_INLINE_DOCUMENT_BYTES |
| 562 | ? { base64Content: buffer.toString('base64') } |
no test coverage detected