Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
emscripten-core
GitHub Repository: emscripten-core/emscripten
Path: blob/main/src/pthread_esm_startup.mjs
6161 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
// The 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
if ({{{ nodeDetectionCode() }}}) {
18
// Create as web-worker-like an environment as we can.
19
globalThis.self = globalThis;
20
var worker_threads = await import('node:worker_threads');
21
globalThis.Worker = worker_threads.Worker;
22
var parentPort = worker_threads['parentPort'];
23
// Deno and Bun already have `postMessage` defined on the global scope and
24
// deliver messages to `globalThis.onmessage`, so we must not duplicate that
25
// behavior here if `postMessage` is already present.
26
if (!globalThis.postMessage) {
27
parentPort.on('message', (msg) => globalThis.onmessage?.({ data: msg }));
28
globalThis.postMessage = (msg) => parentPort['postMessage'](msg);
29
}
30
}
31
#endif
32
33
self.onmessage = async (msg) => {
34
#if RUNTIME_DEBUG
35
console.log('pthread_esm_startup', msg.data.cmd);
36
#endif
37
if (msg.data.cmd == 'load') {
38
// Until we initialize the runtime, queue up any further incoming messages
39
// that can arrive while the async import (await import below) is happening.
40
// For examples the `run` message often arrives right away before the import
41
// is complete.
42
let messageQueue = [msg];
43
self.onmessage = (e) => messageQueue.push(e);
44
45
// Now that we have the wasmMemory we can import the main program
46
globalThis.wasmMemory = msg.data.wasmMemory;
47
const prog = await import('./{{{ TARGET_JS_NAME }}}');
48
49
// Now that the import is completed the main program will have installed
50
// its own `onmessage` handler and replaced our handler.
51
// Now we can dispatch any queued messages to this new handler.
52
for (let msg of messageQueue) {
53
await self.onmessage(msg);
54
}
55
56
await prog.default()
57
}
58
};
59
60