Skip to content
Myr

Count a compressed response as unknown, deep-copy context, and isolate `init` hook assignments

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

authored by Sindre Sorhus · committed by Sindre Sorhus · parent 5b7080a · Browse files · 11 files+307 added−26 removed
This commit

State

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

Diff stats

11 files+307 added−26 removed

  • tests:+237 added−7 removed
  • other:+70 added−19 removed

11 files+307 added−26 removed

modified:source/core/Ky.ts+39 added-11 removed
147 unmodified lines
148 return cloneShallow(searchParameters) as SearchParamsOption | undefined;149};150151// Shallow-clone mutable option properties so init hook mutations don't leak across requests.152// Every one of them also copies on assignment, so a hook that replaces the value with an object of its own cannot153// accumulate mutations on that object across requests. Non-plain values (functions, class instances) are kept by154// reference, matching how option merging treats them as whole values.155function cloneInitHookOptions(options: Options): InitOptions {156 let headers = mergeHeaderContainers({}, options.headers ?? {});157 let context = cloneDeep(options.context) ?? {};155 const clonedOptions: Options = {156 ...options,157 // Deep-clone so init-hook mutations to nested values do not leak across requests, matching the nested `retry` cloning below. Non-plain values (functions, class instances) are kept by reference.158 json: cloneDeep(options.json),159 searchParams: cloneSearchParametersForInitHook(options.searchParams),160 };158 let json = cloneDeep(options.json);159 let searchParameters = cloneSearchParametersForInitHook(options.searchParams);160 let retry = options.retry === undefined ? undefined : cloneRetryOptions(options.retry);161162 const clonedOptions: Options = {...options};163164 Object.defineProperties(clonedOptions, {165 headers: {166 enumerable: true,167 configurable: true,
10 unmodified lines
178 get() {179 return context;180 },181 set(value: Record<string, unknown> | undefined) {180 context = value ?? {};182 context = cloneDeep(value) ?? {};183 },184 },185 json: {186 enumerable: true,187 configurable: true,188 get() {189 return json;190 },191 set(value: unknown) {192 json = cloneDeep(value);193 },194 },195 searchParams: {196 enumerable: true,197 configurable: true,198 get() {199 return searchParameters;200 },201 set(value: SearchParamsOption | undefined) {202 searchParameters = cloneSearchParametersForInitHook(value);203 },204 },205 retry: {206 enumerable: true,207 configurable: true,208 get() {209 return retry;210 },211 set(value: Options['retry']) {212 retry = value === undefined ? undefined : cloneRetryOptions(value);213 },214 },215 });216185 if (options.retry !== undefined) {186 clonedOptions.retry = cloneRetryOptions(options.retry);187 }188217 return clonedOptions as InitOptions;218}219220const validateJsonWithSchema = async (jsonValue: unknown, schema: StandardSchemaV1): Promise<unknown> => {
1279 unmodified lines
modified:source/types/options.ts+2 added
287 unmodified lines
288289 @param progress - Object containing download progress information.290 @param chunk - Data that was received. When an empty response body stream completes, the callback receives an empty chunk.291292 `content-length` is only used as the total for a response that is not content-coded, since it counts encoded bytes while the progress stream counts the bytes after decompression. A compressed response therefore reports `totalBytes: 0` until it completes, which means the percentage cannot be calculated while downloading.293294 Responses with a [null body status](https://fetch.spec.whatwg.org/#null-body-status) are not streamed, so no progress events are emitted for them.295296 When the callback throws, the error is reported by Ky's body method shortcuts. A response read directly with `response.text()` or `response.json()` may instead report the runtime's own stream error, such as Chromium's generic `TypeError`.297
249 unmodified lines
modified:source/utils/body.ts+5 added-1 removed
193 unmodified lines
194 if (!response.body || nullBodyStatuses.has(response.status)) {195 return response;196 }197198 // `content-length` counts encoded bytes on the wire, while the progress stream counts the bytes after199 // decompression. Using it for a content-coded response would report a total below what actually arrives, so200 // every event would sit at ~100%. The total is then unknown, which `Progress` already models with `0`.201 const isContentCoded = response.headers.get('content-encoding') !== null;198 const totalBytes = Math.max(0, Number(response.headers.get('content-length')) || 0);202 const totalBytes = isContentCoded ? 0 : Math.max(0, Number(response.headers.get('content-length')) || 0);203 const body = withProgress(response.body, totalBytes, onDownloadProgress);204205 return copyResponseMetadata(new Response(body, response), response);206};
21 unmodified lines
modified:source/utils/merge.ts+4 added-3 removed
305 unmodified lines
306 if (value !== undefined && value !== null && (!isObject(value) || Array.isArray(value))) {307 throw new TypeError('The `context` option must be an object');308 }309310 // Shallow merge: always create a new object to prevent mutation bugs310 // Shallow merge: top-level keys are replaced, but each layer is deep-copied so nested values are311 // never shared with the caller's object.312 returnValue = {313 ...returnValue,314 context: (value === undefined || value === null)315 ? {}316 : (isReplace316 ? {...value}317 : {...returnValue.context, ...value}),317 ? cloneDeep(value)318 : {...returnValue.context, ...cloneDeep(value as Record<string, unknown>)}),319 };320 continue;321 }322
87 unmodified lines
modified:source/utils/normalize.ts+12 added-2 removed
modified:source/utils/options.ts+6 added-2 removed
modified:test/hooks.ts+99 added
6922 unmodified lines
6923 beforeRetry: [() => ky.stop],6924 },6925 }), undefined);6926});69276928// The defensive copy only ran on the values the options object started with. A hook that assigned one of its own6929// objects got that same object back for every later hook and every later request, so a mutation in a second hook6930// wrote straight through to the object the first hook owned.6931test('an `init` hook that assigns `json` hands later hooks a copy', async t => {6932 const bodies: string[] = [];6933 const ownBody = {list: [1, 2]};6934 const instance = ky.create({6935 method: 'POST',6936 json: {list: [1, 2]},6937 retry: 0,6938 hooks: {6939 init: [6940 options => {6941 options.json = ownBody;6942 },6943 options => {6944 (options.json as typeof ownBody).list.push(99);6945 },6946 ],6947 },6948 async fetch(request) {6949 bodies.push(await request.clone().text());6950 return new Response('ok');6951 },6952 });69536954 await instance('https://example.com').text();6955 await instance('https://example.com').text();69566957 t.deepEqual(bodies, ['{"list":[1,2,99]}', '{"list":[1,2,99]}']);6958 t.deepEqual(ownBody, {list: [1, 2]});6959});69606961test('an `init` hook that assigns `searchParams` or `context` hands later hooks a copy', async t => {6962 const urls: string[] = [];6963 const contexts: string[] = [];6964 const ownSearchParameters = {page: 1};6965 const ownContext = {token: 'first'};69666967 const instance = ky.create({6968 retry: 0,6969 hooks: {6970 init: [6971 options => {6972 options.searchParams = ownSearchParameters;6973 options.context = ownContext;6974 },6975 options => {6976 (options.searchParams as typeof ownSearchParameters).page = 2;6977 (options.context as typeof ownContext).token = 'second';6978 },6979 ],6980 beforeRequest: [({options}) => {6981 contexts.push(JSON.stringify(options.context));6982 }],6983 },6984 async fetch(request) {6985 urls.push(request.url);6986 return new Response('ok');6987 },6988 });69896990 await instance('https://example.com').text();6991 await instance('https://example.com').text();69926993 t.deepEqual(urls, ['https://example.com/?page=2', 'https://example.com/?page=2']);6994 t.deepEqual(contexts, ['{"token":"second"}', '{"token":"second"}']);6995 t.deepEqual(ownSearchParameters, {page: 1});6996 t.deepEqual(ownContext, {token: 'first'});6997});69986999test('an `init` hook that assigns `retry` hands later hooks a copy', async t => {7000 const attemptCounts: number[] = [];7001 const ownRetry = {limit: 0, delay: () => 0};70027003 const instance = ky.create({7004 hooks: {7005 init: [7006 options => {7007 options.retry = ownRetry;7008 },7009 options => {7010 (options.retry as typeof ownRetry).limit = 1;7011 },7012 ],7013 },7014 async fetch() {7015 attemptCounts.push(1);7016 return new Response('server error', {status: 500});7017 },7018 });70197020 await t.throwsAsync(instance('https://example.com').text());7021 await t.throwsAsync(instance('https://example.com').text());70227023 t.deepEqual(attemptCounts, [1, 1, 1, 1]);7024 t.deepEqual(ownRetry, {limit: 0, delay: ownRetry.delay});7025});
modified:test/main.ts+47 added-7 removed
4197 unmodified lines
4198 },4199 }).json());4200});42014202// `hasSearchParameters()` reached `Object.keys()` on `null`, so clearing the option from an `init` hook crashed4203// with an internal error instead of simply leaving the URL alone.4202test('an `init` hook can clear `searchParams`', async t => {4203 const server = await createHttpTestServer(t);4204 server.get('/', (request, response) => {4205 response.end(request.url);
1 unmodified line
42074208 t.is(await ky(server.url, {4209 searchParams: {a: '1'}, hooks: {4210 init: [options => {4213 options.searchParams = null as never;4211 options.searchParams = undefined;4212 }],4213 },4214 }).text(), '/');4217 t.is(await ky(server.url, {4215});42164217// `hasSearchParameters()` reached `Object.keys()` on `null`, so an `init` hook that assigned `null` crashed with an internal error. `null` is not accepted anywhere in Ky, so the error names the option instead.4218test('an `init` hook that sets `searchParams` to `null` gets an error naming the option', t => {4219 t.throws(() => {4220 void ky('https://example.com', {4221 searchParams: {a: '1'},4222 hooks: {4223 init: [options => {4224 options.searchParams = null as never;4225 }],4226 },4227 });4228 }, {4229 instanceOf: TypeError,4230 message: 'The `searchParams` option must not be `null`. Use `undefined` to clear it.',4231 });4232});42334234// The top-level context is merged shallowly, so a nested value arrived from the caller by reference and mutating4235// it after `ky.create()` silently changed what every later request carried. The per-request deep copy happens too4236// late to help. `searchParams` is already copied at this point.4237test('mutating a caller-owned `context` object after creating an instance does not change it', async t => {4238 const bodies: string[] = [];4239 const contexts: string[] = [];4240 const json = {nested: {value: 1}};4241 const context = {nested: {value: 1}};42424243 const instance = ky.create({4244 method: 'POST',4245 json,4246 context,4247 async fetch(request) {4248 bodies.push(await request.clone().text());4249 return new Response('ok');4250 },4251 hooks: {4219 init: [options => {4220 options.searchParams = null as never;4252 beforeRequest: [({options}) => {4253 contexts.push(JSON.stringify(options.context));4254 }],4255 },4223 }).text(), '/');4256 });42574258 context.nested.value = 2;42594260 await instance('https://example.com').text();42614262 t.is(contexts[0], '{"nested":{"value":1}}');4263 t.deepEqual(context, {nested: {value: 2}});4264});
modified:test/retry.ts+41 added
4883 unmodified lines
4884 instanceOf: TypeError,4885 message: '`retry.delay` must return a non-negative number or `Infinity`',4886 });4887});48884889// Array-shaped retry options were only checked for being arrays, so a mistyped entry silently disabled retrying4890// with no indication of why.4891test('rejects non-string `retry.methods` entries and non-number status code entries', t => {4892 for (const [key, value] of [4893 ['methods', ['GET', 5]],4894 ['statusCodes', ['429']],4895 ['statusCodes', [429.5]],4896 ['statusCodes', [null]],4897 ['afterStatusCodes', ['503']],4898 ['afterStatusCodes', [Number.NaN]],4899 ] as Array<[string, unknown]>) {4900 const retry: Record<string, unknown> = {[key]: value};49014902 t.throws(() => {4903 void ky('https://example.com', {retry: retry as never});4904 }, {4905 instanceOf: TypeError,4906 message: `\`retry.${key}\` must only contain ${key === 'methods' ? 'strings' : 'numbers'}`,4907 }, `${key}: ${JSON.stringify(value)}`);4908 }4909});49104911test('a rejected retry list entry is reported before the request is sent', t => {4912 let requestCount = 0;4913 const retry: Record<string, unknown> = {statusCodes: ['500']};49144915 t.throws(() => {4916 void ky('https://example.com', {4917 async fetch() {4918 requestCount++;4919 return new Response(null, {status: 500});4920 },4921 retry: retry as never,4922 });4923 }, {4924 instanceOf: TypeError,4925 message: '`retry.statusCodes` must only contain numbers',4926 });4927 t.is(requestCount, 0);4928});
modified:test/stream.ts+50 added
1319 unmodified lines
1320 transferredBytes: 2,1321 totalBytes: 2,1322 });1323});13241325// `content-length` is the size of the encoded body on the wire, while the progress stream counts the bytes after decompression. Trusting it made every event report 100% for a compressed response, so a progress bar was useless for exactly the responses that are large enough to need one.1326test('download progress does not trust content-length for a compressed response', async t => {1327 const progressEvents: Progress[] = [];1328 const text = await ky('https://example.com', {1329 async fetch() {1330 const body = new ReadableStream<Uint8Array>({1331 start(controller) {1332 for (let index = 0; index < 8; index++) {1333 controller.enqueue(new Uint8Array(1024));1334 }13351336 controller.close();1337 },1338 });13391340 return new Response(body, {headers: {'content-length': '64', 'content-encoding': 'gzip'}});1341 },1342 onDownloadProgress(progress) {1343 progressEvents.push(progress);1344 },1345 }).text();13461347 t.is(text.length, 8192);1348 t.true(progressEvents.length > 1);1349 // The encoded size is not a usable total, so it is reported as unknown instead of pinning every event to ~100%.1350 for (const event of progressEvents.slice(0, -1)) {1351 t.is(event.percent, 0);1352 t.is(event.totalBytes, 0);1353 }13541355 t.deepEqual(progressEvents.at(-1), {1356 percent: 1,1357 transferredBytes: 8192,1358 totalBytes: 8192,1359 });1360});13611362test('download progress still uses content-length for an uncompressed response', async t => {1363 const progressEvents: Progress[] = [];1364 const text = await ky('https://example.com', {1365 fetch: async () => new Response('x'.repeat(64), {headers: {'content-length': '64'}}),1366 onDownloadProgress(progress) {1367 progressEvents.push(progress);1368 },1369 }).text();13701371 t.is(text.length, 64);1372 t.is(progressEvents.at(-1)?.totalBytes, 64);1373});
modified:readme.md+2 added
760 unmodified lines
761 - `transferredBytes` is the number of bytes transferred so far.762 - `totalBytes` is the total number of bytes to be transferred. This is an estimate and may be 0 for an empty transfer or when the total size cannot be determined.763- `chunk` is an instance of `Uint8Array` containing the data that was received. When an empty response body stream completes, the callback receives an empty chunk.764765`content-length` is only used as the total for a response that is not content-coded, since it counts encoded bytes while the progress stream counts the bytes after decompression. A compressed response therefore reports `totalBytes: 0` until it completes, so the percentage cannot be calculated while downloading.766767Responses with a [null body status](https://fetch.spec.whatwg.org/#null-body-status) are not streamed, so no progress events are emitted for them.768769When the callback throws, the error is reported by Ky's body method shortcuts. A response read directly with `response.text()` or `response.json()` may instead report the runtime's own stream error, such as Chromium's generic `TypeError`.770
1137 unmodified lines