Merge dev into feat/native-apps

Brings the native apps branch up to dev (NestJS-only server, MikroORM
repositories, tracked sessions, per-domain locales, the lint ratchets) and
ports its new code onto that architecture:

- server: /api/auth/native moves onto injected services. The session is
  minted by the auth domain's new LoginSessionService (login bookkeeping and
  SessionsService.issue in one transaction), the one-time codes live behind a
  NativeHandoffStore port with a capped in-memory implementation that drops
  expired codes on write instead of running a timer, both routes declare
  response contracts, and the exchange answers { success: true }. Unit and
  e2e suites run on createTestModule and the ORM factories.
- shared: native strings for az, et, sk and th, native wired into every
  locale, the address placeholder as a full URL.
- client: the account and export changes go into dev's shared hooks
  (useAccountSettings, useTripExport), the native server card is a
  desktop/phone pair on useNativeServer, the hand-off call moves out of the
  page hook into native/, best-effort native failures go through
  reportError instead of the console, and the address screen is known to
  knip and lint:i18n-keys.
- package-lock.json regenerated on Linux.
This commit is contained in:
Maurice
2026-10-25 17:04:15 +01:00
11842 changed files with 1361077 additions and 180501 deletions
@@ -25,10 +25,11 @@ describe('fileDownload inside the native app', () => {
})
it('logs a share that failed rather than losing it', async () => {
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
const report = vi.fn()
vi.stubGlobal('reportError', report)
vi.mocked(shareFile).mockRejectedValue(new Error('no space'))
downloadBlob(pdf, 'report.pdf')
await vi.waitFor(() => expect(error).toHaveBeenCalledWith('[download]', expect.any(Error)))
await vi.waitFor(() => expect(report).toHaveBeenCalledWith(expect.any(Error)))
})
it('shares a protected file under its given name, or the one from its URL', async () => {
+1 -79
View File
@@ -1,10 +1,5 @@
import { describe, it, expect } from 'vitest';
import { formatDate, formatTime, formatClockTime, dayTotalCost, currencyDecimals, parseMeridiemTime } from '../../../src/utils/formatters';
import type { AssignmentsMap } from '../../../src/types';
// dayTotalCost intentionally exercises edge-case price inputs (string / non-numeric),
// which are looser than the canonical AssignmentsMap shape — hence the casts below.
const asMap = (m: unknown): AssignmentsMap => m as AssignmentsMap;
import { formatDate, formatTime, formatClockTime, currencyDecimals, parseMeridiemTime } from '../../../src/utils/formatters';
describe('currencyDecimals', () => {
it('returns 0 for zero-decimal currencies', () => {
@@ -123,76 +118,3 @@ describe('formatClockTime', () => {
expect(formatClockTime('later', true)).toBe('later');
});
});
describe('dayTotalCost', () => {
// Intl money strings use non-breaking / narrow no-break spaces; normalize for assertions.
const norm = (s: string | null) => s?.replace(/[\u00A0\u202F]/g, ' ') ?? null;
it('returns null when there are no assignments', () => {
expect(dayTotalCost(1, {}, 'EUR', 'EUR', 'en')).toBeNull();
});
it('returns null when no places have prices', () => {
const assignments = {
'1': [
{ id: 1, day_id: 1, order_index: 0, notes: null, place: { id: 1, trip_id: 1, name: 'P', lat: null, lng: null, description: null, address: null, category_id: null, icon: null, price: null, image_url: null, google_place_id: null, osm_id: null, route_geometry: null, place_time: null, end_time: null, created_at: '' } },
],
};
expect(dayTotalCost(1, asMap(assignments), 'EUR', 'EUR', 'en')).toBeNull();
});
it('sums prices across assignments', () => {
const assignments = {
'1': [
{ id: 1, day_id: 1, order_index: 0, notes: null, place: { id: 1, trip_id: 1, name: 'A', lat: null, lng: null, description: null, address: null, category_id: null, icon: null, price: '20', image_url: null, google_place_id: null, osm_id: null, route_geometry: null, place_time: null, end_time: null, created_at: '' } },
{ id: 2, day_id: 1, order_index: 1, notes: null, place: { id: 2, trip_id: 1, name: 'B', lat: null, lng: null, description: null, address: null, category_id: null, icon: null, price: '30', image_url: null, google_place_id: null, osm_id: null, route_geometry: null, place_time: null, end_time: null, created_at: '' } },
],
};
expect(norm(dayTotalCost(1, asMap(assignments), 'EUR', 'EUR', 'en'))).toBe('50 €');
});
it('ignores non-numeric price strings', () => {
const assignments = {
'1': [
{ id: 1, day_id: 1, order_index: 0, notes: null, place: { id: 1, trip_id: 1, name: 'A', lat: null, lng: null, description: null, address: null, category_id: null, icon: null, price: 'free', image_url: null, google_place_id: null, osm_id: null, route_geometry: null, place_time: null, end_time: null, created_at: '' } },
],
};
expect(dayTotalCost(1, asMap(assignments), 'EUR', 'EUR', 'en')).toBeNull();
});
it('uses the dayId key to look up assignments', () => {
const assignments = {
'2': [
{ id: 3, day_id: 2, order_index: 0, notes: null, place: { id: 3, trip_id: 1, name: 'C', lat: null, lng: null, description: null, address: null, category_id: null, icon: null, price: '10', image_url: null, google_place_id: null, osm_id: null, route_geometry: null, place_time: null, end_time: null, created_at: '' } },
],
};
expect(dayTotalCost(1, asMap(assignments), 'USD', 'USD', 'en')).toBeNull();
expect(dayTotalCost(2, asMap(assignments), 'USD', 'USD', 'en')).toBe('$10');
});
it('resolves a currency-less place to the trip currency, converting into the base (#1561)', () => {
const assignments = {
'1': [
{ id: 1, day_id: 1, order_index: 0, notes: null, place: { id: 1, trip_id: 1, name: 'A', lat: null, lng: null, description: null, address: null, category_id: null, icon: null, price: '100', currency: null, image_url: null, google_place_id: null, osm_id: null, route_geometry: null, place_time: null, end_time: null, created_at: '' } },
],
};
// base USD, trip NOK: the implicit-NOK price must convert (rates[NOK]=10 per USD)…
expect(dayTotalCost(1, asMap(assignments), 'USD', 'NOK', 'en', { NOK: 10 })).toBe('≈ $10');
// …and without rates it must show as NOK, never as a raw number labeled USD.
expect(norm(dayTotalCost(1, asMap(assignments), 'USD', 'NOK', 'en'))).toMatch(/100\s?kr|kr\s?100/);
});
it('mislabels nothing when a foreign-currency price has no rate (#1561)', () => {
const assignments = {
'1': [
{ id: 1, day_id: 1, order_index: 0, notes: null, place: { id: 1, trip_id: 1, name: 'Hotel', lat: null, lng: null, description: null, address: null, category_id: null, icon: null, price: 2730.27, currency: 'USD', image_url: null, google_place_id: null, osm_id: null, route_geometry: null, place_time: null, end_time: null, created_at: '' } },
{ id: 2, day_id: 1, order_index: 1, notes: null, place: { id: 2, trip_id: 1, name: 'Museum', lat: null, lng: null, description: null, address: null, category_id: null, icon: null, price: 2500, currency: 'NOK', image_url: null, google_place_id: null, osm_id: null, route_geometry: null, place_time: null, end_time: null, created_at: '' } },
],
};
const out = norm(dayTotalCost(1, asMap(assignments), 'NOK', 'NOK', 'en'));
expect(out).toContain(' + ');
expect(out).toMatch(/2 500\s?kr|kr\s?2 500/);
expect(out).toContain('$2,730');
expect(out).not.toContain('≈');
});
});
+17 -1
View File
@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'
import { filesForPlace } from '../../../src/utils/placeFiles'
import type { Reservation, TripFile } from '../../../src/types'
// FE-UTIL-PLACEFILES-001 to FE-UTIL-PLACEFILES-006
// FE-UTIL-PLACEFILES-001 to FE-UTIL-PLACEFILES-008
const file = (over: Partial<TripFile>): TripFile => ({
id: 1, trip_id: 5, original_name: 'a.pdf', url: '/uploads/a.pdf',
@@ -54,4 +54,20 @@ describe('filesForPlace', () => {
expect(filesForPlace([gone, bookingFileGone], 7, [booking({ id: 90, place_id: 7 })])).toEqual([])
expect(filesForPlace([file({ id: 10, place_id: 7 })], undefined, [])).toEqual([])
})
it('FE-UTIL-PLACEFILES-007: reaches a hotel booking through the stay on the place', () => {
// A hotel booking keeps place_id empty; the place is the stay's (#2363).
const stay = booking({ id: 90, place_id: null, assignment_id: null, accommodation_place_id: 7 })
const stored = file({ id: 11, reservation_id: 90 })
const linked = file({ id: 12, linked_reservation_ids: [90] })
expect(filesForPlace([stored, linked], 7, [stay]).map(f => f.id)).toEqual([11, 12])
// A stay on another place lends nothing to this one.
expect(filesForPlace([stored], 7, [{ ...stay, accommodation_place_id: 8 }])).toEqual([])
})
it('FE-UTIL-PLACEFILES-008: keeps a file pinned to one of the place\'s stops', () => {
const pinned = file({ id: 13, linked_assignment_ids: [11] })
expect(filesForPlace([pinned], 7, [], [11]).map(f => f.id)).toEqual([13])
expect(filesForPlace([pinned], 7, [], [12])).toEqual([])
})
})
+236
View File
@@ -0,0 +1,236 @@
/**
* public/shell-guard.js (#2524): the classic boot script that recovers a shell
* whose entry module cannot load. It is not a module, so it is run here from its
* source, the way the browser runs it from index.html.
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
const SOURCE = readFileSync(resolve(process.cwd(), 'public/shell-guard.js'), 'utf8');
const ENTRY = '/assets/index-BZcJ9-lk.js';
const MARKER = 'trek:shell-reload';
type Listener = [string, EventListenerOrEventListenerObject, boolean | AddEventListenerOptions | undefined];
let listeners: Listener[] = [];
let scripts: HTMLElement[] = [];
/** Runs the guard and keeps its listeners, so every test starts with exactly one set. */
function runGuard(): void {
const add = vi.spyOn(document, 'addEventListener');
new Function(SOURCE)();
listeners = add.mock.calls.map(call => call as unknown as Listener);
add.mockRestore();
}
function moduleScript(src: string, type = 'module'): HTMLScriptElement {
const el = document.createElement('script');
el.type = type;
el.src = src;
document.head.appendChild(el);
scripts.push(el);
return el;
}
function fail(el: Element): void {
el.dispatchEvent(new Event('error'));
}
/** Lets the guard's promise chain run to its end. */
async function settle(): Promise<void> {
for (let i = 0; i < 10; i++) await new Promise(r => setTimeout(r, 0));
}
function healthAnswer(ok: boolean, type: string) {
return { ok, headers: { get: (name: string) => (name.toLowerCase() === 'content-type' ? type : null) } };
}
interface Env {
replace: ReturnType<typeof vi.fn>;
fetch: ReturnType<typeof vi.fn>;
unregister: ReturnType<typeof vi.fn>;
deleted: string[];
}
/** A page a service worker served, unless `controlled` is false. */
function install(href = 'http://localhost/trips/4?tab=plan#day-2', controlled = true): Env {
const replace = vi.fn();
Object.defineProperty(window, 'location', { value: { ...window.location, href, replace }, writable: true, configurable: true });
const fetch = vi.fn(async () => healthAnswer(true, 'application/json; charset=utf-8'));
vi.stubGlobal('fetch', fetch);
const unregister = vi.fn(async () => true);
Object.defineProperty(navigator, 'serviceWorker', {
value: { controller: controlled ? { scriptURL: 'http://localhost/sw.js' } : null, getRegistration: vi.fn(async () => ({ unregister })) },
configurable: true,
});
const deleted: string[] = [];
Object.defineProperty(globalThis, 'caches', {
value: {
keys: vi.fn(async () => ['workbox-precache-v2-http://localhost/', 'map-tiles', 'gl-map-offline', 'user-uploads']),
delete: vi.fn(async (name: string) => { deleted.push(name); return true; }),
},
configurable: true,
});
return { replace, fetch, unregister, deleted };
}
const originalLocation = Object.getOwnPropertyDescriptor(window, 'location');
beforeEach(() => {
sessionStorage.clear();
});
afterEach(() => {
for (const [type, fn, options] of listeners) document.removeEventListener(type, fn, options);
listeners = [];
for (const el of scripts) el.remove();
scripts = [];
vi.unstubAllGlobals();
vi.restoreAllMocks();
Reflect.deleteProperty(navigator, 'serviceWorker');
Reflect.deleteProperty(globalThis, 'caches');
if (originalLocation) Object.defineProperty(window, 'location', originalLocation);
});
describe('shell-guard.js', () => {
it('FE-SHELLGUARD-001: strips the fresh-reload parameter and keeps the rest of the URL', () => {
window.history.replaceState({ usr: 1 }, '', '/trips/4?tab=plan&trek-reload=mfz3x1&x=2#day-2');
runGuard();
expect(window.location.pathname + window.location.search + window.location.hash).toBe('/trips/4?tab=plan&x=2#day-2');
expect(window.history.state).toEqual({ usr: 1 });
window.history.replaceState(null, '', '/');
});
it('FE-SHELLGUARD-002: leaves a URL without the parameter alone', () => {
window.history.replaceState(null, '', '/dashboard?tab=trips');
const replaceState = vi.spyOn(window.history, 'replaceState');
runGuard();
expect(replaceState).not.toHaveBeenCalled();
window.history.replaceState(null, '', '/');
});
it('FE-SHELLGUARD-003: an entry that cannot load drops the app shell and loads the page afresh', async () => {
const env = install();
vi.spyOn(Date, 'now').mockReturnValue(1790358416100);
runGuard();
fail(moduleScript(ENTRY));
await vi.waitFor(() => expect(env.replace).toHaveBeenCalledTimes(1));
expect(env.fetch).toHaveBeenCalledWith('/api/health', expect.objectContaining({ cache: 'no-store', redirect: 'manual' }));
// Only the precache: offline map regions and cached uploads were downloaded on purpose.
expect(env.deleted).toEqual(['workbox-precache-v2-http://localhost/']);
expect(env.unregister).toHaveBeenCalledTimes(1);
const target = new URL(env.replace.mock.calls[0][0] as string);
expect(target.pathname + target.hash).toBe('/trips/4#day-2');
expect(target.searchParams.get('tab')).toBe('plan');
expect(target.searchParams.get('trek-reload')).toBe((1790358416100).toString(36));
});
it.each([
['offline', () => Promise.reject(new TypeError('Failed to fetch'))],
['a proxy login page', async () => healthAnswer(true, 'text/html')],
['a server error', async () => healthAnswer(false, 'application/json')],
])('FE-SHELLGUARD-004: keeps the shell when the server does not answer (%s)', async (_case, answer) => {
const env = install();
env.fetch.mockImplementation(answer);
runGuard();
fail(moduleScript(ENTRY));
await settle();
// Offline, the precache is the only way the app starts at all.
expect(env.fetch).toHaveBeenCalledTimes(1);
expect(env.deleted).toEqual([]);
expect(env.unregister).not.toHaveBeenCalled();
expect(env.replace).not.toHaveBeenCalled();
// Nothing was tried, so a later load may still recover.
expect(sessionStorage.getItem(MARKER)).toBeNull();
});
it('FE-SHELLGUARD-005: recovers once per session, so a broken build cannot loop', async () => {
const env = install();
runGuard();
fail(moduleScript(ENTRY));
await vi.waitFor(() => expect(env.replace).toHaveBeenCalledTimes(1));
// The reloaded page fails the same way: the marker is still set.
fail(moduleScript(ENTRY));
await settle();
expect(env.fetch).toHaveBeenCalledTimes(1);
expect(env.replace).toHaveBeenCalledTimes(1);
});
it('FE-SHELLGUARD-006: an entry that loaded clears the marker, so a later update may recover too', async () => {
const env = install();
sessionStorage.setItem(MARKER, '1790358416100');
runGuard();
moduleScript(ENTRY).dispatchEvent(new Event('load'));
expect(sessionStorage.getItem(MARKER)).toBeNull();
fail(moduleScript(ENTRY));
await vi.waitFor(() => expect(env.replace).toHaveBeenCalledTimes(1));
});
it('FE-SHELLGUARD-007: does nothing without session storage, where it could not stop a loop', async () => {
const env = install();
vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
throw new Error('storage blocked');
});
runGuard();
fail(moduleScript(ENTRY));
await settle();
expect(env.fetch).not.toHaveBeenCalled();
expect(env.replace).not.toHaveBeenCalled();
});
it('FE-SHELLGUARD-008: still reloads when dropping the shell fails', async () => {
const env = install();
env.unregister.mockRejectedValue(new Error('InvalidStateError'));
runGuard();
fail(moduleScript(ENTRY));
await vi.waitFor(() => expect(env.replace).toHaveBeenCalledTimes(1));
});
it('FE-SHELLGUARD-011: a page that came from the network is reloaded afresh and its worker kept', async () => {
// Nothing the worker keeps answered this load, so throwing it away would only
// cost the offline shell.
const env = install('http://localhost/dashboard', false);
runGuard();
fail(moduleScript(ENTRY));
await vi.waitFor(() => expect(env.replace).toHaveBeenCalledTimes(1));
expect(env.deleted).toEqual([]);
expect(env.unregister).not.toHaveBeenCalled();
expect(new URL(env.replace.mock.calls[0][0] as string).searchParams.has('trek-reload')).toBe(true);
});
it('FE-SHELLGUARD-009: works where there is no service worker and no Cache Storage', async () => {
const env = install();
Reflect.deleteProperty(navigator, 'serviceWorker');
Reflect.deleteProperty(globalThis, 'caches');
runGuard();
fail(moduleScript(ENTRY));
// A proxy that kept a stale index.html is bypassed by the fresh URL alone.
await vi.waitFor(() => expect(env.replace).toHaveBeenCalledTimes(1));
});
it('FE-SHELLGUARD-010: ignores every other failure', async () => {
const env = install();
runGuard();
// Vite's dev entry, a classic script, a lazy chunk's stylesheet, an image.
fail(moduleScript('/src/main.tsx'));
fail(moduleScript('/registerSW.js', 'text/javascript'));
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = '/assets/DashboardPage-v4ODOTOr.css';
document.head.appendChild(link);
scripts.push(link);
fail(link);
const img = document.createElement('img');
img.src = '/uploads/covers/missing.jpg';
document.body.appendChild(img);
scripts.push(img);
fail(img);
// A runtime error of the app is an ErrorEvent on window, not a failed script.
window.dispatchEvent(new Event('error'));
await settle();
expect(env.fetch).not.toHaveBeenCalled();
expect(env.replace).not.toHaveBeenCalled();
});
});