-
-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathrollup.js
77 lines (63 loc) · 1.91 KB
/
rollup.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
const path = require('path')
const { parse: parseURL } = require('url')
const {
outputFile,
pathExists,
readFile,
HTTP_RE,
resolveURL
} = require('./utils')
const createHttpCache = require('./http-cache')
const { CACHE_DIR } = require('./constants')
const fetch = require('./fetch')
const PREFIX = '\0'
const removePrefix = id => id && id.replace(/^\0/, '')
const shouldLoad = id => {
return HTTP_RE.test(removePrefix(id))
}
module.exports = ({ reload, cacheDir = CACHE_DIR } = {}) => {
const DEPS_DIR = path.join(cacheDir, 'deps')
const HTTP_CACHE_FILE = path.join(cacheDir, 'requests.json')
const getFilePathFromURL = url => {
const { host, pathname, protocol } = parseURL(url)
// Where should this url be in the disk
return path.join(DEPS_DIR, protocol.replace(':', ''), host, pathname)
}
const httpCache = createHttpCache(HTTP_CACHE_FILE)
return {
name: 'http',
async resolveId(importee, importer) {
// We're importing from URL
if (HTTP_RE.test(importee)) {
return PREFIX + importee
}
// We're importing a file but the importer the a URL
// Then we should do
if (importer) {
importer = importer.replace(/^\0/, '')
if (HTTP_RE.test(importer)) {
return resolveURL(importer, importee)
}
}
},
async load(id) {
if (!shouldLoad(id)) return
id = removePrefix(id)
const url = await httpCache.get(id)
let file
if (url && !reload) {
file = getFilePathFromURL(url)
if (await pathExists(file)) {
return readFile(file, 'utf8')
}
}
// We have never requested this before
const res = await fetch(id)
file = getFilePathFromURL(res.url)
await httpCache.set(id, res.url)
const content = await res.buffer().then(buff => buff.toString('utf8'))
await outputFile(file, content, 'utf8')
return content
}
}
}