-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
38 lines (30 loc) · 1.11 KB
/
index.js
File metadata and controls
38 lines (30 loc) · 1.11 KB
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
'use strict'
const { createReadStream } = require('node:fs')
const { Readable } = require('node:stream')
const fp = require('fastify-plugin')
async function fastifyWasm (fastify, options) {
// Validate options
if (!options || typeof options !== 'object') {
throw new Error('options must be provided as an object')
}
if (!options.path) {
throw new Error('options.path must be provided')
}
const isString = typeof options.path === 'string'
const isBuffer = Buffer.isBuffer(options.path)
const isURL = URL.canParse(options.path)
const isValidPath = isString || isBuffer || isURL
if (isValidPath === false) {
throw new Error('options.path must be a valid path')
}
const webStream = Readable.toWeb(createReadStream(options.path))
const response = new Response(webStream, { headers: { 'Content-Type': 'application/wasm' } })
const wasm = await WebAssembly.instantiateStreaming(response, options.imports)
fastify.decorate('wasm', wasm)
}
module.exports = fp(fastifyWasm, {
fastify: '5.x',
name: 'fastify-wasm',
})
module.exports.default = fastifyWasm
module.exports.fastifyWasm = fastifyWasm