| 119 | } |
| 120 | |
| 121 | export async function downloadExportFile( |
| 122 | file: ExportedFile, |
| 123 | outputdir: string | undefined, |
| 124 | overwrite: boolean |
| 125 | ): Promise<'downloaded' | 'skipped'> { |
| 126 | if (!file.url) { |
| 127 | throw new Error(`Exported file ${file.filename} has no download URL.`); |
| 128 | } |
| 129 | |
| 130 | const targetFilename = join(outputdir || '.', file.filename); |
| 131 | |
| 132 | if (!overwrite && existsSync(targetFilename)) { |
| 133 | return 'skipped'; |
| 134 | } |
| 135 | |
| 136 | const response = await fetch(file.url); |
| 137 | if (!response.ok) { |
| 138 | throw new Error(`Download failed for ${file.filename}: HTTP ${response.status}`); |
| 139 | } |
| 140 | if (!response.body) { |
| 141 | throw new Error(`Download failed for ${file.filename}: response body is empty.`); |
| 142 | } |
| 143 | |
| 144 | const writeStream = createWriteStream(targetFilename, { |
| 145 | flags: overwrite ? 'w' : 'wx' |
| 146 | }); |
| 147 | |
| 148 | await pipeline(Readable.fromWeb(response.body as unknown as NodeReadableStream), writeStream); |
| 149 | return 'downloaded'; |
| 150 | } |
| 151 | |
| 152 | async function waitForCompletion( |
| 153 | jobId: string, |