Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(i18n): version locale URLs so translation updates reach the browser (#9947)

Alexander Eichhornf6fdfa18c2f0
diff --git a/invokeai/frontend/webv2/scripts/locale-assets-plugin.mjs b/invokeai/frontend/webv2/scripts/locale-assets-plugin.mjs
index 07f27c5a00..1b54809c20 100644
--- a/invokeai/frontend/webv2/scripts/locale-assets-plugin.mjs
+++ b/invokeai/frontend/webv2/scripts/locale-assets-plugin.mjs
@@ -1,3 +1,4 @@
+import { createHash } from 'node:crypto';
import { readFile, readdir } from 'node:fs/promises';
import { resolve } from 'node:path';
@@ -6,52 +7,76 @@ const splitLocale = (translations) => {
return { translation, fonts: fonts ? { fonts } : {} };
};
-/** Keep source locales readable; load font-library copy only when that UI opens. */
-export const localeAssetsPlugin = ({ projectRoot }) => ({
- name: 'invokeai-locale-assets',
- configureServer(server) {
- server.middlewares.use(async (request, response, next) => {
- const match = request.url?.match(/\/locales\/([a-zA-Z0-9_-]+)(\.fonts)?\.json(?:\?.*)?$/);
- if (!match) {
- next();
- return;
- }
- try {
- const source = await readFile(resolve(projectRoot, `public/locales/${match[1]}.json`), 'utf8');
- const parts = splitLocale(JSON.parse(source));
- response.setHeader('Content-Type', 'application/json');
- response.end(JSON.stringify(match[2] ? parts.fonts : parts.translation));
- } catch (error) {
- if (error.code === 'ENOENT') {
+/** The files a build emits for `public/locales`, sorted by name so the version does not depend on readdir order. */
+const buildLocaleAssets = async (projectRoot) => {
+ const directory = resolve(projectRoot, 'public/locales');
+ const entries = await readdir(directory, { withFileTypes: true });
+ const names = entries
+ .filter((entry) => entry.isFile() && entry.name.endsWith('.json'))
+ .map((entry) => entry.name)
+ .sort();
+ const sources = await Promise.all(names.map((name) => readFile(resolve(directory, name), 'utf8')));
+ return names.flatMap((name, index) => {
+ let parsed;
+ try {
+ parsed = JSON.parse(sources[index]);
+ } catch (error) {
+ throw new Error(`Invalid locale JSON: ${name}`, { cause: error });
+ }
+ const parts = splitLocale(parsed);
+ return [
+ { fileName: `locales/${name}`, source: JSON.stringify(parts.translation) },
+ { fileName: `locales/${name.replace('.json', '.fonts.json')}`, source: JSON.stringify(parts.fonts) },
+ ];
+ });
+};
+
+/**
+ * Keep source locales readable; load font-library copy only when that UI opens. Locale URLs stay the same across
+ * releases, so the injected content version tells the client and service worker which files a build carries.
+ */
+export const localeAssetsPlugin = ({ projectRoot }) => {
+ let assets;
+
+ return {
+ name: 'invokeai-locale-assets',
+ async config() {
+ assets = await buildLocaleAssets(projectRoot);
+ // Hash the emitted files, not the sources: formatting-only edits keep the version, transform changes do not.
+ // JSON keeps the boundaries between file names and contents unambiguous.
+ const version = createHash('sha256').update(JSON.stringify(assets)).digest('hex').slice(0, 12);
+ // An env define, not a global: Vitest browser mode re-encodes string globals, wrapping them in quotes.
+ return { define: { 'import.meta.env.LOCALE_VERSION': JSON.stringify(version) } };
+ },
+ configureServer(server) {
+ // Read per request so edits show without a restart. The version stays at its startup value, which only the
+ // production service worker relies on.
+ server.middlewares.use(async (request, response, next) => {
+ const match = request.url?.match(/\/locales\/([a-zA-Z0-9_-]+)(\.fonts)?\.json(?:\?.*)?$/);
+ if (!match) {
next();
- } else {
- next(error);
+ return;
+ }
+ try {
+ const source = await readFile(resolve(projectRoot, `public/locales/${match[1]}.json`), 'utf8');
+ const parts = splitLocale(JSON.parse(source));
+ response.setHeader('Content-Type', 'application/json');
+ response.end(JSON.stringify(match[2] ? parts.fonts : parts.translation));
+ } catch (error) {
+ if (error.code === 'ENOENT') {
+ next();
+ } else {
+ next(error);
+ }
}
- }
- });
- },
- async generateBundle() {
- const directory = resolve(projectRoot, 'public/locales');
- const entries = await readdir(directory, { withFileTypes: true });
- for (const entry of entries) {
- if (!entry.isFile() || !entry.name.endsWith('.json')) {
- continue;
- }
- const source = await readFile(resolve(directory, entry.name), 'utf8');
- let parsed;
- try {
- parsed = JSON.parse(source);
- } catch (error) {
- throw new Error(`Invalid locale JSON: ${entry.name}`, { cause: error });
- }
- const parts = splitLocale(parsed);
- // Vite copies public files before generateBundle; replace only the emitted copy.
- this.emitFile({ type: 'asset', fileName: `locales/${entry.name}`, source: JSON.stringify(parts.translation) });
- this.emitFile({
- type: 'asset',
- fileName: `locales/${entry.name.replace('.json', '.fonts.json')}`,
- source: JSON.stringify(parts.fonts),
});
- }
- },
-});
+ },
+ generateBundle() {
+ // Emit exactly the files config() hashed. Vite copies public files before generateBundle; replace only the
+ // emitted copy.
+ for (const { fileName, source } of assets) {
+ this.emitFile({ type: 'asset', fileName, source });
+ }
+ },
+ };
+};
diff --git a/invokeai/frontend/webv2/scripts/locale-assets-plugin.test.mjs b/invokeai/frontend/webv2/scripts/locale-assets-plugin.test.mjs
index 840d381c79..c8e99be589 100644
--- a/invokeai/frontend/webv2/scripts/locale-assets-plugin.test.mjs
+++ b/invokeai/frontend/webv2/scripts/locale-assets-plugin.test.mjs
@@ -1,5 +1,5 @@
import assert from 'node:assert/strict';
-import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
+import { mkdtemp, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import test from 'node:test';
@@ -17,7 +17,10 @@ const createFixture = async (context) => {
resolve(projectRoot, 'index.html'),
'<html><body><script type="module" src="/main.js"></script></body></html>'
);
- await writeFile(resolve(projectRoot, 'main.js'), 'document.body.dataset.ready = "true";');
+ await writeFile(
+ resolve(projectRoot, 'main.js'),
+ 'document.body.dataset.localeVersion = import.meta.env.LOCALE_VERSION;'
+ );
return projectRoot;
};
@@ -29,6 +32,18 @@ const buildFixture = (projectRoot) =>
plugins: [localeAssetsPlugin({ projectRoot })],
});
+/** Reads the version the build injected into the bundled entry. */
+const readBuiltLocaleVersion = async (projectRoot) => {
+ const directory = resolve(projectRoot, 'dist/assets');
+ const scripts = (await readdir(directory)).filter((name) => name.endsWith('.js'));
+ const sources = await Promise.all(scripts.map((name) => readFile(resolve(directory, name), 'utf8')));
+ const versions = sources.flatMap((source) =>
+ [...source.matchAll(/localeVersion\s*=\s*(["'`])(.*?)\1/g)].map((match) => match[2])
+ );
+ assert.equal(versions.length, 1, 'The entry must assign one string literal as the locale version.');
+ return versions[0];
+};
+
test('production locale assets replace public copies without changing Unicode, values, or source files', async (context) => {
const projectRoot = await createFixture(context);
const translations = {
@@ -55,6 +70,33 @@ test('production locale assets replace public copies without changing Unicode, v
assert.equal(await readFile(resolve(projectRoot, 'dist/keep.txt'), 'utf8'), ' Keep public whitespace.\n');
});
+test('the injected locale version follows the emitted locale files across builds and project paths', async (context) => {
+ const french = { common: { retry: 'Réessayer' } };
+ const writeLocales = async (projectRoot) => {
+ await writeFile(resolve(projectRoot, 'public/locales/en.json'), JSON.stringify({ common: { retry: 'Retry' } }));
+ await writeFile(resolve(projectRoot, 'public/locales/fr.json'), JSON.stringify(french));
+ };
+ const first = await createFixture(context);
+ const second = await createFixture(context);
+ await writeLocales(first);
+ await writeLocales(second);
+
+ await buildFixture(first);
+ await buildFixture(second);
+ const version = await readBuiltLocaleVersion(first);
+ assert.ok(version && version !== 'undefined', `Expected a locale version, got ${JSON.stringify(version)}.`);
+ assert.equal(await readBuiltLocaleVersion(second), version);
+
+ // Reformatting a source leaves the emitted files, and so the version, unchanged.
+ await writeFile(resolve(second, 'public/locales/fr.json'), `${JSON.stringify(french, null, 2)}\n`);
+ await buildFixture(second);
+ assert.equal(await readBuiltLocaleVersion(second), version);
+
+ await writeFile(resolve(second, 'public/locales/fr.json'), JSON.stringify({ common: { retry: 'Encore' } }));
+ await buildFixture(second);
+ assert.notEqual(await readBuiltLocaleVersion(second), version);
+});
+
test('invalid locale JSON fails the production build with the failing filename', async (context) => {
const projectRoot = await createFixture(context);
await writeFile(resolve(projectRoot, 'public/locales/broken.json'), '{ invalid');
@@ -88,7 +130,8 @@ test('font namespace loads separately in production and development, preserving
await server.listen();
const origin = server.resolvedUrls.local[0];
for (const filename of ['en.json', 'en.fonts.json', 'fr.fonts.json']) {
- const response = await fetch(new URL(`locales/${filename}`, origin));
+ // Versioned like the client's requests.
+ const response = await fetch(new URL(`locales/${filename}?v=0123456789ab`, origin));
assert.equal(response.status, 200);
assert.deepEqual(
await response.json(),
diff --git a/invokeai/frontend/webv2/src/platform/i18n/client.ts b/invokeai/frontend/webv2/src/platform/i18n/client.ts
index d06557d2e9..105c0f0b0b 100644
--- a/invokeai/frontend/webv2/src/platform/i18n/client.ts
+++ b/invokeai/frontend/webv2/src/platform/i18n/client.ts
@@ -10,6 +10,9 @@ void i18n
backend: {
loadPath: (_languages: readonly string[], namespaces: readonly string[]) =>
`${getDeploymentBaseUrl()}/locales/{{lng}}${namespaces[0] === 'fonts' ? '.fonts' : ''}.json`,
+ // Changes with locale content, so a release never reads the previous one's cached translations; the service
+ // worker caches only these versioned URLs.
+ queryStringParams: { v: import.meta.env.LOCALE_VERSION },
},
debug: false,
fallbackLng: 'en',
diff --git a/invokeai/frontend/webv2/src/platform/pwa/sw.js b/invokeai/frontend/webv2/src/platform/pwa/sw.js
index c44d1cba84..09770a8f8e 100644
--- a/invokeai/frontend/webv2/src/platform/pwa/sw.js
+++ b/invokeai/frontend/webv2/src/platform/pwa/sw.js
@@ -1,7 +1,7 @@
/**
- * The plugin injects one {version, assets} manifest. Navigation is network-first, hashed assets cache-first,
- * locales stale-while-revalidate; API/socket traffic is untouched. Do not skipWaiting: old tabs may still need
- * lazy assets the new worker prunes.
+ * The plugin injects one {version, assets} manifest. Navigation is network-first, hashed assets and
+ * content-versioned locales cache-first; API/socket traffic is untouched. Do not skipWaiting: old tabs may still
+ * need lazy assets the new worker prunes.
*/
const MANIFEST = self.__SW_MANIFEST__;
@@ -83,27 +83,27 @@ const respondCacheFirst = async (request) => {
return response;
};
-const respondStaleWhileRevalidate = async (request) => {
+const respondVersionedLocale = async (request) => {
const cache = await caches.open(RUNTIME_CACHE);
const cached = await cache.match(request);
- const refresh = fetch(request)
- .then((response) => {
- if (response.ok) {
- void cache.put(request, response.clone());
- }
-
- return response;
- })
- .catch(() => undefined);
if (cached) {
return cached;
}
- const response = await refresh;
+ const response = await fetch(request);
+
+ const contentType = response.headers.get('Content-Type')?.split(';')[0].trim().toLowerCase();
+
+ // Store JSON only: the backend's SPA fallback answers a missing file with a 200 index.html. Keep one entry per
+ // locale file: drop every other version of this path, unversioned ones included.
+ if (response.ok && contentType === 'application/json') {
+ const copy = response.clone();
- if (!response) {
- throw new TypeError(`Offline and not cached: ${request.url}`);
+ void cache.keys(request, { ignoreSearch: true, ignoreVary: true }).then(async (entries) => {
+ await Promise.all(entries.filter((entry) => entry.url !== request.url).map((entry) => cache.delete(entry)));
+ await cache.put(request, copy);
+ });
}
return response;
@@ -126,7 +126,9 @@ self.addEventListener('fetch', (event) => {
return;
}
- if (request.url.startsWith(LOCALES_PREFIX)) {
- event.respondWith(respondStaleWhileRevalidate(request));
+ // `platform/i18n/client.ts` adds the locale content version as `v`. Unversioned requests go to the network, so
+ // none can be pinned in the cache.
+ if (request.url.startsWith(LOCALES_PREFIX) && new URL(request.url).searchParams.has('v')) {
+ event.respondWith(respondVersionedLocale(request));
}
});
diff --git a/invokeai/frontend/webv2/src/vite-env.d.ts b/invokeai/frontend/webv2/src/vite-env.d.ts
index 3a070d8e82..57d00672c3 100644
--- a/invokeai/frontend/webv2/src/vite-env.d.ts
+++ b/invokeai/frontend/webv2/src/vite-env.d.ts
@@ -6,4 +6,6 @@ declare const __CANVAS_GOLDEN_UPDATE__: boolean;
interface ImportMetaEnv {
/** The release version from `invokeai/version/invokeai_version.py`, injected by `vite.config.mts`. */
readonly APP_VERSION: string;
+ /** A content hash of `public/locales`, injected by `scripts/locale-assets-plugin.mjs`. */
+ readonly LOCALE_VERSION: string;
}