-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
1092 lines (891 loc) · 28 KB
/
index.js
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
/// <reference path="types.js" />
import fs from 'fs/promises'
import { createWriteStream, createReadStream, WriteStream, unlinkSync } from 'fs' // eslint-disable-line
import { createHash } from 'crypto'
import { basename, sep, resolve } from 'path'
import * as readline from 'node:readline/promises'
import assert from 'node:assert/strict'
import { Deflate } from 'pako'
import { globSync } from 'glob'
import BTree from 'sorted-btree'
import { Piscina } from 'piscina'
import Archiver from 'archiver'
import { v4 as uuidv4 } from 'uuid'
import { assertValidWACZSignatureFormat } from './utils/assertions.js'
import { PACKAGE_INFO } from './constants.js'
/**
* IDX to CDX ratio for ZipNum Shared Index.
* For X entries in the CDX, there will be 1 in the IDX.
* See: https://pywb.readthedocs.io/en/latest/manual/indexing.html#zipnum-sharded-index
* @constant
* @type {number}
*/
export const ZIP_NUM_SHARED_INDEX_LIMIT = 3000
/**
* Utility class allowing for merging multiple .warc / .warc.gz files into a single .wacz file.
*
* Usage:
* ```
* const archive = new WACZ({
* file: 'collection/*.warc.gz',
* output: 'collection.wacz'
* })
*
* await archive.process() // my-collection.wacz was written to disk.
* ```
*/
export class WACZ {
/** @type {Console} */
log = console
/**
* If `true`, enough information was provided for processing to go on.
* @type {boolean}
*/
ready = false
/**
* If `true`, this object has been consumed and should be discarded
*/
consumed = false
/**
* Worker pool for the `indexWARC` function.
* @type {?Piscina}
*/
indexWARCPool = null
/**
* From WACZOptions.input.
* @type {?string[]}
*/
input = null
/**
* From WACZOptions.output.
* @type {?string}
*/
output = null
/**
* From WACZOptions.detectPages.
* @type {boolean}
*/
detectPages = true
/**
* From WACZOptions.indexFromWARCs.
* @type {boolean}
*/
indexFromWARCs = true
/**
* From WACZOptions.url.
* @type {?string}
*/
url = null
/**
* From WACZOptions.ts.
* @type {?string}
*/
ts = new Date().toISOString()
/**
* From WACZOptions.title.
* @type {?string}
*/
title = null
/**
* From WACZOptions.description.
* @type {?string}
*/
description = null
/**
* From WACZOptions.signingUrl.
* @type {?string}
*/
signingUrl = null
/**
* From WACZOptions.signingToken.
* @type {?string}
*/
signingToken = null
/**
* Date at which datapackage.json was generated. Needed for signing.
* @type {?string}
*/
datapackageDate = null
/**
* From WACZOptions.datapackageExtras. Stringified.
* @type {?object}
*/
datapackageExtras = null
/**
* List of files detected from path provided in `file`.
* @type {string[]}
*/
WARCs = []
/**
* B-Tree in which the key is a CDXJ string and the value is a boolean.
* Used for "sorting on the go".
* @type {BTree}
*/
cdxTree = new BTree.default() // eslint-disable-line
/** @type {string[]} */
cdxArray = []
/** @type {string[]} */
idxArray = []
/**
* B-Tree in which the key is an url string and the value is WACZPage.
* Used for "sorting on the go".
* @type {BTree}
*/
pagesTree = new BTree.default() // eslint-disable-line
/** @type {WACZPage[]} */
pagesArray = []
/**
* All files added to the zip, with the exception of datapackage-digest.json, need to be referenced here.
* @type {WACZDatapackageResource[]}
*/
resources = []
/**
* Stream to output file. To be used by `this.archive`.
* @type {?WriteStream}
*/
outputStream = null
/**
* Writeable ZIP stream.
* @type {?Archiver}
*/
archiveStream = null
/**
* Path to directory of pages JSONL files to copy as-is into WACZ.
* @type {?string}
*/
pagesDir = null
/**
* Path to directory of CDXJ files to copy as-is into WACZ.
* @type {?string}
*/
cdxjDir = null
/**
* Path to directory of log files to copy into WACZ.
* @type {?string}
*/
logDir = null
/**
* @param {WACZOptions} options - See {@link WACZOptions} for details.
*/
constructor (options = {}) {
// Although non-blocking, options.log must be processed first
if (options?.log) {
this.log = options.log
if (typeof this.log.trace !== 'function' ||
typeof this.log.info !== 'function' ||
typeof this.log.warn !== 'function' ||
typeof this.log.error !== 'function'
) {
throw new Error('"log" must be compatible with the Console API.')
}
}
this.filterBlockingOptions(options)
this.filterNonBlockingOptions(options)
this.ready = true
}
/**
* Processes "blocking" options, which can't be skipped.
* @param {WACZOptions} options
* @returns {void}
*/
filterBlockingOptions = (options) => {
const log = this.log
// options.input
try {
if (!options?.input) {
throw new Error('`input` was not provided.')
}
this.input = []
// `input` can be a string or an array of strings
if (options.input.constructor.name === 'String') {
this.input.push(options.input)
} else if (options.input.constructor.name === 'Array') {
this.input.push(...options.input.map(path => String(path).trim()))
} else {
throw new Error('`input` must be a string or an array.')
}
for (const path of this.input) {
for (const file of globSync(path)) {
const filename = basename(file).toLowerCase()
if (!filename.endsWith('.warc') && !filename.endsWith('.warc.gz')) {
this.log.trace(`${file} found but ignored.`)
continue
}
this.WARCs.push(file)
}
}
if (this.WARCs.length < 1) {
throw new Error('No WARC found.')
}
} catch (err) {
log.trace(err)
throw new Error('"input" must be a valid path leading to at least 1 .warc or .warc.gz file.')
}
// options.output
try {
this.output = options?.output
? String(options.output).trim()
: `${process.env.PWD}${sep}archive.wacz`
// Path must end by `.wacz`
if (!this.output.toLocaleLowerCase().endsWith('.wacz')) {
throw new Error('"output" must end with .wacz.')
}
// Delete existing file, if any
try {
unlinkSync(this.output) // [!] We can't use async version here (constructor)
} catch (_err) { }
} catch (err) {
log.trace(err)
throw new Error('"output" must be a valid "*.wacz" path on which the program can write.')
}
}
/**
* Processes "non-blocking" options for which we automatically switch to defaults or skip.
* @param {WACZOptions} options
*/
filterNonBlockingOptions = (options) => {
const log = this.log
if (options?.detectPages === false) {
this.detectPages = false
}
if (options?.indexFromWARCs === false) {
this.indexFromWARCs = false
}
if (options?.pagesDir) {
this.detectPages = false
this.pagesDir = String(options?.pagesDir).trim()
}
if (options?.cdxjDir) {
this.detectPages = false
this.indexFromWARCs = false // Added here for clarity, but implied by calls to `this.addCDXJ()`
this.cdxjDir = String(options?.cdxjDir).trim()
}
if (options?.url) {
try {
new URL(options.url) // eslint-disable-line
this.url = options.url
} catch (_err) {
log.warn('"url" provided is invalid. Skipping.')
}
}
if (options?.ts) {
try {
const ts = new Date(options.ts).toISOString() // will throw if invalid
this.ts = ts
} catch (_err) {
log.warn('"ts" provided is invalid. Skipping.')
}
}
if (options?.title) {
this.title = String(options.title).trim()
}
if (options?.description) {
this.description = String(options.description).trim()
}
if (options?.signingUrl) {
try {
new URL(options.signingUrl) // eslint-disable-line
this.signingUrl = options.signingUrl
} catch (_err) {
log.warn('"signingUrl" provided is not a valid url. Skipping.')
}
}
if (options?.logDir) {
this.logDir = String(options?.logDir).trim()
}
if (options?.signingToken && this.signingUrl) {
this.signingToken = String(options.signingToken)
}
if (options?.datapackageExtras) {
try {
JSON.stringify(options.datapackageExtras)// will throw if invalid
this.datapackageExtras = options.datapackageExtras
} catch (_err) {
log.warn('"datapackageExtras" provided is not JSON-serializable object. Skipping.')
}
}
}
/**
* Convenience method: runs all the processing steps from start to finish.
* @param {boolean} [verbose=true] - If `true`, will log step-by-step progress.
* @returns {Promise<void>}
*/
process = async (verbose = true) => {
this.stateCheck()
const info = verbose ? this.log.info : () => {}
info(`${this.WARCs.length} WARC(s) to process`)
info(`Initializing output stream at: ${this.output}`)
this.initOutputStreams()
info('Initializing indexer')
this.initWorkerPool()
if (this.cdxjDir) {
info('Reading provided CDXJ files')
await this.readFromExistingCDXJ()
}
if (this.indexFromWARCs) {
info('Indexing WARCS')
await this.indexWARCs()
}
info('Harvesting sorted indexes from trees')
this.harvestArraysFromTrees()
info('Writing CDX to WACZ')
await this.writeIndexesToZip()
info('Writing pages.jsonl to WACZ')
if (!this.pagesDir) {
await this.writePagesToZip()
} else {
await this.copyPagesFilesToZip()
}
info('Writing WARCs to WACZ')
await this.writeWARCsToZip()
if (this.logDir) {
info('Writing logs to WACZ')
await this.writeLogsToZip()
}
info('Writing datapackage.json to WACZ')
await this.writeDatapackageToZip()
info('Writing datapackage-digest.json to WACZ')
if (this.signingUrl) {
info(`(Will request signature from: ${this.signingUrl})`)
}
await this.writeDatapackageDigestToZip()
info('Finalizing WACZ')
await this.finalize()
info('WACZ was finalized')
}
/**
* Checks:
* - If `this.ready` is true, throws otherwise.
* - If `this.consumed` is false, throws otherwise.
* @returns {void}
*/
stateCheck = () => {
if (this.ready !== true) {
throw new Error('Not enough information was provided for processing to start.')
}
if (this.consumed === true) {
throw new Error('This instance has been consumed and may only be kept in memory for reference purposes.')
}
}
/**
* Creates an Archiver instance which streams out to `this.output`.
* Will only run if needed (can be called multiple times).
* @returns {void}
*/
initOutputStreams = () => {
this.stateCheck()
if (!this.outputStream) {
this.outputStream = createWriteStream(this.output)
}
if (!this.archiveStream && this.outputStream) {
this.archiveStream = new Archiver('zip', { store: true })
this.archiveStream.pipe(this.outputStream)
}
}
/**
* Initializes the worker pool for the "indexWARC" function.
* @returns {void}
*/
initWorkerPool = () => {
this.stateCheck()
this.indexWARCPool = new Piscina({
filename: new URL('./workers/indexWARC.js', import.meta.url).href
})
}
/**
* Calls the 'indexWARC` worker on each entry of `this.WARCs` for parallel processing.
* Populates `this.cdxTree` and `this.pagesTree`.
*
* @returns {Promise<void>} - From Promise.all.
*/
indexWARCs = async () => {
this.stateCheck()
return await Promise.all(this.WARCs.map(async filename => {
const results = await this.indexWARCPool.run({ filename, detectPages: this.detectPages })
for (const value of results.cdx) {
this.cdxTree.setIfNotPresent(value, true)
}
for (const value of results.pages) {
this.pagesTree.setIfNotPresent(value.url, value)
}
}))
}
/**
* Extract sorted CDX and pages list and clears up associated trees.
* @returns {void}
*/
harvestArraysFromTrees = () => {
this.stateCheck()
this.cdxArray = this.cdxTree.keysArray()
this.cdxTree.clear()
this.pagesArray = this.pagesTree.valuesArray()
this.pagesTree.clear()
}
/**
* Creates index files out of `this.cdxArray` and writes them to ZIP.
* Uses Zip Num Shared Index if there are more than ZIP_NUM_SHARED_INDEX_LIMIT entries in CDX:
* - This will result in two files (index.cdx.gz, index.idx), instead of a simple index.cdx.
* @returns {Promise<void>}
*/
writeIndexesToZip = async () => {
this.stateCheck()
const { cdxArray, idxArray, addFileToZip, log } = this
let cdx = Buffer.alloc(0)
let idxOffset = 0 // Used to for IDX metadata (IDX / CDX cross reference)
//
// Simple `index.cdx` if there is less than ZIP_NUM_SHARED_INDEX_LIMIT entries in CDX.
//
// index.cdx
if (cdxArray.length < ZIP_NUM_SHARED_INDEX_LIMIT) {
try {
for (const entry of cdxArray) {
cdx = Buffer.concat([cdx, Buffer.from(entry)])
}
await addFileToZip(cdx, 'indexes/index.cdx')
return
} catch (err) {
log.trace(err)
throw new Error('An error occurred while generating "indexes/index.cdx".')
}
}
//
// Use ZipNum Shared index for large CDXes (`index.cdx.gz` + `index.idx`)
//
// index.cdx.gz
try {
// Process CDX entries by group of ZIP_NUM_SHARED_INDEX_LIMIT for ZipNum Shared Indexing.
for (let i = 0; i < cdxArray.length; i += ZIP_NUM_SHARED_INDEX_LIMIT) {
let upperBound = null
let cdxSlice = null
let cdxSliceGzipped = null
let idxForSlice = null
let idxMeta = {}
// Cut a slice in cdxArray of ZIP_NUM_SHARED_INDEX_LIMIT length
upperBound = i + ZIP_NUM_SHARED_INDEX_LIMIT
if (upperBound > cdxArray.length) {
upperBound = cdxArray.length - 1
}
cdxSlice = cdxArray.slice(i, upperBound + 1).join('')
// Deflate said slice
cdxSliceGzipped = this.gzip(cdxSlice)
// Prepare and append the first line of this slice to `this.idxArray`
idxForSlice = cdxArray[i]
idxMeta = {
offset: idxOffset,
length: cdxSliceGzipped.byteLength,
digest: await this.sha256(cdxSliceGzipped),
filename: 'index.cdx.gz'
} // The JSON part of this CDX line needs to be edited to reference the CDX file
idxOffset += cdxSliceGzipped.byteLength
// CDXJ elements are separated " ". We only need to replace the last and third (JSON)
idxArray.push(`${idxForSlice.split(' ').slice(0, 1).join(' ')} ${JSON.stringify(idxMeta)}\n`)
// Append gzipped CDX slice to the rest
cdx = Buffer.concat([cdx, cdxSliceGzipped])
}
await addFileToZip(cdx, 'indexes/index.cdx.gz')
} catch (err) {
log.trace(err)
throw new Error('An error occurred while generating "indexes/index.cdx.gz".')
}
// index.idx
try {
let idx = '!meta 0 {"format": "cdxj-gzip-1.0", "filename": "index.cdx.gz"}\n'
for (const entry of idxArray) {
idx += `${entry}`
}
await addFileToZip(Buffer.from(idx), 'indexes/index.idx')
} catch (err) {
log.trace(err)
throw new Error('An error occurred while generating "indexes/index.idx".')
}
}
/**
* Creates `pages.jsonl` out of `this.pagesArray` and writes it to ZIP.
* @returns {Promise<void>}
*/
writePagesToZip = async () => {
this.stateCheck()
const { pagesArray, log, addFileToZip } = this
try {
let pagesJSONL = '{"format": "json-pages-1.0", "id": "pages", "title": "All Pages"}\n'
for (const page of pagesArray) {
pagesJSONL += `${JSON.stringify(page)}\n`
}
await addFileToZip(Buffer.from(pagesJSONL), 'pages/pages.jsonl')
} catch (err) {
log.trace(err)
throw new Error('An error occurred while generating "pages/pages.jsonl".')
}
}
/**
* Copies pages.jsonl and extraPages.jsonl files in `this.pagesDir` into ZIP.
* @returns {Promise<void>}
*/
copyPagesFilesToZip = async () => {
this.stateCheck()
const { pagesDir, log, addFileToZip } = this
if (!pagesDir) {
throw new Error('Error copying pages files, no directory specified.')
}
const pagesFiles = await fs.readdir(pagesDir)
for (let i = 0; i < pagesFiles.length; i++) {
const filename = pagesFiles[i]
const filenameLower = filename.toLowerCase()
const pagesFile = resolve(this.pagesDir, filename)
// Ensure file is JSONL
if (!filenameLower.endsWith('.jsonl')) {
log.warn(`Pages: Skipping file ${basename(pagesFile)}: does not end with jsonl extension.`)
continue
}
let isValidJSONL = true
// Ensure file is valid JSONL
const rl = readline.createInterface({ input: createReadStream(pagesFile) })
let lineIndex = 0
for await (const line of rl) {
try {
const page = JSON.parse(line)
if (lineIndex === 0) {
assert(page.format)
assert(page.id)
} else {
assert(page.url)
assert(page.ts)
}
lineIndex++
} catch (err) {
isValidJSONL = false
log.trace(err)
log.warn(`Pages: Skipping file ${basename(pagesFile)}: not valid JSONL / page entry.`)
break
}
}
if (isValidJSONL) {
await addFileToZip(pagesFile, `pages/${filename}`)
}
}
}
/**
* Reads lines from CDXJ files in `this.cdxjDir` into cdxArray.
* @returns {Promise<void>}
*/
readFromExistingCDXJ = async () => {
this.stateCheck()
const { cdxjDir, log } = this
if (!cdxjDir) {
throw new Error('Error copying CDXJ files, no directory specified.')
}
const allowedExts = ['cdx', 'cdxj']
const cdxjFiles = await fs.readdir(cdxjDir)
for (const cdxjFile of cdxjFiles) {
const cdxjFilepath = resolve(cdxjDir, cdxjFile)
const ext = cdxjFilepath.toLowerCase().split('.').pop()
if (!allowedExts.includes(ext)) {
log.warn(`CDXJ: Skipping file ${cdxjFile}, not a CDXJ file`)
continue
}
log.info(`CDXJ: Reading entries from ${cdxjFile}`)
const rl = readline.createInterface({ input: createReadStream(cdxjFilepath) })
for await (const line of rl) {
this.addCDXJ(line + '\n')
}
}
}
/**
* Streams all the files listed in `this.WARCs` to the output ZIP.
* @returns {Promise<void>}
*/
writeWARCsToZip = async () => {
this.stateCheck()
const { WARCs, addFileToZip, log } = this
for (const warc of WARCs) {
try {
await addFileToZip(warc, `archive/${basename(warc)}`)
} catch (err) {
log.trace(err)
throw new Error(`An error occurred while writing "${warc}" to ZIP.`)
}
}
}
/**
* Streams all the files listed in `this.logDir` to the output ZIP.
* @returns {Promise<void>}
*/
writeLogsToZip = async () => {
this.stateCheck()
const { logDir, addFileToZip, log } = this
const allowedExts = ['log', 'txt']
const logFiles = await fs.readdir(logDir)
for (const logFile of logFiles) {
const logFilepath = resolve(this.logDir, logFile)
const ext = logFilepath.toLowerCase().split('.').pop()
if (!allowedExts.includes(ext)) {
log.warn(`Skipping log file ${logFile}, not in allowed extensions (txt, log).`)
continue
}
try {
await addFileToZip(logFilepath, `logs/${logFile}`)
} catch (err) {
log.trace(err)
throw new Error(`An error occurred while writing "${logFile}" to ZIP.`)
}
}
}
/**
* Creates `datapackage.json` out of `this.resources` and writes it to ZIP.
* @returns {Promise<void>}
*/
writeDatapackageToZip = async () => {
this.stateCheck()
const { addFileToZip, resources, log } = this
this.datapackageDate = new Date().toISOString()
try {
const datapackage = {
created: this.datapackageDate,
wacz_version: '1.1.1',
profile: 'data-package',
software: `${PACKAGE_INFO.name} ${PACKAGE_INFO.version}`,
resources
}
datapackage.title = this.title || 'WACZ'
datapackage.description = this.description || ''
if (this.url) {
datapackage.mainPageUrl = this.url
}
if (this.ts) {
datapackage.mainPageDate = this.ts
}
if (this.datapackageExtras) {
datapackage.extras = this.datapackageExtras
}
const output = Buffer.from(JSON.stringify(datapackage, null, 2))
await addFileToZip(output, 'datapackage.json')
} catch (err) {
log.trace(err)
throw new Error('An error occurred while generating "datapackage.json".')
}
}
/**
* Creates `datapackage-digest.json` and writes it to ZIP.
* @returns {Promise<void>}
*/
writeDatapackageDigestToZip = async () => {
this.stateCheck()
const { archiveStream, resources, log, signingUrl } = this
try {
const datapackageHash = (resources.find(entry => entry.name === 'datapackage.json')).hash
const digest = {
path: 'datapackage.json',
hash: datapackageHash
}
// Request signing from server if needed
if (signingUrl) {
try {
const signature = await this.requestSignature()
digest.signedData = signature
} catch (err) {
log.trace(err)
throw new Error('An error occured while signing "datapackage.json".')
}
}
const datapackageDigest = JSON.stringify(digest, null, 2)
archiveStream.append(datapackageDigest, { name: 'datapackage-digest.json' })
} catch (err) {
log.trace(err)
throw new Error('An error occurred while generating "datapackage-digest.json".')
}
}
/**
* Request signature for the current datapackage and checks its format.
* Expects the remote server to be authsign-compatible (https://github.com/webrecorder/authsign).
* @returns {Promise<object>} - Signature to data to be appended to the datapackage digest.
*/
requestSignature = async () => {
this.stateCheck()
const { resources, log, datapackageDate, signingUrl, signingToken } = this
const datapackageHash = (resources.find(entry => entry.name === 'datapackage.json')).hash
// Throw early if datapackage is not ready.
if (!datapackageDate || !datapackageHash) {
throw new Error('No datapackage to sign.')
}
/** @type {?Response} */
let response = null
/** @type {object} */
let signedData = null
// Request signature
try {
const body = JSON.stringify({
hash: datapackageHash,
created: datapackageDate
})
const headers = { 'Content-Type': 'application/json' }
if (signingToken) {
headers.Authorization = signingToken
}
response = await fetch(signingUrl, { method: 'POST', headers, body })
if (response?.status !== 200) {
throw new Error(`Server responded with HTTP ${response.status}.`)
}
} catch (err) {
log.trace(err)
throw new Error('WACZ Signature request failed.')
}
// Check signature data
try {
signedData = await response.json()
assertValidWACZSignatureFormat(signedData)
} catch (err) {
log.trace(err)
throw new Error('Server returned an invalid WACZ signature.')
}
return signedData
}
/**
* Finalizes ZIP file
* @returns {Promise<void>}
*/
finalize = async () => {
this.stateCheck()
// "Pinky Promise pattern"
let closeStreamResolve = null
const closeStreamPromise = new Promise(resolve => {
closeStreamResolve = resolve
})
this.outputStream.on('close', () => {
closeStreamResolve()
})
this.archiveStream.finalize()
await closeStreamPromise // Wait for file stream to close
this.consumed = true
}
/**
* Manually add an entry for pages.jsonl.
* Entries will be added to `this.pagesTree`.
* Calling this method automatically turns pages detection off.
* @param {string} url - Must be a valid url
* @param {?string} title
* @param {?string} ts - Must be parsable by Date().
* @returns {WACZPage}
*/
addPage = (url, title = null, ts = null) => {
this.stateCheck()
this.detectPages = false
/** @type {WACZPage} */
const page = { id: uuidv4().replaceAll('-', '') }
try {
new URL(url) // eslint-disable-line
page.url = url
} catch (_err) {
throw new Error('"url" must be a valid url.')
}
if (title) {
title = String(title).trim(0)
page.title = title
}
if (ts) {
try {
ts = new Date(ts).toISOString()
page.ts = ts
} catch (err) {
throw new Error('If provided, "ts" must be parsable by JavaScript\'s Date class.')
}
}
this.pagesTree.setIfNotPresent(page.url, page)
return page
}
/**
* Manually add a CDJX entry to `this.cdxTree`.
* Calling this method automatically turns indexing from WARCS off.
* @param {string} cdjx - CDJX as string
* @returns {Promise<void>}
*/
addCDXJ = (cdjx) => {
this.stateCheck()
this.indexFromWARCs = false
this.cdxTree.setIfNotPresent(cdjx, true)
}
/**
* Adds a file to the output ZIP stream.
* Automatically keeps trace of file in `this.resources` so it can be referenced in datapackage.json.
* Must be called before `writeDatapackageToZip()`.
* @param {string|Uint8Array} file - File to be added. Can be a path or a chunk of data.
* @param {string} destination - In-zip path and filename of this file. I.E: "extras/thing.zip"
* @returns {Promise<WACZDatapackageResource>} - What was added to `this.resources`
*/
addFileToZip = async (file, destination) => {
this.initOutputStreams() // Initializes output streams if needed.