host.html raw

   1  <!DOCTYPE html>
   2  <html>
   3  <head><meta charset="utf-8"><title>moxie wasm host</title></head>
   4  <body>
   5  <script type="module">
   6    // Minimal host page: loads a Moxie wasm module through jsruntime/loader.mjs
   7    // and captures its stdout. The module's putchar writes one byte per
   8    // fd_write call, so bytes are accumulated into lines here.
   9    const log = [];
  10    let line = '';
  11    window.__logs = log;
  12    window.__done = false;
  13    window.__error = null;
  14    const errors = [];
  15    window.__consoleErrors = errors;
  16    console.log = (...a) => {
  17      for (const x of a) line += String(x);
  18      // Flush complete lines as they arrive. A module returns from _start and is
  19      // then driven by the page, so some of its output happens AFTER load()
  20      // resolves; a single blob flushed at the end would lose every late line.
  21      let i;
  22      while ((i = line.indexOf('\n')) >= 0) { log.push(line.slice(0, i + 1)); line = line.slice(i + 1); }
  23    };
  24    console.error = (...a) => { errors.push(a.map(String).join(' ')); };
  25    window.addEventListener('error', e => { window.__error = String(e.message); });
  26    // The generic panic action calls this hook after it has stopped every domain
  27    // (see jsruntime/host.mjs). A panic-test fixture reads it as the proof that
  28    // the action ran, not merely that a message was printed.
  29    window.__moxie_panic = (reason) => { window.__panicReason = String(reason); };
  30    // This page is the TEST host: ask jsruntime/host.mjs for load-only stubs for
  31    // import namespaces a fixture may LINK but never call (gojs). A production
  32    // page does not set it, so the same module fails loudly there instead.
  33    globalThis.__moxie_test_stubs = true;
  34    const params = new URLSearchParams(location.search);
  35    try {
  36      // ?host=<url> loads an EMITTED bundle host (the page bootstrap `moxie build
  37      // -target wasm` writes beside the module, with its own $runtime/ copy), so
  38      // the harness can run the scaffolding a real app would ship rather than the
  39      // repository's own jsruntime/. Without it, the repository loader.
  40      const host = params.get('host');
  41      const app = params.get('app');
  42      if (host) {
  43        const m = await import(host);
  44        await m.start();
  45      } else if (!params.get('bundle')) {
  46        // A page that starts a second bundle is a supervisor, not the host of a
  47        // root module: loading /app.wasm as well would run whatever fixture was
  48        // copied there last.
  49        const { load } = await import('/jsruntime/loader.mjs');
  50        // ?app=<url> names the bundle's own bridge module, for a fixture that
  51        // imports symbols only its application can answer.
  52        await load('/app.wasm', app ? { appBridge: app } : {});
  53      }
  54    } catch (e) {
  55      window.__error = String((e && e.stack) || e);
  56    }
  57    // ?bundle=<url> starts a SECOND bundle through the runtime staged beside it,
  58    // the way an app starts its store or feed worker: the page keeps the port, the
  59    // bundle's bridge answers it, and both directions are checked.
  60    const bundleUrl = params.get('bundle');
  61    if (bundleUrl) {
  62      try {
  63        const abs = new URL(bundleUrl, location.href).href;
  64        const runtimeHost = new URL('./$runtime/host.mjs', abs).href;
  65        const { startBundle } = await import(runtimeHost);
  66        const b = startBundle(abs, { appBridge: params.get('bridge') || null });
  67        b.port.onmessage = (e) => {
  68          window.__bundle = { got: String(e.data) };
  69          b.port.postMessage('hello-from-page');
  70        };
  71        await b.ready;
  72      } catch (e) {
  73        window.__bundleError = String((e && e.stack) || e);
  74      }
  75    }
  76    // ?sw=<url> registers the emitted service worker through the bundle's own
  77    // registration glue, and waits for it to activate before reporting the page
  78    // loaded: a worker that never activates is a failed boot, not a slow one.
  79    const swUrl = new URLSearchParams(location.search).get('sw');
  80    if (swUrl) {
  81      try {
  82        await new Promise((resolve) => {
  83          const s = document.createElement('script');
  84          s.src = swUrl;
  85          s.onload = resolve;
  86          s.onerror = () => { window.__swError = 'registration script did not load'; resolve(); };
  87          document.head.appendChild(s);
  88        });
  89        // Poll the registrations rather than awaiting navigator.serviceWorker.ready:
  90        // ready() is scoped to THIS document, and the page lives outside the
  91        // worker's scope in this harness, so it would never resolve even with the
  92        // worker activated. A worker that never activates must also not hang the
  93        // run - the driver waits for __done - so the poll has a deadline and
  94        // reports the state it reached.
  95        const deadline = Date.now() + 25000;
  96        let state = 'timeout';
  97        let scope = '';
  98        for (;;) {
  99          const regs = await navigator.serviceWorker.getRegistrations();
 100          const r = regs[0];
 101          if (r) {
 102            scope = r.scope;
 103            if (r.active && r.active.state === 'activated') { state = 'activated'; break; }
 104          }
 105          if (Date.now() >= deadline) break;
 106          await new Promise((res) => setTimeout(res, 200));
 107        }
 108        const regs = await navigator.serviceWorker.getRegistrations();
 109        window.__sw = {
 110          state: state,
 111          scope: scope,
 112          regs: regs.map((r) => ({
 113            scope: r.scope,
 114            installing: r.installing ? r.installing.state : null,
 115            waiting: r.waiting ? r.waiting.state : null,
 116            active: r.active ? r.active.state : null,
 117          })),
 118        };
 119      } catch (e) {
 120        window.__swError = String((e && e.stack) || e);
 121      }
 122    }
 123    // No partial-line flush here: the hub drains its log queue on a task, so a
 124    // line may still be arriving when load() resolves. Flushing now would split
 125    // one program line into a partial entry plus the completed one. Two task
 126    // turns let the hub's scheduled drain run (and any port message queued with
 127    // it) before the page reports done, so the run's output is complete when
 128    // run.py reads it.
 129    await new Promise((r) => setTimeout(r, 0));
 130    await new Promise((r) => setTimeout(r, 0));
 131    window.__done = true;
 132  </script>
 133  </body>
 134  </html>
 135