nuxt-skew-protection 0.5.0 → 0.6.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.
Files changed (31) hide show
  1. package/dist/module.json +6 -1
  2. package/dist/module.mjs +21 -11
  3. package/dist/runtime/adapters/ably/node.js +3 -2
  4. package/dist/runtime/adapters/ably/web.js +3 -2
  5. package/dist/runtime/adapters/pusher/node.js +3 -2
  6. package/dist/runtime/adapters/pusher/web.js +3 -2
  7. package/dist/runtime/app/composables/useRuntimeConfigSkewProtection.d.ts +0 -1
  8. package/dist/runtime/app/composables/useRuntimeConfigSkewProtection.js +1 -5
  9. package/dist/runtime/app/composables/useSkewProtection.d.ts +13 -1
  10. package/dist/runtime/app/composables/useSkewProtection.js +43 -8
  11. package/dist/runtime/app/plugins/check-updates-adapter.client.d.ts +7 -1
  12. package/dist/runtime/app/plugins/check-updates-adapter.client.js +19 -36
  13. package/dist/runtime/app/plugins/check-updates-sse.client.d.ts +7 -1
  14. package/dist/runtime/app/plugins/check-updates-sse.client.js +21 -37
  15. package/dist/runtime/app/plugins/check-updates-websocket.client.d.ts +7 -1
  16. package/dist/runtime/app/plugins/check-updates-websocket.client.js +35 -64
  17. package/dist/runtime/app/types.d.ts +25 -0
  18. package/dist/runtime/app/types.js +0 -0
  19. package/dist/runtime/app/utils/create-skew-connection.d.ts +17 -0
  20. package/dist/runtime/app/utils/create-skew-connection.js +48 -0
  21. package/dist/runtime/const.d.ts +7 -0
  22. package/dist/runtime/const.js +6 -0
  23. package/dist/runtime/server/middleware/set-skew-protection-cookie.js +4 -7
  24. package/dist/runtime/server/plugins/connection-tracking-cloudflare-durable.d.ts +2 -0
  25. package/dist/runtime/server/plugins/connection-tracking-cloudflare-durable.js +34 -0
  26. package/dist/runtime/server/routes/_skew/sse.js +3 -3
  27. package/dist/runtime/server/routes/_skew/ws.js +8 -7
  28. package/dist/runtime/types.d.ts +0 -1
  29. package/package.json +6 -3
  30. package/dist/runtime/app/plugins/init-build-id.d.ts +0 -12
  31. package/dist/runtime/app/plugins/init-build-id.js +0 -29
package/dist/module.json CHANGED
@@ -4,7 +4,12 @@
4
4
  "nuxt": ">=4.0.0"
5
5
  },
6
6
  "configKey": "skewProtection",
7
- "version": "0.5.0",
7
+ "moduleDependencies": {
8
+ "@nuxtjs/robots": {
9
+ "version": ">=5.6.7"
10
+ }
11
+ },
12
+ "version": "0.6.0",
8
13
  "builder": {
9
14
  "@nuxt/module-builder": "1.0.2",
10
15
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { writeFileSync, unlinkSync, existsSync, readFileSync, promises } from 'node:fs';
2
- import { useLogger, useNuxt, tryUseNuxt, defineNuxtModule, createResolver, hasNuxtModule, addTypeTemplate, addComponent, addImports, addPlugin, addServerHandler, tryResolveModule, addTemplate } from '@nuxt/kit';
2
+ import { useLogger, useNuxt, tryUseNuxt, defineNuxtModule, createResolver, hasNuxtModule, addTypeTemplate, addComponent, addImports, addServerHandler, addPlugin, tryResolveModule, addTemplate } from '@nuxt/kit';
3
3
  import { colors } from 'consola/utils';
4
4
  import { useSiteConfig, installNuxtSiteConfig } from 'nuxt-site-config/kit';
5
5
  import { readPackageJSON } from 'pkg-types';
@@ -725,7 +725,12 @@ const module$1 = defineNuxtModule({
725
725
  compatibility: {
726
726
  nuxt: ">=4.0.0"
727
727
  },
728
- configKey: "skewProtection"
728
+ configKey: "skewProtection",
729
+ moduleDependencies: {
730
+ "@nuxtjs/robots": {
731
+ version: ">=5.6.7"
732
+ }
733
+ }
729
734
  },
730
735
  defaults: {
731
736
  retentionDays: 30,
@@ -771,14 +776,18 @@ const module$1 = defineNuxtModule({
771
776
  addTypeTemplate({
772
777
  filename: "types/nuxt-skew-protection.d.ts",
773
778
  getContents: () => `// Generated by nuxt-skew-protection
779
+ import type { ChunksOutdatedPayload, SkewAdapterConfig, SkewConnection, SkewSSEConfig, SkewWebSocketConfig } from '#skew-protection/app/types'
780
+
774
781
  declare module '#app' {
775
782
  interface RuntimeNuxtHooks {
776
783
  'skew-protection:chunks-outdated': (payload: ChunksOutdatedPayload) => void | Promise<void>
777
784
  'skew:message': (message: { type: string, [key: string]: unknown }) => void | Promise<void>
785
+ 'skew:ws:config': (config: SkewWebSocketConfig) => void | Promise<void>
786
+ 'skew:sse:config': (config: SkewSSEConfig) => void | Promise<void>
787
+ 'skew:adapter:config': (config: SkewAdapterConfig) => void | Promise<void>
778
788
  }
779
789
  interface NuxtApp {
780
- $skewProtectionBuildId: Ref<string | undefined>
781
- $skewProtectionCookie: Ref<string | undefined>
790
+ $skewConnection?: SkewConnection
782
791
  }
783
792
  interface NuxtAppManifestMeta {
784
793
  skewProtection?: {
@@ -796,10 +805,12 @@ declare module 'nuxt/app' {
796
805
  interface RuntimeNuxtHooks {
797
806
  'skew-protection:chunks-outdated': (payload: ChunksOutdatedPayload) => void | Promise<void>
798
807
  'skew:message': (message: { type: string, [key: string]: unknown }) => void | Promise<void>
808
+ 'skew:ws:config': (config: SkewWebSocketConfig) => void | Promise<void>
809
+ 'skew:sse:config': (config: SkewSSEConfig) => void | Promise<void>
810
+ 'skew:adapter:config': (config: SkewAdapterConfig) => void | Promise<void>
799
811
  }
800
812
  interface NuxtApp {
801
- $skewProtectionBuildId: Ref<string | undefined>
802
- $skewProtectionCookie: Ref<string | undefined>
813
+ $skewConnection?: SkewConnection
803
814
  }
804
815
  interface NuxtAppManifestMeta {
805
816
  skewProtection?: {
@@ -813,7 +824,7 @@ declare module 'nuxt/app' {
813
824
  }
814
825
  }
815
826
 
816
- export {}
827
+ export type { ChunksOutdatedPayload, SkewAdapterConfig, SkewConnection, SkewSSEConfig, SkewWebSocketConfig }
817
828
  `
818
829
  }, { nuxt: true });
819
830
  addTypeTemplate({
@@ -848,11 +859,10 @@ export {}
848
859
  });
849
860
  nuxt.options.nitro = nuxt.options.nitro || {};
850
861
  nuxt.options.nitro.plugins = nuxt.options.nitro.plugins || [];
851
- nuxt.options.nitro.plugins.push(resolver.resolve("./runtime/server/plugins/connection-tracking"));
862
+ const connectionTrackingPlugin = nitroPreset === "cloudflare-durable" ? "./runtime/server/plugins/connection-tracking-cloudflare-durable" : "./runtime/server/plugins/connection-tracking";
863
+ nuxt.options.nitro.plugins.push(resolver.resolve(connectionTrackingPlugin));
852
864
  }
853
- addPlugin({
854
- src: resolver.resolve("./runtime/app/plugins/init-build-id")
855
- });
865
+ nuxt.options.alias["#skew-protection"] = resolver.resolve("./runtime");
856
866
  nuxt.options.alias["nuxt-skew-protection/server"] = resolver.resolve("./runtime/server");
857
867
  if (options.storage?.driver) {
858
868
  nuxt.options.nitro = nuxt.options.nitro || {};
@@ -1,9 +1,10 @@
1
1
  import { Rest } from "ably";
2
2
  import { defineNodeBroadcast } from "../../../utils";
3
+ import { SKEW_DEFAULT_CHANNEL, SKEW_MESSAGE_TYPE } from "../../const.js";
3
4
  export const broadcast = defineNodeBroadcast(async (config, version) => {
4
5
  const ably = new Rest({ key: config.key });
5
- const channelName = config.channel || "skew-protection";
6
- const eventName = config.event || "VersionUpdated";
6
+ const channelName = config.channel || SKEW_DEFAULT_CHANNEL;
7
+ const eventName = config.event || SKEW_MESSAGE_TYPE.VERSION;
7
8
  const channel = ably.channels.get(channelName);
8
9
  await channel.publish(eventName, { version });
9
10
  });
@@ -1,12 +1,13 @@
1
1
  import { onNuxtReady } from "nuxt/app";
2
2
  import { defineWebSubscribe } from "../../../utils";
3
+ import { SKEW_DEFAULT_CHANNEL, SKEW_MESSAGE_TYPE } from "../../const.js";
3
4
  export const subscribe = defineWebSubscribe((config, onMessage) => {
4
5
  let cleanup;
5
6
  onNuxtReady(async () => {
6
7
  const { Realtime } = await import("ably");
7
8
  const ably = new Realtime({ key: config.key });
8
- const channelName = config.channel || "skew-protection";
9
- const eventName = config.event || "VersionUpdated";
9
+ const channelName = config.channel || SKEW_DEFAULT_CHANNEL;
10
+ const eventName = config.event || SKEW_MESSAGE_TYPE.VERSION;
10
11
  const channel = ably.channels.get(channelName);
11
12
  await channel.subscribe(eventName, (message) => {
12
13
  const data = typeof message.data === "string" ? JSON.parse(message.data) : message.data;
@@ -1,8 +1,9 @@
1
1
  import { createHash, createHmac } from "node:crypto";
2
2
  import { defineNodeBroadcast } from "../../../utils";
3
+ import { SKEW_DEFAULT_CHANNEL, SKEW_MESSAGE_TYPE } from "../../const.js";
3
4
  export const broadcast = defineNodeBroadcast(async (config, version) => {
4
- const channelName = config.channel || "skew-protection";
5
- const eventName = config.event || "VersionUpdated";
5
+ const channelName = config.channel || SKEW_DEFAULT_CHANNEL;
6
+ const eventName = config.event || SKEW_MESSAGE_TYPE.VERSION;
6
7
  const body = JSON.stringify({
7
8
  name: eventName,
8
9
  channel: channelName,
@@ -1,5 +1,6 @@
1
1
  import { onNuxtReady } from "nuxt/app";
2
2
  import { defineWebSubscribe } from "../../../utils";
3
+ import { SKEW_DEFAULT_CHANNEL, SKEW_MESSAGE_TYPE } from "../../const.js";
3
4
  export const subscribe = defineWebSubscribe((config, onMessage) => {
4
5
  let cleanup;
5
6
  onNuxtReady(async () => {
@@ -7,8 +8,8 @@ export const subscribe = defineWebSubscribe((config, onMessage) => {
7
8
  const pusher = new Pusher(config.key, {
8
9
  cluster: config.cluster
9
10
  });
10
- const channelName = config.channel || "skew-protection";
11
- const eventName = config.event || "VersionUpdated";
11
+ const channelName = config.channel || SKEW_DEFAULT_CHANNEL;
12
+ const eventName = config.event || SKEW_MESSAGE_TYPE.VERSION;
12
13
  const channel = pusher.subscribe(channelName);
13
14
  channel.bind(eventName, (data) => {
14
15
  onMessage({ version: data.version });
@@ -1,6 +1,5 @@
1
1
  import type { SkewProtectionRuntimeConfig } from '../../types.js';
2
2
  /**
3
3
  * Get skew protection runtime config with proper types
4
- * Ensures cookie config is always defined with required properties
5
4
  */
6
5
  export declare function useRuntimeConfigSkewProtection(): SkewProtectionRuntimeConfig;
@@ -1,8 +1,4 @@
1
1
  import { useRuntimeConfig } from "nuxt/app";
2
2
  export function useRuntimeConfigSkewProtection() {
3
- const config = useRuntimeConfig();
4
- return {
5
- ...config.public.skewProtection,
6
- buildId: config.app.buildId
7
- };
3
+ return useRuntimeConfig().public.skewProtection;
8
4
  }
@@ -1,11 +1,23 @@
1
1
  import type { NuxtAppManifestMeta } from 'nuxt/app';
2
2
  import type { ChunksOutdatedPayload } from '../../types.js';
3
+ export interface UseSkewProtectionOptions {
4
+ /**
5
+ * Lazy connection mode - don't auto-connect on mount
6
+ * When false (default), connections are established automatically on mount
7
+ * When true, users must call connect() manually
8
+ * @default false
9
+ */
10
+ lazy?: boolean;
11
+ }
3
12
  export declare function checkForUpdates(): Promise<void>;
4
- export declare function useSkewProtection(): {
13
+ export declare function useSkewProtection(options?: UseSkewProtectionOptions): {
5
14
  manifest: import("vue").Ref<NuxtAppManifestMeta | undefined, NuxtAppManifestMeta | undefined>;
6
15
  clientVersion: any;
16
+ isConnected: import("vue").ComputedRef<boolean>;
7
17
  isOnline: Readonly<import("vue").ShallowRef<boolean>>;
8
18
  isOutdated: import("vue").ComputedRef<boolean | undefined>;
19
+ connect: () => void;
20
+ disconnect: () => void;
9
21
  onCurrentChunksOutdated: (callback: (payload: ChunksOutdatedPayload) => void | Promise<void>) => () => void;
10
22
  onAppOutdated: (callback: (manifest?: NuxtAppManifestMeta) => void | Promise<void>) => () => void;
11
23
  checkForUpdates: typeof checkForUpdates;
@@ -1,14 +1,16 @@
1
1
  import { buildAssetsURL } from "#internal/nuxt/paths";
2
2
  import { useOnline } from "@vueuse/core";
3
- import { useNuxtApp } from "nuxt/app";
4
- import { computed, onUnmounted, ref } from "vue";
5
- import { useRuntimeConfigSkewProtection } from "./useRuntimeConfigSkewProtection.js";
3
+ import { useNuxtApp, useRuntimeConfig } from "nuxt/app";
4
+ import { computed, onMounted, onUnmounted, ref } from "vue";
5
+ import { SKEW_MESSAGE_TYPE } from "../../const.js";
6
+ import { logger } from "../../shared/logger.js";
7
+ import { createBackoffQueue } from "../utils/backoff-queue.js";
8
+ const isConnected = ref(false);
6
9
  export async function checkForUpdates() {
7
10
  if (import.meta.client && !useOnline().value)
8
11
  return;
9
12
  const nuxtApp = useNuxtApp();
10
- const runtimeConfig = useRuntimeConfigSkewProtection();
11
- const clientVersion = nuxtApp.$skewProtectionBuildId?.value || runtimeConfig.buildId;
13
+ const clientVersion = nuxtApp.$skewConnection?.buildId || useRuntimeConfig().app.buildId;
12
14
  const meta = await $fetch(`${buildAssetsURL("builds/latest.json")}?${Date.now()}`).catch(() => {
13
15
  return null;
14
16
  });
@@ -16,11 +18,41 @@ export async function checkForUpdates() {
16
18
  await nuxtApp.hooks.callHook("app:manifest:update", meta);
17
19
  }
18
20
  }
19
- export function useSkewProtection() {
21
+ export function useSkewProtection(options = {}) {
22
+ const { lazy = false } = options;
20
23
  const nuxtApp = useNuxtApp();
21
- const runtimeConfig = useRuntimeConfigSkewProtection();
22
- const clientVersion = nuxtApp.$skewProtectionBuildId?.value || nuxtApp.$skewProtectionCookie?.value || runtimeConfig.buildId;
24
+ const clientVersion = nuxtApp.$skewConnection?.buildId || nuxtApp.$skewConnection?.cookie?.value || useRuntimeConfig().app.buildId;
23
25
  const manifest = ref();
26
+ const queue = createBackoffQueue({
27
+ delays: [0, 5e3, 3e4, 3e5],
28
+ onTick: () => nuxtApp.runWithContext(checkForUpdates)
29
+ });
30
+ if (!lazy) {
31
+ onMounted(() => {
32
+ nuxtApp.$skewConnection?.connect();
33
+ });
34
+ }
35
+ nuxtApp.hooks.hook("skew:message", (msg) => {
36
+ if (msg.type !== SKEW_MESSAGE_TYPE.VERSION && msg.type !== SKEW_MESSAGE_TYPE.CONNECTED)
37
+ return;
38
+ if (!msg.version || msg.version === clientVersion)
39
+ return;
40
+ logger.debug(`[SkewProtection] Version mismatch (${msg.version} !== ${clientVersion}), starting backoff checks`);
41
+ queue.start();
42
+ });
43
+ function connect() {
44
+ if (!import.meta.client || isConnected.value)
45
+ return;
46
+ isConnected.value = true;
47
+ nuxtApp.$skewConnection?.connect();
48
+ }
49
+ function disconnect() {
50
+ if (!import.meta.client || !isConnected.value)
51
+ return;
52
+ isConnected.value = false;
53
+ queue.clear();
54
+ nuxtApp.$skewConnection?.disconnect();
55
+ }
24
56
  function onCurrentChunksOutdated(callback) {
25
57
  const hook = nuxtApp.hooks.hook("skew-protection:chunks-outdated", callback);
26
58
  onUnmounted(() => {
@@ -45,8 +77,11 @@ export function useSkewProtection() {
45
77
  return {
46
78
  manifest,
47
79
  clientVersion,
80
+ isConnected: computed(() => isConnected.value),
48
81
  isOnline: useOnline(),
49
82
  isOutdated: computed(() => manifest.value && clientVersion !== manifest.value.id),
83
+ connect,
84
+ disconnect,
50
85
  onCurrentChunksOutdated,
51
86
  onAppOutdated,
52
87
  checkForUpdates,
@@ -1,2 +1,8 @@
1
- declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
1
+ import type { SkewAdapterConfig } from '../types.js';
2
+ export type { SkewAdapterConfig };
3
+ declare const _default: import("nuxt/app").Plugin<{
4
+ skewConnection: import("../utils/create-skew-connection.js").SkewConnection;
5
+ }> & import("nuxt/app").ObjectPlugin<{
6
+ skewConnection: import("../utils/create-skew-connection.js").SkewConnection;
7
+ }>;
2
8
  export default _default;
@@ -1,42 +1,25 @@
1
- import { config, subscribe } from "#skew-adapter";
2
- import { defineNuxtPlugin, useRuntimeConfig } from "nuxt/app";
3
- import { logger } from "../../shared/logger.js";
4
- import { checkForUpdates, useSkewProtection } from "../composables/useSkewProtection.js";
5
- import { createBackoffQueue } from "../utils/backoff-queue.js";
1
+ import { config as adapterConfig, subscribe } from "#skew-adapter";
2
+ import { defineNuxtPlugin, useNuxtApp, useRuntimeConfig } from "nuxt/app";
3
+ import { SKEW_MESSAGE_TYPE } from "../../const.js";
4
+ import { createSkewConnection } from "../utils/create-skew-connection.js";
6
5
  export default defineNuxtPlugin({
7
6
  name: "skew-protection:adapter-updates",
8
- setup(nuxtApp) {
9
- const { clientVersion } = useSkewProtection();
7
+ async setup() {
8
+ const nuxtApp = useNuxtApp();
10
9
  const adapterName = useRuntimeConfig().public.skewProtection.adapterName;
11
- const channel = config.channel || "skew-protection";
12
- logger.debug(`[${adapterName}] Subscribing to channel: ${channel}`);
13
- let cleanup = null;
14
- const queue = createBackoffQueue({
15
- delays: [0, 5e3, 3e4, 3e5],
16
- onTick: () => nuxtApp.runWithContext(checkForUpdates)
10
+ const config = {
11
+ channel: adapterConfig.channel || "skew-protection",
12
+ adapterConfig
13
+ };
14
+ await nuxtApp.callHook("skew:adapter:config", config);
15
+ const skewConnection = createSkewConnection({
16
+ name: `Adapter:${adapterName}`,
17
+ setup(onMessage) {
18
+ return subscribe(config.adapterConfig, (msg) => {
19
+ onMessage({ type: SKEW_MESSAGE_TYPE.VERSION, channel: config.channel, ...msg });
20
+ });
21
+ }
17
22
  });
18
- nuxtApp.hook("app:mounted", () => {
19
- cleanup = subscribe(config, (msg) => {
20
- if (!msg.version) {
21
- logger.debug(`[${adapterName}] Received message without version, ignoring`);
22
- return;
23
- }
24
- logger.debug(`[${adapterName}] Received version: ${msg.version}`);
25
- if (msg.version !== clientVersion) {
26
- logger.debug(`[${adapterName}] Version mismatch (${msg.version} !== ${clientVersion}), starting backoff checks`);
27
- queue.start();
28
- }
29
- });
30
- });
31
- nuxtApp.hook("app:error", () => {
32
- queue.clear();
33
- cleanup?.();
34
- });
35
- if (import.meta.client) {
36
- window.addEventListener("beforeunload", () => {
37
- queue.clear();
38
- cleanup?.();
39
- });
40
- }
23
+ return { provide: { skewConnection } };
41
24
  }
42
25
  });
@@ -1,2 +1,8 @@
1
- declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
1
+ import type { SkewSSEConfig } from '../types.js';
2
+ export type { SkewSSEConfig };
3
+ declare const _default: import("nuxt/app").Plugin<{
4
+ skewConnection: import("../utils/create-skew-connection.js").SkewConnection;
5
+ }> & import("nuxt/app").ObjectPlugin<{
6
+ skewConnection: import("../utils/create-skew-connection.js").SkewConnection;
7
+ }>;
2
8
  export default _default;
@@ -1,46 +1,30 @@
1
1
  import { useEventSource } from "@vueuse/core";
2
- import { defineNuxtPlugin } from "nuxt/app";
2
+ import { defineNuxtPlugin, useNuxtApp } from "nuxt/app";
3
3
  import { watch } from "vue";
4
- import { logger } from "../../shared/logger.js";
5
- import { checkForUpdates, useSkewProtection } from "../composables/useSkewProtection.js";
4
+ import { createSkewConnection } from "../utils/create-skew-connection.js";
6
5
  export default defineNuxtPlugin({
7
6
  name: "skew-protection:sse-updates",
8
- setup(nuxtApp) {
9
- const { clientVersion } = useSkewProtection();
10
- logger.debug("[SSE] Initializing SSE connection for version updates");
11
- const { data, status, error } = useEventSource(`/_skew/sse`, [], {
12
- autoReconnect: {
13
- retries: 10,
14
- delay: 5e3,
15
- onFailed() {
16
- logger.error("[SSE] Max reconnection attempts reached");
17
- }
18
- },
19
- serializer: {
20
- // @ts-expect-error untyped
21
- read: (rawData) => JSON.parse(rawData)
7
+ async setup() {
8
+ const nuxtApp = useNuxtApp();
9
+ const config = {
10
+ url: "/_skew/sse",
11
+ options: {
12
+ autoReconnect: { retries: 10, delay: 5e3 }
22
13
  }
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
- });
31
- watch(data, (message) => {
32
- logger.debug("[SSE] Message received:", message);
33
- if (!message)
34
- return;
35
- nuxtApp.hooks.callHook("skew:message", message);
36
- if (message.type === "connected" && message.version) {
37
- const newVersion = message.version;
38
- logger.debug(`[SSE] Server version: ${newVersion}, Client version: ${clientVersion}`);
39
- if (newVersion !== clientVersion) {
40
- logger.debug("[SSE] Version mismatch detected, triggering update check");
41
- nuxtApp.runWithContext(checkForUpdates);
42
- }
14
+ };
15
+ await nuxtApp.callHook("skew:sse:config", config);
16
+ const skewConnection = createSkewConnection({
17
+ name: "SSE",
18
+ setup(onMessage) {
19
+ const sse = useEventSource(config.url, [], config.options);
20
+ watch(sse.data, (raw) => {
21
+ if (!raw)
22
+ return;
23
+ onMessage(JSON.parse(raw));
24
+ });
25
+ return sse.close;
43
26
  }
44
27
  });
28
+ return { provide: { skewConnection } };
45
29
  }
46
30
  });
@@ -1,2 +1,8 @@
1
- declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
1
+ import type { SkewWebSocketConfig } from '../types.js';
2
+ export type { SkewWebSocketConfig };
3
+ declare const _default: import("nuxt/app").Plugin<{
4
+ skewConnection: import("../utils/create-skew-connection.js").SkewConnection;
5
+ }> & import("nuxt/app").ObjectPlugin<{
6
+ skewConnection: import("../utils/create-skew-connection.js").SkewConnection;
7
+ }>;
2
8
  export default _default;
@@ -1,71 +1,42 @@
1
1
  import { useWebSocket } from "@vueuse/core";
2
- import { defineNuxtPlugin } from "nuxt/app";
2
+ import { defineNuxtPlugin, useNuxtApp } from "nuxt/app";
3
3
  import { watch } from "vue";
4
- import { logger } from "../../shared/logger.js";
5
- import { checkForUpdates, useSkewProtection } from "../composables/useSkewProtection.js";
4
+ import { SKEW_MESSAGE_TYPE } from "../../const.js";
5
+ import { createSkewConnection } from "../utils/create-skew-connection.js";
6
6
  export default defineNuxtPlugin({
7
- name: "skew-protection:websocket-updates",
8
- setup(nuxtApp) {
9
- const { clientVersion } = useSkewProtection();
10
- const protocol = typeof window !== "undefined" && window.location.protocol === "https:" ? "wss:" : "ws:";
11
- const url = typeof window !== "undefined" ? `${protocol}//${window.location.host}/_skew/ws` : "";
12
- logger.debug(`[WS] Initializing WebSocket connection: ${url}`);
13
- const {
14
- data,
15
- status,
16
- open,
17
- close
18
- } = useWebSocket(url, {
19
- autoReconnect: {
20
- retries: 10,
21
- delay: 5e3,
22
- onFailed() {
23
- logger.error("[WS] Max reconnection attempts reached");
24
- }
25
- },
26
- heartbeat: {
27
- message: JSON.stringify({
28
- type: "ping",
29
- timestamp: Date.now()
30
- }),
31
- interval: 3e4,
32
- pongTimeout: 1e4
33
- },
34
- immediate: false
35
- });
36
- watch(status, (newStatus) => {
37
- logger.debug(`[WS] Connection status changed: ${newStatus}`);
38
- });
39
- watch(data, (message) => {
40
- if (!message)
41
- return;
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);
53
- }
7
+ name: "skew-protection:ws-updates",
8
+ async setup() {
9
+ const nuxtApp = useNuxtApp();
10
+ const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
11
+ const config = {
12
+ url: `${protocol}//${window.location.host}/_skew/ws`,
13
+ options: {
14
+ autoReconnect: { retries: 10, delay: 5e3 },
15
+ heartbeat: {
16
+ message: JSON.stringify({ type: SKEW_MESSAGE_TYPE.PING, timestamp: Date.now() }),
17
+ interval: 3e4,
18
+ pongTimeout: 1e4
19
+ },
20
+ immediate: false
21
+ }
22
+ };
23
+ await nuxtApp.callHook("skew:ws:config", config);
24
+ const skewConnection = createSkewConnection({
25
+ name: "WS",
26
+ setup(onMessage) {
27
+ const ws = useWebSocket(config.url, config.options);
28
+ watch(ws.data, (raw) => {
29
+ if (!raw)
30
+ return;
31
+ const msg = JSON.parse(raw);
32
+ if (msg.type === SKEW_MESSAGE_TYPE.PING)
33
+ return;
34
+ onMessage(msg);
35
+ });
36
+ ws.open();
37
+ return ws.close;
54
38
  }
55
39
  });
56
- nuxtApp.hook("app:mounted", () => {
57
- logger.debug("[WS] App mounted, opening connection");
58
- open();
59
- });
60
- nuxtApp.hook("app:error", () => {
61
- logger.debug("[WS] App error, closing connection");
62
- close();
63
- });
64
- if (import.meta.client) {
65
- window.addEventListener("beforeunload", () => {
66
- logger.debug("[WS] Page unload, closing connection");
67
- close();
68
- });
69
- }
40
+ return { provide: { skewConnection } };
70
41
  }
71
42
  });
@@ -0,0 +1,25 @@
1
+ import type { UseEventSourceOptions, UseWebSocketOptions } from '@vueuse/core';
2
+ import type { Ref } from 'vue';
3
+ export interface SkewWebSocketConfig {
4
+ url: string;
5
+ options: UseWebSocketOptions;
6
+ }
7
+ export interface SkewSSEConfig {
8
+ url: string;
9
+ options: UseEventSourceOptions<string>;
10
+ }
11
+ export interface SkewAdapterConfig {
12
+ channel: string;
13
+ adapterConfig: Record<string, unknown>;
14
+ }
15
+ export interface ChunksOutdatedPayload {
16
+ deletedChunks: string[];
17
+ invalidatedModules: string[];
18
+ passedReleases: string[];
19
+ }
20
+ export interface SkewConnection {
21
+ connect: () => void;
22
+ disconnect: () => void;
23
+ buildId: string;
24
+ cookie: Ref<string | null | undefined>;
25
+ }
File without changes
@@ -0,0 +1,17 @@
1
+ import type { Ref } from 'vue';
2
+ export interface SkewMessage {
3
+ type: string;
4
+ version?: string;
5
+ [key: string]: unknown;
6
+ }
7
+ export interface CreateSkewConnectionConfig {
8
+ name: string;
9
+ setup: (onMessage: (msg: SkewMessage) => void) => (() => void) | void;
10
+ }
11
+ export interface SkewConnection {
12
+ connect: () => void;
13
+ disconnect: () => void;
14
+ buildId: string;
15
+ cookie: Ref<string | null | undefined>;
16
+ }
17
+ export declare function createSkewConnection(config: CreateSkewConnectionConfig): SkewConnection;
@@ -0,0 +1,48 @@
1
+ import { useBotDetection } from "#imports";
2
+ import { useCookie, useNuxtApp, useRuntimeConfig } from "nuxt/app";
3
+ import { init, logger } from "../../shared/logger.js";
4
+ export function createSkewConnection(config) {
5
+ const { name, setup } = config;
6
+ const nuxtApp = useNuxtApp();
7
+ const runtimeConfig = useRuntimeConfig();
8
+ const buildId = runtimeConfig.app.buildId;
9
+ init();
10
+ const { isBot } = useBotDetection();
11
+ const cookieConfig = runtimeConfig.public.skewProtection.cookie;
12
+ const { name: cookieName, ...cookieOpts } = cookieConfig;
13
+ const cookie = useCookie(cookieName, { ...cookieOpts, readonly: false });
14
+ if (isBot.value) {
15
+ logger.debug(`[${name}] Skipping connection for bot`);
16
+ return { connect: () => {
17
+ }, disconnect: () => {
18
+ }, buildId, cookie };
19
+ }
20
+ if (import.meta.client && !cookie.value) {
21
+ cookie.value = buildId;
22
+ }
23
+ let cleanup;
24
+ let isConnected = false;
25
+ const handleMessage = (msg) => {
26
+ logger.debug(`[${name}] Received message:`, msg.type);
27
+ nuxtApp.hooks.callHook("skew:message", msg);
28
+ };
29
+ const connect = () => {
30
+ if (isConnected)
31
+ return;
32
+ isConnected = true;
33
+ logger.debug(`[${name}] Connecting`);
34
+ cleanup = setup(handleMessage);
35
+ };
36
+ const disconnect = () => {
37
+ if (!isConnected)
38
+ return;
39
+ isConnected = false;
40
+ logger.debug(`[${name}] Disconnecting`);
41
+ cleanup?.();
42
+ };
43
+ nuxtApp.hook("app:error", disconnect);
44
+ if (import.meta.client) {
45
+ window.addEventListener("beforeunload", disconnect);
46
+ }
47
+ return { connect, disconnect, buildId, cookie };
48
+ }
@@ -0,0 +1,7 @@
1
+ export declare const SKEW_MESSAGE_TYPE: {
2
+ readonly VERSION: "version";
3
+ readonly CONNECTED: "connected";
4
+ readonly PING: "ping";
5
+ };
6
+ export type SkewMessageType = typeof SKEW_MESSAGE_TYPE[keyof typeof SKEW_MESSAGE_TYPE];
7
+ export declare const SKEW_DEFAULT_CHANNEL = "skew-protection";
@@ -0,0 +1,6 @@
1
+ export const SKEW_MESSAGE_TYPE = {
2
+ VERSION: "version",
3
+ CONNECTED: "connected",
4
+ PING: "ping"
5
+ };
6
+ export const SKEW_DEFAULT_CHANNEL = "skew-protection";
@@ -3,13 +3,10 @@ import { useRuntimeConfig } from "nitropack/runtime";
3
3
  import { setSkewProtectionCookie } from "../imports/cookie.js";
4
4
  export default defineEventHandler(async (event) => {
5
5
  const secFetchDest = getHeader(event, "sec-fetch-dest");
6
- if (secFetchDest !== "document") {
6
+ if (secFetchDest !== "document")
7
7
  return;
8
- }
9
- const config = useRuntimeConfig(event);
10
- const currentBuildId = config.app.buildId;
11
- if (!currentBuildId) {
8
+ const buildId = useRuntimeConfig(event).app.buildId;
9
+ if (!buildId)
12
10
  return;
13
- }
14
- setSkewProtectionCookie(event, currentBuildId);
11
+ setSkewProtectionCookie(event, buildId);
15
12
  });
@@ -0,0 +1,2 @@
1
+ declare const _default: import("nitropack/types").NitroAppPlugin;
2
+ export default _default;
@@ -0,0 +1,34 @@
1
+ import { defineNitroPlugin } from "nitropack/runtime";
2
+ function getCtx(peer) {
3
+ return peer?._internal?.durable?.ctx || null;
4
+ }
5
+ function getStats(ctx) {
6
+ const websockets = ctx.getWebSockets();
7
+ const versions = {};
8
+ for (const ws of websockets) {
9
+ const v = ws.deserializeAttachment?.()?.v || "unknown";
10
+ versions[v] = (versions[v] || 0) + 1;
11
+ }
12
+ return { total: websockets.length, versions };
13
+ }
14
+ function broadcast(ctx) {
15
+ const stats = getStats(ctx);
16
+ const msg = JSON.stringify({ type: "stats", ...stats });
17
+ for (const ws of ctx.getWebSockets()) ws.send(msg);
18
+ }
19
+ export default defineNitroPlugin((nitroApp) => {
20
+ nitroApp.hooks.hook("skew:connection:open", ({ version, peer }) => {
21
+ const ws = peer?._internal?.ws;
22
+ if (ws?.serializeAttachment) {
23
+ ws.serializeAttachment({ ...ws.deserializeAttachment?.() || {}, v: version });
24
+ }
25
+ const ctx = getCtx(peer);
26
+ if (ctx)
27
+ broadcast(ctx);
28
+ });
29
+ nitroApp.hooks.hook("skew:connection:close", ({ peer }) => {
30
+ const ctx = getCtx(peer);
31
+ if (ctx)
32
+ broadcast(ctx);
33
+ });
34
+ });
@@ -1,16 +1,16 @@
1
1
  import { createEventStream, defineEventHandler } from "h3";
2
2
  import { useNitroApp, useRuntimeConfig } from "nitropack/runtime";
3
+ import { SKEW_MESSAGE_TYPE } from "../../../const.js";
3
4
  import { getSkewProtectionCookie } from "../../imports/cookie.js";
4
5
  export default defineEventHandler(async (event) => {
5
6
  const nitroApp = useNitroApp();
6
7
  const stream = createEventStream(event);
7
- const config = useRuntimeConfig();
8
- const serverVersion = config.app.buildId;
8
+ const serverVersion = useRuntimeConfig(event).app.buildId;
9
9
  const send = (data) => {
10
10
  stream.push(JSON.stringify(data));
11
11
  };
12
12
  send({
13
- type: "connected",
13
+ type: SKEW_MESSAGE_TYPE.CONNECTED,
14
14
  version: serverVersion,
15
15
  timestamp: Date.now()
16
16
  });
@@ -1,24 +1,25 @@
1
1
  import { parse as parseCookie } from "cookie-es";
2
2
  import { defineWebSocketHandler } from "h3";
3
3
  import { useNitroApp, useRuntimeConfig } from "nitropack/runtime";
4
+ import { SKEW_MESSAGE_TYPE } from "../../../const.js";
5
+ import { getSkewProtectionCookieName } from "../../imports/cookie.js";
4
6
  export default defineWebSocketHandler({
5
7
  open(peer) {
6
- const runtimeConfig = useRuntimeConfig();
7
- const serverVersion = runtimeConfig.app?.buildId;
8
- const skewConfig = runtimeConfig.public.skewProtection;
8
+ const serverVersion = useRuntimeConfig().app.buildId;
9
+ const cookieName = getSkewProtectionCookieName();
9
10
  peer.send(JSON.stringify({
10
- type: "connected",
11
+ type: SKEW_MESSAGE_TYPE.CONNECTED,
11
12
  version: serverVersion,
12
13
  timestamp: Date.now()
13
14
  }));
14
15
  const cookieHeader = peer.request?.headers?.get("cookie") || "";
15
16
  const cookies = parseCookie(cookieHeader);
16
- const cookieName = skewConfig?.cookie?.name || "__nkpv";
17
17
  const clientVersion = cookies[cookieName] || serverVersion;
18
18
  useNitroApp().hooks.callHook("skew:connection:open", {
19
19
  id: peer.id,
20
20
  version: clientVersion,
21
- send: (data) => peer.send(JSON.stringify(data))
21
+ send: (data) => peer.send(JSON.stringify(data)),
22
+ peer
22
23
  });
23
24
  },
24
25
  message(peer, message) {
@@ -27,6 +28,6 @@ export default defineWebSocketHandler({
27
28
  }
28
29
  },
29
30
  close(peer) {
30
- useNitroApp().hooks.callHook("skew:connection:close", { id: peer.id });
31
+ useNitroApp().hooks.callHook("skew:connection:close", { id: peer.id, peer });
31
32
  }
32
33
  });
@@ -12,7 +12,6 @@ export interface SkewProtectionRuntimeConfig {
12
12
  cookie: Omit<CookieSerializeOptions, 'encode'> & {
13
13
  name: string;
14
14
  };
15
- buildId: string;
16
15
  debug: boolean;
17
16
  connectionTracking?: boolean;
18
17
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-skew-protection",
3
3
  "type": "module",
4
- "version": "0.5.0",
4
+ "version": "0.6.0",
5
5
  "description": "Solve Nuxt version skews with persistent assets and instant updates.",
6
6
  "author": {
7
7
  "name": "Harlan Wilton",
@@ -36,6 +36,7 @@
36
36
  "dist"
37
37
  ],
38
38
  "peerDependencies": {
39
+ "@nuxtjs/robots": ">=5.6.7",
39
40
  "ably": ">=2",
40
41
  "pusher-js": ">=8"
41
42
  },
@@ -54,7 +55,7 @@
54
55
  "consola": "^3.4.2",
55
56
  "cookie-es": "^2.0.0",
56
57
  "defu": "^6.1.4",
57
- "nuxt-site-config": "^3.2.13",
58
+ "nuxt-site-config": "^3.2.14",
58
59
  "ofetch": "^1.5.1",
59
60
  "pathe": "^2.0.3",
60
61
  "pkg-types": "^2.3.0",
@@ -75,6 +76,7 @@
75
76
  "@nuxtjs/color-mode": "^4.0.0",
76
77
  "@nuxtjs/eslint-config-typescript": "^12.1.0",
77
78
  "@nuxtjs/i18n": "^10.2.1",
79
+ "@nuxtjs/robots": "^5.6.7",
78
80
  "@types/ioredis": "^5.0.0",
79
81
  "@types/ws": "^8.18.1",
80
82
  "@unocss/nuxt": "66.5.10",
@@ -105,7 +107,8 @@
105
107
  "ws": "^8.18.3"
106
108
  },
107
109
  "resolutions": {
108
- "nuxt-skew-protection": "workspace:*"
110
+ "nuxt-skew-protection": "workspace:*",
111
+ "reka-ui": "2.6.1"
109
112
  },
110
113
  "scripts": {
111
114
  "lint": "eslint . --fix",
@@ -1,12 +0,0 @@
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;
@@ -1,29 +0,0 @@
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
- });