Skip to content
Myr

Fix hook state leaks and fetch option forwarding

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Clone nested retry options before init hooks run so hook mutations do not leak across requests. Avoid canceling shared response bodies when an `afterResponse` hook wraps an existing body in a new `Response`. Forward all non-standard, non-Ky options directly to `fetch()` instead of filtering against `Request`, which removes the obsolete vendor allowlist and preserves fetch-only extensions like dispatcher and Next.js next.

authored by Sindre Sorhus · committed by Sindre Sorhus · parent 7f2eade · Browse files · 7 files+249 added−24 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+249 added−24 removed

  • tests:+212 added−0 removed
  • other:+37 added−24 removed

7 files+249 added−24 removed

modified:source/core/constants.ts-7 removed
257 unmodified lines
258 fetch: true,259 context: true,260};261262// Vendor-specific fetch options that should always be passed to fetch()263// even if they appear on the Request object due to vendor patching.264// See: https://github.com/sindresorhus/ky/issues/541265export const vendorSpecificOptions = {266 next: true, // Next.js cache revalidation (revalidate, tags)267} as const;268262// Standard RequestInit options that should NOT be passed separately to fetch()263// because they're already applied to the Request object.264// Note: `dispatcher` and `priority` are NOT included here - they're fetch-only265// options that the Request constructor doesn't accept, so they need to be passed
17 unmodified lines
modified:source/core/Ky.ts+26 added-5 removed
19 unmodified lines
20 mergeHeaders,21 mergeHooks,22 deletedParametersSymbol,23} from '../utils/merge.js';24import type {RetryOptions} from '../types/retry.js';25import {normalizeRequestMethod, normalizeRetryOptions} from '../utils/normalize.js';26import timeout from '../utils/timeout.js';27import delay from '../utils/delay.js';28import {type ObjectEntries} from '../utils/types.js';
29 unmodified lines
58};5960const invalidSchemaMessage = 'The `schema` argument must follow the Standard Schema specification';6162const cloneRetryOptions = (retry: RetryOptions | number): RetryOptions | number => {63 if (typeof retry !== 'object') {64 return retry;65 }6667 // Clone nested arrays too so init hooks can mutate retry config without leaking state across requests.68 return {69 ...retry,70 ...(retry.methods && {methods: [...retry.methods]}),71 ...(retry.statusCodes && {statusCodes: [...retry.statusCodes]}),72 ...(retry.afterStatusCodes && {afterStatusCodes: [...retry.afterStatusCodes]}),73 };74};7576// Shallow-clone mutable option properties so init hook mutations don't leak across requests.77function cloneInitHookOptions(options: Options): Options {63 return {78 const clonedOptions: Options = {79 ...options,80 json: cloneShallow(options.json),66 retry: cloneShallow(options.retry)!,81 context: cloneShallow(options.context)!,82 headers: cloneShallow(options.headers)!,83 searchParams: cloneShallow(options.searchParams) as SearchParamsOption | undefined,84 };8586 if (options.retry !== undefined) {87 clonedOptions.retry = cloneRetryOptions(options.retry);88 }8990 return clonedOptions;91}9293const validateJsonWithSchema = async (jsonValue: unknown, schema: StandardSchemaV1): Promise<unknown> => {94 if (
695 unmodified lines
790 );791792 // Cancel any response bodies we won't use to prevent memory leaks.793 // Uses fire-and-forget since hooks may have cloned the response, creating tee branches that block cancellation.774 if (clonedResponse !== nextResponse) {794 // If the hook wrapped an existing body into a new Response, both Response objects can still point at the same stream.795 if (clonedResponse !== nextResponse && clonedResponse.body !== nextResponse.body) {796 this.#cancelResponseBody(clonedResponse);797 }798778 if (response !== nextResponse) {799 if (response !== nextResponse && response.body !== nextResponse.body) {800 this.#cancelResponseBody(response);801 }802803 response = nextResponse;
97 unmodified lines
901 // Recreate request with new signal902 this.request = new globalThis.Request(this.request, {signal: this.#options.signal});903 }904884 const nonRequestOptions = findUnknownOptions(this.request, this.#options);905 const nonRequestOptions = findUnknownOptions(this.#options);906 const retryRequest = this.#options.retry.limit > 0 ? this.request.clone() : undefined;907 const request = this.#wrapRequestWithUploadProgress(this.request, this.#options.body ?? undefined);908909 // Cloning is done here to prepare in advance for retries.
93 unmodified lines
modified:source/utils/normalize.ts+4 added-3 removed
modified:source/utils/options.ts+7 added-9 removed
modified:test/fetch.ts+57 added
133 unmodified lines
134135 await ky(fixture, {...options, fetch: customFetch}).text();136});137138test('unknown options with falsy values are passed to fetch', async t => {139 t.plan(3);140141 const customFetch: typeof fetch = async (request, init) => {142 t.is(init.customNull, null);143 t.is(init.customFalse, false);144 t.is(init.customZero, 0);145 return new Response(request.url);146 };147148 await ky(fixture, {149 customNull: null, customFalse: false, customZero: 0, fetch: customFetch,150 }).text();151});152153test('ky-specific options are not passed to fetch', async t => {154 const customFetch: typeof fetch = async (request, init) => {155 t.is(init.retry, undefined);156 t.is(init.timeout, undefined);157 t.is(init.hooks, undefined);158 t.is(init.throwHttpErrors, undefined);159 t.is(init.json, undefined);160 return new Response(request.url);161 };162163 await ky(fixture, {retry: 3, timeout: 5000, fetch: customFetch}).text();164});165166test('fetch-only options like dispatcher are passed to fetch', async t => {167 t.plan(1);168169 const mockDispatcher = {name: 'custom-agent'};
5 unmodified lines
175176 await ky(fixture, {dispatcher: mockDispatcher, fetch: customFetch}).text();177});178179test.serial('fetch-only options like dispatcher are passed to fetch even when Request is patched', async t => {180 t.plan(1);181182 const mockDispatcher = {name: 'custom-agent'};183 const originalDescriptor = Object.getOwnPropertyDescriptor(Request.prototype, 'dispatcher');184185 try {186 Object.defineProperty(Request.prototype, 'dispatcher', {187 value: undefined,188 writable: true,189 enumerable: true,190 configurable: true,191 });192193 const customFetch: typeof fetch = async (request, init) => {194 t.is(init.dispatcher, mockDispatcher);195 return new Response(request.url);196 };197198 await ky(fixture, {dispatcher: mockDispatcher, fetch: customFetch}).text();199 } finally {200 if (originalDescriptor) {201 Object.defineProperty(Request.prototype, 'dispatcher', originalDescriptor);202 } else {203 delete (Request.prototype as any).dispatcher;204 }205 }206});207208test('priority option is passed to fetch', async t => {209 t.plan(1);210211 const customFetch: typeof fetch = async (request, init) => {
40 unmodified lines
modified:test/hooks.ts+140 added
212 unmodified lines
213 t.is(responseText, 'ok');214 t.true(originalResponse?.bodyUsed);215});216217test('afterResponse hook can wrap the provided body in a new response', async t => {218 const responseText = await ky('https://example.com', {219 fetch: async () => new Response('ok', {220 headers: {221 'content-type': 'text/plain',222 },223 }),224 hooks: {225 afterResponse: [226 ({response}) => new Response(response.body, {227 headers: response.headers,228 }),229 ],230 },231 }).text();232233 t.is(responseText, 'ok');234});235236test('afterResponse hook can wrap a streaming body in a new response', async t => {237 const customFetch = createStreamFetch({text: 'streamed'});238239 const responseText = await ky('https://example.com', {240 fetch: customFetch,241 hooks: {242 afterResponse: [243 ({response}) => new Response(response.body, {244 headers: response.headers,245 }),246 ],247 },248 }).text();249250 t.is(responseText, 'streamed');251});252253test('afterResponse hook chain can forward the same body through multiple hooks', async t => {254 let originalResponse: Response | undefined;255256 const customFetch = createStreamFetch({257 text: 'chained',258 onResponse(response) {259 originalResponse = response;260 },261 });262263 const responseText = await ky('https://example.com', {264 fetch: customFetch,265 hooks: {266 afterResponse: [267 ({response}) => new Response(response.body, {268 headers: response.headers,269 }),270 ({response}) => new Response(response.body, {271 headers: response.headers,272 }),273 ],274 },275 }).text();276277 t.is(responseText, 'chained');278 // The original fetch response body should be cancelled since hooks created new wrappers279 t.true(originalResponse?.bodyUsed);280});281282test('afterResponse hook with multiple hooks cancels all unused clones', async t => {283 let originalResponse: Response | undefined;284 const clones: Response[] = [];285
4503 unmodified lines
47894790 t.deepEqual(seenLimits, [2, 2]);4791});47924793test('init hook nested retry mutations do not leak across requests', async t => {4794 const seenMethods: string[][] = [];47954796 const api = ky.extend({4797 retry: {4798 methods: ['get'],4799 },4800 hooks: {4801 init: [4802 options => {4803 seenMethods.push([...options.retry.methods]);4804 options.retry.methods.push('post');4805 },4806 ],4807 },4808 });48094810 const fetch: typeof globalThis.fetch = async () => new Response('ok');48114812 await api.get('https://example.com', {fetch});4813 await api.get('https://example.com', {fetch});48144815 t.deepEqual(seenMethods, [['get'], ['get']]);4816});48174818test('init hook nested retry statusCodes mutations do not leak across requests', async t => {4819 const seenStatusCodes: number[][] = [];48204821 const api = ky.extend({4822 retry: {4823 statusCodes: [500],4824 },4825 hooks: {4826 init: [4827 options => {4828 seenStatusCodes.push([...options.retry.statusCodes]);4829 options.retry.statusCodes.push(502);4830 },4831 ],4832 },4833 });48344835 const fetch: typeof globalThis.fetch = async () => new Response('ok');48364837 await api.get('https://example.com', {fetch});4838 await api.get('https://example.com', {fetch});48394840 t.deepEqual(seenStatusCodes, [[500], [500]]);4841});48424843test('init hook nested retry afterStatusCodes mutations do not leak across requests', async t => {4844 const seenAfterStatusCodes: number[][] = [];48454846 const api = ky.extend({4847 retry: {4848 afterStatusCodes: [429],4849 },4850 hooks: {4851 init: [4852 options => {4853 seenAfterStatusCodes.push([...options.retry.afterStatusCodes]);4854 options.retry.afterStatusCodes.push(503);4855 },4856 ],4857 },4858 });48594860 const fetch: typeof globalThis.fetch = async () => new Response('ok');48614862 await api.get('https://example.com', {fetch});4863 await api.get('https://example.com', {fetch});48644865 t.deepEqual(seenAfterStatusCodes, [[429], [429]]);4866});48674868test('init hook in-place json mutations do not leak across requests', async t => {4869 let requestIdentifier = 0;4870 const seenRequestIdentifiers: string[] = [];4871
259 unmodified lines
modified:test/main.ts+15 added
776 unmodified lines
777778 t.true(duration < 10);779});780781test('normalizing retry options does not mutate the caller retry object', async t => {782 const retry = {783 methods: ['GET'],784 };785786 await ky('https://example.com', {787 fetch: async () => new Response('ok'),788 retry,789 }).text();790791 t.deepEqual(retry, {792 methods: ['GET'],793 });794});795796test('searchParams option', async t => {797 const server = await createHttpTestServer(t);798799 server.get('/', (request, response) => {
1613 unmodified lines