roamwright 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Route weighted jobs to FIFO workers. Each worker receives { job, input } and
3
+ * replies in order with { result } or { error }. Supply prestarted workers to
4
+ * adopt them immediately, and a synchronous factory to restart after idle.
5
+ */
6
+ export function createPool({ startWorkers, initialWorkers, idleMs = 4000, warn = message => console.warn(message) } = {}) {
7
+ const slots = [];
8
+ const preparations = new Map();
9
+ let broken = typeof startWorkers !== 'function',
10
+ idle = 0,
11
+ held = 0;
12
+
13
+ const pooled = () => !broken;
14
+ const poolSize = () => slots.length;
15
+
16
+ function rest() {
17
+ for (const { worker } of slots) {
18
+ worker.onmessage = worker.onerror = worker.onmessageerror = null;
19
+ worker.terminate();
20
+ }
21
+ slots.length = 0;
22
+ }
23
+ function giveUp(reason) {
24
+ if (broken) return;
25
+ warn(`pool: ${reason}; the work is done on the page from now on`);
26
+ broken = true;
27
+ const waiting = slots.flatMap(slot => slot.tasks);
28
+ clearTimeout(idle);
29
+ rest();
30
+ for (const task of waiting) task.refuse(new Error('pool: ' + reason));
31
+ }
32
+ function adopt(workers) {
33
+ for (const worker of workers) {
34
+ const slot = { worker, tasks: [], holds: new Set() };
35
+ worker.onmessage = ({ data }) => finish(slot, data);
36
+ worker.onerror = event => giveUp(event.message || 'a worker could not start');
37
+ worker.onmessageerror = () => giveUp('an answer could not be read');
38
+ slots.push(slot);
39
+ }
40
+ if (!workers.length || workers.some(worker => worker.failed)) giveUp('the workers could not start');
41
+ else restWhenIdle();
42
+ }
43
+ function restWhenIdle() {
44
+ clearTimeout(idle);
45
+ if (slots.length && !held && slots.every(slot => !slot.tasks.length)) idle = setTimeout(rest, idleMs);
46
+ }
47
+ function keepAwake(until) {
48
+ held++;
49
+ clearTimeout(idle);
50
+ const release = () => {
51
+ held--;
52
+ restWhenIdle();
53
+ };
54
+ until.then(release, release);
55
+ }
56
+ function refusal(job, reason) {
57
+ warn(`pool: ${job} refused (${reason}); worked out on the page instead`);
58
+ return new Error(`pool: ${job}: ${reason}`);
59
+ }
60
+ // Jobs queued after a failed preparation must reject, up to the next attempt to prepare this worker.
61
+ function spoil(slot, name) {
62
+ for (const later of slot.tasks) {
63
+ if (later.prepares === name) return;
64
+ if (later.needs === name) later.spoiled = name;
65
+ }
66
+ slot.holds.delete(name);
67
+ }
68
+ function finish(slot, answer) {
69
+ const task = slot.tasks.shift();
70
+ if (answer.error && task.prepares) spoil(slot, task.prepares);
71
+ if (answer.error) task.refuse(refusal(task.job, answer.error));
72
+ else if (task.spoiled) task.refuse(refusal(task.job, `its preparation, ${task.spoiled}, failed`));
73
+ else task.keep(answer.result);
74
+ restWhenIdle();
75
+ }
76
+ function send(slot, job, input, transfer, cost = 1, needs = null, prepares = null) {
77
+ return new Promise((keep, refuse) => {
78
+ try {
79
+ slot.worker.postMessage({ job, input }, transfer);
80
+ } catch (error) {
81
+ if (prepares) slot.holds.delete(prepares);
82
+ refuse(refusal(job, error.message));
83
+ return;
84
+ }
85
+ slot.tasks.push({ job, keep, refuse, cost, needs, prepares, spoiled: null });
86
+ clearTimeout(idle);
87
+ });
88
+ }
89
+ function awake() {
90
+ if (!broken && !slots.length) {
91
+ try {
92
+ adopt(startWorkers());
93
+ } catch (error) {
94
+ giveUp(error.message);
95
+ }
96
+ }
97
+ return slots;
98
+ }
99
+ const UNNAMED = { input: undefined, cost: 1 };
100
+ const noWorkers = () => Promise.reject(new Error('pool: no workers'));
101
+ const unheard = () => {};
102
+ const load = slot => slot.tasks.reduce((sum, task) => sum + task.cost, 0);
103
+ // Costs include both running and queued jobs. Dispatch immediately, even when the main thread is busy.
104
+ const leastBusy = list => list.reduce((a, b) => (load(b) < load(a) ? b : a));
105
+ // Register the input to send once per worker before a job that names this preparation.
106
+ function prepare(name, input, cost = 1) {
107
+ preparations.set(name, { input, cost });
108
+ for (const slot of slots) slot.holds.delete(name);
109
+ }
110
+ function run(job, input, transfer = [], needs = null, cost = 1) {
111
+ if (!awake().length) return noWorkers();
112
+ let least = leastBusy(slots);
113
+ if (needs && !least.holds.has(needs)) {
114
+ const holding = slots.filter(slot => slot.holds.has(needs)),
115
+ preparation = preparations.get(needs) ?? UNNAMED;
116
+ if (holding.length && load(leastBusy(holding)) <= load(least) + preparation.cost) least = leastBusy(holding);
117
+ else {
118
+ least.holds.add(needs);
119
+ send(least, needs, preparation.input, [], preparation.cost, null, needs).catch(unheard);
120
+ if (!least.holds.has(needs)) return Promise.reject(new Error(`pool: ${job}: ${needs} could not be sent`));
121
+ }
122
+ }
123
+ return send(least, job, input, transfer, cost, needs);
124
+ }
125
+ function runOrHere(job, inputOf, here, cost = 1, needs = null) {
126
+ if (broken) return Promise.resolve().then(here);
127
+ return run(job, inputOf(), [], needs, cost).catch(here);
128
+ }
129
+ function spread(name, count) {
130
+ const preparation = preparations.get(name);
131
+ if (!preparation) return;
132
+ const others = awake().filter(slot => !slot.holds.has(name)),
133
+ more = Math.min(count, slots.length) - (slots.length - others.length);
134
+ for (const slot of others.sort((a, b) => load(a) - load(b)).slice(0, Math.max(0, more))) {
135
+ slot.holds.add(name);
136
+ send(slot, name, preparation.input, [], preparation.cost, null, name).catch(unheard);
137
+ }
138
+ }
139
+ // The worker protocol reserves the load job for fetching a named job's implementation.
140
+ function ready(job) {
141
+ for (const slot of awake())
142
+ if (!slot.holds.has(job)) {
143
+ send(slot, 'load', job, []).catch(unheard);
144
+ slot.holds.add(job);
145
+ }
146
+ }
147
+ function runOnEach(job, input) {
148
+ if (!awake().length) return noWorkers();
149
+ return Promise.all(slots.map(slot => send(slot, job, input, [])));
150
+ }
151
+ if (!broken && initialWorkers) adopt(initialWorkers);
152
+ return { keepAwake, pooled, poolSize, prepare, ready, run, runOnEach, runOrHere, spread };
153
+ }
@@ -0,0 +1,194 @@
1
+ import { LEVELS } from './quality-store.js';
2
+
3
+ const FRAME_MS = 1000 / 60, // the target: sixty frames a second
4
+ SLOW_FPS = 57, // fewer frames than this in a second miss it
5
+ HELD_BACK = 2.5, // frames that come this many times slower than they cost are held back by the browser (a page not in front, a power saver), not by the work
6
+ ROOM = 0.8, // a preset that costs less than this share of a frame holds the target with room to spare
7
+ PROBE_MS = 1000, // how often a frame is timed
8
+ WINDOW = 6, // the timed frames a verdict is drawn from (their median)
9
+ VERDICTS = 2, // the verdicts in a row that step the preset down: one heavy view or one hitch does not
10
+ TRIAL_VERDICTS = 3, // and the roomy ones in a row before the next preset up is tried
11
+ CEILING_MS = 180000, // a drawn size that missed the target is not tried again for this long: the miss may have been a passing load
12
+ // nor a preset that missed, for a minute the first time and longer each time it misses again in a visit: a first miss is
13
+ // often the world still arriving, and a phone must not sit at Low for three minutes for it; a preset that keeps missing
14
+ // is not tried every minute, since each trial makes the houses, the grass and the shaders again
15
+ PRESET_CEILINGS_MS = [60000, 180000, 600000],
16
+ SETTLE_MS = 3000, // after a change the houses, the grass and the shaders are made again: nothing is timed meanwhile
17
+ ARRIVAL_SETTLE_MS = 10000, // nor while the world is still arriving: its first frames, and those after the visitor enters it
18
+ // the shares of each side of the picture the world may be drawn at, the full size first: about 0.72, 0.56 and 0.45 of the pixels
19
+ SCALES = [1, 0.85, 0.75, 0.67];
20
+ export function createQualityFit({ state, post, cardBlocks, cardDone, store, deviceQuality, applyQuality, setDrawScale, warmShaders, emit, noteLog }) {
21
+ const { keepChoice, keepFit, keepScale, keptChoice, keptFit, keptOnce, keptScale } = store;
22
+ const fit = {
23
+ running: false,
24
+ chosen: null, // the preset chosen by hand, if it is not the suggested one
25
+ suggested: 'high',
26
+ ceiling: LEVELS.length - 1, // the highest preset worth trying for now, and when the presets above it may be tried again
27
+ ceilingUntil: 0,
28
+ misses: 0, // how often a preset has missed the target in this visit
29
+ costs: [], // the timed frames of the window, in milliseconds
30
+ timing: null, // the frame being timed: when its script began, and when the card had finished what came before it
31
+ frames: 0, // the frames drawn since the window began, and when it began
32
+ since: 0,
33
+ next: 0, // when the next frame is timed
34
+ slow: 0, // verdicts in a row that the preset is too heavy, and that it leaves room
35
+ roomy: 0,
36
+ scaleAt: 0, // the index in SCALES of the share the world is drawn at
37
+ scaleTop: 0, // the largest share worth trying for now (its index), and when the larger ones may be tried again
38
+ scaleTopUntil: 0,
39
+ };
40
+
41
+ // Applies a preset, drawn at SCALES[scaleAt], and begins timing afresh once the world has been made again for it.
42
+ function change(name, scaleAt = 0) {
43
+ fit.scaleAt = scaleAt;
44
+ setDrawScale(SCALES[scaleAt], true); // applyQuality sizes the picture
45
+ applyQuality(name);
46
+ keepScale(name, SCALES[scaleAt]);
47
+ warmShaders();
48
+ rest();
49
+ }
50
+ // The world is drawn at SCALES[at] of each side.
51
+ function setScale(at) {
52
+ fit.scaleAt = at;
53
+ keepScale(state.quality, SCALES[at]);
54
+ setDrawScale(SCALES[at]); // a resize, which begins the timing afresh
55
+ }
56
+ // May the fit draw the world smaller rather than step down? Where post-processing draws it, at Medium, or at a preset chosen by hand.
57
+ const scalable = () => post.on && (!!fit.chosen || state.quality === 'medium');
58
+ function rest() {
59
+ fit.timing = null;
60
+ fit.costs.length = 0;
61
+ fit.frames = 0;
62
+ fit.slow = fit.roomy = 0;
63
+ fit.next = performance.now() + SETTLE_MS;
64
+ }
65
+ // The world has begun to be drawn, or the visitor has just entered it: figures are being built and geometry is going to the
66
+ // card, and frames are slow for a few seconds whatever the preset. Nothing is timed until that has passed.
67
+ function settleQuality() {
68
+ rest();
69
+ fit.next = performance.now() + ARRIVAL_SETTLE_MS;
70
+ }
71
+ // A picture of another size is another load, and the change itself costs frames (a phone turned on its side): what was
72
+ // timed before it is forgotten.
73
+
74
+ // Opens with the preset chosen by hand, else the one that fitted last time, else the guess from the device; or, on a page that
75
+ // loaded itself afresh because the card dropped its picture, with the lower one that page asked for, for this page only.
76
+ function startQuality() {
77
+ const chosen = keptChoice();
78
+ fit.suggested = keptFit() ?? deviceQuality();
79
+ fit.chosen = chosen;
80
+ fit.running = true;
81
+ const name = keptOnce(true) ?? fit.chosen ?? fit.suggested;
82
+ fit.scaleAt = Math.max(0, SCALES.indexOf(keptScale(name)));
83
+ setDrawScale(SCALES[fit.scaleAt], true);
84
+ applyQuality(name);
85
+ rest();
86
+ }
87
+ // The preset suggested for this device.
88
+ const suggestedQuality = () => fit.suggested;
89
+ // A preset chosen by hand is kept in the browser and holds on every later visit, whatever the device is found to hold and
90
+ // whichever build is out; null goes back to following the device.
91
+ function chooseQuality(name) {
92
+ fit.chosen = name;
93
+ keepChoice(name);
94
+ change(name ?? fit.suggested);
95
+ }
96
+ // How long the graphics card worked on the frame timed last, in milliseconds; null until one has been timed.
97
+ const cardTime = () => fit.card ?? null;
98
+ // The preset chosen by hand, if one was.
99
+ const chosenQuality = () => fit.chosen;
100
+ // Stops or resumes the fitting, for a measurement that must keep one preset.
101
+ function holdQuality(held) {
102
+ fit.running = !held;
103
+ rest();
104
+ }
105
+ // The suggestion moves to LEVELS[level]: applied, unless another preset was chosen by hand.
106
+ function suggest(level) {
107
+ const name = LEVELS[level];
108
+ if (name === fit.suggested) return;
109
+ fit.suggested = name;
110
+ keepFit(name);
111
+ if (fit.chosen || state.quality === name)
112
+ emit('quality', state.quality); // only the suggestion shown beside it changes
113
+ else if (level > LEVELS.indexOf(state.quality) && name === 'medium')
114
+ change(name, SCALES.length - 1); // Medium is tried from below at its smallest, and drawn larger as frames allow
115
+ else change(name);
116
+ }
117
+ // Called at the start of every frame: is this one to be timed? If so, a fence goes into the card's queue before it.
118
+ function probeDue(now) {
119
+ if (!fit.running) return false;
120
+ if (fit.frames++ === 0) fit.since = now;
121
+ if (now < fit.next || fit.timing) return false;
122
+ fit.timing = { began: performance.now(), before: cardDone() };
123
+ return true;
124
+ }
125
+ // A timed frame has been handed over (it began at `now` on the frame clock). Its cost is known once the card has drawn it:
126
+ // from when the script began, or from when the card was free of earlier frames if that came later, until the card was done.
127
+ function probed(now) {
128
+ const timing = fit.timing,
129
+ handed = performance.now();
130
+ Promise.all([timing.before, cardDone()]).then(([before, after]) => {
131
+ if (fit.timing !== timing) return; // the fitting was stopped or begun afresh meanwhile
132
+ fit.timing = null;
133
+ if (before.gaveUp || after.gaveUp) {
134
+ fit.next = now + PROBE_MS; // no answer from the card this time: nothing is learnt from this frame
135
+ return;
136
+ }
137
+ const script = handed - timing.began,
138
+ // where the wait stops the script, the time between the two waits is the script's work and then the card's
139
+ card = cardBlocks() ? after.at - before.at - script : after.at - (before.prompt ? timing.began : before.at);
140
+ fit.card = Math.max(0, card);
141
+ verdict(Math.max(script, card), now);
142
+ });
143
+ }
144
+ // Frames too slow for the preset: a performance problem in the page's log, with what was measured and what the fit does.
145
+ function slowNoted(cost, fps, at) {
146
+ const does =
147
+ scalable() && fit.scaleAt < SCALES.length - 1
148
+ ? `drawn smaller, at ${SCALES[fit.scaleAt + 1]} of each side`
149
+ : at > 0
150
+ ? `stepped down to ${LEVELS[at - 1]}${fit.chosen ? ' as suggested (the preset chosen by hand stays)' : ''}`
151
+ : 'already at the lowest preset';
152
+ noteLog(
153
+ 'perf',
154
+ `frames too slow: ${cost.toFixed(1)} ms a frame, ${fps.toFixed(0)} shown a second, at ${state.quality} drawn at ${SCALES[fit.scaleAt]}: ${does}`,
155
+ );
156
+ }
157
+ // A timed frame's cost joins the window. When the window is full, its verdict.
158
+ function verdict(frameCost, now) {
159
+ fit.costs.push(frameCost);
160
+ fit.next = now + PROBE_MS;
161
+ if (fit.costs.length < WINDOW) return;
162
+ const cost = fit.costs.sort((a, b) => a - b)[WINDOW >> 1],
163
+ fps = ((fit.frames - 1) * 1000) / (now - fit.since),
164
+ at = LEVELS.indexOf(state.quality);
165
+ fit.costs.length = 0;
166
+ fit.frames = 0;
167
+ // too heavy: fewer than sixty frames are being shown, and not because the browser holds back frames that cost little
168
+ fit.slow = cost > FRAME_MS * ROOM && fps < SLOW_FPS && 1000 / fps < cost * HELD_BACK ? fit.slow + 1 : 0;
169
+ fit.roomy = cost < FRAME_MS * ROOM ? fit.roomy + 1 : 0;
170
+ if (now > fit.ceilingUntil) fit.ceiling = LEVELS.length - 1;
171
+ if (now > fit.scaleTopUntil) fit.scaleTop = 0;
172
+ if (fit.slow >= VERDICTS) slowNoted(cost, fps, at);
173
+ if (fit.slow >= VERDICTS && scalable() && fit.scaleAt < SCALES.length - 1) {
174
+ fit.slow = 0;
175
+ fit.scaleTop = fit.scaleAt + 1;
176
+ fit.scaleTopUntil = now + CEILING_MS;
177
+ setScale(fit.scaleAt + 1);
178
+ } else if (fit.slow >= VERDICTS) {
179
+ fit.slow = 0;
180
+ fit.ceiling = Math.max(0, at - 1);
181
+ fit.ceilingUntil = now + PRESET_CEILINGS_MS[Math.min(fit.misses++, PRESET_CEILINGS_MS.length - 1)];
182
+ suggest(Math.min(LEVELS.indexOf(fit.suggested), fit.ceiling));
183
+ } else if (fit.roomy >= TRIAL_VERDICTS && fit.scaleAt > fit.scaleTop) {
184
+ fit.roomy = 0;
185
+ setScale(fit.scaleAt - 1);
186
+ } else if (fit.chosen) {
187
+ if (cost <= FRAME_MS && at > LEVELS.indexOf(fit.suggested)) suggest(at); // chosen by hand above the suggestion, and it holds
188
+ } else if (fit.roomy >= TRIAL_VERDICTS && at < fit.ceiling && fit.scaleAt === 0) {
189
+ fit.roomy = 0;
190
+ suggest(at + 1);
191
+ }
192
+ }
193
+ return { cardTime, chooseQuality, chosenQuality, holdQuality, probeDue, probed, settleQuality, startQuality, suggestedQuality, rest };
194
+ }
@@ -0,0 +1,58 @@
1
+ export const LEVELS = ['low', 'medium', 'high'];
2
+
3
+ export function createQualityStore(namespace) {
4
+ const ONCE = `${namespace}:quality-once`, // in the tab's own storage: the preset its next page opens with, whatever is kept
5
+ CHOSEN = `${namespace}:quality`,
6
+ FITTED = `${namespace}:quality-fit`,
7
+ SCALE = `${namespace}:quality-scale`;
8
+
9
+ function read(key) {
10
+ try {
11
+ const kept = localStorage.getItem(key);
12
+ return LEVELS.includes(kept) ? kept : null;
13
+ } catch {
14
+ return null; // no storage (a private window)
15
+ }
16
+ }
17
+ function write(key, value) {
18
+ try {
19
+ if (value) localStorage.setItem(key, value);
20
+ else localStorage.removeItem(key);
21
+ } catch {
22
+ // no storage: it holds for this page
23
+ }
24
+ }
25
+ // The share of each side the preset `name` was last drawn at, if it was found for that preset.
26
+ function keptScale(name) {
27
+ try {
28
+ const kept = JSON.parse(localStorage.getItem(SCALE));
29
+ return kept?.name === name && kept.scale > 0 && kept.scale <= 1 ? kept.scale : 1;
30
+ } catch {
31
+ return 1;
32
+ }
33
+ }
34
+ const keepScale = (name, scale) => write(SCALE, JSON.stringify({ name, scale }));
35
+ // The preset this tab's next page opens with for once, and that preset on the page it was left for (read twice there: by the
36
+ // renderer for its canvas, then by the fit, which lets go of it with `taken`).
37
+ function keepOnce(name) {
38
+ try {
39
+ sessionStorage.setItem(ONCE, name);
40
+ } catch {
41
+ // no storage: the next page opens as kept
42
+ }
43
+ }
44
+ function keptOnce(taken = false) {
45
+ try {
46
+ const kept = sessionStorage.getItem(ONCE);
47
+ if (taken) sessionStorage.removeItem(ONCE);
48
+ return LEVELS.includes(kept) ? kept : null;
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+ const keptChoice = () => read(CHOSEN),
54
+ keptFit = () => read(FITTED),
55
+ keepChoice = name => write(CHOSEN, name),
56
+ keepFit = name => write(FITTED, name);
57
+ return { keepChoice, keepFit, keepOnce, keepScale, keptChoice, keptFit, keptOnce, keptScale };
58
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Test mesh visibility using asynchronous WebGL 2 occlusion queries from the
3
+ * supplied camera. A stale or unavailable answer is treated as visible.
4
+ * watchSeen takes ownership of the mesh's before/after render callbacks.
5
+ */
6
+ export function createVisibilityQueries({ renderer, camera, frame, freshFrames = 4, patienceMs = 500, now = () => performance.now() }) {
7
+ function watchSeen(mesh) {
8
+ const gl = renderer.getContext(),
9
+ watch = { query: null, asking: false, waiting: false, seen: true, asked: -Infinity, askedAt: 0 };
10
+ mesh.onBeforeRender = (_renderer, _scene, viewer) => {
11
+ if (viewer !== camera || watch.waiting) return;
12
+ watch.query ??= gl.createQuery();
13
+ gl.beginQuery(gl.ANY_SAMPLES_PASSED_CONSERVATIVE, watch.query);
14
+ watch.asking = true;
15
+ };
16
+ mesh.onAfterRender = () => {
17
+ if (!watch.asking) return;
18
+ gl.endQuery(gl.ANY_SAMPLES_PASSED_CONSERVATIVE);
19
+ watch.asking = false;
20
+ watch.waiting = true;
21
+ watch.asked = frame();
22
+ watch.askedAt = now();
23
+ };
24
+ return watch;
25
+ }
26
+ function hidden(watch) {
27
+ const gl = renderer.getContext();
28
+ if (watch.waiting && gl.getQueryParameter(watch.query, gl.QUERY_RESULT_AVAILABLE)) {
29
+ watch.seen = gl.getQueryParameter(watch.query, gl.QUERY_RESULT) > 0;
30
+ watch.waiting = false;
31
+ }
32
+ if (watch.seen) return false;
33
+ return watch.waiting ? now() - watch.askedAt < patienceMs : frame() - watch.asked <= freshFrames;
34
+ }
35
+ return { hidden, watchSeen };
36
+ }
@@ -0,0 +1,53 @@
1
+ // Transfer backing stores once, including when several views share a buffer.
2
+ function transferList(result) {
3
+ const buffers = new Set();
4
+ const visited = new Set();
5
+ function visit(value) {
6
+ if (value === null || typeof value !== 'object') return;
7
+ if (ArrayBuffer.isView(value)) {
8
+ if (value.buffer instanceof ArrayBuffer) buffers.add(value.buffer);
9
+ } else if (value instanceof ArrayBuffer) {
10
+ buffers.add(value);
11
+ } else if (!visited.has(value)) {
12
+ visited.add(value);
13
+ for (const child of Object.values(value)) visit(child);
14
+ }
15
+ }
16
+ visit(result);
17
+ return [...buffers];
18
+ }
19
+
20
+ /**
21
+ * Bind a pool worker to a message port. Jobs receive the input carried in the
22
+ * request. A loader returns a module exposing a jobs object, which may supply
23
+ * several handlers at once. Requests, including asynchronous work, finish FIFO.
24
+ */
25
+ export function attachWorker({ port, jobs = {}, loaders = {} }) {
26
+ const handlers = new Map(Object.entries(jobs));
27
+ const modules = new Map(Object.entries(loaders));
28
+ async function load(name) {
29
+ if (handlers.has(name)) return;
30
+ const fetchModule = modules.get(name);
31
+ if (!fetchModule) throw new Error('Unknown job: ' + name);
32
+ const module = await fetchModule();
33
+ for (const [job, handler] of Object.entries(module.jobs)) handlers.set(job, handler);
34
+ if (!handlers.has(name)) throw new Error('Module did not provide job: ' + name);
35
+ }
36
+ handlers.set('load', async name => {
37
+ await load(name);
38
+ return null;
39
+ });
40
+ async function answer({ job, input }) {
41
+ try {
42
+ await load(job);
43
+ const result = await handlers.get(job)(input);
44
+ port.postMessage({ result }, transferList(result));
45
+ } catch (error) {
46
+ port.postMessage({ error: String(error?.message ?? error) || 'Job failed' });
47
+ }
48
+ }
49
+ let previous = Promise.resolve();
50
+ port.onmessage = ({ data }) => {
51
+ previous = previous.then(() => answer(data));
52
+ };
53
+ }