This repository has been archived by the owner on Dec 22, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
loader.js
112 lines (83 loc) · 2.55 KB
/
loader.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
const {readdir, createReadStream, createWriteStream} = require("fs")
const {basename, extname, dirname, join, parse} = require("path")
const {tmpdir} = require("os")
const promisify = require("@octetstream/promisify")
const spawn = require("./spawn")
const assign = Object.assign
const copy = (src, dest) => new Promise((resolve, reject) => {
createReadStream(src)
.pipe(createWriteStream(dest))
.on("error", reject)
.on("finish", resolve)
})
const rd = promisify(readdir)
const wasmGC = filename => new Promise((resolve, reject) => {
const onFulfilled = () => resolve(filename)
spawn("wasm-gc", [filename, filename]).then(onFulfilled, reject)
})
const wrap = filename => (`
module.exports = (() => {
const wasm = require("${filename}")
return fetch(wasm).then(r => r.arrayBuffer())
})()
`)
const rustc = ({name, filename}) => new Promise((resolve, reject) => {
const dest = `${join(tmpdir(), name)}.wasm`
const onFulfilled = () => resolve(dest)
return spawn("rustc", [
"+nightly",
"--target=wasm32-unknown-unknown",
"--crate-type=cdylib",
"-O",
filename,
"-o",
dest
]).then(onFulfilled, reject)
})
const cargo = ({filename}, ctx) => new Promise((resolve, reject) => {
const dest = `${join(tmpdir(), basename(dirname(filename)))}.wasm`
const buildPath = join(
dirname(filename), "target/wasm32-unknown-unknown/release"
)
const onCompiled = () => rd(buildPath)
function onDir(files) {
files = files.filter(file => extname(file) === ".wasm")
if (files.length === 0) {
return Promise.reject(
new Error(`There are no any .wasm files at build path ${buildPath}`)
)
}
return Promise.all(files.map(file => copy(join(buildPath, file), dest)))
}
function onFulfilled() {
ctx.addContextDependency(join(dirname(filename), "src"))
resolve(dest)
}
spawn("cargo", [
"+nightly",
"build",
`--manifest-path=${filename}`,
"--target=wasm32-unknown-unknown",
"--release"
])
.then(onCompiled)
.then(onDir)
.then(onFulfilled)
.catch(reject)
})
const compilers = {
rs: rustc,
toml: cargo
}
function rustLoader() {
const cb = this.async()
const filename = this.resourcePath
const path = assign({}, parse(filename), {filename})
const compiler = compilers[path.ext.slice(1)]
if (typeof compiler !== "function") {
return cb(new Error(`Unsupported file extension: ${path.ext}`))
}
const onFulfilled = res => cb(null, wrap(res))
compiler(path, this).then(wasmGC).then(onFulfilled).catch(cb)
}
module.exports = rustLoader