Validate the callbacks and the input
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 01b0839 · Browse files · 10 files·+175 added−108 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+175 added−108 removed
- tests:+114 added−61 removed
- other:+61 added−47 removed
Provenance
- Commit
6b67569- Tree
7aadb6d- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
01b0839
10 files changed+175 added−108 removed
modified:source/core/constants.ts+3 added-5 removed
40 unmodified lines41 validate<[42 Expect<Equal<typeof requestMethods[number], RequestHttpMethod>>,43 ]>();44 45-// Each media type is one Ky can actually parse, so a server that only serves one of them does not answer 406 to a46-// request the matching shortcut would have handled.45+// The media type each shortcut advertises. Deliberately narrow: `.text()` asks for text and `.formData()` for multipart, so a server can serve a different representation of the same resource when the caller wants one.46 export const responseTypes = {47 json: 'application/json',49- // `.text()` returns JSON as-is, and `.formData()` parses URL-encoded bodies as well as multipart ones.50- text: 'text/*, application/json',51- formData: 'multipart/form-data, application/x-www-form-urlencoded',48+ text: 'text/*',49+ formData: 'multipart/form-data',50 arrayBuffer: '*/*',51 blob: '*/*',52 // Supported in modern Fetch implementations (for example, browsers and recent Node.js/undici).53 // We still feature-check at runtime before exposing the shortcut.244 unmodified linesmodified:source/core/Ky.ts+23 added-4 removed
261 unmodified lines262 263 const function_ = async (): Promise<Response | void> => {264 validateTimeoutOption(ky.#options.totalTimeout, 'totalTimeout');265 validateTimeoutOption(ky.#options.timeout, 'timeout');266+ ky.#validateCallbackOptions();267 268 // Delay the fetch so that body method shortcuts can set the Accept header269 await Promise.resolve();270 const beforeRequestResponse = await ky.#runBeforeRequestHooks();212 unmodified lines483 readonly #decoratedResponses = new WeakSet<Response>();484 485 // eslint-disable-next-line complexity486 constructor(input: Input, options: Options = {}) {487+ // Checked before the options are built, since building them reads `input.headers`.488+ if (typeof input !== 'string' && !(input instanceof URL || input instanceof globalThis.Request)) {489+ throw new TypeError('`input` must be a string, URL, or Request');490+ }491+492 const {maxResponseSize = Number.POSITIVE_INFINITY} = options;493 if (Object.hasOwn(options, 'prefixUrl')) {494 throw new Error(prefixUrlRenamedErrorMessage);495 }21 unmodified lines517 if (maxResponseSize !== Number.POSITIVE_INFINITY && (!Number.isSafeInteger(maxResponseSize) || maxResponseSize < 0)) {518 throw new TypeError('The `maxResponseSize` option must be a non-negative safe integer or Infinity');519 }520 515- if (typeof input !== 'string' && !(input instanceof URL || input instanceof globalThis.Request)) {516- throw new TypeError('`input` must be a string, URL, or Request');517- }518-521 this.#requestInput = input instanceof globalThis.Request ? input : undefined;522 523 if (typeof input === 'string') {524 if (this.#options.prefix) {127 unmodified lines652 // Ky's internal scheduling and user hook time before the first fetch attempt.653 this.#startTime = typeof this.#options.totalTimeout === 'number' ? this.#getCurrentTime() : undefined;654 }655 656+ // These callbacks are called directly, so a non-function value otherwise surfaces as a runtime error naming Ky's657+ // own internals rather than the option the caller set.658+ #validateCallbackOptions(): void {659+ for (const key of ['parseJson', 'stringifyJson', 'fetch'] as const) {660+ if (this.#options[key] !== undefined && typeof this.#options[key] !== 'function') {661+ throw new TypeError(`The \`${key}\` option must be a function`);662+ }663+ }664+665+ if (666+ typeof this.#options.throwHttpErrors !== 'boolean'667+ && typeof this.#options.throwHttpErrors !== 'function'668+ ) {669+ throw new TypeError('The `throwHttpErrors` option must be a boolean or a function');670+ }671+ }672+673 #calculateDelay(retry: InternalOptions['retry']): number {674 const retryDelay = retry.delay(this.#retryCount + 1);675 676 // A `retry.delay` that does not return a usable number would turn every delay into `NaN`, which870 unmodified linesmodified:source/types/options.ts+1 added-1 removed
289 unmodified lines290 @param chunk - Data that was received. When an empty response body stream completes, the callback receives an empty chunk.291 292 `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.293 294- 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. A `HEAD` response has no body either, but it is not a null body status, so a single completion event is reported from `content-length`.294+ Responses with no body at all are not streamed, so no progress events are emitted for them. That covers a [null body status](https://fetch.spec.whatwg.org/#null-body-status) such as `204`, and a `HEAD` request, which has no body even on an ordinary status.295 296 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 298 @example250 unmodified linesmodified:source/utils/body.ts+3 added-13 removed
194 unmodified lines195 return copyResponseMetadata(new Response(body, response), response, () => sizeError ?? getOriginalSizeError?.());196 };197 198 export const streamResponse = (response: Response, onDownloadProgress: Options['onDownloadProgress']) => {199- if (nullBodyStatuses.has(response.status)) {200- return response;201- }202-203- // A HEAD response has no body even on an ordinary status, so there is nothing to stream, but the download is204- // still complete. Report that from the declared length alone so a progress bar finishes instead of hanging.205- if (!response.body) {206- const totalBytes = Math.max(0, Number(response.headers.get('content-length')) || 0);207- onDownloadProgress?.({percent: 1, totalBytes, transferredBytes: totalBytes}, new Uint8Array());208- return response;209- }210-199+ // A response with no body at all is not streamed. That covers a null body status and a `HEAD` request, which has200+ // no body even on an ordinary status, so neither reports progress.201 // See `limitResponseSize`: there is nothing left to stream and nothing to report once a hook consumed the body.212- if (response.bodyUsed || response.body.locked) {202+ if (!response.body || response.bodyUsed || response.body.locked || nullBodyStatuses.has(response.status)) {203 return response;204 }205 206 // `content-length` counts encoded bytes on the wire, while the progress stream counts the bytes after decompression. Using it for a content-coded response would report a total below what actually arrives, so every event would sit at ~100%. The total is then unknown, which `Progress` already models with `0`. `identity` is a registered no-op coding (RFC 9110 §8.4.2), so it leaves the length valid.29 unmodified linesmodified:source/utils/merge.ts+30 added-23 removed
221 unmodified lines222 };223 224 export const deletedParametersSymbol = Symbol('deletedParameters');225 226-// `replaceOption()` can wrap a value at any depth of a deep-merged option, but a wrapper is only unwrapped where a227-// merge actually runs, so a wrapper on a key with no parent value kept its `{value}` envelope. This resolves the228-// leftovers in one pass, copying only the branches that actually contained a wrapper so every other value keeps its229-// identity. `seen` keeps a cyclic option from recursing forever; a cyclic branch is left as-is.230-const resolveReplaceMarkers = (value: unknown, seen: Set<Record<string, unknown> | unknown[]>): unknown => {231- if (!isMergeable(value) || seen.has(value)) {232- return value;233- }234-235- seen.add(value);236- const resolveItem = (item: unknown) => resolveReplaceMarkers(getReplaceState(item).value, seen);237-238- if (Array.isArray(value)) {239- let resolved: unknown[] | undefined;240- for (const [index, item] of value.entries()) {241- const replacement = resolveItem(item);242- if (replacement !== item) {243- resolved ??= [...value];244- resolved[index] = replacement;226+const resolveArrayMarkers = (value: unknown[], resolveItem: (item: unknown) => unknown): unknown[] | undefined => {227+ let resolved: unknown[] | undefined;228+ for (const [index, item] of value.entries()) {229+ const replacement = resolveItem(item);230+ if (replacement !== item) {231+ resolved ??= [...value];232+ resolved[index] = replacement;245- }233 }247-248- return resolved ?? value;234 }235 236+ return resolved;237+};238+239+const resolveObjectMarkers = (value: Record<string, unknown>, resolveItem: (item: unknown) => unknown): Record<string, unknown> | undefined => {240 let resolved: Record<string, unknown> | undefined;241 for (const [key, item] of Object.entries(value)) {242 const replacement = resolveItem(item);243 if (replacement !== item) {1 unmodified line245 resolved[key] = replacement;246 }247 }248 249+ return resolved;250+};251+252+// `replaceOption()` can wrap a value at any depth of a deep-merged option, but a wrapper is only unwrapped where a253+// merge actually runs, so a wrapper on a key with no parent value kept its `{value}` envelope. This resolves the254+// leftovers in one pass, copying only the branches that actually contained a wrapper so every other value keeps its255+// identity. `seen` only holds the values on the current path, so a cyclic option cannot recurse forever while a256+// value shared by two branches is still resolved in both.257+const resolveReplaceMarkers = (value: unknown, seen: Set<Record<string, unknown> | unknown[]>): unknown => {258+ if (!isMergeable(value) || seen.has(value)) {259+ return value;260+ }261+262+ seen.add(value);263+ const resolveItem = (item: unknown) => resolveReplaceMarkers(getReplaceState(item).value, seen);264+ const resolved = Array.isArray(value) ? resolveArrayMarkers(value, resolveItem) : resolveObjectMarkers(value, resolveItem);265+ seen.delete(value);266+267 return resolved ?? value;268 };269 270 const appendSearchParameters = (target: any, source: any): URLSearchParams => {98 unmodified lines369 ...returnValue,370 context: (value === undefined || value === null)371 ? {}372 : (isReplace366- ? cloneDeep(value)373+ ? {...cloneDeep(value as Record<string, unknown>)}374 : {...returnValue.context, ...cloneDeep(value as Record<string, unknown>)}),375 };376 continue;377 }88 unmodified linesmodified:test/response-consumption.ts+9 added-32 removed
233 unmodified lines234 t.is(fetchCalls, 1);235 t.is(hookCalls, 1);236 });237 238-// Each body shortcut advertises exactly what it can parse, so a server that only serves one of those media types239-// must not answer 406 to a request Ky could have parsed.240-test('the `accept` header of each body shortcut covers what Ky can parse', async t => {238+// The media type each shortcut advertises is deliberately narrow, so a caller that wants another representation asks for it through `headers` instead.239+test('each body shortcut advertises exactly one media type', async t => {240 const accepts: Record<string, string | undefined> = {};241 242 for (const type of ['json', 'text', 'formData', 'arrayBuffer', 'blob'] as const) {243 // eslint-disable-next-line no-await-in-loop5 unmodified lines249 },250 })[type]().catch(() => undefined);251 }252 254- t.is(accepts.json, 'application/json');255- t.true(accepts.text!.includes('text/*'));256- t.true(accepts.text!.includes('application/json'));257- t.true(accepts.formData!.includes('multipart/form-data'));258- t.true(accepts.formData!.includes('application/x-www-form-urlencoded'));259- t.is(accepts.arrayBuffer, '*/*');260- t.is(accepts.blob, '*/*');253+ t.deepEqual(accepts, {254+ json: 'application/json',255+ text: 'text/*',256+ formData: 'multipart/form-data',257+ arrayBuffer: '*/*',258+ blob: '*/*',259+ });260 });262-263-test('a server that only serves a parseable media type does not reject the shortcut', async t => {264- for (const [contentType, body, read] of [265- ['application/json', '{"a":1}', 'text'],266- ['application/x-www-form-urlencoded', 'a=1&b=2', 'formData'],267- ] as Array<[string, string, 'text' | 'formData']>) {268- // eslint-disable-next-line no-await-in-loop269- const server = await createHttpTestServer(t);270- server.get('/', (request, response) => {271- const accept = (request.headers.accept ?? '').split(',').map(mediaType => mediaType.trim());272- if (!accept.includes(contentType)) {273- response.sendStatus(406);274- return;275- }276-277- response.set('content-type', contentType).end(body);278- });279-280- // eslint-disable-next-line no-await-in-loop281- t.truthy(await ky(server.url, {retry: 0})[read]());282- }283-});modified:test/retry.ts+30 added
5065 unmodified lines5066 t.is(new ForceRetryError().message, 'Forced retry');5067 t.is(new ForceRetryError({}).message, 'Forced retry');5068 t.is(new ForceRetryError({code: 'RATE_LIMIT'}).message, 'Forced retry: RATE_LIMIT');5069 });5070+5071+// The replace-marker pass only held the values on the current path, so a value shared by two branches was resolved5072+// in the first and skipped in the second, which kept its `{value}` envelope. A genuine cycle is still left alone.5073+test('`replaceOption` resolves a shared value in every branch that uses it', t => {5074+ const shared = {tags: replaceOption(['a'])};5075+ const merged = validateAndMerge({json: {first: shared, second: shared, list: [shared]}});5076+5077+ t.deepEqual(merged.json, {first: {tags: ['a']}, second: {tags: ['a']}, list: [{tags: ['a']}]});5078+});5079+5080+test('`replaceOption` leaves a cyclic option intact', t => {5081+ const cyclic: Record<string, unknown> = {a: 1};5082+ cyclic.self = cyclic;5083+5084+ const merged = validateAndMerge({custom: cyclic, json: {filters: replaceOption({tags: ['a']})}});5085+5086+ t.is(merged.custom, cyclic);5087+ t.deepEqual(merged.json, {filters: {tags: ['a']}});5088+});5089+5090+test('`replaceOption` on a context keeps it a plain object', t => {5091+ class Holder {5092+ b = 2;5093+ }5094+5095+ const {context} = validateAndMerge({context: {a: 1}}, {context: replaceOption(new Holder() as never)});5096+5097+ t.is(Object.getPrototypeOf(context), Object.prototype);5098+ t.deepEqual(context, {b: 2});5099+});modified:test/stream.ts+20 added-29 removed
1455 unmodified lines1456 1457 t.is(progressEvents.at(-1)?.totalBytes, 10);1458 });1459 1460-// A HEAD response has no body even on a normal status, so the `!response.body` guard returned early and the1461-// callback never fired. The readme only carves out null body *statuses*.1462-for (const [label, headers] of [1463- ['a declared length', {'content-length': '1000'}],1464- ['no declared length', {}],1465-] as Array<[string, Record<string, string>]>) {1466- test(`download progress completes for a HEAD response with ${label}`, async t => {1467- const progressEvents: Progress[] = [];1460+// A response with no body at all is not streamed. That covers a null body status, and a `HEAD` response in runtimes that give it no body, such as Node.js.1461+test('download progress stays silent for a null body status', async t => {1462+ let calls = 0;1463+ const result = await ky('https://example.com', {1464+ fetch: async () => new Response(null, {status: 204}),1465+ onDownloadProgress() {1466+ calls++;1467+ },1468+ });1469 1469- const response = await ky('https://example.com', {1470- method: 'HEAD',1471- async fetch() {1472- return new Response(null, {status: 200, headers});1473- },1474- onDownloadProgress(progress, chunk) {1475- progressEvents.push(progress);1476- t.is(chunk.byteLength, 0);1477- },1478- });1470+ t.is(result.status, 204);1471+ t.is(calls, 0);1472+});1473 1480- t.is(response.status, 200);1481- t.is(progressEvents.length, 1);1482- const expectedTotal = Number(headers['content-length'] ?? 0);1483- t.deepEqual(progressEvents[0], {percent: 1, totalBytes: expectedTotal, transferredBytes: expectedTotal});1474+test('download progress stays silent for a HEAD response', async t => {1475+ const server = await createHttpTestServer(t);1476+ server.head('/', (_request, response) => {1477+ response.setHeader('content-length', '1000');1478+ response.end();1479 });1485-}1480 1487-test('download progress stays silent for a null body status', async t => {1481 let calls = 0;1489- const response = await ky('https://example.com', {1490- async fetch() {1491- return new Response(null, {status: 204});1492- },1482+ const result = await ky.head(server.url, {1483 onDownloadProgress() {1484 calls++;1485 },1486 });1487 1498- t.is(response.status, 204);1488+ t.is(result.status, 200);1489+ t.is(result.headers.get('content-length'), '1000');1490 t.is(calls, 0);1491 });1492 1493 // A throwing progress callback is a user-space error, but `#fetch()` rethrows it as a plain `Error`, so a `shouldRetry` that returns `true` for everything re-sent the body and ran the callback again.28 unmodified linesmodified:test/validation.ts+55 added
71 unmodified lines72 message: 'The `timeout` option must be a non-negative number or `false`',73 },74 );75 });76+77+// These callbacks are called directly, so a non-function value surfaced as a runtime error naming Ky's own78+// internals (`this[#options].stringifyJson`, `initHookOptions.parseJson`) instead of the option the user set.79+test('rejects non-function callback options', async t => {80+ for (const [key, value] of [81+ ['parseJson', 'x'],82+ ['stringifyJson', 5],83+ ['fetch', 'x'],84+ ] as Array<[string, unknown]>) {85+ const options: Record<string, unknown> = {[key]: value};86+87+ // eslint-disable-next-line no-await-in-loop88+ await t.throwsAsync(ky('https://example.com', options as never).json(), {89+ name: 'TypeError',90+ message: `The \`${key}\` option must be a function`,91+ }, `${key}: ${JSON.stringify(value)}`);92+ }93+});94+95+test('rejects a `throwHttpErrors` value that is neither a boolean nor a function', async t => {96+ for (const value of ['yes', 1, {}] as unknown[]) {97+ const options: Record<string, unknown> = {98+ throwHttpErrors: value,99+ fetch: async () => new Response('server error', {status: 500}),100+ };101+102+ // eslint-disable-next-line no-await-in-loop103+ await t.throwsAsync(ky('https://example.com', options as never).json(), {104+ name: 'TypeError',105+ message: 'The `throwHttpErrors` option must be a boolean or a function',106+ }, `throwHttpErrors: ${JSON.stringify(value)}`);107+ }108+});109+110+test('accepts a valid `throwHttpErrors` function', async t => {111+ const options: Record<string, unknown> = {112+ throwHttpErrors: (status: number) => status === 404,113+ fetch: async () => new Response('server error', {status: 500}),114+ };115+116+ t.is(await ky('https://example.com', options as never).text(), 'server error');117+});118+119+// The `input` type check ran after the options were built, so a nullish input dereferenced `.headers` first and120+// reported an internal TypeError instead of the option the caller got wrong.121+test('a nullish or non-string `input` reports the input error', t => {122+ for (const input of [null, undefined, 5, {}, true] as unknown[]) {123+ t.throws(() => {124+ void ky(input as never, {fetch: okFetch});125+ }, {126+ name: 'TypeError',127+ message: '`input` must be a string, URL, or Request',128+ }, `input: ${String(input)}`);129+ }130+});modified:readme.md+1 added-1 removed
762 unmodified lines763 - `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.764 765 `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.766 767-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. A `HEAD` response has no body either, but it is not a null body status, so a single completion event is reported from `content-length`.767+Responses with no body at all are not streamed, so no progress events are emitted for them. That covers a [null body status](https://fetch.spec.whatwg.org/#null-body-status) such as `204`, and a `HEAD` request, which has no body even on an ordinary status.768 769 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`.770 771 ```js1138 unmodified lines