nuxt-skew-protection 0.4.2 → 0.5.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
@@ -24,6 +24,7 @@ Nuxt Skew Protection solves this with proactive update prompts and persistent bu
24
24
  - ⚡ **Instant Update Prompts** - Zero-config real-time notifications on deploy. Users adopt your latest build immediately.
25
25
  - 🎯 **Chunk-Aware Targeting** - Notifications fire only when the user's loaded chunks are invalidated. No noise for unrelated updates.
26
26
  - 🎨 **Headless UI** - Drop-in notification component with first-class Nuxt UI support.
27
+ - 📊 **Live Connection Monitoring** - Track active users and version distribution in real-time for admin dashboards and rollout progress.
27
28
  - 🔌 **Third-Party Adapters** - Real-time updates on any platform (including static sites) via [Pusher](https://pusher.com) or [Ably](https://ably.com).
28
29
 
29
30
  ## Installation
package/dist/module.d.mts CHANGED
@@ -56,6 +56,12 @@ interface ModuleOptions {
56
56
  * @default false
57
57
  */
58
58
  debug?: boolean;
59
+ /**
60
+ * Enable connection tracking to monitor active SSE/WebSocket connections
61
+ * Exposes useActiveConnections() composable with real-time stats
62
+ * @default false
63
+ */
64
+ connectionTracking?: boolean;
59
65
  }
60
66
  interface ModulePublicRuntimeConfig {
61
67
  skewProtection: NuxtSkewProtectionRuntimeConfig;
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "nuxt": ">=4.0.0"
5
5
  },
6
6
  "configKey": "skewProtection",
7
- "version": "0.4.2",
7
+ "version": "0.5.0",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.2",
10
10
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -242,6 +242,29 @@ function isSkewAdapter(value) {
242
242
  return typeof value === "object" && value !== null && "name" in value && "subscribe" in value && "broadcast" in value && typeof value.subscribe === "function" && typeof value.broadcast === "function";
243
243
  }
244
244
 
245
+ function formatStorageError(error, operation) {
246
+ const cause = error instanceof Error ? error.cause : void 0;
247
+ const message = error instanceof Error ? error.message : String(error);
248
+ const causeMessage = cause?.message || "";
249
+ if (causeMessage.includes("ENOTFOUND") || causeMessage.includes("getaddrinfo")) {
250
+ const hostMatch = causeMessage.match(/ENOTFOUND\s+(\S+)/) || causeMessage.match(/getaddrinfo\s+\S+\s+(\S+)/);
251
+ const host = hostMatch?.[1] || "unknown host";
252
+ return new Error(`Storage ${operation} failed: Could not resolve host '${host}'. Check your storage URL/credentials are correct.`);
253
+ }
254
+ if (causeMessage.includes("ECONNREFUSED") || message.includes("ECONNREFUSED")) {
255
+ return new Error(`Storage ${operation} failed: Connection refused. Is the storage server running and accessible?`);
256
+ }
257
+ if (message.includes("401") || message.includes("Unauthorized") || message.includes("WRONGPASS")) {
258
+ return new Error(`Storage ${operation} failed: Authentication failed. Check your storage credentials.`);
259
+ }
260
+ if (message.includes("timeout") || message.includes("ETIMEDOUT")) {
261
+ return new Error(`Storage ${operation} failed: Connection timed out. Check network connectivity to storage.`);
262
+ }
263
+ if (message === "fetch failed") {
264
+ return new Error(`Storage ${operation} failed: Network error. ${causeMessage || "Check your storage configuration."}`);
265
+ }
266
+ return new Error(`Storage ${operation} failed: ${message}`);
267
+ }
245
268
  async function processBatch(items, batchSize, processor) {
246
269
  const results = [];
247
270
  for (let i = 0; i < items.length; i += batchSize) {
@@ -284,24 +307,23 @@ async function getFilesRecursively(dir) {
284
307
  return files;
285
308
  }
286
309
  async function getVersionManifest(storage) {
287
- try {
288
- const manifest = await storage.getItem("version-manifest.json");
289
- if (manifest && typeof manifest === "object" && "versions" in manifest) {
310
+ const emptyManifest = { current: "", versions: {} };
311
+ return storage.getItem("version-manifest.json").then((manifest) => {
312
+ if (manifest && typeof manifest === "object" && "versions" in manifest)
290
313
  return manifest;
291
- }
292
- return {
293
- current: "",
294
- versions: {}
295
- };
296
- } catch {
297
- return {
298
- current: "",
299
- versions: {}
300
- };
301
- }
314
+ return emptyManifest;
315
+ }).catch((e) => {
316
+ const message = e instanceof Error ? e.message : String(e);
317
+ const cause = e instanceof Error ? e.cause?.message || "" : "";
318
+ if (cause.includes("ENOTFOUND") || cause.includes("ECONNREFUSED") || message.includes("401") || message === "fetch failed")
319
+ throw formatStorageError(e, "read");
320
+ return emptyManifest;
321
+ });
302
322
  }
303
323
  async function setVersionManifest(manifest, storage) {
304
- await storage.setItem("version-manifest.json", manifest);
324
+ await storage.setItem("version-manifest.json", manifest).catch((e) => {
325
+ throw formatStorageError(e, "write");
326
+ });
305
327
  }
306
328
  function formatBytes(bytes) {
307
329
  if (bytes < 1024)
@@ -321,9 +343,9 @@ function createAssetManager(options) {
321
343
  });
322
344
  const retentionDays = options.retentionDays || 7;
323
345
  const maxNumberOfVersions = options.maxNumberOfVersions || 20;
324
- async function getAssetsFromBuild(outputDir) {
346
+ async function getAssetsFromBuild(publicDir) {
325
347
  const startTime = Date.now();
326
- const nuxtDir = join$1(outputDir, "public", "_nuxt");
348
+ const nuxtDir = join$1(publicDir, "_nuxt");
327
349
  logger.debug(`Scanning build assets from ${nuxtDir}`);
328
350
  const assets = [];
329
351
  const nuxtFiles = await getFilesRecursively(nuxtDir);
@@ -427,10 +449,9 @@ function createAssetManager(options) {
427
449
  await setVersionManifest(manifest, storage);
428
450
  }
429
451
  }
430
- async function storeAssetsInStorage(buildId, outputDir, assets) {
452
+ async function storeAssetsInStorage(buildId, publicDir, assets) {
431
453
  const startTime = Date.now();
432
454
  logger.debug(`storeAssetsInStorage: starting for ${buildId} (${assets.length} assets)`);
433
- const publicDir = join$1(outputDir, "public");
434
455
  const manifestStart = Date.now();
435
456
  const manifest = await getVersionManifest(storage);
436
457
  logger.debug(`storeAssetsInStorage: loaded manifest in ${formatDuration(Date.now() - manifestStart)}`);
@@ -509,7 +530,7 @@ function createAssetManager(options) {
509
530
  createdAt: new Date(data.timestamp).getTime()
510
531
  }));
511
532
  }
512
- async function restoreOldAssetsToPublic(currentBuildId, outputDir, currentAssets = [], isExistingVersion = false) {
533
+ async function restoreOldAssetsToPublic(currentBuildId, publicDir, currentAssets = [], isExistingVersion = false) {
513
534
  const startTime = Date.now();
514
535
  logger.debug(`restoreOldAssetsToPublic: starting for ${currentBuildId}`);
515
536
  const manifestStart = Date.now();
@@ -525,7 +546,6 @@ function createAssetManager(options) {
525
546
  }
526
547
  const versionCount = Object.keys(manifest.versions).length - 1;
527
548
  logger.debug(`restoreOldAssetsToPublic: checking ${versionCount} previous versions`);
528
- const publicDir = join$1(outputDir, "public");
529
549
  const restoredAssets = [];
530
550
  const currentAssetsSet = new Set(currentAssets);
531
551
  const currentFileIds = /* @__PURE__ */ new Set();
@@ -540,6 +560,7 @@ function createAssetManager(options) {
540
560
  const assetTasks = [];
541
561
  let skippedSamePath = 0;
542
562
  let skippedSameFileId = 0;
563
+ const collectedPaths = /* @__PURE__ */ new Set();
543
564
  for (const [versionId, versionData] of Object.entries(manifest.versions)) {
544
565
  if (versionId === currentBuildId) {
545
566
  continue;
@@ -554,6 +575,10 @@ function createAssetManager(options) {
554
575
  skippedSameFileId++;
555
576
  continue;
556
577
  }
578
+ if (collectedPaths.has(asset)) {
579
+ continue;
580
+ }
581
+ collectedPaths.add(asset);
557
582
  assetTasks.push({ versionId, asset, versionData });
558
583
  }
559
584
  }
@@ -565,12 +590,17 @@ function createAssetManager(options) {
565
590
  const restoreStart = Date.now();
566
591
  let totalBytes = 0;
567
592
  let failedCount = 0;
593
+ const createdDirs = /* @__PURE__ */ new Set();
568
594
  const batchResults = await processBatch(assetTasks, 25, async ({ versionId, asset, versionData }) => {
569
595
  const storageKey = `${versionId}/${asset}`;
570
596
  return await storage.getItemRaw(storageKey).then(async (assetData) => {
571
597
  if (assetData) {
572
598
  const targetPath = join$1(publicDir, asset);
573
- await promises.mkdir(dirname(targetPath), { recursive: true });
599
+ const dir = dirname(targetPath);
600
+ if (!createdDirs.has(dir)) {
601
+ await promises.mkdir(dir, { recursive: true });
602
+ createdDirs.add(dir);
603
+ }
574
604
  let dataToWrite;
575
605
  if (Buffer.isBuffer(assetData)) {
576
606
  dataToWrite = assetData;
@@ -579,7 +609,7 @@ function createAssetManager(options) {
579
609
  } else {
580
610
  dataToWrite = Buffer.from(assetData);
581
611
  }
582
- await promises.writeFile(targetPath, dataToWrite);
612
+ await promises.writeFile(targetPath, dataToWrite, { flag: "wx" });
583
613
  totalBytes += dataToWrite.byteLength;
584
614
  const versionTimestamp = new Date(versionData.timestamp).getTime();
585
615
  const ageMs = now - versionTimestamp;
@@ -605,8 +635,10 @@ function createAssetManager(options) {
605
635
  }
606
636
  return null;
607
637
  }).catch((error) => {
608
- failedCount++;
609
- logger.debug(`Failed to restore asset ${asset} from version ${versionId}: ${error}`);
638
+ if (error.code !== "EEXIST") {
639
+ failedCount++;
640
+ logger.debug(`Failed to restore asset ${asset} from version ${versionId}: ${error}`);
641
+ }
610
642
  return null;
611
643
  });
612
644
  });
@@ -634,9 +666,9 @@ function createAssetManager(options) {
634
666
  }
635
667
  logger.debug(`restoreOldAssetsToPublic: total ${formatDuration(Date.now() - startTime)}`);
636
668
  }
637
- async function augmentBuildMetadata(buildId, outputDir) {
669
+ async function augmentBuildMetadata(buildId, publicDir) {
638
670
  const manifest = await getVersionManifest(storage);
639
- const latestPath = join$1(outputDir, "public", "_nuxt", "builds", "latest.json");
671
+ const latestPath = join$1(publicDir, "_nuxt", "builds", "latest.json");
640
672
  try {
641
673
  const latestData = await promises.readFile(latestPath, "utf-8");
642
674
  const latestJson = JSON.parse(latestData);
@@ -656,7 +688,7 @@ function createAssetManager(options) {
656
688
  logger.warn("Failed to augment builds/latest.json:", error);
657
689
  }
658
690
  }
659
- const metaPath = join$1(outputDir, "public", "_nuxt", "builds", "meta", `${buildId}.json`);
691
+ const metaPath = join$1(publicDir, "_nuxt", "builds", "meta", `${buildId}.json`);
660
692
  try {
661
693
  const metaData = await promises.readFile(metaPath, "utf-8");
662
694
  const metaJson = JSON.parse(metaData);
@@ -682,7 +714,8 @@ function createAssetManager(options) {
682
714
  listExistingVersions,
683
715
  restoreOldAssetsToPublic,
684
716
  augmentBuildMetadata,
685
- getManifest: () => getVersionManifest(storage)
717
+ getManifest: () => getVersionManifest(storage),
718
+ dispose: () => storage.dispose()
686
719
  };
687
720
  }
688
721
 
@@ -725,6 +758,7 @@ const module$1 = defineNuxtModule({
725
758
  nuxt.options.runtimeConfig.public.skewProtection = {
726
759
  cookie: options.cookie,
727
760
  debug: options.debug,
761
+ connectionTracking: options.connectionTracking,
728
762
  version
729
763
  };
730
764
  const nitroPreset = resolveNitroPreset(nuxt.options.nitro);
@@ -736,11 +770,11 @@ const module$1 = defineNuxtModule({
736
770
  }
737
771
  addTypeTemplate({
738
772
  filename: "types/nuxt-skew-protection.d.ts",
739
- getContents: () => {
740
- return `// Generated by nuxt-skew-protection
773
+ getContents: () => `// Generated by nuxt-skew-protection
741
774
  declare module '#app' {
742
775
  interface RuntimeNuxtHooks {
743
776
  'skew-protection:chunks-outdated': (payload: ChunksOutdatedPayload) => void | Promise<void>
777
+ 'skew:message': (message: { type: string, [key: string]: unknown }) => void | Promise<void>
744
778
  }
745
779
  interface NuxtApp {
746
780
  $skewProtectionBuildId: Ref<string | undefined>
@@ -761,6 +795,7 @@ declare module '#app' {
761
795
  declare module 'nuxt/app' {
762
796
  interface RuntimeNuxtHooks {
763
797
  'skew-protection:chunks-outdated': (payload: ChunksOutdatedPayload) => void | Promise<void>
798
+ 'skew:message': (message: { type: string, [key: string]: unknown }) => void | Promise<void>
764
799
  }
765
800
  interface NuxtApp {
766
801
  $skewProtectionBuildId: Ref<string | undefined>
@@ -779,11 +814,25 @@ declare module 'nuxt/app' {
779
814
  }
780
815
 
781
816
  export {}
782
- `;
783
- }
784
- }, {
785
- nuxt: true
786
- });
817
+ `
818
+ }, { nuxt: true });
819
+ addTypeTemplate({
820
+ filename: "types/nuxt-skew-protection-nitro.d.ts",
821
+ getContents: () => `// Generated by nuxt-skew-protection
822
+ declare module 'nitropack/types' {
823
+ interface NitroRuntimeHooks {
824
+ 'skew:connection:open': (payload: {
825
+ id: string
826
+ version: string
827
+ send: (data: { type: string, total: number, versions: Record<string, number> }) => void
828
+ }) => void
829
+ 'skew:connection:close': (payload: { id: string }) => void
830
+ }
831
+ }
832
+
833
+ export {}
834
+ `
835
+ }, { nitro: true });
787
836
  addComponent({
788
837
  name: "SkewNotification",
789
838
  filePath: resolver.resolve(`./runtime/app/components/SkewNotification.vue`)
@@ -792,6 +841,15 @@ export {}
792
841
  name: "useSkewProtection",
793
842
  from: resolver.resolve("./runtime/app/composables/useSkewProtection")
794
843
  });
844
+ if (options.connectionTracking) {
845
+ addImports({
846
+ name: "useActiveConnections",
847
+ from: resolver.resolve("./runtime/app/composables/useActiveConnections")
848
+ });
849
+ nuxt.options.nitro = nuxt.options.nitro || {};
850
+ nuxt.options.nitro.plugins = nuxt.options.nitro.plugins || [];
851
+ nuxt.options.nitro.plugins.push(resolver.resolve("./runtime/server/plugins/connection-tracking"));
852
+ }
795
853
  addPlugin({
796
854
  src: resolver.resolve("./runtime/app/plugins/init-build-id")
797
855
  });
@@ -852,12 +910,12 @@ export {}
852
910
  const buildId = nuxt.options.runtimeConfig.app.buildId ||= nuxt.options.buildId;
853
911
  let assetManager;
854
912
  nitro.hooks.hook("compiled", async () => {
855
- const outputDir = nitro.options.output.dir;
913
+ const publicDir = nitro.options.output.publicDir;
856
914
  assetManager = createAssetManager({
857
915
  ...options,
858
916
  driver: await resolveBuildTimeDriver(options.storage)
859
917
  });
860
- const assets = await assetManager.getAssetsFromBuild(outputDir);
918
+ const assets = await assetManager.getAssetsFromBuild(publicDir);
861
919
  const { isExistingVersion } = await assetManager.updateVersionsManifest(buildId, assets);
862
920
  const manifest = await assetManager.getManifest();
863
921
  const totalReleases = Object.keys(manifest.versions).length;
@@ -871,7 +929,7 @@ export {}
871
929
  } else {
872
930
  logger.log(`Storing ${colors.yellow(assets.length.toString())} assets for ${colors.cyan(buildId.slice(0, 8))} (${totalReleases} releases, oldest from ${timeInfo}) [${storageInfo}]`);
873
931
  }
874
- await assetManager.storeAssetsInStorage(buildId, outputDir, assets).catch((error) => {
932
+ await assetManager.storeAssetsInStorage(buildId, publicDir, assets).catch((error) => {
875
933
  logger.error(`Failed to store assets:`, error instanceof Error ? error.message : error);
876
934
  throw error;
877
935
  });
@@ -890,12 +948,14 @@ export {}
890
948
  }
891
949
  logger.log(`Restoring build files from ${versionCount} release${versionCount > 1 ? "s" : ""} (${totalAssets} assets) [${versionSizes.join(", ")}]...`);
892
950
  }
893
- await assetManager.restoreOldAssetsToPublic(buildId, outputDir, assets, isExistingVersion);
894
- await assetManager.augmentBuildMetadata(buildId, outputDir);
951
+ await assetManager.restoreOldAssetsToPublic(buildId, publicDir, assets, isExistingVersion);
952
+ await assetManager.augmentBuildMetadata(buildId, publicDir);
895
953
  });
896
954
  nitro.hooks.hook("close", async () => {
897
955
  if (assetManager) {
898
- await assetManager.cleanupExpiredVersions();
956
+ await assetManager.cleanupExpiredVersions().catch(() => {
957
+ });
958
+ await assetManager.dispose();
899
959
  }
900
960
  });
901
961
  });
@@ -0,0 +1,8 @@
1
+ export interface ConnectionStats {
2
+ total: number;
3
+ versions: Record<string, number>;
4
+ }
5
+ export declare function useActiveConnections(): {
6
+ total: import("vue").ComputedRef<number>;
7
+ versions: import("vue").ComputedRef<Record<string, number>>;
8
+ };
@@ -0,0 +1,21 @@
1
+ import { useNuxtApp, useRuntimeConfig } from "nuxt/app";
2
+ import { computed, ref } from "vue";
3
+ const stats = ref({ total: 0, versions: {} });
4
+ let hooked = false;
5
+ export function useActiveConnections() {
6
+ const config = useRuntimeConfig().public.skewProtection;
7
+ if (!config?.connectionTracking) {
8
+ throw new Error("[nuxt-skew-protection] useActiveConnections() requires `connectionTracking: true` in your module config.");
9
+ }
10
+ if (!hooked) {
11
+ hooked = true;
12
+ useNuxtApp().hooks.hook("skew:message", (message) => {
13
+ if (message.type === "stats")
14
+ stats.value = { total: message.total, versions: message.versions };
15
+ });
16
+ }
17
+ return {
18
+ total: computed(() => stats.value.total),
19
+ versions: computed(() => stats.value.versions)
20
+ };
21
+ }
@@ -32,6 +32,7 @@ export default defineNuxtPlugin({
32
32
  logger.debug("[SSE] Message received:", message);
33
33
  if (!message)
34
34
  return;
35
+ nuxtApp.hooks.callHook("skew:message", message);
35
36
  if (message.type === "connected" && message.version) {
36
37
  const newVersion = message.version;
37
38
  logger.debug(`[SSE] Server version: ${newVersion}, Client version: ${clientVersion}`);
@@ -1,16 +1,2 @@
1
- /**
2
- * WebSocket Version Updates Plugin
3
- *
4
- * Similar to the SSE plugin, but uses WebSocket for real-time version notifications.
5
- * Works with any WebSocket-capable backend (Cloudflare Durable Objects, custom WebSocket servers, etc.)
6
- *
7
- * Fires the same 'app:manifest:update' hook that Nuxt's chunk-reload plugin listens to.
8
- * This allows our WebSocket updates to integrate seamlessly with Nuxt's existing reload logic.
9
- *
10
- * Can be used on:
11
- * - Cloudflare Workers with Durable Objects
12
- * - Custom WebSocket servers
13
- * - Any platform that supports WebSocket connections
14
- */
15
1
  declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
16
2
  export default _default;
@@ -29,11 +29,9 @@ export default defineNuxtPlugin({
29
29
  timestamp: Date.now()
30
30
  }),
31
31
  interval: 3e4,
32
- // Every 30 seconds
33
32
  pongTimeout: 1e4
34
33
  },
35
34
  immediate: false
36
- // Don't connect immediately, wait for app:mounted
37
35
  });
38
36
  watch(status, (newStatus) => {
39
37
  logger.debug(`[WS] Connection status changed: ${newStatus}`);
@@ -41,23 +39,18 @@ export default defineNuxtPlugin({
41
39
  watch(data, (message) => {
42
40
  if (!message)
43
41
  return;
44
- try {
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
- }
51
- if (parsed.version) {
52
- const newVersion = parsed.version;
53
- logger.debug(`[WS] Server version: ${newVersion}, Client version: ${clientVersion}`);
54
- if (newVersion !== clientVersion) {
55
- logger.debug("[WS] Version mismatch detected, triggering update check");
56
- nuxtApp.runWithContext(checkForUpdates);
57
- }
42
+ const parsed = JSON.parse(message);
43
+ logger.debug("[WS] Message received:", parsed);
44
+ if (parsed.type === "ping")
45
+ return;
46
+ nuxtApp.hooks.callHook("skew:message", parsed);
47
+ if (parsed.version) {
48
+ const newVersion = parsed.version;
49
+ logger.debug(`[WS] Server version: ${newVersion}, Client version: ${clientVersion}`);
50
+ if (newVersion !== clientVersion) {
51
+ logger.debug("[WS] Version mismatch detected, triggering update check");
52
+ nuxtApp.runWithContext(checkForUpdates);
58
53
  }
59
- } catch (error) {
60
- logger.error("[WS] Failed to parse WebSocket message:", error);
61
54
  }
62
55
  });
63
56
  nuxtApp.hook("app:mounted", () => {
@@ -0,0 +1,2 @@
1
+ declare const _default: import("nitropack/types").NitroAppPlugin;
2
+ export default _default;
@@ -0,0 +1,25 @@
1
+ import { defineNitroPlugin } from "nitropack/runtime";
2
+ export default defineNitroPlugin((nitroApp) => {
3
+ const connections = /* @__PURE__ */ new Map();
4
+ const getStats = () => {
5
+ const versions = {};
6
+ for (const conn of connections.values()) {
7
+ versions[conn.version] = (versions[conn.version] || 0) + 1;
8
+ }
9
+ return { total: connections.size, versions };
10
+ };
11
+ const broadcast = () => {
12
+ const stats = getStats();
13
+ for (const conn of connections.values()) {
14
+ conn.send({ type: "stats", ...stats });
15
+ }
16
+ };
17
+ nitroApp.hooks.hook("skew:connection:open", ({ id, version, send }) => {
18
+ connections.set(id, { version, send });
19
+ broadcast();
20
+ });
21
+ nitroApp.hooks.hook("skew:connection:close", ({ id }) => {
22
+ connections.delete(id);
23
+ broadcast();
24
+ });
25
+ });
@@ -1,5 +1,6 @@
1
1
  import { createEventStream, defineEventHandler } from "h3";
2
2
  import { useNitroApp, useRuntimeConfig } from "nitropack/runtime";
3
+ import { getSkewProtectionCookie } from "../../imports/cookie.js";
3
4
  export default defineEventHandler(async (event) => {
4
5
  const nitroApp = useNitroApp();
5
6
  const stream = createEventStream(event);
@@ -13,11 +14,15 @@ export default defineEventHandler(async (event) => {
13
14
  version: serverVersion,
14
15
  timestamp: Date.now()
15
16
  });
17
+ const connectionId = crypto.randomUUID();
18
+ const clientVersion = getSkewProtectionCookie(event) || serverVersion;
19
+ await nitroApp.hooks.callHook("skew:connection:open", {
20
+ id: connectionId,
21
+ version: clientVersion,
22
+ send
23
+ });
16
24
  const keepaliveInterval = setInterval(() => {
17
- send({
18
- type: "keepalive",
19
- timestamp: Date.now()
20
- });
25
+ send({ type: "keepalive", timestamp: Date.now() });
21
26
  }, 3e4);
22
27
  let cleanupDone = false;
23
28
  const close = async () => {
@@ -25,6 +30,7 @@ export default defineEventHandler(async (event) => {
25
30
  return;
26
31
  cleanupDone = true;
27
32
  clearInterval(keepaliveInterval);
33
+ await nitroApp.hooks.callHook("skew:connection:close", { id: connectionId });
28
34
  await stream.close();
29
35
  };
30
36
  stream.onClosed(close);
@@ -1,17 +1,32 @@
1
+ import { parse as parseCookie } from "cookie-es";
1
2
  import { defineWebSocketHandler } from "h3";
2
- import { useRuntimeConfig } from "nitropack/runtime";
3
+ import { useNitroApp, useRuntimeConfig } from "nitropack/runtime";
3
4
  export default defineWebSocketHandler({
4
5
  open(peer) {
5
6
  const runtimeConfig = useRuntimeConfig();
7
+ const serverVersion = runtimeConfig.app?.buildId;
8
+ const skewConfig = runtimeConfig.public.skewProtection;
6
9
  peer.send(JSON.stringify({
7
10
  type: "connected",
8
- version: runtimeConfig.app?.buildId,
11
+ version: serverVersion,
9
12
  timestamp: Date.now()
10
13
  }));
14
+ const cookieHeader = peer.request?.headers?.get("cookie") || "";
15
+ const cookies = parseCookie(cookieHeader);
16
+ const cookieName = skewConfig?.cookie?.name || "__nkpv";
17
+ const clientVersion = cookies[cookieName] || serverVersion;
18
+ useNitroApp().hooks.callHook("skew:connection:open", {
19
+ id: peer.id,
20
+ version: clientVersion,
21
+ send: (data) => peer.send(JSON.stringify(data))
22
+ });
11
23
  },
12
24
  message(peer, message) {
13
25
  if (message.text().includes("ping")) {
14
26
  peer.send(JSON.stringify({ type: "pong" }));
15
27
  }
28
+ },
29
+ close(peer) {
30
+ useNitroApp().hooks.callHook("skew:connection:close", { id: peer.id });
16
31
  }
17
32
  });
@@ -6,6 +6,7 @@ export interface NuxtSkewProtectionRuntimeConfig {
6
6
  name?: string;
7
7
  };
8
8
  debug: boolean;
9
+ connectionTracking?: boolean;
9
10
  }
10
11
  export interface SkewProtectionRuntimeConfig {
11
12
  cookie: Omit<CookieSerializeOptions, 'encode'> & {
@@ -13,6 +14,7 @@ export interface SkewProtectionRuntimeConfig {
13
14
  };
14
15
  buildId: string;
15
16
  debug: boolean;
17
+ connectionTracking?: boolean;
16
18
  }
17
19
  export interface ChunksOutdatedPayload {
18
20
  deletedChunks: string[];
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-skew-protection",
3
3
  "type": "module",
4
- "version": "0.4.2",
4
+ "version": "0.5.0",
5
5
  "description": "Solve Nuxt version skews with persistent assets and instant updates.",
6
6
  "author": {
7
7
  "name": "Harlan Wilton",
@@ -54,7 +54,7 @@
54
54
  "consola": "^3.4.2",
55
55
  "cookie-es": "^2.0.0",
56
56
  "defu": "^6.1.4",
57
- "nuxt-site-config": "^3.2.12",
57
+ "nuxt-site-config": "^3.2.13",
58
58
  "ofetch": "^1.5.1",
59
59
  "pathe": "^2.0.3",
60
60
  "pkg-types": "^2.3.0",
@@ -85,7 +85,7 @@
85
85
  "ably": "^2.15.0",
86
86
  "better-sqlite3": "^12.5.0",
87
87
  "bumpp": "^10.3.2",
88
- "eslint": "^9.39.1",
88
+ "eslint": "^9.39.2",
89
89
  "eventsource": "^4.1.0",
90
90
  "execa": "^9.6.1",
91
91
  "firebase-functions": "^7.0.1",