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
4 changes: 4 additions & 0 deletions packages/web-worker/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,14 @@ function createClonedMessageEvent(

debug('clone worker message %o', data)
const origin = typeof location === 'undefined' ? undefined : location.origin
const ports = transfer?.filter((t): t is MessagePort => t instanceof MessagePort)

if (typeof structuredClone === 'function' && clone === 'native') {
debug('create message event, using native structured clone')
return new MessageEvent('message', {
data: structuredClone(data, { transfer }),
origin,
ports,
})
}
if (clone !== 'none') {
Expand All @@ -50,12 +52,14 @@ function createClonedMessageEvent(
return new MessageEvent('message', {
data: ponyfillStructuredClone(data, { lossy: true } as any),
origin,
ports,
})
}
debug('create message event without cloning an object')
return new MessageEvent('message', {
data,
origin,
ports,
})
}

Expand Down
5 changes: 5 additions & 0 deletions test/core/src/web-worker/worker.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
self.onmessage = (e) => {
self.postMessage(`${e.data} world`)

const port = e.ports[0]
if (port) {
port.postMessage(`${e.data} world via port`)
}
}
13 changes: 13 additions & 0 deletions test/core/test/web-worker-node.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,19 @@ it('self injected into worker and its deps should be equal', async () => {
expect(await testSelfWorker(new Worker(new URL('../src/web-worker/selfWorker.ts', import.meta.url)))).toBeTruthy()
})

it('transfer MessagePort objects to worker as event.ports', async () => {
expect.assertions(1)

const worker = new MyWorker()
const channel = new MessageChannel()
const promise = new Promise<string>((resolve, reject) => {
channel.port1.onmessage = e => resolve(e.data as string)
channel.port1.onmessageerror = reject
})
worker.postMessage('hello', [channel.port2])
await expect(promise).resolves.toBe('hello world via port')
})

it('throws syntax error if no arguments are provided', () => {
const worker = new MyWorker()

Expand Down
Loading