|
| 1 | +/** |
| 2 | + * Collection of helpers for briding the compatibility between the old and the new APIs. |
| 3 | + */ |
| 4 | +import { Emitter } from 'rettime' |
| 5 | +import { |
| 6 | + Emitter as LegacyEmitter, |
| 7 | + EventMap as LegacyEventMap, |
| 8 | +} from 'strict-event-emitter' |
| 9 | +import { type UnhandledRequestStrategy } from '~/core/utils/request/onUnhandledRequest' |
| 10 | +import { |
| 11 | + onUnhandledFrame, |
| 12 | + type UnhandledFrameCallback, |
| 13 | +} from './on-unhandled-frame' |
| 14 | + |
| 15 | +export function toLegacyEmitter<EventMap extends LegacyEventMap>( |
| 16 | + emitter: Emitter<any>, |
| 17 | +): LegacyEmitter<EventMap> { |
| 18 | + const legacy = new LegacyEmitter<EventMap>() |
| 19 | + |
| 20 | + legacy |
| 21 | + .addListener('newListener', (type, listener) => { |
| 22 | + emitter.on(type as any, (event) => listener(event.data)) |
| 23 | + }) |
| 24 | + .addListener('removeListener', (type, listener) => { |
| 25 | + emitter.removeListener(type as any, listener) |
| 26 | + }) |
| 27 | + |
| 28 | + return legacy |
| 29 | +} |
| 30 | + |
| 31 | +export function fromLegacyOnUnhandledRequest( |
| 32 | + getLegacyValue: () => UnhandledRequestStrategy | undefined, |
| 33 | +): UnhandledFrameCallback { |
| 34 | + return ({ frame, defaults }) => { |
| 35 | + const legacyOnUnhandledRequestStrategy = getLegacyValue() |
| 36 | + |
| 37 | + if (legacyOnUnhandledRequestStrategy === undefined) { |
| 38 | + return |
| 39 | + } |
| 40 | + |
| 41 | + if (typeof legacyOnUnhandledRequestStrategy === 'function') { |
| 42 | + const request = |
| 43 | + frame.protocol === 'http' |
| 44 | + ? frame.data.request |
| 45 | + : new Request(frame.data.connection.client.url, { |
| 46 | + headers: { |
| 47 | + connection: 'upgrade', |
| 48 | + upgrade: 'websocket', |
| 49 | + }, |
| 50 | + }) |
| 51 | + |
| 52 | + return legacyOnUnhandledRequestStrategy(request, { |
| 53 | + warning: defaults.warn, |
| 54 | + error: defaults.error, |
| 55 | + }) |
| 56 | + } |
| 57 | + |
| 58 | + return onUnhandledFrame(frame, legacyOnUnhandledRequestStrategy) |
| 59 | + } |
| 60 | +} |
0 commit comments