worker.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. Runs the AGI playground engine (agi.wasm, the real Otto interpreter built
  3. from scripts/agidocgen/playground) off the page's main thread. The page
  4. stops a run by terminating this worker and starting a new one.
  5. page -> worker: {type:"run", req, files} | {type:"ws", text} | {type:"wsclose"}
  6. worker -> page: {type:"ready"} | {type:"fail", message}
  7. {type:"event", kind:"log"|"ws", payload}
  8. {type:"done", json, files}
  9. */
  10. "use strict";
  11. importScripts("wasm_exec.js");
  12. var ready = (function () {
  13. var go = new Go();
  14. var load = WebAssembly.instantiateStreaming
  15. ? WebAssembly.instantiateStreaming(fetch("agi.wasm"), go.importObject).catch(function () {
  16. // Served without the application/wasm type: fall back to bytes.
  17. return fetch("agi.wasm").then(function (r) { return r.arrayBuffer(); })
  18. .then(function (b) { return WebAssembly.instantiate(b, go.importObject); });
  19. })
  20. : fetch("agi.wasm").then(function (r) { return r.arrayBuffer(); })
  21. .then(function (b) { return WebAssembly.instantiate(b, go.importObject); });
  22. return load.then(function (result) {
  23. go.run(result.instance);
  24. return new Promise(function (resolve) {
  25. (function wait() {
  26. if (self.agiPlayground) resolve(self.agiPlayground);
  27. else setTimeout(wait, 5);
  28. })();
  29. });
  30. });
  31. })();
  32. ready.then(function (api) {
  33. postMessage({ type: "ready", defaults: JSON.parse(api.defaults()) });
  34. }, function (err) {
  35. postMessage({ type: "fail", message: String(err && err.message || err) });
  36. });
  37. onmessage = function (e) {
  38. var m = e.data;
  39. ready.then(function (api) {
  40. if (m.type === "run") {
  41. api.run(JSON.stringify(m.req), m.files || [], function (kind, payload) {
  42. postMessage({ type: "event", kind: kind, payload: payload });
  43. }).then(function (out) {
  44. var files = [];
  45. var transfer = [];
  46. for (var i = 0; i < out.files.length; i++) {
  47. var f = out.files[i];
  48. files.push({ path: f.path, dir: f.dir, mtime: f.mtime, data: f.data });
  49. if (f.data) transfer.push(f.data.buffer);
  50. }
  51. postMessage({ type: "done", json: out.json, files: files }, transfer);
  52. });
  53. } else if (m.type === "ws") {
  54. api.wsPush(m.text);
  55. } else if (m.type === "wsclose") {
  56. api.wsClose();
  57. }
  58. });
  59. };