mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-12 23:31:02 +00:00
d7c4324afc
* chore(capacitor): base files for capacitor
* chore(capacitor): base plugins
* feat(auth): hand a browser sign-in over to the native app
The native apps show the server's own UI in a WebView, where neither SSO nor
passkeys can run. They sign in through the system browser instead and need a
way to carry that session back.
The app keeps a random verifier and sends only its sha256 into the browser.
Once signed in there, the browser trades that challenge for a one-time code
(cookie session only, so an API or MCP token cannot mint itself a browser
session), and the WebView redeems the code together with the verifier. The
code rides through a URL scheme any app could claim, so on its own it is
worthless; it is single use and good for a minute.
Also: /api/health/features reports nativeApp so the apps can refuse servers
that predate this, and hashed files under assets/ are served immutable,
which the iOS app needs to start offline without a service worker.
* feat(native): the apps load the server's own UI
The apps ship only an address screen now. Once a server is picked, the
native side points the WebView at it: TrekBridgeViewController on iOS and a
config copy with server.url on Android. The UI then comes from that server,
in the version it runs and on its own origin, so the session cookie,
uploads, /ws and plugins work exactly as in a browser and no app release
has to keep pace with the servers out there.
The address screen (native-shell/, built into native-dist/) probes
/api/health/features through native HTTP, tries https before http when no
scheme was typed, and refuses servers without the nativeApp flag. It also
serves as the error page when the remembered server does not load: retry,
change server, or on iOS the stored copy of the server's start page.
TrekShell is the app's own plugin for all of that: remember, change and
reload the server, sign in through ASWebAuthenticationSession or a Custom
Tab, and on iOS keep and open the offline copy of the start page, because
WKWebView runs no service worker for a domain the app does not list.
Plugins the frame does not use are gone (push, camera, geolocation,
calendar, file transfer, in-app browser and more): the WebView covers the
camera and location itself, and push needs a relay before it is worth
shipping. With them go the push entitlement, the calendar usage strings
and the Firebase bits. The iOS scheme falls back to capacitor://, since
Capacitor drops an iosScheme of https, and the arm64 capability replaces
armv7.
* feat(native): the UI knows when it runs inside the app
Everything the server's UI does differently inside the iOS and Android app
lives under src/native and is inert in a browser.
Sign-in: SSO and the passkey button go through the system browser
(signInThroughBrowser), because identity providers refuse embedded
browsers and WebAuthn needs a domain association no build can have for
every server. The browser end is the new /native-handoff page: it signs
the user in if needed and hands the session over only after an explicit
tap, so a link carrying somebody else's challenge cannot pass a session
on silently. The verifier is hashed with @noble/hashes because
crypto.subtle is missing on the plain-http servers many home networks
use. An OIDC-only install no longer bounces to the IdP inside the
WebView, and passkey management is hidden in the app.
Downloads: the WebView cannot save a blob, so downloadBlob, downloadFile
and openFile write to the app cache and open the share sheet. The eight
places that built their own download anchor now use downloadBlob, which
they should have anyway.
The rest: "Change server" on the login page and in the account settings,
the splash hides after the first frame, Android's back button walks
history before it leaves the app, the status bar follows the scheme, and
on iOS the start page is refreshed and every chunk of the build (listed
in the new asset-manifest.json) is pulled into WebKit's cache so the app
can start without network.
* ci(native): build the Android and iOS shells on every change to them
Compiles the Swift side on a macOS runner so nobody needs a Mac to know it
still builds, and leaves a debug APK on every run to install on a phone.
Unsigned: signing and store uploads need secrets fork PRs do not get.
* feat(native): offline vector maps in the iOS app
In a browser the service worker answers MapLibre from the gl-map-offline
cache that glPrefetcher fills for trips marked for offline. The iOS app has
no service worker, so nothing read that cache there and the map went blank
without network.
A trek-offline:// protocol takes the service worker's place. Inside the iOS
app the MapLibre style URL is rewritten to it, the handler rewrites every
https URL inside the style and its TileJSON the same way, and then serves
documents network first and tiles, glyphs and sprites cache first. Outside
the iOS app nothing changes. The default OpenFreeMap basemap is covered;
Mapbox GL has no protocol hook and stays online-only in the app, as does a
custom raster template, whose opaque responses only a service worker can
store.
* fix(native): keep the iOS offline copy inside the app
loadSimulatedRequest went to the server URL without its trailing slash, and
Capacitor keeps a navigation in the WebView only when it starts with the
bridge's serverURL, slash included. The offline start page would have
opened in Safari instead. Also covers the platform helpers and the
hand-off API module.
* feat(native): the small things that give a WebView away
- A short haptic tap on success, warning and error toasts, which is where
every save and delete already reports. Info toasts stay silent.
- No "‹ › Done" strip above the iOS keyboard.
- No Safari preview when a link is long-pressed.
- The swipe from the left edge goes back on iOS, through the same history
Android's back button walks.
* test(mobile): the backup-code download revokes its URL after the shared delay
The mobile twin of the AccountTab test still expected the object URL to be
revoked in the same tick. Since both screens download through downloadBlob,
the revoke happens after its 100 ms grace period.
* fix(native): remember the login by default inside the app
With the switch off the app got a session cookie, which dies with the app
process, so every time the phone unloaded TREK the user had to sign in
again. Found while running the Android build in the emulator.
* fix(native): no overscroll stretch on Android
The UI asks for no overscroll effect with overscroll-behavior: none on html,
and Chrome honours it. The Android WebView draws the stretch on its root
scroller natively, though, and it scales the whole view, so the top bar and
the bottom dock were pulled along with the page. Found in the emulator.
* fix(native): Android shows "server not reachable" instead of a blank page
Capacitor injects its bridge on Android only into the server's origin once
server.url is set, so the local error page it switches to when the server
does not load had no bridge. It could neither retry nor change the server
and stayed blank.
TrekWebViewClient now catches a failed page load (a network error, or a 5xx
from a proxy while TREK restarts) and the app starts over on the bundled
address screen, where the bridge is present and the screen offers exactly
those two choices. The server config no longer carries errorPath.
Two traps on the way, both found in the emulator: a restart during launch
has to be a fresh task, since recreate() leaves the system splash lying over
the new page; and a restart shows no launch splash at all, because the
splash plugin cannot take it down again when the page hides it early.
* feat(native): TREK's own app icon and launch screen, named just TREK
The shells still carried Capacitor's placeholder icon and splash, the blue
X on a grid. They now show the white TREK mark on a dark, slightly glassy
tile: a soft light from the top left and a sheen over the upper half, in
the app's launch colour #09090b. Android 12+ draws its launch screen on the
same colour instead of light grey.
scripts/generate-app-icons.mjs renders the sources into assets/ from
public/icons/icon-white.svg, and `npm run icons:app` turns them into every
size both platforms ask for through @capacitor/assets. The Android
foreground mark is sized for the adaptive icon's round mask.
The home screen label is TREK: the old "TREK - Plan your trips!" was cut
off under the icon, and the longer title belongs to the store listings.
* fix(native): new lint warnings and the MapLibre protocol type after the dev merge
Awaits that sat in loops in the native-auth tests run together, the hand-off hook marks its navigations as ignored, the native tests drop their non-null assertions, and the offline protocol answers with the data type MapLibre 6.15 expects.
* fix(native): strict types in the address screen, Prettier on the native-auth e2e suite, file-local exports
The address screen's element helper returns the plain element instead of Object.assign's intersection, which strict mode could not represent; the haptics test reads an optional argument as optional; three exports only their own file used are local now.
* fix(native): Prettier on the native client files, rate-limit e2e requests in sequence
Formats the files the client formatting gate listed, and NATIVE-E2E-005 sends its twenty exchange attempts one after another: all at once they reset the test server's connections.
* fix(native): hide passkeys in the app through usePasskeys
The flag in useAccountSettings grew the identical destructuring in both account views past the duplication threshold; the shared passkeys hook already decides when its card is hidden, so the app check lives there now.
* feat(native): everything the App Store and Google Play submissions need
- iOS: microphone usage text for "Take Video", no-export-compliance flag,
ExportOptions.plist for App Store Connect uploads, the unused push
forwarders gone; CI builds with Xcode 26 and lints the property lists.
- Android: version and signing from Gradle properties (unsigned without
them), R8 with keep rules for TREK's and Capacitor's reflective classes,
no Auto Backup of the session cookie, no external file provider path,
template and Firebase leftovers removed, keystores and service accounts
ignored, full-size adaptive icon layers with a monochrome layer; CI also
builds the release APK.
- native-release.yml: signed bundle to a Play testing track and archive to
TestFlight, by hand or on a v* tag, behind the store environment.
- Version handshake: the server reports nativeApi 1, the app refuses a
server below its minimum and tolerates an app older than the offline copy.
- Address screen: privacy policy link, "Try the demo" and "What is a TREK
server?"; the privacy link also in the app's server settings. Three new
native strings in all 27 locales.
- Donation links and the notices asking for one are hidden in the app.
- Store listings for "TREK Travel Planner" in client/fastlane: texts, review
notes with placeholders, privacy and account deletion page drafts, the
feature graphic and icon, a length and image check in CI, and a Playwright
store project with the scripts that turn its captures into screenshots.
- Docs: wiki/Native-Apps.md, README no longer says there is no store app.
* fix(native): read a notice button's href without a weak type
An action button carries no href, so a parameter typed as only an optional href refused the notice DTO; the button type now names its kind as well.
* feat(native): a welcoming onboarding for the address screen
The app's own screen now opens on a welcome: the TREK mark, a line about what
TREK is, and two clear paths — connect the TREK you already open in the browser,
or get TREK Cloud. Both lead to polished screens: the address field with live
validation, a shake and haptic on a bad address and a success tick before the
server takes over; and a TREK Cloud intro with what it offers and a way in.
Screens slide and stagger in, buttons give a tap, and it all respects the safe
areas, light and dark, and reduced motion. Self-hosters are unaffected: cloud is
its own path, never in the way. New native strings are added across all locales
(English placeholders outside en/de, to translate).
* feat(native): a plan picker for TREK Cloud, with live prices
The Get TREK Cloud path now leads to a plan picker that reads the live plans
from the site (/api/plans), so the prices and quotas always match the website.
Monthly and yearly in a segmented toggle, the year marked with its saving, each
plan a card with its price and what it includes. Subscribe is wired to finish on
the web order for now; it becomes an Apple/Google in-app purchase once the store
products exist. New strings across all locales (en and de translated).
* feat(native): light status bar and a Go key on the address screen
The address screen sits on the near-black surface, so set the status bar to draw
its clock and icons in light while it is up; the server's own UI takes over the
style once it loads. The address field's on-screen return key now reads Go. Both
fail quietly where there is no native status bar (web, the simulator).
* i18n(native): translate the onboarding into es, fr, it, nl and pl
The welcome, TREK Cloud and plan-picker strings were English placeholders in
every locale but en and de. The five largest remaining European languages are
now translated in full; the others still carry the English text and are a
follow-up for native speakers.
* feat(native): the in-app TREK Cloud subscription flow
After picking a plan, the app now carries the whole purchase itself when the build
can take one: choose your address (checked for free as you type, against the same
endpoint the website uses), your email, and subscribe. The receipt goes to
/api/iap/redeem, and a Setting up your TREK screen waits on the new address and
loads it the moment it answers.
The purchase sits behind an IapClient seam (src/native/iap.ts): a fake drives the
whole flow in development and preview, the native client reports itself
unavailable until the store plugin and products exist, and until then the plan
picker still finishes on the web, so nothing half-wired faces a customer. New
claim and provisioning strings across all locales (en, de and the five largest
European languages translated).
* i18n(native): translate the app into the remaining 20 languages
The onboarding, plan picker, claim and provisioning strings were English
placeholders outside en, de and the five largest European languages. They are
now translated in full across the other 20 locales (ar, az, br, ca, cs, et, gr,
hu, id, ja, ko, ru, sk, sv, th, tr, uk, vi, zh, zh-TW), placeholders and brand
kept. The app now speaks every language TREK does.
* fix(i18n): add the Hebrew native strings, and correct the LoginPage size baseline
The he locale had every domain but native.ts, which broke i18n parity, the shared
coverage specs and the client parity test once the native strings existed. Add
he/native.ts with all native keys translated. Also correct the LoginPage size
baseline to its current line count.
* i18n(native): excuse the TREK Cloud brand, mark Email same-as-en, exempt the quota counts
The strict i18n checks, which the feature-branch CI does not run, catch three
things now that the native strings exist in every locale: TREK Cloud read as an
untranslated English phrase (it is a product name, like Vacay and Atlas, so add
it to the brand list); Email left identical in Italian, Indonesian and
Vietnamese, where it is the local word too (mark same-as-en) and in Greek (give
it a Greek term); and the GB and AI-document quota strings carrying {n} without
being plural groups (both are figures that never show a singular, like the other
unit-symbol counts in NOT_PLURAL).
* fix(native): typecheck, lint and knip on the native code; wire he's native bundle
The full suite, which the feature-branch CI does not run, catches four things the
native work still had: a non-narrowed union in the claim flow (tsc), a helper
named useFake that the react-hooks rule read as a hook (eslint), two iap types
exported but used only inside the file (knip), and the Hebrew native strings
present as a file but never spread into he's merged bundle (the aggregated key
parity test). All four fixed.
* fix(native): a flat redeem result, so the claim flow typechecks
The discriminated union did not narrow under the native-shell tsconfig, so the
failure code read as absent on the whole type. Use a flat result with optional
instanceUrl and code instead: both are always present on the type, no narrowing
needed, and the ok plus instanceUrl guard still routes success from refusal.
* style: prettier-format the native and i18n changes
The feature-branch CI does not run the formatting check, so the conflict-resolved
files (AboutTab, useAccountSettings, useTripExport), the native shell and iap
module, and the i18n files touched by the translation scripts were never run
through Prettier. Format them all; no behaviour changes.
* chore(native): re-trigger CI on the formatted tree
---------
Co-authored-by: Maurice <mauriceboe@icloud.com>
376 lines
14 KiB
JavaScript
376 lines
14 KiB
JavaScript
#!/usr/bin/env node
|
||
/**
|
||
* i18n:untranslated: English left in the other locales may only shrink.
|
||
*
|
||
* Parity proves every locale has every key, not that the key holds the
|
||
* locale's own language: a copied en string passes it. Two kinds of copy are
|
||
* counted per locale and domain file:
|
||
*
|
||
* marked a declaration carrying `// en-fallback`, the marker a
|
||
* translator leaves on a string they could not translate yet
|
||
* identical an unmarked value equal to en's, unless the rule in
|
||
* `isInvariant` says the text reads the same in every language,
|
||
* or a translator confirmed a single word with `// same-as-en`
|
||
* in a Latin-script locale (`isExcused`). A plural form en has
|
||
* no key for (a Russian `.few` or `.many`) is compared with
|
||
* every form en spells out for its group (`enReference`).
|
||
*
|
||
* Both counts are held at scripts/i18n-untranslated-baseline.json. The check
|
||
* fails when either grows past its entry (a file without one may hold none),
|
||
* so a feature can no longer ship 26 English copies of a new string. Lowering
|
||
* is a separate, explicit step:
|
||
*
|
||
* node scripts/i18n-untranslated.mjs check against the baseline (CI, via i18n-parity --strict)
|
||
* node scripts/i18n-untranslated.mjs --update lower the baseline to today's counts; it never raises an
|
||
* entry and drops the ones that reach zero
|
||
*
|
||
* The two counts are separate on purpose: deleting a marker without
|
||
* translating the string moves it from `marked` to `identical`, and the
|
||
* identical count refuses it.
|
||
*
|
||
* Fails closed: a missing or malformed baseline, a locale lacking one of en's
|
||
* files, or a value the catalogue reader cannot parse is an error, never a
|
||
* pass.
|
||
*/
|
||
import { pluralFormOf, pluralGroups } from '../src/i18n/plural.ts';
|
||
import { asPath, I18N_ROOT, listDomainFiles, listLocales, readCatalog } from './i18n-catalog.mjs';
|
||
|
||
import { existsSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
|
||
import { dirname, join } from 'node:path';
|
||
import { fileURLToPath } from 'node:url';
|
||
|
||
export const BASELINE = join(dirname(fileURLToPath(import.meta.url)), 'i18n-untranslated-baseline.json');
|
||
|
||
/**
|
||
* Product and service names, which read the same in every language. A value
|
||
* is excused for them, never for an ordinary word: German "Status" or French
|
||
* "Transport" are the locale's own words only by coincidence, and a one-word
|
||
* label copied from en ("Appearance", "Settings") is the commonest untranslated
|
||
* string there is. Names with an inner capital (MapLibre, OpenStreetMap) and
|
||
* acronyms need no entry, the word rule below already skips them.
|
||
*/
|
||
export const BRAND_NAMES = [
|
||
'Amap',
|
||
'Anthropic',
|
||
'Apple Maps',
|
||
'Atlas',
|
||
'ChatGPT',
|
||
'Claude',
|
||
'Dawarich',
|
||
'Discord',
|
||
'Docker',
|
||
'Gemini',
|
||
'Google',
|
||
'Google Maps',
|
||
'Google Places',
|
||
'Home Assistant',
|
||
'Immich',
|
||
'Mapbox',
|
||
'Ntfy',
|
||
'Ollama',
|
||
'OpenRouter',
|
||
'Organic Maps',
|
||
'Polaroid',
|
||
// The photo book editor's name, like Atlas and Vacay for their add-ons.
|
||
'Studio',
|
||
'Synology',
|
||
'Synology Photos',
|
||
// The hosted TREK offering, a product name like Vacay and Atlas.
|
||
'TREK Cloud',
|
||
'Vacay',
|
||
'Webhook',
|
||
'wanderer',
|
||
];
|
||
|
||
/** Unit symbols, short codes rather than words: "{count} km", "{minutes} min". */
|
||
export const UNITS = ['km', 'mi', 'ft', 'min'];
|
||
|
||
/**
|
||
* Key cap labels, printed on the keyboard in Latin letters whatever the
|
||
* language around them ("Ctrl" on a Russian or Japanese keyboard too). A
|
||
* locale whose keyboards print another word (German "Strg") translates it.
|
||
*/
|
||
export const KEY_NAMES = ['Ctrl'];
|
||
|
||
/**
|
||
* Locales written in a script other than Latin. A Latin word left in one of
|
||
* them is English whatever the word, so `// same-as-en` is not honoured
|
||
* there. Every locale folder must be listed in exactly one of the two lists,
|
||
* so a new locale cannot slip past this rule unclassified.
|
||
*/
|
||
export const NON_LATIN_LOCALES = ['ar', 'gr', 'he', 'ja', 'ko', 'ru', 'th', 'uk', 'zh', 'zh-TW'];
|
||
export const LATIN_LOCALES = [
|
||
'az',
|
||
'br',
|
||
'ca',
|
||
'cs',
|
||
'de',
|
||
'en',
|
||
'es',
|
||
'et',
|
||
'fr',
|
||
'hu',
|
||
'id',
|
||
'it',
|
||
'nl',
|
||
'pl',
|
||
'sk',
|
||
'sv',
|
||
'tr',
|
||
'vi',
|
||
];
|
||
|
||
const PLACEHOLDER_RE = /\{[a-zA-Z0-9_]+\}/g;
|
||
const TAG_RE = /<\/?[a-zA-Z][^>]*>/g;
|
||
// A URL, an e-mail address or a path: anything with a slash or an at sign in it.
|
||
const ADDRESS_RE = /\S*[/@]\S*/g;
|
||
// Hyphens join a word: "Check-in", "Wi-Fi" and "Auto-Backup" are one each.
|
||
const WORD_RE = /\p{L}[\p{L}\p{M}'’-]*/gu;
|
||
const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||
// Longest first, so "Google Maps" goes as one name before "Google" could split it.
|
||
const NAME_RE = new RegExp(
|
||
`(?<![\\p{L}\\p{N}])(?:${[...BRAND_NAMES, ...UNITS, ...KEY_NAMES]
|
||
.sort((a, b) => b.length - a.length)
|
||
.map(escapeRe)
|
||
.join('|')})(?![\\p{L}\\p{N}])`,
|
||
'gu',
|
||
);
|
||
|
||
/**
|
||
* A word in the sense of the rule: two letters or more and no capital after
|
||
* the first. Single letters (the A and Z of a sort label, the v of
|
||
* "v{version}"), acronyms (GPX, URLs, 2FA) and names with an inner capital
|
||
* (OAuth, AirTrail) are not words here.
|
||
*/
|
||
export const isPlainWord = (word) => word.length >= 2 && !/\p{Lu}/u.test(word.slice(1));
|
||
|
||
/**
|
||
* Whether a value equal to en's is legitimately the same text in every
|
||
* language. True when, after dropping placeholders, markup, addresses, the
|
||
* names in BRAND_NAMES and the UNITS, no plain word is left: "{count} km",
|
||
* "OAuth", "GPX", "Google Maps", "Atlas", "PDF · {size}". A single plain word
|
||
* is counted like a phrase: "Budget" and "Status" may be the locale's word too,
|
||
* and that is for a translator to confirm, not for the rule to assume.
|
||
*/
|
||
export function isInvariant(value) {
|
||
return plainWords(value).length === 0;
|
||
}
|
||
|
||
/** The plain words `value` holds once placeholders, markup, addresses, names and units are dropped. */
|
||
export function plainWords(value) {
|
||
const text = value.replace(PLACEHOLDER_RE, ' ').replace(TAG_RE, ' ').replace(ADDRESS_RE, ' ').replace(NAME_RE, ' ');
|
||
return (text.match(WORD_RE) ?? []).filter(isPlainWord);
|
||
}
|
||
|
||
/** Whether `locale` is written in Latin script. Throws for a locale on neither list. */
|
||
export function isLatinLocale(locale) {
|
||
if (LATIN_LOCALES.includes(locale)) return true;
|
||
if (NON_LATIN_LOCALES.includes(locale)) return false;
|
||
throw new Error(
|
||
`locale ${locale} is on neither LATIN_LOCALES nor NON_LATIN_LOCALES in scripts/i18n-untranslated.mjs`,
|
||
);
|
||
}
|
||
|
||
/**
|
||
* Whether an unmarked value equal to en's is excused: it is invariant, or a
|
||
* translator marked it `// same-as-en` in a Latin-script locale and it holds
|
||
* one plain word. The marker is for a word that really is the locale's own
|
||
* (German "Status"); a phrase that reads the same as en's is a copy, and the
|
||
* marker on it is ignored rather than trusted.
|
||
*/
|
||
export const isExcused = (value, same, locale) => {
|
||
const words = plainWords(value);
|
||
return words.length === 0 || (same && isLatinLocale(locale) && words.length === 1);
|
||
};
|
||
|
||
/**
|
||
* Every en value a locale's `key` may not repeat. A key en declares has its
|
||
* en value. A form of a plural group that en does not declare (Russian
|
||
* `.few`, Arabic `.two`) has every form en spells out for the group, since
|
||
* it has no en counterpart of its own and a copy of any of them is English.
|
||
* A form en declares keeps the exact comparison: Italian "{count} file" for
|
||
* en's general "{count} files" is the Italian plural, not en's `.one`.
|
||
*/
|
||
export function enReference(en, groups) {
|
||
const forms = new Map();
|
||
for (const [key, value] of en) {
|
||
const base = groupOf(key, groups);
|
||
if (base !== null) {
|
||
if (!forms.has(base)) forms.set(base, new Set());
|
||
forms.get(base).add(value);
|
||
}
|
||
}
|
||
return (key) => {
|
||
if (en.has(key)) return new Set([en.get(key)]);
|
||
const base = groupOf(key, groups);
|
||
return base === null ? new Set() : (forms.get(base) ?? new Set());
|
||
};
|
||
}
|
||
|
||
/** The plural group `key` belongs to (its base, `key.other` or a category form), else null. */
|
||
function groupOf(key, groups) {
|
||
if (groups.has(key)) return key;
|
||
if (key.endsWith('.other') && groups.has(key.slice(0, -'.other'.length))) return key.slice(0, -'.other'.length);
|
||
return pluralFormOf(key, groups)?.base ?? null;
|
||
}
|
||
|
||
/**
|
||
* Today's counts: `{ [locale]: { [file]: { marked, identical } } }`, only
|
||
* non-zero entries. Throws on a locale missing one of en's files, a locale
|
||
* on neither script list or a value the reader cannot parse.
|
||
*/
|
||
export function countUntranslated(root = I18N_ROOT) {
|
||
const locales = listLocales(root);
|
||
if (!locales.includes('en')) throw new Error(`${asPath(root)}/en is required as the reference locale`);
|
||
const enFiles = listDomainFiles('en', root);
|
||
const enValues = new Map(
|
||
enFiles.map((f) => {
|
||
const en = new Map(readCatalog('en', f, root).map((e) => [e.key, e.value]));
|
||
return [f, enReference(en, pluralGroups(en.keys()))];
|
||
}),
|
||
);
|
||
const counts = {};
|
||
for (const locale of locales) {
|
||
// Classify every folder first: an unlisted locale is an error, not a pass.
|
||
isLatinLocale(locale);
|
||
if (locale === 'en') continue;
|
||
const files = new Set(listDomainFiles(locale, root));
|
||
for (const file of enFiles) {
|
||
if (!files.has(file)) throw new Error(`${locale}/${file} is missing; run i18n-parity for the file report`);
|
||
const enValuesOf = enValues.get(file);
|
||
let marked = 0;
|
||
let identical = 0;
|
||
for (const { key, value, marked: isMarked, same } of readCatalog(locale, file, root)) {
|
||
if (isMarked) marked++;
|
||
else if (enValuesOf(key).has(value) && !isExcused(value, same, locale)) identical++;
|
||
}
|
||
if (marked || identical) (counts[locale] ??= {})[file] = { marked, identical };
|
||
}
|
||
}
|
||
return counts;
|
||
}
|
||
|
||
/** The committed baseline. Throws when it is missing or not the expected shape. */
|
||
export function readBaseline(path = BASELINE) {
|
||
let parsed;
|
||
try {
|
||
parsed = JSON.parse(readFileSync(path, 'utf8'));
|
||
} catch (err) {
|
||
throw new Error(`${path} cannot be read: ${err.message}. Restore it from git before running the check again.`);
|
||
}
|
||
const isCount = (n) => Number.isInteger(n) && n >= 0;
|
||
const valid =
|
||
parsed !== null &&
|
||
typeof parsed === 'object' &&
|
||
!Array.isArray(parsed) &&
|
||
Object.values(parsed).every(
|
||
(files) =>
|
||
files !== null &&
|
||
typeof files === 'object' &&
|
||
Object.values(files).every(
|
||
(entry) => entry !== null && typeof entry === 'object' && isCount(entry.marked) && isCount(entry.identical),
|
||
),
|
||
);
|
||
if (!valid) throw new Error(`${path} is not a { locale: { file: { marked, identical } } } map of whole numbers`);
|
||
return parsed;
|
||
}
|
||
|
||
const ZERO = { marked: 0, identical: 0 };
|
||
|
||
/** Every count above its baseline entry, and how many entries could come down. */
|
||
export function compare(counts, baseline) {
|
||
const grown = [];
|
||
let lowerable = 0;
|
||
for (const [locale, files] of Object.entries(counts)) {
|
||
for (const [file, now] of Object.entries(files)) {
|
||
const allowed = baseline[locale]?.[file] ?? ZERO;
|
||
for (const kind of ['marked', 'identical']) {
|
||
if (now[kind] > allowed[kind]) grown.push({ locale, file, kind, now: now[kind], allowed: allowed[kind] });
|
||
}
|
||
}
|
||
}
|
||
for (const [locale, files] of Object.entries(baseline)) {
|
||
for (const [file, allowed] of Object.entries(files)) {
|
||
const now = counts[locale]?.[file] ?? ZERO;
|
||
if (now.marked < allowed.marked || now.identical < allowed.identical) lowerable++;
|
||
}
|
||
}
|
||
return { grown, lowerable };
|
||
}
|
||
|
||
/** The baseline lowered to `counts`: never raised, zero entries dropped, sorted. */
|
||
export function lowered(counts, baseline) {
|
||
const out = {};
|
||
for (const locale of Object.keys(baseline).sort()) {
|
||
for (const file of Object.keys(baseline[locale]).sort()) {
|
||
const allowed = baseline[locale][file];
|
||
const now = counts[locale]?.[file] ?? ZERO;
|
||
const entry = {
|
||
marked: Math.min(allowed.marked, now.marked),
|
||
identical: Math.min(allowed.identical, now.identical),
|
||
};
|
||
if (entry.marked || entry.identical) (out[locale] ??= {})[file] = entry;
|
||
}
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/** The baseline as committed: one line per file, so a diff shows which counts came down. */
|
||
export function serialize(baseline) {
|
||
const locales = Object.keys(baseline).map((locale) => {
|
||
const files = Object.entries(baseline[locale]).map(
|
||
([file, { marked, identical }]) =>
|
||
` ${JSON.stringify(file)}: { "marked": ${marked}, "identical": ${identical} }`,
|
||
);
|
||
return ` ${JSON.stringify(locale)}: {\n${files.join(',\n')}\n }`;
|
||
});
|
||
return `{\n${locales.join(',\n')}\n}\n`;
|
||
}
|
||
|
||
export function formatGrown(grown) {
|
||
return grown.map(
|
||
({ locale, file, kind, now, allowed }) =>
|
||
` ${locale}/${file}: ${now} ${kind === 'marked' ? 'marked en-fallback' : 'unmarked English copies'}, ` +
|
||
`the baseline allows ${allowed}`,
|
||
);
|
||
}
|
||
|
||
const total = (map, kind) =>
|
||
Object.values(map)
|
||
.flatMap((files) => Object.values(files))
|
||
.reduce((sum, e) => sum + e[kind], 0);
|
||
|
||
// Compared by real path, so the check still runs when the script is started through a symlink.
|
||
const isCli =
|
||
Boolean(process.argv[1]) &&
|
||
existsSync(process.argv[1]) &&
|
||
realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
|
||
if (isCli) {
|
||
try {
|
||
const counts = countUntranslated();
|
||
let baseline = readBaseline();
|
||
if (process.argv.includes('--update')) {
|
||
baseline = lowered(counts, baseline);
|
||
writeFileSync(BASELINE, serialize(baseline));
|
||
}
|
||
const { grown, lowerable } = compare(counts, baseline);
|
||
if (grown.length) {
|
||
console.error('Untranslated strings grew past scripts/i18n-untranslated-baseline.json:');
|
||
for (const line of formatGrown(grown)) console.error(line);
|
||
console.error('Translate the new strings (shared/CLAUDE.md: an English placeholder is not acceptable).');
|
||
}
|
||
if (lowerable && !process.argv.includes('--update')) {
|
||
console.log(
|
||
`${lowerable} baseline entr${lowerable === 1 ? 'y is' : 'ies are'} above today's count: run with --update to lower.`,
|
||
);
|
||
}
|
||
console.log(
|
||
`untranslated: ${total(counts, 'marked')} marked en-fallback, ${total(counts, 'identical')} unmarked English copies`,
|
||
);
|
||
if (grown.length) process.exit(1);
|
||
} catch (err) {
|
||
console.error(`FAIL ${err.message}`);
|
||
process.exit(1);
|
||
}
|
||
}
|