@swimmesberger/elarion-pwa 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,60 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @swimmesberger/elarion-pwa
2
+
3
+ The installable-app shell for Elarion frontends — what turns "Add to Home Screen" into an app that opens offline,
4
+ loads its assets from the cache, and moves to a new deploy without throwing away what the user was typing. Guide:
5
+ [Installable apps (PWA)](https://elarion.wimmesberger.dev/docs/capabilities/pwa).
6
+
7
+ - **Install** — `createInstallPrompt()` captures Chromium's `beforeinstallprompt` and reports `availability()`:
8
+ `'prompt' | 'ios' | 'none'` (`ios` = show the "Share → Add to Home Screen" instructions). `isStandalone()`,
9
+ `isAppleTouchDevice()` and the pure `installOption()` are exported too.
10
+ - **Updates** — `createUpdateWatcher({ currentVersion })` asks the server which web build is live when the app returns
11
+ to the foreground and reloads into a new one **on the next navigation that changed the path**, never on the
12
+ foreground return itself, never while a dialog is open or a field is focused, at most once a minute.
13
+ - **Registration** — `registerServiceWorker('/sw.js')` with `updateViaCache: 'none'`; resolves `null` instead of
14
+ throwing where there is no service worker.
15
+ - **`/sw`** — `registerShellRouter(self, …)`: network-only or network-first navigations, cache-first hashed assets,
16
+ stale-while-revalidate icons and manifest; never touches the API (`ELARION_SERVER_PREFIXES`), non-GET, cross-origin
17
+ or `no-store` requests, and never stores a redirected, opaque, partial, `no-store`, or (outside the shell) HTML answer.
18
+ Composes with `registerWebPushHandlers(self)` from `@swimmesberger/elarion-webpush/sw` in the same worker.
19
+ - **`/vite`** — `appVersionFile({ version, define })` emits `/app-version.json` and bakes the same version into the
20
+ bundle.
21
+
22
+ ## Page
23
+
24
+ ```ts
25
+ import { createInstallPrompt, createUpdateWatcher, registerServiceWorker } from '@swimmesberger/elarion-pwa'
26
+
27
+ if (import.meta.env.PROD) void registerServiceWorker('/sw.js')
28
+
29
+ export const install = createInstallPrompt() // at module load: the prompt event fires early
30
+
31
+ export const updates = createUpdateWatcher({ currentVersion: __APP_VERSION__, enabled: import.meta.env.PROD })
32
+ router.subscribe('onResolved', (event) => updates.navigationResolved({ pathChanged: event.pathChanged }))
33
+ ```
34
+
35
+ ## Service worker
36
+
37
+ ```ts
38
+ import { ELARION_SERVER_PREFIXES, registerShellRouter } from '@swimmesberger/elarion-pwa/sw'
39
+ import { registerWebPushHandlers } from '@swimmesberger/elarion-webpush/sw'
40
+
41
+ registerShellRouter(self, {
42
+ cacheName: 'myapp-v1',
43
+ serverPrefixes: [...ELARION_SERVER_PREFIXES, '/auth'],
44
+ navigation: { mode: 'network-only', offlineUrl: '/offline.html' }, // or { mode: 'network-first' } for an SPA shell
45
+ staticFiles: ['/manifest.webmanifest', '/icon-192.png', '/icon-512.png', '/apple-touch-icon.png'],
46
+ })
47
+ registerWebPushHandlers(self, { icon: '/icon-192.png' })
48
+ ```
49
+
50
+ The module is ESM: bundle the worker into one classic script served at `/sw.js` (for example a second
51
+ `vite build` with `build.lib.formats: ['iife']`), or register it with `{ type: 'module' }`.
52
+
53
+ ## Vite
54
+
55
+ ```ts
56
+ import { appVersionFile } from '@swimmesberger/elarion-pwa/vite'
57
+
58
+ const version = process.env.APP_VERSION?.trim() || 'dev'
59
+ export default defineConfig({ plugins: [appVersionFile({ version, define: '__APP_VERSION__' })] })
60
+ ```
@@ -0,0 +1,3 @@
1
+ export { createInstallPrompt, installOption, isAppleTouchDevice, isStandalone, readInstallEnvironment, type InstallEnvironment, type InstallOption, type InstallPromptController, type InstallPromptOptions, type InstallPromptOutcome, } from './install.js';
2
+ export { registerServiceWorker, type RegisterServiceWorkerOptions, type ServiceWorkerContainerLike } from './register.js';
3
+ export { BUSY_SELECTOR, createUpdateWatcher, currentEntryScript, DEFAULT_CHECK_INTERVAL_MS, DEFAULT_RELOAD_GUARD_MS, DEFAULT_RELOAD_STORAGE_KEY, DEFAULT_VERSION_URL, entryScriptVersionSource, isDocumentBusy, isTextEntry, jsonVersionSource, parseEntryScript, parseServedVersion, shouldCheckForUpdate, shouldReloadOnNavigation, updateDecision, type BusyDocument, type FocusTarget, type ReloadGuardStorage, type UpdateDecision, type UpdateWatcher, type UpdateWatcherOptions, type VersionSource, type VisibilityDocument, } from './update.js';
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ // The page half of the Elarion installable-app shell (ADR-0083): how the app can be installed (the deferred
2
+ // `beforeinstallprompt` prompt, or the iOS share-sheet instructions), reloading into a new deploy at a safe moment,
3
+ // and registering the service worker. Framework-neutral: subscribe/snapshot pairs plug into React's
4
+ // `useSyncExternalStore`, and the update watcher takes navigation events from any router.
5
+ //
6
+ // The service-worker half (the shell router and its caching strategies) is the `/sw` sub-export; the Vite plugin
7
+ // that publishes the build version is `/vite`.
8
+ export { createInstallPrompt, installOption, isAppleTouchDevice, isStandalone, readInstallEnvironment, } from './install.js';
9
+ export { registerServiceWorker } from './register.js';
10
+ export { BUSY_SELECTOR, createUpdateWatcher, currentEntryScript, DEFAULT_CHECK_INTERVAL_MS, DEFAULT_RELOAD_GUARD_MS, DEFAULT_RELOAD_STORAGE_KEY, DEFAULT_VERSION_URL, entryScriptVersionSource, isDocumentBusy, isTextEntry, jsonVersionSource, parseEntryScript, parseServedVersion, shouldCheckForUpdate, shouldReloadOnNavigation, updateDecision, } from './update.js';
@@ -0,0 +1,77 @@
1
+ /** What the browser says about itself. */
2
+ export interface InstallEnvironment {
3
+ readonly userAgent: string;
4
+ /** `navigator.maxTouchPoints` — the only tell of an iPad, which reports a desktop Mac user agent. */
5
+ readonly maxTouchPoints: number;
6
+ /** Already running as an installed app (`display-mode: standalone`, or iOS's `navigator.standalone`). */
7
+ readonly standalone: boolean;
8
+ }
9
+ /**
10
+ * How this browser can install the app right now:
11
+ * - `prompt` — the browser handed over its install prompt; offer an "Install app" action that calls
12
+ * {@link InstallPromptController.prompt}.
13
+ * - `ios` — iPhone/iPad: no prompt API; show the "Share → Add to Home Screen" instructions.
14
+ * - `none` — already installed, or a browser that cannot install a web app (Firefox desktop, an in-app browser,
15
+ * Chromium before the page qualifies). Hide the entry rather than offering a dead end.
16
+ */
17
+ export type InstallOption = 'prompt' | 'ios' | 'none';
18
+ /** What {@link InstallPromptController.prompt} achieved. */
19
+ export type InstallPromptOutcome = 'accepted' | 'dismissed' | 'unavailable';
20
+ /**
21
+ * iPhone, iPod or iPad. iPadOS 13+ presents a Mac user agent, so a "Mac" with a touch screen counts too — no real
22
+ * Mac has one. Every iOS browser is WebKit and, since iOS 16.4, all of them offer "Add to Home Screen" in their
23
+ * share menu, so this deliberately does not single out Safari.
24
+ */
25
+ export declare function isAppleTouchDevice(userAgent: string, maxTouchPoints: number): boolean;
26
+ /** Whether the page runs as an installed app rather than in a browser tab. `false` outside a browser. */
27
+ export declare function isStandalone(): boolean;
28
+ /** The live {@link InstallEnvironment}, or `null` outside a browser (server rendering, tests without a DOM). */
29
+ export declare function readInstallEnvironment(): InstallEnvironment | null;
30
+ /** How this browser can install the app, given whether a deferred install prompt is in hand. */
31
+ export declare function installOption(env: InstallEnvironment | null, canPrompt: boolean): InstallOption;
32
+ /** Options for {@link createInstallPrompt}. */
33
+ export interface InstallPromptOptions {
34
+ /** Where `beforeinstallprompt` and `appinstalled` are listened for. Defaults to `window`. */
35
+ target?: EventTarget;
36
+ /** Reads the browser state. Defaults to {@link readInstallEnvironment}. */
37
+ environment?: () => InstallEnvironment | null;
38
+ /**
39
+ * Suppress Chromium's own install mini-infobar so the app offers installing where users look for it. Defaults to
40
+ * `true`; pass `false` to keep the browser's UI as well.
41
+ */
42
+ preventDefault?: boolean;
43
+ }
44
+ /** The deferred install prompt and the install option derived from it; see {@link createInstallPrompt}. */
45
+ export interface InstallPromptController {
46
+ /**
47
+ * The current {@link InstallOption}. A string snapshot, so it can back React's `useSyncExternalStore` directly
48
+ * (pass `() => 'none'` as the server snapshot: the environment is unknown while rendering on the server).
49
+ */
50
+ availability(): InstallOption;
51
+ /** Calls `listener` whenever {@link availability} may have changed. Returns the unsubscribe function. */
52
+ subscribe(listener: () => void): () => void;
53
+ /**
54
+ * Shows the browser's install prompt. Call it from a click handler. A prompt can be shown once: whatever the
55
+ * answer, the event is spent and {@link availability} drops to `none` until the browser offers another one.
56
+ */
57
+ prompt(): Promise<InstallPromptOutcome>;
58
+ /** Stops listening. */
59
+ dispose(): void;
60
+ }
61
+ /**
62
+ * Captures the browser's install prompt and tracks how the app can be installed.
63
+ *
64
+ * Create it **once, at module load** of the client bundle (not inside a component effect): Chromium fires
65
+ * `beforeinstallprompt` once, as soon as the page qualifies, which can be before the UI framework has mounted.
66
+ *
67
+ * @example
68
+ * ```ts
69
+ * export const install = createInstallPrompt()
70
+ *
71
+ * // React
72
+ * const option = useSyncExternalStore(install.subscribe, install.availability, () => 'none')
73
+ * if (option === 'prompt') return <button onClick={() => install.prompt()}>Install app</button>
74
+ * if (option === 'ios') return <p>Tap Share, then “Add to Home Screen”.</p>
75
+ * ```
76
+ */
77
+ export declare function createInstallPrompt(options?: InstallPromptOptions): InstallPromptController;
@@ -0,0 +1,106 @@
1
+ // Installing the app: which way this browser offers right now — its own install prompt (`beforeinstallprompt`,
2
+ // Chromium), the share-sheet instructions (iPhone/iPad, which has no prompt API), or nothing (already installed,
3
+ // or a browser that cannot install a web app) — and the deferred prompt itself. The decision is pure so it can be
4
+ // unit-tested; the controller feeds it the live browser state and notifies subscribers when it changes.
5
+ /**
6
+ * iPhone, iPod or iPad. iPadOS 13+ presents a Mac user agent, so a "Mac" with a touch screen counts too — no real
7
+ * Mac has one. Every iOS browser is WebKit and, since iOS 16.4, all of them offer "Add to Home Screen" in their
8
+ * share menu, so this deliberately does not single out Safari.
9
+ */
10
+ export function isAppleTouchDevice(userAgent, maxTouchPoints) {
11
+ if (/\b(iPhone|iPad|iPod)\b/.test(userAgent))
12
+ return true;
13
+ return /\bMacintosh\b/.test(userAgent) && maxTouchPoints > 1;
14
+ }
15
+ /** Whether the page runs as an installed app rather than in a browser tab. `false` outside a browser. */
16
+ export function isStandalone() {
17
+ if (typeof window === 'undefined' || typeof navigator === 'undefined')
18
+ return false;
19
+ if (navigator.standalone === true)
20
+ return true;
21
+ return typeof window.matchMedia === 'function' && window.matchMedia('(display-mode: standalone)').matches;
22
+ }
23
+ /** The live {@link InstallEnvironment}, or `null` outside a browser (server rendering, tests without a DOM). */
24
+ export function readInstallEnvironment() {
25
+ if (typeof window === 'undefined' || typeof navigator === 'undefined')
26
+ return null;
27
+ return { userAgent: navigator.userAgent, maxTouchPoints: navigator.maxTouchPoints ?? 0, standalone: isStandalone() };
28
+ }
29
+ /** How this browser can install the app, given whether a deferred install prompt is in hand. */
30
+ export function installOption(env, canPrompt) {
31
+ if (env === null || env.standalone)
32
+ return 'none';
33
+ if (canPrompt)
34
+ return 'prompt';
35
+ if (isAppleTouchDevice(env.userAgent, env.maxTouchPoints))
36
+ return 'ios';
37
+ return 'none';
38
+ }
39
+ /**
40
+ * Captures the browser's install prompt and tracks how the app can be installed.
41
+ *
42
+ * Create it **once, at module load** of the client bundle (not inside a component effect): Chromium fires
43
+ * `beforeinstallprompt` once, as soon as the page qualifies, which can be before the UI framework has mounted.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * export const install = createInstallPrompt()
48
+ *
49
+ * // React
50
+ * const option = useSyncExternalStore(install.subscribe, install.availability, () => 'none')
51
+ * if (option === 'prompt') return <button onClick={() => install.prompt()}>Install app</button>
52
+ * if (option === 'ios') return <p>Tap Share, then “Add to Home Screen”.</p>
53
+ * ```
54
+ */
55
+ export function createInstallPrompt(options = {}) {
56
+ const target = options.target ?? (typeof window === 'undefined' ? undefined : window);
57
+ const environment = options.environment ?? readInstallEnvironment;
58
+ const listeners = new Set();
59
+ let deferred = null;
60
+ const notify = () => {
61
+ for (const listener of [...listeners])
62
+ listener();
63
+ };
64
+ const onBeforeInstallPrompt = (event) => {
65
+ if (options.preventDefault !== false)
66
+ event.preventDefault();
67
+ deferred = event;
68
+ notify();
69
+ };
70
+ const onAppInstalled = () => {
71
+ deferred = null;
72
+ notify();
73
+ };
74
+ target?.addEventListener('beforeinstallprompt', onBeforeInstallPrompt);
75
+ target?.addEventListener('appinstalled', onAppInstalled);
76
+ return {
77
+ availability: () => installOption(target ? environment() : null, deferred !== null),
78
+ subscribe(listener) {
79
+ listeners.add(listener);
80
+ return () => {
81
+ listeners.delete(listener);
82
+ };
83
+ },
84
+ async prompt() {
85
+ const event = deferred;
86
+ if (!event)
87
+ return 'unavailable';
88
+ deferred = null;
89
+ notify();
90
+ try {
91
+ await event.prompt();
92
+ }
93
+ catch {
94
+ // Chromium refuses a prompt outside a user gesture or a second time; the event is spent either way.
95
+ return 'unavailable';
96
+ }
97
+ const choice = await event.userChoice.catch(() => null);
98
+ return choice?.outcome ?? 'dismissed';
99
+ },
100
+ dispose() {
101
+ target?.removeEventListener('beforeinstallprompt', onBeforeInstallPrompt);
102
+ target?.removeEventListener('appinstalled', onAppInstalled);
103
+ listeners.clear();
104
+ },
105
+ };
106
+ }
@@ -0,0 +1,30 @@
1
+ /** The part of `navigator.serviceWorker` {@link registerServiceWorker} uses. */
2
+ export interface ServiceWorkerContainerLike {
3
+ register(scriptURL: string | URL, options?: RegistrationOptions): Promise<ServiceWorkerRegistration>;
4
+ }
5
+ /** Options for {@link registerServiceWorker}. */
6
+ export interface RegisterServiceWorkerOptions {
7
+ /** The registration scope. Defaults to the script's directory — `/` for `/sw.js`. */
8
+ scope?: string;
9
+ /** `module` for an unbundled ESM worker. Defaults to `classic`, which every browser supports. */
10
+ type?: WorkerType;
11
+ /** Defaults to `'none'`: the worker script and its imports are always fetched past the HTTP cache. */
12
+ updateViaCache?: ServiceWorkerUpdateViaCache;
13
+ /** Called when registration fails; the app keeps working without an installable shell. */
14
+ onError?: (error: unknown) => void;
15
+ /** The container to register with. Defaults to `navigator.serviceWorker`. */
16
+ container?: ServiceWorkerContainerLike;
17
+ }
18
+ /**
19
+ * Registers the service worker and resolves to its registration — or `null` where service workers are unavailable
20
+ * (an old browser, a non-secure context, a private mode that disables them) or registration failed.
21
+ *
22
+ * Gate it on a production build yourself: under a dev server a worker would sit between the browser and the modules
23
+ * hot reload is about to replace.
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * if (import.meta.env.PROD) void registerServiceWorker('/sw.js')
28
+ * ```
29
+ */
30
+ export declare function registerServiceWorker(url?: string | URL, options?: RegisterServiceWorkerOptions): Promise<ServiceWorkerRegistration | null>;
@@ -0,0 +1,31 @@
1
+ // Registering the service worker. Small, but the defaults matter: `updateViaCache: 'none'` makes the browser's
2
+ // update check for the worker script skip the HTTP cache, so a changed worker is picked up on the next start even
3
+ // when a proxy ignored the script's `Cache-Control: no-cache`.
4
+ /**
5
+ * Registers the service worker and resolves to its registration — or `null` where service workers are unavailable
6
+ * (an old browser, a non-secure context, a private mode that disables them) or registration failed.
7
+ *
8
+ * Gate it on a production build yourself: under a dev server a worker would sit between the browser and the modules
9
+ * hot reload is about to replace.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * if (import.meta.env.PROD) void registerServiceWorker('/sw.js')
14
+ * ```
15
+ */
16
+ export async function registerServiceWorker(url = '/sw.js', options = {}) {
17
+ const container = options.container ?? (typeof navigator !== 'undefined' && 'serviceWorker' in navigator ? navigator.serviceWorker : undefined);
18
+ if (!container)
19
+ return null;
20
+ try {
21
+ return await container.register(url, {
22
+ scope: options.scope,
23
+ type: options.type,
24
+ updateViaCache: options.updateViaCache ?? 'none',
25
+ });
26
+ }
27
+ catch (error) {
28
+ options.onError?.(error);
29
+ return null;
30
+ }
31
+ }
package/dist/sw.d.ts ADDED
@@ -0,0 +1,133 @@
1
+ /** The paths Elarion's own endpoints map to by default. Spread it into `serverPrefixes` and add the app's own. */
2
+ export declare const ELARION_SERVER_PREFIXES: readonly string[];
3
+ /**
4
+ * The parts of `ServiceWorkerGlobalScope` the router uses — structural, so the real `self` fits without this package
5
+ * depending on the WebWorker type library.
6
+ */
7
+ export interface ShellServiceWorkerScope {
8
+ readonly location: {
9
+ readonly origin: string;
10
+ };
11
+ readonly caches: CacheStorage;
12
+ fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
13
+ skipWaiting(): Promise<void>;
14
+ readonly clients: {
15
+ claim(): Promise<void>;
16
+ };
17
+ addEventListener(type: string, listener: (event: any) => void): void;
18
+ }
19
+ /** The parts of `FetchEvent` the router uses. */
20
+ export interface ShellFetchEvent {
21
+ readonly request: Request;
22
+ respondWith(response: Response | Promise<Response>): void;
23
+ waitUntil(promise: Promise<unknown>): void;
24
+ }
25
+ /** Answers one fetch event. */
26
+ export type ShellStrategy = (event: ShellFetchEvent) => Promise<Response>;
27
+ /** How page navigations are answered — the application's privacy choice, so it has no default. */
28
+ export type NavigationPolicy = {
29
+ /** Never cached. For server-rendered pages: their HTML carries the signed-in user's data. */
30
+ mode: 'network-only';
31
+ /** A self-contained page (no stylesheet or script requests) precached and shown when the network is gone. */
32
+ offlineUrl?: string;
33
+ } | {
34
+ /** An SPA shell: the last network answer is kept and served only when the network is gone. */
35
+ mode: 'network-first';
36
+ /** The key the shell is cached under — every client route serves the same document. Defaults to `/`. */
37
+ shellUrl?: string;
38
+ /** Shown offline before a shell was ever cached. */
39
+ offlineUrl?: string;
40
+ };
41
+ /** Options for {@link createShellRouter} and {@link registerShellRouter}. */
42
+ export interface ShellRouterOptions {
43
+ /** The Cache Storage name. Change it when the precache list changes; `activate` deletes the previous one. */
44
+ cacheName: string;
45
+ /**
46
+ * Server endpoints the worker must never answer: the API, auth, uploads, SSE, server-rendered non-app pages.
47
+ * Matched by path segment (`/rpc` covers `/rpc` and `/rpc/x`, not `/rpcx`). Start from
48
+ * {@link ELARION_SERVER_PREFIXES}. Required: in `network-first` mode a navigation outside these is cached as the
49
+ * shell.
50
+ */
51
+ serverPrefixes: readonly string[];
52
+ /** Further requests to leave to the network, e.g. a whole other app under the same origin. */
53
+ bypass?: (url: URL, request: Request) => boolean;
54
+ /** How page navigations are answered. */
55
+ navigation: NavigationPolicy;
56
+ /** Same-origin files served stale-while-revalidate and precached — manifest, icons, favicon. Not HTML. */
57
+ staticFiles?: readonly string[];
58
+ /** Further URLs to precache on install, beyond `offlineUrl`, `shellUrl` and `staticFiles`. */
59
+ precache?: readonly string[];
60
+ /** The bundler's hashed output, or `false` to leave it alone. */
61
+ assets?: {
62
+ /** Defaults to `/assets/` (Vite). */
63
+ prefix?: string;
64
+ /**
65
+ * How many entries under `prefix` are kept, newest first. Hold at least one whole build — a larger app emits
66
+ * hundreds of route chunks, and evicting the running build's own chunks breaks its next lazy route offline.
67
+ * Defaults to 400.
68
+ */
69
+ maxEntries?: number;
70
+ /**
71
+ * Files under `prefix` whose URL survives deploys (no content hash) — served network first instead of cache
72
+ * first, which would pin an installed app to the version of its first visit. Defaults to none.
73
+ */
74
+ mutable?: (url: URL) => boolean;
75
+ } | false;
76
+ /** Which other caches `activate` deletes. Defaults to every cache but `cacheName`. */
77
+ ownsCache?: (name: string) => boolean;
78
+ /** Activate a new worker without waiting for every tab of the old one to close. Defaults to `true`. */
79
+ skipWaiting?: boolean;
80
+ }
81
+ /** The strategies a router uses, bound to its cache — for an application's own routes in the same `fetch` listener. */
82
+ export interface ShellStrategies {
83
+ /** The cache if present, else the network (and store a plain answer). */
84
+ cacheFirst: ShellStrategy;
85
+ /** The network (and store a plain answer), else the cache. */
86
+ networkFirst: ShellStrategy;
87
+ /** The cache at once, refreshed from the network in the background; the network when nothing is cached yet. */
88
+ staleWhileRevalidate: ShellStrategy;
89
+ /** The configured {@link NavigationPolicy}. */
90
+ navigation: ShellStrategy;
91
+ }
92
+ /** A configured shell router; see {@link createShellRouter}. */
93
+ export interface ShellRouter {
94
+ /** The strategy that answers `request`, or `null` when the worker must stay out (the browser fetches as usual). */
95
+ route(request: Request): ShellStrategy | null;
96
+ /** Answers `event` when {@link route} has a strategy for it; returns whether it did. */
97
+ handleFetch(event: ShellFetchEvent): boolean;
98
+ /** Precaches the offline page, the shell and the static files; rejects (failing the install) on a non-plain answer. */
99
+ install(): Promise<void>;
100
+ /** Deletes the other caches it owns and claims the open pages. */
101
+ activate(): Promise<void>;
102
+ readonly strategies: ShellStrategies;
103
+ }
104
+ /**
105
+ * Whether `pathname` is one of `prefixes` or below one, by path segment: `/rpc` matches `/rpc` and `/rpc/batch` but
106
+ * not `/rpcx`. A trailing slash on a prefix is ignored.
107
+ */
108
+ export declare function isServerPath(pathname: string, prefixes: readonly string[]): boolean;
109
+ /**
110
+ * Whether a network answer may be stored: a 200 (not partial), not reached through a redirect, same-origin `basic`
111
+ * (an opaque answer's status is unknowable), and not marked `Cache-Control: no-store`.
112
+ */
113
+ export declare function isCacheable(response: Response): boolean;
114
+ /** Creates a shell router without registering it — for a worker that routes some requests itself first. */
115
+ export declare function createShellRouter(scope: ShellServiceWorkerScope, options: ShellRouterOptions): ShellRouter;
116
+ /**
117
+ * Registers the shell router's `install`, `activate` and `fetch` handlers on `scope` and returns the router.
118
+ *
119
+ * @example
120
+ * ```ts
121
+ * import { ELARION_SERVER_PREFIXES, registerShellRouter } from '@swimmesberger/elarion-pwa/sw'
122
+ * import { registerWebPushHandlers } from '@swimmesberger/elarion-webpush/sw'
123
+ *
124
+ * registerShellRouter(self, {
125
+ * cacheName: 'myapp-v1',
126
+ * serverPrefixes: [...ELARION_SERVER_PREFIXES, '/auth'],
127
+ * navigation: { mode: 'network-only', offlineUrl: '/offline.html' },
128
+ * staticFiles: ['/manifest.webmanifest', '/icon-192.png', '/icon-512.png', '/apple-touch-icon.png'],
129
+ * })
130
+ * registerWebPushHandlers(self, { icon: '/icon-192.png' })
131
+ * ```
132
+ */
133
+ export declare function registerShellRouter(scope: ShellServiceWorkerScope, options: ShellRouterOptions): ShellRouter;
package/dist/sw.js ADDED
@@ -0,0 +1,238 @@
1
+ // The service-worker half of the Elarion installable-app shell (ADR-0083): a shell router that makes the Home
2
+ // Screen install an app — it opens offline, loads its hashed assets from the cache — without ever answering the API,
3
+ // a personal page, or a login redirect from a cache. Import it into the application's service worker (bundled into
4
+ // one classic script, or registered with `type: 'module'`) and call registerShellRouter(self, …) once at the top
5
+ // level. It composes with `registerWebPushHandlers(self)` from `@swimmesberger/elarion-webpush/sw` in the same worker:
6
+ // this module handles `install`, `activate` and `fetch`; Web Push handles `push`, `notificationclick` and
7
+ // `pushsubscriptionchange`.
8
+ //
9
+ // Navigations the app's choice (`navigation.mode`):
10
+ // network-only never cached — for server-rendered pages that carry personal data; offline, the
11
+ // precached `offlineUrl` answers instead.
12
+ // network-first an SPA shell: every route serves the same index.html, kept under `shellUrl` and
13
+ // served only when the network is gone, so a deploy reaches an installed app on its
14
+ // next open.
15
+ // `assets.prefix` (/assets/) cache first — content-hashed, so immutable by construction; `assets.mutable` names
16
+ // the hash-free files there (network first). The newest `maxEntries` are kept.
17
+ // `staticFiles` stale-while-revalidate (manifest, icons, favicon); precached.
18
+ // Everything else not touched: `serverPrefixes` (segment-aware) and `bypass`, any non-GET, cross-origin,
19
+ // `cache: 'no-store'` or ranged request, and any path not listed above.
20
+ //
21
+ // Only a plain answer is ever stored: a 200 that did not arrive through a redirect (an auth proxy answering an
22
+ // expired session with its login page), is same-origin `basic` (not opaque), and does not say `no-store`. An HTML
23
+ // answer is stored only as the navigation shell — never under an asset URL, where a server's SPA fallback answering
24
+ // a missing chunk with index.html would otherwise replace the script for good.
25
+ /** The paths Elarion's own endpoints map to by default. Spread it into `serverPrefixes` and add the app's own. */
26
+ export const ELARION_SERVER_PREFIXES = [
27
+ '/rpc', // MapElarionJsonRpc
28
+ '/mcp', // MapElarionMcp
29
+ '/events', // MapElarionClientEvents (SSE)
30
+ '/session', // MapElarionSession
31
+ '/webpush', // MapElarionWebPush
32
+ '/_elarion', // blob uploads, downloads and tus
33
+ ];
34
+ /**
35
+ * Whether `pathname` is one of `prefixes` or below one, by path segment: `/rpc` matches `/rpc` and `/rpc/batch` but
36
+ * not `/rpcx`. A trailing slash on a prefix is ignored.
37
+ */
38
+ export function isServerPath(pathname, prefixes) {
39
+ return prefixes.some((raw) => {
40
+ const prefix = raw.length > 1 && raw.endsWith('/') ? raw.slice(0, -1) : raw;
41
+ return pathname === prefix || pathname.startsWith(prefix === '/' ? '/' : `${prefix}/`);
42
+ });
43
+ }
44
+ /**
45
+ * Whether a network answer may be stored: a 200 (not partial), not reached through a redirect, same-origin `basic`
46
+ * (an opaque answer's status is unknowable), and not marked `Cache-Control: no-store`.
47
+ */
48
+ export function isCacheable(response) {
49
+ return (response.status === 200 &&
50
+ !response.redirected &&
51
+ response.type === 'basic' &&
52
+ !/\bno-store\b/i.test(response.headers.get('cache-control') ?? ''));
53
+ }
54
+ function isHtml(response) {
55
+ return /\btext\/html\b/i.test(response.headers.get('content-type') ?? '');
56
+ }
57
+ /** Creates a shell router without registering it — for a worker that routes some requests itself first. */
58
+ export function createShellRouter(scope, options) {
59
+ const { cacheName, serverPrefixes, navigation: policy } = options;
60
+ const staticFiles = new Set(options.staticFiles ?? []);
61
+ const assets = options.assets === false ? null : (options.assets ?? {});
62
+ const assetPrefix = assets?.prefix ?? '/assets/';
63
+ const maxAssets = assets?.maxEntries ?? 400;
64
+ const shellUrl = policy.mode === 'network-first' ? (policy.shellUrl ?? '/') : null;
65
+ const offlineUrl = policy.offlineUrl ?? null;
66
+ const precache = [
67
+ ...new Set([
68
+ ...(offlineUrl ? [offlineUrl] : []),
69
+ ...(shellUrl ? [shellUrl] : []),
70
+ ...staticFiles,
71
+ ...(options.precache ?? []),
72
+ ]),
73
+ ];
74
+ const open = () => scope.caches.open(cacheName);
75
+ /** Stores without failing the response: a full quota or a `Vary: *` answer only means it is not cached. */
76
+ async function store(key, response) {
77
+ try {
78
+ await (await open()).put(key, response);
79
+ }
80
+ catch {
81
+ // Not cached this time.
82
+ }
83
+ }
84
+ /** Caches a copy of a plain, non-HTML answer in the background of `event`. */
85
+ function keep(event, response, after) {
86
+ if (!isCacheable(response) || isHtml(response))
87
+ return;
88
+ event.waitUntil(store(event.request, response.clone()).then(after));
89
+ }
90
+ async function trimAssets() {
91
+ const cache = await open();
92
+ const keys = (await cache.keys()).filter((key) => new URL(key.url).pathname.startsWith(assetPrefix));
93
+ // Cache keys come back in insertion order, so the oldest entries (earlier deploys) go first.
94
+ for (const key of keys.slice(0, Math.max(0, keys.length - maxAssets)))
95
+ await cache.delete(key);
96
+ }
97
+ function cacheFirstWith(after) {
98
+ return async (event) => {
99
+ const cached = await (await open()).match(event.request);
100
+ if (cached)
101
+ return cached;
102
+ const response = await scope.fetch(event.request);
103
+ keep(event, response, after);
104
+ return response;
105
+ };
106
+ }
107
+ const cacheFirst = cacheFirstWith();
108
+ const assetCacheFirst = cacheFirstWith(trimAssets);
109
+ const networkFirst = async (event) => {
110
+ try {
111
+ const response = await scope.fetch(event.request);
112
+ keep(event, response);
113
+ return response;
114
+ }
115
+ catch {
116
+ return (await (await open()).match(event.request)) ?? Response.error();
117
+ }
118
+ };
119
+ const staleWhileRevalidate = async (event) => {
120
+ const cached = await (await open()).match(event.request);
121
+ const refresh = scope.fetch(event.request).then((response) => {
122
+ keep(event, response);
123
+ return response;
124
+ }, () => undefined);
125
+ if (cached) {
126
+ event.waitUntil(refresh);
127
+ return cached;
128
+ }
129
+ return (await refresh) ?? Response.error();
130
+ };
131
+ async function offline() {
132
+ const cache = await open();
133
+ const shell = shellUrl ? await cache.match(shellUrl) : undefined;
134
+ const page = shell ?? (offlineUrl ? await cache.match(offlineUrl) : undefined);
135
+ return page ?? Response.error();
136
+ }
137
+ const navigation = async (event) => {
138
+ let response;
139
+ try {
140
+ response = await scope.fetch(event.request);
141
+ }
142
+ catch {
143
+ return offline();
144
+ }
145
+ // network-only stores nothing; network-first keeps a plain HTML answer as the shell.
146
+ if (shellUrl && isCacheable(response) && isHtml(response)) {
147
+ event.waitUntil(store(shellUrl, response.clone()));
148
+ }
149
+ return response;
150
+ };
151
+ function route(request) {
152
+ if (request.method !== 'GET')
153
+ return null;
154
+ if (request.cache === 'no-store')
155
+ return null;
156
+ if (request.headers?.has('range'))
157
+ return null;
158
+ const url = new URL(request.url);
159
+ if (url.origin !== scope.location.origin)
160
+ return null;
161
+ if (isServerPath(url.pathname, serverPrefixes))
162
+ return null;
163
+ if (options.bypass?.(url, request))
164
+ return null;
165
+ if (request.mode === 'navigate')
166
+ return navigation;
167
+ if (assets && url.pathname.startsWith(assetPrefix)) {
168
+ return assets.mutable?.(url) ? networkFirst : assetCacheFirst;
169
+ }
170
+ if (staticFiles.has(url.pathname))
171
+ return staleWhileRevalidate;
172
+ return null;
173
+ }
174
+ return {
175
+ route,
176
+ handleFetch(event) {
177
+ const strategy = route(event.request);
178
+ if (!strategy)
179
+ return false;
180
+ event.respondWith(strategy(event));
181
+ return true;
182
+ },
183
+ async install() {
184
+ const cache = await open();
185
+ await Promise.all(precache.map(async (url) => {
186
+ // `reload` skips the HTTP cache: a stale copy would outlive the deploy it belonged to.
187
+ const response = await scope.fetch(url, { cache: 'reload', credentials: 'same-origin' });
188
+ if (!isCacheable(response)) {
189
+ throw new Error(`Precaching ${url} failed: HTTP ${response.status}${response.redirected ? ', redirected' : ''}.`);
190
+ }
191
+ // Only the offline page and the shell are documents; HTML anywhere else is a server's SPA fallback.
192
+ if (url !== offlineUrl && url !== shellUrl && isHtml(response)) {
193
+ throw new Error(`Precaching ${url} failed: the server answered with an HTML page.`);
194
+ }
195
+ await cache.put(url, response);
196
+ }));
197
+ },
198
+ async activate() {
199
+ const ownsCache = options.ownsCache ?? (() => true);
200
+ const names = await scope.caches.keys();
201
+ await Promise.all(names.filter((name) => name !== cacheName && ownsCache(name)).map((name) => scope.caches.delete(name)));
202
+ await scope.clients.claim();
203
+ },
204
+ strategies: { cacheFirst, networkFirst, staleWhileRevalidate, navigation },
205
+ };
206
+ }
207
+ /**
208
+ * Registers the shell router's `install`, `activate` and `fetch` handlers on `scope` and returns the router.
209
+ *
210
+ * @example
211
+ * ```ts
212
+ * import { ELARION_SERVER_PREFIXES, registerShellRouter } from '@swimmesberger/elarion-pwa/sw'
213
+ * import { registerWebPushHandlers } from '@swimmesberger/elarion-webpush/sw'
214
+ *
215
+ * registerShellRouter(self, {
216
+ * cacheName: 'myapp-v1',
217
+ * serverPrefixes: [...ELARION_SERVER_PREFIXES, '/auth'],
218
+ * navigation: { mode: 'network-only', offlineUrl: '/offline.html' },
219
+ * staticFiles: ['/manifest.webmanifest', '/icon-192.png', '/icon-512.png', '/apple-touch-icon.png'],
220
+ * })
221
+ * registerWebPushHandlers(self, { icon: '/icon-192.png' })
222
+ * ```
223
+ */
224
+ export function registerShellRouter(scope, options) {
225
+ const router = createShellRouter(scope, options);
226
+ scope.addEventListener('install', (event) => {
227
+ event.waitUntil(router.install());
228
+ if (options.skipWaiting !== false)
229
+ void scope.skipWaiting().catch(() => undefined);
230
+ });
231
+ scope.addEventListener('activate', (event) => {
232
+ event.waitUntil(router.activate());
233
+ });
234
+ scope.addEventListener('fetch', (event) => {
235
+ router.handleFetch(event);
236
+ });
237
+ return router;
238
+ }
@@ -0,0 +1,156 @@
1
+ /** Where `appVersionFile()` from `@swimmesberger/elarion-pwa/vite` publishes the build version by default. */
2
+ export declare const DEFAULT_VERSION_URL = "/app-version.json";
3
+ /** No second check within this window: switching apps every few seconds must not mean a request each time. */
4
+ export declare const DEFAULT_CHECK_INTERVAL_MS = 60000;
5
+ /** No second update reload within this window — a proxy serving a stale version file must not cause a loop. */
6
+ export declare const DEFAULT_RELOAD_GUARD_MS = 60000;
7
+ /** The sessionStorage key of the last update reload (per tab; it survives the reload itself). */
8
+ export declare const DEFAULT_RELOAD_STORAGE_KEY = "elarion.pwa.reloadedAt";
9
+ /** What counts as "the user is in the middle of something" besides a focused field: an open dialog of any kind. */
10
+ export declare const BUSY_SELECTOR = "[role=\"dialog\"], [role=\"alertdialog\"], dialog[open]";
11
+ /**
12
+ * What a check found: `stay` (same build, or no answer) or `pending` — a different build is live and the app
13
+ * reloads into it on the next safe page change ({@link shouldReloadOnNavigation}). There is no "reload now".
14
+ */
15
+ export type UpdateDecision = 'stay' | 'pending';
16
+ /** Asks the server which build it ships now; `null` when it cannot tell (offline, mid-deploy, malformed). */
17
+ export type VersionSource = () => Promise<string | null>;
18
+ /** Whether a foreground return should ask the server again. */
19
+ export declare function shouldCheckForUpdate({ now, lastCheckAt, intervalMs, }: {
20
+ now: number;
21
+ lastCheckAt: number;
22
+ intervalMs?: number;
23
+ }): boolean;
24
+ /** Compares the running build with the served one. No answer is never a reason to reload. */
25
+ export declare function updateDecision({ currentVersion, servedVersion, }: {
26
+ currentVersion: string;
27
+ servedVersion: string | null;
28
+ }): UpdateDecision;
29
+ /**
30
+ * Whether a resolved navigation applies a pending update. Only a navigation that changed the **path** counts: a
31
+ * search box that writes `?q=` on every keystroke and a router re-resolving the same location must not reload
32
+ * under the user's input. Not while the page is busy (an open dialog, a focused field), and not within
33
+ * `guardMs` of the last update reload.
34
+ */
35
+ export declare function shouldReloadOnNavigation({ pending, pathChanged, busy, now, lastReloadAt, guardMs, }: {
36
+ pending: boolean;
37
+ pathChanged: boolean;
38
+ busy: boolean;
39
+ now: number;
40
+ lastReloadAt: number;
41
+ guardMs?: number;
42
+ }): boolean;
43
+ /** The `version` out of a version file's JSON body, or `null` for anything that is not a non-empty string there. */
44
+ export declare function parseServedVersion(body: unknown): string | null;
45
+ /** The first module entry script under `/assets/` in an HTML document — a content-hashed name, so a build id. */
46
+ export declare function parseEntryScript(html: string): string | null;
47
+ /** The element shape {@link isTextEntry} reads — structural, so it works on `document.activeElement`. */
48
+ export interface FocusTarget {
49
+ readonly tagName: string;
50
+ readonly isContentEditable?: boolean;
51
+ readonly type?: string;
52
+ }
53
+ /** Whether focus on this element means the user is typing (a text input, textarea, select, or contenteditable). */
54
+ export declare function isTextEntry(target: FocusTarget | null | undefined): boolean;
55
+ /** The document shape {@link isDocumentBusy} reads. */
56
+ export interface BusyDocument {
57
+ querySelector(selector: string): unknown;
58
+ readonly activeElement: FocusTarget | null;
59
+ }
60
+ /** The default busy predicate: an open dialog ({@link BUSY_SELECTOR}) or a focused text field. */
61
+ export declare function isDocumentBusy(doc?: BusyDocument | undefined): boolean;
62
+ /**
63
+ * Reads the build version from a JSON file such as the one `appVersionFile()` emits (`{"version":"…"}`). The
64
+ * request is `cache: 'no-store'`, which skips the HTTP cache and which the `/sw` shell router leaves to the network.
65
+ */
66
+ export declare function jsonVersionSource(url?: string): VersionSource;
67
+ /**
68
+ * Reads the build version from the served HTML shell: its hashed entry script ({@link parseEntryScript}). Needs no
69
+ * build step — pair it with {@link currentEntryScript} as the running version — but costs a shell render per
70
+ * check, so prefer {@link jsonVersionSource} where the build can publish a version file.
71
+ */
72
+ export declare function entryScriptVersionSource(url?: string): VersionSource;
73
+ /** The running document's hashed entry script, or `null` (e.g. under a dev server, which serves no hashed entry). */
74
+ export declare function currentEntryScript(doc?: Pick<Document, 'querySelector'> | undefined): string | null;
75
+ /** The visibility surface the watcher listens on. */
76
+ export interface VisibilityDocument {
77
+ readonly visibilityState: DocumentVisibilityState;
78
+ addEventListener(type: 'visibilitychange', listener: () => void): void;
79
+ removeEventListener(type: 'visibilitychange', listener: () => void): void;
80
+ }
81
+ /** The storage the reload guard lives in. */
82
+ export interface ReloadGuardStorage {
83
+ getItem(key: string): string | null;
84
+ setItem(key: string, value: string): void;
85
+ }
86
+ /** Options for {@link createUpdateWatcher}. */
87
+ export interface UpdateWatcherOptions {
88
+ /**
89
+ * The running build's version — the same value the server publishes (bake it into the bundle, e.g. with
90
+ * `appVersionFile({ define })`). An empty or missing value disables the watcher.
91
+ */
92
+ currentVersion: string | null | undefined;
93
+ /** Asks the server which build is live. Defaults to `jsonVersionSource('/app-version.json')`. */
94
+ servedVersion?: VersionSource;
95
+ /** Set `false` to disable checking entirely — e.g. `import.meta.env.PROD`, so a dev server never checks. */
96
+ enabled?: boolean;
97
+ /** Whether the user is in the middle of something right now. Defaults to {@link isDocumentBusy}. */
98
+ isBusy?: () => boolean;
99
+ /** Minimum time between two foreground checks. Defaults to 60 s. */
100
+ checkIntervalMs?: number;
101
+ /** Minimum time between two update reloads of this tab. Defaults to 60 s. */
102
+ reloadGuardMs?: number;
103
+ /** The sessionStorage key of the reload guard. Defaults to {@link DEFAULT_RELOAD_STORAGE_KEY}. */
104
+ storageKey?: string;
105
+ /** Where the reload guard is kept. Defaults to `sessionStorage`; `null` keeps it in memory only. */
106
+ storage?: ReloadGuardStorage | null;
107
+ /** The document whose foreground returns trigger a check. Defaults to `document`. */
108
+ document?: VisibilityDocument;
109
+ /** The path the page started on, the baseline of {@link UpdateWatcher.navigatedTo}. Defaults to `location.pathname`. */
110
+ initialPath?: string;
111
+ /** Reloads the page. Defaults to `location.reload()`. */
112
+ reload?: () => void;
113
+ /** The clock. Defaults to `Date.now`. */
114
+ now?: () => number;
115
+ }
116
+ /** Watches for a new deploy; see {@link createUpdateWatcher}. */
117
+ export interface UpdateWatcher {
118
+ /**
119
+ * Asks the server now. Honors the check interval unless `force` is set — force it when a response failed this
120
+ * build's validation, the surest sign a newer contract is live. A `pending` result still only reloads on the
121
+ * next safe page change.
122
+ */
123
+ check(options?: {
124
+ force?: boolean;
125
+ }): Promise<UpdateDecision>;
126
+ /** Whether a newer build is live and waiting for the next safe page change. */
127
+ isPending(): boolean;
128
+ /** Calls `listener` when {@link isPending} changes — e.g. to show an "Update available" hint. */
129
+ subscribe(listener: () => void): () => void;
130
+ /**
131
+ * Call after every resolved navigation, with whether its **path** changed (TanStack Router's `onResolved` event
132
+ * carries `pathChanged`). Reloads into a pending update when it is safe; returns whether it did.
133
+ */
134
+ navigationResolved(change: {
135
+ pathChanged: boolean;
136
+ }): boolean;
137
+ /** Like {@link navigationResolved}, for routers that only report the new pathname; the watcher compares paths. */
138
+ navigatedTo(pathname: string): boolean;
139
+ /** Applies a pending update at once — for an explicit "Reload" action. Returns whether it reloaded. */
140
+ reloadNow(): boolean;
141
+ /** Stops listening for foreground returns. */
142
+ dispose(): void;
143
+ }
144
+ /**
145
+ * Watches for a new deploy of the web build and reloads into it at a safe moment: checks when the app returns to the
146
+ * foreground (at most once per `checkIntervalMs`), marks a different served version as pending, and reloads on the
147
+ * next navigation that changed the path while no dialog is open and no field is focused — never more than once per
148
+ * `reloadGuardMs`.
149
+ *
150
+ * @example
151
+ * ```ts
152
+ * const updates = createUpdateWatcher({ currentVersion: __APP_VERSION__, enabled: import.meta.env.PROD })
153
+ * router.subscribe('onResolved', (event) => updates.navigationResolved({ pathChanged: event.pathChanged }))
154
+ * ```
155
+ */
156
+ export declare function createUpdateWatcher(options: UpdateWatcherOptions): UpdateWatcher;
package/dist/update.js ADDED
@@ -0,0 +1,276 @@
1
+ // Reload into a new deploy. An installed app is not reopened, it is resumed: it can stay in memory for days, keep
2
+ // talking to an API that was redeployed under it, and fail on a contract it does not know. So when the app returns
3
+ // to the foreground it asks the server which web build is live, and when that differs from its own it reloads into
4
+ // it — on the next page change, never on the foreground return itself.
5
+ //
6
+ // Why not right away: coming back from the camera (a `capture` file input), a share sheet or a password manager is
7
+ // a foreground return too, and the page may hold a whole form in local state that a reload would wipe — with nothing
8
+ // on screen that looks busy, and iOS never asks on `beforeunload`. A page change is the safe moment: the user has
9
+ // left the page, and a page with unsaved input blocks its own navigation first. Even then an open dialog or a
10
+ // focused field postpones it, and a loop guard keeps a proxy that serves a stale version from turning every page
11
+ // change into a reload.
12
+ //
13
+ // The decisions are pure functions; createUpdateWatcher wires them to the document, the version source, and the
14
+ // application's router (navigationResolved / navigatedTo).
15
+ /** Where `appVersionFile()` from `@swimmesberger/elarion-pwa/vite` publishes the build version by default. */
16
+ export const DEFAULT_VERSION_URL = '/app-version.json';
17
+ /** No second check within this window: switching apps every few seconds must not mean a request each time. */
18
+ export const DEFAULT_CHECK_INTERVAL_MS = 60_000;
19
+ /** No second update reload within this window — a proxy serving a stale version file must not cause a loop. */
20
+ export const DEFAULT_RELOAD_GUARD_MS = 60_000;
21
+ /** The sessionStorage key of the last update reload (per tab; it survives the reload itself). */
22
+ export const DEFAULT_RELOAD_STORAGE_KEY = 'elarion.pwa.reloadedAt';
23
+ /** What counts as "the user is in the middle of something" besides a focused field: an open dialog of any kind. */
24
+ export const BUSY_SELECTOR = '[role="dialog"], [role="alertdialog"], dialog[open]';
25
+ /** Whether a foreground return should ask the server again. */
26
+ export function shouldCheckForUpdate({ now, lastCheckAt, intervalMs = DEFAULT_CHECK_INTERVAL_MS, }) {
27
+ return now - lastCheckAt >= intervalMs;
28
+ }
29
+ /** Compares the running build with the served one. No answer is never a reason to reload. */
30
+ export function updateDecision({ currentVersion, servedVersion, }) {
31
+ return servedVersion === null || servedVersion === currentVersion ? 'stay' : 'pending';
32
+ }
33
+ /**
34
+ * Whether a resolved navigation applies a pending update. Only a navigation that changed the **path** counts: a
35
+ * search box that writes `?q=` on every keystroke and a router re-resolving the same location must not reload
36
+ * under the user's input. Not while the page is busy (an open dialog, a focused field), and not within
37
+ * `guardMs` of the last update reload.
38
+ */
39
+ export function shouldReloadOnNavigation({ pending, pathChanged, busy, now, lastReloadAt, guardMs = DEFAULT_RELOAD_GUARD_MS, }) {
40
+ return pending && pathChanged && !busy && now - lastReloadAt >= guardMs;
41
+ }
42
+ /** The `version` out of a version file's JSON body, or `null` for anything that is not a non-empty string there. */
43
+ export function parseServedVersion(body) {
44
+ if (typeof body !== 'object' || body === null)
45
+ return null;
46
+ const version = body.version;
47
+ return typeof version === 'string' && version.trim() !== '' ? version.trim() : null;
48
+ }
49
+ /** The first module entry script under `/assets/` in an HTML document — a content-hashed name, so a build id. */
50
+ export function parseEntryScript(html) {
51
+ for (const match of html.matchAll(/<script\b[^>]*>/gi)) {
52
+ const tag = match[0];
53
+ if (!/\btype\s*=\s*["']?module\b/i.test(tag))
54
+ continue;
55
+ const src = /\bsrc\s*=\s*["']([^"']+)["']/i.exec(tag)?.[1];
56
+ if (src?.startsWith('/assets/'))
57
+ return src;
58
+ }
59
+ return null;
60
+ }
61
+ /** `<input>` types that never raise a keyboard or hold typed text. */
62
+ const NON_TEXT_INPUT_TYPES = new Set([
63
+ 'button',
64
+ 'checkbox',
65
+ 'color',
66
+ 'file',
67
+ 'hidden',
68
+ 'image',
69
+ 'radio',
70
+ 'range',
71
+ 'reset',
72
+ 'submit',
73
+ ]);
74
+ /** Whether focus on this element means the user is typing (a text input, textarea, select, or contenteditable). */
75
+ export function isTextEntry(target) {
76
+ if (!target)
77
+ return false;
78
+ if (target.isContentEditable)
79
+ return true;
80
+ const tag = target.tagName.toUpperCase();
81
+ if (tag === 'TEXTAREA' || tag === 'SELECT')
82
+ return true;
83
+ if (tag !== 'INPUT')
84
+ return false;
85
+ return !NON_TEXT_INPUT_TYPES.has((target.type || 'text').toLowerCase());
86
+ }
87
+ /** The default busy predicate: an open dialog ({@link BUSY_SELECTOR}) or a focused text field. */
88
+ export function isDocumentBusy(doc = globalThis.document) {
89
+ if (!doc)
90
+ return false;
91
+ return doc.querySelector(BUSY_SELECTOR) !== null || isTextEntry(doc.activeElement);
92
+ }
93
+ /**
94
+ * Reads the build version from a JSON file such as the one `appVersionFile()` emits (`{"version":"…"}`). The
95
+ * request is `cache: 'no-store'`, which skips the HTTP cache and which the `/sw` shell router leaves to the network.
96
+ */
97
+ export function jsonVersionSource(url = DEFAULT_VERSION_URL) {
98
+ return async () => {
99
+ try {
100
+ const response = await fetch(url, { cache: 'no-store', credentials: 'same-origin' });
101
+ if (!response.ok)
102
+ return null;
103
+ return parseServedVersion(await response.json());
104
+ }
105
+ catch {
106
+ // Offline, or the server is restarting mid-deploy: ask again on the next foreground return.
107
+ return null;
108
+ }
109
+ };
110
+ }
111
+ /**
112
+ * Reads the build version from the served HTML shell: its hashed entry script ({@link parseEntryScript}). Needs no
113
+ * build step — pair it with {@link currentEntryScript} as the running version — but costs a shell render per
114
+ * check, so prefer {@link jsonVersionSource} where the build can publish a version file.
115
+ */
116
+ export function entryScriptVersionSource(url = '/') {
117
+ return async () => {
118
+ try {
119
+ const response = await fetch(url, {
120
+ cache: 'no-store',
121
+ credentials: 'same-origin',
122
+ headers: { accept: 'text/html' },
123
+ });
124
+ if (!response.ok)
125
+ return null;
126
+ return parseEntryScript(await response.text());
127
+ }
128
+ catch {
129
+ return null;
130
+ }
131
+ };
132
+ }
133
+ /** The running document's hashed entry script, or `null` (e.g. under a dev server, which serves no hashed entry). */
134
+ export function currentEntryScript(doc = globalThis.document) {
135
+ const script = doc?.querySelector('script[type="module"][src^="/assets/"]');
136
+ return script?.getAttribute('src') ?? null;
137
+ }
138
+ /**
139
+ * Watches for a new deploy of the web build and reloads into it at a safe moment: checks when the app returns to the
140
+ * foreground (at most once per `checkIntervalMs`), marks a different served version as pending, and reloads on the
141
+ * next navigation that changed the path while no dialog is open and no field is focused — never more than once per
142
+ * `reloadGuardMs`.
143
+ *
144
+ * @example
145
+ * ```ts
146
+ * const updates = createUpdateWatcher({ currentVersion: __APP_VERSION__, enabled: import.meta.env.PROD })
147
+ * router.subscribe('onResolved', (event) => updates.navigationResolved({ pathChanged: event.pathChanged }))
148
+ * ```
149
+ */
150
+ export function createUpdateWatcher(options) {
151
+ const currentVersion = options.currentVersion?.trim() ?? '';
152
+ const enabled = options.enabled !== false && currentVersion !== '';
153
+ const servedVersion = options.servedVersion ?? jsonVersionSource();
154
+ const isBusy = options.isBusy ?? (() => isDocumentBusy());
155
+ const checkIntervalMs = options.checkIntervalMs ?? DEFAULT_CHECK_INTERVAL_MS;
156
+ const reloadGuardMs = options.reloadGuardMs ?? DEFAULT_RELOAD_GUARD_MS;
157
+ const storageKey = options.storageKey ?? DEFAULT_RELOAD_STORAGE_KEY;
158
+ const storage = options.storage === undefined ? sessionStorageOrNull() : options.storage;
159
+ const doc = options.document ?? globalThis.document;
160
+ const reload = options.reload ?? (() => globalThis.location.reload());
161
+ const now = options.now ?? Date.now;
162
+ const listeners = new Set();
163
+ let pending = false;
164
+ let lastCheckAt = Number.NEGATIVE_INFINITY;
165
+ let inFlight = null;
166
+ let lastPath = options.initialPath ?? globalThis.location?.pathname ?? '';
167
+ let memoryReloadAt = Number.NEGATIVE_INFINITY;
168
+ const setPending = (value) => {
169
+ if (pending === value)
170
+ return;
171
+ pending = value;
172
+ for (const listener of [...listeners])
173
+ listener();
174
+ };
175
+ const readLastReloadAt = () => {
176
+ try {
177
+ const stored = Number(storage?.getItem(storageKey) ?? Number.NaN);
178
+ return Number.isFinite(stored) ? Math.max(stored, memoryReloadAt) : memoryReloadAt;
179
+ }
180
+ catch {
181
+ return memoryReloadAt;
182
+ }
183
+ };
184
+ const doReload = (at) => {
185
+ memoryReloadAt = at;
186
+ try {
187
+ storage?.setItem(storageKey, String(at));
188
+ }
189
+ catch {
190
+ // Private mode or storage disabled: the guard is best effort, the check interval still throttles.
191
+ }
192
+ setPending(false);
193
+ reload();
194
+ };
195
+ async function check({ force = false } = {}) {
196
+ if (!enabled)
197
+ return 'stay';
198
+ if (inFlight)
199
+ return inFlight;
200
+ const at = now();
201
+ if (!force && !shouldCheckForUpdate({ now: at, lastCheckAt, intervalMs: checkIntervalMs })) {
202
+ return pending ? 'pending' : 'stay';
203
+ }
204
+ lastCheckAt = at;
205
+ inFlight = (async () => {
206
+ const served = await servedVersion().catch(() => null);
207
+ // No answer keeps what an earlier check found; an answer equal to ours clears it (a rolled-back deploy).
208
+ if (served !== null)
209
+ setPending(updateDecision({ currentVersion, servedVersion: served }) === 'pending');
210
+ return pending ? 'pending' : 'stay';
211
+ })();
212
+ try {
213
+ return await inFlight;
214
+ }
215
+ finally {
216
+ inFlight = null;
217
+ }
218
+ }
219
+ const onVisibilityChange = () => {
220
+ if (doc?.visibilityState === 'visible')
221
+ void check();
222
+ };
223
+ if (enabled)
224
+ doc?.addEventListener('visibilitychange', onVisibilityChange);
225
+ function navigationResolved({ pathChanged }) {
226
+ if (!pending)
227
+ return false;
228
+ const at = now();
229
+ const reloadNow = shouldReloadOnNavigation({
230
+ pending,
231
+ pathChanged,
232
+ busy: isBusy(),
233
+ now: at,
234
+ lastReloadAt: readLastReloadAt(),
235
+ guardMs: reloadGuardMs,
236
+ });
237
+ if (reloadNow)
238
+ doReload(at);
239
+ return reloadNow;
240
+ }
241
+ return {
242
+ check,
243
+ isPending: () => pending,
244
+ subscribe(listener) {
245
+ listeners.add(listener);
246
+ return () => {
247
+ listeners.delete(listener);
248
+ };
249
+ },
250
+ navigationResolved,
251
+ navigatedTo(pathname) {
252
+ const pathChanged = pathname !== lastPath;
253
+ lastPath = pathname;
254
+ return navigationResolved({ pathChanged });
255
+ },
256
+ reloadNow() {
257
+ if (!pending)
258
+ return false;
259
+ doReload(now());
260
+ return true;
261
+ },
262
+ dispose() {
263
+ doc?.removeEventListener('visibilitychange', onVisibilityChange);
264
+ listeners.clear();
265
+ },
266
+ };
267
+ }
268
+ function sessionStorageOrNull() {
269
+ try {
270
+ return globalThis.sessionStorage ?? null;
271
+ }
272
+ catch {
273
+ // Reading sessionStorage throws where storage is blocked (sandboxed frames, some privacy modes).
274
+ return null;
275
+ }
276
+ }
package/dist/vite.d.ts ADDED
@@ -0,0 +1,60 @@
1
+ /** Options for {@link appVersionFile}. */
2
+ export interface AppVersionFileOptions {
3
+ /** The build's version — a CI run number, a commit hash, a date stamp. Normalize it once, here. */
4
+ version: string;
5
+ /** The emitted file name, relative to the build output. Defaults to `app-version.json`. */
6
+ fileName?: string;
7
+ /**
8
+ * A global constant to define as the same version in the bundle, e.g. `'__APP_VERSION__'` (declare it in a
9
+ * `.d.ts`: `declare const __APP_VERSION__: string`). Applies to the dev server as well.
10
+ */
11
+ define?: string;
12
+ /**
13
+ * The Vite environment that emits the file (Vite 6+ environment API) — the one whose output the web server
14
+ * serves. Defaults to `client`; an SSR environment never has a static directory to serve it from.
15
+ */
16
+ environment?: string;
17
+ }
18
+ /** The emitted-file shape the plugin uses from Vite's plugin context. */
19
+ export interface AppVersionEmittedAsset {
20
+ type: 'asset';
21
+ fileName: string;
22
+ source: string;
23
+ }
24
+ /** The plugin context the plugin uses. */
25
+ export interface AppVersionPluginContext {
26
+ emitFile(file: AppVersionEmittedAsset): string;
27
+ readonly environment?: {
28
+ readonly name: string;
29
+ };
30
+ }
31
+ /** The plugin {@link appVersionFile} returns — assignable to Vite's `Plugin`. */
32
+ export interface AppVersionPlugin {
33
+ readonly name: string;
34
+ config(): {
35
+ define: Record<string, string>;
36
+ } | undefined;
37
+ configResolved(config: {
38
+ readonly build: {
39
+ readonly ssr?: boolean | string;
40
+ };
41
+ }): void;
42
+ generateBundle(this: AppVersionPluginContext): void;
43
+ }
44
+ /**
45
+ * Emits `{"version": "…"}` as `/app-version.json` in the client build, for `jsonVersionSource()` and
46
+ * `createUpdateWatcher` from `@swimmesberger/elarion-pwa`.
47
+ *
48
+ * Serve the file with `Cache-Control: no-cache` (the watcher also fetches it with `cache: 'no-store'`), and keep it
49
+ * on the web build's side of a reverse proxy — not routed to the API.
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * // vite.config.ts
54
+ * import { appVersionFile } from '@swimmesberger/elarion-pwa/vite'
55
+ *
56
+ * const version = process.env.APP_VERSION?.trim() || 'dev'
57
+ * export default defineConfig({ plugins: [appVersionFile({ version, define: '__APP_VERSION__' }), react()] })
58
+ * ```
59
+ */
60
+ export declare function appVersionFile(options: AppVersionFileOptions): AppVersionPlugin;
package/dist/vite.js ADDED
@@ -0,0 +1,41 @@
1
+ // A Vite plugin that publishes the build's version next to its assets (`/app-version.json`), which the page half's
2
+ // update watcher compares with the version baked into the running bundle. Optionally it bakes that same value in
3
+ // (`define`), so the two ends cannot drift apart. Typed structurally: this package does not import Vite.
4
+ /**
5
+ * Emits `{"version": "…"}` as `/app-version.json` in the client build, for `jsonVersionSource()` and
6
+ * `createUpdateWatcher` from `@swimmesberger/elarion-pwa`.
7
+ *
8
+ * Serve the file with `Cache-Control: no-cache` (the watcher also fetches it with `cache: 'no-store'`), and keep it
9
+ * on the web build's side of a reverse proxy — not routed to the API.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * // vite.config.ts
14
+ * import { appVersionFile } from '@swimmesberger/elarion-pwa/vite'
15
+ *
16
+ * const version = process.env.APP_VERSION?.trim() || 'dev'
17
+ * export default defineConfig({ plugins: [appVersionFile({ version, define: '__APP_VERSION__' }), react()] })
18
+ * ```
19
+ */
20
+ export function appVersionFile(options) {
21
+ const fileName = options.fileName ?? 'app-version.json';
22
+ const environment = options.environment ?? 'client';
23
+ const source = JSON.stringify({ version: options.version });
24
+ let ssrBuild = false;
25
+ return {
26
+ name: 'elarion:app-version',
27
+ config() {
28
+ return options.define ? { define: { [options.define]: JSON.stringify(options.version) } } : undefined;
29
+ },
30
+ configResolved(config) {
31
+ ssrBuild = Boolean(config.build.ssr);
32
+ },
33
+ generateBundle() {
34
+ // Vite 6+ runs one bundle per environment; before that, an SSR build is a separate `vite build --ssr`.
35
+ const name = this.environment?.name;
36
+ if (name !== undefined ? name !== environment : ssrBuild)
37
+ return;
38
+ this.emitFile({ type: 'asset', fileName, source });
39
+ },
40
+ };
41
+ }
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
- {
2
- "name": "@swimmesberger/elarion-pwa",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@swimmesberger/elarion-pwa",
3
+ "version": "0.0.0",
4
+ "description": "The installable-app shell for Elarion frontends: install-prompt capture with iOS Home Screen instructions, a deploy-update watcher that reloads only on a safe page change, service-worker registration, a /sw module whose shell router never caches the API, HTML, redirects, or no-store answers, and a /vite plugin that publishes the build version.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "import": "./dist/index.js"
11
+ },
12
+ "./sw": {
13
+ "types": "./dist/sw.d.ts",
14
+ "import": "./dist/sw.js"
15
+ },
16
+ "./vite": {
17
+ "types": "./dist/vite.d.ts",
18
+ "import": "./dist/vite.js"
19
+ }
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "README.md"
24
+ ],
25
+ "sideEffects": false,
26
+ "scripts": {
27
+ "build": "tsc -p tsconfig.json",
28
+ "typecheck": "tsc --noEmit -p tsconfig.test.json && tsc --noEmit -p tsconfig.sw-test.json",
29
+ "test": "npm run typecheck && vitest run",
30
+ "prepack": "npm run build",
31
+ "prepare": "npm run build"
32
+ },
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/swimmesberger/Elarion.git",
36
+ "directory": "src/elarion-pwa"
37
+ },
38
+ "bugs": {
39
+ "url": "https://github.com/swimmesberger/Elarion/issues"
40
+ },
41
+ "homepage": "https://github.com/swimmesberger/Elarion#readme",
42
+ "publishConfig": {
43
+ "access": "public",
44
+ "registry": "https://registry.npmjs.org/"
45
+ },
46
+ "engines": {
47
+ "node": ">=20.11"
48
+ },
49
+ "peerDependencies": {
50
+ "vite": ">=5"
51
+ },
52
+ "peerDependenciesMeta": {
53
+ "vite": {
54
+ "optional": true
55
+ }
56
+ },
57
+ "devDependencies": {
58
+ "typescript": "^6.0.3",
59
+ "vite": "^8.3.1",
60
+ "vitest": "^5.0.2"
61
+ }
62
+ }