33 * SPDX-License-Identifier: Apache-2.0
44 */
55
6- import archiver from 'archiver'
76import { WritableStreamBuffer } from 'stream-buffers'
87import crypto from 'crypto'
9- import { getLogger } from '../logger'
8+ import { readFileAsString } from '../filesystemUtilities'
9+ // Use require instead of import since this package doesn't support commonjs
10+ const { ZipWriter, TextReader } = require ( '@zip.js/zip.js' )
1011
1112export interface ZipStreamResult {
1213 sizeInBytes : number
@@ -27,45 +28,41 @@ export interface ZipStreamResult {
2728 * ```
2829 */
2930export class ZipStream {
30- private _archive : archiver . Archiver
31+ // TypeScript compiler is confused about using ZipWriter as a type
32+ // @ts -ignore
33+ private _zipWriter : ZipWriter < WritableStream >
3134 private _streamBuffer : WritableStreamBuffer
3235 private _hasher : crypto . Hash
3336
3437 constructor ( ) {
35- this . _archive = archiver ( 'zip' )
3638 this . _streamBuffer = new WritableStreamBuffer ( )
37- this . _archive . pipe ( this . _streamBuffer )
3839 this . _hasher = crypto . createHash ( 'md5' )
3940
40- this . _archive . on ( 'data' , data => {
41- this . _hasher . update ( data )
42- } )
43- this . _archive . on ( 'error' , err => {
44- throw err
45- } )
46- this . _archive . on ( 'warning' , err => {
47- getLogger ( ) . warn ( err )
48- } )
41+ this . _zipWriter = new ZipWriter (
42+ new WritableStream ( {
43+ write : chunk => {
44+ this . _streamBuffer . write ( chunk )
45+ this . _hasher . update ( chunk )
46+ } ,
47+ } )
48+ )
4949 }
5050
51- public writeString ( data : string , path : string ) {
52- this . _archive . append ( Buffer . from ( data , 'utf-8' ) , { name : path } )
51+ public async writeString ( data : string , path : string ) {
52+ return this . _zipWriter . add ( path , new TextReader ( data ) )
5353 }
5454
55- public writeFile ( file : string , path : string ) {
56- this . _archive . file ( file , { name : path } )
55+ public async writeFile ( file : string , path : string ) {
56+ const content = await readFileAsString ( file )
57+ return this . _zipWriter . add ( path , new TextReader ( content ) )
5758 }
5859
59- public finalize ( ) : Promise < ZipStreamResult > {
60- return new Promise ( ( resolve , reject ) => {
61- void this . _archive . finalize ( )
62- this . _archive . on ( 'finish' , ( ) => {
63- resolve ( {
64- sizeInBytes : this . _archive . pointer ( ) ,
65- md5 : this . _hasher . digest ( 'base64' ) ,
66- streamBuffer : this . _streamBuffer ,
67- } )
68- } )
69- } )
60+ public async finalize ( ) : Promise < ZipStreamResult > {
61+ await this . _zipWriter . close ( )
62+ return {
63+ sizeInBytes : this . _streamBuffer . size ( ) ,
64+ md5 : this . _hasher . digest ( 'base64' ) ,
65+ streamBuffer : this . _streamBuffer ,
66+ }
7067 }
7168}
0 commit comments