Skip to content

Commit 40acade

Browse files
authored
fix: fetch proxy compatible with node 24 (#333)
In NodeJS v24 undici Response objects are constructed using a mixin pattern that looks like this: ```javascript class Test { #prop = "foo" get prop() { return this.#prop } static getProp(test) { return test.#prop } } function mixin(prototype, getInternal) { const methods = { status() { return getInternal(this) }, } Object.assign(prototype.prototype, methods) } mixin(Test, Test.getProp) const test = new Test() const proxied = new Proxy(test, { get(target, prop) { const r = Reflect.get(target, prop) if (typeof r === "function") { return r.bind(target) } return r }, }) console.log(test.prop) console.log(test.status()) console.log(proxied.prop) console.log(proxied.status()) ``` If we don't bind functions, then we'll get errors like this: ```shell return test.#prop ^ TypeError: Cannot read private member #prop from an object whose class did not declare it at getProp at Proxy.status at Object.<anonymous> ```
1 parent c4ad101 commit 40acade

1 file changed

Lines changed: 11 additions & 2 deletions

File tree

  • packages/typescript-fetch-runtime/src

packages/typescript-fetch-runtime/src/common.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,21 @@ export function responseValidationFactoryFactory<Schema>(
3838
}
3939

4040
return new Proxy(res, {
41-
get(target, prop, receiver) {
41+
get(target, prop) {
4242
if (prop === "json") {
4343
return json
4444
}
4545

46-
return Reflect.get(target, prop, receiver)
46+
const result = Reflect.get(target, prop)
47+
48+
// undici does some mixin magic, where it's important that the `this` context
49+
// is correct, or else it'll fail to access #private properties on the response
50+
// https://github.com/nodejs/undici/blob/edf9b3ff8bfdf5099826b612d8a55572bb707086/lib/web/fetch/response.js#L310
51+
if (typeof result === "function") {
52+
return result.bind(target)
53+
}
54+
55+
return result
4756
},
4857
})
4958
}

0 commit comments

Comments
 (0)