Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/framecast-destroy-listener-leak.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@ciolabs/framecast': minor
---

Fix window `message` listener leak and add `destroy()` method. The constructor previously passed a fresh `this.handlePostedMessage.bind(this)` to both `removeEventListener` and `addEventListener`, so the removal never matched and every Framecast instance leaked its listener for the life of the page. A single bound handler is now kept on the instance, and the new `destroy()` method removes the listener, rejects pending `call()`s with a "Framecast destroyed" error (clearing their timeouts), clears broadcast listeners, discards queued broadcasts, and nulls the target window so a detached iframe can be garbage collected. After `destroy()`, `postMessage` becomes a no-op instead of posting to a stale window.
107 changes: 105 additions & 2 deletions packages/framecast/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,111 @@ describe('Framecast', () => {
expect(mockSelfWindow.addEventListener).toHaveBeenCalledWith('message', expect.any(Function));
});

it('should remove existing message listener before adding new one', () => {
expect(mockSelfWindow.removeEventListener).toHaveBeenCalledWith('message', expect.any(Function));
it('should not remove any message listener on construction', () => {
expect(mockSelfWindow.removeEventListener).not.toHaveBeenCalled();
});
});

describe('destroy', () => {
type MessageListener = (event: MessageEvent) => void;

type StubWindow = Window & { messageListeners: Set<MessageListener>; postMessage: ReturnType<typeof vi.fn> };

function createStubWindow(): StubWindow {
const messageListeners = new Set<MessageListener>();

return {
messageListeners,
addEventListener(type: string, listener: MessageListener) {
if (type === 'message') {
messageListeners.add(listener);
}
},
removeEventListener(type: string, listener: MessageListener) {
if (type === 'message') {
messageListeners.delete(listener);
}
},
postMessage: vi.fn(),
} as unknown as StubWindow;
}

it('adds a single message listener to self on construction', () => {
const self = createStubWindow();
const target = createStubWindow();

new Framecast(target, { self });

expect(self.messageListeners.size).toBe(1);
});

it('removes the message listener added on construction', () => {
const self = createStubWindow();
const target = createStubWindow();

const instance = new Framecast(target, { self });
instance.destroy();

expect(self.messageListeners.size).toBe(0);
});

it('does not accumulate window listeners across create/destroy cycles', () => {
const self = createStubWindow();

for (let index = 0; index < 5; index++) {
const instance = new Framecast(createStubWindow(), { self });
instance.destroy();
}

expect(self.messageListeners.size).toBe(0);
});

it('rejects pending function calls and clears their timeouts', async () => {
const self = createStubWindow();
const target = createStubWindow();
const instance = new Framecast(target, {
self,
functionTimeoutMs: 20,
});

const rejected = vi.fn();
instance.call('anything').catch(rejected);

instance.destroy();
await new Promise(resolve => setTimeout(resolve, 60));

// rejected once by destroy, not a second time by the call timeout
expect(rejected).toHaveBeenCalledTimes(1);
expect(rejected).toHaveBeenCalledWith(new Error('Framecast destroyed'));
});

it('releases the target window and makes postMessage a no-op', () => {
const self = createStubWindow();
const target = createStubWindow();
const instance = new Framecast(target, { self });

instance.destroy();
instance.broadcast({ hello: 'world' });

expect(target.postMessage).not.toHaveBeenCalled();
});

it('discards queued broadcasts', async () => {
const self = createStubWindow();
const target = createStubWindow();
const instance = new Framecast(target, { self, functionTimeoutMs: 20 });

const readyPromise = instance.waitForReady({ interval: 10, timeout: 50, queueMessages: true });
instance.broadcast({ hello: 'queued' });

instance.destroy();
await expect(readyPromise).rejects.toThrow();

const flushed = target.postMessage.mock.calls.filter(call => {
const message = superjson.parse(call[0]) as any;
return message.type === 'broadcast';
});
expect(flushed).toHaveLength(0);
});
});

Expand Down
41 changes: 37 additions & 4 deletions packages/framecast/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,10 @@ type ListenerMap = {

export class Framecast {
/**
* The element we are communicating with.
* The element we are communicating with. Nulled by destroy() so a
* detached iframe window can be garbage collected.
*/
private target: Window;
private target: Window | null;

/**
* Config for the framecast.
Expand All @@ -61,6 +62,14 @@ export class Framecast {
*/
private pendingFunctionCalls: Map<string, { timeout: number; resolve: Function; reject: Function }> = new Map();

/**
* The bound message handler, kept so the window listener added in the
* constructor can be removed again in destroy(). Binding inline in
* add/removeEventListener creates a new function each time, so the
* listener would never actually be removed.
*/
private boundHandlePostedMessage = this.handlePostedMessage.bind(this);

/**
* When true, broadcast() queues messages instead of posting them.
* Set by waitForReady({ queueMessages: true }), cleared on
Expand All @@ -76,8 +85,7 @@ export class Framecast {

this.target = target;
this.config = { ...this.config, ...config };
this.self.removeEventListener('message', this.handlePostedMessage.bind(this));
this.self.addEventListener('message', this.handlePostedMessage.bind(this));
this.self.addEventListener('message', this.boundHandlePostedMessage);

if (this.config.supportEvaluate) {
this.on('function:evaluate', async (function_: string) => {
Expand Down Expand Up @@ -112,6 +120,10 @@ export class Framecast {
}

private postMessage(type: string, message: any) {
if (this.target == null) {
return;
}

this.target.postMessage(superjson.stringify({ ...message, type, channel: this.channel }), this.origin);
}

Expand Down Expand Up @@ -144,6 +156,27 @@ export class Framecast {
}
}

/**
* Removes the window message listener, rejects pending function calls
* with a "Framecast destroyed" error, clears all event listeners,
* discards any queued broadcasts and releases the reference to the
* target window so a detached iframe window can be garbage collected.
* postMessage becomes a no-op after destroy. The instance must not be
* used after calling destroy.
*/
destroy(): void {
this.self.removeEventListener('message', this.boundHandlePostedMessage);

for (const [id, pendingCall] of this.pendingFunctionCalls.entries()) {
this.clearPendingFunctionCall(id);
pendingCall.reject(new Error('Framecast destroyed'));
}

this.listeners = { broadcast: new Set() };
this.clearQueue();
this.target = null;
}

/**
* Sends an message
*
Expand Down
Loading