buildPluginWasm.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.createBuildWasmPlugin = void 0;
  4. const buildPluginAsset_1 = require("./buildPluginAsset");
  5. const wasmHelperId = 'vite/wasm-helper';
  6. const wasmHelper = (opts = {}, url) => {
  7. let instance;
  8. if (url.startsWith('data:')) {
  9. // @ts-ignore
  10. const binaryString = atob(url.replace(/^data:.*?base64,/, ''));
  11. const bytes = new Uint8Array(binaryString.length);
  12. for (let i = 0; i < binaryString.length; i++) {
  13. bytes[i] = binaryString.charCodeAt(i);
  14. }
  15. // @ts-ignore
  16. instance = WebAssembly.instantiate(bytes.buffer, opts);
  17. }
  18. else {
  19. // https://github.com/mdn/webassembly-examples/issues/5
  20. // WebAssembly.instantiateStreaming requires the server to provide the
  21. // correct MIME type for .wasm files, which unfortunately doesn't work for
  22. // a lot of static file servers, so we just work around it by getting the
  23. // raw buffer.
  24. // @ts-ignore
  25. instance = fetch(url)
  26. // @ts-ignore
  27. .then((r) => r.arrayBuffer())
  28. // @ts-ignore
  29. .then((bytes) => WebAssembly.instantiate(bytes, opts));
  30. }
  31. return instance.then((i) => i.instance.exports);
  32. };
  33. const wasmHelperCode = wasmHelper.toString();
  34. exports.createBuildWasmPlugin = (root, publicBase, assetsDir, inlineLimit) => {
  35. return {
  36. name: 'vite:wasm',
  37. resolveId(id) {
  38. if (id === wasmHelperId) {
  39. return id;
  40. }
  41. },
  42. async load(id) {
  43. if (id === wasmHelperId) {
  44. return `export default ${wasmHelperCode}`;
  45. }
  46. if (id.endsWith('.wasm')) {
  47. let { fileName, content, url } = await buildPluginAsset_1.resolveAsset(id, root, publicBase, assetsDir, inlineLimit);
  48. if (!url && fileName && content) {
  49. url =
  50. 'import.meta.ROLLUP_FILE_URL_' +
  51. this.emitFile({
  52. name: fileName,
  53. type: 'asset',
  54. source: content
  55. });
  56. }
  57. return `
  58. import initWasm from "${wasmHelperId}"
  59. export default opts => initWasm(opts, ${JSON.stringify(url)})
  60. `;
  61. }
  62. }
  63. };
  64. };
  65. //# sourceMappingURL=buildPluginWasm.js.map