Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
emscripten-core
GitHub Repository: emscripten-core/emscripten
Path: blob/main/src/pthread_esm_startup.mjs
4129 views
1
/**
2
* @license
3
* Copyright 2025 The Emscripten Authors
4
* SPDX-License-Identifier: MIT
5
*/
6
7
// This file is used as the initial script loaded into pthread workers when
8
// running in WASM_ESM_INTEGRATION mode.
9
// Tyhe point of this file is to delay the loading of the main program module
10
// until the wasm memory has been received via postMessage.
11
12
#if RUNTIME_DEBUG
13
console.log("Running pthread_esm_startup");
14
#endif
15
16
#if ENVIRONMENT_MAY_BE_NODE
17
// Create as web-worker-like an environment as we can.
18
var worker_threads = await import('worker_threads');
19
global.Worker = worker_threads.Worker;
20
var parentPort = worker_threads['parentPort'];
21
parentPort.on('message', (msg) => global.onmessage?.({ data: msg }));
22
Object.assign(globalThis, {
23
self: global,
24
postMessage: (msg) => parentPort['postMessage'](msg),
25
});
26
#endif
27
28
self.onmessage = async (msg) => {
29
#if RUNTIME_DEBUG
30
console.log('pthread_esm_startup', msg.data.cmd);
31
#endif
32
if (msg.data.cmd == 'load') {
33
// Until we initialize the runtime, queue up any further incoming messages
34
// that can arrive while the async import (await import below) is happening.
35
// For examples the `run` message often arrives right away before the import
36
// is complete.
37
let messageQueue = [msg];
38
self.onmessage = (e) => messageQueue.push(e);
39
40
// Now that we have the wasmMemory we can import the main program
41
globalThis.wasmMemory = msg.data.wasmMemory;
42
const prog = await import('./{{{ TARGET_JS_NAME }}}');
43
44
// Now that the import is completed the main program will have installed
45
// its own `onmessage` handler and replaced our handler.
46
// Now we can dispatch any queued messages to this new handler.
47
for (let msg of messageQueue) {
48
await self.onmessage(msg);
49
}
50
51
await prog.default()
52
}
53
};
54
55