Skip to content
Myr

Reject a nullish hook list instead of treating it as absent

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 4cc6698 · Browse files · 3 files+58 added−19 removed
This commit

State

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

Diff stats

3 files+58 added−19 removed

  • tests:+45 added−7 removed
  • other:+13 added−12 removed

3 files+58 added−19 removed

modified:source/types/options.ts+2 added
263 unmodified lines
264 maxResponseSize?: number | undefined;265266 /**267 Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially, unless otherwise noted.268269 Each hook must be an array of functions. A single function, a string, or any other value, `null` included, throws a `TypeError` rather than being silently dropped. `undefined` means absent, so it clears the hooks it would have replaced.270 */271 hooks?: Hooks | undefined;272273 /**
295 unmodified lines
modified:source/utils/merge.ts+11 added-12 removed
193 unmodified lines
194export const mergeHeaderContainers = (source1: KyHeadersInit, source2: KyHeadersInit): Record<string, string | undefined> =>195 mergeHeaderObjects(toHeaderObject(source1), toHeaderObject(source2));196197function newHookValue<K extends keyof Hooks>(original: Hooks, incoming: Hooks, property: K): NormalizedHooks[K] {198 // An absent key must keep the parent's hooks, which is why this check needs `Object.hasOwn`.199 if (Object.hasOwn(incoming, property) && incoming[property] === undefined) {200 return [];201 }202203 // A single hook type can be wrapped in `replaceOption()` to replace only that array instead of the whole `hooks` object.204 const {isReplace, value} = getReplaceState(incoming[property]);204 if (value !== undefined && !Array.isArray(value)) {205 // Merging ignores anything that is neither an array nor an object, so a single function, a string or `null`206 // used to be dropped without a word and the hook simply never ran.207 throw new TypeError(`\`hooks.${property}\` must be an array`);205 // Merging ignores anything that is neither an array nor an object, so a single function or a string used to be dropped without a word and the hook simply never ran. `null` is rejected here too, rather than treated as absent: use `undefined` to clear a hook list.206 if (value !== undefined && (!Array.isArray(value) || !value.every(hook => typeof hook === 'function'))) {207 throw new TypeError(`\`hooks.${property}\` must be an array of functions`);208 }209210 if (isReplace) {211 return [...(value ?? [])] as NormalizedHooks[K];
2 unmodified lines
214 return deepMerge<NormalizedHooks[K]>(original[property] ?? [], value ?? []);215}216217export const mergeHooks = (original: Hooks = {}, incoming: Hooks = {}): NormalizedHooks => {218 // `null` selects the default, the same way option merging treats a nullish value as absent.219 const incomingHooks = incoming ?? {};220 if (!isObject(incomingHooks) || Array.isArray(incomingHooks)) {218 // `undefined` selects the default through the parameter default. `null` is not accepted, so it reaches this check and is reported like any other bad shape.219 if (!isObject(incoming) || Array.isArray(incoming)) {220 throw new TypeError('The `hooks` option must be an object');221 }222223 return {225 init: newHookValue(original, incomingHooks, 'init'),226 beforeRequest: newHookValue(original, incomingHooks, 'beforeRequest'),227 beforeRetry: newHookValue(original, incomingHooks, 'beforeRetry'),228 beforeError: newHookValue(original, incomingHooks, 'beforeError'),229 afterResponse: newHookValue(original, incomingHooks, 'afterResponse'),224 init: newHookValue(original, incoming, 'init'),225 beforeRequest: newHookValue(original, incoming, 'beforeRequest'),226 beforeRetry: newHookValue(original, incoming, 'beforeRetry'),227 beforeError: newHookValue(original, incoming, 'beforeError'),228 afterResponse: newHookValue(original, incoming, 'afterResponse'),229 };230};231232export const deletedParametersSymbol = Symbol('deletedParameters');
248 unmodified lines
modified:test/hooks.ts+45 added-7 removed
7256 unmodified lines
7257 t.true(cancelled);7258});72597260// `newHookValue` merged with `deepMerge`, which ignores sources that are neither arrays nor objects, so a single7261// function, a string or `null` was dropped without a word and the hook simply never ran.7261// function, a string or a `null` was dropped without a word and the hook simply never ran. `null` is reported like any7262// other bad shape, since `undefined` is how a hook list is cleared.7263test('rejects a hook list that is not an array', t => {7264 for (const [key, value] of [7265 ['init', () => undefined],7266 ['beforeRequest', 'not a function'],7266 ['afterResponse', null],7267 ['beforeRetry', {}],7268 ['beforeError', 0],7269 ['afterResponse', true],7270 ['beforeRequest', null],7271 // An entry that is not a function only failed once the hook ran, with an error that did not name the option.7272 ['beforeRequest', [null]],7273 ['afterResponse', [() => undefined, 'not a function']],7274 ] as Array<[string, unknown]>) {7275 const hooks: Record<string, unknown> = {[key]: value};72767277 t.throws(() => {
46 unmodified lines
7324 }, `hooks: ${JSON.stringify(hooks)}`);7325 }7326});73277323test('`hooks: null` selects the default', async t => {7324 t.is(await ky('https://example.com', {hooks: null as never, fetch: async () => new Response('ok')}).text(), 'ok');7328// `hooks: null` used to reach `Object.hasOwn(null, ...)` and report an internal error. It is reported like any other7329// bad shape instead, since `undefined` is how the option is omitted.7330test('`hooks: null` reports a clear error', t => {7331 for (const hooks of [null, undefined, 'none', 42, true, []] as unknown[]) {7332 if (hooks === undefined) {7333 // The one shape that selects the default, through the parameter default.7334 t.pass();7335 continue;7336 }73377338 t.throws(() => {7339 void ky('https://example.com', {hooks: hooks as never});7340 }, {7341 instanceOf: TypeError,7342 message: 'The `hooks` option must be an object',7343 }, `hooks: ${JSON.stringify(hooks)}`);7344 }7345});73467327// `instanceof Error` fails for an error from another realm, so a cross-realm failure skipped the hooks entirely and7328// a cross-realm replacement from a hook was dropped. The Ky type guards already accept branded errors from another7329// copy of Ky, so the error checks here read the internal brand too.7347test('an explicit `undefined` hook list clears the parent hooks', async t => {7348 const cleared: string[] = [];7349 const undefinedHookList = {hooks: {beforeRequest: undefined}} as Options;7350 const instance = ky.create({7351 hooks: {7352 beforeRequest: [() => {7353 cleared.push('parent');7354 }],7355 },7356 fetch: async () => new Response('ok'),7357 });73587359 await instance('https://example.com', undefinedHookList).text();7360 t.deepEqual(cleared, []);73617362 await instance('https://example.com').text();7363 t.deepEqual(cleared, ['parent']);7364 t.is(await instance('https://example.com', undefinedHookList).text(), 'ok');7365});73667367// `instanceof Error` fails for an error from another realm, so a cross-realm failure skipped the hooks entirely and a cross-realm replacement from a hook was dropped. The Ky type guards already accept branded errors from another copy of Ky, so the error checks here read the internal brand too.7368test('a cross-realm error thrown by fetch still runs `beforeError` hooks', async t => {7369 const foreignError = runInNewContext('new Error("foreign fetch failure")') as Error;7370 const seen: string[] = [];7371
135 unmodified lines