Skip to content

Commit

Permalink
Provide a ponyfill for CustomEvent (bluesky-social#2710)
Browse files Browse the repository at this point in the history
* fix(oauth-client): provide a ponyfill for CustomEvent (required by NodeJS < 20)
  • Loading branch information
matthieusieben authored Aug 15, 2024
1 parent acbacbb commit 0411278
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/hot-cows-scream.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@atproto/oauth-client": patch
---

Add CustomEvent ponyfill for enviroments that don't provide it
38 changes: 37 additions & 1 deletion packages/oauth/oauth-client/src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,39 @@ export function contentMime(headers: Headers): string | undefined {
return headers.get('content-type')?.split(';')[0]!.trim()
}

/**
* Ponyfill for `CustomEvent` constructor.
*/
export const CustomEvent: typeof globalThis.CustomEvent =
globalThis.CustomEvent ??
(() => {
class CustomEvent<T> extends Event {
#detail: T | null
constructor(type: string, options?: CustomEventInit<T>) {
if (!arguments.length) throw new TypeError('type argument is required')
super(type, options)
this.#detail = options?.detail ?? null
}
get detail() {
return this.#detail
}
}

Object.defineProperties(CustomEvent.prototype, {
[Symbol.toStringTag]: {
writable: false,
enumerable: false,
configurable: true,
value: 'CustomEvent',
},
detail: {
enumerable: true,
},
})

return CustomEvent
})()

export class CustomEventTarget<EventDetailMap extends Record<string, unknown>> {
readonly eventTarget = new EventTarget()

Expand All @@ -76,7 +109,10 @@ export class CustomEventTarget<EventDetailMap extends Record<string, unknown>> {
dispatchCustomEvent<T extends Extract<keyof EventDetailMap, string>>(
type: T,
detail: EventDetailMap[T],
init?: EventInit,
): boolean {
return this.eventTarget.dispatchEvent(new CustomEvent(type, { detail }))
return this.eventTarget.dispatchEvent(
new CustomEvent(type, { ...init, detail }),
)
}
}

0 comments on commit 0411278

Please sign in to comment.