Skip to content

Commit

Permalink
Allow dynamically import atmosphere.js for SW context
Browse files Browse the repository at this point in the history
Fixes #2867
  • Loading branch information
krissvaa committed Nov 11, 2024
1 parent f5f6170 commit 7e3b139
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions packages/ts/frontend/src/FluxConnection.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -9,6 +11,8 @@ import {
type ServerMessage,
} from './FluxMessages.js';

let atmosphere: Atmosphere.Atmosphere;

export enum State {
ACTIVE = 'active',
INACTIVE = 'inactive',
Expand Down Expand Up @@ -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.
*/
Expand All @@ -89,7 +101,17 @@ export class FluxConnection extends EventTarget {

constructor(connectPrefix: string, atmosphereOptions?: Partial<Atmosphere.Request>) {
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() {
Expand Down

0 comments on commit 7e3b139

Please sign in to comment.