This repository has been archived by the owner on Mar 5, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
createDownloader.ts
209 lines (193 loc) · 6.07 KB
/
createDownloader.ts
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
import {FetchResult} from '@pnpm/fetcher-base'
import createFetcher from 'fetch-from-npm-registry'
import createWriteStreamAtomic = require('fs-write-stream-atomic')
import {IncomingMessage} from 'http'
import mkdirp = require('mkdirp-promise')
import path = require('path')
import pathTemp = require('path-temp')
import retry = require('retry')
import rimraf = require('rimraf')
import ssri = require('ssri')
import unpackStream = require('unpack-stream')
import urlLib = require('url')
import {BadTarballError} from './errorTypes'
export interface HttpResponse {
body: string
}
export type DownloadFunction = (url: string, saveto: string, opts: {
auth?: {
scope: string,
token: string | undefined,
password: string | undefined,
username: string | undefined,
email: string | undefined,
auth: string | undefined,
alwaysAuth: string | undefined,
},
unpackTo: string,
registry?: string,
onStart?: (totalSize: number | null, attempt: number) => void,
onProgress?: (downloaded: number) => void,
ignore?: (filename: string) => boolean,
integrity?: string
generatePackageIntegrity?: boolean,
}) => Promise<FetchResult>
export interface NpmRegistryClient {
get: (url: string, getOpts: object, cb: (err: Error, data: object, raw: object, res: HttpResponse) => void) => void,
fetch: (url: string, opts: {auth?: object}, cb: (err: Error, res: IncomingMessage) => void) => void,
}
export default (
gotOpts: {
alwaysAuth: boolean,
registry: string,
// proxy
proxy?: string,
localAddress?: string,
// ssl
ca?: string,
cert?: string,
key?: string,
strictSSL?: boolean,
// retry
retry?: {
retries?: number,
factor?: number,
minTimeout?: number,
maxTimeout?: number,
randomize?: boolean,
},
userAgent?: string,
},
): DownloadFunction => {
const fetchFromNpmRegistry = createFetcher(gotOpts)
const retryOpts = {
retries: 2,
factor: 10,
minTimeout: 1e4, // 10 seconds
maxTimeout: 6e4, // 1 minute
...gotOpts.retry
}
return async function download (url: string, saveto: string, opts: {
auth?: {
scope: string,
token: string | undefined,
password: string | undefined,
username: string | undefined,
email: string | undefined,
auth: string | undefined,
alwaysAuth: string | undefined,
},
unpackTo: string,
registry?: string,
onStart?: (totalSize: number | null, attempt: number) => void,
onProgress?: (downloaded: number) => void,
ignore?: (filename: string) => boolean,
integrity?: string,
generatePackageIntegrity?: boolean,
}): Promise<FetchResult> {
await mkdirp(path.dirname(saveto))
// If a tarball is hosted on a different place than the manifest, only send
// credentials on `alwaysAuth`
const shouldAuth = opts.auth && (
opts.auth.alwaysAuth ||
!opts.registry ||
urlLib.parse(url).host === urlLib.parse(opts.registry).host
)
const op = retry.operation(retryOpts)
return new Promise<FetchResult>((resolve, reject) => {
op.attempt((currentAttempt) => {
fetch(currentAttempt)
.then(resolve)
.catch((err) => {
if (err.code === 'E403') {
reject(err)
return
}
if (op.retry(err)) {
return
}
reject(op.mainError())
})
})
})
async function fetch (currentAttempt: number): Promise<FetchResult> {
try {
const res = await fetchFromNpmRegistry(url, {auth: shouldAuth && opts.auth as any || undefined}) // tslint:disable-line
if (res.status !== 200) {
const err = new Error(`${res.status} ${res.statusText}: ${url}`)
// tslint:disable
err['code'] = `E${res.status}`
err['uri'] = url
err['response'] = res
// tslint:enable
throw err
}
const contentLength = res.headers.has('content-length') && res.headers.get('content-length')
const size = typeof contentLength === 'string'
? parseInt(contentLength, 10)
: null
if (opts.onStart) {
opts.onStart(size, currentAttempt)
}
const onProgress = opts.onProgress
let downloaded = 0
res.body.on('data', (chunk: Buffer) => {
downloaded += chunk.length
if (onProgress) onProgress(downloaded)
})
const writeStream = createWriteStreamAtomic(saveto)
return await new Promise<FetchResult>((resolve, reject) => {
const stream = res.body
.on('error', reject)
.pipe(writeStream)
.on('error', reject)
const tempLocation = pathTemp(opts.unpackTo)
Promise.all([
opts.integrity && ssri.checkStream(res.body, opts.integrity),
unpackStream.local(res.body, tempLocation, {
generateIntegrity: opts.generatePackageIntegrity,
ignore: opts.ignore,
}),
waitTillClosed({ stream, size, getDownloaded: () => downloaded, url }),
])
.then((vals) => resolve({ tempLocation, filesIndex: vals[1] }))
.catch((err) => {
rimraf(tempLocation, (err) => {
// Just ignoring this error
// A redundant stage folder won't break anything
})
reject(err)
})
})
} catch (err) {
err.attempts = currentAttempt
err.resource = url
throw err
}
}
}
}
function waitTillClosed (
opts: {
stream: NodeJS.ReadableStream,
size: null | number,
getDownloaded: () => number,
url: string,
},
) {
return new Promise((resolve, reject) => {
opts.stream.on('close', () => {
const downloaded = opts.getDownloaded()
if (opts.size !== null && opts.size !== downloaded) {
const err = new BadTarballError({
expectedSize: opts.size,
receivedSize: downloaded,
tarballUrl: opts.url,
})
reject(err)
return
}
resolve()
})
})
}