Skip to content

Commit 558a9a9

Browse files
refactor: use magic-string for proper source maps in WASM fix (#234)
* refactor: use magic-string for proper source maps in WASM fix Improve the WASM data URL fix to use magic-string for accurate source map generation. This eliminates build warnings and ensures proper debugging support. - Replace string.replace() with MagicString.overwrite() - Return both code and source map from renderChunk - Uses existing magic-string dependency (via vite-plugin-dts) * fix: remove non-null assertion and fix line endings - Replace match.index! with proper undefined check - Fix CRLF to LF line endings (biome format)
1 parent 752cfaa commit 558a9a9

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

vite.config.ts

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import fs from "node:fs";
22
import path from "node:path";
3+
import MagicString from "magic-string";
34
import type { Plugin } from "vite";
45
import { defineConfig } from "vite";
56
import dts from "vite-plugin-dts";
@@ -15,6 +16,8 @@ import glsl from "vite-plugin-glsl";
1516
* This plugin transforms:
1617
* new URL("data:...", import.meta.url) → new URL("data:...")
1718
*
19+
* Uses magic-string to ensure proper source map generation.
20+
*
1821
* See: https://github.com/sparkjsdev/spark/issues/95
1922
*/
2023
function fixWasmDataUrl(): Plugin {
@@ -25,8 +28,23 @@ function fixWasmDataUrl(): Plugin {
2528
// The data URL can contain any characters including quotes (escaped)
2629
const dataUrlPattern =
2730
/new\s+URL\(\s*("data:[^"]*")\s*,\s*import\.meta\.url\s*\)/g;
28-
const result = code.replace(dataUrlPattern, "new URL($1)");
29-
return result !== code ? result : null;
31+
32+
const matches = [...code.matchAll(dataUrlPattern)];
33+
if (matches.length === 0) return null;
34+
35+
const s = new MagicString(code);
36+
for (const match of matches) {
37+
if (match.index === undefined) continue;
38+
const start = match.index;
39+
const end = start + match[0].length;
40+
const replacement = `new URL(${match[1]})`;
41+
s.overwrite(start, end, replacement);
42+
}
43+
44+
return {
45+
code: s.toString(),
46+
map: s.generateMap({ hires: true }),
47+
};
3048
},
3149
};
3250
}

0 commit comments

Comments
 (0)