@igstack/app-catalog-frontend-core 0.3.1-alpha-20260401002820 → 0.3.1-alpha-20260401160844

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.
@@ -2,3 +2,5 @@ export { appPropsFactory } from './appPropsFactory.js';
2
2
  export { App } from './App.js';
3
3
  export type { AppProps } from './App.js';
4
4
  export type { UiSettings } from './types/uiSettings.js';
5
+ export { PwaAutoUpdateProvider, usePwaAutoUpdate } from './modules/pwa.js';
6
+ export type { PwaAutoUpdateOptions, PwaUpdateHandle } from './modules/pwa.js';
package/dist/esm/index.js CHANGED
@@ -1,7 +1,10 @@
1
1
  import { appPropsFactory } from "./appPropsFactory.js";
2
2
  import { App } from "./App.js";
3
+ import { PwaAutoUpdateProvider, usePwaAutoUpdate } from "./modules/pwa/PwaAutoUpdateContext.js";
3
4
  export {
4
5
  App,
5
- appPropsFactory
6
+ PwaAutoUpdateProvider,
7
+ appPropsFactory,
8
+ usePwaAutoUpdate
6
9
  };
7
10
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;"}
@@ -3,7 +3,6 @@ import { useQuery } from "@tanstack/react-query";
3
3
  import { createContext, useMemo, useEffect, use } from "react";
4
4
  import { ApiQueryMagazineAppCatalog } from "../api/ApiQueryMagazineAppCatalog.js";
5
5
  import { useUiSettings } from "../../../context/UiSettingsContext.js";
6
- import "../ui/context/AppCatalogFiltersContext.js";
7
6
  import "@tanstack/react-query-devtools";
8
7
  import "next-themes";
9
8
  import "@radix-ui/react-dialog";
@@ -1 +1 @@
1
- {"version":3,"file":"AppCatalogContext.js","sources":["../../../../../src/modules/appCatalog/context/AppCatalogContext.tsx"],"sourcesContent":["import type {\n AppApprovalMethod,\n AppForCatalog,\n AppVersionInfo,\n GroupingTagDefinition,\n} from '@igstack/app-catalog-backend-core'\nimport { useQuery } from '@tanstack/react-query'\nimport type { ReactNode } from 'react'\nimport { createContext, use, useEffect, useMemo } from 'react'\nimport { ApiQueryMagazineAppCatalog } from '~/modules/appCatalog'\nimport { useUiSettings } from '~/context/UiSettingsContext'\n\nexport interface AppCatalogContextIface {\n apps: AppForCatalog[]\n isLoadingApps: boolean\n tagsDefinitions: GroupingTagDefinition[]\n approvalMethods: AppApprovalMethod[]\n versions?: AppVersionInfo\n}\n\nexport const AppCatalogContext = createContext<\n AppCatalogContextIface | undefined\n>(undefined)\n\ninterface AppCatalogProviderProps {\n children: ReactNode\n}\n\nexport function AppCatalogProvider({ children }: AppCatalogProviderProps) {\n const { data, isLoading: isLoadingApps } = useQuery(\n ApiQueryMagazineAppCatalog.getAppCatalog(),\n )\n const uiSettings = useUiSettings()\n\n const contextValue = useMemo<AppCatalogContextIface>(\n () => ({\n apps: data?.apps ?? [],\n isLoadingApps,\n tagsDefinitions: data?.tagsDefinitions ?? [],\n approvalMethods: data?.approvalMethods ?? [],\n versions: {\n ...data?.versions,\n ...(uiSettings.frontendBuildId && {\n frontend: {\n displayName:\n uiSettings.frontendBuildId === 'local'\n ? 'local'\n : `#${uiSettings.frontendBuildId}`,\n },\n }),\n },\n }),\n [\n data?.approvalMethods,\n data?.apps,\n data?.tagsDefinitions,\n data?.versions,\n uiSettings.frontendBuildId,\n isLoadingApps,\n ],\n )\n\n // Update document title based on backend version\n useEffect(() => {\n if (data?.versions?.backend?.displayName === 'local') {\n document.title = 'Local'\n } else {\n document.title = 'App Catalog'\n }\n }, [data?.versions?.backend?.displayName])\n\n return <AppCatalogContext value={contextValue}>{children}</AppCatalogContext>\n}\n\nexport function useAppCatalogContext(): AppCatalogContextIface {\n const context = use(AppCatalogContext)\n if (!context) {\n throw new Error(\n 'useAppCatalogContext must be used within AppCatalogProvider',\n )\n }\n return context\n}\n"],"names":["_b","_a"],"mappings":";;;;;;;;;;;;;;;;;AAoBO,MAAM,oBAAoB,cAE/B,MAAS;AAMJ,SAAS,mBAAmB,EAAE,YAAqC;;AACxE,QAAM,EAAE,MAAM,WAAW,cAAA,IAAkB;AAAA,IACzC,2BAA2B,cAAA;AAAA,EAAc;AAE3C,QAAM,aAAa,cAAA;AAEnB,QAAM,eAAe;AAAA,IACnB,OAAO;AAAA,MACL,OAAM,6BAAM,SAAQ,CAAA;AAAA,MACpB;AAAA,MACA,kBAAiB,6BAAM,oBAAmB,CAAA;AAAA,MAC1C,kBAAiB,6BAAM,oBAAmB,CAAA;AAAA,MAC1C,UAAU;AAAA,QACR,GAAG,6BAAM;AAAA,QACT,GAAI,WAAW,mBAAmB;AAAA,UAChC,UAAU;AAAA,YACR,aACE,WAAW,oBAAoB,UAC3B,UACA,IAAI,WAAW,eAAe;AAAA,UAAA;AAAA,QACtC;AAAA,MACF;AAAA,IACF;AAAA,IAEF;AAAA,MACE,6BAAM;AAAA,MACN,6BAAM;AAAA,MACN,6BAAM;AAAA,MACN,6BAAM;AAAA,MACN,WAAW;AAAA,MACX;AAAA,IAAA;AAAA,EACF;AAIF,YAAU,MAAM;;AACd,UAAIA,OAAAC,MAAA,6BAAM,aAAN,gBAAAA,IAAgB,YAAhB,gBAAAD,IAAyB,iBAAgB,SAAS;AACpD,eAAS,QAAQ;AAAA,IACnB,OAAO;AACL,eAAS,QAAQ;AAAA,IACnB;AAAA,EACF,GAAG,EAAC,wCAAM,aAAN,mBAAgB,YAAhB,mBAAyB,WAAW,CAAC;AAEzC,SAAO,oBAAC,mBAAA,EAAkB,OAAO,cAAe,SAAA,CAAS;AAC3D;AAEO,SAAS,uBAA+C;AAC7D,QAAM,UAAU,IAAI,iBAAiB;AACrC,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ;AACA,SAAO;AACT;"}
1
+ {"version":3,"file":"AppCatalogContext.js","sources":["../../../../../src/modules/appCatalog/context/AppCatalogContext.tsx"],"sourcesContent":["import type {\n AppApprovalMethod,\n AppForCatalog,\n AppVersionInfo,\n GroupingTagDefinition,\n} from '@igstack/app-catalog-backend-core'\nimport { useQuery } from '@tanstack/react-query'\nimport type { ReactNode } from 'react'\nimport { createContext, use, useEffect, useMemo } from 'react'\nimport { ApiQueryMagazineAppCatalog } from '~/modules/appCatalog'\nimport { useUiSettings } from '~/context/UiSettingsContext'\n\nexport interface AppCatalogContextIface {\n apps: AppForCatalog[]\n isLoadingApps: boolean\n tagsDefinitions: GroupingTagDefinition[]\n approvalMethods: AppApprovalMethod[]\n versions?: AppVersionInfo\n}\n\nexport const AppCatalogContext = createContext<\n AppCatalogContextIface | undefined\n>(undefined)\n\ninterface AppCatalogProviderProps {\n children: ReactNode\n}\n\nexport function AppCatalogProvider({ children }: AppCatalogProviderProps) {\n const { data, isLoading: isLoadingApps } = useQuery(\n ApiQueryMagazineAppCatalog.getAppCatalog(),\n )\n const uiSettings = useUiSettings()\n\n const contextValue = useMemo<AppCatalogContextIface>(\n () => ({\n apps: data?.apps ?? [],\n isLoadingApps,\n tagsDefinitions: data?.tagsDefinitions ?? [],\n approvalMethods: data?.approvalMethods ?? [],\n versions: {\n ...data?.versions,\n ...(uiSettings.frontendBuildId && {\n frontend: {\n displayName:\n uiSettings.frontendBuildId === 'local'\n ? 'local'\n : `#${uiSettings.frontendBuildId}`,\n },\n }),\n },\n }),\n [\n data?.approvalMethods,\n data?.apps,\n data?.tagsDefinitions,\n data?.versions,\n uiSettings.frontendBuildId,\n isLoadingApps,\n ],\n )\n\n // Update document title based on backend version\n useEffect(() => {\n if (data?.versions?.backend?.displayName === 'local') {\n document.title = 'Local'\n } else {\n document.title = 'App Catalog'\n }\n }, [data?.versions?.backend?.displayName])\n\n return <AppCatalogContext value={contextValue}>{children}</AppCatalogContext>\n}\n\nexport function useAppCatalogContext(): AppCatalogContextIface {\n const context = use(AppCatalogContext)\n if (!context) {\n throw new Error(\n 'useAppCatalogContext must be used within AppCatalogProvider',\n )\n }\n return context\n}\n"],"names":["_b","_a"],"mapp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Options, PwaUpdateHandle } from './types.js';
3
+ export interface PwaAutoUpdateContextValue {
4
+ triggerUpdateOnError: () => void;
5
+ }
6
+ interface PwaAutoUpdateProviderProps {
7
+ handle: PwaUpdateHandle | undefined;
8
+ options?: PwaAutoUpdateOptions;
9
+ children: ReactNode;
10
+ }
11
+ export declare function PwaAutoUpdateProvider({ handle, options, children, }: PwaAutoUpdateProviderProps): import("react/jsx-runtime").JSX.Element;
12
+ /**
13
+ * Returns the PWA auto-update context, or null if outside the provider.
14
+ * Null return allows graceful degradation when PWA is not configured.
15
+ */
16
+ export declare function usePwaAutoUpdate(): PwaAutoUpdateContextValue | null;
17
+ export {};
@@ -0,0 +1,46 @@
1
+ import { jsx } from "react/jsx-runtime";
2
+ import { createContext, useRef, useEffect, useMemo, use } from "react";
3
+ import { PwaAutoUpdateController } from "./PwaAutoUpdateController.js";
4
+ const PwaAutoUpdateContext = createContext(
5
+ null
6
+ );
7
+ function PwaAutoUpdateProvider({
8
+ handle,
9
+ options,
10
+ children
11
+ }) {
12
+ const controllerRef = useRef(void 0);
13
+ useEffect(() => {
14
+ if (!handle) return;
15
+ const controller = new PwaAutoUpdateController(handle, options);
16
+ controllerRef.current = controller;
17
+ controller.start();
18
+ return () => {
19
+ controller.destroy();
20
+ controllerRef.current = void 0;
21
+ };
22
+ }, [handle, options]);
23
+ useEffect(() => {
24
+ if (handle && controllerRef.current) {
25
+ controllerRef.current.updateHandle(handle);
26
+ }
27
+ }, [handle]);
28
+ const contextValue = useMemo(
29
+ () => ({
30
+ triggerUpdateOnError: () => {
31
+ var _a;
32
+ (_a = controllerRef.current) == null ? void 0 : _a.triggerUpdateOnError();
33
+ }
34
+ }),
35
+ []
36
+ );
37
+ return /* @__PURE__ */ jsx(PwaAutoUpdateContext, { value: contextValue, children });
38
+ }
39
+ function usePwaAutoUpdate() {
40
+ return use(PwaAutoUpdateContext);
41
+ }
42
+ export {
43
+ PwaAutoUpdateProvider,
44
+ usePwaAutoUpdate
45
+ };
46
+ //# sourceMappingURL=PwaAutoUpdateContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PwaAutoUpdateContext.js","sources":["../../../../src/modules/pwa/PwaAutoUpdateContext.tsx"],"sourcesContent":["import type { ReactNode } from 'react'\nimport { createContext, use, useEffect, useMemo, useRef } from 'react'\nimport { PwaAutoUpdateController } from './PwaAutoUpdateController'\nimport type { PwaAutoUpdateOptions, PwaUpdateHandle } from './types'\n\nexport interface PwaAutoUpdateContextValue {\n triggerUpdateOnError: () => void\n}\n\nconst PwaAutoUpdateContext = createContext<PwaAutoUpdateContextValue | null>(\n null,\n)\n\ninterface PwaAutoUpdateProviderProps {\n handle: PwaUpdateHandle | undefined\n options?: PwaAutoUpdateOptions\n children: ReactNode\n}\n\nexport function PwaAutoUpdateProvider({\n handle,\n options,\n children,\n}: PwaAutoUpdateProviderProps) {\n const controllerRef = useRef<PwaAutoUpdateController | undefined>(undefined)\n\n useEffect(() => {\n if (!handle) return\n\n const controller = new PwaAutoUpdateController(handle, options)\n controllerRef.current = controller\n controller.start()\n\n return () => {\n controller.destroy()\n controllerRef.current = undefined\n }\n }, [handle, options])\n\n // Update handle when registration arrives async\n useEffect(() => {\n if (handle && controllerRef.current) {\n controllerRef.current.updateHandle(handle)\n }\n }, [handle])\n\n const contextValue = useMemo<PwaAutoUpdateContextValue>(\n () => ({\n triggerUpdateOnError: () => {\n controllerRef.current?.triggerUpdateOnError()\n },\n }),\n [],\n )\n\n return (\n <PwaAutoUpdateContext value={contextValue}>{children}</PwaAutoUpdateContext>\n )\n}\n\n/**\n * Returns the PWA auto-update context, or null if outside the provider.\n * Null return allows graceful degradation when PWA is not configured.\n */\nexport function usePwaAutoUpdate(): PwaAutoUpdateContextValue | null {\n return use(PwaAutoUpdateContext)\n}\n"],"names":[],"mappings":";;;AASA,MAAM,uBAAuB;AAAA,EAC3B;AACF;AAQO,SAAS,sBAAsB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AACF,GAA+B;AAC7B,QAAM,gBAAgB,OAA4C,MAAS;AAE3E,YAAU,MAAM;AACd,QAAI,CAAC,OAAQ;AAEb,UAAM,aAAa,IAAI,wBAAwB,QAAQ,OAAO;AAC9D,kBAAc,UAAU;AACxB,eAAW,MAAA;AAEX,WAAO,MAAM;AACX,iBAAW,QAAA;AACX,oBAAc,UAAU;AAAA,IAC1B;AAAA,EACF,GAAG,CAAC,QAAQ,OAAO,CAAC;AAGpB,YAAU,MAAM;AACd,QAAI,UAAU,cAAc,SAAS;AACnC,oBAAc,QAAQ,aAAa,MAAM;AAAA,IAC3C;AAAA,EACF,GAAG,CAAC,MAAM,CAAC;AAEX,QAAM,eAAe;AAAA,IACnB,OAAO;AAAA,MACL,sBAAsB,MAAM;;AAC1B,4BAAc,YAAd,mBAAuB;AAAA,MACzB;AAAA,IAAA;AAAA,IAEF,CAAA;AAAA,EAAC;AAGH,SACE,oBAAC,sBAAA,EAAqB,OAAO,cAAe,SAAA,CAAS;AAEzD;AAMO,SAAS,mBAAqD;AACnE,SAAO,IAAI,oBAAoB;AACjC;"}
@@ -0,0 +1,32 @@
1
+ import { PwaAutoUpdateOptions, PwaUpdateHandle } from './types.js';
2
+ /**
3
+ * Framework-agnostic controller that triggers service worker update checks
4
+ * when the user is idle, switches tabs, or encounters errors.
5
+ */
6
+ export declare class PwaAutoUpdateController {
7
+ private handle;
8
+ private options;
9
+ private lastCheckTimestamp;
10
+ private lastActivityTimestamp;
11
+ private isReloading;
12
+ private visibilityDebounceTimer;
13
+ private idlePollTimer;
14
+ private boundOnVisibilityChange;
15
+ private boundOnUserActivity;
16
+ constructor(handle: PwaUpdateHandle, options?: PwaAutoUpdateOptions);
17
+ start(): void;
18
+ destroy(): void;
19
+ /**
20
+ * Called by the error boundary. Immediately checks for update,
21
+ * waits briefly for a new SW, then reloads regardless.
22
+ */
23
+ triggerUpdateOnError(): Promise<void>;
24
+ /** Update the handle when registration becomes available async */
25
+ updateHandle(handle: PwaUpdateHandle): void;
26
+ private onVisibilityChange;
27
+ private onUserActivity;
28
+ private checkIdleState;
29
+ private checkForUpdate;
30
+ private reload;
31
+ private log;
32
+ }
@@ -0,0 +1,135 @@
1
+ const DEFAULT_IDLE_TIMEOUT_MS = 5 * 60 * 1e3;
2
+ const DEFAULT_MIN_CHECK_INTERVAL_MS = 30 * 1e3;
3
+ const VISIBILITY_DEBOUNCE_MS = 1e3;
4
+ const ERROR_UPDATE_WAIT_MS = 3e3;
5
+ const IDLE_POLL_INTERVAL_MS = 10 * 1e3;
6
+ const USER_ACTIVITY_EVENTS = [
7
+ "mousemove",
8
+ "keydown",
9
+ "scroll",
10
+ "touchstart",
11
+ "click"
12
+ ];
13
+ class PwaAutoUpdateController {
14
+ constructor(handle, options) {
15
+ this.lastCheckTimestamp = 0;
16
+ this.lastActivityTimestamp = Date.now();
17
+ this.isReloading = false;
18
+ this.boundOnVisibilityChange = this.onVisibilityChange.bind(this);
19
+ this.boundOnUserActivity = this.onUserActivity.bind(this);
20
+ this.handle = handle;
21
+ this.options = {
22
+ idleTimeoutMs: (options == null ? void 0 : options.idleTimeoutMs) ?? DEFAULT_IDLE_TIMEOUT_MS,
23
+ minCheckIntervalMs: (options == null ? void 0 : options.minCheckIntervalMs) ?? DEFAULT_MIN_CHECK_INTERVAL_MS,
24
+ debug: (options == null ? void 0 : options.debug) ?? false
25
+ };
26
+ }
27
+ start() {
28
+ this.log("Starting auto-update controller");
29
+ document.addEventListener("visibilitychange", this.boundOnVisibilityChange);
30
+ for (const event of USER_ACTIVITY_EVENTS) {
31
+ document.addEventListener(event, this.boundOnUserActivity, {
32
+ passive: true
33
+ });
34
+ }
35
+ this.idlePollTimer = setInterval(() => {
36
+ this.checkIdleState();
37
+ }, IDLE_POLL_INTERVAL_MS);
38
+ }
39
+ destroy() {
40
+ this.log("Destroying auto-update controller");
41
+ document.removeEventListener(
42
+ "visibilitychange",
43
+ this.boundOnVisibilityChange
44
+ );
45
+ for (const event of USER_ACTIVITY_EVENTS) {
46
+ document.removeEventListener(event, this.boundOnUserActivity);
47
+ }
48
+ if (this.visibilityDebounceTimer != null) {
49
+ clearTimeout(this.visibilityDebounceTimer);
50
+ this.visibilityDebounceTimer = void 0;
51
+ }
52
+ if (this.idlePollTimer != null) {
53
+ clearInterval(this.idlePollTimer);
54
+ this.idlePollTimer = void 0;
55
+ }
56
+ }
57
+ /**
58
+ * Called by the error boundary. Immediately checks for update,
59
+ * waits briefly for a new SW, then reloads regardless.
60
+ */
61
+ async triggerUpdateOnError() {
62
+ this.log("Error-triggered update check");
63
+ if (this.isReloading) return;
64
+ const { registration } = this.handle;
65
+ if (registration) {
66
+ try {
67
+ await registration.update();
68
+ } catch {
69
+ this.log("registration.update() failed, reloading anyway");
70
+ }
71
+ }
72
+ await new Promise((resolve) => setTimeout(resolve, ERROR_UPDATE_WAIT_MS));
73
+ this.reload();
74
+ }
75
+ /** Update the handle when registration becomes available async */
76
+ updateHandle(handle) {
77
+ this.handle = handle;
78
+ }
79
+ onVisibilityChange() {
80
+ if (document.visibilityState !== "visible") return;
81
+ if (this.visibilityDebounceTimer != null) {
82
+ clearTimeout(this.visibilityDebounceTimer);
83
+ }
84
+ this.visibilityDebounceTimer = setTimeout(() => {
85
+ this.visibilityDebounceTimer = void 0;
86
+ this.log("Tab became visible, checking for update");
87
+ this.checkForUpdate();
88
+ }, VISIBILITY_DEBOUNCE_MS);
89
+ }
90
+ onUserActivity() {
91
+ this.lastActivityTimestamp = Date.now();
92
+ }
93
+ checkIdleState() {
94
+ const idleTime = Date.now() - this.lastActivityTimestamp;
95
+ if (idleTime >= this.options.idleTimeoutMs) {
96
+ this.log(`Idle for ${Math.round(idleTime / 1e3)}s, checking for update`);
97
+ this.checkForUpdate();
98
+ }
99
+ }
100
+ async checkForUpdate() {
101
+ if (this.isReloading) return;
102
+ const now = Date.now();
103
+ if (now - this.lastCheckTimestamp < this.options.minCheckIntervalMs) {
104
+ this.log("Skipping check — too soon since last check");
105
+ return;
106
+ }
107
+ const { registration } = this.handle;
108
+ if (!registration) {
109
+ this.log("No SW registration available, skipping check");
110
+ return;
111
+ }
112
+ this.lastCheckTimestamp = now;
113
+ this.log("Calling registration.update()");
114
+ try {
115
+ await registration.update();
116
+ } catch (error) {
117
+ this.log("registration.update() failed:", error);
118
+ }
119
+ }
120
+ reload() {
121
+ if (this.isReloading) return;
122
+ this.isReloading = true;
123
+ this.log("Reloading page");
124
+ this.handle.updateSW(true);
125
+ }
126
+ log(...args) {
127
+ if (this.options.debug) {
128
+ console.log("[PWA Auto-Update]", ...args);
129
+ }
130
+ }
131
+ }
132
+ export {
133
+ PwaAutoUpdateController
134
+ };
135
+ //# sourceMappingURL=PwaAutoUpdateController.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PwaAutoUpdateController.js","sources":["../../../../src/modules/pwa/PwaAutoUpdateController.ts"],"sourcesContent":["import type { PwaAutoUpdateOptions, PwaUpdateHandle } from './types'\n\nconst DEFAULT_IDLE_TIMEOUT_MS = 5 * 60 * 1000 // 5 minutes\nconst DEFAULT_MIN_CHECK_INTERVAL_MS = 30 * 1000 // 30 seconds\nconst VISIBILITY_DEBOUNCE_MS = 1000\nconst ERROR_UPDATE_WAIT_MS = 3000\nconst IDLE_POLL_INTERVAL_MS = 10 * 1000 // check idle state every 10s\n\nconst USER_ACTIVITY_EVENTS = [\n 'mousemove',\n 'keydown',\n 'scroll',\n 'touchstart',\n 'click',\n] as const\n\n/**\n * Framework-agnostic controller that triggers service worker update checks\n * when the user is idle, switches tabs, or encounters errors.\n */\nexport class PwaAutoUpdateController {\n private handle: PwaUpdateHandle\n private options: Required<PwaAutoUpdateOptions>\n\n private lastCheckTimestamp = 0\n private lastActivityTimestamp = Date.now()\n private isReloading = false\n private visibilityDebounceTimer: ReturnType<typeof setTimeout> | undefined\n private idlePollTimer: ReturnType<typeof setInterval> | undefined\n\n private boundOnVisibilityChange = this.onVisibilityChange.bind(this)\n private boundOnUserActivity = this.onUserActivity.bind(this)\n\n constructor(handle: PwaUpdateHandle, options?: PwaAutoUpdateOptions) {\n this.handle = handle\n this.options = {\n idleTimeoutMs: options?.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS,\n minCheckIntervalMs:\n options?.minCheckIntervalMs ?? DEFAULT_MIN_CHECK_INTERVAL_MS,\n debug: options?.debug ?? false,\n }\n }\n\n start(): void {\n this.log('Starting auto-update controller')\n\n document.addEventListener('visibilitychange', this.boundOnVisibilityChange)\n\n for (const event of USER_ACTIVITY_EVENTS) {\n document.addEventListener(event, this.boundOnUserActivity, {\n passive: true,\n })\n }\n\n this.idlePollTimer = setInterval(() => {\n this.checkIdleState()\n }, IDLE_POLL_INTERVAL_MS)\n }\n\n destroy(): void {\n this.log('Destroying auto-update controller')\n\n document.removeEventListener(\n 'visibilitychange',\n this.boundOnVisibilityChange,\n )\n\n for (const event of USER_ACTIVITY_EVENTS) {\n document.removeEventListener(event, this.boundOnUserActivity)\n }\n\n if (this.visibilityDebounceTimer != null) {\n clearTimeout(this.visibilityDebounceTimer)\n this.visibilityDebounceTimer = undefined\n }\n\n if (this.idlePollTimer != null) {\n clearInterval(this.idlePollTimer)\n this.idlePollTimer = undefined\n }\n }\n\n /**\n * Called by the error boundary. Immediately checks for update,\n * waits briefly for a new SW, then reloads regardless.\n */\n async triggerUpdateOnError(): Promise<void> {\n this.log('Error-triggered update check')\n\n if (this.isReloading) return\n\n const { registration } = this.handle\n if (registration) {\n try {\n await registration.update()\n } catch {\n this.log('registration.update() failed, reloading anyway')\n }\n }\n\n // Wait briefly for a new SW to activate, then reload\n await new Promise((resolve) => setTimeout(resolve, ERROR_UPDATE_WAIT_MS))\n this.reload()\n }\n\n /** Update the handle when registration becomes available async */\n updateHandle(handle: PwaUpdateHandle): void {\n this.handle = handle\n }\n\n private onVisibilityChange(): void {\n if (document.visibilityState !== 'visible') return\n\n // Debounce rapid tab switches\n if (this.visibilityDebounceTimer != null) {\n clearTimeout(this.visibilityDebounceTimer)\n }\n\n this.visibilityDebounceTimer = setTimeout(() => {\n this.visibilityDebounceTimer = undefined\n this.log('Tab became visible, checking for update')\n this.checkForUpdate()\n }, VISIBILITY_DEBOUNCE_MS)\n }\n\n private onUserActivity(): void {\n this.lastActivityTimestamp = Date.now()\n }\n\n private checkIdleState(): void {\n const idleTime = Date.now() - this.lastActivityTimestamp\n if (idleTime >= this.options.idleTimeoutMs) {\n this.log(`Idle for ${Math.round(idleTime / 1000)}s, checking for update`)\n this.checkForUpdate()\n }\n }\n\n private async checkForUpdate(): Promise<void> {\n if (this.isReloading) return\n\n const now = Date.now()\n if (now - this.lastCheckTimestamp < this.options.minCheckIntervalMs) {\n this.log('Skipping check — too soon since last check')\n return\n }\n\n const { registration } = this.handle\n if (!registration) {\n this.log('No SW registration available, skipping check')\n return\n }\n\n this.lastCheckTimestamp = now\n this.log('Calling registration.update()')\n\n try {\n await registration.update()\n } catch (error) {\n this.log('registration.update() failed:', error)\n }\n // With autoUpdate registerType, vite-plugin-pwa handles\n // skipWaiting + clientsClaim + calling updateSW() automatically\n }\n\n private reload(): void {\n if (this.isReloading) return\n this.isReloading = true\n this.log('Reloading page')\n this.handle.updateSW(true)\n }\n\n private log(...args: unknown[]): void {\n if (this.options.debug) {\n console.log('[PWA Auto-Update]', ...args)\n }\n }\n}\n"],"names":[],"mappings":"AAEA,MAAM,0BAA0B,IAAI,KAAK;AACzC,MAAM,gCAAgC,KAAK;AAC3C,MAAM,yBAAyB;AAC/B,MAAM,uBAAuB;AAC7B,MAAM,wBAAwB,KAAK;AAEnC,MAAM,uBAAuB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAMO,MAAM,wBAAwB;AAAA,EAanC,YAAY,QAAyB,SAAgC;AATrE,SAAQ,qBAAqB;AAC7B,SAAQ,wBAAwB,KAAK,IAAA;AACrC,SAAQ,cAAc;AAItB,SAAQ,0BAA0B,KAAK,mBAAmB,KAAK,IAAI;AACnE,SAAQ,sBAAsB,KAAK,eAAe,KAAK,IAAI;AAGzD,SAAK,SAAS;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"}
@@ -0,0 +1,3 @@
1
+ export { PwaAutoUpdateProvider, usePwaAutoUpdate } from './PwaAutoUpdateContext.js';
2
+ export type { PwaAutoUpdateContextValue } from './PwaAutoUpdateContext.js';
3
+ export type { PwaAutoUpdateOptions, PwaUpdateHandle } from './types.js';
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Handle returned by the consuming app's registerSW() call.
3
+ * The consuming app constructs this from virtual:pwa-register callbacks.
4
+ */
5
+ export interface PwaUpdateHandle {
6
+ /** Triggers the service worker update + page reload */
7
+ updateSW: (reloadPage?: boolean) => Promise<void>;
8
+ /** The active SW registration, for calling registration.update() */
9
+ registration: ServiceWorkerRegistration | undefined;
10
+ }
11
+ /**
12
+ * Configuration for auto-update behavior.
13
+ */
14
+ export interface PwaAutoUpdateOptions {
15
+ /** Milliseconds of idle time before triggering an update check. Default: 300_000 (5 min) */
16
+ idleTimeoutMs?: number;
17
+ /** Minimum milliseconds between consecutive SW update checks. Default: 30_000 (30s) */
18
+ minCheckIntervalMs?: number;
19
+ /** Log auto-update activity to console. Default: false */
20
+ debug?: boolean;
21
+ }
@@ -1,3 +1,4 @@
1
+ import { PwaAutoUpdateOptions } from '~/modules/pwa/types';
1
2
  /**
2
3
  * UI settings passed from the app entry point.
3
4
  */
@@ -9,4 +10,6 @@ export interface UiSettings {
9
10
  };
10
11
  /** Frontend build identifier baked at build time (e.g., pipeline ID via VITE env var) */
11
12
  frontendBuildId?: string;
13
+ /** PWA auto-update configuration (idle timeout, check interval, debug) */
14
+ pwaAutoUpdate?: PwaAutoUpdateOptions;
12
15
  }
@@ -1,14 +1,26 @@
1
1
  import { jsx, jsxs } from "react/jsx-runtime";
2
2
  import { BugIcon, RefreshCcwIcon } from "lucide-react";
3
- import { useState } from "react";
3
+ import { useState, useEffect } from "react";
4
4
  import { Button } from "../../button.js";
5
5
  import { Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription, EmptyContent } from "../../empty.js";
6
6
  import { useDb } from "../../../userDb/DbContext.js";
7
7
  import { isDexieError, isDexieMigrationError } from "../../../util/error-utils.js";
8
8
  import { BaseErrorPage } from "./BaseErrorPage.js";
9
+ import { usePwaAutoUpdate } from "../../../modules/pwa/PwaAutoUpdateContext.js";
9
10
  function Treatment({ error, reset }) {
10
11
  const db = useDb();
12
+ const pwaAutoUpdate = usePwaAutoUpdate();
11
13
  const [isResetting, setIsResetting] = useState(false);
14
+ const [isCheckingUpdate, setIsCheckingUpdate] = useState(false);
15
+ useEffect(() => {
16
+ if (!isDexieError(error) && pwaAutoUpdate) {
17
+ setIsCheckingUpdate(true);
18
+ pwaAutoUpdate.triggerUpdateOnError();
19
+ const timer = setTimeout(() => setIsCheckingUpdate(false), 2e3);
20
+ return () => clearTimeout(timer);
21
+ }
22
+ return void 0;
23
+ }, [error, pwaAutoUpdate]);
12
24
  async function dexieResetDb() {
13
25
  setIsResetting(true);
14
26
  try {
@@ -39,6 +51,12 @@ function Treatment({ error, reset }) {
39
51
  }
40
52
  );
41
53
  }
54
+ if (isCheckingUpdate) {
55
+ return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm text-muted-foreground", children: [
56
+ /* @__PURE__ */ jsx(RefreshCcwIcon, { className: "h-4 w-4 animate-spin" }),
57
+ "Checking for updates..."
58
+ ] });
59
+ }
42
60
  return /* @__PURE__ */ jsx("div", { className: "flex gap-2", children: /* @__PURE__ */ jsxs(Button, { variant: "outline", size: "sm", onClick: () => reset(), children: [
43
61
  /* @__PURE__ */ jsx(RefreshCcwIcon, {}),
44
62
  "Try reset error"
@@ -1 +1 @@
1
- {"version":3,"file":"DefaultErrorComponent.js","sources":["../../../../../src/ui/components/error/DefaultErrorComponent.tsx"],"sourcesContent":["import type { ErrorComponentProps } from '@tanstack/react-router'\nimport { BugIcon, RefreshCcwIcon } from 'lucide-react'\nimport { useState } from 'react'\nimport { Button } from '~/ui/button'\nimport {\n Empty,\n EmptyContent,\n EmptyDescription,\n EmptyHeader,\n EmptyMedia,\n EmptyTitle,\n} from '~/ui/empty'\nimport { useDb } from '~/userDb/DbContext'\nimport { isDexieError, isDexieMigrationError } from '~/util/error-utils'\nimport { BaseErrorPage } from './BaseErrorPage'\n\nexport function Treatment({ error, reset }: ErrorComponentProps) {\n const db = useDb()\n const [isResetting, setIsResetting] = useState(false)\n\n async function dexieResetDb() {\n setIsResetting(true)\n try {\n await db.resetDatabase()\n console.log('Database deleted and recreated successfully')\n // Reload the page after successful reset\n window.location.reload()\n } catch (resetError) {\n console.error('Failed to reset database:', resetError)\n // Still reload the page even if reset fails, as it might help\n window.location.reload()\n } finally {\n setIsResetting(false)\n }\n }\n\n if (isDexieError(error)) {\n const isMigrationError = isDexieMigrationError(error)\n const buttonText = isMigrationError\n ? isResetting\n ? 'Clearing database...'\n : 'Clear database and reload'\n : isResetting\n ? 'Resetting...'\n : 'Try reset local settings'\n\n return (\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={() => dexieResetDb()}\n disabled={isResetting}\n >\n <RefreshCcwIcon className={isResetting ? 'animate-spin' : ''} />\n {buttonText}\n </Button>\n )\n }\n\n return (\n <div className=\"flex gap-2\">\n <Button variant=\"outline\" size=\"sm\" onClick={() => reset()}>\n <RefreshCcwIcon />\n Try reset error\n </Button>\n {/* <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={() => window.location.reload()}\n >\n <RefreshCcwIcon />\n Try refresh page\n </Button> */}\n </div>\n )\n}\n\nexport function DefaultErrorComponent({ error, reset }: ErrorComponentProps) {\n return (\n <BaseErrorPage>\n <Empty role=\"alert\">\n <EmptyHeader>\n <EmptyMedia variant=\"icon\">\n <BugIcon />\n </EmptyMedia>\n <EmptyTitle>Ooops!</EmptyTitle>\n <EmptyDescription>\n Error inside app-catalog occured: {<i>{error.message}</i>}\n </EmptyDescription>\n </EmptyHeader>\n <EmptyContent>\n <Treatment error={error} reset={reset} />\n\n <div\n className={\n 'mt-8 text-center max-w-[90vw] max-h-[80vh] overflow-auto'\n }\n >\n <pre className={'text-left mt-8 text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A,EAAW,SAAQ,QAClB,UAAA,oBAAC,WAAQ,GACX;AAAA,MACA,oBAAC,cAAW,UAAA,SAAA,CAAM;AAAA,2BACjB,kBAAA,EAAiB,UAAA;AAAA,QAAA;AAAA,QACmB,oBAAC,KAAA,EAAG,UAAA,MAAM,QAAA,CAAQ;AAAA,MAAA,EAAA,CACvD;AAAA,IAAA,GACF;AAAA,yBACC,cAAA,EACC,UAAA;AAAA,MAAA,oBAAC,WAAA,EAAU,OAAc,MAAA,CAAc;AAAA,MAEvC;AAAA,QAAC;AAAA,QAAA;AAAA,UACC,WACE;AAAA,UAGF,UAAA,oBAAC,SAAI,WAAW,0BACb,8BAAC,KAAA,EAAG,UAAA,MAAM,OAAM,EAAA,CACnB;AAAA,QAAA;AAAA,MAAA;AAAA,IACF,EAAA,CACF;AAAA,EAAA,EAAA,CACF,EAAA,CACF;AAEJ;"}
1
+ {"version":3,"file":"DefaultErrorComponent.js","sources":["../../../../../src/ui/components/error/DefaultErrorComponent.tsx"],"sourcesContent":["import type { ErrorComponentProps } from '@tanstack/react-router'\nimport { BugIcon, RefreshCcwIcon } from 'lucide-react'\nimport { useEffect, useState } from 'react'\nimport { Button } from '~/ui/button'\nimport {\n Empty,\n EmptyContent,\n EmptyDescription,\n EmptyHeader,\n EmptyMedia,\n EmptyTitle,\n} from '~/ui/empty'\nimport { useDb } from '~/userDb/DbContext'\nimport { usePwaAutoUpdate } from '~/modules/pwa'\nimport { isDexieError, isDexieMigrationError } from '~/util/error-utils'\nimport { BaseErrorPage } from './BaseErrorPage'\n\nexport function Treatment({ error, reset }: ErrorComponentProps) {\n const db = useDb()\n const pwaAutoUpdate = usePwaAutoUpdate()\n const [isResetting, setIsResetting] = useState(false)\n const [isCheckingUpdate, setIsCheckingUpdate] = useState(false)\n\n useEffect(() => {\n if (!isDexieError(error) && pwaAutoUpdate) {\n setIsCheckingUpdate(true)\n pwaAutoUpdate.triggerUpdateOnError()\n const timer = setTimeout(() => setIsCheckingUpdate(false), 2000)\n return () => clearTimeout(timer)\n }\n return undefined\n }, [error, pwaAutoUpdate])\n\n async function dexieResetDb() {\n setIsResetting(true)\n try {\n await db.resetDatabase()\n console.log('Database deleted and recreated successfully')\n // Reload the page after successful reset\n window.location.reload()\n } catch (resetError) {\n console.error('Failed to reset database:', resetError)\n // Still reload the page even if reset fails, as it might help\n window.location.reload()\n } finally {\n setIsResetting(false)\n }\n }\n\n if (isDexieError(error)) {\n const isMigrationError = isDexieMigrationError(error)\n const buttonText = isMigrationError\n ? isResetting\n ? 'Clearing database...'\n : 'Clear database and reload'\n : isResetting\n ? 'Resetting...'\n : 'Try reset local settings'\n\n return (\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={() => dexieResetDb()}\n disabled={isResetting}\n >\n <RefreshCcwIcon className={isResetting ? 'animate-spin' : ''} />\n {buttonText}\n </Button>\n )\n }\n\n if (isCheckingUpdate) {\n return (\n <div className=\"flex items-center gap-2 text-sm text-muted-foreground\">\n <RefreshCcwIcon className=\"h-4 w-4 animate-spin\" />\n Checking for updates...\n </div>\n )\n }\n\n return (\n <div className=\"flex gap-2\">\n <Button variant=\"outline\" size=\"sm\" onClick={() => reset()}>\n <RefreshCcwIcon />\n Try reset error\n </Button>\n {/* <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={() => window.location.reload()}\n >\n <RefreshCcwIcon />\n Try refresh page\n </Button> */}\n </div>\n )\n}\n\nexport function DefaultErrorComponent({ error, reset }: ErrorComponentProps) {\n return (\n <BaseErrorPage>\n <Empty role=\"alert\">\n <EmptyHeader>\n <EmptyMedia variant=\"icon\">\n <BugIcon />\n </EmptyMedia>\n <EmptyTitle>Ooops!</EmptyTitle>\n <EmptyDescription>\n Error inside app-catalog occured: {<i>{error.message}</i>}\n </EmptyDescription>\n </EmptyHeader>\n <EmptyContent>\n <Treatment error={error} reset={reset} />\n\n <div\n className={\n 'mt-8 text-center max-w-[90vw] max-h-[80vh] overflow-auto'\n }\n >\n <pre className={'text-left mt-8 text-sm'}>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AI,WAAU,yDACb,UAAA;AAAA,MAAA,oBAAC,gBAAA,EAAe,WAAU,uBAAA,CAAuB;AAAA,MAAE;AAAA,IAAA,GAErD;AAAA,EAEJ;AAEA,SACE,oBAAC,OAAA,EAAI,WAAU,cACb,UAAA,qBAAC,QAAA,EAAO,SAAQ,WAAU,MAAK,MAAK,SAAS,MAAM,SACjD,UAAA;AAAA,IAAA,oBAAC,gBAAA,EAAe;AAAA,IAAE;AAAA,EAAA,EAAA,CAEpB,EAAA,CASF;AAEJ;AAEO,SAAS,sBAAsB,EAAE,OAAO,SAA8B;AAC3E,SACE,oBAAC,eAAA,EACC,UAAA,qBAAC,OAAA,EAAM,MAAK,SACV,UAAA;AAAA,IAAA,qBAAC,aAAA,EACC,UAAA;AAAA,MAAA,oBAAC,YAAA,EAAW,SAAQ,QAClB,UAAA,oBAAC,WAAQ,GACX;AAAA,MACA,oBAAC,cAAW,UAAA,SAAA,CAAM;AAAA,2BACjB,kBAAA,EAAiB,UAAA;AAAA,QAAA;AAAA,QACmB,oBAAC,KAAA,EAAG,UAAA,MAAM,QAAA,CAAQ;AAAA,MAAA,EAAA,CACvD;AAAA,IAAA,GACF;AAAA,yBACC,cAAA,EACC,UAAA;AAAA,MAAA,oBAAC,WAAA,EAAU,OAAc,MAAA,CAAc;AAAA,MAEvC;AAAA,QAAC;AAAA,QAAA;AAAA,UACC,WACE;AAAA,UAGF,UAAA,oBAAC,SAAI,WAAW,0BACb,8BAAC,KAAA,EAAG,UAAA,MAAM,OAAM,EAAA,CACnB;AAAA,QAAA;AAAA,MAAA;AAAA,IACF,EAAA,CACF;AAAA,EAAA,EAAA,CACF,EAAA,CACF;AAEJ;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@igstack/app-catalog-frontend-core",
3
- "version": "0.3.1-alpha-20260401002820",
3
+ "version": "0.3.1-alpha-20260401160844",
4
4
  "description": "Frontend core library for App Catalog",
5
5
  "homepage": "https://github.com/lislon/app-catalog",
6
6
  "repository": {
@@ -134,8 +134,8 @@
134
134
  "vite-plugin-static-copy": "^3.1.4",
135
135
  "vite-plugin-svgr": "^4.2.0",
136
136
  "vitest": "^4.1.2",
137
- "@igstack/app-catalog-backend-core": "0.3.1-alpha-20260401002820",
138
- "@igstack/app-catalog-shared-core": "0.3.1-alpha-20260401002820"
137
+ "@igstack/app-catalog-backend-core": "0.3.1-alpha-20260401160844",
138
+ "@igstack/app-catalog-shared-core": "0.3.1-alpha-20260401160844"
139
139
  },
140
140
  "peerDependencies": {
141
141
  "react": "19.1.2",
package/src/index.tsx CHANGED
@@ -2,3 +2,5 @@ export { appPropsFactory } from './appPropsFactory.js'
2
2
  export { App } from './App'
3
3
  export type { AppProps } from './App'
4
4
  export type { UiSettings } from './types/uiSettings'
5
+ export { PwaAutoUpdateProvider, usePwaAutoUpdate } from './modules/pwa'
6
+ export type { PwaAutoUpdateOptions, PwaUpdateHandle } from './modules/pwa'
@@ -0,0 +1,67 @@
1
+ import type { ReactNode } from 'react'
2
+ import { createContext, use, useEffect, useMemo, useRef } from 'react'
3
+ import { PwaAutoUpdateController } from './PwaAutoUpdateController'
4
+ import type { PwaAutoUpdateOptions, PwaUpdateHandle } from './types'
5
+
6
+ export interface PwaAutoUpdateContextValue {
7
+ triggerUpdateOnError: () => void
8
+ }
9
+
10
+ const PwaAutoUpdateContext = createContext<PwaAutoUpdateContextValue | null>(
11
+ null,
12
+ )
13
+
14
+ interface PwaAutoUpdateProviderProps {
15
+ handle: PwaUpdateHandle | undefined
16
+ options?: PwaAutoUpdateOptions
17
+ children: ReactNode
18
+ }
19
+
20
+ export function PwaAutoUpdateProvider({
21
+ handle,
22
+ options,
23
+ children,
24
+ }: PwaAutoUpdateProviderProps) {
25
+ const controllerRef = useRef<PwaAutoUpdateController | undefined>(undefined)
26
+
27
+ useEffect(() => {
28
+ if (!handle) return
29
+
30
+ const controller = new PwaAutoUpdateController(handle, options)
31
+ controllerRef.current = controller
32
+ controller.start()
33
+
34
+ return () => {
35
+ controller.destroy()
36
+ controllerRef.current = undefined
37
+ }
38
+ }, [handle, options])
39
+
40
+ // Update handle when registration arrives async
41
+ useEffect(() => {
42
+ if (handle && controllerRef.current) {
43
+ controllerRef.current.updateHandle(handle)
44
+ }
45
+ }, [handle])
46
+
47
+ const contextValue = useMemo<PwaAutoUpdateContextValue>(
48
+ () => ({
49
+ triggerUpdateOnError: () => {
50
+ controllerRef.current?.triggerUpdateOnError()
51
+ },
52
+ }),
53
+ [],
54
+ )
55
+
56
+ return (
57
+ <PwaAutoUpdateContext value={contextValue}>{children}</PwaAutoUpdateContext>
58
+ )
59
+ }
60
+
61
+ /**
62
+ * Returns the PWA auto-update context, or null if outside the provider.
63
+ * Null return allows graceful degradation when PWA is not configured.
64
+ */
65
+ export function usePwaAutoUpdate(): PwaAutoUpdateContextValue | null {
66
+ return use(PwaAutoUpdateContext)
67
+ }
@@ -0,0 +1,177 @@
1
+ import type { PwaAutoUpdateOptions, PwaUpdateHandle } from './types'
2
+
3
+ const DEFAULT_IDLE_TIMEOUT_MS = 5 * 60 * 1000 // 5 minutes
4
+ const DEFAULT_MIN_CHECK_INTERVAL_MS = 30 * 1000 // 30 seconds
5
+ const VISIBILITY_DEBOUNCE_MS = 1000
6
+ const ERROR_UPDATE_WAIT_MS = 3000
7
+ const IDLE_POLL_INTERVAL_MS = 10 * 1000 // check idle state every 10s
8
+
9
+ const USER_ACTIVITY_EVENTS = [
10
+ 'mousemove',
11
+ 'keydown',
12
+ 'scroll',
13
+ 'touchstart',
14
+ 'click',
15
+ ] as const
16
+
17
+ /**
18
+ * Framework-agnostic controller that triggers service worker update checks
19
+ * when the user is idle, switches tabs, or encounters errors.
20
+ */
21
+ export class PwaAutoUpdateController {
22
+ private handle: PwaUpdateHandle
23
+ private options: Required<PwaAutoUpdateOptions>
24
+
25
+ private lastCheckTimestamp = 0
26
+ private lastActivityTimestamp = Date.now()
27
+ private isReloading = false
28
+ private visibilityDebounceTimer: ReturnType<typeof setTimeout> | undefined
29
+ private idlePollTimer: ReturnType<typeof setInterval> | undefined
30
+
31
+ private boundOnVisibilityChange = this.onVisibilityChange.bind(this)
32
+ private boundOnUserActivity = this.onUserActivity.bind(this)
33
+
34
+ constructor(handle: PwaUpdateHandle, options?: PwaAutoUpdateOptions) {
35
+ this.handle = handle
36
+ this.options = {
37
+ idleTimeoutMs: options?.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS,
38
+ minCheckIntervalMs:
39
+ options?.minCheckIntervalMs ?? DEFAULT_MIN_CHECK_INTERVAL_MS,
40
+ debug: options?.debug ?? false,
41
+ }
42
+ }
43
+
44
+ start(): void {
45
+ this.log('Starting auto-update controller')
46
+
47
+ document.addEventListener('visibilitychange', this.boundOnVisibilityChange)
48
+
49
+ for (const event of USER_ACTIVITY_EVENTS) {
50
+ document.addEventListener(event, this.boundOnUserActivity, {
51
+ passive: true,
52
+ })
53
+ }
54
+
55
+ this.idlePollTimer = setInterval(() => {
56
+ this.checkIdleState()
57
+ }, IDLE_POLL_INTERVAL_MS)
58
+ }
59
+
60
+ destroy(): void {
61
+ this.log('Destroying auto-update controller')
62
+
63
+ document.removeEventListener(
64
+ 'visibilitychange',
65
+ this.boundOnVisibilityChange,
66
+ )
67
+
68
+ for (const event of USER_ACTIVITY_EVENTS) {
69
+ document.removeEventListener(event, this.boundOnUserActivity)
70
+ }
71
+
72
+ if (this.visibilityDebounceTimer != null) {
73
+ clearTimeout(this.visibilityDebounceTimer)
74
+ this.visibilityDebounceTimer = undefined
75
+ }
76
+
77
+ if (this.idlePollTimer != null) {
78
+ clearInterval(this.idlePollTimer)
79
+ this.idlePollTimer = undefined
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Called by the error boundary. Immediately checks for update,
85
+ * waits briefly for a new SW, then reloads regardless.
86
+ */
87
+ async triggerUpdateOnError(): Promise<void> {
88
+ this.log('Error-triggered update check')
89
+
90
+ if (this.isReloading) return
91
+
92
+ const { registration } = this.handle
93
+ if (registration) {
94
+ try {
95
+ await registration.update()
96
+ } catch {
97
+ this.log('registration.update() failed, reloading anyway')
98
+ }
99
+ }
100
+
101
+ // Wait briefly for a new SW to activate, then reload
102
+ await new Promise((resolve) => setTimeout(resolve, ERROR_UPDATE_WAIT_MS))
103
+ this.reload()
104
+ }
105
+
106
+ /** Update the handle when registration becomes available async */
107
+ updateHandle(handle: PwaUpdateHandle): void {
108
+ this.handle = handle
109
+ }
110
+
111
+ private onVisibilityChange(): void {
112
+ if (document.visibilityState !== 'visible') return
113
+
114
+ // Debounce rapid tab switches
115
+ if (this.visibilityDebounceTimer != null) {
116
+ clearTimeout(this.visibilityDebounceTimer)
117
+ }
118
+
119
+ this.visibilityDebounceTimer = setTimeout(() => {
120
+ this.visibilityDebounceTimer = undefined
121
+ this.log('Tab became visible, checking for update')
122
+ this.checkForUpdate()
123
+ }, VISIBILITY_DEBOUNCE_MS)
124
+ }
125
+
126
+ private onUserActivity(): void {
127
+ this.lastActivityTimestamp = Date.now()
128
+ }
129
+
130
+ private checkIdleState(): void {
131
+ const idleTime = Date.now() - this.lastActivityTimestamp
132
+ if (idleTime >= this.options.idleTimeoutMs) {
133
+ this.log(`Idle for ${Math.round(idleTime / 1000)}s, checking for update`)
134
+ this.checkForUpdate()
135
+ }
136
+ }
137
+
138
+ private async checkForUpdate(): Promise<void> {
139
+ if (this.isReloading) return
140
+
141
+ const now = Date.now()
142
+ if (now - this.lastCheckTimestamp < this.options.minCheckIntervalMs) {
143
+ this.log('Skipping check — too soon since last check')
144
+ return
145
+ }
146
+
147
+ const { registration } = this.handle
148
+ if (!registration) {
149
+ this.log('No SW registration available, skipping check')
150
+ return
151
+ }
152
+
153
+ this.lastCheckTimestamp = now
154
+ this.log('Calling registration.update()')
155
+
156
+ try {
157
+ await registration.update()
158
+ } catch (error) {
159
+ this.log('registration.update() failed:', error)
160
+ }
161
+ // With autoUpdate registerType, vite-plugin-pwa handles
162
+ // skipWaiting + clientsClaim + calling updateSW() automatically
163
+ }
164
+
165
+ private reload(): void {
166
+ if (this.isReloading) return
167
+ this.isReloading = true
168
+ this.log('Reloading page')
169
+ this.handle.updateSW(true)
170
+ }
171
+
172
+ private log(...args: unknown[]): void {
173
+ if (this.options.debug) {
174
+ console.log('[PWA Auto-Update]', ...args)
175
+ }
176
+ }
177
+ }
@@ -0,0 +1,3 @@
1
+ export { PwaAutoUpdateProvider, usePwaAutoUpdate } from './PwaAutoUpdateContext'
2
+ export type { PwaAutoUpdateContextValue } from './PwaAutoUpdateContext'
3
+ export type { PwaAutoUpdateOptions, PwaUpdateHandle } from './types'
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Handle returned by the consuming app's registerSW() call.
3
+ * The consuming app constructs this from virtual:pwa-register callbacks.
4
+ */
5
+ export interface PwaUpdateHandle {
6
+ /** Triggers the service worker update + page reload */
7
+ updateSW: (reloadPage?: boolean) => Promise<void>
8
+ /** The active SW registration, for calling registration.update() */
9
+ registration: ServiceWorkerRegistration | undefined
10
+ }
11
+
12
+ /**
13
+ * Configuration for auto-update behavior.
14
+ */
15
+ export interface PwaAutoUpdateOptions {
16
+ /** Milliseconds of idle time before triggering an update check. Default: 300_000 (5 min) */
17
+ idleTimeoutMs?: number
18
+ /** Minimum milliseconds between consecutive SW update checks. Default: 30_000 (30s) */
19
+ minCheckIntervalMs?: number
20
+ /** Log auto-update activity to console. Default: false */
21
+ debug?: boolean
22
+ }
@@ -1,3 +1,5 @@
1
+ import type { PwaAutoUpdateOptions } from '~/modules/pwa/types'
2
+
1
3
  /**
2
4
  * UI settings passed from the app entry point.
3
5
  */
@@ -9,4 +11,6 @@ export interface UiSettings {
9
11
  }
10
12
  /** Frontend build identifier baked at build time (e.g., pipeline ID via VITE env var) */
11
13
  frontendBuildId?: string
14
+ /** PWA auto-update configuration (idle timeout, check interval, debug) */
15
+ pwaAutoUpdate?: PwaAutoUpdateOptions
12
16
  }
@@ -1,6 +1,6 @@
1
1
  import type { ErrorComponentProps } from '@tanstack/react-router'
2
2
  import { BugIcon, RefreshCcwIcon } from 'lucide-react'
3
- import { useState } from 'react'
3
+ import { useEffect, useState } from 'react'
4
4
  import { Button } from '~/ui/button'
5
5
  import {
6
6
  Empty,
@@ -11,12 +11,25 @@ import {
11
11
  EmptyTitle,
12
12
  } from '~/ui/empty'
13
13
  import { useDb } from '~/userDb/DbContext'
14
+ import { usePwaAutoUpdate } from '~/modules/pwa'
14
15
  import { isDexieError, isDexieMigrationError } from '~/util/error-utils'
15
16
  import { BaseErrorPage } from './BaseErrorPage'
16
17
 
17
18
  export function Treatment({ error, reset }: ErrorComponentProps) {
18
19
  const db = useDb()
20
+ const pwaAutoUpdate = usePwaAutoUpdate()
19
21
  const [isResetting, setIsResetting] = useState(false)
22
+ const [isCheckingUpdate, setIsCheckingUpdate] = useState(false)
23
+
24
+ useEffect(() => {
25
+ if (!isDexieError(error) && pwaAutoUpdate) {
26
+ setIsCheckingUpdate(true)
27
+ pwaAutoUpdate.triggerUpdateOnError()
28
+ const timer = setTimeout(() => setIsCheckingUpdate(false), 2000)
29
+ return () => clearTimeout(timer)
30
+ }
31
+ return undefined
32
+ }, [error, pwaAutoUpdate])
20
33
 
21
34
  async function dexieResetDb() {
22
35
  setIsResetting(true)
@@ -57,6 +70,15 @@ export function Treatment({ error, reset }: ErrorComponentProps) {
57
70
  )
58
71
  }
59
72
 
73
+ if (isCheckingUpdate) {
74
+ return (
75
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
76
+ <RefreshCcwIcon className="h-4 w-4 animate-spin" />
77
+ Checking for updates...
78
+ </div>
79
+ )
80
+ }
81
+
60
82
  return (
61
83
  <div className="flex gap-2">
62
84
  <Button variant="outline" size="sm" onClick={() => reset()}>