ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(i18n): one locale-aware format door; delete the timeAgo shim
Juan Denis7050b24137a4
diff --git a/frontend/package.json b/frontend/package.jsonindex 820078f8..0759f807 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -7,10 +7,11 @@"dev": "vite","build": "vite build","test": "node --test",- "lint": "eslint . && node scripts/check-settings-index.mjs && node scripts/check-theme-tokens.mjs && node scripts/check-frontend-boundaries.mjs && node scripts/check-style-ownership.mjs && node scripts/check-status-one-door.mjs && node scripts/check-status-scss.mjs && node scripts/check-i18n-literals.mjs && node ../scripts/check-html-sinks.mjs",+ "lint": "eslint . && node scripts/check-settings-index.mjs && node scripts/check-theme-tokens.mjs && node scripts/check-frontend-boundaries.mjs && node scripts/check-style-ownership.mjs && node scripts/check-status-one-door.mjs && node scripts/check-status-scss.mjs && node scripts/check-i18n-literals.mjs && node scripts/check-intl-door.mjs && node ../scripts/check-html-sinks.mjs","lint:settings-index": "node scripts/check-settings-index.mjs","lint:status": "node scripts/check-status-one-door.mjs","lint:i18n": "node scripts/check-i18n-literals.mjs",+ "lint:intl": "node scripts/check-intl-door.mjs","lint:html-sinks": "node ../scripts/check-html-sinks.mjs","lint:frontend-boundaries": "node scripts/check-frontend-boundaries.mjs","capture:skeletons": "node scripts/capture-skeletons.mjs",diff --git a/frontend/scripts/INTL_DOOR_CEILING b/frontend/scripts/INTL_DOOR_CEILINGnew file mode 100644index 00000000..fc902f4f--- /dev/null+++ b/frontend/scripts/INTL_DOOR_CEILING@@ -0,0 +1 @@+124diff --git a/frontend/scripts/check-intl-door.mjs b/frontend/scripts/check-intl-door.mjsnew file mode 100644index 00000000..3a43a1a6--- /dev/null+++ b/frontend/scripts/check-intl-door.mjs@@ -0,0 +1,126 @@+#!/usr/bin/env node+// Plan 79 ratchet 5 — one locale-aware formatting door.+//+// Counts direct `toLocaleString` / `toLocaleDateString` / `toLocaleTimeString`+// calls and direct `new Intl.*` construction outside `src/utils/intl.js`.+//+// Every one of these is a locale bug, not merely a style problem: called with+// no argument they follow the BROWSER's locale rather than the panel's, so a+// panel switched to Spanish still renders English dates -- and a formatter+// built at module load can never follow a switch at all. They are also the+// slow path: tables construct one formatter per cell per render, which is the+// expensive half of Intl.+//+// Usage (from frontend/):+// node scripts/check-intl-door.mjs # check against the ceiling+// node scripts/check-intl-door.mjs --report # list the offenders+// node scripts/check-intl-door.mjs --update # write the current count++import { readFileSync, readdirSync, writeFileSync } from 'node:fs';+import { dirname, extname, join, relative, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++const here = dirname(fileURLToPath(import.meta.url));+const root = resolve(here, '..');+const srcDir = resolve(root, 'src');+const ceilingFile = resolve(here, 'INTL_DOOR_CEILING');++// The door itself, and the tests that prove it behaves per locale.+const ALLOWED = new Set([+ 'utils/intl.js',+ 'utils/__tests__/intl.test.mjs',+]);++const PATTERN = /\.toLocale(?:Date|Time)?String\s*\(|new\s+Intl\.\w+/g;++function walk(dir) {+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {+ const path = join(dir, entry.name);+ if (entry.isDirectory()) {+ return entry.name === 'node_modules' ? [] : walk(path);+ }+ return ['.js', '.jsx', '.mjs'].includes(extname(entry.name)) ? [path] : [];+ });+}++export function census() {+ const byFile = new Map();+ for (const path of walk(srcDir)) {+ const rel = relative(srcDir, path).replaceAll('\\', '/');+ if (ALLOWED.has(rel)) continue;+ const hits = [];+ const lines = readFileSync(path, 'utf8').split(/\r?\n/);+ // Comments are stripped first: a doc comment that NAMES the pattern is+ // not a call, and counting it would mean a violation could be "fixed"+ // by commenting it out.+ let inBlock = false;+ lines.forEach((line, index) => {+ let code = line;+ if (inBlock) {+ const end = code.indexOf('*/');+ if (end === -1) return;+ code = code.slice(end + 2);+ inBlock = false;+ }+ code = code.replace(/\/\*[^*]*\*\//g, '');+ const blockStart = code.indexOf('/*');+ if (blockStart !== -1) {+ inBlock = true;+ code = code.slice(0, blockStart);+ }+ const lineComment = code.indexOf('//');+ if (lineComment !== -1) code = code.slice(0, lineComment);++ for (const match of code.matchAll(PATTERN)) {+ hits.push({ line: index + 1, text: match[0].trim() });+ }+ });+ if (hits.length) byFile.set(rel, hits);+ }+ return byFile;+}++const byFile = census();+const count = [...byFile.values()].reduce((total, hits) => total + hits.length, 0);++if (process.argv.includes('--update')) {+ writeFileSync(ceilingFile, `${count}\n`);+ console.log(`intl door ceiling updated to ${count}`);+ process.exit(0);+}++if (process.argv.includes('--report')) {+ const rows = [...byFile].sort((a, b) => b[1].length - a[1].length);+ for (const [file, hits] of rows) {+ console.log(` ${String(hits.length).padStart(3)} ${file}`);+ for (const hit of hits.slice(0, 3)) {+ console.log(` :${hit.line} ${hit.text}`);+ }+ }+ console.log(`\ntotal: ${count} direct calls in ${byFile.size} files`);+ process.exit(0);+}++const ceiling = Number(readFileSync(ceilingFile, 'utf8').trim());++if (count > ceiling) {+ const worst = [...byFile].sort((a, b) => b[1].length - a[1].length).slice(0, 5);+ console.error('\nintl door check failed:\n');+ console.error(` ${count} direct Intl / toLocale* calls; the ceiling is ${ceiling}.`);+ console.error(' Format through the door so the value follows the PANEL locale:\n');+ console.error(" import useFormat from '@/hooks/useFormat'; // components");+ console.error(" import { formatDate } from '@/utils/intl'; // everything else\n");+ for (const [file, hits] of worst) {+ console.error(` ${String(hits.length).padStart(3)} ${file}`);+ }+ console.error('');+ process.exit(1);+}++if (ceiling - count > 5) {+ console.error(`\nintl door ceiling is ${ceiling} but only ${count} remain; run`);+ console.error(' node scripts/check-intl-door.mjs --update\n');+ process.exit(1);+}++console.log(`✓ intl door: ${count} direct Intl/toLocale calls remain ratcheted (ceiling ${ceiling}).`);diff --git a/frontend/src/components/NotificationBell.jsx b/frontend/src/components/NotificationBell.jsxindex cd0cea22..d58423a6 100644--- a/frontend/src/components/NotificationBell.jsx+++ b/frontend/src/components/NotificationBell.jsx@@ -2,7 +2,7 @@ import { useState, useRef, useEffect } from 'react';import { useNavigate } from 'react-router-dom';import { Bell, Check, X } from 'lucide-react';import { useNotifications } from '../contexts/NotificationsContext';-import { timeAgo } from '../utils/timeAgo';+import { timeAgo } from '../utils/time';// Severity → dot color, mirroring the email/brand palette.const SEVERITY_DOT = {diff --git a/frontend/src/components/backups/format.js b/frontend/src/components/backups/format.jsindex 44c9bb56..0370b0c9 100644--- a/frontend/src/components/backups/format.js+++ b/frontend/src/components/backups/format.js@@ -1,5 +1,5 @@// Shared formatting helpers for the backup "Protection" components.-import { timeAgo } from '@/utils/timeAgo';+import { timeAgo } from '@/utils/time';const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];diff --git a/frontend/src/components/settings/connections/DnsActivity.jsx b/frontend/src/components/settings/connections/DnsActivity.jsxindex eff1c7a1..d27fe9ba 100644--- a/frontend/src/components/settings/connections/DnsActivity.jsx+++ b/frontend/src/components/settings/connections/DnsActivity.jsx@@ -5,7 +5,7 @@import { useCallback, useEffect, useState } from 'react';import { Activity } from 'lucide-react';import api from '../../../services/api';-import { timeAgo } from '../../../utils/timeAgo';+import { timeAgo } from '../../../utils/time';// result → Badge-like pill tone. ok=green, error=red, conflict=amber, skipped=muted.const RESULT_TONE = {diff --git a/frontend/src/contexts/LocaleContext.jsx b/frontend/src/contexts/LocaleContext.jsxindex 2e7f0016..6021d782 100644--- a/frontend/src/contexts/LocaleContext.jsx+++ b/frontend/src/contexts/LocaleContext.jsx@@ -2,6 +2,7 @@ import {createContext, useCallback, useContext, useEffect, useMemo, useRef, useState,} from 'react';import { activateLocale } from '../i18n';+import { setFormatLocale } from '../utils/intl';import {DEFAULT_LANGUAGE, LANGUAGES, STORAGE_KEY,directionFor, languageInfo, matchSupported, navigatorLanguages, resolveLocale,@@ -36,6 +37,11 @@ export function LocaleProvider({ children }) {// during page load does not get overwritten by their own stored value.const hydratedRef = useRef(false);+ // Publish to the format door BEFORE the render that follows, so a+ // non-React caller (API error mapper, CSV export) can never format against+ // the previous locale. Doing this in an effect would be one paint late.+ setFormatLocale(language);+useEffect(() => {let cancelled = false;activateLocale(language).then((applied) => {diff --git a/frontend/src/hooks/useFormat.js b/frontend/src/hooks/useFormat.jsnew file mode 100644index 00000000..3c732356--- /dev/null+++ b/frontend/src/hooks/useFormat.js@@ -0,0 +1,32 @@+import { useMemo } from 'react';+import { useLocale } from '../contexts/LocaleContext';+import * as intl from '../utils/intl';++/**+ * The format door for components (plan 79 §C).+ *+ * Same implementation as `utils/intl` — this is a subscription, not a second+ * door. Components need it because a locale switch has to re-render them;+ * non-React callers (the API error mapper, the log formatter, CSV export)+ * import the module directly. Both read one module-level locale.+ */+export default function useFormat() {+ const { language } = useLocale();++ // `language` is the dependency on purpose: the functions themselves are+ // stable module references, so without it a switch would not re-render.+ return useMemo(() => ({+ formatDate: intl.formatDate,+ formatTime: intl.formatTime,+ formatDateTime: intl.formatDateTime,+ formatRelative: intl.formatRelative,+ formatRelativeShort: intl.formatRelativeShort,+ formatDuration: intl.formatDuration,+ formatNumber: intl.formatNumber,+ formatCompactNumber: intl.formatCompactNumber,+ formatPercent: intl.formatPercent,+ formatList: intl.formatList,+ locale: language,+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }), [language]);+}diff --git a/frontend/src/pages/DeliveryLog.jsx b/frontend/src/pages/DeliveryLog.jsxindex b5f2c937..d177c4f0 100644--- a/frontend/src/pages/DeliveryLog.jsx+++ b/frontend/src/pages/DeliveryLog.jsx@@ -15,7 +15,7 @@ import EmptyState from '../components/EmptyState';import { Button } from '@/components/ui/button';import { useAuth } from '../contexts/AuthContext';import { useToast } from '../contexts/ToastContext';-import { timeAgo } from '../utils/timeAgo';+import { timeAgo } from '../utils/time';import EmailProviders from '../components/EmailProviders';import { usePolling } from '@/hooks/usePolling';diff --git a/frontend/src/pages/Jobs.jsx b/frontend/src/pages/Jobs.jsxindex 35aa1d2a..4ddb7ec3 100644--- a/frontend/src/pages/Jobs.jsx+++ b/frontend/src/pages/Jobs.jsx@@ -29,7 +29,7 @@ import { useTableSort } from '@/hooks/useTableSort';import { useColumnVisibility } from '@/hooks/useColumnVisibility';import { useAuth } from '../contexts/AuthContext';import { useToast } from '../contexts/ToastContext';-import { timeAgo } from '../utils/timeAgo';+import { timeAgo } from '../utils/time';import { usePolling } from '@/hooks/usePolling';const titleCase = (value = '') => value.charAt(0).toUpperCase() + value.slice(1);diff --git a/frontend/src/pages/Notifications.jsx b/frontend/src/pages/Notifications.jsxindex b95da6a0..afb115c4 100644--- a/frontend/src/pages/Notifications.jsx+++ b/frontend/src/pages/Notifications.jsx@@ -6,7 +6,7 @@ import PageLayout from '../layouts/PageLayout';import { Button } from '@/components/ui/button';import { useAuth } from '../contexts/AuthContext';import { useNotifications } from '../contexts/NotificationsContext';-import { timeAgo } from '../utils/timeAgo';+import { timeAgo } from '../utils/time';const SEVERITY_DOT = {critical: '#fb6f6f',diff --git a/frontend/src/utils/__tests__/intl.test.mjs b/frontend/src/utils/__tests__/intl.test.mjsnew file mode 100644index 00000000..2e2ebd19--- /dev/null+++ b/frontend/src/utils/__tests__/intl.test.mjs@@ -0,0 +1,145 @@+import assert from 'node:assert/strict';+import test, { afterEach } from 'node:test';++import {+ formatBytes,+} from '../formatBytes.js';+import {+ formatDate, formatDateTime, formatDuration, formatList, formatNumber,+ formatPercent, formatRelative, formatRelativeShort, formatTime,+ getFormatLocale, setFormatLocale,+} from '../intl.js';+import { timeAgo, formatRelativeTime } from '../time.js';++afterEach(() => setFormatLocale('en'));++test('the door starts on English', () => {+ assert.equal(getFormatLocale(), 'en');+});++test('dates follow the panel locale, not the browser', () => {+ // The bug this door exists for: `toLocaleDateString()` with no argument+ // follows the browser. These must differ by panel locale alone.+ const iso = '2026-08-19T10:00:00Z';+ const english = formatDate(iso);+ setFormatLocale('es');+ const spanish = formatDate(iso);++ assert.notEqual(english, spanish);+ assert.match(english, /Aug/);+ assert.match(spanish, /ago/);+});++test('numbers use the locale separators', () => {+ assert.equal(formatNumber(1234567.89, { decimals: 1 }), '1,234,567.9');+ setFormatLocale('es');+ assert.equal(formatNumber(1234567.89, { decimals: 1 }), '1.234.567,9');+});++test('relative time is localized by Intl, not by keys', () => {+ const threeDaysAgo = Date.now() - 3 * 86400000;+ assert.equal(formatRelative(threeDaysAgo), '3 days ago');+ setFormatLocale('es');+ assert.equal(formatRelative(threeDaysAgo), 'hace 3 días');+});++test('relative time handles the future and the present', () => {+ assert.equal(formatRelative(Date.now() + 2 * 3600000), 'in 2 hours');+ assert.match(formatRelative(Date.now()), /now|second/);+});++test('lists join the way the language joins', () => {+ assert.equal(formatList(['a', 'b', 'c']), 'a, b, and c');+ setFormatLocale('es');+ assert.equal(formatList(['a', 'b', 'c']), 'a, b y c');+});++test('percent is a percentage, not a ratio', () => {+ assert.equal(formatPercent(42), '42%');+ assert.equal(formatPercent(42.55, { decimals: 1 }), '42.6%');+});++test('durations read in seconds', () => {+ assert.equal(formatDuration(45), '45s');+ assert.equal(formatDuration(200), '3m 20s');+ assert.equal(formatDuration(180), '3m');+ assert.equal(formatDuration(7500), '2h 5m');+ assert.equal(formatDuration(7200), '2h');+});++test('unusable input yields a placeholder, never NaN or Invalid Date', () => {+ for (const bad of [null, undefined, '', 'not-a-date', NaN]) {+ assert.equal(formatDate(bad), '-', `formatDate(${String(bad)})`);+ assert.equal(formatTime(bad), '-', `formatTime(${String(bad)})`);+ assert.equal(formatDateTime(bad), '-', `formatDateTime(${String(bad)})`);+ assert.equal(formatRelative(bad), '', `formatRelative(${String(bad)})`);+ }+ for (const bad of [null, undefined, 'abc', NaN, Infinity]) {+ assert.equal(formatNumber(bad), '-', `formatNumber(${String(bad)})`);+ }+ assert.equal(formatDuration(-1), '-');+});++test('accepts ISO strings, epoch millis, and Date alike', () => {+ const iso = '2026-08-19T10:00:00Z';+ const expected = formatDate(iso);+ assert.equal(formatDate(new Date(iso)), expected);+ assert.equal(formatDate(new Date(iso).getTime()), expected);+});++test('the compact style keeps its shape, and its date tail follows the locale', () => {+ // Deliberately NOT switched to Intl's "4 minutes ago": the compact form is+ // a table style with no Intl equivalent, so its units are translation keys.+ assert.equal(formatRelativeShort(Date.now() - 10 * 1000), 'just now');+ assert.equal(formatRelativeShort(Date.now() - 4 * 60000), '4m');+ assert.equal(formatRelativeShort(Date.now() - 3 * 3600000), '3h');+ assert.equal(formatRelativeShort(Date.now() - 2 * 86400000), '2d');++ // Past a week it becomes a date -- which used to be the browser's date.+ const old = Date.now() - 60 * 86400000;+ const english = formatRelativeShort(old);+ setFormatLocale('es');+ assert.notEqual(formatRelativeShort(old), english);+});++test('time.js delegates rather than reimplementing', () => {+ assert.equal(timeAgo(Date.now() - 4 * 60000), formatRelativeShort(Date.now() - 4 * 60000));+ assert.equal(+ formatRelativeTime(Date.now() - 3 * 86400000),+ formatRelative(Date.now() - 3 * 86400000),+ );+ assert.equal(timeAgo(null), '');+ assert.equal(timeAgo('nonsense'), '');+});++test('formatBytes output is unchanged for English', () => {+ // Parity against the examples documented on the pre-migration util. The+ // trimming used to be a regex on toFixed(); it is now Intl's+ // maximumFractionDigits, which must behave the same in en.+ assert.equal(formatBytes(1536), '1.5 KB');+ assert.equal(formatBytes(0), '0 B');+ assert.equal(formatBytes(null), '-');+ assert.equal(formatBytes(1234567, { decimals: 2 }), '1.18 MB');+ assert.equal(formatBytes(2048, { iec: true }), '2 KiB');+ assert.equal(formatBytes(2048, { suffix: false }), '2');+ assert.equal(formatBytes(512), '512 B');+ assert.equal(formatBytes(1073741824), '1 GB');+ assert.equal(formatBytes(-2048), '-2 KB');+});++test('formatBytes uses the locale decimal separator', () => {+ // The old regex trim could not: a Spanish panel read "1.5 KB" while every+ // other number on the page used a comma.+ setFormatLocale('es');+ assert.equal(formatBytes(1536), '1,5 KB');+});++test('switching locale invalidates the formatter cache', () => {+ const iso = '2026-08-19T10:00:00Z';+ const first = formatDate(iso);+ setFormatLocale('es');+ const second = formatDate(iso);+ setFormatLocale('en');+ assert.equal(formatDate(iso), first);+ assert.notEqual(first, second);+});diff --git a/frontend/src/utils/formatBytes.js b/frontend/src/utils/formatBytes.jsindex e6b2bc5b..3cd25904 100644--- a/frontend/src/utils/formatBytes.js+++ b/frontend/src/utils/formatBytes.js@@ -12,6 +12,8 @@// formatBytes(2048, { iec: true }) -> "2 KiB"// formatBytes(2048, { suffix: false }) -> "2"+import { formatNumber } from './intl.js';+const DECIMAL_UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'];const IEC_UNITS = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB'];@@ -42,12 +44,13 @@ export function formatBytes(bytes, options = {}) {// Whole-byte values never need decimals.const places = exponent === 0 ? 0 : decimals;- let formatted = scaled.toFixed(places);- // Trim trailing zeros ("1.0" -> "1", "1.50" -> "1.5") for a cleaner read.- if (formatted.includes('.')) {- formatted = formatted.replace(/\.?0+$/, '');- }+ // Plan 79 §C: through the format door rather than toFixed + a regex trim.+ // `maximumFractionDigits` drops trailing zeros for free ("1.0" -> "1",+ // "1.50" -> "1.5") AND uses the locale's decimal separator, which the+ // string-trim could not: a Spanish panel showed "1.5 KB" where every other+ // number on the page read "1,5".+ const formatted = formatNumber(scaled, { maximumFractionDigits: places });const sign = negative ? '-' : '';return suffix ? `${sign}${formatted} ${units[exponent]}` : `${sign}${formatted}`;diff --git a/frontend/src/utils/formatNumber.js b/frontend/src/utils/formatNumber.jsindex 772a3615..147fa65a 100644--- a/frontend/src/utils/formatNumber.js+++ b/frontend/src/utils/formatNumber.js@@ -1,27 +1,28 @@// Number formatting helpers for KPI tiles and count badges.//-// `formatCompact` renders large counts in a space-tight notation (107814 →+// `formatCompact` renders large counts in a space-tight notation (107814 ->// "107.8K") so a 6-digit total never bursts a narrow tile; `formatFull` is the-// grouped exact form (107814 → "107,814") used as the hover title so the precise-// count stays one hover away. Non-finite / non-numeric input is returned-// unchanged, letting callers pass placeholders like '—' straight through.-const compactFormatter = new Intl.NumberFormat('en', {- notation: 'compact',- maximumFractionDigits: 1,-});+// grouped exact form (107814 -> "107,814") used as the hover title so the+// precise count stays one hover away. Non-finite / non-numeric input is+// returned unchanged, letting callers pass placeholders like an em dash+// straight through.+//+// Plan 79 §C: both used to build `new Intl.NumberFormat('en')` at module load+// -- a hardcoded locale AND a formatter that could never follow a switch.+// They now delegate to the format door.-const fullFormatter = new Intl.NumberFormat('en');+import { formatCompactNumber, formatNumber } from './intl.js';export function formatCompact(value) {const n = typeof value === 'number' ? value : Number(value);if (!Number.isFinite(n)) return value;- return compactFormatter.format(n);+ return formatCompactNumber(n);}export function formatFull(value) {const n = typeof value === 'number' ? value : Number(value);if (!Number.isFinite(n)) return value;- return fullFormatter.format(n);+ return formatNumber(n);}export default formatCompact;diff --git a/frontend/src/utils/intl.js b/frontend/src/utils/intl.jsnew file mode 100644index 00000000..8f27f9e3--- /dev/null+++ b/frontend/src/utils/intl.js@@ -0,0 +1,261 @@+// Plan 79 §C — the one locale-aware formatting door.+//+// Before this, five util files formatted things for humans and none of them+// took a locale, while 93 files called `toLocaleDateString()` with no+// argument. That follows the BROWSER's locale, not the panel's, so a panel set+// to Spanish already rendered English chrome around Spanish dates — a bug that+// predates any translation work.+//+// Three properties this door has that the scattered calls did not:+//+// 1. A module-level `currentLocale`, published by LocaleContext rather than+// read from a hook. The API error mapper, the log formatter and the CSV+// exporter all format for humans outside React; a hook cannot serve them,+// and a second source of locale is a second locale.+// 2. `useFormat()` for components, so they re-render on a locale switch.+// Same implementation underneath — the hook is a subscription, not a+// second door.+// 3. Formatter instances cached per (locale, kind, options). Tables format+// thousands of cells and `Intl.DateTimeFormat` construction is the+// expensive part; the `toLocaleDateString()` calls this replaces built a+// fresh formatter per cell per render.++import i18next from 'i18next';++let currentLocale = 'en';+const formatters = new Map();++/**+ * Point the door at a locale. Called by LocaleContext BEFORE it re-renders,+ * so non-React callers never format against the previous locale.+ */+export function setFormatLocale(locale) {+ if (!locale || locale === currentLocale) return;+ currentLocale = locale;+ formatters.clear(); // cached instances are locale-bound+}++export function getFormatLocale() {+ return currentLocale;+}++function cached(kind, options, build) {+ const key = `${currentLocale}|${kind}|${JSON.stringify(options)}`;+ let instance = formatters.get(key);+ if (!instance) {+ instance = build(currentLocale, options);+ formatters.set(key, instance);+ }+ return instance;+}++/**+ * Translate with an inline English default, tolerating an uninitialised+ * i18next (node tooling, tests, a crash before the provider mounts).+ */+function translate(key, fallback, values) {+ if (i18next.isInitialized) {+ return i18next.t(key, { defaultValue: fallback, ...values });+ }+ return String(fallback).replace(/\{\{(\w+)\}\}/g, (_, name) => (+ values && name in values ? values[name] : `{{${name}}}`+ ));+}++/** Accepts an ISO string, epoch millis, or a Date. Returns null when unusable. */+function toDate(value) {+ if (value === null || value === undefined || value === '') return null;+ const date = value instanceof Date ? value : new Date(value);+ return Number.isNaN(date.getTime()) ? null : date;+}++function toNumber(value) {+ // `Number(null)`, `Number('')` and `Number([])` are all 0, so a plain+ // coercion renders a missing metric as a real zero -- which reads as data.+ if (value === null || value === undefined || value === '') return null;+ if (typeof value !== 'number' && typeof value !== 'string') return null;+ const number = typeof value === 'number' ? value : Number(value);+ return Number.isFinite(number) ? number : null;+}++// ---------------------------------------------------------------- dates ---++const DATE_STYLES = { short: 'short', medium: 'medium', long: 'long', full: 'full' };++export function formatDate(value, { style = 'medium', fallback = '-' } = {}) {+ const date = toDate(value);+ if (!date) return fallback;+ return cached('date', { style }, (locale, options) => new Intl.DateTimeFormat(locale, {+ dateStyle: DATE_STYLES[options.style] || 'medium',+ })).format(date);+}++export function formatTime(value, { seconds = false, fallback = '-' } = {}) {+ const date = toDate(value);+ if (!date) return fallback;+ return cached('time', { seconds }, (locale, options) => new Intl.DateTimeFormat(locale, {+ timeStyle: options.seconds ? 'medium' : 'short',+ })).format(date);+}++export function formatDateTime(value, { style = 'medium', seconds = false, fallback = '-' } = {}) {+ const date = toDate(value);+ if (!date) return fallback;+ return cached('datetime', { style, seconds }, (locale, options) => new Intl.DateTimeFormat(locale, {+ dateStyle: DATE_STYLES[options.style] || 'medium',+ timeStyle: options.seconds ? 'medium' : 'short',+ })).format(date);+}++// ------------------------------------------------------------- relative ---++const RELATIVE_UNITS = [+ ['year', 31536000],+ ['month', 2592000],+ ['week', 604800],+ ['day', 86400],+ ['hour', 3600],+ ['minute', 60],+ ['second', 1],+];++/**+ * Locale-correct relative time — "3 days ago", "hace 3 días".+ *+ * Uses Intl.RelativeTimeFormat rather than translation keys on purpose: the+ * browser already knows every language's plural rules and wording for this,+ * and hand-keying "{{count}} days ago" would need a per-language plural table+ * that Intl maintains for free.+ */+export function formatRelative(value, { style = 'long', numeric = 'auto', fallback = '' } = {}) {+ const date = toDate(value);+ if (!date) return fallback;++ const deltaSeconds = (date.getTime() - Date.now()) / 1000;+ const absolute = Math.abs(deltaSeconds);++ const [unit, size] = RELATIVE_UNITS.find(([, seconds]) => absolute >= seconds)+ || ['second', 1];+ const amount = Math.round(deltaSeconds / size);++ return cached('relative', { style, numeric }, (locale, options) => (+ new Intl.RelativeTimeFormat(locale, options)+ )).format(amount, unit);+}++/**+ * The panel's compact relative style — "just now", "4m", "3h", "2d", then a+ * date. Intl has no compact-without-"ago" form, so the units come from+ * translation keys; the date tail goes through formatDate and so follows the+ * panel locale rather than the browser's.+ */+export function formatRelativeShort(value, { fallback = '' } = {}) {+ const date = toDate(value);+ if (!date) return fallback;++ const seconds = Math.floor((Date.now() - date.getTime()) / 1000);+ if (seconds < 45) return translate('common.time.justNow', 'just now');++ const minutes = Math.floor(seconds / 60);+ if (minutes < 60) return translate('common.time.minutesShort', '{{count}}m', { count: minutes });++ const hours = Math.floor(minutes / 60);+ if (hours < 24) return translate('common.time.hoursShort', '{{count}}h', { count: hours });++ const days = Math.floor(hours / 24);+ if (days < 7) return translate('common.time.daysShort', '{{count}}d', { count: days });++ return formatDate(date, { style: 'short' });+}++/** Duration in SECONDS — "45s", "3m 20s", "2h 5m". */+export function formatDuration(seconds, { fallback = '-' } = {}) {+ const total = toNumber(seconds);+ if (total === null || total < 0) return fallback;++ if (total < 60) {+ return translate('common.duration.seconds', '{{count}}s', { count: Math.round(total) });+ }+ const minutes = Math.floor(total / 60);+ if (minutes < 60) {+ const rest = Math.round(total % 60);+ return rest+ ? translate('common.duration.minutesSeconds', '{{minutes}}m {{seconds}}s',+ { minutes, seconds: rest })+ : translate('common.duration.minutes', '{{count}}m', { count: minutes });+ }+ const hours = Math.floor(minutes / 60);+ const restMinutes = minutes % 60;+ return restMinutes+ ? translate('common.duration.hoursMinutes', '{{hours}}h {{minutes}}m',+ { hours, minutes: restMinutes })+ : translate('common.duration.hours', '{{count}}h', { count: hours });+}++// -------------------------------------------------------------- numbers ---++/**+ * `decimals` pins both bounds (a fixed 2dp money-style read);+ * `maximumFractionDigits` only caps them, so trailing zeros drop — which is+ * what size and metric readouts want.+ */+export function formatNumber(value, { decimals, maximumFractionDigits, fallback = '-' } = {}) {+ const number = toNumber(value);+ if (number === null) return fallback;+ return cached('number', { decimals, maximumFractionDigits }, (locale, options) => (+ new Intl.NumberFormat(locale, {+ ...(options.decimals === undefined ? {} : {+ minimumFractionDigits: options.decimals,+ maximumFractionDigits: options.decimals,+ }),+ ...(options.maximumFractionDigits === undefined ? {} : {+ maximumFractionDigits: options.maximumFractionDigits,+ }),+ })+ )).format(number);+}++/** Space-tight form for KPI tiles — 107814 -> "107.8K" (and its locale's form). */+export function formatCompactNumber(value, { fallback = '-' } = {}) {+ const number = toNumber(value);+ if (number === null) return fallback;+ return cached('compact', {}, (locale) => new Intl.NumberFormat(locale, {+ notation: 'compact',+ maximumFractionDigits: 1,+ })).format(number);+}++/** `value` is the percentage itself (42 -> "42%"), not a 0..1 ratio. */+export function formatPercent(value, { decimals = 0, fallback = '-' } = {}) {+ const number = toNumber(value);+ if (number === null) return fallback;+ return cached('percent', { decimals }, (locale, options) => new Intl.NumberFormat(locale, {+ style: 'percent',+ minimumFractionDigits: options.decimals,+ maximumFractionDigits: options.decimals,+ })).format(number / 100);+}++/** "a, b and c" — join wording differs by language. */+export function formatList(items, { type = 'conjunction' } = {}) {+ const list = (items || []).filter((item) => item !== null && item !== undefined).map(String);+ if (!list.length) return '';+ if (typeof Intl.ListFormat !== 'function') return list.join(', ');+ return cached('list', { type }, (locale, options) => new Intl.ListFormat(locale, {+ style: 'long',+ type: options.type,+ })).format(list);+}++export default {+ formatDate,+ formatTime,+ formatDateTime,+ formatRelative,+ formatRelativeShort,+ formatDuration,+ formatNumber,+ formatCompactNumber,+ formatPercent,+ formatList,+};diff --git a/frontend/src/utils/time.js b/frontend/src/utils/time.jsindex 23bd981c..40046a57 100644--- a/frontend/src/utils/time.js+++ b/frontend/src/utils/time.js@@ -1,54 +1,29 @@-// Canonical relative-time helpers for the whole frontend.+// Relative-time and duration helpers.//-// Two output styles existed across the codebase; keep both, but in one place:-// - timeAgo(iso) compact: "just now", "4m", "3h", "2d", else a date-// - formatRelativeTime verbose: "just now", "4m ago", "3h ago", "2d ago"+// Plan 79 §C: the implementations moved to `utils/intl.js`, which is the one+// locale-aware formatting door. These names stay because ten files import+// them and the two output shapes are deliberate — but they are now thin+// delegations, not a second implementation. Notably the date tail of both+// styles used to be `toLocaleDateString()` with no argument, which follows the+// BROWSER's locale rather than the panel's.//-// Replaces the scattered local copies in Dashboard.jsx, serviceTypes.js,-// logHelpers.js, and the wordpress/* components.+// - timeAgo(iso) compact: "just now", "4m", "3h", "2d", else a date+// - formatRelativeTime verbose, now fully localized by Intl:+// "4 minutes ago", "hace 4 minutos"+// - formatDuration(secs) "45s", "3m 20s"++import { formatRelative, formatRelativeShort, formatDuration as formatDurationIntl } from './intl.js';-// Compact relative time, e.g. "just now", "4m", "3h", "2d", else a date.export function timeAgo(iso) {- if (!iso) return '';- const then = new Date(iso).getTime();- if (Number.isNaN(then)) return '';- const seconds = Math.floor((Date.now() - then) / 1000);- if (seconds < 45) return 'just now';- const minutes = Math.floor(seconds / 60);- if (minutes < 60) return `${minutes}m`;- const hours = Math.floor(minutes / 60);- if (hours < 24) return `${hours}h`;- const days = Math.floor(hours / 24);- if (days < 7) return `${days}d`;- return new Date(then).toLocaleDateString();+ return formatRelativeShort(iso);}-// Verbose relative time, e.g. "just now", "4m ago", "3h ago", "2d ago",-// else a localized date once past ~30 days.export function formatRelativeTime(iso) {- if (!iso) return '';- const date = new Date(iso);- const then = date.getTime();- if (Number.isNaN(then)) return '';- const diffSec = Math.floor((Date.now() - then) / 1000);- const diffMin = Math.floor(diffSec / 60);- const diffHour = Math.floor(diffMin / 60);- const diffDay = Math.floor(diffHour / 24);-- if (diffSec < 60) return 'just now';- if (diffMin < 60) return `${diffMin}m ago`;- if (diffHour < 24) return `${diffHour}h ago`;- if (diffDay < 30) return `${diffDay}d ago`;- return date.toLocaleDateString();+ return formatRelative(iso);}-// Humanize a duration in seconds, e.g. "45s", "3m 20s".export function formatDuration(seconds) {- if (!seconds || seconds < 0) return '-';- if (seconds < 60) return `${Math.round(seconds)}s`;- const min = Math.floor(seconds / 60);- const sec = Math.round(seconds % 60);- return `${min}m ${sec}s`;+ return formatDurationIntl(seconds);}export default timeAgo;diff --git a/frontend/src/utils/timeAgo.js b/frontend/src/utils/timeAgo.jsdeleted file mode 100644index ab30442b..00000000--- a/frontend/src/utils/timeAgo.js+++ /dev/null@@ -1,4 +0,0 @@-// Back-compat shim: the canonical implementation now lives in ./time.js.-// Existing imports of `utils/timeAgo` keep working; new code should import-// { timeAgo, formatRelativeTime } from 'utils/time'.-export { timeAgo, timeAgo as default } from './time';