@tylix/pwa 0.0.0-stage → 2.1.1
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/LICENSE +21 -0
- package/README.md +119 -2
- package/assets/apple-touch-icon.png +0 -0
- package/assets/pwa-192.png +0 -0
- package/assets/pwa-512.png +0 -0
- package/assets/pwa-maskable-512.png +0 -0
- package/package.json +91 -4
- package/src/angular.d.ts +9 -0
- package/src/angular.js +20 -0
- package/src/client.d.ts +49 -0
- package/src/client.js +44 -0
- package/src/index.d.ts +75 -0
- package/src/index.js +359 -0
- package/src/react.d.ts +7 -0
- package/src/react.js +22 -0
- package/src/runtime.js +161 -0
- package/src/svelte.d.ts +8 -0
- package/src/svelte.js +13 -0
- package/src/vue.d.ts +9 -0
- package/src/vue.js +22 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mbiyrukzz
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,120 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tylix/pwa
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Make any web app an installable **progressive web app** that keeps working
|
|
4
|
+
offline: the web manifest, a generated service worker with safe caching,
|
|
5
|
+
update and install prompts, and helpers for React, Vue, Svelte and
|
|
6
|
+
Angular. No dependencies.
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
npm install @tylix/pwa
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## In a Tylix app
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
tylix make:pwa
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
That adds `pwa` to `tylix.config`, icons and an offline page to
|
|
19
|
+
`public/`, and an install/update prompt (a `.tyx` component and `Pwa`
|
|
20
|
+
capability, or a React, Vue, Svelte or Angular component). Tylix then
|
|
21
|
+
serves `/manifest.webmanifest` and `/sw.js` and puts the tags in every
|
|
22
|
+
page. It works the same for `.tyx` pages and for React, Vue, Svelte and
|
|
23
|
+
Angular, server-rendered or not.
|
|
24
|
+
|
|
25
|
+
```js
|
|
26
|
+
// tylix.config
|
|
27
|
+
pwa: {
|
|
28
|
+
name: 'Acme',
|
|
29
|
+
shortName: 'Acme',
|
|
30
|
+
themeColor: '#0034CA',
|
|
31
|
+
backgroundColor: '#ffffff',
|
|
32
|
+
// optional:
|
|
33
|
+
pages: 'network-only', // or 'network-first' (see Caching)
|
|
34
|
+
exclude: [/^\/admin\//], // paths the worker never touches
|
|
35
|
+
runtimeCaching: [{ match: /^\/uploads\//, strategy: 'cache-first', maxEntries: 60 }],
|
|
36
|
+
shortcuts: [{ name: 'New post', url: '/dashboard?new=1' }],
|
|
37
|
+
dev: false, // register in development too
|
|
38
|
+
}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
`pwa: true` uses every default (the name comes from `app.name`).
|
|
42
|
+
|
|
43
|
+
The worker only runs in production (`tylix build`, `tylix start`). In
|
|
44
|
+
development `/sw.js` is a worker that removes itself and its caches, so a
|
|
45
|
+
production run on the same port never serves you stale files.
|
|
46
|
+
|
|
47
|
+
Each deploy whose files changed is a new version: open pages get "A new
|
|
48
|
+
version is ready" and switch when the user clicks Reload.
|
|
49
|
+
|
|
50
|
+
## Caching
|
|
51
|
+
|
|
52
|
+
| Request | Strategy |
|
|
53
|
+
| --- | --- |
|
|
54
|
+
| Precached files (`public/` top level, the built `/assets/` bundle) | cache first, refreshed per version |
|
|
55
|
+
| Page navigations | network only, the offline page when offline (default) |
|
|
56
|
+
| Other scripts, styles, fonts, images | stale-while-revalidate |
|
|
57
|
+
| `/api/`, `/_tylix/`, dev tools, `/sw.js`, the manifest | never touched |
|
|
58
|
+
| Your `runtimeCaching` rules | as configured |
|
|
59
|
+
|
|
60
|
+
Pages are not cached by default on purpose: a page can hold the signed-in
|
|
61
|
+
user's data (server-rendered sessions do), and a cached copy would be
|
|
62
|
+
shown to the next person on that device. `pages: 'network-first'` caches
|
|
63
|
+
them anyway, for public sites.
|
|
64
|
+
|
|
65
|
+
Offline visitors get `public/offline.html` (what `make:pwa` writes), or a
|
|
66
|
+
built-in page in your theme colour.
|
|
67
|
+
|
|
68
|
+
## In the browser
|
|
69
|
+
|
|
70
|
+
```js
|
|
71
|
+
import { pwa } from '@tylix/pwa/client'
|
|
72
|
+
|
|
73
|
+
const app = pwa() // the shared instance (Tylix already started it)
|
|
74
|
+
app.subscribe((s) => {
|
|
75
|
+
s.installable // the browser offers installation
|
|
76
|
+
s.updateAvailable // a new version is waiting
|
|
77
|
+
s.offlineReady // first install done
|
|
78
|
+
s.online
|
|
79
|
+
s.installed // running as an installed app
|
|
80
|
+
})
|
|
81
|
+
await app.install() // 'accepted' | 'dismissed' | 'unavailable'
|
|
82
|
+
app.update() // switch to the new version and reload
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
| | |
|
|
86
|
+
| --- | --- |
|
|
87
|
+
| React | `const { installable, updateAvailable, install, update } = usePwa()` from `@tylix/pwa/react` |
|
|
88
|
+
| Vue | `const { state, install, update } = usePwa()` from `@tylix/pwa/vue` |
|
|
89
|
+
| Svelte | `import { pwa } from '@tylix/pwa/svelte'` then `$pwa.updateAvailable`, `pwa.update()` |
|
|
90
|
+
| Angular | `pwa = injectPwa()` from `@tylix/pwa/angular` then `pwa.state().updateAvailable` |
|
|
91
|
+
| `.tyx` pages | the `Pwa` capability: `Pwa.installable`, `Pwa.install()`, `Pwa.update()` |
|
|
92
|
+
|
|
93
|
+
On the server (SSR) these return an inert state, so pages render the same
|
|
94
|
+
there and in the browser.
|
|
95
|
+
|
|
96
|
+
## Without Tylix
|
|
97
|
+
|
|
98
|
+
```js
|
|
99
|
+
import { manifest, serviceWorker, headTags } from '@tylix/pwa'
|
|
100
|
+
|
|
101
|
+
const options = { name: 'Acme', themeColor: '#0034CA', version: process.env.BUILD_ID, precache: ['/app.css', '/app.js'] }
|
|
102
|
+
|
|
103
|
+
app.get('/manifest.webmanifest', (req, res) => res.type('application/manifest+json').send(JSON.stringify(manifest(options))))
|
|
104
|
+
app.get('/sw.js', (req, res) => res.type('text/javascript').set('Cache-Control', 'no-cache').send(serviceWorker(options)))
|
|
105
|
+
// and headTags(options) inside <head> of every page
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
`offlinePage(options)` returns the built-in offline page and
|
|
109
|
+
`devServiceWorker()` the self-removing worker.
|
|
110
|
+
|
|
111
|
+
## Icons
|
|
112
|
+
|
|
113
|
+
Browsers offer installation once the manifest has a 192px and a 512px
|
|
114
|
+
PNG icon. `make:pwa` copies the Tylix mark (`pwa-192.png`, `pwa-512.png`,
|
|
115
|
+
`pwa-maskable-512.png`, `apple-touch-icon.png`): replace them with your
|
|
116
|
+
own. A maskable icon keeps its artwork inside the middle 80%.
|
|
117
|
+
|
|
118
|
+
## License
|
|
119
|
+
|
|
120
|
+
MIT
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,93 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tylix/pwa",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "2.1.1",
|
|
4
|
+
"description": "Make any web app an installable, offline-ready PWA: web manifest, a generated service worker with safe caching strategies, update and install prompts, and React, Vue, Svelte and Angular helpers. Built into Tylix with pwa: true. No dependencies.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Mbiyrukzz",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"keywords": [
|
|
9
|
+
"pwa",
|
|
10
|
+
"progressive-web-app",
|
|
11
|
+
"service-worker",
|
|
12
|
+
"offline",
|
|
13
|
+
"manifest",
|
|
14
|
+
"install",
|
|
15
|
+
"react",
|
|
16
|
+
"vue",
|
|
17
|
+
"svelte",
|
|
18
|
+
"angular",
|
|
19
|
+
"tylix"
|
|
20
|
+
],
|
|
21
|
+
"homepage": "https://github.com/Mbiyrukzz/tylix/tree/main/packages/pwa#readme",
|
|
22
|
+
"repository": {
|
|
23
|
+
"type": "git",
|
|
24
|
+
"url": "git+https://github.com/Mbiyrukzz/tylix.git",
|
|
25
|
+
"directory": "packages/pwa"
|
|
26
|
+
},
|
|
27
|
+
"bugs": {
|
|
28
|
+
"url": "https://github.com/Mbiyrukzz/tylix/issues"
|
|
29
|
+
},
|
|
30
|
+
"engines": {
|
|
31
|
+
"node": ">=18"
|
|
32
|
+
},
|
|
33
|
+
"main": "./src/index.js",
|
|
34
|
+
"types": "./src/index.d.ts",
|
|
35
|
+
"exports": {
|
|
36
|
+
".": {
|
|
37
|
+
"types": "./src/index.d.ts",
|
|
38
|
+
"default": "./src/index.js"
|
|
39
|
+
},
|
|
40
|
+
"./client": {
|
|
41
|
+
"types": "./src/client.d.ts",
|
|
42
|
+
"default": "./src/client.js"
|
|
43
|
+
},
|
|
44
|
+
"./react": {
|
|
45
|
+
"types": "./src/react.d.ts",
|
|
46
|
+
"default": "./src/react.js"
|
|
47
|
+
},
|
|
48
|
+
"./vue": {
|
|
49
|
+
"types": "./src/vue.d.ts",
|
|
50
|
+
"default": "./src/vue.js"
|
|
51
|
+
},
|
|
52
|
+
"./svelte": {
|
|
53
|
+
"types": "./src/svelte.d.ts",
|
|
54
|
+
"default": "./src/svelte.js"
|
|
55
|
+
},
|
|
56
|
+
"./angular": {
|
|
57
|
+
"types": "./src/angular.d.ts",
|
|
58
|
+
"default": "./src/angular.js"
|
|
59
|
+
},
|
|
60
|
+
"./assets/*": "./assets/*",
|
|
61
|
+
"./package.json": "./package.json"
|
|
62
|
+
},
|
|
63
|
+
"sideEffects": false,
|
|
64
|
+
"files": [
|
|
65
|
+
"src",
|
|
66
|
+
"assets",
|
|
67
|
+
"!**/*.test.js",
|
|
68
|
+
"README.md",
|
|
69
|
+
"LICENSE"
|
|
70
|
+
],
|
|
71
|
+
"publishConfig": {
|
|
72
|
+
"access": "public"
|
|
73
|
+
},
|
|
74
|
+
"scripts": {
|
|
75
|
+
"test": "node --test test/*.test.js"
|
|
76
|
+
},
|
|
77
|
+
"peerDependencies": {
|
|
78
|
+
"@angular/core": ">=17.0.0",
|
|
79
|
+
"react": ">=18.0.0",
|
|
80
|
+
"vue": ">=3.3.0"
|
|
81
|
+
},
|
|
82
|
+
"peerDependenciesMeta": {
|
|
83
|
+
"@angular/core": {
|
|
84
|
+
"optional": true
|
|
85
|
+
},
|
|
86
|
+
"react": {
|
|
87
|
+
"optional": true
|
|
88
|
+
},
|
|
89
|
+
"vue": {
|
|
90
|
+
"optional": true
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
package/src/angular.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Signal } from '@angular/core'
|
|
2
|
+
import type { PwaState, RuntimeOptions } from './client.js'
|
|
3
|
+
export function injectPwa(options?: RuntimeOptions): {
|
|
4
|
+
state: Signal<PwaState>
|
|
5
|
+
install(): Promise<'accepted' | 'dismissed' | 'unavailable'>
|
|
6
|
+
update(): boolean
|
|
7
|
+
dismissUpdate(): void
|
|
8
|
+
dismissOfflineReady(): void
|
|
9
|
+
}
|
package/src/angular.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Angular: the PWA state as a signal.
|
|
2
|
+
//
|
|
3
|
+
// pwa = injectPwa()
|
|
4
|
+
// @if (pwa.state().updateAvailable) { <button (click)="pwa.update()">Reload</button> }
|
|
5
|
+
import { DestroyRef, inject, signal } from '@angular/core'
|
|
6
|
+
import { pwa } from './client.js'
|
|
7
|
+
|
|
8
|
+
export function injectPwa(options) {
|
|
9
|
+
const instance = pwa(options)
|
|
10
|
+
const state = signal(instance.state)
|
|
11
|
+
const stop = instance.subscribe((next) => state.set(next))
|
|
12
|
+
inject(DestroyRef, { optional: true })?.onDestroy(stop)
|
|
13
|
+
return {
|
|
14
|
+
state: state.asReadonly(),
|
|
15
|
+
install: () => instance.install(),
|
|
16
|
+
update: () => instance.update(),
|
|
17
|
+
dismissUpdate: () => instance.dismissUpdate(),
|
|
18
|
+
dismissOfflineReady: () => instance.dismissOfflineReady(),
|
|
19
|
+
}
|
|
20
|
+
}
|
package/src/client.d.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
export interface PwaState {
|
|
2
|
+
/** The browser supports service workers. */
|
|
3
|
+
supported: boolean
|
|
4
|
+
registered: boolean
|
|
5
|
+
/** The first install finished: the app now works offline. */
|
|
6
|
+
offlineReady: boolean
|
|
7
|
+
/** A new version is installed and waiting; update() switches to it. */
|
|
8
|
+
updateAvailable: boolean
|
|
9
|
+
/** The browser offered installation; install() shows its dialog. */
|
|
10
|
+
installable: boolean
|
|
11
|
+
/** Running as an installed app. */
|
|
12
|
+
installed: boolean
|
|
13
|
+
online: boolean
|
|
14
|
+
error: string | null
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface Pwa {
|
|
18
|
+
readonly state: PwaState
|
|
19
|
+
/** Calls fn now and on every change. Returns the unsubscribe function (Svelte store contract). */
|
|
20
|
+
subscribe(fn: (state: PwaState) => void): () => void
|
|
21
|
+
install(): Promise<'accepted' | 'dismissed' | 'unavailable'>
|
|
22
|
+
/** Activates the waiting version and reloads. False when none is waiting. */
|
|
23
|
+
update(): boolean
|
|
24
|
+
dismissUpdate(): void
|
|
25
|
+
dismissOfflineReady(): void
|
|
26
|
+
register(): Promise<ServiceWorkerRegistration | null>
|
|
27
|
+
unregister(): Promise<boolean>
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface RuntimeOptions {
|
|
31
|
+
/** Default "/sw.js". */
|
|
32
|
+
url?: string
|
|
33
|
+
/** Default "/". */
|
|
34
|
+
scope?: string
|
|
35
|
+
/** Register the worker. Default true. */
|
|
36
|
+
register?: boolean
|
|
37
|
+
/** Milliseconds between update checks (0: never). Default one hour. */
|
|
38
|
+
checkEvery?: number
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The app's PWA instance (shared, created on first use). */
|
|
42
|
+
export function pwa(options?: RuntimeOptions): Pwa
|
|
43
|
+
export function installPwaRuntime(win: Window, options?: RuntimeOptions): Pwa
|
|
44
|
+
|
|
45
|
+
declare global {
|
|
46
|
+
interface Window {
|
|
47
|
+
__TYLIX_PWA__?: Pwa
|
|
48
|
+
}
|
|
49
|
+
}
|
package/src/client.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// The PWA state in the browser, for any framework:
|
|
2
|
+
//
|
|
3
|
+
// import { pwa } from '@tylix/pwa/client'
|
|
4
|
+
// pwa().subscribe((s) => console.log(s.installable, s.updateAvailable, s.online))
|
|
5
|
+
// await pwa().install() // the browser's install dialog
|
|
6
|
+
// pwa().update() // switch to the new version and reload
|
|
7
|
+
//
|
|
8
|
+
// In a Tylix app the server already started it (config pwa); this returns
|
|
9
|
+
// that same instance. Elsewhere the first call starts it and registers
|
|
10
|
+
// /sw.js (pass options to change that).
|
|
11
|
+
import { installPwaRuntime } from './runtime.js'
|
|
12
|
+
|
|
13
|
+
const SERVER_STATE = Object.freeze({
|
|
14
|
+
supported: false,
|
|
15
|
+
registered: false,
|
|
16
|
+
offlineReady: false,
|
|
17
|
+
updateAvailable: false,
|
|
18
|
+
installable: false,
|
|
19
|
+
installed: false,
|
|
20
|
+
online: true,
|
|
21
|
+
error: null,
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
// During server rendering there is no window: a fixed, inert stand-in.
|
|
25
|
+
const inert = {
|
|
26
|
+
state: SERVER_STATE,
|
|
27
|
+
subscribe(fn) {
|
|
28
|
+
fn(SERVER_STATE)
|
|
29
|
+
return () => {}
|
|
30
|
+
},
|
|
31
|
+
install: async () => 'unavailable',
|
|
32
|
+
update: () => false,
|
|
33
|
+
dismissUpdate() {},
|
|
34
|
+
dismissOfflineReady() {},
|
|
35
|
+
register: async () => null,
|
|
36
|
+
unregister: async () => false,
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function pwa(options) {
|
|
40
|
+
if (typeof window === 'undefined') return inert
|
|
41
|
+
return installPwaRuntime(window, options)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export { installPwaRuntime }
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { RuntimeOptions } from './client.js'
|
|
2
|
+
export type { Pwa, PwaState, RuntimeOptions } from './client.js'
|
|
3
|
+
export { installPwaRuntime } from './client.js'
|
|
4
|
+
|
|
5
|
+
export interface ManifestIcon {
|
|
6
|
+
src: string
|
|
7
|
+
sizes: string
|
|
8
|
+
type?: string
|
|
9
|
+
purpose?: 'any' | 'maskable' | 'monochrome' | string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface RuntimeCachingRule {
|
|
13
|
+
/** A RegExp or regex source, tested on the path (same origin) or full URL. */
|
|
14
|
+
match: RegExp | string
|
|
15
|
+
strategy: 'cache-first' | 'stale-while-revalidate' | 'network-first' | 'network-only'
|
|
16
|
+
maxEntries?: number
|
|
17
|
+
maxAgeSeconds?: number
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface PwaOptions {
|
|
21
|
+
name?: string
|
|
22
|
+
shortName?: string
|
|
23
|
+
description?: string
|
|
24
|
+
lang?: string
|
|
25
|
+
startUrl?: string
|
|
26
|
+
scope?: string
|
|
27
|
+
display?: 'standalone' | 'fullscreen' | 'minimal-ui' | 'browser'
|
|
28
|
+
orientation?: string
|
|
29
|
+
themeColor?: string
|
|
30
|
+
backgroundColor?: string
|
|
31
|
+
icons?: ManifestIcon[]
|
|
32
|
+
appleTouchIcon?: string | null
|
|
33
|
+
shortcuts?: { name: string; url: string; short_name?: string; description?: string; icons?: ManifestIcon[] }[]
|
|
34
|
+
screenshots?: { src: string; sizes: string; type?: string; form_factor?: 'wide' | 'narrow'; label?: string }[]
|
|
35
|
+
categories?: string[]
|
|
36
|
+
/** Extra manifest fields, merged last. */
|
|
37
|
+
manifest?: Record<string, unknown>
|
|
38
|
+
|
|
39
|
+
swUrl?: string
|
|
40
|
+
/** Changes when the precached files change; a new version prompts an update. */
|
|
41
|
+
version?: string
|
|
42
|
+
/** Static files cached on install. Not pages. */
|
|
43
|
+
precache?: string[]
|
|
44
|
+
/** Path of the offline page, or null for the built-in one. Default "/offline.html". */
|
|
45
|
+
offline?: string | null
|
|
46
|
+
/** "network-only" (default) or "network-first" for page navigations. */
|
|
47
|
+
pages?: 'network-only' | 'network-first'
|
|
48
|
+
/** Paths the worker never touches, besides /api/ and dev tools. */
|
|
49
|
+
exclude?: (RegExp | string)[]
|
|
50
|
+
runtimeCaching?: RuntimeCachingRule[]
|
|
51
|
+
/** Register the worker in development too. */
|
|
52
|
+
dev?: boolean
|
|
53
|
+
/** Milliseconds between update checks. Default one hour. */
|
|
54
|
+
checkEvery?: number
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export type ResolvedPwaOptions = Required<Omit<PwaOptions, 'orientation' | 'shortcuts' | 'screenshots' | 'categories' | 'exclude' | 'runtimeCaching'>> &
|
|
58
|
+
Pick<PwaOptions, 'orientation' | 'shortcuts' | 'screenshots' | 'categories'> & {
|
|
59
|
+
exclude: string[]
|
|
60
|
+
runtimeCaching: (RuntimeCachingRule & { match: string })[]
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export const DEFAULT_EXCLUDE: readonly string[]
|
|
64
|
+
export function resolveOptions(options?: PwaOptions | true): ResolvedPwaOptions
|
|
65
|
+
export function manifest(options?: PwaOptions | true): Record<string, unknown>
|
|
66
|
+
/** <link rel="manifest">, theme colour, iOS tags, and the runtime script. */
|
|
67
|
+
export function headTags(options?: PwaOptions | true, opts?: { register?: boolean }): string
|
|
68
|
+
export function runtimeScript(options?: PwaOptions | true, opts?: { register?: boolean }): string
|
|
69
|
+
/** The service worker's source, to serve at /sw.js with Cache-Control: no-cache. */
|
|
70
|
+
export function serviceWorker(options?: PwaOptions | true): string
|
|
71
|
+
/** A worker that removes itself and the caches (for development). */
|
|
72
|
+
export function devServiceWorker(): string
|
|
73
|
+
/** A self-contained offline page. */
|
|
74
|
+
export function offlinePage(options?: PwaOptions | true): string
|
|
75
|
+
export type { RuntimeOptions as ClientOptions }
|
package/src/index.js
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
// @tylix/pwa: make any web app installable and usable offline.
|
|
2
|
+
//
|
|
3
|
+
// The server side, framework-agnostic: build the web manifest, the service
|
|
4
|
+
// worker and the <head> tags from one options object, then serve them from
|
|
5
|
+
// whatever server you use. Tylix does all of it for you (pwa in
|
|
6
|
+
// tylix.config); elsewhere:
|
|
7
|
+
//
|
|
8
|
+
// import { manifest, serviceWorker, headTags } from '@tylix/pwa'
|
|
9
|
+
// const options = { name: 'Acme', themeColor: '#0034CA', precache: ['/app.css', '/app.js'] }
|
|
10
|
+
// app.get('/manifest.webmanifest', (req, res) => res.type('application/manifest+json').send(JSON.stringify(manifest(options))))
|
|
11
|
+
// app.get('/sw.js', (req, res) => res.type('text/javascript').set('Cache-Control', 'no-cache').send(serviceWorker(options)))
|
|
12
|
+
// // and headTags(options) inside <head> of every page
|
|
13
|
+
import { installPwaRuntime } from './runtime.js'
|
|
14
|
+
|
|
15
|
+
export { installPwaRuntime }
|
|
16
|
+
|
|
17
|
+
export const DEFAULT_EXCLUDE = Object.freeze([
|
|
18
|
+
'^/api/',
|
|
19
|
+
'^/_tylix/',
|
|
20
|
+
'^/@',
|
|
21
|
+
'^/__',
|
|
22
|
+
'^/node_modules/',
|
|
23
|
+
'^/sw\\.js$',
|
|
24
|
+
'^/manifest\\.webmanifest$',
|
|
25
|
+
])
|
|
26
|
+
|
|
27
|
+
const DEFAULT_ICONS = Object.freeze([
|
|
28
|
+
{ src: '/pwa-192.png', sizes: '192x192', type: 'image/png', purpose: 'any' },
|
|
29
|
+
{ src: '/pwa-512.png', sizes: '512x512', type: 'image/png', purpose: 'any' },
|
|
30
|
+
{ src: '/pwa-maskable-512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' },
|
|
31
|
+
])
|
|
32
|
+
|
|
33
|
+
const RESOLVED = Symbol.for('tylix.pwa.resolved')
|
|
34
|
+
|
|
35
|
+
// Fills in defaults. Accepts true (all defaults) or an options object.
|
|
36
|
+
// Resolving twice is harmless.
|
|
37
|
+
export function resolveOptions(input = {}) {
|
|
38
|
+
if (input && input[RESOLVED]) return input
|
|
39
|
+
const o = input === true || !input ? {} : input
|
|
40
|
+
const name = o.name ?? 'Tylix app'
|
|
41
|
+
return {
|
|
42
|
+
name,
|
|
43
|
+
shortName: o.shortName ?? (name.length > 12 ? name.split(/\s+/)[0].slice(0, 12) : name),
|
|
44
|
+
description: o.description ?? '',
|
|
45
|
+
lang: o.lang ?? 'en',
|
|
46
|
+
startUrl: o.startUrl ?? '/',
|
|
47
|
+
scope: o.scope ?? '/',
|
|
48
|
+
display: o.display ?? 'standalone',
|
|
49
|
+
orientation: o.orientation,
|
|
50
|
+
themeColor: o.themeColor ?? '#0034CA',
|
|
51
|
+
backgroundColor: o.backgroundColor ?? '#ffffff',
|
|
52
|
+
icons: o.icons ?? DEFAULT_ICONS,
|
|
53
|
+
appleTouchIcon: o.appleTouchIcon ?? '/apple-touch-icon.png',
|
|
54
|
+
shortcuts: o.shortcuts,
|
|
55
|
+
screenshots: o.screenshots,
|
|
56
|
+
categories: o.categories,
|
|
57
|
+
// Extra manifest fields, merged last.
|
|
58
|
+
manifest: o.manifest ?? {},
|
|
59
|
+
|
|
60
|
+
// Service worker
|
|
61
|
+
swUrl: o.swUrl ?? '/sw.js',
|
|
62
|
+
version: o.version ?? '1',
|
|
63
|
+
// Static files to cache on install. Not pages: a page can hold the
|
|
64
|
+
// signed-in user's data, and would be served to the next person.
|
|
65
|
+
precache: o.precache ?? [],
|
|
66
|
+
offline: o.offline === undefined ? '/offline.html' : o.offline,
|
|
67
|
+
// How page navigations are cached:
|
|
68
|
+
// 'network-only' always from the network; the offline page when it fails (default,
|
|
69
|
+
// and right for pages that show a signed-in user)
|
|
70
|
+
// 'network-first' from the network, falling back to the last copy seen
|
|
71
|
+
pages: o.pages ?? 'network-only',
|
|
72
|
+
exclude: [...DEFAULT_EXCLUDE, ...(o.exclude ?? []).map((p) => (p instanceof RegExp ? p.source : String(p)))],
|
|
73
|
+
// [{ match: '^/images/', strategy: 'cache-first' | 'stale-while-revalidate' | 'network-first' | 'network-only', maxEntries, maxAgeSeconds }]
|
|
74
|
+
runtimeCaching: (o.runtimeCaching ?? []).map((r) => ({
|
|
75
|
+
...r,
|
|
76
|
+
match: r.match instanceof RegExp ? r.match.source : String(r.match),
|
|
77
|
+
})),
|
|
78
|
+
// Register the worker in development too (off by default: it caches
|
|
79
|
+
// files you are editing).
|
|
80
|
+
dev: o.dev === true,
|
|
81
|
+
checkEvery: o.checkEvery ?? 3600000,
|
|
82
|
+
[RESOLVED]: true,
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function manifest(input) {
|
|
87
|
+
const o = resolveOptions(input)
|
|
88
|
+
const out = {
|
|
89
|
+
id: o.startUrl,
|
|
90
|
+
name: o.name,
|
|
91
|
+
short_name: o.shortName,
|
|
92
|
+
description: o.description || undefined,
|
|
93
|
+
lang: o.lang,
|
|
94
|
+
start_url: o.startUrl,
|
|
95
|
+
scope: o.scope,
|
|
96
|
+
display: o.display,
|
|
97
|
+
orientation: o.orientation,
|
|
98
|
+
theme_color: o.themeColor,
|
|
99
|
+
background_color: o.backgroundColor,
|
|
100
|
+
icons: o.icons,
|
|
101
|
+
shortcuts: o.shortcuts,
|
|
102
|
+
screenshots: o.screenshots,
|
|
103
|
+
categories: o.categories,
|
|
104
|
+
...o.manifest,
|
|
105
|
+
}
|
|
106
|
+
return JSON.parse(JSON.stringify(out)) // drops undefined
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const escapeAttr = (value) => String(value).replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<')
|
|
110
|
+
|
|
111
|
+
// The tags for <head>: manifest link, theme colour, iOS meta, and the
|
|
112
|
+
// script that registers the worker and tracks install/update state.
|
|
113
|
+
export function headTags(input, { register = true } = {}) {
|
|
114
|
+
const o = resolveOptions(input)
|
|
115
|
+
const runtime = runtimeScript(o, { register })
|
|
116
|
+
return [
|
|
117
|
+
`<link rel="manifest" href="/manifest.webmanifest">`,
|
|
118
|
+
`<meta name="theme-color" content="${escapeAttr(o.themeColor)}">`,
|
|
119
|
+
`<meta name="mobile-web-app-capable" content="yes">`,
|
|
120
|
+
`<meta name="apple-mobile-web-app-capable" content="yes">`,
|
|
121
|
+
`<meta name="apple-mobile-web-app-title" content="${escapeAttr(o.shortName)}">`,
|
|
122
|
+
`<meta name="apple-mobile-web-app-status-bar-style" content="default">`,
|
|
123
|
+
o.appleTouchIcon ? `<link rel="apple-touch-icon" href="${escapeAttr(o.appleTouchIcon)}">` : '',
|
|
124
|
+
runtime,
|
|
125
|
+
]
|
|
126
|
+
.filter(Boolean)
|
|
127
|
+
.join('\n ')
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export function runtimeScript(input, { register = true } = {}) {
|
|
131
|
+
const o = resolveOptions(input)
|
|
132
|
+
const config = JSON.stringify({ url: o.swUrl, scope: o.scope, register, checkEvery: o.checkEvery }).replace(/</g, '\\u003c')
|
|
133
|
+
return `<script>(${installPwaRuntime.toString()})(window, ${config});</script>`
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// A small, self-contained offline page, used when the app has no
|
|
137
|
+
// /offline.html of its own. Follows the system light/dark preference.
|
|
138
|
+
export function offlinePage(input) {
|
|
139
|
+
const o = resolveOptions(input)
|
|
140
|
+
const name = escapeAttr(o.name)
|
|
141
|
+
return `<!doctype html>
|
|
142
|
+
<html lang="${escapeAttr(o.lang)}">
|
|
143
|
+
<head>
|
|
144
|
+
<meta charset="utf-8">
|
|
145
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
146
|
+
<title>Offline · ${name}</title>
|
|
147
|
+
<meta name="theme-color" content="${escapeAttr(o.themeColor)}">
|
|
148
|
+
<style>
|
|
149
|
+
:root { --bg: #f3f2f6; --panel: #fff; --ink: #17151c; --muted: #6b6878; --line: #dedbe6; --brand: ${escapeAttr(o.themeColor)}; color-scheme: light dark; }
|
|
150
|
+
@media (prefers-color-scheme: dark) { :root { --bg: #17161c; --panel: #211f27; --ink: #ecebf1; --muted: #9592a3; --line: #34313d; } }
|
|
151
|
+
* { box-sizing: border-box; }
|
|
152
|
+
body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 24px; background: var(--bg); color: var(--ink);
|
|
153
|
+
font: 15px/1.6 "Inter", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
|
|
154
|
+
main { max-width: 420px; width: 100%; text-align: center; background: var(--panel); border: 1px solid var(--line); border-radius: 16px; padding: 40px 32px; }
|
|
155
|
+
.icon { width: 56px; height: 56px; margin: 0 auto 20px; border-radius: 16px; display: grid; place-items: center; background: color-mix(in srgb, var(--brand) 12%, transparent); color: var(--brand); }
|
|
156
|
+
h1 { margin: 0 0 8px; font-size: 20px; letter-spacing: -0.01em; }
|
|
157
|
+
p { margin: 0 0 24px; color: var(--muted); }
|
|
158
|
+
button { font: inherit; font-weight: 600; font-size: 14px; border: 0; border-radius: 10px; padding: 10px 20px; background: var(--brand); color: #fff; cursor: pointer; }
|
|
159
|
+
small { display: block; margin-top: 16px; color: var(--muted); font-size: 12px; }
|
|
160
|
+
</style>
|
|
161
|
+
</head>
|
|
162
|
+
<body>
|
|
163
|
+
<main>
|
|
164
|
+
<div class="icon" aria-hidden="true"><svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 2l20 20"/><path d="M8.5 16.5a5 5 0 0 1 7 0"/><path d="M2 8.82a15 15 0 0 1 4.17-2.65"/><path d="M10.66 5c4.01-.36 8.14.9 11.34 3.76"/><path d="M16.85 11.25a10 10 0 0 1 2.22 1.68"/><path d="M5 13a10 10 0 0 1 5.24-2.76"/><path d="M12 20h.01"/></svg></div>
|
|
165
|
+
<h1>You’re offline</h1>
|
|
166
|
+
<p>${name} can’t reach the network right now. Check your connection; this page reloads by itself when you’re back.</p>
|
|
167
|
+
<button type="button" onclick="location.reload()">Try again</button>
|
|
168
|
+
<small>Pages you opened before may still work.</small>
|
|
169
|
+
</main>
|
|
170
|
+
<script>addEventListener('online', function () { location.reload() })</script>
|
|
171
|
+
</body>
|
|
172
|
+
</html>`
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// The service worker source. Strategies:
|
|
176
|
+
// precached files cache first, refreshed on every new version
|
|
177
|
+
// page navigations network only (default) or network first; the offline page when offline
|
|
178
|
+
// static assets stale-while-revalidate (fingerprinted /assets/ are cache first)
|
|
179
|
+
// excluded paths never touched (the API, dev tools, the worker itself)
|
|
180
|
+
export function serviceWorker(input) {
|
|
181
|
+
const o = resolveOptions(input)
|
|
182
|
+
const config = {
|
|
183
|
+
version: String(o.version),
|
|
184
|
+
precache: [...new Set(o.precache)],
|
|
185
|
+
offline: o.offline || null,
|
|
186
|
+
builtinOffline: o.offline ? null : offlinePage(o),
|
|
187
|
+
pages: o.pages,
|
|
188
|
+
exclude: o.exclude,
|
|
189
|
+
runtime: o.runtimeCaching,
|
|
190
|
+
}
|
|
191
|
+
return `// Generated by @tylix/pwa. Served with Cache-Control: no-cache, so the
|
|
192
|
+
// browser sees each new version on its next check.
|
|
193
|
+
const CONFIG = ${JSON.stringify(config, null, 2)};
|
|
194
|
+
${WORKER_BODY}`
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const WORKER_BODY = String.raw`
|
|
198
|
+
const STATIC = 'tylix-static-' + CONFIG.version;
|
|
199
|
+
const RUNTIME = 'tylix-runtime';
|
|
200
|
+
const PAGES = 'tylix-pages';
|
|
201
|
+
const EXCLUDE = CONFIG.exclude.map((p) => new RegExp(p));
|
|
202
|
+
const RULES = CONFIG.runtime.map((r) => ({ ...r, re: new RegExp(r.match) }));
|
|
203
|
+
const ASSET = /\.(?:js|mjs|css|woff2?|ttf|otf|png|jpe?g|gif|svg|webp|avif|ico)$/i;
|
|
204
|
+
|
|
205
|
+
self.addEventListener('install', (event) => {
|
|
206
|
+
event.waitUntil(
|
|
207
|
+
caches.open(STATIC).then((cache) =>
|
|
208
|
+
Promise.all(
|
|
209
|
+
[...CONFIG.precache, CONFIG.offline]
|
|
210
|
+
.filter(Boolean)
|
|
211
|
+
.map((url) => cache.add(new Request(url, { cache: 'reload' })).catch((err) => console.warn('[pwa] could not precache', url, err))),
|
|
212
|
+
),
|
|
213
|
+
),
|
|
214
|
+
);
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
self.addEventListener('activate', (event) => {
|
|
218
|
+
event.waitUntil(
|
|
219
|
+
caches
|
|
220
|
+
.keys()
|
|
221
|
+
.then((keys) => Promise.all(keys.filter((k) => k.startsWith('tylix-static-') && k !== STATIC).map((k) => caches.delete(k))))
|
|
222
|
+
.then(() => self.clients.claim()),
|
|
223
|
+
);
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
self.addEventListener('message', (event) => {
|
|
227
|
+
if (event.data && event.data.type === 'SKIP_WAITING') self.skipWaiting();
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
function storable(response) {
|
|
231
|
+
if (!response || !response.ok || response.type === 'opaque' || response.redirected) return false;
|
|
232
|
+
const cc = response.headers.get('Cache-Control') || '';
|
|
233
|
+
return !/no-store|private/i.test(cc);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
async function trim(cacheName, maxEntries) {
|
|
237
|
+
if (!maxEntries) return;
|
|
238
|
+
const cache = await caches.open(cacheName);
|
|
239
|
+
const keys = await cache.keys();
|
|
240
|
+
for (let i = 0; i < keys.length - maxEntries; i++) await cache.delete(keys[i]);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function fresh(response, maxAgeSeconds) {
|
|
244
|
+
if (!maxAgeSeconds || !response) return Boolean(response);
|
|
245
|
+
const date = Date.parse(response.headers.get('Date') || '');
|
|
246
|
+
return !date || Date.now() - date < maxAgeSeconds * 1000;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
async function cacheFirst(request, cacheName, rule = {}) {
|
|
250
|
+
const cached = await caches.match(request);
|
|
251
|
+
if (cached && fresh(cached, rule.maxAgeSeconds)) return cached;
|
|
252
|
+
const response = await fetch(request);
|
|
253
|
+
if (storable(response)) {
|
|
254
|
+
const cache = await caches.open(cacheName);
|
|
255
|
+
await cache.put(request, response.clone());
|
|
256
|
+
trim(cacheName, rule.maxEntries);
|
|
257
|
+
}
|
|
258
|
+
return response;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
async function staleWhileRevalidate(request, cacheName, rule = {}) {
|
|
262
|
+
const cache = await caches.open(cacheName);
|
|
263
|
+
const cached = await cache.match(request);
|
|
264
|
+
const network = fetch(request)
|
|
265
|
+
.then((response) => {
|
|
266
|
+
if (storable(response)) {
|
|
267
|
+
cache.put(request, response.clone());
|
|
268
|
+
trim(cacheName, rule.maxEntries || 80);
|
|
269
|
+
}
|
|
270
|
+
return response;
|
|
271
|
+
})
|
|
272
|
+
.catch(() => cached);
|
|
273
|
+
return cached || network;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
async function networkFirst(request, cacheName, rule = {}) {
|
|
277
|
+
try {
|
|
278
|
+
const response = await fetch(request);
|
|
279
|
+
if (storable(response)) {
|
|
280
|
+
const cache = await caches.open(cacheName);
|
|
281
|
+
cache.put(request, response.clone());
|
|
282
|
+
trim(cacheName, rule.maxEntries || 50);
|
|
283
|
+
}
|
|
284
|
+
return response;
|
|
285
|
+
} catch (err) {
|
|
286
|
+
const cached = await caches.match(request);
|
|
287
|
+
if (cached) return cached;
|
|
288
|
+
throw err;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
async function offlineResponse() {
|
|
293
|
+
if (CONFIG.offline) {
|
|
294
|
+
const cached = await caches.match(CONFIG.offline);
|
|
295
|
+
if (cached) return cached;
|
|
296
|
+
}
|
|
297
|
+
return new Response(CONFIG.builtinOffline || '<h1>Offline</h1>', {
|
|
298
|
+
status: 503,
|
|
299
|
+
headers: { 'Content-Type': 'text/html; charset=utf-8' },
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
async function navigate(request) {
|
|
304
|
+
try {
|
|
305
|
+
if (CONFIG.pages === 'network-first') return await networkFirst(request, PAGES);
|
|
306
|
+
return await fetch(request);
|
|
307
|
+
} catch (err) {
|
|
308
|
+
return offlineResponse();
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
self.addEventListener('fetch', (event) => {
|
|
313
|
+
const request = event.request;
|
|
314
|
+
if (request.method !== 'GET') return;
|
|
315
|
+
const url = new URL(request.url);
|
|
316
|
+
const sameOrigin = url.origin === self.location.origin;
|
|
317
|
+
const path = sameOrigin ? url.pathname : url.href;
|
|
318
|
+
if (sameOrigin && EXCLUDE.some((re) => re.test(url.pathname))) return;
|
|
319
|
+
|
|
320
|
+
const rule = RULES.find((r) => r.re.test(path));
|
|
321
|
+
if (rule) {
|
|
322
|
+
if (rule.strategy === 'network-only') return;
|
|
323
|
+
const name = 'tylix-rule-' + rule.match;
|
|
324
|
+
const run = rule.strategy === 'cache-first' ? cacheFirst : rule.strategy === 'network-first' ? networkFirst : staleWhileRevalidate;
|
|
325
|
+
event.respondWith(run(request, name, rule));
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
if (!sameOrigin) return;
|
|
329
|
+
|
|
330
|
+
if (request.mode === 'navigate') {
|
|
331
|
+
event.respondWith(navigate(request));
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
if (CONFIG.precache.includes(url.pathname) || url.pathname.startsWith('/assets/')) {
|
|
335
|
+
event.respondWith(cacheFirst(request, url.pathname.startsWith('/assets/') ? RUNTIME : STATIC));
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
if (ASSET.test(url.pathname)) event.respondWith(staleWhileRevalidate(request, RUNTIME));
|
|
339
|
+
});
|
|
340
|
+
`
|
|
341
|
+
|
|
342
|
+
// Served in development instead of the real worker: it removes any worker
|
|
343
|
+
// a production run left on this origin, so dev always sees fresh files.
|
|
344
|
+
export function devServiceWorker() {
|
|
345
|
+
return `// Development: this worker unregisters itself and clears Tylix caches.
|
|
346
|
+
self.addEventListener('install', () => self.skipWaiting());
|
|
347
|
+
self.addEventListener('activate', (event) => {
|
|
348
|
+
event.waitUntil(
|
|
349
|
+
(async () => {
|
|
350
|
+
const keys = await caches.keys();
|
|
351
|
+
await Promise.all(keys.filter((k) => k.startsWith('tylix-')).map((k) => caches.delete(k)));
|
|
352
|
+
await self.registration.unregister();
|
|
353
|
+
const clients = await self.clients.matchAll({ type: 'window' });
|
|
354
|
+
clients.forEach((client) => client.navigate(client.url));
|
|
355
|
+
})(),
|
|
356
|
+
);
|
|
357
|
+
});
|
|
358
|
+
`
|
|
359
|
+
}
|
package/src/react.d.ts
ADDED
package/src/react.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// React: the PWA state as a hook.
|
|
2
|
+
//
|
|
3
|
+
// const { installable, updateAvailable, online, install, update } = usePwa()
|
|
4
|
+
// {updateAvailable && <button onClick={update}>Reload for the new version</button>}
|
|
5
|
+
import { useSyncExternalStore } from 'react'
|
|
6
|
+
import { pwa } from './client.js'
|
|
7
|
+
|
|
8
|
+
export function usePwa(options) {
|
|
9
|
+
const instance = pwa(options)
|
|
10
|
+
const state = useSyncExternalStore(
|
|
11
|
+
(onChange) => instance.subscribe(onChange),
|
|
12
|
+
() => instance.state,
|
|
13
|
+
() => instance.state,
|
|
14
|
+
)
|
|
15
|
+
return {
|
|
16
|
+
...state,
|
|
17
|
+
install: instance.install,
|
|
18
|
+
update: instance.update,
|
|
19
|
+
dismissUpdate: instance.dismissUpdate,
|
|
20
|
+
dismissOfflineReady: instance.dismissOfflineReady,
|
|
21
|
+
}
|
|
22
|
+
}
|
package/src/runtime.js
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
// The browser side of a Tylix PWA. One self-contained function: the server
|
|
2
|
+
// inlines it into every page (installPwaRuntime.toString()), and
|
|
3
|
+
// @tylix/pwa/client calls it, so native pages and React, Vue, Svelte and
|
|
4
|
+
// Angular apps share the same instance at window.__TYLIX_PWA__.
|
|
5
|
+
//
|
|
6
|
+
// Nothing here may refer to anything outside the function body.
|
|
7
|
+
export function installPwaRuntime(win, options) {
|
|
8
|
+
if (win.__TYLIX_PWA__) return win.__TYLIX_PWA__
|
|
9
|
+
var opts = Object.assign({ url: '/sw.js', scope: '/', register: true, checkEvery: 3600000 }, options || {})
|
|
10
|
+
var nav = win.navigator
|
|
11
|
+
var listeners = new Set()
|
|
12
|
+
var deferredPrompt = null
|
|
13
|
+
var registration = null
|
|
14
|
+
var updating = false
|
|
15
|
+
|
|
16
|
+
function standalone() {
|
|
17
|
+
try {
|
|
18
|
+
return (win.matchMedia && win.matchMedia('(display-mode: standalone)').matches) || nav.standalone === true
|
|
19
|
+
} catch (e) {
|
|
20
|
+
return false
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
var state = {
|
|
25
|
+
supported: Boolean(nav && 'serviceWorker' in nav),
|
|
26
|
+
registered: false,
|
|
27
|
+
offlineReady: false,
|
|
28
|
+
updateAvailable: false,
|
|
29
|
+
installable: false,
|
|
30
|
+
installed: standalone(),
|
|
31
|
+
online: !nav || nav.onLine !== false,
|
|
32
|
+
error: null,
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function set(patch) {
|
|
36
|
+
state = Object.assign({}, state, patch)
|
|
37
|
+
listeners.forEach(function (fn) {
|
|
38
|
+
try {
|
|
39
|
+
fn(state)
|
|
40
|
+
} catch (err) {
|
|
41
|
+
console.error('[pwa] listener failed:', err)
|
|
42
|
+
}
|
|
43
|
+
})
|
|
44
|
+
try {
|
|
45
|
+
win.dispatchEvent(new win.CustomEvent('tylix:pwa', { detail: state }))
|
|
46
|
+
} catch (e) {}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
win.addEventListener('beforeinstallprompt', function (event) {
|
|
50
|
+
event.preventDefault()
|
|
51
|
+
deferredPrompt = event
|
|
52
|
+
set({ installable: true })
|
|
53
|
+
})
|
|
54
|
+
win.addEventListener('appinstalled', function () {
|
|
55
|
+
deferredPrompt = null
|
|
56
|
+
set({ installable: false, installed: true })
|
|
57
|
+
})
|
|
58
|
+
win.addEventListener('online', function () {
|
|
59
|
+
set({ online: true })
|
|
60
|
+
})
|
|
61
|
+
win.addEventListener('offline', function () {
|
|
62
|
+
set({ online: false })
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
function watch(worker) {
|
|
66
|
+
worker.addEventListener('statechange', function () {
|
|
67
|
+
if (worker.state !== 'installed') return
|
|
68
|
+
// A worker installed while another controls the page is an update
|
|
69
|
+
// waiting for the user; the first one ever means offline is ready.
|
|
70
|
+
if (nav.serviceWorker.controller) set({ updateAvailable: true })
|
|
71
|
+
else set({ offlineReady: true })
|
|
72
|
+
})
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function register() {
|
|
76
|
+
if (!state.supported) return Promise.resolve(null)
|
|
77
|
+
return nav.serviceWorker
|
|
78
|
+
.register(opts.url, { scope: opts.scope })
|
|
79
|
+
.then(function (reg) {
|
|
80
|
+
registration = reg
|
|
81
|
+
set({ registered: true })
|
|
82
|
+
if (reg.waiting && nav.serviceWorker.controller) set({ updateAvailable: true })
|
|
83
|
+
if (reg.installing) watch(reg.installing)
|
|
84
|
+
reg.addEventListener('updatefound', function () {
|
|
85
|
+
if (reg.installing) watch(reg.installing)
|
|
86
|
+
})
|
|
87
|
+
// Reload once the new worker takes over, but only when the user
|
|
88
|
+
// asked for the update: the very first install claims the page too.
|
|
89
|
+
nav.serviceWorker.addEventListener('controllerchange', function () {
|
|
90
|
+
if (!updating) return
|
|
91
|
+
updating = false
|
|
92
|
+
win.location.reload()
|
|
93
|
+
})
|
|
94
|
+
if (opts.checkEvery > 0) {
|
|
95
|
+
setInterval(function () {
|
|
96
|
+
reg.update().catch(function () {})
|
|
97
|
+
}, opts.checkEvery)
|
|
98
|
+
}
|
|
99
|
+
return reg
|
|
100
|
+
})
|
|
101
|
+
.catch(function (err) {
|
|
102
|
+
set({ error: String((err && err.message) || err) })
|
|
103
|
+
return null
|
|
104
|
+
})
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
var api = {
|
|
108
|
+
get state() {
|
|
109
|
+
return state
|
|
110
|
+
},
|
|
111
|
+
// Svelte's store contract: run(fn) now and on every change; returns
|
|
112
|
+
// the unsubscribe function.
|
|
113
|
+
subscribe: function (fn) {
|
|
114
|
+
listeners.add(fn)
|
|
115
|
+
fn(state)
|
|
116
|
+
return function () {
|
|
117
|
+
listeners.delete(fn)
|
|
118
|
+
}
|
|
119
|
+
},
|
|
120
|
+
// Shows the browser's install dialog. Resolves 'accepted',
|
|
121
|
+
// 'dismissed' or 'unavailable' (the browser didn't offer it).
|
|
122
|
+
install: function () {
|
|
123
|
+
if (!deferredPrompt) return Promise.resolve('unavailable')
|
|
124
|
+
var prompt = deferredPrompt
|
|
125
|
+
deferredPrompt = null
|
|
126
|
+
prompt.prompt()
|
|
127
|
+
return prompt.userChoice.then(function (choice) {
|
|
128
|
+
set({ installable: false })
|
|
129
|
+
return choice.outcome
|
|
130
|
+
})
|
|
131
|
+
},
|
|
132
|
+
// Activates the waiting version and reloads the page into it.
|
|
133
|
+
update: function () {
|
|
134
|
+
var waiting = registration && registration.waiting
|
|
135
|
+
if (!waiting) return false
|
|
136
|
+
updating = true
|
|
137
|
+
waiting.postMessage({ type: 'SKIP_WAITING' })
|
|
138
|
+
return true
|
|
139
|
+
},
|
|
140
|
+
dismissUpdate: function () {
|
|
141
|
+
set({ updateAvailable: false })
|
|
142
|
+
},
|
|
143
|
+
dismissOfflineReady: function () {
|
|
144
|
+
set({ offlineReady: false })
|
|
145
|
+
},
|
|
146
|
+
register: register,
|
|
147
|
+
unregister: function () {
|
|
148
|
+
return registration ? registration.unregister() : Promise.resolve(false)
|
|
149
|
+
},
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
win.__TYLIX_PWA__ = api
|
|
153
|
+
if (opts.register && state.supported) {
|
|
154
|
+
if (win.document.readyState === 'complete') register()
|
|
155
|
+
else
|
|
156
|
+
win.addEventListener('load', function () {
|
|
157
|
+
register()
|
|
158
|
+
})
|
|
159
|
+
}
|
|
160
|
+
return api
|
|
161
|
+
}
|
package/src/svelte.d.ts
ADDED
package/src/svelte.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// Svelte: the PWA instance is already a store.
|
|
2
|
+
//
|
|
3
|
+
// import { pwa } from '@tylix/pwa/svelte'
|
|
4
|
+
// {#if $pwa.updateAvailable}<button on:click={pwa.update}>Reload for the new version</button>{/if}
|
|
5
|
+
import { pwa as instance } from './client.js'
|
|
6
|
+
|
|
7
|
+
export const pwa = {
|
|
8
|
+
subscribe: (run) => instance().subscribe(run),
|
|
9
|
+
install: () => instance().install(),
|
|
10
|
+
update: () => instance().update(),
|
|
11
|
+
dismissUpdate: () => instance().dismissUpdate(),
|
|
12
|
+
dismissOfflineReady: () => instance().dismissOfflineReady(),
|
|
13
|
+
}
|
package/src/vue.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { DeepReadonly, Ref } from 'vue'
|
|
2
|
+
import type { PwaState, RuntimeOptions } from './client.js'
|
|
3
|
+
export function usePwa(options?: RuntimeOptions): {
|
|
4
|
+
state: DeepReadonly<Ref<PwaState>>
|
|
5
|
+
install(): Promise<'accepted' | 'dismissed' | 'unavailable'>
|
|
6
|
+
update(): boolean
|
|
7
|
+
dismissUpdate(): void
|
|
8
|
+
dismissOfflineReady(): void
|
|
9
|
+
}
|
package/src/vue.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Vue: the PWA state as a readonly ref, plus its actions.
|
|
2
|
+
//
|
|
3
|
+
// const { state, install, update } = usePwa()
|
|
4
|
+
// <button v-if="state.updateAvailable" @click="update">Reload for the new version</button>
|
|
5
|
+
import { onScopeDispose, readonly, shallowRef, getCurrentScope } from 'vue'
|
|
6
|
+
import { pwa } from './client.js'
|
|
7
|
+
|
|
8
|
+
export function usePwa(options) {
|
|
9
|
+
const instance = pwa(options)
|
|
10
|
+
const state = shallowRef(instance.state)
|
|
11
|
+
const stop = instance.subscribe((next) => {
|
|
12
|
+
state.value = next
|
|
13
|
+
})
|
|
14
|
+
if (getCurrentScope()) onScopeDispose(stop)
|
|
15
|
+
return {
|
|
16
|
+
state: readonly(state),
|
|
17
|
+
install: instance.install,
|
|
18
|
+
update: instance.update,
|
|
19
|
+
dismissUpdate: instance.dismissUpdate,
|
|
20
|
+
dismissOfflineReady: instance.dismissOfflineReady,
|
|
21
|
+
}
|
|
22
|
+
}
|