-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathassemblies.ts
More file actions
1987 lines (1726 loc) · 54.9 KB
/
assemblies.ts
File metadata and controls
1987 lines (1726 loc) · 54.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { randomUUID } from 'node:crypto'
import EventEmitter from 'node:events'
import fs from 'node:fs'
import fsp from 'node:fs/promises'
import path from 'node:path'
import process from 'node:process'
import type { Readable } from 'node:stream'
import { Writable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
import { setTimeout as delay } from 'node:timers/promises'
import { promisify } from 'node:util'
import { Command, Option } from 'clipanion'
import got from 'got'
import PQueue from 'p-queue'
import * as t from 'typanion'
import { z } from 'zod'
import { formatLintIssue } from '../../alphalib/assembly-linter.lang.en.ts'
import { tryCatch } from '../../alphalib/tryCatch.ts'
import type { StepsInput } from '../../alphalib/types/template.ts'
import type { CreateAssemblyParams, ReplayAssemblyParams } from '../../apiTypes.ts'
import { ensureUniqueCounterValue } from '../../ensureUniqueCounter.ts'
import type { LintFatalLevel } from '../../lintAssemblyInstructions.ts'
import { lintAssemblyInstructions } from '../../lintAssemblyInstructions.ts'
import type { CreateAssemblyOptions, Transloadit } from '../../Transloadit.ts'
import { lintingExamples } from '../docs/assemblyLintingExamples.ts'
import {
concurrencyOption,
deleteAfterProcessingOption,
inputPathsOption,
printUrlsOption,
recursiveOption,
reprocessStaleOption,
singleAssemblyOption,
validateSharedFileProcessingOptions,
watchOption,
} from '../fileProcessingOptions.ts'
import { formatAPIError, readCliInput } from '../helpers.ts'
import type { IOutputCtl } from '../OutputCtl.ts'
import type { NormalizedAssemblyResultFile, NormalizedAssemblyResults } from '../resultFiles.ts'
import { normalizeAssemblyResults } from '../resultFiles.ts'
import type { ResultUrlRow } from '../resultUrls.ts'
import { collectNormalizedResultUrlRows, printResultUrls } from '../resultUrls.ts'
import { readStepsInputFile } from '../stepsInput.ts'
import { ensureError, isErrnoException } from '../types.ts'
import { AuthenticatedCommand, UnauthenticatedCommand } from './BaseCommand.ts'
// --- From assemblies.ts: Schemas and interfaces ---
export interface AssemblyListOptions {
before?: string
after?: string
fields?: string[]
keywords?: string[]
pagesize?: number
}
export interface AssemblyGetOptions {
assemblies: string[]
}
interface AssemblyDeleteOptions {
assemblies: string[]
}
export interface AssemblyReplayOptions {
fields?: Record<string, string>
reparse?: boolean
steps?: string
notify_url?: string
assemblies: string[]
}
export interface AssemblyLintOptions {
steps?: string
template?: string
fatal?: LintFatalLevel
fix?: boolean
providedInput?: string
json?: boolean
}
function formatAssemblyReference({
assemblyId,
assemblyUrl,
}: {
assemblyId: string
assemblyUrl: string | null
}): string {
if (assemblyUrl != null) {
return `Assembly ID: ${assemblyId}, Assembly URL: ${assemblyUrl}`
}
return `Assembly ID: ${assemblyId}`
}
function parseTemplateFieldAssignments(
output: IOutputCtl,
fields: string[] | undefined,
): Record<string, string> | undefined {
if (fields == null || fields.length === 0) {
return undefined
}
const fieldsMap: Record<string, string> = {}
for (const field of fields) {
const eqIndex = field.indexOf('=')
if (eqIndex === -1) {
output.error(`invalid argument for --field: '${field}'`)
return undefined
}
const key = field.slice(0, eqIndex)
const value = field.slice(eqIndex + 1)
fieldsMap[key] = value
}
return fieldsMap
}
const AssemblySchema = z.object({
id: z.string(),
})
// --- Business logic functions (from assemblies.ts) ---
export function list(
output: IOutputCtl,
client: Transloadit,
{ before, after, fields, keywords, pagesize }: AssemblyListOptions,
): Promise<void> {
const assemblies = client.streamAssemblies({
fromdate: after,
todate: before,
keywords,
pagesize,
})
assemblies.on('readable', () => {
// Drain the stream, otherwise `end` may never fire.
// eslint-disable-next-line no-constant-condition
while (true) {
const assembly: unknown = assemblies.read()
if (assembly == null) return
const parsed = AssemblySchema.safeParse(assembly)
if (!parsed.success) continue
if (fields == null) {
output.print(parsed.data.id, assembly)
} else {
const assemblyRecord = assembly as Record<string, unknown>
output.print(fields.map((field) => assemblyRecord[field]).join(' '), assembly)
}
}
})
return new Promise<void>((resolve) => {
assemblies.on('end', resolve)
assemblies.on('close', resolve)
assemblies.on('error', (err: unknown) => {
output.error(formatAPIError(err))
resolve()
})
})
}
export async function get(
output: IOutputCtl,
client: Transloadit,
{ assemblies }: AssemblyGetOptions,
): Promise<void> {
for (const assembly of assemblies) {
await delay(1000)
const [err, result] = await tryCatch(client.getAssembly(assembly))
if (err) {
output.error(formatAPIError(err))
throw ensureError(err)
}
output.print(result, result)
}
}
async function deleteAssemblies(
output: IOutputCtl,
client: Transloadit,
{ assemblies }: AssemblyDeleteOptions,
): Promise<void> {
const promises = assemblies.map(async (assembly) => {
const [err] = await tryCatch(client.cancelAssembly(assembly))
if (err) {
output.error(formatAPIError(err))
}
})
await Promise.all(promises)
}
// Export with `delete` alias for tests (can't use `delete` as function name)
export { deleteAssemblies as delete }
export async function replay(
output: IOutputCtl,
client: Transloadit,
{ fields, reparse, steps, notify_url, assemblies }: AssemblyReplayOptions,
): Promise<void> {
if (steps) {
try {
await apiCall(await readStepsInputFile(steps))
} catch (err) {
const error = ensureError(err)
output.error(error.message)
}
} else {
await apiCall()
}
async function apiCall(stepsOverride?: StepsInput): Promise<void> {
const promises = assemblies.map(async (assembly) => {
const [err] = await tryCatch(
client.replayAssembly(assembly, {
reparse_template: reparse ? 1 : 0,
fields,
notify_url,
steps: stepsOverride as ReplayAssemblyParams['steps'],
}),
)
if (err) {
output.error(formatAPIError(err))
}
})
await Promise.all(promises)
}
}
export async function lint(
output: IOutputCtl,
client: Transloadit | null,
{ steps, template, fatal, fix, providedInput, json }: AssemblyLintOptions,
): Promise<number> {
let content: string | null
let isStdin: boolean
let inputPath: string | undefined
try {
;({
content,
isStdin,
path: inputPath,
} = await readCliInput({
inputPath: steps,
providedInput,
allowStdinWhenNoPath: true,
}))
} catch (error) {
output.error(ensureError(error).message)
return 1
}
if (content == null && template == null) {
output.error('assemblies lint requires --steps or stdin input unless --template is provided')
return 1
}
if (fix && content == null && template != null) {
output.error('assemblies lint --fix requires local instructions (stdin or --steps)')
return 1
}
let result: Awaited<ReturnType<typeof lintAssemblyInstructions>>
try {
if (template != null) {
if (!client) {
output.error('Missing client for template lookup')
return 1
}
result = await client.lintAssemblyInstructions({
assemblyInstructions: content ?? undefined,
templateId: template,
fatal,
fix,
})
} else {
result = await lintAssemblyInstructions({
assemblyInstructions: content ?? undefined,
fatal,
fix,
})
}
} catch (error) {
output.error(ensureError(error).message)
return 1
}
const issues = result.issues
if (fix && isStdin) {
if (result.fixedInstructions == null) {
output.error('No fixed output available.')
return 1
}
process.stdout.write(`${result.fixedInstructions}\n`)
for (const issue of issues) {
const line = formatLintIssue(issue)
if (issue.type === 'warning') output.warn(line)
else output.error(line)
}
return result.success ? 0 : 1
}
if (fix && inputPath && result.fixedInstructions != null) {
await fsp.writeFile(inputPath, result.fixedInstructions)
}
if (json) {
output.print({ ...result, issues }, result)
} else if (issues.length === 0) {
output.print('No issues found', result)
} else {
for (const issue of issues) {
output.print(formatLintIssue(issue), issue)
}
}
return result.success ? 0 : 1
}
// --- From assemblies-create.ts: Helper classes and functions ---
interface NodeWatcher {
on(event: 'error', listener: (err: Error) => void): void
on(event: 'close', listener: () => void): void
on(event: 'change', listener: (evt: string, filename: string) => void): void
on(event: string, listener: (...args: unknown[]) => void): void
close(): void
}
type NodeWatchFn = (path: string, options?: { recursive?: boolean }) => NodeWatcher
let nodeWatch: NodeWatchFn | undefined
async function getNodeWatch(): Promise<NodeWatchFn> {
if (!nodeWatch) {
const mod = (await import('node-watch')) as unknown as { default: NodeWatchFn }
nodeWatch = mod.default
}
return nodeWatch
}
// workaround for determining mime-type of stdin
const stdinWithPath = process.stdin as unknown as { path: string }
stdinWithPath.path = '/dev/stdin'
interface OutputPlan {
mtime: Date
path?: string
}
interface Job {
inputPath: string | null
out: OutputPlan | null
watchEvent?: boolean
}
type OutputPlanProvider = (inpath: string | null, indir?: string) => Promise<OutputPlan | null>
interface JobEmitterOptions {
allowOutputCollisions?: boolean
recursive?: boolean
outputPlanProvider: OutputPlanProvider
singleAssembly?: boolean
watch?: boolean
reprocessStale?: boolean
}
interface ReaddirJobEmitterOptions {
dir: string
recursive?: boolean
outputPlanProvider: OutputPlanProvider
topdir?: string
}
interface SingleJobEmitterOptions {
file: string
outputPlanProvider: OutputPlanProvider
}
interface WatchJobEmitterOptions {
file: string
recursive?: boolean
outputPlanProvider: OutputPlanProvider
}
interface StatLike {
isDirectory(): boolean
}
const fstatAsync = promisify(fs.fstat)
async function myStat(
stdioStream: NodeJS.ReadStream | NodeJS.WriteStream,
filepath: string,
): Promise<fs.Stats> {
if (filepath === '-') {
const stream = stdioStream as NodeJS.ReadStream & { fd: number }
return await fstatAsync(stream.fd)
}
return await fsp.stat(filepath)
}
function getJobInputPath(filepath: string): string {
const normalizedFile = path.normalize(filepath)
if (normalizedFile === '-') {
return stdinWithPath.path
}
return normalizedFile
}
function createInputUploadStream(filepath: string): Readable {
const instream = fs.createReadStream(filepath)
// Attach a no-op error handler to prevent unhandled errors if stream is destroyed
// before being consumed (e.g., due to output collision detection)
instream.on('error', () => {})
return instream
}
function createOutputPlan(pathname: string | undefined, mtime: Date): OutputPlan {
if (pathname == null) {
return {
mtime,
}
}
return {
mtime,
path: pathname,
}
}
async function createExistingPathOutputPlan(outputPath: string | undefined): Promise<OutputPlan> {
if (outputPath == null) {
return createOutputPlan(undefined, new Date(0))
}
const [, stats] = await tryCatch(fsp.stat(outputPath))
return createOutputPlan(outputPath, stats?.mtime ?? new Date(0))
}
function dirProvider(output: string): OutputPlanProvider {
return async (inpath, indir = process.cwd()) => {
if (inpath == null) {
return await createExistingPathOutputPlan(output)
}
if (inpath === '-') {
throw new Error('You must provide an input to output to a directory')
}
let relpath = path.relative(indir, inpath)
relpath = relpath.replace(/^(\.\.\/)+/, '')
const outpath = path.join(output, relpath)
return await createExistingPathOutputPlan(outpath)
}
}
function fileProvider(output: string): OutputPlanProvider {
return async (_inpath) => {
if (output === '-') {
return await createExistingPathOutputPlan(undefined)
}
return await createExistingPathOutputPlan(output)
}
}
function nullProvider(): OutputPlanProvider {
return async (_inpath) => null
}
async function downloadResultToFile(
resultUrl: string,
outPath: string,
signal: AbortSignal,
): Promise<void> {
await fsp.mkdir(path.dirname(outPath), { recursive: true })
const tempPath = path.join(
path.dirname(outPath),
`.${path.basename(outPath)}.${randomUUID()}.tmp`,
)
const outStream = fs.createWriteStream(tempPath)
outStream.on('error', () => {})
const [dlErr] = await tryCatch(pipeline(got.stream(resultUrl, { signal }), outStream))
if (dlErr) {
await fsp.rm(tempPath, { force: true })
throw dlErr
}
await fsp.rename(tempPath, outPath)
}
async function downloadResultToStdout(resultUrl: string, signal: AbortSignal): Promise<void> {
const stdoutStream = new Writable({
write(chunk, _encoding, callback) {
let settled = false
const finish = (err?: Error | null) => {
if (settled) return
settled = true
process.stdout.off('drain', onDrain)
process.stdout.off('error', onError)
callback(err ?? undefined)
}
const onDrain = () => finish()
const onError = (err: Error) => finish(err)
process.stdout.once('error', onError)
try {
if (process.stdout.write(chunk)) {
finish()
return
}
process.stdout.once('drain', onDrain)
} catch (err) {
finish(ensureError(err))
}
},
final(callback) {
callback()
},
})
await pipeline(got.stream(resultUrl, { signal }), stdoutStream)
}
function sanitizeResultName(value: string): string {
const base = path.basename(value)
return base.replaceAll('\\', '_').replaceAll('/', '_').replaceAll('\u0000', '')
}
async function ensureUniquePath(targetPath: string, reservedPaths: Set<string>): Promise<string> {
const parsed = path.parse(targetPath)
return await ensureUniqueCounterValue({
initialValue: targetPath,
isTaken: async (candidate) => {
if (reservedPaths.has(candidate)) {
return true
}
const [statErr] = await tryCatch(fsp.stat(candidate))
return statErr == null
},
reserve: (candidate) => {
reservedPaths.add(candidate)
},
nextValue: (counter) => path.join(parsed.dir, `${parsed.name}__${counter}${parsed.ext}`),
scope: reservedPaths,
})
}
function getResultFileName(file: NormalizedAssemblyResultFile): string {
return sanitizeResultName(file.name)
}
interface AssemblyDownloadTarget {
resultUrl: string
targetPath: string | null
}
const STALE_OUTPUT_GRACE_MS = 1000
function isMeaningfullyNewer(newer: Date, older: Date): boolean {
return newer.getTime() - older.getTime() > STALE_OUTPUT_GRACE_MS
}
async function buildDirectoryDownloadTargets({
allFiles,
baseDir,
groupByStep,
reservedPaths,
}: {
allFiles: NormalizedAssemblyResultFile[]
baseDir: string
groupByStep: boolean
reservedPaths: Set<string>
}): Promise<AssemblyDownloadTarget[]> {
await fsp.mkdir(baseDir, { recursive: true })
const targets: AssemblyDownloadTarget[] = []
for (const resultFile of allFiles) {
const targetDir = groupByStep ? path.join(baseDir, resultFile.stepName) : baseDir
await fsp.mkdir(targetDir, { recursive: true })
targets.push({
resultUrl: resultFile.url,
targetPath: await ensureUniquePath(
path.join(targetDir, getResultFileName(resultFile)),
reservedPaths,
),
})
}
return targets
}
function getSingleResultDownloadTarget(
allFiles: NormalizedAssemblyResultFile[],
targetPath: string | null,
): AssemblyDownloadTarget[] {
const first = allFiles[0]
const resultUrl = first?.url ?? null
if (resultUrl == null) {
return []
}
return [{ resultUrl, targetPath }]
}
async function resolveResultDownloadTargets({
hasDirectoryInput,
inPath,
inputs,
normalizedResults,
outputMode,
outputPath,
outputRoot,
outputRootIsDirectory,
reservedPaths,
singleAssembly,
}: {
hasDirectoryInput: boolean
inPath: string | null
inputs: string[]
normalizedResults: NormalizedAssemblyResults
outputMode?: 'directory' | 'file'
outputPath: string | null
outputRoot: string
outputRootIsDirectory: boolean
reservedPaths: Set<string>
singleAssembly?: boolean
}): Promise<AssemblyDownloadTarget[]> {
const { allFiles, entries } = normalizedResults
const shouldGroupByInput =
!singleAssembly && inPath != null && (hasDirectoryInput || inputs.length > 1)
const resolveDirectoryBaseDir = (): string => {
if (!shouldGroupByInput || inPath == null) {
return outputRoot
}
if (hasDirectoryInput && outputPath != null) {
const mappedRelative = path.relative(outputRoot, outputPath)
const mappedDir = path.dirname(mappedRelative)
const mappedStem = path.parse(mappedRelative).name
return path.join(outputRoot, mappedDir === '.' ? '' : mappedDir, mappedStem)
}
return path.join(outputRoot, path.parse(path.basename(inPath)).name)
}
if (!outputRootIsDirectory) {
if (allFiles.length > 1) {
if (outputPath == null) {
throw new Error('stdout can only receive a single result file')
}
throw new Error('file outputs can only receive a single result file')
}
return getSingleResultDownloadTarget(allFiles, outputPath)
}
if (singleAssembly) {
return await buildDirectoryDownloadTargets({
allFiles,
baseDir: outputRoot,
groupByStep: false,
reservedPaths,
})
}
if (outputMode === 'directory' || outputPath == null || inPath == null) {
return await buildDirectoryDownloadTargets({
allFiles,
baseDir: resolveDirectoryBaseDir(),
groupByStep: entries.length > 1,
reservedPaths,
})
}
if (allFiles.length === 1) {
return getSingleResultDownloadTarget(allFiles, outputPath)
}
return await buildDirectoryDownloadTargets({
allFiles,
baseDir: path.join(path.dirname(outputPath), path.parse(outputPath).name),
groupByStep: true,
reservedPaths,
})
}
async function shouldSkipStaleOutput({
inputPaths,
outputPath,
outputPlanMtime,
outputRootIsDirectory,
reprocessStale,
singleInputReference = 'output-plan',
}: {
inputPaths: string[]
outputPath: string | null
outputPlanMtime: Date
outputRootIsDirectory: boolean
reprocessStale?: boolean
singleInputReference?: 'input' | 'output-plan'
}): Promise<boolean> {
if (reprocessStale || outputPath == null || outputRootIsDirectory) {
return false
}
if (inputPaths.length === 0 || inputPaths.some((inputPath) => inputPath === stdinWithPath.path)) {
return false
}
const [outputErr, outputStat] = await tryCatch(fsp.stat(outputPath))
if (outputErr != null || outputStat == null) {
return false
}
if (inputPaths.length === 1) {
if (singleInputReference === 'output-plan') {
return isMeaningfullyNewer(outputStat.mtime, outputPlanMtime)
}
const [inputErr, inputStat] = await tryCatch(fsp.stat(inputPaths[0]))
if (inputErr != null || inputStat == null) {
return false
}
return isMeaningfullyNewer(outputStat.mtime, inputStat.mtime)
}
const inputStats = await Promise.all(
inputPaths.map(async (inputPath) => {
const [inputErr, inputStat] = await tryCatch(fsp.stat(inputPath))
if (inputErr != null || inputStat == null) {
return null
}
return inputStat
}),
)
if (inputStats.some((inputStat) => inputStat == null)) {
return false
}
return inputStats.every((inputStat) => {
return inputStat != null && isMeaningfullyNewer(outputStat.mtime, inputStat.mtime)
})
}
async function materializeAssemblyResults({
abortSignal,
hasDirectoryInput,
inPath,
inputs,
normalizedResults,
outputMode,
outputPath,
outputRoot,
outputRootIsDirectory,
outputctl,
reservedPaths,
singleAssembly,
}: {
abortSignal: AbortSignal
hasDirectoryInput: boolean
inPath: string | null
inputs: string[]
normalizedResults: NormalizedAssemblyResults
outputMode?: 'directory' | 'file'
outputPath: string | null
outputRoot: string | null
outputRootIsDirectory: boolean
outputctl: IOutputCtl
reservedPaths: Set<string>
singleAssembly?: boolean
}): Promise<void> {
if (outputRoot == null) {
return
}
const targets = await resolveResultDownloadTargets({
hasDirectoryInput,
inPath,
inputs,
normalizedResults,
outputMode,
outputPath,
outputRoot,
outputRootIsDirectory,
reservedPaths,
singleAssembly,
})
for (const { resultUrl, targetPath } of targets) {
outputctl.debug('DOWNLOADING')
const [dlErr] = await tryCatch(
targetPath == null
? downloadResultToStdout(resultUrl, abortSignal)
: downloadResultToFile(resultUrl, targetPath, abortSignal),
)
if (dlErr) {
if (dlErr.name === 'AbortError') {
continue
}
outputctl.error(dlErr.message)
throw dlErr
}
}
}
class MyEventEmitter extends EventEmitter {
protected hasEnded: boolean
constructor() {
super()
this.hasEnded = false
}
override emit(event: string | symbol, ...args: unknown[]): boolean {
if (this.hasEnded) return false
if (event === 'end' || event === 'error') {
this.hasEnded = true
return super.emit(event, ...args)
}
return super.emit(event, ...args)
}
}
class ReaddirJobEmitter extends MyEventEmitter {
constructor({ dir, recursive, outputPlanProvider, topdir = dir }: ReaddirJobEmitterOptions) {
super()
process.nextTick(() => {
this.processDirectory({
dir,
recursive,
outputPlanProvider,
topdir,
}).catch((err) => {
this.emit('error', err)
})
})
}
private async processDirectory({
dir,
recursive,
outputPlanProvider,
topdir,
}: ReaddirJobEmitterOptions & { topdir: string }): Promise<void> {
const files = await fsp.readdir(dir)
const pendingOperations: Promise<void>[] = []
for (const filename of files) {
const file = path.normalize(path.join(dir, filename))
pendingOperations.push(this.processFile({ file, recursive, outputPlanProvider, topdir }))
}
await Promise.all(pendingOperations)
this.emit('end')
}
private async processFile({
file,
recursive = false,
outputPlanProvider,
topdir,
}: {
file: string
recursive?: boolean
outputPlanProvider: OutputPlanProvider
topdir: string
}): Promise<void> {
const stats = await fsp.stat(file)
if (stats.isDirectory()) {
if (recursive) {
await new Promise<void>((resolve, reject) => {
const subdirEmitter = new ReaddirJobEmitter({
dir: file,
recursive,
outputPlanProvider,
topdir,
})
subdirEmitter.on('job', (job: Job) => this.emit('job', job))
subdirEmitter.on('error', (error: Error) => reject(error))
subdirEmitter.on('end', () => resolve())
})
}
} else {
const outputPlan = await outputPlanProvider(file, topdir)
this.emit('job', { inputPath: getJobInputPath(file), out: outputPlan })
}
}
}
class SingleJobEmitter extends MyEventEmitter {
constructor({ file, outputPlanProvider }: SingleJobEmitterOptions) {
super()
const normalizedFile = path.normalize(file)
outputPlanProvider(normalizedFile)
.then((outputPlan) => {
process.nextTick(() => {
this.emit('job', { inputPath: getJobInputPath(normalizedFile), out: outputPlan })
this.emit('end')
})
})
.catch((err: unknown) => {
process.nextTick(() => {
this.emit('error', ensureError(err))
})
})
}
}
class InputlessJobEmitter extends MyEventEmitter {
constructor({ outputPlanProvider }: { outputPlanProvider: OutputPlanProvider }) {
super()
process.nextTick(() => {
outputPlanProvider(null)
.then((outputPlan) => {
try {
this.emit('job', { inputPath: null, out: outputPlan })
} catch (err) {
this.emit('error', ensureError(err))
return
}
this.emit('end')
})
.catch((err: unknown) => {
this.emit('error', ensureError(err))
})
})
}
}
class NullJobEmitter extends MyEventEmitter {
constructor() {
super()
process.nextTick(() => this.emit('end'))
}
}
class WatchJobEmitter extends MyEventEmitter {
private watcher: NodeWatcher | null = null
constructor({ file, recursive, outputPlanProvider }: WatchJobEmitterOptions) {
super()
this.init({ file, recursive, outputPlanProvider }).catch((err) => {
this.emit('error', err)
})
// Clean up watcher on process exit signals
const cleanup = () => this.close()
process.once('SIGINT', cleanup)
process.once('SIGTERM', cleanup)
}
/** Close the file watcher and release resources */
close(): void {
if (this.watcher) {
this.watcher.close()
this.watcher = null
}
}
private async init({
file,
recursive,
outputPlanProvider,
}: WatchJobEmitterOptions): Promise<void> {
const stats = await fsp.stat(file)
const topdir = stats.isDirectory() ? file : undefined
const watchFn = await getNodeWatch()
this.watcher = watchFn(file, { recursive })
this.watcher.on('error', (err: Error) => {
this.close()
this.emit('error', err)
})
this.watcher.on('close', () => this.emit('end'))
this.watcher.on('change', (_evt: string, filename: string) => {