nuxt-skew-protection 0.2.3 → 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.3",
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, addPlugin, addServerHandler } 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);
115
+ return keys.map((k) => unprefixKey(k.name));
106
116
  },
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 : [];
168
- },
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];
@@ -588,6 +551,7 @@ const module = defineNuxtModule({
588
551
  },
589
552
  async setup(options, nuxt) {
590
553
  const resolver = createResolver(import.meta.url);
554
+ const { version } = await readPackageJSON(resolver.resolve("../package.json"));
591
555
  logger.level = options.debug || nuxt.options.debug ? 4 : 3;
592
556
  if (options.enabled === false) {
593
557
  logger.debug("The module is disabled, skipping setup.");
@@ -599,6 +563,12 @@ const module = defineNuxtModule({
599
563
  debug: options.debug
600
564
  };
601
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
+ }
602
572
  addTypeTemplate({
603
573
  filename: "types/nuxt-skew-protection.d.ts",
604
574
  getContents: () => {
@@ -711,8 +681,16 @@ export {}
711
681
  });
712
682
  const assets = await assetManager.getAssetsFromBuild(outputDir);
713
683
  const { isExistingVersion } = await assetManager.updateVersionsManifest(buildId, assets);
714
- logger.log(`Storing ${assets.length} assets in storage...`);
715
- 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
+ });
716
694
  const existingVersions = await assetManager.listExistingVersions();
717
695
  const versionCount = existingVersions.filter((v) => v.id !== buildId).length;
718
696
  if (versionCount > 0) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-skew-protection",
3
3
  "type": "module",
4
- "version": "0.2.3",
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": {