Skip to content

Commit 3d63b6e

Browse files
feat(audience): guard CDN bundle against double-import
- Preserves the first window.ImmutableAudience if the bundle runs twice. - Emits a console.warn instead of silently overwriting a live instance. - Prevents session loss if a studio accidentally loads the script twice. Refs SDK-115
1 parent 5a3d37f commit 3d63b6e

File tree

2 files changed

+27
-6
lines changed

2 files changed

+27
-6
lines changed

packages/audience/sdk/src/cdn.test.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,4 +42,18 @@ describe('cdn entry point', () => {
4242
});
4343
expect(err).toBeInstanceOf(Error);
4444
});
45+
46+
it('does not overwrite a pre-existing global', async () => {
47+
const sentinel = { Audience: 'FAKE' };
48+
(globalThis as unknown as { ImmutableAudience?: unknown }).ImmutableAudience = sentinel;
49+
50+
const warn = jest.spyOn(console, 'warn').mockImplementation(() => {});
51+
await import('./cdn');
52+
53+
expect(
54+
(globalThis as unknown as { ImmutableAudience?: unknown }).ImmutableAudience,
55+
).toBe(sentinel);
56+
expect(warn).toHaveBeenCalledWith(expect.stringContaining('loaded twice'));
57+
warn.mockRestore();
58+
});
4559
});

packages/audience/sdk/src/cdn.ts

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,16 @@ const globalObj = (
3636
typeof globalThis !== 'undefined' ? globalThis : window
3737
) as unknown as { ImmutableAudience?: ImmutableAudienceGlobal };
3838

39-
globalObj.ImmutableAudience = {
40-
Audience,
41-
AudienceError,
42-
IdentityType,
43-
version: LIBRARY_VERSION,
44-
};
39+
if (globalObj.ImmutableAudience) {
40+
// eslint-disable-next-line no-console
41+
console.warn(
42+
'[@imtbl/audience] CDN bundle loaded twice; keeping the first instance.',
43+
);
44+
} else {
45+
globalObj.ImmutableAudience = {
46+
Audience,
47+
AudienceError,
48+
IdentityType,
49+
version: LIBRARY_VERSION,
50+
};
51+
}

0 commit comments

Comments
 (0)