Normalize mutable init hook options
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 8778439 · Browse files · 5 files·+60 added−6 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+60 added−6 removed
- tests:+20 added−0 removed
- other:+40 added−6 removed
Provenance
- Commit
ff0155d- Tree
f3912be- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
8778439
5 files changed+60 added−6 removed
modified:source/core/Ky.ts+27 added-4 removed
6 unmodified lines7 import type {8 Input,9 InitOptions,10 InternalOptions,11+ KyHeadersInit,12 NormalizedOptions,13 Options,14 SearchParamsInit,15 SearchParamsOption,9 unmodified lines25 import {26 cloneShallow,27 cloneDeep,28 mergeHeaders,29+ mergeHeaderContainers,30 mergeHooks,31 deletedParametersSymbol,32 } from '../utils/merge.js';33 import type {RetryOptions} from '../types/retry.js';99 unmodified lines133 };134 135 // Shallow-clone mutable option properties so init hook mutations don't leak across requests.136 function cloneInitHookOptions(options: Options): InitOptions {137+ let headers = mergeHeaderContainers({}, options.headers ?? {});138+ let context = cloneDeep(options.context) ?? {};139 const clonedOptions: Options = {140 ...options,141 // 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.142 json: cloneDeep(options.json),139- // `context` is documented to always be an object in every hook, including `init`.140- context: cloneDeep(options.context) ?? {},141- // `headers` is documented to always be a plain object in `init` hooks, so hooks can add headers in place even when none were provided.142- headers: cloneShallow(options.headers) ?? {},143 searchParams: cloneSearchParametersForInitHook(options.searchParams),144 };145 146+ Object.defineProperties(clonedOptions, {147+ headers: {148+ enumerable: true,149+ configurable: true,150+ get() {151+ return headers;152+ },153+ set(value: KyHeadersInit | undefined) {154+ headers = mergeHeaderContainers({}, value ?? {});155+ },156+ },157+ context: {158+ enumerable: true,159+ configurable: true,160+ get() {161+ return context;162+ },163+ set(value: Record<string, unknown> | undefined) {164+ context = value ?? {};165+ },166+ },167+ });168+169 if (options.retry !== undefined) {170 clonedOptions.retry = cloneRetryOptions(options.retry);171 }172 1243 unmodified linesmodified:source/types/options.ts+5 added-1 removed
493 unmodified lines494 // eslint-disable-next-line @typescript-eslint/no-restricted-types495 signal?: AbortSignal | null | undefined;496 }497 498-export type InitOptions = Omit<Options, 'retry' | 'hooks'> & {498+export type InitOptions = Omit<Options, 'retry' | 'hooks' | 'headers' | 'context'> & {499+ get headers(): Record<string, string | undefined>;500+ set headers(value: KyHeadersInit | undefined);501+ get context(): Record<string, unknown>;502+ set context(value: Record<string, unknown> | undefined);503 retry?: MutableRetryOptions | number | undefined;504 hooks?: {[Key in keyof Hooks]?: NormalizedHooks[Key] | undefined} | undefined;505 };506 36 unmodified linesmodified:source/utils/merge.ts+1 added-1 removed
179 unmodified lines180 181 return result;182 };183 184-const mergeHeaderContainers = (source1: KyHeadersInit, source2: KyHeadersInit): Record<string, string | undefined> =>184+export const mergeHeaderContainers = (source1: KyHeadersInit, source2: KyHeadersInit): Record<string, string | undefined> =>185 mergeHeaderObjects(toHeaderObject(source1), toHeaderObject(source2));186 187 function newHookValue<K extends keyof Hooks>(original: Hooks, incoming: Hooks, property: K): NormalizedHooks[K] {188 if (Object.hasOwn(incoming, property) && incoming[property] === undefined) {219 unmodified linesmodified:test/hooks.ts+20 added
5613 unmodified lines5614 },5615 });5616 });5617 5618+test('init hook replacements stay normalized for later init hooks', async t => {5619+ await ky.get('https://example.com', {5620+ fetch: async () => new Response('ok'),5621+ hooks: {5622+ init: [5623+ options => {5624+ options.headers = new Headers({'X-Test': 'value'});5625+ options.context = undefined;5626+ },5627+ options => {5628+ t.deepEqual(options.headers, {'x-test': 'value'});5629+ t.deepEqual(options.context, {});5630+ options.headers['x-added'] = 'added';5631+ options.context.added = true;5632+ },5633+ ],5634+ },5635+ });5636+});5637+5638 test('init hook sees per-request options merged with defaults', async t => {5639 t.plan(2);5640 5641 const api = ky.extend({1069 unmodified linesmodified:test-d/hooks.ts+7 added
2 unmodified lines345678910114 unmodified lines16171819202122232425262728292 unmodified lines2 unmodified lines
const hookList = [() => undefined] as const;const beforeErrorHook: BeforeErrorHook = ({error}) => error;const beforeErrorHooks = [beforeErrorHook] as const;const exampleKey = String('example');const hooks: Hooks = { init: hookList, beforeRequest: hookList, beforeRetry: hookList,4 unmodified linesexpectTypeOf(hooks).toEqualTypeOf<Hooks>();
const initHook: InitHook = options => { options.hooks?.beforeRequest?.push(() => undefined); expectTypeOf(options.headers).toEqualTypeOf<Record<string, string | undefined>>(); expectTypeOf(options.context).toEqualTypeOf<Record<string, unknown>>(); options.headers = new Headers(); options.headers[exampleKey] = 'value'; options.context = undefined; options.context[exampleKey] = 'value'; if (options.hooks) { options.hooks.beforeRequest = undefined; }};2 unmodified lines