@devopsplaybook.io/common-web 0.10.0 → 0.11.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/CHANGELOG.md CHANGED
@@ -5,6 +5,44 @@ All notable changes to this project are documented here.
5
5
  This project follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/)
6
6
  and [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.11.0] - 2026-11-01
9
+
10
+ ### Added
11
+
12
+ - Optional CSP nonce for the pre-paint theme script: set
13
+ `COMMON_WEB_THEME_SCRIPT_NONCE` at build time, or build the head entry with
14
+ the new `themeInitScriptEntry(nonce)` helper and override `app.head.script`
15
+ in the consuming application for per-request nonces.
16
+ - Cross-tab theme synchronisation through the `storage` event.
17
+
18
+ ### Changed
19
+
20
+ - `useTheme()` state is a module-wide singleton: every call shares
21
+ `preference` and `isDark`, so independent instances stay in sync. The public
22
+ API is unchanged.
23
+ - `useOfflineStatus()` starts from `true` and reads `navigator.onLine` after
24
+ mount, so a page loaded offline hydrates without a mismatch and shows the
25
+ banner immediately afterwards.
26
+ - `PreferencesService` and `RefreshIntervalService` route storage through the
27
+ shared guarded helper and are now safe during SSR and with blocked storage.
28
+
29
+ ### Fixed
30
+
31
+ - M3: `useTheme()` no longer throws when `localStorage` is missing or blocked
32
+ (sandboxed iframe, privacy mode); the theme still applies and persistence is
33
+ skipped.
34
+ - M4: theme state is shared between `useTheme()` instances and across tabs.
35
+ - M8: `OfflineBanner` no longer produces a hydration mismatch on an offline
36
+ page.
37
+ - L1: `PreferencesService` and `RefreshIntervalService` fall back instead of
38
+ throwing without storage.
39
+ - L9: the injected theme script accepts a CSP nonce.
40
+ - L13: unmounting one `useAppHeight()` instance no longer cancels a pending
41
+ frame scheduled by another; the shared frame is cancelled with the last
42
+ instance.
43
+
44
+ No dependency changed and no OpenTelemetry metric is added in this release.
45
+
8
46
  ## [0.10.0] - 2026-11-01
9
47
 
10
48
  ### Added
package/README.md CHANGED
@@ -61,32 +61,51 @@ const NuxtLink = resolveComponent("NuxtLink");
61
61
 
62
62
  `OfflineBanner` keeps its `role="status"` live region mounted at all times so
63
63
  screen readers announce the transition; while online the region is visually
64
- hidden. The default copy is the neutral `You are offline.`; replace it with
65
- the `message` prop or the default slot.
64
+ hidden. The banner renders hidden in server HTML and reflects the real
65
+ connectivity right after hydration. The default copy is the neutral
66
+ `You are offline.`; replace it with the `message` prop or the default slot.
66
67
 
67
68
  ## Composables and services
68
69
 
69
70
  - `useTheme()` persists `light`/`dark` preferences in `localStorage` and applies
70
- `data-theme` to the document root. `isDark` reflects the effective theme: the
71
- default `system` preference follows `prefers-color-scheme`, including live
72
- operating-system changes, and `toggleTheme()` toggles from that effective
73
- value. Use `setTheme("system")` to return to the operating-system preference.
71
+ `data-theme` to the document root. State is a module-wide singleton: every
72
+ `useTheme()` call shares the same `preference` and `isDark` refs, so a second
73
+ call never sees a stale copy. A window `storage` listener keeps tabs in sync.
74
+ `isDark` reflects the effective theme: the default `system` preference
75
+ follows `prefers-color-scheme`, including live operating-system changes, and
76
+ `toggleTheme()` toggles from that effective value. Use `setTheme("system")`
77
+ to return to the operating-system preference. When `localStorage` is missing
78
+ (SSR) or blocked (sandboxed iframe, privacy mode), the theme still applies
79
+ and only persistence is skipped.
74
80
  The layer also injects a small pre-paint `<head>` script that applies
75
81
  `data-theme` from `localStorage` and `prefers-color-scheme` before first
76
82
  paint, so a stored dark preference no longer flashes the light theme during
77
83
  load. Applications with a strict CSP must allow this inline script (nonce or
78
84
  `unsafe-inline`); without it, the `prefers-color-scheme` CSS path still
79
85
  applies and the theme resolves after hydration.
86
+ Set the `COMMON_WEB_THEME_SCRIPT_NONCE` environment variable at build time to
87
+ add a nonce to the injected tag (it is read when `nuxt.config.ts` is
88
+ evaluated). Per-request nonces are not supported by the shared layer: build
89
+ the head entry with the exported
90
+ `themeInitScriptEntry(nonce)` helper from
91
+ `@devopsplaybook.io/common-web/composables/theme` and override
92
+ `app.head.script` in the consuming application.
80
93
  - `useAppHeight()` updates `--app-height` from `visualViewport` when available
81
94
  and cleans up resize listeners on unmount. Resize updates are coalesced with
82
95
  `requestAnimationFrame`, so repeated resize events and multiple component
83
- instances write the custom property at most once per frame.
84
- - `useOfflineStatus()` returns a reactive `isOnline` ref, initialised from
85
- `navigator.onLine` so a page loaded offline renders offline immediately.
86
- - Services are browser-only and available through package deep imports, for
87
- example `@devopsplaybook.io/common-web/services/AuthService`. `AuthService`
88
- guards every `localStorage` access, so during SSR `getToken()` resolves
89
- `null` and `saveToken()` / `removeToken()` are no-ops.
96
+ instances write the custom property at most once per frame. The pending frame
97
+ is shared across instances and cancelled only when the last instance unmounts,
98
+ so unmounting one component never cancels another one's update.
99
+ - `useOfflineStatus()` returns a reactive `isOnline` ref. It starts as `true`
100
+ so server HTML and the first client render agree, then reads
101
+ `navigator.onLine` after mount and follows the `online`/`offline` events, so a
102
+ page loaded offline shows the offline banner right after hydration without a
103
+ hydration mismatch.
104
+ - Services are available through package deep imports, for example
105
+ `@devopsplaybook.io/common-web/services/AuthService`. `AuthService`,
106
+ `PreferencesService` and `RefreshIntervalService` guard every `localStorage`
107
+ access through an internal `BrowserStorage` helper, so during SSR or with
108
+ blocked storage reads return their documented fallback and writes are no-ops.
90
109
  - `createAuthenticationStore()` returns the Pinia store definition; `Pinia`
91
110
  must be available in the consuming app.
92
111
 
@@ -210,29 +229,33 @@ or response body.
210
229
  `RefreshIntervalService.get()` falls back to `"10000"` when the stored value is
211
230
  missing or malformed; `set()` normalises valid non-negative integer strings
212
231
  (for example `"05000"` becomes `"5000"`) and throws `TypeError` otherwise.
213
- `"0"` is valid and keeps polling disabled.
232
+ `"0"` is valid and keeps polling disabled. Both `PreferencesService` and
233
+ `RefreshIntervalService` tolerate missing or blocked storage: reads return
234
+ `null` / `"10000"` and writes are skipped, so they are safe during SSR; an
235
+ invalid `set()` value still throws `TypeError`.
214
236
 
215
237
  ## SSR and client-only usage
216
238
 
217
239
  The layer is SSR-compatible: the components render on the server, and the
218
240
  composables guard their browser-only access.
219
241
 
220
- - `useTheme()` guards `document` and `localStorage` (`applyTheme()` returns
221
- early when `document` is missing; storage writes are skipped), and reads the
222
- stored preference and media query in `onMounted`, which never runs during SSR.
223
- - `useOfflineStatus()` defaults `isOnline` to `true` when `navigator` is
224
- missing, and registers its listeners in `onMounted`.
242
+ - `useTheme()` keeps module-level state, but touches `document`, `window` and
243
+ `localStorage` only in `onMounted` (which never runs during SSR) and through
244
+ the guarded `BrowserStorage` helper; the server always renders the default
245
+ `system` preference.
246
+ - `useOfflineStatus()` initialises `isOnline` to `true`, so the server and the
247
+ first client render agree; the real value is read in `onMounted`, so an
248
+ offline page shows the banner right after hydration instead of in server
249
+ HTML.
225
250
  - `useAppHeight()` touches `window` only inside `onMounted`.
226
- - `AuthService` guards every `localStorage` access: during SSR `getToken()`
227
- resolves `null` and `saveToken()` / `removeToken()` are no-ops.
251
+ - `AuthService`, `PreferencesService` and `RefreshIntervalService` guard every
252
+ `localStorage` access: during SSR reads return their documented fallback and
253
+ writes are no-ops.
228
254
 
229
255
  Token storage, session renewal, `AUTH_UPDATED` propagation, cross-tab
230
256
  synchronisation and the opt-in Axios integration are browser-only: register the
231
257
  Axios helper from a `.client.ts` plugin as shown above, and expect the
232
258
  authentication state to become meaningful only after hydration.
233
- `PreferencesService` and `RefreshIntervalService` access `localStorage`
234
- unguarded and must only be called in the browser (a client plugin or a
235
- composable hook, never during SSR).
236
259
 
237
260
  `tests/ssr.spec.ts` renders the shipped components with `createSSRApp` and
238
261
  `renderToString` in a Node environment, so this server-rendering contract is
@@ -1,5 +1,30 @@
1
1
  export const THEME_KEY = "UI_THEME";
2
2
 
3
+ export const THEME_SCRIPT_KEY = "common-web-theme";
4
+
5
+ // Build-time CSP nonce forwarded to the inline pre-paint script. Per-request
6
+ // nonces require a consumer override using `themeInitScriptEntry(nonce)`.
7
+ export const THEME_SCRIPT_NONCE_ENV = "COMMON_WEB_THEME_SCRIPT_NONCE";
8
+
9
+ export function themeScriptNonceFromEnv(): string | undefined {
10
+ if (typeof process === "undefined" || !process.env) return undefined;
11
+ const nonce = process.env[THEME_SCRIPT_NONCE_ENV]?.trim();
12
+ return nonce ? nonce : undefined;
13
+ }
14
+
15
+ export interface ThemeInitScriptEntry {
16
+ [key: `data-${string}`]: string;
17
+ key: string;
18
+ innerHTML: string;
19
+ nonce?: string;
20
+ }
21
+
22
+ export function themeInitScriptEntry(nonce?: string): ThemeInitScriptEntry {
23
+ return nonce
24
+ ? { key: THEME_SCRIPT_KEY, innerHTML: THEME_INIT_SCRIPT, nonce }
25
+ : { key: THEME_SCRIPT_KEY, innerHTML: THEME_INIT_SCRIPT };
26
+ }
27
+
3
28
  // Runs synchronously in <head> before first paint; must stay dependency-free.
4
29
  // An explicit stored preference always wins over the OS scheme; re-reading
5
30
  // localStorage on media changes keeps setTheme() authoritative afterwards.
@@ -1,6 +1,7 @@
1
1
  import { onMounted, onUnmounted } from "vue";
2
2
 
3
3
  let frame: number | null = null;
4
+ let mountedConsumers = 0;
4
5
 
5
6
  export function useAppHeight(): void {
6
7
  function updateAppHeight(): void {
@@ -21,6 +22,7 @@ export function useAppHeight(): void {
21
22
  }
22
23
 
23
24
  onMounted(() => {
25
+ mountedConsumers += 1;
24
26
  updateAppHeight();
25
27
  window.addEventListener("resize", scheduleAppHeight);
26
28
  window.visualViewport?.addEventListener("resize", scheduleAppHeight);
@@ -29,8 +31,12 @@ export function useAppHeight(): void {
29
31
  onUnmounted(() => {
30
32
  window.removeEventListener("resize", scheduleAppHeight);
31
33
  window.visualViewport?.removeEventListener("resize", scheduleAppHeight);
32
- if (frame !== null) {
33
- cancelAnimationFrame(frame);
34
+ mountedConsumers = Math.max(0, mountedConsumers - 1);
35
+ // Another instance may still use the shared pending frame.
36
+ if (mountedConsumers === 0 && frame !== null) {
37
+ if (typeof cancelAnimationFrame === "function") {
38
+ cancelAnimationFrame(frame);
39
+ }
34
40
  frame = null;
35
41
  }
36
42
  });
@@ -1,11 +1,12 @@
1
1
  import { onMounted, onUnmounted, ref } from "vue";
2
2
 
3
3
  export function useOfflineStatus() {
4
- const isOnline = ref(
5
- typeof navigator === "undefined" ? true : navigator.onLine,
6
- );
4
+ // Always start online so server HTML and the first client render agree;
5
+ // the real value is read after mount to avoid a hydration mismatch.
6
+ const isOnline = ref(true);
7
7
 
8
8
  function updateStatus(): void {
9
+ if (typeof navigator === "undefined") return;
9
10
  isOnline.value = navigator.onLine;
10
11
  }
11
12
 
@@ -1,57 +1,83 @@
1
1
  import { computed, onMounted, onUnmounted, ref } from "vue";
2
+ import { BrowserStorage } from "../services/BrowserStorage";
2
3
  import { THEME_KEY } from "./theme";
3
4
 
4
5
  export type ThemePreference = "light" | "dark" | "system";
5
6
 
6
- export function useTheme() {
7
- const preference = ref<ThemePreference>("system");
8
- const systemPrefersDark = ref(false);
9
- const isDark = computed(
10
- () =>
11
- preference.value === "dark" ||
12
- (preference.value === "system" && systemPrefersDark.value),
7
+ // Module-level so every `useTheme()` call and every tab observes one state.
8
+ const preference = ref<ThemePreference>("system");
9
+ const systemPrefersDark = ref(false);
10
+ const isDark = computed(
11
+ () =>
12
+ preference.value === "dark" ||
13
+ (preference.value === "system" && systemPrefersDark.value),
14
+ );
15
+
16
+ let mountedConsumers = 0;
17
+ let mediaQuery: MediaQueryList | undefined;
18
+
19
+ function storedPreference(): ThemePreference {
20
+ const stored = BrowserStorage.get(THEME_KEY);
21
+ return stored === "light" || stored === "dark" ? stored : "system";
22
+ }
23
+
24
+ function applyTheme(): void {
25
+ if (typeof document === "undefined") return;
26
+
27
+ document.documentElement.setAttribute(
28
+ "data-theme",
29
+ isDark.value ? "dark" : "light",
13
30
  );
14
- let mediaQuery: MediaQueryList | undefined;
15
-
16
- function applyTheme(): void {
17
- if (typeof document === "undefined") return;
18
-
19
- document.documentElement.setAttribute(
20
- "data-theme",
21
- isDark.value ? "dark" : "light",
22
- );
23
- }
24
-
25
- function setTheme(theme: ThemePreference): void {
26
- preference.value = theme;
27
- if (typeof localStorage !== "undefined") {
28
- if (theme === "system") localStorage.removeItem(THEME_KEY);
29
- else localStorage.setItem(THEME_KEY, theme);
30
- }
31
- applyTheme();
32
- }
31
+ }
32
+
33
+ function setTheme(theme: ThemePreference): void {
34
+ preference.value = theme;
35
+ if (theme === "system") BrowserStorage.remove(THEME_KEY);
36
+ else BrowserStorage.set(THEME_KEY, theme);
37
+ applyTheme();
38
+ }
33
39
 
34
- function toggleTheme(): void {
35
- setTheme(isDark.value ? "light" : "dark");
36
- }
40
+ function toggleTheme(): void {
41
+ setTheme(isDark.value ? "light" : "dark");
42
+ }
43
+
44
+ function handleSystemThemeChange(event: MediaQueryListEvent): void {
45
+ systemPrefersDark.value = event.matches;
46
+ if (preference.value === "system") applyTheme();
47
+ }
48
+
49
+ function handleStorage(event: StorageEvent): void {
50
+ if (event.key !== null && event.key !== THEME_KEY) return;
51
+ preference.value = storedPreference();
52
+ applyTheme();
53
+ }
37
54
 
38
- function handleSystemThemeChange(event: MediaQueryListEvent): void {
39
- systemPrefersDark.value = event.matches;
40
- if (preference.value === "system") applyTheme();
41
- }
55
+ function registerListeners(): void {
56
+ mediaQuery = window.matchMedia?.("(prefers-color-scheme: dark)");
57
+ systemPrefersDark.value = mediaQuery?.matches ?? false;
58
+ mediaQuery?.addEventListener?.("change", handleSystemThemeChange);
59
+ window.addEventListener("storage", handleStorage);
60
+ }
61
+
62
+ function unregisterListeners(): void {
63
+ mediaQuery?.removeEventListener?.("change", handleSystemThemeChange);
64
+ mediaQuery = undefined;
65
+ window.removeEventListener("storage", handleStorage);
66
+ }
42
67
 
68
+ export function useTheme() {
43
69
  onMounted(() => {
44
- const storedTheme = localStorage.getItem(THEME_KEY);
45
- preference.value =
46
- storedTheme === "light" || storedTheme === "dark" ? storedTheme : "system";
47
- mediaQuery = window.matchMedia?.("(prefers-color-scheme: dark)");
48
- systemPrefersDark.value = mediaQuery?.matches ?? false;
49
- mediaQuery?.addEventListener?.("change", handleSystemThemeChange);
50
- applyTheme();
70
+ if (mountedConsumers === 0) {
71
+ preference.value = storedPreference();
72
+ registerListeners();
73
+ applyTheme();
74
+ }
75
+ mountedConsumers += 1;
51
76
  });
52
77
 
53
78
  onUnmounted(() => {
54
- mediaQuery?.removeEventListener?.("change", handleSystemThemeChange);
79
+ mountedConsumers = Math.max(0, mountedConsumers - 1);
80
+ if (mountedConsumers === 0) unregisterListeners();
55
81
  });
56
82
 
57
83
  return { preference, isDark, setTheme, toggleTheme };
package/nuxt.config.ts CHANGED
@@ -1,5 +1,8 @@
1
1
  import { fileURLToPath } from "node:url";
2
- import { THEME_INIT_SCRIPT } from "./composables/theme";
2
+ import {
3
+ themeInitScriptEntry,
4
+ themeScriptNonceFromEnv,
5
+ } from "./composables/theme";
3
6
 
4
7
  export default defineNuxtConfig({
5
8
  css: [
@@ -8,7 +11,7 @@ export default defineNuxtConfig({
8
11
  ],
9
12
  app: {
10
13
  head: {
11
- script: [{ key: "common-web-theme", innerHTML: THEME_INIT_SCRIPT }],
14
+ script: [themeInitScriptEntry(themeScriptNonceFromEnv())],
12
15
  },
13
16
  },
14
17
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devopsplaybook.io/common-web",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Shared Nuxt layer for DevOpsPlaybook web applications",
5
5
  "license": "ISC",
6
6
  "repository": {
@@ -0,0 +1,42 @@
1
+ function storage(): Storage | null {
2
+ try {
3
+ return typeof localStorage === "undefined" ? null : localStorage;
4
+ } catch {
5
+ // Access itself throws in sandboxed iframes and with blocked storage.
6
+ return null;
7
+ }
8
+ }
9
+
10
+ // Every call tolerates missing or blocked storage: reads fall back to `null`
11
+ // and writes are skipped, so SSR and privacy modes never crash.
12
+ export const BrowserStorage = {
13
+ get(key: string): string | null {
14
+ const store = storage();
15
+ if (!store) return null;
16
+ try {
17
+ return store.getItem(key);
18
+ } catch {
19
+ return null;
20
+ }
21
+ },
22
+
23
+ set(key: string, value: string): void {
24
+ const store = storage();
25
+ if (!store) return;
26
+ try {
27
+ store.setItem(key, value);
28
+ } catch {
29
+ // Quota exceeded or storage blocked after the initial access.
30
+ }
31
+ },
32
+
33
+ remove(key: string): void {
34
+ const store = storage();
35
+ if (!store) return;
36
+ try {
37
+ store.removeItem(key);
38
+ } catch {
39
+ // Storage blocked after the initial access.
40
+ }
41
+ },
42
+ };
@@ -1,13 +1,15 @@
1
+ import { BrowserStorage } from "./BrowserStorage";
2
+
1
3
  export const PreferencesService = {
2
4
  get(key: string): string | null {
3
- return localStorage.getItem(key);
5
+ return BrowserStorage.get(key);
4
6
  },
5
7
 
6
8
  set(key: string, value: string): void {
7
- localStorage.setItem(key, value);
9
+ BrowserStorage.set(key, value);
8
10
  },
9
11
 
10
12
  remove(key: string): void {
11
- localStorage.removeItem(key);
13
+ BrowserStorage.remove(key);
12
14
  },
13
15
  };
@@ -1,9 +1,11 @@
1
+ import { BrowserStorage } from "./BrowserStorage";
2
+
1
3
  export class RefreshIntervalService {
2
4
  static readonly KEY = "REFRESH_INTERVAL";
3
5
  static readonly DEFAULT = "10000";
4
6
 
5
7
  static get(): string {
6
- const stored = localStorage.getItem(RefreshIntervalService.KEY);
8
+ const stored = BrowserStorage.get(RefreshIntervalService.KEY);
7
9
  if (stored === null) return RefreshIntervalService.DEFAULT;
8
10
  return (
9
11
  RefreshIntervalService.normalise(stored) ??
@@ -18,7 +20,7 @@ export class RefreshIntervalService {
18
20
  `Invalid refresh interval: ${String(value)} (expected a non-negative integer string)`,
19
21
  );
20
22
  }
21
- localStorage.setItem(RefreshIntervalService.KEY, normalised);
23
+ BrowserStorage.set(RefreshIntervalService.KEY, normalised);
22
24
  }
23
25
 
24
26
  private static normalise(value: string): string | null {