@oxy.so/app-preset 6.7.1 → 6.7.3

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
@@ -100,7 +100,8 @@ The app keeps its own `public/manifest.json` and icons. The step:
100
100
  app has no `public/sw.js`. An app with its own worker (web push) keeps it and
101
101
  opts in with `importScripts('/oxy-sw-base.js');` as its first line; until it
102
102
  does, the step warns. A worker that already answers `fetch` (Inbosh, Nilo)
103
- must not import it. `--no-sw` ships no worker.
103
+ must not import it. `--no-sw` ships no worker; `--remove-sw` retires one
104
+ shipped before (see Cleanup below).
104
105
 
105
106
  `theme-color` comes from the manifest's `theme_color`, one tag. An app whose
106
107
  startup colour is a light/dark pair (Bloom adopts one and owns it at runtime)
@@ -108,16 +109,36 @@ passes it instead: `oxy-web-pwa dist --theme-color=#f9f2f6,#100d11` (hex or a
108
109
  colour name; a page that already has a `theme-color` keeps it).
109
110
 
110
111
  The base worker (`web/oxy-sw-base.js`, from Inbosh's) answers navigations
111
- network-first with the one `/index.html` shell as the offline fallback, and
112
+ network-first with the one shell (fetched from `/`, stored under `/index.html`,
113
+ never as a redirected response, which Chrome refuses for a navigation) as the
114
+ offline fallback, and
112
115
  same-origin static files (`/_expo/`, `/assets/`, images, fonts, JS, CSS)
113
- stale-while-revalidate. It never stores or serves anything else: cross-origin
116
+ stale-while-revalidate. On install it stores the shell's bundles and CSS, and
117
+ the registration sends it the files the page loaded before it took control,
118
+ so the app works offline from the first visit. It never stores or serves anything else: cross-origin
114
119
  requests (every Oxy API), non-GET, `/api/`, requests carrying `Authorization`
115
- or `Range`, and `private`/`no-store` responses. Its
116
- cache name is a hash of the export, so each deploy installs a new worker and
117
- drops the old cache; the cache holds at most 150 entries.
118
-
119
- Serve `/sw.js` with `Cache-Control: no-cache` (`public/_headers`). `@oxy.so/doctor`
120
- 1.10.0+ warns (`web-not-installable`) about a web export without this step.
120
+ or `Range`, and `private`/`no-store` responses.
121
+
122
+ **Updates.** `oxy-web-pwa` stamps `/oxy-sw-base.js` with a hash of the export,
123
+ so every deploy changes its bytes and the browser installs the new worker, which
124
+ takes over at once. The registration uses `updateViaCache: 'none'`, and a page
125
+ that returns to the foreground checks for an update at most once an hour (an
126
+ installed app can stay open for days without a navigation). App code is never
127
+ stale: navigations are network-first, so the next load runs the new deploy.
128
+
129
+ **Cleanup.** One cache, `oxy-sw-v1`, holds at most 150 entries, oldest dropped
130
+ first and the shell never. It is not renamed per deploy: hashed chunks never
131
+ collide, so a tab opened before a deploy can still lazy-load the chunks the
132
+ server has already dropped. `activate` deletes every other `oxy-sw-*` cache, so
133
+ bumping the name in the base worker clears old entries everywhere on the next
134
+ deploy. To take the worker away, build with `--remove-sw`: it ships a `/sw.js`
135
+ that deletes the Oxy caches and unregisters itself (shipping no `/sw.js` would
136
+ leave the old worker running, since a failed update check keeps it).
137
+
138
+ Serve `/sw.js` and `/oxy-sw-base.js` with `Cache-Control: no-cache` or
139
+ `max-age=0, must-revalidate` (Cloudflare's default for unhashed assets).
140
+ `@oxy.so/doctor` 1.10.0+ warns (`web-not-installable`) about a web export
141
+ without this step.
121
142
 
122
143
  ## Usage
123
144
 
@@ -5,14 +5,15 @@
5
5
  *
6
6
  * expo export --platform web --output-dir dist && oxy-web-pwa dist
7
7
  *
8
- * oxy-web-pwa [dist] [--no-sw] [--theme-color=<light>,<dark>]
8
+ * oxy-web-pwa [dist] [--no-sw | --remove-sw] [--theme-color=<light>,<dark>]
9
9
  *
10
10
  * `dist` defaults to `dist`. The step checks the exported manifest
11
11
  * (public/manifest.json) against what browsers need to offer installation,
12
12
  * adds the manifest link, theme colour, Apple tags and the worker registration
13
13
  * to every exported page that lacks them, and ships the Oxy base service
14
14
  * worker (`/oxy-sw-base.js`, plus `/sw.js` when the app has none).
15
- * `--no-sw` skips the worker. `--theme-color=<light>,<dark>` writes the
15
+ * `--no-sw` skips the worker. `--remove-sw` ships a `/sw.js` that retires a
16
+ * worker shipped before (deletes its caches and unregisters it). `--theme-color=<light>,<dark>` writes the
16
17
  * startup `theme-color` as a light/dark pair (the one Bloom adopts at runtime)
17
18
  * instead of the manifest's single `theme_color`.
18
19
  *
@@ -22,16 +23,18 @@
22
23
  const { resolve } = require('node:path');
23
24
  const { PwaError, makeInstallable } = require('../web/pwa');
24
25
 
25
- const usage = 'oxy-web-pwa [dist] [--no-sw] [--theme-color=<light>,<dark>]';
26
+ const usage = 'oxy-web-pwa [dist] [--no-sw | --remove-sw] [--theme-color=<light>,<dark>]';
26
27
  const args = process.argv.slice(2);
27
28
  let dist = 'dist';
28
29
  let serviceWorker = true;
30
+ let removeServiceWorker = false;
29
31
  let themeColors;
30
32
  for (const arg of args) {
31
33
  if (arg === '--help' || arg === '-h') {
32
34
  console.log(usage);
33
35
  process.exit(0);
34
36
  } else if (arg === '--no-sw') serviceWorker = false;
37
+ else if (arg === '--remove-sw') removeServiceWorker = true;
35
38
  else if (arg.startsWith('--theme-color='))
36
39
  themeColors = arg
37
40
  .slice('--theme-color='.length)
@@ -44,7 +47,11 @@ for (const arg of args) {
44
47
  }
45
48
 
46
49
  try {
47
- const result = makeInstallable(resolve(dist), { serviceWorker, themeColors });
50
+ const result = makeInstallable(resolve(dist), {
51
+ serviceWorker,
52
+ removeServiceWorker,
53
+ themeColors,
54
+ });
48
55
  for (const warning of result.warnings) console.warn(`oxy-web-pwa: warning: ${warning}`);
49
56
  console.log(
50
57
  `oxy-web-pwa: ${result.manifest} is installable; ${result.updated.length} of ${result.pages} pages updated` +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oxy.so/app-preset",
3
- "version": "6.7.1",
3
+ "version": "6.7.3",
4
4
  "description": "The Oxy distro of Expo — centralized Expo config plugin, Metro/Babel/ESLint factories, Tailwind base CSS and TypeScript bases shared by every Oxy app (Mention, Homiio, Allo, accounts, …). A zero-build package: apps replace copy-pasted config with a single dependency bump.",
5
5
  "main": "./app.plugin.js",
6
6
  "publishConfig": {
@@ -11,7 +11,8 @@
11
11
  * Strategies (ported from Inbosh's worker, which paid for each rule):
12
12
  *
13
13
  * - Navigation: network-first, so a deploy is visible on the next load. The
14
- * one SPA shell is stored once under `/index.html` and served offline.
14
+ * one SPA shell, fetched from `/`, is stored once under `/index.html` and
15
+ * served offline, always as a response that went through no redirect.
15
16
  * - Same-origin static files (`/_expo/`, `/assets/`, images, fonts, JS, CSS):
16
17
  * stale-while-revalidate. Metro hashes these names, so an entry is never
17
18
  * stale in content, and chunks of the previous deploy stay loadable for a
@@ -24,10 +25,21 @@
24
25
  * Private responses must never be cached by URL: Inbosh once served one
25
26
  * signed-in user's API response to the next.
26
27
  *
27
- * `__OXY_SW_VERSION__` is replaced by `oxy-web-pwa` with a hash of the export,
28
- * so the bytes change on every deploy and the browser installs the new worker
29
- * (imported scripts are compared byte for byte too). The cache is bounded and
30
- * old caches are dropped on `activate`.
28
+ * Updates. `__OXY_SW_VERSION__` is replaced by `oxy-web-pwa` with a hash of
29
+ * the export, so this file's bytes change on every deploy; the browser compares
30
+ * imported scripts byte for byte, so it installs the new worker, which takes
31
+ * over at once (`skipWaiting`, `clients.claim`). App code is never stale: a
32
+ * navigation is network-first, so the next load or reload runs the new deploy,
33
+ * and a page still running the old one keeps loading its own chunks.
34
+ *
35
+ * Cleanup. The cache name is fixed (`oxy-sw-v1`), not per deploy: hashed
36
+ * chunks never collide, so one cache holds both deploys and a tab opened
37
+ * before a deploy can still lazy-load the chunks it was built with (the server
38
+ * no longer has them). It holds at most 150 entries, oldest dropped first, the
39
+ * shell never. `activate` deletes every other `oxy-sw-*` cache, so bumping the
40
+ * name here (when a strategy changes what a cached entry means) clears old
41
+ * entries everywhere on the next deploy. `oxy-web-pwa --remove-sw` retires the
42
+ * worker and its caches entirely.
31
43
  */
32
44
  (() => {
33
45
  if (self.__oxySwBase) return;
@@ -35,21 +47,99 @@
35
47
 
36
48
  const VERSION = '__OXY_SW_VERSION__';
37
49
  const CACHE_PREFIX = 'oxy-sw-';
38
- const CACHE_NAME = `${CACHE_PREFIX}${VERSION}`;
50
+ const CACHE_NAME = `${CACHE_PREFIX}v1`;
51
+ self.__oxySwVersion = VERSION;
39
52
  const SHELL_KEY = '/index.html';
40
53
  const MAX_ENTRIES = 150;
41
54
  const STATIC_FILE = /\.(?:js|mjs|css|woff2?|ttf|otf|png|jpe?g|gif|svg|ico|webp|avif|wasm)$/i;
42
55
 
43
56
  const offline = () => new Response('Offline', { status: 503, statusText: 'Service Unavailable' });
44
57
 
58
+ /**
59
+ * A response a navigation can be answered with. Chrome refuses a response
60
+ * that went through a redirect for a navigation (`net::ERR_FAILED`), and
61
+ * hosts redirect: Cloudflare's static assets send `/index.html` to `/` with
62
+ * a 307. So a stored shell is always rebuilt as a plain response.
63
+ */
64
+ function servable(response) {
65
+ if (!response?.redirected) return response;
66
+ return new Response(response.body, {
67
+ status: response.status,
68
+ statusText: response.statusText,
69
+ headers: response.headers,
70
+ });
71
+ }
72
+
73
+ /** A same-origin static file this worker stores: a bundle, stylesheet, font or image. */
74
+ function isStatic(url) {
75
+ if (url.origin !== self.location.origin || url.pathname.startsWith('/api/')) return false;
76
+ return (
77
+ url.pathname.startsWith('/_expo/') ||
78
+ url.pathname.startsWith('/assets/') ||
79
+ STATIC_FILE.test(url.pathname)
80
+ );
81
+ }
82
+
83
+ /** The static files the shell's own tags load (its bundles and CSS). */
84
+ function shellAssets(html) {
85
+ const urls = new Set();
86
+ for (const [, src] of html.matchAll(/<(?:script|link)\b[^>]*?\s(?:src|href)="([^"]+)"/gi)) {
87
+ const url = new URL(src, self.location.origin);
88
+ if (isStatic(url)) urls.add(url.href);
89
+ }
90
+ return [...urls];
91
+ }
92
+
93
+ /** Stores each of `urls` that is a static file and not stored yet; a failure is skipped. */
94
+ async function storeAssets(cache, urls) {
95
+ const wanted = [
96
+ ...new Set(
97
+ urls
98
+ .map((url) => {
99
+ try {
100
+ return new URL(url, self.location.origin);
101
+ } catch {
102
+ return null;
103
+ }
104
+ })
105
+ .filter((url) => url && isStatic(url))
106
+ .map((url) => url.href),
107
+ ),
108
+ ].slice(0, MAX_ENTRIES);
109
+ await Promise.all(
110
+ wanted.map(async (url) => {
111
+ try {
112
+ if (await cache.match(url)) return;
113
+ const asset = await fetch(url);
114
+ if (cacheable(asset)) await cache.put(url, asset);
115
+ } catch {
116
+ // A file left out is fetched (and stored) the next time the page asks for it.
117
+ }
118
+ }),
119
+ );
120
+ await trim(cache);
121
+ }
122
+
123
+ /**
124
+ * Stores the shell from `/` (the URL the host serves it at) and the bundles
125
+ * it loads. A first visit fetches those before this worker controls the page,
126
+ * so without this the app would only work offline from the second visit on.
127
+ */
128
+ async function storeShell() {
129
+ const response = await fetch('/', { cache: 'reload' });
130
+ if (!cacheable(response) || !(response.headers.get('content-type') || '').includes('text/html'))
131
+ return;
132
+ const html = await response.clone().text();
133
+ const cache = await caches.open(CACHE_NAME);
134
+ await cache.put(SHELL_KEY, servable(response));
135
+ await storeAssets(cache, shellAssets(html));
136
+ }
137
+
45
138
  self.addEventListener('install', (event) => {
46
139
  event.waitUntil(
47
- caches
48
- .open(CACHE_NAME)
49
- .then((cache) => cache.add(new Request(SHELL_KEY, { cache: 'reload' })))
50
- .catch(() => {
51
- // Non-fatal: the shell is stored on the first navigation instead.
52
- }),
140
+ storeShell().catch(() => {
141
+ // Non-fatal: the shell is stored on the first navigation instead.
142
+ }),
53
143
  );
54
144
  self.skipWaiting();
55
145
  });
@@ -69,8 +159,16 @@
69
159
  );
70
160
  });
71
161
 
162
+ /**
163
+ * `OXY_SW_STORE`: the files a page loaded before this worker controlled it
164
+ * (its route chunks, fonts), which `oxy-sw-register.js` sends when the worker
165
+ * takes over. Only static same-origin files are stored, whatever is sent.
166
+ */
72
167
  self.addEventListener('message', (event) => {
73
- if (event.data && event.data.type === 'SKIP_WAITING') self.skipWaiting();
168
+ const data = event.data;
169
+ if (data?.type === 'SKIP_WAITING') self.skipWaiting();
170
+ if (data?.type === 'OXY_SW_STORE' && Array.isArray(data.urls))
171
+ event.waitUntil(caches.open(CACHE_NAME).then((cache) => storeAssets(cache, data.urls)));
74
172
  });
75
173
 
76
174
  /** `'navigation'`, `'static'`, or `null` for a request this worker leaves alone. */
@@ -81,13 +179,7 @@
81
179
  if (url.pathname.startsWith('/api/')) return null;
82
180
  if (request.headers.has('authorization') || request.headers.has('range')) return null;
83
181
  if (request.mode === 'navigate') return 'navigation';
84
- if (
85
- url.pathname.startsWith('/_expo/') ||
86
- url.pathname.startsWith('/assets/') ||
87
- STATIC_FILE.test(url.pathname)
88
- )
89
- return 'static';
90
- return null;
182
+ return isStatic(url) ? 'static' : null;
91
183
  }
92
184
 
93
185
  /** Only a complete, same-origin, storable response is ever cached. */
@@ -115,12 +207,13 @@
115
207
  (response.headers.get('content-type') || '').includes('text/html')
116
208
  ) {
117
209
  const cache = await caches.open(CACHE_NAME);
118
- await cache.put(SHELL_KEY, response.clone());
210
+ await cache.put(SHELL_KEY, servable(response.clone()));
119
211
  }
120
212
  return response;
121
213
  } catch {
122
214
  const cache = await caches.open(CACHE_NAME);
123
- return (await cache.match(SHELL_KEY)) || offline();
215
+ // servable() again: a shell stored by 6.7.2 or earlier may be a redirected one.
216
+ return servable(await cache.match(SHELL_KEY)) || offline();
124
217
  }
125
218
  }
126
219
 
@@ -149,5 +242,17 @@
149
242
  else if (strategy === 'static') event.respondWith(staleWhileRevalidate(event));
150
243
  });
151
244
 
152
- self.__oxySwBaseInternals = { strategyFor, cacheable, CACHE_NAME, SHELL_KEY, MAX_ENTRIES };
245
+ self.__oxySwBaseInternals = {
246
+ strategyFor,
247
+ cacheable,
248
+ servable,
249
+ shellAssets,
250
+ storeAssets,
251
+ navigation,
252
+ storeShell,
253
+ trim,
254
+ CACHE_NAME,
255
+ SHELL_KEY,
256
+ MAX_ENTRIES,
257
+ };
153
258
  })();
@@ -8,11 +8,43 @@
8
8
  * after `load` has often fired, and a `load` listener added then never runs,
9
9
  * so the page's state is checked first. Failure is silent: the app works
10
10
  * without a worker.
11
+ *
12
+ * First visit: the page loads its bundles and route chunks before the worker
13
+ * controls it, so none of them goes through the worker's cache. When the worker
14
+ * takes over, this sends it the same-origin files the page has loaded so far
15
+ * (`OXY_SW_STORE`), and the app works offline from the first visit.
16
+ *
17
+ * Updates: `updateViaCache: 'none'` makes every update check fetch `/sw.js` and
18
+ * `/oxy-sw-base.js` past the HTTP cache. The browser checks on each navigation,
19
+ * but an installed app can stay open for days without one, so a page that
20
+ * comes back to the foreground checks too, at most once an hour.
11
21
  */
12
22
  (() => {
13
23
  if (!('serviceWorker' in navigator) || !window.isSecureContext) return;
24
+ const HOUR = 60 * 60 * 1000;
25
+ let checked = Date.now();
26
+ const sendLoaded = () => {
27
+ const worker = navigator.serviceWorker.controller;
28
+ if (!worker || typeof performance === 'undefined') return;
29
+ const urls = performance
30
+ .getEntriesByType('resource')
31
+ .map((entry) => entry.name)
32
+ .filter((name) => name.startsWith(`${location.origin}/`));
33
+ worker.postMessage({ type: 'OXY_SW_STORE', urls });
34
+ };
35
+ if (!navigator.serviceWorker.controller)
36
+ navigator.serviceWorker.addEventListener('controllerchange', sendLoaded, { once: true });
14
37
  const register = () => {
15
- navigator.serviceWorker.register('/sw.js').catch(() => {});
38
+ navigator.serviceWorker
39
+ .register('/sw.js', { updateViaCache: 'none' })
40
+ .then((registration) => {
41
+ document.addEventListener('visibilitychange', () => {
42
+ if (document.visibilityState !== 'visible' || Date.now() - checked < HOUR) return;
43
+ checked = Date.now();
44
+ registration.update().catch(() => {});
45
+ });
46
+ })
47
+ .catch(() => {});
16
48
  };
17
49
  if (document.readyState === 'complete') register();
18
50
  else window.addEventListener('load', register, { once: true });
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Written as `/sw.js` by `oxy-web-pwa --remove-sw`: retires this origin's
3
+ * worker. The browser installs it on the next update check (it differs from the
4
+ * worker it replaces), and on `activate` it deletes the Oxy caches and
5
+ * unregisters itself. It answers no `fetch`, so open pages go to the network
6
+ * at once (nothing reloads under the user) and the next load has no worker.
7
+ * Shipping no `/sw.js` at all would not do this: a failed update check leaves
8
+ * the old worker running.
9
+ */
10
+ self.addEventListener('install', () => self.skipWaiting());
11
+ self.addEventListener('activate', (event) => {
12
+ event.waitUntil(
13
+ (async () => {
14
+ for (const key of await caches.keys())
15
+ if (key.startsWith('oxy-sw-')) await caches.delete(key);
16
+ await self.registration.unregister();
17
+ })(),
18
+ );
19
+ });
package/web/pwa.js CHANGED
@@ -27,6 +27,7 @@ const REQUIRED_ICON_SIZES = ['192x192', '512x512'];
27
27
  const SKIPPED_DIRS = new Set(['_expo', 'assets', 'node_modules']);
28
28
  const SW_BASE = 'oxy-sw-base.js';
29
29
  const SW_REGISTER = 'oxy-sw-register.js';
30
+ const SW_REMOVE = 'oxy-sw-remove.js';
30
31
  const WEB_DIR = __dirname;
31
32
 
32
33
  class PwaError extends Error {}
@@ -203,7 +204,15 @@ importScripts('/${SW_BASE}');
203
204
  * Runs the whole step on `dist`. Throws PwaError on anything that leaves the
204
205
  * app uninstallable; returns what it did and any warnings.
205
206
  */
206
- function makeInstallable(dist, { serviceWorker = true, themeColors } = {}) {
207
+ function makeInstallable(
208
+ dist,
209
+ { serviceWorker = true, removeServiceWorker = false, themeColors } = {},
210
+ ) {
211
+ if (removeServiceWorker && !serviceWorker)
212
+ throw new PwaError(
213
+ '--remove-sw and --no-sw cannot be combined; --remove-sw ships no worker either',
214
+ );
215
+ if (removeServiceWorker) serviceWorker = false;
207
216
  if (themeColors !== undefined) {
208
217
  const valid = /^(?:#[0-9a-f]{3,8}|[a-z]+|(?:rgb|hsl)a?\([^"<>]*\))$/i;
209
218
  if (
@@ -250,7 +259,14 @@ function makeInstallable(dist, { serviceWorker = true, themeColors } = {}) {
250
259
  }
251
260
 
252
261
  let worker = null;
253
- if (serviceWorker) {
262
+ if (removeServiceWorker) {
263
+ if (existsSync(join(dist, 'sw.js')))
264
+ throw new PwaError(
265
+ '--remove-sw replaces /sw.js, but the app ships its own public/sw.js; drop its importScripts line instead',
266
+ );
267
+ writeFileSync(join(dist, 'sw.js'), readFileSync(join(WEB_DIR, SW_REMOVE)));
268
+ worker = 'removal (retires the worker and its caches)';
269
+ } else if (serviceWorker) {
254
270
  const version = exportVersion(pages);
255
271
  const base = readFileSync(join(WEB_DIR, SW_BASE), 'utf8').replace(
256
272
  /__OXY_SW_VERSION__/g,
@@ -281,4 +297,5 @@ module.exports = {
281
297
  wantedTags,
282
298
  SW_BASE,
283
299
  SW_REGISTER,
300
+ SW_REMOVE,
284
301
  };