Skip to content

Commit f74b154

Browse files
committed
feat(console): register the app-shell service worker under the Console's mount
Production builds register service-worker.js with the Console's own scope, and post the files the first load fetched so an offline start finds them. In the native shell no worker is registered and an earlier one is removed. The generated manifest's start_url, scope and icon are absolute URLs, since a Blob URL is no base to resolve ./ against. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QsR2jQhk3S1XeTLgXSkEMt
1 parent b061f3e commit f74b154

1 file changed

Lines changed: 86 additions & 4 deletions

File tree

‎ui/apps/console/src/main.tsx‎

Lines changed: 86 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,20 @@ import ReactDOM from 'react-dom/client';
99
import './index.css';
1010
import { App } from './App';
1111
import { I18nProvider, preloadBootstrapLocale } from '@object-ui/i18n';
12-
import { MobileProvider, generatePWAManifest, getNativeHost } from '@object-ui/mobile';
12+
import {
13+
MobileProvider,
14+
cacheLoadedResources,
15+
generatePWAManifest,
16+
getNativeHost,
17+
registerServiceWorker,
18+
} from '@object-ui/mobile';
1319
import { registerPlaceholders } from '@object-ui/components';
1420
import { initSentry, initRuntimeConfig, getProductName, getProductShortName, getFaviconUrl, getPwaDescription, getPwaThemeColor } from '@object-ui/app-shell';
1521
import { loadLanguage } from './loadLanguage';
1622
import { loadLocales } from './loadLocales';
1723
import { seedTenantLanguage } from './languageSeed';
1824
import { preflightAuth } from './lib/auth-preflight';
25+
import { withConsoleBaseRootRelative } from './utils/consoleBase';
1926

2027
const AUTH_URL = `${import.meta.env.VITE_SERVER_URL || ''}/api/v1/auth`;
2128

@@ -70,6 +77,16 @@ registerPlaceholders();
7077
// Change the spelling here and that script has to change with it;
7178
// `src/__tests__/runtimeConfigBootDedup.test.ts` fails when the two stop agreeing.
7279
const SERVER_BASE = (import.meta.env.VITE_SERVER_URL || '').replace(/\/+$/, '');
80+
81+
/**
82+
* The Console's mount as an absolute URL with its trailing slash
83+
* (`https://host/_console/`): the Service Worker's scope and the installed
84+
* app's `start_url` and `scope`. `/` resolves through the same
85+
* `withConsoleBaseRootRelative` the auth pages use, so it agrees with where a
86+
* full-page navigation lands under every mount.
87+
*/
88+
const CONSOLE_SCOPE = new URL(withConsoleBaseRootRelative('/'), window.location.origin).href;
89+
7390
// The third entry seeds the UI language from the server's resolved locale for
7491
// the signed-in caller (objectui#4035). It joins this existing gate rather than adding one of its
7592
// own, which is what keeps it off the critical path: it runs CONCURRENTLY with
@@ -149,10 +166,19 @@ Promise.all([
149166
themeColor: getPwaThemeColor(),
150167
backgroundColor: '#ffffff',
151168
display: 'standalone',
152-
startUrl: './',
153-
scope: './',
169+
// Absolute URLs, because a Blob URL is no base to resolve `./` against:
170+
// the installed app opens at, and stays inside, the Console's mount.
171+
startUrl: CONSOLE_SCOPE,
172+
scope: CONSOLE_SCOPE,
154173
orientation: 'any',
155-
icons: [{ src: faviconUrl || './favicon.svg', sizes: 'any', type: 'image/svg+xml', purpose: 'any' }],
174+
icons: [
175+
{
176+
src: new URL(faviconUrl || './favicon.svg', document.baseURI).href,
177+
sizes: 'any',
178+
type: 'image/svg+xml',
179+
purpose: 'any',
180+
},
181+
],
156182
});
157183
const blob = new Blob([JSON.stringify(manifestJson)], { type: 'application/json' });
158184
const manifestUrl = URL.createObjectURL(blob);
@@ -162,6 +188,10 @@ Promise.all([
162188
document.head.appendChild(manifestLink);
163189
}
164190

191+
// The Console's Service Worker (objectstack#29155): the offline app shell
192+
// and the push handlers. Not awaited — it must never hold up first paint.
193+
void syncServiceWorker();
194+
165195
// The two loaders wait for this page load's session answer. Signed in, they
166196
// read `/i18n` with the session's credentials; signed out, they request
167197
// nothing and the sign-in page renders from the built-in packs
@@ -176,3 +206,55 @@ Promise.all([
176206
</React.StrictMode>
177207
);
178208
});
209+
210+
/**
211+
* Registers the Console's Service Worker (`service-worker.js`, emitted at the
212+
* build root by `vite.config.ts`) under the Console's own scope, never the site
213+
* root. It is the `@object-ui/mobile` `'app-shell'` worker: API requests stay
214+
* network-only, the HTML entry is network-first, so the next navigation after a
215+
* deploy always runs the new build (the worker installs with `skipWaiting` and
216+
* no reload prompt is needed).
217+
*
218+
* Inside the ObjectStack mobile shell (`getNativeHost()`), the shell owns
219+
* offline: no worker is registered, and one this Console registered earlier in
220+
* the same WebView is unregistered. A bridge that lands after this read leaves
221+
* that page load's worker in place; the next load, which sees the bridge at
222+
* boot, removes it.
223+
*
224+
* Production builds only: a dev server's modules are not hashed build output.
225+
*/
226+
async function syncServiceWorker(): Promise<void> {
227+
if (typeof navigator === 'undefined' || !('serviceWorker' in navigator)) return;
228+
try {
229+
if (getNativeHost()) {
230+
const registration = await navigator.serviceWorker.getRegistration(CONSOLE_SCOPE);
231+
if (registration?.scope === CONSOLE_SCOPE) await registration.unregister();
232+
return;
233+
}
234+
if (!import.meta.env.PROD) return;
235+
const registration = await registerServiceWorker({
236+
url: `${CONSOLE_SCOPE}service-worker.js`,
237+
scope: CONSOLE_SCOPE,
238+
});
239+
if (!registration) return;
240+
// Cache what this load fetched before the worker controlled it — the
241+
// first visit's lazy chunks — so an offline start finds them. Read off this
242+
// registration, not `serviceWorker.ready`, which waits on the page's URL.
243+
cacheLoadedResources(await whenActive(registration));
244+
} catch {
245+
// A refused registration costs the offline shell, never the page.
246+
}
247+
}
248+
249+
/** The registration's worker once it is active (at once when it already is). */
250+
function whenActive(registration: ServiceWorkerRegistration): Promise<ServiceWorker | null> {
251+
if (registration.active) return Promise.resolve(registration.active);
252+
const worker = registration.installing ?? registration.waiting;
253+
if (!worker) return Promise.resolve(null);
254+
return new Promise((resolve) => {
255+
worker.addEventListener('statechange', () => {
256+
if (worker.state === 'activated') resolve(worker);
257+
else if (worker.state === 'redundant') resolve(registration.active);
258+
});
259+
});
260+
}

0 commit comments

Comments
 (0)