This repository has been archived by the owner on Jul 28, 2021. It is now read-only.
/
fetch-packument.js
71 lines (65 loc) · 2.04 KB
/
fetch-packument.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
'use strict'
const fetch = require('npm-registry-fetch')
const optCheck = require('pacote/lib/util/opt-check')
const BB = require('bluebird')
const LRU = require('lru-cache')
const CORGI_DOC = 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*'
const JSON_DOC = 'application/json'
module.exports = packument
function packument (name, opts) {
opts = optCheck(opts)
const registry = fetch.pickRegistry(name, opts)
const uri = registry.replace(/\/?$/, `/${name.replace(/[/]/g, '%2f')}`)
return fetchPackument(uri, name, registry, opts)
}
function fetchPackument (uri, spec, registry, opts) {
const mem = pickMem(opts)
if (mem && !opts.preferOnline && mem.has(uri)) {
return BB.resolve(mem.get(uri))
}
return fetch(uri, Object.assign({
headers: {
'pacote-req-type': 'packument',
'pacote-pkg-id': `registry:${spec}`,
accept: opts.fullMetadata ? JSON_DOC : CORGI_DOC
},
spec
}, opts, {
// Force integrity to null: we never check integrity hashes for manifests
integrity: null
})).then(res => res.json().then(packument => {
packument._cached = decodeURIComponent(res.headers.has('x-local-cache'))
packument._contentLength = +res.headers.get('content-length')
// NOTE - we need to call pickMem again because proxy
// objects get reused!
const mem = pickMem(opts)
if (mem) {
mem.set(uri, packument)
}
return packument
}))
}
const MEMO = new LRU({
length: m => m._contentLength,
max: 200 * 1024 * 1024, // 200MB
maxAge: 30 * 1000 // 30s
})
class ObjProxy {
get (key) { return this.obj[key] }
set (key, val) { this.obj[key] = val }
}
// This object is used synchronously and immediately, so
// we can safely reuse it instead of consing up new ones
const PROX = new ObjProxy()
function pickMem (opts) {
if (!opts || !opts.memoize) {
return MEMO
} else if (opts.memoize.get && opts.memoize.set) {
return opts.memoize
} else if (typeof opts.memoize === 'object') {
PROX.obj = opts.memoize
return PROX
} else {
return null
}
}