fetch.ts
This file
Path
test/fetch.ts
979 lines · 26.6 KiB · TypeScript
Last changed by
RefactorSindre Sorhusbefore adoptiona5ed57b
History of this fileTake it
The walk stopped after 200 commits: lines older than 37fc250 point at it.
Fix a stale timeout timer aborting the retried attempt when a custom `fetch` throws synchronouslySindre Sorhusbefore adoption0f2e281
line 1why, one step back1import {setTimeout as delay} from 'node:timers/promises';Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 2why, one step back2import test from 'ava';TweaksSindre Sorhusbefore adoption3ded2aa
line 3why, one step back3import ky, {NetworkError} from '../source/index.js';Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 4–7why, one step back4import {createHttpTestServer} from './helpers/create-http-test-server.js';56const fixture = 'https://example.com/unicorn';7Type custom fetch callbacks with Request inputsSindre Sorhusbefore adoptione58817d
lines 8–30why, one step back8for (const timeout of [false, 1000] as const) {9 test(`custom fetch receives a normalized Request with timeout ${timeout}`, async t => {10 for (const input of [fixture, new URL(fixture), new Request(fixture)]) {11 // eslint-disable-next-line no-await-in-loop12 const response = await ky(input, {13 timeout,14 method: 'POST',15 json: {answer: 42},16 searchParams: {page: 2},17 async fetch(request) {18 t.true(request instanceof Request);19 t.is(request.method, 'POST');20 t.is(request.url, `${fixture}?page=2`);21 t.is(request.headers.get('content-type'), 'application/json');22 t.deepEqual(await request.json(), {answer: 42});23 return new Response('ok');24 },25 }).text();26 t.is(response, 'ok');27 }28 });29}30Support readonly inputs and explicit undefined in TypeScript optionsSindre Sorhusbefore adoption51b3177
lines 31–47why, one step back31test('undefined restores native fetch without changing the parent', async t => {32 const server = await createHttpTestServer(t);33 let requestCount = 0;34 server.get('/', (_request, response) => {35 requestCount++;36 response.end('native fetch');37 });38 const parent = ky.create({fetch: async () => new Response('custom fetch')});39 const child = parent.extend({fetch: undefined});4041 t.is(await parent(server.url).text(), 'custom fetch');42 t.is(await child(server.url).text(), 'native fetch');43 t.is(await parent(server.url, {fetch: undefined}).text(), 'native fetch');44 t.is(await parent(server.url).text(), 'custom fetch');45 t.is(requestCount, 2);46});47Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f
lines 48–74why, one step back48for (const retry of [0, 2]) {49 test(`custom fetch can return the request body as a response with retry ${retry}`, async t => {50 const text = await ky.post(fixture, {51 retry,52 body: 'echo-payload',53 fetch: async request => new Response(request.body),54 }).text();5556 t.is(text, 'echo-payload');57 });58}5960test('beforeRequest can return a response that shares the outgoing request body', async t => {61 const text = await ky.post(fixture, {62 body: 'cached-body',63 hooks: {64 beforeRequest: [({request}) => new Response(request.body)],65 },66 async fetch() {67 t.fail('A hook-provided response must skip fetch');68 return new Response();69 },70 }).text();7172 t.is(text, 'cached-body');73});74Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 75–133why, one step back75test('fetch option takes a custom fetch function', async t => {76 t.plan(10);7778 const customFetch: typeof fetch = async input => {79 if (!(input instanceof Request)) {80 throw new TypeError('Expected to have input as request');81 }8283 return new Response(input.url);84 };8586 t.is(await ky(fixture, {fetch: customFetch}).text(), fixture);87 t.is(88 await ky(fixture, {89 fetch: customFetch,90 searchParams: {foo: 'bar'},91 }).text(),92 `${fixture}?foo=bar`,93 );94 t.is(95 await ky(fixture, {96 fetch: customFetch,97 searchParams: {},98 }).text(),99 `${fixture}`,100 );101 t.is(102 await ky(fixture, {103 fetch: customFetch,104 searchParams: [],105 }).text(),106 `${fixture}`,107 );108 t.is(109 await ky(fixture, {110 fetch: customFetch,111 searchParams: new URLSearchParams(),112 }).text(),113 `${fixture}`,114 );115 t.is(116 await ky(fixture, {117 fetch: customFetch,118 searchParams: ' ',119 }).text(),120 `${fixture}`,121 );122 t.is(123 await ky(`${fixture}#hash`, {124 fetch: customFetch,125 searchParams: 'foo',126 }).text(),127 `${fixture}?foo#hash`,128 );129 t.is(130 await ky(`${fixture}?old`, {131 fetch: customFetch,132 searchParams: 'new',133 }).text(),Merge `searchParams` with input URL (#840)AkaHarshitbefore adoption29e78fe
line 134why, one step back134 `${fixture}?old&new`,Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 135–140why, one step back135 );136 t.is(137 await ky(`${fixture}?old#hash`, {138 fetch: customFetch,139 searchParams: 'new',140 }).text(),Merge `searchParams` with input URL (#840)AkaHarshitbefore adoption29e78fe
line 141why, one step back141 `${fixture}?old&new#hash`,Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 142why, one step back142 );Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f
line 143why, one step back143 t.is(await ky('unicorn', {fetch: customFetch, prefix: `${fixture}/api/`}).text(), `${fixture}/api/unicorn`);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 144–158why, one step back144});145146test('options are correctly passed to Fetch #1', async t => {147 t.plan(1);148149 const cache = 'no-store';150151 const customFetch: typeof fetch = async request => {152 t.is(request.cache, cache);153 return new Response(request.url);154 };155156 await ky(fixture, {cache, fetch: customFetch}).text();157});158Preserve request referrer optionsSindre Sorhusbefore adoptionf87efe6
lines 159–189why, one step back159for (const searchParameters of [undefined, {page: '2'}]) {160 test(`Request input preserves referrer options${searchParameters ? ' with searchParams' : ''}`, async t => {161 const referrer = 'https://example.com/source';162 const referrerPolicy = 'no-referrer';163 const request = new Request(fixture, {referrer, referrerPolicy});164165 const result = await ky(request, {166 searchParams: searchParameters,167 async fetch(request) {168 return Response.json({referrer: request.referrer, referrerPolicy: request.referrerPolicy});169 },170 }).json();171172 t.deepEqual(result, {referrer, referrerPolicy});173 });174175 test(`Request input allows overriding referrer options${searchParameters ? ' with searchParams' : ''}`, async t => {176 const request = new Request(fixture, {referrer: 'https://example.com/source', referrerPolicy: 'no-referrer'});177 const result = await ky(request, {178 referrer: '',179 referrerPolicy: 'same-origin',180 searchParams: searchParameters,181 async fetch(request) {182 return Response.json({referrer: request.referrer, referrerPolicy: request.referrerPolicy});183 },184 }).json();185186 t.deepEqual(result, {referrer: '', referrerPolicy: 'same-origin'});187 });188}189Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 190why, one step back190test('options are correctly passed to Fetch #2', async t => {Simplify testsSindre Sorhusbefore adoptiondfa3f59
line 191why, one step back191 const server = await createHttpTestServer(t);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 192–201why, one step back192193 server.post('/anything', (request, response) => {194 response.json({json: request.body});195 });196197 const fixture = {x: true};198 const json = await ky.post(`${server.url}/anything`, {json: fixture}).json();199 t.deepEqual(json.json, fixture);200});201Add regression for custom fetch POST body hangSindre Sorhusbefore adoption6ed304d
lines 202–223why, one step back202test('post with json does not hang when custom fetch consumes request body', async t => {203 const fixture = {x: true};204205 const customFetch: typeof fetch = async request => {206 t.is(request.method, 'POST');207 const parsedBody = await request.json();208209 return new Response(JSON.stringify({ok: true, parsedBody}), {210 headers: {211 'content-type': 'application/json',212 },213 });214 };215216 const json = await ky.post('https://example.com/endpoint', {217 json: fixture,218 fetch: customFetch,219 }).json();220221 t.deepEqual(json, {ok: true, parsedBody: fixture});222});223RefactorSindre Sorhusbefore adoptiona5ed57b
lines 224–242why, one step back224// Ky cancels the request body once the request settles, and canceling a stream that a reader still holds rejects, so that rejection must not reach the caller.225test('a custom fetch that locks a stream request body without reading it still resolves', async t => {226 const text = await ky.post(fixture, {227 body: new ReadableStream<Uint8Array>({228 start(controller) {229 controller.enqueue(new TextEncoder().encode('payload'));230 controller.close();231 },232 }),233 retry: 0,234 async fetch(request) {235 (request as Request).body!.getReader();236 return new Response('ok');237 },238 }).text();239240 t.is(text, 'ok');241});242Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 243–255why, one step back243test('unknown options are passed to fetch', async t => {244 t.plan(1);245246 const options = {next: {revalidate: 3600}};247248 const customFetch: typeof fetch = async (request, init) => {249 t.is(init.next, options.next);250 return new Response(request.url);251 };252253 await ky(fixture, {...options, fetch: customFetch}).text();254});255Fix hook state leaks and fetch option forwardingSindre Sorhusbefore adoption2df9b7e
lines 256–283why, one step back256test('unknown options with falsy values are passed to fetch', async t => {257 t.plan(3);258259 const customFetch: typeof fetch = async (request, init) => {260 t.is(init.customNull, null);261 t.is(init.customFalse, false);262 t.is(init.customZero, 0);263 return new Response(request.url);264 };265266 await ky(fixture, {267 customNull: null, customFalse: false, customZero: 0, fetch: customFetch,268 }).text();269});270271test('ky-specific options are not passed to fetch', async t => {272 const customFetch: typeof fetch = async (request, init) => {273 t.is(init.retry, undefined);274 t.is(init.timeout, undefined);275 t.is(init.hooks, undefined);276 t.is(init.throwHttpErrors, undefined);277 t.is(init.json, undefined);278 return new Response(request.url);279 };280281 await ky(fixture, {retry: 3, timeout: 5000, fetch: customFetch}).text();282});283Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 284–294why, one step back284test('fetch-only options like dispatcher are passed to fetch', async t => {285 t.plan(1);286287 const mockDispatcher = {name: 'custom-agent'};288289 const customFetch: typeof fetch = async (request, init) => {290 t.is(init.dispatcher, mockDispatcher);291 return new Response(request.url);292 };293294 await ky(fixture, {dispatcher: mockDispatcher, fetch: customFetch}).text();Fix hook state leaks and fetch option forwardingSindre Sorhusbefore adoption2df9b7e
lines 295–296why, one step back295});296Fix option merging rewriting nested user data and flattening class instancesSindre Sorhusbefore adoptione06d351
lines 297–335why, one step back297test('class instance options like dispatcher replace instance defaults instead of being merged into plain objects', async t => {298 t.plan(2);299300 class Agent {301 constructor(readonly name: string) {}302303 // eslint-disable-next-line @typescript-eslint/no-empty-function304 dispatch() {}305 }306307 const defaultAgent = new Agent('default');308 const requestAgent = new Agent('request');309310 const customFetch: typeof fetch = async (request, init) => {311 t.is(init.dispatcher, requestAgent);312 t.true(init.dispatcher instanceof Agent);313 return new Response(request.url);314 };315316 const api = ky.create({dispatcher: defaultAgent, fetch: customFetch});317 await api(fixture, {dispatcher: requestAgent}).text();318});319320test('plain object options replace class instance defaults instead of being merged into them', async t => {321 t.plan(1);322323 class Agent {324 constructor(readonly name: string) {}325 }326327 const customFetch: typeof fetch = async (request, init) => {328 t.deepEqual(init.dispatcher, {name: 'request'});329 return new Response(request.url);330 };331332 const api = ky.create({dispatcher: new Agent('default'), fetch: customFetch});333 await api(fixture, {dispatcher: {name: 'request'}}).text();334});335Fix hook state leaks and fetch option forwardingSindre Sorhusbefore adoption2df9b7e
lines 336–362why, one step back336test.serial('fetch-only options like dispatcher are passed to fetch even when Request is patched', async t => {337 t.plan(1);338339 const mockDispatcher = {name: 'custom-agent'};340 const originalDescriptor = Object.getOwnPropertyDescriptor(Request.prototype, 'dispatcher');341342 try {343 Object.defineProperty(Request.prototype, 'dispatcher', {344 value: undefined,345 writable: true,346 enumerable: true,347 configurable: true,348 });349350 const customFetch: typeof fetch = async (request, init) => {351 t.is(init.dispatcher, mockDispatcher);352 return new Response(request.url);353 };354355 await ky(fixture, {dispatcher: mockDispatcher, fetch: customFetch}).text();356 } finally {357 if (originalDescriptor) {358 Object.defineProperty(Request.prototype, 'dispatcher', originalDescriptor);359 } else {360 delete (Request.prototype as any).dispatcher;361 }362 }Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 363–374why, one step back363});364365test('priority option is passed to fetch', async t => {366 t.plan(1);367368 const customFetch: typeof fetch = async (request, init) => {369 t.is(init.priority, 'high');370 return new Response(request.url);371 };372373 await ky(fixture, {priority: 'high', fetch: customFetch}).text();374});Fix Next.js edge runtime `next` option support (#775)Sindre Sorhusbefore adoptioncaf78d2
lines 375–407why, one step back375376test.serial('vendor-specific options like `next` are passed to fetch even when Request is patched', async t => {377 t.plan(1);378379 const options = {next: {revalidate: 3600, tags: ['test']}};380381 // Simulate Next.js edge runtime behavior by patching Request.prototype382 const originalDescriptor = Object.getOwnPropertyDescriptor(Request.prototype, 'next');383384 try {385 // Patch Request.prototype to have a 'next' property (like Next.js does in edge runtime)386 Object.defineProperty(Request.prototype, 'next', {387 value: undefined,388 writable: true,389 enumerable: true,390 configurable: true,391 });392393 const customFetch: typeof fetch = async (request, init) => {394 // Verify that the `next` option is still passed to fetch despite being on Request.prototype395 t.deepEqual(init.next, options.next);396 return new Response(request.url);397 };398399 await ky(fixture, {...options, fetch: customFetch}).text();400 } finally {401 // Restore original state402 if (originalDescriptor) {403 Object.defineProperty(Request.prototype, 'next', originalDescriptor);404 } else {405 delete (Request.prototype as any).next;406 }407 }Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f
lines 408–499why, one step back408});409410for (const totalTimeout of [false, 1000] as const) {411 test(`a response returned after fetch timeout has its unused body cancelled with totalTimeout ${totalTimeout}`, async t => {412 let resolveFetch!: (response: Response) => void;413 const fetchPromise = new Promise<Response>(resolve => {414 resolveFetch = resolve;415 });416 let cancelled = false;417 const response = new Response(new ReadableStream({418 cancel() {419 cancelled = true;420 },421 }));422 t.teardown(async () => {423 await response.body?.cancel();424 });425426 let fetchStarted = false;427 await t.throwsAsync(ky(fixture, {428 timeout: totalTimeout === false ? 20 : false,429 totalTimeout,430 retry: 0,431 async fetch() {432 fetchStarted = true;433 return fetchPromise;434 },435 }), {name: 'TimeoutError'});436437 t.true(fetchStarted);438 resolveFetch(response);439 await delay(0);440 t.true(cancelled);441 });442}443444for (const cancellation of ['rejects', 'never settles'] as const) {445 test(`late response cleanup does not change the timeout when cancellation ${cancellation}`, async t => {446 let resolveFetch!: (response: Response) => void;447 const fetchPromise = new Promise<Response>(resolve => {448 resolveFetch = resolve;449 });450 let cancellations = 0;451 const response = new Response(new ReadableStream({452 async cancel() {453 cancellations++;454 if (cancellation === 'rejects') {455 throw new Error('cancellation failed');456 }457458 await new Promise(() => {459 // Simulate an underlying stream that never finishes cancellation.460 });461 },462 }));463 const errors: Error[] = [];464 const error = await t.throwsAsync(ky(fixture, {465 timeout: 20,466 retry: 0,467 fetch: async () => fetchPromise,468 hooks: {469 beforeError: [({error}) => {470 errors.push(error);471 return error;472 }],473 },474 }), {name: 'TimeoutError'});475476 resolveFetch(response);477 await delay(0);478 t.is(cancellations, 1);479 t.deepEqual(errors, [error]);480 });481}482483test('a late response from a timed-out attempt does not cancel the active retry', async t => {484 const firstFetch = Promise.withResolvers<Response>();485 const cancellation = Promise.withResolvers<void>();486 let attempts = 0;487 let cancellations = 0;488 let retryHookCalls = 0;489 const discardedResponse = new Response(new ReadableStream({490 cancel() {491 cancellations++;492 cancellation.resolve();493 },494 }));495 t.teardown(() => {496 void discardedResponse.body?.cancel().catch(() => undefined);497 });498499 const result = await ky(fixture, {Detect request stream support in Bun and Deno, and cover the pipeline with testsSindre Sorhusbefore adoption83c711c
line 500why, one step back500 timeout: 50,Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f
lines 501–552why, one step back501 retry: {limit: 1, retryOnTimeout: true, delay: () => 0},502 hooks: {503 beforeRetry: [({error, retryCount}) => {504 retryHookCalls++;505 t.is(error.name, 'TimeoutError');506 t.is(retryCount, 1);507 }],508 beforeError: [({error}) => {509 t.fail('A successful retry must not run beforeError');510 return error;511 }],512 },513 async fetch(request) {514 attempts++;515 if (attempts === 1) {516 return firstFetch.promise;517 }518519 firstFetch.resolve(discardedResponse);520 await cancellation.promise;521 t.is(cancellations, 1);522 t.false(request.signal.aborted);523 return new Response('retry succeeded');524 },525 }).text();526527 t.is(result, 'retry succeeded');528 t.is(attempts, 2);529 t.is(retryHookCalls, 1);530 t.is(cancellations, 1);531});532533test('a response returned before fetch timeout remains readable', async t => {534 let cancelled = false;535 const response = await ky(fixture, {536 timeout: 1000,537 retry: 0,538 async fetch() {539 return new Response(new ReadableStream({540 start(controller) {541 controller.enqueue(new TextEncoder().encode('response'));542 controller.close();543 },544 cancel() {545 cancelled = true;546 },547 }));548 },549 });550551 t.is(await response.text(), 'response');552 t.false(cancelled);Fix a stale timeout timer aborting the retried attempt when a custom `fetch` throws synchronouslySindre Sorhusbefore adoption0f2e281
lines 553–779why, one step back553});554555test('a synchronously throwing fetch rejects with that error', async t => {556 const error = new Error('sync boom');557558 await t.throwsAsync(ky(fixture, {559 retry: 0,560 fetch() {561 throw error;562 },563 }), {is: error});564});565566test('a synchronously throwing fetch rejects with that error when timeout is disabled', async t => {567 const error = new Error('sync boom');568569 await t.throwsAsync(ky(fixture, {570 retry: 0,571 timeout: false,572 fetch() {573 throw error;574 },575 }), {is: error});576});577578test('a synchronously thrown non-Error value is propagated as-is', async t => {579 const error = await t.throwsAsync<unknown>(ky(fixture, {580 retry: 0,581 fetch() {582 // eslint-disable-next-line @typescript-eslint/only-throw-error583 throw 'sync boom';584 },585 }) as unknown as Promise<unknown>, {any: true});586587 t.is(error, 'sync boom');588});589590test('a synchronously thrown network error is wrapped in NetworkError and retried', async t => {591 let requestCount = 0;592593 const text = await ky(fixture, {594 retry: {limit: 1, delay: () => 0},595 // Not `async` so the throw stays synchronous.596 // eslint-disable-next-line @typescript-eslint/promise-function-async597 fetch() {598 requestCount++;599 if (requestCount === 1) {600 throw new TypeError('Failed to fetch');601 }602603 return Promise.resolve(new Response('ok'));604 },605 }).text();606607 t.is(text, 'ok');608 t.is(requestCount, 2);609});610611test('a synchronously thrown network error is visible to beforeRetry hooks', async t => {612 let requestCount = 0;613 const retryErrors: Error[] = [];614615 await ky(fixture, {616 retry: {limit: 1, delay: () => 0},617 // Not `async` so the throw stays synchronous.618 // eslint-disable-next-line @typescript-eslint/promise-function-async619 fetch() {620 requestCount++;621 if (requestCount === 1) {622 throw new TypeError('Failed to fetch');623 }624625 return Promise.resolve(new Response('ok'));626 },627 hooks: {628 beforeRetry: [629 ({error}) => {630 retryErrors.push(error);631 },632 ],633 },634 }).text();635636 t.is(retryErrors.length, 1);637 t.true(retryErrors[0] instanceof NetworkError);638});639640test('a synchronously throwing fetch runs beforeError hooks', async t => {641 const error = new Error('sync boom');642 const seenErrors: Error[] = [];643644 await t.throwsAsync(ky(fixture, {645 retry: 0,646 fetch() {647 throw error;648 },649 hooks: {650 beforeError: [651 ({error}) => {652 seenErrors.push(error);653 return error;654 },655 ],656 },657 }), {is: error});658659 t.deepEqual(seenErrors, [error]);660});661662test('a synchronously throwing fetch does not turn into a TimeoutError when totalTimeout is set', async t => {663 const error = new Error('sync boom');664665 await t.throwsAsync(ky(fixture, {666 retry: 0,667 timeout: 50,668 totalTimeout: 1000,669 fetch() {670 throw error;671 },672 }), {is: error});673});674675test('the timeout of a synchronously throwing attempt does not abort the retried attempt', async t => {676 let requestCount = 0;677 let retriedRequestSignalAborted: boolean | undefined;678679 const text = await ky(fixture, {680 timeout: 100,681 retry: {limit: 1, delay: () => 50},682 // Not `async` so the throw stays synchronous.683 // eslint-disable-next-line @typescript-eslint/promise-function-async684 fetch(request) {685 requestCount++;686 if (requestCount === 1) {687 throw new TypeError('Failed to fetch');688 }689690 return (async () => {691 // Resolve after the first attempt's timeout would have fired, but before this attempt's own timeout.692 await delay(80);693 retriedRequestSignalAborted = (request as Request).signal.aborted;694 return new Response('ok');695 })();696 },697 }).text();698699 t.is(text, 'ok');700 t.is(requestCount, 2);701 t.false(retriedRequestSignalAborted);702});703704test('the timeout of a synchronously throwing attempt does not abort a retried attempt that reads its body late', async t => {705 let requestCount = 0;706707 const responsePromise = ky(fixture, {708 timeout: 100,709 retry: {limit: 1, delay: () => 50},710 // Not `async` so the throw stays synchronous.711 // eslint-disable-next-line @typescript-eslint/promise-function-async712 fetch(request) {713 requestCount++;714 if (requestCount === 1) {715 throw new TypeError('Failed to fetch');716 }717718 const {signal} = request as Request;719 return Promise.resolve(new Response(new ReadableStream({720 async pull(controller) {721 // Deliver the body after the first attempt's timeout would have fired, but within this attempt's own body read timeout.722 await delay(70);723 if (signal.aborted) {724 controller.error(signal.reason);725 return;726 }727728 controller.enqueue(new TextEncoder().encode('ok'));729 controller.close();730 },731 })));732 },733 });734735 t.is(await responsePromise.text(), 'ok');736 t.is(requestCount, 2);737});738739test('a synchronously throwing retry attempt rejects with that error', async t => {740 let requestCount = 0;741 const error = new Error('sync boom on retry');742743 await t.throwsAsync(ky(fixture, {744 retry: {limit: 1, delay: () => 0},745 fetch() {746 requestCount++;747 if (requestCount === 1) {748 throw new TypeError('Failed to fetch');749 }750751 throw error;752 },753 }), {is: error});754755 t.is(requestCount, 2);756});757758test('a fetch that rejects asynchronously does not leave a timer that aborts the retried attempt', async t => {759 let requestCount = 0;760 let retriedRequestSignalAborted: boolean | undefined;761762 const text = await ky(fixture, {763 timeout: 100,764 retry: {limit: 1, delay: () => 50},765 async fetch(request) {766 requestCount++;767 if (requestCount === 1) {768 throw new TypeError('Failed to fetch');769 }770771 await delay(80);772 retriedRequestSignalAborted = (request as Request).signal.aborted;773 return new Response('ok');774 },775 }).text();776777 t.is(text, 'ok');778 t.is(requestCount, 2);779 t.false(retriedRequestSignalAborted);Fix Next.js edge runtime `next` option support (#775)Sindre Sorhusbefore adoptioncaf78d2
line 780why, one step back780});Fix `fetch: window.fetch` throwing "Illegal invocation" in browsersSindre Sorhusbefore adoption92ef60e
lines 781–911why, one step back781782test('the fetch option is called without a `this` value', async t => {783 const thisValues: unknown[] = [];784785 const text = await ky(fixture, {786 retry: 0,787 async fetch(this: unknown) {788 thisValues.push(this);789 return new Response('ok');790 },791 }).text();792793 t.is(text, 'ok');794 t.deepEqual(thisValues, [undefined]);795});796797test('the fetch option is called without a `this` value when timeout is disabled', async t => {798 const thisValues: unknown[] = [];799800 const text = await ky(fixture, {801 retry: 0,802 timeout: false,803 async fetch(this: unknown) {804 thisValues.push(this);805 return new Response('ok');806 },807 }).text();808809 t.is(text, 'ok');810 t.deepEqual(thisValues, [undefined]);811});812813test('the fetch option is called without a `this` value on retries', async t => {814 const thisValues: unknown[] = [];815816 const text = await ky(fixture, {817 retry: {limit: 2, delay: () => 0},818 async fetch(this: unknown) {819 thisValues.push(this);820 return new Response(thisValues.length < 3 ? 'error' : 'ok', {status: thisValues.length < 3 ? 500 : 200});821 },822 }).text();823824 t.is(text, 'ok');825 t.deepEqual(thisValues, [undefined, undefined, undefined]);826});827828test('the fetch option is called without a `this` value on forced retries with a custom request', async t => {829 const thisValues: unknown[] = [];830831 const text = await ky(fixture, {832 retry: {limit: 1, delay: () => 0},833 async fetch(this: unknown) {834 thisValues.push(this);835 return new Response('ok');836 },837 hooks: {838 afterResponse: [839 ({request}) => {840 if (thisValues.length === 1) {841 return ky.retry({request: new Request(request)});842 }843 },844 ],845 },846 }).text();847848 t.is(text, 'ok');849 t.deepEqual(thisValues, [undefined, undefined]);850});851852test('an unbound global fetch works as the fetch option', async t => {853 const server = await createHttpTestServer(t);854 server.get('/', (_request, response) => {855 response.end('unicorn');856 });857858 t.is(await ky(server.url, {fetch: globalThis.fetch}).text(), 'unicorn');859 t.is(await ky(server.url, {fetch: globalThis.fetch, timeout: false}).text(), 'unicorn');860});861862test('an unbound global fetch works as an instance default', async t => {863 const server = await createHttpTestServer(t);864 server.get('/', (_request, response) => {865 response.end('unicorn');866 });867868 const api = ky.create({fetch: globalThis.fetch}).extend({retry: 0});869 t.is(await api(server.url).text(), 'unicorn');870});871872test('an unbound global fetch works with a Request input', async t => {873 const server = await createHttpTestServer(t);874 server.get('/', (_request, response) => {875 response.end('unicorn');876 });877878 t.is(await ky(new Request(server.url), {fetch: globalThis.fetch}).text(), 'unicorn');879});880881test('an unbound global fetch works when searchParams rebuild the request', async t => {882 const server = await createHttpTestServer(t);883 server.get('/', (request, response) => {884 response.end(request.url);885 });886887 t.is(await ky(server.url, {fetch: globalThis.fetch, searchParams: {unicorn: 'rainbow'}}).text(), '/?unicorn=rainbow');888});889890test('a bound fetch still works as the fetch option', async t => {891 const server = await createHttpTestServer(t);892 server.get('/', (_request, response) => {893 response.end('unicorn');894 });895896 t.is(await ky(server.url, {fetch: globalThis.fetch.bind(globalThis)}).text(), 'unicorn');897});898899test('the fetch option inherited through ky.create() and ky.extend() is called without a `this` value', async t => {900 const thisValues: unknown[] = [];901902 const api = ky.create({903 async fetch(this: unknown) {904 thisValues.push(this);905 return new Response('ok');906 },907 }).extend({retry: 0});908909 t.is(await api(fixture).text(), 'ok');910 t.deepEqual(thisValues, [undefined]);911});Validate the retry options and forward every fetch-only extensionSindre Sorhusbefore adoptiond9774cf
lines 912–931why, one step back912913// A vendor extension named after an `Object.prototype` member was silently dropped, because the lookup went through the prototype chain of the option registries.914test('unknown options named after Object.prototype members are passed to fetch', async t => {915 t.plan(4);916917 const customFetch: typeof fetch = async (request, init) => {918 t.is(init.constructor, 'fetch-constructor');919 t.is(init.toString, 'fetch-to-string');920 t.is(init.valueOf, 'fetch-value-of');921 t.is(init.hasOwnProperty, 'fetch-has-own-property');922 return new Response(request.url);923 };924925 await ky(fixture, {926 constructor: 'fetch-constructor',927 toString: 'fetch-to-string',928 valueOf: 'fetch-value-of',929 hasOwnProperty: 'fetch-has-own-property',930 fetch: customFetch,931 } as never).text();Fix docsSindre Sorhusbefore adoptiond4ce7b1
lines 932–933why, one step back932});933TweaksSindre Sorhusbefore adoption3ded2aa
lines 934–963why, one step back934// The init object was built with a plain assignment, so a `__proto__` key hit the inherited setter instead of becoming an own property. The extension was dropped and `fetch()` received an object whose prototype was caller data.935test('a `__proto__` fetch extension is forwarded as an own property', async t => {936 let init: unknown;937938 await ky(fixture, {939 ...JSON.parse('{"__proto__": {"marker": 1}, "priority": "low"}'),940 async fetch(request, options) {941 init = options;942 return new Response(request.url);943 },944 } as never).text();945946 t.is(Object.getPrototypeOf(init), Object.prototype);947 t.deepEqual(Object.getOwnPropertyDescriptor(init, '__proto__')?.value, {marker: 1});948 t.is((init as {priority: unknown}).priority, 'low');949});950951// `undefined` would otherwise look like `ky.stop`, and any other value failed later with an error that did not name the cause.952test('a custom fetch that resolves with a value that is not a Response is reported', async t => {953 for (const value of [undefined, null, 'ok', 42, {}] as unknown[]) {954 // eslint-disable-next-line no-await-in-loop955 await t.throwsAsync(ky(fixture, {retry: 0, fetch: async () => value as Response}), {956 instanceOf: TypeError,957 message: 'The `fetch` option must resolve with a `Response`',958 }, `value: ${String(value)}`);959 }960});961962// A Response from another realm or a Response-like object with the `Response` brand is accepted as-is.963test('a custom fetch can resolve with a branded Response-like object', async t => {Fix docsSindre Sorhusbefore adoptiond4ce7b1
lines 964–978why, one step back964 const responseLike = {965 status: 200,966 ok: true,967 type: 'default',968 headers: new Headers(),969 async text() {970 return 'ok';971 },972 clone() {973 return responseLike;974 },975 [Symbol.toStringTag]: 'Response',976 };977978 t.is(await ky(fixture, {retry: 0, fetch: async () => responseLike as unknown as Response}), responseLike);Validate the retry options and forward every fetch-only extensionSindre Sorhusbefore adoptiond9774cf
line 979why, one step back979});