-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
285 lines (235 loc) · 7.08 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
'use strict';
const {createGunzip} = require('zlib');
const {inspect} = require('util');
const {join} = require('path');
const {PassThrough, Transform} = require('stream');
const cancelablePump = require('cancelable-pump');
const Extract = require('tar-stream').extract;
const fsExtract = require('tar-fs').extract;
const gracefulFs = require('graceful-fs');
const inspectWithKind = require('inspect-with-kind');
const isPlainObj = require('is-plain-obj');
const isStream = require('is-stream');
const loadRequestFromCwdOrNpm = require('load-request-from-cwd-or-npm');
const Observable = require('zen-observable');
class InternalExtract extends Extract {
constructor(options) {
super();
this.cwd = options.cwd;
this.ignore = options.ignore;
this.observer = options.observer;
this.url = '';
this.responseHeaders = null;
this.responseBytes = 0;
}
emit(eventName, header, stream, originalNext) {
if (eventName !== 'entry') {
super.emit(eventName, header);
return;
}
if (this.ignore && this.ignore(join(this.cwd, join('/', header.name)), header)) {
stream.resume();
originalNext();
return;
}
super.emit('entry', header, stream, err => {
if (err) {
originalNext(err);
return;
}
this.observer.next({
entry: {
header,
bytes: header.size
},
response: {
url: this.url,
headers: this.responseHeaders,
bytes: this.responseBytes
}
});
originalNext();
});
}
}
const functionOptions = new Set(['ignore', 'map', 'mapStream']);
const priorRequestOption = {encoding: null};
const priorTarFsOption = {ignore: null};
function echo(val) {
return val;
}
const DEST_ERROR = 'Expected a path where downloaded tgz archive will be extracted';
const MAP_STREAM_ERROR = 'The function passed to `mapStream` option must return a stream';
const STRIP_ERROR = 'Expected `strip` option to be a non-negative integer (0, 1, ...) ' +
'that specifies how many leading components from file names will be stripped';
module.exports = function dlTgz(...args) {
const argLen = args.length;
if (argLen !== 2 && argLen !== 3) {
throw new RangeError(`Expected 2 or 3 arguments (<string>, <string>[, <Object>]), but got ${
argLen === 0 ? 'no' : argLen
} arguments instead.`);
}
const [url, dest] = args;
return new Observable(observer => {
if (typeof url !== 'string') {
throw new TypeError(`Expected a URL of tgz archive, but got ${inspect(url)}.`);
}
if (url.length === 0) {
throw new Error('Expected a URL of tgz archive, but got \'\' (empty string).');
}
if (typeof dest !== 'string') {
throw new TypeError(`${DEST_ERROR}, but got ${inspect(dest)}.`);
}
if (dest.length === 0) {
throw new Error(`${DEST_ERROR}, but got '' (empty string).`);
}
const options = argLen === 3 ? args[2] : {};
if (argLen === 3) {
if (!isPlainObj(options)) {
throw new TypeError(`Expected an object to specify \`dl-tgz\` options, but got ${inspect(options)}.`);
}
if (options.method) {
const formattedMethod = inspect(options.method);
if (formattedMethod.toLowerCase() !== '\'get\'') {
throw new (typeof options.method === 'string' ? Error : TypeError)(`Invalid \`method\` option: ${
formattedMethod
}. \`dl-tgz\` module is designed to download archive files. So it only supports the default request method "GET" and it cannot be overridden by \`method\` option.`);
}
}
for (const optionName of functionOptions) {
const val = options[optionName];
if (val !== undefined && typeof val !== 'function') {
throw new TypeError(`\`${optionName}\` option must be a function, but got ${
inspectWithKind(val)
}.`);
}
}
if (options.strip !== undefined) {
if (typeof options.strip !== 'number') {
throw new TypeError(`${STRIP_ERROR}, but got a non-number value ${inspect(options.strip)}.`);
}
if (!isFinite(options.strip)) {
throw new RangeError(`${STRIP_ERROR}, but got ${options.strip}.`);
}
if (options.strip > Number.MAX_SAFE_INTEGER) {
throw new RangeError(`${STRIP_ERROR}, but got a too large number.`);
}
if (options.strip < 0) {
throw new RangeError(`${STRIP_ERROR}, but got a negative number ${options.strip}.`);
}
if (!Number.isInteger(options.strip)) {
throw new Error(`${STRIP_ERROR}, but got a non-integer number ${options.strip}.`);
}
}
}
const extractStream = new InternalExtract({
cwd: dest,
ignore: options.ignore,
observer
});
const mapStream = options.mapStream || echo;
const fileStreams = [];
let ended = false;
let cancel;
const fsExtractStream = fsExtract(dest, {
extract: extractStream,
fs: gracefulFs,
strip: 1,
...options,
mapStream(fileStream, header) {
const newStream = mapStream(fileStream, header);
if (!isStream.readable(newStream)) {
fsExtractStream.emit(
'error',
new TypeError(`${MAP_STREAM_ERROR}${
isStream(newStream) ?
' that is readable, but returned a non-readable stream' :
`, but returned a non-stream value ${inspect(newStream)}`
}.`)
);
fileStreams.push(fileStream);
return new PassThrough();
}
let bytes = 0;
fileStreams.push(newStream);
if (header.size !== 0) {
observer.next({
entry: {header, bytes},
response: {
url: extractStream.url,
headers: extractStream.responseHeaders,
bytes: extractStream.responseBytes
}
});
}
return newStream.pipe(new Transform({
transform(chunk, encoding, cb) {
bytes += chunk.length;
if (bytes !== header.size) {
observer.next({
entry: {header, bytes},
response: {
url: extractStream.url,
headers: extractStream.responseHeaders,
bytes: extractStream.responseBytes
}
});
}
cb(null, chunk);
}
}));
},
...priorTarFsOption
});
(async () => {
try {
const request = await loadRequestFromCwdOrNpm();
if (ended) {
return;
}
cancel = cancelablePump([
request({url, ...options, ...priorRequestOption})
.on('response', function(response) {
if (response.statusCode < 200 || 299 < response.statusCode) {
this.emit('error', new Error(`${response.statusCode} ${response.statusMessage}`));
return;
}
if (typeof response.headers['content-length'] === 'string') {
response.headers['content-length'] = Number(response.headers['content-length']);
}
extractStream.url = response.request.uri.href;
extractStream.responseHeaders = response.headers;
}),
new Transform({
transform(chunk, encoding, cb) {
extractStream.responseBytes += chunk.length;
cb(null, chunk);
}
}),
createGunzip(),
fsExtractStream
], err => {
ended = true;
if (err) {
observer.error(err);
return;
}
observer.complete();
});
} catch (err) {
ended = true;
observer.error(err);
}
})();
return function cancelExtract() {
if (!cancel) {
ended = true;
return;
}
if (ended) {
return;
}
cancel();
};
});
};