@hunghg255/napi-zig-cli 1.6.0 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -3
- package/lib/artifacts.mjs +44 -7
- package/lib/browser-wasi.mjs +100 -0
- package/lib/wasm-memory.mjs +131 -0
- package/lib/wasm.mjs +189 -18
- package/package.json +1 -1
- package/template/browser.mjs.tmpl +12 -0
- package/template/package.json.tmpl +13 -2
package/README.md
CHANGED
|
@@ -35,8 +35,31 @@ too: `npm/wasm32-wasi/` holds `<name>.wasm32-wasi.wasm` and the loader
|
|
|
35
35
|
`@emnapi/runtime`, and installs on every platform; `wasm32-wasi-threads`
|
|
36
36
|
adds a worker script and `@emnapi/wasi-threads`. `index.js` tries the native
|
|
37
37
|
binary for the platform first, then `wasm32-wasi-threads`, then
|
|
38
|
-
`wasm32-wasi`.
|
|
39
|
-
(`wasm_initial_memory` / `wasm_max_memory`
|
|
40
|
-
`"napi": { "wasm": { "initialMemory": ..., "maxMemory": ... } }`
|
|
38
|
+
`wasm32-wasi`. The threaded loader reads the shared memory's bounds
|
|
39
|
+
(`wasm_initial_memory` / `wasm_max_memory` in `build.zig`) from the module
|
|
40
|
+
itself; `"napi": { "wasm": { "initialMemory": ..., "maxMemory": ... } }`
|
|
41
|
+
(bytes) still overrides them, but is no longer needed (1.7).
|
|
42
|
+
|
|
43
|
+
Browsers and bundlers (1.7; stable from 1.8): each wasm package also carries
|
|
44
|
+
`<name>.<target>.browser.mjs`, an ES module that fetches the `.wasm` with
|
|
45
|
+
`new URL('./<file>.wasm', import.meta.url)` (which webpack, Vite, Rollup and
|
|
46
|
+
Parcel turn into an asset), instantiates it on import and exports
|
|
47
|
+
`load(options)` for more instances (`wasm`, `wasi`, `context`; threaded also
|
|
48
|
+
`memory`, `reuseWorker`, `onCreateWorker`). The package's `exports` map
|
|
49
|
+
sends Node.js, Bun and Deno (condition `node`) to the CommonJS loader and
|
|
50
|
+
browsers and bundlers (`browser`, `import`) to the ES module. A minimal
|
|
51
|
+
WASI (console, clocks, random bytes, no files) is built in; pass a full one
|
|
52
|
+
as `wasi` if the addon needs it. The threaded flavour starts each thread as
|
|
53
|
+
a module worker (`<name>.<target>.browser-worker.mjs`), needs
|
|
54
|
+
`SharedArrayBuffer` - serve the page with `Cross-Origin-Opener-Policy:
|
|
55
|
+
same-origin` and `Cross-Origin-Embedder-Policy: require-corp` - and should
|
|
56
|
+
be imported in a worker, as the page's main thread may not block. New
|
|
57
|
+
projects get a `browser.mjs` that re-exports a wasm package and an
|
|
58
|
+
`exports` map that keeps Node.js on `index.js`; from 1.8 `artifacts` points
|
|
59
|
+
it at `wasm32-wasi` if that is in `napi.targets`, else at
|
|
60
|
+
`wasm32-wasi-threads` (a line edited by hand is left alone). Tested in Chromium
|
|
61
|
+
without a bundler; no bundler is tested yet (esbuild does not handle
|
|
62
|
+
`new Worker(new URL(...))`, so the threaded flavour needs a bundler that
|
|
63
|
+
does, or `load({ onCreateWorker })`).
|
|
41
64
|
|
|
42
65
|
The `zig` executable is taken from `PATH` (override with `NAPI_ZIG_ZIG`).
|
package/lib/artifacts.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { copyFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs'
|
|
1
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
2
2
|
import { join, resolve } from 'node:path'
|
|
3
3
|
import { loadProject } from './project.mjs'
|
|
4
4
|
import { binaryName, findTarget } from './targets.mjs'
|
|
5
|
-
import { EMNAPI_DEPENDENCIES, EMNAPI_THREADS_DEPENDENCIES,
|
|
5
|
+
import { EMNAPI_DEPENDENCIES, EMNAPI_THREADS_DEPENDENCIES, wasmLoaderFiles, wasmPackageEntries } from './wasm.mjs'
|
|
6
6
|
|
|
7
7
|
/** The npm package that carries the binary of one target. */
|
|
8
8
|
export function platformPackageName(pkg, id) {
|
|
@@ -26,13 +26,17 @@ export function packageFiles(project, target) {
|
|
|
26
26
|
* `npm install` downloads only the binary matching the user's machine.
|
|
27
27
|
*
|
|
28
28
|
* A WebAssembly target's package fits every machine (no `os` or `cpu`):
|
|
29
|
-
* it holds the `.wasm`, the loader that is its `main`
|
|
30
|
-
*
|
|
31
|
-
*
|
|
29
|
+
* it holds the `.wasm`, the Node.js loader that is its `main` and its
|
|
30
|
+
* "node" export, the browser loader (an ES module) that is its "browser"
|
|
31
|
+
* export (and, threaded, the worker script of each), and depends on
|
|
32
|
+
* emnapi. The generated index.js falls back to it where no native package
|
|
33
|
+
* fits; the generated browser.mjs imports it.
|
|
32
34
|
*
|
|
33
|
-
* npm/wasm32-wasi/package.json { main: "<name>.wasm32-wasi.cjs",
|
|
35
|
+
* npm/wasm32-wasi/package.json { main: "<name>.wasm32-wasi.cjs", exports: { node, browser, ... },
|
|
36
|
+
* dependencies: { "@emnapi/core", ... } }
|
|
34
37
|
* npm/wasm32-wasi/<name>.wasm32-wasi.wasm
|
|
35
38
|
* npm/wasm32-wasi/<name>.wasm32-wasi.cjs
|
|
39
|
+
* npm/wasm32-wasi/<name>.wasm32-wasi.browser.mjs
|
|
36
40
|
*/
|
|
37
41
|
export function artifacts(options) {
|
|
38
42
|
const project = loadProject(resolve(options.cwd ?? '.'))
|
|
@@ -55,7 +59,7 @@ export function artifacts(options) {
|
|
|
55
59
|
...(target.os ? { os: [target.os] } : {}),
|
|
56
60
|
...(target.cpu ? { cpu: target.cpu } : {}),
|
|
57
61
|
...(target.libc ? { libc: [target.libc] } : {}),
|
|
58
|
-
|
|
62
|
+
...(target.wasm ? wasmPackageEntries(addonName, target) : { main: binary }),
|
|
59
63
|
files: packageFiles(project, target),
|
|
60
64
|
...(target.wasm ? { dependencies: target.threads ? EMNAPI_THREADS_DEPENDENCIES : EMNAPI_DEPENDENCIES } : {}),
|
|
61
65
|
license: pkg.license,
|
|
@@ -79,8 +83,41 @@ export function artifacts(options) {
|
|
|
79
83
|
...Object.fromEntries(targets.map((id) => [platformPackageName(pkg, id), pkg.version])),
|
|
80
84
|
}
|
|
81
85
|
writeFileSync(project.packagePath, JSON.stringify(pkg, null, 2) + '\n')
|
|
86
|
+
const browser = updateBrowserEntry(project)
|
|
87
|
+
if (browser) console.log(`napi-zig: browser.mjs now loads ${browser}`)
|
|
82
88
|
|
|
83
89
|
for (const dir of created) console.log(`napi-zig: prepared ${dir}`)
|
|
84
90
|
for (const binary of missing) console.warn(`napi-zig: warning: ${binary} has not been built yet`)
|
|
85
91
|
return { created, missing }
|
|
86
92
|
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The WebAssembly flavour the browser entry should load, from
|
|
96
|
+
* "napi.targets": `wasm32-wasi` if it is built, else `wasm32-wasi-threads`
|
|
97
|
+
* (which needs a cross-origin isolated page), else none. (1.8)
|
|
98
|
+
*/
|
|
99
|
+
export function browserFlavour(targets) {
|
|
100
|
+
if (targets.includes('wasm32-wasi')) return 'wasm32-wasi'
|
|
101
|
+
if (targets.includes('wasm32-wasi-threads')) return 'wasm32-wasi-threads'
|
|
102
|
+
return null
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Points the project's browser.mjs, as `napi-zig new` wrote it (a re-export
|
|
107
|
+
* of one wasm package), at the flavour in "napi.targets". A browser.mjs
|
|
108
|
+
* changed by hand is left alone. Returns the package it now loads, if it
|
|
109
|
+
* changed.
|
|
110
|
+
*/
|
|
111
|
+
export function updateBrowserEntry(project) {
|
|
112
|
+
const path = join(project.dir, 'browser.mjs')
|
|
113
|
+
const flavour = browserFlavour(project.targets)
|
|
114
|
+
if (!flavour || !existsSync(path)) return null
|
|
115
|
+
const text = readFileSync(path, 'utf8')
|
|
116
|
+
const escaped = project.pkg.name.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')
|
|
117
|
+
const generated = new RegExp(`^export \\{ default, load \\} from '${escaped}-(wasm32-wasi(?:-threads)?)'$`, 'm')
|
|
118
|
+
const match = text.match(generated)
|
|
119
|
+
if (!match || match[1] === flavour) return null
|
|
120
|
+
const target = platformPackageName(project.pkg, flavour)
|
|
121
|
+
writeFileSync(path, text.replace(generated, `export { default, load } from '${target}'`))
|
|
122
|
+
return target
|
|
123
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// A minimal WASI (preview 1) for browsers, used by the browser loaders that
|
|
2
|
+
// `napi-zig build` writes for WebAssembly targets.
|
|
3
|
+
//
|
|
4
|
+
// napi-zig modules import nothing from WASI unless the addon itself does
|
|
5
|
+
// I/O through the standard library (printing, randomness, clocks); this
|
|
6
|
+
// gives such an addon a console for stdout/stderr, the clocks, random
|
|
7
|
+
// bytes, empty argv/environ, and ENOSYS for everything else - enough for
|
|
8
|
+
// `std.debug.print`, `std.crypto.random` and timers, not for files. Pass a
|
|
9
|
+
// full implementation (e.g. `new WASI(...)` from @tybys/wasm-util) as the
|
|
10
|
+
// loader's `wasi` option for more.
|
|
11
|
+
//
|
|
12
|
+
// `createBrowserWasi` is embedded verbatim (through Function.prototype
|
|
13
|
+
// .toString) in the generated loaders, so it must stay self-contained.
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* `{ wasiImport, initialize(instance) }`, the shape emnapi expects.
|
|
17
|
+
* `options.memory`: the module's memory, if it imports it (threads);
|
|
18
|
+
* otherwise `initialize` picks up the exported one. `options.child`: a
|
|
19
|
+
* wasm thread's instance, which must not run the module's initializer.
|
|
20
|
+
*/
|
|
21
|
+
export function createBrowserWasi(options = {}) {
|
|
22
|
+
let memory = options.memory ?? null
|
|
23
|
+
const SUCCESS = 0
|
|
24
|
+
const EBADF = 8
|
|
25
|
+
const ENOSYS = 52
|
|
26
|
+
const view = () => new DataView(memory.buffer)
|
|
27
|
+
const pending = { 1: '', 2: '' }
|
|
28
|
+
const decoders = { 1: new TextDecoder(), 2: new TextDecoder() }
|
|
29
|
+
const flush = (fd, all) => {
|
|
30
|
+
const text = pending[fd]
|
|
31
|
+
const cut = all ? text.length : text.lastIndexOf('\n') + 1
|
|
32
|
+
if (cut === 0) return
|
|
33
|
+
for (const line of text.slice(0, cut).replace(/\n$/, '').split('\n')) (fd === 1 ? console.log : console.error)(line)
|
|
34
|
+
pending[fd] = text.slice(cut)
|
|
35
|
+
}
|
|
36
|
+
const nanoseconds = (id) =>
|
|
37
|
+
id === 0 ? BigInt(Date.now()) * 1000000n : BigInt(Math.round((performance.timeOrigin + performance.now()) * 1e6))
|
|
38
|
+
const sizes = (count, size) => {
|
|
39
|
+
const v = view()
|
|
40
|
+
v.setUint32(count, 0, true)
|
|
41
|
+
v.setUint32(size, 0, true)
|
|
42
|
+
return SUCCESS
|
|
43
|
+
}
|
|
44
|
+
const wasiImport = {
|
|
45
|
+
args_sizes_get: sizes,
|
|
46
|
+
args_get: () => SUCCESS,
|
|
47
|
+
environ_sizes_get: sizes,
|
|
48
|
+
environ_get: () => SUCCESS,
|
|
49
|
+
clock_res_get(id, out) {
|
|
50
|
+
view().setBigUint64(out, 1000n, true)
|
|
51
|
+
return SUCCESS
|
|
52
|
+
},
|
|
53
|
+
clock_time_get(id, precision, out) {
|
|
54
|
+
view().setBigUint64(out, nanoseconds(id), true)
|
|
55
|
+
return SUCCESS
|
|
56
|
+
},
|
|
57
|
+
random_get(buffer, length) {
|
|
58
|
+
// (getRandomValues takes at most 64 KiB, and no shared memory.)
|
|
59
|
+
for (let done = 0; done < length; done += 65536) {
|
|
60
|
+
const chunk = new Uint8Array(Math.min(65536, length - done))
|
|
61
|
+
crypto.getRandomValues(chunk)
|
|
62
|
+
new Uint8Array(memory.buffer, buffer + done, chunk.length).set(chunk)
|
|
63
|
+
}
|
|
64
|
+
return SUCCESS
|
|
65
|
+
},
|
|
66
|
+
fd_write(fd, iovs, count, written) {
|
|
67
|
+
if (fd !== 1 && fd !== 2) return EBADF
|
|
68
|
+
const v = view()
|
|
69
|
+
let total = 0
|
|
70
|
+
for (let i = 0; i < count; i++) {
|
|
71
|
+
const pointer = v.getUint32(iovs + i * 8, true)
|
|
72
|
+
const length = v.getUint32(iovs + i * 8 + 4, true)
|
|
73
|
+
// (A copy: TextDecoder does not read shared memory.)
|
|
74
|
+
pending[fd] += decoders[fd].decode(new Uint8Array(memory.buffer, pointer, length).slice(), { stream: true })
|
|
75
|
+
total += length
|
|
76
|
+
}
|
|
77
|
+
flush(fd, false)
|
|
78
|
+
v.setUint32(written, total, true)
|
|
79
|
+
return SUCCESS
|
|
80
|
+
},
|
|
81
|
+
fd_close: (fd) => (fd <= 2 ? SUCCESS : EBADF),
|
|
82
|
+
fd_fdstat_get: (fd) => (fd <= 2 ? ENOSYS : EBADF),
|
|
83
|
+
sched_yield: () => SUCCESS,
|
|
84
|
+
proc_exit(code) {
|
|
85
|
+
flush(1, true)
|
|
86
|
+
flush(2, true)
|
|
87
|
+
throw new Error(`the WebAssembly module exited with code ${code}`)
|
|
88
|
+
},
|
|
89
|
+
}
|
|
90
|
+
return {
|
|
91
|
+
// Anything else a module may import answers ENOSYS.
|
|
92
|
+
wasiImport: new Proxy(wasiImport, {
|
|
93
|
+
get: (target, name) => (name in target ? target[name] : () => ENOSYS),
|
|
94
|
+
}),
|
|
95
|
+
initialize(instance) {
|
|
96
|
+
memory = memory ?? instance.exports.memory
|
|
97
|
+
if (!options.child && typeof instance.exports._initialize === 'function') instance.exports._initialize()
|
|
98
|
+
},
|
|
99
|
+
}
|
|
100
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// Reads the bounds of the memory a WebAssembly module imports, from the
|
|
2
|
+
// module itself.
|
|
3
|
+
//
|
|
4
|
+
// A threaded wasm32-wasi build imports its (shared) memory as `env.memory`,
|
|
5
|
+
// so whoever instantiates it has to create a `WebAssembly.Memory` whose
|
|
6
|
+
// bounds fit what the module was linked with (addAddon's
|
|
7
|
+
// wasm_initial_memory / wasm_max_memory). `WebAssembly.Module.imports()`
|
|
8
|
+
// names the import but not its limits, so the loaders read them from the
|
|
9
|
+
// binary's import section instead.
|
|
10
|
+
//
|
|
11
|
+
// `wasmMemoryImport` is embedded verbatim (through Function.prototype
|
|
12
|
+
// .toString) in the loaders that `napi-zig build` writes, so it must stay
|
|
13
|
+
// self-contained: no imports, no references outside its own body. The
|
|
14
|
+
// reference loader of the repository (examples/wasm-threads/load.cjs)
|
|
15
|
+
// carries a copy, which the CLI tests compare with this one.
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The limits of the memory that a WebAssembly module imports as
|
|
19
|
+
* `env.memory`, in pages of `pageSize` bytes (64 KiB unless the module
|
|
20
|
+
* says otherwise): `{ initial, maximum, shared, memory64, pageSize }`,
|
|
21
|
+
* `maximum` being undefined when the module sets none. Null if the module
|
|
22
|
+
* imports no `env.memory` (it defines its own, or has none). Throws on
|
|
23
|
+
* anything that is not a well-formed core module up to the import section.
|
|
24
|
+
*
|
|
25
|
+
* @param {ArrayBuffer | ArrayBufferView} source the module's bytes
|
|
26
|
+
*/
|
|
27
|
+
export function wasmMemoryImport(source) {
|
|
28
|
+
const bytes = ArrayBuffer.isView(source)
|
|
29
|
+
? new Uint8Array(source.buffer, source.byteOffset, source.byteLength)
|
|
30
|
+
: new Uint8Array(source)
|
|
31
|
+
let at = 0
|
|
32
|
+
let end = bytes.length
|
|
33
|
+
const fail = (what) => {
|
|
34
|
+
throw new Error(`not a valid WebAssembly module: ${what} (at byte ${at})`)
|
|
35
|
+
}
|
|
36
|
+
const byte = () => {
|
|
37
|
+
if (at >= end) fail('unexpected end')
|
|
38
|
+
return bytes[at++]
|
|
39
|
+
}
|
|
40
|
+
// Unsigned LEB128 of at most `bits` bits, as a Number (exact up to 2^53).
|
|
41
|
+
const unsigned = (bits) => {
|
|
42
|
+
let value = 0
|
|
43
|
+
let scale = 1
|
|
44
|
+
for (let shift = 0; ; shift += 7) {
|
|
45
|
+
const b = byte()
|
|
46
|
+
// The last byte may only use the bits that are left.
|
|
47
|
+
if (shift + 7 > bits && b >> (bits - shift) !== 0) fail('integer too large')
|
|
48
|
+
value += (b & 0x7f) * scale
|
|
49
|
+
scale *= 128
|
|
50
|
+
if ((b & 0x80) === 0) break
|
|
51
|
+
}
|
|
52
|
+
if (value > Number.MAX_SAFE_INTEGER) fail('integer too large')
|
|
53
|
+
return value
|
|
54
|
+
}
|
|
55
|
+
// Signed LEB128 of at most 33 bits (a heap type); only skipped.
|
|
56
|
+
const skipSigned33 = () => {
|
|
57
|
+
for (let shift = 0; ; shift += 7) {
|
|
58
|
+
if (shift >= 35) fail('integer too long')
|
|
59
|
+
if ((byte() & 0x80) === 0) return
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const name = () => {
|
|
63
|
+
const length = unsigned(32)
|
|
64
|
+
if (length > end - at) fail('name runs past its section')
|
|
65
|
+
let text = ''
|
|
66
|
+
for (let i = 0; i < length; i++) text += String.fromCharCode(bytes[at + i])
|
|
67
|
+
at += length
|
|
68
|
+
return text
|
|
69
|
+
}
|
|
70
|
+
// A value or reference type: one byte, or (ref null? <heap type>).
|
|
71
|
+
const skipType = () => {
|
|
72
|
+
const b = byte()
|
|
73
|
+
if (b === 0x63 || b === 0x64) skipSigned33()
|
|
74
|
+
}
|
|
75
|
+
const limits = () => {
|
|
76
|
+
const flags = byte()
|
|
77
|
+
if (flags & ~0x0f) fail(`unknown limits flags 0x${flags.toString(16)}`)
|
|
78
|
+
const memory64 = (flags & 0x04) !== 0
|
|
79
|
+
const bits = memory64 ? 64 : 32
|
|
80
|
+
const initial = unsigned(bits)
|
|
81
|
+
const maximum = flags & 0x01 ? unsigned(bits) : undefined
|
|
82
|
+
// (Custom page sizes: the page size's log2 follows.)
|
|
83
|
+
const pageSize = flags & 0x08 ? 2 ** unsigned(32) : 65536
|
|
84
|
+
return { initial, maximum, shared: (flags & 0x02) !== 0, memory64, pageSize }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (bytes.length < 8) fail('too short')
|
|
88
|
+
if (bytes[0] !== 0x00 || bytes[1] !== 0x61 || bytes[2] !== 0x73 || bytes[3] !== 0x6d) fail('no \\0asm magic')
|
|
89
|
+
if (bytes[4] !== 0x01 || bytes[5] !== 0x00 || bytes[6] !== 0x00 || bytes[7] !== 0x00) fail('not a version 1 core module')
|
|
90
|
+
at = 8
|
|
91
|
+
while (at < bytes.length) {
|
|
92
|
+
end = bytes.length
|
|
93
|
+
const id = byte()
|
|
94
|
+
const size = unsigned(32)
|
|
95
|
+
if (size > bytes.length - at) fail('section runs past the end')
|
|
96
|
+
const sectionEnd = at + size
|
|
97
|
+
// Custom sections (0) may come anywhere and the type section (1)
|
|
98
|
+
// before the imports; any other section comes after them.
|
|
99
|
+
if (id === 2) {
|
|
100
|
+
end = sectionEnd
|
|
101
|
+
const count = unsigned(32)
|
|
102
|
+
for (let i = 0; i < count; i++) {
|
|
103
|
+
const module = name()
|
|
104
|
+
const field = name()
|
|
105
|
+
const kind = byte()
|
|
106
|
+
if (kind === 0x00) {
|
|
107
|
+
unsigned(32) // a function: its type index
|
|
108
|
+
} else if (kind === 0x01) {
|
|
109
|
+
skipType() // a table
|
|
110
|
+
limits()
|
|
111
|
+
} else if (kind === 0x02) {
|
|
112
|
+
const memory = limits()
|
|
113
|
+
if (module === 'env' && field === 'memory') return memory
|
|
114
|
+
} else if (kind === 0x03) {
|
|
115
|
+
skipType() // a global
|
|
116
|
+
if (byte() > 1) fail('bad global mutability')
|
|
117
|
+
} else if (kind === 0x04) {
|
|
118
|
+
byte() // a tag: its attribute, then its type index
|
|
119
|
+
unsigned(32)
|
|
120
|
+
} else {
|
|
121
|
+
fail(`unknown import kind 0x${kind.toString(16)}`)
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (at !== sectionEnd) fail('import section size mismatch')
|
|
125
|
+
return null
|
|
126
|
+
}
|
|
127
|
+
if (id !== 0 && id !== 1) return null
|
|
128
|
+
at = sectionEnd
|
|
129
|
+
}
|
|
130
|
+
return null
|
|
131
|
+
}
|
package/lib/wasm.mjs
CHANGED
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
// examples (examples/wasm/load.cjs, examples/wasm-threads/load.cjs).
|
|
6
6
|
|
|
7
7
|
import { binaryName } from './targets.mjs'
|
|
8
|
+
import { wasmMemoryImport } from './wasm-memory.mjs'
|
|
9
|
+
import { createBrowserWasi } from './browser-wasi.mjs'
|
|
8
10
|
|
|
9
11
|
/** The emnapi packages a loader needs, as npm dependency ranges. */
|
|
10
12
|
export const EMNAPI_DEPENDENCIES = {
|
|
@@ -16,38 +18,98 @@ export const EMNAPI_THREADS_DEPENDENCIES = {
|
|
|
16
18
|
'@emnapi/wasi-threads': '^1.0.0',
|
|
17
19
|
}
|
|
18
20
|
|
|
19
|
-
// The linker's defaults in addAddon (wasm_initial_memory / wasm_max_memory)
|
|
21
|
+
// The linker's defaults in addAddon (wasm_initial_memory / wasm_max_memory):
|
|
22
|
+
// only used if a threaded module does not import its memory as `env.memory`
|
|
23
|
+
// (which napi-zig's builds always do; the loaders read the bounds from there).
|
|
20
24
|
export const DEFAULT_INITIAL_MEMORY = 32 << 20
|
|
21
25
|
export const DEFAULT_MAX_MEMORY = 2 ** 30
|
|
22
26
|
|
|
23
|
-
/** `<name>.<target>.cjs`: the module that loads `<name>.<target>.wasm
|
|
27
|
+
/** `<name>.<target>.cjs`: the module that loads `<name>.<target>.wasm` in Node.js (and Bun, Deno). */
|
|
24
28
|
export function loaderName(addonName, target) {
|
|
25
29
|
return `${addonName}.${target.id}.cjs`
|
|
26
30
|
}
|
|
27
31
|
|
|
28
|
-
/** `<name>.<target>.worker.cjs`: what each wasm thread runs. */
|
|
32
|
+
/** `<name>.<target>.worker.cjs`: what each wasm thread runs in Node.js. */
|
|
29
33
|
export function workerName(addonName, target) {
|
|
30
34
|
return `${addonName}.${target.id}.worker.cjs`
|
|
31
35
|
}
|
|
32
36
|
|
|
37
|
+
/** `<name>.<target>.browser.mjs`: the ES module that loads the .wasm in browsers and bundlers. */
|
|
38
|
+
export function browserLoaderName(addonName, target) {
|
|
39
|
+
return `${addonName}.${target.id}.browser.mjs`
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** `<name>.<target>.browser-worker.mjs`: what each wasm thread runs in a browser (a module worker). */
|
|
43
|
+
export function browserWorkerName(addonName, target) {
|
|
44
|
+
return `${addonName}.${target.id}.browser-worker.mjs`
|
|
45
|
+
}
|
|
46
|
+
|
|
33
47
|
/** The files that load a wasm target's binary: `{ name: contents }`. */
|
|
34
48
|
export function wasmLoaderFiles(project, target) {
|
|
35
49
|
const threaded = Boolean(target.threads)
|
|
36
|
-
const
|
|
50
|
+
const { addonName } = project
|
|
51
|
+
const binary = binaryName(addonName, target)
|
|
52
|
+
const memory = project.wasm ?? {}
|
|
37
53
|
const files = {
|
|
38
|
-
[loaderName(
|
|
39
|
-
? threadedLoader(binary, workerName(project.addonName, target), project.wasm ?? {})
|
|
40
|
-
: loader(binary),
|
|
54
|
+
[loaderName(addonName, target)]: threaded ? threadedLoader(binary, workerName(addonName, target), memory) : loader(binary),
|
|
41
55
|
}
|
|
42
|
-
if (threaded) files[workerName(
|
|
56
|
+
if (threaded) files[workerName(addonName, target)] = worker()
|
|
57
|
+
files[browserLoaderName(addonName, target)] = threaded
|
|
58
|
+
? threadedBrowserLoader(binary, browserWorkerName(addonName, target), memory)
|
|
59
|
+
: browserLoader(binary)
|
|
60
|
+
if (threaded) files[browserWorkerName(addonName, target)] = browserWorker()
|
|
43
61
|
return files
|
|
44
62
|
}
|
|
45
63
|
|
|
64
|
+
/** The `package.json` fields that point at a wasm target's loaders. */
|
|
65
|
+
export function wasmPackageEntries(addonName, target) {
|
|
66
|
+
const node = `./${loaderName(addonName, target)}`
|
|
67
|
+
const browser = `./${browserLoaderName(addonName, target)}`
|
|
68
|
+
return {
|
|
69
|
+
main: loaderName(addonName, target),
|
|
70
|
+
browser: browserLoaderName(addonName, target),
|
|
71
|
+
// Node.js, Bun and Deno match "node": the CommonJS loader (node:wasi,
|
|
72
|
+
// worker_threads). Browsers and bundlers for the web match "browser"
|
|
73
|
+
// (or "import"): the ES module that fetches the .wasm.
|
|
74
|
+
exports: {
|
|
75
|
+
'.': { node, browser, import: browser, default: node },
|
|
76
|
+
'./package.json': './package.json',
|
|
77
|
+
'./*': './*',
|
|
78
|
+
},
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
46
82
|
const header = (what) => `// Generated by napi-zig: ${what}
|
|
47
83
|
// through emnapi (@emnapi/core, @emnapi/runtime).
|
|
48
84
|
'use strict'
|
|
49
85
|
`
|
|
50
86
|
|
|
87
|
+
const esmHeader = (what) => `// Generated by napi-zig: ${what}
|
|
88
|
+
// through emnapi (@emnapi/core, @emnapi/runtime).
|
|
89
|
+
`
|
|
90
|
+
|
|
91
|
+
/** Explicit bounds ("napi.wasm" in package.json, in bytes) as pages, or the module's own. */
|
|
92
|
+
function memoryBounds(options) {
|
|
93
|
+
const pages = (bytes) => String(Math.ceil(bytes / 65536))
|
|
94
|
+
return {
|
|
95
|
+
initial: options.initialMemory != null ? pages(options.initialMemory) : 'imported.initial',
|
|
96
|
+
maximum: options.maxMemory != null ? pages(options.maxMemory) : 'imported.maximum',
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Declares `memory`, the shared memory of a threaded module (`found`: what wasmMemoryImport returned). */
|
|
101
|
+
function memorySource(options, found, indent = '') {
|
|
102
|
+
const { initial, maximum } = memoryBounds(options)
|
|
103
|
+
const overridden = options.initialMemory != null || options.maxMemory != null
|
|
104
|
+
return [
|
|
105
|
+
'// One memory shared by every thread, with the bounds the module imports',
|
|
106
|
+
`// it with (as linked by build.zig: wasm_initial_memory, wasm_max_memory)${overridden ? ',' : '.'}`,
|
|
107
|
+
...(overridden ? ['// overridden by "napi.wasm" in package.json.'] : []),
|
|
108
|
+
`const imported = ${found} ?? { initial: ${DEFAULT_INITIAL_MEMORY / 65536}, maximum: ${DEFAULT_MAX_MEMORY / 65536} }`,
|
|
109
|
+
`const memory = new WebAssembly.Memory({ initial: ${initial}, maximum: ${maximum}, shared: true })`,
|
|
110
|
+
].join(`\n${indent}`)
|
|
111
|
+
}
|
|
112
|
+
|
|
51
113
|
const shared = `
|
|
52
114
|
// Bun's node:wasi has no \`initialize\` (the entry point of reactor modules
|
|
53
115
|
// such as this one); do what it does there.
|
|
@@ -104,8 +166,6 @@ module.exports = napiModule.exports
|
|
|
104
166
|
}
|
|
105
167
|
|
|
106
168
|
function threadedLoader(binary, workerFile, options) {
|
|
107
|
-
const initial = options.initialMemory ?? DEFAULT_INITIAL_MEMORY
|
|
108
|
-
const maximum = options.maxMemory ?? DEFAULT_MAX_MEMORY
|
|
109
169
|
return `${header('loads the threaded wasm32-wasi build of this addon')}
|
|
110
170
|
const { readFileSync } = require('node:fs')
|
|
111
171
|
const { join } = require('node:path')
|
|
@@ -114,14 +174,13 @@ const { Worker } = require('node:worker_threads')
|
|
|
114
174
|
const { instantiateNapiModuleSync } = require('@emnapi/core')
|
|
115
175
|
const { getDefaultContext } = require('@emnapi/runtime')
|
|
116
176
|
${shared}${context}
|
|
117
|
-
//
|
|
118
|
-
//
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
}
|
|
124
|
-
const { napiModule } = instantiateNapiModuleSync(readFileSync(join(__dirname, ${JSON.stringify(binary)})), {
|
|
177
|
+
// The limits of the memory a module imports as env.memory, read from its
|
|
178
|
+
// import section (WebAssembly.Module.imports() does not report them).
|
|
179
|
+
${wasmMemoryImport}
|
|
180
|
+
|
|
181
|
+
const bytes = readFileSync(join(__dirname, ${JSON.stringify(binary)}))
|
|
182
|
+
${memorySource(options, 'wasmMemoryImport(bytes)')}
|
|
183
|
+
const { napiModule } = instantiateNapiModuleSync(bytes, {
|
|
125
184
|
context: context(),
|
|
126
185
|
wasi: newWasi(),
|
|
127
186
|
// Each thread the addon spawns is a worker running ${workerFile}.
|
|
@@ -163,3 +222,115 @@ const handler = new MessageHandler({
|
|
|
163
222
|
parentPort.on('message', (data) => handler.handle({ data }))
|
|
164
223
|
`
|
|
165
224
|
}
|
|
225
|
+
|
|
226
|
+
// --- browsers and bundlers ----------------------------------------------------
|
|
227
|
+
|
|
228
|
+
const fetchBytes = `
|
|
229
|
+
// The .wasm's bytes: \`source\` is a URL (or string), a Response, bytes, or
|
|
230
|
+
// a compiled WebAssembly.Module (passed through).
|
|
231
|
+
async function bytesOf(source) {
|
|
232
|
+
if (source instanceof WebAssembly.Module || source instanceof ArrayBuffer || ArrayBuffer.isView(source)) return source
|
|
233
|
+
const response = typeof Response !== 'undefined' && source instanceof Response ? source : await fetch(source)
|
|
234
|
+
if (!response.ok) throw new Error(\`could not fetch \${response.url || source}: HTTP \${response.status}\`)
|
|
235
|
+
return new Uint8Array(await response.arrayBuffer())
|
|
236
|
+
}
|
|
237
|
+
`
|
|
238
|
+
|
|
239
|
+
function browserLoader(binary) {
|
|
240
|
+
return `${esmHeader('loads the wasm32-wasi build of this addon in browsers and bundlers')}//
|
|
241
|
+
// import addon from '<package>' // instantiated once, on import
|
|
242
|
+
// import { load } from '<package>' // load({ wasm, wasi, context }): another instance
|
|
243
|
+
import { instantiateNapiModule } from '@emnapi/core'
|
|
244
|
+
import { getDefaultContext } from '@emnapi/runtime'
|
|
245
|
+
|
|
246
|
+
// A console for stdout/stderr, clocks and random bytes: enough WASI for a
|
|
247
|
+
// module that does not touch files (pass \`wasi\` for more).
|
|
248
|
+
${createBrowserWasi}
|
|
249
|
+
|
|
250
|
+
// (The pattern bundlers know: they copy the .wasm and rewrite the URL.)
|
|
251
|
+
const wasmUrl = new URL(${JSON.stringify(`./${binary}`)}, import.meta.url)
|
|
252
|
+
${fetchBytes}
|
|
253
|
+
export async function load(options = {}) {
|
|
254
|
+
const { napiModule } = await instantiateNapiModule(await bytesOf(options.wasm ?? wasmUrl), {
|
|
255
|
+
context: options.context ?? getDefaultContext(),
|
|
256
|
+
wasi: options.wasi ?? createBrowserWasi(),
|
|
257
|
+
})
|
|
258
|
+
return napiModule.exports
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export default await load()
|
|
262
|
+
`
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function threadedBrowserLoader(binary, workerFile, options) {
|
|
266
|
+
return `${esmHeader('loads the threaded wasm32-wasi build of this addon in browsers and bundlers')}//
|
|
267
|
+
// Threads are Web Workers sharing one WebAssembly.Memory, which takes a
|
|
268
|
+
// SharedArrayBuffer: the page must be cross-origin isolated (served with
|
|
269
|
+
// Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy:
|
|
270
|
+
// require-corp). Load it in a worker rather than on the page's main thread,
|
|
271
|
+
// which may not block.
|
|
272
|
+
//
|
|
273
|
+
// import addon from '<package>' // instantiated once, on import
|
|
274
|
+
// import { load } from '<package>' // load({ wasm, wasi, context, memory, reuseWorker, onCreateWorker })
|
|
275
|
+
import { instantiateNapiModule } from '@emnapi/core'
|
|
276
|
+
import { getDefaultContext } from '@emnapi/runtime'
|
|
277
|
+
|
|
278
|
+
// The limits of the memory a module imports as env.memory, read from its
|
|
279
|
+
// import section (WebAssembly.Module.imports() does not report them).
|
|
280
|
+
${wasmMemoryImport}
|
|
281
|
+
|
|
282
|
+
// A console for stdout/stderr, clocks and random bytes: enough WASI for a
|
|
283
|
+
// module that does not touch files (pass \`wasi\` for more).
|
|
284
|
+
${createBrowserWasi}
|
|
285
|
+
|
|
286
|
+
// (The pattern bundlers know: they copy the .wasm and rewrite the URL.)
|
|
287
|
+
const wasmUrl = new URL(${JSON.stringify(`./${binary}`)}, import.meta.url)
|
|
288
|
+
${fetchBytes}
|
|
289
|
+
export async function load(options = {}) {
|
|
290
|
+
const bytes = await bytesOf(options.wasm ?? wasmUrl)
|
|
291
|
+
const memory = options.memory ?? createMemory(bytes instanceof WebAssembly.Module ? null : bytes)
|
|
292
|
+
const { napiModule } = await instantiateNapiModule(bytes, {
|
|
293
|
+
context: options.context ?? getDefaultContext(),
|
|
294
|
+
wasi: options.wasi ?? createBrowserWasi({ memory }),
|
|
295
|
+
// A worker cannot start while the thread that asked for it is busy, so
|
|
296
|
+
// a few are kept ready (as many as napi-zig's Async pool has threads by
|
|
297
|
+
// default); more are started when needed.
|
|
298
|
+
reuseWorker: options.reuseWorker ?? { size: 4, strict: false },
|
|
299
|
+
// Each thread the addon spawns is a module worker running ${workerFile}.
|
|
300
|
+
onCreateWorker: options.onCreateWorker ?? (() => new Worker(new URL(${JSON.stringify(`./${workerFile}`)}, import.meta.url), { type: 'module' })),
|
|
301
|
+
overwriteImports(imports) {
|
|
302
|
+
imports.env.memory = memory
|
|
303
|
+
},
|
|
304
|
+
})
|
|
305
|
+
return napiModule.exports
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function createMemory(bytes) {
|
|
309
|
+
${memorySource(options, '(bytes && wasmMemoryImport(bytes))', ' ')}
|
|
310
|
+
return memory
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
export default await load()
|
|
314
|
+
`
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function browserWorker() {
|
|
318
|
+
return `${esmHeader('runs one thread of the threaded wasm32-wasi build of this addon in a browser')}import { instantiateNapiModuleSync, MessageHandler } from '@emnapi/core'
|
|
319
|
+
|
|
320
|
+
${createBrowserWasi}
|
|
321
|
+
|
|
322
|
+
const handler = new MessageHandler({
|
|
323
|
+
onLoad({ wasmModule, wasmMemory }) {
|
|
324
|
+
return instantiateNapiModuleSync(wasmModule, {
|
|
325
|
+
childThread: true,
|
|
326
|
+
wasi: createBrowserWasi({ memory: wasmMemory, child: true }),
|
|
327
|
+
overwriteImports(imports) {
|
|
328
|
+
imports.env.memory = wasmMemory
|
|
329
|
+
},
|
|
330
|
+
})
|
|
331
|
+
},
|
|
332
|
+
})
|
|
333
|
+
|
|
334
|
+
globalThis.onmessage = (event) => handler.handle(event)
|
|
335
|
+
`
|
|
336
|
+
}
|
package/package.json
CHANGED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// Browsers and bundlers (the "browser" export of package.json): the
|
|
2
|
+
// WebAssembly build of the addon, instantiated on import. Node.js, Bun and
|
|
3
|
+
// Deno load index.js instead (native binary first, WebAssembly as the
|
|
4
|
+
// fallback).
|
|
5
|
+
//
|
|
6
|
+
// import addon from '{{PACKAGE_NAME}}'
|
|
7
|
+
//
|
|
8
|
+
// It loads the WebAssembly package of "napi.targets": `napi-zig artifacts`
|
|
9
|
+
// points the line below at "wasm32-wasi" if that is a target, else at
|
|
10
|
+
// "wasm32-wasi-threads" (which needs a cross-origin isolated page and is
|
|
11
|
+
// best loaded in a worker). Edit the line by hand and it is left alone.
|
|
12
|
+
export { default, load } from '{{PACKAGE_NAME}}-wasm32-wasi'
|
|
@@ -4,9 +4,20 @@
|
|
|
4
4
|
"description": "A Node.js addon written in Zig",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"types": "index.d.ts",
|
|
7
|
+
"browser": "browser.mjs",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./index.d.ts",
|
|
11
|
+
"node": "./index.js",
|
|
12
|
+
"browser": "./browser.mjs",
|
|
13
|
+
"default": "./index.js"
|
|
14
|
+
},
|
|
15
|
+
"./package.json": "./package.json"
|
|
16
|
+
},
|
|
7
17
|
"files": [
|
|
8
18
|
"index.js",
|
|
9
|
-
"index.d.ts"
|
|
19
|
+
"index.d.ts",
|
|
20
|
+
"browser.mjs"
|
|
10
21
|
],
|
|
11
22
|
"napi": {
|
|
12
23
|
"name": "{{ADDON_NAME}}",
|
|
@@ -21,7 +32,7 @@
|
|
|
21
32
|
"test": "node --test"
|
|
22
33
|
},
|
|
23
34
|
"devDependencies": {
|
|
24
|
-
"@hunghg255/napi-zig-cli": "^1.
|
|
35
|
+
"@hunghg255/napi-zig-cli": "^1.8.0"
|
|
25
36
|
},
|
|
26
37
|
"license": "MIT"
|
|
27
38
|
}
|