@farm.js/pwa 0.1.0-beta.0 → 0.1.0-beta.2
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 +27 -4
- package/dist/build.d.ts +3 -0
- package/dist/build.d.ts.map +1 -1
- package/dist/build.js +125 -31
- package/dist/config.d.ts +11 -5
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +96 -15
- package/dist/index.d.ts +6 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +14 -11
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
# @farm.js/pwa
|
|
2
2
|
|
|
3
3
|
Installable, offline-aware Progressive Web Apps for Farm.js. The plugin generates a route-aware
|
|
4
|
-
service worker during the production build
|
|
4
|
+
service worker or copies a custom one during the production build, then registers it through Farm's
|
|
5
|
+
browser plugin lifecycle.
|
|
5
6
|
|
|
6
7
|
Farm.js is currently in beta.
|
|
7
8
|
|
|
@@ -21,7 +22,7 @@ export default defineConfig({
|
|
|
21
22
|
plugins: [
|
|
22
23
|
pwa({
|
|
23
24
|
offline: "/offline",
|
|
24
|
-
cache: "
|
|
25
|
+
cache: "auto",
|
|
25
26
|
}),
|
|
26
27
|
],
|
|
27
28
|
});
|
|
@@ -33,15 +34,18 @@ does not duplicate it.
|
|
|
33
34
|
|
|
34
35
|
## Short cache configuration
|
|
35
36
|
|
|
36
|
-
`
|
|
37
|
+
`auto` precaches emitted static pages and uses SWR for public same-origin images. It is the default,
|
|
38
|
+
so you can omit `cache` when you want this behavior:
|
|
37
39
|
|
|
38
40
|
```ts
|
|
39
41
|
pwa({
|
|
40
42
|
offline: "/offline",
|
|
41
|
-
cache: "
|
|
43
|
+
cache: "auto",
|
|
42
44
|
});
|
|
43
45
|
```
|
|
44
46
|
|
|
47
|
+
The previous `recommended` value remains available as a compatibility alias for `auto`.
|
|
48
|
+
|
|
45
49
|
The explicit short form is:
|
|
46
50
|
|
|
47
51
|
```ts
|
|
@@ -71,6 +75,25 @@ pwa({
|
|
|
71
75
|
});
|
|
72
76
|
```
|
|
73
77
|
|
|
78
|
+
## Bring your own service worker
|
|
79
|
+
|
|
80
|
+
Advanced applications can replace the generated worker with a prebuilt JavaScript file:
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
pwa({
|
|
84
|
+
serviceWorker: {
|
|
85
|
+
source: "src/service-worker.js",
|
|
86
|
+
type: "module",
|
|
87
|
+
},
|
|
88
|
+
});
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
The source path is relative to the Farm project root. Farm copies the file verbatim to the final
|
|
92
|
+
`sw.js` location and keeps its production registration and update lifecycle. A custom worker owns
|
|
93
|
+
all fetch, offline, and cache behavior, so `serviceWorker` cannot be combined with `offline` or
|
|
94
|
+
`cache`. It must handle the `FARM_PWA_SKIP_WAITING` message for Farm's update action to activate a
|
|
95
|
+
waiting worker.
|
|
96
|
+
|
|
74
97
|
## Updates
|
|
75
98
|
|
|
76
99
|
`update: "prompt"` is the default. The plugin dispatches `farm:pwa:update-available` when a new
|
package/dist/build.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { ResolvedPwaOptions } from "./config.js";
|
|
2
2
|
export interface PwaBuildInput {
|
|
3
|
+
root?: string;
|
|
3
4
|
outputDir: string;
|
|
4
5
|
publicDir?: string;
|
|
5
6
|
preset: string;
|
|
@@ -7,6 +8,7 @@ export interface PwaBuildInput {
|
|
|
7
8
|
options: ResolvedPwaOptions;
|
|
8
9
|
}
|
|
9
10
|
export interface PwaBuildResult {
|
|
11
|
+
mode: "generated" | "custom";
|
|
10
12
|
workerPath: string;
|
|
11
13
|
workerUrl: string;
|
|
12
14
|
precacheUrls: string[];
|
|
@@ -15,6 +17,7 @@ export interface PwaBuildResult {
|
|
|
15
17
|
}
|
|
16
18
|
export declare function writePwaBuildArtifacts(input: PwaBuildInput): Promise<PwaBuildResult>;
|
|
17
19
|
export interface GenerateServiceWorkerOptions {
|
|
20
|
+
basePath: string;
|
|
18
21
|
cacheId: string;
|
|
19
22
|
precacheUrls: string[];
|
|
20
23
|
staticRoutes: Record<string, string>;
|
package/dist/build.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../src/build.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEtD,MAAM,WAAW,aAAa;IAC5B,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,kBAAkB,CAAC;CAC7B;AAED,MAAM,WAAW,cAAc;IAC7B,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACrC,OAAO,EAAE,MAAM,CAAC;CACjB;AAcD,wBAAsB,sBAAsB,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,cAAc,CAAC,
|
|
1
|
+
{"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../src/build.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEtD,MAAM,WAAW,aAAa;IAC5B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,kBAAkB,CAAC;CAC7B;AAED,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,WAAW,GAAG,QAAQ,CAAC;IAC7B,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACrC,OAAO,EAAE,MAAM,CAAC;CACjB;AAcD,wBAAsB,sBAAsB,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,cAAc,CAAC,CAyG1F;AAED,MAAM,WAAW,4BAA4B;IAC3C,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACrC,YAAY,EAAE,MAAM,GAAG,KAAK,CAAC;IAC7B,MAAM,EAAE,QAAQ,GAAG,MAAM,CAAC;IAC1B,MAAM,EAAE,kBAAkB,CAAC,OAAO,CAAC,CAAC,QAAQ,CAAC,CAAC;CAC/C;AAED,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,4BAA4B,GAAG,MAAM,CAyKnF;AAED,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAK7E;AAiDD,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAGnE;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAQpE"}
|
package/dist/build.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
-
import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
|
|
2
|
+
import { lstat, mkdir, readdir, readFile, realpath, writeFile } from "node:fs/promises";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
const PRECACHE_EXTENSIONS = new Set([
|
|
5
5
|
".css",
|
|
@@ -14,10 +14,32 @@ const PRECACHE_EXTENSIONS = new Set([
|
|
|
14
14
|
]);
|
|
15
15
|
export async function writePwaBuildArtifacts(input) {
|
|
16
16
|
const publicDir = input.publicDir ?? resolvePwaPublicDir(input.outputDir, input.preset);
|
|
17
|
-
const files = await walkFiles(publicDir);
|
|
18
|
-
const staticRouteFiles = resolveStaticRouteFiles(files);
|
|
19
17
|
const basePath = normalizeBasePath(input.basePath);
|
|
20
18
|
const workerRelativePath = path.posix.join(basePath.replace(/^\//, ""), "sw.js");
|
|
19
|
+
const workerPath = path.join(publicDir, ...workerRelativePath.split("/"));
|
|
20
|
+
await assertWorkerPathInsidePublicDir(publicDir, workerPath);
|
|
21
|
+
if (input.options.serviceWorker) {
|
|
22
|
+
const sourcePath = path.resolve(input.root ?? process.cwd(), input.options.serviceWorker.source);
|
|
23
|
+
let source;
|
|
24
|
+
try {
|
|
25
|
+
source = await readFile(sourcePath);
|
|
26
|
+
}
|
|
27
|
+
catch (cause) {
|
|
28
|
+
throw new Error(`[farm:pwa] Custom service worker ${JSON.stringify(input.options.serviceWorker.source)} could not be read.`, { cause });
|
|
29
|
+
}
|
|
30
|
+
await mkdir(path.dirname(workerPath), { recursive: true });
|
|
31
|
+
await writeFile(workerPath, source);
|
|
32
|
+
return {
|
|
33
|
+
mode: "custom",
|
|
34
|
+
workerPath,
|
|
35
|
+
workerUrl: withBasePath("/sw.js", basePath),
|
|
36
|
+
precacheUrls: [],
|
|
37
|
+
staticRoutes: {},
|
|
38
|
+
cacheId: createHash("sha256").update(source).digest("hex").slice(0, 16),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
const files = await walkFiles(publicDir);
|
|
42
|
+
const staticRouteFiles = resolveStaticRouteFiles(files);
|
|
21
43
|
const selectedRoutes = selectStaticRoutes(staticRouteFiles, input.options.cache.staticRoutes, basePath);
|
|
22
44
|
const configuredOfflineRoute = input.options.offline;
|
|
23
45
|
const offlineRoute = configuredOfflineRoute
|
|
@@ -31,9 +53,10 @@ export async function writePwaBuildArtifacts(input) {
|
|
|
31
53
|
}
|
|
32
54
|
selectedRoutes[offlineRoute] = emittedOfflineFile;
|
|
33
55
|
}
|
|
34
|
-
const assetFiles = files.filter((file) => file !==
|
|
56
|
+
const assetFiles = files.filter((file) => toPublicUrl(file, basePath) !== withBasePath("/sw.js", basePath) &&
|
|
57
|
+
PRECACHE_EXTENSIONS.has(path.extname(file).toLowerCase()));
|
|
35
58
|
const precacheFiles = [...new Set([...assetFiles, ...Object.values(selectedRoutes)])].sort();
|
|
36
|
-
const precacheUrls = precacheFiles.map(toPublicUrl);
|
|
59
|
+
const precacheUrls = precacheFiles.map((file) => toPublicUrl(file, basePath));
|
|
37
60
|
const fileHashes = await Promise.all(precacheFiles.map(async (file) => {
|
|
38
61
|
const content = await readFile(path.join(publicDir, file));
|
|
39
62
|
return `${file}:${createHash("sha256").update(content).digest("hex")}`;
|
|
@@ -48,9 +71,9 @@ export async function writePwaBuildArtifacts(input) {
|
|
|
48
71
|
}))
|
|
49
72
|
.digest("hex")
|
|
50
73
|
.slice(0, 16);
|
|
51
|
-
const workerPath = path.join(publicDir, ...workerRelativePath.split("/"));
|
|
52
74
|
await mkdir(path.dirname(workerPath), { recursive: true });
|
|
53
75
|
await writeFile(workerPath, generateServiceWorker({
|
|
76
|
+
basePath,
|
|
54
77
|
cacheId,
|
|
55
78
|
precacheUrls,
|
|
56
79
|
staticRoutes: selectedRoutes,
|
|
@@ -59,6 +82,7 @@ export async function writePwaBuildArtifacts(input) {
|
|
|
59
82
|
images: input.options.cache.images,
|
|
60
83
|
}));
|
|
61
84
|
return {
|
|
85
|
+
mode: "generated",
|
|
62
86
|
workerPath,
|
|
63
87
|
workerUrl: withBasePath("/sw.js", basePath),
|
|
64
88
|
precacheUrls,
|
|
@@ -67,11 +91,22 @@ export async function writePwaBuildArtifacts(input) {
|
|
|
67
91
|
};
|
|
68
92
|
}
|
|
69
93
|
export function generateServiceWorker(options) {
|
|
70
|
-
const routeFiles = Object.fromEntries(Object.entries(options.staticRoutes).map(([route, file]) => [
|
|
71
|
-
|
|
94
|
+
const routeFiles = Object.fromEntries(Object.entries(options.staticRoutes).map(([route, file]) => [
|
|
95
|
+
encodePathname(route),
|
|
96
|
+
toPublicUrl(file, options.basePath),
|
|
97
|
+
]));
|
|
98
|
+
const offlineFile = options.offlineRoute
|
|
99
|
+
? (routeFiles[encodePathname(options.offlineRoute)] ?? null)
|
|
100
|
+
: null;
|
|
101
|
+
const cacheScope = createHash("sha256")
|
|
102
|
+
.update(normalizeBasePath(options.basePath))
|
|
103
|
+
.digest("hex")
|
|
104
|
+
.slice(0, 16);
|
|
105
|
+
const precachePrefix = `farm-pwa-precache-${cacheScope}-`;
|
|
72
106
|
return `/* Generated by @farm.js/pwa. */
|
|
73
|
-
const
|
|
74
|
-
const
|
|
107
|
+
const PRECACHE_PREFIX = ${JSON.stringify(precachePrefix)};
|
|
108
|
+
const PRECACHE = ${JSON.stringify(`${precachePrefix}${options.cacheId}`)};
|
|
109
|
+
const IMAGE_CACHE = ${JSON.stringify(`farm-pwa-images-${cacheScope}-v1`)};
|
|
75
110
|
const PRECACHE_URLS = ${JSON.stringify(options.precacheUrls)};
|
|
76
111
|
const PRECACHE_PATHS = new Set(PRECACHE_URLS.map((value) => new URL(value, self.location.origin).pathname));
|
|
77
112
|
const STATIC_ROUTES = ${JSON.stringify(routeFiles)};
|
|
@@ -90,7 +125,7 @@ self.addEventListener("activate", (event) => {
|
|
|
90
125
|
event.waitUntil((async () => {
|
|
91
126
|
const names = await caches.keys();
|
|
92
127
|
await Promise.all(names
|
|
93
|
-
.filter((name) => name.startsWith(
|
|
128
|
+
.filter((name) => name.startsWith(PRECACHE_PREFIX) && name !== PRECACHE)
|
|
94
129
|
.map((name) => caches.delete(name)));
|
|
95
130
|
await self.clients.claim();
|
|
96
131
|
})());
|
|
@@ -118,7 +153,9 @@ self.addEventListener("fetch", (event) => {
|
|
|
118
153
|
}
|
|
119
154
|
|
|
120
155
|
if (IMAGE_OPTIONS && request.destination === "image") {
|
|
121
|
-
|
|
156
|
+
const image = staleWhileRevalidateImage(request);
|
|
157
|
+
event.respondWith(image.response);
|
|
158
|
+
event.waitUntil(image.lifetime);
|
|
122
159
|
}
|
|
123
160
|
});
|
|
124
161
|
|
|
@@ -145,26 +182,36 @@ async function handleNavigation(request, url) {
|
|
|
145
182
|
}
|
|
146
183
|
}
|
|
147
184
|
|
|
148
|
-
|
|
149
|
-
|
|
185
|
+
function staleWhileRevalidateImage(request) {
|
|
186
|
+
let update = Promise.resolve();
|
|
187
|
+
const response = (async () => {
|
|
188
|
+
if (request.headers.has("authorization")) return fetch(request);
|
|
150
189
|
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
190
|
+
const cache = await caches.open(IMAGE_CACHE);
|
|
191
|
+
const cached = await cache.match(request);
|
|
192
|
+
const cachedAt = Number(cached?.headers.get("x-farm-pwa-cached-at") || 0);
|
|
193
|
+
const fresh = cached && Date.now() - cachedAt <= IMAGE_OPTIONS.ttlMs;
|
|
194
|
+
update = fetchAndCacheImage(request, cache);
|
|
156
195
|
|
|
157
|
-
|
|
158
|
-
void update.catch(() => undefined);
|
|
159
|
-
return cached;
|
|
160
|
-
}
|
|
196
|
+
if (fresh) return cached;
|
|
161
197
|
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
198
|
+
try {
|
|
199
|
+
return await update;
|
|
200
|
+
} catch (error) {
|
|
201
|
+
if (cached) return cached;
|
|
202
|
+
throw error;
|
|
203
|
+
}
|
|
204
|
+
})();
|
|
205
|
+
const lifetime = response
|
|
206
|
+
.then(
|
|
207
|
+
() => update,
|
|
208
|
+
() => update,
|
|
209
|
+
)
|
|
210
|
+
.then(
|
|
211
|
+
() => undefined,
|
|
212
|
+
() => undefined,
|
|
213
|
+
);
|
|
214
|
+
return { response, lifetime };
|
|
168
215
|
}
|
|
169
216
|
|
|
170
217
|
async function fetchAndCacheImage(request, cache) {
|
|
@@ -213,6 +260,46 @@ function normalizePathname(pathname) {
|
|
|
213
260
|
export function resolvePwaPublicDir(outputDir, preset) {
|
|
214
261
|
return path.join(outputDir, preset === "vercel" || preset === "vercel-edge" ? "static" : "public");
|
|
215
262
|
}
|
|
263
|
+
async function assertWorkerPathInsidePublicDir(publicDir, workerPath) {
|
|
264
|
+
const prospectivePublicDir = await resolveProspectiveRealPath(publicDir);
|
|
265
|
+
const prospectiveWorkerPath = await resolveProspectiveRealPath(workerPath);
|
|
266
|
+
const relativePath = path.relative(prospectivePublicDir, prospectiveWorkerPath);
|
|
267
|
+
if (relativePath === ".." ||
|
|
268
|
+
relativePath.startsWith(`..${path.sep}`) ||
|
|
269
|
+
path.isAbsolute(relativePath)) {
|
|
270
|
+
throw new Error("[farm:pwa] Service worker output must stay inside the public output directory, including through symlinks.");
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
async function resolveProspectiveRealPath(candidate) {
|
|
274
|
+
const missingSegments = [];
|
|
275
|
+
let existingAncestor = path.resolve(candidate);
|
|
276
|
+
while (true) {
|
|
277
|
+
try {
|
|
278
|
+
return path.join(await realpath(existingAncestor), ...missingSegments);
|
|
279
|
+
}
|
|
280
|
+
catch (error) {
|
|
281
|
+
if (error.code !== "ENOENT")
|
|
282
|
+
throw error;
|
|
283
|
+
let existingEntry = false;
|
|
284
|
+
try {
|
|
285
|
+
await lstat(existingAncestor);
|
|
286
|
+
existingEntry = true;
|
|
287
|
+
}
|
|
288
|
+
catch (statError) {
|
|
289
|
+
if (statError.code !== "ENOENT")
|
|
290
|
+
throw statError;
|
|
291
|
+
}
|
|
292
|
+
if (existingEntry) {
|
|
293
|
+
throw new Error("[farm:pwa] Service worker output must stay inside the public output directory, including through symlinks.");
|
|
294
|
+
}
|
|
295
|
+
const parent = path.dirname(existingAncestor);
|
|
296
|
+
if (parent === existingAncestor)
|
|
297
|
+
throw error;
|
|
298
|
+
missingSegments.unshift(path.basename(existingAncestor));
|
|
299
|
+
existingAncestor = parent;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
216
303
|
export function normalizeBasePath(value) {
|
|
217
304
|
if (!value || value === "/")
|
|
218
305
|
return "/";
|
|
@@ -270,10 +357,17 @@ function selectStaticRoutes(emitted, configured, basePath) {
|
|
|
270
357
|
}
|
|
271
358
|
return selected;
|
|
272
359
|
}
|
|
273
|
-
function toPublicUrl(file) {
|
|
274
|
-
|
|
360
|
+
function toPublicUrl(file, basePath) {
|
|
361
|
+
const url = `/${file
|
|
275
362
|
.replace(/\\/g, "/")
|
|
276
363
|
.split("/")
|
|
277
364
|
.map((segment) => encodeURIComponent(segment))
|
|
278
365
|
.join("/")}`;
|
|
366
|
+
return withBasePath(url, basePath);
|
|
367
|
+
}
|
|
368
|
+
function encodePathname(pathname) {
|
|
369
|
+
return pathname
|
|
370
|
+
.split("/")
|
|
371
|
+
.map((segment) => encodeURIComponent(segment))
|
|
372
|
+
.join("/");
|
|
279
373
|
}
|
package/dist/config.d.ts
CHANGED
|
@@ -14,15 +14,21 @@ export interface PwaCacheOptions {
|
|
|
14
14
|
/** Opt in to same-origin public image caching. */
|
|
15
15
|
images?: PwaImageCache;
|
|
16
16
|
}
|
|
17
|
+
export interface PwaServiceWorkerOptions {
|
|
18
|
+
/** JavaScript file copied verbatim into the production output as sw.js. */
|
|
19
|
+
source: string;
|
|
20
|
+
/** Registration type for the custom worker. */
|
|
21
|
+
type?: "classic" | "module";
|
|
22
|
+
}
|
|
17
23
|
export interface PwaPluginOptions {
|
|
18
|
-
/** Set false to keep the plugin registered without emitting or registering a worker. */
|
|
19
|
-
enabled?: boolean;
|
|
20
24
|
/** Static route to serve after an offline navigation misses the cache. */
|
|
21
25
|
offline?: string | false;
|
|
22
26
|
/** How a waiting service worker becomes active. */
|
|
23
27
|
update?: "prompt" | "auto";
|
|
24
|
-
/**
|
|
25
|
-
cache?: "recommended" | PwaCacheOptions | false;
|
|
28
|
+
/** Generated-worker caching, a custom cache policy, or build assets only. */
|
|
29
|
+
cache?: "auto" | "recommended" | PwaCacheOptions | false;
|
|
30
|
+
/** Copy and register a prebuilt service worker instead of generating one. */
|
|
31
|
+
serviceWorker?: PwaServiceWorkerOptions;
|
|
26
32
|
}
|
|
27
33
|
export interface ResolvedPwaImageCacheOptions {
|
|
28
34
|
strategy: "swr";
|
|
@@ -30,9 +36,9 @@ export interface ResolvedPwaImageCacheOptions {
|
|
|
30
36
|
ttlMs: number;
|
|
31
37
|
}
|
|
32
38
|
export interface ResolvedPwaOptions {
|
|
33
|
-
enabled: boolean;
|
|
34
39
|
offline: string | false;
|
|
35
40
|
update: "prompt" | "auto";
|
|
41
|
+
serviceWorker: Required<PwaServiceWorkerOptions> | false;
|
|
36
42
|
cache: {
|
|
37
43
|
staticRoutes: boolean | string[];
|
|
38
44
|
images: ResolvedPwaImageCacheOptions | false;
|
package/dist/config.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,GAAG,MAAM,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,EAAE,CAAC;AAE7E,MAAM,WAAW,oBAAoB;IACnC,0EAA0E;IAC1E,QAAQ,EAAE,KAAK,CAAC;IAChB,0EAA0E;IAC1E,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,uEAAuE;IACvE,GAAG,CAAC,EAAE,WAAW,CAAC;CACnB;AAED,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG,KAAK,GAAG,oBAAoB,CAAC;AAEnE,MAAM,WAAW,eAAe;IAC9B,+EAA+E;IAC/E,YAAY,CAAC,EAAE,OAAO,GAAG,MAAM,EAAE,CAAC;IAClC,kDAAkD;IAClD,MAAM,CAAC,EAAE,aAAa,CAAC;CACxB;AAED,MAAM,WAAW,
|
|
1
|
+
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,GAAG,MAAM,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,EAAE,CAAC;AAE7E,MAAM,WAAW,oBAAoB;IACnC,0EAA0E;IAC1E,QAAQ,EAAE,KAAK,CAAC;IAChB,0EAA0E;IAC1E,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,uEAAuE;IACvE,GAAG,CAAC,EAAE,WAAW,CAAC;CACnB;AAED,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG,KAAK,GAAG,oBAAoB,CAAC;AAEnE,MAAM,WAAW,eAAe;IAC9B,+EAA+E;IAC/E,YAAY,CAAC,EAAE,OAAO,GAAG,MAAM,EAAE,CAAC;IAClC,kDAAkD;IAClD,MAAM,CAAC,EAAE,aAAa,CAAC;CACxB;AAED,MAAM,WAAW,uBAAuB;IACtC,2EAA2E;IAC3E,MAAM,EAAE,MAAM,CAAC;IACf,+CAA+C;IAC/C,IAAI,CAAC,EAAE,SAAS,GAAG,QAAQ,CAAC;CAC7B;AAED,MAAM,WAAW,gBAAgB;IAC/B,0EAA0E;IAC1E,OAAO,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;IACzB,mDAAmD;IACnD,MAAM,CAAC,EAAE,QAAQ,GAAG,MAAM,CAAC;IAC3B,6EAA6E;IAC7E,KAAK,CAAC,EAAE,MAAM,GAAG,aAAa,GAAG,eAAe,GAAG,KAAK,CAAC;IACzD,6EAA6E;IAC7E,aAAa,CAAC,EAAE,uBAAuB,CAAC;CACzC;AAED,MAAM,WAAW,4BAA4B;IAC3C,QAAQ,EAAE,KAAK,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,MAAM,GAAG,KAAK,CAAC;IACxB,MAAM,EAAE,QAAQ,GAAG,MAAM,CAAC;IAC1B,aAAa,EAAE,QAAQ,CAAC,uBAAuB,CAAC,GAAG,KAAK,CAAC;IACzD,KAAK,EAAE;QACL,YAAY,EAAE,OAAO,GAAG,MAAM,EAAE,CAAC;QACjC,MAAM,EAAE,4BAA4B,GAAG,KAAK,CAAC;KAC9C,CAAC;CACH;AAKD,wBAAgB,iBAAiB,CAAC,OAAO,GAAE,gBAAqB,GAAG,kBAAkB,CA8DpF;AAoBD,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,WAAW,GAAG,MAAM,CA0B3D"}
|
package/dist/config.js
CHANGED
|
@@ -1,26 +1,74 @@
|
|
|
1
1
|
const DEFAULT_IMAGE_LIMIT = 100;
|
|
2
2
|
const DEFAULT_IMAGE_TTL = "30d";
|
|
3
3
|
export function resolvePwaOptions(options = {}) {
|
|
4
|
-
|
|
4
|
+
if (!options || typeof options !== "object" || Array.isArray(options)) {
|
|
5
|
+
throw new TypeError("PWA options must be an object");
|
|
6
|
+
}
|
|
7
|
+
if ("enabled" in options) {
|
|
8
|
+
throw new TypeError("PWA no longer accepts enabled; remove pwa() from plugins to disable it");
|
|
9
|
+
}
|
|
10
|
+
if (options.offline !== undefined &&
|
|
11
|
+
options.offline !== false &&
|
|
12
|
+
typeof options.offline !== "string") {
|
|
13
|
+
throw new TypeError('PWA offline must be a route starting with "/" or false');
|
|
14
|
+
}
|
|
15
|
+
if (options.update !== undefined && options.update !== "prompt" && options.update !== "auto") {
|
|
16
|
+
throw new TypeError('PWA update must be "prompt" or "auto"');
|
|
17
|
+
}
|
|
18
|
+
const serviceWorker = resolveServiceWorker(options.serviceWorker);
|
|
19
|
+
if (serviceWorker && (options.offline !== undefined || options.cache !== undefined)) {
|
|
20
|
+
throw new TypeError("PWA serviceWorker cannot be combined with offline or cache because the custom worker owns those behaviors");
|
|
21
|
+
}
|
|
22
|
+
const configuredCache = options.cache;
|
|
23
|
+
if (configuredCache !== undefined &&
|
|
24
|
+
configuredCache !== false &&
|
|
25
|
+
configuredCache !== "auto" &&
|
|
26
|
+
configuredCache !== "recommended" &&
|
|
27
|
+
(!configuredCache || typeof configuredCache !== "object" || Array.isArray(configuredCache))) {
|
|
28
|
+
throw new TypeError('PWA cache must be "auto", "recommended", an options object, or false');
|
|
29
|
+
}
|
|
30
|
+
const cache = configuredCache ?? "auto";
|
|
31
|
+
const usesAutomaticCache = cache === "auto" || cache === "recommended";
|
|
5
32
|
const customCache = typeof cache === "object" ? cache : undefined;
|
|
6
33
|
return {
|
|
7
|
-
|
|
8
|
-
offline: normalizeRoute(options.offline ?? false, "offline"),
|
|
34
|
+
offline: serviceWorker ? false : normalizeRoute(options.offline ?? false, "offline"),
|
|
9
35
|
update: options.update ?? "prompt",
|
|
36
|
+
serviceWorker,
|
|
10
37
|
cache: {
|
|
11
|
-
staticRoutes:
|
|
12
|
-
?
|
|
13
|
-
:
|
|
14
|
-
?
|
|
15
|
-
:
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
38
|
+
staticRoutes: serviceWorker
|
|
39
|
+
? false
|
|
40
|
+
: usesAutomaticCache
|
|
41
|
+
? true
|
|
42
|
+
: cache === false
|
|
43
|
+
? false
|
|
44
|
+
: normalizeStaticRoutes(customCache?.staticRoutes === undefined ? false : customCache.staticRoutes),
|
|
45
|
+
images: serviceWorker
|
|
46
|
+
? false
|
|
47
|
+
: usesAutomaticCache
|
|
48
|
+
? resolveImageCache("swr")
|
|
49
|
+
: cache === false
|
|
50
|
+
? false
|
|
51
|
+
: resolveImageCache(customCache?.images === undefined ? false : customCache.images),
|
|
21
52
|
},
|
|
22
53
|
};
|
|
23
54
|
}
|
|
55
|
+
function resolveServiceWorker(value) {
|
|
56
|
+
if (value === undefined)
|
|
57
|
+
return false;
|
|
58
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
59
|
+
throw new TypeError("PWA serviceWorker must be an options object");
|
|
60
|
+
}
|
|
61
|
+
if (typeof value.source !== "string") {
|
|
62
|
+
throw new TypeError("PWA serviceWorker source must be a non-empty path");
|
|
63
|
+
}
|
|
64
|
+
const source = value.source.trim();
|
|
65
|
+
if (!source)
|
|
66
|
+
throw new TypeError("PWA serviceWorker source must be a non-empty path");
|
|
67
|
+
if (value.type !== undefined && value.type !== "classic" && value.type !== "module") {
|
|
68
|
+
throw new TypeError('PWA serviceWorker type must be "classic" or "module"');
|
|
69
|
+
}
|
|
70
|
+
return { source, type: value.type ?? "classic" };
|
|
71
|
+
}
|
|
24
72
|
export function parsePwaDuration(value) {
|
|
25
73
|
if (typeof value === "number") {
|
|
26
74
|
if (!Number.isFinite(value) || value <= 0) {
|
|
@@ -48,7 +96,9 @@ export function parsePwaDuration(value) {
|
|
|
48
96
|
function resolveImageCache(value) {
|
|
49
97
|
if (value === false)
|
|
50
98
|
return false;
|
|
51
|
-
if (value !== true &&
|
|
99
|
+
if (value !== true &&
|
|
100
|
+
value !== "swr" &&
|
|
101
|
+
(!value || typeof value !== "object" || Array.isArray(value) || value.strategy !== "swr")) {
|
|
52
102
|
throw new TypeError('PWA image cache strategy must be "swr"');
|
|
53
103
|
}
|
|
54
104
|
const configured = typeof value === "object" ? value : undefined;
|
|
@@ -63,8 +113,11 @@ function resolveImageCache(value) {
|
|
|
63
113
|
};
|
|
64
114
|
}
|
|
65
115
|
function normalizeStaticRoutes(value) {
|
|
66
|
-
if (
|
|
116
|
+
if (typeof value === "boolean")
|
|
67
117
|
return value;
|
|
118
|
+
if (!Array.isArray(value)) {
|
|
119
|
+
throw new TypeError("PWA cache staticRoutes must be boolean or an array of routes");
|
|
120
|
+
}
|
|
68
121
|
return [...new Set(value.map((route) => normalizeRoute(route, "static route")))];
|
|
69
122
|
}
|
|
70
123
|
function normalizeRoute(value, label) {
|
|
@@ -74,8 +127,36 @@ function normalizeRoute(value, label) {
|
|
|
74
127
|
if (!route.startsWith("/")) {
|
|
75
128
|
throw new TypeError(`PWA ${label} must start with "/"`);
|
|
76
129
|
}
|
|
130
|
+
if (route.startsWith("//")) {
|
|
131
|
+
throw new TypeError(`PWA ${label} must be an application pathname, not a URL`);
|
|
132
|
+
}
|
|
77
133
|
if (route.includes("?") || route.includes("#")) {
|
|
78
134
|
throw new TypeError(`PWA ${label} cannot contain a query string or fragment`);
|
|
79
135
|
}
|
|
136
|
+
if (hasUnstablePathCharacters(route)) {
|
|
137
|
+
throw new TypeError(`PWA ${label} cannot contain backslashes or control characters`);
|
|
138
|
+
}
|
|
139
|
+
for (const segment of route.split("/")) {
|
|
140
|
+
let decoded = segment;
|
|
141
|
+
try {
|
|
142
|
+
decoded = decodeURIComponent(segment);
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
// Malformed escapes remain literal URL pathname segments.
|
|
146
|
+
}
|
|
147
|
+
if (hasUnstablePathCharacters(decoded) || decoded.includes("/")) {
|
|
148
|
+
throw new TypeError(`PWA ${label} cannot contain encoded path separators`);
|
|
149
|
+
}
|
|
150
|
+
if (decoded === "." || decoded === "..") {
|
|
151
|
+
throw new TypeError(`PWA ${label} cannot contain "." or ".." path segments`);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
80
154
|
return route === "/" ? route : route.replace(/\/+$/, "");
|
|
81
155
|
}
|
|
156
|
+
function hasUnstablePathCharacters(value) {
|
|
157
|
+
return (value.includes("\\") ||
|
|
158
|
+
Array.from(value).some((character) => {
|
|
159
|
+
const code = character.charCodeAt(0);
|
|
160
|
+
return code <= 31 || (code >= 127 && code <= 159);
|
|
161
|
+
}));
|
|
162
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { type PwaCacheOptions, type PwaDuration, type PwaImageCache, type PwaImageCacheOptions, type PwaPluginOptions } from "./config.js";
|
|
2
|
-
export type { PwaCacheOptions, PwaDuration, PwaImageCache, PwaImageCacheOptions, PwaPluginOptions };
|
|
1
|
+
import { type PwaCacheOptions, type PwaDuration, type PwaImageCache, type PwaImageCacheOptions, type PwaPluginOptions, type PwaServiceWorkerOptions } from "./config.js";
|
|
2
|
+
export type { PwaCacheOptions, PwaDuration, PwaImageCache, PwaImageCacheOptions, PwaPluginOptions, PwaServiceWorkerOptions, };
|
|
3
3
|
export interface FarmPwaBrowserRuntime {
|
|
4
4
|
registration: ServiceWorkerRegistration;
|
|
5
5
|
applyUpdate(): void;
|
|
@@ -15,16 +15,16 @@ declare global {
|
|
|
15
15
|
}
|
|
16
16
|
}
|
|
17
17
|
/**
|
|
18
|
-
* Generate and register a
|
|
19
|
-
*
|
|
20
|
-
* constrained to safe GET navigation and same-origin
|
|
18
|
+
* Generate or copy and then register a service worker for a Farm application.
|
|
19
|
+
* In generated mode, build assets are always precached while optional page and
|
|
20
|
+
* image caching stays constrained to safe GET navigation and same-origin images.
|
|
21
21
|
*/
|
|
22
22
|
export declare function pwa(options?: PwaPluginOptions): import("@farm.js/core/plugin").FarmPlugin<undefined, Record<string, never>, {
|
|
23
23
|
cleanup(): void;
|
|
24
24
|
} | undefined, {
|
|
25
|
-
enabled: boolean;
|
|
26
25
|
workerUrl: string;
|
|
27
26
|
scope: string;
|
|
28
27
|
update: "prompt" | "auto";
|
|
28
|
+
workerType: "classic" | "module";
|
|
29
29
|
}, unknown, false>;
|
|
30
30
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,WAAW,EAChB,KAAK,aAAa,EAClB,KAAK,oBAAoB,EACzB,KAAK,gBAAgB,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,WAAW,EAChB,KAAK,aAAa,EAClB,KAAK,oBAAoB,EACzB,KAAK,gBAAgB,EACrB,KAAK,uBAAuB,EAC7B,MAAM,aAAa,CAAC;AAErB,YAAY,EACV,eAAe,EACf,WAAW,EACX,aAAa,EACb,oBAAoB,EACpB,gBAAgB,EAChB,uBAAuB,GACxB,CAAC;AAEF,MAAM,WAAW,qBAAqB;IACpC,YAAY,EAAE,yBAAyB,CAAC;IACxC,WAAW,IAAI,IAAI,CAAC;CACrB;AAED,MAAM,WAAW,wBAAwB;IACvC,YAAY,EAAE,yBAAyB,CAAC;IACxC,WAAW,IAAI,IAAI,CAAC;CACrB;AAED,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,MAAM;QACd,mDAAmD;QACnD,YAAY,CAAC,EAAE,qBAAqB,CAAC;KACtC;CACF;AAED;;;;GAIG;AACH,wBAAgB,GAAG,CAAC,OAAO,GAAE,gBAAqB;;;;;;;mBA0IjD"}
|
package/dist/index.js
CHANGED
|
@@ -2,23 +2,25 @@ import { definePlugin } from "@farm.js/core/plugin";
|
|
|
2
2
|
import { normalizeBasePath, withBasePath, writePwaBuildArtifacts } from "./build.js";
|
|
3
3
|
import { resolvePwaOptions, } from "./config.js";
|
|
4
4
|
/**
|
|
5
|
-
* Generate and register a
|
|
6
|
-
*
|
|
7
|
-
* constrained to safe GET navigation and same-origin
|
|
5
|
+
* Generate or copy and then register a service worker for a Farm application.
|
|
6
|
+
* In generated mode, build assets are always precached while optional page and
|
|
7
|
+
* image caching stays constrained to safe GET navigation and same-origin images.
|
|
8
8
|
*/
|
|
9
9
|
export function pwa(options = {}) {
|
|
10
10
|
const resolved = resolvePwaOptions(options);
|
|
11
|
+
let configuredRoot = ".";
|
|
11
12
|
let configuredBasePath = "/";
|
|
12
13
|
let configuredOutputDir = ".farm/.output";
|
|
13
14
|
const publicConfig = {
|
|
14
|
-
enabled: resolved.enabled,
|
|
15
15
|
workerUrl: "/sw.js",
|
|
16
16
|
scope: "/",
|
|
17
17
|
update: resolved.update,
|
|
18
|
+
workerType: resolved.serviceWorker ? resolved.serviceWorker.type : "classic",
|
|
18
19
|
};
|
|
19
20
|
return definePlugin({
|
|
20
21
|
name: "farm:pwa",
|
|
21
22
|
configure(config) {
|
|
23
|
+
configuredRoot = config.root ?? ".";
|
|
22
24
|
const basePath = normalizeBasePath(config.basePath);
|
|
23
25
|
configuredBasePath = basePath;
|
|
24
26
|
configuredOutputDir = `${config.root ?? "."}/.farm/.output`;
|
|
@@ -27,8 +29,6 @@ export function pwa(options = {}) {
|
|
|
27
29
|
},
|
|
28
30
|
build: {
|
|
29
31
|
configure(nitroConfig) {
|
|
30
|
-
if (!resolved.enabled)
|
|
31
|
-
return nitroConfig;
|
|
32
32
|
let generated = false;
|
|
33
33
|
const hooks = nitroConfig.hooks ?? {};
|
|
34
34
|
const previousPrerenderDone = hooks["prerender:done"];
|
|
@@ -37,6 +37,7 @@ export function pwa(options = {}) {
|
|
|
37
37
|
if (generated)
|
|
38
38
|
return;
|
|
39
39
|
const built = await writePwaBuildArtifacts({
|
|
40
|
+
root: configuredRoot,
|
|
40
41
|
outputDir: nitroConfig.output?.dir ?? configuredOutputDir,
|
|
41
42
|
publicDir: nitroConfig.output?.publicDir,
|
|
42
43
|
preset: nitroConfig.preset ?? "node-server",
|
|
@@ -44,7 +45,9 @@ export function pwa(options = {}) {
|
|
|
44
45
|
options: resolved,
|
|
45
46
|
});
|
|
46
47
|
generated = true;
|
|
47
|
-
console.info(
|
|
48
|
+
console.info(built.mode === "custom"
|
|
49
|
+
? `[farm:pwa] Copied custom service worker to ${built.workerUrl}`
|
|
50
|
+
: `[farm:pwa] Generated ${built.workerUrl} with ${built.precacheUrls.length} precached files`);
|
|
48
51
|
};
|
|
49
52
|
return {
|
|
50
53
|
...nitroConfig,
|
|
@@ -67,11 +70,11 @@ export function pwa(options = {}) {
|
|
|
67
70
|
client: {
|
|
68
71
|
public: publicConfig,
|
|
69
72
|
async setup({ public: config, isProd }) {
|
|
70
|
-
if (!
|
|
73
|
+
if (!isProd || !("serviceWorker" in navigator))
|
|
71
74
|
return undefined;
|
|
72
|
-
const registration = await navigator.serviceWorker.register(config.workerUrl,
|
|
73
|
-
scope: config.scope,
|
|
74
|
-
|
|
75
|
+
const registration = await navigator.serviceWorker.register(config.workerUrl, config.workerType === "module"
|
|
76
|
+
? { scope: config.scope, type: "module" }
|
|
77
|
+
: { scope: config.scope });
|
|
75
78
|
const hadControllerAtSetup = Boolean(navigator.serviceWorker.controller);
|
|
76
79
|
let applyingUpdate = false;
|
|
77
80
|
let reloading = false;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@farm.js/pwa",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.2",
|
|
4
4
|
"description": "Installable, offline-aware Progressive Web Apps for Farm.js",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"farm.js",
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
"access": "public"
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"@farm.js/core": "0.1.0-beta.
|
|
35
|
+
"@farm.js/core": "0.1.0-beta.93"
|
|
36
36
|
},
|
|
37
37
|
"devDependencies": {
|
|
38
38
|
"@types/node": "^20.10.5",
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
"vitest": "^3.2.7"
|
|
41
41
|
},
|
|
42
42
|
"engines": {
|
|
43
|
-
"node": ">=
|
|
43
|
+
"node": ">=22.13.0"
|
|
44
44
|
},
|
|
45
45
|
"scripts": {
|
|
46
46
|
"build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc",
|