@serwist/vite 9.0.0-preview.0 → 9.0.0-preview.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/dist/index.js CHANGED
@@ -9,13 +9,7 @@ import 'node:fs';
9
9
  import 'fast-glob';
10
10
  import 'node:assert';
11
11
 
12
- /**
13
- * Internal build plugin used by `@serwist/vite`.
14
- * @internal
15
- * @param ctx
16
- * @param api
17
- * @returns
18
- */ const buildPlugin = (ctx, api)=>{
12
+ const buildPlugin = (ctx, api)=>{
19
13
  return {
20
14
  name: "@serwist/vite:build",
21
15
  enforce: "post",
@@ -35,11 +29,7 @@ import 'node:assert';
35
29
  };
36
30
  };
37
31
 
38
- /**
39
- * Integrates Serwist into your Vite app.
40
- * @param userOptions
41
- * @returns
42
- */ const serwist = (userOptions)=>{
32
+ const serwist = (userOptions)=>{
43
33
  const ctx = createContext(userOptions, undefined);
44
34
  const api = createApi(ctx);
45
35
  return [
@@ -29,7 +29,6 @@ const buildPlugin = (ctx, api)=>{
29
29
 
30
30
  const configurateSvelteKitOptions = (viteConfig, kit, options)=>{
31
31
  const clientOutDir = path.resolve(viteConfig.root, viteConfig.build.outDir, "../client");
32
- // Kit fixes the service worker's name to 'service-worker.js'
33
32
  if (viteConfig.isProduction) {
34
33
  options.swSrc = path.resolve(clientOutDir, "service-worker.js");
35
34
  options.swDest = path.resolve(clientOutDir, "service-worker.js");
@@ -43,8 +42,6 @@ const configurateSvelteKitOptions = (viteConfig, kit, options)=>{
43
42
  }
44
43
  }
45
44
  options.swUrl = "/service-worker.js";
46
- // SvelteKit's outDir is `.svelte-kit/output/client`.
47
- // We need to include the parent folder in globDirectory since SvelteKit will generate SSG in `.svelte-kit/output/prerendered` folder.
48
45
  if (!options.globDirectory) {
49
46
  options.globDirectory = path.resolve(clientOutDir, "..");
50
47
  }
@@ -62,9 +59,7 @@ const configurateSvelteKitOptions = (viteConfig, kit, options)=>{
62
59
  options.globPatterns.push(`client/${buildAssetsDir}version.json`);
63
60
  }
64
61
  }
65
- // Exclude server assets: sw is built on SSR build
66
62
  options.globIgnores = buildGlobIgnores(options.globIgnores);
67
- // Vite 5 support: allow override dontCacheBustURLsMatching
68
63
  if (!("dontCacheBustURLsMatching" in options)) {
69
64
  options.dontCacheBustURLsMatching = new RegExp(`${buildAssetsDir}immutable/`);
70
65
  }
@@ -78,18 +73,12 @@ function createManifestTransform(base, webManifestName, options) {
78
73
  const suffix = options?.trailingSlash === "always" ? "/" : "";
79
74
  let adapterFallback = options?.adapterFallback;
80
75
  let excludeFallback = false;
81
- // the fallback will be always generated by SvelteKit.
82
- // The adapter will copy the fallback only if it is provided in its options: we need to exclude it
83
76
  if (!adapterFallback) {
84
77
  adapterFallback = defaultAdapterFallback;
85
78
  excludeFallback = true;
86
79
  }
87
- // the fallback will be always in .svelte-kit/output/prerendered/fallback.html
88
80
  const manifest = entries.filter(({ url })=>!(excludeFallback && url === defaultAdapterFallback)).map((e)=>{
89
81
  let url = e.url;
90
- // client assets in `.svelte-kit/output/client` folder.
91
- // SSG pages in `.svelte-kit/output/prerendered/pages` folder.
92
- // fallback page in `.svelte-kit/output/prerendered` folder (fallback.html is the default).
93
82
  if (url.startsWith("client/")) url = url.slice(7);
94
83
  else if (url.startsWith("prerendered/pages/")) url = url.slice(18);
95
84
  else if (url === defaultAdapterFallback) url = adapterFallback;
@@ -100,11 +89,9 @@ function createManifestTransform(base, webManifestName, options) {
100
89
  } else {
101
90
  const idx = url.lastIndexOf("/");
102
91
  if (idx > -1) {
103
- // abc/index.html -> abc/?
104
92
  if (url.endsWith("/index.html")) url = `${url.slice(0, idx)}${suffix}`;
105
93
  else url = `${url.substring(0, url.lastIndexOf("."))}${suffix}`;
106
94
  } else {
107
- // xxx.html -> xxx/?
108
95
  url = `${url.substring(0, url.lastIndexOf("."))}${suffix}`;
109
96
  }
110
97
  }
@@ -142,12 +129,7 @@ function buildGlobIgnores(globIgnores) {
142
129
  ];
143
130
  }
144
131
 
145
- // TODO: handle SvelteKit build errors.
146
- /**
147
- * Integrates Serwist into your SvelteKit app.
148
- * @param userOptions
149
- * @returns
150
- */ const serwist = (userOptions = {})=>{
132
+ const serwist = (userOptions = {})=>{
151
133
  if (!userOptions.integration) userOptions.integration = {};
152
134
  userOptions.integration.closeBundleOrder = "pre";
153
135
  userOptions.integration.configureOptions = (viteConfig, options)=>configurateSvelteKitOptions(viteConfig, userOptions.kit ?? {}, options);
package/dist/main.js CHANGED
@@ -8,11 +8,8 @@ import fg from 'fast-glob';
8
8
  import assert from 'node:assert';
9
9
 
10
10
  let enabled = true;
11
- // Support both browser and node environments
12
11
  const globalVar = typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : {};
13
- /**
14
- * Detect how much colors the current terminal supports
15
- */ let supportLevel = 0 /* none */ ;
12
+ let supportLevel = 0;
16
13
  if (globalVar.process && globalVar.process.env && globalVar.process.stdout) {
17
14
  const { FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, COLORTERM } = globalVar.process.env;
18
15
  if (NODE_DISABLE_COLORS || NO_COLOR || FORCE_COLOR === '0') {
@@ -35,17 +32,15 @@ if (globalVar.process && globalVar.process.env && globalVar.process.stdout) {
35
32
  enabled = process.stdout.isTTY;
36
33
  }
37
34
  if (enabled) {
38
- // Windows supports 24bit True Colors since Windows 10 revision #14931,
39
- // see https://devblogs.microsoft.com/commandline/24-bit-color-in-the-windows-console/
40
35
  if (process.platform === 'win32') {
41
- supportLevel = 3 /* trueColor */ ;
36
+ supportLevel = 3;
42
37
  } else {
43
38
  if (COLORTERM && (COLORTERM === 'truecolor' || COLORTERM === '24bit')) {
44
- supportLevel = 3 /* trueColor */ ;
39
+ supportLevel = 3;
45
40
  } else if (TERM && (TERM.endsWith('-256color') || TERM.endsWith('256'))) {
46
- supportLevel = 2 /* ansi256 */ ;
41
+ supportLevel = 2;
47
42
  } else {
48
- supportLevel = 1 /* ansi */ ;
43
+ supportLevel = 1;
49
44
  }
50
45
  }
51
46
  }
@@ -54,7 +49,7 @@ let options = {
54
49
  enabled,
55
50
  supportLevel
56
51
  };
57
- function kolorist(start, end, level = 1 /* ansi */ ) {
52
+ function kolorist(start, end, level = 1) {
58
53
  const open = `\x1b[${start}m`;
59
54
  const close = `\x1b[${end}m`;
60
55
  const regex = new RegExp(`\\x1b\\[${end}m`, 'g');
@@ -67,7 +62,7 @@ const green = kolorist(32, 39);
67
62
  const yellow = kolorist(33, 39);
68
63
  const cyan = kolorist(36, 39);
69
64
 
70
- var version = "9.0.0-preview.0";
65
+ var version = "9.0.0-preview.2";
71
66
 
72
67
  const logSerwistResult = (buildResult, viteOptions)=>{
73
68
  const { logLevel = "info" } = viteOptions;
@@ -78,7 +73,6 @@ const logSerwistResult = (buildResult, viteOptions)=>{
78
73
  "",
79
74
  `${cyan(`@serwist/vite v${version}`)} ${green("files generated.")}`,
80
75
  `${green("✓")} ${count} precache entries ${dim(`(${(size / 1024).toFixed(2)} KiB)`)}`,
81
- // log build warning
82
76
  warnings && warnings.length > 0 ? yellow([
83
77
  "⚠ warnings",
84
78
  ...warnings.map((w)=>` ${w}`),
@@ -89,12 +83,9 @@ const logSerwistResult = (buildResult, viteOptions)=>{
89
83
  };
90
84
 
91
85
  const loadSerwistBuild = async ()=>{
92
- // "@serwist/build" is large and makes config loading slow.
93
- // Since it is not always used, we only load this when it is needed.
94
86
  try {
95
87
  return await import('@serwist/build');
96
88
  } catch (_) {
97
- // We don't have a default export, don't worry.
98
89
  return require("@serwist/build");
99
90
  }
100
91
  };
@@ -126,7 +117,6 @@ const generateServiceWorker = async (ctx)=>{
126
117
  throw new Error("injectManifest failed to generate results. This is likely a bug.");
127
118
  }
128
119
  const { errors, escapeRegExp, getSourceMapURL, rebasePath, replaceAndUpdateSourceMap, translateURLToSourcemapPaths } = await loadSerwistBuild();
129
- // Make sure we leave swSrc and swDest out of the precache manifest.
130
120
  for (const file of [
131
121
  ctx.options.injectManifest.swSrc,
132
122
  ctx.options.injectManifest.swDest
@@ -145,24 +135,16 @@ const generateServiceWorker = async (ctx)=>{
145
135
  throw new Error(`${errors["invalid-sw-src"]} ${error instanceof Error && error.message ? error.message : ""}`);
146
136
  }
147
137
  const injectionResults = swFileContents.match(globalRegexp);
148
- // See https://github.com/GoogleChrome/workbox/issues/2230
149
138
  if (!injectionResults) {
150
139
  throw new Error(`${errors["injection-point-not-found"]} ${injectionPoint}`);
151
140
  }
152
141
  assert(injectionResults.length === 1, `${errors["multiple-injection-points"]} ${injectionPoint}`);
153
142
  const filesToWrite = {};
154
143
  const url = getSourceMapURL(swFileContents);
155
- // See https://github.com/GoogleChrome/workbox/issues/2957
156
144
  const { destPath, srcPath, warning } = translateURLToSourcemapPaths(url, ctx.options.injectManifest.swSrc, ctx.options.injectManifest.swDest);
157
145
  if (warning) {
158
146
  injectManifestResult.warnings.push(warning);
159
147
  }
160
- // If our swSrc file contains a sourcemap, we would invalidate that
161
- // mapping if we just replaced injectionPoint with the stringified manifest.
162
- // Instead, we need to update the swDest contents as well as the sourcemap
163
- // (assuming it's a real file, not a data: URL) at the same time.
164
- // See https://github.com/GoogleChrome/workbox/issues/2235
165
- // and https://github.com/GoogleChrome/workbox/issues/2648
166
148
  if (srcPath && destPath) {
167
149
  const { map, source } = await replaceAndUpdateSourceMap({
168
150
  originalMap: JSON.parse(await fs.readFile(srcPath, "utf8")),
@@ -174,8 +156,6 @@ const generateServiceWorker = async (ctx)=>{
174
156
  filesToWrite[ctx.options.injectManifest.swDest] = source;
175
157
  filesToWrite[destPath] = map;
176
158
  } else {
177
- // If there's no sourcemap associated with swSrc, a simple string
178
- // replacement will suffice.
179
159
  filesToWrite[ctx.options.injectManifest.swDest] = swFileContents.replace(globalRegexp, injectManifestResult.manifestString);
180
160
  }
181
161
  for (const [file, contents] of Object.entries(filesToWrite)){
@@ -190,10 +170,6 @@ const generateServiceWorker = async (ctx)=>{
190
170
  }
191
171
  } else {
192
172
  const define = {
193
- // Nuxt does some really weird stuff. During the build, they MANUALLY
194
- // set browser APIs, such as window, document, location,..., to `undefined`??
195
- // Probably some Vue or server stuff. Their `define` doesn't seem to have anything
196
- // particularly useful for the service worker anyway, so we don't extend it.
197
173
  ...ctx.framework === "nuxt" ? undefined : ctx.viteConfig.define,
198
174
  "process.env.NODE_ENV": `"${ctx.options.mode}"`
199
175
  };
@@ -206,7 +182,6 @@ const generateServiceWorker = async (ctx)=>{
206
182
  root: ctx.viteConfig.root,
207
183
  base: ctx.viteConfig.base,
208
184
  resolve: ctx.viteConfig.resolve,
209
- // Don't copy anything from public folder
210
185
  publicDir: false,
211
186
  build: {
212
187
  sourcemap: ctx.viteConfig.build.sourcemap,
@@ -247,7 +222,6 @@ const createApi = (ctx)=>{
247
222
  const buildResult = await generateServiceWorker(ctx);
248
223
  if (buildResult) {
249
224
  if (ctx.viteConfig.isProduction) {
250
- // Log Serwist result
251
225
  logSerwistResult(buildResult, ctx.viteConfig);
252
226
  } else if (buildResult.warnings && buildResult.warnings.length > 0) {
253
227
  console.warn(yellow([
@@ -290,17 +264,7 @@ const resolveBasePath = (base)=>{
290
264
  const isAbsolute = (url)=>{
291
265
  return url.match(/^(?:[a-z]+:)?\/\//i);
292
266
  };
293
- // Source: https://github.com/sveltejs/kit/blob/6419d3eaa7bf1b0a756b28f06a73f71fe042de0a/packages/kit/src/utils/filesystem.js
294
- // License: MIT
295
- /**
296
- * Internal function used by `@serwist/vite`.
297
- * Resolves a file path without extension. Also handles `/index` if the path
298
- * actually points to a directory.
299
- * @internal
300
- * @param ctx
301
- * @param api
302
- * @returns
303
- */ const resolveEntry = (entry)=>{
267
+ const resolveEntry = (entry)=>{
304
268
  if (fs$1.existsSync(entry)) {
305
269
  const stats = fs$1.statSync(entry);
306
270
  if (stats.isDirectory()) {
@@ -317,34 +281,12 @@ const isAbsolute = (url)=>{
317
281
  }
318
282
  return null;
319
283
  };
320
- // Source: https://github.com/sveltejs/kit/blob/6419d3eaa7bf1b0a756b28f06a73f71fe042de0a/packages/kit/src/utils/filesystem.js
321
- // License: MIT
322
- /**
323
- * Internal function used by `@serwist/vite`.
324
- * Converts a filesystem path to a Vite `@fs` URL.
325
- * @internal
326
- * @param ctx
327
- * @param api
328
- * @returns
329
- */ const toFs = (str)=>{
284
+ const toFs = (str)=>{
330
285
  str = str.replace(/\\/g, "/");
331
- // Windows/Linux separation - Windows starts with a drive letter, we need a / in front there
332
286
  return `/@fs${str.startsWith("/") ? "" : "/"}${str}`;
333
287
  };
334
288
 
335
- // This plugin handles the service worker in two ways:
336
- // - If `devOptions.bundle` is enabled, hook a middleware that bundles the service worker
337
- // through `api.generateSW()` and returns the result into Vite's dev server.
338
- // - Otherwise, run `injectManifest` and return the service worker through `async load(id)`. Although
339
- // `precacheEntries` is always `undefined`, we still do this to check the user's `injectManifest` options
340
- // in dev mode.
341
- /**
342
- * Internal dev plugin used by `@serwist/vite`.
343
- * @internal
344
- * @param ctx
345
- * @param api
346
- * @returns
347
- */ const devPlugin = (ctx, api)=>{
289
+ const devPlugin = (ctx, api)=>{
348
290
  return {
349
291
  name: "@serwist/vite:dev",
350
292
  apply: "serve",
@@ -408,8 +350,6 @@ const buildManifestEntry = (publicDir, url)=>{
408
350
  const lookupAdditionalPrecacheEntries = (serwistOptions)=>{
409
351
  return serwistOptions.additionalPrecacheEntries || [];
410
352
  };
411
- // we need to make icons relative, we can have for example icon entries with: /pwa.png
412
- // fast-glob will not resolve absolute paths
413
353
  const normalizeIconPath = (path)=>{
414
354
  return path.startsWith("/") ? path.substring(1) : path;
415
355
  };
@@ -419,8 +359,6 @@ const configureStaticAssets = async (resolvedPluginOptions, viteConfig)=>{
419
359
  const globs = [];
420
360
  const manifestEntries = lookupAdditionalPrecacheEntries(injectManifest);
421
361
  if (includeAssets) {
422
- // we need to make icons relative, we can have for example icon entries with: /pwa.png
423
- // fast-glob will not resolve absolute paths
424
362
  if (Array.isArray(includeAssets)) globs.push(...includeAssets.map(normalizeIconPath));
425
363
  else globs.push(normalizeIconPath(includeAssets));
426
364
  }
@@ -430,7 +368,6 @@ const configureStaticAssets = async (resolvedPluginOptions, viteConfig)=>{
430
368
  onlyFiles: true,
431
369
  unique: true
432
370
  });
433
- // we also need to remove from the list existing included by the user
434
371
  if (manifestEntries.length > 0) {
435
372
  const included = manifestEntries.map((me)=>{
436
373
  if (typeof me === "string") return me;
@@ -451,7 +388,6 @@ const configureStaticAssets = async (resolvedPluginOptions, viteConfig)=>{
451
388
  const resolveOptions = async (options, viteConfig)=>{
452
389
  const { type = "classic", mode = process$1.env.NODE_ENV || "production", injectRegister = "auto", registerType = "prompt", minify = true, base = viteConfig.base, scope: _scope, swUrl = "/sw.js", includeAssets = undefined, useCredentials = false, disable = false, integration = {}, buildBase, devOptions, plugins = [], rollupOptions = {}, rollupFormat = "es", ...injectManifest } = options;
453
390
  const basePath = resolveBasePath(base);
454
- // check typescript service worker for injectManifest strategy
455
391
  const scope = _scope || basePath;
456
392
  let assetsDir = slash(viteConfig.build.assetsDir ?? "assets");
457
393
  if (assetsDir[assetsDir.length - 1] !== "/") assetsDir += "/";
@@ -460,7 +396,6 @@ const resolveOptions = async (options, viteConfig)=>{
460
396
  minify: false,
461
397
  ...devOptions
462
398
  };
463
- // remove './' prefix from assetsDir
464
399
  const dontCacheBustURLsMatching = new RegExp(`^${assetsDir.replace(/^\.*?\//, "")}`);
465
400
  const { validateViteInjectManifestOptions } = await loadSerwistBuild();
466
401
  const validatedInjectManifest = await validateViteInjectManifestOptions(injectManifest);
@@ -493,19 +428,12 @@ const resolveOptions = async (options, viteConfig)=>{
493
428
  },
494
429
  devOptions: resolvedDevOptions
495
430
  };
496
- // calculate hash only when required
497
431
  const calculateHash = !resolvedPluginOptions.disable && resolvedPluginOptions.includeAssets && viteConfig.command === "build";
498
432
  if (calculateHash) await configureStaticAssets(resolvedPluginOptions, viteConfig);
499
433
  return resolvedPluginOptions;
500
434
  };
501
435
 
502
- /**
503
- * Internal plugin used by `@serwist/vite`.
504
- * @internal
505
- * @param ctx
506
- * @param api
507
- * @returns
508
- */ const mainPlugin = (ctx, api)=>{
436
+ const mainPlugin = (ctx, api)=>{
509
437
  return {
510
438
  name: "@serwist/vite",
511
439
  enforce: "pre",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@serwist/vite",
3
- "version": "9.0.0-preview.0",
3
+ "version": "9.0.0-preview.2",
4
4
  "type": "module",
5
5
  "description": "A module that integrates Serwist into your Vite application.",
6
6
  "files": [
@@ -72,8 +72,8 @@
72
72
  "debug": "4.3.4",
73
73
  "fast-glob": "3.3.2",
74
74
  "pretty-bytes": "6.1.1",
75
- "@serwist/build": "9.0.0-preview.0",
76
- "@serwist/window": "9.0.0-preview.0"
75
+ "@serwist/build": "9.0.0-preview.2",
76
+ "@serwist/window": "9.0.0-preview.2"
77
77
  },
78
78
  "devDependencies": {
79
79
  "@playwright/test": "1.41.2",
@@ -81,7 +81,7 @@
81
81
  "@types/debug": "4.1.12",
82
82
  "@types/node": "20.11.16",
83
83
  "@types/prompts": "2.4.9",
84
- "@types/react": "18.2.52",
84
+ "@types/react": "18.2.54",
85
85
  "bumpp": "9.3.0",
86
86
  "kolorist": "1.8.0",
87
87
  "preact": "10.19.3",
@@ -89,13 +89,13 @@
89
89
  "publint": "0.2.7",
90
90
  "react": "18.2.0",
91
91
  "rollup": "4.9.6",
92
- "solid-js": "1.8.12",
93
- "svelte": "5.0.0-next.45",
94
- "typescript": "5.4.0-dev.20240203",
92
+ "solid-js": "1.8.14",
93
+ "svelte": "5.0.0-next.48",
94
+ "typescript": "5.4.0-dev.20240206",
95
95
  "vite": "5.0.12",
96
96
  "vue": "3.4.15",
97
- "@serwist/constants": "9.0.0-preview.0",
98
- "@serwist/sw": "9.0.0-preview.0"
97
+ "@serwist/constants": "9.0.0-preview.2",
98
+ "@serwist/sw": "9.0.0-preview.2"
99
99
  },
100
100
  "peerDependencies": {
101
101
  "@sveltejs/kit": "^1.0.0 || ^2.0.0",
@@ -106,7 +106,7 @@
106
106
  "typescript": ">=5.0.0",
107
107
  "vite": "^5.0.0",
108
108
  "vue": "^3.0.0",
109
- "@serwist/sw": "9.0.0-preview.0"
109
+ "@serwist/sw": "9.0.0-preview.2"
110
110
  },
111
111
  "peerDependenciesMeta": {
112
112
  "@serwist/sw": {