/ proof-of-concept / instrawave
Sign in
proof-of-concept / instrawave
instrawave / scripts / nodeWebGpu.ts
39 lines · 1.4 KBCodeBlameHistory
2 * Desktop WebGPU for the command-line scripts, via the optional `webgpu`
3 * package (prebuilt Google Dawn). Installs Dawn under the globals the
4 * host code expects (navigator.gpu, GPUBufferUsage, ...) so everything
5 * under src/ runs here unchanged.
6 */
7export const errMsg = (e: unknown): string =>
8 e instanceof Error ? e.message : String(e);
10export async function installWebGpu(): Promise<string> {
11 const specifier = 'webgpu';
12 let mod: { create: (flags: string[]) => GPU; globals: Record<string, unknown> };
13 try {
14 mod = await import(specifier);
15 } catch (e) {
16 const detail = errMsg(e);
17 if (/Cannot find (package|module) '?webgpu'?/.test(detail)) {
18 throw new Error(
19 'desktop WebGPU needs the optional `webgpu` package (prebuilt Google Dawn):\n' +
20 ' npm install webgpu',
21 );
22 }
23 throw new Error(`the \`webgpu\` package is installed but did not load:\n ${detail}`);
24 }
25 Object.assign(globalThis, mod.globals);
26 const dawnFlags = process.env.DAWN_FLAGS?.split(';').filter(Boolean) ?? [];
27 Object.defineProperty(globalThis, 'navigator', {
28 value: { gpu: mod.create(dawnFlags) },
29 configurable: true,
30 writable: true,
31 });
32 const { version } = await import(`${specifier}/package.json`, {
33 with: { type: 'json' },
34 }).then(
35 (m) => m.default as { version: string },
36 () => ({ version: '?' }),
37 );
38 return `node-webgpu ${version} (Google Dawn)`;
↑↓ move↵openescclose