Skip to content

Commit 7e3b139

Browse files
committed
Allow dynamically import atmosphere.js for SW context
Fixes #2867
1 parent f5f6170 commit 7e3b139

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

packages/ts/frontend/src/FluxConnection.ts

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import type { ReactiveControllerHost } from '@lit/reactive-element';
2-
import atmosphere from 'atmosphere.js';
2+
3+
import type Atmosphere from 'atmosphere.js';
4+
35
import type { Subscription } from './Connect.js';
46
import { getCsrfTokenHeadersForEndpointRequest } from './CsrfUtils.js';
57
import {
@@ -9,6 +11,8 @@ import {
911
type ServerMessage,
1012
} from './FluxMessages.js';
1113

14+
let atmosphere: Atmosphere.Atmosphere;
15+
1216
export enum State {
1317
ACTIVE = 'active',
1418
INACTIVE = 'inactive',
@@ -71,6 +75,14 @@ type EndpointInfo = {
7175
reconnect?(): ActionOnLostSubscription | void;
7276
};
7377

78+
interface ImportMetaEnv {
79+
readonly SW_CONTEXT: boolean;
80+
}
81+
82+
interface ImportMeta {
83+
readonly env: ImportMetaEnv;
84+
}
85+
7486
/**
7587
* A representation of the underlying persistent network connection used for subscribing to Flux type endpoint methods.
7688
*/
@@ -89,7 +101,17 @@ export class FluxConnection extends EventTarget {
89101

90102
constructor(connectPrefix: string, atmosphereOptions?: Partial<Atmosphere.Request>) {
91103
super();
92-
this.#connectWebsocket(connectPrefix.replace(/connect$/u, ''), atmosphereOptions ?? {});
104+
// @ts-expect-error - vite environment variable
105+
const meta: ImportMeta = import.meta;
106+
if (!meta.env.SW_CONTEXT) {
107+
(async () => {
108+
atmosphere = await import('atmosphere.js');
109+
this.#connectWebsocket(connectPrefix.replace(/connect$/u, ''), atmosphereOptions ?? {});
110+
})().catch((e) => {
111+
// eslint-disable-next-line no-console
112+
console.error('Failed to load atmosphere.js', e);
113+
});
114+
}
93115
}
94116

95117
#resubscribeIfWasClosed() {

0 commit comments

Comments
 (0)