@oxy.so/app-preset 6.6.0 → 6.7.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 +46 -1
- package/bin/oxy-web-pwa.js +51 -0
- package/package.json +5 -2
- package/web/oxy-sw-base.js +152 -0
- package/web/oxy-sw-register.js +19 -0
- package/web/pwa.js +247 -0
package/README.md
CHANGED
|
@@ -22,6 +22,7 @@ and JSON.
|
|
|
22
22
|
| ESLint | `@oxy.so/app-preset/eslint` | `eslint-config-expo/flat` + `dist/*` ignore |
|
|
23
23
|
| CSS base | `@oxy.so/app-preset/base.css` | Tailwind v4 + NativeWind + Bloom design-token imports + SDK `@source` globs |
|
|
24
24
|
| tsconfig | `@oxy.so/app-preset/tsconfig/{base,frontend,backend}.json` | the shared strict/composite TypeScript bases |
|
|
25
|
+
| Installable web | `oxy-web-pwa dist` (bin) | a hand-written manifest link per app (lost under `output: 'single'`), its install checks and a copied service worker |
|
|
25
26
|
|
|
26
27
|
## Static web hydration on Expo 58
|
|
27
28
|
|
|
@@ -69,6 +70,50 @@ screenshots must show real chrome, and hydration must retain the same workspace
|
|
|
69
70
|
DOM node without recoverable React errors. The package tests exercise real
|
|
70
71
|
`prerender` and `hydrateRoot`; publication runs those gates too.
|
|
71
72
|
|
|
73
|
+
## Installable web apps
|
|
74
|
+
|
|
75
|
+
With `web.output: 'single'` Expo exports its default SPA page and **ignores
|
|
76
|
+
`app/+html.tsx`**, so a `<link rel="manifest">` written there never reaches the
|
|
77
|
+
browser and the site cannot be installed: alia.onl served a valid manifest and
|
|
78
|
+
worker that no page linked. Run `oxy-web-pwa` on the export instead; it works
|
|
79
|
+
on the exported HTML, so `single` and `static` output are the same:
|
|
80
|
+
|
|
81
|
+
```json
|
|
82
|
+
"build": "expo export --platform web --output-dir dist && oxy-web-pwa dist"
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
The app keeps its own `public/manifest.json` and icons. The step:
|
|
86
|
+
|
|
87
|
+
- **fails the build** (exit 1) when the exported manifest is missing or a
|
|
88
|
+
browser would refuse it: no `name`/`short_name`, no `start_url`, a `display`
|
|
89
|
+
other than `standalone`/`fullscreen`/`minimal-ui`, no 192x192 or 512x512
|
|
90
|
+
icon, an icon the export does not contain, or `prefer_related_applications`.
|
|
91
|
+
A missing `maskable` icon, `theme_color` or `background_color` is a warning;
|
|
92
|
+
- adds to every exported page (`_expo/` and `assets/` excepted) whichever of
|
|
93
|
+
these it lacks, never touching one that is there: the manifest link,
|
|
94
|
+
`apple-touch-icon` (when `public/apple-touch-icon.png` exists), `theme-color`
|
|
95
|
+
(from the manifest), `mobile-web-app-capable`, `apple-mobile-web-app-capable`,
|
|
96
|
+
`apple-mobile-web-app-title`, and `<script src="/oxy-sw-register.js" defer>`
|
|
97
|
+
(a file, not inline, so no CSP needs an exception). Running it twice changes
|
|
98
|
+
nothing;
|
|
99
|
+
- ships the Oxy base service worker as `/oxy-sw-base.js`, and `/sw.js` when the
|
|
100
|
+
app has no `public/sw.js`. An app with its own worker (web push) keeps it and
|
|
101
|
+
opts in with `importScripts('/oxy-sw-base.js');` as its first line; until it
|
|
102
|
+
does, the step warns. A worker that already answers `fetch` (Inbosh, Nilo)
|
|
103
|
+
must not import it. `--no-sw` ships no worker.
|
|
104
|
+
|
|
105
|
+
The base worker (`web/oxy-sw-base.js`, from Inbosh's) answers navigations
|
|
106
|
+
network-first with the one `/index.html` shell as the offline fallback, and
|
|
107
|
+
same-origin static files (`/_expo/`, `/assets/`, images, fonts, JS, CSS)
|
|
108
|
+
stale-while-revalidate. It never stores or serves anything else: cross-origin
|
|
109
|
+
requests (every Oxy API), non-GET, `/api/`, requests carrying `Authorization`,
|
|
110
|
+
`credentials: 'include'` or `Range`, and `private`/`no-store` responses. Its
|
|
111
|
+
cache name is a hash of the export, so each deploy installs a new worker and
|
|
112
|
+
drops the old cache; the cache holds at most 150 entries.
|
|
113
|
+
|
|
114
|
+
Serve `/sw.js` with `Cache-Control: no-cache` (`public/_headers`). `@oxy.so/doctor`
|
|
115
|
+
1.10.0+ warns (`web-not-installable`) about a web export without this step.
|
|
116
|
+
|
|
72
117
|
## Usage
|
|
73
118
|
|
|
74
119
|
### 1. Config plugin (`app.config.js` / `app.json`)
|
|
@@ -514,6 +559,6 @@ the web host; native scroll remains owned by the native Screen/ScrollView.
|
|
|
514
559
|
|
|
515
560
|
Configure this in the stylesheet, not only in a custom `+html.tsx`: Expo's
|
|
516
561
|
`web.output="single"` export uses its default HTML and does not render that custom
|
|
517
|
-
document. Static output must keep its script/style `headNodes` and `bodyNodes`.
|
|
562
|
+
document (the same trap that left apps uninstallable; see "Installable web apps"). Static output must keep its script/style `headNodes` and `bodyNodes`.
|
|
518
563
|
The generated scaffold defaults to a bounded host. Changing the host permission
|
|
519
564
|
is separate from choosing the scroll owner for each route.
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* oxy-web-pwa: makes an Expo web export installable. Run it right after
|
|
4
|
+
* `expo export --platform web`, in the app's `build` script:
|
|
5
|
+
*
|
|
6
|
+
* expo export --platform web --output-dir dist && oxy-web-pwa dist
|
|
7
|
+
*
|
|
8
|
+
* oxy-web-pwa [dist] [--no-sw]
|
|
9
|
+
*
|
|
10
|
+
* `dist` defaults to `dist`. The step checks the exported manifest
|
|
11
|
+
* (public/manifest.json) against what browsers need to offer installation,
|
|
12
|
+
* adds the manifest link, theme colour, Apple tags and the worker registration
|
|
13
|
+
* to every exported page that lacks them, and ships the Oxy base service
|
|
14
|
+
* worker (`/oxy-sw-base.js`, plus `/sw.js` when the app has none).
|
|
15
|
+
* `--no-sw` skips the worker.
|
|
16
|
+
*
|
|
17
|
+
* Exits 0 when the export is installable, 1 when it is not, 2 on bad usage.
|
|
18
|
+
* See README "Installable web apps".
|
|
19
|
+
*/
|
|
20
|
+
const { resolve } = require('node:path');
|
|
21
|
+
const { PwaError, makeInstallable } = require('../web/pwa');
|
|
22
|
+
|
|
23
|
+
const usage = 'oxy-web-pwa [dist] [--no-sw]';
|
|
24
|
+
const args = process.argv.slice(2);
|
|
25
|
+
let dist = 'dist';
|
|
26
|
+
let serviceWorker = true;
|
|
27
|
+
for (const arg of args) {
|
|
28
|
+
if (arg === '--help' || arg === '-h') {
|
|
29
|
+
console.log(usage);
|
|
30
|
+
process.exit(0);
|
|
31
|
+
} else if (arg === '--no-sw') serviceWorker = false;
|
|
32
|
+
else if (arg.startsWith('-')) {
|
|
33
|
+
console.error(`Unknown option ${arg}\n${usage}`);
|
|
34
|
+
process.exit(2);
|
|
35
|
+
} else dist = arg;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
try {
|
|
39
|
+
const result = makeInstallable(resolve(dist), { serviceWorker });
|
|
40
|
+
for (const warning of result.warnings) console.warn(`oxy-web-pwa: warning: ${warning}`);
|
|
41
|
+
console.log(
|
|
42
|
+
`oxy-web-pwa: ${result.manifest} is installable; ${result.updated.length} of ${result.pages} pages updated` +
|
|
43
|
+
(result.worker ? `; service worker: ${result.worker}` : '; no service worker'),
|
|
44
|
+
);
|
|
45
|
+
} catch (error) {
|
|
46
|
+
if (error instanceof PwaError) {
|
|
47
|
+
console.error(`oxy-web-pwa: ${error.message}`);
|
|
48
|
+
process.exit(1);
|
|
49
|
+
}
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
package/package.json
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@oxy.so/app-preset",
|
|
3
|
-
"version": "6.
|
|
3
|
+
"version": "6.7.0",
|
|
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": {
|
|
7
7
|
"access": "public"
|
|
8
8
|
},
|
|
9
9
|
"bin": {
|
|
10
|
-
"oxy-check-keychain-entitlements": "./bin/oxy-check-keychain-entitlements.js"
|
|
10
|
+
"oxy-check-keychain-entitlements": "./bin/oxy-check-keychain-entitlements.js",
|
|
11
|
+
"oxy-web-pwa": "./bin/oxy-web-pwa.js"
|
|
11
12
|
},
|
|
12
13
|
"exports": {
|
|
13
14
|
".": "./app.plugin.js",
|
|
@@ -16,6 +17,7 @@
|
|
|
16
17
|
"./plugin/withOxyKeychain": "./plugin/withOxyKeychain.js",
|
|
17
18
|
"./plugin/oxyKeychainGroups": "./plugin/oxyKeychainGroups.js",
|
|
18
19
|
"./check-entitlements": "./bin/oxy-check-keychain-entitlements.js",
|
|
20
|
+
"./web-pwa": "./web/pwa.js",
|
|
19
21
|
"./plugin/withOxyBuildProperties": "./plugin/withOxyBuildProperties.js",
|
|
20
22
|
"./plugin/withOxyAndroidRelease": "./plugin/withOxyAndroidRelease.js",
|
|
21
23
|
"./plugin/withOxyAndroidWebp": "./plugin/withOxyAndroidWebp.js",
|
|
@@ -41,6 +43,7 @@
|
|
|
41
43
|
"build-id",
|
|
42
44
|
"eslint",
|
|
43
45
|
"certs",
|
|
46
|
+
"web",
|
|
44
47
|
"css",
|
|
45
48
|
"tsconfig",
|
|
46
49
|
"README.md"
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Oxy base service worker: an offline app shell and a cache of this
|
|
3
|
+
* origin's public, content-hashed files, and nothing else.
|
|
4
|
+
*
|
|
5
|
+
* `oxy-web-pwa` copies this file into every Oxy web export as
|
|
6
|
+
* `/oxy-sw-base.js` and, when the app has no `public/sw.js`, writes a `/sw.js`
|
|
7
|
+
* that only imports it. An app with its own worker (web push) opts in with
|
|
8
|
+
* `importScripts('/oxy-sw-base.js');` as its first line. An app whose worker
|
|
9
|
+
* already answers `fetch` must not import it: the first `respondWith` wins.
|
|
10
|
+
*
|
|
11
|
+
* Strategies (ported from Inbosh's worker, which paid for each rule):
|
|
12
|
+
*
|
|
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.
|
|
15
|
+
* - Same-origin static files (`/_expo/`, `/assets/`, images, fonts, JS, CSS):
|
|
16
|
+
* stale-while-revalidate. Metro hashes these names, so an entry is never
|
|
17
|
+
* stale in content, and chunks of the previous deploy stay loadable for a
|
|
18
|
+
* page that is still running it.
|
|
19
|
+
* - Everything else is left to the browser, never stored and never served
|
|
20
|
+
* from here: cross-origin requests (every Oxy API), non-GET, `/api/`, any
|
|
21
|
+
* request carrying credentials, range requests and `no-store` responses.
|
|
22
|
+
* Private responses must never be cached by URL: Inbosh once served one
|
|
23
|
+
* signed-in user's API response to the next.
|
|
24
|
+
*
|
|
25
|
+
* `__OXY_SW_VERSION__` is replaced by `oxy-web-pwa` with a hash of the export,
|
|
26
|
+
* so the bytes change on every deploy and the browser installs the new worker
|
|
27
|
+
* (imported scripts are compared byte for byte too). The cache is bounded and
|
|
28
|
+
* old caches are dropped on `activate`.
|
|
29
|
+
*/
|
|
30
|
+
(() => {
|
|
31
|
+
if (self.__oxySwBase) return;
|
|
32
|
+
self.__oxySwBase = true;
|
|
33
|
+
|
|
34
|
+
const VERSION = '__OXY_SW_VERSION__';
|
|
35
|
+
const CACHE_PREFIX = 'oxy-sw-';
|
|
36
|
+
const CACHE_NAME = `${CACHE_PREFIX}${VERSION}`;
|
|
37
|
+
const SHELL_KEY = '/index.html';
|
|
38
|
+
const MAX_ENTRIES = 150;
|
|
39
|
+
const STATIC_FILE = /\.(?:js|mjs|css|woff2?|ttf|otf|png|jpe?g|gif|svg|ico|webp|avif|wasm)$/i;
|
|
40
|
+
|
|
41
|
+
const offline = () => new Response('Offline', { status: 503, statusText: 'Service Unavailable' });
|
|
42
|
+
|
|
43
|
+
self.addEventListener('install', (event) => {
|
|
44
|
+
event.waitUntil(
|
|
45
|
+
caches
|
|
46
|
+
.open(CACHE_NAME)
|
|
47
|
+
.then((cache) => cache.add(new Request(SHELL_KEY, { cache: 'reload' })))
|
|
48
|
+
.catch(() => {
|
|
49
|
+
// Non-fatal: the shell is stored on the first navigation instead.
|
|
50
|
+
}),
|
|
51
|
+
);
|
|
52
|
+
self.skipWaiting();
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
self.addEventListener('activate', (event) => {
|
|
56
|
+
event.waitUntil(
|
|
57
|
+
caches
|
|
58
|
+
.keys()
|
|
59
|
+
.then((keys) =>
|
|
60
|
+
Promise.all(
|
|
61
|
+
keys
|
|
62
|
+
.filter((key) => key.startsWith(CACHE_PREFIX) && key !== CACHE_NAME)
|
|
63
|
+
.map((key) => caches.delete(key)),
|
|
64
|
+
),
|
|
65
|
+
)
|
|
66
|
+
.then(() => self.clients.claim()),
|
|
67
|
+
);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
self.addEventListener('message', (event) => {
|
|
71
|
+
if (event.data && event.data.type === 'SKIP_WAITING') self.skipWaiting();
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
/** `'navigation'`, `'static'`, or `null` for a request this worker leaves alone. */
|
|
75
|
+
function strategyFor(request) {
|
|
76
|
+
if (request.method !== 'GET') return null;
|
|
77
|
+
const url = new URL(request.url);
|
|
78
|
+
if (url.origin !== self.location.origin) return null;
|
|
79
|
+
if (url.pathname.startsWith('/api/')) return null;
|
|
80
|
+
if (request.headers.has('authorization') || request.headers.has('range')) return null;
|
|
81
|
+
if (request.credentials === 'include') return null;
|
|
82
|
+
if (request.mode === 'navigate') return 'navigation';
|
|
83
|
+
if (
|
|
84
|
+
url.pathname.startsWith('/_expo/') ||
|
|
85
|
+
url.pathname.startsWith('/assets/') ||
|
|
86
|
+
STATIC_FILE.test(url.pathname)
|
|
87
|
+
)
|
|
88
|
+
return 'static';
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Only a complete, same-origin, storable response is ever cached. */
|
|
93
|
+
function cacheable(response) {
|
|
94
|
+
if (!response?.ok || response.status !== 200 || response.type !== 'basic') return false;
|
|
95
|
+
const control = response.headers.get('cache-control') || '';
|
|
96
|
+
return !/no-store|private/i.test(control);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function trim(cache) {
|
|
100
|
+
const keys = await cache.keys();
|
|
101
|
+
const excess = keys.length - MAX_ENTRIES;
|
|
102
|
+
for (let i = 0, dropped = 0; i < keys.length && dropped < excess; i++) {
|
|
103
|
+
if (new URL(keys[i].url).pathname === SHELL_KEY) continue;
|
|
104
|
+
await cache.delete(keys[i]);
|
|
105
|
+
dropped++;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function navigation(request) {
|
|
110
|
+
try {
|
|
111
|
+
const response = await fetch(request);
|
|
112
|
+
if (
|
|
113
|
+
cacheable(response) &&
|
|
114
|
+
(response.headers.get('content-type') || '').includes('text/html')
|
|
115
|
+
) {
|
|
116
|
+
const cache = await caches.open(CACHE_NAME);
|
|
117
|
+
await cache.put(SHELL_KEY, response.clone());
|
|
118
|
+
}
|
|
119
|
+
return response;
|
|
120
|
+
} catch {
|
|
121
|
+
const cache = await caches.open(CACHE_NAME);
|
|
122
|
+
return (await cache.match(SHELL_KEY)) || offline();
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function staleWhileRevalidate(event) {
|
|
127
|
+
const cache = await caches.open(CACHE_NAME);
|
|
128
|
+
const cached = await cache.match(event.request);
|
|
129
|
+
const network = fetch(event.request)
|
|
130
|
+
.then(async (response) => {
|
|
131
|
+
if (cacheable(response)) {
|
|
132
|
+
await cache.put(event.request, response.clone());
|
|
133
|
+
await trim(cache);
|
|
134
|
+
}
|
|
135
|
+
return response;
|
|
136
|
+
})
|
|
137
|
+
.catch(() => null);
|
|
138
|
+
if (cached) {
|
|
139
|
+
event.waitUntil(network);
|
|
140
|
+
return cached;
|
|
141
|
+
}
|
|
142
|
+
return (await network) || offline();
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
self.addEventListener('fetch', (event) => {
|
|
146
|
+
const strategy = strategyFor(event.request);
|
|
147
|
+
if (strategy === 'navigation') event.respondWith(navigation(event.request));
|
|
148
|
+
else if (strategy === 'static') event.respondWith(staleWhileRevalidate(event));
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
self.__oxySwBaseInternals = { strategyFor, cacheable, CACHE_NAME, SHELL_KEY, MAX_ENTRIES };
|
|
152
|
+
})();
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Registers the app's `/sw.js`. `oxy-web-pwa` copies this file into the web
|
|
3
|
+
* export and links it from every HTML page with `defer`, as a file and not an
|
|
4
|
+
* inline script so an app's CSP needs no exception.
|
|
5
|
+
*
|
|
6
|
+
* Registering a URL that is already registered is a no-op, so this coexists
|
|
7
|
+
* with an app that registers `/sw.js` itself (web push setup). An app hydrates
|
|
8
|
+
* after `load` has often fired, and a `load` listener added then never runs,
|
|
9
|
+
* so the page's state is checked first. Failure is silent: the app works
|
|
10
|
+
* without a worker.
|
|
11
|
+
*/
|
|
12
|
+
(() => {
|
|
13
|
+
if (!('serviceWorker' in navigator) || !window.isSecureContext) return;
|
|
14
|
+
const register = () => {
|
|
15
|
+
navigator.serviceWorker.register('/sw.js').catch(() => {});
|
|
16
|
+
};
|
|
17
|
+
if (document.readyState === 'complete') register();
|
|
18
|
+
else window.addEventListener('load', register, { once: true });
|
|
19
|
+
})();
|
package/web/pwa.js
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Makes an Expo web export installable: the work behind `oxy-web-pwa`.
|
|
3
|
+
*
|
|
4
|
+
* Why it exists: with `web.output: 'single'` Expo ignores `app/+html.tsx` and
|
|
5
|
+
* serves its default SPA template, so a `<link rel="manifest">` written there
|
|
6
|
+
* never reaches the browser and the app cannot be installed (alia.onl served a
|
|
7
|
+
* valid manifest and worker that no page linked). This step works on the
|
|
8
|
+
* exported HTML itself, so it is the same for `single` and `static` output.
|
|
9
|
+
*
|
|
10
|
+
* It validates the manifest against what browsers require to install, adds the
|
|
11
|
+
* missing head tags to every exported page (never touching one that is already
|
|
12
|
+
* there), and ships the Oxy base service worker.
|
|
13
|
+
*/
|
|
14
|
+
const { createHash } = require('node:crypto');
|
|
15
|
+
const { existsSync, readFileSync, readdirSync, statSync, writeFileSync } = require('node:fs');
|
|
16
|
+
const { join, relative } = require('node:path');
|
|
17
|
+
const { parse } = require('parse5');
|
|
18
|
+
|
|
19
|
+
const MANIFEST_NAMES = ['manifest.json', 'manifest.webmanifest', 'site.webmanifest'];
|
|
20
|
+
const INSTALLABLE_DISPLAYS = new Set([
|
|
21
|
+
'standalone',
|
|
22
|
+
'fullscreen',
|
|
23
|
+
'minimal-ui',
|
|
24
|
+
'window-controls-overlay',
|
|
25
|
+
]);
|
|
26
|
+
const REQUIRED_ICON_SIZES = ['192x192', '512x512'];
|
|
27
|
+
const SKIPPED_DIRS = new Set(['_expo', 'assets', 'node_modules']);
|
|
28
|
+
const SW_BASE = 'oxy-sw-base.js';
|
|
29
|
+
const SW_REGISTER = 'oxy-sw-register.js';
|
|
30
|
+
const WEB_DIR = __dirname;
|
|
31
|
+
|
|
32
|
+
class PwaError extends Error {}
|
|
33
|
+
|
|
34
|
+
function findManifest(dist) {
|
|
35
|
+
return MANIFEST_NAMES.find((name) => existsSync(join(dist, name))) ?? null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Problems that stop a browser from offering to install the app; warnings do not. */
|
|
39
|
+
function validateManifest(manifest, dist) {
|
|
40
|
+
const errors = [];
|
|
41
|
+
const warnings = [];
|
|
42
|
+
if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
|
|
43
|
+
return { errors: ['the manifest is not a JSON object'], warnings };
|
|
44
|
+
}
|
|
45
|
+
if (!manifest.name && !manifest.short_name) errors.push('it has neither "name" nor "short_name"');
|
|
46
|
+
if (!manifest.start_url) errors.push('it has no "start_url"');
|
|
47
|
+
if (!INSTALLABLE_DISPLAYS.has(manifest.display))
|
|
48
|
+
errors.push(
|
|
49
|
+
`"display" is ${JSON.stringify(manifest.display)}; it must be one of ${[...INSTALLABLE_DISPLAYS].join(', ')}`,
|
|
50
|
+
);
|
|
51
|
+
if (manifest.prefer_related_applications === true)
|
|
52
|
+
errors.push(
|
|
53
|
+
'"prefer_related_applications" is true, which tells browsers not to offer the web app',
|
|
54
|
+
);
|
|
55
|
+
|
|
56
|
+
const icons = Array.isArray(manifest.icons) ? manifest.icons : [];
|
|
57
|
+
const sizes = new Set(icons.flatMap((icon) => String(icon.sizes ?? '').split(/\s+/)));
|
|
58
|
+
for (const size of REQUIRED_ICON_SIZES)
|
|
59
|
+
if (!sizes.has(size)) errors.push(`it has no ${size} icon`);
|
|
60
|
+
for (const icon of icons) {
|
|
61
|
+
if (typeof icon.src !== 'string' || !icon.src) {
|
|
62
|
+
errors.push('an icon has no "src"');
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(icon.src) || icon.src.startsWith('//')) continue;
|
|
66
|
+
const file = join(dist, decodeURIComponent(icon.src.split(/[?#]/)[0]).replace(/^\/+/, ''));
|
|
67
|
+
if (!existsSync(file)) errors.push(`icon ${icon.src} is not in the export`);
|
|
68
|
+
}
|
|
69
|
+
if (
|
|
70
|
+
!icons.some((icon) =>
|
|
71
|
+
String(icon.purpose ?? '')
|
|
72
|
+
.split(/\s+/)
|
|
73
|
+
.includes('maskable'),
|
|
74
|
+
)
|
|
75
|
+
)
|
|
76
|
+
warnings.push('it has no "maskable" icon, so Android shows the icon on a white disc');
|
|
77
|
+
if (!manifest.theme_color) warnings.push('it has no "theme_color"');
|
|
78
|
+
if (!manifest.background_color)
|
|
79
|
+
warnings.push('it has no "background_color" for the splash screen');
|
|
80
|
+
return { errors, warnings };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function htmlFiles(directory, root = directory) {
|
|
84
|
+
const files = [];
|
|
85
|
+
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
|
86
|
+
const path = join(directory, entry.name);
|
|
87
|
+
if (entry.isDirectory()) {
|
|
88
|
+
if (directory === root && SKIPPED_DIRS.has(entry.name)) continue;
|
|
89
|
+
files.push(...htmlFiles(path, root));
|
|
90
|
+
} else if (entry.isFile() && entry.name.endsWith('.html')) files.push(path);
|
|
91
|
+
}
|
|
92
|
+
return files.sort();
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function walk(node, visit) {
|
|
96
|
+
visit(node);
|
|
97
|
+
for (const child of node.childNodes ?? []) walk(child, visit);
|
|
98
|
+
if (node.content) walk(node.content, visit);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function attrs(node) {
|
|
102
|
+
return Object.fromEntries((node.attrs ?? []).map(({ name, value }) => [name, value]));
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const escapeAttribute = (value) =>
|
|
106
|
+
String(value).replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<');
|
|
107
|
+
|
|
108
|
+
/** The tags `html` is missing, rendered as one string. */
|
|
109
|
+
function missingTags(document, wanted) {
|
|
110
|
+
const rels = new Set();
|
|
111
|
+
const metas = new Set();
|
|
112
|
+
const scripts = new Set();
|
|
113
|
+
walk(document, (node) => {
|
|
114
|
+
const a = attrs(node);
|
|
115
|
+
if (node.tagName === 'link' && a.rel)
|
|
116
|
+
for (const rel of a.rel.toLowerCase().split(/\s+/)) rels.add(rel);
|
|
117
|
+
if (node.tagName === 'meta' && a.name) metas.add(a.name.toLowerCase());
|
|
118
|
+
if (node.tagName === 'script' && a.src) scripts.add(a.src.split(/[?#]/)[0]);
|
|
119
|
+
});
|
|
120
|
+
const out = [];
|
|
121
|
+
for (const tag of wanted) {
|
|
122
|
+
if (tag.kind === 'link' && rels.has(tag.rel)) continue;
|
|
123
|
+
if (tag.kind === 'meta' && metas.has(tag.name)) continue;
|
|
124
|
+
if (tag.kind === 'script' && scripts.has(tag.src)) continue;
|
|
125
|
+
if (tag.kind === 'link')
|
|
126
|
+
out.push(`<link rel="${tag.rel}" href="${escapeAttribute(tag.href)}" />`);
|
|
127
|
+
if (tag.kind === 'meta')
|
|
128
|
+
out.push(`<meta name="${tag.name}" content="${escapeAttribute(tag.content)}" />`);
|
|
129
|
+
if (tag.kind === 'script')
|
|
130
|
+
out.push(`<script src="${escapeAttribute(tag.src)}" defer></script>`);
|
|
131
|
+
}
|
|
132
|
+
return out;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Adds the missing tags before `</head>`; returns the new HTML, or null when nothing was missing. */
|
|
136
|
+
function injectHead(html, wanted) {
|
|
137
|
+
const document = parse(html, { sourceCodeLocationInfo: true });
|
|
138
|
+
const tags = missingTags(document, wanted);
|
|
139
|
+
if (tags.length === 0) return null;
|
|
140
|
+
let head = null;
|
|
141
|
+
walk(document, (node) => {
|
|
142
|
+
if (!head && node.tagName === 'head') head = node;
|
|
143
|
+
});
|
|
144
|
+
const end = head?.sourceCodeLocation?.endTag?.startOffset;
|
|
145
|
+
if (end === undefined) throw new PwaError('the page has no </head>');
|
|
146
|
+
const block = `<!-- oxy-web-pwa -->${tags.join('')}`;
|
|
147
|
+
return `${html.slice(0, end)}${block}${html.slice(end)}`;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function wantedTags(manifestName, manifest, dist, { serviceWorker }) {
|
|
151
|
+
const wanted = [{ kind: 'link', rel: 'manifest', href: `/${manifestName}` }];
|
|
152
|
+
if (existsSync(join(dist, 'apple-touch-icon.png')))
|
|
153
|
+
wanted.push({ kind: 'link', rel: 'apple-touch-icon', href: '/apple-touch-icon.png' });
|
|
154
|
+
if (manifest.theme_color)
|
|
155
|
+
wanted.push({ kind: 'meta', name: 'theme-color', content: manifest.theme_color });
|
|
156
|
+
wanted.push({ kind: 'meta', name: 'mobile-web-app-capable', content: 'yes' });
|
|
157
|
+
wanted.push({ kind: 'meta', name: 'apple-mobile-web-app-capable', content: 'yes' });
|
|
158
|
+
const title = manifest.short_name || manifest.name;
|
|
159
|
+
if (title) wanted.push({ kind: 'meta', name: 'apple-mobile-web-app-title', content: title });
|
|
160
|
+
if (serviceWorker) wanted.push({ kind: 'script', src: `/${SW_REGISTER}` });
|
|
161
|
+
return wanted;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** A hash of the export's pages, which name every content-hashed bundle: it changes on each deploy. */
|
|
165
|
+
function exportVersion(pages) {
|
|
166
|
+
const hash = createHash('sha256');
|
|
167
|
+
for (const page of pages) hash.update(readFileSync(page));
|
|
168
|
+
return hash.digest('hex').slice(0, 16);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const OWN_WORKER = `// Written by oxy-web-pwa (@oxy.so/app-preset): this app has no public/sw.js,
|
|
172
|
+
// so its worker is the Oxy base worker alone. Add public/sw.js to extend it.
|
|
173
|
+
importScripts('/${SW_BASE}');
|
|
174
|
+
`;
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Runs the whole step on `dist`. Throws PwaError on anything that leaves the
|
|
178
|
+
* app uninstallable; returns what it did and any warnings.
|
|
179
|
+
*/
|
|
180
|
+
function makeInstallable(dist, { serviceWorker = true } = {}) {
|
|
181
|
+
if (!existsSync(dist) || !statSync(dist).isDirectory())
|
|
182
|
+
throw new PwaError(`${dist} is not a directory; run expo export first`);
|
|
183
|
+
const manifestName = findManifest(dist);
|
|
184
|
+
if (!manifestName)
|
|
185
|
+
throw new PwaError(
|
|
186
|
+
`${dist} has no web app manifest (${MANIFEST_NAMES.join(', ')}); add public/manifest.json`,
|
|
187
|
+
);
|
|
188
|
+
let manifest;
|
|
189
|
+
try {
|
|
190
|
+
manifest = JSON.parse(readFileSync(join(dist, manifestName), 'utf8'));
|
|
191
|
+
} catch (error) {
|
|
192
|
+
throw new PwaError(`${manifestName} is not valid JSON: ${error.message}`);
|
|
193
|
+
}
|
|
194
|
+
const { errors, warnings } = validateManifest(manifest, dist);
|
|
195
|
+
if (errors.length > 0)
|
|
196
|
+
throw new PwaError(`${manifestName} cannot make the app installable: ${errors.join('; ')}`);
|
|
197
|
+
|
|
198
|
+
const pages = htmlFiles(dist);
|
|
199
|
+
if (pages.length === 0) throw new PwaError(`${dist} has no HTML page`);
|
|
200
|
+
const wanted = wantedTags(manifestName, manifest, dist, { serviceWorker });
|
|
201
|
+
const updated = [];
|
|
202
|
+
for (const page of pages) {
|
|
203
|
+
let next;
|
|
204
|
+
try {
|
|
205
|
+
next = injectHead(readFileSync(page, 'utf8'), wanted);
|
|
206
|
+
} catch (error) {
|
|
207
|
+
throw new PwaError(`${relative(dist, page)}: ${error.message}`);
|
|
208
|
+
}
|
|
209
|
+
if (next !== null) {
|
|
210
|
+
writeFileSync(page, next);
|
|
211
|
+
updated.push(relative(dist, page));
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
let worker = null;
|
|
216
|
+
if (serviceWorker) {
|
|
217
|
+
const version = exportVersion(pages);
|
|
218
|
+
const base = readFileSync(join(WEB_DIR, SW_BASE), 'utf8').replace(
|
|
219
|
+
/__OXY_SW_VERSION__/g,
|
|
220
|
+
version,
|
|
221
|
+
);
|
|
222
|
+
writeFileSync(join(dist, SW_BASE), base);
|
|
223
|
+
writeFileSync(join(dist, SW_REGISTER), readFileSync(join(WEB_DIR, SW_REGISTER)));
|
|
224
|
+
if (existsSync(join(dist, 'sw.js'))) {
|
|
225
|
+
const own = readFileSync(join(dist, 'sw.js'), 'utf8');
|
|
226
|
+
worker = own.includes(SW_BASE) ? 'app (imports the base)' : 'app (does not import the base)';
|
|
227
|
+
if (!own.includes(SW_BASE))
|
|
228
|
+
warnings.push(
|
|
229
|
+
`sw.js does not import /${SW_BASE}, so it has no offline shell; add importScripts('/${SW_BASE}') unless it caches on its own`,
|
|
230
|
+
);
|
|
231
|
+
} else {
|
|
232
|
+
writeFileSync(join(dist, 'sw.js'), OWN_WORKER);
|
|
233
|
+
worker = 'base';
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return { manifest: manifestName, pages: pages.length, updated, worker, warnings };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
module.exports = {
|
|
240
|
+
PwaError,
|
|
241
|
+
makeInstallable,
|
|
242
|
+
validateManifest,
|
|
243
|
+
injectHead,
|
|
244
|
+
wantedTags,
|
|
245
|
+
SW_BASE,
|
|
246
|
+
SW_REGISTER,
|
|
247
|
+
};
|