sveltekit-cache-first 0.0.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 +48 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +4 -0
- package/dist/sw.d.ts +11 -0
- package/dist/sw.js +94 -0
- package/dist/update.d.ts +1 -0
- package/dist/update.js +53 -0
- package/package.json +59 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Isaac Boorman
|
|
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
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# SvelteKit Cache First
|
|
2
|
+
|
|
3
|
+
A small library to make your SvelteKit Web App / PWA local first.
|
|
4
|
+
|
|
5
|
+
## Setup
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install sveltekit-cache-first
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```js
|
|
12
|
+
// src/service-worker.js
|
|
13
|
+
import { version, build, files } from '$service-worker';
|
|
14
|
+
import { setupServiceWorker } from 'sveltekit-cache-first';
|
|
15
|
+
|
|
16
|
+
setupServiceWorker(self, { version, build, files });
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
```js
|
|
20
|
+
// src/routes/+layout.svelte
|
|
21
|
+
// Example using toast from svelte-sonner
|
|
22
|
+
import { toast } from 'svelte-sonner';
|
|
23
|
+
import { onUpdate } from 'sveltekit-cache-first';
|
|
24
|
+
|
|
25
|
+
onMount(() => {
|
|
26
|
+
onUpdate((accept) => {
|
|
27
|
+
// Your notification logic here, eg:
|
|
28
|
+
toast('An update is available', {
|
|
29
|
+
description: 'Refresh the page to update',
|
|
30
|
+
action: {
|
|
31
|
+
label: 'Refresh',
|
|
32
|
+
onClick: () => accept()
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
});
|
|
36
|
+
});
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Config
|
|
40
|
+
|
|
41
|
+
```js
|
|
42
|
+
// default values
|
|
43
|
+
const options = {
|
|
44
|
+
cachePageData: false, // Cache _data.json: data returned by load functions
|
|
45
|
+
ignoredRoutes: ['/api'] // Routes to always fetch fresh for
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
setupServiceWorker(self, { version, build, files, options });
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
package/dist/sw.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
type Options = {
|
|
2
|
+
cachePageData?: boolean;
|
|
3
|
+
ignoredPaths?: string[];
|
|
4
|
+
};
|
|
5
|
+
export declare function setupServiceWorker(self: ServiceWorkerGlobalScope, { version, build, files, options }: {
|
|
6
|
+
version: string;
|
|
7
|
+
build: string[];
|
|
8
|
+
files: string[];
|
|
9
|
+
options?: Options;
|
|
10
|
+
}): void;
|
|
11
|
+
export {};
|
package/dist/sw.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
const defaultOptions = {
|
|
2
|
+
cachePageData: true,
|
|
3
|
+
ignoredPaths: ['/api'],
|
|
4
|
+
};
|
|
5
|
+
export function setupServiceWorker(self, { version, build, files, options }) {
|
|
6
|
+
const CACHE = `cache-${version}`;
|
|
7
|
+
const ASSETS = [...build, ...files];
|
|
8
|
+
options = options ? { ...defaultOptions, ...options } : defaultOptions;
|
|
9
|
+
self.addEventListener('install', (event) => {
|
|
10
|
+
event.waitUntil((async () => {
|
|
11
|
+
const cache = await caches.open(CACHE);
|
|
12
|
+
await cache.addAll(ASSETS);
|
|
13
|
+
// Ensure the SPA shell is cached
|
|
14
|
+
if (!ASSETS.includes('/')) {
|
|
15
|
+
await cache.add('/');
|
|
16
|
+
}
|
|
17
|
+
})());
|
|
18
|
+
});
|
|
19
|
+
self.addEventListener('activate', (event) => {
|
|
20
|
+
event.waitUntil((async () => {
|
|
21
|
+
for (const key of await caches.keys()) {
|
|
22
|
+
if (key !== CACHE) {
|
|
23
|
+
await caches.delete(key);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
await self.clients.claim();
|
|
27
|
+
})());
|
|
28
|
+
});
|
|
29
|
+
self.addEventListener('fetch', (event) => {
|
|
30
|
+
const url = new URL(event.request.url);
|
|
31
|
+
let skipCache = false;
|
|
32
|
+
if (event.request.method !== 'GET')
|
|
33
|
+
skipCache = true;
|
|
34
|
+
// Never cache SvelteKit page data
|
|
35
|
+
if (!options.cachePageData && url.pathname.endsWith('/__data.json'))
|
|
36
|
+
skipCache = true;
|
|
37
|
+
// Never cache ignored routes
|
|
38
|
+
if (options.ignoredPaths?.some((route) => url.pathname.startsWith(route)))
|
|
39
|
+
skipCache = true;
|
|
40
|
+
if (skipCache)
|
|
41
|
+
return;
|
|
42
|
+
event.respondWith(cacheFirstWithSpaFallback(event));
|
|
43
|
+
});
|
|
44
|
+
async function cacheFirstWithSpaFallback(event) {
|
|
45
|
+
const cache = await caches.open(CACHE);
|
|
46
|
+
const cachedResponse = await cache.match(event.request);
|
|
47
|
+
const isNavigation = event.request.mode === 'navigate' ||
|
|
48
|
+
event.request.headers.get('accept')?.includes('text/html');
|
|
49
|
+
// Start background update
|
|
50
|
+
const networkUpdate = fetch(event.request)
|
|
51
|
+
.then((response) => {
|
|
52
|
+
if (response && response.status === 200) {
|
|
53
|
+
cache.put(event.request, response.clone());
|
|
54
|
+
}
|
|
55
|
+
return response;
|
|
56
|
+
})
|
|
57
|
+
.catch(() => undefined);
|
|
58
|
+
event.waitUntil(networkUpdate);
|
|
59
|
+
// 1️⃣ Serve cache immediately
|
|
60
|
+
if (cachedResponse) {
|
|
61
|
+
return cachedResponse;
|
|
62
|
+
}
|
|
63
|
+
// 2️⃣ Try network
|
|
64
|
+
const networkResponse = await networkUpdate;
|
|
65
|
+
if (networkResponse) {
|
|
66
|
+
return networkResponse;
|
|
67
|
+
}
|
|
68
|
+
// 3️⃣ Offline navigation → serve SPA shell
|
|
69
|
+
if (isNavigation) {
|
|
70
|
+
const shell = await cache.match('/');
|
|
71
|
+
if (shell) {
|
|
72
|
+
return shell;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
throw new Error('No cached response and network unavailable');
|
|
76
|
+
}
|
|
77
|
+
self.addEventListener('message', (event) => {
|
|
78
|
+
if (event.data?.type === 'SKLOCALFIRST_GET_VERSION') {
|
|
79
|
+
console.log('SW received message', event.data, 'ports', event.ports);
|
|
80
|
+
if (event.data?.type === 'SKLOCALFIRST_GET_VERSION') {
|
|
81
|
+
const port = event.ports[0];
|
|
82
|
+
if (port) {
|
|
83
|
+
port.postMessage(version);
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
console.warn('No port received!');
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (event.data?.type === 'SKLOCALFIRST_SKIP_WAITING') {
|
|
91
|
+
self.skipWaiting();
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
}
|
package/dist/update.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function onUpdate(handle: (onAccept: () => void) => void): () => void;
|
package/dist/update.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
function getVersion(worker) {
|
|
2
|
+
return new Promise((resolve) => {
|
|
3
|
+
const channel = new MessageChannel();
|
|
4
|
+
channel.port1.onmessage = (e) => resolve(e.data ?? null);
|
|
5
|
+
worker.postMessage({ type: 'SKLOCALFIRST_GET_VERSION' }, [channel.port2]);
|
|
6
|
+
});
|
|
7
|
+
}
|
|
8
|
+
async function checkVersionChanged(worker) {
|
|
9
|
+
const version = await getVersion(worker);
|
|
10
|
+
if (!version)
|
|
11
|
+
return false;
|
|
12
|
+
const lastPrompted = localStorage.getItem('lastPrompted');
|
|
13
|
+
if (lastPrompted === version)
|
|
14
|
+
return false;
|
|
15
|
+
localStorage.setItem('lastPrompted', version);
|
|
16
|
+
return true;
|
|
17
|
+
}
|
|
18
|
+
function handleAccept(worker) {
|
|
19
|
+
worker.postMessage({ type: 'SKLOCALFIRST_SKIP_WAITING' });
|
|
20
|
+
}
|
|
21
|
+
export function onUpdate(handle) {
|
|
22
|
+
if (!('serviceWorker' in navigator)) {
|
|
23
|
+
return () => { };
|
|
24
|
+
}
|
|
25
|
+
navigator.serviceWorker.getRegistration().then(async (reg) => {
|
|
26
|
+
if (!reg)
|
|
27
|
+
return;
|
|
28
|
+
// 1️⃣ Detect if a waiting SW already exists
|
|
29
|
+
if (reg.waiting) {
|
|
30
|
+
const sw = reg.waiting;
|
|
31
|
+
if (await checkVersionChanged(sw)) {
|
|
32
|
+
handle(() => handleAccept(sw));
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
// 2️⃣ Listen for new SW installations
|
|
36
|
+
reg.addEventListener('updatefound', () => {
|
|
37
|
+
const sw = reg.installing;
|
|
38
|
+
if (!sw)
|
|
39
|
+
return;
|
|
40
|
+
sw.addEventListener('statechange', () => {
|
|
41
|
+
if (sw.state === 'installed' && navigator.serviceWorker.controller) {
|
|
42
|
+
// SW installed, new version waiting
|
|
43
|
+
handle(() => handleAccept(sw));
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
// 3️⃣ Reload page when the new SW takes control
|
|
49
|
+
navigator.serviceWorker.addEventListener('controllerchange', () => {
|
|
50
|
+
window.location.reload();
|
|
51
|
+
});
|
|
52
|
+
return () => { };
|
|
53
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "sveltekit-cache-first",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"scripts": {
|
|
5
|
+
"dev": "vite dev",
|
|
6
|
+
"build": "vite build && npm run prepack",
|
|
7
|
+
"preview": "vite preview",
|
|
8
|
+
"prepare": "svelte-kit sync || echo ''",
|
|
9
|
+
"prepack": "svelte-kit sync && svelte-package && publint",
|
|
10
|
+
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
|
11
|
+
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
|
|
12
|
+
"lint": "prettier --check . && eslint .",
|
|
13
|
+
"format": "prettier --write ."
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"!dist/**/*.test.*",
|
|
18
|
+
"!dist/**/*.spec.*"
|
|
19
|
+
],
|
|
20
|
+
"sideEffects": [
|
|
21
|
+
"**/*.css"
|
|
22
|
+
],
|
|
23
|
+
"svelte": "./dist/index.js",
|
|
24
|
+
"types": "./dist/index.d.ts",
|
|
25
|
+
"type": "module",
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"svelte": "./dist/index.js"
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"svelte": "^5.0.0",
|
|
34
|
+
"@sveltejs/kit": "^2.63.0"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@eslint/js": "^10.0.1",
|
|
38
|
+
"@sveltejs/adapter-auto": "^7.0.1",
|
|
39
|
+
"@sveltejs/kit": "^2.63.0",
|
|
40
|
+
"@sveltejs/package": "^2.5.8",
|
|
41
|
+
"@sveltejs/vite-plugin-svelte": "^7.1.2",
|
|
42
|
+
"@types/node": "^24",
|
|
43
|
+
"eslint": "^10.4.1",
|
|
44
|
+
"eslint-config-prettier": "^10.1.8",
|
|
45
|
+
"eslint-plugin-svelte": "^3.19.0",
|
|
46
|
+
"globals": "^17.6.0",
|
|
47
|
+
"prettier": "^3.8.3",
|
|
48
|
+
"prettier-plugin-svelte": "^4.1.0",
|
|
49
|
+
"publint": "^0.3.21",
|
|
50
|
+
"svelte": "^5.56.1",
|
|
51
|
+
"svelte-check": "^4.6.0",
|
|
52
|
+
"typescript": "^6.0.3",
|
|
53
|
+
"typescript-eslint": "^8.60.1",
|
|
54
|
+
"vite": "^8.0.16"
|
|
55
|
+
},
|
|
56
|
+
"keywords": [
|
|
57
|
+
"svelte"
|
|
58
|
+
]
|
|
59
|
+
}
|