-
Notifications
You must be signed in to change notification settings - Fork 550
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(cloudflare): wasm support with dynamic chunks (#1957)
- Loading branch information
Showing
8 changed files
with
172 additions
and
74 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -74,3 +74,4 @@ playground/firebase.json | |
test/fixture/functions | ||
|
||
.pnpm-store | ||
.wrangler |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,71 +1,160 @@ | ||
import { createHash } from "node:crypto"; | ||
import { extname, basename } from "node:path"; | ||
import { promises as fs } from "node:fs"; | ||
import { promises as fs, existsSync } from "node:fs"; | ||
import { basename, normalize } from "pathe"; | ||
import type { Plugin } from "rollup"; | ||
import wasmBundle from "@rollup/plugin-wasm"; | ||
import { isWindows } from "std-env"; | ||
import MagicString from "magic-string"; | ||
import { walk } from "estree-walker"; | ||
import { WasmOptions } from "../../types"; | ||
|
||
const PLUGIN_NAME = "nitro:wasm-import"; | ||
const wasmRegex = /\.wasm$/; | ||
|
||
export function wasm(options: WasmOptions): Plugin { | ||
return options.esmImport && !isWindows /* TODO */ | ||
? wasmImport() | ||
: wasmBundle(options.rollup); | ||
return options.esmImport ? wasmImport() : wasmBundle(options.rollup); | ||
} | ||
|
||
const WASM_IMPORT_PREFIX = "\0nitro:wasm/"; | ||
|
||
export function wasmImport(): Plugin { | ||
const copies = Object.create(null); | ||
type WasmAssetInfo = { | ||
fileName: string; | ||
id: string; | ||
source: Buffer; | ||
hash: string; | ||
}; | ||
|
||
return { | ||
name: PLUGIN_NAME, | ||
async resolveId(id: string, importer: string) { | ||
if (copies[id]) { | ||
return { | ||
id: copies[id].publicFilepath, | ||
external: true, | ||
const wasmSources = new Map<string /* sourceFile */, WasmAssetInfo>(); | ||
const wasmImports = new Map<string /* id */, WasmAssetInfo>(); | ||
const wasmGlobals = new Map<string /* global id */, WasmAssetInfo>(); | ||
|
||
return <Plugin>{ | ||
name: "nitro:wasm", | ||
async resolveId(id, importer, options) { | ||
// Only handle .wasm imports | ||
if (!id.endsWith(".wasm")) { | ||
return null; | ||
} | ||
|
||
// Resolve the source file real path | ||
const sourceFile = await this.resolve(id, importer, options).then((r) => | ||
r?.id ? normalize(r.id) : null | ||
); | ||
if (!sourceFile || !existsSync(sourceFile)) { | ||
return null; | ||
} | ||
|
||
// Read (cached) Asset | ||
let wasmAsset: WasmAssetInfo | undefined = wasmSources.get(sourceFile); | ||
if (!wasmAsset) { | ||
wasmAsset = { | ||
id: WASM_IMPORT_PREFIX + sourceFile, | ||
fileName: "", | ||
source: undefined, | ||
hash: "", | ||
}; | ||
wasmSources.set(sourceFile, wasmAsset); | ||
wasmImports.set(wasmAsset.id, wasmAsset); | ||
|
||
wasmAsset.source = await fs.readFile(sourceFile); | ||
wasmAsset.hash = sha1(wasmAsset.source); | ||
const _baseName = basename(sourceFile, ".wasm"); | ||
wasmAsset.fileName = `wasm/${_baseName}-${wasmAsset.hash}.wasm`; | ||
|
||
await this.emitFile({ | ||
type: "asset", | ||
source: wasmAsset.source, | ||
fileName: wasmAsset.fileName, | ||
}); | ||
} | ||
|
||
// Resolve as external | ||
return { | ||
id: wasmAsset.id, | ||
external: true, | ||
}; | ||
}, | ||
renderChunk(code, chunk) { | ||
if (!code.includes(WASM_IMPORT_PREFIX)) { | ||
return null; | ||
} | ||
if (wasmRegex.test(id)) { | ||
const { id: filepath } = (await this.resolve(id, importer)) || {}; | ||
if (!filepath || filepath === id) { | ||
|
||
const s = new MagicString(code); | ||
|
||
const resolveImport = (specifier?: string) => { | ||
if ( | ||
typeof specifier !== "string" || | ||
!specifier.startsWith(WASM_IMPORT_PREFIX) | ||
) { | ||
return null; | ||
} | ||
const buffer = await fs.readFile(filepath); | ||
const hash = createHash("sha1") | ||
.update(buffer) | ||
.digest("hex") | ||
.slice(0, 16); | ||
const ext = extname(filepath); | ||
const name = basename(filepath, ext); | ||
|
||
const outputFileName = `wasm/${name}-${hash}${ext}`; | ||
const publicFilepath = `./${outputFileName}`; | ||
const asset = wasmImports.get(specifier); | ||
if (!asset) { | ||
return null; | ||
} | ||
const nestedLevel = chunk.fileName.split("/").length - 1; | ||
return ( | ||
(nestedLevel ? "../".repeat(nestedLevel) : "./") + asset.fileName | ||
); | ||
}; | ||
|
||
copies[id] = { | ||
filename: outputFileName, | ||
publicFilepath, | ||
buffer, | ||
}; | ||
walk(this.parse(code) as any, { | ||
enter(node, parent, prop, index) { | ||
if ( | ||
// prettier-ignore | ||
(node.type === "ImportDeclaration" || node.type === "ImportExpression") && | ||
"value" in node.source && typeof node.source.value === "string" && | ||
"start" in node.source && typeof node.source.start === "number" && | ||
"end" in node.source && typeof node.source.end === "number" | ||
) { | ||
const resolved = resolveImport(node.source.value); | ||
if (resolved) { | ||
// prettier-ignore | ||
s.update(node.source.start, node.source.end, JSON.stringify(resolved)); | ||
} | ||
} | ||
}, | ||
}); | ||
|
||
if (s.hasChanged()) { | ||
return { | ||
id: publicFilepath, | ||
external: true, | ||
code: s.toString(), | ||
map: s.generateMap({ includeContent: true }), | ||
}; | ||
} | ||
}, | ||
async generateBundle() { | ||
await Promise.all( | ||
Object.keys(copies).map(async (name) => { | ||
const copy = copies[name]; | ||
await this.emitFile({ | ||
type: "asset", | ||
source: copy.buffer, | ||
fileName: copy.filename, | ||
}); | ||
}) | ||
); | ||
// --- [temporary] IIFE/UMD support for cloudflare (non module targets) --- | ||
renderStart(options) { | ||
if (options.format === "iife" || options.format === "umd") { | ||
for (const [importName, wasmAsset] of wasmImports.entries()) { | ||
if (!(importName in options.globals)) { | ||
const globalName = `_wasm_${wasmAsset.hash}`; | ||
wasmGlobals.set(globalName, wasmAsset); | ||
options.globals[importName] = globalName; | ||
} | ||
} | ||
} | ||
}, | ||
generateBundle(options, bundle) { | ||
if (wasmGlobals.size > 0) { | ||
for (const [fileName, chunkInfo] of Object.entries(bundle)) { | ||
if (chunkInfo.type !== "chunk" || !chunkInfo.isEntry) { | ||
continue; | ||
} | ||
const imports: string[] = []; | ||
for (const [globalName, wasmAsset] of wasmGlobals.entries()) { | ||
if (chunkInfo.code.includes(globalName)) { | ||
imports.push( | ||
`import ${globalName} from "${wasmAsset.fileName}";` | ||
); | ||
} | ||
} | ||
if (imports.length > 0) { | ||
chunkInfo.code = imports.join("\n") + "\n" + chunkInfo.code; | ||
} | ||
} | ||
} | ||
}, | ||
}; | ||
} | ||
|
||
function sha1(source: Buffer) { | ||
return createHash("sha1").update(source).digest("hex").slice(0, 16); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
export default defineLazyEventHandler(async () => { | ||
const { sum } = await importWasm(import("~/wasm/sum.wasm" as string)); | ||
return eventHandler(() => { | ||
return `2+3=${sum(2, 3)}`; | ||
}); | ||
}); | ||
|
||
// TODO: Extract as reusable utility once stable | ||
async function importWasm(input: any) { | ||
const _input = await input; | ||
const _module = _input.default || _input; | ||
const _instance = | ||
typeof _module === "function" | ||
? await _module({}).then((r) => r.instance || r) | ||
: await WebAssembly.instantiate(_module, {}); | ||
return _instance.exports; | ||
} |
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters