feat(waiter): configurable server/venue layer for native app and plain-HTTP browser mode
New waiter_pwa/src/config/server.js is the single place that knows where the backend is. Served by the venue's server (https domain or http://<LAN IP>) nothing changes: same-origin URLs and the original storage keys, so existing installs keep their token and unsynced offline queue. With an active venue (native app, or dev builds with VITE_SERVER_URL) URLs become absolute and all venue data is namespaced by siteId: token/savedUsername keys, the Dexie DB (pos_snapshot__<siteId>, which also covers the WS cursor), favorites and table-view prefs. Switching venue reloads the app. - api client baseURL, WebSocket and SSE URLs routed through the layer - product images / waiter avatars rendered via assetUrl() - service-worker update prompt skipped in native builds - InstallAppBanner: shown only in plain-HTTP browser mode and only when VITE_APP_DOWNLOAD_URL is set at build time (dismiss for 7 days) - VITE_SERVER_URL override is DEV-only (a URL-controlled server in prod would let a crafted link capture PINs) - pack README: rule CS-8 on never assuming same-origin Verified with Playwright/Edge against a local backend: prod build same-origin, prod build via LAN IP over plain HTTP (insecure context, no SW, banner shown), and dev build pointed at the backend by URL - all three log in, reach /tables and receive the WebSocket 'ready' frame; storage keys and IndexedDB names are as expected. Lint: no new problems (103 before/after). Build passes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* Server / venue configuration — the single place that knows WHERE the backend is.
|
||||
*
|
||||
* Two ways the waiter app runs:
|
||||
*
|
||||
* 1. Served by the venue's own server (https domain, or plain http://<LAN IP>).
|
||||
* No venue is configured → every URL is same-origin and storage uses the
|
||||
* original un-prefixed keys. Behaviour is identical to before venues existed,
|
||||
* so existing installs keep their token and offline queue across the update.
|
||||
*
|
||||
* 2. Bundled in the native app (Capacitor), or a dev build with VITE_SERVER_URL.
|
||||
* An active venue { siteId, name, baseUrl } → absolute URLs to that server,
|
||||
* and all persistent storage (token, IndexedDB, per-venue prefs) is namespaced
|
||||
* by siteId so several venues can live side by side on one phone.
|
||||
*
|
||||
* The active venue is resolved ONCE at module load. Switching venue reloads the
|
||||
* app so every module-level singleton (Dexie db, auth store, persisted stores)
|
||||
* re-initialises against the new namespace — no half-switched state.
|
||||
*/
|
||||
|
||||
const VENUES_KEY = 'xenia.venues'
|
||||
|
||||
function normalizeBaseUrl(url) {
|
||||
const trimmed = String(url || '').trim().replace(/\/+$/, '')
|
||||
if (!/^https?:\/\/[^/]+/i.test(trimmed)) {
|
||||
throw new Error(`Invalid server URL: "${url}" (expected http(s)://host[:port])`)
|
||||
}
|
||||
return trimmed
|
||||
}
|
||||
|
||||
function readState() {
|
||||
try {
|
||||
const parsed = JSON.parse(localStorage.getItem(VENUES_KEY) || 'null')
|
||||
if (parsed && typeof parsed === 'object') {
|
||||
return { active: parsed.active ?? null, venues: parsed.venues ?? {} }
|
||||
}
|
||||
} catch {
|
||||
// corrupted or unavailable storage — fall through to empty state
|
||||
}
|
||||
return { active: null, venues: {} }
|
||||
}
|
||||
|
||||
function writeState(state) {
|
||||
localStorage.setItem(VENUES_KEY, JSON.stringify(state))
|
||||
}
|
||||
|
||||
function resolveActiveVenue() {
|
||||
// Dev convenience: point a `npm run dev` build at a real server on the LAN.
|
||||
// Deliberately DEV-only — a URL/query-controlled server in production would let
|
||||
// a crafted link send waiters' PINs to someone else's machine.
|
||||
const devUrl = import.meta.env.DEV ? import.meta.env.VITE_SERVER_URL : ''
|
||||
if (devUrl) {
|
||||
return { siteId: 'dev', name: 'Dev server', baseUrl: normalizeBaseUrl(devUrl) }
|
||||
}
|
||||
const { active, venues } = readState()
|
||||
return (active && venues[active]) || null
|
||||
}
|
||||
|
||||
const ACTIVE_VENUE = resolveActiveVenue()
|
||||
|
||||
// ── Reading ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/** The venue this app instance is talking to, or null when running same-origin. */
|
||||
export function getActiveVenue() {
|
||||
return ACTIVE_VENUE
|
||||
}
|
||||
|
||||
/** All paired venues (used by the venue switcher). */
|
||||
export function listVenues() {
|
||||
return Object.values(readState().venues)
|
||||
}
|
||||
|
||||
/** Base URL for REST calls: '' (same-origin) or 'http(s)://host[:port]'. */
|
||||
export function apiBase() {
|
||||
return ACTIVE_VENUE?.baseUrl ?? ''
|
||||
}
|
||||
|
||||
/** Absolute ws(s):// URL for a backend path such as '/api/ws/connect?token=…'. */
|
||||
export function wsUrl(path) {
|
||||
if (ACTIVE_VENUE) {
|
||||
return ACTIVE_VENUE.baseUrl.replace(/^http/i, 'ws') + path
|
||||
}
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
|
||||
return `${protocol}//${window.location.host}${path}`
|
||||
}
|
||||
|
||||
/**
|
||||
* URL for a backend-served asset (product images, avatars). The backend returns
|
||||
* root-relative paths like '/static/product_images/x.jpg'; in native mode those
|
||||
* must point at the venue server, not at the app bundle.
|
||||
*/
|
||||
export function assetUrl(url) {
|
||||
if (!url || !ACTIVE_VENUE) return url
|
||||
if (/^(https?:|data:|blob:)/i.test(url)) return url
|
||||
return url.startsWith('/') ? ACTIVE_VENUE.baseUrl + url : url
|
||||
}
|
||||
|
||||
/**
|
||||
* localStorage key for per-venue data. Same-origin mode keeps the original
|
||||
* un-prefixed key so existing installs don't lose their session.
|
||||
*/
|
||||
export function storageKey(name) {
|
||||
return ACTIVE_VENUE ? `xenia:${ACTIVE_VENUE.siteId}:${name}` : name
|
||||
}
|
||||
|
||||
/** IndexedDB (Dexie) database name — the original name in same-origin mode. */
|
||||
export function dbName() {
|
||||
return ACTIVE_VENUE ? `pos_snapshot__${ACTIVE_VENUE.siteId}` : 'pos_snapshot'
|
||||
}
|
||||
|
||||
/**
|
||||
* How the app is being delivered:
|
||||
* 'native' — inside the Capacitor app
|
||||
* 'secure-web' — https (or localhost): service worker, installable PWA
|
||||
* 'plain-web' — plain http://<LAN IP>: no service worker, no real install
|
||||
*/
|
||||
export function deliveryMode() {
|
||||
if (window.Capacitor?.isNativePlatform?.()) return 'native'
|
||||
return window.isSecureContext ? 'secure-web' : 'plain-web'
|
||||
}
|
||||
|
||||
// ── Writing (used by pairing / venue switcher in the native app) ─────────────
|
||||
|
||||
/** Add or update a paired venue without switching to it. */
|
||||
export function saveVenue({ siteId, name, baseUrl }) {
|
||||
if (!siteId) throw new Error('saveVenue: siteId is required')
|
||||
const state = readState()
|
||||
state.venues[siteId] = { siteId, name: name || siteId, baseUrl: normalizeBaseUrl(baseUrl) }
|
||||
writeState(state)
|
||||
return state.venues[siteId]
|
||||
}
|
||||
|
||||
/** Make a paired venue active and reload the app into it. */
|
||||
export function switchVenue(siteId) {
|
||||
const state = readState()
|
||||
if (!state.venues[siteId]) throw new Error(`switchVenue: unknown venue ${siteId}`)
|
||||
state.active = siteId
|
||||
writeState(state)
|
||||
window.location.replace('/')
|
||||
}
|
||||
|
||||
/**
|
||||
* Forget a paired venue. Its namespaced storage and IndexedDB are left in place
|
||||
* on purpose — they may hold unsynced offline orders. Cleanup is an explicit,
|
||||
* separate action (see the native app's venue manager).
|
||||
*/
|
||||
export function removeVenue(siteId) {
|
||||
const state = readState()
|
||||
delete state.venues[siteId]
|
||||
if (state.active === siteId) state.active = null
|
||||
writeState(state)
|
||||
}
|
||||
Reference in New Issue
Block a user