/ interactive_tutorials / hardening_softening
Sign in
interactive_tutorials / hardening_softening
Run the orbits worker as a classic script on sandboxed sites
In a sandboxed page no module worker starts, so fetch the worker's modules and run them as one classic script, each in its own scope; compute on the main thread if that fails too.
Jeremy Magland <jmagland@flatironinstitute.org> committed commit 0d7d5b706eba parent f598eb6 Browse files
1 changed file+68−19
app/js/phase-page.jsmodified+68−19View file
@@ -44,30 +44,79 @@ function tickStep(range) {
4444
4545 // A worker running orbits-worker.js. A sandboxed page (one served with an
4646 // opaque origin, as on the vault's sites) may not start a worker from its own
47-// URL, so then start one from a small in-memory module that imports it; and if
48-// that fails too, compute on the main thread, through the same messages.
47+// URL, nor any module worker; so there, fetch the worker's modules and run
48+// them as one classic script (see classicWorker). If that fails too, compute
49+// on the main thread, through the same messages. Messages posted while the
50+// worker is being set up wait for it.
4951 function createOrbitsWorker() {
50- const url = new URL('./orbits-worker.js', import.meta.url);
51- try {
52- return new Worker(url, { type: 'module' });
53- } catch {
52+ if (self.origin !== 'null') {
5453 try {
55- const blob = new Blob([`import ${JSON.stringify(url.href)};`], { type: 'text/javascript' });
56- return new Worker(URL.createObjectURL(blob), { type: 'module' });
54+ return new Worker(new URL('./orbits-worker.js', import.meta.url), { type: 'module' });
5755 } catch {
58- const fallback = {
59- onmessage: null,
60- terminate() { this.onmessage = null; },
61- postMessage({ id, p, from }) {
62- setTimeout(() => {
63- const data = from ? { id, orbit: computeOrbitFrom(p, from) } : { id, ...computeOrbits(p) };
64- fallback.onmessage?.({ data });
65- }, 0);
66- },
67- };
68- return fallback;
56+ // fall through
6957 }
7058 }
59+ const proxy = {
60+ onmessage: null,
61+ queue: [],
62+ target: null,
63+ stopped: false,
64+ postMessage(m) {
65+ if (this.target) this.target.postMessage(m);
66+ else this.queue.push(m);
67+ },
68+ terminate() {
69+ this.stopped = true;
70+ this.target?.terminate();
71+ },
72+ };
73+ const attach = (target) => {
74+ proxy.target = target;
75+ target.onmessage = (e) => proxy.onmessage?.(e);
76+ if (proxy.stopped) target.terminate();
77+ else proxy.queue.splice(0).forEach((m) => target.postMessage(m));
78+ };
79+ classicWorker(['./duffing.js', './orbits.js', './orbits-worker.js'])
80+ .then(attach)
81+ .catch(() => attach(mainThreadWorker()));
82+ return proxy;
83+}
84+
85+// A classic worker running these modules (relative to this file, in order),
86+// each in its own scope: its imports read from the modules before it, and its
87+// exports (export const / function) are collected for the ones after.
88+async function classicWorker(paths) {
89+ const sources = await Promise.all(paths.map((path) => fetch(new URL(path, import.meta.url)).then((r) => {
90+ if (!r.ok) throw new Error(`${path}: ${r.status}`);
91+ return r.text();
92+ })));
93+ const code = sources.map((src, i) => {
94+ const names = [];
95+ const body = src
96+ .replace(/^import \{([^}]*)\} from '([^']+)';$/gm, (m, list, from) => `const {${list}} = __modules[${JSON.stringify(from)}];`)
97+ .replace(/^export (const|function|let) (\w+)/gm, (m, kind, name) => {
98+ names.push(name);
99+ return `${kind} ${name}`;
100+ });
101+ return `__modules[${JSON.stringify(paths[i])}] = (() => {\n${body}\nreturn { ${names.join(', ')} };\n})();`;
102+ }).join('\n');
103+ const url = URL.createObjectURL(new Blob([`const __modules = {};\n${code}`], { type: 'text/javascript' }));
104+ return new Worker(url);
105+}
106+
107+// the worker's job on the main thread, through the same messages
108+function mainThreadWorker() {
109+ const w = {
110+ onmessage: null,
111+ postMessage({ id, p, from }) {
112+ setTimeout(() => {
113+ const data = from ? { id, orbit: computeOrbitFrom(p, from) } : { id, ...computeOrbits(p) };
114+ w.onmessage?.({ data });
115+ }, 0);
116+ },
117+ terminate() { w.onmessage = null; },
118+ };
119+ return w;
71120 }
72121
73122 export function createPhasePage({ controls, container, params, sliders = {}, presets, instruments = false }) {
↑↓ move↵openescclose