@@ -466,4 +466,59 @@ jsepDownload:_pp_")
466466 endif ()
467467
468468 set_target_properties (onnxruntime_webassembly PROPERTIES OUTPUT_NAME ${target_name} SUFFIX ".mjs" )
469+
470+ #
471+ # The following POST_BUILD script is a workaround for enabling:
472+ # - using onnxruntime-web with Multi-threading enabled when import from CDN
473+ # - using onnxruntime-web when consumed in some frameworks like Vite
474+ #
475+ # In the use case mentioned above, the file name of the script may be changed. So we need to replace the line:
476+ # `new Worker(new URL("ort-wasm-*.mjs", import.meta.url),`
477+ # with
478+ # `new Worker(new URL(import.meta.url),`
479+ #
480+ # This behavior is introduced in https://github.com/emscripten-core/emscripten/pull/22165. Since it's unlikely to be
481+ # reverted, and there is no config to disable this behavior, we have to use a post-build script to workaround it.
482+ #
483+
484+ # Generate a script to do the post-build work
485+ file (WRITE ${CMAKE_CURRENT_BINARY_DIR} /wasm_post_build.js "
486+ const fs = require('fs');
487+ const path = require('path');
488+
489+ // node wasm_post_build.js <mjsFilePath>
490+ const mjsFilePath = process.argv[2];
491+ let contents = fs.readFileSync(mjsFilePath).toString();
492+
493+ const regex = 'new Worker\\\\ (new URL\\\\ (\" .+?\" , ?import\\\\ .meta\\\\ .url\\\\ ),';
494+ const matches = [...contents.matchAll(new RegExp(regex, 'g'))];
495+ if (matches.length !== 1) {
496+ throw new Error(
497+ `Unexpected number of matches for \" ${regex} \" in \" ${filepath} \" : ${matches.length}.`,
498+ );
499+ }
500+
501+ // Replace the only occurrence.
502+ contents = contents.replace(
503+ new RegExp(regex),
504+ `new Worker(new URL(import.meta.url),`,
505+ );
506+
507+ fs.writeFileSync(mjsFilePath, contents);
508+ "
509+ )
510+
511+ find_program (NODE_EXECUTABLE node required)
512+ if (NOT NODE_EXECUTABLE)
513+ message (FATAL_ERROR "Node is required to run the post-build script" )
514+ endif ()
515+
516+ add_custom_command (
517+ TARGET onnxruntime_webassembly
518+ POST_BUILD
519+ COMMAND ${CMAKE_COMMAND} -E echo "Backup file at $<TARGET_FILE_NAME:onnxruntime_webassembly>.bak"
520+ COMMAND ${CMAKE_COMMAND} -E copy_if_different "$<TARGET_FILE_NAME:onnxruntime_webassembly>" "$<TARGET_FILE_NAME:onnxruntime_webassembly>.bak"
521+ COMMAND ${CMAKE_COMMAND} -E echo "Performing workaround for $<TARGET_FILE_NAME:onnxruntime_webassembly>"
522+ COMMAND ${NODE_EXECUTABLE} "${CMAKE_CURRENT_BINARY_DIR} /wasm_post_build.js" "$<TARGET_FILE_NAME:onnxruntime_webassembly>"
523+ )
469524endif ()
0 commit comments