Load only the selected viewer language and document full uploads

This commit is contained in:
coyotte508 2026-09-30 00:29:47 +02:00
commit 5e7dfbccc6
10 changed files with 141 additions and 56 deletions

View file

@ -129,20 +129,12 @@ curl -X POST "$BASE/1/engine" -H "$AUTH" \
-H "Content-Type: application/octet-stream" \
--data-binary @packages/engine/outpost-engine-<version>.tgz
# 2. Viewer files: each upload returns { url } (content-hashed, S3).
curl -X POST "$BASE/1/viewer/file?filename=outpost-viewer.iife.js" -H "$AUTH" \
-H "Content-Type: application/octet-stream" \
--data-binary @packages/viewer/dist/outpost-viewer.iife.js
curl -X POST "$BASE/1/viewer/file?filename=outpost-viewer.css" -H "$AUTH" \
-H "Content-Type: application/octet-stream" \
--data-binary @packages/viewer/dist/outpost-viewer.css
# 3. Persist the new viewer URLs: GET the doc, set viewer.url (and
# viewer.dependencies.stylesheets if the css hash changed), drop
# _id/createdAt/updatedAt/meta, PUT it back.
curl "$BASE/1" -H "$AUTH" # read
curl -X PUT "$BASE/1" -H "$AUTH" -H "Content-Type: application/json" \
--data-binary @gameinfo.json # write
# 2–3. Upload the complete viewer folder and activate after verification.
# Use the publisher from your BGS checkout (not this game repository):
node /path/to/boardgamers/scripts/publish-viewer.mjs --game outpost --version 1 \
--dir packages/viewer/dist --entry outpost-viewer.iife.js --style outpost-viewer.css \
--token /path/to/admin-token --record /tmp/outpost-release.json --apply --activate
# This includes language JSON and sets scriptBytes. BGS compresses uploads itself.
# 4. Verify: engine.package.version and viewer.url on the doc.
curl "$BASE/1" -H "$AUTH"

View file

@ -134,7 +134,7 @@ Set `OUTPOST_CHROMIUM_EXECUTABLE` when using an existing Chromium installation.
- Engine: `npm pack` the built `outpost-engine` (or publish) and register it as the game
engine in the BGS admin panel; entry point `dist/wrapper.js`.
- Viewer: upload `packages/viewer/dist/outpost-viewer.iife.js` + `outpost-viewer.css`
- Viewer: upload the complete `packages/viewer/dist` folder, including language JSON
(and the `.map` with a shared bundle id if you want devtools sourcemaps).
See <https://docs.boardgamers.space/guide/adding-a-game>.
@ -142,3 +142,5 @@ See <https://docs.boardgamers.space/guide/adding-a-game>.
## License
AGPL-3.0.
Viewer releases: see [uploading the complete viewer build](docs/viewer-publishing.md).

11
docs/viewer-publishing.md Normal file
View file

@ -0,0 +1,11 @@
# Publishing the viewer
Upload the complete `packages/viewer/dist` folder, including language JSON and any images or sound files.
All files in a release must share one BGS `bundle` directory, with their relative paths preserved. Upload everything before saving the new entry URL. A main-JS-only upload will break language or asset loading. Keep engines and test data out of the viewer upload.
BGS compresses JS, CSS, JSON and WASM automatically during upload. Send the original bytes; do not create `.gz` files. Keep sourcemaps local unless you deliberately want to publish them. Set `viewer.scriptBytes` to the original entry size so BGS can show download progress.
The BGS admin's **Upload folder** control handles multi-file builds. For scripted releases, use BGS's `scripts/publish-viewer.mjs` with `--dir`, `--entry` and `--style`; it verifies every uploaded file, records the previous viewer, and activates only with `--apply --activate`. The full command and API contract are in the [BGS viewer documentation](https://docs.boardgamers.space/guide/viewer-api#publishing-a-viewer-with-multiple-files).
English needs no language download; other languages load when selected. Test a cold load and a language change after publishing. Also check the browser Network panel for missing relative assets.

View file

@ -2,7 +2,8 @@ import type { TutorialMount } from "@boardgamers/protocol/tutorial";
export interface Localization {
readonly locale: string;
translate(text: string): string;
setLocale(locale: unknown): void;
readonly ready: Promise<boolean>;
setLocale(locale: unknown): Promise<boolean>;
setState(state: unknown): void;
setNames(names: unknown[]): void;
refresh(): void;
@ -14,3 +15,5 @@ export function resolveLocale(value: unknown): string;
export function translateText(text: string, locale?: string): string;
export function mountLocalization(target: Element, locale?: unknown): Localization;
export function localizeTutorial(mount: TutorialMount): TutorialMount;
export function loadLocale(locale: unknown): Promise<string>;

View file

@ -1,39 +1,48 @@
import catalog0 from "./en.json";
import catalog1 from "./de.json";
import catalog2 from "./fr.json";
import catalog3 from "./pl.json";
import catalog4 from "./ro.json";
import catalog5 from "./el.json";
import catalog6 from "./hi.json";
import catalog7 from "./ru.json";
import catalog8 from "./da.json";
import catalog9 from "./pt-BR.json";
import catalog10 from "./ko.json";
import catalog11 from "./zh-TW.json";
import catalog12 from "./vi.json";
import catalog13 from "./it.json";
import catalog14 from "./nl.json";
import catalog15 from "./fa.json";
import { mountLocalization as mount, createTranslator } from "./runtime.js";
import { mountLocalization as mount, createTranslator, resolveLocale } from "./runtime.js";
export { languages, resolveLocale } from "./runtime.js";
export const catalogs = {
en: catalog0,
de: catalog1,
fr: catalog2,
pl: catalog3,
ro: catalog4,
el: catalog5,
hi: catalog6,
ru: catalog7,
da: catalog8,
"pt-BR": catalog9,
ko: catalog10,
"zh-TW": catalog11,
vi: catalog12,
it: catalog13,
nl: catalog14,
fa: catalog15,
};
const catalogUrls = import.meta.glob(["./*.json", "!./en.json"], {
eager: true,
query: "?url&no-inline",
import: "default",
});
async function fetchCatalog(locale) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 20000);
try {
const response = await fetch(catalogUrls[`./${locale}.json`], { signal: controller.signal });
if (!response.ok) {
throw new Error(`Language ${locale}: HTTP ${response.status}`);
}
return { default: await response.json() };
} finally {
clearTimeout(timeout);
}
}
export const catalogs = { en: {} };
const pending = new Map();
export function loadLocale(value) {
const locale = resolveLocale(value);
if (catalogs[locale]) {
return Promise.resolve(locale);
}
if (!pending.has(locale)) {
pending.set(
locale,
fetchCatalog(locale)
.then((module) => {
catalogs[locale] = module.default;
translators.delete(locale);
return locale;
})
.catch((error) => {
pending.delete(locale);
throw error;
})
);
}
return pending.get(locale);
}
const translators = new Map();
export function translateText(text, locale = "en") {
if (!translators.has(locale)) {
@ -42,12 +51,50 @@ export function translateText(text, locale = "en") {
return translators.get(locale).translate(text);
}
export function mountLocalization(target, locale) {
return mount(target, catalogs, locale ?? target.ownerDocument.documentElement.lang ?? "en");
const localization = mount(target, catalogs, "en");
let revision = 0;
let ready = Promise.resolve(true);
function setLocale(value) {
const attempt = ++revision;
ready = loadLocale(value)
.then((loaded) => {
if (attempt !== revision) {
return false;
}
localization.setLocale(loaded);
return true;
})
.catch((error) => {
console.warn("Could not load game language", error);
if (attempt !== revision) {
return false;
}
localization.setLocale("en");
return true;
});
return ready;
}
setLocale(locale ?? target.ownerDocument.documentElement.lang ?? "en");
return {
...localization,
setLocale,
get locale() {
return localization.locale;
},
get ready() {
return ready;
},
destroy() {
revision++;
localization.destroy();
},
};
}
export function localizeTutorial(mountTutorial) {
return async (target, options) => {
const localization = mountLocalization(target, options.locale);
try {
await localization.ready;
const dispose = await mountTutorial(target, options);
localization.refresh();
return () => {

View file

@ -28,6 +28,7 @@ registerViewer<GameState, Move>(
return thumbnail.render(commands.target.querySelector(".main"), size, "#0a1421", ".side");
},
async onState(state) {
await localization.ready;
localization.setState(state);
sounds.onState(state);
store.setState(state);
@ -39,8 +40,10 @@ registerViewer<GameState, Move>(
onAvatars(avatars) {
store.avatars = avatars;
},
onPreferences(preferences) {
localization.setLocale(preferences.locale);
async onPreferences(preferences) {
if (!(await localization.setLocale(preferences.locale))) {
return;
}
store.preferences = preferences;
sounds.onPreferences(preferences);
},

View file

@ -2,6 +2,7 @@ import { svelte } from "@sveltejs/vite-plugin-svelte";
import { defineConfig } from "vite";
export default defineConfig(({ command }) => ({
base: "./",
plugins: [svelte()],
build: {
outDir: "dist",

View file

@ -1,8 +1,12 @@
import { previewServer } from "./tutorial-preview.mjs";
import assert from "node:assert/strict";
import { chromium } from "playwright";
import { initGame } from "../packages/engine/dist/index.js";
import { stripSecret } from "../packages/engine/dist/wrapper.js";
const server = previewServer();
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;
const browser = await chromium.launch({ headless: true });
try {
const configurations = [
@ -28,7 +32,7 @@ try {
await page.setContent(`${markup}<footer style="height:600px"></footer>`);
}
await frame.addStyleTag({ path: "packages/viewer/dist/outpost-viewer.css" });
await frame.addScriptTag({ path: "packages/viewer/dist/outpost-viewer.iife.js" });
await frame.addScriptTag({ url: base + "/bundle.js" });
const state = initGame(3, { fastBid: true, kicker: true }, "protocol-smoke");
await frame.evaluate(
(state) => {
@ -196,4 +200,5 @@ try {
);
} finally {
await browser.close();
await new Promise((resolve) => server.close(resolve));
}

View file

@ -1,18 +1,28 @@
import { previewServer } from "./tutorial-preview.mjs";
import { checkHostPresentation } from "./host-presentation-smoke.mjs";
import assert from "node:assert/strict";
import { chromium } from "playwright";
import { initGame } from "../packages/engine/dist/index.js";
import { stripSecret } from "../packages/engine/dist/wrapper.js";
const server = previewServer();
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;
const browser = await chromium.launch({ executablePath: process.env.OUTPOST_CHROMIUM_EXECUTABLE });
try {
for (const width of [390, 1400]) {
const page = await browser.newPage({ viewport: { width, height: 950 } });
const errors = [];
const languageRequests = [];
page.on("request", (request) => {
if (request.url().endsWith(".json")) {
languageRequests.push(request.url());
}
});
page.on("pageerror", (error) => errors.push(error.message));
await page.setContent('<div id="app"></div>');
await page.addStyleTag({ path: "packages/viewer/dist/outpost-viewer.css" });
await page.addScriptTag({ path: "packages/viewer/dist/outpost-viewer.iife.js" });
await page.addScriptTag({ url: base + "/bundle.js" });
const state = initGame(3, { fastBid: true, kicker: true }, "protocol-smoke");
state.players.forEach((player, i) => {
player.name = ["You", "Full Name", "Other"][i];
@ -106,6 +116,7 @@ try {
1
);
if (width === 390) {
await page.evaluate(() => window.scrollTo(0, 0));
await page.waitForTimeout(650);
assert.equal(await page.evaluate(() => events.filter((e) => e.name === "chat:read").length), 0);
}
@ -295,6 +306,12 @@ try {
const count = Number((await stack.textContent()).trim());
assert.match(await stack.getAttribute("title"), new RegExp(`cards: ${count}$`));
}
assert.equal(languageRequests.length, 0, "English needs no language download");
await page.evaluate(() => emitter.emit("preferences", { locale: "fr", sound: false }));
await page.waitForFunction(() => document.body.textContent.includes("Eau"));
assert.equal(languageRequests.length, 1);
await page.evaluate(() => emitter.emit("preferences", { locale: "en", sound: false }));
await page.waitForFunction(() => document.body.textContent.includes("Water"));
await page.screenshot({ path: `/tmp/outpost-resource-icons-${width}.png`, fullPage: true });
await checkHostPresentation(page, "emitter", `/tmp/outpost-board-thumbnail-${width}.png`);
assert.deepEqual(errors, []);
@ -303,4 +320,5 @@ try {
console.log("Outpost protocol: mobile/desktop chat, mentions, reads, drafts, replay, refresh and relaunch passed.");
} finally {
await browser.close();
await new Promise((resolve) => server.close(resolve));
}

View file

@ -16,6 +16,9 @@ export function previewServer() {
if (files[path]) {
res.setHeader("Content-Type", path.endsWith(".css") ? "text/css" : "text/javascript");
res.end(await readFile(files[path]));
} else if (/^\/[a-zA-Z0-9_-]+\.json$/.test(path)) {
res.setHeader("Content-Type", "application/json");
res.end(await readFile(new URL("../packages/viewer/dist" + path, import.meta.url)));
} else if (path === "/") {
res.setHeader("Content-Type", "text/html");
res.end(html);