nuxt-skew-protection 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,12 +18,12 @@
18
18
  ## Why Nuxt Skew Protection?
19
19
 
20
20
  Congrats on shipping that latest release! Unfortunately, many of your users are going to be using the previous version of your app
21
- for hours to days afterwards until they refresh.
21
+ for hours to days afterward until they refresh.
22
22
 
23
23
  Finally fixed that SEO issue? Great, but crawlers will often hit your site and request build chunks that no longer exist, leading
24
24
  to 500 errors and broken indexes.
25
25
 
26
- You've just been "skewed"! Skew is the version difference between what your users are running and what is currently deployed.
26
+ You've just been "skewed"! Skew is the version difference between what your users are running and what is deployed.
27
27
 
28
28
  While Nuxt helps us by hard-reloading on navigation when it detects a new release, it's often not enough to ensure a smooth experience for all users
29
29
  and crawlers. Just check out one of Nuxt's top commented [issues](https://github.com/nuxt/nuxt/issues/29624).
@@ -33,7 +33,7 @@ Nuxt Skew Protection aims to solve skews by providing better UX on top of app up
33
33
  ## Features
34
34
 
35
35
  - ⚡ **Instantly Adopted Releases** - Zero-config Real-time notifications to users when a new version is deployed.
36
- - 🎯 **Intelligent User Notifications** - Avoid spamming your users by only sending update notifications when their chunks are outdated. No annoying popups for unrelated updates.
36
+ - 🎯 **Targeted User Notifications** - Send update notifications only when the chunks the user has loaded have invalidated. No annoying popups for unrelated updates.
37
37
  - 📦 **Long-lived Build Assets** - Avoid breaking crawlers or old sessions with previous build assets remain accessible.
38
38
  - 🎨 **Headless UI** - Ship it quicker with a headless notification component that works perfectly with Nuxt UI.
39
39
 
@@ -45,7 +45,11 @@ Install `nuxt-skew-protection` dependency to your project:
45
45
  npx nuxi@latest module add nuxt-skew-protection
46
46
  ```
47
47
 
48
- Nuxt Skew Protection is a [Nuxt SEO Pro](https://nuxtseo.com/pricing) module, **please see the [licensing](#license) for commercial use**.
48
+ ## License & Early Access
49
+
50
+ **This module is in early access (v0.x).** All v0.x versions are MIT licensed for all projects to enable broader testing and feedback on stability.
51
+
52
+ Nuxt Skew Protection is a [Nuxt SEO Pro](https://nuxtseo.com/pricing) module. Once stable (v1+), a commercial license will be required for commercial use. **You can always use v0.x versions without a license.** See [licensing](#license) for details.
49
53
 
50
54
  ## Documentation
51
55
 
package/dist/module.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as _nuxt_schema from '@nuxt/schema';
2
2
  import { CookieSerializeOptions } from 'cookie-es';
3
- import { NuxtSkewProtectionRuntimeConfig } from '/home/runner/work/nuxt-skew-protection/nuxt-skew-protection/dist/runtime/types.js';
3
+ import { NuxtSkewProtectionRuntimeConfig } from '../dist/runtime/types.js';
4
4
 
5
5
  interface ModuleOptions {
6
6
  /**
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "nuxt": ">=4.0.0"
5
5
  },
6
6
  "configKey": "skewProtection",
7
- "version": "0.2.2",
7
+ "version": "0.3.0",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.2",
10
10
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -1,11 +1,12 @@
1
1
  import { writeFileSync, unlinkSync, existsSync, readFileSync, promises } from 'node:fs';
2
- import { useNuxt, tryUseNuxt, useLogger, defineNuxtModule, createResolver, addTypeTemplate, addComponent, addImports, addServerHandler, addPlugin } from '@nuxt/kit';
2
+ import { useNuxt, tryUseNuxt, useLogger, defineNuxtModule, createResolver, hasNuxtModule, addTypeTemplate, addComponent, addImports, addPlugin, addServerHandler } from '@nuxt/kit';
3
+ import { colors } from 'consola/utils';
4
+ import { readPackageJSON } from 'pkg-types';
3
5
  import { provider, env } from 'std-env';
4
6
  import { join } from 'node:path';
5
7
  import { tmpdir } from 'node:os';
6
8
  import { x } from 'tinyexec';
7
9
  import { defineDriver, createStorage } from 'unstorage';
8
- import { colors } from 'consola/utils';
9
10
  import { join as join$1, dirname } from 'pathe';
10
11
 
11
12
  function isStaticPreset(nuxt = useNuxt()) {
@@ -45,11 +46,13 @@ function resolveNitroPreset(nitroConfig) {
45
46
  const logger = useLogger("nuxt-skew-protection");
46
47
 
47
48
  const cloudflareKVWranglerDriver = defineDriver((opts) => {
48
- const { namespaceId, local = false } = opts;
49
+ const { namespaceId, local = false, base = "" } = opts;
49
50
  if (!namespaceId) {
50
51
  throw new Error("[cloudflare-kv-wrangler] namespaceId is required");
51
52
  }
52
53
  const locationFlag = local ? "--local" : "--remote";
54
+ const prefixKey = (key) => base ? `${base}${key}` : key;
55
+ const unprefixKey = (key) => base && key.startsWith(base) ? key.slice(base.length) : key;
53
56
  async function execWrangler(command, throwOnError = true) {
54
57
  const result = await x("sh", ["-c", `npx ${command}`]);
55
58
  if (throwOnError && result.exitCode !== 0) {
@@ -66,108 +69,53 @@ stderr: ${result.stderr}`
66
69
  name: "cloudflare-kv-wrangler",
67
70
  options: opts,
68
71
  async hasItem(key) {
69
- const result = await execWrangler(`wrangler kv key get "${key}" --namespace-id="${namespaceId}" ${locationFlag}`, false);
72
+ const prefixedKey = prefixKey(key);
73
+ const result = await execWrangler(`wrangler kv key get "${prefixedKey}" --namespace-id="${namespaceId}" ${locationFlag}`, false);
70
74
  return result.exitCode === 0;
71
75
  },
72
76
  async getItem(key) {
73
- const result = await execWrangler(`wrangler kv key get "${key}" --namespace-id="${namespaceId}" ${locationFlag}`, false);
77
+ const prefixedKey = prefixKey(key);
78
+ const result = await execWrangler(`wrangler kv key get "${prefixedKey}" --namespace-id="${namespaceId}" ${locationFlag}`, false);
74
79
  if (result.exitCode !== 0) {
75
80
  return null;
76
81
  }
77
82
  return JSON.parse(result.stdout);
78
83
  },
79
84
  async getItemRaw(key) {
80
- const result = await execWrangler(`wrangler kv key get "${key}" --namespace-id="${namespaceId}" ${locationFlag}`);
85
+ const prefixedKey = prefixKey(key);
86
+ const result = await execWrangler(`wrangler kv key get "${prefixedKey}" --namespace-id="${namespaceId}" ${locationFlag}`);
81
87
  return Buffer.from(result.stdout, "utf-8");
82
88
  },
83
89
  async setItem(key, value) {
90
+ const prefixedKey = prefixKey(key);
84
91
  const tmpFile = join(tmpdir(), `kv-${Date.now()}-${Math.random().toString(36).substring(7)}.json`);
85
92
  writeFileSync(tmpFile, JSON.stringify(value));
86
93
  try {
87
- await execWrangler(`wrangler kv key put "${key}" --path="${tmpFile}" --namespace-id="${namespaceId}" ${locationFlag}`);
94
+ await execWrangler(`wrangler kv key put "${prefixedKey}" --path="${tmpFile}" --namespace-id="${namespaceId}" ${locationFlag}`);
88
95
  } finally {
89
96
  unlinkSync(tmpFile);
90
97
  }
91
98
  },
92
99
  async setItemRaw(key, value) {
100
+ const prefixedKey = prefixKey(key);
93
101
  const tmpFile = join(tmpdir(), `kv-${Date.now()}.bin`);
94
102
  writeFileSync(tmpFile, value);
95
- await execWrangler(`wrangler kv key put "${key}" --path="${tmpFile}" --namespace-id="${namespaceId}" ${locationFlag}`);
103
+ await execWrangler(`wrangler kv key put "${prefixedKey}" --path="${tmpFile}" --namespace-id="${namespaceId}" ${locationFlag}`);
96
104
  unlinkSync(tmpFile);
97
105
  },
98
106
  async removeItem(key) {
99
- await execWrangler(`wrangler kv key delete "${key}" --namespace-id="${namespaceId}" ${locationFlag}`);
107
+ const prefixedKey = prefixKey(key);
108
+ await execWrangler(`wrangler kv key delete "${prefixedKey}" --namespace-id="${namespaceId}" ${locationFlag}`);
100
109
  },
101
- async getKeys(base) {
102
- const prefix = base ? `--prefix="${base}"` : "";
110
+ async getKeys(basePrefix) {
111
+ const fullPrefix = base ? basePrefix ? `${base}${basePrefix}` : base : basePrefix;
112
+ const prefix = fullPrefix ? `--prefix="${fullPrefix}"` : "";
103
113
  const result = await execWrangler(`wrangler kv key list ${prefix} --namespace-id="${namespaceId}" ${locationFlag}`);
104
114
  const keys = JSON.parse(result.stdout);
105
- return keys.map((k) => k.name);
106
- },
107
- async clear(base) {
108
- const keys = await driver.getKeys(base);
109
- for (const key of keys) {
110
- await driver.removeItem(key);
111
- }
112
- },
113
- async dispose() {
114
- }
115
- };
116
- return driver;
117
- });
118
-
119
- const vercelKVCLIDriver = defineDriver((opts) => {
120
- const { storeName, teamId } = opts;
121
- if (!storeName) {
122
- throw new Error("[vercel-kv-cli] storeName is required");
123
- }
124
- function buildCommand(subcommand) {
125
- const teamFlag = teamId ? `--team ${teamId}` : "";
126
- return `vercel kv ${subcommand} ${storeName} ${teamFlag}`.trim();
127
- }
128
- async function execVercelKV(subcommand) {
129
- const command = buildCommand(subcommand);
130
- const result = await x("sh", ["-c", command], {
131
- throwOnError: true
132
- });
133
- return result.stdout.trim();
134
- }
135
- const driver = {
136
- name: "vercel-kv-cli",
137
- options: opts,
138
- async hasItem(key) {
139
- const result = await execVercelKV(`get "${key}"`);
140
- return !!result;
141
- },
142
- async getItem(key) {
143
- const result = await execVercelKV(`get "${key}"`);
144
- return JSON.parse(result);
145
- },
146
- async getItemRaw(key) {
147
- const result = await execVercelKV(`get "${key}"`);
148
- return Buffer.from(result, "utf-8");
149
- },
150
- async setItem(key, value) {
151
- const jsonValue = JSON.stringify(value);
152
- const escapedValue = jsonValue.replace(/"/g, '\\"');
153
- await execVercelKV(`set "${key}" "${escapedValue}"`);
154
- },
155
- async setItemRaw(key, value) {
156
- const base64Value = Buffer.from(value).toString("base64");
157
- const escapedValue = base64Value.replace(/"/g, '\\"');
158
- await execVercelKV(`set "${key}" "${escapedValue}"`);
159
- },
160
- async removeItem(key) {
161
- await execVercelKV(`del "${key}"`);
162
- },
163
- async getKeys(base) {
164
- const pattern = base ? `"${base}*"` : '"*"';
165
- const result = await execVercelKV(`keys ${pattern}`);
166
- const keys = JSON.parse(result);
167
- return Array.isArray(keys) ? keys : [];
115
+ return keys.map((k) => unprefixKey(k.name));
168
116
  },
169
- async clear(base) {
170
- const keys = await driver.getKeys(base);
117
+ async clear(basePrefix) {
118
+ const keys = await driver.getKeys(basePrefix);
171
119
  for (const key of keys) {
172
120
  await driver.removeItem(key);
173
121
  }
@@ -180,41 +128,58 @@ const vercelKVCLIDriver = defineDriver((opts) => {
180
128
 
181
129
  async function detectCloudflareKVNamespace() {
182
130
  const nuxt = useNuxt();
183
- const rootDir = nuxt.options.rootDir || process.cwd();
184
- const wranglerPath = join(rootDir, "wrangler.toml");
185
- if (!existsSync(wranglerPath)) {
186
- return null;
131
+ const kvNamespaces = nuxt.options.nitro?.cloudflare?.wrangler?.kv_namespaces;
132
+ if (kvNamespaces?.length) {
133
+ const skewNamespace = kvNamespaces.find((ns) => ns?.binding === "SKEW_PROTECTION");
134
+ if (skewNamespace?.id) {
135
+ return skewNamespace.id;
136
+ }
137
+ if (kvNamespaces[0]?.id) {
138
+ return kvNamespaces[0].id;
139
+ }
187
140
  }
188
- try {
189
- const content = readFileSync(wranglerPath, "utf-8");
190
- const kvNamespaceMatch = content.match(/\[\[kv_namespaces\]\][^[]*?id\s*=\s*"([^"]+)"/);
191
- if (kvNamespaceMatch?.[1]) {
192
- return kvNamespaceMatch[1];
141
+ const rootDir = nuxt.options.rootDir || process.cwd();
142
+ const possiblePaths = [
143
+ join(rootDir, "wrangler.toml"),
144
+ join(rootDir, "app", "wrangler.toml")
145
+ ];
146
+ for (const wranglerPath of possiblePaths) {
147
+ if (!existsSync(wranglerPath)) {
148
+ continue;
149
+ }
150
+ try {
151
+ const content = readFileSync(wranglerPath, "utf-8");
152
+ const skewMatch = content.match(/\[\[kv_namespaces\]\][^[]*?binding\s*=\s*"SKEW_PROTECTION"[^[]*?id\s*=\s*"([^"]+)"/);
153
+ if (skewMatch?.[1]) {
154
+ return skewMatch[1];
155
+ }
156
+ const kvNamespaceMatch = content.match(/\[\[kv_namespaces\]\][^[]*?id\s*=\s*"([^"]+)"/);
157
+ if (kvNamespaceMatch?.[1]) {
158
+ return kvNamespaceMatch[1];
159
+ }
160
+ } catch {
193
161
  }
194
- return null;
195
- } catch {
196
- return null;
197
162
  }
163
+ return null;
198
164
  }
199
165
  async function resolveBuildTimeDriver(storage) {
200
- const { driver, ...driverOptions } = storage;
166
+ const { driver, base, ...driverOptions } = storage;
201
167
  switch (driver) {
202
168
  case "cloudflare-kv-binding": {
203
169
  let namespaceId = storage.namespaceId;
204
170
  if (!namespaceId) {
205
171
  namespaceId = await detectCloudflareKVNamespace();
206
172
  }
173
+ const kvBase = base?.includes("/") ? "skew-protection:" : base || "skew-protection:";
207
174
  return cloudflareKVWranglerDriver({
208
175
  namespaceId,
176
+ base: kvBase,
209
177
  ...driverOptions
210
178
  });
211
179
  }
212
- case "vercel-kv": {
213
- return vercelKVCLIDriver(driverOptions);
214
- }
215
180
  }
216
181
  const lazyDriver = await import(`unstorage/drivers/${storage.driver}`).then((m) => m.default);
217
- return lazyDriver(driverOptions);
182
+ return lazyDriver({ base, ...driverOptions });
218
183
  }
219
184
 
220
185
  function extractFileId(assetPath) {
@@ -226,7 +191,7 @@ function extractFileId(assetPath) {
226
191
  }
227
192
  function calculateDeletedChunks(currentAssets, previousAssets) {
228
193
  const currentSet = new Set(currentAssets);
229
- return previousAssets.filter((asset) => !currentSet.has(asset));
194
+ return previousAssets.filter((asset) => !currentSet.has(asset)).filter((asset) => asset.endsWith(".js"));
230
195
  }
231
196
  function getPreviousVersion(manifest, currentVersionId) {
232
197
  const sortedVersions = Object.entries(manifest.versions).map(([id, data]) => ({ id, timestamp: new Date(data.timestamp).getTime() })).sort((a, b) => b.timestamp - a.timestamp);
@@ -381,9 +346,7 @@ function createAssetManager(options) {
381
346
  if (assetData) {
382
347
  const storageKey = `${buildId}/${asset}`;
383
348
  await storage.setItemRaw(storageKey, assetData).catch((error) => {
384
- if (options.debug) {
385
- logger.warn(`Failed to store ${storageKey}:`, error);
386
- }
349
+ logger.error(`Failed to store ${storageKey}:`, error?.message || error);
387
350
  });
388
351
  if (fileId && fileIdToVersion[fileId] && fileIdToVersion[fileId] !== buildId) {
389
352
  const previousVersionId = fileIdToVersion[fileId];
@@ -515,8 +478,15 @@ function createAssetManager(options) {
515
478
  try {
516
479
  const latestData = await promises.readFile(latestPath, "utf-8");
517
480
  const latestJson = JSON.parse(latestData);
481
+ const clientVersions = {};
482
+ for (const [versionId, versionData] of Object.entries(manifest.versions)) {
483
+ clientVersions[versionId] = {
484
+ timestamp: versionData.timestamp,
485
+ deletedChunks: versionData.deletedChunks
486
+ };
487
+ }
518
488
  latestJson.skewProtection = {
519
- versions: manifest.versions
489
+ versions: clientVersions
520
490
  };
521
491
  await promises.writeFile(latestPath, JSON.stringify(latestJson, null, 2), "utf-8");
522
492
  } catch (error) {
@@ -531,10 +501,8 @@ function createAssetManager(options) {
531
501
  const versionData = manifest.versions[buildId];
532
502
  if (versionData) {
533
503
  metaJson.skewProtection = {
534
- assets: versionData.assets,
535
504
  deletedChunks: versionData.deletedChunks,
536
- timestamp: versionData.timestamp,
537
- expires: versionData.expires
505
+ timestamp: versionData.timestamp
538
506
  };
539
507
  }
540
508
  await promises.writeFile(metaPath, JSON.stringify(metaJson, null, 2), "utf-8");
@@ -583,6 +551,7 @@ const module = defineNuxtModule({
583
551
  },
584
552
  async setup(options, nuxt) {
585
553
  const resolver = createResolver(import.meta.url);
554
+ const { version } = await readPackageJSON(resolver.resolve("../package.json"));
586
555
  logger.level = options.debug || nuxt.options.debug ? 4 : 3;
587
556
  if (options.enabled === false) {
588
557
  logger.debug("The module is disabled, skipping setup.");
@@ -594,11 +563,24 @@ const module = defineNuxtModule({
594
563
  debug: options.debug
595
564
  };
596
565
  const nitroPreset = resolveNitroPreset(nuxt.options.nitro);
566
+ const isNuxtHub = hasNuxtModule("@nuxthub/core");
567
+ if (isNuxtHub && options.storage?.driver === "cloudflare-kv-binding" && !options.storage.namespaceId) {
568
+ logger.error("NuxtHub detected with cloudflare-kv-binding driver but no namespaceId configured.");
569
+ logger.info("Learn more: https://nuxtseo.com/docs/skew-protection/guides/cloudflare");
570
+ throw new Error("namespaceId required for cloudflare-kv-binding driver with NuxtHub");
571
+ }
597
572
  addTypeTemplate({
598
573
  filename: "types/nuxt-skew-protection.d.ts",
599
574
  getContents: () => {
600
575
  return `// Generated by nuxt-skew-protection
601
576
  declare module '#app' {
577
+ interface RuntimeNuxtHooks {
578
+ 'skew-protection:chunks-outdated': (payload: ChunksOutdatedPayload) => void | Promise<void>
579
+ }
580
+ interface NuxtApp {
581
+ $skewProtectionBuildId: Ref<string | undefined>
582
+ $skewProtectionCookie: Ref<string | undefined>
583
+ }
602
584
  interface NuxtAppManifestMeta {
603
585
  skewProtection?: {
604
586
  versions?: Record<string, {
@@ -612,6 +594,13 @@ declare module '#app' {
612
594
  }
613
595
 
614
596
  declare module 'nuxt/app' {
597
+ interface RuntimeNuxtHooks {
598
+ 'skew-protection:chunks-outdated': (payload: ChunksOutdatedPayload) => void | Promise<void>
599
+ }
600
+ interface NuxtApp {
601
+ $skewProtectionBuildId: Ref<string | undefined>
602
+ $skewProtectionCookie: Ref<string | undefined>
603
+ }
615
604
  interface NuxtAppManifestMeta {
616
605
  skewProtection?: {
617
606
  versions?: Record<string, {
@@ -638,6 +627,9 @@ export {}
638
627
  name: "useSkewProtection",
639
628
  from: resolver.resolve("./runtime/app/composables/useSkewProtection")
640
629
  });
630
+ addPlugin({
631
+ src: resolver.resolve("./runtime/app/plugins/init-build-id")
632
+ });
641
633
  nuxt.options.alias["nuxt-skew-protection/server"] = resolver.resolve("./runtime/server");
642
634
  if (options.storage?.driver) {
643
635
  nuxt.options.nitro = nuxt.options.nitro || {};
@@ -689,8 +681,16 @@ export {}
689
681
  });
690
682
  const assets = await assetManager.getAssetsFromBuild(outputDir);
691
683
  const { isExistingVersion } = await assetManager.updateVersionsManifest(buildId, assets);
692
- logger.log(`Storing ${assets.length} assets in storage...`);
693
- await assetManager.storeAssetsInStorage(buildId, outputDir, assets);
684
+ logger.log(colors.cyan(`Initialising Nuxt Skew Protection v${version}...`));
685
+ const storageInfo = options.storage.base ? `${colors.green(options.storage.driver)} ${colors.gray(`(${options.storage.base})`)}` : colors.green(options.storage.driver);
686
+ logger.log(` Database: ${storageInfo}`);
687
+ logger.log(` Storing ${colors.yellow(assets.length.toString())} assets in storage...`);
688
+ await assetManager.storeAssetsInStorage(buildId, outputDir, assets).then(() => {
689
+ logger.success(` \u2713 Successfully stored ${assets.length} assets`);
690
+ }).catch((error) => {
691
+ logger.error(` \u2717 Failed to store assets:`, error instanceof Error ? error.message : error);
692
+ throw error;
693
+ });
694
694
  const existingVersions = await assetManager.listExistingVersions();
695
695
  const versionCount = existingVersions.filter((v) => v.id !== buildId).length;
696
696
  if (versionCount > 0) {
@@ -3,7 +3,7 @@ import type { ChunksOutdatedPayload } from '../../types.js';
3
3
  export declare function checkForUpdates(): Promise<void>;
4
4
  export declare function useSkewProtection(): {
5
5
  manifest: import("vue").Ref<NuxtAppManifestMeta | undefined, NuxtAppManifestMeta | undefined>;
6
- clientVersion: string;
6
+ clientVersion: any;
7
7
  isOutdated: import("vue").ComputedRef<boolean | undefined>;
8
8
  onCurrentChunksOutdated: (callback: (payload: ChunksOutdatedPayload) => void | Promise<void>) => () => void;
9
9
  onAppOutdated: (callback: (manifest?: NuxtAppManifestMeta) => void | Promise<void>) => () => void;
@@ -1,12 +1,11 @@
1
1
  import { buildAssetsURL } from "#internal/nuxt/paths";
2
- import { useCookie, useNuxtApp } from "nuxt/app";
2
+ import { useNuxtApp } from "nuxt/app";
3
3
  import { computed, onUnmounted, ref } from "vue";
4
4
  import { useRuntimeConfigSkewProtection } from "./useRuntimeConfigSkewProtection.js";
5
5
  export async function checkForUpdates() {
6
6
  const nuxtApp = useNuxtApp();
7
7
  const runtimeConfig = useRuntimeConfigSkewProtection();
8
- const cookie = useCookie(runtimeConfig.cookie.name);
9
- const clientVersion = import.meta.client ? cookie.value : runtimeConfig.buildId;
8
+ const clientVersion = nuxtApp.$skewProtectionBuildId?.value || runtimeConfig.buildId;
10
9
  const meta = await $fetch(`${buildAssetsURL("builds/latest.json")}?${Date.now()}`).catch(() => {
11
10
  return null;
12
11
  });
@@ -17,12 +16,7 @@ export async function checkForUpdates() {
17
16
  export function useSkewProtection() {
18
17
  const nuxtApp = useNuxtApp();
19
18
  const runtimeConfig = useRuntimeConfigSkewProtection();
20
- const cookie = useCookie(runtimeConfig.cookie.name, {
21
- default() {
22
- return runtimeConfig.buildId;
23
- }
24
- });
25
- const clientVersion = import.meta.client ? cookie.value : runtimeConfig.buildId;
19
+ const clientVersion = nuxtApp.$skewProtectionBuildId?.value || nuxtApp.$skewProtectionCookie?.value || runtimeConfig.buildId;
26
20
  const manifest = ref();
27
21
  function onCurrentChunksOutdated(callback) {
28
22
  const hook = nuxtApp.hooks.hook("skew-protection:chunks-outdated", callback);
@@ -1,2 +1,2 @@
1
- declare const _default: import("#app").Plugin<Record<string, unknown>> & import("#app").ObjectPlugin<Record<string, unknown>>;
1
+ declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
2
2
  export default _default;
@@ -7,12 +7,13 @@ export default defineNuxtPlugin({
7
7
  name: "skew-protection:sse-updates",
8
8
  setup(nuxtApp) {
9
9
  const { clientVersion } = useSkewProtection();
10
- const { data } = useEventSource(`/_skew/sse`, [], {
10
+ logger.debug("[SSE] Initializing SSE connection for version updates");
11
+ const { data, status, error } = useEventSource(`/_skew/sse`, [], {
11
12
  autoReconnect: {
12
13
  retries: 10,
13
14
  delay: 5e3,
14
15
  onFailed() {
15
- logger.error("SSE max reconnection attempts reached");
16
+ logger.error("[SSE] Max reconnection attempts reached");
16
17
  }
17
18
  },
18
19
  serializer: {
@@ -20,13 +21,22 @@ export default defineNuxtPlugin({
20
21
  read: (rawData) => JSON.parse(rawData)
21
22
  }
22
23
  });
24
+ watch(status, (newStatus) => {
25
+ logger.debug(`[SSE] Connection status changed: ${newStatus}`);
26
+ });
27
+ watch(error, (err) => {
28
+ if (err)
29
+ logger.debug("[SSE] Connection error:", err);
30
+ });
23
31
  watch(data, (message) => {
24
- logger.debug("SSE message received:", message);
32
+ logger.debug("[SSE] Message received:", message);
25
33
  if (!message)
26
34
  return;
27
35
  if (message.type === "connected" && message.version) {
28
36
  const newVersion = message.version;
37
+ logger.debug(`[SSE] Server version: ${newVersion}, Client version: ${clientVersion}`);
29
38
  if (newVersion !== clientVersion) {
39
+ logger.debug("[SSE] Version mismatch detected, triggering update check");
30
40
  nuxtApp.runWithContext(checkForUpdates);
31
41
  }
32
42
  }
@@ -12,5 +12,5 @@
12
12
  * - Custom WebSocket servers
13
13
  * - Any platform that supports WebSocket connections
14
14
  */
15
- declare const _default: import("#app").Plugin<Record<string, unknown>> & import("#app").ObjectPlugin<Record<string, unknown>>;
15
+ declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
16
16
  export default _default;
@@ -9,8 +9,10 @@ export default defineNuxtPlugin({
9
9
  const { clientVersion } = useSkewProtection();
10
10
  const protocol = typeof window !== "undefined" && window.location.protocol === "https:" ? "wss:" : "ws:";
11
11
  const url = typeof window !== "undefined" ? `${protocol}//${window.location.host}/_skew/ws` : "";
12
+ logger.debug(`[WS] Initializing WebSocket connection: ${url}`);
12
13
  const {
13
14
  data,
15
+ status,
14
16
  open,
15
17
  close
16
18
  } = useWebSocket(url, {
@@ -18,7 +20,7 @@ export default defineNuxtPlugin({
18
20
  retries: 10,
19
21
  delay: 5e3,
20
22
  onFailed() {
21
- logger.error("WebSocket max reconnection attempts reached");
23
+ logger.error("[WS] Max reconnection attempts reached");
22
24
  }
23
25
  },
24
26
  heartbeat: {
@@ -33,29 +35,42 @@ export default defineNuxtPlugin({
33
35
  immediate: false
34
36
  // Don't connect immediately, wait for app:mounted
35
37
  });
38
+ watch(status, (newStatus) => {
39
+ logger.debug(`[WS] Connection status changed: ${newStatus}`);
40
+ });
36
41
  watch(data, (message) => {
37
42
  if (!message)
38
43
  return;
39
44
  try {
40
45
  const parsed = JSON.parse(message);
46
+ logger.debug("[WS] Message received:", parsed);
47
+ if (parsed.type === "ping") {
48
+ logger.debug("[WS] Heartbeat ping");
49
+ return;
50
+ }
41
51
  if (parsed.version) {
42
52
  const newVersion = parsed.version;
53
+ logger.debug(`[WS] Server version: ${newVersion}, Client version: ${clientVersion}`);
43
54
  if (newVersion !== clientVersion) {
55
+ logger.debug("[WS] Version mismatch detected, triggering update check");
44
56
  nuxtApp.runWithContext(checkForUpdates);
45
57
  }
46
58
  }
47
59
  } catch (error) {
48
- logger.error("Failed to parse WebSocket message:", error);
60
+ logger.error("[WS] Failed to parse WebSocket message:", error);
49
61
  }
50
62
  });
51
63
  nuxtApp.hook("app:mounted", () => {
64
+ logger.debug("[WS] App mounted, opening connection");
52
65
  open();
53
66
  });
54
67
  nuxtApp.hook("app:error", () => {
68
+ logger.debug("[WS] App error, closing connection");
55
69
  close();
56
70
  });
57
71
  if (import.meta.client) {
58
72
  window.addEventListener("beforeunload", () => {
73
+ logger.debug("[WS] Page unload, closing connection");
59
74
  close();
60
75
  });
61
76
  }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Initialize buildId state for SSR->client hydration
3
+ * Also sets cookie client-side for static/prerendered scenarios
4
+ */
5
+ declare const _default: import("nuxt/app").Plugin<{
6
+ skewProtectionBuildId: import("vue").Ref<any, any>;
7
+ skewProtectionCookie: import("nuxt/app").CookieRef<any>;
8
+ }> & import("nuxt/app").ObjectPlugin<{
9
+ skewProtectionBuildId: import("vue").Ref<any, any>;
10
+ skewProtectionCookie: import("nuxt/app").CookieRef<any>;
11
+ }>;
12
+ export default _default;
@@ -0,0 +1,29 @@
1
+ import { defineNuxtPlugin, useCookie, useRuntimeConfig, useState } from "nuxt/app";
2
+ import { init } from "../../shared/logger.js";
3
+ export default defineNuxtPlugin({
4
+ name: "skew-protection:init-build-id",
5
+ enforce: "pre",
6
+ setup() {
7
+ init();
8
+ const runtimeConfig = useRuntimeConfig();
9
+ const buildId = runtimeConfig.app.buildId;
10
+ const cookieConfig = runtimeConfig.public.skewProtection.cookie;
11
+ const buildIdState = useState("skew-protection:build-id", () => buildId);
12
+ const { name, ...cookieOpts } = cookieConfig;
13
+ const cookie = useCookie(name, {
14
+ ...cookieOpts,
15
+ readonly: false
16
+ });
17
+ if (import.meta.client && cookieConfig) {
18
+ if (!cookie.value && buildIdState.value) {
19
+ cookie.value = buildIdState.value;
20
+ }
21
+ }
22
+ return {
23
+ provide: {
24
+ skewProtectionBuildId: buildIdState,
25
+ skewProtectionCookie: cookie
26
+ }
27
+ };
28
+ }
29
+ });
@@ -1,2 +1,2 @@
1
- declare const _default: import("#app").Plugin<Record<string, unknown>> & import("#app").ObjectPlugin<Record<string, unknown>>;
1
+ declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
2
2
  export default _default;
@@ -1,4 +1,5 @@
1
1
  import { defineNuxtPlugin } from "nuxt/app";
2
+ import { logger } from "../../shared/logger.js";
2
3
  import { useSkewProtection } from "../composables/useSkewProtection.js";
3
4
  function normalizePath(pathOrUrl) {
4
5
  try {
@@ -12,31 +13,43 @@ export default defineNuxtPlugin({
12
13
  name: "skew-protection:service-worker",
13
14
  setup(nuxtApp) {
14
15
  if (!("serviceWorker" in navigator)) {
16
+ logger.debug("[SW] Service Worker not supported in this browser");
15
17
  return;
16
18
  }
17
19
  const { clientVersion, onAppOutdated } = useSkewProtection();
20
+ logger.debug("[SW] Initializing service worker tracking");
18
21
  const swRegistration = navigator.serviceWorker.register("/_nuxt-skew-sw.js");
19
22
  swRegistration.then((registration) => {
23
+ logger.debug("[SW] Service worker registered successfully");
20
24
  const sw = registration.active || registration.installing || registration.waiting;
21
- if (!sw)
25
+ if (!sw) {
26
+ logger.debug("[SW] No active/installing/waiting service worker found");
22
27
  return;
28
+ }
23
29
  const alreadyLoadedModules = performance.getEntriesByType("resource").filter((r) => r.name.includes("/_nuxt/") && r.name.endsWith(".js")).map((r) => r.name);
30
+ logger.debug(`[SW] Syncing ${alreadyLoadedModules.length} pre-loaded modules to service worker`);
24
31
  alreadyLoadedModules.forEach((url) => {
32
+ logger.debug(`[SW] Sending module to SW: ${url}`);
25
33
  sw.postMessage({ type: "ADD_MODULE", url });
26
34
  });
35
+ }).catch((error) => {
36
+ logger.debug("[SW] Service worker registration failed:", error);
27
37
  });
28
38
  async function getLoadedModules() {
29
39
  const registration = await swRegistration;
30
40
  const sw = registration.active;
31
41
  if (!sw) {
42
+ logger.debug("[SW] No active service worker to get modules from");
32
43
  return [];
33
44
  }
45
+ logger.debug("[SW] Requesting loaded modules from service worker");
34
46
  return new Promise((resolve) => {
35
47
  let timeoutId;
36
48
  const messageHandler = (event) => {
37
49
  if (event.data.type === "MODULES_LIST") {
38
50
  clearTimeout(timeoutId);
39
51
  navigator.serviceWorker.removeEventListener("message", messageHandler);
52
+ logger.debug(`[SW] Received ${event.data.modules.length} loaded modules from SW`);
40
53
  resolve(event.data.modules);
41
54
  }
42
55
  };
@@ -44,16 +57,20 @@ export default defineNuxtPlugin({
44
57
  sw.postMessage({ type: "GET_MODULES" });
45
58
  timeoutId = setTimeout(() => {
46
59
  navigator.serviceWorker.removeEventListener("message", messageHandler);
60
+ logger.debug("[SW] Timeout waiting for modules list from service worker");
47
61
  resolve([]);
48
62
  }, 5e3);
49
63
  });
50
64
  }
51
65
  async function checkDeletedChunks(deletedChunks, passedReleases) {
52
66
  if (deletedChunks.length === 0) {
67
+ logger.debug("[SW] No deleted chunks to check");
53
68
  return;
54
69
  }
70
+ logger.debug(`[SW] Checking ${deletedChunks.length} deleted chunks against loaded modules`);
55
71
  const loadedModules = await getLoadedModules();
56
72
  if (loadedModules.length === 0) {
73
+ logger.debug("[SW] No loaded modules to check against");
57
74
  return;
58
75
  }
59
76
  const normalizedDeletedChunks = new Set(deletedChunks.map(normalizePath));
@@ -61,7 +78,13 @@ export default defineNuxtPlugin({
61
78
  const normalizedModule = normalizePath(module);
62
79
  return normalizedDeletedChunks.has(normalizedModule);
63
80
  });
81
+ logger.debug(`[SW] Found ${invalidatedModules.length} invalidated modules`);
64
82
  if (invalidatedModules.length > 0) {
83
+ logger.debug("[SW] Triggering chunks-outdated hook with:", {
84
+ deletedChunks,
85
+ invalidatedModules,
86
+ passedReleases
87
+ });
65
88
  await nuxtApp.hooks.callHook("skew-protection:chunks-outdated", {
66
89
  deletedChunks,
67
90
  invalidatedModules,
@@ -70,17 +93,22 @@ export default defineNuxtPlugin({
70
93
  }
71
94
  }
72
95
  onAppOutdated(async (_manifest) => {
96
+ logger.debug("[SW] App outdated event received");
73
97
  const versions = _manifest?.skewProtection?.versions;
74
98
  if (!versions) {
99
+ logger.debug("[SW] No version information in manifest");
75
100
  return;
76
101
  }
77
102
  const newVersionId = _manifest.id;
103
+ logger.debug(`[SW] Checking version transition: ${clientVersion} \u2192 ${newVersionId}`);
78
104
  const sortedVersions = Object.entries(versions).map(([id, data]) => ({ id, timestamp: new Date(data.timestamp).getTime() })).sort((a, b) => a.timestamp - b.timestamp);
79
105
  const currentIdx = sortedVersions.findIndex((v) => v.id === clientVersion);
80
106
  const newIdx = sortedVersions.findIndex((v) => v.id === newVersionId);
107
+ logger.debug(`[SW] Version indices - current: ${currentIdx}, new: ${newIdx}`);
81
108
  const allDeletedChunks = [];
82
109
  const passedReleases = [];
83
110
  if (currentIdx === -1) {
111
+ logger.debug("[SW] Current version not found in manifest, checking all versions");
84
112
  for (const version of sortedVersions) {
85
113
  passedReleases.push(version.id);
86
114
  const versionData = versions[version.id];
@@ -89,6 +117,7 @@ export default defineNuxtPlugin({
89
117
  }
90
118
  }
91
119
  } else if (newIdx === -1) {
120
+ logger.debug("[SW] New version not in manifest, checking all versions after current");
92
121
  for (let i = currentIdx + 1; i < sortedVersions.length; i++) {
93
122
  const version = sortedVersions[i];
94
123
  if (version) {
@@ -100,6 +129,7 @@ export default defineNuxtPlugin({
100
129
  }
101
130
  }
102
131
  } else {
132
+ logger.debug(`[SW] Checking versions between current (${currentIdx}) and new (${newIdx})`);
103
133
  for (let i = currentIdx + 1; i <= newIdx; i++) {
104
134
  const version = sortedVersions[i];
105
135
  if (version) {
@@ -111,10 +141,12 @@ export default defineNuxtPlugin({
111
141
  }
112
142
  }
113
143
  }
144
+ logger.debug(`[SW] Collected ${allDeletedChunks.length} deleted chunks across ${passedReleases.length} releases`);
114
145
  if (allDeletedChunks.length > 0) {
115
146
  await new Promise((resolve) => setTimeout(resolve, 100));
116
147
  await checkDeletedChunks(allDeletedChunks, passedReleases);
117
148
  }
149
+ logger.debug("[SW] Resetting modules in service worker");
118
150
  swRegistration.then((reg) => reg.active?.postMessage({ type: "RESET_MODULES" }));
119
151
  });
120
152
  }
@@ -1 +1,5 @@
1
1
  export declare const logger: import("consola").ConsolaInstance;
2
+ /**
3
+ * Initialize logger with runtime config
4
+ */
5
+ export declare function init(): void;
@@ -1,6 +1,11 @@
1
1
  import { createConsola } from "consola";
2
+ import { useRuntimeConfig } from "nuxt/app";
2
3
  export const logger = createConsola({
3
4
  defaults: {
4
5
  tag: "nuxt-skew-protection"
5
6
  }
6
7
  });
8
+ export function init() {
9
+ const config = useRuntimeConfig();
10
+ logger.level = config.public.skewProtection.debug ? 4 : 3;
11
+ }
@@ -19,8 +19,3 @@ export interface ChunksOutdatedPayload {
19
19
  invalidatedModules: string[];
20
20
  passedReleases: string[];
21
21
  }
22
- declare module '#app' {
23
- interface RuntimeNuxtHooks {
24
- 'skew-protection:chunks-outdated': (payload: ChunksOutdatedPayload) => void | Promise<void>;
25
- }
26
- }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-skew-protection",
3
3
  "type": "module",
4
- "version": "0.2.2",
4
+ "version": "0.3.0",
5
5
  "description": "Instantly adopted Nuxt releases with long-lived build assets.",
6
6
  "author": {
7
7
  "name": "Harlan Wilton",
@@ -35,15 +35,15 @@
35
35
  "consola": "^3.4.2",
36
36
  "cookie-es": "^2.0.0",
37
37
  "defu": "^6.1.4",
38
- "nuxt-site-config": "^3.2.9",
38
+ "nuxt-site-config": "^3.2.10",
39
39
  "pathe": "^2.0.3",
40
40
  "pkg-types": "^2.3.0",
41
- "std-env": "^3.9.0",
41
+ "std-env": "^3.10.0",
42
42
  "tinyexec": "^1.0.1",
43
43
  "ufo": "^1.6.1"
44
44
  },
45
45
  "devDependencies": {
46
- "@antfu/eslint-config": "^5.4.1",
46
+ "@antfu/eslint-config": "^6.0.0",
47
47
  "@arethetypeswrong/cli": "^0.18.2",
48
48
  "@nuxt/content": "^3.7.1",
49
49
  "@nuxt/devtools-ui-kit": "^2.6.5",
@@ -52,13 +52,13 @@
52
52
  "@nuxt/ui": "^4.0.1",
53
53
  "@nuxtjs/color-mode": "^3.5.2",
54
54
  "@nuxtjs/eslint-config-typescript": "^12.1.0",
55
- "@nuxtjs/i18n": "^10.1.0",
55
+ "@nuxtjs/i18n": "^10.1.1",
56
56
  "@types/ioredis": "^5.0.0",
57
57
  "@types/ws": "^8.18.1",
58
- "@unocss/nuxt": "^66.5.2",
59
- "@unocss/preset-icons": "^66.5.2",
60
- "@unocss/preset-uno": "^66.5.2",
61
- "@unocss/runtime": "^66.5.2",
58
+ "@unocss/nuxt": "^66.5.4",
59
+ "@unocss/preset-icons": "^66.5.4",
60
+ "@unocss/preset-uno": "^66.5.4",
61
+ "@unocss/runtime": "^66.5.4",
62
62
  "@vueuse/nuxt": "^13.9.0",
63
63
  "better-sqlite3": "^12.4.1",
64
64
  "bumpp": "^10.3.1",
@@ -66,19 +66,19 @@
66
66
  "eventsource": "^4.0.0",
67
67
  "execa": "^9.6.0",
68
68
  "firebase-functions": "^6.5.0",
69
- "happy-dom": "^19.0.2",
69
+ "happy-dom": "^20.0.2",
70
70
  "ioredis": "^5.8.1",
71
71
  "nuxt": "^4.1.3",
72
72
  "playwright-core": "^1.56.0",
73
73
  "tsx": "^4.20.6",
74
74
  "typescript": "^5.9.3",
75
- "unocss": "^66.5.2",
75
+ "unocss": "^66.5.4",
76
76
  "unstorage": "^1.17.1",
77
77
  "vitest": "^3.2.4",
78
78
  "vue": "^3.5.22",
79
- "vue-router": "^4.5.1",
79
+ "vue-router": "^4.6.2",
80
80
  "vue-tsc": "^3.1.1",
81
- "wrangler": "^4.42.1",
81
+ "wrangler": "^4.43.0",
82
82
  "ws": "^8.18.3"
83
83
  },
84
84
  "resolutions": {