domain.mjs raw

   1  // domain.mjs — Domain manager for spawn in the Moxie JS runtime.
   2  //
   3  // Each spawned domain is an isolated execution context with its own
   4  // cooperative scheduler. Maps to a Web Worker in the browser.
   5  //
   6  // IPC between domains uses BroadcastChannel.
   7  
   8  let domainCounter = 0;
   9  
  10  // spawn creates a new isolated domain that runs the given async function.
  11  // Each domain gets its own microtask queue via queueMicrotask.
  12  // True Worker isolation requires registering a new Worker scope, which
  13  // needs a separate .js file. For now, simulate with a BroadcastChannel-
  14  // isolated microtask domain.
  15  export function spawn(asyncFn) {
  16      const domainId = ++domainCounter;
  17      const channel = new BroadcastChannel(`moxie-domain-${domainId}`);
  18      queueMicrotask(async () => {
  19          try {
  20              await asyncFn();
  21          } catch (e) {
  22              console.error(`[domain ${domainId}] panic:`, e);
  23          } finally {
  24              channel.close();
  25          }
  26      });
  27      return { id: domainId, channel };
  28  }
  29