const app = JSON.parse(document.getElementById("nsh-app").textContent);
const url = (path) => new URL(path, document.baseURI).href;
for (const key of ["wasm", "glue", "code", "host"]) if (app[key]) app[key] = url(app[key]);
for (const urls of [app.assets, app.data, app.chunks]) for (const key in urls) urls[key] = url(urls[key]);
for (const name in app.sides) app.sides[name].url = url(app.sides[name].url);
const status = document.getElementById("status");
const fonts = new Map();
let player;
function fail(title, detail) {
status.hidden = false;
status.className = "failed";
status.setAttribute("role", "alert");
const heading = document.createElement("strong");
heading.textContent = title;
const pre = document.createElement("pre");
pre.textContent = detail;
status.replaceChildren(heading, pre);
}
function take(url) {
const response = fetches.get(url) ?? fetch(url);
fetches.delete(url);
return response;
}
async function get(url) {
const response = await take(url);
if (!response.ok) throw new Error(`${url}: HTTP ${response.status}`);
return response;
}
const path = (uri) => uri.replace(/^asset:\/+/, "");
const loads = new Map();
const loadFont = (font) => {
if (!loads.has(font)) {
loads.set(font, get(app.assets[font]).then(async (r) => fonts.set(font, new Uint8Array(await r.arrayBuffer()))));
}
return loads.get(font);
};
try {
const { createPlayer } = await import(url(app.runtime));
let host;
const [loaded, hostModule] = await Promise.all([
createPlayer(document.getElementById("app"), {
wasm: take(app.wasm),
glue: app.glue,
host: app.host ? { call: (name, args) => host.call(name, args), post: (name, args) => (host.post ?? host.call).call(host, name, args) } : undefined,
assets: app.assets,
data: app.data,
sides: app.sides,
history: app.history,
baseURL: app.base,
readAsset: (uri) => fonts.get(path(uri)) ?? null,
prepareChunk: (id) => Promise.all([
...(app.chunkFonts[id] ?? []).map(loadFont),
player.loadSides(app.chunkSides?.[id], app.sides),
]),
overlay: false,
onError: (message) => {
if (!player || player.views.size <= 1) fail("This app could not start.", message);
},
}),
app.host ? import(app.host) : null,
...app.fonts.map(loadFont),
...(app.entryChunks ?? []).flatMap(id => (app.chunkFonts[id] ?? []).map(loadFont)),
]);
player = loaded;
player.prefetchSides(app.sides);
if (hostModule) {
host = await hostModule.createHost(player);
if (typeof host?.call !== "function") throw new Error("nsh.json web.host: createHost(player) returned no call(name, args)");
}
status.hidden = true;
const served = document.getElementById("nsh-params");
const params = served ? JSON.parse(served.textContent) : undefined;
if (app.rust) player.runRust();
else await player.runModule(app.code, { capabilities: app.capabilities ?? "", appId: app.id ?? "", chunks: app.chunks, nativeExports: app.nativeExports, linked: app.linked, params });
player.preloadSides(app.sides);
} catch (err) {
fail("This app could not be loaded.", String(err?.message ?? err));
}