From 7e3b1397955ef25666e4a6bb49f8a874d0f796b6 Mon Sep 17 00:00:00 2001 From: Krisjanis Seglins Date: Mon, 11 Nov 2024 18:47:25 +0200 Subject: [PATCH] Allow dynamically import atmosphere.js for SW context Fixes #2867 --- packages/ts/frontend/src/FluxConnection.ts | 26 ++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/packages/ts/frontend/src/FluxConnection.ts b/packages/ts/frontend/src/FluxConnection.ts index 562f5594a..7c38011f5 100644 --- a/packages/ts/frontend/src/FluxConnection.ts +++ b/packages/ts/frontend/src/FluxConnection.ts @@ -1,5 +1,7 @@ import type { ReactiveControllerHost } from '@lit/reactive-element'; -import atmosphere from 'atmosphere.js'; + +import type Atmosphere from 'atmosphere.js'; + import type { Subscription } from './Connect.js'; import { getCsrfTokenHeadersForEndpointRequest } from './CsrfUtils.js'; import { @@ -9,6 +11,8 @@ import { type ServerMessage, } from './FluxMessages.js'; +let atmosphere: Atmosphere.Atmosphere; + export enum State { ACTIVE = 'active', INACTIVE = 'inactive', @@ -71,6 +75,14 @@ type EndpointInfo = { reconnect?(): ActionOnLostSubscription | void; }; +interface ImportMetaEnv { + readonly SW_CONTEXT: boolean; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} + /** * A representation of the underlying persistent network connection used for subscribing to Flux type endpoint methods. */ @@ -89,7 +101,17 @@ export class FluxConnection extends EventTarget { constructor(connectPrefix: string, atmosphereOptions?: Partial) { super(); - this.#connectWebsocket(connectPrefix.replace(/connect$/u, ''), atmosphereOptions ?? {}); + // @ts-expect-error - vite environment variable + const meta: ImportMeta = import.meta; + if (!meta.env.SW_CONTEXT) { + (async () => { + atmosphere = await import('atmosphere.js'); + this.#connectWebsocket(connectPrefix.replace(/connect$/u, ''), atmosphereOptions ?? {}); + })().catch((e) => { + // eslint-disable-next-line no-console + console.error('Failed to load atmosphere.js', e); + }); + } } #resubscribeIfWasClosed() {