| 165 | } |
| 166 | |
| 167 | public on<Event extends keyof ConsumerEvents & string>( |
| 168 | event: Event, |
| 169 | listener: ( |
| 170 | message: ConsumerEvents[Event] extends [infer PayloadType, infer _] ? PayloadType : ConsumerEvents[Event] |
| 171 | ) => MaybePromise<ConsumerEvents[Event] extends [infer _, infer ReturnType] ? ReturnType | undefined : void>, |
| 172 | options?: AddEventListenerOptions |
| 173 | ): void { |
| 174 | this.emitter.addEventListener( |
| 175 | event, |
| 176 | async (message) => { |
| 177 | if (!(message instanceof MessageEvent)) { |
| 178 | return; |
| 179 | } |
| 180 | |
| 181 | // Send back the confirmation about the operation completion. |
| 182 | const { operationId, payload } = message.data; |
| 183 | |
| 184 | try { |
| 185 | const listenerPayload = await listener(payload); |
| 186 | this.send('internal/operation/done', { operationId, listenerPayload }); |
| 187 | } catch (error) { |
| 188 | if (error instanceof Error) { |
| 189 | this.send('internal/operation/failed', { operationId, error }); |
| 190 | } |
| 191 | } |
| 192 | }, |
| 193 | options |
| 194 | ); |
| 195 | } |
| 196 | |
| 197 | public send<Event extends keyof WorkerEvents & string>( |
| 198 | event: Event, |