http-error.ts
This file
Path
test/http-error.ts
951 lines · 27.9 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.
RefactorSindre Sorhusbefore adoptiona5ed57b
lines 1–2why, one step back1import {setImmediate} from 'node:timers/promises';2import test, {type ExecutionContext} from 'ava';Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 3why, one step back3import {expectTypeOf} from 'expect-type';Enforce total timeout after fetch and body processingSindre Sorhusbefore adoption82fa84c
line 4why, one step back4import ky, {HTTPError, isHTTPError, TimeoutError} from '../source/index.js';Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 5why, one step back5import {type Mutable} from '../source/utils/types.js';Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
line 6why, one step back6import {createHttpTestServer} from './helpers/create-http-test-server.js';Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 7–17why, one step back78function createFakeResponse({status, statusText}: {status?: number; statusText?: string}): Response {9 // Start with a realistic fetch Response.10 const response: Partial<Mutable<Response>> = {...new Response()};1112 response.status = status;13 response.statusText = statusText;1415 return response as Response;16}17Preserve abort reasons while reading HTTP error bodiesSindre Sorhusbefore adoption96a25cc
lines 18–56why, one step back18for (const useCustomReason of [false, true]) {19 test(`aborting an HTTP error body preserves the abort reason (custom: ${useCustomReason})`, async t => {20 const server = await createHttpTestServer(t);21 const controller = new AbortController();22 const reason = useCustomReason ? new Error('Canceled by the user') : undefined;23 let hookError: Error | undefined;24 let hookCallCount = 0;25 let requestCount = 0;2627 server.get('/', (_request, response) => {28 requestCount++;29 response.status(500).type('application/json');30 response.write('{"error":"');31 });3233 const error = await t.throwsAsync(ky(server.url, {34 signal: controller.signal,35 retry: 0,36 hooks: {37 afterResponse: [() => {38 setTimeout(() => {39 controller.abort(reason);40 }, 0);41 }],42 beforeError: [({error}) => {43 hookError = error;44 hookCallCount++;45 return error;46 }],47 },48 }));4950 t.is(error, controller.signal.reason);51 t.is(hookError, controller.signal.reason);52 t.is(hookCallCount, 1);53 t.is(requestCount, 1);54 });55}56Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 57–100why, one step back57test('HTTPError handles undefined response.statusText', t => {58 const status = 500;59 // @ts-expect-error missing options60 const error = new HTTPError(61 // This simulates the case where a browser Response object does62 // not define statusText, such as IE, Safari, etc.63 // See https://developer.mozilla.org/en-US/docs/Web/API/Response/statusText#Browser_compatibility64 createFakeResponse({statusText: undefined, status}),65 new Request('invalid:foo'),66 );6768 t.is(error.message, 'Request failed with status code 500: GET invalid:foo');69});7071test('HTTPError handles undefined response.status', t => {72 // @ts-expect-error missing options73 const error = new HTTPError(74 // This simulates a catastrophic case where some unexpected75 // response object was sent to HTTPError.76 createFakeResponse({statusText: undefined, status: undefined}),77 new Request('invalid:foo'),78 );7980 t.is(error.message, 'Request failed with an unknown error: GET invalid:foo');81});8283test('HTTPError handles a response.status of 0', t => {84 // @ts-expect-error missing options85 const error = new HTTPError(86 // Apparently, it's possible to get a response status of 0.87 createFakeResponse({statusText: undefined, status: 0}),88 new Request('invalid:foo'),89 );9091 t.is(error.message, 'Request failed with status code 0: GET invalid:foo');92});9394test('HTTPError provides response.json()', async t => {95 // @ts-expect-error missing options96 const error = new HTTPError<{foo: 'bar'}>(97 new Response(JSON.stringify({foo: 'bar'})),98 new Request('invalid:foo'),99 );100Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 101–102why, one step back101 expectTypeOf(error.data).toEqualTypeOf<{foo: 'bar'} | string | undefined>();102Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 103–108why, one step back103 const responseJson = await error.response.json();104105 expectTypeOf(responseJson).toEqualTypeOf<{foo: 'bar'}>();106107 t.true(error.response instanceof Response);108 t.deepEqual(responseJson, {foo: 'bar'});Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 109–111why, one step back109});110111test('HTTPError#data is populated with parsed JSON', async t => {Simplify testsSindre Sorhusbefore adoptiondfa3f59
line 112why, one step back112 const server = await createHttpTestServer(t);Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 113–122why, one step back113 const body = {error: 'not found', code: 42};114 server.get('/', (_request, response) => {115 response.status(404).json(body);116 });117118 const error = await t.throwsAsync<HTTPError>(ky.get(server.url));119 t.deepEqual(error?.data, body);120});121122test('HTTPError#data is populated with text for non-JSON', async t => {Simplify testsSindre Sorhusbefore adoptiondfa3f59
line 123why, one step back123 const server = await createHttpTestServer(t);Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 124–132why, one step back124 server.get('/', (_request, response) => {125 response.status(500).type('text/plain').send('Internal failure');126 });127128 const error = await t.throwsAsync<HTTPError>(ky.get(server.url, {retry: 0}));129 t.is(error?.data, 'Internal failure');130});131132test('HTTPError#data is undefined for empty body', async t => {Simplify testsSindre Sorhusbefore adoptiondfa3f59
line 133why, one step back133 const server = await createHttpTestServer(t);Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 134–142why, one step back134 server.get('/', (_request, response) => {135 response.status(404).end();136 });137138 const error = await t.throwsAsync<HTTPError>(ky.get(server.url));139 t.is(error?.data, undefined);140});141142test('HTTPError#data is undefined when JSON parse fails', async t => {Simplify testsSindre Sorhusbefore adoptiondfa3f59
line 143why, one step back143 const server = await createHttpTestServer(t);Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 144–152why, one step back144 server.get('/', (_request, response) => {145 response.status(500).type('application/json').send('not json');146 });147148 const error = await t.throwsAsync<HTTPError>(ky.get(server.url, {retry: 0}));149 t.is(error?.data, undefined);150});151152test('HTTPError#data respects parseJson option', async t => {Simplify testsSindre Sorhusbefore adoptiondfa3f59
line 153why, one step back153 const server = await createHttpTestServer(t);Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 154–168why, one step back154 const body = {value: 1};155 server.get('/', (_request, response) => {156 response.status(400).json(body);157 });158159 const error = await t.throwsAsync<HTTPError>(ky.get(server.url, {160 parseJson(text) {161 const data = JSON.parse(text) as Record<string, unknown>;162 data.custom = true;163 return data;164 },165 }));166 t.deepEqual(error?.data, {value: 1, custom: true});167});168Add request/response context to `parseJson` option (#849)Sindre Sorhusbefore adoption3713ce8
lines 169–211why, one step back169test('HTTPError#data parseJson receives context', async t => {170 const server = await createHttpTestServer(t);171 const body = {value: 1};172 server.get('/', (_request, response) => {173 response.status(400).json(body);174 });175176 const error = await t.throwsAsync<HTTPError>(ky.get(server.url, {177 parseJson(text, {request, response}) {178 t.true(request instanceof Request);179 t.true(response instanceof Response);180 t.is(response.status, 400);181 t.true(request.url.includes(server.url));182 const data = JSON.parse(text) as Record<string, unknown>;183 data.custom = true;184 return data;185 },186 }));187 t.deepEqual(error?.data, {value: 1, custom: true});188});189190test('HTTPError#data async parseJson receives context', async t => {191 const server = await createHttpTestServer(t);192 const body = {value: 1};193 server.get('/', (_request, response) => {194 response.status(400).json(body);195 });196197 const error = await t.throwsAsync<HTTPError>(ky.get(server.url, {198 async parseJson(text, {request, response}) {199 t.true(request instanceof Request);200 t.true(response instanceof Response);201 t.is(response.status, 400);202 t.true(request.url.includes(server.url));203 await Promise.resolve();204 const data = JSON.parse(text) as Record<string, unknown>;205 data.custom = true;206 return data;207 },208 }));209 t.deepEqual(error?.data, {value: 1, custom: true});210});211Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
line 212why, one step back212test('HTTPError#data awaits async parseJson option', async t => {Simplify testsSindre Sorhusbefore adoptiondfa3f59
line 213why, one step back213 const server = await createHttpTestServer(t);Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 214–230why, one step back214 const body = {value: 1};215 server.get('/', (_request, response) => {216 response.status(400).json(body);217 });218219 const error = await t.throwsAsync<HTTPError>(ky.get(server.url, {220 async parseJson(text) {221 await Promise.resolve();222 const data = JSON.parse(text) as Record<string, unknown>;223 data.custom = true;224 return data;225 },226 }));227 t.deepEqual(error?.data, {value: 1, custom: true});228});229230test('HTTPError#data is undefined when async parseJson rejects', async t => {Simplify testsSindre Sorhusbefore adoptiondfa3f59
line 231why, one step back231 const server = await createHttpTestServer(t);Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 232–251why, one step back232 const body = {value: 1};233 server.get('/', (_request, response) => {234 response.status(400).json(body);235 });236237 const error = await t.throwsAsync<HTTPError>(ky.get(server.url, {238 async parseJson() {239 throw new Error('custom parse failure');240 },241 }));242 t.true(error instanceof HTTPError);243 t.is(error?.data, undefined);244});245246test('HTTPError#data does not hang when async parseJson never resolves', async t => {247 const customFetch: typeof fetch = async () => new Response('{"error":"parse-timeout"}', {248 status: 500,249 headers: {'content-type': 'application/json'},250 });251Fix CISindre Sorhusbefore adoptionc2ac4a1
lines 252–253why, one step back252 const {promise: neverSettles} = Promise.withResolvers<never>();253Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 254–257why, one step back254 const start = Date.now();255 const error = await t.throwsAsync<HTTPError>(ky('https://example.com', {256 fetch: customFetch,257 retry: 0,Strip Ky-specific properties from normalized options passed to hooks (#826)Sindre Sorhusbefore adoption433febd
line 258why, one step back258 timeout: 500,Fix CISindre Sorhusbefore adoptionc2ac4a1
line 259why, one step back259 parseJson: async () => neverSettles,Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 260–262why, one step back260 }));261 t.true(error instanceof HTTPError);262 t.is(error?.data, undefined);Strip Ky-specific properties from normalized options passed to hooks (#826)Sindre Sorhusbefore adoption433febd
line 263why, one step back263 t.true(Date.now() - start < 5000);Enforce total timeout after fetch and body processingSindre Sorhusbefore adoption82fa84c
lines 264–315why, one step back264});265266test.serial('totalTimeout is enforced after synchronous error JSON parsing', async t => {267 const originalPerformanceNow = globalThis.performance.now;268 let currentTime = 0;269 let didParse = false;270 globalThis.performance.now = () => currentTime;271 t.teardown(() => {272 globalThis.performance.now = originalPerformanceNow;273 });274275 await t.throwsAsync(ky('https://example.com', {276 retry: 0,277 totalTimeout: 500,278 async fetch() {279 return Response.json({error: 'failure'}, {status: 500});280 },281 parseJson(text) {282 didParse = true;283 currentTime = 501;284 return JSON.parse(text);285 },286 }), {instanceOf: TimeoutError});287288 t.true(didParse);289});290291test.serial('totalTimeout is enforced after reading a plain-text error body', async t => {292 const originalPerformanceNow = globalThis.performance.now;293 let currentTime = 0;294 let didRead = false;295 globalThis.performance.now = () => currentTime;296 t.teardown(() => {297 globalThis.performance.now = originalPerformanceNow;298 });299300 await t.throwsAsync(ky('https://example.com', {301 retry: 0,302 totalTimeout: 500,303 async fetch() {304 return new Response(new ReadableStream({305 pull(controller) {306 didRead = true;307 currentTime = 501;308 controller.enqueue(new TextEncoder().encode('failure'));309 controller.close();310 },311 }, {highWaterMark: 0}), {status: 500});312 },313 }), {instanceOf: TimeoutError});314315 t.true(didRead);Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 316–318why, one step back316});317318test('HTTPError#data does not call parseJson for non-JSON responses', async t => {Simplify testsSindre Sorhusbefore adoptiondfa3f59
line 319why, one step back319 const server = await createHttpTestServer(t);Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 320–337why, one step back320 server.get('/', (_request, response) => {321 response.status(400).type('text/plain').send('plain text');322 });323324 let didCallParseJson = false;325 const error = await t.throwsAsync<HTTPError>(ky.get(server.url, {326 retry: 0,327 parseJson() {328 didCallParseJson = true;329 return {shouldNot: 'run'};330 },331 }));332333 t.false(didCallParseJson);334 t.is(error?.data, 'plain text');335});336337test('HTTPError#data is available in beforeError hooks', async t => {Simplify testsSindre Sorhusbefore adoptiondfa3f59
line 338why, one step back338 const server = await createHttpTestServer(t);Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 339–347why, one step back339 const body = {reason: 'bad request'};340 server.get('/', (_request, response) => {341 response.status(400).json(body);342 });343344 let hookData: unknown;345 await t.throwsAsync(ky.get(server.url, {346 hooks: {347 beforeError: [Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e
line 348why, one step back348 ({error}) => {Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b
lines 349–352why, one step back349 if (isHTTPError(error)) {350 hookData = error.data;351 }352Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 353–361why, one step back353 return error;354 },355 ],356 },357 }));358 t.deepEqual(hookData, body);359});360361test('HTTPError#data handles non-standard JSON content types', async t => {Simplify testsSindre Sorhusbefore adoptiondfa3f59
line 362why, one step back362 const server = await createHttpTestServer(t);Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 363–372why, one step back363 const body = {type: 'https://example.com/not-found', title: 'Not Found', status: 404};364 server.get('/', (_request, response) => {365 response.status(404).type('application/problem+json').send(JSON.stringify(body));366 });367368 const error = await t.throwsAsync<HTTPError>(ky.get(server.url));369 t.deepEqual(error?.data, body);370});371372test('HTTPError#data parses JSON for case-insensitive content types', async t => {Simplify testsSindre Sorhusbefore adoptiondfa3f59
line 373why, one step back373 const server = await createHttpTestServer(t);Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 374–383why, one step back374 const body = {error: 'case-insensitive'};375 server.get('/', (_request, response) => {376 response.status(400).set('content-type', 'Application/JSON; Charset=UTF-8').send(JSON.stringify(body));377 });378379 const error = await t.throwsAsync<HTTPError>(ky.get(server.url, {retry: 0}));380 t.deepEqual(error?.data, body);381});382383test('HTTPError#data does not parse non-JSON content types with json parameters', async t => {Simplify testsSindre Sorhusbefore adoptiondfa3f59
line 384why, one step back384 const server = await createHttpTestServer(t);Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 385–394why, one step back385 const body = '{"error":"plain text"}';386 server.get('/', (_request, response) => {387 response.status(400).set('content-type', 'text/plain; note=json').send(body);388 });389390 const error = await t.throwsAsync<HTTPError>(ky.get(server.url, {retry: 0}));391 t.is(error?.data, body);392});393394test('HTTPError#data is text for JSON-like but non-JSON media types', async t => {Simplify testsSindre Sorhusbefore adoptiondfa3f59
line 395why, one step back395 const server = await createHttpTestServer(t);Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 396–405why, one step back396 const body = '{"error":"sequence"}';397 server.get('/', (_request, response) => {398 response.status(400).set('content-type', 'application/json-seq').send(body);399 });400401 const error = await t.throwsAsync<HTTPError>(ky.get(server.url, {retry: 0}));402 t.is(error?.data, body);403});404405test('HTTPError#data is text for HTML error pages', async t => {Simplify testsSindre Sorhusbefore adoptiondfa3f59
line 406why, one step back406 const server = await createHttpTestServer(t);Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 407–416why, one step back407 const html = '<html><body>Bad Gateway</body></html>';408 server.get('/', (_request, response) => {409 response.status(502).type('text/html').send(html);410 });411412 const error = await t.throwsAsync<HTTPError>(ky.get(server.url, {retry: 0}));413 t.is(error?.data, html);414});415416test('HTTPError#data is text when no content-type header', async t => {Simplify testsSindre Sorhusbefore adoptiondfa3f59
line 417why, one step back417 const server = await createHttpTestServer(t);Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 418–426why, one step back418 server.get('/', (_request, response) => {419 response.removeHeader('content-type');420 response.status(500).end('plain error');421 });422423 const error = await t.throwsAsync<HTTPError>(ky.get(server.url, {retry: 0}));424 t.is(error?.data, 'plain error');425});426Fix UTF-8 decoding of JSON error responsesSindre Sorhusbefore adoption8546080
lines 427–443why, one step back427for (const contentType of ['application/json', 'application/problem+json']) {428 test(`HTTPError#data decodes ${contentType} as UTF-8 regardless of charset`, async t => {429 const body = {error: 'café 日本語 🌍'};430 const error = await t.throwsAsync<HTTPError>(ky('https://example.com', {431 retry: 0,432 async fetch() {433 return new Response(JSON.stringify(body), {434 status: 400,435 headers: {'content-type': `${contentType}; charset=iso-8859-1`},436 });437 },438 }));439440 t.deepEqual(error?.data, body);441 });442}443Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 444–491why, one step back444test('HTTPError#data decodes stream text using response charset when provided', async t => {445 const customFetch: typeof fetch = async () => {446 const body = new ReadableStream<Uint8Array>({447 start(controller) {448 controller.enqueue(Uint8Array.from([0x63, 0x61, 0x66, 0xE9]));449 controller.close();450 },451 });452453 return new Response(body, {454 status: 500,455 headers: {'content-type': 'text/plain; charset=iso-8859-1'},456 });457 };458459 const error = await t.throwsAsync<HTTPError>(ky('https://example.com', {460 fetch: customFetch,461 retry: 0,462 timeout: 500,463 }));464 t.is(error?.data, 'café');465});466467test('HTTPError#data falls back to response.text() when response.body is null', async t => {468 const body = {error: 'streamless'};469 const customFetch: typeof fetch = async () => {470 const response = new Response(JSON.stringify(body), {471 status: 500,472 headers: {'content-type': 'application/json'},473 });474475 Object.defineProperty(response, 'body', {476 get() {477 return null;478 },479 });480481 return response;482 };483484 const error = await t.throwsAsync<HTTPError>(ky('https://example.com', {485 fetch: customFetch,486 retry: 0,487 }));488 t.deepEqual(error?.data, body);489});490491test('HTTPError#data is preserved for slow error bodies when timeout is disabled', async t => {Simplify testsSindre Sorhusbefore adoptiondfa3f59
line 492why, one step back492 const server = await createHttpTestServer(t);Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 493–508why, one step back493 server.get('/', (_request, response) => {494 response.status(500).type('application/json');495 response.write('{"error":"');496 setTimeout(() => {497 response.end('slow"}');498 }, 1100);499 });500501 const error = await t.throwsAsync<HTTPError>(ky.get(server.url, {502 retry: 0,503 timeout: false,504 }));505 t.deepEqual(error?.data, {error: 'slow'});506});507508test('HTTPError#data is preserved for slow error bodies when timeout is greater than 1 second', async t => {Simplify testsSindre Sorhusbefore adoptiondfa3f59
line 509why, one step back509 const server = await createHttpTestServer(t);Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 510–525why, one step back510 server.get('/', (_request, response) => {511 response.status(500).type('application/json');512 response.write('{"error":"');513 setTimeout(() => {514 response.end('slow"}');515 }, 1100);516 });517518 const error = await t.throwsAsync<HTTPError>(ky.get(server.url, {519 retry: 0,520 timeout: 2000,521 }));522 t.deepEqual(error?.data, {error: 'slow'});523});524525test('response body is consumed after HTTPError is thrown', async t => {Simplify testsSindre Sorhusbefore adoptiondfa3f59
line 526why, one step back526 const server = await createHttpTestServer(t);Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 527–535why, one step back527 server.get('/', (_request, response) => {528 response.status(500).json({error: 'fail'});529 });530531 const error = await t.throwsAsync<HTTPError>(ky.get(server.url, {retry: 0}));532 t.true(error?.response.bodyUsed);533});534535test('HTTPError response body readers throw after data is populated', async t => {Simplify testsSindre Sorhusbefore adoptiondfa3f59
line 536why, one step back536 const server = await createHttpTestServer(t);Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 537–644why, one step back537 server.get('/', (_request, response) => {538 response.status(500).json({error: 'fail'});539 });540541 const error = await t.throwsAsync<HTTPError>(ky.get(server.url, {retry: 0}));542 await t.throwsAsync(error!.response.json());543});544545test('HTTPError does not hang on never-ending error response body when timeout is configured', async t => {546 const customFetch: typeof fetch = async () => {547 const body = new ReadableStream<Uint8Array>({548 start(controller) {549 controller.enqueue(new TextEncoder().encode('{"error":"partial"'));550 },551 });552553 return new Response(body, {554 status: 500,555 headers: {'content-type': 'application/json'},556 });557 };558559 const start = Date.now();560 const error = await t.throwsAsync<HTTPError>(ky('https://example.com', {561 fetch: customFetch,562 retry: 0,563 timeout: 50,564 }));565 t.true(error instanceof HTTPError);566 t.is(error?.data, undefined);567 t.true(Date.now() - start < 2000);568});569570test('HTTPError timeout path cancels never-ending stream reader', async t => {571 let didCancel = false;572 const customFetch: typeof fetch = async () => {573 const body = new ReadableStream<Uint8Array>({574 start(controller) {575 controller.enqueue(new TextEncoder().encode('{"error":"partial"'));576 },577 cancel() {578 didCancel = true;579 },580 });581582 return new Response(body, {583 status: 500,584 headers: {'content-type': 'application/json'},585 });586 };587588 const error = await t.throwsAsync<HTTPError>(ky('https://example.com', {589 fetch: customFetch,590 retry: 0,591 timeout: 50,592 }));593 t.true(error instanceof HTTPError);594 t.is(error?.data, undefined);595 await new Promise(resolve => {596 setTimeout(resolve, 0);597 });598 t.true(didCancel);599});600601test('HTTPError#data is undefined when error response body exceeds max size', async t => {602 const customFetch: typeof fetch = async () => {603 const body = new ReadableStream<Uint8Array>({604 start(controller) {605 controller.enqueue(new Uint8Array(11 * 1024 * 1024));606 controller.close();607 },608 });609610 return new Response(body, {611 status: 500,612 headers: {'content-type': 'text/plain'},613 });614 };615616 const error = await t.throwsAsync<HTTPError>(ky('https://example.com', {617 fetch: customFetch,618 retry: 0,619 timeout: 500,620 }));621 t.true(error instanceof HTTPError);622 t.is(error?.data, undefined);623});624625test('HTTPError does not throw TypeError when error response stream is already locked', async t => {626 const customFetch: typeof fetch = async () => {627 const body = new ReadableStream<Uint8Array>({628 start(controller) {629 controller.enqueue(new TextEncoder().encode('{"error":"locked"}'));630 },631 });632633 return new Response(body, {634 status: 500,635 headers: {'content-type': 'application/json'},636 });637 };638639 const error = await t.throwsAsync<HTTPError>(ky('https://example.com', {640 fetch: customFetch,641 retry: 0,642 timeout: false,643 hooks: {644 afterResponse: [Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e
line 645why, one step back645 ({response}) => {Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 646–656why, one step back646 void response.text();647 return response;648 },649 ],650 },651 }));652653 t.true(error instanceof HTTPError);654 t.is(error?.data, undefined);655});656Add `totalTimeout` option and make `timeout` be per retry (#848)Sindre Sorhusbefore adoptionc20d7c7
line 657why, one step back657test('never-ending error response body is bounded and retry proceeds', async t => {Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 658–678why, one step back658 let requestCount = 0;659660 const customFetch: typeof fetch = async () => {661 requestCount++;662 if (requestCount === 1) {663 const body = new ReadableStream<Uint8Array>({664 start(controller) {665 controller.enqueue(new TextEncoder().encode('{"error":"partial"'));666 },667 });668669 return new Response(body, {670 status: 500,671 headers: {'content-type': 'application/json'},672 });673 }674675 return new Response('ok');676 };677678 const start = Date.now();Add `totalTimeout` option and make `timeout` be per retry (#848)Sindre Sorhusbefore adoptionc20d7c7
line 679why, one step back679 const result = await ky('https://example.com', {Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
line 680why, one step back680 fetch: customFetch,Fix timeout to apply to total operation including retries (#825)Sindre Sorhusbefore adoptionaac83fa
lines 681–685why, one step back681 retry: {682 limit: 1,683 delay: () => 0,684 },685 timeout: 1000,Add `totalTimeout` option and make `timeout` be per retry (#848)Sindre Sorhusbefore adoptionc20d7c7
lines 686–689why, one step back686 }).text();687 t.is(result, 'ok');688 t.is(requestCount, 2);689 // The body read is bounded by the per-attempt timeout, so the retry proceeds within a reasonable timeAdd `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
line 690why, one step back690 t.true(Date.now() - start < 3000);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 691why, one step back691});HardenSindre Sorhusbefore adoption8d8e7a4
lines 692–760why, one step back692693for (const [contentType, expected] of [694 ['application/json', {value: 1}],695 ['application/json; charset=utf-8', {value: 1}],696 ['application/problem+json', {value: 1}],697 ['application/vnd.api+json', {value: 1}],698 ['application/ld+json', {value: 1}],699 ['text/json', {value: 1}],700 ['application/merge-patch+json', {value: 1}],701 ['text/plain', '{"value":1}'],702 ['application/jsonx', '{"value":1}'],703 ['application/notjson', '{"value":1}'],704 ['application/octet-stream', '{"value":1}'],705 ['json', '{"value":1}'],706 ['/json', {value: 1}],707 ['a/json', {value: 1}],708 ['a.json', '{"value":1}'],709 ['a+json', '{"value":1}'],710 ['a-json', '{"value":1}'],711 ['a/b.json', {value: 1}],712] as const) {713 test(`error data for a ${contentType} content type`, async t => {714 const error = (await t.throwsAsync(ky('https://example.com', {715 retry: {limit: 0},716 async fetch() {717 return new Response('{"value":1}', {status: 500, headers: {'content-type': contentType}});718 },719 }), {instanceOf: HTTPError}))!;720721 t.deepEqual(error.data, expected);722 });723}724725test('a hostile content type does not stall the error data path', async t => {726 // The content type is attacker-controlled. A backtracking matcher here would block the event loop for minutes on this input.727 const hostileContentType = `text/${'/'.repeat(200_000)}`;728 const start = Date.now();729730 const error = (await t.throwsAsync(ky('https://example.com', {731 retry: {limit: 0},732 async fetch() {733 return new Response('{}', {status: 500, headers: {'content-type': hostileContentType}});734 },735 }), {instanceOf: HTTPError}))!;736737 const elapsed = Date.now() - start;738 // The old matcher needs about 90 seconds on this input, so the bound is not close to the real cost.739 t.true(elapsed < 2000, `error data took ${elapsed}ms, expected under 2000ms`);740 t.is(error.data, '{}');741});742743test('TimeoutError from the error data path reports the request that was sent', async t => {744 let sentRequest: Request | undefined;745746 const error = (await t.throwsAsync(ky('https://example.com/?x=1', {747 retry: {limit: 1, delay: () => 0},748 totalTimeout: 300,749 async fetch(request) {750 sentRequest = request;751 return new Response(new ReadableStream({752 start(streamController) {753 streamController.enqueue(new TextEncoder().encode('{"partial":'));754 },755 }), {status: 500, headers: {'content-type': 'application/json'}});756 },757 }), {instanceOf: TimeoutError}))!;758759 t.is(error.request, sentRequest);760});Release the body when a predicate throws, an abort wins, or a response cannot be decoratedSindre Sorhusbefore adoptiondeb5a33
line 761why, one step back761Restore the retry-only marker condition and cover the remaining casesSindre Sorhusbefore adoption692c435
line 762why, one step back762// A `throwHttpErrors` predicate ran inside the `if` condition, so a throw from it escaped before the body was read or released, leaving the caller with an error and no handle on the response to release it with.Release the body when a predicate throws, an abort wins, or a response cannot be decoratedSindre Sorhusbefore adoptiondeb5a33
line 763why, one step back763test('a `throwHttpErrors` predicate that throws releases the response body', async t => {Restore the retry-only marker condition and cover the remaining casesSindre Sorhusbefore adoption692c435
lines 764–768why, one step back764 let release: () => void;765 // Awaiting the cancel itself, rather than a sleep, keeps this reliable on a loaded machine.766 const cancelled = new Promise<void>(resolve => {767 release = resolve;768 });Release the body when a predicate throws, an abort wins, or a response cannot be decoratedSindre Sorhusbefore adoptiondeb5a33
lines 769–773why, one step back769 const body = new ReadableStream<Uint8Array>({770 start(controller) {771 controller.enqueue(new TextEncoder().encode('server error'));772 },773 cancel() {Restore the retry-only marker condition and cover the remaining casesSindre Sorhusbefore adoption692c435
line 774why, one step back774 release!();Release the body when a predicate throws, an abort wins, or a response cannot be decoratedSindre Sorhusbefore adoptiondeb5a33
lines 775–786why, one step back775 },776 });777778 const error = await t.throwsAsync(ky('https://example.com', {779 retry: 0,780 throwHttpErrors() {781 throw new Error('policy engine exploded');782 },783 fetch: async () => new Response(body, {status: 500}),784 }).text(), {message: 'policy engine exploded'});785786 t.is(error?.message, 'policy engine exploded');Restore the retry-only marker condition and cover the remaining casesSindre Sorhusbefore adoption692c435
line 787why, one step back787 await cancelled;Release the body when a predicate throws, an abort wins, or a response cannot be decoratedSindre Sorhusbefore adoptiondeb5a33
lines 788–790why, one step back788});789790test('a `throwHttpErrors` predicate that throws is still seen by `beforeError`', async t => {Restore the retry-only marker condition and cover the remaining casesSindre Sorhusbefore adoption692c435
lines 791–792why, one step back791 const seen: unknown[] = [];792 const thrown = new Error('policy engine exploded');Release the body when a predicate throws, an abort wins, or a response cannot be decoratedSindre Sorhusbefore adoptiondeb5a33
lines 793–796why, one step back793794 await t.throwsAsync(ky('https://example.com', {795 retry: 0,796 throwHttpErrors() {Restore the retry-only marker condition and cover the remaining casesSindre Sorhusbefore adoption692c435
line 797why, one step back797 throw thrown;Release the body when a predicate throws, an abort wins, or a response cannot be decoratedSindre Sorhusbefore adoptiondeb5a33
lines 798–801why, one step back798 },799 fetch: async () => new Response('server error', {status: 500}),800 hooks: {801 beforeError: [({error}) => {Restore the retry-only marker condition and cover the remaining casesSindre Sorhusbefore adoption692c435
line 802why, one step back802 seen.push(error);Release the body when a predicate throws, an abort wins, or a response cannot be decoratedSindre Sorhusbefore adoptiondeb5a33
lines 803–806why, one step back803 }],804 },805 }).text(), {message: 'policy engine exploded'});806Restore the retry-only marker condition and cover the remaining casesSindre Sorhusbefore adoption692c435
lines 807–808why, one step back807 // The predicate's own error is what the hook sees, unchanged.808 t.deepEqual(seen, [thrown]);RefactorSindre Sorhusbefore adoptiona5ed57b
lines 809–950why, one step back809});810811test('an error JSON parse that times out still lets the retry go ahead', async t => {812 let requestCount = 0;813 const {promise: neverSettles} = Promise.withResolvers<never>();814815 const text = await ky('https://example.com', {816 timeout: 200,817 retry: {limit: 1, delay: () => 0},818 parseJson: async () => neverSettles,819 async fetch() {820 requestCount++;821 return requestCount === 1822 ? new Response('{"error":"slow parse"}', {status: 500, headers: {'content-type': 'application/json'}})823 : new Response('ok');824 },825 }).text();826827 t.is(text, 'ok');828 t.is(requestCount, 2);829});830831/*832Tracks the timers created until the test ends. A timer stops being active once it fires or is cleared.833834The tests that use this are serial, and AVA runs serial tests before concurrent ones, so every tracked timer comes from the request under test or the test itself.835*/836const trackActiveTimers = (t: ExecutionContext) => {837 const originalSetTimeout = globalThis.setTimeout;838 const originalClearTimeout = globalThis.clearTimeout;839 const state = {840 createdCount: 0,841 active: new Set<unknown>(),842 };843844 globalThis.setTimeout = ((handler: (...arguments_: unknown[]) => void, milliseconds?: number, ...arguments_: unknown[]) => {845 state.createdCount++;846 const timeoutId = originalSetTimeout((...handlerArguments: unknown[]) => {847 state.active.delete(timeoutId);848 handler(...handlerArguments);849 }, milliseconds, ...arguments_);850 state.active.add(timeoutId);851 return timeoutId;852 }) as typeof globalThis.setTimeout;853854 globalThis.clearTimeout = ((timeoutId?: Parameters<typeof globalThis.clearTimeout>[0]) => {855 state.active.delete(timeoutId);856 originalClearTimeout(timeoutId);857 }) as typeof globalThis.clearTimeout;858859 t.teardown(() => {860 globalThis.setTimeout = originalSetTimeout;861 globalThis.clearTimeout = originalClearTimeout;862 });863864 return state;865};866867const assertNoActiveTimers = async (t: ExecutionContext, timers: ReturnType<typeof trackActiveTimers>) => {868 // Some timers are cleared in a `finally` callback that runs a few microtasks after the request settles.869 await setImmediate();870 t.true(timers.createdCount > 0, 'the request should have created timers');871 t.is(timers.active.size, 0, `${timers.active.size} of ${timers.createdCount} timers are still active`);872};873874const jsonErrorResponse = () => new Response('{"error":"failure"}', {status: 500, headers: {'content-type': 'application/json'}});875876test.serial('no timer is left behind after an HTTPError with JSON data', async t => {877 const timers = trackActiveTimers(t);878879 const error = await t.throwsAsync(ky('https://example.com', {880 retry: 0,881 fetch: async () => jsonErrorResponse(),882 }), {instanceOf: HTTPError});883884 t.deepEqual(error?.data, {error: 'failure'});885 await assertNoActiveTimers(t, timers);886});887888test.serial('no timer is left behind after hooks and a body read are raced against totalTimeout', async t => {889 const timers = trackActiveTimers(t);890891 const text = await ky('https://example.com', {892 totalTimeout: 60_000,893 fetch: async () => new Response('ok'),894 hooks: {895 beforeRequest: [() => undefined],896 afterResponse: [() => undefined],897 },898 }).text();899900 t.is(text, 'ok');901 await assertNoActiveTimers(t, timers);902});903904test.serial('no timer is left behind after shouldRetry and beforeRetry are raced against totalTimeout', async t => {905 const timers = trackActiveTimers(t);906 let requestCount = 0;907908 const text = await ky('https://example.com', {909 totalTimeout: 60_000,910 retry: {911 limit: 1,912 delay: () => 0,913 shouldRetry: () => true,914 },915 async fetch() {916 requestCount++;917 return requestCount === 1 ? jsonErrorResponse() : new Response('ok');918 },919 hooks: {920 beforeRetry: [() => undefined],921 },922 }).text();923924 t.is(text, 'ok');925 t.is(requestCount, 2);926 await assertNoActiveTimers(t, timers);927});928929test.serial('no timer is left behind after a user abort during the retry delay', async t => {930 const timers = trackActiveTimers(t);931 const controller = new AbortController();932 const reason = new Error('Cancelled during the delay');933934 const error = await t.throwsAsync(ky('https://example.com', {935 signal: controller.signal,936 retry: {937 limit: 1,938 delay() {939 // `retry.delay` runs just before the wait starts, so this fires once Ky is waiting.940 setTimeout(() => {941 controller.abort(reason);942 }, 0);943 return 60_000;944 },945 },946 fetch: async () => jsonErrorResponse(),947 }));948949 t.is(error, reason);950 await assertNoActiveTimers(t, timers);Release the body when a predicate throws, an abort wins, or a response cannot be decoratedSindre Sorhusbefore adoptiondeb5a33
line 951why, one step back951});