Files
vibemake/js/cad/engine.js
T
2026-11-12 11:05:55 +08:00

134 lines
7.0 KiB
JavaScript

import { CAD } from './config.js';
import { cadError } from './api.js';
import { locale } from './i18n.js';
let engine, workerRegistration, initializedBuild;
let engineProgress = { phase: 'download', loaded: 0, total: null };
const progressListeners = new Set();
function reportProgress(phase, loaded, total) {
engineProgress = { phase, loaded, total };
for (const listener of progressListeners) listener(engineProgress);
}
export function loadEngine({ onProgress, signal } = {}) {
if (signal?.aborted) return Promise.reject(signal.reason);
if (!engine) engineProgress = { phase: 'download', loaded: 0, total: null };
if (onProgress) { progressListeners.add(onProgress); onProgress(engineProgress); }
// Loading is shared across retries. Cancelling an opening detaches its observer,
// while the engine can finish safely for the next opening.
const pending = engine ??= start().catch((error) => { engine = null; throw error; });
return new Promise((resolve, reject) => {
const cleanup = () => { progressListeners.delete(onProgress); signal?.removeEventListener('abort', abort); };
const abort = () => { cleanup(); reject(signal.reason); };
signal?.addEventListener('abort', abort, { once: true });
pending.then((value) => { cleanup(); resolve(value); }, (error) => { cleanup(); reject(error); });
});
}
async function start() {
const manifestResponse = await fetch(CAD.engineManifest, { cache: 'no-store' });
if (!manifestResponse.ok) throw cadError('ENGINE_MISSING');
const manifest = await manifestResponse.json();
if (manifest.bridgeVersion !== CAD.bridgeVersion || !/^[a-zA-Z0-9_-]+$/.test(manifest.buildId)) throw cadError('FORMAT_UNSUPPORTED');
const prefix = `/cad/_assets/${manifest.buildId}/`;
for (const key of ['js', 'wasm', 'chineseFont']) if (!manifest[key]?.startsWith(prefix) || /[?#]|\.\./.test(manifest[key])) throw cadError('BAD_RESPONSE');
const sizeOf = (path) => {
const size = Array.isArray(manifest.files) ? manifest.files.find((file) => file.path === path)?.size : null;
return Number.isSafeInteger(size) && size > 0 ? size : null;
};
const jsSize = sizeOf(manifest.js), wasmSize = sizeOf(manifest.wasm);
const total = jsSize && wasmSize ? jsSize + wasmSize : null;
let loaded = 0;
// Set before WASM starts. Standalone engine builds keep their original behaviour.
window.__VIBEMAKE_CAD__ = { bridgeVersion: 1, buildId: manifest.buildId, locale: locale(), assetBase: prefix, chineseFont: manifest.chineseFont };
if (initializedBuild !== manifest.buildId) {
reportProgress('download', loaded, total);
const [{ default: init }, response] = await Promise.all([
import(manifest.js).then((module) => { loaded += jsSize || 0; reportProgress('download', loaded, total); return module; }),
fetch(manifest.wasm).then((response) => { if (!response.ok) throw cadError('ENGINE_MISSING'); return response; }),
]);
let wasmResponse = response;
if (response.body) {
const headers = new Headers(response.headers);
// Fetch chunks are decoded bytes, like manifest sizes, even on gzip/Brotli hosts.
headers.delete('content-encoding'); headers.delete('content-length');
const body = response.body.pipeThrough(new TransformStream({
transform(chunk, controller) {
loaded += chunk.byteLength;
reportProgress('download', loaded, total);
controller.enqueue(chunk);
},
flush() { reportProgress('initialize', loaded, total); },
}));
// Keep streaming compilation and the module's original import.meta.url.
wasmResponse = new Response(body, { headers, status: response.status, statusText: response.statusText });
}
await init({ module_or_path: wasmResponse });
// Font failures can be retried without downloading an initialized WASM again.
initializedBuild = manifest.buildId;
}
reportProgress('initialize', loaded, total);
const deadline = performance.now() + 90000;
while (!window.vibemakeCad) { if (performance.now() > deadline) throw cadError('ENGINE_TIMEOUT'); await new Promise((r) => setTimeout(r, 30)); }
await window.vibemakeCad.ready();
reportProgress('ready', loaded, total);
if ('serviceWorker' in navigator) {
workerRegistration = navigator.serviceWorker.register('/cad/worker.js', { scope: '/cad/', updateViaCache: 'none' }).then((registration) => {
let notifiedBuild;
const notify = async () => {
try {
const response = await fetch(CAD.engineManifest, { cache: 'no-store' });
if (!response.ok) return;
const latest = await response.json();
// A waiting cache worker does not mean the running engine is outdated.
if (typeof latest.buildId !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(latest.buildId) || latest.buildId === manifest.buildId || latest.buildId === notifiedBuild) return;
notifiedBuild = latest.buildId;
window.dispatchEvent(new CustomEvent('vm:cad:update'));
} catch { /* An unavailable update check must not interrupt editing. */ }
};
if (registration.waiting) notify();
const watch = (worker) => {
worker?.addEventListener('statechange', () => { if (worker.state === 'installed' && navigator.serviceWorker.controller) notify(); });
};
watch(registration.installing);
registration.addEventListener('updatefound', () => watch(registration.installing));
return registration;
}).catch(() => null); // Editor remains usable when static caching is unavailable.
}
return window.vibemakeCad;
}
function waitForWorker(worker, states, timeout) {
return new Promise((resolve) => {
const finish = (result) => {
clearTimeout(timer);
worker.removeEventListener('statechange', changed);
resolve(result);
};
const changed = () => {
if (states.includes(worker.state)) finish(true);
else if (worker.state === 'redundant') finish(false);
};
const timer = setTimeout(() => finish(false), timeout);
worker.addEventListener('statechange', changed);
changed();
});
}
// Called only after the editor has completed its unsaved-changes guard.
export async function prepareEngineRefresh() {
if (!('serviceWorker' in navigator)) return;
const registration = await (workerRegistration || navigator.serviceWorker.getRegistration('/cad/'));
if (!registration || registration.scope !== new URL('/cad/', location.href).href) return;
await registration.update();
if (registration.installing && !await waitForWorker(registration.installing, ['installed', 'activated'], 10000)) throw cadError('ENGINE_UPDATE_FAILED');
const worker = registration.waiting;
if (!worker) return;
const activated = waitForWorker(worker, ['activated'], 2000);
worker.postMessage({ type: 'SKIP_WAITING' });
if (!await activated) throw cadError('ENGINE_UPDATE_FAILED');
}
export function downloadBytes(bytes, name) {
const url = URL.createObjectURL(new Blob([bytes], { type: 'application/octet-stream' }));
const link = document.createElement('a'); link.href = url; link.download = name; link.click();
setTimeout(() => URL.revokeObjectURL(url), 30000);
}