/**1* @license2* Copyright 2025 The Emscripten Authors3* SPDX-License-Identifier: MIT4*/56// This file is used as the initial script loaded into pthread workers when7// running in WASM_ESM_INTEGRATION mode.8// The point of this file is to delay the loading of the main program module9// until the wasm memory has been received via postMessage.1011#if RUNTIME_DEBUG12console.log("Running pthread_esm_startup");13#endif1415#if ENVIRONMENT_MAY_BE_NODE16if ({{{ nodeDetectionCode() }}}) {17// Create as web-worker-like an environment as we can.18globalThis.self = globalThis;19var worker_threads = await import('node:worker_threads');20globalThis.Worker = worker_threads.Worker;21var parentPort = worker_threads['parentPort'];22// Deno and Bun already have `postMessage` defined on the global scope and23// deliver messages to `globalThis.onmessage`, so we must not duplicate that24// behavior here if `postMessage` is already present.25if (!globalThis.postMessage) {26parentPort.on('message', (msg) => globalThis.onmessage?.({ data: msg }));27globalThis.postMessage = (msg) => parentPort['postMessage'](msg);28}29}30#endif3132self.onmessage = async (msg) => {33#if RUNTIME_DEBUG34console.log('pthread_esm_startup', msg.data.cmd);35#endif36if (msg.data.cmd == 'load') {37// Until we initialize the runtime, queue up any further incoming messages38// that can arrive while the async import (await import below) is happening.39// For examples the `run` message often arrives right away before the import40// is complete.41let messageQueue = [msg];42self.onmessage = (e) => messageQueue.push(e);4344// Now that we have the wasmMemory we can import the main program45globalThis.wasmMemory = msg.data.wasmMemory;46const prog = await import('./{{{ TARGET_JS_NAME }}}');4748// Now that the import is completed the main program will have installed49// its own `onmessage` handler and replaced our handler.50// Now we can dispatch any queued messages to this new handler.51for (let msg of messageQueue) {52await self.onmessage(msg);53}5455await prog.default()56}57};585960